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

Generated by: LCOV version 2.1-beta