From 4e05b592989560fefc1f97fdc38912c71b6df7e4 Mon Sep 17 00:00:00 2001 From: Harshavardhana Date: Fri, 24 Apr 2015 02:05:10 -0700 Subject: [PATCH] Implement access command --- acl.go | 24 ++++++---- aliases.go | 2 + cmd-access.go | 94 +++++++++++++++++++++++++++++++++++++ cmd-cat.go | 15 +----- cmd-cp.go | 2 +- cmd-mb.go | 20 +++----- cmd-options.go | 55 +++++++++++++++++----- cmd_test.go | 20 ++++---- pkg/client/fs/fs_unix.go | 38 ++++++++++++++- pkg/client/fs/fs_windows.go | 38 ++++++++++++++- pkg/client/s3/bucket.go | 34 +++++++++----- 11 files changed, 269 insertions(+), 73 deletions(-) create mode 100644 cmd-access.go diff --git a/acl.go b/acl.go index f0e54443..e0b8451c 100644 --- a/acl.go +++ b/acl.go @@ -21,9 +21,9 @@ func (b bucketACL) isValidBucketACL() bool { switch true { case b.isPrivate(): fallthrough - case b.isPublicRead(): + case b.isReadOnly(): fallthrough - case b.isPublicReadWrite(): + case b.isPublic(): return true case b.String() == "private": // by default its "private" @@ -38,15 +38,21 @@ type bucketACL string // different types of ACL's currently supported for buckets const ( - bucketPrivate = bucketACL("private") - bucketPublicRead = bucketACL("public-read") - bucketPublicReadWrite = bucketACL("public-read-write") + bucketPrivate = bucketACL("private") + bucketReadOnly = bucketACL("readonly") + bucketPublic = bucketACL("public") ) func (b bucketACL) String() string { if string(b) == "" { return "private" } + if string(b) == "readonly" { + return "public-read" + } + if string(b) == "public" { + return "public-read-write" + } return string(b) } @@ -56,11 +62,11 @@ func (b bucketACL) isPrivate() bool { } // IsPublicRead - is acl PublicRead -func (b bucketACL) isPublicRead() bool { - return b == bucketPublicRead +func (b bucketACL) isReadOnly() bool { + return b == bucketReadOnly } // IsPublicReadWrite - is acl PublicReadWrite -func (b bucketACL) isPublicReadWrite() bool { - return b == bucketPublicReadWrite +func (b bucketACL) isPublic() bool { + return b == bucketPublic } diff --git a/aliases.go b/aliases.go index af3f5d3c..80fc0b41 100644 --- a/aliases.go +++ b/aliases.go @@ -35,6 +35,8 @@ func isValidAliasName(aliasName string) bool { fallthrough case "private": fallthrough + case "read-only": + fallthrough case "public-read": fallthrough case "public-read-write": diff --git a/cmd-access.go b/cmd-access.go new file mode 100644 index 00000000..6df178c6 --- /dev/null +++ b/cmd-access.go @@ -0,0 +1,94 @@ +package main + +import ( + "fmt" + "time" + + "github.com/minio-io/cli" + "github.com/minio-io/mc/pkg/client" + "github.com/minio-io/mc/pkg/console" + "github.com/minio-io/minio/pkg/iodine" + "github.com/minio-io/minio/pkg/utils/log" +) + +func runAccessCmd(ctx *cli.Context) { + if !ctx.Args().Present() || ctx.Args().First() == "help" { + cli.ShowCommandHelpAndExit(ctx, "access", 1) // last argument is exit code + } + + config, err := getMcConfig() + if err != nil { + log.Debug.Println(iodine.New(err, nil)) + console.Fatalf("mc: loading config file failed with following reason: [%s]\n", iodine.ToError(err)) + } + + targetURLConfigMap := make(map[string]*hostConfig) + targetURLs, err := getURLs(ctx.Args(), config.Aliases) + if err != nil { + switch e := iodine.ToError(err).(type) { + case errUnsupportedScheme: + log.Debug.Println(iodine.New(err, nil)) + console.Fatalf("mc: reading URL [%s] failed with following reason: [%s]\n", e.url, e) + default: + log.Debug.Println(iodine.New(err, nil)) + console.Fatalf("mc: reading URLs failed with following reason: [%s]\n", e) + } + } + acl := bucketACL(ctx.Args().First()) + if !acl.isValidBucketACL() { + log.Debug.Println(iodine.New(errInvalidACL{acl: acl.String()}, nil)) + console.Fatalf("Access type [%s] is not supported. Valid types are [private, public, readonly].\n", acl) + } + targetURLs = targetURLs[1:] // 1 or more target URLs + for _, targetURL := range targetURLs { + targetConfig, err := getHostConfig(targetURL) + if err != nil { + log.Debug.Println(iodine.New(err, nil)) + console.Fatalf("Unable to read configuration for host [%s]. Reason: [%s].\n", targetURL, iodine.ToError(err)) + } + targetURLConfigMap[targetURL] = targetConfig + } + for targetURL, targetConfig := range targetURLConfigMap { + errorMsg, err := doUpdateAccessCmd(mcClientManager{}, targetURL, acl.String(), targetConfig, globalDebugFlag) + err = iodine.New(err, nil) + if err != nil { + if errorMsg == "" { + errorMsg = "Empty error message. Please rerun this command with --debug and file a bug report." + } + log.Debug.Println(err) + console.Errorf("%s", errorMsg) + } + } +} + +func doUpdateAccessCmd(manager clientManager, targetURL, targetACL string, targetConfig *hostConfig, debug bool) (string, error) { + var err error + var clnt client.Client + clnt, err = manager.getNewClient(targetURL, targetConfig, debug) + if err != nil { + err := iodine.New(err, nil) + msg := fmt.Sprintf("Unable to initialize client for [%s]. Reason: [%s].\n", + targetURL, iodine.ToError(err)) + return msg, err + } + return doUpdateAccess(clnt, targetURL, targetACL) +} + +func doUpdateAccess(clnt client.Client, targetURL, targetACL string) (string, error) { + err := clnt.PutBucket(targetACL) + if err != nil && isValidRetry(err) { + console.Infof("Retrying ...") + } + for i := 0; i < globalMaxRetryFlag && err != nil && isValidRetry(err); i++ { + err = clnt.PutBucket(targetACL) + console.Errorf(" %d", i) + // Progressively longer delays + time.Sleep(time.Duration(i*i) * time.Second) + } + if err != nil { + err := iodine.New(err, nil) + msg := fmt.Sprintf("Failed to add bucket access policy for URL [%s]. Reason: [%s].\n", targetURL, iodine.ToError(err)) + return msg, err + } + return "", nil +} diff --git a/cmd-cat.go b/cmd-cat.go index 382ef70c..c46226e9 100644 --- a/cmd-cat.go +++ b/cmd-cat.go @@ -21,7 +21,6 @@ import ( "errors" "io" "os" - "strings" "sync" "github.com/minio-io/cli" @@ -33,10 +32,9 @@ import ( ) func runCatCmd(ctx *cli.Context) { - if len(ctx.Args()) != 1 { + if len(ctx.Args()) != 1 || ctx.Args().First() == "help" { cli.ShowCommandHelpAndExit(ctx, "cat", 1) // last argument is exit code } - config, err := getMcConfig() if err != nil { log.Debug.Println(iodine.New(err, nil)) @@ -57,12 +55,6 @@ func runCatCmd(ctx *cli.Context) { } sourceURL := urls[0] // First arg is source - recursive := isURLRecursive(sourceURL) - // if recursive strip off the "..." - if recursive { - sourceURL = strings.TrimSuffix(sourceURL, recursiveSeparator) - } - sourceURLConfigMap := make(map[string]*hostConfig) sourceConfig, err := getHostConfig(sourceURL) if err != nil { @@ -70,11 +62,6 @@ func runCatCmd(ctx *cli.Context) { console.Fatalf("mc: reading host config for URL [%s] failed with following reason: [%s]\n", sourceURL, iodine.ToError(err)) } sourceURLConfigMap[sourceURL] = sourceConfig - - if err != nil { - log.Debug.Println(iodine.New(err, nil)) - os.Exit(1) - } humanReadable, err := doCatCmd(mcClientManager{}, os.Stdout, sourceURLConfigMap, globalDebugFlag) if err != nil { log.Debug.Println(iodine.New(err, nil)) diff --git a/cmd-cp.go b/cmd-cp.go index c8b4e7a6..fe490479 100644 --- a/cmd-cp.go +++ b/cmd-cp.go @@ -28,7 +28,7 @@ import ( ) func runCopyCmd(ctx *cli.Context) { - if len(ctx.Args()) < 2 { + if len(ctx.Args()) < 2 || ctx.Args().First() == "help" { cli.ShowCommandHelpAndExit(ctx, "cp", 1) // last argument is exit code } diff --git a/cmd-mb.go b/cmd-mb.go index 0d10a119..b7940a3a 100644 --- a/cmd-mb.go +++ b/cmd-mb.go @@ -29,7 +29,7 @@ import ( // doMakeBucketCmd creates a new bucket func runMakeBucketCmd(ctx *cli.Context) { - if len(ctx.Args()) < 2 { + if !ctx.Args().Present() || ctx.Args().First() == "help" { cli.ShowCommandHelpAndExit(ctx, "mb", 1) // last argument is exit code } config, err := getMcConfig() @@ -49,12 +49,6 @@ func runMakeBucketCmd(ctx *cli.Context) { console.Fatalf("Error in parsing path or URL. Reason: [%s].\n", e) } } - acl := bucketACL(ctx.Args().First()) - if !acl.isValidBucketACL() { - log.Debug.Println(iodine.New(errInvalidACL{acl: acl.String()}, nil)) - console.Fatalf("Access type [%s] is not supported. Valid types are [private, private, read-only].\n", acl) - } - targetURLs = targetURLs[1:] // 1 or more target URLs for _, targetURL := range targetURLs { targetConfig, err := getHostConfig(targetURL) if err != nil { @@ -64,7 +58,7 @@ func runMakeBucketCmd(ctx *cli.Context) { targetURLConfigMap[targetURL] = targetConfig } for targetURL, targetConfig := range targetURLConfigMap { - errorMsg, err := doMakeBucketCmd(mcClientManager{}, targetURL, acl.String(), targetConfig, globalDebugFlag) + errorMsg, err := doMakeBucketCmd(mcClientManager{}, targetURL, targetConfig, globalDebugFlag) err = iodine.New(err, nil) if err != nil { if errorMsg == "" { @@ -76,7 +70,7 @@ func runMakeBucketCmd(ctx *cli.Context) { } } -func doMakeBucketCmd(manager clientManager, targetURL, targetACL string, targetConfig *hostConfig, debug bool) (string, error) { +func doMakeBucketCmd(manager clientManager, targetURL string, targetConfig *hostConfig, debug bool) (string, error) { var err error var clnt client.Client clnt, err = manager.getNewClient(targetURL, targetConfig, debug) @@ -86,16 +80,16 @@ func doMakeBucketCmd(manager clientManager, targetURL, targetACL string, targetC targetURL, iodine.ToError(err)) return msg, err } - return doMakeBucket(clnt, targetURL, targetACL) + return doMakeBucket(clnt, targetURL) } -func doMakeBucket(clnt client.Client, targetURL, targetACL string) (string, error) { - err := clnt.PutBucket(targetACL) +func doMakeBucket(clnt client.Client, targetURL string) (string, error) { + err := clnt.PutBucket("") if err != nil && isValidRetry(err) { console.Infof("Retrying ...") } for i := 0; i < globalMaxRetryFlag && err != nil && isValidRetry(err); i++ { - err = clnt.PutBucket(targetACL) + err = clnt.PutBucket("") console.Errorf(" %d", i) // Progressively longer delays time.Sleep(time.Duration(i*i) * time.Second) diff --git a/cmd-options.go b/cmd-options.go index fcba7f7e..d91b2321 100644 --- a/cmd-options.go +++ b/cmd-options.go @@ -26,6 +26,36 @@ import ( // List of commands var ( + accessCmd = cli.Command{ + Name: "access", + Usage: "Set permissions [public, private, readonly] for buckets and folders.", + Action: runAccessCmd, + CustomHelpTemplate: `Name: + mc {{.Name}} - {{.Usage}} + +USAGE: + mc {{.Name}}{{if .Flags}} [ARGS...]{{end}} PERMISSION TARGET [TARGET...] {{if .Description}} + +DESCRIPTION: + {{.Description}}{{end}}{{if .Flags}} + +OPTIONS: + {{range .Flags}}{{.}} + {{end}}{{ end }} + +EXAMPLES: + + 1. Set bucket to "private" on Amazon S3 object storage + $ mc {{.Name}} private https://s3.amazonaws.com/burningman2011 + + 2. Set bucket to "public" on Amazon S3 object storage + $ mc {{.Name}} public https://s3.amazonaws.com/shared + + 3. Set folder to world readwrite (chmod 777) on local filesystem + $ mc {{.Name}} public /shared/Music + +`, + } catCmd = cli.Command{ Name: "cat", Usage: "Concantenate an object to standard output", @@ -86,9 +116,8 @@ EXAMPLES: } lsCmd = cli.Command{ - Name: "ls", - Usage: "List files and objects", - // Description: `List files and objects recursively on object storage and fileystems`, + Name: "ls", + Usage: "List files and objects", Action: runListCmd, CustomHelpTemplate: `NAME: mc {{.Name}} - {{.Usage}} @@ -130,15 +159,14 @@ EXAMPLES: } mbCmd = cli.Command{ - Name: "mb", - Usage: "Make a bucket", - // Description: `Create a bucket on object storage or a folder on filesystem`, + Name: "mb", + Usage: "Make a bucket", Action: runMakeBucketCmd, CustomHelpTemplate: `NAME: mc {{.Name}} - {{.Usage}} USAGE: - mc {{.Name}} ACL TARGET [TARGET...] {{if .Description}} + mc {{.Name}} TARGET [TARGET...] {{if .Description}} DESCRIPTION: {{.Description}}{{end}}{{if .Flags}} @@ -148,14 +176,14 @@ OPTIONS: {{end}}{{ end }} EXAMPLES: - 1. Create a public bucket on Amazon S3 object storage - $ mc {{.Name}} public-read-write https://s3.amazonaws.com/public-document-store + 1. Create a bucket on Amazon S3 object storage + $ mc {{.Name}} https://s3.amazonaws.com/public-document-store - 2. Create a private bucket on Minio object storage - $ mc {{.Name}} private http://localhost:9000/mongodb-backup + 2. Create a bucket on Minio object storage + $ mc {{.Name}} http://localhost:9000/mongodb-backup - 3. Create multiple buckets on Amazon S3 object storage with same ACL - $ mc {{.Name}} public-read https://s3.amazonaws.com/public-photo-store https://s3.amazonaws.com/public-store + 3. Create multiple buckets on Amazon S3 object storage and Minio object storage + $ mc {{.Name}} https://s3.amazonaws.com/public-photo-store https://s3.amazonaws.com/public-store http://localhost:9000/mongodb-backup `, } @@ -209,6 +237,7 @@ EXAMPLES: ) var options = []cli.Command{ + accessCmd, catCmd, cpCmd, lsCmd, diff --git a/cmd_test.go b/cmd_test.go index 656857ab..c7ea55df 100644 --- a/cmd_test.go +++ b/cmd_test.go @@ -407,8 +407,8 @@ func (s *CmdTestSuite) TestMbCmd(c *C) { sourceURLConfigMap[sourceURL] = sourceConfig manager.On("getNewClient", sourceURL, sourceConfig, false).Return(cl1, nil).Once() - cl1.On("PutBucket", "private").Return(nil).Once() - msg, err := doMakeBucketCmd(manager, sourceURL, "private", sourceConfig, false) + cl1.On("PutBucket", "").Return(nil).Once() + msg, err := doMakeBucketCmd(manager, sourceURL, sourceConfig, false) c.Assert(msg, Equals, "") c.Assert(err, IsNil) @@ -430,14 +430,14 @@ func (s *CmdTestSuite) TestMbCmdFailures(c *C) { sourceURLConfigMap[sourceURL] = sourceConfig manager.On("getNewClient", sourceURL, sourceConfig, false).Return(nil, errors.New("Expected Failure")).Once() - msg, err := doMakeBucketCmd(manager, sourceURL, "private", sourceConfig, false) + msg, err := doMakeBucketCmd(manager, sourceURL, sourceConfig, false) c.Assert(len(msg) > 0, Equals, true) c.Assert(err, Not(IsNil)) manager.On("getNewClient", sourceURL, sourceConfig, false).Return(cl1, nil).Once() - cl1.On("PutBucket", "private").Return(&net.DNSError{}).Once() - cl1.On("PutBucket", "private").Return(nil).Once() - msg, err = doMakeBucketCmd(manager, sourceURL, "private", sourceConfig, false) + cl1.On("PutBucket", "").Return(&net.DNSError{}).Once() + cl1.On("PutBucket", "").Return(nil).Once() + msg, err = doMakeBucketCmd(manager, sourceURL, sourceConfig, false) c.Assert(msg, Equals, "") c.Assert(err, IsNil) @@ -450,9 +450,9 @@ func (s *CmdTestSuite) TestMbCmdFailures(c *C) { err.Op = "dial" err.Net = "tcp" err.Err = errors.New("Another expected error") - cl1.On("PutBucket", "private").Return(err).Once() + cl1.On("PutBucket", "").Return(err).Once() } - msg, err = doMakeBucketCmd(manager, sourceURL, "private", sourceConfig, false) + msg, err = doMakeBucketCmd(manager, sourceURL, sourceConfig, false) globalMaxRetryFlag = retries c.Assert(len(msg) > 0, Equals, true) c.Assert(err, Not(IsNil)) @@ -475,8 +475,8 @@ func (s *CmdTestSuite) TestMbCmdOnFile(c *C) { sourceURLConfigMap[sourceURL] = sourceConfig manager.On("getNewClient", sourceURL, sourceConfig, false).Return(cl1, nil).Once() - cl1.On("PutBucket", "private").Return(nil).Once() - msg, err := doMakeBucketCmd(manager, sourceURL, "private", sourceConfig, false) + cl1.On("PutBucket", "").Return(nil).Once() + msg, err := doMakeBucketCmd(manager, sourceURL, sourceConfig, false) c.Assert(msg, Equals, "") c.Assert(err, IsNil) diff --git a/pkg/client/fs/fs_unix.go b/pkg/client/fs/fs_unix.go index 8e2436dd..5ee37318 100644 --- a/pkg/client/fs/fs_unix.go +++ b/pkg/client/fs/fs_unix.go @@ -19,6 +19,7 @@ package fs import ( + "errors" "io" "os" "path/filepath" @@ -145,9 +146,44 @@ func (f *fsClient) listInGoroutine(itemCh chan client.ItemOnChannel) { } } +func isValidBucketACL(acl string) bool { + switch acl { + case "private": + fallthrough + case "public-read": + fallthrough + case "public-read-write": + fallthrough + case "": + return true + default: + return false + } +} + +func aclToPerm(acl string) os.FileMode { + switch acl { + case "private": + return os.FileMode(0700) + case "public-read": + return os.FileMode(0500) + case "public-read-write": + return os.FileMode(0777) + default: + return os.FileMode(0700) + } +} + // PutBucket - create a new bucket func (f *fsClient) PutBucket(acl string) error { - err := os.MkdirAll(f.path, 0700) + if !isValidBucketACL(acl) { + return iodine.New(errors.New("invalid acl"), nil) + } + err := os.MkdirAll(f.path, aclToPerm(acl)) + if err != nil { + return iodine.New(err, nil) + } + err = os.Chmod(f.path, aclToPerm(acl)) if err != nil { return iodine.New(err, nil) } diff --git a/pkg/client/fs/fs_windows.go b/pkg/client/fs/fs_windows.go index a23a88df..71db2343 100644 --- a/pkg/client/fs/fs_windows.go +++ b/pkg/client/fs/fs_windows.go @@ -17,6 +17,7 @@ package fs import ( + "errors" "io" "os" "strings" @@ -160,9 +161,44 @@ func (f *fsClient) listInGoroutine(itemCh chan client.ItemOnChannel) { } } +func isValidBucketACL(acl string) bool { + switch acl { + case "private": + fallthrough + case "public-read": + fallthrough + case "public-read-write": + fallthrough + case "": + return true + default: + return false + } +} + +func aclToPerm(acl string) os.FileMode { + switch acl { + case "private": + return os.FileMode(0700) + case "public-read": + return os.FileMode(0500) + case "public-read-write": + return os.FileMode(0777) + default: + return os.FileMode(0700) + } +} + // PutBucket - create a new bucket func (f *fsClient) PutBucket(acl string) error { - err := os.MkdirAll(f.path, 0700) + if !isValidBucketACL(acl) { + return iodine.New(errors.New("invalid acl"), nil) + } + err := os.MkdirAll(f.path, aclToPerm(acl)) + if err != nil { + return iodine.New(err, nil) + } + err = os.Chmod(f.path, aclToPerm(acl)) if err != nil { return iodine.New(err, nil) } diff --git a/pkg/client/s3/bucket.go b/pkg/client/s3/bucket.go index 93e0dd8f..254e5d40 100644 --- a/pkg/client/s3/bucket.go +++ b/pkg/client/s3/bucket.go @@ -126,22 +126,34 @@ func (c *s3Client) PutBucket(acl string) error { if !isValidBucketACL(acl) { return iodine.New(InvalidACL{ACL: acl}, nil) } - if acl == "" { - acl = "private" - } bucket, _ := c.url2BucketAndObject() if !client.IsValidBucketName(bucket) || strings.Contains(bucket, ".") { return iodine.New(InvalidBucketName{Bucket: bucket}, nil) } - u := fmt.Sprintf("%s://%s/%s", c.Scheme, c.Host, bucket) - // new request - req, err := c.newRequest("PUT", u, nil) - if err != nil { - return iodine.New(err, nil) + var req *http.Request + var err error + switch len(acl) > 0 { + case true: + u := fmt.Sprintf("%s://%s/%s?acl", c.Scheme, c.Host, bucket) + // new request + req, err = c.newRequest("PUT", u, nil) + if err != nil { + return iodine.New(err, nil) + } + // by default without acl while creating a bucket + // make it default "private" + req.Header.Add("x-amz-acl", acl) + default: + u := fmt.Sprintf("%s://%s/%s", c.Scheme, c.Host, bucket) + // new request + req, err = c.newRequest("PUT", u, nil) + if err != nil { + return iodine.New(err, nil) + } + // by default without acl while creating a bucket + // make it default "private" + req.Header.Add("x-amz-acl", "private") } - // add canned ACL's while creating a bucket - req.Header.Add("x-amz-acl", acl) - if c.AccessKeyID != "" && c.SecretAccessKey != "" { c.signRequest(req, c.Host) }