kopia-k8s/command_kopia_backup.go

78 lines
1.4 KiB
Go

package main
import (
"fmt"
"os"
"github.com/urfave/cli/v2"
)
func newKopiaBackupCommand() *cli.Command {
hostname, err := os.Hostname()
if err != nil {
hostname = "kopia-k8s"
}
return &cli.Command{
Name: "backup",
Usage: "Does a backup",
Action: runBackup,
Flags: []cli.Flag{
&cli.PathFlag{
Name: "path",
Aliases: []string{"p"},
Usage: "Path which should get backed up, required",
EnvVars: envVars("BACKUP_PATH"),
Required: true,
},
&cli.PathFlag{
Name: "config",
Aliases: []string{"c"},
Usage: "Path, where the repository json is stored",
EnvVars: envVars("CONFIG_PATH"),
Value: "/config",
},
&cli.StringFlag{
Name: "hostname",
Usage: "Set the hostname for the backup",
EnvVars: []string{"HOSTNAME"},
Value: hostname,
},
},
}
}
func runBackup(c *cli.Context) error {
err := checkEmptyPath(c.Path("path"))
if err != nil {
return err
}
kopia := newKopiaInstance(c)
err = kopia.Backup(c.Path("path"))
if err != nil {
return err
}
return kopia.LastExitCode
}
func checkEmptyPath(path string) error {
files, err := os.ReadDir(path)
if err != nil {
return fmt.Errorf("cannot determine if backup source is empty: %w", err)
}
count := 0
for _, file := range files {
if file.Name() != "lost+found" {
count++
}
}
if count == 0 {
return fmt.Errorf("the source directory appears to be empty")
}
return nil
}