Debian Codegraph @

cmd/influxd/backup/backup.go

raw
1 // Package backup implements both the backup and export subcommands for the influxd command.
2 package backup
3
4 import (
5 "encoding/binary"
6 "encoding/json"
7 "errors"
8 "flag"
9 "fmt"
10 "io"
11 "io/ioutil"
12 "log"
13 "math"
14 "os"
15 "path/filepath"
16 "strconv"
17 "time"
18
19 "github.com/influxdata/influxdb/cmd/influxd/backup_util"
20 "github.com/influxdata/influxdb/services/snapshotter"
21 "github.com/influxdata/influxdb/tcp"
22 gzip "github.com/klauspost/pgzip"
23 )
24
25 const (
26 // Suffix is a suffix added to the backup while it's in-process.
27 Suffix = ".pending"
28
29 // Metafile is the base name given to the metastore backups.
30 Metafile = "meta"
31
32 // BackupFilePattern is the beginning of the pattern for a backup
33 // file. They follow the scheme <database>.<retention>.<shardID>.<increment>
34 BackupFilePattern = "%s.%s.%05d"
35 )
36
37 // Command represents the program execution for "influxd backup".
38 type Command struct {
39 // The logger passed to the ticker during execution.
40 StdoutLogger *log.Logger
41 StderrLogger *log.Logger
42
43 // Standard input/output, overridden for testing.
44 Stderr io.Writer
45 Stdout io.Writer
46
47 host string
48 path string
49 database string
50 retentionPolicy string
51 shardID string
52
53 isBackup bool
54 since time.Time
55 start time.Time
56 end time.Time
57
58 portable bool
59 manifest backup_util.Manifest
60 portableFileBase string
61
62 BackupFiles []string
63 }
64
65 // NewCommand returns a new instance of Command with default settings.
66 func NewCommand() *Command {
67 return &Command{
68 Stderr: os.Stderr,
69 Stdout: os.Stdout,
70 }
71 }
72
73 // Run executes the program.
74 func (cmd *Command) Run(args ...string) error {
75 // Set up logger.
76 cmd.StdoutLogger = log.New(cmd.Stdout, "", log.LstdFlags)
77 cmd.StderrLogger = log.New(cmd.Stderr, "", log.LstdFlags)
78
79 // Parse command line arguments.
80 err := cmd.parseFlags(args)
81 if err != nil {
82 return err
83 }
84
85 if cmd.shardID != "" {
86 // always backup the metastore
87 if err := cmd.backupMetastore(); err != nil {
88 return err
89 }
90 err = cmd.backupShard(cmd.database, cmd.retentionPolicy, cmd.shardID)
91
92 } else if cmd.retentionPolicy != "" {
93 // always backup the metastore
94 if err := cmd.backupMetastore(); err != nil {
95 return err
96 }
97 err = cmd.backupRetentionPolicy()
98 } else if cmd.database != "" {
99 // always backup the metastore
100 if err := cmd.backupMetastore(); err != nil {
101 return err
102 }
103 err = cmd.backupDatabase()
104 } else {
105 // always backup the metastore
106 if err := cmd.backupMetastore(); err != nil {
107 return err
108 }
109
110 cmd.StdoutLogger.Println("No database, retention policy or shard ID given. Full meta store backed up.")
111 if cmd.portable {
112 cmd.StdoutLogger.Println("Backing up all databases in portable format")
113 if err := cmd.backupDatabase(); err != nil {
114 cmd.StderrLogger.Printf("backup failed: %v", err)
115 return err
116 }
117
118 }
119
120 }
121
122 if cmd.portable {
123 filename := cmd.portableFileBase + ".manifest"
124 if err := cmd.manifest.Save(filepath.Join(cmd.path, filename)); err != nil {
125 cmd.StderrLogger.Printf("manifest save failed: %v", err)
126 return err
127 }
128 cmd.BackupFiles = append(cmd.BackupFiles, filename)
129 }
130
131 if err != nil {
132 cmd.StderrLogger.Printf("backup failed: %v", err)
133 return err
134 }
135 cmd.StdoutLogger.Println("backup complete:")
136 for _, v := range cmd.BackupFiles {
137 cmd.StdoutLogger.Println("\t" + filepath.Join(cmd.path, v))
138 }
139
140 return nil
141 }
142
143 // parseFlags parses and validates the command line arguments into a request object.
144 func (cmd *Command) parseFlags(args []string) (err error) {
145 fs := flag.NewFlagSet("", flag.ContinueOnError)
146
147 fs.StringVar(&cmd.host, "host", "localhost:8088", "")
148 fs.StringVar(&cmd.database, "database", "", "")
149 fs.StringVar(&cmd.database, "db", "", "")
150 fs.StringVar(&cmd.retentionPolicy, "retention", "", "")
151 fs.StringVar(&cmd.retentionPolicy, "rp", "", "")
152 fs.StringVar(&cmd.shardID, "shard", "", "")
153 var sinceArg string
154 var startArg string
155 var endArg string
156 fs.StringVar(&sinceArg, "since", "", "")
157 fs.StringVar(&startArg, "start", "", "")
158 fs.StringVar(&endArg, "end", "", "")
159 fs.BoolVar(&cmd.portable, "portable", false, "")
160
161 fs.SetOutput(cmd.Stderr)
162 fs.Usage = cmd.printUsage
163
164 err = fs.Parse(args)
165 if err != nil {
166 return err
167 }
168
169 cmd.BackupFiles = []string{}
170
171 // for portable saving, if needed
172 cmd.portableFileBase = time.Now().UTC().Format(backup_util.PortableFileNamePattern)
173
174 // if startArg and endArg are unspecified, or if we are using -since then assume we are doing a full backup of the shards
175 cmd.isBackup = (startArg == "" && endArg == "") || sinceArg != ""
176
177 if sinceArg != "" {
178 cmd.since, err = time.Parse(time.RFC3339, sinceArg)
179 if err != nil {
180 return err
181 }
182 }
183 if startArg != "" {
184 if cmd.isBackup {
185 return errors.New("backup command uses one of -since or -start/-end")
186 }
187 cmd.start, err = time.Parse(time.RFC3339, startArg)
188 if err != nil {
189 return err
190 }
191 }
192
193 if endArg != "" {
194 if cmd.isBackup {
195 return errors.New("backup command uses one of -since or -start/-end")
196 }
197 cmd.end, err = time.Parse(time.RFC3339, endArg)
198 if err != nil {
199 return err
200 }
201
202 // start should be < end
203 if !cmd.start.Before(cmd.end) {
204 return errors.New("start date must be before end date")
205 }
206 }
207
208 // Ensure that only one arg is specified.
209 if fs.NArg() != 1 {
210 return errors.New("Exactly one backup path is required.")
211 }
212 cmd.path = fs.Arg(0)
213
214 err = os.MkdirAll(cmd.path, 0700)
215
216 return err
217 }
218
219 func (cmd *Command) backupShard(db, rp, sid string) error {
220 reqType := snapshotter.RequestShardBackup
221 if !cmd.isBackup {
222 reqType = snapshotter.RequestShardExport
223 }
224
225 id, err := strconv.ParseUint(sid, 10, 64)
226 if err != nil {
227 return err
228 }
229
230 shardArchivePath, err := cmd.nextPath(filepath.Join(cmd.path, fmt.Sprintf(backup_util.BackupFilePattern, db, rp, id)))
231 if err != nil {
232 return err
233 }
234
235 if cmd.isBackup {
236 cmd.StdoutLogger.Printf("backing up db=%v rp=%v shard=%v to %s since %s",
237 db, rp, sid, shardArchivePath, cmd.since.Format(time.RFC3339))
238 } else {
239 cmd.StdoutLogger.Printf("backing up db=%v rp=%v shard=%v to %s with boundaries start=%s, end=%s",
240 db, rp, sid, shardArchivePath, cmd.start.Format(time.RFC3339), cmd.end.Format(time.RFC3339))
241 }
242 req := &snapshotter.Request{
243 Type: reqType,
244 BackupDatabase: db,
245 BackupRetentionPolicy: rp,
246 ShardID: id,
247 Since: cmd.since,
248 ExportStart: cmd.start,
249 ExportEnd: cmd.end,
250 }
251
252 // TODO: verify shard backup data
253 err = cmd.downloadAndVerify(req, shardArchivePath, nil)
254 if !cmd.portable {
255 cmd.BackupFiles = append(cmd.BackupFiles, shardArchivePath)
256 }
257
258 if err != nil {
259 return err
260 }
261
262 if cmd.portable {
263 f, err := os.Open(shardArchivePath)
264 if err != nil {
265 return err
266 }
267 defer f.Close()
268 defer os.Remove(shardArchivePath)
269
270 filePrefix := cmd.portableFileBase + ".s" + sid
271 filename := filePrefix + ".tar.gz"
272 out, err := os.OpenFile(filepath.Join(cmd.path, filename), os.O_CREATE|os.O_RDWR, 0600)
273 if err != nil {
274 return err
275 }
276
277 zw := gzip.NewWriter(out)
278 zw.Name = filePrefix + ".tar"
279
280 cw := backup_util.CountingWriter{Writer: zw}
281
282 _, err = io.Copy(&cw, f)
283 if err != nil {
284 if err := zw.Close(); err != nil {
285 return err
286 }
287
288 if err := out.Close(); err != nil {
289 return err
290 }
291 return err
292 }
293
294 shardid, err := strconv.ParseUint(sid, 10, 64)
295 if err != nil {
296 if err := zw.Close(); err != nil {
297 return err
298 }
299
300 if err := out.Close(); err != nil {
301 return err
302 }
303 return err
304 }
305 cmd.manifest.Files = append(cmd.manifest.Files, backup_util.Entry{
306 Database: db,
307 Policy: rp,
308 ShardID: shardid,
309 FileName: filename,
310 Size: cw.Total,
311 LastModified: 0,
312 })
313
314 if err := zw.Close(); err != nil {
315 return err
316 }
317
318 if err := out.Close(); err != nil {
319 return err
320 }
321
322 cmd.BackupFiles = append(cmd.BackupFiles, filename)
323 }
324 return nil
325
326 }
327
328 // backupDatabase will request the database information from the server and then backup
329 // every shard in every retention policy in the database. Each shard will be written to a separate file.
330 func (cmd *Command) backupDatabase() error {
331 cmd.StdoutLogger.Printf("backing up db=%s", cmd.database)
332
333 req := &snapshotter.Request{
334 Type: snapshotter.RequestDatabaseInfo,
335 BackupDatabase: cmd.database,
336 }
337
338 response, err := cmd.requestInfo(req)
339 if err != nil {
340 return err
341 }
342
343 return cmd.backupResponsePaths(response)
344 }
345
346 // backupRetentionPolicy will request the retention policy information from the server and then backup
347 // every shard in the retention policy. Each shard will be written to a separate file.
348 func (cmd *Command) backupRetentionPolicy() error {
349 if cmd.isBackup {
350 cmd.StdoutLogger.Printf("backing up rp=%s since %s", cmd.retentionPolicy, cmd.since.Format(time.RFC3339))
351 } else {
352 cmd.StdoutLogger.Printf("backing up rp=%s with boundaries start=%s, end=%s",
353 cmd.retentionPolicy, cmd.start.Format(time.RFC3339), cmd.end.Format(time.RFC3339))
354 }
355
356 req := &snapshotter.Request{
357 Type: snapshotter.RequestRetentionPolicyInfo,
358 BackupDatabase: cmd.database,
359 BackupRetentionPolicy: cmd.retentionPolicy,
360 }
361
362 response, err := cmd.requestInfo(req)
363 if err != nil {
364 return err
365 }
366
367 return cmd.backupResponsePaths(response)
368 }
369
370 // backupResponsePaths will backup all shards identified by shard paths in the response struct
371 func (cmd *Command) backupResponsePaths(response *snapshotter.Response) error {
372
373 // loop through the returned paths and back up each shard
374 for _, path := range response.Paths {
375 db, rp, id, err := backup_util.DBRetentionAndShardFromPath(path)
376 if err != nil {
377 return err
378 }
379
380 err = cmd.backupShard(db, rp, id)
381
382 if err != nil {
383 return err
384 }
385 }
386
387 return nil
388 }
389
390 // backupMetastore will backup the whole metastore on the host to the backup path
391 // if useDB is non-empty, it will backup metadata only for the named database.
392 func (cmd *Command) backupMetastore() error {
393 metastoreArchivePath, err := cmd.nextPath(filepath.Join(cmd.path, backup_util.Metafile))
394 if err != nil {
395 return err
396 }
397
398 cmd.StdoutLogger.Printf("backing up metastore to %s", metastoreArchivePath)
399
400 req := &snapshotter.Request{
401 Type: snapshotter.RequestMetastoreBackup,
402 }
403
404 err = cmd.downloadAndVerify(req, metastoreArchivePath, func(file string) error {
405 f, err := os.Open(file)
406 if err != nil {
407 return err
408 }
409 defer f.Close()
410
411 var magicByte [8]byte
412 n, err := io.ReadFull(f, magicByte[:])
413 if err != nil {
414 return err
415 }
416
417 if n < 8 {
418 return errors.New("Not enough bytes data to verify")
419 }
420
421 magic := binary.BigEndian.Uint64(magicByte[:])
422 if magic != snapshotter.BackupMagicHeader {
423 cmd.StderrLogger.Println("Invalid metadata blob, ensure the metadata service is running (default port 8088)")
424 return errors.New("invalid metadata received")
425 }
426
427 return nil
428 })
429
430 if err != nil {
431 return err
432 }
433
434 if !cmd.portable {
435 cmd.BackupFiles = append(cmd.BackupFiles, metastoreArchivePath)
436 }
437
438 if cmd.portable {
439 metaBytes, err := backup_util.GetMetaBytes(metastoreArchivePath)
440 defer os.Remove(metastoreArchivePath)
441 if err != nil {
442 return err
443 }
444 filename := cmd.portableFileBase + ".meta"
445 ep := backup_util.PortablePacker{Data: metaBytes, MaxNodeID: 0}
446 protoBytes, err := ep.MarshalBinary()
447 if err != nil {
448 return err
449 }
450 if err := ioutil.WriteFile(filepath.Join(cmd.path, filename), protoBytes, 0644); err != nil {
451 fmt.Fprintln(cmd.Stdout, "Error.")
452 return err
453 }
454
455 cmd.manifest.Meta.FileName = filename
456 cmd.manifest.Meta.Size = int64(len(metaBytes))
457 cmd.BackupFiles = append(cmd.BackupFiles, filename)
458 }
459
460 return nil
461 }
462
463 // nextPath returns the next file to write to.
464 func (cmd *Command) nextPath(path string) (string, error) {
465 // Iterate through incremental files until one is available.
466 for i := 0; ; i++ {
467 s := fmt.Sprintf(path+".%02d", i)
468 if _, err := os.Stat(s); os.IsNotExist(err) {
469 return s, nil
470 } else if err != nil {
471 return "", err
472 }
473 }
474 }
475
476 // downloadAndVerify will download either the metastore or shard to a temp file and then
477 // rename it to a good backup file name after complete
478 func (cmd *Command) downloadAndVerify(req *snapshotter.Request, path string, validator func(string) error) error {
479 tmppath := path + backup_util.Suffix
480 if err := cmd.download(req, tmppath); err != nil {
481 return err
482 }
483
484 if validator != nil {
485 if err := validator(tmppath); err != nil {
486 if rmErr := os.Remove(tmppath); rmErr != nil {
487 cmd.StderrLogger.Printf("Error cleaning up temporary file: %v", rmErr)
488 }
489 return err
490 }
491 }
492
493 f, err := os.Stat(tmppath)
494 if err != nil {
495 return err
496 }
497
498 // There was nothing downloaded, don't create an empty backup file.
499 if f.Size() == 0 {
500 return os.Remove(tmppath)
501 }
502
503 // Rename temporary file to final path.
504 if err := os.Rename(tmppath, path); err != nil {
505 return fmt.Errorf("rename: %s", err)
506 }
507
508 return nil
509 }
510
511 // download downloads a snapshot of either the metastore or a shard from a host to a given path.
512 func (cmd *Command) download(req *snapshotter.Request, path string) error {
513 // Create local file to write to.
514 f, err := os.Create(path)
515 if err != nil {
516 return fmt.Errorf("open temp file: %s", err)
517 }
518 defer f.Close()
519
520 min := 2 * time.Second
521 for i := 0; i < 10; i++ {
522 if err = func() error {
523 // Connect to snapshotter service.
524 conn, err := tcp.Dial("tcp", cmd.host, snapshotter.MuxHeader)
525 if err != nil {
526 return err
527 }
528 defer conn.Close()
529
530 _, err = conn.Write([]byte{byte(req.Type)})
531 if err != nil {
532 return err
533 }
534
535 // Write the request
536 if err := json.NewEncoder(conn).Encode(req); err != nil {
537 return fmt.Errorf("encode snapshot request: %s", err)
538 }
539
540 // Read snapshot from the connection
541 if n, err := io.Copy(f, conn); err != nil || n == 0 {
542 return fmt.Errorf("copy backup to file: err=%v, n=%d", err, n)
543 }
544 return nil
545 }(); err == nil {
546 break
547 } else if err != nil {
548 backoff := time.Duration(math.Pow(3.8, float64(i))) * time.Millisecond
549 if backoff < min {
550 backoff = min
551 }
552 cmd.StderrLogger.Printf("Download shard %v failed %s. Waiting %v and retrying (%d)...\n", req.ShardID, err, backoff, i)
553 time.Sleep(backoff)
554 }
555 }
556
557 return err
558 }
559
560 // requestInfo will request the database or retention policy information from the host
561 func (cmd *Command) requestInfo(request *snapshotter.Request) (*snapshotter.Response, error) {
562 // Connect to snapshotter service.
563 var r snapshotter.Response
564 conn, err := tcp.Dial("tcp", cmd.host, snapshotter.MuxHeader)
565 if err != nil {
566 return nil, err
567 }
568 defer conn.Close()
569 _, err = conn.Write([]byte{byte(request.Type)})
570 if err != nil {
571 return &r, err
572 }
573
574 // Write the request
575 if err := json.NewEncoder(conn).Encode(request); err != nil {
576 return nil, fmt.Errorf("encode snapshot request: %s", err)
577 }
578
579 // Read the response
580
581 if err := json.NewDecoder(conn).Decode(&r); err != nil {
582 return nil, err
583 }
584
585 return &r, nil
586 }
587
588 // printUsage prints the usage message to STDERR.
589 func (cmd *Command) printUsage() {
590 fmt.Fprintf(cmd.Stdout, `
591 Creates a backup copy of specified InfluxDB OSS database(s) and saves the files in an Enterprise-compatible
592 format to PATH (directory where backups are saved).
593
594 Usage: influxd backup [options] PATH
595
596 -portable
597 Required to generate backup files in a portable format that can be restored to InfluxDB OSS or InfluxDB
598 Enterprise. Use unless the legacy backup is required.
599 -host <host:port>
600 InfluxDB OSS host to back up from. Optional. Defaults to 127.0.0.1:8088.
601 -db <name>
602 InfluxDB OSS database name to back up. Optional. If not specified, all databases are backed up when
603 using '-portable'.
604 -rp <name>
605 Retention policy to use for the backup. Optional. If not specified, all retention policies are used by
606 default.
607 -shard <id>
608 The identifier of the shard to back up. Optional. If specified, '-rp <rp_name>' is required.
609 -start <2015-12-24T08:12:23Z>
610 Include all points starting with specified timestamp (RFC3339 format).
611 Not compatible with '-since <timestamp>'.
612 -end <2015-12-24T08:12:23Z>
613 Exclude all points after timestamp (RFC3339 format).
614 Not compatible with '-since <timestamp>'.
615 -since <2015-12-24T08:12:23Z>
616 Create an incremental backup of all points after the timestamp (RFC3339 format). Optional.
617 Recommend using '-start <timestamp>' instead.
618 `)
619
620 }