make sure active/active enables watch by default (#3271)

- effectively use context everywhere
- effectively look for source-mtime in all
  variations
- `mc diff` should do metadata diff as well
This commit is contained in:
Harshavardhana
2020-06-23 16:57:00 -07:00
parent cfea4fdc75
commit 9ebde383d4
6 changed files with 128 additions and 86 deletions
+26 -13
View File
@@ -381,11 +381,11 @@ func getAllMetadata(ctx context.Context, sourceAlias, sourceURLStr string, srcSS
}
for k, v := range st.Metadata {
metadata[k] = v
metadata[http.CanonicalHeaderKey(k)] = v
}
for k, v := range urls.TargetContent.UserMetadata {
metadata[k] = v
metadata[http.CanonicalHeaderKey(k)] = v
}
return filterMetadata(metadata), nil
@@ -462,21 +462,22 @@ func uploadSourceToTargetURL(ctx context.Context, urls URLs, progress io.Reader,
}
}
// Get metadata from target content as well
for k, v := range urls.TargetContent.Metadata {
metadata[http.CanonicalHeaderKey(k)] = v
}
// Get userMetadata from target content as well
for k, v := range urls.TargetContent.UserMetadata {
metadata[http.CanonicalHeaderKey(k)] = v
}
sourcePath := filepath.ToSlash(sourceURL.Path)
if urls.SourceContent.RetentionEnabled {
err = putTargetRetention(ctx, targetAlias, targetURL.String(), metadata)
return urls.WithError(err.Trace(sourceURL.String()))
}
// Get metadata from target content as well
for k, v := range urls.TargetContent.Metadata {
metadata[k] = v
}
// Get userMetadata from target content as well
for k, v := range urls.TargetContent.UserMetadata {
metadata[k] = v
}
err = copySourceToTargetURL(ctx, targetAlias, targetURL.String(), sourcePath, mode, until,
legalHold, length, progress, srcSSE, tgtSSE, filterMetadata(metadata), urls.DisableMultipart)
} else {
@@ -490,9 +491,20 @@ func uploadSourceToTargetURL(ctx context.Context, urls URLs, progress io.Reader,
}
}
// Get metadata from target content as well
for k, v := range urls.TargetContent.Metadata {
metadata[http.CanonicalHeaderKey(k)] = v
}
// Get userMetadata from target content as well
for k, v := range urls.TargetContent.UserMetadata {
metadata[http.CanonicalHeaderKey(k)] = v
}
err = putTargetRetention(ctx, targetAlias, targetURL.String(), metadata)
return urls.WithError(err.Trace(sourceURL.String()))
}
var reader io.ReadCloser
// Proceed with regular stream copy.
reader, metadata, err = getSourceStream(ctx, sourceAlias, sourceURL.String(), true, srcSSE, preserve)
@@ -503,11 +515,12 @@ func uploadSourceToTargetURL(ctx context.Context, urls URLs, progress io.Reader,
// Get metadata from target content as well
for k, v := range urls.TargetContent.Metadata {
metadata[k] = v
metadata[http.CanonicalHeaderKey(k)] = v
}
// Get userMetadata from target content as well
for k, v := range urls.TargetContent.UserMetadata {
metadata[k] = v
metadata[http.CanonicalHeaderKey(k)] = v
}
if isReadAt(reader) {
+3 -3
View File
@@ -149,7 +149,7 @@ func checkDiffSyntax(ctx context.Context, cliCtx *cli.Context, encKeyDB map[stri
}
// doDiffMain runs the diff.
func doDiffMain(firstURL, secondURL string) error {
func doDiffMain(ctx context.Context, firstURL, secondURL string) error {
// Source and targets are always directories
sourceSeparator := string(newClientURL(firstURL).Separator)
if !strings.HasSuffix(firstURL, sourceSeparator) {
@@ -177,7 +177,7 @@ func doDiffMain(firstURL, secondURL string) error {
}
// Diff first and second urls.
for diffMsg := range objectDifference(firstClient, secondClient, firstURL, secondURL, false) {
for diffMsg := range objectDifference(ctx, firstClient, secondClient, firstURL, secondURL, true) {
if diffMsg.Error != nil {
errorIf(diffMsg.Error, "Unable to calculate objects difference.")
// Ignore error and proceed to next object.
@@ -214,5 +214,5 @@ func mainDiff(cliCtx *cli.Context) error {
firstURL := URLs.Get(0)
secondURL := URLs.Get(1)
return doDiffMain(firstURL, secondURL)
return doDiffMain(ctx, firstURL, secondURL)
}
+59 -29
View File
@@ -17,6 +17,7 @@
package cmd
import (
"context"
"strings"
"time"
"unicode/utf8"
@@ -63,18 +64,20 @@ func (d differType) String() string {
const activeActiveSourceModTimeKey = "X-Amz-Meta-Mm-Source-Mtime"
func oldestNonNullTime(t1, t2 time.Time) time.Time {
if t1.IsZero() {
return t2
func getSourceModTimeKey(metadata map[string]string) string {
if metadata[activeActiveSourceModTimeKey] != "" {
return metadata[activeActiveSourceModTimeKey]
}
if t2.IsZero() {
return t1
if metadata[strings.ToLower(activeActiveSourceModTimeKey)] != "" {
return metadata[strings.ToLower(activeActiveSourceModTimeKey)]
}
if t1.Before(t2) {
return t1
if metadata[strings.ToLower("Mm-Source-Mtime")] != "" {
return metadata[strings.ToLower("Mm-Source-Mtime")]
}
return t2
if metadata["Mm-Source-Mtime"] != "" {
return metadata["Mm-Source-Mtime"]
}
return ""
}
// activeActiveModTimeUpdated tries to calculate if the object copy in the target
@@ -91,18 +94,39 @@ func activeActiveModTimeUpdated(src, dst *ClientContent) bool {
return false
}
_, ok1 := src.UserMetadata[activeActiveSourceModTimeKey]
_, ok2 := dst.UserMetadata[activeActiveSourceModTimeKey]
if !ok1 && !ok2 {
// No multimaster context found, consider src & dst as similar
srcModTime := getSourceModTimeKey(src.UserMetadata)
dstModTime := getSourceModTimeKey(dst.UserMetadata)
if srcModTime == "" && dstModTime == "" {
// No active-active mirror context found, consider src & dst as similar
return false
}
srcOriginLastModified, _ := time.Parse(time.RFC3339Nano, src.UserMetadata[activeActiveSourceModTimeKey])
dstOriginLastModified, _ := time.Parse(time.RFC3339Nano, dst.UserMetadata[activeActiveSourceModTimeKey])
var srcOriginLastModified, dstOriginLastModified time.Time
var err error
if srcModTime != "" {
srcOriginLastModified, err = time.Parse(time.RFC3339Nano, srcModTime)
if err != nil {
// failure to parse source modTime, modTime tampered ignore the file
return false
}
}
if dstModTime != "" {
dstOriginLastModified, err = time.Parse(time.RFC3339Nano, dstModTime)
if err != nil {
// failure to parse source modTime, modTime tampered ignore the file
return false
}
}
srcActualModTime := oldestNonNullTime(src.Time, srcOriginLastModified)
dstActualModTime := oldestNonNullTime(dst.Time, dstOriginLastModified)
srcActualModTime := src.Time
if !srcOriginLastModified.IsZero() && srcOriginLastModified.After(src.Time) {
srcActualModTime = srcOriginLastModified
}
dstActualModTime := dst.Time
if !dstOriginLastModified.IsZero() && dstOriginLastModified.After(dst.Time) {
dstActualModTime = dstOriginLastModified
}
return srcActualModTime.After(dstActualModTime)
}
@@ -112,6 +136,9 @@ func metadataEqual(m1, m2 map[string]string) bool {
if k == activeActiveSourceModTimeKey {
continue
}
if k == strings.ToLower(activeActiveSourceModTimeKey) {
continue
}
if m2[k] != v {
return false
}
@@ -120,6 +147,9 @@ func metadataEqual(m1, m2 map[string]string) bool {
if k == activeActiveSourceModTimeKey {
continue
}
if k == strings.ToLower(activeActiveSourceModTimeKey) {
continue
}
if m1[k] != v {
return false
}
@@ -127,19 +157,19 @@ func metadataEqual(m1, m2 map[string]string) bool {
return true
}
func objectDifference(sourceClnt, targetClnt Client, sourceURL, targetURL string, isMetadata bool) (diffCh chan diffMessage) {
return difference(sourceClnt, targetClnt, sourceURL, targetURL, isMetadata, true, false, DirNone)
func objectDifference(ctx context.Context, sourceClnt, targetClnt Client, sourceURL, targetURL string, isMetadata bool) (diffCh chan diffMessage) {
return difference(ctx, 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, false, true, DirFirst)
func dirDifference(ctx context.Context, sourceClnt, targetClnt Client, sourceURL, targetURL string) (diffCh chan diffMessage) {
return difference(ctx, sourceClnt, targetClnt, sourceURL, targetURL, false, false, true, DirFirst)
}
func differenceInternal(sourceClnt, targetClnt Client, sourceURL, targetURL string, isMetadata bool, isRecursive, returnSimilar bool, dirOpt DirOpt, diffCh chan<- diffMessage) *probe.Error {
func differenceInternal(ctx context.Context, sourceClnt, targetClnt Client, sourceURL, targetURL string, isMetadata bool, isRecursive, returnSimilar bool, dirOpt DirOpt, diffCh chan<- diffMessage) *probe.Error {
// Set default values for listing.
isIncomplete := false // we will not compare any incomplete objects.
srcCh := sourceClnt.List(globalContext, isRecursive, isIncomplete, isMetadata, dirOpt)
tgtCh := targetClnt.List(globalContext, isRecursive, isIncomplete, isMetadata, dirOpt)
srcCh := sourceClnt.List(ctx, isRecursive, isIncomplete, isMetadata, dirOpt)
tgtCh := targetClnt.List(ctx, isRecursive, isIncomplete, isMetadata, dirOpt)
srcCtnt, srcOk := <-srcCh
tgtCtnt, tgtOk := <-tgtCh
@@ -296,17 +326,17 @@ func differenceInternal(sourceClnt, targetClnt Client, sourceURL, targetURL stri
// objectDifference function finds the difference between all objects
// recursively in sorted order from source and target.
func difference(sourceClnt, targetClnt Client, sourceURL, targetURL string, isMetadata bool, isRecursive, returnSimilar bool, dirOpt DirOpt) (diffCh chan diffMessage) {
func difference(ctx context.Context, sourceClnt, targetClnt Client, sourceURL, targetURL string, isMetadata bool, isRecursive, returnSimilar bool, dirOpt DirOpt) (diffCh chan diffMessage) {
diffCh = make(chan diffMessage, 10000)
go func() {
defer close(diffCh)
doneCh := make(chan struct{}, 1)
defer close(doneCh)
retryCtx, cancel := context.WithCancel(ctx)
defer cancel()
for range newRetryTimerContinous(time.Second, time.Second*30, minio.MaxJitter, doneCh) {
err := differenceInternal(sourceClnt, targetClnt, sourceURL, targetURL,
for range newRetryTimerContinous(retryCtx, time.Second, time.Second*30, minio.MaxJitter) {
err := differenceInternal(retryCtx, sourceClnt, targetClnt, sourceURL, targetURL,
isMetadata, isRecursive, returnSimilar, dirOpt, diffCh)
if err != nil {
// handle this specifically for filesystem related errors.
+25 -30
View File
@@ -335,10 +335,11 @@ func (mj *mirrorJob) doMirror(ctx context.Context, sURLs URLs) URLs {
}
if mj.opts.activeActive {
srcModTime := getSourceModTimeKey(sURLs.SourceContent.Metadata)
// If the source object already has source modtime attribute set, then
// use it in target. Otherwise use the S3 modtime instead.
if sURLs.SourceContent.Metadata[activeActiveSourceModTimeKey] != "" {
sURLs.TargetContent.Metadata[activeActiveSourceModTimeKey] = sURLs.SourceContent.Metadata[activeActiveSourceModTimeKey]
if srcModTime != "" {
sURLs.TargetContent.Metadata[activeActiveSourceModTimeKey] = srcModTime
} else {
sURLs.TargetContent.Metadata[activeActiveSourceModTimeKey] = sURLs.SourceContent.Time.Format(time.RFC3339Nano)
}
@@ -465,7 +466,8 @@ func (mj *mirrorJob) watchMirrorEvents(ctx context.Context, events []EventInfo)
encKeyDB: mj.opts.encKeyDB,
}
if mj.opts.activeActive &&
mirrorURL.SourceContent.Metadata[activeActiveSourceModTimeKey] != "" {
(getSourceModTimeKey(mirrorURL.SourceContent.Metadata) != "" ||
getSourceModTimeKey(mirrorURL.SourceContent.UserMetadata) != "") {
// If source has active-active attributes, it means that the
// object was uploaded by "mc mirror", hence ignore the event
// to avoid copying it.
@@ -541,7 +543,7 @@ func (mj *mirrorJob) startMirror(ctx context.Context, cancelMirror context.Cance
mj.m.Lock()
defer mj.m.Unlock()
URLsCh := prepareMirrorURLs(mj.sourceURL, mj.targetURL, mj.opts)
URLsCh := prepareMirrorURLs(ctx, mj.sourceURL, mj.targetURL, mj.opts)
for {
select {
@@ -716,7 +718,7 @@ func getEventPathURLWin(srcURL, eventPath string) string {
}
// runMirror - mirrors all buckets to another S3 server
func runMirror(srcURL, dstURL string, cli *cli.Context, encKeyDB map[string][]prefixSSEPair) bool {
func runMirror(ctx context.Context, cancelMirror context.CancelFunc, srcURL, dstURL string, cli *cli.Context, encKeyDB map[string][]prefixSSEPair) bool {
// This is kept for backward compatibility, `--force` means
// --overwrite.
isOverwrite := cli.Bool("force")
@@ -757,7 +759,7 @@ func runMirror(srcURL, dstURL string, cli *cli.Context, encKeyDB map[string][]pr
isFake: cli.Bool("fake"),
isRemove: cli.Bool("remove"),
isOverwrite: isOverwrite,
isWatch: cli.Bool("watch"),
isWatch: cli.Bool("watch") || cli.Bool("multi-master") || cli.Bool("active-active"),
isMetadata: cli.Bool("a") || cli.Bool("multi-master") || cli.Bool("active-active") || len(userMetadata) > 0,
md5: cli.Bool("md5"),
disableMultipart: cli.Bool("disable-multipart"),
@@ -770,20 +772,12 @@ func runMirror(srcURL, dstURL string, cli *cli.Context, encKeyDB map[string][]pr
activeActive: cli.Bool("multi-master") || cli.Bool("active-active"),
})
go func() {
<-globalContext.Done()
os.Exit(globalErrorExitStatus)
}()
ctx, cancelMirror := context.WithCancel(globalContext)
defer cancelMirror()
if mirrorAllBuckets {
// Synchronize buckets using dirDifference function
for d := range dirDifference(srcClt, dstClt, srcURL, dstURL) {
for d := range dirDifference(ctx, srcClt, dstClt, srcURL, dstURL) {
if d.Error != nil {
if mj.opts.activeActive {
errorIf(d.Error, "Failed to start mirroring.")
errorIf(d.Error, "Failed to start mirroring.. retrying")
return true
}
mj.status.fatalIf(d.Error, "Failed to start mirroring.")
@@ -825,7 +819,7 @@ func runMirror(srcURL, dstURL string, cli *cli.Context, encKeyDB map[string][]pr
// and queue them for copying.
if err := mj.watchURL(ctx, newSrcClt); err != nil {
if mj.opts.activeActive {
errorIf(err, "Failed to start monitoring.")
errorIf(err, "Failed to start monitoring.. retrying")
return true
}
mj.status.fatalIf(err, "Failed to start monitoring.")
@@ -873,14 +867,12 @@ func runMirror(srcURL, dstURL string, cli *cli.Context, encKeyDB map[string][]pr
// and queue them for copying.
if err := mj.watchURL(ctx, srcClt); err != nil {
if mj.opts.activeActive {
errorIf(err, "Failed to start monitoring.")
errorIf(err, "Failed to start monitoring.. retrying")
return true
}
mj.status.fatalIf(err, "Failed to start monitoring.")
}
}
// Start mirroring job
return mj.mirror(ctx, cancelMirror)
}
@@ -913,16 +905,19 @@ func mainMirror(cliCtx *cli.Context) error {
}
}
if cliCtx.Bool("multi-master") || cliCtx.Bool("active-active") {
for {
runMirror(srcURL, tgtURL, cliCtx, encKeyDB)
time.Sleep(time.Second * 2)
for {
select {
case <-ctx.Done():
return exitStatus(globalErrorExitStatus)
default:
if errorDetected := runMirror(ctx, cancelMirror, srcURL, tgtURL, cliCtx, encKeyDB); errorDetected {
if cliCtx.Bool("multi-master") || cliCtx.Bool("active-active") {
time.Sleep(2 * time.Second)
continue
}
return exitStatus(globalErrorExitStatus)
}
return nil
}
}
if errorDetected := runMirror(srcURL, tgtURL, cliCtx, encKeyDB); errorDetected {
return exitStatus(globalErrorExitStatus)
}
return nil
}
+6 -6
View File
@@ -70,9 +70,9 @@ func checkMirrorSyntax(ctx context.Context, cliCtx *cli.Context, encKeyDB map[st
}
/****** Generic rules *******/
if !cliCtx.Bool("watch") {
if !cliCtx.Bool("watch") && !cliCtx.Bool("active-active") && !cliCtx.Bool("multi-master") {
_, srcContent, err := url2Stat(ctx, srcURL, false, encKeyDB)
// incomplete uploads are not necessary for copy operation, no need to verify for them.
// incomplete uploads are not necessary for mirror operation, no need to verify for them.
isIncomplete := false
if err != nil && !isURLPrefixExists(srcURL, isIncomplete) {
errorIf(err.Trace(srcURL), "Unable to stat source `"+srcURL+"`.")
@@ -96,7 +96,7 @@ func matchExcludeOptions(excludeOptions []string, srcSuffix string) bool {
return false
}
func deltaSourceTarget(sourceURL, targetURL string, opts mirrorOptions, URLsCh chan<- URLs) {
func deltaSourceTarget(ctx context.Context, sourceURL, targetURL string, opts mirrorOptions, URLsCh chan<- URLs) {
// source and targets are always directories
sourceSeparator := string(newClientURL(sourceURL).Separator)
if !strings.HasSuffix(sourceURL, sourceSeparator) {
@@ -126,7 +126,7 @@ func deltaSourceTarget(sourceURL, targetURL string, opts mirrorOptions, URLsCh c
}
// List both source and target, compare and return values through channel.
for diffMsg := range objectDifference(sourceClnt, targetClnt, sourceURL, targetURL, opts.isMetadata) {
for diffMsg := range objectDifference(ctx, sourceClnt, targetClnt, sourceURL, targetURL, opts.isMetadata) {
if diffMsg.Error != nil {
// Send all errors through the channel
URLsCh <- URLs{Error: diffMsg.Error}
@@ -208,8 +208,8 @@ type mirrorOptions struct {
}
// Prepares urls that need to be copied or removed based on requested options.
func prepareMirrorURLs(sourceURL string, targetURL string, opts mirrorOptions) <-chan URLs {
func prepareMirrorURLs(ctx context.Context, sourceURL string, targetURL string, opts mirrorOptions) <-chan URLs {
URLsCh := make(chan URLs)
go deltaSourceTarget(sourceURL, targetURL, opts, URLsCh)
go deltaSourceTarget(ctx, sourceURL, targetURL, opts, URLsCh)
return URLsCh
}
+9 -5
View File
@@ -18,6 +18,7 @@
package cmd
import (
"context"
"math/rand"
"sync"
"time"
@@ -51,7 +52,7 @@ func (r *lockedRandSource) Seed(seed int64) {
var random = rand.New(&lockedRandSource{src: rand.NewSource(time.Now().UTC().UnixNano())})
// newRetryTimerContinous creates a timer with exponentially increasing delays forever.
func newRetryTimerContinous(unit time.Duration, cap time.Duration, jitter float64, doneCh chan struct{}) <-chan int {
func newRetryTimerContinous(ctx context.Context, unit time.Duration, cap time.Duration, jitter float64) <-chan int {
attemptCh := make(chan int)
// normalize jitter to the range [0, 1.0]
@@ -86,14 +87,17 @@ func newRetryTimerContinous(unit time.Duration, cap time.Duration, jitter float6
var nextBackoff int
for {
select {
// Attempts starts.
case attemptCh <- nextBackoff:
nextBackoff++
case <-doneCh:
// Stop the routine.
case <-ctx.Done():
return
}
select {
case <-time.After(exponentialBackoffWait(nextBackoff)):
case <-ctx.Done():
return
}
time.Sleep(exponentialBackoffWait(nextBackoff))
}
}()
return attemptCh