Line data Source code
1 : use std::fs::{self, File};
2 : use std::path::{Path, PathBuf};
3 :
4 : use anyhow::Result;
5 : use camino::{Utf8Path, Utf8PathBuf};
6 : use clap::Subcommand;
7 : use pageserver::context::{DownloadBehavior, RequestContext};
8 : use pageserver::task_mgr::TaskKind;
9 : use pageserver::tenant::storage_layer::{DeltaLayer, ImageLayer, delta_layer, image_layer};
10 : use pageserver::tenant::{TENANTS_SEGMENT_NAME, TIMELINES_SEGMENT_NAME};
11 : use pageserver::virtual_file::api::IoMode;
12 : use pageserver::{page_cache, virtual_file};
13 : use pageserver_api::key::Key;
14 : use utils::id::{TenantId, TimelineId};
15 :
16 : use crate::layer_map_analyzer::parse_filename;
17 :
18 : #[derive(Subcommand)]
19 : pub(crate) enum LayerCmd {
20 : /// List all tenants and timelines under the pageserver path
21 : ///
22 : /// Example: `cargo run --bin pagectl layer list .neon/`
23 0 : List { path: PathBuf },
24 : /// List all layers of a given tenant and timeline
25 : ///
26 : /// Example: `cargo run --bin pagectl layer list .neon/`
27 : ListLayer {
28 0 : path: PathBuf,
29 0 : tenant: String,
30 0 : timeline: String,
31 : key: Option<Key>,
32 : },
33 : /// Dump all information of a layer file
34 : DumpLayer {
35 0 : path: PathBuf,
36 0 : tenant: String,
37 0 : timeline: String,
38 : /// The id from list-layer command
39 0 : id: usize,
40 : },
41 : RewriteSummary {
42 0 : layer_file_path: Utf8PathBuf,
43 : #[clap(long)]
44 : new_tenant_id: Option<TenantId>,
45 : #[clap(long)]
46 : new_timeline_id: Option<TimelineId>,
47 : },
48 : }
49 :
50 0 : async fn read_delta_file(path: impl AsRef<Path>, ctx: &RequestContext) -> Result<()> {
51 0 : virtual_file::init(
52 0 : 10,
53 0 : virtual_file::api::IoEngineKind::StdFs,
54 0 : IoMode::preferred(),
55 0 : virtual_file::SyncMode::Sync,
56 0 : );
57 0 : page_cache::init(100);
58 0 : let path = Utf8Path::from_path(path.as_ref()).expect("non-Unicode path");
59 0 : let file = File::open(path)?;
60 0 : let delta_layer = DeltaLayer::new_for_path(path, file)?;
61 0 : delta_layer.dump(true, ctx).await?;
62 0 : Ok(())
63 0 : }
64 :
65 0 : async fn read_image_file(path: impl AsRef<Path>, ctx: &RequestContext) -> Result<()> {
66 0 : virtual_file::init(
67 0 : 10,
68 0 : virtual_file::api::IoEngineKind::StdFs,
69 0 : IoMode::preferred(),
70 0 : virtual_file::SyncMode::Sync,
71 0 : );
72 0 : page_cache::init(100);
73 0 : let path = Utf8Path::from_path(path.as_ref()).expect("non-Unicode path");
74 0 : let file = File::open(path)?;
75 0 : let image_layer = ImageLayer::new_for_path(path, file)?;
76 0 : image_layer.dump(true, ctx).await?;
77 0 : Ok(())
78 0 : }
79 :
80 0 : pub(crate) async fn main(cmd: &LayerCmd) -> Result<()> {
81 0 : let ctx =
82 0 : RequestContext::new(TaskKind::DebugTool, DownloadBehavior::Error).with_scope_debug_tools();
83 0 : match cmd {
84 0 : LayerCmd::List { path } => {
85 0 : for tenant in fs::read_dir(path.join(TENANTS_SEGMENT_NAME))? {
86 0 : let tenant = tenant?;
87 0 : if !tenant.file_type()?.is_dir() {
88 0 : continue;
89 0 : }
90 0 : println!("tenant {}", tenant.file_name().to_string_lossy());
91 0 : for timeline in fs::read_dir(tenant.path().join(TIMELINES_SEGMENT_NAME))? {
92 0 : let timeline = timeline?;
93 0 : if !timeline.file_type()?.is_dir() {
94 0 : continue;
95 0 : }
96 0 : println!("- timeline {}", timeline.file_name().to_string_lossy());
97 : }
98 : }
99 0 : Ok(())
100 : }
101 : LayerCmd::ListLayer {
102 0 : path,
103 0 : tenant,
104 0 : timeline,
105 0 : key,
106 0 : } => {
107 0 : let timeline_path = path
108 0 : .join(TENANTS_SEGMENT_NAME)
109 0 : .join(tenant)
110 0 : .join(TIMELINES_SEGMENT_NAME)
111 0 : .join(timeline);
112 0 : let mut idx = 0;
113 0 : let mut to_print = Vec::default();
114 0 : for layer in fs::read_dir(timeline_path)? {
115 0 : let layer = layer?;
116 0 : if let Ok(layer_file) = parse_filename(&layer.file_name().into_string().unwrap()) {
117 0 : if let Some(key) = key {
118 0 : if layer_file.key_range.start <= *key && *key < layer_file.key_range.end {
119 0 : to_print.push((idx, layer_file));
120 0 : }
121 0 : } else {
122 0 : to_print.push((idx, layer_file));
123 0 : }
124 0 : idx += 1;
125 0 : }
126 : }
127 :
128 0 : if key.is_some() {
129 0 : to_print
130 0 : .sort_by_key(|(_idx, layer_file)| std::cmp::Reverse(layer_file.lsn_range.end));
131 0 : }
132 :
133 0 : for (idx, layer_file) in to_print {
134 0 : println!(
135 0 : "[{:3}] key:{}-{}\n lsn:{}-{}\n delta:{}",
136 0 : idx,
137 0 : layer_file.key_range.start,
138 0 : layer_file.key_range.end,
139 0 : layer_file.lsn_range.start,
140 0 : layer_file.lsn_range.end,
141 0 : layer_file.is_delta,
142 0 : );
143 0 : }
144 0 : Ok(())
145 : }
146 : LayerCmd::DumpLayer {
147 0 : path,
148 0 : tenant,
149 0 : timeline,
150 0 : id,
151 0 : } => {
152 0 : let timeline_path = path
153 0 : .join("tenants")
154 0 : .join(tenant)
155 0 : .join("timelines")
156 0 : .join(timeline);
157 0 : let mut idx = 0;
158 0 : for layer in fs::read_dir(timeline_path)? {
159 0 : let layer = layer?;
160 0 : if let Ok(layer_file) = parse_filename(&layer.file_name().into_string().unwrap()) {
161 0 : if *id == idx {
162 : // TODO(chi): dedup code
163 0 : println!(
164 0 : "[{:3}] key:{}-{}\n lsn:{}-{}\n delta:{}",
165 0 : idx,
166 0 : layer_file.key_range.start,
167 0 : layer_file.key_range.end,
168 0 : layer_file.lsn_range.start,
169 0 : layer_file.lsn_range.end,
170 0 : layer_file.is_delta,
171 0 : );
172 0 :
173 0 : if layer_file.is_delta {
174 0 : read_delta_file(layer.path(), &ctx).await?;
175 : } else {
176 0 : read_image_file(layer.path(), &ctx).await?;
177 : }
178 :
179 0 : break;
180 0 : }
181 0 : idx += 1;
182 0 : }
183 : }
184 0 : Ok(())
185 : }
186 : LayerCmd::RewriteSummary {
187 0 : layer_file_path,
188 0 : new_tenant_id,
189 0 : new_timeline_id,
190 0 : } => {
191 0 : pageserver::virtual_file::init(
192 0 : 10,
193 0 : virtual_file::api::IoEngineKind::StdFs,
194 0 : IoMode::preferred(),
195 0 : virtual_file::SyncMode::Sync,
196 0 : );
197 0 : pageserver::page_cache::init(100);
198 0 :
199 0 : let ctx = RequestContext::new(TaskKind::DebugTool, DownloadBehavior::Error)
200 0 : .with_scope_debug_tools();
201 :
202 : macro_rules! rewrite_closure {
203 : ($($summary_ty:tt)*) => {{
204 : |summary| $($summary_ty)* {
205 : tenant_id: new_tenant_id.unwrap_or(summary.tenant_id),
206 : timeline_id: new_timeline_id.unwrap_or(summary.timeline_id),
207 : ..summary
208 0 : }
209 : }};
210 : }
211 :
212 0 : let res = ImageLayer::rewrite_summary(
213 0 : layer_file_path,
214 0 : rewrite_closure!(image_layer::Summary),
215 0 : &ctx,
216 0 : )
217 0 : .await;
218 0 : match res {
219 : Ok(()) => {
220 0 : println!("Successfully rewrote summary of image layer {layer_file_path}");
221 0 : return Ok(());
222 : }
223 0 : Err(image_layer::RewriteSummaryError::MagicMismatch) => (), // fallthrough
224 0 : Err(image_layer::RewriteSummaryError::Other(e)) => {
225 0 : return Err(e);
226 : }
227 : }
228 :
229 0 : let res = DeltaLayer::rewrite_summary(
230 0 : layer_file_path,
231 0 : rewrite_closure!(delta_layer::Summary),
232 0 : &ctx,
233 0 : )
234 0 : .await;
235 0 : match res {
236 : Ok(()) => {
237 0 : println!("Successfully rewrote summary of delta layer {layer_file_path}");
238 0 : return Ok(());
239 : }
240 0 : Err(delta_layer::RewriteSummaryError::MagicMismatch) => (), // fallthrough
241 0 : Err(delta_layer::RewriteSummaryError::Other(e)) => {
242 0 : return Err(e);
243 : }
244 : }
245 :
246 0 : anyhow::bail!("not an image or delta layer: {layer_file_path}");
247 : }
248 : }
249 0 : }
|