Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

feat: save backup files to s3 (#2286)

Yilong Li3d71af6ed5aa
diff --git a/README.md b/README.md
index 11b24e6ad2..0995e3eed9 100644
--- a/README.md
+++ b/README.md
@@ -172,10 +172,16 @@ working on the code:
Change the open file limit if you encounter "error: too many open files".
- ```
+ ```bash
ulimit -n 10240
```
+ If you need additional runtime parameters such as --backup-bucket, please add them like this:
+
+ ```bash
+ air -c scripts/.air.toml -- --backup-region us-east-1 --backup-bucket s3:\\/\\/example-bucket --backup-credential ~/.aws/credentials
+ ```
+
1. Start frontend (with live reload).
```bash
diff --git a/bin/server/cmd/profile.go b/bin/server/cmd/profile.go
index 0760349186..96a03848be 100644
--- a/bin/server/cmd/profile.go
+++ b/bin/server/cmd/profile.go
@@ -18,6 +18,10 @@ func getBaseProfile() server.Profile {
}
demoDataDir = fmt.Sprintf("demo/%s", demoName)
}
+ backupStorageBackend := api.BackupStorageBackendLocal
+ if flags.backupBucket != "" {
+ backupStorageBackend = api.BackupStorageBackendS3
+ }
// Using flags.port + 1 as our datastore port
datastorePort := flags.port + 1
@@ -34,8 +38,11 @@ func getBaseProfile() server.Profile {
Version: version,
GitCommit: gitcommit,
PgURL: flags.pgURL,
- BackupStorageBackend: api.BackupStorageBackendLocal,
DisableMetric: flags.disableMetric,
+ BackupStorageBackend: backupStorageBackend,
+ BackupRegion: flags.backupRegion,
+ BackupBucket: flags.backupBucket,
+ BackupCredentialFile: flags.backupCredential,
}
}
diff --git a/bin/server/cmd/root.go b/bin/server/cmd/root.go
index 50ee088f50..a1b4dd1f67 100644
--- a/bin/server/cmd/root.go
+++ b/bin/server/cmd/root.go
@@ -98,7 +98,13 @@ var (
pgURL string
// disableMetric is the flag to disable the metric collector.
disableMetric bool
+
+ // Cloud backup configs.
+ backupRegion string
+ backupBucket string
+ backupCredential string
}
+
rootCmd = &cobra.Command{
Use: "bytebase",
Short: "Bytebase is a database schema change and version control tool",
@@ -134,6 +140,12 @@ func init() {
rootCmd.PersistentFlags().BoolVar(&flags.debug, "debug", false, "whether to enable debug level logging")
rootCmd.PersistentFlags().StringVar(&flags.pgURL, "pg", "", "optional external PostgreSQL instance connection url(must provide dbname); for example postgresql://user:secret@masterhost:5432/dbname?sslrootcert=cert")
rootCmd.PersistentFlags().BoolVar(&flags.disableMetric, "disable-metric", false, "disable the metric collector")
+
+ // Cloud backup related flags.
+ // TODO(dragonly): Add GCS usages when it's supported.
+ rootCmd.PersistentFlags().StringVar(&flags.backupBucket, "backup-bucket", "", "bucket where Bytebase stores backup data, e.g., s3://example-bucket. When provided, Bytebase will store data to the S3 bucket.")
+ rootCmd.PersistentFlags().StringVar(&flags.backupRegion, "backup-region", "", "region of the backup bucket, e.g., us-west-2 for AWS S3.")
+ rootCmd.PersistentFlags().StringVar(&flags.backupCredential, "backup-credential", "", "credentials file to use for the backup bucket. It should be the same format as the AWS/GCP credential files.")
}
// -----------------------------------Command Line Config END--------------------------------------
@@ -160,6 +172,23 @@ func checkDataDir() error {
return nil
}
+func checkCloudBackupFlags() error {
+ if flags.backupBucket == "" {
+ return nil
+ }
+ if !strings.HasPrefix(flags.backupBucket, "s3://") {
+ return errors.Errorf("only support bucket URI starting with s3://")
+ }
+ flags.backupBucket = strings.TrimPrefix(flags.backupBucket, "s3://")
+ if flags.backupCredential == "" {
+ return errors.Errorf("must specify --backup-credential when --backup-bucket is present")
+ }
+ if flags.backupRegion == "" {
+ return errors.Errorf("must specify --backup-region for AWS S3 backup")
+ }
+ return nil
+}
+
func start() {
if flags.debug {
log.SetLevel(zap.DebugLevel)
@@ -176,7 +205,11 @@ func start() {
return
}
- activeProfile := activeProfile(flags.dataDir)
+ if err := checkCloudBackupFlags(); err != nil {
+ log.Error("invalid flags for cloud backup", zap.Error(err))
+ return
+ }
+ profile := activeProfile(flags.dataDir)
var s *server.Server
// Setup signal handlers.
@@ -195,12 +228,12 @@ func start() {
cancel()
}()
- s, err := server.NewServer(ctx, activeProfile)
+ s, err := server.NewServer(ctx, profile)
if err != nil {
log.Error("Cannot new server", zap.Error(err))
return
}
- fmt.Printf(greetingBanner, fmt.Sprintf("Version %s has started at %s:%d", activeProfile.Version, activeProfile.BackendHost, activeProfile.BackendPort))
+ fmt.Printf(greetingBanner, fmt.Sprintf("Version %s has started at %s:%d", profile.Version, profile.BackendHost, profile.BackendPort))
// Execute program.
if err := s.Run(ctx); err != nil {
if err != http.ErrServerClosed {
diff --git a/go.mod b/go.mod
index a54f7bf6a8..ad14269936 100644
--- a/go.mod
+++ b/go.mod
@@ -5,6 +5,7 @@ go 1.17
require (
github.com/ClickHouse/clickhouse-go/v2 v2.2.0
github.com/VictoriaMetrics/fastcache v1.6.0
+ github.com/aws/aws-sdk-go-v2 v1.16.8
github.com/aws/aws-sdk-go-v2/config v1.15.15
github.com/aws/aws-sdk-go-v2/credentials v1.12.10
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.11.21
@@ -48,7 +49,6 @@ require (
github.com/Knetic/govaluate v3.0.1-0.20171022003610-9aa49832a739+incompatible // indirect
github.com/KyleBanks/depth v1.2.1 // indirect
github.com/apache/arrow/go/arrow v0.0.0-20211112161151-bc219186db40 // indirect
- github.com/aws/aws-sdk-go-v2 v1.16.8 // indirect
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.4.3 // indirect
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.12.9 // indirect
github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.15 // indirect
diff --git a/plugin/storage/s3/s3.go b/plugin/storage/s3/s3.go
index 8cedbe6c4d..1b523ebbe9 100644
--- a/plugin/storage/s3/s3.go
+++ b/plugin/storage/s3/s3.go
@@ -4,6 +4,7 @@ import (
"context"
"io"
+ "github.com/aws/aws-sdk-go-v2/aws"
awsconfig "github.com/aws/aws-sdk-go-v2/config"
awscredentials "github.com/aws/aws-sdk-go-v2/credentials"
"github.com/aws/aws-sdk-go-v2/feature/s3/manager"
@@ -12,20 +13,29 @@ import (
"github.com/pkg/errors"
)
-// Credentials is the AWS S3 credentials.
-type Credentials struct {
- AccessKeyID string `json:"accessKeyId"`
- SecretAccessKey string `json:"secretAccessKey"`
-}
-
// Client wraps the AWS S3 client.
type Client struct {
c *s3.Client
bucket string
}
+// GetCredentialsFromFile load AWS credentials from file.
+func GetCredentialsFromFile(ctx context.Context, credentialsFileName string) (aws.Credentials, error) {
+ cfg, err := awsconfig.LoadDefaultConfig(ctx,
+ awsconfig.WithSharedCredentialsFiles([]string{credentialsFileName}),
+ )
+ if err != nil {
+ return aws.Credentials{}, errors.Wrap(err, "failed to load AWS S3 config")
+ }
+ credentials, err := cfg.Credentials.Retrieve(ctx)
+ if err != nil {
+ return aws.Credentials{}, errors.Wrap(err, "failed to retrieve AWS S3 credentials")
+ }
+ return credentials, nil
+}
+
// NewClient returns a new AWS S3 client.
-func NewClient(ctx context.Context, region, bucket string, credentials Credentials) (*Client, error) {
+func NewClient(ctx context.Context, region, bucket string, credentials aws.Credentials) (*Client, error) {
cfg, err := awsconfig.LoadDefaultConfig(ctx,
awsconfig.WithRegion(region),
awsconfig.WithCredentialsProvider(awscredentials.NewStaticCredentialsProvider(credentials.AccessKeyID, credentials.SecretAccessKey, "")),
@@ -59,12 +69,11 @@ func (c *Client) DownloadObject(ctx context.Context, path string, w io.WriterAt)
// UploadObject uploads an object with the path.
// Defaults to multipart upload with chunk size 5MB.
-func (c *Client) UploadObject(ctx context.Context, path string, metadata map[string]string, body io.Reader) (*manager.UploadOutput, error) {
+func (c *Client) UploadObject(ctx context.Context, path string, body io.Reader) (*manager.UploadOutput, error) {
uploader := manager.NewUploader(c.c)
return uploader.Upload(ctx, &s3.PutObjectInput{
Bucket: &c.bucket,
Key: &path,
- Metadata: metadata,
Body: body,
ChecksumAlgorithm: types.ChecksumAlgorithmSha256,
})
@@ -77,3 +86,8 @@ func (c *Client) DeleteObject(ctx context.Context, path string) (*s3.DeleteObjec
Key: &path,
})
}
+
+// GetBucket returns the bucket.
+func (c *Client) GetBucket() string {
+ return c.bucket
+}
diff --git a/plugin/storage/s3/s3_test.go b/plugin/storage/s3/s3_test.go
index b23510272b..b9a88f1529 100644
--- a/plugin/storage/s3/s3_test.go
+++ b/plugin/storage/s3/s3_test.go
@@ -6,6 +6,7 @@ import (
"os"
"testing"
+ "github.com/aws/aws-sdk-go-v2/aws"
"github.com/bytebase/bytebase/common/log"
"github.com/stretchr/testify/require"
"go.uber.org/zap"
@@ -17,64 +18,48 @@ const (
)
var (
- credentials = Credentials{
+ credentials = aws.Credentials{
AccessKeyID: os.Getenv("ACCESS_KEY_ID"),
SecretAccessKey: os.Getenv("SECRET_ACCESS_KEY"),
}
)
-func TestListObjects(t *testing.T) {
+// Only for manual test.
+// Should be skipped in CI.
+func TestS3Operations(t *testing.T) {
t.Skip()
a := require.New(t)
ctx := context.Background()
client, err := NewClient(ctx, region, bucket, credentials)
a.NoError(err)
- resp, err := client.ListObjects(ctx, "backup/")
- a.NoError(err)
- for _, obj := range resp.Contents {
- log.Info("Object", zap.Any("*", obj))
- }
-}
+ t.Run("ListObjects", func(t *testing.T) {
+ resp, err := client.ListObjects(ctx, "backup/")
+ a.NoError(err)
+ for _, obj := range resp.Contents {
+ log.Info("Object", zap.Any("*", obj))
+ }
+ })
-func TestUploadObjects(t *testing.T) {
- t.Skip()
- a := require.New(t)
- ctx := context.Background()
- client, err := NewClient(ctx, region, bucket, credentials)
- a.NoError(err)
+ t.Run("UploadObjects", func(t *testing.T) {
+ buf := make([]byte, 10*1024*1024)
+ blob := bytes.NewReader(buf)
+ resp, err := client.UploadObject(ctx, "backup/test/blob", blob)
+ a.NoError(err)
+ log.Info("Uploaded", zap.String("name", *resp.Key))
+ })
- metadata := make(map[string]string)
- metadata["project_id"] = "233"
- buf := make([]byte, 10*1024*1024)
- blob := bytes.NewReader(buf)
- resp, err := client.UploadObject(ctx, "backup/test/blob", metadata, blob)
- a.NoError(err)
- log.Info("Uploaded", zap.String("name", *resp.Key))
-}
+ t.Run("DownloadObjects", func(t *testing.T) {
+ file, err := os.CreateTemp(t.TempDir(), "blob")
+ a.NoError(err)
+ n, err := client.DownloadObject(ctx, "backup/test/blob", file)
+ a.NoError(err)
+ log.Info("Downloaded", zap.Int64("length", n))
+ })
-func TestDownloadObjects(t *testing.T) {
- t.Skip()
- a := require.New(t)
- ctx := context.Background()
- client, err := NewClient(ctx, region, bucket, credentials)
- a.NoError(err)
-
- file, err := os.CreateTemp(t.TempDir(), "blob")
- a.NoError(err)
- n, err := client.DownloadObject(ctx, "backup/test/blob", file)
- a.NoError(err)
- log.Info("Downloaded", zap.Int64("length", n))
-}
-
-func TestDeleteObjects(t *testing.T) {
- t.Skip()
- a := require.New(t)
- ctx := context.Background()
- client, err := NewClient(ctx, region, bucket, credentials)
- a.NoError(err)
-
- resp, err := client.DeleteObject(ctx, "backup/test/blob")
- a.NoError(err)
- log.Info("Deleted", zap.Any("meta", resp.ResultMetadata))
+ t.Run("DeleteObjects", func(t *testing.T) {
+ resp, err := client.DeleteObject(ctx, "backup/test/blob")
+ a.NoError(err)
+ log.Info("Deleted", zap.Any("meta", resp.ResultMetadata))
+ })
}
diff --git a/server/config.go b/server/config.go
index a77d95d129..f886c6ab1f 100644
--- a/server/config.go
+++ b/server/config.go
@@ -54,6 +54,12 @@ type Profile struct {
BackupRunnerInterval time.Duration
// BackupStorageBackend is the backup storage backend.
BackupStorageBackend api.BackupStorageBackend
+
+ // Cloud backup related fields
+ BackupRegion string
+ BackupBucket string
+ BackupCredentialFile string
+
// Version is the bytebase's version
Version string
// Git commit hash of the build
diff --git a/server/server.go b/server/server.go
index 018347b9ff..8d08d14056 100644
--- a/server/server.go
+++ b/server/server.go
@@ -31,6 +31,7 @@ import (
enterpriseService "github.com/bytebase/bytebase/enterprise/service"
"github.com/bytebase/bytebase/metric"
metricCollector "github.com/bytebase/bytebase/metric/collector"
+ s3bb "github.com/bytebase/bytebase/plugin/storage/s3"
"github.com/bytebase/bytebase/resources/mysqlutil"
"github.com/bytebase/bytebase/resources/postgres"
"github.com/bytebase/bytebase/store"
@@ -63,6 +64,8 @@ type Server struct {
startedTs int64
secret string
+ s3Client *s3bb.Client
+
// boot specifies that whether the server boot correctly
cancel context.CancelFunc
}
@@ -117,6 +120,9 @@ func NewServer(ctx context.Context, prof Profile) (*Server, error) {
log.Info(fmt.Sprintf("debug=%t", prof.Debug))
log.Info(fmt.Sprintf("dataDir=%s", prof.DataDir))
log.Info(fmt.Sprintf("backupStorageBackend=%s", prof.BackupStorageBackend))
+ log.Info(fmt.Sprintf("backupBucket=%s", prof.BackupBucket))
+ log.Info(fmt.Sprintf("backupRegion=%s", prof.BackupRegion))
+ log.Info(fmt.Sprintf("backupCredentialFile=%s", prof.BackupCredentialFile))
log.Info("-----Config END-------")
serverStarted := false
@@ -198,6 +204,18 @@ func NewServer(ctx context.Context, prof Profile) (*Server, error) {
embedFrontend(e)
s.e = e
+ if prof.BackupBucket != "" {
+ credentials, err := s3bb.GetCredentialsFromFile(ctx, prof.BackupCredentialFile)
+ if err != nil {
+ return nil, errors.Wrap(err, "failed to get credentials from file")
+ }
+ s3Client, err := s3bb.NewClient(ctx, prof.BackupRegion, prof.BackupBucket, credentials)
+ if err != nil {
+ return nil, errors.Wrap(err, "failed to create AWS S3 client")
+ }
+ s.s3Client = s3Client
+ }
+
if !prof.Readonly {
// Task scheduler
taskScheduler := NewTaskScheduler(s)
diff --git a/server/task_executor_database_backup.go b/server/task_executor_database_backup.go
index 8133a5d7f8..ae30349d49 100644
--- a/server/task_executor_database_backup.go
+++ b/server/task_executor_database_backup.go
@@ -10,6 +10,7 @@ import (
"github.com/bytebase/bytebase/api"
"github.com/bytebase/bytebase/common/log"
+ "github.com/bytebase/bytebase/plugin/db"
"github.com/pkg/errors"
"go.uber.org/zap"
)
@@ -80,6 +81,19 @@ func (exec *DatabaseBackupTaskExecutor) RunOnce(ctx context.Context, server *Ser
}, nil
}
+func dumpBackupFile(ctx context.Context, driver db.Driver, databaseName, backupFilePath string) (string, error) {
+ backupFile, err := os.Create(backupFilePath)
+ if err != nil {
+ return "", errors.Errorf("failed to open backup path %q", backupFilePath)
+ }
+ defer backupFile.Close()
+ payload, err := driver.Dump(ctx, databaseName, backupFile, false /* schemaOnly */)
+ if err != nil {
+ return "", errors.Wrapf(err, "failed to dump database %q to local backup file %q", databaseName, backupFilePath)
+ }
+ return payload, nil
+}
+
// backupDatabase will take a backup of a database.
func (*DatabaseBackupTaskExecutor) backupDatabase(ctx context.Context, server *Server, instance *api.Instance, databaseName string, backup *api.Backup) (string, error) {
driver, err := server.getAdminDatabaseDriver(ctx, instance, databaseName)
@@ -88,18 +102,37 @@ func (*DatabaseBackupTaskExecutor) backupDatabase(ctx context.Context, server *S
}
defer driver.Close(ctx)
- f, err := os.Create(filepath.Join(server.profile.DataDir, backup.Path))
+ backupFilePathLocal := filepath.Join(server.profile.DataDir, backup.Path)
+ payload, err := dumpBackupFile(ctx, driver, databaseName, backupFilePathLocal)
if err != nil {
- return "", errors.Errorf("failed to open backup path: %s", backup.Path)
+ return "", errors.Wrapf(err, "failed to dump backup file %q", backupFilePathLocal)
}
- defer f.Close()
- payload, err := driver.Dump(ctx, databaseName, f, false /* schemaOnly */)
- if err != nil {
- return "", err
+ switch backup.StorageBackend {
+ case api.BackupStorageBackendLocal:
+ return payload, nil
+ case api.BackupStorageBackendS3:
+ log.Debug("Uploading backup to s3 bucket.", zap.String("bucket", server.s3Client.GetBucket()), zap.String("path", backupFilePathLocal))
+ bucketFileToUpload, err := os.Open(backupFilePathLocal)
+ if err != nil {
+ return "", errors.Wrapf(err, "failed to open backup file %q for uploading to s3 bucket", backupFilePathLocal)
+ }
+ defer bucketFileToUpload.Close()
+
+ if _, err := server.s3Client.UploadObject(ctx, backup.Path, bucketFileToUpload); err != nil {
+ return "", errors.Wrapf(err, "failed to upload backup to AWS S3")
+ }
+ log.Debug("Successfully uploaded backup to s3 bucket.")
+
+ if err := os.Remove(backupFilePathLocal); err != nil {
+ log.Warn("Failed to remove the local backup file after uploading to s3 bucket.", zap.String("path", backupFilePathLocal), zap.Error(err))
+ } else {
+ log.Debug("Successfully removed the local backup file after uploading to s3 bucket.", zap.String("path", backupFilePathLocal))
+ }
+ return payload, nil
+ default:
+ return "", errors.Errorf("backup to %s not implemented yet", backup.StorageBackend)
}
-
- return payload, nil
}
// Get backup dir relative to the data dir.