diff --git a/mc/client-fs.go b/mc/client-fs.go index 49cb6519..935e8d0f 100644 --- a/mc/client-fs.go +++ b/mc/client-fs.go @@ -86,7 +86,7 @@ func (f *fsClient) GetURL() clientURL { return *f.PathURL } -func (f *fsClient) Watch(recursive bool) (*watchObject, *probe.Error) { +func (f *fsClient) Watch(params watchParams) (*watchObject, *probe.Error) { eventChan := make(chan Event) errorChan := make(chan *probe.Error) doneChan := make(chan bool) @@ -128,7 +128,7 @@ func (f *fsClient) Watch(recursive bool) (*watchObject, *probe.Error) { errorChan <- probe.NewError(err) } else if !i.IsDir() { // we want files - } else if !recursive { + } else if !params.recursive { // we don't want to watch recursively continue } else if err := watcher.Add(event.Name); err == nil { @@ -143,12 +143,14 @@ func (f *fsClient) Watch(recursive bool) (*watchObject, *probe.Error) { fallthrough case event.Op&fsnotify.Write == fsnotify.Write: eventChan <- Event{ + Time: time.Now(), Path: event.Name, Client: f, Type: EventCreate, } case event.Op&fsnotify.Remove == fsnotify.Remove: eventChan <- Event{ + Time: time.Now(), Path: event.Name, Client: f, Type: EventRemove, @@ -165,7 +167,7 @@ func (f *fsClient) Watch(recursive bool) (*watchObject, *probe.Error) { }() // add recursive folders - if recursive { + if params.recursive { if err := ioutils.FTW(f.PathURL.Path, func(fp string, fi os.FileInfo, e error) error { if !fi.IsDir() { return ioutils.ErrSkipFile diff --git a/mc/client-s3.go b/mc/client-s3.go index 22466453..b07b5fa8 100644 --- a/mc/client-s3.go +++ b/mc/client-s3.go @@ -23,7 +23,6 @@ import ( "net/http" "net/url" "os" - "path" "path/filepath" "regexp" "strings" @@ -158,27 +157,49 @@ func (w *watchObject) Close() { close(w.done) } -func (c *s3Client) Watch(recursive bool) (*watchObject, *probe.Error) { +// Enable/Disable lambda bucket notification +func (c *s3Client) ToogleLambdaNotificationStatus(enable bool, region, accountID string) *probe.Error { + + bucket, _ := c.url2BucketAndObject() + + if err := isValidBucketName(bucket); err != nil { + return err + } + + mb, err := c.api.GetBucketNotification(bucket) + if err != nil { + return probe.NewError(err) + } + + accountARN := minio.NewArn("minio", "lambda", region, accountID, "lambda") + + if enable { + // Enable lambda bucket notification + lc := minio.NewNotificationConfig(accountARN) + lc.AddEvents(minio.ObjectCreatedAll, minio.ObjectRemovedAll) + mb.AddLambda(lc) + } else { + // Remove lambda bucket notification + mb.RemoveLambdaByArn(accountARN) + } + + // Set the new bucket configuration + if err := c.api.SetBucketNotification(bucket, mb); err != nil { + return probe.NewError(err) + } + return nil +} + +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() - - // todo(nl5887): correct arn creation - accountARN := minio.NewArn("minio", "lambda", "us-east-1", "mc", "lambda") - - // enable bucket notifications - lc := minio.NewNotificationConfig(accountARN) - lc.AddEvents(minio.ObjectCreatedAll, minio.ObjectRemovedAll) - mb := minio.BucketNotification{} - mb.AddLambda(lc) - - if err := c.api.SetBucketNotification(bucket, mb); err != nil { - return nil, probe.NewError(err) + if err := isValidBucketName(bucket); err != nil { + return nil, err } - // Create a done channel to control 'ListObjects' go routine. doneCh := make(chan struct{}) // wait for doneChan to close the other channels @@ -190,6 +211,7 @@ func (c *s3Client) Watch(recursive bool) (*watchObject, *probe.Error) { close(errorChan) }() + accountARN := minio.NewArn("minio", "lambda", params.accountRegion, params.accountID, "lambda") eventsCh := c.api.ListenBucketNotification(bucket, accountARN, doneCh) // wait for events to occur and sent them through the eventChan and errorChan @@ -201,21 +223,22 @@ func (c *s3Client) Watch(recursive bool) (*watchObject, *probe.Error) { } for _, record := range notificationInfo.Records { + bucketName := record.S3.Bucket.Name key := record.S3.Object.Key - // copy targeturl to source and update path - source := *c.targetURL - source.Path = path.Join(source.Path, key) + source := bucketName + "/" + key if strings.HasPrefix(record.EventName, "s3:ObjectCreated:") { eventChan <- Event{ - Path: source.String(), + Time: time.Now(), + Path: source, Client: c, Type: EventCreate, } } else if strings.HasPrefix(record.EventName, "s3:ObjectRemoved:") { eventChan <- Event{ - Path: source.String(), + Time: time.Now(), + Path: source, Client: c, Type: EventRemove, } @@ -451,12 +474,13 @@ func (c *s3Client) Stat() (*clientContent, *probe.Error) { if bucket == "" { return nil, probe.NewError(BucketNameEmpty{}) } else if object == "" { - if exists, e := c.api.BucketExists(bucket); e != nil { + exists, e := c.api.BucketExists(bucket) + if e != nil { return nil, probe.NewError(e) - } else if !exists { + } + if !exists { return nil, probe.NewError(BucketDoesNotExist{Bucket: bucket}) } - bucketMetadata := &clientContent{} bucketMetadata.URL = *c.targetURL bucketMetadata.Type = os.ModeDir diff --git a/mc/client.go b/mc/client.go index 103367cf..ebdf4b1c 100644 --- a/mc/client.go +++ b/mc/client.go @@ -46,6 +46,9 @@ type Client interface { ShareDownload(expires time.Duration) (string, *probe.Error) ShareUpload(bool, time.Duration, string) (map[string]string, *probe.Error) + // Watch events + Watch(params watchParams) (*watchObject, *probe.Error) + // Delete operations Remove(incomplete bool) *probe.Error diff --git a/mc/main.go b/mc/main.go index 5f7de1eb..7461bf81 100644 --- a/mc/main.go +++ b/mc/main.go @@ -246,6 +246,7 @@ func registerApp() *cli.App { registerCmd(mirrorCmd) // Mirror objects and files from single source to multiple destinations. registerCmd(diffCmd) // Computer differences between two files or folders. registerCmd(rmCmd) // Remove a file or bucket + registerCmd(notifyCmd) // Add notify cmd registerCmd(policyCmd) // Set policy permissions. registerCmd(sessionCmd) // Manage sessions for copy and mirror. registerCmd(configCmd) // Configure minio client. diff --git a/mc/notify-listen.go b/mc/notify-listen.go new file mode 100644 index 00000000..5e854636 --- /dev/null +++ b/mc/notify-listen.go @@ -0,0 +1,149 @@ +/* + * Minio Client (C) 2016 Minio, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package mc + +import ( + "encoding/json" + "sync" + + "github.com/fatih/color" + "github.com/minio/cli" + "github.com/minio/mc/pkg/console" + "github.com/minio/minio/pkg/probe" +) + +var ( + notifyListenFlags = []cli.Flag{ + cli.StringFlag{ + Name: "account-region", + Value: "us-east-1", + Usage: "Specify notification region. Defaults to ‘us-east-1’.", + }, + cli.StringFlag{ + Name: "account-id", + Value: "mc", + Usage: "Specify notification account id. Defaults to ‘mc’.", + }, + cli.BoolFlag{ + Name: "recursive", + Usage: "Indicate if we should watch events in sub-directories.", + }, + } +) + +var notifyListenCmd = cli.Command{ + Name: "listen", + Usage: "Print realtime bucket notification.", + Action: mainNotifyListen, + Flags: append(notifyListenFlags, globalFlags...), + CustomHelpTemplate: `NAME: + mc notify {{.Name}} - {{.Usage}} + +USAGE: + mc notify {{.Name}} [FLAGS] + +FLAGS: + {{range .Flags}}{{.}} + {{end}} +EXAMPLES: + 1. Watch new S3 operations on a minio server + $ mc notify {{.Name}} myminio/testbucket + + 2. Watch new events on a specific region and account id + $ mc notify {{.Name}} myminio/testbucket --account-region us-west-2 --account-id 81132344 +`, +} + +// checkNotifyListenSyntax - validate all the passed arguments +func checkNotifyListenSyntax(ctx *cli.Context) { + if !ctx.Args().Present() { + cli.ShowCommandHelpAndExit(ctx, "listen", 1) // last argument is exit code + } +} + +// notifyListenMessage container to hold one event notification +type notifyListenMessage struct { + Status string `json:"status"` + Event Event `json:"event"` +} + +// JSON jsonified update message. +func (u notifyListenMessage) JSON() string { + u.Status = "success" + notifyMessageJSONBytes, e := json.Marshal(u) + fatalIf(probe.NewError(e), "Unable to marshal into JSON.") + return string(notifyMessageJSONBytes) +} + +func (u notifyListenMessage) String() string { + msg := console.Colorize("Time", u.Event.Time.String()+"\t") + msg += console.Colorize("EventType", u.Event.Type+"\t") + msg += console.Colorize("ObjectName", u.Event.Path) + return msg +} + +func mainNotifyListen(ctx *cli.Context) { + + console.SetColor("Time", color.New(color.FgYellow, color.Bold)) + console.SetColor("EventType", color.New(color.FgCyan, color.Bold)) + console.SetColor("EventName", color.New(color.Bold)) + + setGlobalsFromContext(ctx) + + checkNotifyListenSyntax(ctx) + + args := ctx.Args() + path := args[0] + + region := ctx.String("account-region") + accountID := ctx.String("account-id") + recursive := ctx.Bool("recursive") + + s3Client, pErr := newClient(path) + if pErr != nil { + fatalIf(pErr.Trace(), "Cannot parse the provided url.") + } + + // Start watching on events + wo, err := s3Client.Watch(watchParams{recursive: recursive, accountRegion: region, accountID: accountID}) + + fatalIf(err, "Cannot watch on the specified bucket.") + + wg := sync.WaitGroup{} + wg.Add(1) + go func() { + defer wg.Done() + for { + select { + case event, ok := <-wo.Events(): + if !ok { + return + } + msg := notifyListenMessage{Event: event} + printMsg(msg) + case err, ok := <-wo.Errors(): + if !ok { + return + } + fatalIf(err, "Cannot listen to events.") + return + } + } + }() + + wg.Wait() +} diff --git a/mc/notify-main.go b/mc/notify-main.go new file mode 100644 index 00000000..12963b5d --- /dev/null +++ b/mc/notify-main.go @@ -0,0 +1,67 @@ +/* + * Minio Client (C) 2016 Minio, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package mc + +import "github.com/minio/cli" + +var ( + notifyFlags = []cli.Flag{ + cli.BoolFlag{ + Name: "help, h", + Usage: "Help of notify.", + }, + } +) + +var notifyCmd = cli.Command{ + Name: "notify", + Usage: "Manage bucket notification operations", + Action: mainNotify, + Flags: append(notifyFlags, globalFlags...), + Subcommands: []cli.Command{ + notifyServiceCmd, + notifyListenCmd, + }, + CustomHelpTemplate: `NAME: + {{.Name}} - {{.Usage}} + +USAGE: + {{.Name}} [FLAGS] COMMAND + +FLAGS: + {{range .Flags}}{{.}} + {{end}} +COMMANDS: + {{range .Commands}}{{join .Names ", "}}{{ "\t" }}{{.Usage}} + {{end}} +`, +} + +// mainNotify is the handle for "mc notify" command. +func mainNotify(ctx *cli.Context) { + // Set global flags from context. + setGlobalsFromContext(ctx) + + if ctx.Args().First() != "" { // command help. + cli.ShowCommandHelp(ctx, ctx.Args().First()) + } else { + // command with Subcommands is an App. + cli.ShowAppHelp(ctx) + } + + // Sub-commands like "listen", "enable" and "disable" have their own main. +} diff --git a/mc/notify-service.go b/mc/notify-service.go new file mode 100644 index 00000000..7a666082 --- /dev/null +++ b/mc/notify-service.go @@ -0,0 +1,120 @@ +/* + * Minio Client (C) 2016 Minio, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package mc + +import ( + "encoding/json" + + "github.com/fatih/color" + "github.com/minio/cli" + "github.com/minio/mc/pkg/console" + "github.com/minio/minio/pkg/probe" +) + +var ( + notifyServiceFlags = []cli.Flag{ + cli.StringFlag{ + Name: "account-region", + Value: "us-east-1", + Usage: "Specify notification region. Defaults to ‘us-east-1’.", + }, + cli.StringFlag{ + Name: "account-id", + Value: "mc", + Usage: "Specify notification account id. Defaults to ‘mc’.", + }, + } +) + +var notifyServiceCmd = cli.Command{ + Name: "service", + Usage: "Enable/Disable lambda notification", + Action: mainNotifyService, + Flags: append(notifyServiceFlags, globalFlags...), + CustomHelpTemplate: `NAME: + mc notify {{.Name}} - {{.Usage}} + +USAGE: + mc notify {{.Name}} {enable|disable} [FLAGS] + +FLAGS: + {{range .Flags}}{{.}} + {{end}} +EXAMPLES: + 1. Enable bucket notification with a specific region and account id + $ mc notify {{.Name}} enable myminio/testbucket + 2. Disable bucket notification with specific region and accnout id + $ mc notify {{.Name}} disable myminio/testbucket --account-region us-west-2 --account-id 81132344 + +`, +} + +// checkNotifyEnableSyntax - validate all the passed arguments +func checkNotifyServiceSyntax(ctx *cli.Context) { + if len(ctx.Args()) != 2 { + cli.ShowCommandHelpAndExit(ctx, "service", 1) // last argument is exit code + } + if ctx.Args()[0] != "enable" && ctx.Args()[0] != "disable" { + cli.ShowCommandHelpAndExit(ctx, "service", 1) + } +} + +// notifyServiceMessage container +type notifyServiceMessage struct { + Status string `json:"status"` +} + +// JSON jsonified update message. +func (u notifyServiceMessage) JSON() string { + u.Status = "success" + notifyMessageJSONBytes, e := json.Marshal(u) + fatalIf(probe.NewError(e), "Unable to marshal into JSON.") + return string(notifyMessageJSONBytes) +} + +func (u notifyServiceMessage) String() string { + msg := console.Colorize("Service", "Successfully accomplished.") + return msg +} + +func mainNotifyService(ctx *cli.Context) { + console.SetColor("Service", color.New(color.FgGreen, color.Bold)) + + setGlobalsFromContext(ctx) + checkNotifyServiceSyntax(ctx) + + args := ctx.Args() + serviceStatus := args[0] + path := args[1] + + region := ctx.String("account-region") + accountID := ctx.String("account-id") + + client, err := newClient(path) + if err != nil { + fatalIf(err.Trace(), "Cannot parse the provided url.") + } + + s3Client, ok := client.(*s3Client) + if !ok { + fatalIf(errDummy().Trace(), "The provided url doesn't point to a S3 server.") + } + + err = s3Client.ToogleLambdaNotificationStatus(serviceStatus == "enable", region, accountID) + fatalIf(err, "Cannot enable notification on the specified bucket.") + printMsg(notifyServiceMessage{}) +} diff --git a/mc/watch.go b/mc/watch.go index 0ae90b22..6f11218f 100644 --- a/mc/watch.go +++ b/mc/watch.go @@ -19,25 +19,33 @@ package mc import ( "fmt" "sync" + "time" "github.com/minio/minio/pkg/probe" ) // EventType is the type of the event that occurred -type EventType uint8 +type EventType string const ( // EventCreate notifies when a new object has been created - EventCreate EventType = iota + EventCreate EventType = "ObjectCreated" // EventRemove notifies when a new object has been deleted - EventRemove + EventRemove = "ObjectRemoved" ) // Event contains the information of the event that occurred type Event struct { - Path string - Client Client - Type EventType + Time time.Time `json:"time"` + Path string `json:"path"` + Client Client `json:"-"` + Type EventType `json:"type"` +} + +type watchParams struct { + accountID string + accountRegion string + recursive bool } type watchObject struct { @@ -51,7 +59,7 @@ type watchObject struct { // ClientWatcher is the interface being implemented by the different clients type ClientWatcher interface { - Watch(recursive bool) (*watchObject, *probe.Error) + Watch(params watchParams) (*watchObject, *probe.Error) } // Watcher can be used to have one or multiple clients watch for notifications @@ -118,7 +126,7 @@ func (w *Watcher) Join(client Client, recursive bool) *probe.Error { return probe.NewError(fmt.Errorf("Client has no Watcher interface.")) } - wo, err := cw.Watch(recursive) + wo, err := cw.Watch(watchParams{recursive: recursive}) if err != nil { return err }