innodb-utils 5.1.0

InnoDB file analysis toolkit
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
use std::io::Write;

use colored::Colorize;
use rayon::prelude::*;
use serde::Serialize;

use crate::cli::{create_progress_bar, wprintln};
use crate::innodb::checksum::{validate_checksum, validate_lsn, ChecksumAlgorithm, ChecksumResult};
use crate::innodb::page::FilHeader;
use crate::IdbError;

/// Options for the `inno checksum` subcommand.
pub struct ChecksumOptions {
    /// Path to the InnoDB tablespace file (.ibd).
    pub file: String,
    /// Show per-page checksum details.
    pub verbose: bool,
    /// Emit output as JSON.
    pub json: bool,
    /// Output as CSV.
    pub csv: bool,
    /// Override the auto-detected page size.
    pub page_size: Option<u32>,
    /// Path to MySQL keyring file for decrypting encrypted tablespaces.
    pub keyring: Option<String>,
    /// Number of threads for parallel processing (0 = auto-detect).
    pub threads: usize,
    /// Use memory-mapped I/O for file access.
    pub mmap: bool,
    /// Stream results incrementally for lower memory usage.
    pub streaming: bool,
}

#[derive(Serialize)]
struct ChecksumSummaryJson {
    file: String,
    page_size: u32,
    total_pages: u64,
    empty_pages: u64,
    valid_pages: u64,
    invalid_pages: u64,
    lsn_mismatches: u64,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pages: Vec<PageChecksumJson>,
}

#[derive(Serialize)]
struct PageChecksumJson {
    page_number: u64,
    status: String,
    algorithm: String,
    stored_checksum: u32,
    calculated_checksum: u32,
    lsn_valid: bool,
}

/// Result of validating a single page's checksum, used for parallel processing.
enum PageResult {
    /// Page header could not be parsed.
    ParseError,
    /// Page is all zeros (empty/allocated).
    Empty,
    /// Page was validated successfully.
    Validated {
        csum_result: ChecksumResult,
        lsn_valid: bool,
    },
}

/// Validate a single page's checksum and LSN. Pure function safe for parallel execution.
fn validate_page(
    page_data: &[u8],
    page_size: u32,
    vendor_info: &crate::innodb::vendor::VendorInfo,
) -> PageResult {
    let header = match FilHeader::parse(page_data) {
        Some(h) => h,
        None => return PageResult::ParseError,
    };

    if header.checksum == 0 && page_data.iter().all(|&b| b == 0) {
        return PageResult::Empty;
    }

    let csum_result = validate_checksum(page_data, page_size, Some(vendor_info));
    let lsn_valid = validate_lsn(page_data, page_size);

    PageResult::Validated {
        csum_result,
        lsn_valid,
    }
}

