2
2
mirror of https://github.com/octoleo/restic.git synced 2024-11-15 17:47:21 +00:00
restic/cmd/restic/cmd_backup.go

320 lines
7.3 KiB
Go
Raw Normal View History

2014-04-27 22:00:15 +00:00
package main
import (
"errors"
2014-04-27 22:00:15 +00:00
"fmt"
2014-09-23 20:39:12 +00:00
"os"
2015-03-02 13:48:47 +00:00
"path/filepath"
"strings"
2014-11-16 21:50:20 +00:00
"time"
2014-04-27 22:00:15 +00:00
2014-12-05 20:45:49 +00:00
"github.com/restic/restic"
"github.com/restic/restic/backend"
"github.com/restic/restic/filter"
2015-05-09 23:08:24 +00:00
"github.com/restic/restic/repository"
"golang.org/x/crypto/ssh/terminal"
2014-04-27 22:00:15 +00:00
)
2015-03-02 13:48:47 +00:00
type CmdBackup struct {
Parent string `short:"p" long:"parent" description:"use this parent snapshot (default: last snapshot in repo that has the same target)"`
Force bool `short:"f" long:"force" description:"Force re-reading the target. Overrides the \"parent\" flag"`
Excludes []string `short:"e" long:"exclude" description:"Exclude a pattern (can be specified multiple times)"`
global *GlobalOptions
2015-03-02 13:48:47 +00:00
}
2014-12-07 15:30:52 +00:00
2014-11-30 21:39:58 +00:00
func init() {
2014-12-07 15:30:52 +00:00
_, err := parser.AddCommand("backup",
"save file/directory",
"The backup command creates a snapshot of a file or directory",
&CmdBackup{global: &globalOpts})
2014-12-07 15:30:52 +00:00
if err != nil {
panic(err)
}
2014-11-30 21:39:58 +00:00
}
2015-04-24 23:39:32 +00:00
func formatBytes(c uint64) string {
b := float64(c)
switch {
case c > 1<<40:
2014-11-23 13:53:46 +00:00
return fmt.Sprintf("%.3f TiB", b/(1<<40))
case c > 1<<30:
2014-11-23 13:53:46 +00:00
return fmt.Sprintf("%.3f GiB", b/(1<<30))
case c > 1<<20:
2014-11-23 13:53:46 +00:00
return fmt.Sprintf("%.3f MiB", b/(1<<20))
case c > 1<<10:
2014-11-23 13:53:46 +00:00
return fmt.Sprintf("%.3f KiB", b/(1<<10))
default:
2014-11-23 11:05:43 +00:00
return fmt.Sprintf("%dB", c)
}
}
2015-04-24 23:39:32 +00:00
func formatSeconds(sec uint64) string {
2014-11-23 11:05:43 +00:00
hours := sec / 3600
sec -= hours * 3600
min := sec / 60
sec -= min * 60
if hours > 0 {
return fmt.Sprintf("%d:%02d:%02d", hours, min, sec)
}
return fmt.Sprintf("%d:%02d", min, sec)
}
2015-04-25 17:20:41 +00:00
func formatPercent(numerator uint64, denominator uint64) string {
if denominator == 0 {
return ""
}
percent := 100.0 * float64(numerator) / float64(denominator)
if percent > 100 {
percent = 100
}
return fmt.Sprintf("%3.2f%%", percent)
}
func formatRate(bytes uint64, duration time.Duration) string {
sec := float64(duration) / float64(time.Second)
rate := float64(bytes) / sec / (1 << 20)
return fmt.Sprintf("%.2fMiB/s", rate)
}
2015-04-24 23:39:32 +00:00
func formatDuration(d time.Duration) string {
sec := uint64(d / time.Second)
2015-04-24 23:39:32 +00:00
return formatSeconds(sec)
}
2015-04-24 23:39:32 +00:00
func printTree2(indent int, t *restic.Tree) {
for _, node := range t.Nodes {
if node.Tree() != nil {
fmt.Printf("%s%s/\n", strings.Repeat(" ", indent), node.Name)
2015-04-24 23:39:32 +00:00
printTree2(indent+1, node.Tree())
} else {
fmt.Printf("%s%s\n", strings.Repeat(" ", indent), node.Name)
}
}
}
2014-12-07 15:30:52 +00:00
func (cmd CmdBackup) Usage() string {
2015-05-02 00:05:09 +00:00
return "DIR/FILE [DIR/FILE] [...]"
2014-12-07 15:30:52 +00:00
}
func (cmd CmdBackup) newScanProgress() *restic.Progress {
if !cmd.global.ShowProgress() {
2015-02-21 13:23:49 +00:00
return nil
}
2015-02-21 14:32:48 +00:00
p := restic.NewProgress(time.Second)
p.OnUpdate = func(s restic.Stat, d time.Duration, ticker bool) {
2015-04-24 23:39:32 +00:00
fmt.Printf("\x1b[2K[%s] %d directories, %d files, %s\r", formatDuration(d), s.Dirs, s.Files, formatBytes(s.Bytes))
2015-02-21 14:32:48 +00:00
}
p.OnDone = func(s restic.Stat, d time.Duration, ticker bool) {
2015-04-24 23:39:32 +00:00
fmt.Printf("\x1b[2Kscanned %d directories, %d files in %s\n", s.Dirs, s.Files, formatDuration(d))
2015-02-21 14:32:48 +00:00
}
return p
}
func (cmd CmdBackup) newArchiveProgress(todo restic.Stat) *restic.Progress {
if !cmd.global.ShowProgress() {
2015-02-21 13:23:49 +00:00
return nil
}
archiveProgress := restic.NewProgress(time.Second)
var bps, eta uint64
itemsTodo := todo.Files + todo.Dirs
archiveProgress.OnUpdate = func(s restic.Stat, d time.Duration, ticker bool) {
sec := uint64(d / time.Second)
if todo.Bytes > 0 && sec > 0 && ticker {
bps = s.Bytes / sec
2015-03-16 19:20:53 +00:00
if s.Bytes >= todo.Bytes {
eta = 0
} else if bps > 0 {
2015-02-21 13:23:49 +00:00
eta = (todo.Bytes - s.Bytes) / bps
}
}
itemsDone := s.Files + s.Dirs
2015-03-16 19:20:53 +00:00
status1 := fmt.Sprintf("[%s] %s %s/s %s / %s %d / %d items %d errors ",
2015-04-24 23:39:32 +00:00
formatDuration(d),
2015-04-25 17:20:41 +00:00
formatPercent(s.Bytes, todo.Bytes),
2015-04-24 23:39:32 +00:00
formatBytes(bps),
formatBytes(s.Bytes), formatBytes(todo.Bytes),
itemsDone, itemsTodo,
s.Errors)
2015-04-24 23:39:32 +00:00
status2 := fmt.Sprintf("ETA %s ", formatSeconds(eta))
w, _, err := terminal.GetSize(int(os.Stdout.Fd()))
if err == nil {
if len(status1)+len(status2) > w {
max := w - len(status2) - 4
status1 = status1[:max] + "... "
}
}
fmt.Printf("\x1b[2K%s%s\r", status1, status2)
2015-02-21 13:23:49 +00:00
}
archiveProgress.OnDone = func(s restic.Stat, d time.Duration, ticker bool) {
2015-04-25 17:20:41 +00:00
fmt.Printf("\nduration: %s, %s\n", formatDuration(d), formatRate(todo.Bytes, d))
2015-02-21 13:23:49 +00:00
}
return archiveProgress
2015-02-16 22:44:26 +00:00
}
2015-05-09 23:08:24 +00:00
func samePaths(expected, actual []string) bool {
if expected == nil || actual == nil {
return true
}
if len(expected) != len(actual) {
return false
}
for i := range expected {
if expected[i] != actual[i] {
return false
}
}
return true
}
func findLatestSnapshot(repo *repository.Repository, targets []string) (backend.ID, error) {
var (
latest time.Time
latestID backend.ID
)
for snapshotID := range repo.List(backend.Snapshot, make(chan struct{})) {
snapshot, err := restic.LoadSnapshot(repo, snapshotID)
if err != nil {
return nil, fmt.Errorf("Error listing snapshot: %v", err)
}
if snapshot.Time.After(latest) && samePaths(snapshot.Paths, targets) {
latest = snapshot.Time
latestID = snapshotID
}
}
return latestID, nil
}
// filterExisting returns a slice of all existing items, or an error if no
// items exist at all.
func filterExisting(items []string) (result []string, err error) {
for _, item := range items {
_, err := os.Lstat(item)
if err != nil && os.IsNotExist(err) {
continue
}
result = append(result, item)
}
if len(result) == 0 {
return nil, errors.New("all target directories/files do not exist")
}
return
}
2014-12-07 15:30:52 +00:00
func (cmd CmdBackup) Execute(args []string) error {
2015-03-02 13:48:47 +00:00
if len(args) == 0 {
2014-12-07 15:30:52 +00:00
return fmt.Errorf("wrong number of parameters, Usage: %s", cmd.Usage())
}
2015-03-02 13:48:47 +00:00
target := make([]string, 0, len(args))
for _, d := range args {
if a, err := filepath.Abs(d); err == nil {
d = a
}
target = append(target, d)
}
target, err := filterExisting(target)
if err != nil {
return err
}
repo, err := cmd.global.OpenRepository()
2014-12-07 15:30:52 +00:00
if err != nil {
return err
2014-04-27 22:00:15 +00:00
}
lock, err := lockRepo(repo)
defer unlockRepo(lock)
2015-06-27 12:40:18 +00:00
if err != nil {
return err
}
err = repo.LoadIndex()
if err != nil {
return err
}
var parentSnapshotID backend.ID
2014-11-30 21:34:21 +00:00
// Force using a parent
if !cmd.Force && cmd.Parent != "" {
parentSnapshotID, err = restic.FindSnapshot(repo, cmd.Parent)
2014-11-30 21:34:21 +00:00
if err != nil {
2015-03-02 13:48:47 +00:00
return fmt.Errorf("invalid id %q: %v", cmd.Parent, err)
2014-11-30 21:34:21 +00:00
}
2015-06-21 11:25:26 +00:00
cmd.global.Verbosef("found parent snapshot %v\n", parentSnapshotID.Str())
2014-11-30 21:34:21 +00:00
}
2014-04-27 22:00:15 +00:00
// Find last snapshot to set it as parent, if not already set
if !cmd.Force && parentSnapshotID == nil {
parentSnapshotID, err = findLatestSnapshot(repo, target)
2015-05-09 23:08:24 +00:00
if err != nil {
return err
}
if parentSnapshotID != nil {
2015-06-21 11:25:26 +00:00
cmd.global.Verbosef("using parent snapshot %v\n", parentSnapshotID)
}
}
2015-06-21 11:25:26 +00:00
cmd.global.Verbosef("scan %v\n", target)
selectFilter := func(item string, fi os.FileInfo) bool {
matched, err := filter.List(cmd.Excludes, item)
if err != nil {
cmd.global.Warnf("error for exclude pattern: %v", err)
}
return !matched
}
stat, err := restic.Scan(target, selectFilter, cmd.newScanProgress())
if err != nil {
return err
}
arch := restic.NewArchiver(repo)
arch.Excludes = cmd.Excludes
arch.SelectFilter = selectFilter
2014-11-23 11:05:43 +00:00
arch.Error = func(dir string, fi os.FileInfo, err error) error {
// TODO: make ignoring errors configurable
cmd.global.Warnf("\x1b[2K\rerror for %s: %v\n", dir, err)
return nil
}
_, id, err := arch.Snapshot(cmd.newArchiveProgress(stat), target, parentSnapshotID)
if err != nil {
2015-02-03 21:05:46 +00:00
return err
}
2015-06-21 11:25:26 +00:00
cmd.global.Verbosef("snapshot %s saved\n", id.Str())
2014-04-27 22:00:15 +00:00
return nil
}