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