/// Validate page checksums for every page in an InnoDB tablespace.
///
/// Iterates over all pages and validates the stored checksum (bytes 0-3 of the
/// FIL header) against two algorithms: **CRC-32C** (MySQL 5.7.7+), which XORs
/// two independent CRC-32C values computed over bytes \[4..26) and
/// \[38..page_size-8); and **legacy InnoDB**, which uses `ut_fold_ulint_pair`
/// with u32 wrapping arithmetic over the same two byte ranges. A page is
/// considered valid if either algorithm matches the stored value.
///
/// Additionally checks **LSN consistency**: the low 32 bits of the header LSN
/// (bytes 16-23) must match the LSN value in the 8-byte FIL trailer at the
/// end of the page. All-zero pages are counted as empty and skipped entirely.
///
/// When the tablespace has more than one page, all page data is read into memory
/// and checksums are validated in parallel using rayon. Results are collected in
/// page order for deterministic output.
///
/// Prints a summary with total, empty, valid, and invalid page counts. In
/// `--verbose` mode, every non-empty page is printed with its algorithm,
/// stored and calculated checksum values, and LSN status. The process exits
/// with code 1 if any page has an invalid checksum, making this suitable for
/// scripted integrity checks.
///
/// **Note**: When `--streaming` is combined with `--json`, the output uses
/// NDJSON (one JSON object per line) rather than a single JSON document.
pub fn execute(opts: &ChecksumOptions, writer: &mut dyn Write) -> Result<(), IdbError> {
    let mut ts = crate::cli::open_tablespace(&opts.file, opts.page_size, opts.mmap)?;

    if let Some(ref keyring_path) = opts.keyring {
        crate::cli::setup_decryption(&mut ts, keyring_path)?;
    }

    let page_size = ts.page_size();
    let page_count = ts.page_count();
    let vendor_info = ts.vendor_info().clone();

    // Streaming mode: process one page at a time, output immediately
    if opts.streaming {
        return execute_streaming(opts, &mut ts, page_size, page_count, &vendor_info, writer);
    }

    // Read all pages into memory for parallel processing
    let all_data = ts.read_all_pages()?;
    let ps = page_size as usize;

    if opts.json {
        return execute_json_parallel(
            opts,
            &all_data,
            ps,
            page_size,
            page_count,
            &vendor_info,
            writer,
        );
    }

    if opts.csv {
        return execute_csv_parallel(&all_data, ps, page_size, page_count, &vendor_info, writer);
    }

    wprintln!(
        writer,
        "Validating checksums for {} ({} pages, page size {})...",
        opts.file,
        page_count,
        page_size
    )?;
    wprintln!(writer)?;

    // Create progress bar before parallel work so it tracks real progress
    let pb = create_progress_bar(page_count, "pages");

    // Process all pages in parallel
    let results: Vec<(u64, PageResult)> = (0..page_count)
        .into_par_iter()
        .map(|page_num| {
            let offset = page_num as usize * ps;
            if offset + ps > all_data.len() {
                pb.inc(1);
                return (page_num, PageResult::ParseError);
            }
            let page_data = &all_data[offset..offset + ps];
            let result = validate_page(page_data, page_size, &vendor_info);
            pb.inc(1);
            (page_num, result)
        })
        .collect();

    pb.finish_and_clear();

    // Output results sequentially in page order (rayon collect preserves order)
    let mut valid_count = 0u64;
    let mut invalid_count = 0u64;
    let mut empty_count = 0u64;
    let mut lsn_mismatch_count = 0u64;

    for (page_num, result) in &results {
        match result {
            PageResult::ParseError => {
                eprintln!("Page {}: Could not parse FIL header", page_num);
                invalid_count += 1;
            }
            PageResult::Empty => {
                empty_count += 1;
                if opts.verbose {
                    wprintln!(writer, "Page {}: EMPTY", page_num)?;
                }
            }
            PageResult::Validated {
                csum_result,
                lsn_valid,
            } => {
                if csum_result.valid {
                    valid_count += 1;
                    if opts.verbose {
                        wprintln!(
                            writer,
                            "Page {}: {} ({:?}, stored={}, calculated={})",
                            page_num,
                            "OK".green(),
                            csum_result.algorithm,
                            csum_result.stored_checksum,
                            csum_result.calculated_checksum,
                        )?;
                    }
                } else {
                    invalid_count += 1;
                    wprintln!(
                        writer,
                        "Page {}: {} checksum (stored={}, calculated={}, algorithm={:?})",
                        page_num,
                        "INVALID".red(),
                        csum_result.stored_checksum,
                        csum_result.calculated_checksum,
                        csum_result.algorithm,
                    )?;
                }

                if !lsn_valid {
                    lsn_mismatch_count += 1;
                    if csum_result.valid {
                        wprintln!(
                            writer,
                            "Page {}: {} - header LSN low32 does not match trailer",
                            page_num,
                            "LSN MISMATCH".yellow(),
                        )?;
                    }
                }
            }
        }
    }

    wprintln!(writer)?;
    wprintln!(writer, "Summary:")?;
    wprintln!(writer, "  Total pages: {}", page_count)?;
    wprintln!(writer, "  Empty pages: {}", empty_count)?;
    wprintln!(writer, "  Valid checksums: {}", valid_count)?;
    if invalid_count > 0 {
        wprintln!(
            writer,
            "  Invalid checksums: {}",
            format!("{}", invalid_count).red()
        )?;
    } else {
        wprintln!(
            writer,
            "  Invalid checksums: {}",
            format!("{}", invalid_count).green()
        )?;
    }
    if lsn_mismatch_count > 0 {
        wprintln!(
            writer,
            "  LSN mismatches: {}",
            format!("{}", lsn_mismatch_count).yellow()
        )?;
    }

    if invalid_count > 0 {
        return Err(IdbError::Parse(format!(
            "{} pages with invalid checksums",
            invalid_count
        )));
    }

    Ok(())
}

/// Return a short string name for a checksum algorithm.
fn algorithm_name(algo: ChecksumAlgorithm) -> &'static str {
    match algo {
        ChecksumAlgorithm::Crc32c => "crc32c",
        ChecksumAlgorithm::InnoDB => "innodb",
        ChecksumAlgorithm::MariaDbFullCrc32 => "mariadb_full_crc32",
        ChecksumAlgorithm::None => "none",
    }
}

