Line data Source code
1 : use std::collections::{HashMap, HashSet};
2 :
3 : use anyhow::Context;
4 : use pageserver::tenant::layer_map::LayerMap;
5 : use pageserver::tenant::remote_timeline_client::index::LayerFileMetadata;
6 : use pageserver_api::shard::ShardIndex;
7 : use tokio_util::sync::CancellationToken;
8 : use tracing::{error, info, warn};
9 : use utils::generation::Generation;
10 : use utils::id::TimelineId;
11 :
12 : use crate::cloud_admin_api::BranchData;
13 : use crate::metadata_stream::stream_listing;
14 : use crate::{download_object_with_retries, RootTarget, TenantShardTimelineId};
15 : use futures_util::StreamExt;
16 : use pageserver::tenant::remote_timeline_client::{parse_remote_index_path, remote_layer_path};
17 : use pageserver::tenant::storage_layer::LayerName;
18 : use pageserver::tenant::IndexPart;
19 : use remote_storage::{GenericRemoteStorage, ListingObject, RemotePath};
20 :
21 : pub(crate) struct TimelineAnalysis {
22 : /// Anomalies detected
23 : pub(crate) errors: Vec<String>,
24 :
25 : /// Healthy-but-noteworthy, like old-versioned structures that are readable but
26 : /// worth reporting for awareness that we must not remove that old version decoding
27 : /// yet.
28 : pub(crate) warnings: Vec<String>,
29 :
30 : /// Keys not referenced in metadata: candidates for removal, but NOT NECESSARILY: beware
31 : /// of races between reading the metadata and reading the objects.
32 : pub(crate) garbage_keys: Vec<String>,
33 : }
34 :
35 : impl TimelineAnalysis {
36 0 : fn new() -> Self {
37 0 : Self {
38 0 : errors: Vec::new(),
39 0 : warnings: Vec::new(),
40 0 : garbage_keys: Vec::new(),
41 0 : }
42 0 : }
43 :
44 : /// Whether a timeline is healthy.
45 0 : pub(crate) fn is_healthy(&self) -> bool {
46 0 : self.errors.is_empty() && self.warnings.is_empty()
47 0 : }
48 : }
49 :
50 0 : pub(crate) async fn branch_cleanup_and_check_errors(
51 0 : remote_client: &GenericRemoteStorage,
52 0 : id: &TenantShardTimelineId,
53 0 : tenant_objects: &mut TenantObjectListing,
54 0 : s3_active_branch: Option<&BranchData>,
55 0 : console_branch: Option<BranchData>,
56 0 : s3_data: Option<RemoteTimelineBlobData>,
57 0 : ) -> TimelineAnalysis {
58 0 : let mut result = TimelineAnalysis::new();
59 0 :
60 0 : info!("Checking timeline {id}");
61 :
62 0 : if let Some(s3_active_branch) = s3_active_branch {
63 0 : info!(
64 0 : "Checking console status for timeline for branch {:?}/{:?}",
65 : s3_active_branch.project_id, s3_active_branch.id
66 : );
67 0 : match console_branch {
68 0 : Some(_) => {result.errors.push(format!("Timeline has deleted branch data in the console (id = {:?}, project_id = {:?}), recheck whether it got removed during the check",
69 0 : s3_active_branch.id, s3_active_branch.project_id))
70 : },
71 : None => {
72 0 : result.errors.push(format!("Timeline has no branch data in the console (id = {:?}, project_id = {:?}), recheck whether it got removed during the check",
73 0 : s3_active_branch.id, s3_active_branch.project_id))
74 : }
75 : };
76 0 : }
77 :
78 0 : match s3_data {
79 0 : Some(s3_data) => {
80 0 : result
81 0 : .garbage_keys
82 0 : .extend(s3_data.unknown_keys.into_iter().map(|k| k.key.to_string()));
83 0 :
84 0 : match s3_data.blob_data {
85 : BlobDataParseResult::Parsed {
86 0 : index_part,
87 0 : index_part_generation: _index_part_generation,
88 0 : s3_layers: _s3_layers,
89 0 : } => {
90 0 : if !IndexPart::KNOWN_VERSIONS.contains(&index_part.version()) {
91 0 : result
92 0 : .errors
93 0 : .push(format!("index_part.json version: {}", index_part.version()))
94 0 : }
95 :
96 0 : let mut newest_versions = IndexPart::KNOWN_VERSIONS.iter().rev().take(3);
97 0 : if !newest_versions.any(|ip| ip == &index_part.version()) {
98 0 : info!(
99 0 : "index_part.json version is not latest: {}",
100 0 : index_part.version()
101 : );
102 0 : }
103 :
104 0 : if index_part.metadata.disk_consistent_lsn()
105 0 : != index_part.duplicated_disk_consistent_lsn()
106 : {
107 : // Tech debt: let's get rid of one of these, they are redundant
108 : // https://github.com/neondatabase/neon/issues/8343
109 0 : result.errors.push(format!(
110 0 : "Mismatching disk_consistent_lsn in TimelineMetadata ({}) and in the index_part ({})",
111 0 : index_part.metadata.disk_consistent_lsn(),
112 0 : index_part.duplicated_disk_consistent_lsn(),
113 0 : ))
114 0 : }
115 :
116 0 : if index_part.layer_metadata.is_empty() {
117 0 : if index_part.metadata.ancestor_timeline().is_none() {
118 0 : // The initial timeline with no ancestor should ALWAYS have layers.
119 0 : result.errors.push(
120 0 : "index_part.json has no layers (ancestor_timeline=None)"
121 0 : .to_string(),
122 0 : );
123 0 : } else {
124 : // Not an error, can happen for branches with zero writes, but notice that
125 0 : info!("index_part.json has no layers (ancestor_timeline exists)");
126 : }
127 0 : }
128 :
129 0 : for (layer, metadata) in index_part.layer_metadata {
130 0 : if metadata.file_size == 0 {
131 0 : result.errors.push(format!(
132 0 : "index_part.json contains a layer {} that has 0 size in its layer metadata", layer,
133 0 : ))
134 0 : }
135 :
136 0 : if !tenant_objects.check_ref(id.timeline_id, &layer, &metadata) {
137 0 : let path = remote_layer_path(
138 0 : &id.tenant_shard_id.tenant_id,
139 0 : &id.timeline_id,
140 0 : metadata.shard,
141 0 : &layer,
142 0 : metadata.generation,
143 0 : );
144 :
145 : // HEAD request used here to address a race condition when an index was uploaded concurrently
146 : // with our scan. We check if the object is uploaded to S3 after taking the listing snapshot.
147 0 : let response = remote_client
148 0 : .head_object(&path, &CancellationToken::new())
149 0 : .await;
150 :
151 0 : if response.is_err() {
152 : // Object is not present.
153 0 : let is_l0 = LayerMap::is_l0(layer.key_range());
154 0 :
155 0 : let msg = format!(
156 0 : "index_part.json contains a layer {}{} (shard {}) that is not present in remote storage (layer_is_l0: {})",
157 0 : layer,
158 0 : metadata.generation.get_suffix(),
159 0 : metadata.shard,
160 0 : is_l0,
161 0 : );
162 0 :
163 0 : if is_l0 {
164 0 : result.warnings.push(msg);
165 0 : } else {
166 0 : result.errors.push(msg);
167 0 : }
168 0 : }
169 0 : }
170 : }
171 : }
172 0 : BlobDataParseResult::Relic => {}
173 : BlobDataParseResult::Incorrect {
174 0 : errors,
175 0 : s3_layers: _,
176 0 : } => result.errors.extend(
177 0 : errors
178 0 : .into_iter()
179 0 : .map(|error| format!("parse error: {error}")),
180 0 : ),
181 : }
182 : }
183 0 : None => result
184 0 : .errors
185 0 : .push("Timeline has no data on S3 at all".to_string()),
186 : }
187 :
188 0 : if result.errors.is_empty() {
189 0 : info!("No check errors found");
190 : } else {
191 0 : warn!("Timeline metadata errors: {0:?}", result.errors);
192 : }
193 :
194 0 : if !result.warnings.is_empty() {
195 0 : warn!("Timeline metadata warnings: {0:?}", result.warnings);
196 0 : }
197 :
198 0 : if !result.garbage_keys.is_empty() {
199 0 : error!(
200 0 : "The following keys should be removed from S3: {0:?}",
201 : result.garbage_keys
202 : )
203 0 : }
204 :
205 0 : result
206 0 : }
207 :
208 : #[derive(Default)]
209 : pub(crate) struct LayerRef {
210 : ref_count: usize,
211 : }
212 :
213 : /// Top-level index of objects in a tenant. This may be used by any shard-timeline within
214 : /// the tenant to query whether an object exists.
215 : #[derive(Default)]
216 : pub(crate) struct TenantObjectListing {
217 : shard_timelines: HashMap<(ShardIndex, TimelineId), HashMap<(LayerName, Generation), LayerRef>>,
218 : }
219 :
220 : impl TenantObjectListing {
221 : /// Having done an S3 listing of the keys within a timeline prefix, merge them into the overall
222 : /// list of layer keys for the Tenant.
223 0 : pub(crate) fn push(
224 0 : &mut self,
225 0 : ttid: TenantShardTimelineId,
226 0 : layers: HashSet<(LayerName, Generation)>,
227 0 : ) {
228 0 : let shard_index = ShardIndex::new(
229 0 : ttid.tenant_shard_id.shard_number,
230 0 : ttid.tenant_shard_id.shard_count,
231 0 : );
232 0 : let replaced = self.shard_timelines.insert(
233 0 : (shard_index, ttid.timeline_id),
234 0 : layers
235 0 : .into_iter()
236 0 : .map(|l| (l, LayerRef::default()))
237 0 : .collect(),
238 0 : );
239 0 :
240 0 : assert!(
241 0 : replaced.is_none(),
242 0 : "Built from an S3 object listing, which should never repeat a key"
243 : );
244 0 : }
245 :
246 : /// Having loaded a timeline index, check if a layer referenced by the index exists. If it does,
247 : /// the layer's refcount will be incremented. Later, after calling this for all references in all indices
248 : /// in a tenant, orphan layers may be detected by their zero refcounts.
249 : ///
250 : /// Returns true if the layer exists
251 0 : pub(crate) fn check_ref(
252 0 : &mut self,
253 0 : timeline_id: TimelineId,
254 0 : layer_file: &LayerName,
255 0 : metadata: &LayerFileMetadata,
256 0 : ) -> bool {
257 0 : let Some(shard_tl) = self.shard_timelines.get_mut(&(metadata.shard, timeline_id)) else {
258 0 : return false;
259 : };
260 :
261 0 : let Some(layer_ref) = shard_tl.get_mut(&(layer_file.clone(), metadata.generation)) else {
262 0 : return false;
263 : };
264 :
265 0 : layer_ref.ref_count += 1;
266 0 :
267 0 : true
268 0 : }
269 :
270 0 : pub(crate) fn get_orphans(&self) -> Vec<(ShardIndex, TimelineId, LayerName, Generation)> {
271 0 : let mut result = Vec::new();
272 0 : for ((shard_index, timeline_id), layers) in &self.shard_timelines {
273 0 : for ((layer_file, generation), layer_ref) in layers {
274 0 : if layer_ref.ref_count == 0 {
275 0 : result.push((*shard_index, *timeline_id, layer_file.clone(), *generation))
276 0 : }
277 : }
278 : }
279 :
280 0 : result
281 0 : }
282 : }
283 :
284 : #[derive(Debug)]
285 : pub(crate) struct RemoteTimelineBlobData {
286 : pub(crate) blob_data: BlobDataParseResult,
287 :
288 : // Index objects that were not used when loading `blob_data`, e.g. those from old generations
289 : pub(crate) unused_index_keys: Vec<ListingObject>,
290 :
291 : // Objects whose keys were not recognized at all, i.e. not layer files, not indices
292 : pub(crate) unknown_keys: Vec<ListingObject>,
293 : }
294 :
295 : #[derive(Debug)]
296 : pub(crate) enum BlobDataParseResult {
297 : Parsed {
298 : index_part: Box<IndexPart>,
299 : index_part_generation: Generation,
300 : s3_layers: HashSet<(LayerName, Generation)>,
301 : },
302 : /// The remains of a deleted Timeline (i.e. an initdb archive only)
303 : Relic,
304 : Incorrect {
305 : errors: Vec<String>,
306 : s3_layers: HashSet<(LayerName, Generation)>,
307 : },
308 : }
309 :
310 0 : pub(crate) fn parse_layer_object_name(name: &str) -> Result<(LayerName, Generation), String> {
311 0 : match name.rsplit_once('-') {
312 : // FIXME: this is gross, just use a regex?
313 0 : Some((layer_filename, gen)) if gen.len() == 8 => {
314 0 : let layer = layer_filename.parse::<LayerName>()?;
315 0 : let gen =
316 0 : Generation::parse_suffix(gen).ok_or("Malformed generation suffix".to_string())?;
317 0 : Ok((layer, gen))
318 : }
319 0 : _ => Ok((name.parse::<LayerName>()?, Generation::none())),
320 : }
321 0 : }
322 :
323 0 : pub(crate) async fn list_timeline_blobs(
324 0 : remote_client: &GenericRemoteStorage,
325 0 : id: TenantShardTimelineId,
326 0 : root_target: &RootTarget,
327 0 : ) -> anyhow::Result<RemoteTimelineBlobData> {
328 0 : let mut s3_layers = HashSet::new();
329 0 :
330 0 : let mut errors = Vec::new();
331 0 : let mut unknown_keys = Vec::new();
332 0 :
333 0 : let mut timeline_dir_target = root_target.timeline_root(&id);
334 0 : timeline_dir_target.delimiter = String::new();
335 0 :
336 0 : let mut index_part_keys: Vec<ListingObject> = Vec::new();
337 0 : let mut initdb_archive: bool = false;
338 0 :
339 0 : let prefix_str = &timeline_dir_target
340 0 : .prefix_in_bucket
341 0 : .strip_prefix("/")
342 0 : .unwrap_or(&timeline_dir_target.prefix_in_bucket);
343 0 :
344 0 : let mut stream = std::pin::pin!(stream_listing(remote_client, &timeline_dir_target));
345 0 : while let Some(obj) = stream.next().await {
346 0 : let (key, Some(obj)) = obj? else {
347 0 : panic!("ListingObject not specified");
348 : };
349 :
350 0 : let blob_name = key.get_path().as_str().strip_prefix(prefix_str);
351 0 : match blob_name {
352 0 : Some(name) if name.starts_with("index_part.json") => {
353 0 : tracing::debug!("Index key {key}");
354 0 : index_part_keys.push(obj)
355 : }
356 0 : Some("initdb.tar.zst") => {
357 0 : tracing::debug!("initdb archive {key}");
358 0 : initdb_archive = true;
359 : }
360 0 : Some("initdb-preserved.tar.zst") => {
361 0 : tracing::info!("initdb archive preserved {key}");
362 : }
363 0 : Some(maybe_layer_name) => match parse_layer_object_name(maybe_layer_name) {
364 0 : Ok((new_layer, gen)) => {
365 0 : tracing::debug!("Parsed layer key: {new_layer} {gen:?}");
366 0 : s3_layers.insert((new_layer, gen));
367 : }
368 0 : Err(e) => {
369 0 : tracing::info!("Error parsing key {maybe_layer_name}");
370 0 : errors.push(
371 0 : format!("S3 list response got an object with key {key} that is not a layer name: {e}"),
372 0 : );
373 0 : unknown_keys.push(obj);
374 : }
375 : },
376 : None => {
377 0 : tracing::warn!("Unknown key {key}");
378 0 : errors.push(format!("S3 list response got an object with odd key {key}"));
379 0 : unknown_keys.push(obj);
380 : }
381 : }
382 : }
383 :
384 0 : if index_part_keys.is_empty() && s3_layers.is_empty() && initdb_archive {
385 0 : tracing::debug!(
386 0 : "Timeline is empty apart from initdb archive: expected post-deletion state."
387 : );
388 0 : return Ok(RemoteTimelineBlobData {
389 0 : blob_data: BlobDataParseResult::Relic,
390 0 : unused_index_keys: index_part_keys,
391 0 : unknown_keys: Vec::new(),
392 0 : });
393 0 : }
394 :
395 : // Choose the index_part with the highest generation
396 0 : let (index_part_object, index_part_generation) = match index_part_keys
397 0 : .iter()
398 0 : .filter_map(|key| {
399 0 : // Stripping the index key to the last part, because RemotePath doesn't
400 0 : // like absolute paths, and depending on prefix_in_bucket it's possible
401 0 : // for the keys we read back to start with a slash.
402 0 : let basename = key.key.get_path().as_str().rsplit_once('/').unwrap().1;
403 0 : parse_remote_index_path(RemotePath::from_string(basename).unwrap()).map(|g| (key, g))
404 0 : })
405 0 : .max_by_key(|i| i.1)
406 0 : .map(|(k, g)| (k.clone(), g))
407 : {
408 0 : Some((key, gen)) => (Some::<ListingObject>(key.to_owned()), gen),
409 : None => {
410 : // Legacy/missing case: one or zero index parts, which did not have a generation
411 0 : (index_part_keys.pop(), Generation::none())
412 : }
413 : };
414 :
415 0 : match index_part_object.as_ref() {
416 0 : Some(selected) => index_part_keys.retain(|k| k != selected),
417 0 : None => {
418 0 : errors.push("S3 list response got no index_part.json file".to_string());
419 0 : }
420 : }
421 :
422 0 : if let Some(index_part_object_key) = index_part_object.as_ref() {
423 0 : let index_part_bytes =
424 0 : download_object_with_retries(remote_client, &index_part_object_key.key)
425 0 : .await
426 0 : .context("index_part.json download")?;
427 :
428 0 : match serde_json::from_slice(&index_part_bytes) {
429 0 : Ok(index_part) => {
430 0 : return Ok(RemoteTimelineBlobData {
431 0 : blob_data: BlobDataParseResult::Parsed {
432 0 : index_part: Box::new(index_part),
433 0 : index_part_generation,
434 0 : s3_layers,
435 0 : },
436 0 : unused_index_keys: index_part_keys,
437 0 : unknown_keys,
438 0 : })
439 : }
440 0 : Err(index_parse_error) => errors.push(format!(
441 0 : "index_part.json body parsing error: {index_parse_error}"
442 0 : )),
443 : }
444 0 : }
445 :
446 0 : if errors.is_empty() {
447 0 : errors.push(
448 0 : "Unexpected: no errors did not lead to a successfully parsed blob return".to_string(),
449 0 : );
450 0 : }
451 :
452 0 : Ok(RemoteTimelineBlobData {
453 0 : blob_data: BlobDataParseResult::Incorrect { errors, s3_layers },
454 0 : unused_index_keys: index_part_keys,
455 0 : unknown_keys,
456 0 : })
457 0 : }
|