2023-09-14 22:15:37 +00:00
|
|
|
package internal
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"fmt"
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
"github.com/minio/minio-go/v7"
|
|
|
|
"github.com/minio/minio-go/v7/pkg/credentials"
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
2023-09-19 11:48:08 +00:00
|
|
|
MinioClient *minio.Client
|
|
|
|
backupBuckets = []string{}
|
|
|
|
backupRoot string
|
|
|
|
s3Host string
|
|
|
|
s3Secure bool
|
|
|
|
s3Region string
|
|
|
|
s3User string
|
|
|
|
s3Pass string
|
2023-09-14 22:15:37 +00:00
|
|
|
)
|
|
|
|
|
2023-09-19 11:48:08 +00:00
|
|
|
func init() {
|
|
|
|
for _, bucket := range strings.Split(GetEnvWithDefault("BUCKET_NAMES", ""), ",") {
|
|
|
|
backupBuckets = append(backupBuckets, strings.TrimSpace(bucket))
|
|
|
|
}
|
|
|
|
backupRoot = GetEnvWithDefault("BACKUP_ROOT", "/backup")
|
|
|
|
s3Host = GetEnvWithDefault("S3_HOST", "localhost:9000")
|
|
|
|
s3Secure = GetEnvWithDefault("S3_USE_SSL", "") == "true"
|
|
|
|
s3Region = GetEnvWithDefault("S3_REGION", "us-east-1")
|
|
|
|
s3User = GetEnvWithDefault("S3_ACCESS_KEY_ID", "")
|
|
|
|
s3Pass = GetEnvWithDefault("S3_ACCESS_KEY_SECRET", "")
|
|
|
|
}
|
|
|
|
|
2023-09-14 22:15:37 +00:00
|
|
|
func Backup(ctx context.Context) error {
|
2023-09-19 11:48:08 +00:00
|
|
|
logger.Info("Starting backup")
|
2023-09-14 22:15:37 +00:00
|
|
|
var err error
|
|
|
|
var getErrors = []string{}
|
|
|
|
|
2023-09-19 11:48:08 +00:00
|
|
|
MinioClient, err = minio.New(s3Host, &minio.Options{
|
|
|
|
Creds: credentials.NewStaticV4(s3User, s3Pass, ""),
|
|
|
|
Secure: s3Secure,
|
|
|
|
Region: s3Region,
|
2023-09-14 22:15:37 +00:00
|
|
|
})
|
|
|
|
if err != nil {
|
2023-09-19 11:48:08 +00:00
|
|
|
logger.Error("Error connecting to S3", "error", err)
|
2023-09-14 22:15:37 +00:00
|
|
|
return err
|
|
|
|
}
|
2023-09-19 11:48:08 +00:00
|
|
|
logger.Debug("Connected to S3", "host", s3Host)
|
2023-09-14 22:15:37 +00:00
|
|
|
|
2023-09-19 11:48:08 +00:00
|
|
|
for _, bucket := range backupBuckets {
|
|
|
|
logger.Debug("Backing up bucket", "bucket", bucket)
|
2023-09-14 22:15:37 +00:00
|
|
|
for object := range MinioClient.ListObjects(ctx, bucket, minio.ListObjectsOptions{Recursive: true}) {
|
|
|
|
getError := MinioClient.FGetObject(ctx, bucket, object.Key, fmt.Sprintf("%s/%s/%s", backupRoot, bucket, object.Key), minio.GetObjectOptions{})
|
|
|
|
if getError != nil {
|
2023-09-19 11:48:08 +00:00
|
|
|
logger.Error("Error getting object", "bucket", bucket, "error", getError)
|
2023-09-14 22:15:37 +00:00
|
|
|
getErrors = append(getErrors, getError.Error())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(getErrors) > 0 {
|
|
|
|
err = fmt.Errorf("%d errors retrieving objects: %s", len(getErrors), strings.Join(getErrors, ", "))
|
|
|
|
}
|
|
|
|
|
|
|
|
return err
|
|
|
|
}
|