/// Streaming mode: process pages one at a time via `for_each_page()`, writing
/// each result immediately. No progress bar, no bulk memory allocation.
/// JSON output uses NDJSON (one JSON object per line).
fn execute_streaming(
    opts: &ChecksumOptions,
    ts: &mut crate::innodb::tablespace::Tablespace,
    page_size: u32,
    page_count: u64,
    vendor_info: &crate::innodb::vendor::VendorInfo,
    writer: &mut dyn Write,
) -> Result<(), IdbError> {
    let mut valid_count = 0u64;
    let mut invalid_count = 0u64;
    let mut empty_count = 0u64;
    let mut lsn_mismatch_count = 0u64;

    if !opts.json {
        wprintln!(
            writer,
            "Validating checksums for {} ({} pages, page size {})...",
            opts.file,
            page_count,
            page_size
        )?;
        wprintln!(writer)?;
    }

    ts.for_each_page(|page_num, page_data| {
        let result = validate_page(page_data, page_size, vendor_info);

        match &result {
            PageResult::ParseError => {
                invalid_count += 1;
                if opts.json {
                    let obj = PageChecksumJson {
                        page_number: page_num,
                        status: "error".to_string(),
                        algorithm: "unknown".to_string(),
                        stored_checksum: 0,
                        calculated_checksum: 0,
                        lsn_valid: false,
                    };
                    let line = serde_json::to_string(&obj)
                        .map_err(|e| IdbError::Parse(format!("JSON error: {}", e)))?;
                    wprintln!(writer, "{}", line)?;
                } else {
                    eprintln!("Page {}: Could not parse FIL header", page_num);
                }
            }
            PageResult::Empty => {
                empty_count += 1;
                // In streaming JSON mode, skip empty pages (same as non-streaming)
                if !opts.json && opts.verbose {
                    wprintln!(writer, "Page {}: EMPTY", page_num)?;
                }
            }
            PageResult::Validated {
                csum_result,
                lsn_valid,
            } => {
                if csum_result.valid {
                    valid_count += 1;
                } else {
                    invalid_count += 1;
                }
                if !lsn_valid {
                    lsn_mismatch_count += 1;
                }

                if opts.json {
                    if opts.verbose || !csum_result.valid || !lsn_valid {
                        let obj = PageChecksumJson {
                            page_number: page_num,
                            status: if csum_result.valid {
                                "valid".to_string()
                            } else {
                                "invalid".to_string()
                            },
                            algorithm: algorithm_name(csum_result.algorithm).to_string(),
                            stored_checksum: csum_result.stored_checksum,
                            calculated_checksum: csum_result.calculated_checksum,
                            lsn_valid: *lsn_valid,
                        };
                        let line = serde_json::to_string(&obj)
                            .map_err(|e| IdbError::Parse(format!("JSON error: {}", e)))?;
                        wprintln!(writer, "{}", line)?;
                    }
                } else {
                    if csum_result.valid {
                        if opts.verbose {
                            wprintln!(
                                writer,
                                "Page {}: {} ({:?}, stored={}, calculated={})",
                                page_num,
                                "OK".green(),
                                csum_result.algorithm,
                                csum_result.stored_checksum,
                                csum_result.calculated_checksum,
                            )?;
                        }
                    } else {
                        wprintln!(
                            writer,
                            "Page {}: {} checksum (stored={}, calculated={}, algorithm={:?})",
                            page_num,
                            "INVALID".red(),
                            csum_result.stored_checksum,
                            csum_result.calculated_checksum,
                            csum_result.algorithm,
                        )?;
                    }

                    if !lsn_valid && csum_result.valid {
                        wprintln!(
                            writer,
                            "Page {}: {} - header LSN low32 does not match trailer",
                            page_num,
                            "LSN MISMATCH".yellow(),
                        )?;
                    }
                }
            }
        }
        Ok(())
    })?;

    if !opts.json {
        wprintln!(writer)?;
        wprintln!(writer, "Summary:")?;
        wprintln!(writer, "  Total pages: {}", page_count)?;
        wprintln!(writer, "  Empty pages: {}", empty_count)?;
        wprintln!(writer, "  Valid checksums: {}", valid_count)?;
        if invalid_count > 0 {
            wprintln!(
                writer,
                "  Invalid checksums: {}",
                format!("{}", invalid_count).red()
            )?;
        } else {
            wprintln!(
                writer,
                "  Invalid checksums: {}",
                format!("{}", invalid_count).green()
            )?;
        }
        if lsn_mismatch_count > 0 {
            wprintln!(
                writer,
                "  LSN mismatches: {}",
                format!("{}", lsn_mismatch_count).yellow()
            )?;
        }
    }

    if invalid_count > 0 {
        return Err(IdbError::Parse(format!(
            "{} pages with invalid checksums",
            invalid_count
        )));
    }

    Ok(())
}

