Line data Source code
1 : use std::path::{Path, PathBuf};
2 :
3 : use anyhow::Result;
4 : use camino::{Utf8Path, Utf8PathBuf};
5 : use clap::Subcommand;
6 : use pageserver::context::{DownloadBehavior, RequestContext};
7 : use pageserver::task_mgr::TaskKind;
8 : use pageserver::tenant::block_io::BlockCursor;
9 : use pageserver::tenant::disk_btree::DiskBtreeReader;
10 : use pageserver::tenant::storage_layer::delta_layer::{BlobRef, Summary};
11 : use pageserver::tenant::storage_layer::{delta_layer, image_layer};
12 : use pageserver::tenant::storage_layer::{DeltaLayer, ImageLayer};
13 : use pageserver::tenant::{TENANTS_SEGMENT_NAME, TIMELINES_SEGMENT_NAME};
14 : use pageserver::{page_cache, virtual_file};
15 : use pageserver::{
16 : repository::{Key, KEY_SIZE},
17 : tenant::{
18 : block_io::FileBlockReader, disk_btree::VisitDirection,
19 : storage_layer::delta_layer::DELTA_KEY_SIZE,
20 : },
21 : virtual_file::VirtualFile,
22 : };
23 : use std::fs;
24 : use utils::bin_ser::BeSer;
25 : use utils::id::{TenantId, TimelineId};
26 :
27 : use crate::layer_map_analyzer::parse_filename;
28 :
29 0 : #[derive(Subcommand)]
30 : pub(crate) enum LayerCmd {
31 : /// List all tenants and timelines under the pageserver path
32 : ///
33 : /// Example: `cargo run --bin pagectl layer list .neon/`
34 0 : List { path: PathBuf },
35 : /// List all layers of a given tenant and timeline
36 : ///
37 : /// Example: `cargo run --bin pagectl layer list .neon/`
38 : ListLayer {
39 0 : path: PathBuf,
40 0 : tenant: String,
41 0 : timeline: String,
42 : },
43 : /// Dump all information of a layer file
44 : DumpLayer {
45 0 : path: PathBuf,
46 0 : tenant: String,
47 0 : timeline: String,
48 : /// The id from list-layer command
49 0 : id: usize,
50 : },
51 : RewriteSummary {
52 0 : layer_file_path: Utf8PathBuf,
53 : #[clap(long)]
54 : new_tenant_id: Option<TenantId>,
55 : #[clap(long)]
56 : new_timeline_id: Option<TimelineId>,
57 : },
58 : }
59 :
60 0 : async fn read_delta_file(path: impl AsRef<Path>, ctx: &RequestContext) -> Result<()> {
61 0 : let path = Utf8Path::from_path(path.as_ref()).expect("non-Unicode path");
62 0 : virtual_file::init(10, virtual_file::api::IoEngineKind::StdFs, 1);
63 0 : page_cache::init(100);
64 0 : let file = VirtualFile::open(path, ctx).await?;
65 0 : let file_id = page_cache::next_file_id();
66 0 : let block_reader = FileBlockReader::new(&file, file_id);
67 0 : let summary_blk = block_reader.read_blk(0, ctx).await?;
68 0 : let actual_summary = Summary::des_prefix(summary_blk.as_ref())?;
69 0 : let tree_reader = DiskBtreeReader::<_, DELTA_KEY_SIZE>::new(
70 0 : actual_summary.index_start_blk,
71 0 : actual_summary.index_root_blk,
72 0 : &block_reader,
73 0 : );
74 0 : // TODO(chi): dedup w/ `delta_layer.rs` by exposing the API.
75 0 : let mut all = vec![];
76 0 : tree_reader
77 0 : .visit(
78 0 : &[0u8; DELTA_KEY_SIZE],
79 0 : VisitDirection::Forwards,
80 0 : |key, value_offset| {
81 0 : let curr = Key::from_slice(&key[..KEY_SIZE]);
82 0 : all.push((curr, BlobRef(value_offset)));
83 0 : true
84 0 : },
85 0 : ctx,
86 0 : )
87 0 : .await?;
88 0 : let cursor = BlockCursor::new_fileblockreader(&block_reader);
89 0 : for (k, v) in all {
90 0 : let value = cursor.read_blob(v.pos(), ctx).await?;
91 0 : println!("key:{} value_len:{}", k, value.len());
92 0 : assert!(k.is_i128_representable(), "invalid key: ");
93 : }
94 : // TODO(chi): special handling for last key?
95 0 : Ok(())
96 0 : }
97 :
98 0 : pub(crate) async fn main(cmd: &LayerCmd) -> Result<()> {
99 0 : let ctx = RequestContext::new(TaskKind::DebugTool, DownloadBehavior::Error);
100 0 : match cmd {
101 0 : LayerCmd::List { path } => {
102 0 : for tenant in fs::read_dir(path.join(TENANTS_SEGMENT_NAME))? {
103 0 : let tenant = tenant?;
104 0 : if !tenant.file_type()?.is_dir() {
105 0 : continue;
106 0 : }
107 0 : println!("tenant {}", tenant.file_name().to_string_lossy());
108 0 : for timeline in fs::read_dir(tenant.path().join(TIMELINES_SEGMENT_NAME))? {
109 0 : let timeline = timeline?;
110 0 : if !timeline.file_type()?.is_dir() {
111 0 : continue;
112 0 : }
113 0 : println!("- timeline {}", timeline.file_name().to_string_lossy());
114 : }
115 : }
116 0 : Ok(())
117 : }
118 : LayerCmd::ListLayer {
119 0 : path,
120 0 : tenant,
121 0 : timeline,
122 0 : } => {
123 0 : let timeline_path = path
124 0 : .join(TENANTS_SEGMENT_NAME)
125 0 : .join(tenant)
126 0 : .join(TIMELINES_SEGMENT_NAME)
127 0 : .join(timeline);
128 0 : let mut idx = 0;
129 0 : for layer in fs::read_dir(timeline_path)? {
130 0 : let layer = layer?;
131 0 : if let Some(layer_file) = parse_filename(&layer.file_name().into_string().unwrap())
132 0 : {
133 0 : println!(
134 0 : "[{:3}] key:{}-{}\n lsn:{}-{}\n delta:{}",
135 0 : idx,
136 0 : layer_file.key_range.start,
137 0 : layer_file.key_range.end,
138 0 : layer_file.lsn_range.start,
139 0 : layer_file.lsn_range.end,
140 0 : layer_file.is_delta,
141 0 : );
142 0 : idx += 1;
143 0 : }
144 : }
145 0 : Ok(())
146 : }
147 : LayerCmd::DumpLayer {
148 0 : path,
149 0 : tenant,
150 0 : timeline,
151 0 : id,
152 0 : } => {
153 0 : let timeline_path = path
154 0 : .join("tenants")
155 0 : .join(tenant)
156 0 : .join("timelines")
157 0 : .join(timeline);
158 0 : let mut idx = 0;
159 0 : for layer in fs::read_dir(timeline_path)? {
160 0 : let layer = layer?;
161 0 : if let Some(layer_file) = parse_filename(&layer.file_name().into_string().unwrap())
162 : {
163 0 : if *id == idx {
164 : // TODO(chi): dedup code
165 0 : println!(
166 0 : "[{:3}] key:{}-{}\n lsn:{}-{}\n delta:{}",
167 0 : idx,
168 0 : layer_file.key_range.start,
169 0 : layer_file.key_range.end,
170 0 : layer_file.lsn_range.start,
171 0 : layer_file.lsn_range.end,
172 0 : layer_file.is_delta,
173 0 : );
174 0 :
175 0 : if layer_file.is_delta {
176 0 : read_delta_file(layer.path(), &ctx).await?;
177 : } else {
178 0 : anyhow::bail!("not supported yet :(");
179 : }
180 :
181 0 : break;
182 0 : }
183 0 : idx += 1;
184 0 : }
185 : }
186 0 : Ok(())
187 : }
188 : LayerCmd::RewriteSummary {
189 0 : layer_file_path,
190 0 : new_tenant_id,
191 0 : new_timeline_id,
192 0 : } => {
193 0 : pageserver::virtual_file::init(
194 0 : 10,
195 0 : virtual_file::api::IoEngineKind::StdFs,
196 0 : pageserver_api::config::defaults::DEFAULT_IO_BUFFER_ALIGNMENT,
197 0 : );
198 0 : pageserver::page_cache::init(100);
199 0 :
200 0 : let ctx = RequestContext::new(TaskKind::DebugTool, DownloadBehavior::Error);
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 : }
|