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.
This commit is contained in:
Harshavardhana
2016-08-16 14:32:15 -07:00
committed by GitHub
parent 082ea3c295
commit a47c86c54c
9 changed files with 238 additions and 97 deletions
+6
View File
@@ -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)
+90 -7
View File
@@ -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,
}
+1
View File
@@ -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
+40 -34
View File
@@ -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
+23 -16
View File
@@ -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
}
+56 -39
View File
@@ -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, &notificationInfo); 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(), &notificationInfo); 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)
+14 -1
View File
@@ -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
}
+2
View File
@@ -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",
+6
View File
@@ -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",