From a47c86c54cc6ba303aba6559cc0e763f6941e10b Mon Sep 17 00:00:00 2001 From: Harshavardhana Date: Tue, 16 Aug 2016 14:32:15 -0700 Subject: [PATCH] mirror: Watch() for events based on session time. (#1799) Enable notification if not already set, avoid overriding or append to existing notification set - all of this needs to be done to make this transparent. --- mc/client-fs.go | 6 ++ mc/client-s3.go | 97 +++++++++++++++++-- mc/client.go | 1 + mc/mirror-main.go | 74 +++++++------- mc/watch.go | 39 +++++--- .../minio/minio-go/api-notification.go | 95 ++++++++++-------- .../github.com/minio/minio-go/bucket-cache.go | 15 ++- .../github.com/minio/minio-go/s3-endpoints.go | 2 + vendor/vendor.json | 6 ++ 9 files changed, 238 insertions(+), 97 deletions(-) diff --git a/mc/client-fs.go b/mc/client-fs.go index 935e8d0f..f81ab7c6 100644 --- a/mc/client-fs.go +++ b/mc/client-fs.go @@ -86,6 +86,12 @@ func (f *fsClient) GetURL() clientURL { return *f.PathURL } +// Unwatch - not implemented for fs, on purpose. +func (f *fsClient) Unwatch(params watchParams) *probe.Error { + return nil +} + +// Watches for all fs events on an input path. func (f *fsClient) Watch(params watchParams) (*watchObject, *probe.Error) { eventChan := make(chan Event) errorChan := make(chan *probe.Error) diff --git a/mc/client-s3.go b/mc/client-s3.go index b07b5fa8..bdcf9daa 100644 --- a/mc/client-s3.go +++ b/mc/client-s3.go @@ -23,6 +23,7 @@ import ( "net/http" "net/url" "os" + "path" "path/filepath" "regexp" "strings" @@ -190,16 +191,94 @@ func (c *s3Client) ToogleLambdaNotificationStatus(enable bool, region, accountID return nil } +// Unwatch de-registers all bucket notification events for a given accountID. +func (c *s3Client) Unwatch(params watchParams) *probe.Error { + // Extract bucket and object. + bucket, _ := c.url2BucketAndObject() + if err := isValidBucketName(bucket); err != nil { + return err + } + + // Fetch the bucket location. + location, e := c.api.GetBucketLocation(bucket) + if e != nil { + return probe.NewError(e) + } + + // Fetch any existing bucket notification on the bucket. + nConfig, e := c.api.GetBucketNotification(bucket) + if e != nil { + return probe.NewError(e) + } + + // Construct account ARN. + accountARN := minio.NewArn("minio", "sns", location, params.accountID, "listen") + + // Remove account ARN if any. + nConfig.RemoveTopicByArn(accountARN) + + // Set back the new sets of notifications. + e = c.api.SetBucketNotification(bucket, nConfig) + if e != nil { + return probe.NewError(e) + } + + // Success. + return nil +} + +// Start watching on all bucket events for a given account ID. func (c *s3Client) Watch(params watchParams) (*watchObject, *probe.Error) { eventChan := make(chan Event) errorChan := make(chan *probe.Error) doneChan := make(chan bool) - bucket, _ := c.url2BucketAndObject() + // Extract bucket and object. + bucket, object := c.url2BucketAndObject() if err := isValidBucketName(bucket); err != nil { return nil, err } + // Fetch the bucket location. + location, e := c.api.GetBucketLocation(bucket) + if e != nil { + return nil, probe.NewError(e) + } + + // Fetch any existing bucket notification on the bucket. + nConfig, e := c.api.GetBucketNotification(bucket) + if e != nil { + return nil, probe.NewError(e) + } + + accountARN := minio.NewArn("minio", "sns", location, params.accountID, "listen") + // If there are no SNS topics configured, configure the first one. + shouldSetNotification := len(nConfig.TopicConfigs) == 0 + if !shouldSetNotification { + // Assume we are going to set bucket notification. + shouldSetNotification = true + // We found previously configured SNS topics, validate if current account-id is same. + for _, topicConfig := range nConfig.TopicConfigs { + if topicConfig.Topic == accountARN.String() { + shouldSetNotification = false + break + } + } + } + // Flag set to set the notification. + if shouldSetNotification { + topicConfig := minio.NewNotificationConfig(accountARN) + topicConfig.AddEvents(minio.ObjectCreatedAll, minio.ObjectRemovedAll) + if object != "" { + topicConfig.AddFilterPrefix(object) + } + nConfig.AddTopic(topicConfig) + e = c.api.SetBucketNotification(bucket, nConfig) + if e != nil { + return nil, probe.NewError(e) + } + } + doneCh := make(chan struct{}) // wait for doneChan to close the other channels @@ -211,7 +290,7 @@ func (c *s3Client) Watch(params watchParams) (*watchObject, *probe.Error) { close(errorChan) }() - accountARN := minio.NewArn("minio", "lambda", params.accountRegion, params.accountID, "lambda") + // Start listening on all bucket events. eventsCh := c.api.ListenBucketNotification(bucket, accountARN, doneCh) // wait for events to occur and sent them through the eventChan and errorChan @@ -224,21 +303,25 @@ func (c *s3Client) Watch(params watchParams) (*watchObject, *probe.Error) { for _, record := range notificationInfo.Records { bucketName := record.S3.Bucket.Name - key := record.S3.Object.Key - - source := bucketName + "/" + key + 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:") { eventChan <- Event{ Time: time.Now(), - Path: source, + Path: u.String(), Client: c, Type: EventCreate, } } else if strings.HasPrefix(record.EventName, "s3:ObjectRemoved:") { eventChan <- Event{ Time: time.Now(), - Path: source, + Path: u.String(), Client: c, Type: EventRemove, } diff --git a/mc/client.go b/mc/client.go index ebdf4b1c..acb2446d 100644 --- a/mc/client.go +++ b/mc/client.go @@ -48,6 +48,7 @@ type Client interface { // Watch events Watch(params watchParams) (*watchObject, *probe.Error) + Unwatch(params watchParams) *probe.Error // Delete operations Remove(incomplete bool) *probe.Error diff --git a/mc/mirror-main.go b/mc/mirror-main.go index 326e6e96..fedf1c7d 100644 --- a/mc/mirror-main.go +++ b/mc/mirror-main.go @@ -88,12 +88,14 @@ EXAMPLES: 4. Mirror a bucket from aliased Amazon S3 cloud storage to a local folder use '--force' to overwrite destination. $ mc {{.Name}} --force s3/miniocloud miniocloud-backup - 5. Fake mirror a bucket from Minio cloud storage to a bucket on Amazon S3 cloud storage. - $ mc {{.Name}} --fake play/photos/2014 s3/backup-photos/2014 - - 6. Mirror a bucket from Minio cloud storage to a bucket on Amazon S3 cloud storage and remove any extraneous + 5. Mirror a bucket from Minio cloud storage to a bucket on Amazon S3 cloud storage and remove any extraneous files on Amazon S3 cloud storage. NOTE: '--remove' is only supported with '--force'. $ mc {{.Name}} --force --remove play/photos/2014 s3/backup-photos/2014 + + 6. Continuously mirror a local folder recursively to Minio cloud storage. '--watch' continuously watches for + new objects and uploads them. + $ mc {{.Name}} --force --remove --watch /var/lib/backups play/backups + `, } @@ -133,8 +135,8 @@ type mirrorSession struct { status Status scanBar scanBarFunc - sourceURLs string - targetURL string + sourceURL string + targetURL string } // mirrorMessage container for file mirror messages @@ -303,7 +305,9 @@ func (ms *mirrorSession) startStatus() { case BrokenSymlink, TooManyLevelsSymlink, PathNotFound, PathInsufficientPermission: continue // Handle these specifically for object storage related errors. - case BucketNameEmpty, ObjectMissing, ObjectAlreadyExists, ObjectAlreadyExistsAsDirectory, BucketDoesNotExist, BucketInvalid, ObjectOnGlacier: + case BucketNameEmpty, ObjectMissing, ObjectAlreadyExists: + continue + case ObjectAlreadyExistsAsDirectory, BucketDoesNotExist, BucketInvalid, ObjectOnGlacier: continue } @@ -391,21 +395,15 @@ func (ms *mirrorSession) watch() { // this code seems complicated, 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(ms.sourceURLs) + sourceAlias, sourceURLFull, _ := mustExpandAlias(ms.sourceURL) sourceURL := newClientURL(event.Path) - aliasedPath := strings.Replace(event.Path, sourceURLFull, ms.sourceURLs, -1) + aliasedPath := strings.Replace(event.Path, sourceURLFull, ms.sourceURL, -1) // build target path, it is the relative of the event.Path with the sourceUrl // joined to the targetURL. - targetPath := ms.targetURL - if rel, err := filepath.Rel(event.Client.GetURL().Path, newClientURL(event.Path).Path); err == nil { - targetPath = filepath.Join(targetPath, rel) - } else { - ms.status.errorIf(probe.NewError(err), - fmt.Sprintf("Got error during monitoring.")) - continue - } + sourceSuffix := strings.TrimPrefix(event.Path, sourceURLFull) + targetPath := urlJoinPath(ms.targetURL, sourceSuffix) // newClient needs the unexpanded path, newCLientURL needs the expanded path targetAlias, expandedTargetPath, _ := mustExpandAlias(targetPath) @@ -462,23 +460,27 @@ func (ms *mirrorSession) watch() { } case err := <-ms.watcher.Errors(): - errorIf(err, - fmt.Sprintf("Got error during monitoring.")) + errorIf(err, "Unexpected error during monitoring.") } } } -func (ms *mirrorSession) watchSourceURLs(recursive bool) *probe.Error { - if sourceClient, err := newClient(ms.sourceURLs); err != nil { - return err - } else if err := ms.watcher.Join(sourceClient, recursive /*, events to monitor here*/); err != nil { - return err - } else { - // no errors, all set. - } - - return nil +func (ms *mirrorSession) unwatchSourceURL(recursive bool) *probe.Error { + sourceClient, err := newClient(ms.sourceURL) + if err == nil { + return ms.watcher.Unjoin(sourceClient, recursive) + } // Failed to initialize client. + return err } + +func (ms *mirrorSession) watchSourceURL(recursive bool) *probe.Error { + sourceClient, err := newClient(ms.sourceURL) + if err == nil { + return ms.watcher.Join(sourceClient, recursive) + } // Failed to initialize client. + return err +} + func (ms *mirrorSession) harvestSessionUrls() { defer close(ms.harvestCh) @@ -506,7 +508,7 @@ func (ms *mirrorSession) harvestSourceUrls(recursive bool) { defer close(ms.harvestCh) - URLsCh := prepareMirrorURLs(ms.sourceURLs, ms.targetURL, isForce, isFake, isRemove) + URLsCh := prepareMirrorURLs(ms.sourceURL, ms.targetURL, isForce, isFake, isRemove) for url := range URLsCh { ms.harvestCh <- url } @@ -609,6 +611,9 @@ func (ms *mirrorSession) mirror() { ms.shutdown() + // Remove watches on source url. + ms.unwatchSourceURL(true) + // no items left, just stop if ms.queue.Count() == 0 { ms.Delete() @@ -623,7 +628,7 @@ func (ms *mirrorSession) mirror() { // and queue them for copying. Monitor mode can be stopped // only by SIGTERM. if watch { - if err := ms.watchSourceURLs(true); err != nil { + if err := ms.watchSourceURL(true); err != nil { ms.status.fatalIf(err, fmt.Sprintf("Failed to start monitoring.")) } @@ -643,6 +648,7 @@ func (ms *mirrorSession) mirror() { } } +// Called upon signal trigger. func (ms *mirrorSession) shutdown() { // make sure only one shutdown can be active ms.m.Lock() @@ -679,7 +685,7 @@ func newMirrorSession(session *sessionV7) *mirrorSession { harvestCh: make(chan URLs), errorCh: make(chan *probe.Error), - watcher: NewWatcher(), + watcher: NewWatcher(session.Header.When), // we're using a queue instead of a channel, this allows us to gracefully // stop. if we're using a channel and want to trap a signal, the channel @@ -695,8 +701,8 @@ func newMirrorSession(session *sessionV7) *mirrorSession { scanBar: func(s string) { }, - sourceURLs: args[0], - targetURL: args[len(args)-1], // Last one is target + sourceURL: args[0], + targetURL: args[len(args)-1], // Last one is target } return &ms diff --git a/mc/watch.go b/mc/watch.go index 6f11218f..2e43e833 100644 --- a/mc/watch.go +++ b/mc/watch.go @@ -57,13 +57,10 @@ type watchObject struct { done chan bool } -// ClientWatcher is the interface being implemented by the different clients -type ClientWatcher interface { - Watch(params watchParams) (*watchObject, *probe.Error) -} - // Watcher can be used to have one or multiple clients watch for notifications type Watcher struct { + sessionStartTime time.Time + // all errors will be added to this chan errorsChan chan *probe.Error // all events will be added to this chan @@ -77,12 +74,12 @@ type Watcher struct { } // NewWatcher creates a new watcher -func NewWatcher() *Watcher { +func NewWatcher(sessionStartTime time.Time) *Watcher { return &Watcher{ - errorsChan: make(chan *probe.Error), - eventsChan: make(chan Event), - - o: []*watchObject{}, + sessionStartTime: sessionStartTime, + errorsChan: make(chan *probe.Error), + eventsChan: make(chan Event), + o: []*watchObject{}, } } @@ -119,14 +116,24 @@ func (w *Watcher) Wait() { w.wg.Wait() } +// Unjoin the watcher from client. +func (w *Watcher) Unjoin(client Client, recursive bool) *probe.Error { + err := client.Unwatch(watchParams{ + recursive: recursive, + accountID: fmt.Sprintf("%d", w.sessionStartTime.Unix()), + }) + if err != nil { + return err + } + return nil +} + // Join the watcher with client func (w *Watcher) Join(client Client, recursive bool) *probe.Error { - cw, ok := client.(ClientWatcher) - if !ok { - return probe.NewError(fmt.Errorf("Client has no Watcher interface.")) - } - - wo, err := cw.Watch(watchParams{recursive: recursive}) + wo, err := client.Watch(watchParams{ + recursive: recursive, + accountID: fmt.Sprintf("%d", w.sessionStartTime.Unix()), + }) if err != nil { return err } diff --git a/vendor/github.com/minio/minio-go/api-notification.go b/vendor/github.com/minio/minio-go/api-notification.go index b89c2e86..2e7e2c82 100644 --- a/vendor/github.com/minio/minio-go/api-notification.go +++ b/vendor/github.com/minio/minio-go/api-notification.go @@ -19,6 +19,7 @@ package minio import ( "bufio" "encoding/json" + "io" "net/http" "net/url" ) @@ -125,6 +126,7 @@ func (c Client) ListenBucketNotification(bucketName string, accountArn Arn, done go func(notificationInfoCh chan<- NotificationInfo) { defer close(notificationInfoCh) + // Validate the bucket name. if err := isValidBucketName(bucketName); err != nil { notificationInfoCh <- NotificationInfo{ Err: err, @@ -132,53 +134,68 @@ func (c Client) ListenBucketNotification(bucketName string, accountArn Arn, done return } - urlValues := make(url.Values) - urlValues.Set("notificationARN", accountArn.String()) + // Continously run and listen on bucket notification. + for { + urlValues := make(url.Values) + urlValues.Set("notificationARN", accountArn.String()) - // Execute GET on bucket to list objects. - resp, err := c.executeMethod("GET", requestMetadata{ - bucketName: bucketName, - queryValues: urlValues, - }) - if err != nil { - notificationInfoCh <- NotificationInfo{ - Err: err, - } - return - } - - // Validate http response, upon error return quickly. - if resp.StatusCode != http.StatusOK { - errResponse := httpRespToErrorResponse(resp, bucketName, "") - notificationInfoCh <- NotificationInfo{ - Err: errResponse, - } - return - } - - // Initialize a new bufio scanner, to read line by line. - bio := bufio.NewScanner(resp.Body) - - // Close the response body. - defer resp.Body.Close() - - // Unmarshal each line, returns marshalled values. - for bio.Scan() { - var notificationInfo NotificationInfo - buf := bio.Bytes() - if err = json.Unmarshal(buf, ¬ificationInfo); err != nil { + // Execute GET on bucket to list objects. + resp, err := c.executeMethod("GET", requestMetadata{ + bucketName: bucketName, + queryValues: urlValues, + }) + if err != nil { notificationInfoCh <- NotificationInfo{ Err: err, } return } - // Send notifications on channel only if there are events received. - if len(notificationInfo.Records) > 0 { - select { - case notificationInfoCh <- notificationInfo: - case <-doneCh: + + // Validate http response, upon error return quickly. + if resp.StatusCode != http.StatusOK { + errResponse := httpRespToErrorResponse(resp, bucketName, "") + notificationInfoCh <- NotificationInfo{ + Err: errResponse, + } + return + } + + // Initialize a new bufio scanner, to read line by line. + bio := bufio.NewScanner(resp.Body) + + // Close the response body. + defer resp.Body.Close() + + // Unmarshal each line, returns marshalled values. + for bio.Scan() { + var notificationInfo NotificationInfo + if err = json.Unmarshal(bio.Bytes(), ¬ificationInfo); err != nil { + notificationInfoCh <- NotificationInfo{ + Err: err, + } return } + // Send notifications on channel only if there are events received. + if len(notificationInfo.Records) > 0 { + select { + case notificationInfoCh <- notificationInfo: + case <-doneCh: + return + } + } + } + // Look for any underlying errors. + if err = bio.Err(); err != nil { + // For an unexpected connection drop from server, we close the body + // and re-connect. + if err == io.ErrUnexpectedEOF { + resp.Body.Close() + continue + } + notificationInfoCh <- NotificationInfo{ + Err: err, + } + return } } }(notificationInfoCh) diff --git a/vendor/github.com/minio/minio-go/bucket-cache.go b/vendor/github.com/minio/minio-go/bucket-cache.go index a5737064..1c2ccd62 100644 --- a/vendor/github.com/minio/minio-go/bucket-cache.go +++ b/vendor/github.com/minio/minio-go/bucket-cache.go @@ -66,8 +66,21 @@ func (r *bucketLocationCache) Delete(bucketName string) { delete(r.items, bucketName) } -// getBucketLocation - Get location for the bucketName from location map cache. +// GetBucketLocation - get location for the bucket name from location cache, if not +// fetch freshly by making a new request. +func (c Client) GetBucketLocation(bucketName string) (string, error) { + if err := isValidBucketName(bucketName); err != nil { + return "", err + } + return c.getBucketLocation(bucketName) +} + +// getBucketLocation - Get location for the bucketName from location map cache, if not +// fetch freshly by making a new request. func (c Client) getBucketLocation(bucketName string) (string, error) { + if err := isValidBucketName(bucketName); err != nil { + return "", err + } if location, ok := c.bucketLocCache.Get(bucketName); ok { return location, nil } diff --git a/vendor/github.com/minio/minio-go/s3-endpoints.go b/vendor/github.com/minio/minio-go/s3-endpoints.go index a46b5e33..3f159bd9 100644 --- a/vendor/github.com/minio/minio-go/s3-endpoints.go +++ b/vendor/github.com/minio/minio-go/s3-endpoints.go @@ -24,7 +24,9 @@ var awsS3EndpointMap = map[string]string{ "us-west-1": "s3-us-west-1.amazonaws.com", "eu-west-1": "s3-eu-west-1.amazonaws.com", "eu-central-1": "s3-eu-central-1.amazonaws.com", + "ap-south-1": "s3-ap-south-1.amazonaws.com", "ap-southeast-1": "s3-ap-southeast-1.amazonaws.com", + "ap-southeast-2": "s3-ap-southeast-2.amazonaws.com", "ap-northeast-1": "s3-ap-northeast-1.amazonaws.com", "ap-northeast-2": "s3-ap-northeast-2.amazonaws.com", "sa-east-1": "s3-sa-east-1.amazonaws.com", diff --git a/vendor/vendor.json b/vendor/vendor.json index 13a35f9a..a7ebb3f1 100644 --- a/vendor/vendor.json +++ b/vendor/vendor.json @@ -48,6 +48,12 @@ "revision": "d682a8f0cf139663a984ff12528da460ca963de9", "revisionTime": "2015-10-24T22:24:27-07:00" }, + { + "checksumSHA1": "4TwE8a1CRfxopbchnRBdDCHZ6rA=", + "path": "github.com/minio/minio-go", + "revision": "7f874569b7d80cf98fdb2a581ac47344107eab60", + "revisionTime": "2016-08-16T03:55:40Z" + }, { "path": "github.com/minio/minio/pkg/atomic", "revision": "f98675660bb2049dea7e39e5113f5af29b8f6815",