Skip to content
This repository was archived by the owner on Apr 5, 2024. It is now read-only.

Commit f9fc7b1

Browse files
author
Lukas Knuth
committed
Added basic restic command module.
This helps interact with a restic binary to get the actual backup process running.
1 parent f416dd3 commit f9fc7b1

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

restic/command.go

+70
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
package restic
2+
3+
import (
4+
"errors"
5+
"fmt"
6+
"os"
7+
"os/exec"
8+
)
9+
10+
// Empty string = current directory.
11+
const CURRENT_DIR = ""
12+
13+
func SafeInit() (err error) {
14+
err = execRestic([]string{"snapshots"}, CURRENT_DIR)
15+
var e *exec.ExitError
16+
if err != nil && errors.As(err, &e) {
17+
if e.ExitCode() != 0 {
18+
// No repo initialized yet!
19+
err = execRestic([]string{"init"}, CURRENT_DIR)
20+
}
21+
}
22+
// no error, the repo is initialized and accessible
23+
return
24+
}
25+
26+
func Backup(pvcName string) error {
27+
workingDir := envFallback("BACKUP_TARGET_DIR", "/mnt/target")
28+
err := execRestic([]string{"backup", ".", "--no-cache", "--host", pvcName}, workingDir)
29+
return err
30+
}
31+
32+
func Restore(pvcName string) error {
33+
workingDir := envFallback("RESTORE_TARGET_DIR", "/mnt/target")
34+
err := execRestic([]string{"restore", "latest", "--target", workingDir, "--no-cache", "--host", pvcName}, CURRENT_DIR)
35+
return err
36+
}
37+
38+
func Version() error {
39+
return execRestic([]string{"version"}, CURRENT_DIR)
40+
}
41+
42+
func execRestic(args []string, workingDir string) error {
43+
resticPath := envFallback("RESTIC_PATH", "/app/restic")
44+
command := exec.Cmd {
45+
Path: resticPath,
46+
Args: append([]string{resticPath}, args...),
47+
Env: nil, // Re-use environment from this process!
48+
Dir: workingDir,
49+
}
50+
var e *exec.ExitError
51+
output, err := command.CombinedOutput()
52+
fmt.Printf("--- Restic invocation ---\n")
53+
fmt.Printf("Path: %s\nArgs: %s\n", resticPath, args)
54+
if err != nil && errors.As(err, &e) {
55+
fmt.Printf("Exit Code: %d", e.ExitCode())
56+
} else {
57+
fmt.Println("Exit Code: 0")
58+
}
59+
fmt.Printf("--- Output Start ---\n%s\n--- Output End ---\n", output)
60+
return err
61+
}
62+
63+
func envFallback(name string, fallback string) string {
64+
value, found := os.LookupEnv(name)
65+
if found {
66+
return value
67+
} else {
68+
return fallback
69+
}
70+
}

0 commit comments

Comments
 (0)