Compare commits

..

3 Commits

Author SHA1 Message Date
Boris Bera
c330cf5074 Merge 5e98d4b362 into 6424c64304 2024-10-14 14:42:50 +00:00
Boris Bera
5e98d4b362 chore(ci): install restic in test env 2024-10-14 10:42:34 -04:00
Boris Bera
d243c924cc chore(tests): add integration tests for backup cmd 2024-10-14 10:41:46 -04:00
11 changed files with 132 additions and 129 deletions

View File

@@ -4,11 +4,25 @@ on:
push: push:
branches: [master] branches: [master]
env:
RESTIC_VERSION: "0.17.1"
jobs: jobs:
test: test:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v3 - uses: actions/checkout@v3
- name: Install restic@${{ env.RESTIC_VERSION }}
run: |
mkdir -p tools/restic
curl --fail --location --silent --show-error --output tools/restic/restic.bz2 \
"https://github.com/restic/restic/releases/download/v${RESTIC_VERSION}/restic_${RESTIC_VERSION}_linux_amd64.bz2"
bzip2 -d tools/restic/restic.bz2
chmod +x tools/restic/restic
echo "$GITHUB_WORKSPACE/tools/restic" >> "$GITHUB_PATH"
- run: restic version
- uses: actions/setup-go@v3 - uses: actions/setup-go@v3
with: with:
go-version: '^1.21' go-version: '^1.21'

View File

@@ -1,4 +1,4 @@
FROM golang:1.25-alpine as builder FROM golang:1.23-alpine as builder
WORKDIR /app WORKDIR /app
COPY go.* . COPY go.* .
@@ -6,7 +6,7 @@ RUN go mod download
COPY . . COPY . .
RUN go build RUN go build
FROM restic/restic:0.17.3 FROM restic/restic:0.17.1
RUN apk add --no-cache rclone bash curl docker-cli RUN apk add --no-cache rclone bash curl docker-cli
COPY --from=builder /app/autorestic /usr/bin/autorestic COPY --from=builder /app/autorestic /usr/bin/autorestic
ENTRYPOINT [] ENTRYPOINT []

View File

