idb/cli/mod.rs
1//! CLI subcommand implementations for the `inno` binary.
2//!
3//! The `inno` binary provides twenty subcommands for analyzing InnoDB data files,
4//! redo logs, and system tablespaces. CLI argument parsing uses clap derive macros,
5//! with the top-level [`app::Cli`] struct and [`app::Commands`] enum defined in
6//! [`app`] and shared between `main.rs` and `build.rs` (for man page generation)
7//! via `include!()`.
8//!
9//! Each subcommand module follows the same pattern: an `Options` struct holding
10//! the parsed arguments and a `pub fn execute(opts, writer) -> Result<(), IdbError>`
11//! entry point. The `writer: &mut dyn Write` parameter allows output to be
12//! captured in tests or redirected to a file via the global `--output` flag.
13//!
14//! # Subcommands
15//!
16//! | Command | Module | Purpose |
17//! |---------|--------|---------|
18//! | `inno parse` | [`parse`] | Parse FIL headers for every page and show a page-type summary table |
19//! | `inno pages` | [`pages`] | Deep structure analysis of INDEX, UNDO, BLOB/LOB, and SDI pages |
20//! | `inno dump` | [`dump`] | Hex dump of raw bytes by page number or absolute file offset |
21//! | `inno checksum` | [`checksum`] | Validate CRC-32C and legacy InnoDB checksums for every page |
22//! | `inno diff` | [`diff`] | Compare two tablespace files page-by-page and report differences |
23//! | `inno watch` | [`watch`] | Monitor a tablespace file for page-level changes in real time |
24//! | `inno corrupt` | [`corrupt`] | Inject random bytes into a page for testing recovery workflows |
25//! | `inno recover` | [`recover`] | Assess page-level recoverability and count salvageable records |
26//! | `inno repair` | [`repair`] | Recalculate and fix corrupt page checksums |
27//! | `inno find` | [`find`] | Search a MySQL data directory for pages matching a page number |
28//! | `inno tsid` | [`tsid`] | List or look up tablespace (space) IDs across `.ibd`/`.ibu` files |
29//! | `inno sdi` | [`sdi`] | Extract SDI metadata (MySQL 8.0+ serialized data dictionary) |
30//! | `inno schema` | [`schema`] | Extract schema and reconstruct DDL from tablespace metadata |
31//! | `inno export` | [`export`] | Export record-level data from INDEX pages as CSV, JSON, or hex |
32//! | `inno health` | [`health`] | Per-index B+Tree health metrics (fill factor, fragmentation, garbage) |
33//! | `inno log` | [`log`] | Analyze redo log file headers, checkpoints, and data blocks |
34//! | `inno info` | [`info`] | Inspect `ibdata1`, compare LSNs, or query a live MySQL instance |
35//! | `inno defrag` | [`defrag`] | Defragment a tablespace by reclaiming free space and reordering pages |
36//! | `inno transplant` | [`transplant`] | Copy specific pages from a donor tablespace into a target |
37//! | `inno audit` | [`audit`] | Audit a data directory for integrity, health, or corrupt pages |
38//! | `inno completions` | — | Generate shell completion scripts for bash, zsh, fish, or powershell |
39//!
40//! # Common patterns
41//!
42//! - **`--json`** — Every subcommand supports structured JSON output via
43//! `#[derive(Serialize)]` structs and `serde_json`.
44//! - **`--page-size`** — Override auto-detected page size (useful for non-standard
45//! 4K, 8K, 32K, or 64K tablespaces).
46//! - **`--verbose` / `-v`** — Show additional detail such as per-page checksum
47//! status, FSEG internals, or MLOG record types.
48//! - **`--color`** (global) — Control colored terminal output (`auto`, `always`,
49//! `never`).
50//! - **`--output` / `-o`** (global) — Redirect output to a file instead of stdout.
51//!
52//! Progress bars (via [`indicatif`]) are displayed for long-running operations
53//! in `parse`, `checksum`, `find`, and `audit`. The `wprintln!` and `wprint!` macros
54//! wrap `writeln!`/`write!` to convert `io::Error` into `IdbError`.
55
56pub mod app;
57pub mod audit;
58pub mod checksum;
59pub mod compat;
60pub mod corrupt;
61pub mod defrag;
62pub mod diff;
63pub mod dump;
64pub mod export;
65pub mod find;
66pub mod health;
67pub mod info;
68pub mod log;
69pub mod pages;
70pub mod parse;
71pub mod recover;
72pub mod repair;
73pub mod schema;
74pub mod sdi;
75pub mod transplant;
76pub mod tsid;
77pub mod validate;
78pub mod verify;
79pub mod watch;
80
81/// Write a line to the given writer, converting io::Error to IdbError.
82macro_rules! wprintln {
83 ($w:expr) => {
84 writeln!($w).map_err(|e| $crate::IdbError::Io(e.to_string()))
85 };
86 ($w:expr, $($arg:tt)*) => {
87 writeln!($w, $($arg)*).map_err(|e| $crate::IdbError::Io(e.to_string()))
88 };
89}
90
91/// Write (without newline) to the given writer, converting io::Error to IdbError.
92macro_rules! wprint {
93 ($w:expr, $($arg:tt)*) => {
94 write!($w, $($arg)*).map_err(|e| $crate::IdbError::Io(e.to_string()))
95 };
96}
97
98pub(crate) use wprint;
99pub(crate) use wprintln;
100
101/// Escape a string value for CSV output.
102///
103/// If the value contains a comma, double-quote, or newline, it is enclosed
104/// in double-quotes with internal double-quotes doubled. Otherwise the value
105/// is returned as-is.
106pub(crate) fn csv_escape(val: &str) -> String {
107 if val.contains(',') || val.contains('"') || val.contains('\n') {
108 format!("\"{}\"", val.replace('"', "\"\""))
109 } else {
110 val.to_string()
111 }
112}
113
114use crate::innodb::decryption::DecryptionContext;
115use crate::innodb::keyring::Keyring;
116use crate::innodb::tablespace::Tablespace;
117use crate::IdbError;
118use indicatif::{ProgressBar, ProgressStyle};
119
120/// Open a tablespace file, selecting mmap or buffered I/O based on the flag.
121///
122/// When `use_mmap` is true, the file is memory-mapped via `mmap(2)` for
123/// potentially better performance on large files (especially with parallel
124/// processing). When `page_size` is `Some`, auto-detection is bypassed.
125pub(crate) fn open_tablespace(
126 path: &str,
127 page_size: Option<u32>,
128 use_mmap: bool,
129) -> Result<Tablespace, IdbError> {
130 match (use_mmap, page_size) {
131 (true, Some(ps)) => Tablespace::open_mmap_with_page_size(path, ps),
132 (true, None) => Tablespace::open_mmap(path),
133 (false, Some(ps)) => Tablespace::open_with_page_size(path, ps),
134 (false, None) => Tablespace::open(path),
135 }
136}
137
138/// Set up decryption on a tablespace if a keyring path is provided.
139///
140/// Loads the keyring file, reads the encryption info from page 0,
141/// decrypts the tablespace key, and installs the decryption context
142/// on the tablespace for transparent page decryption.
143pub(crate) fn setup_decryption(ts: &mut Tablespace, keyring_path: &str) -> Result<(), IdbError> {
144 let keyring = Keyring::load(keyring_path)?;
145 let enc_info = ts.encryption_info().ok_or_else(|| {
146 IdbError::Parse(
147 "Keyring provided but tablespace has no encryption info on page 0".to_string(),
148 )
149 })?;
150 let ctx = DecryptionContext::from_encryption_info(enc_info, &keyring)?;
151 ts.set_decryption_context(ctx);
152 Ok(())
153}
154
155/// Create a styled progress bar for iterating over pages or files.
156pub(crate) fn create_progress_bar(count: u64, unit: &str) -> ProgressBar {
157 let pb = ProgressBar::new(count);
158 pb.set_style(
159 ProgressStyle::default_bar()
160 .template(&format!(
161 "{{spinner:.green}} [{{bar:40.cyan/blue}}] {{pos}}/{{len}} {} ({{eta}})",
162 unit
163 ))
164 .unwrap()
165 .progress_chars("#>-"),
166 );
167 pb
168}