From df8bb795bac7fffb7b7fc564d27c6543765d2a21 Mon Sep 17 00:00:00 2001 From: Harshavardhana Date: Sat, 2 May 2020 12:07:21 -0700 Subject: [PATCH] refactor watch mirror for performance (#3196) --- cmd/client-fs.go | 16 +-- cmd/client-s3.go | 219 ++++++++++++++++------------------ cmd/client-url.go | 12 ++ cmd/find.go | 25 ++-- cmd/mirror-main.go | 291 +++++++++++++++++++++------------------------ cmd/watch-main.go | 28 +++-- cmd/watch.go | 16 +-- go.mod | 2 +- go.sum | 4 +- 9 files changed, 300 insertions(+), 313 deletions(-) diff --git a/cmd/client-fs.go b/cmd/client-fs.go index a46c88f8..0f772f3c 100644 --- a/cmd/client-fs.go +++ b/cmd/client-fs.go @@ -127,9 +127,9 @@ func (f *fsClient) Select(expression string, sse encrypt.ServerSide, opts Select // Watches for all fs events on an input path. func (f *fsClient) Watch(params watchParams) (*WatchObject, *probe.Error) { - eventChan := make(chan EventInfo) + eventChan := make(chan []EventInfo) errorChan := make(chan *probe.Error) - doneChan := make(chan bool) + doneChan := make(chan struct{}) // Make the channel buffered to ensure no event is dropped. Notify will drop // an event if the receiver is not able to keep up the sending pace. in, out := PipeChan(1000) @@ -192,24 +192,24 @@ func (f *fsClient) Watch(params watchParams) (*WatchObject, *probe.Error) { // we want files continue } - eventChan <- EventInfo{ + eventChan <- []EventInfo{{ Time: UTCNow().Format(timeFormatFS), Size: i.Size(), Path: event.Path(), Type: EventCreate, - } + }} } else if IsDeleteEvent(event.Event()) { - eventChan <- EventInfo{ + eventChan <- []EventInfo{{ Time: UTCNow().Format(timeFormatFS), Path: event.Path(), Type: EventRemove, - } + }} } else if IsGetEvent(event.Event()) { - eventChan <- EventInfo{ + eventChan <- []EventInfo{{ Time: UTCNow().Format(timeFormatFS), Path: event.Path(), Type: EventAccessed, - } + }} } } }() diff --git a/cmd/client-s3.go b/cmd/client-s3.go index bd670fe8..1e32fddf 100644 --- a/cmd/client-s3.go +++ b/cmd/client-s3.go @@ -226,7 +226,7 @@ var S3New = newFactory() // GetURL get url. func (c *S3Client) GetURL() ClientURL { - return *c.targetURL + return c.targetURL.Clone() } // AddNotificationConfig - Add bucket notification @@ -624,99 +624,83 @@ func (c *S3Client) Select(expression string, sse encrypt.ServerSide, selOpts Sel return reader, nil } -func (c *S3Client) watchOneBucket(bucket, prefix, suffix string, events []string, doneCh chan struct{}, eventChan chan EventInfo, errorChan chan *probe.Error) { - // Start listening on all bucket events. - eventsCh := c.api.ListenBucketNotification(bucket, prefix, suffix, events, doneCh) - for notificationInfo := range eventsCh { - if notificationInfo.Err != nil { - if nErr, ok := notificationInfo.Err.(minio.ErrorResponse); ok && nErr.Code == "APINotSupported" { - errorChan <- probe.NewError(APINotImplemented{ - API: "Watch", - APIType: c.targetURL.Scheme + "://" + c.targetURL.Host, - }) - return - } - errorChan <- probe.NewError(notificationInfo.Err) - } - - for _, record := range notificationInfo.Records { - bucketName := record.S3.Bucket.Name - key, e := url.QueryUnescape(record.S3.Object.Key) - if e != nil { - errorChan <- probe.NewError(e) - continue - } - u := *c.targetURL - u.Path = path.Join(string(u.Separator), bucketName, key) - if strings.HasPrefix(record.EventName, "s3:ObjectCreated:") { - if strings.HasPrefix(record.EventName, "s3:ObjectCreated:Copy") { - eventChan <- EventInfo{ - Time: record.EventTime, - Size: record.S3.Object.Size, - UserMetadata: record.S3.Object.UserMetadata, - Path: u.String(), - Type: EventCreateCopy, - Host: record.Source.Host, - Port: record.Source.Port, - UserAgent: record.Source.UserAgent, - } - } else if strings.HasPrefix(record.EventName, "s3:ObjectCreated:PutRetention") { - eventChan <- EventInfo{ - Time: record.EventTime, - Size: record.S3.Object.Size, - UserMetadata: record.S3.Object.UserMetadata, - Path: u.String(), - Type: EventCreatePutRetention, - Host: record.Source.Host, - Port: record.Source.Port, - UserAgent: record.Source.UserAgent, - } - } else { - eventChan <- EventInfo{ - Time: record.EventTime, - Size: record.S3.Object.Size, - UserMetadata: record.S3.Object.UserMetadata, - Path: u.String(), - Type: EventCreate, - Host: record.Source.Host, - Port: record.Source.Port, - UserAgent: record.Source.UserAgent, - } - } - } else if strings.HasPrefix(record.EventName, "s3:ObjectRemoved:") { - eventChan <- EventInfo{ - Time: record.EventTime, - Path: u.String(), - Type: EventRemove, - Host: record.Source.Host, - Port: record.Source.Port, - UserAgent: record.Source.UserAgent, - } - } else if record.EventName == minio.ObjectAccessedGet { - eventChan <- EventInfo{ +func (c *S3Client) notificationToEventsInfo(ninfo minio.NotificationInfo) []EventInfo { + var eventsInfo = make([]EventInfo, len(ninfo.Records)) + for i, record := range ninfo.Records { + bucketName := record.S3.Bucket.Name + u := c.targetURL.Clone() + u.Path = path.Join(string(u.Separator), bucketName, record.S3.Object.Key) + if strings.HasPrefix(record.EventName, "s3:ObjectCreated:") { + if strings.HasPrefix(record.EventName, "s3:ObjectCreated:Copy") { + eventsInfo[i] = EventInfo{ Time: record.EventTime, Size: record.S3.Object.Size, UserMetadata: record.S3.Object.UserMetadata, Path: u.String(), - Type: EventAccessedRead, + Type: EventCreateCopy, Host: record.Source.Host, Port: record.Source.Port, UserAgent: record.Source.UserAgent, } - } else if record.EventName == minio.ObjectAccessedHead { - eventChan <- EventInfo{ + } else if strings.HasPrefix(record.EventName, "s3:ObjectCreated:PutRetention") { + eventsInfo[i] = EventInfo{ Time: record.EventTime, Size: record.S3.Object.Size, UserMetadata: record.S3.Object.UserMetadata, Path: u.String(), - Type: EventAccessedStat, + Type: EventCreatePutRetention, Host: record.Source.Host, Port: record.Source.Port, UserAgent: record.Source.UserAgent, } + } else { + eventsInfo[i] = EventInfo{ + Time: record.EventTime, + Size: record.S3.Object.Size, + UserMetadata: record.S3.Object.UserMetadata, + Path: u.String(), + Type: EventCreate, + Host: record.Source.Host, + Port: record.Source.Port, + UserAgent: record.Source.UserAgent, + } + } + } else if strings.HasPrefix(record.EventName, "s3:ObjectRemoved:") { + eventsInfo[i] = EventInfo{ + Time: record.EventTime, + Size: record.S3.Object.Size, + UserMetadata: record.S3.Object.UserMetadata, + Path: u.String(), + Type: EventRemove, + Host: record.Source.Host, + Port: record.Source.Port, + UserAgent: record.Source.UserAgent, + } + } else if record.EventName == minio.ObjectAccessedGet { + eventsInfo[i] = EventInfo{ + Time: record.EventTime, + Size: record.S3.Object.Size, + UserMetadata: record.S3.Object.UserMetadata, + Path: u.String(), + Type: EventAccessedRead, + Host: record.Source.Host, + Port: record.Source.Port, + UserAgent: record.Source.UserAgent, + } + } else if record.EventName == minio.ObjectAccessedHead { + eventsInfo[i] = EventInfo{ + Time: record.EventTime, + Size: record.S3.Object.Size, + UserMetadata: record.S3.Object.UserMetadata, + Path: u.String(), + Type: EventAccessedStat, + Host: record.Source.Host, + Port: record.Source.Port, + UserAgent: record.Source.UserAgent, } } } + return eventsInfo } // Watch - Start watching on all bucket events for a given account ID. @@ -760,33 +744,36 @@ func (c *S3Client) Watch(params watchParams) (*WatchObject, *probe.Error) { } wo := &WatchObject{ - eventInfoChan: make(chan EventInfo), + eventInfoChan: make(chan []EventInfo), errorChan: make(chan *probe.Error), - doneChan: make(chan bool), + doneChan: make(chan struct{}), } - // A done channel for each bucket listening API call - doneChs := make([]chan struct{}, len(buckets)) - for i := range doneChs { - doneChs[i] = make(chan struct{}) - } - - go func() { - // Stop all listening bucket API calls when - // receiving the main done call - <-wo.doneChan - for i := range doneChs { - close(doneChs[i]) - } - }() - var wg sync.WaitGroup - for i, bucket := range buckets { - wg.Add(1) - go func(bucket string, doneCh chan struct{}) { - c.watchOneBucket(bucket, params.prefix, params.suffix, events, doneCh, wo.Events(), wo.Errors()) - wg.Done() - }(bucket, doneChs[i]) + 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(bucket, params.prefix, params.suffix, events, wo.doneChan) + for notificationInfo := range eventsCh { + if notificationInfo.Err != nil { + var perr *probe.Error + if nErr, ok := notificationInfo.Err.(minio.ErrorResponse); ok && nErr.Code == "APINotSupported" { + 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) + } + } + }() } go func() { @@ -1326,7 +1313,7 @@ func (c *S3Client) statIncompleteUpload(bucket, object string) (*ClientContent, } if objectMultipartInfo.Key == object { - objectMetadata.URL = *c.targetURL + objectMetadata.URL = c.targetURL.Clone() objectMetadata.Time = objectMultipartInfo.Initiated objectMetadata.Size = objectMultipartInfo.Size objectMetadata.Type = os.FileMode(0664) @@ -1335,7 +1322,7 @@ func (c *S3Client) statIncompleteUpload(bucket, object string) (*ClientContent, } if strings.HasSuffix(objectMultipartInfo.Key, string(c.targetURL.Separator)) { - objectMetadata.URL = *c.targetURL + objectMetadata.URL = c.targetURL.Clone() objectMetadata.Type = os.ModeDir objectMetadata.Metadata = map[string]string{} return objectMetadata, nil @@ -1404,7 +1391,7 @@ func (c *S3Client) Stat(isIncomplete, isPreserve bool, sse encrypt.ServerSide) ( return nil, probe.NewError(objectStat.Err) } if strings.HasSuffix(objectStat.Key, string(c.targetURL.Separator)) { - objectMetadata.URL = *c.targetURL + objectMetadata.URL = c.targetURL.Clone() objectMetadata.Type = os.ModeDir return objectMetadata, nil } @@ -1437,7 +1424,7 @@ func (c *S3Client) getObjectStat(bucket, object string, opts minio.StatObjectOpt } return nil, probe.NewError(e) } - objectMetadata.URL = *c.targetURL + objectMetadata.URL = c.targetURL.Clone() objectMetadata.Time = objectStat.LastModified objectMetadata.Size = objectStat.Size objectMetadata.ETag = objectStat.ETag @@ -1593,7 +1580,7 @@ func (c *S3Client) listIncompleteInRoutine(contentCh chan *ClientContent) { return } content := &ClientContent{} - url := *c.targetURL + url := c.targetURL.Clone() // Join bucket with - incoming object key. url.Path = c.joinPath(bucket.Name, object.Key) switch { @@ -1621,7 +1608,7 @@ func (c *S3Client) listIncompleteInRoutine(contentCh chan *ClientContent) { return } content := &ClientContent{} - url := *c.targetURL + url := c.targetURL.Clone() // Join bucket with - incoming object key. url.Path = c.joinPath(b, object.Key) switch { @@ -1663,7 +1650,7 @@ func (c *S3Client) listIncompleteRecursiveInRoutine(contentCh chan *ClientConten } return } - url := *c.targetURL + url := c.targetURL.Clone() url.Path = c.joinPath(bucket.Name, object.Key) content := &ClientContent{} content.URL = url @@ -1682,7 +1669,7 @@ func (c *S3Client) listIncompleteRecursiveInRoutine(contentCh chan *ClientConten } return } - url := *c.targetURL + url := c.targetURL.Clone() // Join bucket and incoming object key. url.Path = c.joinPath(b, object.Key) content := &ClientContent{} @@ -1699,7 +1686,7 @@ func (c *S3Client) listIncompleteRecursiveInRoutine(contentCh chan *ClientConten func (c *S3Client) objectMultipartInfo2ClientContent(bucket string, entry minio.ObjectMultipartInfo) ClientContent { content := ClientContent{} - url := *c.targetURL + url := c.targetURL.Clone() // Join bucket and incoming object key. url.Path = c.joinPath(bucket, entry.Key) content.URL = url @@ -1726,7 +1713,7 @@ func (c *S3Client) listIncompleteRecursiveInRoutineDirOpt(contentCh chan *Client isRecursive := false for entry := range c.api.ListIncompleteUploads(bucket, object, isRecursive, nil) { if entry.Err != nil { - url := *c.targetURL + url := c.targetURL.Clone() url.Path = c.joinPath(bucket, object) contentCh <- &ClientContent{URL: url, Err: probe.NewError(entry.Err)} @@ -1793,7 +1780,7 @@ func (c *S3Client) listIncompleteRecursiveInRoutineDirOpt(contentCh chan *Client } for _, bucket := range buckets { if allBuckets { - url := *c.targetURL + url := c.targetURL.Clone() url.Path = c.joinPath(bucket.Name) cContent = &ClientContent{ URL: url, @@ -1825,7 +1812,7 @@ func (c *S3Client) joinPath(bucket string, objects ...string) string { // Convert objectInfo to ClientContent func (c *S3Client) objectInfo2ClientContent(bucket string, entry minio.ObjectInfo) *ClientContent { content := &ClientContent{} - url := *c.targetURL + url := c.targetURL.Clone() // Join bucket and incoming object key. url.Path = c.joinPath(bucket, entry.Key) content.URL = url @@ -1860,7 +1847,7 @@ func (c *S3Client) bucketStat(bucket string) (*ClientContent, *probe.Error) { if !exists { return nil, probe.NewError(BucketDoesNotExist{Bucket: bucket}) } - return &ClientContent{URL: *c.targetURL, Time: time.Unix(0, 0), Type: os.ModeDir}, nil + return &ClientContent{URL: c.targetURL.Clone(), Time: time.Unix(0, 0), Type: os.ModeDir}, nil } // Recursively lists objects. @@ -1873,7 +1860,7 @@ func (c *S3Client) listRecursiveInRoutineDirOpt(contentCh chan *ClientContent, d isRecursive := false for entry := range c.listObjectWrapper(bucket, object, isRecursive, nil, metadata) { if entry.Err != nil { - url := *c.targetURL + url := c.targetURL.Clone() url.Path = c.joinPath(bucket, object) contentCh <- &ClientContent{URL: url, Err: probe.NewError(entry.Err)} @@ -1940,7 +1927,7 @@ func (c *S3Client) listRecursiveInRoutineDirOpt(contentCh chan *ClientContent, d for _, bucket := range buckets { if allBuckets { - url := *c.targetURL + url := c.targetURL.Clone() url.Path = c.joinPath(bucket.Name) cContent = &ClientContent{ URL: url, @@ -1974,7 +1961,7 @@ func (c *S3Client) listInRoutine(contentCh chan *ClientContent, metadata bool) { return } for _, bucket := range buckets { - url := *c.targetURL + url := c.targetURL.Clone() url.Path = c.joinPath(bucket.Name) content := &ClientContent{} content.URL = url @@ -2046,7 +2033,7 @@ func (c *S3Client) listRecursiveInRoutine(contentCh chan *ClientContent, metadat return } content := &ClientContent{} - objectURL := *c.targetURL + objectURL := c.targetURL.Clone() objectURL.Path = c.joinPath(bucket.Name, object.Key) content.URL = objectURL content.StorageClass = object.StorageClass @@ -2072,7 +2059,7 @@ func (c *S3Client) listRecursiveInRoutine(contentCh chan *ClientContent, metadat return } content := &ClientContent{} - url := *c.targetURL + url := c.targetURL.Clone() // Join bucket and incoming object key. url.Path = c.joinPath(b, object.Key) content.URL = url diff --git a/cmd/client-url.go b/cmd/client-url.go index 061efdc7..b70945e9 100644 --- a/cmd/client-url.go +++ b/cmd/client-url.go @@ -132,6 +132,18 @@ func joinURLs(url1, url2 *ClientURL) *ClientURL { return url1 } +// Clone the url into a new object. +func (u ClientURL) Clone() ClientURL { + return ClientURL{ + Type: u.Type, + Scheme: u.Scheme, + Host: u.Host, + Path: u.Path, + SchemeSeparator: u.SchemeSeparator, + Separator: u.Separator, + } +} + // String convert URL into its canonical form. func (u ClientURL) String() string { var buf bytes.Buffer diff --git a/cmd/find.go b/cmd/find.go index 61b5900a..cd379058 100644 --- a/cmd/find.go +++ b/cmd/find.go @@ -150,23 +150,24 @@ func watchFind(ctx *findContext) { console.Println() close(watchObj.doneChan) return - case event, ok := <-watchObj.Events(): + case events, ok := <-watchObj.Events(): if !ok { return } - time, e := time.Parse(time.RFC3339, event.Time) - if e != nil { - errorIf(probe.NewError(e).Trace(event.Time), "Unable to parse event time.") - continue + for _, event := range events { + time, e := time.Parse(time.RFC3339, event.Time) + if e != nil { + errorIf(probe.NewError(e).Trace(event.Time), "Unable to parse event time.") + continue + } + + find(ctx, contentMessage{ + Key: getAliasedPath(ctx, event.Path), + Time: time, + Size: event.Size, + }) } - - find(ctx, contentMessage{ - Key: getAliasedPath(ctx, event.Path), - Time: time, - Size: event.Size, - }) - case err, ok := <-watchObj.Errors(): if !ok { return diff --git a/cmd/mirror-main.go b/cmd/mirror-main.go index fd9da9db..ddd11b90 100644 --- a/cmd/mirror-main.go +++ b/cmd/mirror-main.go @@ -31,6 +31,7 @@ import ( "github.com/minio/cli" json "github.com/minio/mc/pkg/colorjson" "github.com/minio/mc/pkg/probe" + "github.com/minio/minio-go/v6/pkg/encrypt" "github.com/minio/minio/pkg/console" ) @@ -276,6 +277,36 @@ func (mj *mirrorJob) doRemove(sURLs URLs) URLs { return sURLs.WithError(nil) } +// doMirror - Mirror an object to multiple destination. URLs status contains a copy of sURLs and error if any. +func (mj *mirrorJob) doMirrorWatch(ctx context.Context, targetPath string, tgtSSE encrypt.ServerSide, sURLs URLs) URLs { + shouldQueue := false + if !mj.isOverwrite && !mj.multiMasterEnable { + targetClient, err := newClient(targetPath) + if err != nil { + // cannot create targetclient + return sURLs.WithError(err) + } + _, err = targetClient.Stat(false, false, tgtSSE) + if err == nil { + if !sURLs.SourceContent.Retention { + return sURLs.WithError(probe.NewError(ObjectAlreadyExists{})) + } + } // doesn't exist + shouldQueue = true + } + if shouldQueue || mj.isOverwrite || mj.multiMasterEnable { + // adjust total, because we want to show progress of + // the item still queued to be copied. + mj.status.Add(sURLs.SourceContent.Size) + mj.status.SetTotal(mj.status.Get()).Update() + mj.status.AddCounts(1) + sURLs.TotalSize = mj.status.Get() + sURLs.TotalCount = mj.status.GetCounts() + return mj.doMirror(ctx, sURLs) + } + return sURLs.WithError(probe.NewError(ObjectAlreadyExists{})) +} + // doMirror - Mirror an object to multiple destination. URLs status contains a copy of sURLs and error if any. func (mj *mirrorJob) doMirror(ctx context.Context, sURLs URLs) URLs { @@ -377,173 +408,125 @@ func (mj *mirrorJob) monitorMirrorStatus() (errDuringMirror bool) { return } +func (mj *mirrorJob) watchMirrorEvents(ctx context.Context, events []EventInfo) { + for _, event := range events { + // It will change the expanded alias back to the alias + // again, by replacing the sourceUrlFull with the sourceAlias. + // This url will be used to mirror. + sourceAlias, sourceURLFull, _ := mustExpandAlias(mj.sourceURL) + + // If the passed source URL points to fs, fetch the absolute src path + // to correctly calculate targetPath + if sourceAlias == "" { + tmpSrcURL, err := filepath.Abs(sourceURLFull) + if err == nil { + sourceURLFull = tmpSrcURL + } + } + 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):] + } else if runtime.GOOS == "windows" { + // Shared folder as source URL and if event path is an absolute path. + eventPath = getEventPathURLWin(mj.sourceURL, eventPath) + } + + sourceURL := newClientURL(eventPath) + + // build target path, it is the relative of the eventPath with the sourceUrl + // joined to the targetURL. + sourceSuffix := strings.TrimPrefix(eventPath, sourceURLFull) + //Skip the object, if it matches the Exclude options provided + if matchExcludeOptions(mj.excludeOptions, sourceSuffix) { + continue + } + + targetPath := urlJoinPath(mj.targetURL, sourceSuffix) + + // newClient needs the unexpanded path, newCLientURL needs the expanded path + targetAlias, expandedTargetPath, _ := mustExpandAlias(targetPath) + targetURL := newClientURL(expandedTargetPath) + tgtSSE := getSSE(targetPath, mj.encKeyDB[targetAlias]) + + if (event.Type == EventCreate) || + (event.Type == EventCreateCopy) || + (event.Type == EventCreatePutRetention) { + sourceModTime, _ := time.Parse(time.RFC3339Nano, event.Time) + mirrorURL := URLs{ + SourceAlias: sourceAlias, + SourceContent: &ClientContent{ + URL: *sourceURL, + Retention: event.Type == EventCreatePutRetention, + Size: event.Size, + Time: sourceModTime, + Metadata: event.UserMetadata, + }, + TargetAlias: targetAlias, + TargetContent: &ClientContent{URL: *targetURL}, + MD5: mj.md5, + DisableMultipart: mj.disableMultipart, + encKeyDB: mj.encKeyDB, + } + if mj.multiMasterEnable && + mirrorURL.SourceContent.Metadata[multiMasterSourceModTimeKey] != "" { + // If source has multi-master attributes, it means that the + // object was uploaded by "mc mirror", hence ignore the event + // to avoid copying it. + continue + } + mj.queueCh <- func() URLs { + return mj.doMirrorWatch(ctx, targetPath, tgtSSE, mirrorURL) + } + } else if event.Type == EventRemove { + if strings.Contains(event.UserAgent, uaMirrorAppName) { + continue + } + mirrorURL := URLs{ + SourceAlias: sourceAlias, + SourceContent: nil, + TargetAlias: targetAlias, + TargetContent: &ClientContent{URL: *targetURL}, + MD5: mj.md5, + DisableMultipart: mj.disableMultipart, + encKeyDB: mj.encKeyDB, + } + mirrorURL.TotalCount = mj.status.GetCounts() + mirrorURL.TotalSize = mj.status.Get() + if mirrorURL.TargetContent != nil && (mj.isRemove || mj.multiMasterEnable) { + mj.queueCh <- func() URLs { + return mj.doRemove(mirrorURL) + } + } + } + } +} + // this goroutine will watch for notifications, and add modified objects to the queue -func (mj *mirrorJob) watchMirror(ctx context.Context, cancelMirror context.CancelFunc, stopParallel func()) { +func (mj *mirrorJob) watchMirror(ctx context.Context, stopParallel func()) { for { select { - case event, ok := <-mj.watcher.Events(): + case events, ok := <-mj.watcher.Events(): if !ok { stopParallel() return } - - // It will change the expanded alias back to the alias - // again, by replacing the sourceUrlFull with the sourceAlias. - // This url will be used to mirror. - sourceAlias, sourceURLFull, _ := mustExpandAlias(mj.sourceURL) - - // If the passed source URL points to fs, fetch the absolute src path - // to correctly calculate targetPath - if sourceAlias == "" { - tmpSrcURL, err := filepath.Abs(sourceURLFull) - if err == nil { - sourceURLFull = tmpSrcURL - } + mj.watchMirrorEvents(ctx, events) + case err, ok := <-mj.watcher.Errors(): + if !ok { + stopParallel() + return } - 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):] - } else if runtime.GOOS == "windows" { - // Shared folder as source URL and if event path is an absolute path. - eventPath = getEventPathURLWin(mj.sourceURL, eventPath) - } - - sourceURL := newClientURL(eventPath) - - // build target path, it is the relative of the eventPath with the sourceUrl - // joined to the targetURL. - sourceSuffix := strings.TrimPrefix(eventPath, sourceURLFull) - //Skip the object, if it matches the Exclude options provided - if matchExcludeOptions(mj.excludeOptions, sourceSuffix) { - continue - } - - targetPath := urlJoinPath(mj.targetURL, sourceSuffix) - - // newClient needs the unexpanded path, newCLientURL needs the expanded path - targetAlias, expandedTargetPath, _ := mustExpandAlias(targetPath) - targetURL := newClientURL(expandedTargetPath) - tgtSSE := getSSE(targetPath, mj.encKeyDB[targetAlias]) - - if (event.Type == EventCreate) || - (event.Type == EventCreateCopy) || - (event.Type == EventCreatePutRetention) { - sourceModTime, _ := time.Parse(time.RFC3339Nano, event.Time) - mirrorURL := URLs{ - SourceAlias: sourceAlias, - SourceContent: &ClientContent{ - URL: *sourceURL, - Retention: event.Type == EventCreatePutRetention, - Size: event.Size, - Time: sourceModTime, - Metadata: event.UserMetadata, - }, - TargetAlias: targetAlias, - TargetContent: &ClientContent{URL: *targetURL}, - MD5: mj.md5, - DisableMultipart: mj.disableMultipart, - encKeyDB: mj.encKeyDB, - } - if mj.multiMasterEnable && - mirrorURL.SourceContent.Metadata[multiMasterSourceModTimeKey] != "" { - // If source has multi-master attributes, it means that the - // object was uploaded by "mc mirror", hence ignore the event - // to avoid copying it. - continue - } - if mirrorURL.SourceContent.Size == 0 && mirrorURL.SourceContent.Retention { - targetClient, err := newClient(targetPath) - if err != nil { - // cannot create targetclient - mj.statusCh <- mirrorURL.WithError(err) - return - } - shouldQueue := false - if !mj.isOverwrite { - _, err = targetClient.Stat(false, false, tgtSSE) - if err == nil { - continue - } // doesn't exist - shouldQueue = true - } - if shouldQueue || mj.isOverwrite || mj.multiMasterEnable { - // adjust total, because we want to show progress of - // the item still queued to be copied. - mj.status.Add(mirrorURL.SourceContent.Size) - mj.status.SetTotal(mj.status.Get()).Update() - mj.status.AddCounts(1) - mirrorURL.TotalSize = mj.status.Get() - mirrorURL.TotalCount = mj.status.GetCounts() - mj.queueCh <- func() URLs { - return mj.doMirror(ctx, mirrorURL) - } - } - continue - } - shouldQueue := false - if !mj.isOverwrite && !mj.multiMasterEnable { - targetClient, err := newClient(targetPath) - if err != nil { - // cannot create targetclient - mj.queueCh <- func() URLs { - return mirrorURL.WithError(err) - } - return - } - _, err = targetClient.Stat(false, false, tgtSSE) - if err == nil { - if mirrorURL.SourceContent.Retention { - shouldQueue = true - } else { - continue - } - } // doesn't exist - shouldQueue = true - } - if shouldQueue || mj.isOverwrite || mj.multiMasterEnable { - // adjust total, because we want to show progress - // of the itemj stiil queued to be copied. - mj.status.Add(mirrorURL.SourceContent.Size) - mj.status.SetTotal(mj.status.Get()).Update() - mj.status.AddCounts(1) - mirrorURL.TotalSize = mj.status.Get() - mirrorURL.TotalCount = mj.status.GetCounts() - mj.queueCh <- func() URLs { - return mj.doMirror(ctx, mirrorURL) - } - } - } else if event.Type == EventRemove { - if strings.Contains(event.UserAgent, uaMirrorAppName) { - continue - } - mirrorURL := URLs{ - SourceAlias: sourceAlias, - SourceContent: nil, - TargetAlias: targetAlias, - TargetContent: &ClientContent{URL: *targetURL}, - MD5: mj.md5, - DisableMultipart: mj.disableMultipart, - encKeyDB: mj.encKeyDB, - } - mirrorURL.TotalCount = mj.status.GetCounts() - mirrorURL.TotalSize = mj.status.Get() - if mirrorURL.TargetContent != nil && (mj.isRemove || mj.multiMasterEnable) { - mj.queueCh <- func() URLs { - return mj.doRemove(mirrorURL) - } - } - } - - case err := <-mj.watcher.Errors(): switch err.ToGoError().(type) { case APINotImplemented: errorIf(err.Trace(), "Unable to Watch on source, perhaps source doesn't support Watching for events") return } - mj.queueCh <- func() URLs { - return URLs{Error: err} + if err != nil { + mj.queueCh <- func() URLs { + return URLs{Error: err} + } } case <-globalContext.Done(): stopParallel() @@ -631,7 +614,7 @@ func (mj *mirrorJob) mirror(ctx context.Context, cancelMirror context.CancelFunc mj.parallel.wait() cancelMirror() } - mj.watchMirror(ctx, cancelMirror, stopParallel) + mj.watchMirror(ctx, stopParallel) }() } diff --git a/cmd/watch-main.go b/cmd/watch-main.go index 9741be90..9392c028 100644 --- a/cmd/watch-main.go +++ b/cmd/watch-main.go @@ -178,25 +178,29 @@ func mainWatch(ctx *cli.Context) error { // Signal received we are done. close(wo.doneChan) return - case event, ok := <-wo.Events(): + case events, ok := <-wo.Events(): if !ok { return } - msg := watchMessage{} - msg.Event.Path = event.Path - msg.Event.Size = event.Size - msg.Event.Time = event.Time - msg.Event.Type = event.Type - msg.Source.Host = event.Host - msg.Source.Port = event.Port - msg.Source.UserAgent = event.UserAgent - printMsg(msg) + for _, event := range events { + msg := watchMessage{} + msg.Event.Path = event.Path + msg.Event.Size = event.Size + msg.Event.Time = event.Time + msg.Event.Type = event.Type + msg.Source.Host = event.Host + msg.Source.Port = event.Port + msg.Source.UserAgent = event.UserAgent + printMsg(msg) + } case err, ok := <-wo.Errors(): if !ok { return } - errorIf(err, "Unable to watch for events.") - return + if err != nil { + errorIf(err, "Unable to watch for events.") + return + } } } }() diff --git a/cmd/watch.go b/cmd/watch.go index 127feaad..c5f306a9 100644 --- a/cmd/watch.go +++ b/cmd/watch.go @@ -68,15 +68,15 @@ type watchParams struct { // WatchObject captures watch channels to read and listen on. type WatchObject struct { // eventInfo will be put on this chan - eventInfoChan chan EventInfo + eventInfoChan chan []EventInfo // errors will be put on this chan errorChan chan *probe.Error // will stop the watcher goroutines - doneChan chan bool + doneChan chan struct{} } // Events returns the chan receiving events -func (w *WatchObject) Events() chan EventInfo { +func (w *WatchObject) Events() chan []EventInfo { return w.eventInfoChan } @@ -100,7 +100,7 @@ type Watcher struct { // all error will be added to this chan errorChan chan *probe.Error // all events will be added to this chan - eventInfoChan chan EventInfo + eventInfoChan chan []EventInfo // array of watchers joined o []*WatchObject @@ -114,7 +114,7 @@ func NewWatcher(sessionStartTime time.Time) *Watcher { return &Watcher{ sessionStartTime: sessionStartTime, errorChan: make(chan *probe.Error), - eventInfoChan: make(chan EventInfo), + eventInfoChan: make(chan []EventInfo), o: []*WatchObject{}, } } @@ -125,7 +125,7 @@ func (w *Watcher) Errors() chan *probe.Error { } // Events returns a channel which will receive events -func (w *Watcher) Events() chan EventInfo { +func (w *Watcher) Events() chan []EventInfo { return w.eventInfoChan } @@ -174,11 +174,11 @@ func (w *Watcher) Join(client Client, recursive bool) *probe.Error { for { select { - case event, ok := <-wo.Events(): + case events, ok := <-wo.Events(): if !ok { return } - w.eventInfoChan <- event + w.eventInfoChan <- events case err, ok := <-wo.Errors(): if !ok { return diff --git a/go.mod b/go.mod index ea5da85c..80bf57ef 100644 --- a/go.mod +++ b/go.mod @@ -17,7 +17,7 @@ require ( github.com/mattn/go-runewidth v0.0.5 // indirect github.com/minio/cli v1.22.0 github.com/minio/minio v0.0.0-20200421050159-282c9f790a03 - github.com/minio/minio-go/v6 v6.0.55 + github.com/minio/minio-go/v6 v6.0.56-0.20200502013257-a81c8c13cc3f github.com/minio/sha256-simd v0.1.1 github.com/mitchellh/go-homedir v1.1.0 github.com/pkg/profile v1.3.0 diff --git a/go.sum b/go.sum index e8a47684..0c17b67e 100644 --- a/go.sum +++ b/go.sum @@ -256,8 +256,8 @@ github.com/minio/minio v0.0.0-20200421050159-282c9f790a03 h1:qEWJAXNbLp1Uovs9gzP github.com/minio/minio v0.0.0-20200421050159-282c9f790a03/go.mod h1:zBua5AiljGs1Irdl2XEyiJjvZVCVDIG8gjozzRBcVlw= github.com/minio/minio-go/v6 v6.0.53 h1:8jzpwiOzZ5Iz7/goFWqNZRICbyWYShbb5rARjrnSCNI= github.com/minio/minio-go/v6 v6.0.53/go.mod h1:DIvC/IApeHX8q1BAMVCXSXwpmrmM+I+iBvhvztQorfI= -github.com/minio/minio-go/v6 v6.0.55 h1:Hqm41952DdRNKXM+6hCnPXCsHCYSgLf03iuYoxJG2Wk= -github.com/minio/minio-go/v6 v6.0.55/go.mod h1:KQMM+/44DSlSGSQWSfRrAZ12FVMmpWNuX37i2AX0jfI= +github.com/minio/minio-go/v6 v6.0.56-0.20200502013257-a81c8c13cc3f h1:ifHrI8+exqLi5RztIWWKS5k+Wu+W7DJisVXwNaCH2zs= +github.com/minio/minio-go/v6 v6.0.56-0.20200502013257-a81c8c13cc3f/go.mod h1:KQMM+/44DSlSGSQWSfRrAZ12FVMmpWNuX37i2AX0jfI= github.com/minio/parquet-go v0.0.0-20200414234858-838cfa8aae61/go.mod h1:4trzEJ7N1nBTd5Tt7OCZT5SEin+WiAXpdJ/WgPkESA8= github.com/minio/sha256-simd v0.1.1 h1:5QHSlgo3nt5yKOJrC7W8w7X+NFl8cMPZm96iu8kKUJU= github.com/minio/sha256-simd v0.1.1/go.mod h1:B5e1o+1/KgNmWrSQK08Y6Z1Vb5pwIktudl0J58iy0KM=