Line data Source code
1 : //! A helper tool to manage pageserver binary files.
2 : //! Accepts a file as an argument, attempts to parse it with all ways possible
3 : //! and prints its interpreted context.
4 : //!
5 : //! Separate, `metadata` subcommand allows to print and update pageserver's metadata file.
6 :
7 : mod draw_timeline_dir;
8 : mod index_part;
9 : mod key;
10 : mod layer_map_analyzer;
11 : mod layers;
12 :
13 : use std::{
14 : str::FromStr,
15 : time::{Duration, SystemTime},
16 : };
17 :
18 : use camino::{Utf8Path, Utf8PathBuf};
19 : use clap::{Parser, Subcommand};
20 : use index_part::IndexPartCmd;
21 : use layers::LayerCmd;
22 : use pageserver::{
23 : config::defaults::DEFAULT_IO_BUFFER_ALIGNMENT,
24 : context::{DownloadBehavior, RequestContext},
25 : page_cache,
26 : task_mgr::TaskKind,
27 : tenant::{dump_layerfile_from_path, metadata::TimelineMetadata},
28 : virtual_file,
29 : };
30 : use pageserver_api::shard::TenantShardId;
31 : use postgres_ffi::ControlFileData;
32 : use remote_storage::{RemotePath, RemoteStorageConfig};
33 : use tokio_util::sync::CancellationToken;
34 : use utils::{
35 : id::TimelineId,
36 : logging::{self, LogFormat, TracingErrorLayerEnablement},
37 : lsn::Lsn,
38 : project_git_version,
39 : };
40 :
41 : project_git_version!(GIT_VERSION);
42 :
43 0 : #[derive(Parser)]
44 : #[command(
45 : version = GIT_VERSION,
46 : about = "Neon Pageserver binutils",
47 : long_about = "Reads pageserver (and related) binary files management utility"
48 : )]
49 : #[command(propagate_version = true)]
50 : struct CliOpts {
51 : #[command(subcommand)]
52 : command: Commands,
53 : }
54 :
55 0 : #[derive(Subcommand)]
56 : enum Commands {
57 : Metadata(MetadataCmd),
58 : #[command(subcommand)]
59 : IndexPart(IndexPartCmd),
60 : PrintLayerFile(PrintLayerFileCmd),
61 : TimeTravelRemotePrefix(TimeTravelRemotePrefixCmd),
62 : DrawTimeline {},
63 : AnalyzeLayerMap(AnalyzeLayerMapCmd),
64 : #[command(subcommand)]
65 : Layer(LayerCmd),
66 : /// Debug print a hex key found from logs
67 : Key(key::DescribeKeyCommand),
68 : }
69 :
70 : /// Read and update pageserver metadata file
71 0 : #[derive(Parser)]
72 : struct MetadataCmd {
73 : /// Input metadata file path
74 0 : metadata_path: Utf8PathBuf,
75 : /// Replace disk consistent Lsn
76 : disk_consistent_lsn: Option<Lsn>,
77 : /// Replace previous record Lsn
78 : prev_record_lsn: Option<Lsn>,
79 : /// Replace latest gc cuttoff
80 : latest_gc_cuttoff: Option<Lsn>,
81 : }
82 :
83 0 : #[derive(Parser)]
84 : struct PrintLayerFileCmd {
85 : /// Pageserver data path
86 0 : path: Utf8PathBuf,
87 : }
88 :
89 : /// Roll back the time for the specified prefix using S3 history.
90 : ///
91 : /// The command is fairly low level and powerful. Validation is only very light,
92 : /// so it is more powerful, and thus potentially more dangerous.
93 0 : #[derive(Parser)]
94 : struct TimeTravelRemotePrefixCmd {
95 : /// A configuration string for the remote_storage configuration.
96 : ///
97 : /// Example: `remote_storage = { bucket_name = "aws-storage-bucket-name", bucket_region = "us-east-2" }`
98 0 : config_toml_str: String,
99 : /// remote prefix to time travel recover. For safety reasons, we require it to contain
100 : /// a timeline or tenant ID in the prefix.
101 0 : prefix: String,
102 : /// Timestamp to travel to. Given in format like `2024-01-20T10:45:45Z`. Assumes UTC and second accuracy.
103 0 : travel_to: String,
104 : /// Timestamp of the start of the operation, must be after any changes we want to roll back and after.
105 : /// You can use a few seconds before invoking the command. Same format as `travel_to`.
106 : done_if_after: Option<String>,
107 : }
108 :
109 0 : #[derive(Parser)]
110 : struct AnalyzeLayerMapCmd {
111 : /// Pageserver data path
112 0 : path: Utf8PathBuf,
113 : /// Max holes
114 : max_holes: Option<usize>,
115 : }
116 :
117 : #[tokio::main]
118 0 : async fn main() -> anyhow::Result<()> {
119 0 : logging::init(
120 0 : LogFormat::Plain,
121 0 : TracingErrorLayerEnablement::EnableWithRustLogFilter,
122 0 : logging::Output::Stdout,
123 0 : )?;
124 0 :
125 0 : logging::replace_panic_hook_with_tracing_panic_hook().forget();
126 0 :
127 0 : let cli = CliOpts::parse();
128 0 :
129 0 : match cli.command {
130 0 : Commands::Layer(cmd) => {
131 0 : layers::main(&cmd).await?;
132 0 : }
133 0 : Commands::Metadata(cmd) => {
134 0 : handle_metadata(&cmd)?;
135 0 : }
136 0 : Commands::IndexPart(cmd) => {
137 0 : index_part::main(&cmd).await?;
138 0 : }
139 0 : Commands::DrawTimeline {} => {
140 0 : draw_timeline_dir::main()?;
141 0 : }
142 0 : Commands::AnalyzeLayerMap(cmd) => {
143 0 : layer_map_analyzer::main(&cmd).await?;
144 0 : }
145 0 : Commands::PrintLayerFile(cmd) => {
146 0 : if let Err(e) = read_pg_control_file(&cmd.path) {
147 0 : println!(
148 0 : "Failed to read input file as a pg control one: {e:#}\n\
149 0 : Attempting to read it as layer file"
150 0 : );
151 0 : print_layerfile(&cmd.path).await?;
152 0 : }
153 0 : }
154 0 : Commands::TimeTravelRemotePrefix(cmd) => {
155 0 : let timestamp = humantime::parse_rfc3339(&cmd.travel_to)
156 0 : .map_err(|_e| anyhow::anyhow!("Invalid time for travel_to: '{}'", cmd.travel_to))?;
157 0 :
158 0 : let done_if_after = if let Some(done_if_after) = &cmd.done_if_after {
159 0 : humantime::parse_rfc3339(done_if_after).map_err(|_e| {
160 0 : anyhow::anyhow!("Invalid time for done_if_after: '{}'", done_if_after)
161 0 : })?
162 0 : } else {
163 0 : const SAFETY_MARGIN: Duration = Duration::from_secs(3);
164 0 : tokio::time::sleep(SAFETY_MARGIN).await;
165 0 : // Convert to string representation and back to get rid of sub-second values
166 0 : let done_if_after = SystemTime::now();
167 0 : tokio::time::sleep(SAFETY_MARGIN).await;
168 0 : done_if_after
169 0 : };
170 0 :
171 0 : let timestamp = strip_subsecond(timestamp);
172 0 : let done_if_after = strip_subsecond(done_if_after);
173 0 :
174 0 : let Some(prefix) = validate_prefix(&cmd.prefix) else {
175 0 : println!("specified prefix '{}' failed validation", cmd.prefix);
176 0 : return Ok(());
177 0 : };
178 0 : let toml_document = toml_edit::Document::from_str(&cmd.config_toml_str)?;
179 0 : let toml_item = toml_document
180 0 : .get("remote_storage")
181 0 : .expect("need remote_storage");
182 0 : let config = RemoteStorageConfig::from_toml(toml_item)?;
183 0 : let storage = remote_storage::GenericRemoteStorage::from_config(&config).await;
184 0 : let cancel = CancellationToken::new();
185 0 : storage
186 0 : .unwrap()
187 0 : .time_travel_recover(Some(&prefix), timestamp, done_if_after, &cancel)
188 0 : .await?;
189 0 : }
190 0 : Commands::Key(dkc) => dkc.execute(),
191 0 : };
192 0 : Ok(())
193 0 : }
194 :
195 0 : fn read_pg_control_file(control_file_path: &Utf8Path) -> anyhow::Result<()> {
196 0 : let control_file = ControlFileData::decode(&std::fs::read(control_file_path)?)?;
197 0 : println!("{control_file:?}");
198 0 : let control_file_initdb = Lsn(control_file.checkPoint);
199 0 : println!(
200 0 : "pg_initdb_lsn: {}, aligned: {}",
201 0 : control_file_initdb,
202 0 : control_file_initdb.align()
203 0 : );
204 0 : Ok(())
205 0 : }
206 :
207 0 : async fn print_layerfile(path: &Utf8Path) -> anyhow::Result<()> {
208 0 : // Basic initialization of things that don't change after startup
209 0 : virtual_file::init(
210 0 : 10,
211 0 : virtual_file::api::IoEngineKind::StdFs,
212 0 : DEFAULT_IO_BUFFER_ALIGNMENT,
213 0 : );
214 0 : page_cache::init(100);
215 0 : let ctx = RequestContext::new(TaskKind::DebugTool, DownloadBehavior::Error);
216 0 : dump_layerfile_from_path(path, true, &ctx).await
217 0 : }
218 :
219 0 : fn handle_metadata(
220 0 : MetadataCmd {
221 0 : metadata_path: path,
222 0 : disk_consistent_lsn,
223 0 : prev_record_lsn,
224 0 : latest_gc_cuttoff,
225 0 : }: &MetadataCmd,
226 0 : ) -> Result<(), anyhow::Error> {
227 0 : let metadata_bytes = std::fs::read(path)?;
228 0 : let mut meta = TimelineMetadata::from_bytes(&metadata_bytes)?;
229 0 : println!("Current metadata:\n{meta:?}");
230 0 : let mut update_meta = false;
231 : // TODO: simplify this part
232 0 : if let Some(disk_consistent_lsn) = disk_consistent_lsn {
233 0 : meta = TimelineMetadata::new(
234 0 : *disk_consistent_lsn,
235 0 : meta.prev_record_lsn(),
236 0 : meta.ancestor_timeline(),
237 0 : meta.ancestor_lsn(),
238 0 : meta.latest_gc_cutoff_lsn(),
239 0 : meta.initdb_lsn(),
240 0 : meta.pg_version(),
241 0 : );
242 0 : update_meta = true;
243 0 : }
244 0 : if let Some(prev_record_lsn) = prev_record_lsn {
245 0 : meta = TimelineMetadata::new(
246 0 : meta.disk_consistent_lsn(),
247 0 : Some(*prev_record_lsn),
248 0 : meta.ancestor_timeline(),
249 0 : meta.ancestor_lsn(),
250 0 : meta.latest_gc_cutoff_lsn(),
251 0 : meta.initdb_lsn(),
252 0 : meta.pg_version(),
253 0 : );
254 0 : update_meta = true;
255 0 : }
256 0 : if let Some(latest_gc_cuttoff) = latest_gc_cuttoff {
257 0 : meta = TimelineMetadata::new(
258 0 : meta.disk_consistent_lsn(),
259 0 : meta.prev_record_lsn(),
260 0 : meta.ancestor_timeline(),
261 0 : meta.ancestor_lsn(),
262 0 : *latest_gc_cuttoff,
263 0 : meta.initdb_lsn(),
264 0 : meta.pg_version(),
265 0 : );
266 0 : update_meta = true;
267 0 : }
268 :
269 0 : if update_meta {
270 0 : let metadata_bytes = meta.to_bytes()?;
271 0 : std::fs::write(path, metadata_bytes)?;
272 0 : }
273 :
274 0 : Ok(())
275 0 : }
276 :
277 : /// Ensures that the given S3 prefix is sufficiently constrained.
278 : /// The command is very risky already and we don't want to expose something
279 : /// that allows usually unintentional and quite catastrophic time travel of
280 : /// an entire bucket, which would be a major catastrophy and away
281 : /// by only one character change (similar to "rm -r /home /username/foobar").
282 15 : fn validate_prefix(prefix: &str) -> Option<RemotePath> {
283 15 : if prefix.is_empty() {
284 : // Empty prefix means we want to specify the *whole* bucket
285 1 : return None;
286 14 : }
287 14 : let components = prefix.split('/').collect::<Vec<_>>();
288 14 : let (last, components) = {
289 14 : let last = components.last()?;
290 14 : if last.is_empty() {
291 : (
292 7 : components.iter().nth_back(1)?,
293 7 : &components[..(components.len() - 1)],
294 : )
295 : } else {
296 7 : (last, &components[..])
297 : }
298 : };
299 : 'valid: {
300 14 : if let Ok(_timeline_id) = TimelineId::from_str(last) {
301 : // Ends in either a tenant or timeline ID
302 5 : break 'valid;
303 9 : }
304 9 : if *last == "timelines" {
305 3 : if let Some(before_last) = components.iter().nth_back(1) {
306 3 : if let Ok(_tenant_id) = TenantShardId::from_str(before_last) {
307 : // Has a valid tenant id
308 3 : break 'valid;
309 0 : }
310 0 : }
311 6 : }
312 :
313 6 : return None;
314 : }
315 8 : RemotePath::from_string(prefix).ok()
316 15 : }
317 :
318 0 : fn strip_subsecond(timestamp: SystemTime) -> SystemTime {
319 0 : let ts_str = humantime::format_rfc3339_seconds(timestamp).to_string();
320 0 : humantime::parse_rfc3339(&ts_str).expect("can't parse just created timestamp")
321 0 : }
322 :
323 : #[cfg(test)]
324 : mod tests {
325 : use super::*;
326 :
327 : #[test]
328 1 : fn test_validate_prefix() {
329 1 : assert_eq!(validate_prefix(""), None);
330 1 : assert_eq!(validate_prefix("/"), None);
331 : #[track_caller]
332 7 : fn assert_valid(prefix: &str) {
333 7 : let remote_path = RemotePath::from_string(prefix).unwrap();
334 7 : assert_eq!(validate_prefix(prefix), Some(remote_path));
335 7 : }
336 1 : assert_valid("wal/3aa8fcc61f6d357410b7de754b1d9001/641e5342083b2235ee3deb8066819683/");
337 1 : // Path is not relative but absolute
338 1 : assert_eq!(
339 1 : validate_prefix(
340 1 : "/wal/3aa8fcc61f6d357410b7de754b1d9001/641e5342083b2235ee3deb8066819683/"
341 1 : ),
342 1 : None
343 1 : );
344 1 : assert_valid("wal/3aa8fcc61f6d357410b7de754b1d9001/");
345 1 : // Partial tenant IDs should be invalid, S3 will match all tenants with the specific ID prefix
346 1 : assert_eq!(validate_prefix("wal/3aa8fcc61f6d357410b7d"), None);
347 1 : assert_eq!(validate_prefix("wal"), None);
348 1 : assert_eq!(validate_prefix("/wal/"), None);
349 1 : assert_valid("pageserver/v1/tenants/3aa8fcc61f6d357410b7de754b1d9001");
350 1 : // Partial tenant ID
351 1 : assert_eq!(
352 1 : validate_prefix("pageserver/v1/tenants/3aa8fcc61f6d357410b"),
353 1 : None
354 1 : );
355 1 : assert_valid("pageserver/v1/tenants/3aa8fcc61f6d357410b7de754b1d9001/timelines");
356 1 : assert_valid("pageserver/v1/tenants/3aa8fcc61f6d357410b7de754b1d9001-0004/timelines");
357 1 : assert_valid("pageserver/v1/tenants/3aa8fcc61f6d357410b7de754b1d9001/timelines/");
358 1 : assert_valid("pageserver/v1/tenants/3aa8fcc61f6d357410b7de754b1d9001/timelines/641e5342083b2235ee3deb8066819683");
359 1 : assert_eq!(validate_prefix("pageserver/v1/tenants/"), None);
360 1 : }
361 : }
|