Debian Codegraph @

cmd/influxd/restore/restore.go

raw
1 // Package restore is the restore subcommand for the influxd command,
2 // for restoring from a backup.
3 package restore
4
5 import (
6 "archive/tar"
7 "bytes"
8 "encoding/binary"
9 "flag"
10 "fmt"
11 "io"
12 "io/ioutil"
13 "log"
14 "os"
15 "path/filepath"
16 "strconv"
17 "strings"
18
19 gzip "github.com/klauspost/pgzip"
20
21 "github.com/influxdata/influxdb/cmd/influxd/backup_util"
22 tarstream "github.com/influxdata/influxdb/pkg/tar"
23 "github.com/influxdata/influxdb/services/meta"
24 "github.com/influxdata/influxdb/services/snapshotter"
25 )
26
27 // Command represents the program execution for "influxd restore".
28 type Command struct {
29 // The logger passed to the ticker during execution.
30 StdoutLogger *log.Logger
31 StderrLogger *log.Logger
32
33 // Standard input/output, overridden for testing.
34 Stderr io.Writer
35 Stdout io.Writer
36
37 host string
38 client *snapshotter.Client
39
40 backupFilesPath string
41 metadir string
42 datadir string
43 destinationDatabase string
44 sourceDatabase string
45 backupRetention string
46 restoreRetention string
47 shard uint64
48 portable bool
49 online bool
50 manifestMeta *backup_util.MetaEntry
51 manifestFiles map[uint64]*backup_util.Entry
52
53 // TODO: when the new meta stuff is done this should not be exported or be gone
54 MetaConfig *meta.Config
55
56 shardIDMap map[uint64]uint64
57 }
58
59 // NewCommand returns a new instance of Command with default settings.
60 func NewCommand() *Command {
61 return &Command{
62 Stdout: os.Stdout,
63 Stderr: os.Stderr,
64 MetaConfig: meta.NewConfig(),
65 }
66 }
67
68 // Run executes the program.
69 func (cmd *Command) Run(args ...string) error {
70 // Set up logger.
71 cmd.StdoutLogger = log.New(cmd.Stdout, "", log.LstdFlags)
72 cmd.StderrLogger = log.New(cmd.Stderr, "", log.LstdFlags)
73 if err := cmd.parseFlags(args); err != nil {
74 return err
75 }
76
77 if cmd.portable {
78 return cmd.runOnlinePortable()
79 } else if cmd.online {
80 return cmd.runOnlineLegacy()
81 } else {
82 return cmd.runOffline()
83 }
84 }
85
86 func (cmd *Command) runOffline() error {
87 if cmd.metadir != "" {
88 if err := cmd.unpackMeta(); err != nil {
89 return err
90 }
91 }
92
93 if cmd.shard != 0 {
94 return cmd.unpackShard(cmd.shard)
95 } else if cmd.restoreRetention != "" {
96 return cmd.unpackRetention()
97 } else if cmd.datadir != "" {
98 return cmd.unpackDatabase()
99 }
100 return nil
101 }
102
103 func (cmd *Command) runOnlinePortable() error {
104 err := cmd.updateMetaPortable()
105 if err != nil {
106 cmd.StderrLogger.Printf("error updating meta: %v", err)
107 return err
108 }
109 err = cmd.uploadShardsPortable()
110 if err != nil {
111 cmd.StderrLogger.Printf("error updating shards: %v", err)
112 return err
113 }
114 return nil
115 }
116
117 func (cmd *Command) runOnlineLegacy() error {
118 err := cmd.updateMetaLegacy()
119 if err != nil {
120 cmd.StderrLogger.Printf("error updating meta: %v", err)
121 return err
122 }
123 err = cmd.uploadShardsLegacy()
124 if err != nil {
125 cmd.StderrLogger.Printf("error updating shards: %v", err)
126 return err
127 }
128 return nil
129 }
130
131 // parseFlags parses and validates the command line arguments.
132 func (cmd *Command) parseFlags(args []string) error {
133 fs := flag.NewFlagSet("", flag.ContinueOnError)
134 fs.StringVar(&cmd.host, "host", "localhost:8088", "")
135 fs.StringVar(&cmd.metadir, "metadir", "", "")
136 fs.StringVar(&cmd.datadir, "datadir", "", "")
137
138 fs.StringVar(&cmd.sourceDatabase, "database", "", "")
139 fs.StringVar(&cmd.sourceDatabase, "db", "", "")
140 fs.StringVar(&cmd.destinationDatabase, "newdb", "", "")
141
142 fs.StringVar(&cmd.backupRetention, "retention", "", "")
143 fs.StringVar(&cmd.backupRetention, "rp", "", "")
144 fs.StringVar(&cmd.restoreRetention, "newrp", "", "")
145
146 fs.Uint64Var(&cmd.shard, "shard", 0, "")
147 fs.BoolVar(&cmd.online, "online", false, "")
148 fs.BoolVar(&cmd.portable, "portable", false, "")
149 fs.SetOutput(cmd.Stdout)
150 fs.Usage = cmd.printUsage
151 if err := fs.Parse(args); err != nil {
152 return err
153 }
154
155 cmd.MetaConfig = meta.NewConfig()
156 cmd.MetaConfig.Dir = cmd.metadir
157 cmd.client = snapshotter.NewClient(cmd.host)
158
159 // Require output path.
160 cmd.backupFilesPath = fs.Arg(0)
161 if cmd.backupFilesPath == "" {
162 return fmt.Errorf("path with backup files required")
163 }
164
165 fi, err := os.Stat(cmd.backupFilesPath)
166 if err != nil || !fi.IsDir() {
167 return fmt.Errorf("backup path should be a valid directory: %s", cmd.backupFilesPath)
168 }
169
170 if cmd.portable || cmd.online {
171 // validate the arguments
172
173 if cmd.metadir != "" {
174 return fmt.Errorf("offline parameter metadir found, not compatible with -portable")
175 }
176
177 if cmd.datadir != "" {
178 return fmt.Errorf("offline parameter datadir found, not compatible with -portable")
179 }
180
181 if cmd.restoreRetention == "" {
182 cmd.restoreRetention = cmd.backupRetention
183 }
184
185 if cmd.portable {
186 var err error
187 cmd.manifestMeta, cmd.manifestFiles, err = backup_util.LoadIncremental(cmd.backupFilesPath)
188 if err != nil {
189 return fmt.Errorf("restore failed while processing manifest files: %s", err.Error())
190 } else if cmd.manifestMeta == nil {
191 // No manifest files found.
192 return fmt.Errorf("No manifest files found in: %s\n", cmd.backupFilesPath)
193
194 }
195 }
196 } else {
197 // validate the arguments
198 if cmd.metadir == "" && cmd.destinationDatabase == "" {
199 return fmt.Errorf("-metadir or -destinationDatabase are required to restore")
200 }
201
202 if cmd.destinationDatabase != "" && cmd.datadir == "" {
203 return fmt.Errorf("-datadir is required to restore")
204 }
205
206 if cmd.shard != 0 {
207 if cmd.destinationDatabase == "" {
208 return fmt.Errorf("-destinationDatabase is required to restore shard")
209 }
210 if cmd.backupRetention == "" {
211 return fmt.Errorf("-retention is required to restore shard")
212 }
213 } else if cmd.backupRetention != "" && cmd.destinationDatabase == "" {
214 return fmt.Errorf("-destinationDatabase is required to restore retention policy")
215 }
216 }
217
218 return nil
219 }
220
221 // unpackMeta reads the metadata from the backup directory and initializes a raft
222 // cluster and replaces the root metadata.
223 func (cmd *Command) unpackMeta() error {
224 // find the meta file
225 metaFiles, err := filepath.Glob(filepath.Join(cmd.backupFilesPath, backup_util.Metafile+".*"))
226 if err != nil {
227 return err
228 }
229
230 if len(metaFiles) == 0 {
231 return fmt.Errorf("no metastore backups in %s", cmd.backupFilesPath)
232 }
233
234 latest := metaFiles[len(metaFiles)-1]
235
236 fmt.Fprintf(cmd.Stdout, "Using metastore snapshot: %v\n", latest)
237 // Read the metastore backup
238 f, err := os.Open(latest)
239 if err != nil {
240 return err
241 }
242
243 var buf bytes.Buffer
244 if _, err := io.Copy(&buf, f); err != nil {
245 return fmt.Errorf("copy: %s", err)
246 }
247
248 b := buf.Bytes()
249 var i int
250
251 // Make sure the file is actually a meta store backup file
252 magic := binary.BigEndian.Uint64(b[:8])
253 if magic != snapshotter.BackupMagicHeader {
254 return fmt.Errorf("invalid metadata file")
255 }
256 i += 8
257
258 // Size of the meta store bytes
259 length := int(binary.BigEndian.Uint64(b[i : i+8]))
260 i += 8
261 metaBytes := b[i : i+length]
262 i += int(length)
263
264 // Size of the node.json bytes
265 length = int(binary.BigEndian.Uint64(b[i : i+8]))
266 i += 8
267 nodeBytes := b[i : i+length]
268
269 // Unpack into metadata.
270 var data meta.Data
271 if err := data.UnmarshalBinary(metaBytes); err != nil {
272 return fmt.Errorf("unmarshal: %s", err)
273 }
274
275 // Copy meta config and remove peers so it starts in single mode.
276 c := cmd.MetaConfig
277 c.Dir = cmd.metadir
278
279 // Create the meta dir
280 if err := os.MkdirAll(c.Dir, 0700); err != nil {
281 return err
282 }
283
284 // Write node.json back to meta dir
285 if err := ioutil.WriteFile(filepath.Join(c.Dir, "node.json"), nodeBytes, 0655); err != nil {
286 return err
287 }
288
289 client := meta.NewClient(c)
290 if err := client.Open(); err != nil {
291 return err
292 }
293 defer client.Close()
294
295 // Force set the full metadata.
296 if err := client.SetData(&data); err != nil {
297 return fmt.Errorf("set data: %s", err)
298 }
299
300 // remove the raft.db file if it exists
301 err = os.Remove(filepath.Join(cmd.metadir, "raft.db"))
302 if err != nil {
303 if os.IsNotExist(err) {
304 return nil
305 }
306 return err
307 }
308
309 // remove the node.json file if it exists
310 err = os.Remove(filepath.Join(cmd.metadir, "node.json"))
311 if err != nil {
312 if os.IsNotExist(err) {
313 return nil
314 }
315 return err
316 }
317
318 return nil
319 }
320
321 func (cmd *Command) updateMetaPortable() error {
322 var metaBytes []byte
323 fileName := filepath.Join(cmd.backupFilesPath, cmd.manifestMeta.FileName)
324
325 fileBytes, err := ioutil.ReadFile(fileName)
326 if err != nil {
327 return err
328 }
329
330 var ep backup_util.PortablePacker
331 ep.UnmarshalBinary(fileBytes)
332
333 metaBytes = ep.Data
334
335 req := &snapshotter.Request{
336 Type: snapshotter.RequestMetaStoreUpdate,
337 BackupDatabase: cmd.sourceDatabase,
338 RestoreDatabase: cmd.destinationDatabase,
339 BackupRetentionPolicy: cmd.backupRetention,
340 RestoreRetentionPolicy: cmd.restoreRetention,
341 UploadSize: int64(len(metaBytes)),
342 }
343
344 shardIDMap, err := cmd.client.UpdateMeta(req, bytes.NewReader(metaBytes))
345 cmd.shardIDMap = shardIDMap
346 return err
347
348 }
349
350 // updateMetaLive takes a metadata backup and sends it to the influx server
351 // for a live merger of metadata.
352 func (cmd *Command) updateMetaLegacy() error {
353
354 var metaBytes []byte
355
356 // find the meta file
357 metaFiles, err := filepath.Glob(filepath.Join(cmd.backupFilesPath, backup_util.Metafile+".*"))
358 if err != nil {
359 return err
360 }
361
362 if len(metaFiles) == 0 {
363 return fmt.Errorf("no metastore backups in %s", cmd.backupFilesPath)
364 }
365
366 fileName := metaFiles[len(metaFiles)-1]
367 cmd.StdoutLogger.Printf("Using metastore snapshot: %v\n", fileName)
368 metaBytes, err = backup_util.GetMetaBytes(fileName)
369 if err != nil {
370 return err
371 }
372
373 req := &snapshotter.Request{
374 Type: snapshotter.RequestMetaStoreUpdate,
375 BackupDatabase: cmd.sourceDatabase,
376 RestoreDatabase: cmd.destinationDatabase,
377 BackupRetentionPolicy: cmd.backupRetention,
378 RestoreRetentionPolicy: cmd.restoreRetention,
379 UploadSize: int64(len(metaBytes)),
380 }
381
382 shardIDMap, err := cmd.client.UpdateMeta(req, bytes.NewReader(metaBytes))
383 cmd.shardIDMap = shardIDMap
384 return err
385 }
386
387 func (cmd *Command) uploadShardsPortable() error {
388 for _, file := range cmd.manifestFiles {
389 if cmd.sourceDatabase == "" || cmd.sourceDatabase == file.Database {
390 if cmd.backupRetention == "" || cmd.backupRetention == file.Policy {
391 if cmd.shard == 0 || cmd.shard == file.ShardID {
392 oldID := file.ShardID
393 // if newID not found then this shard's metadata was NOT imported
394 // and should be skipped
395 newID, ok := cmd.shardIDMap[oldID]
396 if !ok {
397 cmd.StdoutLogger.Printf("Meta info not found for shard %d on database %s. Skipping shard file %s", oldID, file.Database, file.FileName)
398 continue
399 }
400 cmd.StdoutLogger.Printf("Restoring shard %d live from backup %s\n", file.ShardID, file.FileName)
401 f, err := os.Open(filepath.Join(cmd.backupFilesPath, file.FileName))
402 if err != nil {
403 f.Close()
404 return err
405 }
406 gr, err := gzip.NewReader(f)
407 if err != nil {
408 f.Close()
409 return err
410 }
411 tr := tar.NewReader(gr)
412 targetDB := cmd.destinationDatabase
413 if targetDB == "" {
414 targetDB = file.Database
415 }
416
417 if err := cmd.client.UploadShard(oldID, newID, targetDB, cmd.restoreRetention, tr); err != nil {
418 f.Close()
419 return err
420 }
421 f.Close()
422 }
423 }
424 }
425 }
426 return nil
427 }
428
429 // unpackFiles will look for backup files matching the pattern and restore them to the data dir
430 func (cmd *Command) uploadShardsLegacy() error {
431 // find the destinationDatabase backup files
432 pat := fmt.Sprintf("%s.*", filepath.Join(cmd.backupFilesPath, cmd.sourceDatabase))
433 cmd.StdoutLogger.Printf("Restoring live from backup %s\n", pat)
434 backupFiles, err := filepath.Glob(pat)
435 if err != nil {
436 return err
437 }
438 if len(backupFiles) == 0 {
439 return fmt.Errorf("no backup files in %s", cmd.backupFilesPath)
440 }
441
442 for _, fn := range backupFiles {
443 parts := strings.Split(fn, ".")
444
445 if len(parts) != 4 {
446 cmd.StderrLogger.Printf("Skipping mis-named backup file: %s", fn)
447 }
448 shardID, err := strconv.ParseUint(parts[2], 10, 64)
449 if err != nil {
450 return err
451 }
452
453 // if newID not found then this shard's metadata was NOT imported
454 // and should be skipped
455 newID, ok := cmd.shardIDMap[shardID]
456 if !ok {
457 cmd.StdoutLogger.Printf("Meta info not found for shard %d. Skipping shard file %s", shardID, fn)
458 continue
459 }
460 f, err := os.Open(fn)
461 if err != nil {
462 return err
463 }
464 tr := tar.NewReader(f)
465 if err := cmd.client.UploadShard(shardID, newID, cmd.destinationDatabase, cmd.restoreRetention, tr); err != nil {
466 f.Close()
467 return err
468 }
469 f.Close()
470 }
471
472 return nil
473 }
474
475 // unpackDatabase will look for all backup files in the path matching this destinationDatabase
476 // and restore them to the data dir
477 func (cmd *Command) unpackDatabase() error {
478 // make sure the shard isn't already there so we don't clobber anything
479 restorePath := filepath.Join(cmd.datadir, cmd.sourceDatabase)
480 if _, err := os.Stat(restorePath); err != nil && !os.IsNotExist(err) {
481 return fmt.Errorf("database already present: %s", restorePath)
482 }
483
484 // find the database backup files
485 pat := filepath.Join(cmd.backupFilesPath, cmd.sourceDatabase)
486 return cmd.unpackFiles(pat + ".*")
487 }
488
489 // unpackRetention will look for all backup files in the path matching this retention
490 // and restore them to the data dir
491 func (cmd *Command) unpackRetention() error {
492 // make sure the shard isn't already there so we don't clobber anything
493 restorePath := filepath.Join(cmd.datadir, cmd.sourceDatabase, cmd.backupRetention)
494 if _, err := os.Stat(restorePath); err != nil && !os.IsNotExist(err) {
495 return fmt.Errorf("retention already present: %s", restorePath)
496 }
497
498 // find the retention backup files
499 pat := filepath.Join(cmd.backupFilesPath, cmd.sourceDatabase)
500 return cmd.unpackFiles(fmt.Sprintf("%s.%s.*", pat, cmd.backupRetention))
501 }
502
503 // unpackShard will look for all backup files in the path matching this shard ID
504 // and restore them to the data dir
505 func (cmd *Command) unpackShard(shard uint64) error {
506 shardID := strconv.FormatUint(shard, 10)
507 // make sure the shard isn't already there so we don't clobber anything
508 restorePath := filepath.Join(cmd.datadir, cmd.sourceDatabase, cmd.backupRetention, shardID)
509 if _, err := os.Stat(restorePath); err != nil && !os.IsNotExist(err) {
510 return fmt.Errorf("shard already present: %s", restorePath)
511 }
512
513 id, err := strconv.ParseUint(shardID, 10, 64)
514 if err != nil {
515 return err
516 }
517
518 // find the shard backup files
519 pat := filepath.Join(cmd.backupFilesPath, fmt.Sprintf(backup_util.BackupFilePattern, cmd.sourceDatabase, cmd.backupRetention, id))
520 return cmd.unpackFiles(pat + ".*")
521 }
522
523 // unpackFiles will look for backup files matching the pattern and restore them to the data dir
524 func (cmd *Command) unpackFiles(pat string) error {
525 cmd.StdoutLogger.Printf("Restoring offline from backup %s\n", pat)
526
527 backupFiles, err := filepath.Glob(pat)
528 if err != nil {
529 return err
530 }
531
532 if len(backupFiles) == 0 {
533 return fmt.Errorf("no backup files for %s in %s", pat, cmd.backupFilesPath)
534 }
535
536 for _, fn := range backupFiles {
537 if err := cmd.unpackTar(fn); err != nil {
538 return err
539 }
540 }
541
542 return nil
543 }
544
545 // unpackTar will restore a single tar archive to the data dir
546 func (cmd *Command) unpackTar(tarFile string) error {
547 f, err := os.Open(tarFile)
548 if err != nil {
549 return err
550 }
551 defer f.Close()
552
553 // should get us ["db","rp", "00001", "00"]
554 pathParts := strings.Split(filepath.Base(tarFile), ".")
555 if len(pathParts) != 4 {
556 return fmt.Errorf("backup tarfile name incorrect format")
557 }
558
559 shardPath := filepath.Join(cmd.datadir, pathParts[0], pathParts[1], strings.Trim(pathParts[2], "0"))
560 os.MkdirAll(shardPath, 0755)
561
562 return tarstream.Restore(f, shardPath)
563 }
564
565 // printUsage prints the usage message to STDERR.
566 func (cmd *Command) printUsage() {
567 fmt.Fprintf(cmd.Stdout, `
568 Uses backup copies from the specified PATH to restore databases or specific shards from InfluxDB OSS
569 or InfluxDB Enterprise to an InfluxDB OSS instance.
570
571 Usage: influxd restore -portable [options] PATH
572
573 Note: Restore using the '-portable' option consumes files in an improved Enterprise-compatible
574 format that includes a file manifest.
575
576 Options:
577 -portable
578 Required to activate the portable restore mode. If not specified, the legacy restore mode is used.
579 -host <host:port>
580 InfluxDB OSS host to connect to where the data will be restored. Defaults to '127.0.0.1:8088'.
581 -db <name>
582 Name of database to be restored from the backup (InfluxDB OSS or InfluxDB Enterprise)
583 -newdb <name>
584 Name of the InfluxDB OSS database into which the archived data will be imported on the target system.
585 Optional. If not given, then the value of '-db <db_name>' is used. The new database name must be unique
586 to the target system.
587 -rp <name>
588 Name of retention policy from the backup that will be restored. Optional.
589 Requires that '-db <db_name>' is specified.
590 -newrp <name>
591 Name of the retention policy to be created on the target system. Optional. Requires that '-rp <rp_name>'
592 is set. If not given, the '-rp <rp_name>' value is used.
593 -shard <id>
594 Identifier of the shard to be restored. Optional. If specified, then '-db <db_name>' and '-rp <rp_name>' are
595 required.
596 PATH
597 Path to directory containing the backup files.
598
599 `)
600 }