@@ -18,11 +18,9 @@ var backupCmd = &cobra.Command{
err := lock.Lock() err := lock.Lock()
CheckErr(err) CheckErr(err)
defer lock.Unlock() defer lock.Unlock()
dry, _ := cmd.Flags().GetBool("dry-run")
selected, err := internal.GetAllOrSelected(cmd, false) selected, err := internal.GetAllOrSelected(cmd, false)
CheckErr(err) CheckErr(err)
errors := 0 errors := 0
for _, name := range selected { for _, name := range selected {
var splitted = strings.Split(name, "@") var splitted = strings.Split(name, "@")
@@ -31,7 +29,7 @@ var backupCmd = &cobra.Command{
specificBackend = splitted[1] specificBackend = splitted[1]
} }
location, _ := internal.GetLocation(splitted[0]) location, _ := internal.GetLocation(splitted[0])
errs := location.Backup(false, dry, specificBackend) errs := location.Backup(false, specificBackend)
for _, err := range errs { for _, err := range errs {
colors.Error.Printf("%s\n\n", err) colors.Error.Printf("%s\n\n", err)
errors++ errors++
@@ -46,5 +44,4 @@ var backupCmd = &cobra.Command{
func init() { func init() {
rootCmd.AddCommand(backupCmd) rootCmd.AddCommand(backupCmd)
internal.AddFlagsToCommand(backupCmd, false) internal.AddFlagsToCommand(backupCmd, false)
backupCmd.Flags().Bool("dry-run", false, "do not write changes, show what would be affected")
} }

75
cmd/backup_test.go Normal file
View File

@@ -0,0 +1,75 @@
package cmd
import (
"os"
"path"
"testing"
"github.com/spf13/viper"
"github.com/stretchr/testify/assert"
"gopkg.in/yaml.v3"
)
func runCmd(t *testing.T, args ...string) error {
t.Helper()
viper.Reset()
rootCmd.SetArgs(args)
err := rootCmd.Execute()
return err
}
func TestBackupCmd(t *testing.T) {
t.Run("simple local backup and restore", func(t *testing.T) {
workDir := t.TempDir()
// Prepare content to be backed up
locationDir := path.Join(workDir, "my-location")
err := os.Mkdir(locationDir, 0750)
assert.Nil(t, err)
err = os.WriteFile(path.Join(locationDir, "back-me-up.txt"), []byte("hello world"), 0640)
assert.Nil(t, err)
// Write config file
config, err := yaml.Marshal(map[string]interface{}{
"version": 2,
"locations": map[string]map[string]interface{}{
"my-location": {
"type": "local",
"from": []string{locationDir},
"to": []string{"test"},
},
},
"backends": map[string]map[string]interface{}{
"test": {
"type": "local",
"path": path.Join(workDir, "test-backend"),
"key": "supersecret",
},
},
})
assert.Nil(t, err)
configPath := path.Join(workDir, ".autorestic.yml")
err = os.WriteFile(configPath, config, 0640)
assert.Nil(t, err)
// Init repo (not initialized by default)
err = runCmd(t, "exec", "--ci", "-a", "-c", configPath, "init")
assert.Nil(t, err)
// Do the backup
err = runCmd(t, "backup", "--ci", "-a", "-c", configPath)
assert.Nil(t, err)
// Restore in a separate dir
restoreDir := path.Join(workDir, "restore")
err = runCmd(t, "restore", "--ci", "-c", configPath, "-l", "my-location", "--to", restoreDir)
assert.Nil(t, err)
// Check restored file
restoredContent, err := os.ReadFile(path.Join(restoreDir, locationDir, "back-me-up.txt"))
assert.Nil(t, err)
assert.Equal(t, "hello world", string(restoredContent))
})
}

View File

@@ -1,14 +1,11 @@
# Backup # Backup
```bash ```bash
autorestic backup [-l, --location] [-a, --all] [--dry-run] autorestic backup [-l, --location] [-a, --all]
``` ```
Performs a backup of all locations if the `-a` flag is passed. To only backup some locations pass one or more `-l` or `--location` flags. Performs a backup of all locations if the `-a` flag is passed. To only backup some locations pass one or more `-l` or `--location` flags.
The `--dry-run` flag will do a dry run showing what would have been deleted, but won't touch the actual data.
```bash ```bash
# All # All
autorestic backup -a autorestic backup -a

View File

@@ -1,5 +1,5 @@
#!/bin/bash #!/bin/bash
set -e -o pipefail
shopt -s nocaseglob shopt -s nocaseglob
OUT_FILE=/usr/local/bin/autorestic OUT_FILE=/usr/local/bin/autorestic

View File

@@ -14,19 +14,19 @@ import (
) )
type BackendRest struct { type BackendRest struct {
User string `mapstructure:"user,omitempty" yaml:"user,omitempty"` User string `mapstructure:"user,omitempty"`
Password string `mapstructure:"password,omitempty" yaml:"password,omitempty"` Password string `mapstructure:"password,omitempty"`
} }
type Backend struct { type Backend struct {
name string name string
Type string `mapstructure:"type,omitempty" yaml:"type,omitempty"` Type string `mapstructure:"type,omitempty"`
Path string `mapstructure:"path,omitempty" yaml:"path,omitempty"` Path string `mapstructure:"path,omitempty"`
Key string `mapstructure:"key,omitempty" yaml:"key,omitempty"` Key string `mapstructure:"key,omitempty"`
RequireKey bool `mapstructure:"requireKey,omitempty" yaml:"requireKey,omitempty"` RequireKey bool `mapstructure:"requireKey,omitempty"`
Env map[string]string `mapstructure:"env,omitempty" yaml:"env,omitempty"` Env map[string]string `mapstructure:"env,omitempty"`
Rest BackendRest `mapstructure:"rest,omitempty" yaml:"rest,omitempty"` Rest BackendRest `mapstructure:"rest,omitempty"`
Options Options `mapstructure:"options,omitempty" yaml:"options,omitempty"` Options Options `mapstructure:"options,omitempty"`
} }
func GetBackend(name string) (Backend, bool) { func GetBackend(name string) (Backend, bool) {

View File

@@ -23,11 +23,11 @@ type OptionMap map[string][]interface{}
type Options map[string]OptionMap type Options map[string]OptionMap
type Config struct { type Config struct {
Version string `mapstructure:"version" yaml:"version"` Version string `mapstructure:"version"`
Extras interface{} `mapstructure:"extras" yaml:"extras"` Extras interface{} `mapstructure:"extras"`
Locations map[string]Location `mapstructure:"locations" yaml:"locations"` Locations map[string]Location `mapstructure:"locations"`
Backends map[string]Backend `mapstructure:"backends" yaml:"backends"` Backends map[string]Backend `mapstructure:"backends"`
Global Options `mapstructure:"global" yaml:"global"` Global Options `mapstructure:"global"`
} }
var once sync.Once var once sync.Once
@@ -188,34 +188,18 @@ func CheckConfig() error {
if !CheckIfResticIsCallable() { if !CheckIfResticIsCallable() {
return fmt.Errorf(`%s was not found. Install either with "autorestic install" or manually`, flags.RESTIC_BIN) return fmt.Errorf(`%s was not found. Install either with "autorestic install" or manually`, flags.RESTIC_BIN)
} }
cwd, _ := GetPathRelativeToConfig(".")
for name, location := range c.Locations {
location.name = name
// Hooks before location validation
options := ExecuteOptions{
Command: "bash",
Dir: cwd,
Envs: map[string]string{
"AUTORESTIC_LOCATION": location.name,
},
}
if err := location.ExecuteHooks(location.Hooks.PreValidate, options); err != nil {
return err
}
if err := location.validate(); err != nil {
return err
}
}
for name, backend := range c.Backends { for name, backend := range c.Backends {
backend.name = name backend.name = name
if err := backend.validate(); err != nil { if err := backend.validate(); err != nil {
return err return err
} }
} }
for name, location := range c.Locations {
location.name = name
if err := location.validate(); err != nil {
return err
}
}
return nil return nil
} }

View File

@@ -1,15 +1,10 @@
package internal package internal
import ( import (
"path"
"reflect" "reflect"
"strconv" "strconv"
"strings" "strings"
"sync"
"testing" "testing"
"github.com/spf13/viper"
"github.com/stretchr/testify/assert"
) )
func TestOptionToString(t *testing.T) { func TestOptionToString(t *testing.T) {
@@ -148,48 +143,6 @@ func TestGetOptionsMultipleKeys(t *testing.T) {
reflect.DeepEqual(result, expected) reflect.DeepEqual(result, expected)
} }
func TestSaveConfigProducesReadableConfig(t *testing.T) {
workDir := t.TempDir()
viper.SetConfigFile(path.Join(workDir, ".autorestic.yml"))
// Required to appease the config reader
viper.Set("version", 2)
c := Config{
Version: "2",
Locations: map[string]Location{
"test": {
Type: "local",
name: "test",
From: []string{"in-dir"},
To: []string{"test"},
// ForgetOption & ConfigOption have previously marshalled in a way that
// can't get read correctly
ForgetOption: "foo",
CopyOption: map[string][]string{"foo": {"bar"}},
},
},
Backends: map[string]Backend{
"test": {
name: "test",
Type: "local",
Path: "backup-target",
Key: "supersecret",
},
},
}
err := c.SaveConfig()
assert.NoError(t, err)
// Ensure we the config reading logic actually runs
config = nil
once = sync.Once{}
readConfig := GetConfig()
assert.NotNil(t, readConfig)
assert.Equal(t, c, *readConfig)
}
func assertEqual[T comparable](t testing.TB, result, expected T) { func assertEqual[T comparable](t testing.TB, result, expected T) {
t.Helper() t.Helper()

View File

@@ -1,22 +1,12 @@
package internal package internal
import (
"errors"
"fmt"
)
func RunCron() error { func RunCron() error {
c := GetConfig() c := GetConfig()
var errs []error
for name, l := range c.Locations { for name, l := range c.Locations {
l.name = name l.name = name
if err := l.RunCron(); err != nil { if err := l.RunCron(); err != nil {
errs = append(errs, err) return err
} }
} }
if len(errs) > 0 {
return fmt.Errorf("Encountered errors during cron process:\n%w", errors.Join(errs...))
}
return nil return nil
} }

View File

@@ -1,7 +1,6 @@
package internal package internal
import ( import (
"errors"
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"os" "os"
@@ -34,26 +33,26 @@ const (
) )
type Hooks struct { type Hooks struct {
Dir string `mapstructure:"dir" yaml:"dir"` Dir string `mapstructure:"dir"`
PreValidate HookArray `mapstructure:"prevalidate,omitempty" yaml:"prevalidate,omitempty"` PreValidate HookArray `mapstructure:"prevalidate,omitempty"`
Before HookArray `mapstructure:"before,omitempty" yaml:"before,omitempty"` Before HookArray `mapstructure:"before,omitempty"`
After HookArray `mapstructure:"after,omitempty" yaml:"after,omitempty"` After HookArray `mapstructure:"after,omitempty"`
Success HookArray `mapstructure:"success,omitempty" yaml:"success,omitempty"` Success HookArray `mapstructure:"success,omitempty"`
Failure HookArray `mapstructure:"failure,omitempty" yaml:"failure,omitempty"` Failure HookArray `mapstructure:"failure,omitempty"`
} }
type LocationCopy = map[string][]string type LocationCopy = map[string][]string
type Location struct { type Location struct {
name string `mapstructure:",omitempty" yaml:",omitempty"` name string `mapstructure:",omitempty"`
From []string `mapstructure:"from,omitempty" yaml:"from,omitempty"` From []string `mapstructure:"from,omitempty"`
Type string `mapstructure:"type,omitempty" yaml:"type,omitempty"` Type string `mapstructure:"type,omitempty"`
To []string `mapstructure:"to,omitempty" yaml:"to,omitempty"` To []string `mapstructure:"to,omitempty"`
Hooks Hooks `mapstructure:"hooks,omitempty" yaml:"hooks,omitempty"` Hooks Hooks `mapstructure:"hooks,omitempty"`
Cron string `mapstructure:"cron,omitempty" yaml:"cron,omitempty"` Cron string `mapstructure:"cron,omitempty"`
Options Options `mapstructure:"options,omitempty" yaml:"options,omitempty"` Options Options `mapstructure:"options,omitempty"`
ForgetOption LocationForgetOption `mapstructure:"forget,omitempty" yaml:"forget,omitempty"` ForgetOption LocationForgetOption `mapstructure:"forget,omitempty"`
CopyOption LocationCopy `mapstructure:"copy,omitempty" yaml:"copy,omitempty"` CopyOption LocationCopy `mapstructure:"copy,omitempty"`
} }
func GetLocation(name string) (Location, bool) { func GetLocation(name string) (Location, bool) {
@@ -168,7 +167,7 @@ func (l Location) getLocationTags() string {
return buildTag("location", l.name) return buildTag("location", l.name)
} }
func (l Location) Backup(cron bool, dry bool, specificBackend string) []error { func (l Location) Backup(cron bool, specificBackend string) []error {
var errors []error var errors []error
var backends []string var backends []string
colors.PrimaryPrint(" Backing up location \"%s\" ", l.name) colors.PrimaryPrint(" Backing up location \"%s\" ", l.name)
@@ -228,9 +227,6 @@ func (l Location) Backup(cron bool, dry bool, specificBackend string) []error {
if cron { if cron {
cmd = append(cmd, "--tag", buildTag("cron")) cmd = append(cmd, "--tag", buildTag("cron"))
} }
if dry {
cmd = append(cmd, "--dry-run")
}
cmd = append(cmd, "--tag", l.getLocationTags()) cmd = append(cmd, "--tag", l.getLocationTags())
backupOptions := ExecuteOptions{ backupOptions := ExecuteOptions{
Envs: env, Envs: env,
@@ -450,10 +446,7 @@ func (l Location) RunCron() error {
now := time.Now() now := time.Now()
if now.After(next) { if now.After(next) {
lock.SetCron(l.name, now.Unix()) lock.SetCron(l.name, now.Unix())
errs := l.Backup(true, false, "") l.Backup(true, "")
if len(errs) > 0 {
return fmt.Errorf("Failed to backup location \"%s\":\n%w", l.name, errors.Join(errs...))
}
} else { } else {
if !flags.CRON_LEAN { if !flags.CRON_LEAN {
colors.Body.Printf("Skipping \"%s\", not due yet.\n", l.name) colors.Body.Printf("Skipping \"%s\", not due yet.\n", l.name)