2022-02-13 10:52:19 +01:00
|
|
|
// Copyright 2022 - Offen Authors <hioffen@posteo.de>
|
|
|
|
// SPDX-License-Identifier: MPL-2.0
|
|
|
|
|
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
2023-08-19 19:20:13 +02:00
|
|
|
"bytes"
|
2022-02-13 10:52:19 +01:00
|
|
|
"context"
|
2023-02-02 21:07:25 +01:00
|
|
|
"errors"
|
2022-02-13 10:52:19 +01:00
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"io/fs"
|
2023-08-10 19:41:03 +02:00
|
|
|
"log/slog"
|
2022-02-13 10:52:19 +01:00
|
|
|
"os"
|
|
|
|
"path"
|
|
|
|
"path/filepath"
|
2023-08-27 19:19:11 +02:00
|
|
|
"slices"
|
|
|
|
"strings"
|
2022-02-13 10:52:19 +01:00
|
|
|
"text/template"
|
|
|
|
"time"
|
|
|
|
|
2022-08-18 08:52:09 +02:00
|
|
|
"github.com/offen/docker-volume-backup/internal/storage"
|
2023-01-11 21:40:48 +01:00
|
|
|
"github.com/offen/docker-volume-backup/internal/storage/azure"
|
2023-08-24 19:33:47 +02:00
|
|
|
"github.com/offen/docker-volume-backup/internal/storage/dropbox"
|
2022-08-18 08:52:09 +02:00
|
|
|
"github.com/offen/docker-volume-backup/internal/storage/local"
|
|
|
|
"github.com/offen/docker-volume-backup/internal/storage/s3"
|
|
|
|
"github.com/offen/docker-volume-backup/internal/storage/ssh"
|
|
|
|
"github.com/offen/docker-volume-backup/internal/storage/webdav"
|
|
|
|
|
2023-08-27 18:14:55 +02:00
|
|
|
"github.com/ProtonMail/go-crypto/openpgp"
|
2022-02-13 10:52:19 +01:00
|
|
|
"github.com/containrrr/shoutrrr"
|
|
|
|
"github.com/containrrr/shoutrrr/pkg/router"
|
|
|
|
"github.com/docker/docker/api/types"
|
2023-07-25 19:46:57 +02:00
|
|
|
ctr "github.com/docker/docker/api/types/container"
|
2022-02-13 10:52:19 +01:00
|
|
|
"github.com/docker/docker/api/types/filters"
|
|
|
|
"github.com/docker/docker/api/types/swarm"
|
|
|
|
"github.com/docker/docker/client"
|
|
|
|
"github.com/kelseyhightower/envconfig"
|
|
|
|
"github.com/leekchan/timeutil"
|
|
|
|
"github.com/otiai10/copy"
|
2022-09-01 14:38:04 +02:00
|
|
|
"golang.org/x/sync/errgroup"
|
2022-02-13 10:52:19 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
// script holds all the stateful information required to orchestrate a
|
|
|
|
// single backup run.
|
|
|
|
type script struct {
|
2022-08-18 08:52:09 +02:00
|
|
|
cli *client.Client
|
|
|
|
storages []storage.Backend
|
2023-08-10 19:41:03 +02:00
|
|
|
logger *slog.Logger
|
2022-08-18 08:52:09 +02:00
|
|
|
sender *router.ServiceRouter
|
|
|
|
template *template.Template
|
|
|
|
hooks []hook
|
|
|
|
hookLevel hookLevel
|
2022-02-13 10:52:19 +01:00
|
|
|
|
|
|
|
file string
|
|
|
|
stats *Stats
|
|
|
|
|
2022-03-25 18:26:34 +01:00
|
|
|
encounteredLock bool
|
|
|
|
|
2022-02-13 10:52:19 +01:00
|
|
|
c *Config
|
|
|
|
}
|
|
|
|
|
|
|
|
// newScript creates all resources needed for the script to perform actions against
|
|
|
|
// remote resources like the Docker engine or remote storage locations. All
|
|
|
|
// reading from env vars or other configuration sources is expected to happen
|
|
|
|
// in this method.
|
|
|
|
func newScript() (*script, error) {
|
2022-08-18 10:11:13 +02:00
|
|
|
stdOut, logBuffer := buffer(os.Stdout)
|
2022-02-13 10:52:19 +01:00
|
|
|
s := &script{
|
2023-08-10 19:41:03 +02:00
|
|
|
c: &Config{},
|
|
|
|
logger: slog.New(slog.NewTextHandler(stdOut, nil)),
|
2022-02-13 10:52:19 +01:00
|
|
|
stats: &Stats{
|
|
|
|
StartTime: time.Now(),
|
|
|
|
LogOutput: logBuffer,
|
2022-08-18 08:52:09 +02:00
|
|
|
Storages: map[string]StorageStats{
|
2023-08-24 19:33:47 +02:00
|
|
|
"S3": {},
|
|
|
|
"WebDAV": {},
|
|
|
|
"SSH": {},
|
|
|
|
"Local": {},
|
|
|
|
"Azure": {},
|
|
|
|
"Dropbox": {},
|
2022-08-18 08:52:09 +02:00
|
|
|
},
|
2022-02-13 10:52:19 +01:00
|
|
|
},
|
|
|
|
}
|
|
|
|
|
|
|
|
s.registerHook(hookLevelPlumbing, func(error) error {
|
|
|
|
s.stats.EndTime = time.Now()
|
2022-02-14 17:32:05 +01:00
|
|
|
s.stats.TookTime = s.stats.EndTime.Sub(s.stats.StartTime)
|
2022-02-13 10:52:19 +01:00
|
|
|
return nil
|
|
|
|
})
|
|
|
|
|
|
|
|
if err := envconfig.Process("", s.c); err != nil {
|
|
|
|
return nil, fmt.Errorf("newScript: failed to process configuration values: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
s.file = path.Join("/tmp", s.c.BackupFilename)
|
2023-08-19 19:20:13 +02:00
|
|
|
|
|
|
|
tmplFileName, tErr := template.New("extension").Parse(s.file)
|
|
|
|
if tErr != nil {
|
|
|
|
return nil, fmt.Errorf("newScript: unable to parse backup file extension template: %w", tErr)
|
|
|
|
}
|
|
|
|
|
|
|
|
var bf bytes.Buffer
|
|
|
|
if tErr := tmplFileName.Execute(&bf, map[string]string{
|
|
|
|
"Extension": fmt.Sprintf("tar.%s", s.c.BackupCompression),
|
|
|
|
}); tErr != nil {
|
|
|
|
return nil, fmt.Errorf("newScript: error executing backup file extension template: %w", tErr)
|
|
|
|
}
|
|
|
|
s.file = bf.String()
|
|
|
|
|
2022-02-13 10:52:19 +01:00
|
|
|
if s.c.BackupFilenameExpand {
|
|
|
|
s.file = os.ExpandEnv(s.file)
|
|
|
|
s.c.BackupLatestSymlink = os.ExpandEnv(s.c.BackupLatestSymlink)
|
|
|
|
s.c.BackupPruningPrefix = os.ExpandEnv(s.c.BackupPruningPrefix)
|
|
|
|
}
|
|
|
|
s.file = timeutil.Strftime(&s.stats.StartTime, s.file)
|
|
|
|
|
|
|
|
_, err := os.Stat("/var/run/docker.sock")
|
2022-02-18 09:08:21 +01:00
|
|
|
_, dockerHostSet := os.LookupEnv("DOCKER_HOST")
|
|
|
|
if !os.IsNotExist(err) || dockerHostSet {
|
2022-02-13 10:52:19 +01:00
|
|
|
cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("newScript: failed to create docker client")
|
|
|
|
}
|
|
|
|
s.cli = cli
|
|
|
|
}
|
|
|
|
|
2023-03-16 19:48:12 +01:00
|
|
|
logFunc := func(logType storage.LogLevel, context string, msg string, params ...any) {
|
2022-08-18 08:52:09 +02:00
|
|
|
switch logType {
|
2022-08-18 10:11:13 +02:00
|
|
|
case storage.LogLevelWarning:
|
2023-08-25 12:44:43 +02:00
|
|
|
s.logger.Warn(fmt.Sprintf(msg, params...), "storage", context)
|
2022-08-18 10:11:13 +02:00
|
|
|
case storage.LogLevelError:
|
2023-08-25 12:44:43 +02:00
|
|
|
s.logger.Error(fmt.Sprintf(msg, params...), "storage", context)
|
2022-08-18 08:52:09 +02:00
|
|
|
default:
|
2023-08-25 12:44:43 +02:00
|
|
|
s.logger.Info(fmt.Sprintf(msg, params...), "storage", context)
|
2022-02-13 10:52:19 +01:00
|
|
|
}
|
2022-08-18 08:52:09 +02:00
|
|
|
}
|
2022-02-13 10:52:19 +01:00
|
|
|
|
2022-08-18 08:52:09 +02:00
|
|
|
if s.c.AwsS3BucketName != "" {
|
2022-10-12 19:14:57 +02:00
|
|
|
accessKeyID, err := s.c.resolveSecret(s.c.AwsAccessKeyID, s.c.AwsAccessKeyIDFile)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("newScript: error resolving AwsAccessKeyID: %w", err)
|
|
|
|
}
|
|
|
|
secretAccessKey, err := s.c.resolveSecret(s.c.AwsSecretAccessKey, s.c.AwsSecretAccessKeyFile)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("newScript: error resolving AwsSecretAccessKey: %w", err)
|
|
|
|
}
|
2022-08-18 10:11:13 +02:00
|
|
|
s3Config := s3.Config{
|
|
|
|
Endpoint: s.c.AwsEndpoint,
|
2022-10-12 19:14:57 +02:00
|
|
|
AccessKeyID: accessKeyID,
|
|
|
|
SecretAccessKey: secretAccessKey,
|
2022-08-18 10:11:13 +02:00
|
|
|
IamRoleEndpoint: s.c.AwsIamRoleEndpoint,
|
|
|
|
EndpointProto: s.c.AwsEndpointProto,
|
|
|
|
EndpointInsecure: s.c.AwsEndpointInsecure,
|
|
|
|
RemotePath: s.c.AwsS3Path,
|
|
|
|
BucketName: s.c.AwsS3BucketName,
|
|
|
|
StorageClass: s.c.AwsStorageClass,
|
2022-12-22 14:37:51 +01:00
|
|
|
CACert: s.c.AwsEndpointCACert.Cert,
|
2023-06-02 16:30:02 +02:00
|
|
|
PartSize: s.c.AwsPartSize,
|
2022-08-18 10:11:13 +02:00
|
|
|
}
|
|
|
|
if s3Backend, err := s3.NewStorageBackend(s3Config, logFunc); err != nil {
|
2023-08-24 19:33:47 +02:00
|
|
|
return nil, fmt.Errorf("newScript: error creating s3 storage backend: %w", err)
|
2022-08-18 08:52:09 +02:00
|
|
|
} else {
|
|
|
|
s.storages = append(s.storages, s3Backend)
|
2022-02-13 10:52:19 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if s.c.WebdavUrl != "" {
|
2022-08-18 10:11:13 +02:00
|
|
|
webDavConfig := webdav.Config{
|
|
|
|
URL: s.c.WebdavUrl,
|
|
|
|
URLInsecure: s.c.WebdavUrlInsecure,
|
|
|
|
Username: s.c.WebdavUsername,
|
|
|
|
Password: s.c.WebdavPassword,
|
|
|
|
RemotePath: s.c.WebdavPath,
|
|
|
|
}
|
|
|
|
if webdavBackend, err := webdav.NewStorageBackend(webDavConfig, logFunc); err != nil {
|
2023-08-24 19:33:47 +02:00
|
|
|
return nil, fmt.Errorf("newScript: error creating webdav storage backend: %w", err)
|
2022-02-13 10:52:19 +01:00
|
|
|
} else {
|
2022-08-18 08:52:09 +02:00
|
|
|
s.storages = append(s.storages, webdavBackend)
|
2022-02-13 10:52:19 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-06-17 11:06:15 +02:00
|
|
|
if s.c.SSHHostName != "" {
|
2022-08-18 10:11:13 +02:00
|
|
|
sshConfig := ssh.Config{
|
|
|
|
HostName: s.c.SSHHostName,
|
|
|
|
Port: s.c.SSHPort,
|
|
|
|
User: s.c.SSHUser,
|
|
|
|
Password: s.c.SSHPassword,
|
|
|
|
IdentityFile: s.c.SSHIdentityFile,
|
|
|
|
IdentityPassphrase: s.c.SSHIdentityPassphrase,
|
|
|
|
RemotePath: s.c.SSHRemotePath,
|
|
|
|
}
|
|
|
|
if sshBackend, err := ssh.NewStorageBackend(sshConfig, logFunc); err != nil {
|
2023-08-24 19:33:47 +02:00
|
|
|
return nil, fmt.Errorf("newScript: error creating ssh storage backend: %w", err)
|
2022-08-18 08:52:09 +02:00
|
|
|
} else {
|
|
|
|
s.storages = append(s.storages, sshBackend)
|
2022-06-17 11:06:15 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-08-18 10:11:13 +02:00
|
|
|
if _, err := os.Stat(s.c.BackupArchive); !os.IsNotExist(err) {
|
|
|
|
localConfig := local.Config{
|
|
|
|
ArchivePath: s.c.BackupArchive,
|
|
|
|
LatestSymlink: s.c.BackupLatestSymlink,
|
|
|
|
}
|
|
|
|
localBackend := local.NewStorageBackend(localConfig, logFunc)
|
|
|
|
s.storages = append(s.storages, localBackend)
|
|
|
|
}
|
2022-08-18 08:52:09 +02:00
|
|
|
|
2023-01-11 21:40:48 +01:00
|
|
|
if s.c.AzureStorageAccountName != "" {
|
|
|
|
azureConfig := azure.Config{
|
|
|
|
ContainerName: s.c.AzureStorageContainerName,
|
|
|
|
AccountName: s.c.AzureStorageAccountName,
|
|
|
|
PrimaryAccountKey: s.c.AzureStoragePrimaryAccountKey,
|
|
|
|
Endpoint: s.c.AzureStorageEndpoint,
|
|
|
|
RemotePath: s.c.AzureStoragePath,
|
|
|
|
}
|
|
|
|
azureBackend, err := azure.NewStorageBackend(azureConfig, logFunc)
|
|
|
|
if err != nil {
|
2023-08-24 19:33:47 +02:00
|
|
|
return nil, fmt.Errorf("newScript: error creating azure storage backend: %w", err)
|
2023-01-11 21:40:48 +01:00
|
|
|
}
|
|
|
|
s.storages = append(s.storages, azureBackend)
|
|
|
|
}
|
|
|
|
|
2023-08-24 19:33:47 +02:00
|
|
|
if s.c.DropboxRefreshToken != "" && s.c.DropboxAppKey != "" && s.c.DropboxAppSecret != "" {
|
|
|
|
dropboxConfig := dropbox.Config{
|
|
|
|
Endpoint: s.c.DropboxEndpoint,
|
|
|
|
OAuth2Endpoint: s.c.DropboxOAuth2Endpoint,
|
|
|
|
RefreshToken: s.c.DropboxRefreshToken,
|
|
|
|
AppKey: s.c.DropboxAppKey,
|
|
|
|
AppSecret: s.c.DropboxAppSecret,
|
|
|
|
RemotePath: s.c.DropboxRemotePath,
|
|
|
|
ConcurrencyLevel: s.c.DropboxConcurrencyLevel.Int(),
|
|
|
|
}
|
|
|
|
dropboxBackend, err := dropbox.NewStorageBackend(dropboxConfig, logFunc)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("newScript: error creating dropbox storage backend: %w", err)
|
|
|
|
}
|
|
|
|
s.storages = append(s.storages, dropboxBackend)
|
|
|
|
}
|
|
|
|
|
2022-02-13 10:52:19 +01:00
|
|
|
if s.c.EmailNotificationRecipient != "" {
|
|
|
|
emailURL := fmt.Sprintf(
|
|
|
|
"smtp://%s:%s@%s:%d/?from=%s&to=%s",
|
|
|
|
s.c.EmailSMTPUsername,
|
|
|
|
s.c.EmailSMTPPassword,
|
|
|
|
s.c.EmailSMTPHost,
|
|
|
|
s.c.EmailSMTPPort,
|
|
|
|
s.c.EmailNotificationSender,
|
|
|
|
s.c.EmailNotificationRecipient,
|
|
|
|
)
|
|
|
|
s.c.NotificationURLs = append(s.c.NotificationURLs, emailURL)
|
|
|
|
s.logger.Warn(
|
|
|
|
"Using EMAIL_* keys for providing notification configuration has been deprecated and will be removed in the next major version.",
|
|
|
|
)
|
|
|
|
s.logger.Warn(
|
|
|
|
"Please use NOTIFICATION_URLS instead. Refer to the README for an upgrade guide.",
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
hookLevel, ok := hookLevels[s.c.NotificationLevel]
|
|
|
|
if !ok {
|
|
|
|
return nil, fmt.Errorf("newScript: unknown NOTIFICATION_LEVEL %s", s.c.NotificationLevel)
|
|
|
|
}
|
|
|
|
s.hookLevel = hookLevel
|
|
|
|
|
|
|
|
if len(s.c.NotificationURLs) > 0 {
|
|
|
|
sender, senderErr := shoutrrr.CreateSender(s.c.NotificationURLs...)
|
|
|
|
if senderErr != nil {
|
|
|
|
return nil, fmt.Errorf("newScript: error creating sender: %w", senderErr)
|
|
|
|
}
|
|
|
|
s.sender = sender
|
|
|
|
|
|
|
|
tmpl := template.New("")
|
|
|
|
tmpl.Funcs(templateHelpers)
|
|
|
|
tmpl, err = tmpl.Parse(defaultNotifications)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("newScript: unable to parse default notifications templates: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
if fi, err := os.Stat("/etc/dockervolumebackup/notifications.d"); err == nil && fi.IsDir() {
|
|
|
|
tmpl, err = tmpl.ParseGlob("/etc/dockervolumebackup/notifications.d/*.*")
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("newScript: unable to parse user defined notifications templates: %w", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
s.template = tmpl
|
|
|
|
|
|
|
|
// To prevent duplicate notifications, ensure the regsistered callbacks
|
|
|
|
// run mutually exclusive.
|
|
|
|
s.registerHook(hookLevelError, func(err error) error {
|
|
|
|
if err == nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
return s.notifyFailure(err)
|
|
|
|
})
|
|
|
|
s.registerHook(hookLevelInfo, func(err error) error {
|
|
|
|
if err != nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
return s.notifySuccess()
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
return s, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// stopContainers stops all Docker containers that are marked as to being
|
|
|
|
// stopped during the backup and returns a function that can be called to
|
|
|
|
// restart everything that has been stopped.
|
|
|
|
func (s *script) stopContainers() (func() error, error) {
|
|
|
|
if s.cli == nil {
|
2022-08-18 10:11:13 +02:00
|
|
|
return noop, nil
|
2022-02-13 10:52:19 +01:00
|
|
|
}
|
|
|
|
|
2023-07-25 19:46:57 +02:00
|
|
|
allContainers, err := s.cli.ContainerList(context.Background(), types.ContainerListOptions{})
|
2022-02-13 10:52:19 +01:00
|
|
|
if err != nil {
|
2022-09-15 10:49:45 +02:00
|
|
|
return noop, fmt.Errorf("stopContainers: error querying for containers: %w", err)
|
2022-02-13 10:52:19 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
containerLabel := fmt.Sprintf(
|
|
|
|
"docker-volume-backup.stop-during-backup=%s",
|
|
|
|
s.c.BackupStopContainerLabel,
|
|
|
|
)
|
|
|
|
containersToStop, err := s.cli.ContainerList(context.Background(), types.ContainerListOptions{
|
|
|
|
Filters: filters.NewArgs(filters.KeyValuePair{
|
|
|
|
Key: "label",
|
|
|
|
Value: containerLabel,
|
|
|
|
}),
|
|
|
|
})
|
|
|
|
|
|
|
|
if err != nil {
|
2022-09-15 10:49:45 +02:00
|
|
|
return noop, fmt.Errorf("stopContainers: error querying for containers to stop: %w", err)
|
2022-02-13 10:52:19 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
if len(containersToStop) == 0 {
|
2022-08-18 10:11:13 +02:00
|
|
|
return noop, nil
|
2022-02-13 10:52:19 +01:00
|
|
|
}
|
|
|
|
|
2023-08-10 19:41:03 +02:00
|
|
|
s.logger.Info(
|
|
|
|
fmt.Sprintf(
|
|
|
|
"Stopping %d container(s) labeled `%s` out of %d running container(s).",
|
|
|
|
len(containersToStop),
|
|
|
|
containerLabel,
|
|
|
|
len(allContainers),
|
|
|
|
),
|
2022-02-13 10:52:19 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
var stoppedContainers []types.Container
|
|
|
|
var stopErrors []error
|
|
|
|
for _, container := range containersToStop {
|
2023-07-25 19:46:57 +02:00
|
|
|
if err := s.cli.ContainerStop(context.Background(), container.ID, ctr.StopOptions{}); err != nil {
|
2022-02-13 10:52:19 +01:00
|
|
|
stopErrors = append(stopErrors, err)
|
|
|
|
} else {
|
|
|
|
stoppedContainers = append(stoppedContainers, container)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
var stopError error
|
|
|
|
if len(stopErrors) != 0 {
|
|
|
|
stopError = fmt.Errorf(
|
2022-09-15 10:49:45 +02:00
|
|
|
"stopContainers: %d error(s) stopping containers: %w",
|
2022-02-13 10:52:19 +01:00
|
|
|
len(stopErrors),
|
2023-02-02 21:07:25 +01:00
|
|
|
errors.Join(stopErrors...),
|
2022-02-13 10:52:19 +01:00
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
s.stats.Containers = ContainersStats{
|
|
|
|
All: uint(len(allContainers)),
|
|
|
|
ToStop: uint(len(containersToStop)),
|
|
|
|
Stopped: uint(len(stoppedContainers)),
|
|
|
|
}
|
|
|
|
|
|
|
|
return func() error {
|
|
|
|
servicesRequiringUpdate := map[string]struct{}{}
|
|
|
|
|
|
|
|
var restartErrors []error
|
|
|
|
for _, container := range stoppedContainers {
|
|
|
|
if swarmServiceName, ok := container.Labels["com.docker.swarm.service.name"]; ok {
|
|
|
|
servicesRequiringUpdate[swarmServiceName] = struct{}{}
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
if err := s.cli.ContainerStart(context.Background(), container.ID, types.ContainerStartOptions{}); err != nil {
|
|
|
|
restartErrors = append(restartErrors, err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(servicesRequiringUpdate) != 0 {
|
|
|
|
services, _ := s.cli.ServiceList(context.Background(), types.ServiceListOptions{})
|
|
|
|
for serviceName := range servicesRequiringUpdate {
|
|
|
|
var serviceMatch swarm.Service
|
|
|
|
for _, service := range services {
|
|
|
|
if service.Spec.Name == serviceName {
|
|
|
|
serviceMatch = service
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if serviceMatch.ID == "" {
|
2022-09-15 10:49:45 +02:00
|
|
|
return fmt.Errorf("stopContainers: couldn't find service with name %s", serviceName)
|
2022-02-13 10:52:19 +01:00
|
|
|
}
|
2023-04-26 08:45:12 +02:00
|
|
|
serviceMatch.Spec.TaskTemplate.ForceUpdate += 1
|
2022-02-13 10:52:19 +01:00
|
|
|
if _, err := s.cli.ServiceUpdate(
|
|
|
|
context.Background(), serviceMatch.ID,
|
|
|
|
serviceMatch.Version, serviceMatch.Spec, types.ServiceUpdateOptions{},
|
|
|
|
); err != nil {
|
|
|
|
restartErrors = append(restartErrors, err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(restartErrors) != 0 {
|
|
|
|
return fmt.Errorf(
|
2022-09-15 10:49:45 +02:00
|
|
|
"stopContainers: %d error(s) restarting containers and services: %w",
|
2022-02-13 10:52:19 +01:00
|
|
|
len(restartErrors),
|
2023-02-02 21:07:25 +01:00
|
|
|
errors.Join(restartErrors...),
|
2022-02-13 10:52:19 +01:00
|
|
|
)
|
|
|
|
}
|
2023-08-10 19:41:03 +02:00
|
|
|
s.logger.Info(
|
|
|
|
fmt.Sprintf(
|
|
|
|
"Restarted %d container(s) and the matching service(s).",
|
|
|
|
len(stoppedContainers),
|
|
|
|
),
|
2022-02-13 10:52:19 +01:00
|
|
|
)
|
|
|
|
return nil
|
|
|
|
}, stopError
|
|
|
|
}
|
|
|
|
|
2022-07-10 10:36:56 +02:00
|
|
|
// createArchive creates a tar archive of the configured backup location and
|
2022-02-13 10:52:19 +01:00
|
|
|
// saves it to disk.
|
2022-07-10 10:36:56 +02:00
|
|
|
func (s *script) createArchive() error {
|
2022-02-13 10:52:19 +01:00
|
|
|
backupSources := s.c.BackupSources
|
|
|
|
|
|
|
|
if s.c.BackupFromSnapshot {
|
2022-03-25 18:28:58 +01:00
|
|
|
s.logger.Warn(
|
|
|
|
"Using BACKUP_FROM_SNAPSHOT has been deprecated and will be removed in the next major version.",
|
|
|
|
)
|
|
|
|
s.logger.Warn(
|
2022-07-10 10:36:56 +02:00
|
|
|
"Please use `archive-pre` and `archive-post` commands to prepare your backup sources. Refer to the README for an upgrade guide.",
|
2022-03-25 18:28:58 +01:00
|
|
|
)
|
2022-02-13 10:52:19 +01:00
|
|
|
backupSources = filepath.Join("/tmp", s.c.BackupSources)
|
|
|
|
// copy before compressing guard against a situation where backup folder's content are still growing.
|
|
|
|
s.registerHook(hookLevelPlumbing, func(error) error {
|
2022-08-18 10:11:13 +02:00
|
|
|
if err := remove(backupSources); err != nil {
|
2022-09-15 10:49:45 +02:00
|
|
|
return fmt.Errorf("createArchive: error removing snapshot: %w", err)
|
2022-02-13 10:52:19 +01:00
|
|
|
}
|
2023-08-10 19:41:03 +02:00
|
|
|
s.logger.Info(
|
|
|
|
fmt.Sprintf("Removed snapshot `%s`.", backupSources),
|
|
|
|
)
|
2022-02-13 10:52:19 +01:00
|
|
|
return nil
|
|
|
|
})
|
|
|
|
if err := copy.Copy(s.c.BackupSources, backupSources, copy.Options{
|
|
|
|
PreserveTimes: true,
|
|
|
|
PreserveOwner: true,
|
|
|
|
}); err != nil {
|
2022-08-18 10:11:13 +02:00
|
|
|
return fmt.Errorf("createArchive: error creating snapshot: %w", err)
|
2022-02-13 10:52:19 +01:00
|
|
|
}
|
2023-08-10 19:41:03 +02:00
|
|
|
s.logger.Info(
|
|
|
|
fmt.Sprintf("Created snapshot of `%s` at `%s`.", s.c.BackupSources, backupSources),
|
|
|
|
)
|
2022-02-13 10:52:19 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
tarFile := s.file
|
|
|
|
s.registerHook(hookLevelPlumbing, func(error) error {
|
2022-08-18 10:11:13 +02:00
|
|
|
if err := remove(tarFile); err != nil {
|
|
|
|
return fmt.Errorf("createArchive: error removing tar file: %w", err)
|
2022-02-13 10:52:19 +01:00
|
|
|
}
|
2023-08-10 19:41:03 +02:00
|
|
|
s.logger.Info(
|
|
|
|
fmt.Sprintf("Removed tar file `%s`.", tarFile),
|
|
|
|
)
|
2022-02-13 10:52:19 +01:00
|
|
|
return nil
|
|
|
|
})
|
2022-05-08 11:20:38 +02:00
|
|
|
|
|
|
|
backupPath, err := filepath.Abs(stripTrailingSlashes(backupSources))
|
|
|
|
if err != nil {
|
2022-08-18 10:11:13 +02:00
|
|
|
return fmt.Errorf("createArchive: error getting absolute path: %w", err)
|
2022-05-08 11:20:38 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
var filesEligibleForBackup []string
|
|
|
|
if err := filepath.WalkDir(backupPath, func(path string, di fs.DirEntry, err error) error {
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
if s.c.BackupExcludeRegexp.Re != nil && s.c.BackupExcludeRegexp.Re.MatchString(path) {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
filesEligibleForBackup = append(filesEligibleForBackup, path)
|
|
|
|
return nil
|
|
|
|
}); err != nil {
|
2022-08-18 10:11:13 +02:00
|
|
|
return fmt.Errorf("createArchive: error walking filesystem tree: %w", err)
|
2022-05-08 11:20:38 +02:00
|
|
|
}
|
|
|
|
|
2023-08-19 19:20:13 +02:00
|
|
|
if err := createArchive(filesEligibleForBackup, backupSources, tarFile, s.c.BackupCompression.String()); err != nil {
|
2022-08-18 10:11:13 +02:00
|
|
|
return fmt.Errorf("createArchive: error compressing backup folder: %w", err)
|
2022-02-13 10:52:19 +01:00
|
|
|
}
|
|
|
|
|
2023-08-10 19:41:03 +02:00
|
|
|
s.logger.Info(
|
|
|
|
fmt.Sprintf("Created backup of `%s` at `%s`.", backupSources, tarFile),
|
|
|
|
)
|
2022-02-13 10:52:19 +01:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-07-10 10:36:56 +02:00
|
|
|
// encryptArchive encrypts the backup file using PGP and the configured passphrase.
|
2022-02-13 10:52:19 +01:00
|
|
|
// In case no passphrase is given it returns early, leaving the backup file
|
|
|
|
// untouched.
|
2022-07-10 10:36:56 +02:00
|
|
|
func (s *script) encryptArchive() error {
|
2022-02-13 10:52:19 +01:00
|
|
|
if s.c.GpgPassphrase == "" {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
gpgFile := fmt.Sprintf("%s.gpg", s.file)
|
|
|
|
s.registerHook(hookLevelPlumbing, func(error) error {
|
2022-08-18 10:11:13 +02:00
|
|
|
if err := remove(gpgFile); err != nil {
|
|
|
|
return fmt.Errorf("encryptArchive: error removing gpg file: %w", err)
|
2022-02-13 10:52:19 +01:00
|
|
|
}
|
2023-08-10 19:41:03 +02:00
|
|
|
s.logger.Info(
|
|
|
|
fmt.Sprintf("Removed GPG file `%s`.", gpgFile),
|
|
|
|
)
|
2022-02-13 10:52:19 +01:00
|
|
|
return nil
|
|
|
|
})
|
|
|
|
|
|
|
|
outFile, err := os.Create(gpgFile)
|
|
|
|
if err != nil {
|
2022-08-18 10:11:13 +02:00
|
|
|
return fmt.Errorf("encryptArchive: error opening out file: %w", err)
|
2022-02-13 10:52:19 +01:00
|
|
|
}
|
2022-08-18 08:52:09 +02:00
|
|
|
defer outFile.Close()
|
2022-02-13 10:52:19 +01:00
|
|
|
|
|
|
|
_, name := path.Split(s.file)
|
|
|
|
dst, err := openpgp.SymmetricallyEncrypt(outFile, []byte(s.c.GpgPassphrase), &openpgp.FileHints{
|
|
|
|
IsBinary: true,
|
|
|
|
FileName: name,
|
|
|
|
}, nil)
|
|
|
|
if err != nil {
|
2022-08-18 10:11:13 +02:00
|
|
|
return fmt.Errorf("encryptArchive: error encrypting backup file: %w", err)
|
2022-02-13 10:52:19 +01:00
|
|
|
}
|
2022-08-18 08:52:09 +02:00
|
|
|
defer dst.Close()
|
2022-02-13 10:52:19 +01:00
|
|
|
|
|
|
|
src, err := os.Open(s.file)
|
|
|
|
if err != nil {
|
2022-08-18 10:11:13 +02:00
|
|
|
return fmt.Errorf("encryptArchive: error opening backup file `%s`: %w", s.file, err)
|
2022-02-13 10:52:19 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
if _, err := io.Copy(dst, src); err != nil {
|
2022-08-18 10:11:13 +02:00
|
|
|
return fmt.Errorf("encryptArchive: error writing ciphertext to file: %w", err)
|
2022-02-13 10:52:19 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
s.file = gpgFile
|
2023-08-10 19:41:03 +02:00
|
|
|
s.logger.Info(
|
|
|
|
fmt.Sprintf("Encrypted backup using given passphrase, saving as `%s`.", s.file),
|
|
|
|
)
|
2022-02-13 10:52:19 +01:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-07-10 10:36:56 +02:00
|
|
|
// copyArchive makes sure the backup file is copied to both local and remote locations
|
2022-02-13 10:52:19 +01:00
|
|
|
// as per the given configuration.
|
2022-07-10 10:36:56 +02:00
|
|
|
func (s *script) copyArchive() error {
|
2022-02-13 10:52:19 +01:00
|
|
|
_, name := path.Split(s.file)
|
|
|
|
if stat, err := os.Stat(s.file); err != nil {
|
2022-08-18 10:11:13 +02:00
|
|
|
return fmt.Errorf("copyArchive: unable to stat backup file: %w", err)
|
2022-02-13 10:52:19 +01:00
|
|
|
} else {
|
|
|
|
size := stat.Size()
|
|
|
|
s.stats.BackupFile = BackupFileStats{
|
|
|
|
Size: uint64(size),
|
|
|
|
Name: name,
|
|
|
|
FullPath: s.file,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-09-01 14:38:04 +02:00
|
|
|
eg := errgroup.Group{}
|
2022-08-18 08:52:09 +02:00
|
|
|
for _, backend := range s.storages {
|
2022-09-01 14:38:04 +02:00
|
|
|
b := backend
|
|
|
|
eg.Go(func() error {
|
|
|
|
return b.Copy(s.file)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
if err := eg.Wait(); err != nil {
|
|
|
|
return fmt.Errorf("copyArchive: error copying archive: %w", err)
|
2022-06-17 11:06:15 +02:00
|
|
|
}
|
|
|
|
|
2022-02-13 10:52:19 +01:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// pruneBackups rotates away backups from local and remote storages using
|
|
|
|
// the given configuration. In case the given configuration would delete all
|
|
|
|
// backups, it does nothing instead and logs a warning.
|
|
|
|
func (s *script) pruneBackups() error {
|
|
|
|
if s.c.BackupRetentionDays < 0 {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
deadline := time.Now().AddDate(0, 0, -int(s.c.BackupRetentionDays)).Add(s.c.BackupPruningLeeway)
|
|
|
|
|
2022-09-01 14:38:04 +02:00
|
|
|
eg := errgroup.Group{}
|
2022-08-18 08:52:09 +02:00
|
|
|
for _, backend := range s.storages {
|
2022-09-01 14:38:04 +02:00
|
|
|
b := backend
|
|
|
|
eg.Go(func() error {
|
2023-08-27 19:19:11 +02:00
|
|
|
if skipPrune(b.Name(), s.c.BackupSkipBackendsFromPrune) {
|
|
|
|
s.logger.Info(
|
|
|
|
fmt.Sprintf("Skipping pruning for backend `%s`.", b.Name()),
|
|
|
|
)
|
|
|
|
return nil
|
|
|
|
}
|
2022-09-01 14:38:04 +02:00
|
|
|
stats, err := b.Prune(deadline, s.c.BackupPruningPrefix)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
s.stats.Lock()
|
|
|
|
s.stats.Storages[b.Name()] = StorageStats{
|
2022-08-18 08:52:09 +02:00
|
|
|
Total: stats.Total,
|
|
|
|
Pruned: stats.Pruned,
|
2022-06-17 11:06:15 +02:00
|
|
|
}
|
2022-09-01 14:38:04 +02:00
|
|
|
s.stats.Unlock()
|
|
|
|
return nil
|
|
|
|
})
|
|
|
|
}
|
2022-06-17 11:06:15 +02:00
|
|
|
|
2022-09-01 14:38:04 +02:00
|
|
|
if err := eg.Wait(); err != nil {
|
|
|
|
return fmt.Errorf("pruneBackups: error pruning backups: %w", err)
|
2022-06-17 11:06:15 +02:00
|
|
|
}
|
|
|
|
|
2022-02-13 10:52:19 +01:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// must exits the script run prematurely in case the given error
|
|
|
|
// is non-nil.
|
|
|
|
func (s *script) must(err error) {
|
|
|
|
if err != nil {
|
2023-08-10 19:41:03 +02:00
|
|
|
s.logger.Error(
|
|
|
|
fmt.Sprintf("Fatal error running backup: %s", err),
|
|
|
|
)
|
2022-02-13 10:52:19 +01:00
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
}
|
2023-08-27 19:19:11 +02:00
|
|
|
|
|
|
|
// skipPrune returns true if the given backend name is contained in the
|
|
|
|
// list of skipped backends.
|
|
|
|
func skipPrune(name string, skippedBackends []string) bool {
|
|
|
|
return slices.ContainsFunc(
|
|
|
|
skippedBackends,
|
|
|
|
func(b string) bool {
|
|
|
|
return strings.EqualFold(b, name) // ignore case on both sides
|
|
|
|
},
|
|
|
|
)
|
|
|
|
}
|