Debian Codegraph @

cmd/influx_inspect/buildtsi/buildtsi.go

raw
1 // Package buildtsi reads an in-memory index and exports it as a TSI index.
2 package buildtsi
3
4 import (
5 "flag"
6 "fmt"
7 "io"
8 "io/ioutil"
9 "os"
10 "os/user"
11 "path/filepath"
12 "runtime"
13 "strconv"
14 "strings"
15 "sync/atomic"
16
17 "github.com/influxdata/influxdb/logger"
18 "github.com/influxdata/influxdb/models"
19 "github.com/influxdata/influxdb/tsdb"
20 "github.com/influxdata/influxdb/tsdb/engine/tsm1"
21 "github.com/influxdata/influxdb/tsdb/index/tsi1"
22 "go.uber.org/zap"
23 )
24
25 const defaultBatchSize = 10000
26
27 // Command represents the program execution for "influx_inspect buildtsi".
28 type Command struct {
29 Stderr io.Writer
30 Stdout io.Writer
31 Verbose bool
32 Logger *zap.Logger
33
34 concurrency int // Number of goroutines to dedicate to shard index building.
35 databaseFilter string
36 retentionFilter string
37 shardFilter string
38 maxLogFileSize int64
39 maxCacheSize uint64
40 batchSize int
41 }
42
43 // NewCommand returns a new instance of Command.
44 func NewCommand() *Command {
45 return &Command{
46 Stderr: os.Stderr,
47 Stdout: os.Stdout,
48 Logger: zap.NewNop(),
49 batchSize: defaultBatchSize,
50 concurrency: runtime.GOMAXPROCS(0),
51 }
52 }
53
54 // Run executes the command.
55 func (cmd *Command) Run(args ...string) error {
56 fs := flag.NewFlagSet("buildtsi", flag.ExitOnError)
57 dataDir := fs.String("datadir", "", "data directory")
58 walDir := fs.String("waldir", "", "WAL directory")
59 fs.IntVar(&cmd.concurrency, "concurrency", runtime.GOMAXPROCS(0), "Number of workers to dedicate to shard index building. Defaults to GOMAXPROCS")
60 fs.StringVar(&cmd.databaseFilter, "database", "", "optional: database name")
61 fs.StringVar(&cmd.retentionFilter, "retention", "", "optional: retention policy")
62 fs.StringVar(&cmd.shardFilter, "shard", "", "optional: shard id")
63 fs.Int64Var(&cmd.maxLogFileSize, "max-log-file-size", tsdb.DefaultMaxIndexLogFileSize, "optional: maximum log file size")
64 fs.Uint64Var(&cmd.maxCacheSize, "max-cache-size", tsdb.DefaultCacheMaxMemorySize, "optional: maximum cache size")
65 fs.IntVar(&cmd.batchSize, "batch-size", defaultBatchSize, "optional: set the size of the batches we write to the index. Setting this can have adverse affects on performance and heap requirements")
66 fs.BoolVar(&cmd.Verbose, "v", false, "verbose")
67 fs.SetOutput(cmd.Stdout)
68 if err := fs.Parse(args); err != nil {
69 return err
70 } else if fs.NArg() > 0 || *dataDir == "" || *walDir == "" {
71 fs.Usage()
72 return nil
73 }
74 cmd.Logger = logger.New(cmd.Stderr)
75
76 return cmd.run(*dataDir, *walDir)
77 }
78
79 func (cmd *Command) run(dataDir, walDir string) error {
80 // Verify the user actually wants to run as root.
81 if isRoot() {
82 fmt.Println("You are currently running as root. This will build your")
83 fmt.Println("index files with root ownership and will be inaccessible")
84 fmt.Println("if you run influxd as a non-root user. You should run")
85 fmt.Println("buildtsi as the same user you are running influxd.")
86 fmt.Print("Are you sure you want to continue? (y/N): ")
87 var answer string
88 if fmt.Scanln(&answer); !strings.HasPrefix(strings.TrimSpace(strings.ToLower(answer)), "y") {
89 return fmt.Errorf("operation aborted")
90 }
91 }
92
93 fis, err := ioutil.ReadDir(dataDir)
94 if err != nil {
95 return err
96 }
97
98 for _, fi := range fis {
99 name := fi.Name()
100 if !fi.IsDir() {
101 continue
102 } else if cmd.databaseFilter != "" && name != cmd.databaseFilter {
103 continue
104 }
105
106 if err := cmd.processDatabase(name, filepath.Join(dataDir, name), filepath.Join(walDir, name)); err != nil {
107 return err
108 }
109 }
110
111 return nil
112 }
113
114 func (cmd *Command) processDatabase(dbName, dataDir, walDir string) error {
115 cmd.Logger.Info("Rebuilding database", zap.String("name", dbName))
116
117 sfile := tsdb.NewSeriesFile(filepath.Join(dataDir, tsdb.SeriesFileDirectory))
118 sfile.Logger = cmd.Logger
119 if err := sfile.Open(); err != nil {
120 return err
121 }
122 defer sfile.Close()
123
124 fis, err := ioutil.ReadDir(dataDir)
125 if err != nil {
126 return err
127 }
128
129 for _, fi := range fis {
130 rpName := fi.Name()
131 if !fi.IsDir() {
132 continue
133 } else if rpName == tsdb.SeriesFileDirectory {
134 continue
135 } else if cmd.retentionFilter != "" && rpName != cmd.retentionFilter {
136 continue
137 }
138
139 if err := cmd.processRetentionPolicy(sfile, dbName, rpName, filepath.Join(dataDir, rpName), filepath.Join(walDir, rpName)); err != nil {
140 return err
141 }
142 }
143
144 return nil
145 }
146
147 func (cmd *Command) processRetentionPolicy(sfile *tsdb.SeriesFile, dbName, rpName, dataDir, walDir string) error {
148 cmd.Logger.Info("Rebuilding retention policy", logger.Database(dbName), logger.RetentionPolicy(rpName))
149
150 fis, err := ioutil.ReadDir(dataDir)
151 if err != nil {
152 return err
153 }
154
155 type shard struct {
156 ID uint64
157 Path string
158 }
159
160 var shards []shard
161
162 for _, fi := range fis {
163 if !fi.IsDir() {
164 continue
165 } else if cmd.shardFilter != "" && fi.Name() != cmd.shardFilter {
166 continue
167 }
168
169 shardID, err := strconv.ParseUint(fi.Name(), 10, 64)
170 if err != nil {
171 continue
172 }
173
174 shards = append(shards, shard{shardID, fi.Name()})
175 }
176
177 errC := make(chan error, len(shards))
178 var maxi uint32 // index of maximum shard being worked on.
179 for k := 0; k < cmd.concurrency; k++ {
180 go func() {
181 for {
182 i := int(atomic.AddUint32(&maxi, 1) - 1) // Get next partition to work on.
183 if i >= len(shards) {
184 return // No more work.
185 }
186
187 id, name := shards[i].ID, shards[i].Path
188 errC <- cmd.processShard(sfile, dbName, rpName, id, filepath.Join(dataDir, name), filepath.Join(walDir, name))
189 }
190 }()
191 }
192
193 // Check for error
194 for i := 0; i < cap(errC); i++ {
195 if err := <-errC; err != nil {
196 return err
197 }
198 }
199 return nil
200 }
201
202 func (cmd *Command) processShard(sfile *tsdb.SeriesFile, dbName, rpName string, shardID uint64, dataDir, walDir string) error {
203 log := cmd.Logger.With(logger.Database(dbName), logger.RetentionPolicy(rpName), logger.Shard(shardID))
204 log.Info("Rebuilding shard")
205
206 // Check if shard already has a TSI index.
207 indexPath := filepath.Join(dataDir, "index")
208 log.Info("Checking index path", zap.String("path", indexPath))
209 if _, err := os.Stat(indexPath); !os.IsNotExist(err) {
210 log.Info("tsi1 index already exists, skipping", zap.String("path", indexPath))
211 return nil
212 }
213
214 log.Info("Opening shard")
215
216 // Find shard files.
217 tsmPaths, err := cmd.collectTSMFiles(dataDir)
218 if err != nil {
219 return err
220 }
221 walPaths, err := cmd.collectWALFiles(walDir)
222 if err != nil {
223 return err
224 }
225
226 // Remove temporary index files if this is being re-run.
227 tmpPath := filepath.Join(dataDir, ".index")
228 log.Info("Cleaning up partial index from previous run, if any")
229 if err := os.RemoveAll(tmpPath); err != nil {
230 return err
231 }
232
233 // Open TSI index in temporary path.
234 tsiIndex := tsi1.NewIndex(sfile, dbName,
235 tsi1.WithPath(tmpPath),
236 tsi1.WithMaximumLogFileSize(cmd.maxLogFileSize),
237 tsi1.DisableFsync(),
238 // Each new series entry in a log file is ~12 bytes so this should
239 // roughly equate to one flush to the file for every batch.
240 tsi1.WithLogFileBufferSize(12*cmd.batchSize),
241 )
242
243 tsiIndex.WithLogger(cmd.Logger)
244
245 log.Info("Opening tsi index in temporary location", zap.String("path", tmpPath))
246 if err := tsiIndex.Open(); err != nil {
247 return err
248 }
249 defer tsiIndex.Close()
250
251 // Write out tsm1 files.
252 log.Info("Iterating over tsm files")
253 for _, path := range tsmPaths {
254 log.Info("Processing tsm file", zap.String("path", path))
255 if err := cmd.processTSMFile(tsiIndex, path, log); err != nil {
256 return err
257 }
258 }
259
260 // Write out wal files.
261 log.Info("Building cache from wal files")
262 cache := tsm1.NewCache(cmd.maxCacheSize)
263 loader := tsm1.NewCacheLoader(walPaths)
264 loader.WithLogger(cmd.Logger)
265 if err := loader.Load(cache); err != nil {
266 return err
267 }
268
269 log.Info("Iterating over cache")
270 keysBatch := make([][]byte, 0, cmd.batchSize)
271 namesBatch := make([][]byte, 0, cmd.batchSize)
272 tagsBatch := make([]models.Tags, 0, cmd.batchSize)
273
274 for _, key := range cache.Keys() {
275 seriesKey, _ := tsm1.SeriesAndFieldFromCompositeKey(key)
276 name, tags := models.ParseKeyBytes(seriesKey)
277
278 if cmd.Verbose {
279 log.Info("Series", zap.String("name", string(name)), zap.String("tags", tags.String()))
280 }
281
282 keysBatch = append(keysBatch, seriesKey)
283 namesBatch = append(namesBatch, name)
284 tagsBatch = append(tagsBatch, tags)
285
286 // Flush batch?
287 if len(keysBatch) == cmd.batchSize {
288 if err := tsiIndex.CreateSeriesListIfNotExists(keysBatch, namesBatch, tagsBatch); err != nil {
289 return fmt.Errorf("problem creating series: (%s)", err)
290 }
291 keysBatch = keysBatch[:0]
292 namesBatch = namesBatch[:0]
293 tagsBatch = tagsBatch[:0]
294 }
295 }
296
297 // Flush any remaining series in the batches
298 if len(keysBatch) > 0 {
299 if err := tsiIndex.CreateSeriesListIfNotExists(keysBatch, namesBatch, tagsBatch); err != nil {
300 return fmt.Errorf("problem creating series: (%s)", err)
301 }
302 keysBatch = nil
303 namesBatch = nil
304 tagsBatch = nil
305 }
306
307 // Attempt to compact the index & wait for all compactions to complete.
308 log.Info("compacting index")
309 tsiIndex.Compact()
310 tsiIndex.Wait()
311
312 // Close TSI index.
313 log.Info("Closing tsi index")
314 if err := tsiIndex.Close(); err != nil {
315 return err
316 }
317
318 // Rename TSI to standard path.
319 log.Info("Moving tsi to permanent location")
320 return os.Rename(tmpPath, indexPath)
321 }
322
323 func (cmd *Command) processTSMFile(index *tsi1.Index, path string, log *zap.Logger) error {
324 f, err := os.Open(path)
325 if err != nil {
326 return err
327 }
328 defer f.Close()
329
330 r, err := tsm1.NewTSMReader(f)
331 if err != nil {
332 log.Warn("Unable to read, skipping", zap.String("path", path), zap.Error(err))
333 return nil
334 }
335 defer r.Close()
336
337 keysBatch := make([][]byte, 0, cmd.batchSize)
338 namesBatch := make([][]byte, 0, cmd.batchSize)
339 tagsBatch := make([]models.Tags, cmd.batchSize)
340 var ti int
341 for i := 0; i < r.KeyCount(); i++ {
342 key, _ := r.KeyAt(i)
343 seriesKey, _ := tsm1.SeriesAndFieldFromCompositeKey(key)
344 var name []byte
345 name, tagsBatch[ti] = models.ParseKeyBytesWithTags(seriesKey, tagsBatch[ti])
346
347 if cmd.Verbose {
348 log.Info("Series", zap.String("name", string(name)), zap.String("tags", tagsBatch[ti].String()))
349 }
350
351 keysBatch = append(keysBatch, seriesKey)
352 namesBatch = append(namesBatch, name)
353 ti++
354
355 // Flush batch?
356 if len(keysBatch) == cmd.batchSize {
357 if err := index.CreateSeriesListIfNotExists(keysBatch, namesBatch, tagsBatch[:ti]); err != nil {
358 return fmt.Errorf("problem creating series: (%s)", err)
359 }
360 keysBatch = keysBatch[:0]
361 namesBatch = namesBatch[:0]
362 ti = 0 // Reset tags.
363 }
364 }
365
366 // Flush any remaining series in the batches
367 if len(keysBatch) > 0 {
368 if err := index.CreateSeriesListIfNotExists(keysBatch, namesBatch, tagsBatch[:ti]); err != nil {
369 return fmt.Errorf("problem creating series: (%s)", err)
370 }
371 }
372 return nil
373 }
374
375 func (cmd *Command) collectTSMFiles(path string) ([]string, error) {
376 fis, err := ioutil.ReadDir(path)
377 if err != nil {
378 return nil, err
379 }
380
381 var paths []string
382 for _, fi := range fis {
383 if filepath.Ext(fi.Name()) != "."+tsm1.TSMFileExtension {
384 continue
385 }
386 paths = append(paths, filepath.Join(path, fi.Name()))
387 }
388 return paths, nil
389 }
390
391 func (cmd *Command) collectWALFiles(path string) ([]string, error) {
392 fis, err := ioutil.ReadDir(path)
393 if err != nil {
394 return nil, err
395 }
396
397 var paths []string
398 for _, fi := range fis {
399 if filepath.Ext(fi.Name()) != "."+tsm1.WALFileExtension {
400 continue
401 }
402 paths = append(paths, filepath.Join(path, fi.Name()))
403 }
404 return paths, nil
405 }
406
407 func isRoot() bool {
408 user, _ := user.Current()
409 return user != nil && user.Username == "root"
410 }