fn execute_csv_parallel(
    all_data: &[u8],
    ps: usize,
    page_size: u32,
    page_count: u64,
    vendor_info: &crate::innodb::vendor::VendorInfo,
    writer: &mut dyn Write,
) -> Result<(), IdbError> {
    use rayon::prelude::*;

    wprintln!(
        writer,
        "page_number,status,algorithm,stored_checksum,calculated_checksum"
    )?;

    let results: Vec<(u64, PageResult)> = (0..page_count)
        .into_par_iter()
        .map(|page_num| {
            let offset = page_num as usize * ps;
            if offset + ps > all_data.len() {
                return (page_num, PageResult::ParseError);
            }
            let page_data = &all_data[offset..offset + ps];
            (page_num, validate_page(page_data, page_size, vendor_info))
        })
        .collect();

    for (page_num, result) in results {
        match result {
            PageResult::Empty | PageResult::ParseError => {}
            PageResult::Validated {
                csum_result,
                lsn_valid: _,
            } => {
                let algo = match csum_result.algorithm {
                    ChecksumAlgorithm::Crc32c => "crc32c",
                    ChecksumAlgorithm::InnoDB => "innodb",
                    ChecksumAlgorithm::MariaDbFullCrc32 => "mariadb_full_crc32",
                    ChecksumAlgorithm::None => "none",
                };
                let status = if csum_result.valid {
                    "valid"
                } else {
                    "invalid"
                };
                wprintln!(
                    writer,
                    "{},{},{},{},{}",
                    page_num,
                    status,
                    algo,
                    csum_result.stored_checksum,
                    csum_result.calculated_checksum
                )?;
            }
        }
    }
    Ok(())
}

fn execute_json_parallel(
    opts: &ChecksumOptions,
    all_data: &[u8],
    ps: usize,
    page_size: u32,
    page_count: u64,
    vendor_info: &crate::innodb::vendor::VendorInfo,
    writer: &mut dyn Write,
) -> Result<(), IdbError> {
    // Process all pages in parallel
    let results: Vec<(u64, PageResult)> = (0..page_count)
        .into_par_iter()
        .map(|page_num| {
            let offset = page_num as usize * ps;
            if offset + ps > all_data.len() {
                return (page_num, PageResult::ParseError);
            }
            let page_data = &all_data[offset..offset + ps];
            (page_num, validate_page(page_data, page_size, vendor_info))
        })
        .collect();

    let mut valid_count = 0u64;
    let mut invalid_count = 0u64;
    let mut empty_count = 0u64;
    let mut lsn_mismatch_count = 0u64;
    let mut pages = Vec::new();

    for (page_num, result) in &results {
        match result {
            PageResult::ParseError => {
                invalid_count += 1;
                if opts.verbose {
                    pages.push(PageChecksumJson {
                        page_number: *page_num,
                        status: "error".to_string(),
                        algorithm: "unknown".to_string(),
                        stored_checksum: 0,
                        calculated_checksum: 0,
                        lsn_valid: false,
                    });
                }
            }
            PageResult::Empty => {
                empty_count += 1;
            }
            PageResult::Validated {
                csum_result,
                lsn_valid,
            } => {
                if csum_result.valid {
                    valid_count += 1;
                } else {
                    invalid_count += 1;
                }
                if !lsn_valid {
                    lsn_mismatch_count += 1;
                }

                if opts.verbose || !csum_result.valid || !lsn_valid {
                    pages.push(PageChecksumJson {
                        page_number: *page_num,
                        status: if csum_result.valid {
                            "valid".to_string()
                        } else {
                            "invalid".to_string()
                        },
                        algorithm: algorithm_name(csum_result.algorithm).to_string(),
                        stored_checksum: csum_result.stored_checksum,
                        calculated_checksum: csum_result.calculated_checksum,
                        lsn_valid: *lsn_valid,
                    });
                }
            }
        }
    }

    let summary = ChecksumSummaryJson {
        file: opts.file.clone(),
        page_size,
        total_pages: page_count,
        empty_pages: empty_count,
        valid_pages: valid_count,
        invalid_pages: invalid_count,
        lsn_mismatches: lsn_mismatch_count,
        pages,
    };

    let json = serde_json::to_string_pretty(&summary)
        .map_err(|e| IdbError::Parse(format!("JSON serialization error: {}", e)))?;
    wprintln!(writer, "{}", json)?;

    if invalid_count > 0 {
        return Err(IdbError::Parse(format!(
            "{} pages with invalid checksums",
            invalid_count
        )));
    }

    Ok(())
}