You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
autorestic/internal/location.go

449 lines
11 KiB

4 years ago
package internal
import (
"fmt"
4 years ago
"io/ioutil"
"os"
"path/filepath"
"strings"
4 years ago
"time"
4 years ago
"github.com/cupcakearmy/autorestic/internal/colors"
3 years ago
"github.com/cupcakearmy/autorestic/internal/flags"
4 years ago
"github.com/cupcakearmy/autorestic/internal/lock"
3 years ago
"github.com/cupcakearmy/autorestic/internal/metadata"
4 years ago
"github.com/robfig/cron"
4 years ago
)
type LocationType string
const (
TypeLocal LocationType = "local"
TypeVolume LocationType = "volume"
)
4 years ago
type HookArray = []string
type LocationForgetOption string
const (
LocationForgetYes LocationForgetOption = "yes"
LocationForgetNo LocationForgetOption = "no"
LocationForgetPrune LocationForgetOption = "prune"
)
4 years ago
type Hooks struct {
Dir string `mapstructure:"dir"`
Before HookArray `mapstructure:"before,omitempty"`
After HookArray `mapstructure:"after,omitempty"`
Success HookArray `mapstructure:"success,omitempty"`
Failure HookArray `mapstructure:"failure,omitempty"`
4 years ago
}
type LocationCopy = map[string][]string
4 years ago
type Location struct {
name string `mapstructure:",omitempty"`
From []string `mapstructure:"from,omitempty"`
Type string `mapstructure:"type,omitempty"`
To []string `mapstructure:"to,omitempty"`
Hooks Hooks `mapstructure:"hooks,omitempty"`
Cron string `mapstructure:"cron,omitempty"`
Options Options `mapstructure:"options,omitempty"`
ForgetOption LocationForgetOption `mapstructure:"forget,omitempty"`
CopyOption LocationCopy `mapstructure:"copy,omitempty"`
4 years ago
}
func GetLocation(name string) (Location, bool) {
l, ok := GetConfig().Locations[name]
l.name = name
return l, ok
}
func (l Location) validate() error {
if len(l.From) == 0 {
return fmt.Errorf(`Location "%s" is missing "from" key`, l.name)
}
t, err := l.getType()
if err != nil {
return err
}
switch t {
case TypeLocal:
for _, path := range l.From {
if from, err := GetPathRelativeToConfig(path); err != nil {
return err
} else {
if _, err := os.Stat(from); err != nil {
return err
}
4 years ago
}
}
case TypeVolume:
if len(l.From) > 1 {
return fmt.Errorf(`location "%s" has more than one docker volume`, l.name)
}
4 years ago
}
if len(l.To) == 0 {
return fmt.Errorf(`location "%s" has no "to" targets`, l.name)
}
4 years ago
// Check if backends are all valid
for _, to := range l.To {
_, ok := GetBackend(to)
4 years ago
if !ok {
return fmt.Errorf(`location "%s" has an invalid backend "%s"`, l.name, to)
}
}
// Check copy option
for copyFrom, copyTo := range l.CopyOption {
if _, ok := GetBackend(copyFrom); !ok {
return fmt.Errorf(`location "%s" has an invalid backend "%s" in copy option`, l.name, copyFrom)
}
if !ArrayContains(l.To, copyFrom) {
return fmt.Errorf(`location "%s" has an invalid copy from "%s"`, l.name, copyFrom)
}
for _, copyToTarget := range copyTo {
if _, ok := GetBackend(copyToTarget); !ok {
return fmt.Errorf(`location "%s" has an invalid backend "%s" in copy option`, l.name, copyToTarget)
}
if ArrayContains(l.To, copyToTarget) {
return fmt.Errorf(`location "%s" cannot copy to "%s" as it's already a target`, l.name, copyToTarget)
}
}
}
// Check if forget type is correct
if l.ForgetOption != "" {
if l.ForgetOption != LocationForgetYes && l.ForgetOption != LocationForgetNo && l.ForgetOption != LocationForgetPrune {
return fmt.Errorf("invalid value for forget option: %s", l.ForgetOption)
4 years ago
}
}
return nil
}
func (l Location) ExecuteHooks(commands []string, options ExecuteOptions) error {
4 years ago
if len(commands) == 0 {
return nil
}
if l.Hooks.Dir != "" {
if dir, err := GetPathRelativeToConfig(l.Hooks.Dir); err != nil {
return err
} else {
options.Dir = dir
}
}
colors.Secondary.Println("\nRunning hooks")
4 years ago
for _, command := range commands {
colors.Body.Println("> " + command)
_, out, err := ExecuteCommand(options, "-c", command)
if err != nil {
4 years ago
colors.Error.Println(out)
4 years ago
return err
}
}
colors.Body.Println("")
4 years ago
return nil
}
4 years ago
func (l Location) getType() (LocationType, error) {
t := strings.ToLower(l.Type)
if t == "" || t == "local" {
return TypeLocal, nil
} else if t == "volume" {
return TypeVolume, nil
}
return "", fmt.Errorf("invalid location type \"%s\"", l.Type)
}
3 years ago
func buildTag(parts ...string) string {
parts = append([]string{"ar"}, parts...)
return strings.Join(parts, ":")
}
3 years ago
func (l Location) getLocationTags() string {
return buildTag("location", l.name)
}
func (l Location) Backup(cron bool, specificBackend string) []error {
var errors []error
var backends []string
colors.PrimaryPrint(" Backing up location \"%s\" ", l.name)
t, err := l.getType()
if err != nil {
errors = append(errors, err)
return errors
}
cwd, _ := GetPathRelativeToConfig(".")
4 years ago
options := ExecuteOptions{
Command: "bash",
Dir: cwd,
3 years ago
Envs: map[string]string{
"AUTORESTIC_LOCATION": l.name,
},
4 years ago
}
if err := l.validate(); err != nil {
errors = append(errors, err)
goto after
}
// Hooks
if err := l.ExecuteHooks(l.Hooks.Before, options); err != nil {
errors = append(errors, err)
goto after
4 years ago
}
// Backup
if specificBackend == "" {
backends = l.To
} else {
if l.hasBackend(specificBackend) {
backends = []string{specificBackend}
} else {
errors = append(errors, fmt.Errorf("backup location \"%s\" has no backend \"%s\"", l.name, specificBackend))
return errors
}
}
for i, to := range backends {
4 years ago
backend, _ := GetBackend(to)
colors.Secondary.Printf("Backend: %s\n", backend.name)
4 years ago
env, err := backend.getEnv()
if err != nil {
errors = append(errors, err)
continue
4 years ago
}
4 years ago
cmd := []string{"backup"}
cmd = append(cmd, combineAllOptions("backup", l, backend)...)
4 years ago
if cron {
3 years ago
cmd = append(cmd, "--tag", buildTag("cron"))
4 years ago
}
3 years ago
cmd = append(cmd, "--tag", l.getLocationTags())
backupOptions := ExecuteOptions{
Envs: env,
}
var code int = 0
var out string
switch t {
case TypeLocal:
for _, from := range l.From {
path, err := GetPathRelativeToConfig(from)
if err != nil {
errors = append(errors, err)
goto after
}
cmd = append(cmd, path)
}
code, out, err = ExecuteResticCommand(backupOptions, cmd...)
case TypeVolume:
ok := CheckIfVolumeExists(l.From[0])
if !ok {
errors = append(errors, fmt.Errorf("volume \"%s\" does not exist", l.From[0]))
continue
}
cmd = append(cmd, "/data")
code, out, err = backend.ExecDocker(l, cmd)
4 years ago
}
3 years ago
// Extract metadata
3 years ago
md := metadata.ExtractMetadataFromBackupLog(out)
md.ExitCode = fmt.Sprint(code)
3 years ago
mdEnv := metadata.MakeEnvFromMetadata(&md)
for k, v := range mdEnv {
options.Envs[k+"_"+fmt.Sprint(i)] = v
options.Envs[k+"_"+strings.ToUpper(backend.name)] = v
}
// If error save it and continue
if err != nil {
colors.Error.Println(out)
errors = append(errors, fmt.Errorf("%s@%s:\n%s%s", l.name, backend.name, out, err))
continue
}
// Copy
if md.SnapshotID != "" {
for copyFrom, copyTo := range l.CopyOption {
b1, _ := GetBackend(copyFrom)
for _, copyToTarget := range copyTo {
b2, _ := GetBackend(copyToTarget)
colors.Secondary.Println("Copying " + copyFrom + " → " + copyToTarget)
env, _ := b1.getEnv()
env2, _ := b2.getEnv()
// Add the second repo to the env with a "2" suffix
for k, v := range env2 {
env[k+"2"] = v
}
_, _, err := ExecuteResticCommand(ExecuteOptions{
Envs: env,
}, "copy", md.SnapshotID)
if err != nil {
errors = append(errors, err)
}
}
}
}
4 years ago
}
// After hooks
if err := l.ExecuteHooks(l.Hooks.After, options); err != nil {
errors = append(errors, err)
4 years ago
}
after:
var commands []string
var isSuccess = len(errors) == 0
if isSuccess {
commands = l.Hooks.Success
} else {
commands = l.Hooks.Failure
}
if err := l.ExecuteHooks(commands, options); err != nil {
errors = append(errors, err)
}
// Forget and optionally prune
if isSuccess && l.ForgetOption != "" && l.ForgetOption != LocationForgetNo {
err := l.Forget(l.ForgetOption == LocationForgetPrune, false)
if err != nil {
errors = append(errors, err)
}
}
if len(errors) == 0 {
colors.Success.Println("Done")
}
return errors
4 years ago
}
4 years ago
func (l Location) Forget(prune bool, dry bool) error {
colors.PrimaryPrint("Forgetting for location \"%s\"", l.name)
backendsToForget := l.To
for _, copyBackends := range l.CopyOption {
backendsToForget = append(backendsToForget, copyBackends...)
}
for _, to := range backendsToForget {
backend, _ := GetBackend(to)
colors.Secondary.Printf("For backend \"%s\"\n", backend.name)
env, err := backend.getEnv()
if err != nil {
return nil
}
options := ExecuteOptions{
Envs: env,
}
3 years ago
cmd := []string{"forget", "--tag", l.getLocationTags()}
4 years ago
if prune {
cmd = append(cmd, "--prune")
}
if dry {
cmd = append(cmd, "--dry-run")
}
cmd = append(cmd, combineAllOptions("forget", l, backend)...)
_, _, err = ExecuteResticCommand(options, cmd...)
4 years ago
if err != nil {
return err
}
}
colors.Success.Println("Done")
return nil
4 years ago
}
4 years ago
func (l Location) hasBackend(backend string) bool {
for _, b := range l.To {
if b == backend {
return true
}
}
return false
}
func buildRestoreCommand(l Location, to string, snapshot string, options []string) []string {
base := []string{"restore", "--target", to, "--tag", l.getLocationTags(), snapshot}
base = append(base, options...)
return base
}
func (l Location) Restore(to, from string, force bool, snapshot string, options []string) error {
4 years ago
if from == "" {
from = l.To[0]
} else if !l.hasBackend(from) {
return fmt.Errorf("invalid backend: \"%s\"", from)
}
if snapshot == "" {
snapshot = "latest"
}
colors.PrimaryPrint("Restoring location \"%s\"", l.name)
backend, _ := GetBackend(from)
colors.Secondary.Printf("Restoring %s@%s → %s\n", snapshot, backend.name, to)
t, err := l.getType()
4 years ago
if err != nil {
return err
4 years ago
}
switch t {
case TypeLocal:
to, err = filepath.Abs(to)
if err != nil {
return err
}
// Check if target is empty
if !force {
notEmptyError := fmt.Errorf("target %s is not empty", to)
_, err = os.Stat(to)
if err == nil {
files, err := ioutil.ReadDir(to)
if err != nil {
return err
}
if len(files) > 0 {
return notEmptyError
}
} else {
if !os.IsNotExist(err) {
return err
}
}
}
err = backend.Exec(buildRestoreCommand(l, to, snapshot, options))
case TypeVolume:
_, _, err = backend.ExecDocker(l, buildRestoreCommand(l, "/", snapshot, options))
}
4 years ago
if err != nil {
return err
}
colors.Success.Println("Done")
4 years ago
return nil
}
4 years ago
func (l Location) RunCron() error {
if l.Cron == "" {
return nil
}
schedule, err := cron.ParseStandard(l.Cron)
if err != nil {
return err
}
last := time.Unix(lock.GetCron(l.name), 0)
4 years ago
next := schedule.Next(last)
4 years ago
now := time.Now()
if now.After(next) {
lock.SetCron(l.name, now.Unix())
l.Backup(true, "")
4 years ago
} else {
3 years ago
if !flags.CRON_LEAN {
4 years ago
colors.Body.Printf("Skipping \"%s\", not due yet.\n", l.name)
}
4 years ago
}
return nil
}