github.com/coocood/badger@v1.5.1-0.20200528065104-c02ac3616d04/cmd/badger/cmd/backup.go (about) 1 /* 2 * Copyright 2017 Dgraph Labs, Inc. and Contributors 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package cmd 18 19 import ( 20 "os" 21 22 "github.com/coocood/badger" 23 "github.com/spf13/cobra" 24 ) 25 26 var backupFile string 27 var truncate bool 28 29 // backupCmd represents the backup command 30 var backupCmd = &cobra.Command{ 31 Use: "backup", 32 Short: "Backup Badger database.", 33 Long: `Backup Badger database to a file in a version-agnostic manner. 34 35 Iterates over each key-value pair, encodes it along with its metadata and 36 version in protocol buffers and writes them to a file. This file can later be 37 used by the restore command to create an identical copy of the 38 database.`, 39 RunE: doBackup, 40 } 41 42 func init() { 43 RootCmd.AddCommand(backupCmd) 44 backupCmd.Flags().StringVarP(&backupFile, "backup-file", "f", 45 "badger.bak", "File to backup to") 46 backupCmd.Flags().BoolVarP(&truncate, "truncate", "t", 47 false, "Allow value log truncation if required.") 48 } 49 50 func doBackup(cmd *cobra.Command, args []string) error { 51 // Open DB 52 opts := badger.DefaultOptions 53 opts.Dir = sstDir 54 opts.ValueDir = vlogDir 55 opts.Truncate = truncate 56 db, err := badger.Open(opts) 57 if err != nil { 58 return err 59 } 60 defer db.Close() 61 62 // Create File 63 f, err := os.Create(backupFile) 64 if err != nil { 65 return err 66 } 67 defer f.Close() 68 69 // Run Backup 70 _, err = db.Backup(f, 0) 71 return err 72 }