From dff077e34b75756989624b59422f84d9994b5801 Mon Sep 17 00:00:00 2001 From: Harshavardhana Date: Thu, 19 Sep 2019 08:22:45 -0700 Subject: [PATCH] Add support for attr flag in mirror (#2892) --- cmd/common-methods.go | 40 +++++++++++++++++++--------------------- cmd/cp-main.go | 19 ++++++++----------- cmd/diff-main.go | 4 +++- cmd/difference.go | 32 ++++++++++++++++++++++---------- cmd/mirror-main.go | 33 +++++++++++++++++++++++++++------ cmd/mirror-url.go | 17 ++++++----------- 6 files changed, 85 insertions(+), 60 deletions(-) diff --git a/cmd/common-methods.go b/cmd/common-methods.go index 50b69943..ccb9d29f 100644 --- a/cmd/common-methods.go +++ b/cmd/common-methods.go @@ -246,7 +246,7 @@ func copySourceToTargetURL(alias string, urlStr string, source string, size int6 } // createUserMetadata - returns a map of user defined function -// by combining the usermetadata of object and values passed by attr keyword +// by combining the usermetadata of object and values passed by attr keyword func createUserMetadata(sourceAlias, sourceURLStr string, srcSSE encrypt.ServerSide, urls URLs) (map[string]string, *probe.Error) { metadata := make(map[string]string) sourceClnt, err := newClientFromAlias(sourceAlias, sourceURLStr) @@ -258,14 +258,15 @@ func createUserMetadata(sourceAlias, sourceURLStr string, srcSSE encrypt.ServerS return nil, err.Trace(sourceAlias, sourceURLStr) } for k, v := range st.Metadata { - if httpguts.ValidHeaderFieldName(k) && strings.HasPrefix(k, "X-Amz-Meta-") && - httpguts.ValidHeaderFieldValue(v) { + if httpguts.ValidHeaderFieldName(k) && httpguts.ValidHeaderFieldValue(v) { metadata[k] = v } } for k, v := range urls.TargetContent.UserMetadata { - metadata[k] = v + if httpguts.ValidHeaderFieldName(k) && httpguts.ValidHeaderFieldValue(v) { + metadata[k] = v + } } return metadata, nil } @@ -286,48 +287,45 @@ func uploadSourceToTargetURL(ctx context.Context, urls URLs, progress io.Reader, srcSSE := getSSE(sourcePath, encKeyDB[sourceAlias]) tgtSSE := getSSE(targetPath, encKeyDB[targetAlias]) + var err *probe.Error + var metadata map[string]string + // Optimize for server side copy if the host is same. if sourceAlias == targetAlias { - - metadata, err := createUserMetadata(sourceAlias, sourceURL.String(), srcSSE, urls) + metadata, err = createUserMetadata(sourceAlias, sourceURL.String(), srcSSE, urls) if err != nil { return urls.WithError(err.Trace(sourceURL.String())) } sourcePath := filepath.ToSlash(sourceURL.Path) err = copySourceToTargetURL(targetAlias, targetURL.String(), sourcePath, length, progress, srcSSE, tgtSSE, metadata) - if err != nil { - return urls.WithError(err.Trace(sourceURL.String())) - } } else { + var reader io.ReadCloser // Proceed with regular stream copy. - reader, metadata, err := getSourceStream(sourceAlias, sourceURL.String(), true, srcSSE) + reader, metadata, err = getSourceStream(sourceAlias, sourceURL.String(), true, srcSSE) if err != nil { return urls.WithError(err.Trace(sourceURL.String())) } defer reader.Close() // Get metadata from target content as well - if urls.TargetContent.Metadata != nil { - for k, v := range urls.TargetContent.Metadata { - metadata[k] = v - } + for k, v := range urls.TargetContent.Metadata { + metadata[k] = v } // Get userMetadata from target content as well - if urls.TargetContent.UserMetadata != nil { - for k, v := range urls.TargetContent.UserMetadata { - metadata[k] = v - } + for k, v := range urls.TargetContent.UserMetadata { + metadata[k] = v } if srcSSE != nil { delete(metadata, "X-Amz-Server-Side-Encryption-Customer-Algorithm") delete(metadata, "X-Amz-Server-Side-Encryption-Customer-Key-Md5") } _, err = putTargetStream(ctx, targetAlias, targetURL.String(), reader, length, metadata, progress, tgtSSE) - if err != nil { - return urls.WithError(err.Trace(targetURL.String())) - } } + if err != nil { + return urls.WithError(err.Trace(sourceURL.String())) + } + return urls.WithError(nil) } diff --git a/cmd/cp-main.go b/cmd/cp-main.go index 374d2c8b..c2aefd78 100644 --- a/cmd/cp-main.go +++ b/cmd/cp-main.go @@ -118,10 +118,10 @@ EXAMPLES: 10. Copy a folder with encrypted objects recursively from Amazon S3 to MinIO cloud storage. In case the encryption key contains non-printable character like tab, pass the base64 encoded string as key. $ {{.HelpName}} --recursive --encrypt-key "s3/documents/=MzJieXRlc2xvbmdzZWNyZWFiY2RlZmcJZ2l2ZW5uMjE=,myminio/documents/=MzJieXRlc2xvbmdzZWNyZWFiY2RlZmcJZ2l2ZW5uMjE=" s3/documents/ myminio/documents/ - + 11. Copy a list of objects from local file system to MinIO cloud storage with specified metadata. $ {{.HelpName}} --attr key1=value1,key2=value2 Music/*.mp4 play/mybucket/ - + 12. Copy a folder recursively from MinIO cloud storage to Amazon S3 cloud storage with specified metadata. $ {{.HelpName}} --attr Cache-Control=max-age=90000,min-fresh=9000\;key1=value1\;key2=value2 --recursive play/mybucket/burningman2011/ s3/mybucket/ @@ -360,22 +360,19 @@ func doCopySession(session *sessionV8, encKeyDB map[string][]prefixSSEPair) erro // Save totalSize. cpURLs.TotalSize = session.Header.TotalBytes + // Initialize target metadata. + cpURLs.TargetContent.Metadata = make(map[string]string) + + // Initialize target user metadata. + cpURLs.TargetContent.UserMetadata = make(map[string]string) + // Check and handle storage class if passed in command line args if _, ok := session.Header.CommandStringFlags["storage-class"]; ok { - if cpURLs.TargetContent.Metadata == nil { - cpURLs.TargetContent.Metadata = make(map[string]string) - } cpURLs.TargetContent.Metadata["X-Amz-Storage-Class"] = session.Header.CommandStringFlags["storage-class"] } - // metaMap, metaSet := session.Header.UserMetaData - // Check and handle metadata if passed in command line args - if len(session.Header.UserMetaData) != 0 { - if cpURLs.TargetContent.UserMetadata == nil { - cpURLs.TargetContent.UserMetadata = make(map[string]string) - } for metaDataKey, metaDataVal := range session.Header.UserMetaData { cpURLs.TargetContent.UserMetadata[metaDataKey] = metaDataVal } diff --git a/cmd/diff-main.go b/cmd/diff-main.go index ab1a4baf..3f5eb0c2 100644 --- a/cmd/diff-main.go +++ b/cmd/diff-main.go @@ -90,6 +90,8 @@ func (d diffMessage) String() string { msg = console.Colorize("DiffSize", "! "+d.SecondURL) case differInTime: msg = console.Colorize("DiffTime", "! "+d.SecondURL) + case differInMetadata: + msg = console.Colorize("DiffMetadata", "! "+d.SecondURL) default: fatalIf(errDummy().Trace(d.FirstURL, d.SecondURL), "Unhandled difference between `"+d.FirstURL+"` and `"+d.SecondURL+"`.") @@ -174,7 +176,7 @@ func doDiffMain(firstURL, secondURL string) error { } // Diff first and second urls. - for diffMsg := range objectDifference(firstClient, secondClient, firstURL, secondURL) { + for diffMsg := range objectDifference(firstClient, secondClient, firstURL, secondURL, false) { if diffMsg.Error != nil { errorIf(diffMsg.Error, "Unable to calculate objects difference.") // Ignore error and proceed to next object. diff --git a/cmd/difference.go b/cmd/difference.go index 474f2e88..3a5387b4 100644 --- a/cmd/difference.go +++ b/cmd/difference.go @@ -29,12 +29,13 @@ import ( type differType int const ( - differInNone differType = iota // does not differ - differInSize // differs in size - differInTime // differs in time - differInType // differs in type, exfile/directory - differInFirst // only in source (FIRST) - differInSecond // only in target (SECOND) + differInNone differType = iota // does not differ + differInSize // differs in size + differInTime // differs in time + differInMetadata // differs in metadata + differInType // differs in type, exfile/directory + differInFirst // only in source (FIRST) + differInSecond // only in target (SECOND) ) func (d differType) String() string { @@ -45,6 +46,8 @@ func (d differType) String() string { return "size" case differInTime: return "time" + case differInMetadata: + return "metadata" case differInType: return "type" case differInFirst: @@ -55,17 +58,17 @@ func (d differType) String() string { return "unknown" } -func objectDifference(sourceClnt, targetClnt Client, sourceURL, targetURL string) (diffCh chan diffMessage) { - return difference(sourceClnt, targetClnt, sourceURL, targetURL, true, false, DirNone) +func objectDifference(sourceClnt, targetClnt Client, sourceURL, targetURL string, isMetadata bool) (diffCh chan diffMessage) { + return difference(sourceClnt, targetClnt, sourceURL, targetURL, isMetadata, true, false, DirNone) } func dirDifference(sourceClnt, targetClnt Client, sourceURL, targetURL string) (diffCh chan diffMessage) { - return difference(sourceClnt, targetClnt, sourceURL, targetURL, false, true, DirFirst) + return difference(sourceClnt, targetClnt, sourceURL, targetURL, false, false, true, DirFirst) } // objectDifference function finds the difference between all objects // recursively in sorted order from source and target. -func difference(sourceClnt, targetClnt Client, sourceURL, targetURL string, isRecursive, returnSimilar bool, dirOpt DirOpt) (diffCh chan diffMessage) { +func difference(sourceClnt, targetClnt Client, sourceURL, targetURL string, isMetadata bool, isRecursive, returnSimilar bool, dirOpt DirOpt) (diffCh chan diffMessage) { var ( srcEOF, tgtEOF bool srcOk, tgtOk bool @@ -196,6 +199,15 @@ func difference(sourceClnt, targetClnt Client, sourceURL, targetURL string, isRe firstContent: srcCtnt, secondContent: tgtCtnt, } + } else if isMetadata { + // Regular files user requesting additional metadata to same file. + diffCh <- diffMessage{ + FirstURL: srcCtnt.URL.String(), + SecondURL: tgtCtnt.URL.String(), + Diff: differInMetadata, + firstContent: srcCtnt, + secondContent: tgtCtnt, + } } // No differ if returnSimilar { diff --git a/cmd/mirror-main.go b/cmd/mirror-main.go index 0460f2b8..c1e6d72c 100644 --- a/cmd/mirror-main.go +++ b/cmd/mirror-main.go @@ -87,6 +87,10 @@ var ( Name: "encrypt", Usage: "encrypt/decrypt objects (using server-side encryption with server managed keys)", }, + cli.StringFlag{ + Name: "attr", + Usage: "add custom metadata for all objects", + }, } ) @@ -150,6 +154,9 @@ EXAMPLES: 12. 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. $ {{.HelpName}} --encrypt-key "s3/photos/=32byteslongsecretkeymustbegiven1,play/archive/=MzJieXRlc2xvbmdzZWNyZXRrZQltdXN0YmVnaXZlbjE=" s3/photos/ play/archive/ + + 13. Update 'Cache-Control' header on existing objects. + $ {{.HelpName}} --attr Cache-Control=max-age=90000,min-fresh=9000 myminio/video-files myminio/video-files `, } @@ -184,6 +191,7 @@ type mirrorJob struct { isFake, isRemove, isOverwrite, isWatch bool olderThan, newerThan string storageClass string + userMetadata map[string]string excludeOptions []string encKeyDB map[string][]prefixSSEPair @@ -267,13 +275,16 @@ func (mj *mirrorJob) doMirror(ctx context.Context, cancelMirror context.CancelFu mj.status.SetCaption(sourceURL.String() + ": ") + // Initialize target metadata. + sURLs.TargetContent.Metadata = make(map[string]string) + if mj.storageClass != "" { - if sURLs.TargetContent.Metadata == nil { - sURLs.TargetContent.Metadata = make(map[string]string) - } sURLs.TargetContent.Metadata["X-Amz-Storage-Class"] = mj.storageClass } + // Initialize additional target user metadata. + sURLs.TargetContent.UserMetadata = mj.userMetadata + sourcePath := filepath.ToSlash(filepath.Join(sourceAlias, sourceURL.Path)) targetPath := filepath.ToSlash(filepath.Join(targetAlias, targetURL.Path)) mj.status.PrintMsg(mirrorMessage{ @@ -347,7 +358,6 @@ func (mj *mirrorJob) watchMirror(ctx context.Context, cancelMirror context.Cance } } eventPath := event.Path - if runtime.GOOS == "darwin" { // Strip the prefixes in the event path. Happens in darwin OS only eventPath = eventPath[strings.Index(eventPath, sourceURLFull):] @@ -486,7 +496,8 @@ func (mj *mirrorJob) startMirror(ctx context.Context, cancelMirror context.Cance mj.parallel.wait() } - URLsCh := prepareMirrorURLs(mj.sourceURL, mj.targetURL, mj.isFake, mj.isOverwrite, mj.isRemove, mj.excludeOptions, mj.encKeyDB) + isMetadata := len(mj.userMetadata) > 0 + URLsCh := prepareMirrorURLs(mj.sourceURL, mj.targetURL, mj.isFake, mj.isOverwrite, mj.isRemove, isMetadata, mj.excludeOptions, mj.encKeyDB) for { select { @@ -569,7 +580,7 @@ func (mj *mirrorJob) mirror(ctx context.Context, cancelMirror context.CancelFunc return mj.monitorMirrorStatus() } -func newMirrorJob(srcURL, dstURL string, isFake, isRemove, isOverwrite, isWatch bool, excludeOptions []string, olderThan, newerThan string, storageClass string, encKeyDB map[string][]prefixSSEPair) *mirrorJob { +func newMirrorJob(srcURL, dstURL string, isFake, isRemove, isOverwrite, isWatch bool, excludeOptions []string, olderThan, newerThan string, storageClass string, userMetadata map[string]string, encKeyDB map[string][]prefixSSEPair) *mirrorJob { mj := mirrorJob{ trapCh: signalTrap(os.Interrupt, syscall.SIGTERM, syscall.SIGKILL), m: new(sync.Mutex), @@ -585,6 +596,7 @@ func newMirrorJob(srcURL, dstURL string, isFake, isRemove, isOverwrite, isWatch olderThan: olderThan, newerThan: newerThan, storageClass: storageClass, + userMetadata: userMetadata, encKeyDB: encKeyDB, statusCh: make(chan URLs), watcher: NewWatcher(UTCNow()), @@ -638,6 +650,14 @@ func runMirror(srcURL, dstURL string, ctx *cli.Context, encKeyDB map[string][]pr isOverwrite = ctx.Bool("overwrite") } + // Parse metadata. + userMetaMap := make(map[string]string) + if ctx.String("attr") != "" { + var err *probe.Error + userMetaMap, err = getMetaDataEntry(ctx.String("attr")) + fatalIf(err, "Unable to parse attribute %v", ctx.String("attr")) + } + // Create a new mirror job and execute it mj := newMirrorJob(srcURL, dstURL, ctx.Bool("fake"), @@ -648,6 +668,7 @@ func runMirror(srcURL, dstURL string, ctx *cli.Context, encKeyDB map[string][]pr ctx.String("older-than"), ctx.String("newer-than"), ctx.String("storage-class"), + userMetaMap, encKeyDB) srcClt, err := newClient(srcURL) diff --git a/cmd/mirror-url.go b/cmd/mirror-url.go index cc012f07..f17d00c1 100644 --- a/cmd/mirror-url.go +++ b/cmd/mirror-url.go @@ -56,7 +56,7 @@ func checkMirrorSyntax(ctx *cli.Context, encKeyDB map[string][]prefixSSEPair) { /****** Generic rules *******/ if !ctx.Bool("watch") { - c, srcContent, err := url2Stat(srcURL, false, encKeyDB) + _, srcContent, err := url2Stat(srcURL, false, encKeyDB) // incomplete uploads are not necessary for copy operation, no need to verify for them. isIncomplete := false if err != nil && !isURLPrefixExists(srcURL, isIncomplete) { @@ -67,11 +67,6 @@ func checkMirrorSyntax(ctx *cli.Context, encKeyDB map[string][]prefixSSEPair) { 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)) } - - // Disallow mirroring a directory to itself - if isURLContains(srcURL, tgtURL, string(c.GetURL().Separator)) { - fatalIf(errInvalidArgument().Trace(), "Mirroring a folder into itself is not allowed.") - } } } @@ -86,7 +81,7 @@ func matchExcludeOptions(excludeOptions []string, srcSuffix string) bool { return false } -func deltaSourceTarget(sourceURL, targetURL string, isFake, isOverwrite, isRemove bool, excludeOptions []string, URLsCh chan<- URLs, encKeyDB map[string][]prefixSSEPair) { +func deltaSourceTarget(sourceURL, targetURL string, isFake, isOverwrite, isRemove, isMetadata bool, excludeOptions []string, URLsCh chan<- URLs, encKeyDB map[string][]prefixSSEPair) { // source and targets are always directories sourceSeparator := string(newClientURL(sourceURL).Separator) if !strings.HasSuffix(sourceURL, sourceSeparator) { @@ -116,7 +111,7 @@ func deltaSourceTarget(sourceURL, targetURL string, isFake, isOverwrite, isRemov } // List both source and target, compare and return values through channel. - for diffMsg := range objectDifference(sourceClnt, targetClnt, sourceURL, targetURL) { + for diffMsg := range objectDifference(sourceClnt, targetClnt, sourceURL, targetURL, isMetadata) { if diffMsg.Error != nil { // Send all errors through the channel URLsCh <- URLs{Error: diffMsg.Error} @@ -140,7 +135,7 @@ func deltaSourceTarget(sourceURL, targetURL string, isFake, isOverwrite, isRemov // No difference, continue. case differInType: URLsCh <- URLs{Error: errInvalidTarget(diffMsg.SecondURL)} - case differInSize, differInTime: + case differInSize, differInTime, differInMetadata: if !isOverwrite && !isFake { // Size or time differs but --overwrite not set. URLsCh <- URLs{Error: errOverWriteNotAllowed(diffMsg.SecondURL)} @@ -187,8 +182,8 @@ func deltaSourceTarget(sourceURL, targetURL string, isFake, isOverwrite, isRemov } // Prepares urls that need to be copied or removed based on requested options. -func prepareMirrorURLs(sourceURL string, targetURL string, isFake, isOverwrite, isRemove bool, excludeOptions []string, encKeyDB map[string][]prefixSSEPair) <-chan URLs { +func prepareMirrorURLs(sourceURL string, targetURL string, isFake, isOverwrite, isRemove, isMetadata bool, excludeOptions []string, encKeyDB map[string][]prefixSSEPair) <-chan URLs { URLsCh := make(chan URLs) - go deltaSourceTarget(sourceURL, targetURL, isFake, isOverwrite, isRemove, excludeOptions, URLsCh, encKeyDB) + go deltaSourceTarget(sourceURL, targetURL, isFake, isOverwrite, isRemove, isMetadata, excludeOptions, URLsCh, encKeyDB) return URLsCh }