LCOV - code coverage report
Current view: top level - storage_scrubber/src - main.rs (source / functions) Coverage Total Hit
Test: fc67f8dc6087a0b4f4f0bcd74f6e1dc25fab8cf3.info Lines: 0.0 % 305 0
Test Date: 2024-09-24 13:57:57 Functions: 0.0 % 79 0

            Line data    Source code
       1              : use anyhow::{anyhow, bail, Context};
       2              : use camino::Utf8PathBuf;
       3              : use pageserver_api::controller_api::{MetadataHealthUpdateRequest, MetadataHealthUpdateResponse};
       4              : use pageserver_api::shard::TenantShardId;
       5              : use reqwest::{Method, Url};
       6              : use storage_controller_client::control_api;
       7              : use storage_scrubber::garbage::{find_garbage, purge_garbage, PurgeMode};
       8              : use storage_scrubber::pageserver_physical_gc::GcMode;
       9              : use storage_scrubber::scan_pageserver_metadata::scan_pageserver_metadata;
      10              : use storage_scrubber::scan_safekeeper_metadata::DatabaseOrList;
      11              : use storage_scrubber::tenant_snapshot::SnapshotDownloader;
      12              : use storage_scrubber::{find_large_objects, ControllerClientConfig};
      13              : use storage_scrubber::{
      14              :     init_logging, pageserver_physical_gc::pageserver_physical_gc,
      15              :     scan_safekeeper_metadata::scan_safekeeper_metadata, BucketConfig, ConsoleConfig, NodeKind,
      16              :     TraversingDepth,
      17              : };
      18              : 
      19              : use clap::{Parser, Subcommand};
      20              : use utils::id::TenantId;
      21              : 
      22              : use utils::{project_build_tag, project_git_version};
      23              : 
      24              : project_git_version!(GIT_VERSION);
      25              : project_build_tag!(BUILD_TAG);
      26              : 
      27            0 : #[derive(Parser)]
      28              : #[command(author, version, about, long_about = None)]
      29              : #[command(arg_required_else_help(true))]
      30              : struct Cli {
      31              :     #[command(subcommand)]
      32              :     command: Command,
      33              : 
      34            0 :     #[arg(short, long, default_value_t = false)]
      35            0 :     delete: bool,
      36              : 
      37              :     #[arg(long)]
      38              :     /// URL to storage controller.  e.g. http://127.0.0.1:1234 when using `neon_local`
      39              :     controller_api: Option<Url>,
      40              : 
      41              :     #[arg(long)]
      42              :     /// JWT token for authenticating with storage controller.  Requires scope 'scrubber' or 'admin'.
      43              :     controller_jwt: Option<String>,
      44              : 
      45              :     /// If set to true, the scrubber will exit with error code on fatal error.
      46            0 :     #[arg(long, default_value_t = false)]
      47            0 :     exit_code: bool,
      48              : }
      49              : 
      50            0 : #[derive(Subcommand, Debug)]
      51              : enum Command {
      52              :     FindGarbage {
      53              :         #[arg(short, long)]
      54            0 :         node_kind: NodeKind,
      55            0 :         #[arg(short, long, default_value_t=TraversingDepth::Tenant)]
      56            0 :         depth: TraversingDepth,
      57            0 :         #[arg(short, long, default_value_t = String::from("garbage.json"))]
      58            0 :         output_path: String,
      59              :     },
      60              :     PurgeGarbage {
      61              :         #[arg(short, long)]
      62            0 :         input_path: String,
      63            0 :         #[arg(short, long, default_value_t = PurgeMode::DeletedOnly)]
      64            0 :         mode: PurgeMode,
      65              :         #[arg(long = "min-age")]
      66            0 :         min_age: humantime::Duration,
      67              :     },
      68              :     #[command(verbatim_doc_comment)]
      69              :     ScanMetadata {
      70              :         #[arg(short, long)]
      71            0 :         node_kind: NodeKind,
      72            0 :         #[arg(short, long, default_value_t = false)]
      73            0 :         json: bool,
      74              :         #[arg(long = "tenant-id", num_args = 0..)]
      75            0 :         tenant_ids: Vec<TenantShardId>,
      76            0 :         #[arg(long = "post", default_value_t = false)]
      77            0 :         post_to_storcon: bool,
      78              :         #[arg(long, default_value = None)]
      79              :         /// For safekeeper node_kind only, points to db with debug dump
      80              :         dump_db_connstr: Option<String>,
      81              :         /// For safekeeper node_kind only, table in the db with debug dump
      82              :         #[arg(long, default_value = None)]
      83              :         dump_db_table: Option<String>,
      84              :         /// For safekeeper node_kind only, json list of timelines and their lsn info
      85              :         #[arg(long, default_value = None)]
      86              :         timeline_lsns: Option<String>,
      87              :     },
      88              :     TenantSnapshot {
      89              :         #[arg(long = "tenant-id")]
      90            0 :         tenant_id: TenantId,
      91            0 :         #[arg(long = "concurrency", short = 'j', default_value_t = 8)]
      92            0 :         concurrency: usize,
      93              :         #[arg(short, long)]
      94            0 :         output_path: Utf8PathBuf,
      95              :     },
      96              :     PageserverPhysicalGc {
      97              :         #[arg(long = "tenant-id", num_args = 0..)]
      98            0 :         tenant_ids: Vec<TenantShardId>,
      99              :         #[arg(long = "min-age")]
     100            0 :         min_age: humantime::Duration,
     101            0 :         #[arg(short, long, default_value_t = GcMode::IndicesOnly)]
     102            0 :         mode: GcMode,
     103              :     },
     104              :     FindLargeObjects {
     105              :         #[arg(long = "min-size")]
     106            0 :         min_size: u64,
     107            0 :         #[arg(short, long, default_value_t = false)]
     108            0 :         ignore_deltas: bool,
     109            0 :         #[arg(long = "concurrency", short = 'j', default_value_t = 64)]
     110            0 :         concurrency: usize,
     111              :     },
     112              :     CronJob {
     113              :         // PageserverPhysicalGc
     114              :         #[arg(long = "min-age")]
     115            0 :         gc_min_age: humantime::Duration,
     116            0 :         #[arg(short, long, default_value_t = GcMode::IndicesOnly)]
     117            0 :         gc_mode: GcMode,
     118              :         // ScanMetadata
     119            0 :         #[arg(long = "post", default_value_t = false)]
     120            0 :         post_to_storcon: bool,
     121              :     },
     122              : }
     123              : 
     124              : #[tokio::main]
     125            0 : async fn main() -> anyhow::Result<()> {
     126            0 :     let cli = Cli::parse();
     127            0 : 
     128            0 :     let bucket_config = BucketConfig::from_env()?;
     129            0 : 
     130            0 :     let command_log_name = match &cli.command {
     131            0 :         Command::ScanMetadata { .. } => "scan",
     132            0 :         Command::FindGarbage { .. } => "find-garbage",
     133            0 :         Command::PurgeGarbage { .. } => "purge-garbage",
     134            0 :         Command::TenantSnapshot { .. } => "tenant-snapshot",
     135            0 :         Command::PageserverPhysicalGc { .. } => "pageserver-physical-gc",
     136            0 :         Command::FindLargeObjects { .. } => "find-large-objects",
     137            0 :         Command::CronJob { .. } => "cron-job",
     138            0 :     };
     139            0 :     let _guard = init_logging(&format!(
     140            0 :         "{}_{}_{}_{}.log",
     141            0 :         std::env::args().next().unwrap(),
     142            0 :         command_log_name,
     143            0 :         bucket_config.bucket,
     144            0 :         chrono::Utc::now().format("%Y_%m_%d__%H_%M_%S")
     145            0 :     ));
     146            0 : 
     147            0 :     tracing::info!("version: {}, build_tag {}", GIT_VERSION, BUILD_TAG);
     148            0 : 
     149            0 :     let controller_client = cli.controller_api.map(|controller_api| {
     150            0 :         ControllerClientConfig {
     151            0 :             controller_api,
     152            0 :             // Default to no key: this is a convenience when working in a development environment
     153            0 :             controller_jwt: cli.controller_jwt.unwrap_or("".to_owned()),
     154            0 :         }
     155            0 :         .build_client()
     156            0 :     });
     157            0 : 
     158            0 :     match cli.command {
     159            0 :         Command::ScanMetadata {
     160            0 :             json,
     161            0 :             tenant_ids,
     162            0 :             node_kind,
     163            0 :             post_to_storcon,
     164            0 :             dump_db_connstr,
     165            0 :             dump_db_table,
     166            0 :             timeline_lsns,
     167            0 :         } => {
     168            0 :             if let NodeKind::Safekeeper = node_kind {
     169            0 :                 let db_or_list = match (timeline_lsns, dump_db_connstr) {
     170            0 :                     (Some(timeline_lsns), _) => {
     171            0 :                         let timeline_lsns = serde_json::from_str(&timeline_lsns).context("parsing timeline_lsns")?;
     172            0 :                         DatabaseOrList::List(timeline_lsns)
     173            0 :                     }
     174            0 :                     (None, Some(dump_db_connstr)) => {
     175            0 :                         let dump_db_table = dump_db_table.ok_or_else(|| anyhow::anyhow!("dump_db_table not specified"))?;
     176            0 :                         let tenant_ids = tenant_ids.iter().map(|tshid| tshid.tenant_id).collect();
     177            0 :                         DatabaseOrList::Database { tenant_ids, connstr: dump_db_connstr, table: dump_db_table }
     178            0 :                     }
     179            0 :                     (None, None) => anyhow::bail!("neither `timeline_lsns` specified, nor `dump_db_connstr` and `dump_db_table`"),
     180            0 :                 };
     181            0 :                 let summary = scan_safekeeper_metadata(bucket_config.clone(), db_or_list).await?;
     182            0 :                 if json {
     183            0 :                     println!("{}", serde_json::to_string(&summary).unwrap())
     184            0 :                 } else {
     185            0 :                     println!("{}", summary.summary_string());
     186            0 :                 }
     187            0 :                 if summary.is_fatal() {
     188            0 :                     bail!("Fatal scrub errors detected");
     189            0 :                 }
     190            0 :                 if summary.is_empty() {
     191            0 :                     // Strictly speaking an empty bucket is a valid bucket, but if someone ran the
     192            0 :                     // scrubber they were likely expecting to scan something, and if we see no timelines
     193            0 :                     // at all then it's likely due to some configuration issues like a bad prefix
     194            0 :                     bail!(
     195            0 :                         "No timelines found in bucket {} prefix {}",
     196            0 :                         bucket_config.bucket,
     197            0 :                         bucket_config
     198            0 :                             .prefix_in_bucket
     199            0 :                             .unwrap_or("<none>".to_string())
     200            0 :                     );
     201            0 :                 }
     202            0 :                 Ok(())
     203            0 :             } else {
     204            0 :                 scan_pageserver_metadata_cmd(
     205            0 :                     bucket_config,
     206            0 :                     controller_client.as_ref(),
     207            0 :                     tenant_ids,
     208            0 :                     json,
     209            0 :                     post_to_storcon,
     210            0 :                     cli.exit_code,
     211            0 :                 )
     212            0 :                 .await
     213            0 :             }
     214            0 :         }
     215            0 :         Command::FindGarbage {
     216            0 :             node_kind,
     217            0 :             depth,
     218            0 :             output_path,
     219            0 :         } => {
     220            0 :             let console_config = ConsoleConfig::from_env()?;
     221            0 :             find_garbage(bucket_config, console_config, depth, node_kind, output_path).await
     222            0 :         }
     223            0 :         Command::PurgeGarbage {
     224            0 :             input_path,
     225            0 :             mode,
     226            0 :             min_age,
     227            0 :         } => purge_garbage(input_path, mode, min_age.into(), !cli.delete).await,
     228            0 :         Command::TenantSnapshot {
     229            0 :             tenant_id,
     230            0 :             output_path,
     231            0 :             concurrency,
     232            0 :         } => {
     233            0 :             let downloader =
     234            0 :                 SnapshotDownloader::new(bucket_config, tenant_id, output_path, concurrency).await?;
     235            0 :             downloader.download().await
     236            0 :         }
     237            0 :         Command::PageserverPhysicalGc {
     238            0 :             tenant_ids,
     239            0 :             min_age,
     240            0 :             mode,
     241            0 :         } => {
     242            0 :             pageserver_physical_gc_cmd(
     243            0 :                 &bucket_config,
     244            0 :                 controller_client.as_ref(),
     245            0 :                 tenant_ids,
     246            0 :                 min_age,
     247            0 :                 mode,
     248            0 :             )
     249            0 :             .await
     250            0 :         }
     251            0 :         Command::FindLargeObjects {
     252            0 :             min_size,
     253            0 :             ignore_deltas,
     254            0 :             concurrency,
     255            0 :         } => {
     256            0 :             let summary = find_large_objects::find_large_objects(
     257            0 :                 bucket_config,
     258            0 :                 min_size,
     259            0 :                 ignore_deltas,
     260            0 :                 concurrency,
     261            0 :             )
     262            0 :             .await?;
     263            0 :             println!("{}", serde_json::to_string(&summary).unwrap());
     264            0 :             Ok(())
     265            0 :         }
     266            0 :         Command::CronJob {
     267            0 :             gc_min_age,
     268            0 :             gc_mode,
     269            0 :             post_to_storcon,
     270            0 :         } => {
     271            0 :             run_cron_job(
     272            0 :                 bucket_config,
     273            0 :                 controller_client.as_ref(),
     274            0 :                 gc_min_age,
     275            0 :                 gc_mode,
     276            0 :                 post_to_storcon,
     277            0 :                 cli.exit_code,
     278            0 :             )
     279            0 :             .await
     280            0 :         }
     281            0 :     }
     282            0 : }
     283              : 
     284              : /// Runs the scrubber cron job.
     285              : /// 1. Do pageserver physical gc
     286              : /// 2. Scan pageserver metadata
     287            0 : pub async fn run_cron_job(
     288            0 :     bucket_config: BucketConfig,
     289            0 :     controller_client: Option<&control_api::Client>,
     290            0 :     gc_min_age: humantime::Duration,
     291            0 :     gc_mode: GcMode,
     292            0 :     post_to_storcon: bool,
     293            0 :     exit_code: bool,
     294            0 : ) -> anyhow::Result<()> {
     295            0 :     tracing::info!(%gc_min_age, %gc_mode, "Running pageserver-physical-gc");
     296            0 :     pageserver_physical_gc_cmd(
     297            0 :         &bucket_config,
     298            0 :         controller_client,
     299            0 :         Vec::new(),
     300            0 :         gc_min_age,
     301            0 :         gc_mode,
     302            0 :     )
     303            0 :     .await?;
     304            0 :     tracing::info!(%post_to_storcon, node_kind = %NodeKind::Pageserver, "Running scan-metadata");
     305            0 :     scan_pageserver_metadata_cmd(
     306            0 :         bucket_config,
     307            0 :         controller_client,
     308            0 :         Vec::new(),
     309            0 :         true,
     310            0 :         post_to_storcon,
     311            0 :         exit_code,
     312            0 :     )
     313            0 :     .await?;
     314              : 
     315            0 :     Ok(())
     316            0 : }
     317              : 
     318            0 : pub async fn pageserver_physical_gc_cmd(
     319            0 :     bucket_config: &BucketConfig,
     320            0 :     controller_client: Option<&control_api::Client>,
     321            0 :     tenant_shard_ids: Vec<TenantShardId>,
     322            0 :     min_age: humantime::Duration,
     323            0 :     mode: GcMode,
     324            0 : ) -> anyhow::Result<()> {
     325            0 :     match (controller_client, mode) {
     326            0 :         (Some(_), _) => {
     327            0 :             // Any mode may run when controller API is set
     328            0 :         }
     329              :         (None, GcMode::Full) => {
     330              :             // The part of physical GC where we erase ancestor layers cannot be done safely without
     331              :             // confirming the most recent complete shard split with the controller.  Refuse to run, rather
     332              :             // than doing it unsafely.
     333            0 :             return Err(anyhow!(
     334            0 :                 "Full physical GC requires `--controller-api` and `--controller-jwt` to run"
     335            0 :             ));
     336              :         }
     337            0 :         (None, GcMode::DryRun | GcMode::IndicesOnly) => {
     338            0 :             // These GcModes do not require the controller to run.
     339            0 :         }
     340              :     }
     341              : 
     342            0 :     let summary = pageserver_physical_gc(
     343            0 :         bucket_config,
     344            0 :         controller_client,
     345            0 :         tenant_shard_ids,
     346            0 :         min_age.into(),
     347            0 :         mode,
     348            0 :     )
     349            0 :     .await?;
     350            0 :     println!("{}", serde_json::to_string(&summary).unwrap());
     351            0 :     Ok(())
     352            0 : }
     353              : 
     354            0 : pub async fn scan_pageserver_metadata_cmd(
     355            0 :     bucket_config: BucketConfig,
     356            0 :     controller_client: Option<&control_api::Client>,
     357            0 :     tenant_shard_ids: Vec<TenantShardId>,
     358            0 :     json: bool,
     359            0 :     post_to_storcon: bool,
     360            0 :     exit_code: bool,
     361            0 : ) -> anyhow::Result<()> {
     362            0 :     if controller_client.is_none() && post_to_storcon {
     363            0 :         return Err(anyhow!("Posting pageserver scan health status to storage controller requires `--controller-api` and `--controller-jwt` to run"));
     364            0 :     }
     365            0 :     match scan_pageserver_metadata(bucket_config.clone(), tenant_shard_ids).await {
     366            0 :         Err(e) => {
     367            0 :             tracing::error!("Failed: {e}");
     368            0 :             Err(e)
     369              :         }
     370            0 :         Ok(summary) => {
     371            0 :             if json {
     372            0 :                 println!("{}", serde_json::to_string(&summary).unwrap())
     373            0 :             } else {
     374            0 :                 println!("{}", summary.summary_string());
     375            0 :             }
     376              : 
     377            0 :             if post_to_storcon {
     378            0 :                 if let Some(client) = controller_client {
     379            0 :                     let body = summary.build_health_update_request();
     380            0 :                     client
     381            0 :                         .dispatch::<MetadataHealthUpdateRequest, MetadataHealthUpdateResponse>(
     382            0 :                             Method::POST,
     383            0 :                             "control/v1/metadata_health/update".to_string(),
     384            0 :                             Some(body),
     385            0 :                         )
     386            0 :                         .await?;
     387            0 :                 }
     388            0 :             }
     389              : 
     390            0 :             if summary.is_fatal() {
     391            0 :                 tracing::error!("Fatal scrub errors detected");
     392            0 :                 if exit_code {
     393            0 :                     std::process::exit(1);
     394            0 :                 }
     395            0 :             } else if summary.is_empty() {
     396              :                 // Strictly speaking an empty bucket is a valid bucket, but if someone ran the
     397              :                 // scrubber they were likely expecting to scan something, and if we see no timelines
     398              :                 // at all then it's likely due to some configuration issues like a bad prefix
     399            0 :                 tracing::error!(
     400            0 :                     "No timelines found in bucket {} prefix {}",
     401            0 :                     bucket_config.bucket,
     402            0 :                     bucket_config
     403            0 :                         .prefix_in_bucket
     404            0 :                         .unwrap_or("<none>".to_string())
     405              :                 );
     406            0 :                 if exit_code {
     407            0 :                     std::process::exit(1);
     408            0 :                 }
     409            0 :             }
     410              : 
     411            0 :             Ok(())
     412              :         }
     413              :     }
     414            0 : }
        

Generated by: LCOV version 2.1-beta