mirror: Add support of site-wide mirroring (#3467)

This commit is contained in:
Anis Elleuch
2020-12-14 14:10:09 -08:00
committed by GitHub
parent 1967d38dd4
commit 4e8e67fb04
8 changed files with 177 additions and 253 deletions
+49 -53
View File
@@ -722,6 +722,14 @@ func (c *S3Client) Watch(ctx context.Context, options WatchOptions) (*WatchObjec
// Extract bucket and object.
bucket, object := c.url2BucketAndObject()
// Validation
if bucket == "" && object != "" {
return nil, errInvalidArgument().Trace(bucket, object)
}
if object != "" && options.Prefix != "" {
return nil, errInvalidArgument().Trace(options.Prefix, object)
}
// Flag set to set the notification.
var events []string
for _, event := range options.Events {
@@ -736,30 +744,14 @@ func (c *S3Client) Watch(ctx context.Context, options WatchOptions) (*WatchObjec
events = append(events, "s3:Replication:*") // TODO: add it to minio-go as constant
case "ilm":
events = append(events, "s3:ObjectRestore:*", "s3:ObjectTransition:*") // TODO: add it to minio-go as constant
case "bucket-creation":
events = append(events, string(notification.BucketCreatedAll))
case "bucket-removal":
events = append(events, string(notification.BucketRemovedAll))
default:
return nil, errInvalidArgument().Trace(event)
}
}
if object != "" && options.Prefix != "" {
return nil, errInvalidArgument().Trace(options.Prefix, object)
}
if object != "" && options.Prefix == "" {
options.Prefix = object
}
// The list of buckets to watch
var buckets []string
if bucket == "" {
bkts, err := c.api.ListBuckets(ctx)
if err != nil {
return nil, probe.NewError(err)
}
for _, b := range bkts {
buckets = append(buckets, b.Name)
}
} else {
buckets = append(buckets, bucket)
}
wo := &WatchObject{
EventInfoChan: make(chan []EventInfo),
@@ -767,36 +759,35 @@ func (c *S3Client) Watch(ctx context.Context, options WatchOptions) (*WatchObjec
DoneChan: make(chan struct{}),
}
var wg sync.WaitGroup
wg.Add(len(buckets))
for _, bucket := range buckets {
bucket := bucket
go func() {
defer wg.Done()
// Start listening on all bucket events.
eventsCh := c.api.ListenBucketNotification(ctx, bucket, options.Prefix, options.Suffix, events)
for notificationInfo := range eventsCh {
if notificationInfo.Err != nil {
var perr *probe.Error
if minio.ToErrorResponse(notificationInfo.Err).Code == "NotImplemented" {
perr = probe.NewError(APINotImplemented{
API: "Watch",
APIType: c.GetURL().String(),
})
} else {
perr = probe.NewError(notificationInfo.Err)
}
wo.Errors() <- perr
} else {
wo.Events() <- c.notificationToEventsInfo(notificationInfo)
}
}
}()
var eventsCh <-chan notification.Info
if bucket != "" {
if object != "" && options.Prefix == "" {
options.Prefix = object
}
eventsCh = c.api.ListenBucketNotification(ctx, bucket, options.Prefix, options.Suffix, events)
} else {
eventsCh = c.api.ListenNotification(ctx, "", "", events)
}
go func() {
wg.Wait() // this occurs when all watchers have returned
// we can safely close data and error channels
// Start listening on all bucket events.
for notificationInfo := range eventsCh {
if notificationInfo.Err != nil {
var perr *probe.Error
if minio.ToErrorResponse(notificationInfo.Err).Code == "NotImplemented" {
perr = probe.NewError(APINotImplemented{
API: "Watch",
APIType: c.GetURL().String(),
})
} else {
perr = probe.NewError(notificationInfo.Err)
}
wo.Errors() <- perr
} else {
wo.Events() <- c.notificationToEventsInfo(notificationInfo)
}
}
close(wo.EventInfoChan)
close(wo.ErrorChan)
}()
@@ -807,6 +798,7 @@ func (c *S3Client) Watch(ctx context.Context, options WatchOptions) (*WatchObjec
// Get - get object with GET options.
func (c *S3Client) Get(ctx context.Context, opts GetOptions) (io.ReadCloser, *probe.Error) {
bucket, object := c.url2BucketAndObject()
reader, e := c.api.GetObject(ctx, bucket, object,
minio.GetObjectOptions{
ServerSideEncryption: opts.SSE,
@@ -1376,7 +1368,12 @@ func (c *S3Client) Stat(ctx context.Context, opts StatOptions) (*ClientContent,
// Bucket name cannot be empty, stat on URL has no meaning.
if bucket == "" {
return nil, probe.NewError(BucketNameEmpty{})
url := c.targetURL.Clone()
url.Path = string(c.targetURL.Separator)
return &ClientContent{URL: url,
Size: 0,
Type: os.ModeDir,
}, nil
}
if object == "" {
@@ -1426,11 +1423,10 @@ func (c *S3Client) Stat(ctx context.Context, opts StatOptions) (*ClientContent,
return nil, probe.NewError(objectStat.Err)
}
if objectStat.Key != object {
break
if objectStat.Key == strings.TrimSuffix(object, string(c.targetURL.Separator)) {
return c.objectInfo2ClientContent(bucket, objectStat), nil
}
return c.objectInfo2ClientContent(bucket, objectStat), nil
break
}
return nil, probe.NewError(ObjectMissing{opts.timeRef})
@@ -2024,7 +2020,7 @@ func (c *S3Client) listRecursiveInRoutine(ctx context.Context, contentCh chan *C
return
}
for _, bucket := range buckets {
if opts.ShowDir != DirLast {
if opts.ShowDir == DirFirst {
contentCh <- c.bucketInfo2ClientContent(bucket)
}
+2
View File
@@ -95,6 +95,8 @@ func (d diffMessage) String() string {
msg = console.Colorize("DiffMetadata", "! "+d.SecondURL)
case differInAASourceMTime:
msg = console.Colorize("DiffMMSourceMTime", "! "+d.SecondURL)
case differInNone:
msg = console.Colorize("DiffInNone", "= "+d.FirstURL)
default:
fatalIf(errDummy().Trace(d.FirstURL, d.SecondURL),
"Unhandled difference between `"+d.FirstURL+"` and `"+d.SecondURL+"`.")
+91 -112
View File
@@ -20,7 +20,6 @@ import (
"context"
"fmt"
"math/rand"
"os"
"path"
"path/filepath"
"runtime"
@@ -160,30 +159,33 @@ EXAMPLES:
new objects, uploads and removes extraneous files on Amazon S3 cloud storage.
{{.Prompt}} {{.HelpName}} --remove --watch /var/lib/backups play/backups
08. Mirror a bucket from aliased Amazon S3 cloud storage to a local folder.
08. Continuously mirror all buckets and objects from site 1 to site 2, removed buckets and objects will be reflected as well.
{{.Prompt}} {{.HelpName}} --remove --watch site1-alias/ site2-alias/
09. Mirror a bucket from aliased Amazon S3 cloud storage to a local folder.
Exclude all .* files and *.temp files when mirroring.
{{.Prompt}} {{.HelpName}} --exclude ".*" --exclude "*.temp" s3/test ~/test
09. Mirror objects newer than 10 days from bucket test to a local folder.
10. Mirror objects newer than 10 days from bucket test to a local folder.
{{.Prompt}} {{.HelpName}} --newer-than 10d s3/test ~/localfolder
10. Mirror objects older than 30 days from Amazon S3 bucket test to a local folder.
11. Mirror objects older than 30 days from Amazon S3 bucket test to a local folder.
{{.Prompt}} {{.HelpName}} --older-than 30d s3/test ~/test
11. Mirror server encrypted objects from MinIO cloud storage to a bucket on Amazon S3 cloud storage
12. Mirror server encrypted objects from MinIO cloud storage to a bucket on Amazon S3 cloud storage
{{.Prompt}} {{.HelpName}} --encrypt-key "minio/photos=32byteslongsecretkeymustbegiven1,s3/archive=32byteslongsecretkeymustbegiven2" minio/photos/ s3/archive/
12. Mirror server encrypted objects from MinIO cloud storage to a bucket on Amazon S3 cloud storage. In case the encryption key contains
13. Mirror server encrypted objects from MinIO cloud storage to a bucket on Amazon S3 cloud storage. In case the encryption key contains
non-printable character like tab, pass the base64 encoded string as key.
{{.Prompt}} {{.HelpName}} --encrypt-key "s3/photos/=32byteslongsecretkeymustbegiven1,play/archive/=MzJieXRlc2xvbmdzZWNyZXRrZQltdXN0YmVnaXZlbjE=" s3/photos/ play/archive/
13. Update 'Cache-Control' header on all existing objects recursively.
14. Update 'Cache-Control' header on all existing objects recursively.
{{.Prompt}} {{.HelpName}} --attr "Cache-Control=max-age=90000,min-fresh=9000" myminio/video-files myminio/video-files
14. Mirror a local folder recursively to Amazon S3 cloud storage and preserve all local file attributes.
15. Mirror a local folder recursively to Amazon S3 cloud storage and preserve all local file attributes.
{{.Prompt}} {{.HelpName}} -a backup/ s3/archive
15. Cross mirror between sites in a active-active deployment.
16. Cross mirror between sites in a active-active deployment.
Site-A: {{.Prompt}} {{.HelpName}} --active-active siteA siteB
Site-B: {{.Prompt}} {{.HelpName}} --active-active siteB siteA
`,
@@ -243,6 +245,49 @@ func (m mirrorMessage) JSON() string {
return string(mirrorMessageBytes)
}
func (mj *mirrorJob) doCreateBucket(ctx context.Context, sURLs URLs) URLs {
if mj.opts.isFake {
return sURLs.WithError(nil)
}
// Construct proper path with alias.
aliasedURL := filepath.Join(sURLs.TargetAlias, sURLs.TargetContent.URL.Path)
clnt, pErr := newClient(aliasedURL)
if pErr != nil {
return sURLs.WithError(pErr)
}
err := clnt.MakeBucket(ctx, "", mj.opts.isOverwrite, false)
if err != nil {
return sURLs.WithError(err)
}
return sURLs.WithError(nil)
}
func (mj *mirrorJob) doDeleteBucket(ctx context.Context, sURLs URLs) URLs {
if mj.opts.isFake {
return sURLs.WithError(nil)
}
// Construct proper path with alias.
aliasedURL := filepath.Join(sURLs.TargetAlias, sURLs.TargetContent.URL.Path)
clnt, pErr := newClient(aliasedURL)
if pErr != nil {
return sURLs.WithError(pErr)
}
var contentCh = make(chan *ClientContent, 1)
contentCh <- &ClientContent{URL: clnt.GetURL()}
close(contentCh)
for err := range clnt.Remove(ctx, false, true, false, contentCh) {
return sURLs.WithError(err)
}
return sURLs.WithError(nil)
}
// doRemove - removes files on target.
func (mj *mirrorJob) doRemove(ctx context.Context, sURLs URLs) URLs {
if mj.opts.isFake {
@@ -502,7 +547,26 @@ func (mj *mirrorJob) watchMirrorEvents(ctx context.Context, events []EventInfo)
return mj.doRemove(ctx, mirrorURL)
})
}
} else if event.Type == notification.BucketCreatedAll {
mirrorURL := URLs{
SourceAlias: sourceAlias,
SourceContent: &ClientContent{URL: *sourceURL},
TargetAlias: targetAlias,
TargetContent: &ClientContent{URL: *targetURL},
}
mj.parallel.queueTaskWithBarrier(func() URLs {
return mj.doCreateBucket(ctx, mirrorURL)
})
} else if event.Type == notification.BucketRemovedAll && mj.opts.isRemove {
mirrorURL := URLs{
TargetAlias: targetAlias,
TargetContent: &ClientContent{URL: *targetURL},
}
mj.parallel.queueTaskWithBarrier(func() URLs {
return mj.doDeleteBucket(ctx, mirrorURL)
})
}
}
}
@@ -737,14 +801,14 @@ func runMirror(ctx context.Context, cancelMirror context.CancelFunc, srcURL, dst
dstClt, err := newClient(dstURL)
fatalIf(err, "Unable to initialize `"+dstURL+"`.")
// This is kept for backward compatibility, `--force` means
// --overwrite.
// This is kept for backward compatibility, `--force` means --overwrite.
isOverwrite := cli.Bool("force")
if !isOverwrite {
isOverwrite = cli.Bool("overwrite")
}
isWatch := cli.Bool("watch") || cli.Bool("multi-master") || cli.Bool("active-active")
isRemove := cli.Bool("remove")
// preserve is also expected to be overwritten if necessary
isMetadata := cli.Bool("a") || isWatch || len(userMetadata) > 0
@@ -752,7 +816,7 @@ func runMirror(ctx context.Context, cancelMirror context.CancelFunc, srcURL, dst
mopts := mirrorOptions{
isFake: cli.Bool("fake"),
isRemove: cli.Bool("remove"),
isRemove: isRemove,
isOverwrite: isOverwrite,
isWatch: isWatch,
isMetadata: isMetadata,
@@ -776,7 +840,7 @@ func runMirror(ctx context.Context, cancelMirror context.CancelFunc, srcURL, dst
mirrorSrcBuckets := srcClt.GetURL().Type == objectStorage && srcClt.GetURL().Path == string(srcClt.GetURL().Separator)
mirrorBucketsToBuckets := mirrorSrcBuckets && createDstBuckets
if mirrorBucketsToBuckets {
if mirrorSrcBuckets || createDstBuckets {
// Synchronize buckets using dirDifference function
for d := range dirDifference(ctx, srcClt, dstClt, srcURL, dstURL) {
if d.Error != nil {
@@ -786,12 +850,19 @@ func runMirror(ctx context.Context, cancelMirror context.CancelFunc, srcURL, dst
}
mj.status.fatalIf(d.Error, "Failed to start mirroring.")
}
if d.Diff == differInSecond {
// Ignore buckets that only exist in target instance
diffBucket := strings.TrimPrefix(d.SecondURL, dstClt.GetURL().String())
if isRemove {
aliasedDstBucket := path.Join(dstURL, diffBucket)
err := deleteBucket(ctx, aliasedDstBucket)
mj.status.fatalIf(err, "Failed to start mirroring.")
}
continue
}
sourceSuffix := strings.TrimPrefix(d.FirstURL, srcClt.GetURL().String())
newSrcURL := path.Join(srcURL, sourceSuffix)
newTgtURL := path.Join(dstURL, sourceSuffix)
@@ -833,89 +904,10 @@ func runMirror(ctx context.Context, cancelMirror context.CancelFunc, srcURL, dst
"Unable to copy bucket policies to `"+newDstClt.GetURL().String()+"`.")
}
}
if mirrorSrcBuckets && mj.opts.isWatch {
// monitor mode will watch the source folders for changes,
// and queue them for copying.
if err := mj.watchURL(ctx, newSrcClt); err != nil {
if mj.opts.activeActive {
errorIf(err, "Failed to start monitoring.. retrying")
return true
}
mj.status.fatalIf(err, "Failed to start monitoring.")
}
}
}
} else if _, err := dstClt.Stat(ctx, StatOptions{}); err != nil {
var (
withLock bool
mode minio.RetentionMode
validity uint64
unit minio.ValidityUnit
err *probe.Error
)
if preserve {
_, mode, validity, unit, err = srcClt.GetObjectLockConfig(ctx)
if err == nil {
withLock = true
}
}
if dstClt.GetURL().Path == string(dstClt.GetURL().Separator) {
targetAlias, targetURL, _ := mustExpandAlias(srcURL)
if !strings.HasSuffix(targetURL, string(srcClt.GetURL().Separator)) {
targetURL += string(srcClt.GetURL().Separator)
}
srcClt, err := newClientFromAlias(targetAlias, targetURL)
fatalIf(err.Trace(targetURL), "Unable to initialize target `"+targetURL+"`.")
dstInitialURL := dstURL
for content := range srcClt.List(ctx, ListOptions{Recursive: false, ShowDir: DirNone}) {
if content.Err != nil {
errorIf(content.Err.Trace(srcClt.GetURL().String()), "Unable to list folder.")
continue
}
if content.Type.IsDir() {
dstURL = urlJoinPath(dstInitialURL, filepath.Base(content.URL.Path)+string(srcClt.GetURL().Separator))
dstClt, err = newClient(dstURL)
fatalIf(err, "Unable to initialize `"+dstURL+"`.")
mj.status.fatalIf(dstClt.MakeBucket(ctx, cli.String("region"), true, withLock),
"Unable to create bucket at `"+dstURL+"`.")
}
}
} else {
// Create bucket if it doesn't exist at destination.
// ignore if already exists.
err = dstClt.MakeBucket(ctx, cli.String("region"), true, withLock)
errorIf(err, "Unable to create bucket at `"+dstURL+"`.")
if err != nil {
return true
}
}
if preserve {
if mode != "" {
// object lock configuration set on bucket
err = dstClt.SetObjectLockConfig(ctx, mode, validity, unit)
errorIf(err, "Unable to set object lock config in `"+dstURL+"`.")
if err != nil && mj.opts.activeActive {
return true
}
if err == nil {
mj.opts.md5 = true
}
}
errorIf(copyBucketPolicies(ctx, srcClt, dstClt, isOverwrite),
"Unable to copy bucket policies to `"+dstClt.GetURL().String()+"`.")
}
}
if !mirrorSrcBuckets && mj.opts.isWatch {
if mj.opts.isWatch {
// monitor mode will watch the source folders for changes,
// and queue them for copying.
if err := mj.watchURL(ctx, srcClt); err != nil {
@@ -926,11 +918,15 @@ func runMirror(ctx context.Context, cancelMirror context.CancelFunc, srcURL, dst
mj.status.fatalIf(err, "Failed to start monitoring.")
}
}
return mj.mirror(ctx, cancelMirror)
}
// Main entry point for mirror command.
func mainMirror(cliCtx *cli.Context) error {
// Additional command specific theme customization.
console.SetColor("Mirror", color.New(color.FgGreen, color.Bold))
ctx, cancelMirror := context.WithCancel(globalContext)
defer cancelMirror()
@@ -939,24 +935,7 @@ func mainMirror(cliCtx *cli.Context) error {
fatalIf(err, "Unable to parse encryption keys.")
// check 'mirror' cli arguments.
checkMirrorSyntax(ctx, cliCtx, encKeyDB)
// Additional command specific theme customization.
console.SetColor("Mirror", color.New(color.FgGreen, color.Bold))
args := cliCtx.Args()
srcURL := args[0]
tgtURL := args[1]
srcFI, e := os.Stat(srcURL)
if e == nil && srcFI.IsDir() && !filepath.IsAbs(srcURL) {
origSrcURL := srcURL
// Changing relative path to absolute path, if it is a local directory.
// Save original in case of error
if srcURL, e = filepath.Abs(srcURL); e != nil {
srcURL = origSrcURL
}
}
srcURL, tgtURL := checkMirrorSyntax(ctx, cliCtx, encKeyDB)
r := rand.New(rand.NewSource(time.Now().UnixNano()))
for {
+21 -17
View File
@@ -19,6 +19,7 @@ package cmd
import (
"context"
"fmt"
"path/filepath"
"runtime"
"strings"
"time"
@@ -33,15 +34,15 @@ import (
// mirror(d1..., d2) -> []mirror(d1/f, d2/d1/f)
// checkMirrorSyntax(URLs []string)
func checkMirrorSyntax(ctx context.Context, cliCtx *cli.Context, encKeyDB map[string][]prefixSSEPair) {
func checkMirrorSyntax(ctx context.Context, cliCtx *cli.Context, encKeyDB map[string][]prefixSSEPair) (srcURL, tgtURL string) {
if len(cliCtx.Args()) != 2 {
cli.ShowCommandHelpAndExit(cliCtx, "mirror", 1) // last argument is exit code.
}
// extract URLs.
URLs := cliCtx.Args()
srcURL := URLs[0]
tgtURL := URLs[1]
srcURL = URLs[0]
tgtURL = URLs[1]
if cliCtx.Bool("force") && cliCtx.Bool("remove") {
errorIf(errInvalidArgument().Trace(URLs...), "`--force` is deprecated, please use `--overwrite` instead with `--remove` for the same functionality.")
@@ -49,14 +50,6 @@ func checkMirrorSyntax(ctx context.Context, cliCtx *cli.Context, encKeyDB map[st
errorIf(errInvalidArgument().Trace(URLs...), "`--force` is deprecated, please use `--overwrite` instead for the same functionality.")
}
tgtClientURL := newClientURL(tgtURL)
if tgtClientURL.Host != "" {
if tgtClientURL.Path == string(tgtClientURL.Separator) {
fatalIf(errInvalidArgument().Trace(tgtURL),
fmt.Sprintf("Target `%s` does not contain bucket name.", tgtURL))
}
}
_, expandedSourcePath, _ := mustExpandAlias(srcURL)
srcClient := newClientURL(expandedSourcePath)
_, expandedTargetPath, _ := mustExpandAlias(tgtURL)
@@ -73,19 +66,30 @@ func checkMirrorSyntax(ctx context.Context, cliCtx *cli.Context, encKeyDB map[st
/****** Generic rules *******/
if !cliCtx.Bool("watch") && !cliCtx.Bool("active-active") && !cliCtx.Bool("multi-master") {
_, srcContent, err := url2Stat(ctx, srcURL, "", false, encKeyDB, time.Time{})
// incomplete uploads are not necessary for mirror operation, no need to verify for them.
isIncomplete := false
if err != nil && !isURLPrefixExists(srcURL, isIncomplete) {
if err != nil {
fatalIf(err.Trace(srcURL), "Unable to stat source `"+srcURL+"`.")
}
if err == nil {
if !srcContent.Type.IsDir() {
fatalIf(errInvalidArgument().Trace(srcContent.URL.String(), srcContent.Type.String()), fmt.Sprintf("Source `%s` is not a folder. Only folders are supported by mirror command.", srcURL))
if !srcContent.Type.IsDir() {
fatalIf(errInvalidArgument().Trace(srcContent.URL.String(), srcContent.Type.String()), fmt.Sprintf("Source `%s` is not a folder. Only folders are supported by mirror command.", srcURL))
}
if srcClient.Type == fileSystem && !filepath.IsAbs(srcURL) {
var origSrcURL = srcURL
var e error
// Changing relative path to absolute path, if it is a local directory.
// Save original in case of error
if srcURL, e = filepath.Abs(srcURL); e != nil {
srcURL = origSrcURL
}
}
if !strings.HasSuffix(srcURL, string(srcContent.URL.Separator)) {
srcURL += string(srcContent.URL.Separator)
}
}
return
}
func matchExcludeOptions(excludeOptions []string, srcSuffix string) bool {
+1 -1
View File
@@ -116,7 +116,7 @@ func (w *Watcher) Wait() {
func (w *Watcher) Join(ctx context.Context, client Client, recursive bool) *probe.Error {
wo, err := client.Watch(ctx, WatchOptions{
Recursive: recursive,
Events: []string{"put", "delete"},
Events: []string{"put", "delete", "bucket-creation", "bucket-removal"},
})
if err != nil {
return err