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