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

Generated by: LCOV version 2.1-beta