Debian Codegraph @

cmd/influx_inspect/verify/tsm/verify.go

raw
1 // Package tsm verifies integrity of TSM files.
2 package tsm
3
4 import (
5 "flag"
6 "fmt"
7 "hash/crc32"
8 "io"
9 "os"
10 "path/filepath"
11 "text/tabwriter"
12 "time"
13
14 "github.com/influxdata/influxdb/tsdb/engine/tsm1"
15 )
16
17 // Command represents the program execution for "influx_inspect verify".
18 type Command struct {
19 Stderr io.Writer
20 Stdout io.Writer
21 }
22
23 // NewCommand returns a new instance of Command.
24 func NewCommand() *Command {
25 return &Command{
26 Stderr: os.Stderr,
27 Stdout: os.Stdout,
28 }
29 }
30
31 // Run executes the command.
32 func (cmd *Command) Run(args ...string) error {
33 var path string
34 fs := flag.NewFlagSet("verify", flag.ExitOnError)
35 fs.StringVar(&path, "dir", os.Getenv("HOME")+"/.influxdb", "Root storage path. [$HOME/.influxdb]")
36
37 fs.SetOutput(cmd.Stdout)
38 fs.Usage = cmd.printUsage
39
40 if err := fs.Parse(args); err != nil {
41 return err
42 }
43
44 start := time.Now()
45 dataPath := filepath.Join(path, "data")
46
47 brokenBlocks := 0
48 totalBlocks := 0
49
50 // No need to do this in a loop
51 ext := fmt.Sprintf(".%s", tsm1.TSMFileExtension)
52
53 // Get all TSM files by walking through the data dir
54 files := []string{}
55 err := filepath.Walk(dataPath, func(path string, f os.FileInfo, err error) error {
56 if err != nil {
57 return err
58 }
59 if filepath.Ext(path) == ext {
60 files = append(files, path)
61 }
62 return nil
63 })
64 if err != nil {
65 panic(err)
66 }
67
68 tw := tabwriter.NewWriter(cmd.Stdout, 16, 8, 0, '\t', 0)
69
70 // Verify the checksums of every block in every file
71 for _, f := range files {
72 file, err := os.OpenFile(f, os.O_RDONLY, 0600)
73 if err != nil {
74 return err
75 }
76
77 reader, err := tsm1.NewTSMReader(file)
78 if err != nil {
79 return err
80 }
81
82 blockItr := reader.BlockIterator()
83 brokenFileBlocks := 0
84 count := 0
85 for blockItr.Next() {
86 totalBlocks++
87 key, _, _, _, checksum, buf, err := blockItr.Read()
88 if err != nil {
89 brokenBlocks++
90 fmt.Fprintf(tw, "%s: could not get checksum for key %v block %d due to error: %q\n", f, key, count, err)
91 } else if expected := crc32.ChecksumIEEE(buf); checksum != expected {
92 brokenBlocks++
93 fmt.Fprintf(tw, "%s: got %d but expected %d for key %v, block %d\n", f, checksum, expected, key, count)
94 }
95 count++
96 }
97 if brokenFileBlocks == 0 {
98 fmt.Fprintf(tw, "%s: healthy\n", f)
99 }
100 reader.Close()
101 }
102
103 fmt.Fprintf(tw, "Broken Blocks: %d / %d, in %vs\n", brokenBlocks, totalBlocks, time.Since(start).Seconds())
104 tw.Flush()
105 return nil
106 }
107
108 // printUsage prints the usage message to STDERR.
109 func (cmd *Command) printUsage() {
110 usage := fmt.Sprintf(`Verifies the integrity of TSM files.
111
112 Usage: influx_inspect verify [flags]
113
114 -dir <path>
115 Root storage path
116 Defaults to "%[1]s/.influxdb".
117 `, os.Getenv("HOME"))
118
119 fmt.Fprintf(cmd.Stdout, usage)
120 }