From 7084a4361e3511dff9e33c24e2ac0e2b952b1565 Mon Sep 17 00:00:00 2001 From: Krishnan Parthasarathi Date: Tue, 4 Apr 2017 00:46:21 +0530 Subject: [PATCH 01/38] Replace admin-heal-list with admin-heal --fake (#2101) * Replace admin-heal-list with admin-heal --fake * Improve admin-heal message for partial healing * Vendorize pkg/madmin changes to include improved messaging for partial healing of objects/uploads. * Modify message strings to include additional heal result information like number of disks where heal was successful. --- cmd/admin-heal-list.go | 256 ------------------ cmd/admin-heal.go | 226 ++++++++++++++-- .../github.com/minio/minio/pkg/madmin/API.md | 15 +- .../minio/minio/pkg/madmin/heal-commands.go | 68 ++++- vendor/vendor.json | 6 +- 5 files changed, 272 insertions(+), 299 deletions(-) delete mode 100644 cmd/admin-heal-list.go diff --git a/cmd/admin-heal-list.go b/cmd/admin-heal-list.go deleted file mode 100644 index 4abaa76d..00000000 --- a/cmd/admin-heal-list.go +++ /dev/null @@ -1,256 +0,0 @@ -/* - * Minio Client (C) 2017 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 cmd - -import ( - "encoding/json" - "fmt" - "path/filepath" - "strings" - - "github.com/fatih/color" - "github.com/minio/cli" - "github.com/minio/mc/pkg/console" - "github.com/minio/minio/pkg/madmin" - "github.com/minio/minio/pkg/probe" -) - -var ( - adminHealListFlags = []cli.Flag{ - cli.BoolFlag{ - Name: "recursive, r", - Usage: "List recursively.", - }, - cli.BoolFlag{ - Name: "incomplete, I", - Usage: "List incomplete uploads", - }, - } -) - -var adminHealListCmd = cli.Command{ - Name: "list", - Usage: "Get the list of buckets or objects that need to be healed.", - Before: setGlobalsFromContext, - Action: mainAdminHealList, - Flags: append(adminHealListFlags, globalFlags...), - CustomHelpTemplate: `NAME: - {{.HelpName}} - {{.Usage}} - -USAGE: - {{.HelpName}} ALIAS/[BUCKET/][PREFIX/] - -FLAGS: - {{range .VisibleFlags}}{{.}} - {{end}} -EXAMPLES: - 1. List objects than need to be healed related to 'testbucket' in a Minio server represented by its alias 'play'. - $ {{.HelpName}} play/testbucket/ - - 2. Recursively list objects than need to be healed. - $ {{.HelpName}} --recursive play/ - - 3. Recursively list incomplete uploads than need to be healed. - $ {{.HelpName}} --incomplete --recursive play/ - -`, -} - -// healListMessage container to hold heal information. -type healListMessage struct { - Status string `json:"status"` - Bucket string `json:"bucket"` - Object *madmin.ObjectInfo `json:"object"` - Upload *madmin.UploadInfo `json:"upload"` -} - -// String colorized service status message. -func (u healListMessage) String() string { - msg := "" - var healStatus madmin.HealStatus - - // Check if we have object heal information - if u.Object != nil { - msg += fmt.Sprintf("Object: %s/%s, ", u.Bucket, u.Object.Key) - healStatus = u.Object.HealObjectInfo.Status - } else { - msg += fmt.Sprintf("Upload: %s/%s, ", u.Bucket, u.Upload.Key) - healStatus = u.Upload.HealUploadInfo.Status - } - - // Print heal status - switch healStatus { - case madmin.CanHeal: - msg += "can be healed." - case madmin.Corrupted: - msg += "cannot be healed." - case madmin.QuorumUnavailable: - msg += "quorum not available for healing." - } - return console.Colorize("Heal", msg) -} - -// JSON jsonified service status Message message. -func (u healListMessage) JSON() string { - u.Status = "success" - statusJSONBytes, e := json.Marshal(u) - fatalIf(probe.NewError(e), "Unable to marshal into JSON.") - - return string(statusJSONBytes) -} - -// healBucketListMessage container to hold heal information. -type healBucketListMessage struct { - Status string `json:"status"` - Bucket madmin.BucketInfo `json:"bucket"` -} - -// String colorized service status message. -func (u healBucketListMessage) String() string { - msg := fmt.Sprintf("Bucket: `%s`, ", u.Bucket.Name) - switch u.Bucket.HealBucketInfo.Status { - case madmin.CanHeal: - msg += "can be healed" - case madmin.Corrupted: - msg += "cannot be healed" - case madmin.QuorumUnavailable: - msg += "quorum not available for healing" - } - msg += ".\n" - return console.Colorize("Heal", msg) -} - -// JSON jsonified service status Message message. -func (u healBucketListMessage) JSON() string { - u.Status = "success" - statusJSONBytes, e := json.Marshal(u) - fatalIf(probe.NewError(e), "Unable to marshal into JSON.") - - return string(statusJSONBytes) -} - -// checkAdminHealListSyntax - validate all the passed arguments -func checkAdminHealListSyntax(ctx *cli.Context) { - if len(ctx.Args()) == 0 || len(ctx.Args()) > 2 { - cli.ShowCommandHelpAndExit(ctx, "list", 1) // last argument is exit code - } -} - -func mainAdminHealList(ctx *cli.Context) error { - - // Check for heal list syntax - checkAdminHealListSyntax(ctx) - // Set console theme for heal command - console.SetColor("Heal", color.New(color.FgGreen, color.Bold)) - - // Get the alias parameter from cli - args := ctx.Args() - aliasedURL := args.Get(0) - isRecursive := ctx.Bool("recursive") - isIncomplete := ctx.Bool("incomplete") - - // Create a new Minio Admin Client - client, err := newAdminClient(aliasedURL) - if err != nil { - return err.ToGoError() - } - - // Transform windows backslash to the regular slash in the aliased url - aliasedURL = filepath.ToSlash(aliasedURL) - - // Compute bucket and object from aliased url - splits := splitStr(aliasedURL, "/", 3) - bucket, object := splits[1], splits[2] - - // If bucket is not specified, list buckets that need to be healed - if bucket == "" { - bucketsToHeal, e := client.ListBucketsHeal() - fatalIf(probe.NewError(e), "Cannot list buckets that need healing.") - // Iterate over buckets that need healing and print them - for _, bucketHeal := range bucketsToHeal { - printMsg(healBucketListMessage{Bucket: bucketHeal}) - } - } - - // When bucket is not specified and recursive flag is not activated, - // it means we will not scan inside buckets - if bucket == "" && !isRecursive { - return nil - } - - // Now, it is time to examine for objects that need to be healed - var buckets []string - if bucket == "" { - // Bucket is not specified, so we target all buckets so we need to list them. - s3Client, err := newClient(aliasedURL) - if err != nil { - fatalIf(err, "Cannot resolve the provided path.") - } - recursive := false - incomplete := false - listCh := s3Client.List(recursive, incomplete, DirFirst) - for content := range listCh { - // Trim the leading slash and add to the list of buckets - buckets = append(buckets, - strings.TrimPrefix(content.URL.Path, string(content.URL.Separator))) - } - } else { - // Bucket is passed in argument, so we will only search for objects in the specified bucket - buckets = append(buckets, bucket) - } - - // Iterate over all computed buckets - for _, currBucket := range buckets { - // Search for objects that need to be healed in the current bucket - doneCh := make(chan struct{}) - - if isIncomplete { - listCh, e := client.ListUploadsHeal(currBucket, object, isRecursive, doneCh) - fatalIf(probe.NewError(e), "Cannot list heal uploads.") - // Iterate over uploads and print them when not errors - for upload := range listCh { - if upload.Err != nil { - errorIf(probe.NewError(upload.Err), "Cannot heal upload `"+upload.Key+"`.") - continue - } - // Skip for non-recursive use case. - if upload.HealUploadInfo == nil { - continue - } - printMsg(healListMessage{Bucket: currBucket, Upload: &upload}) - } - - } else { - listCh, e := client.ListObjectsHeal(currBucket, object, isRecursive, doneCh) - fatalIf(probe.NewError(e), "Cannot list heal objects.") - // Iterate over objects and print them when not errors - for obj := range listCh { - if obj.Err != nil { - errorIf(probe.NewError(obj.Err), "Cannot heal object `"+obj.Key+"`.") - continue - } - // Skip for non-recursive use case. - if obj.HealObjectInfo == nil { - continue - } - printMsg(healListMessage{Bucket: currBucket, Object: &obj}) - } - } - } - - return nil -} diff --git a/cmd/admin-heal.go b/cmd/admin-heal.go index 0cf2d5af..f377611b 100644 --- a/cmd/admin-heal.go +++ b/cmd/admin-heal.go @@ -21,6 +21,7 @@ import ( "fmt" "os" "path/filepath" + "strings" "github.com/fatih/color" "github.com/minio/cli" @@ -59,34 +60,44 @@ FLAGS: {{range .VisibleFlags}}{{.}} {{end}} EXAMPLES: - 1. Heal 'testbucket' in a Minio server represented by its alias 'play'. + 1. To format newly replaced disks in a Minio server with alias 'play' + $ {{.HelpName}} play + + 2. Heal 'testbucket' in a Minio server with alias 'play' $ {{.HelpName}} play/testbucket/ - 2. Heal all objects under 'dir' prefix + 3. Heal all objects under 'dir' prefix $ {{.HelpName}} --recursive play/testbucket/dir/ - 3. Heal all uploads under 'dir' prefix + 4. Heal all uploads under 'dir' prefix $ {{.HelpName}} --incomplete --recursive play/testbucket/dir/ - 4. Issue a fake heal operation to see what the server could report - $ {{.HelpName}} --fake play/testbucket/dir/ + 5. Issue a fake heal operation to list all objects to be healed + $ {{.HelpName}} --fake play + + 6. Issue a fake heal operation to list all uploads to be healed + $ {{.HelpName}} --fake --incomplete play + + 7. Issue a fake heal operation to list all objects to be healed under 'dir' prefix + $ {{.HelpName}} --recursive --fake play/testbucket/dir/ + + 8. Issue a fake heal operation to list all uploads to be healed under 'dir' prefix + $ {{.HelpName}} --incomplete --recursive --fake play/testbucket/dir/ ` var adminHealCmd = cli.Command{ - Name: "heal", - Usage: "Manage heal tasks", - Before: setGlobalsFromContext, - Action: mainAdminHeal, - Flags: append(adminHealFlags, globalFlags...), - Subcommands: []cli.Command{ - adminHealListCmd, - }, + Name: "heal", + Usage: "Manage heal tasks", + Before: setGlobalsFromContext, + Action: mainAdminHeal, + Flags: append(adminHealFlags, globalFlags...), HideHelpCommand: true, } // healMessage container to hold repair information. type healMessage struct { Status string `json:"status"` + Result madmin.HealResult `json:"result"` Bucket string `json:"bucket"` Object *madmin.ObjectInfo `json:"object"` Upload *madmin.UploadInfo `json:"upload"` @@ -94,12 +105,27 @@ type healMessage struct { // String colorized service status message. func (u healMessage) String() string { + allOfflineTmpl := "isn't healed since %d disks were offline" + allHealedTmpl := "is healed on all %d disks" + someHealedTmpl := "is healed on %d disks while %d disks were offline" + msg := "" if u.Object != nil { - msg += fmt.Sprintf("Object %s/%s is healed.", u.Bucket, u.Object.Key) + msg = fmt.Sprintf("Object %s/%s ", u.Bucket, u.Object.Key) } else { - msg += fmt.Sprintf("Upload %s/%s/%s is healed.", u.Bucket, u.Upload.Key, u.Upload.UploadID) + msg = fmt.Sprintf("Upload %s/%s/%s ", u.Bucket, u.Upload.Key, u.Upload.UploadID) } + + healed, offline := u.Result.HealedCount, u.Result.OfflineCount + switch { + case healed == 0: + msg += fmt.Sprintf(allOfflineTmpl, offline) + case offline == 0: + msg += fmt.Sprintf(allHealedTmpl, healed) + case healed > 0 && offline > 0: + msg += fmt.Sprintf(someHealedTmpl, healed, offline) + } + return console.Colorize("Heal", msg) } @@ -112,6 +138,81 @@ func (u healMessage) JSON() string { return string(statusJSONBytes) } +// healListMessage container to hold heal information. +type healListMessage struct { + Status string `json:"status"` + Bucket string `json:"bucket"` + Object *madmin.ObjectInfo `json:"object"` + Upload *madmin.UploadInfo `json:"upload"` +} + +// String colorized service status message. +func (u healListMessage) String() string { + msg := "" + var healStatus madmin.HealStatus + + // Check if we have object heal information + if u.Object != nil { + msg += fmt.Sprintf("Object: %s/%s, ", u.Bucket, u.Object.Key) + healStatus = u.Object.HealObjectInfo.Status + } else { + msg += fmt.Sprintf("Upload: %s/%s, ", u.Bucket, u.Upload.Key) + healStatus = u.Upload.HealUploadInfo.Status + } + + // Print heal status + switch healStatus { + case madmin.CanHeal: + msg += "can be healed." + case madmin.CanPartiallyHeal: + msg += "can be partially healed." + case madmin.Corrupted: + msg += "cannot be healed." + case madmin.QuorumUnavailable: + msg += "quorum not available for healing." + } + return console.Colorize("Heal", msg) +} + +// JSON jsonified service status Message message. +func (u healListMessage) JSON() string { + u.Status = "success" + statusJSONBytes, e := json.Marshal(u) + fatalIf(probe.NewError(e), "Unable to marshal into JSON.") + + return string(statusJSONBytes) +} + +// healBucketListMessage container to hold heal information. +type healBucketListMessage struct { + Status string `json:"status"` + Bucket madmin.BucketInfo `json:"bucket"` +} + +// String colorized service status message. +func (u healBucketListMessage) String() string { + msg := fmt.Sprintf("Bucket: `%s`, ", u.Bucket.Name) + switch u.Bucket.HealBucketInfo.Status { + case madmin.CanHeal: + msg += "can be healed" + case madmin.Corrupted: + msg += "cannot be healed" + case madmin.QuorumUnavailable: + msg += "quorum not available for healing" + } + msg += ".\n" + return console.Colorize("Heal", msg) +} + +// JSON jsonified service status Message message. +func (u healBucketListMessage) JSON() string { + u.Status = "success" + statusJSONBytes, e := json.Marshal(u) + fatalIf(probe.NewError(e), "Unable to marshal into JSON.") + + return string(statusJSONBytes) +} + func healObjects(client *madmin.AdminClient, bucket, object string, isRecursive, isFake bool) { // Search for objects that need healing doneCh := make(chan struct{}) @@ -132,15 +233,20 @@ func healObjects(client *madmin.AdminClient, bucket, object string, isRecursive, // Check the heal status, and call heal object API only when an object can be healed switch healInfo := *obj.HealObjectInfo; healInfo.Status { - case madmin.CanHeal: + case madmin.CanHeal, madmin.CanPartiallyHeal: // Heal Object - if e = client.HealObject(bucket, obj.Key, isFake); e != nil { + var healResult madmin.HealResult + if healResult, e = client.HealObject(bucket, obj.Key, isFake); e != nil { errorIf(probe.NewError(e), "Cannot repair object: `"+obj.Key+"`") continue } // Print successful message - printMsg(healMessage{Bucket: bucket, Object: &obj}) + if isFake { + printMsg(healListMessage{Bucket: bucket, Object: &obj}) + } else { + printMsg(healMessage{Bucket: bucket, Object: &obj, Result: healResult}) + } case madmin.QuorumUnavailable: errorIf(errDummy().Trace(), obj.Key+" cannot be healed until quorum is available.") case madmin.Corrupted: @@ -169,14 +275,19 @@ func healUploads(client *madmin.AdminClient, bucket, object string, isRecursive, // Check the heal status, and call heal upload API only when an upload can be healed switch healInfo := *upload.HealUploadInfo; healInfo.Status { - case madmin.CanHeal: + case madmin.CanHeal, madmin.CanPartiallyHeal: // Heal Upload - if e = client.HealUpload(bucket, upload.Key, upload.UploadID, isFake); e != nil { + var healResult madmin.HealResult + if healResult, e = client.HealUpload(bucket, upload.Key, upload.UploadID, isFake); e != nil { errorIf(probe.NewError(e), "Cannot repair upload: `"+upload.Key+"`") continue } // Print successful message - printMsg(healMessage{Bucket: bucket, Upload: &upload}) + if isFake { + printMsg(healListMessage{Bucket: bucket, Upload: &upload}) + } else { + printMsg(healMessage{Bucket: bucket, Upload: &upload, Result: healResult}) + } case madmin.QuorumUnavailable: errorIf(errDummy().Trace(), upload.Key+" cannot be healed until quorum is available.") case madmin.Corrupted: @@ -193,6 +304,72 @@ func checkAdminHealSyntax(ctx *cli.Context) { } } +// listAllToBeHealed - list objects/uploads to be healed in the object +// store with alias `aliasedURL` +// - isIncomplete - if true we list uploads to be healed otherwise +// list objects to be healed +func listAllToBeHealed(client *madmin.AdminClient, aliasedURL string, isIncomplete bool) *probe.Error { + s3Client, err := newClient(aliasedURL) + if err != nil { + return err + } + + recursive := false + incomplete := false + listCh := s3Client.List(recursive, incomplete, DirFirst) + + var buckets []string + for content := range listCh { + // Trim the leading slash and add to the list of buckets + buckets = append(buckets, + strings.TrimPrefix(content.URL.Path, string(content.URL.Separator))) + } + + // isRecursive is always true since we have empty object names + // when `mc admin heal --fake [-r] s1/` is invoked. + isRecursive := true + + // Iterate over all computed buckets + for _, currBucket := range buckets { + // Search for objects that need to be healed in the current bucket + doneCh := make(chan struct{}) + + if isIncomplete { + listCh, e := client.ListUploadsHeal(currBucket, "", isRecursive, doneCh) + fatalIf(probe.NewError(e), "Cannot list heal uploads.") + // Iterate over uploads and print them when not errors + for upload := range listCh { + if upload.Err != nil { + errorIf(probe.NewError(upload.Err), "Cannot heal upload `"+upload.Key+"`.") + continue + } + // Skip for non-recursive use case. + if upload.HealUploadInfo == nil { + continue + } + printMsg(healListMessage{Bucket: currBucket, Upload: &upload}) + } + + } else { + listCh, e := client.ListObjectsHeal(currBucket, "", isRecursive, doneCh) + fatalIf(probe.NewError(e), "Cannot list heal objects.") + // Iterate over objects and print them when not errors + for obj := range listCh { + if obj.Err != nil { + errorIf(probe.NewError(obj.Err), "Cannot heal object `"+obj.Key+"`.") + continue + } + // Skip for non-recursive use case. + if obj.HealObjectInfo == nil { + continue + } + printMsg(healListMessage{Bucket: currBucket, Object: &obj}) + } + } + } + return nil +} + // mainAdminHeal - the entry function of heal command func mainAdminHeal(ctx *cli.Context) error { @@ -225,6 +402,13 @@ func mainAdminHeal(ctx *cli.Context) error { // Heal format if bucket is not specified and quit immediately if bucket == "" { + // If --fake was given, print all objects/uploads that + // need to be healed. + if isFake { + lErr := listAllToBeHealed(client, aliasedURL, isIncomplete) + fatalIf(lErr, "Unable to list all objects to be healed") + return nil + } e = client.HealFormat(isFake) fatalIf(probe.NewError(e), "Cannot heal the disks.") return nil diff --git a/vendor/github.com/minio/minio/pkg/madmin/API.md b/vendor/github.com/minio/minio/pkg/madmin/API.md index ad9af656..0698c97a 100644 --- a/vendor/github.com/minio/minio/pkg/madmin/API.md +++ b/vendor/github.com/minio/minio/pkg/madmin/API.md @@ -242,18 +242,19 @@ __Example__ ``` -### HealObject(bucket, object string, isDryRun bool) error +### HealObject(bucket, object string, isDryRun bool) (HealResult, error) If object is successfully healed returns nil, otherwise returns error indicating the reason for failure. If isDryRun is true, then the object is not healed, but heal object request is validated by the server. e.g, if the object exists, if object name is valid etc. __Example__ ``` go - isDryRun := false - err := madmClnt.HealObject("mybucket", "myobject", isDryRun) + isDryRun = false + healResult, err := madmClnt.HealObject("mybucket", "myobject", isDryRun) if err != nil { log.Fatalln(err) } - log.Println("successfully healed mybucket/myobject") + + log.Println("Heal-object result: ", healResult) ``` @@ -323,17 +324,17 @@ __Example__ ``` -### HealUpload(bucket, object, uploadID string, isDryRun bool) error +### HealUpload(bucket, object, uploadID string, isDryRun bool) (HealResult, error) If upload is successfully healed returns nil, otherwise returns error indicating the reason for failure. If isDryRun is true, then the upload is not healed, but heal upload request is validated by the server. e.g, if the upload exists, if upload name is valid etc. ``` go isDryRun = false - err = madmClnt.HealUpload("mybucket", "myobject", "myuploadID", isDryRun) + healResult, err := madmClnt.HealUpload("mybucket", "myobject", "myUploadID", isDryRun) if err != nil { log.Fatalln(err) } - log.Println("successfully healed mybucket/myobject/myuploadID") + log.Println("Heal-upload result: ", healResult) ``` ## 5. Config operations diff --git a/vendor/github.com/minio/minio/pkg/madmin/heal-commands.go b/vendor/github.com/minio/minio/pkg/madmin/heal-commands.go index cbedf9a5..8b69236f 100644 --- a/vendor/github.com/minio/minio/pkg/madmin/heal-commands.go +++ b/vendor/github.com/minio/minio/pkg/madmin/heal-commands.go @@ -20,8 +20,10 @@ package madmin import ( + "encoding/json" "encoding/xml" "fmt" + "io/ioutil" "net/http" "net/url" "time" @@ -104,8 +106,12 @@ const ( CanHeal // Corrupted - Object can't be healed Corrupted - // QuorumUnavailable - Object can't be healed until read quorum is available + // QuorumUnavailable - Object can't be healed until read + // quorum is available QuorumUnavailable + // CanPartiallyHeal - Object can't be healed completely until + // disks with missing parts come online + CanPartiallyHeal ) // HealBucketInfo - represents healing related information of a bucket. @@ -127,9 +133,9 @@ type BucketInfo struct { // HealObjectInfo - represents healing related information of an object. type HealObjectInfo struct { - Status HealStatus - MissingDataCount int - MissingPartityCount int + Status HealStatus + MissingDataCount int + MissingParityCount int } // ObjectInfo container for object metadata. @@ -434,7 +440,7 @@ func (adm *AdminClient) HealBucket(bucket string, dryrun bool) error { } // HealUpload - Heal the given upload. -func (adm *AdminClient) HealUpload(bucket, object, uploadID string, dryrun bool) error { +func (adm *AdminClient) HealUpload(bucket, object, uploadID string, dryrun bool) (HealResult, error) { // Construct query params. queryVal := url.Values{} queryVal.Set("heal", "") @@ -460,18 +466,40 @@ func (adm *AdminClient) HealUpload(bucket, object, uploadID string, dryrun bool) defer closeResponse(resp) if err != nil { - return err + return HealResult{}, err } if resp.StatusCode != http.StatusOK { - return httpRespToErrorResponse(resp) + return HealResult{}, httpRespToErrorResponse(resp) } - return nil + // Healing is not performed so heal object result is empty. + if dryrun { + return HealResult{}, nil + } + + jsonBytes, err := ioutil.ReadAll(resp.Body) + if err != nil { + return HealResult{}, err + } + + healResult := HealResult{} + err = json.Unmarshal(jsonBytes, &healResult) + if err != nil { + return HealResult{}, err + } + + return healResult, nil +} + +// HealResult - represents result of heal-object admin API. +type HealResult struct { + HealedCount int // number of disks that were healed. + OfflineCount int // number of disks that needed healing but were offline. } // HealObject - Heal the given object. -func (adm *AdminClient) HealObject(bucket, object string, dryrun bool) error { +func (adm *AdminClient) HealObject(bucket, object string, dryrun bool) (HealResult, error) { // Construct query params. queryVal := url.Values{} queryVal.Set("heal", "") @@ -494,14 +522,30 @@ func (adm *AdminClient) HealObject(bucket, object string, dryrun bool) error { defer closeResponse(resp) if err != nil { - return err + return HealResult{}, err } if resp.StatusCode != http.StatusOK { - return httpRespToErrorResponse(resp) + return HealResult{}, httpRespToErrorResponse(resp) } - return nil + // Healing is not performed so heal object result is empty. + if dryrun { + return HealResult{}, nil + } + + jsonBytes, err := ioutil.ReadAll(resp.Body) + if err != nil { + return HealResult{}, err + } + + healResult := HealResult{} + err = json.Unmarshal(jsonBytes, &healResult) + if err != nil { + return HealResult{}, err + } + + return healResult, nil } // HealFormat - heal storage format on available disks. diff --git a/vendor/vendor.json b/vendor/vendor.json index e03e6e52..3f023ea4 100644 --- a/vendor/vendor.json +++ b/vendor/vendor.json @@ -80,10 +80,10 @@ "revisionTime": "2016-08-18T00:31:20Z" }, { - "checksumSHA1": "M7IzPNZncWn7ve14/YPF2HKhCko=", + "checksumSHA1": "KLEdjpItmkn1LDY/2xTQHSzebnU=", "path": "github.com/minio/minio/pkg/madmin", - "revision": "97dc34fe06274894316a68e0e86e6c8cf498e21a", - "revisionTime": "2017-03-21T19:02:39Z" + "revision": "522b307ea67ed04f68fcbf98b67549532a6ac424", + "revisionTime": "2017-04-03T11:36:28Z" }, { "path": "github.com/minio/minio/pkg/probe", From ad04a6fcc4ec40d280a4862427c8d0454131492a Mon Sep 17 00:00:00 2001 From: Anis Elleuch Date: Wed, 5 Apr 2017 21:58:54 +0100 Subject: [PATCH 02/38] heal: Fix help text (#2111) --- cmd/admin-heal.go | 27 +++++++++++---------------- 1 file changed, 11 insertions(+), 16 deletions(-) diff --git a/cmd/admin-heal.go b/cmd/admin-heal.go index f377611b..9051de05 100644 --- a/cmd/admin-heal.go +++ b/cmd/admin-heal.go @@ -19,7 +19,6 @@ package cmd import ( "encoding/json" "fmt" - "os" "path/filepath" "strings" @@ -47,15 +46,19 @@ var ( } ) -var adminHealHelpTemplate = `NAME: +var adminHealCmd = cli.Command{ + Name: "heal", + Usage: "Manage heal tasks", + Before: setGlobalsFromContext, + Action: mainAdminHeal, + Flags: append(adminHealFlags, globalFlags...), + HideHelpCommand: true, + CustomHelpTemplate: `NAME: {{.HelpName}} - {{.Usage}} USAGE: - {{.HelpName}} [FLAGS] [COMMAND] + {{.HelpName}} [FLAGS] [ALIAS] -COMMANDS: - {{range .VisibleCommands}}{{join .Names ", "}}{{ "\t" }}{{.Usage}} - {{end}} FLAGS: {{range .VisibleFlags}}{{.}} {{end}} @@ -84,14 +87,7 @@ EXAMPLES: 8. Issue a fake heal operation to list all uploads to be healed under 'dir' prefix $ {{.HelpName}} --incomplete --recursive --fake play/testbucket/dir/ -` -var adminHealCmd = cli.Command{ - Name: "heal", - Usage: "Manage heal tasks", - Before: setGlobalsFromContext, - Action: mainAdminHeal, - Flags: append(adminHealFlags, globalFlags...), - HideHelpCommand: true, +`, } // healMessage container to hold repair information. @@ -299,8 +295,7 @@ func healUploads(client *madmin.AdminClient, bucket, object string, isRecursive, // checkAdminHealSyntax - validate all the passed arguments func checkAdminHealSyntax(ctx *cli.Context) { if len(ctx.Args()) != 1 { - cli.HelpPrinter(ctx.App.Writer, adminHealHelpTemplate, ctx.App) - os.Exit(1) + cli.ShowCommandHelpAndExit(ctx, "heal", 1) // last argument is exit code } } From 5805a37d27ac99d8c91913b2c0c0e81f066d5810 Mon Sep 17 00:00:00 2001 From: Anis Elleuch Date: Wed, 5 Apr 2017 22:53:57 +0100 Subject: [PATCH 03/38] alias: Support underscore in alias name (#2113) my_minio will be supported. --- cmd/config.go | 2 +- cmd/mc_test.go | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/cmd/config.go b/cmd/config.go index db731d9c..87730b4d 100644 --- a/cmd/config.go +++ b/cmd/config.go @@ -149,7 +149,7 @@ func isMcConfigExists() bool { // isValidAlias - Check if alias valid. func isValidAlias(alias string) bool { - return regexp.MustCompile("^[a-zA-Z][a-zA-Z0-9-]+$").MatchString(alias) + return regexp.MustCompile("^[a-zA-Z][a-zA-Z0-9-_]+$").MatchString(alias) } // getHostConfig retrieves host specific configuration such as access keys, signature type. diff --git a/cmd/mc_test.go b/cmd/mc_test.go index 7327410a..43cfabd4 100644 --- a/cmd/mc_test.go +++ b/cmd/mc_test.go @@ -89,6 +89,7 @@ func (s *TestSuite) TestGetMcConfigPath(c *C) { func (s *TestSuite) TestIsvalidAliasName(c *C) { c.Check(isValidAlias("helloWorld0"), Equals, true) + c.Check(isValidAlias("hello_World0"), Equals, true) c.Check(isValidAlias("h0SFD2k24Fdsa"), Equals, true) c.Check(isValidAlias("fdslka-4"), Equals, true) c.Check(isValidAlias("fdslka-"), Equals, true) From e494e138fe73e0b18bc7a446805bcdbecce7e2a0 Mon Sep 17 00:00:00 2001 From: Harshavardhana Date: Fri, 7 Apr 2017 03:39:56 -0700 Subject: [PATCH 04/38] docs: Fix README.md to point to new homebrew tap (#2114) --- README.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/README.md b/README.md index 3f56bb95..b2330de6 100644 --- a/README.md +++ b/README.md @@ -39,9 +39,8 @@ docker run minio/mc ls play Install mc packages using [Homebrew](http://brew.sh/) ```sh -brew install minio-mc +brew install minio/stable/mc mc --help - ``` ## GNU/Linux From fac4ef81b2435139f6b3b83cfb79c1e48cd8acda Mon Sep 17 00:00:00 2001 From: Harshavardhana Date: Sun, 9 Apr 2017 10:43:47 -0700 Subject: [PATCH 05/38] docs: Fix README.md to reference edge container. (#2118) --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b2330de6..1e6007e7 100644 --- a/README.md +++ b/README.md @@ -31,7 +31,7 @@ docker run minio/mc ls play ### Edge ``` docker pull minio/mc:edge -docker run minio/mc ls play +docker run minio/mc:edge ls play ``` ## macOS From b0968e29e867bae945dc6ec6cca5080b861836ab Mon Sep 17 00:00:00 2001 From: Harshavardhana Date: Mon, 10 Apr 2017 11:50:52 -0700 Subject: [PATCH 06/38] watch/events: Support events on Get/Head operations as well. (#2116) Fixes #2073 --- cmd/client-fs.go | 51 +++++++--- cmd/client-fs_linux.go | 40 ++++---- cmd/client-fs_other.go | 34 ++++--- cmd/client-fs_windows.go | 50 ++++++++++ cmd/client-s3.go | 92 ++++++++++++++++--- cmd/events-add.go | 4 +- cmd/mirror-main.go | 16 ++-- cmd/watch-main.go | 10 +- cmd/watch.go | 46 ++++++++-- vendor/github.com/minio/minio-go/api-list.go | 12 +-- .../minio/minio-go/api-notification.go | 9 ++ .../minio/minio-go/api-s3-datatypes.go | 2 +- vendor/github.com/minio/minio-go/api.go | 14 +-- vendor/github.com/minio/minio-go/core.go | 44 ++------- vendor/vendor.json | 6 +- 15 files changed, 290 insertions(+), 140 deletions(-) create mode 100644 cmd/client-fs_windows.go diff --git a/cmd/client-fs.go b/cmd/client-fs.go index da820946..c2a8d509 100644 --- a/cmd/client-fs.go +++ b/cmd/client-fs.go @@ -96,7 +96,10 @@ func (f *fsClient) GetURL() clientURL { // Watches for all fs events on an input path. func (f *fsClient) Watch(params watchParams) (*watchObject, *probe.Error) { - eventChan := make(chan Event) + eventChan := make(chan struct { + Event Event + Source Source + }) errorChan := make(chan *probe.Error) doneChan := make(chan bool) // Make the channel buffered to ensure no event is dropped. Notify will drop @@ -110,6 +113,8 @@ func (f *fsClient) Watch(params watchParams) (*watchObject, *probe.Error) { fsEvents = append(fsEvents, EventTypePut...) case "delete": fsEvents = append(fsEvents, EventTypeDelete...) + case "get": + fsEvents = append(fsEvents, EventTypeGet...) default: return nil, errInvalidArgument().Trace(event) } @@ -159,19 +164,41 @@ func (f *fsClient) Watch(params watchParams) (*watchObject, *probe.Error) { // we want files continue } - eventChan <- Event{ - Time: time.Now().Format(timeFormatFS), - Size: i.Size(), - Path: event.Path(), - Client: f, - Type: EventCreate, + eventChan <- struct { + Event Event + Source Source + }{ + Event: Event{ + Time: time.Now().Format(timeFormatFS), + Size: i.Size(), + Path: event.Path(), + Client: f, + Type: EventCreate, + }, } } else if IsDeleteEvent(event.Event()) { - eventChan <- Event{ - Time: time.Now().Format(timeFormatFS), - Path: event.Path(), - Client: f, - Type: EventRemove, + eventChan <- struct { + Event Event + Source Source + }{ + Event: Event{ + Time: time.Now().Format(timeFormatFS), + Path: event.Path(), + Client: f, + Type: EventRemove, + }, + } + } else if IsGetEvent(event.Event()) { + eventChan <- struct { + Event Event + Source Source + }{ + Event: Event{ + Time: time.Now().Format(timeFormatFS), + Path: event.Path(), + Client: f, + Type: EventAccessed, + }, } } } diff --git a/cmd/client-fs_linux.go b/cmd/client-fs_linux.go index 2b2befc0..1ee38cb7 100644 --- a/cmd/client-fs_linux.go +++ b/cmd/client-fs_linux.go @@ -1,7 +1,7 @@ // +build linux /* - * Minio Client (C) 2015 Minio, Inc. + * Minio Client (C) 2015, 2016, 2017 Minio, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this fs except in compliance with the License. @@ -23,34 +23,40 @@ import ( ) var ( - // EventTypePut contains the notify events that will cause a put + // EventTypePut contains the notify events that will cause a put (write) EventTypePut = []notify.Event{notify.InCloseWrite | notify.InMovedTo} - // EventTypeDelete contains the notify events that will cause a delete + // EventTypeDelete contains the notify events that will cause a delete (remove) EventTypeDelete = []notify.Event{notify.InDelete | notify.InDeleteSelf | notify.InMovedFrom} + // EventTypeGet contains the notify events that will cause a get (read) + EventTypeGet = []notify.Event{notify.InAccess | notify.InOpen} ) +// IsGetEvent checks if the event return is a get event. +func IsGetEvent(event notify.Event) bool { + for _, ev := range EventTypeGet { + if event == ev { + return true + } + } + return false +} + // IsPutEvent checks if the event returned is a put event func IsPutEvent(event notify.Event) bool { - switch event { - case notify.InCloseWrite: - return true - case notify.InMovedTo: - return true + for _, ev := range EventTypePut { + if event == ev { + return true + } } - return false } // IsDeleteEvent checks if the event returned is a delete event func IsDeleteEvent(event notify.Event) bool { - switch event { - case notify.InDelete: - return true - case notify.InDeleteSelf: - return true - case notify.InMovedFrom: - return true + for _, ev := range EventTypeDelete { + if event == ev { + return true + } } - return false } diff --git a/cmd/client-fs_other.go b/cmd/client-fs_other.go index 00204af0..6426d79d 100644 --- a/cmd/client-fs_other.go +++ b/cmd/client-fs_other.go @@ -1,7 +1,7 @@ -// +build !linux +// +build darwin,freebsd,solaris /* - * Minio Client (C) 2015 Minio, Inc. + * Minio Client (C) 2015, 2016, 2017 Minio, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this fs except in compliance with the License. @@ -21,32 +21,30 @@ package cmd import "github.com/rjeczalik/notify" var ( - // EventTypePut contains the notify events that will cause a put + // EventTypePut contains the notify events that will cause a put (writer) EventTypePut = []notify.Event{notify.Create, notify.Write, notify.Rename} - // EventTypeDelete contains the notify events that will cause a delete + // EventTypeDelete contains the notify events that will cause a delete (remove) EventTypeDelete = []notify.Event{notify.Remove} + // EventTypeGet contains the notify events that will cause a get (read) + EventTypeGet = []notify.Event{} // On macOS, FreeBSD, Solaris this is not available. ) +// IsGetEvent checks if the event return is a get event. +func IsGetEvent(event notify.Event) bool { + return false +} + // IsPutEvent checks if the event returned is a put event func IsPutEvent(event notify.Event) bool { - switch event { - case notify.Create: - return true - case notify.Rename: - return true - case notify.Write: - return true + for _, ev := range EventTypePut { + if event == ev { + return true + } } - return false } // IsDeleteEvent checks if the event returned is a delete event func IsDeleteEvent(event notify.Event) bool { - switch event { - case notify.Remove: - return true - } - - return false + return event == notify.Remove } diff --git a/cmd/client-fs_windows.go b/cmd/client-fs_windows.go new file mode 100644 index 00000000..f28bc5d6 --- /dev/null +++ b/cmd/client-fs_windows.go @@ -0,0 +1,50 @@ +// +build windows + +/* + * Minio Client (C) 2017 Minio, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this fs 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 cmd + +import "github.com/rjeczalik/notify" + +var ( + // EventTypePut contains the notify events that will cause a put (writer) + EventTypePut = []notify.Event{notify.Create, notify.Write, notify.Rename} + // EventTypeDelete contains the notify events that will cause a delete (remove) + EventTypeDelete = []notify.Event{notify.Remove} + // EventTypeGet contains the notify events that will cause a get (read) + EventTypeGet = []notify.Event{notify.FileNotifyChangeLastAccess} +) + +// IsGetEvent checks if the event return is a get event. +func IsGetEvent(event notify.Event) bool { + return event == notify.FileNotifyChangeLastAccess +} + +// IsPutEvent checks if the event returned is a put event +func IsPutEvent(event notify.Event) bool { + for _, ev := range EventTypePut { + if event == ev { + return true + } + } + return false +} + +// IsDeleteEvent checks if the event returned is a delete event +func IsDeleteEvent(event notify.Event) bool { + return event == notify.Remove +} diff --git a/cmd/client-s3.go b/cmd/client-s3.go index a253a18e..7bff5c46 100644 --- a/cmd/client-s3.go +++ b/cmd/client-s3.go @@ -1,5 +1,5 @@ /* - * Minio Client (C) 2015 Minio, Inc. + * Minio Client (C) 2015, 2016, 2017 Minio, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -206,6 +206,8 @@ func (c *s3Client) AddNotificationConfig(arn string, events []string, prefix, su nc.AddEvents(minio.ObjectCreatedAll) case "delete": nc.AddEvents(minio.ObjectRemovedAll) + case "get": + nc.AddEvents(minio.ObjectAccessedAll) default: return errInvalidArgument().Trace(events...) } @@ -366,7 +368,10 @@ func (c *s3Client) ListNotificationConfigs(arn string) ([]notificationConfig, *p // Start watching on all bucket events for a given account ID. func (c *s3Client) Watch(params watchParams) (*watchObject, *probe.Error) { - eventChan := make(chan Event) + eventChan := make(chan struct { + Event Event + Source Source + }) errorChan := make(chan *probe.Error) doneChan := make(chan bool) @@ -384,6 +389,8 @@ func (c *s3Client) Watch(params watchParams) (*watchObject, *probe.Error) { events = append(events, string(minio.ObjectCreatedAll)) case "delete": events = append(events, string(minio.ObjectRemovedAll)) + case "get": + events = append(events, string(minio.ObjectAccessedAll)) default: return nil, errInvalidArgument().Trace(event) } @@ -441,22 +448,77 @@ func (c *s3Client) Watch(params watchParams) (*watchObject, *probe.Error) { u := *c.targetURL u.Path = path.Join(string(u.Separator), bucketName, key) if strings.HasPrefix(record.EventName, "s3:ObjectCreated:") { - eventChan <- Event{ - Time: record.EventTime, - Size: record.S3.Object.Size, - Path: u.String(), - Client: c, - Type: EventCreate, + eventChan <- struct { + Event Event + Source Source + }{ + Event: Event{ + Time: record.EventTime, + Size: record.S3.Object.Size, + Path: u.String(), + Client: c, + Type: EventCreate, + }, + Source: Source{ + IP: record.Source.Host, + Port: record.Source.Port, + UserAgent: record.Source.UserAgent, + }, } + } else if strings.HasPrefix(record.EventName, "s3:ObjectRemoved:") { - eventChan <- Event{ - Time: record.EventTime, - Path: u.String(), - Client: c, - Type: EventRemove, + eventChan <- struct { + Event Event + Source Source + }{ + Event: Event{ + Time: record.EventTime, + Path: u.String(), + Client: c, + Type: EventRemove, + }, + Source: Source{ + IP: record.Source.Host, + Port: record.Source.Port, + UserAgent: record.Source.UserAgent, + }, + } + } else if record.EventName == minio.ObjectAccessedGet { + eventChan <- struct { + Event Event + Source Source + }{ + Event: Event{ + Time: record.EventTime, + Size: record.S3.Object.Size, + Path: u.String(), + Client: c, + Type: EventAccessedRead, + }, + Source: Source{ + IP: record.Source.Host, + Port: record.Source.Port, + UserAgent: record.Source.UserAgent, + }, + } + } else if record.EventName == minio.ObjectAccessedHead { + eventChan <- struct { + Event Event + Source Source + }{ + Event: Event{ + Time: record.EventTime, + Size: record.S3.Object.Size, + Path: u.String(), + Client: c, + Type: EventAccessedStat, + }, + Source: Source{ + IP: record.Source.Host, + Port: record.Source.Port, + UserAgent: record.Source.UserAgent, + }, } - } else { - // ignore other events } } } diff --git a/cmd/events-add.go b/cmd/events-add.go index 764258ea..525ff8ee 100644 --- a/cmd/events-add.go +++ b/cmd/events-add.go @@ -30,7 +30,7 @@ var ( eventsAddFlags = []cli.Flag{ cli.StringFlag{ Name: "events", - Value: "put,delete", + Value: "put,delete,get", Usage: "Filter specific type of events. Defaults to all events.", }, cli.StringFlag{ @@ -64,7 +64,7 @@ EXAMPLES: $ {{.HelpName}} myminio/mybucket arn:aws:sqs:us-west-2:444455556666:your-queue 2. Enable bucket notification with filters parameters - $ {{.HelpName}} s3/mybucket arn:aws:sqs:us-west-2:444455556666:your-queue --events put,delete --prefix photos/ --suffix .jpg + $ {{.HelpName}} s3/mybucket arn:aws:sqs:us-west-2:444455556666:your-queue --events put,delete,get --prefix photos/ --suffix .jpg `, } diff --git a/cmd/mirror-main.go b/cmd/mirror-main.go index 8f38d8f1..4f828295 100644 --- a/cmd/mirror-main.go +++ b/cmd/mirror-main.go @@ -289,19 +289,19 @@ func (mj *mirrorJob) watchMirror() { } } - sourceURL := newClientURL(event.Path) - aliasedPath := strings.Replace(event.Path, sourceURLFull, mj.sourceURL, -1) + sourceURL := newClientURL(event.Event.Path) + aliasedPath := strings.Replace(event.Event.Path, sourceURLFull, mj.sourceURL, -1) // build target path, it is the relative of the event.Path with the sourceUrl // joined to the targetURL. - sourceSuffix := strings.TrimPrefix(event.Path, sourceURLFull) + sourceSuffix := strings.TrimPrefix(event.Event.Path, sourceURLFull) targetPath := urlJoinPath(mj.targetURL, sourceSuffix) // newClient needs the unexpanded path, newCLientURL needs the expanded path targetAlias, expandedTargetPath, _ := mustExpandAlias(targetPath) targetURL := newClientURL(expandedTargetPath) - if event.Type == EventCreate { + if event.Event.Type == EventCreate { // we are checking if a destination file exists now, and if we only // overwrite it when force is enabled. mirrorURL := URLs{ @@ -310,7 +310,7 @@ func (mj *mirrorJob) watchMirror() { TargetAlias: targetAlias, TargetContent: &clientContent{URL: *targetURL}, } - if event.Size == 0 { + if event.Event.Size == 0 { sourceClient, err := newClient(aliasedPath) if err != nil { // cannot create sourceclient @@ -361,14 +361,14 @@ func (mj *mirrorJob) watchMirror() { shouldQueue = true } if shouldQueue || mj.isForce { - mirrorURL.SourceContent.Size = event.Size + mirrorURL.SourceContent.Size = event.Event.Size mirrorURL.TotalCount = mj.TotalObjects mirrorURL.TotalSize = mj.TotalBytes // adjust total, because we want to show progress of the itemj stiil queued to be copied. - mj.status.SetTotal(mj.status.Total() + event.Size).Update() + mj.status.SetTotal(mj.status.Total() + event.Event.Size).Update() mj.statusCh <- mj.doMirror(mirrorURL) } - } else if event.Type == EventRemove { + } else if event.Event.Type == EventRemove { mirrorURL := URLs{ SourceAlias: sourceAlias, SourceContent: nil, diff --git a/cmd/watch-main.go b/cmd/watch-main.go index 0bc4f1ce..f4f4fec2 100644 --- a/cmd/watch-main.go +++ b/cmd/watch-main.go @@ -36,7 +36,7 @@ var ( watchFlags = []cli.Flag{ cli.StringFlag{ Name: "events", - Value: "put,delete", + Value: "put,delete,get", Usage: "Filter specific type of events. Defaults to all events by default.", }, cli.StringFlag{ @@ -64,7 +64,7 @@ var watchCmd = cli.Command{ {{.HelpName}} - {{.Usage}} USAGE: - {{.HelpName}} [FLAGS] + {{.HelpName}} PATH [FLAGS] {{if .VisibleFlags}} FLAGS: {{range .VisibleFlags}}{{.}} @@ -98,6 +98,7 @@ func checkWatchSyntax(ctx *cli.Context) { type watchMessage struct { Status string `json:"status"` Event Event `json:"events"` + Source Source `json:"source,omitempty"` } func (u watchMessage) JSON() string { @@ -175,7 +176,10 @@ func mainWatch(ctx *cli.Context) error { if !ok { return } - msg := watchMessage{Event: event} + msg := watchMessage{ + Event: event.Event, + Source: event.Source, + } printMsg(msg) case err, ok := <-wo.Errors(): if !ok { diff --git a/cmd/watch.go b/cmd/watch.go index 363ec0a3..cc368626 100644 --- a/cmd/watch.go +++ b/cmd/watch.go @@ -24,14 +24,20 @@ import ( "github.com/minio/minio/pkg/probe" ) -// EventType is the type of the event that occurred +// EventType represents the type of the event occurred. type EventType string const ( - // EventCreate notifies when a new object has been created + // EventCreate notifies when a new object is created EventCreate EventType = "ObjectCreated" - // EventRemove notifies when a new object has been deleted + // EventRemove notifies when a new object is deleted EventRemove = "ObjectRemoved" + // EventAccessed notifies when an object is accessed. + EventAccessed = "ObjectAccessed" + // EventAccessedRead notifies when an object is accessed (specifically read). + EventAccessedRead = "ObjectAccessed:Read" + // EventAccessedStat notifies when an object is accessed (specifically stat). + EventAccessedStat = "ObjectAccessed:Stat" ) // Event contains the information of the event that occurred @@ -43,6 +49,13 @@ type Event struct { Type EventType `json:"type"` } +// Source obtains the information of the client which generated the event. +type Source struct { + IP string `json:"ip"` + Port string `json:"port"` + UserAgent string `json:"userAgent"` +} + type watchParams struct { accountID string prefix string @@ -53,7 +66,10 @@ type watchParams struct { type watchObject struct { // events will be put on this chan - events chan Event + events chan struct { + Event Event + Source Source + } // errors will be put on this chan errors chan *probe.Error // will stop the watcher goroutines @@ -61,7 +77,10 @@ type watchObject struct { } // Events returns the chan receiving events -func (w *watchObject) Events() chan Event { +func (w *watchObject) Events() chan struct { + Event Event + Source Source +} { return w.events } @@ -82,7 +101,10 @@ type Watcher struct { // all errors will be added to this chan errorsChan chan *probe.Error // all events will be added to this chan - eventsChan chan Event + eventsChan chan struct { + Event Event + Source Source + } // array of watchers joined o []*watchObject @@ -96,8 +118,11 @@ func NewWatcher(sessionStartTime time.Time) *Watcher { return &Watcher{ sessionStartTime: sessionStartTime, errorsChan: make(chan *probe.Error), - eventsChan: make(chan Event), - o: []*watchObject{}, + eventsChan: make(chan struct { + Event Event + Source Source + }), + o: []*watchObject{}, } } @@ -107,7 +132,10 @@ func (w *Watcher) Errors() chan *probe.Error { } // Events returns a channel which will receive events -func (w *Watcher) Events() chan Event { +func (w *Watcher) Events() chan struct { + Event Event + Source Source +} { return w.eventsChan } diff --git a/vendor/github.com/minio/minio-go/api-list.go b/vendor/github.com/minio/minio-go/api-list.go index 25bea39e..a19156ae 100644 --- a/vendor/github.com/minio/minio-go/api-list.go +++ b/vendor/github.com/minio/minio-go/api-list.go @@ -168,14 +168,14 @@ func (c Client) ListObjectsV2(bucketName, objectPrefix string, recursive bool, d // ?delimiter - A delimiter is a character you use to group keys. // ?prefix - Limits the response to keys that begin with the specified prefix. // ?max-keys - Sets the maximum number of keys returned in the response body. -func (c Client) listObjectsV2Query(bucketName, objectPrefix, continuationToken string, fetchOwner bool, delimiter string, maxkeys int) (listBucketV2Result, error) { +func (c Client) listObjectsV2Query(bucketName, objectPrefix, continuationToken string, fetchOwner bool, delimiter string, maxkeys int) (ListBucketV2Result, error) { // Validate bucket name. if err := isValidBucketName(bucketName); err != nil { - return listBucketV2Result{}, err + return ListBucketV2Result{}, err } // Validate object prefix. if err := isValidObjectPrefix(objectPrefix); err != nil { - return listBucketV2Result{}, err + return ListBucketV2Result{}, err } // Get resources properly escaped and lined up before // using them in http request. @@ -216,16 +216,16 @@ func (c Client) listObjectsV2Query(bucketName, objectPrefix, continuationToken s }) defer closeResponse(resp) if err != nil { - return listBucketV2Result{}, err + return ListBucketV2Result{}, err } if resp != nil { if resp.StatusCode != http.StatusOK { - return listBucketV2Result{}, httpRespToErrorResponse(resp, bucketName, "") + return ListBucketV2Result{}, httpRespToErrorResponse(resp, bucketName, "") } } // Decode listBuckets XML. - listBucketResult := listBucketV2Result{} + listBucketResult := ListBucketV2Result{} err = xmlDecoder(resp.Body, &listBucketResult) if err != nil { return listBucketResult, err diff --git a/vendor/github.com/minio/minio-go/api-notification.go b/vendor/github.com/minio/minio-go/api-notification.go index 9c2a2ebd..fa9f1fa3 100644 --- a/vendor/github.com/minio/minio-go/api-notification.go +++ b/vendor/github.com/minio/minio-go/api-notification.go @@ -102,6 +102,14 @@ type eventMeta struct { Object objectMeta `json:"object"` } +// sourceInfo represents information on the client that +// triggered the event notification. +type sourceInfo struct { + Host string `json:"host"` + Port string `json:"port"` + UserAgent string `json:"userAgent"` +} + // NotificationEvent represents an Amazon an S3 bucket notification event. type NotificationEvent struct { EventVersion string `json:"eventVersion"` @@ -113,6 +121,7 @@ type NotificationEvent struct { RequestParameters map[string]string `json:"requestParameters"` ResponseElements map[string]string `json:"responseElements"` S3 eventMeta `json:"s3"` + Source sourceInfo `json:"source"` } // NotificationInfo - represents the collection of notification events, additionally diff --git a/vendor/github.com/minio/minio-go/api-s3-datatypes.go b/vendor/github.com/minio/minio-go/api-s3-datatypes.go index fd9fc7fd..5bd0bcc5 100644 --- a/vendor/github.com/minio/minio-go/api-s3-datatypes.go +++ b/vendor/github.com/minio/minio-go/api-s3-datatypes.go @@ -42,7 +42,7 @@ type commonPrefix struct { } // listBucketResult container for listObjects V2 response. -type listBucketV2Result struct { +type ListBucketV2Result struct { // A response can contain CommonPrefixes only if you have // specified a delimiter. CommonPrefixes []commonPrefix diff --git a/vendor/github.com/minio/minio-go/api.go b/vendor/github.com/minio/minio-go/api.go index 2beba77b..d5821c01 100644 --- a/vendor/github.com/minio/minio-go/api.go +++ b/vendor/github.com/minio/minio-go/api.go @@ -543,9 +543,9 @@ func (c Client) executeMethod(method string, metadata requestMetadata) (res *htt // For errors verify if its retryable otherwise fail quickly. errResponse := ToErrorResponse(httpRespToErrorResponse(res, metadata.bucketName, metadata.objectName)) - // Bucket region if set in error response, we can retry the - // request with the new region. - if errResponse.Region != "" { + // Bucket region if set in error response and the error code dictates invalid region, + // we can retry the request with the new region. + if errResponse.Code == "InvalidRegion" && errResponse.Region != "" { c.bucketLocCache.Set(metadata.bucketName, errResponse.Region) continue // Retry. } @@ -625,14 +625,6 @@ func (c Client) newRequest(method string, metadata requestMetadata) (req *http.R return req, nil } - // FIXME: Enable this when Google Cloud Storage properly supports 100-continue. - // Skip setting 'expect' header for Google Cloud Storage, there - // are some known issues - https://github.com/restic/restic/issues/520 - if !s3utils.IsGoogleEndpoint(c.endpointURL) && c.s3AccelerateEndpoint == "" { - // Set 'Expect' header for the request. - req.Header.Set("Expect", "100-continue") - } - // Set 'User-Agent' header for the request. c.setUserAgent(req) diff --git a/vendor/github.com/minio/minio-go/core.go b/vendor/github.com/minio/minio-go/core.go index ba12d3b8..ba5f8ef7 100644 --- a/vendor/github.com/minio/minio-go/core.go +++ b/vendor/github.com/minio/minio-go/core.go @@ -17,7 +17,6 @@ package minio import "io" -import "encoding/hex" // Inherits Client and adds new methods to expose the low level S3 APIs. type Core struct { @@ -40,24 +39,14 @@ func (c Core) ListObjects(bucket, prefix, marker, delimiter string, maxKeys int) return c.listObjectsQuery(bucket, prefix, marker, delimiter, maxKeys) } +// ListObjectsV2 - List the objects. +func (c Core) ListObjectsV2(bucketName, objectPrefix, continuationToken string, fetchOwner bool, delimiter string, maxkeys int) (ListBucketV2Result, error) { + return c.listObjectsV2Query(bucketName, objectPrefix, continuationToken, fetchOwner, delimiter, maxkeys) +} + // PutObject - Upload object. Uploads using single PUT call. -func (c Core) PutObject(bucket, object string, size int64, data io.Reader, md5Sum string, sha256Sum string, metadata map[string][]string) (ObjectInfo, error) { - var md5SumBytes []byte - var sha256SumBytes []byte - var err error - if md5Sum != "" { - md5SumBytes, err = hex.DecodeString(md5Sum) - if err != nil { - return ObjectInfo{}, err - } - } - if sha256Sum != "" { - sha256SumBytes, err = hex.DecodeString(sha256Sum) - if err != nil { - return ObjectInfo{}, err - } - } - return c.putObjectDo(bucket, object, data, md5SumBytes, sha256SumBytes, size, metadata) +func (c Core) PutObject(bucket, object string, size int64, data io.Reader, md5Sum, sha256Sum []byte, metadata map[string][]string) (ObjectInfo, error) { + return c.putObjectDo(bucket, object, data, md5Sum, sha256Sum, size, metadata) } // NewMultipartUpload - Initiates new multipart upload and returns the new uploaID. @@ -72,23 +61,8 @@ func (c Core) ListMultipartUploads(bucket, prefix, keyMarker, uploadIDMarker, de } // PutObjectPart - Upload an object part. -func (c Core) PutObjectPart(bucket, object, uploadID string, partID int, size int64, data io.Reader, md5Sum, sha256Sum string) (ObjectPart, error) { - var md5SumBytes []byte - var sha256SumBytes []byte - var err error - if md5Sum != "" { - md5SumBytes, err = hex.DecodeString(md5Sum) - if err != nil { - return ObjectPart{}, err - } - } - if sha256Sum != "" { - sha256SumBytes, err = hex.DecodeString(sha256Sum) - if err != nil { - return ObjectPart{}, err - } - } - return c.uploadPart(bucket, object, uploadID, data, partID, md5SumBytes, sha256SumBytes, size) +func (c Core) PutObjectPart(bucket, object, uploadID string, partID int, size int64, data io.Reader, md5Sum, sha256Sum []byte) (ObjectPart, error) { + return c.uploadPart(bucket, object, uploadID, data, partID, md5Sum, sha256Sum, size) } // ListObjectParts - List uploaded parts of an incomplete upload. diff --git a/vendor/vendor.json b/vendor/vendor.json index 3f023ea4..f8667bd7 100644 --- a/vendor/vendor.json +++ b/vendor/vendor.json @@ -50,10 +50,10 @@ "revisionTime": "2015-10-24T22:24:27-07:00" }, { - "checksumSHA1": "q2mnNtdkxvuzEx8d5W0uCO0wmgI=", + "checksumSHA1": "mDmRRka//itovrS4jtcpVdr0Weg=", "path": "github.com/minio/minio-go", - "revision": "ef0dc7e81b008739bd2ab9cb5b5cfbdc22bf32a5", - "revisionTime": "2017-04-01T21:28:19Z" + "revision": "6d434a3827cdfa3fcf43bde6864fbdd2aad19089", + "revisionTime": "2017-04-08T08:09:03Z" }, { "checksumSHA1": "qTxOBp3GVxCC70ykb7Hxg6UgWwA=", From 0733d37c6795b5a1e0b48767f703d9c89dfc13de Mon Sep 17 00:00:00 2001 From: koolhead17 Date: Tue, 11 Apr 2017 12:56:05 +0530 Subject: [PATCH 07/38] docs: Fix brew command to install mc. (#2121) --- docs/minio-client-complete-guide.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/minio-client-complete-guide.md b/docs/minio-client-complete-guide.md index f635fc4e..ac8d709e 100644 --- a/docs/minio-client-complete-guide.md +++ b/docs/minio-client-complete-guide.md @@ -41,7 +41,7 @@ version Print version. Install minio packages using [Homebrew](http://brew.sh/) ```sh -brew install minio-mc +brew install minio/stable/mc mc --help ``` From 018bcbf6298daf7aa1717960bdefd8d6083439a9 Mon Sep 17 00:00:00 2001 From: Harshavardhana Date: Tue, 11 Apr 2017 04:06:02 -0700 Subject: [PATCH 08/38] cli/docs: Fix all cli docs to be consistent in terms of usage. (#2119) ALIAS should be called as TARGET for all cli commands. --- cmd/admin-config-get.go | 2 +- cmd/admin-config-set.go | 2 +- cmd/{admin-password.go => admin-credentials.go} | 2 +- cmd/admin-heal.go | 2 +- cmd/admin-info.go | 2 +- cmd/admin-lock-clear.go | 2 +- cmd/admin-lock-list.go | 2 +- cmd/admin-service-restart.go | 2 +- cmd/admin-service-status.go | 2 +- cmd/events-add.go | 2 +- cmd/events-list.go | 2 +- cmd/events-remove.go | 2 +- cmd/policy-main.go | 1 + cmd/session-main.go | 2 +- cmd/share-download-main.go | 2 +- cmd/share-upload-main.go | 2 +- 16 files changed, 16 insertions(+), 15 deletions(-) rename cmd/{admin-password.go => admin-credentials.go} (97%) diff --git a/cmd/admin-config-get.go b/cmd/admin-config-get.go index 5370357e..94bc6b9f 100644 --- a/cmd/admin-config-get.go +++ b/cmd/admin-config-get.go @@ -33,7 +33,7 @@ var adminConfigGetCmd = cli.Command{ {{.HelpName}} - {{.Usage}} USAGE: - {{.HelpName}} ALIAS/ + {{.HelpName}} TARGET FLAGS: {{range .VisibleFlags}}{{.}} diff --git a/cmd/admin-config-set.go b/cmd/admin-config-set.go index 3ca717b7..0fe95641 100644 --- a/cmd/admin-config-set.go +++ b/cmd/admin-config-set.go @@ -38,7 +38,7 @@ var adminConfigSetCmd = cli.Command{ {{.HelpName}} - {{.Usage}} USAGE: - {{.HelpName}} ALIAS/ + {{.HelpName}} TARGET FLAGS: {{range .VisibleFlags}}{{.}} diff --git a/cmd/admin-password.go b/cmd/admin-credentials.go similarity index 97% rename from cmd/admin-password.go rename to cmd/admin-credentials.go index e40f9b3d..af020b28 100644 --- a/cmd/admin-password.go +++ b/cmd/admin-credentials.go @@ -36,7 +36,7 @@ var adminCredsCmd = cli.Command{ {{.HelpName}} - {{.Usage}} USAGE: - {{.HelpName}} ALIAS ACCESS_KEY SECRET_KEY + {{.HelpName}} TARGET ACCESS_KEY SECRET_KEY FLAGS: {{range .VisibleFlags}}{{.}} diff --git a/cmd/admin-heal.go b/cmd/admin-heal.go index 9051de05..674b1e74 100644 --- a/cmd/admin-heal.go +++ b/cmd/admin-heal.go @@ -57,7 +57,7 @@ var adminHealCmd = cli.Command{ {{.HelpName}} - {{.Usage}} USAGE: - {{.HelpName}} [FLAGS] [ALIAS] + {{.HelpName}} [FLAGS] TARGET FLAGS: {{range .VisibleFlags}}{{.}} diff --git a/cmd/admin-info.go b/cmd/admin-info.go index 8c26865e..9ff8aa2b 100644 --- a/cmd/admin-info.go +++ b/cmd/admin-info.go @@ -43,7 +43,7 @@ var adminInfoCmd = cli.Command{ {{.HelpName}} - {{.Usage}} USAGE: - {{.HelpName}} ALIAS + {{.HelpName}} TARGET FLAGS: {{range .VisibleFlags}}{{.}} diff --git a/cmd/admin-lock-clear.go b/cmd/admin-lock-clear.go index 126173aa..9283da31 100644 --- a/cmd/admin-lock-clear.go +++ b/cmd/admin-lock-clear.go @@ -51,7 +51,7 @@ var adminLockClearCmd = cli.Command{ {{.HelpName}} - {{.Usage}} USAGE: - {{.HelpName}} ALIAS/BUCKET/PREFIX + {{.HelpName}} [FLAGS] TARGET FLAGS: {{range .VisibleFlags}}{{.}} diff --git a/cmd/admin-lock-list.go b/cmd/admin-lock-list.go index a926c9c5..835440cc 100644 --- a/cmd/admin-lock-list.go +++ b/cmd/admin-lock-list.go @@ -47,7 +47,7 @@ var adminLockListCmd = cli.Command{ {{.HelpName}} - {{.Usage}} USAGE: - {{.HelpName}} ALIAS/BUCKET/PREFIX + {{.HelpName}} [FLAGS] TARGET FLAGS: {{range .VisibleFlags}}{{.}} diff --git a/cmd/admin-service-restart.go b/cmd/admin-service-restart.go index 6ba7d880..eadd30f5 100644 --- a/cmd/admin-service-restart.go +++ b/cmd/admin-service-restart.go @@ -35,7 +35,7 @@ var adminServiceRestartCmd = cli.Command{ {{.HelpName}} - {{.Usage}} USAGE: - {{.HelpName}} ALIAS + {{.HelpName}} TARGET FLAGS: {{range .VisibleFlags}}{{.}} diff --git a/cmd/admin-service-status.go b/cmd/admin-service-status.go index c61782ee..2bfb2598 100644 --- a/cmd/admin-service-status.go +++ b/cmd/admin-service-status.go @@ -42,7 +42,7 @@ var adminServiceStatusCmd = cli.Command{ {{.HelpName}} - {{.Usage}} USAGE: - {{.HelpName}} ALIAS + {{.HelpName}} TARGET FLAGS: {{range .VisibleFlags}}{{.}} diff --git a/cmd/events-add.go b/cmd/events-add.go index 525ff8ee..41ad1437 100644 --- a/cmd/events-add.go +++ b/cmd/events-add.go @@ -54,7 +54,7 @@ var eventsAddCmd = cli.Command{ {{.HelpName}} - {{.Usage}} USAGE: - {{.HelpName}} ALIAS/BUCKET ARN [FLAGS] + {{.HelpName}} TARGET ARN [FLAGS] FLAGS: {{range .VisibleFlags}}{{.}} diff --git a/cmd/events-list.go b/cmd/events-list.go index f7d3a56a..28435de0 100644 --- a/cmd/events-list.go +++ b/cmd/events-list.go @@ -40,7 +40,7 @@ var eventsListCmd = cli.Command{ {{.HelpName}} - {{.Usage}} USAGE: - {{.HelpName}} ALIAS/BUCKET ARN [FLAGS] + {{.HelpName}} TARGET ARN [FLAGS] FLAGS: {{range .VisibleFlags}}{{.}} diff --git a/cmd/events-remove.go b/cmd/events-remove.go index caa80e03..bce4bfe6 100644 --- a/cmd/events-remove.go +++ b/cmd/events-remove.go @@ -45,7 +45,7 @@ var eventsRemoveCmd = cli.Command{ {{.HelpName}} - {{.Usage}} USAGE: - {{.HelpName}} ALIAS/BUCKET [ARN] [FLAGS] + {{.HelpName}} TARGET [ARN] [FLAGS] FLAGS: {{range .VisibleFlags}}{{.}} diff --git a/cmd/policy-main.go b/cmd/policy-main.go index edb57865..ede9d02a 100644 --- a/cmd/policy-main.go +++ b/cmd/policy-main.go @@ -49,6 +49,7 @@ var policyCmd = cli.Command{ USAGE: {{.HelpName}} [FLAGS] PERMISSION TARGET {{.HelpName}} [FLAGS] TARGET + {{.HelpName}} list [FLAGS] TARGET PERMISSION: Allowed policies are: [none, download, upload, public]. diff --git a/cmd/session-main.go b/cmd/session-main.go index 6b8e4815..7709c2c0 100644 --- a/cmd/session-main.go +++ b/cmd/session-main.go @@ -45,7 +45,7 @@ var sessionCmd = cli.Command{ {{.HelpName}} - {{.Usage}} USAGE: - {{.HelpName}} [FLAGS] OPERATION [ARG] + {{.HelpName}} [FLAGS] OPERATION [SESSION-ID] OPERATION: resume Resume a previously saved session. diff --git a/cmd/share-download-main.go b/cmd/share-download-main.go index 58268adc..e25b1fd8 100644 --- a/cmd/share-download-main.go +++ b/cmd/share-download-main.go @@ -44,7 +44,7 @@ var shareDownload = cli.Command{ {{.HelpName}} - {{.Usage}} USAGE: - {{.HelpName}} [OPTIONS] TARGET [TARGET...] + {{.HelpName}} [FLAGS] TARGET [TARGET...] OPTIONS: {{range .VisibleFlags}}{{.}} diff --git a/cmd/share-upload-main.go b/cmd/share-upload-main.go index 46a5bbbe..b8b632f2 100644 --- a/cmd/share-upload-main.go +++ b/cmd/share-upload-main.go @@ -47,7 +47,7 @@ var shareUpload = cli.Command{ {{.HelpName}} - {{.Usage}} USAGE: - {{.HelpName}} [OPTIONS] TARGET [TARGET...] + {{.HelpName}} [FLAGS] TARGET [TARGET...] OPTIONS: {{range .VisibleFlags}}{{.}} From 9ea42680b0cac8dd1c578cc34d886bbef2693805 Mon Sep 17 00:00:00 2001 From: Harshavardhana Date: Tue, 11 Apr 2017 09:08:04 -0700 Subject: [PATCH 09/38] watch/events: Add eventInfo struct for brevity. (#2120) --- cmd/client-fs.go | 58 +++++++++--------------- cmd/client-s3.go | 109 ++++++++++++++++----------------------------- cmd/mirror-main.go | 16 +++---- cmd/watch-main.go | 27 ++++++++--- cmd/watch.go | 82 +++++++++++++--------------------- 5 files changed, 119 insertions(+), 173 deletions(-) diff --git a/cmd/client-fs.go b/cmd/client-fs.go index c2a8d509..9573021d 100644 --- a/cmd/client-fs.go +++ b/cmd/client-fs.go @@ -96,10 +96,7 @@ func (f *fsClient) GetURL() clientURL { // Watches for all fs events on an input path. func (f *fsClient) Watch(params watchParams) (*watchObject, *probe.Error) { - eventChan := make(chan struct { - Event Event - Source Source - }) + eventChan := make(chan EventInfo) errorChan := make(chan *probe.Error) doneChan := make(chan bool) // Make the channel buffered to ensure no event is dropped. Notify will drop @@ -164,50 +161,35 @@ func (f *fsClient) Watch(params watchParams) (*watchObject, *probe.Error) { // we want files continue } - eventChan <- struct { - Event Event - Source Source - }{ - Event: Event{ - Time: time.Now().Format(timeFormatFS), - Size: i.Size(), - Path: event.Path(), - Client: f, - Type: EventCreate, - }, + eventChan <- EventInfo{ + Time: time.Now().Format(timeFormatFS), + Size: i.Size(), + Path: event.Path(), + Client: f, + Type: EventCreate, } } else if IsDeleteEvent(event.Event()) { - eventChan <- struct { - Event Event - Source Source - }{ - Event: Event{ - Time: time.Now().Format(timeFormatFS), - Path: event.Path(), - Client: f, - Type: EventRemove, - }, + eventChan <- EventInfo{ + Time: time.Now().Format(timeFormatFS), + Path: event.Path(), + Client: f, + Type: EventRemove, } } else if IsGetEvent(event.Event()) { - eventChan <- struct { - Event Event - Source Source - }{ - Event: Event{ - Time: time.Now().Format(timeFormatFS), - Path: event.Path(), - Client: f, - Type: EventAccessed, - }, + eventChan <- EventInfo{ + Time: time.Now().Format(timeFormatFS), + Path: event.Path(), + Client: f, + Type: EventAccessed, } } } }() return &watchObject{ - events: eventChan, - errors: errorChan, - done: doneChan, + eventInfoChan: eventChan, + errorChan: errorChan, + doneChan: doneChan, }, nil } diff --git a/cmd/client-s3.go b/cmd/client-s3.go index 7bff5c46..b393c9e2 100644 --- a/cmd/client-s3.go +++ b/cmd/client-s3.go @@ -368,10 +368,7 @@ func (c *s3Client) ListNotificationConfigs(arn string) ([]notificationConfig, *p // Start watching on all bucket events for a given account ID. func (c *s3Client) Watch(params watchParams) (*watchObject, *probe.Error) { - eventChan := make(chan struct { - Event Event - Source Source - }) + eventChan := make(chan EventInfo) errorChan := make(chan *probe.Error) doneChan := make(chan bool) @@ -417,9 +414,9 @@ func (c *s3Client) Watch(params watchParams) (*watchObject, *probe.Error) { eventsCh := c.api.ListenBucketNotification(bucket, params.prefix, params.suffix, events, doneCh) wo := &watchObject{ - events: eventChan, - errors: errorChan, - done: doneChan, + eventInfoChan: eventChan, + errorChan: errorChan, + doneChan: doneChan, } // wait for events to occur and sent them through the eventChan and errorChan @@ -448,76 +445,48 @@ func (c *s3Client) Watch(params watchParams) (*watchObject, *probe.Error) { u := *c.targetURL u.Path = path.Join(string(u.Separator), bucketName, key) if strings.HasPrefix(record.EventName, "s3:ObjectCreated:") { - eventChan <- struct { - Event Event - Source Source - }{ - Event: Event{ - Time: record.EventTime, - Size: record.S3.Object.Size, - Path: u.String(), - Client: c, - Type: EventCreate, - }, - Source: Source{ - IP: record.Source.Host, - Port: record.Source.Port, - UserAgent: record.Source.UserAgent, - }, + eventChan <- EventInfo{ + Time: record.EventTime, + Size: record.S3.Object.Size, + Path: u.String(), + Client: c, + Type: EventCreate, + Host: record.Source.Host, + Port: record.Source.Port, + UserAgent: record.Source.UserAgent, } } else if strings.HasPrefix(record.EventName, "s3:ObjectRemoved:") { - eventChan <- struct { - Event Event - Source Source - }{ - Event: Event{ - Time: record.EventTime, - Path: u.String(), - Client: c, - Type: EventRemove, - }, - Source: Source{ - IP: record.Source.Host, - Port: record.Source.Port, - UserAgent: record.Source.UserAgent, - }, + eventChan <- EventInfo{ + Time: record.EventTime, + Path: u.String(), + Client: c, + Type: EventRemove, + Host: record.Source.Host, + Port: record.Source.Port, + UserAgent: record.Source.UserAgent, } } else if record.EventName == minio.ObjectAccessedGet { - eventChan <- struct { - Event Event - Source Source - }{ - Event: Event{ - Time: record.EventTime, - Size: record.S3.Object.Size, - Path: u.String(), - Client: c, - Type: EventAccessedRead, - }, - Source: Source{ - IP: record.Source.Host, - Port: record.Source.Port, - UserAgent: record.Source.UserAgent, - }, + eventChan <- EventInfo{ + Time: record.EventTime, + Size: record.S3.Object.Size, + Path: u.String(), + Client: c, + Type: EventAccessedRead, + Host: record.Source.Host, + Port: record.Source.Port, + UserAgent: record.Source.UserAgent, } } else if record.EventName == minio.ObjectAccessedHead { - eventChan <- struct { - Event Event - Source Source - }{ - Event: Event{ - Time: record.EventTime, - Size: record.S3.Object.Size, - Path: u.String(), - Client: c, - Type: EventAccessedStat, - }, - Source: Source{ - IP: record.Source.Host, - Port: record.Source.Port, - UserAgent: record.Source.UserAgent, - }, + eventChan <- EventInfo{ + Time: record.EventTime, + Size: record.S3.Object.Size, + Path: u.String(), + Client: c, + Type: EventAccessedStat, + Host: record.Source.Host, + Port: record.Source.Port, + UserAgent: record.Source.UserAgent, } } } diff --git a/cmd/mirror-main.go b/cmd/mirror-main.go index 4f828295..8f38d8f1 100644 --- a/cmd/mirror-main.go +++ b/cmd/mirror-main.go @@ -289,19 +289,19 @@ func (mj *mirrorJob) watchMirror() { } } - sourceURL := newClientURL(event.Event.Path) - aliasedPath := strings.Replace(event.Event.Path, sourceURLFull, mj.sourceURL, -1) + sourceURL := newClientURL(event.Path) + aliasedPath := strings.Replace(event.Path, sourceURLFull, mj.sourceURL, -1) // build target path, it is the relative of the event.Path with the sourceUrl // joined to the targetURL. - sourceSuffix := strings.TrimPrefix(event.Event.Path, sourceURLFull) + sourceSuffix := strings.TrimPrefix(event.Path, sourceURLFull) targetPath := urlJoinPath(mj.targetURL, sourceSuffix) // newClient needs the unexpanded path, newCLientURL needs the expanded path targetAlias, expandedTargetPath, _ := mustExpandAlias(targetPath) targetURL := newClientURL(expandedTargetPath) - if event.Event.Type == EventCreate { + if event.Type == EventCreate { // we are checking if a destination file exists now, and if we only // overwrite it when force is enabled. mirrorURL := URLs{ @@ -310,7 +310,7 @@ func (mj *mirrorJob) watchMirror() { TargetAlias: targetAlias, TargetContent: &clientContent{URL: *targetURL}, } - if event.Event.Size == 0 { + if event.Size == 0 { sourceClient, err := newClient(aliasedPath) if err != nil { // cannot create sourceclient @@ -361,14 +361,14 @@ func (mj *mirrorJob) watchMirror() { shouldQueue = true } if shouldQueue || mj.isForce { - mirrorURL.SourceContent.Size = event.Event.Size + mirrorURL.SourceContent.Size = event.Size mirrorURL.TotalCount = mj.TotalObjects mirrorURL.TotalSize = mj.TotalBytes // adjust total, because we want to show progress of the itemj stiil queued to be copied. - mj.status.SetTotal(mj.status.Total() + event.Event.Size).Update() + mj.status.SetTotal(mj.status.Total() + event.Size).Update() mj.statusCh <- mj.doMirror(mirrorURL) } - } else if event.Event.Type == EventRemove { + } else if event.Type == EventRemove { mirrorURL := URLs{ SourceAlias: sourceAlias, SourceContent: nil, diff --git a/cmd/watch-main.go b/cmd/watch-main.go index f4f4fec2..ebd8ba89 100644 --- a/cmd/watch-main.go +++ b/cmd/watch-main.go @@ -97,8 +97,17 @@ func checkWatchSyntax(ctx *cli.Context) { // watchMessage container to hold one event notification type watchMessage struct { Status string `json:"status"` - Event Event `json:"events"` - Source Source `json:"source,omitempty"` + Event struct { + Time string `json:"time"` + Size int64 `json:"size"` + Path string `json:"path"` + Type EventType `json:"type"` + } `json:"events"` + Source struct { + Host string `json:"host,omitempty"` + Port string `json:"port,omitempty"` + UserAgent string `json:"userAgent,omitempty"` + } `json:"source,omitempty"` } func (u watchMessage) JSON() string { @@ -170,16 +179,20 @@ func mainWatch(ctx *cli.Context) error { select { case <-trapCh: // Signal received we are done. - close(wo.done) + close(wo.doneChan) return case event, ok := <-wo.Events(): if !ok { return } - msg := watchMessage{ - Event: event.Event, - Source: event.Source, - } + 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 { diff --git a/cmd/watch.go b/cmd/watch.go index cc368626..7a618c51 100644 --- a/cmd/watch.go +++ b/cmd/watch.go @@ -40,20 +40,17 @@ const ( EventAccessedStat = "ObjectAccessed:Stat" ) -// Event contains the information of the event that occurred -type Event struct { - Time string `json:"time"` - Size int64 `json:"size"` - Path string `json:"path"` - Client Client `json:"-"` - Type EventType `json:"type"` -} - -// Source obtains the information of the client which generated the event. -type Source struct { - IP string `json:"ip"` - Port string `json:"port"` - UserAgent string `json:"userAgent"` +// EventInfo contains the information of the event that occurred and the source +// IP:PORT of the client which triggerred the event. +type EventInfo struct { + Time string + Size int64 + Path string + Client Client + Type EventType + Host string + Port string + UserAgent string } type watchParams struct { @@ -65,46 +62,37 @@ type watchParams struct { } type watchObject struct { - // events will be put on this chan - events chan struct { - Event Event - Source Source - } + // eventInfo will be put on this chan + eventInfoChan chan EventInfo // errors will be put on this chan - errors chan *probe.Error + errorChan chan *probe.Error // will stop the watcher goroutines - done chan bool + doneChan chan bool } // Events returns the chan receiving events -func (w *watchObject) Events() chan struct { - Event Event - Source Source -} { - return w.events +func (w *watchObject) Events() chan EventInfo { + return w.eventInfoChan } // Errors returns the chan receiving errors func (w *watchObject) Errors() chan *probe.Error { - return w.errors + return w.errorChan } // Close the watcher, will stop all goroutines func (w *watchObject) Close() { - close(w.done) + close(w.doneChan) } // 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 error will be added to this chan + errorChan chan *probe.Error // all events will be added to this chan - eventsChan chan struct { - Event Event - Source Source - } + eventInfoChan chan EventInfo // array of watchers joined o []*watchObject @@ -117,26 +105,20 @@ type Watcher struct { func NewWatcher(sessionStartTime time.Time) *Watcher { return &Watcher{ sessionStartTime: sessionStartTime, - errorsChan: make(chan *probe.Error), - eventsChan: make(chan struct { - Event Event - Source Source - }), - o: []*watchObject{}, + errorChan: make(chan *probe.Error), + eventInfoChan: make(chan EventInfo), + o: []*watchObject{}, } } // Errors returns a channel which will receive errors func (w *Watcher) Errors() chan *probe.Error { - return w.errorsChan + return w.errorChan } // Events returns a channel which will receive events -func (w *Watcher) Events() chan struct { - Event Event - Source Source -} { - return w.eventsChan +func (w *Watcher) Events() chan EventInfo { + return w.eventInfoChan } // Stop watcher @@ -148,8 +130,8 @@ func (w *Watcher) Stop() { w.wg.Wait() - close(w.errorsChan) - close(w.eventsChan) + close(w.errorChan) + close(w.eventInfoChan) } // Watching returns if the watcher is watching for notifications @@ -190,13 +172,13 @@ func (w *Watcher) Join(client Client, recursive bool) *probe.Error { return } - w.eventsChan <- event + w.eventInfoChan <- event case err, ok := <-wo.Errors(): if !ok { return } - w.errorsChan <- err + w.errorChan <- err } } }() From 81f3ffa3af9fdee89f4c0d0d4ffea6e01afbdd5f Mon Sep 17 00:00:00 2001 From: Peter Tribble Date: Wed, 12 Apr 2017 18:55:02 +0100 Subject: [PATCH 10/38] Fix solaris build (#2122) --- cmd/client-fs_other.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmd/client-fs_other.go b/cmd/client-fs_other.go index 6426d79d..40a9c527 100644 --- a/cmd/client-fs_other.go +++ b/cmd/client-fs_other.go @@ -1,4 +1,4 @@ -// +build darwin,freebsd,solaris +// +build darwin freebsd solaris /* * Minio Client (C) 2015, 2016, 2017 Minio, Inc. From 313d0a358fe3e833b6608b69ccdeefd76061ce8f Mon Sep 17 00:00:00 2001 From: Anis Elleuch Date: Sat, 15 Apr 2017 08:20:13 +0100 Subject: [PATCH 11/38] cp: Set exit status to 1 for any error (#2127) Non fatal errors during copy were not setting mc exit code with 1. This commit fixes the behavior. --- cmd/cp-main.go | 128 ++++++++++++++++++++++++------------------------- 1 file changed, 64 insertions(+), 64 deletions(-) diff --git a/cmd/cp-main.go b/cmd/cp-main.go index d4d07fac..0cc274a2 100644 --- a/cmd/cp-main.go +++ b/cmd/cp-main.go @@ -24,7 +24,6 @@ import ( "os" "path/filepath" "strings" - "sync" "syscall" "github.com/cheggaaa/pb" @@ -242,7 +241,7 @@ func doPrepareCopyURLs(session *sessionV8, trapCh <-chan bool) { session.Save() } -func doCopySession(session *sessionV8) { +func doCopySession(session *sessionV8) error { trapCh := signalTrap(os.Interrupt, syscall.SIGTERM, syscall.SIGKILL) if !session.HasData() { @@ -267,75 +266,74 @@ func doCopySession(session *sessionV8) { // Wait on status of doCopy() operation. var statusCh = make(chan URLs) - // Add a wait group. - var wg = new(sync.WaitGroup) - wg.Add(1) - - // Go routine to monitor signal traps if any. go func() { - defer wg.Done() - for { - select { - case <-trapCh: - // Receive interrupt notification. + // Loop through all urls. + for urlScanner.Scan() { + var cpURLs URLs + // Unmarshal copyURLs from each line. + json.Unmarshal([]byte(urlScanner.Text()), &cpURLs) + + // Save total count. + cpURLs.TotalCount = session.Header.TotalObjects + + // Save totalSize. + cpURLs.TotalSize = session.Header.TotalBytes + + // Verify if previously copied, notify progress bar. + if isCopied(cpURLs.SourceContent.URL.String()) { + statusCh <- doCopyFake(cpURLs, progressReader) + } else { + statusCh <- doCopy(cpURLs, progressReader, accntReader) + } + } + + // URLs feeding finished + close(statusCh) + + }() + + var retErr error + +loop: + for { + select { + case <-trapCh: + // Receive interrupt notification. + if !globalQuiet && !globalJSON { + console.Eraseline() + } + session.CloseAndDie() + case cpURLs, ok := <-statusCh: + // Status channel is closed, we should return. + if !ok { + break loop + } + if cpURLs.Error == nil { + session.Header.LastCopied = cpURLs.SourceContent.URL.String() + session.Save() + } else { + + // Set exit status for any copy error + retErr = exitStatus(globalErrorExitStatus) + + // Print in new line and adjust to top so that we + // don't print over the ongoing progress bar. if !globalQuiet && !globalJSON { console.Eraseline() } + errorIf(cpURLs.Error.Trace(cpURLs.SourceContent.URL.String()), + fmt.Sprintf("Failed to copy `%s`.", cpURLs.SourceContent.URL.String())) + if isErrIgnored(cpURLs.Error) { + continue loop + } + // For critical errors we should exit. Session + // can be resumed after the user figures out + // the problem. session.CloseAndDie() - case cpURLs, ok := <-statusCh: - // Status channel is closed, we should return. - if !ok { - return - } - if cpURLs.Error == nil { - session.Header.LastCopied = cpURLs.SourceContent.URL.String() - session.Save() - } else { - // Print in new line and adjust to top so that we - // don't print over the ongoing progress bar. - if !globalQuiet && !globalJSON { - console.Eraseline() - } - errorIf(cpURLs.Error.Trace(cpURLs.SourceContent.URL.String()), - fmt.Sprintf("Failed to copy `%s`.", cpURLs.SourceContent.URL.String())) - if isErrIgnored(cpURLs.Error) { - continue - } - // For critical errors we should exit. Session - // can be resumed after the user figures out - // the problem. - session.CloseAndDie() - } } } - }() - - // Loop through all urls. - for urlScanner.Scan() { - var cpURLs URLs - // Unmarshal copyURLs from each line. - json.Unmarshal([]byte(urlScanner.Text()), &cpURLs) - - // Save total count. - cpURLs.TotalCount = session.Header.TotalObjects - - // Save totalSize. - cpURLs.TotalSize = session.Header.TotalBytes - - // Verify if previously copied, notify progress bar. - if isCopied(cpURLs.SourceContent.URL.String()) { - statusCh <- doCopyFake(cpURLs, progressReader) - } else { - statusCh <- doCopy(cpURLs, progressReader, accntReader) - } } - // Close the goroutine. - close(statusCh) - - // Wait for the goroutines to finish. - wg.Wait() - if !globalQuiet && !globalJSON { if progressReader.ProgressBar.Get() > 0 { progressReader.ProgressBar.Finish() @@ -345,6 +343,8 @@ func doCopySession(session *sessionV8) { console.Println(console.Colorize("Copy", accntReader.Stat().String())) } } + + return retErr } // mainCopy is the entry point for cp command. @@ -368,8 +368,8 @@ func mainCopy(ctx *cli.Context) error { // extract URLs. session.Header.CommandArgs = ctx.Args() - doCopySession(session) + e = doCopySession(session) session.Delete() - return nil + return e } From 1bf5ac350fde25f693e84b8a471a0486c071fb27 Mon Sep 17 00:00:00 2001 From: Anis Elleuch Date: Mon, 17 Apr 2017 04:42:55 +0100 Subject: [PATCH 12/38] madmin: Update and adapt mc to new lib changes (#2131) --- cmd/admin-heal.go | 21 ++++++++--------- .../github.com/minio/minio/pkg/madmin/API.md | 23 +++++++++++++++++++ .../minio/minio/pkg/madmin/heal-commands.go | 15 ++++++++++-- .../minio/minio/pkg/madmin/lock-commands.go | 11 ++++----- vendor/vendor.json | 6 ++--- 5 files changed, 54 insertions(+), 22 deletions(-) diff --git a/cmd/admin-heal.go b/cmd/admin-heal.go index 674b1e74..42f6f992 100644 --- a/cmd/admin-heal.go +++ b/cmd/admin-heal.go @@ -101,9 +101,9 @@ type healMessage struct { // String colorized service status message. func (u healMessage) String() string { - allOfflineTmpl := "isn't healed since %d disks were offline" - allHealedTmpl := "is healed on all %d disks" - someHealedTmpl := "is healed on %d disks while %d disks were offline" + allOfflineTmpl := "is not healed since many disks were offline" + allHealedTmpl := "is healed on all disks" + someHealedTmpl := "is healed on some disks while other disks were offline" msg := "" if u.Object != nil { @@ -112,14 +112,13 @@ func (u healMessage) String() string { msg = fmt.Sprintf("Upload %s/%s/%s ", u.Bucket, u.Upload.Key, u.Upload.UploadID) } - healed, offline := u.Result.HealedCount, u.Result.OfflineCount - switch { - case healed == 0: - msg += fmt.Sprintf(allOfflineTmpl, offline) - case offline == 0: - msg += fmt.Sprintf(allHealedTmpl, healed) - case healed > 0 && offline > 0: - msg += fmt.Sprintf(someHealedTmpl, healed, offline) + switch u.Result.State { + case madmin.HealNone: + msg += allOfflineTmpl + case madmin.HealPartial: + msg += someHealedTmpl + case madmin.HealOK: + msg += allHealedTmpl } return console.Colorize("Heal", msg) diff --git a/vendor/github.com/minio/minio/pkg/madmin/API.md b/vendor/github.com/minio/minio/pkg/madmin/API.md index 0698c97a..dc09b997 100644 --- a/vendor/github.com/minio/minio/pkg/madmin/API.md +++ b/vendor/github.com/minio/minio/pkg/madmin/API.md @@ -245,6 +245,18 @@ __Example__ ### HealObject(bucket, object string, isDryRun bool) (HealResult, error) If object is successfully healed returns nil, otherwise returns error indicating the reason for failure. If isDryRun is true, then the object is not healed, but heal object request is validated by the server. e.g, if the object exists, if object name is valid etc. +| Param | Type | Description | +|---|---|---| +|`h.State` | _HealState_ | Represents the result of heal operation. It could be one of `HealNone`, `HealPartial` or `HealOK`. | + + +| Value | Description | +|---|---| +|`HealNone` | Object/Upload wasn't healed on any of the disks | +|`HealPartial` | Object/Upload was healed on some of the disks needing heal | +| `HealOK` | Object/Upload was healed on all the disks needing heal | + + __Example__ ``` go @@ -327,6 +339,17 @@ __Example__ ### HealUpload(bucket, object, uploadID string, isDryRun bool) (HealResult, error) If upload is successfully healed returns nil, otherwise returns error indicating the reason for failure. If isDryRun is true, then the upload is not healed, but heal upload request is validated by the server. e.g, if the upload exists, if upload name is valid etc. +| Param | Type | Description | +|---|---|---| +|`h.State` | _HealState_ | Represents the result of heal operation. It could be one of `HealNone`, `HealPartial` or `HealOK`. | + + +| Value | Description | +|---|---| +| `HealNone` | Object/Upload wasn't healed on any of the disks | +| `HealPartial` | Object/Upload was healed on some of the disks needing heal | +| `HealOK` | Object/Upload was healed on all the disks needing heal | + ``` go isDryRun = false healResult, err := madmClnt.HealUpload("mybucket", "myobject", "myUploadID", isDryRun) diff --git a/vendor/github.com/minio/minio/pkg/madmin/heal-commands.go b/vendor/github.com/minio/minio/pkg/madmin/heal-commands.go index 8b69236f..4bb2cf6c 100644 --- a/vendor/github.com/minio/minio/pkg/madmin/heal-commands.go +++ b/vendor/github.com/minio/minio/pkg/madmin/heal-commands.go @@ -494,10 +494,21 @@ func (adm *AdminClient) HealUpload(bucket, object, uploadID string, dryrun bool) // HealResult - represents result of heal-object admin API. type HealResult struct { - HealedCount int // number of disks that were healed. - OfflineCount int // number of disks that needed healing but were offline. + State HealState `json:"state"` } +// HealState - different states of heal operation +type HealState int + +const ( + // HealNone - none of the disks healed + HealNone HealState = iota + // HealPartial - some disks were healed, others were offline + HealPartial + // HealOK - all disks were healed + HealOK +) + // HealObject - Heal the given object. func (adm *AdminClient) HealObject(bucket, object string, dryrun bool) (HealResult, error) { // Construct query params. diff --git a/vendor/github.com/minio/minio/pkg/madmin/lock-commands.go b/vendor/github.com/minio/minio/pkg/madmin/lock-commands.go index 3a3b44f5..f21ff460 100644 --- a/vendor/github.com/minio/minio/pkg/madmin/lock-commands.go +++ b/vendor/github.com/minio/minio/pkg/madmin/lock-commands.go @@ -42,12 +42,11 @@ const ( // OpsLockState - represents lock specific details. type OpsLockState struct { - OperationID string `json:"id"` // String containing operation ID. - LockSource string `json:"source"` // Operation type (GetObject, PutObject...) - LockType lockType `json:"type"` // Lock type (RLock, WLock) - Status statusType `json:"status"` // Status can be Running/Ready/Blocked. - Since time.Time `json:"since"` // Time when the lock was initially held. - Duration time.Duration `json:"duration"` // Duration since the lock was held. + OperationID string `json:"id"` // String containing operation ID. + LockSource string `json:"source"` // Operation type (GetObject, PutObject...) + LockType lockType `json:"type"` // Lock type (RLock, WLock) + Status statusType `json:"status"` // Status can be Running/Ready/Blocked. + Since time.Time `json:"since"` // Time when the lock was initially held. } // VolumeLockInfo - represents summary and individual lock details of all diff --git a/vendor/vendor.json b/vendor/vendor.json index f8667bd7..171a2ad8 100644 --- a/vendor/vendor.json +++ b/vendor/vendor.json @@ -80,10 +80,10 @@ "revisionTime": "2016-08-18T00:31:20Z" }, { - "checksumSHA1": "KLEdjpItmkn1LDY/2xTQHSzebnU=", + "checksumSHA1": "v1OEKlUTmnwiQ2RxIFfDhz77Uu0=", "path": "github.com/minio/minio/pkg/madmin", - "revision": "522b307ea67ed04f68fcbf98b67549532a6ac424", - "revisionTime": "2017-04-03T11:36:28Z" + "revision": "3032f0f505437c2f631e304cd64a7c1ed7a3479a", + "revisionTime": "2017-04-15T18:40:01Z" }, { "path": "github.com/minio/minio/pkg/probe", From 9eb967cabfc9f71a463192e321ae333509ec1e15 Mon Sep 17 00:00:00 2001 From: Scott McClellan Date: Mon, 17 Apr 2017 17:37:11 -0700 Subject: [PATCH 13/38] minor fixes to `mc share download` command (#2106) improved error messages and issue with `--recursive` option. Fixes #2099 --- cmd/client-errors.go | 2 +- cmd/share-download-main.go | 12 +++++++++--- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/cmd/client-errors.go b/cmd/client-errors.go index 2a22f2a3..bc7b5f42 100644 --- a/cmd/client-errors.go +++ b/cmd/client-errors.go @@ -150,7 +150,7 @@ func (e EmptyPath) Error() string { type ObjectMissing struct{} func (e ObjectMissing) Error() string { - return "Object key is missing, object key cannot be empty" + return "Object does not exist" } // UnexpectedShortWrite - write wrote less bytes than expected. diff --git a/cmd/share-download-main.go b/cmd/share-download-main.go index e25b1fd8..c6f3105f 100644 --- a/cmd/share-download-main.go +++ b/cmd/share-download-main.go @@ -89,9 +89,15 @@ func checkShareDownloadSyntax(ctx *cli.Context) { fatalIf(errDummy().Trace(expiry.String()), "Expiry cannot be larger than 7 days.") } - for _, url := range ctx.Args() { - _, _, err := url2Stat(url) - fatalIf(err.Trace(url), "Unable to stat `"+url+"`.") + // Validate if object exists only if the `--recursive` option was NOT specified + isRecursive := ctx.Bool("recursive") + if !isRecursive { + for _, url := range ctx.Args() { + _, _, err := url2Stat(url) + if err != nil { + fatalIf(err.Trace(url), "Unable to stat `"+url+"`.") + } + } } } From 656f4f13d0e8e75f3719a8d778c1a9af782eafdf Mon Sep 17 00:00:00 2001 From: Anis Elleuch Date: Tue, 18 Apr 2017 20:37:54 +0100 Subject: [PATCH 14/38] session: Close data session file when migrating (#2126) Cleanup needed before removing the data file --- cmd/session-main.go | 4 ++-- cmd/session-migrate.go | 3 +++ 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/cmd/session-main.go b/cmd/session-main.go index 7709c2c0..34ddaac8 100644 --- a/cmd/session-main.go +++ b/cmd/session-main.go @@ -134,7 +134,7 @@ func clearSession(sid string) { session, err := loadSessionV8(sid) fatalIf(err.Trace(sid), "Unable to load session `"+sid+"`.") - fatalIf(session.Delete().Trace(sid), "Unable to load session `"+sid+"`.") + fatalIf(session.Delete().Trace(sid), "Unable to remove session `"+sid+"`.") printMsg(clearSessionMessage{Status: "success", SessionID: sid}) } @@ -156,7 +156,7 @@ func clearSession(sid string) { } if session != nil { - fatalIf(session.Delete().Trace(sid), "Unable to load session `"+sid+"`.") + fatalIf(session.Delete().Trace(sid), "Unable to remove session `"+sid+"`.") printMsg(clearSessionMessage{Status: "success", SessionID: sid}) } } diff --git a/cmd/session-migrate.go b/cmd/session-migrate.go index dbc8fb55..4735bc55 100644 --- a/cmd/session-migrate.go +++ b/cmd/session-migrate.go @@ -37,6 +37,9 @@ func migrateSessionV7ToV8() { fatalIf(err.Trace(sid), "Unable to load version `7`. Migration failed please report this issue at https://github.com/minio/mc/issues.") } + // Close underlying session data file. + sV7.DataFP.Close() + sessionVersion, e := strconv.Atoi(sV7.Header.Version) fatalIf(probe.NewError(e), "Unable to load version `7`. Migration failed please report this issue at https://github.com/minio/mc/issues.") if sessionVersion > 7 { // It is new format. From 9a881562b93f5fb7af0968ab85282896caa81f9f Mon Sep 17 00:00:00 2001 From: Anis Elleuch Date: Tue, 18 Apr 2017 20:43:09 +0100 Subject: [PATCH 15/38] watch: Fix regression in watch local fs events (#2133) --- cmd/client-fs_linux.go | 6 +++--- cmd/client-fs_other.go | 4 ++-- cmd/client-fs_windows.go | 6 +++--- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/cmd/client-fs_linux.go b/cmd/client-fs_linux.go index 1ee38cb7..cf734062 100644 --- a/cmd/client-fs_linux.go +++ b/cmd/client-fs_linux.go @@ -34,7 +34,7 @@ var ( // IsGetEvent checks if the event return is a get event. func IsGetEvent(event notify.Event) bool { for _, ev := range EventTypeGet { - if event == ev { + if event&ev != 0 { return true } } @@ -44,7 +44,7 @@ func IsGetEvent(event notify.Event) bool { // IsPutEvent checks if the event returned is a put event func IsPutEvent(event notify.Event) bool { for _, ev := range EventTypePut { - if event == ev { + if event&ev != 0 { return true } } @@ -54,7 +54,7 @@ func IsPutEvent(event notify.Event) bool { // IsDeleteEvent checks if the event returned is a delete event func IsDeleteEvent(event notify.Event) bool { for _, ev := range EventTypeDelete { - if event == ev { + if event&ev != 0 { return true } } diff --git a/cmd/client-fs_other.go b/cmd/client-fs_other.go index 40a9c527..fd2cbb1f 100644 --- a/cmd/client-fs_other.go +++ b/cmd/client-fs_other.go @@ -37,7 +37,7 @@ func IsGetEvent(event notify.Event) bool { // IsPutEvent checks if the event returned is a put event func IsPutEvent(event notify.Event) bool { for _, ev := range EventTypePut { - if event == ev { + if event&ev != 0 { return true } } @@ -46,5 +46,5 @@ func IsPutEvent(event notify.Event) bool { // IsDeleteEvent checks if the event returned is a delete event func IsDeleteEvent(event notify.Event) bool { - return event == notify.Remove + return event¬ify.Remove != 0 } diff --git a/cmd/client-fs_windows.go b/cmd/client-fs_windows.go index f28bc5d6..b7784538 100644 --- a/cmd/client-fs_windows.go +++ b/cmd/client-fs_windows.go @@ -31,13 +31,13 @@ var ( // IsGetEvent checks if the event return is a get event. func IsGetEvent(event notify.Event) bool { - return event == notify.FileNotifyChangeLastAccess + return event¬ify.FileNotifyChangeLastAccess != 0 } // IsPutEvent checks if the event returned is a put event func IsPutEvent(event notify.Event) bool { for _, ev := range EventTypePut { - if event == ev { + if event&ev != 0 { return true } } @@ -46,5 +46,5 @@ func IsPutEvent(event notify.Event) bool { // IsDeleteEvent checks if the event returned is a delete event func IsDeleteEvent(event notify.Event) bool { - return event == notify.Remove + return event¬ify.Remove != 0 } From 9bdb7affb110b4a5b47d706c7ce67193b556617d Mon Sep 17 00:00:00 2001 From: Harshavardhana Date: Thu, 20 Apr 2017 14:42:10 -0700 Subject: [PATCH 16/38] build: Fix add macOS source work-around for Go bug. (#2138) Upstream bug https://github.com/golang/go/issues/19734 Fixes #2137 --- Makefile | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Makefile b/Makefile index 5940d0ad..ffb3d0c2 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,5 @@ LDFLAGS := $(shell go run buildscripts/gen-ldflags.go) +BUILD_LDFLAGS := '$(LDFLAGS) -s -w' all: install @@ -59,7 +60,7 @@ test: getdeps verifiers gomake-all: build @echo "Installing mc:" - @go build --ldflags "$(LDFLAGS)" -o $(GOPATH)/bin/mc + @go build --ldflags $(BUILD_LDFLAGS) -o $(GOPATH)/bin/mc @mkdir -p $(HOME)/.mc coverage: getdeps verifiers From dd9e715599c31d3117e08546c02879f6a22940e6 Mon Sep 17 00:00:00 2001 From: Scott McClellan Date: Sat, 22 Apr 2017 14:15:27 -0700 Subject: [PATCH 17/38] Improved Error Msg For Bucket Names that Contain non-LOWERCASE chars (#2134) (#2135) --- cmd/client-s3.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmd/client-s3.go b/cmd/client-s3.go index b393c9e2..7ec36563 100644 --- a/cmd/client-s3.go +++ b/cmd/client-s3.go @@ -746,7 +746,7 @@ func isValidBucketName(bucketName string) *probe.Error { return probe.NewError(errors.New("Bucket name should be more than 3 characters and less than 64 characters")) } if !validBucketName.MatchString(bucketName) { - return probe.NewError(errors.New("Bucket name can contain alphabet, '-' and numbers, but first character should be an alphabet or number")) + return probe.NewError(errors.New("Bucket names can only contain lowercase alpha characters `a-z`, numbers '0-9', or '-'. First/last character cannot be a '-'")) } return nil } From 61e511cc3e4d80f7910869c37a3a200b2e438d10 Mon Sep 17 00:00:00 2001 From: Anis Elleuch Date: Mon, 24 Apr 2017 09:01:11 +0100 Subject: [PATCH 18/38] fs watch: Use a dynamically sized channel (#2109) Write a growing/shrinking channel to be able to absorb filesystem notify events even when they come in large numbers. --- cmd/client-fs.go | 8 +-- cmd/pipechan.go | 89 +++++++++++++++++++++++++++ cmd/pipechan_test.go | 141 +++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 234 insertions(+), 4 deletions(-) create mode 100644 cmd/pipechan.go create mode 100644 cmd/pipechan_test.go diff --git a/cmd/client-fs.go b/cmd/client-fs.go index 9573021d..2f605fc5 100644 --- a/cmd/client-fs.go +++ b/cmd/client-fs.go @@ -101,7 +101,7 @@ func (f *fsClient) Watch(params watchParams) (*watchObject, *probe.Error) { doneChan := make(chan bool) // 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. - neventChan := make(chan notify.EventInfo, 1) + in, out := PipeChan(1000) var fsEvents []notify.Event for _, event := range params.events { @@ -123,7 +123,7 @@ func (f *fsClient) Watch(params watchParams) (*watchObject, *probe.Error) { if params.recursive { recursivePath = f.PathURL.Path + "..." } - if e := notify.Watch(recursivePath, neventChan, fsEvents...); e != nil { + if e := notify.Watch(recursivePath, in, fsEvents...); e != nil { return nil, probe.NewError(e) } @@ -133,7 +133,7 @@ func (f *fsClient) Watch(params watchParams) (*watchObject, *probe.Error) { close(eventChan) close(errorChan) - notify.Stop(neventChan) + notify.Stop(in) }() timeFormatFS := "2006-01-02T15:04:05.000Z" @@ -141,7 +141,7 @@ func (f *fsClient) Watch(params watchParams) (*watchObject, *probe.Error) { // Get fsnotify notifications for events and errors, and sent them // using eventChan and errorChan go func() { - for event := range neventChan { + for event := range out { if isIgnoredFile(event.Path()) { continue } diff --git a/cmd/pipechan.go b/cmd/pipechan.go new file mode 100644 index 00000000..9458e7fe --- /dev/null +++ b/cmd/pipechan.go @@ -0,0 +1,89 @@ +/* + * Minio Client (C) 2017 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 cmd + +import "github.com/rjeczalik/notify" + +// Dynamically sized logical channel: a pipe which never blocks even when +// it receives too many elements. Memory consumption is increased and decresed +// on the fly following the number of elements. Here is the benchmark which +// compares a regular channel which a large capacity (like 1 Million) in +// contrast to a PipeChan with an realtime increasing/decreasing capacity. +// +// BenchmarkRegular1M-4 200 172809399 ns/op +// BenchmarkPipeChan1M-4 100 316668338 ns/op +// BenchmarkRegular100K-4 2000 16540648 ns/op +// BenchmarkPipeChan100K-4 1000 31905966 ns/op +// BenchmarkRegular10K-4 20000 1637665 ns/op +// BenchmarkPipeChan10K-4 10000 3324329 ns/op +// BenchmarkRegular1K-4 200000 168512 ns/op +// BenchmarkPipeChan1K-4 100000 550623 ns/op + +// PipeChan builds a new dynamically sized channel +func PipeChan(capacity int) (inputCh chan notify.EventInfo, outputCh chan notify.EventInfo) { + + // A set of channels which store all elements received from input + channels := make(chan chan notify.EventInfo, 1000) + + inputCh = make(chan notify.EventInfo, capacity) + + // A goroutine which receives elements from inputCh and creates + // new channels when needed. + go func() { + // Create the first channel + currCh := make(chan notify.EventInfo, capacity) + channels <- currCh + + for elem := range inputCh { + // Prepare next channel with a double capacity when + // half of the current channel is already filled. + if len(currCh) >= cap(currCh)/2 { + close(currCh) + currCh = make(chan notify.EventInfo, cap(currCh)*2) + channels <- currCh + } + // Prepare next channel with half capacity when + // current channel is 1/4 filled + if len(currCh) >= capacity && len(currCh) <= cap(currCh)/4 { + close(currCh) + currCh = make(chan notify.EventInfo, cap(currCh)/2) + channels <- currCh + } + // Send element to current channel + currCh <- elem + } + + close(currCh) + close(channels) + }() + + // Copy elements from infinite channel set to the output + outputCh = make(chan notify.EventInfo, capacity) + go func() { + for { + currCh, ok := <-channels + if !ok { + break + } + for v := range currCh { + outputCh <- v + } + } + close(outputCh) + }() + return inputCh, outputCh +} diff --git a/cmd/pipechan_test.go b/cmd/pipechan_test.go new file mode 100644 index 00000000..752ad359 --- /dev/null +++ b/cmd/pipechan_test.go @@ -0,0 +1,141 @@ +/* + * Minio Client (C) 2017 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 cmd + +import ( + "fmt" + "sync" + "testing" + + "github.com/rjeczalik/notify" +) + +func testPipeChan(inputCh, outputCh chan notify.EventInfo, totalMsgs int) error { + + var wg sync.WaitGroup + + msgCtnt := notify.EventInfo(nil) + + // Send messages up to totalMsgs + wg.Add(1) + go func() { + defer wg.Done() + for i := 0; i < totalMsgs; i++ { + select { + case inputCh <- msgCtnt: + } + } + close(inputCh) + }() + + // Goroutine to receive and check messages + var recvMsgs int + var recvErr error + + wg.Add(1) + + go func() { + defer wg.Done() + for msg := range outputCh { + recvMsgs++ + if msg != msgCtnt { + recvErr = fmt.Errorf("Corrupted message, expected = `%s`, found = `%s`", msgCtnt, msg) + return + } + } + }() + + // Wait until we finish sending and receiving messages + wg.Wait() + + if recvErr != nil { + return recvErr + } + + // Check if all messages are received + if recvMsgs != totalMsgs { + return fmt.Errorf("unable to receive all messages, expected: %d, lost: %d", totalMsgs, totalMsgs-recvMsgs) + } + + return nil +} + +// Testing code + +func TestPipeChannel(t *testing.T) { + fastCh, slowCh := PipeChan(1000) + err := testPipeChan(fastCh, slowCh, 10*1000) + if err != nil { + t.Errorf("ERR: %v\n", err) + } +} + +func TestRegularChannel(t *testing.T) { + ch := make(chan notify.EventInfo, 1000) + err := testPipeChan(ch, ch, 10*1000) + if err != nil { + t.Errorf("ERR: %v\n", err) + } +} + +// Benchmark code + +func benchmarkRegular(b *testing.B, msgsNum int) { + for n := 0; n < b.N; n++ { + ch := make(chan notify.EventInfo, msgsNum) + testPipeChan(ch, ch, msgsNum) + } +} + +func benchmarkPipeChan(b *testing.B, msgsNum int) { + for n := 0; n < b.N; n++ { + fastCh, slowCh := PipeChan(1000) + testPipeChan(fastCh, slowCh, msgsNum) + } +} + +func BenchmarkRegular1M(b *testing.B) { + benchmarkRegular(b, 1*1000*1000) +} + +func BenchmarkPipeChan1M(b *testing.B) { + benchmarkPipeChan(b, 1*1000*1000) +} + +func BenchmarkRegular100K(b *testing.B) { + benchmarkRegular(b, 100*1000) +} + +func BenchmarkPipeChan100K(b *testing.B) { + benchmarkPipeChan(b, 100*1000) +} + +func BenchmarkRegular10K(b *testing.B) { + benchmarkRegular(b, 10*1000) +} + +func BenchmarkPipeChan10K(b *testing.B) { + benchmarkPipeChan(b, 10*1000) +} + +func BenchmarkRegular1K(b *testing.B) { + benchmarkRegular(b, 1*1000) +} + +func BenchmarkPipeChan1K(b *testing.B) { + benchmarkPipeChan(b, 1*1000) +} From 39aa635971f26d1e2068742c315b196c1fb974db Mon Sep 17 00:00:00 2001 From: Marco Liceti Date: Wed, 26 Apr 2017 22:50:32 +0200 Subject: [PATCH 19/38] Added configure section with note for Docker users (#2141) --- README.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/README.md b/README.md index 1e6007e7..68821ae6 100644 --- a/README.md +++ b/README.md @@ -34,6 +34,14 @@ docker pull minio/mc:edge docker run minio/mc:edge ls play ``` +**Note:** Above examples run `mc` against Minio [_play_ environment](#test-your-setup) by default. To run `mc` against other S3 compatible servers, start the container this way: + +```sh +docker run -it --entrypoint=/bin/sh minio/mc +``` + +then use the [`mc config` command](#add-a-cloud-storage-service). + ## macOS ### Homebrew Install mc packages using [Homebrew](http://brew.sh/) From e54962e17f48f5e0082b17ae779831add5b22b0e Mon Sep 17 00:00:00 2001 From: Anis Elleuch Date: Fri, 28 Apr 2017 21:13:44 +0100 Subject: [PATCH 20/38] mb: Add -p flag to ignore existing bucket/dir (#2143) If a remote directory/bucket exists, -p will still make mb cmd happy if the target already exists. --- cmd/client-fs.go | 5 ++++- cmd/client-fs_test.go | 6 +++--- cmd/client-s3.go | 11 ++++++++++- cmd/client-s3_test.go | 2 +- cmd/client.go | 2 +- cmd/mb-main.go | 7 ++++++- cmd/mirror-main.go | 2 +- 7 files changed, 26 insertions(+), 9 deletions(-) diff --git a/cmd/client-fs.go b/cmd/client-fs.go index 2f605fc5..19853c7b 100644 --- a/cmd/client-fs.go +++ b/cmd/client-fs.go @@ -942,7 +942,10 @@ func (f *fsClient) listRecursiveInRoutine(contentCh chan *clientContent) { } // MakeBucket - create a new bucket. -func (f *fsClient) MakeBucket(region string) *probe.Error { +func (f *fsClient) MakeBucket(region string, ignoreExisting bool) *probe.Error { + // TODO: ignoreExisting has no effect currently. In the future, we want + // to call os.Mkdir() when ignoredExisting is disabled and os.MkdirAll() + // otherwise. e := os.MkdirAll(f.PathURL.Path, 0777) if e != nil { return probe.NewError(e) diff --git a/cmd/client-fs_test.go b/cmd/client-fs_test.go index b4b64b4f..e56c3885 100644 --- a/cmd/client-fs_test.go +++ b/cmd/client-fs_test.go @@ -193,7 +193,7 @@ func (s *TestSuite) TestPutBucket(c *C) { bucketPath := filepath.Join(root, "bucket") fsClient, err := fsNew(bucketPath) c.Assert(err, IsNil) - err = fsClient.MakeBucket("us-east-1") + err = fsClient.MakeBucket("us-east-1", true) c.Assert(err, IsNil) } @@ -207,7 +207,7 @@ func (s *TestSuite) TestStatBucket(c *C) { fsClient, err := fsNew(bucketPath) c.Assert(err, IsNil) - err = fsClient.MakeBucket("us-east-1") + err = fsClient.MakeBucket("us-east-1", true) c.Assert(err, IsNil) _, err = fsClient.Stat(false) c.Assert(err, IsNil) @@ -222,7 +222,7 @@ func (s *TestSuite) TestBucketACLFails(c *C) { bucketPath := filepath.Join(root, "bucket") fsClient, err := fsNew(bucketPath) c.Assert(err, IsNil) - err = fsClient.MakeBucket("us-east-1") + err = fsClient.MakeBucket("us-east-1", true) c.Assert(err, IsNil) // On windows setting permissions is not supported. diff --git a/cmd/client-s3.go b/cmd/client-s3.go index 7ec36563..e75f2949 100644 --- a/cmd/client-s3.go +++ b/cmd/client-s3.go @@ -752,7 +752,7 @@ func isValidBucketName(bucketName string) *probe.Error { } // MakeBucket - make a new bucket. -func (c *s3Client) MakeBucket(region string) *probe.Error { +func (c *s3Client) MakeBucket(region string, ignoreExisting bool) *probe.Error { bucket, object := c.url2BucketAndObject() if object != "" { return probe.NewError(BucketNameTopLevel{}) @@ -762,6 +762,15 @@ func (c *s3Client) MakeBucket(region string) *probe.Error { } e := c.api.MakeBucket(bucket, region) if e != nil { + // Ignore bucket already existing error when ignoreExisting flag is enabled + if ignoreExisting { + switch minio.ToErrorResponse(e).Code { + case "BucketAlreadyOwnedByYou": + fallthrough + case "BucketAlreadyExists": + return nil + } + } return probe.NewError(e) } return nil diff --git a/cmd/client-s3_test.go b/cmd/client-s3_test.go index 5a189629..c7e69361 100644 --- a/cmd/client-s3_test.go +++ b/cmd/client-s3_test.go @@ -174,7 +174,7 @@ func (s *TestSuite) TestBucketOperations(c *C) { s3c, err := s3New(conf) c.Assert(err, IsNil) - err = s3c.MakeBucket("us-east-1") + err = s3c.MakeBucket("us-east-1", true) c.Assert(err, IsNil) conf.HostURL = server.URL + string(s3c.GetURL().Separator) diff --git a/cmd/client.go b/cmd/client.go index 7c8a45c2..9b8a6285 100644 --- a/cmd/client.go +++ b/cmd/client.go @@ -43,7 +43,7 @@ type Client interface { List(isRecursive, isIncomplete bool, showDir DirOpt) <-chan *clientContent // Bucket operations - MakeBucket(region string) *probe.Error + MakeBucket(region string, ignoreExisting bool) *probe.Error // Access policy operations. GetAccess() (access string, error *probe.Error) diff --git a/cmd/mb-main.go b/cmd/mb-main.go index 7bda23fe..11d16f2e 100644 --- a/cmd/mb-main.go +++ b/cmd/mb-main.go @@ -32,6 +32,10 @@ var ( Value: "us-east-1", Usage: "Specify bucket region. Defaults to `us-east-1`.", }, + cli.BoolFlag{ + Name: "ignore-existing, p", + Usage: "Ignore if bucket/directory already exists", + }, } ) @@ -108,6 +112,7 @@ func mainMakeBucket(ctx *cli.Context) error { // Save region. region := ctx.String("region") + ignoreExisting := ctx.Bool("p") var cErr error for i := range ctx.Args() { @@ -121,7 +126,7 @@ func mainMakeBucket(ctx *cli.Context) error { } // Make bucket. - err = clnt.MakeBucket(region) + err = clnt.MakeBucket(region, ignoreExisting) if err != nil { errorIf(err.Trace(targetURL), "Unable to make bucket `"+targetURL+"`.") cErr = exitStatus(globalErrorExitStatus) diff --git a/cmd/mirror-main.go b/cmd/mirror-main.go index 8f38d8f1..b7e096dc 100644 --- a/cmd/mirror-main.go +++ b/cmd/mirror-main.go @@ -578,7 +578,7 @@ func runMirror(srcURL, dstURL string, ctx *cli.Context) *probe.Error { if d.Diff == differInFirst { // Bucket only exists in the source, create the same bucket in the destination - err := newDstClt.MakeBucket(ctx.String("region")) + err := newDstClt.MakeBucket(ctx.String("region"), false) if err != nil { mj.mirrorErr = err errorIf(err, "Cannot created bucket in `"+newTgtURL+"`") From 136e286ef4e02e5f3ee527af491fcf9f9183062a Mon Sep 17 00:00:00 2001 From: Anis Elleuch Date: Sat, 29 Apr 2017 08:34:26 +0100 Subject: [PATCH 21/38] mb: Update pkg to retry mb with unmatched region (#2139) --- .../minio/minio-go/api-error-response.go | 46 +-- .../minio/minio-go/api-get-object.go | 9 +- .../minio/minio-go/api-get-policy.go | 30 +- .../minio/minio-go/api-put-bucket.go | 94 ++++-- .../minio/minio-go/api-put-object-file.go | 18 +- .../minio-go/api-put-object-multipart.go | 106 +++++++ .../minio/minio-go/api-put-object-progress.go | 107 +++++-- .../minio/minio-go/api-put-object-readat.go | 2 +- .../minio/minio-go/api-put-object.go | 1 - .../github.com/minio/minio-go/api-remove.go | 1 - .../minio/minio-go/api-s3-datatypes.go | 12 +- vendor/github.com/minio/minio-go/api.go | 88 +++--- vendor/github.com/minio/minio-go/constants.go | 10 + vendor/github.com/minio/minio-go/core.go | 30 +- .../{encryption-cbc.go => pkg/encrypt/cbc.go} | 56 ++-- .../encrypt/interface.go} | 34 ++- .../encrypt/keys.go} | 11 +- .../minio-go/pkg/policy/bucket-policy.go | 9 +- .../s3signer/request-signature-streaming.go | 285 ++++++++++++++++++ .../pkg/s3signer/request-signature-v4.go | 20 +- .../minio/minio-go/pkg/set/stringset.go | 8 +- vendor/github.com/minio/minio-go/retry.go | 12 +- vendor/github.com/minio/minio-go/s3-error.go | 60 ++++ .../minio/minio-go/signature-type.go | 6 + vendor/vendor.json | 30 +- 25 files changed, 848 insertions(+), 237 deletions(-) rename vendor/github.com/minio/minio-go/{encryption-cbc.go => pkg/encrypt/cbc.go} (80%) rename vendor/github.com/minio/minio-go/{encryption.go => pkg/encrypt/interface.go} (53%) rename vendor/github.com/minio/minio-go/{encryption-keys.go => pkg/encrypt/keys.go} (94%) create mode 100644 vendor/github.com/minio/minio-go/pkg/s3signer/request-signature-streaming.go create mode 100644 vendor/github.com/minio/minio-go/s3-error.go diff --git a/vendor/github.com/minio/minio-go/api-error-response.go b/vendor/github.com/minio/minio-go/api-error-response.go index fee3c7d5..04d9a2a1 100644 --- a/vendor/github.com/minio/minio-go/api-error-response.go +++ b/vendor/github.com/minio/minio-go/api-error-response.go @@ -1,5 +1,5 @@ /* - * Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2015 Minio, Inc. + * Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2015, 2016, 2017 Minio, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,6 +48,9 @@ type ErrorResponse struct { // Region where the bucket is located. This header is returned // only in HEAD bucket and ListObjects response. Region string + + // Headers of the returned S3 XML error + Headers http.Header `xml:"-" json:"-"` } // ToErrorResponse - Returns parsed ErrorResponse struct from body and @@ -72,8 +75,15 @@ func ToErrorResponse(err error) ErrorResponse { } } -// Error - Returns HTTP error string +// Error - Returns S3 error string. func (e ErrorResponse) Error() string { + if e.Message == "" { + msg, ok := s3ErrorResponseMap[e.Code] + if !ok { + msg = fmt.Sprintf("Error response code %s.", e.Code) + } + return msg + } return e.Message } @@ -91,6 +101,7 @@ func httpRespToErrorResponse(resp *http.Response, bucketName, objectName string) return ErrInvalidArgument(msg) } var errResp ErrorResponse + err := xmlDecoder(resp.Body, &errResp) // Xml decoding failed with no body, fall back to HTTP headers. if err != nil { @@ -101,9 +112,6 @@ func httpRespToErrorResponse(resp *http.Response, bucketName, objectName string) Code: "NoSuchBucket", Message: "The specified bucket does not exist.", BucketName: bucketName, - RequestID: resp.Header.Get("x-amz-request-id"), - HostID: resp.Header.Get("x-amz-id-2"), - Region: resp.Header.Get("x-amz-bucket-region"), } } else { errResp = ErrorResponse{ @@ -111,9 +119,6 @@ func httpRespToErrorResponse(resp *http.Response, bucketName, objectName string) Message: "The specified key does not exist.", BucketName: bucketName, Key: objectName, - RequestID: resp.Header.Get("x-amz-request-id"), - HostID: resp.Header.Get("x-amz-id-2"), - Region: resp.Header.Get("x-amz-bucket-region"), } } case http.StatusForbidden: @@ -122,30 +127,37 @@ func httpRespToErrorResponse(resp *http.Response, bucketName, objectName string) Message: "Access Denied.", BucketName: bucketName, Key: objectName, - RequestID: resp.Header.Get("x-amz-request-id"), - HostID: resp.Header.Get("x-amz-id-2"), - Region: resp.Header.Get("x-amz-bucket-region"), } case http.StatusConflict: errResp = ErrorResponse{ Code: "Conflict", Message: "Bucket not empty.", BucketName: bucketName, - RequestID: resp.Header.Get("x-amz-request-id"), - HostID: resp.Header.Get("x-amz-id-2"), - Region: resp.Header.Get("x-amz-bucket-region"), } default: errResp = ErrorResponse{ Code: resp.Status, Message: resp.Status, BucketName: bucketName, - RequestID: resp.Header.Get("x-amz-request-id"), - HostID: resp.Header.Get("x-amz-id-2"), - Region: resp.Header.Get("x-amz-bucket-region"), } } } + + // Save hodID, requestID and region information + // from headers if not available through error XML. + if errResp.RequestID == "" { + errResp.RequestID = resp.Header.Get("x-amz-request-id") + } + if errResp.HostID == "" { + errResp.HostID = resp.Header.Get("x-amz-id-2") + } + if errResp.Region == "" { + errResp.Region = resp.Header.Get("x-amz-bucket-region") + } + + // Save headers returned in the API XML error + errResp.Headers = resp.Header + return errResp } diff --git a/vendor/github.com/minio/minio-go/api-get-object.go b/vendor/github.com/minio/minio-go/api-get-object.go index ade94c2d..8066f70f 100644 --- a/vendor/github.com/minio/minio-go/api-get-object.go +++ b/vendor/github.com/minio/minio-go/api-get-object.go @@ -24,10 +24,12 @@ import ( "strings" "sync" "time" + + "github.com/minio/minio-go/pkg/encrypt" ) // GetEncryptedObject deciphers and streams data stored in the server after applying a specifed encryption materiels -func (c Client) GetEncryptedObject(bucketName, objectName string, encryptMaterials EncryptionMaterials) (io.Reader, error) { +func (c Client) GetEncryptedObject(bucketName, objectName string, encryptMaterials encrypt.Materials) (io.Reader, error) { if encryptMaterials == nil { return nil, ErrInvalidArgument("Unable to recognize empty encryption properties") @@ -44,8 +46,11 @@ func (c Client) GetEncryptedObject(bucketName, objectName string, encryptMateria return nil, err } - encryptMaterials.SetupDecryptMode(encReader, st.Metadata) + // Setup object for decrytion, object is transparently + // decrypted as the consumer starts reading. + encryptMaterials.SetupDecryptMode(encReader, st.Metadata.Get(amzHeaderIV), st.Metadata.Get(amzHeaderKey)) + // Success. return encryptMaterials, nil } diff --git a/vendor/github.com/minio/minio-go/api-get-policy.go b/vendor/github.com/minio/minio-go/api-get-policy.go index da0a409c..50b91901 100644 --- a/vendor/github.com/minio/minio-go/api-get-policy.go +++ b/vendor/github.com/minio/minio-go/api-get-policy.go @@ -34,8 +34,12 @@ func (c Client) GetBucketPolicy(bucketName, objectPrefix string) (bucketPolicy p if err := isValidObjectPrefix(objectPrefix); err != nil { return policy.BucketPolicyNone, err } - policyInfo, err := c.getBucketPolicy(bucketName, objectPrefix) + policyInfo, err := c.getBucketPolicy(bucketName) if err != nil { + errResponse := ToErrorResponse(err) + if errResponse.Code == "NoSuchBucketPolicy" { + return policy.BucketPolicyNone, nil + } return policy.BucketPolicyNone, err } return policy.GetPolicy(policyInfo.Statements, bucketName, objectPrefix), nil @@ -50,15 +54,24 @@ func (c Client) ListBucketPolicies(bucketName, objectPrefix string) (bucketPolic if err := isValidObjectPrefix(objectPrefix); err != nil { return map[string]policy.BucketPolicy{}, err } - policyInfo, err := c.getBucketPolicy(bucketName, objectPrefix) + policyInfo, err := c.getBucketPolicy(bucketName) if err != nil { + errResponse := ToErrorResponse(err) + if errResponse.Code == "NoSuchBucketPolicy" { + return map[string]policy.BucketPolicy{}, nil + } return map[string]policy.BucketPolicy{}, err } return policy.GetPolicies(policyInfo.Statements, bucketName), nil } +// Default empty bucket access policy. +var emptyBucketAccessPolicy = policy.BucketAccessPolicy{ + Version: "2012-10-17", +} + // Request server for current bucket policy. -func (c Client) getBucketPolicy(bucketName string, objectPrefix string) (policy.BucketAccessPolicy, error) { +func (c Client) getBucketPolicy(bucketName string) (policy.BucketAccessPolicy, error) { // Get resources properly escaped and lined up before // using them in http request. urlValues := make(url.Values) @@ -72,21 +85,18 @@ func (c Client) getBucketPolicy(bucketName string, objectPrefix string) (policy. defer closeResponse(resp) if err != nil { - return policy.BucketAccessPolicy{}, err + return emptyBucketAccessPolicy, err } if resp != nil { if resp.StatusCode != http.StatusOK { - errResponse := httpRespToErrorResponse(resp, bucketName, "") - if ToErrorResponse(errResponse).Code == "NoSuchBucketPolicy" { - return policy.BucketAccessPolicy{Version: "2012-10-17"}, nil - } - return policy.BucketAccessPolicy{}, errResponse + return emptyBucketAccessPolicy, httpRespToErrorResponse(resp, bucketName, "") } } + bucketPolicyBuf, err := ioutil.ReadAll(resp.Body) if err != nil { - return policy.BucketAccessPolicy{}, err + return emptyBucketAccessPolicy, err } policy := policy.BucketAccessPolicy{} diff --git a/vendor/github.com/minio/minio-go/api-put-bucket.go b/vendor/github.com/minio/minio-go/api-put-bucket.go index 7c7e03f4..11c2735a 100644 --- a/vendor/github.com/minio/minio-go/api-put-bucket.go +++ b/vendor/github.com/minio/minio-go/api-put-bucket.go @@ -41,7 +41,14 @@ import ( // // For Amazon S3 for more supported regions - http://docs.aws.amazon.com/general/latest/gr/rande.html // For Google Cloud Storage for more supported regions - https://cloud.google.com/storage/docs/bucket-locations -func (c Client) MakeBucket(bucketName string, location string) error { +func (c Client) MakeBucket(bucketName string, location string) (err error) { + defer func() { + // Save the location into cache on a successful makeBucket response. + if err == nil { + c.bucketLocCache.Set(bucketName, location) + } + }() + // Validate the input arguments. if err := isValidBucketName(bucketName); err != nil { return err @@ -52,45 +59,70 @@ func (c Client) MakeBucket(bucketName string, location string) error { location = "us-east-1" } - // Instantiate the request. - req, err := c.makeBucketRequest(bucketName, location) - if err != nil { - return err - } + // Try creating bucket with the provided region, in case of + // invalid region error let's guess the appropriate region + // from S3 API headers - // Execute the request. - resp, err := c.do(req) - defer closeResponse(resp) - if err != nil { - return err - } + // Create a done channel to control 'newRetryTimer' go routine. + doneCh := make(chan struct{}, 1) - if resp != nil { - if resp.StatusCode != http.StatusOK { - return httpRespToErrorResponse(resp, bucketName, "") + // Indicate to our routine to exit cleanly upon return. + defer close(doneCh) + + // Blank indentifier is kept here on purpose since 'range' without + // blank identifiers is only supported since go1.4 + // https://golang.org/doc/go1.4#forrange. + for _ = range c.newRetryTimer(MaxRetry, DefaultRetryUnit, DefaultRetryCap, MaxJitter, doneCh) { + // Initialize the makeBucket request. + req, err := c.makeBucketRequest(bucketName, location) + if err != nil { + return err } + + // Execute make bucket request. + resp, err := c.do(req) + defer closeResponse(resp) + if err != nil { + return err + } + + if resp.StatusCode != http.StatusOK { + err := httpRespToErrorResponse(resp, bucketName, "") + errResp := ToErrorResponse(err) + if errResp.Code == "InvalidRegion" && errResp.Region != "" { + // Fetch bucket region found in headers + // of S3 error response, attempt bucket + // create again. + location = errResp.Region + continue + } + // Nothing to retry, fail. + return err + } + + // Control reaches here when bucket create was successful, + // break out. + break } - // Save the location into cache on a successful makeBucket response. - c.bucketLocCache.Set(bucketName, location) - - // Return. + // Success. return nil } -// makeBucketRequest constructs request for makeBucket. +// Low level wrapper API For makeBucketRequest. func (c Client) makeBucketRequest(bucketName string, location string) (*http.Request, error) { // Validate input arguments. if err := isValidBucketName(bucketName); err != nil { return nil, err } - // In case of Amazon S3. The make bucket issued on already - // existing bucket would fail with 'AuthorizationMalformed' error - // if virtual style is used. So we default to 'path style' as that - // is the preferred method here. The final location of the - // 'bucket' is provided through XML LocationConstraint data with - // the request. + // In case of Amazon S3. The make bucket issued on + // already existing bucket would fail with + // 'AuthorizationMalformed' error if virtual style is + // used. So we default to 'path style' as that is the + // preferred method here. The final location of the + // 'bucket' is provided through XML LocationConstraint + // data with the request. targetURL := c.endpointURL targetURL.Path = path.Join(bucketName, "") + "/" @@ -103,7 +135,8 @@ func (c Client) makeBucketRequest(bucketName string, location string) (*http.Req // set UserAgent for the request. c.setUserAgent(req) - // set sha256 sum for signature calculation only with signature version '4'. + // set sha256 sum for signature calculation only with + // signature version '4'. if c.signature.isV4() { req.Header.Set("X-Amz-Content-Sha256", hex.EncodeToString(sum256([]byte{}))) } @@ -157,11 +190,14 @@ func (c Client) SetBucketPolicy(bucketName string, objectPrefix string, bucketPo if err := isValidObjectPrefix(objectPrefix); err != nil { return err } + if !bucketPolicy.IsValidBucketPolicy() { return ErrInvalidArgument(fmt.Sprintf("Invalid bucket policy provided. %s", bucketPolicy)) } - policyInfo, err := c.getBucketPolicy(bucketName, objectPrefix) - if err != nil { + + policyInfo, err := c.getBucketPolicy(bucketName) + errResponse := ToErrorResponse(err) + if err != nil && errResponse.Code != "NoSuchBucketPolicy" { return err } diff --git a/vendor/github.com/minio/minio-go/api-put-object-file.go b/vendor/github.com/minio/minio-go/api-put-object-file.go index f67999f9..09fec769 100644 --- a/vendor/github.com/minio/minio-go/api-put-object-file.go +++ b/vendor/github.com/minio/minio-go/api-put-object-file.go @@ -91,25 +91,11 @@ func (c Client) FPutObject(bucketName, objectName, filePath, contentType string) return c.putObjectNoChecksum(bucketName, objectName, fileReader, fileSize, objMetadata, nil) } - // NOTE: S3 doesn't allow anonymous multipart requests. - if s3utils.IsAmazonEndpoint(c.endpointURL) && c.anonymous { - if fileSize > int64(maxSinglePutObjectSize) { - return 0, ErrorResponse{ - Code: "NotImplemented", - Message: fmt.Sprintf("For anonymous requests Content-Length cannot be %d.", fileSize), - Key: objectName, - BucketName: bucketName, - } - } - // Do not compute MD5 for anonymous requests to Amazon - // S3. Uploads up to 5GiB in size. - return c.putObjectNoChecksum(bucketName, objectName, fileReader, fileSize, objMetadata, nil) - } - // Small object upload is initiated for uploads for input data size smaller than 5MiB. if fileSize < minPartSize && fileSize >= 0 { return c.putObjectSingle(bucketName, objectName, fileReader, fileSize, objMetadata, nil) } + // Upload all large objects as multipart. n, err = c.putObjectMultipartFromFile(bucketName, objectName, fileReader, fileSize, objMetadata, nil) if err != nil { @@ -187,7 +173,7 @@ func (c Client) putObjectMultipartFromFile(bucketName, objectName string, fileRe close(uploadPartsCh) // Use three 'workers' to upload parts in parallel. - for w := 1; w <= 3; w++ { + for w := 1; w <= totalWorkers; w++ { go func() { // Deal with each part as it comes through the channel. for uploadReq := range uploadPartsCh { diff --git a/vendor/github.com/minio/minio-go/api-put-object-multipart.go b/vendor/github.com/minio/minio-go/api-put-object-multipart.go index 6ca44b21..3a299f65 100644 --- a/vendor/github.com/minio/minio-go/api-put-object-multipart.go +++ b/vendor/github.com/minio/minio-go/api-put-object-multipart.go @@ -66,6 +66,112 @@ func (c Client) putObjectMultipart(bucketName, objectName string, reader io.Read return c.putObjectMultipartStream(bucketName, objectName, reader, size, metaData, progress) } +// putObjectMultipartStreamNoChecksum - upload a large object using +// multipart upload and streaming signature for signing payload. +// N B We don't resume an incomplete multipart upload, we overwrite +// existing parts of an incomplete upload. +func (c Client) putObjectMultipartStreamNoChecksum(bucketName, objectName string, + reader io.Reader, size int64, metadata map[string][]string, progress io.Reader) (int64, error) { + + // Input validation. + if err := isValidBucketName(bucketName); err != nil { + return 0, err + } + if err := isValidObjectName(objectName); err != nil { + return 0, err + } + + // Get the upload id of a previously partially uploaded object or initiate a new multipart upload + uploadID, err := c.findUploadID(bucketName, objectName) + if err != nil { + return 0, err + } + if uploadID == "" { + // Initiates a new multipart request + uploadID, err = c.newUploadID(bucketName, objectName, metadata) + if err != nil { + return 0, err + } + } + + // Calculate the optimal parts info for a given size. + totalPartsCount, partSize, lastPartSize, err := optimalPartInfo(size) + if err != nil { + return 0, err + } + + // Total data read and written to server. should be equal to 'size' at the end of the call. + var totalUploadedSize int64 + + // Initialize parts uploaded map. + partsInfo := make(map[int]ObjectPart) + + // Part number always starts with '1'. + var partNumber int + for partNumber = 1; partNumber <= totalPartsCount; partNumber++ { + // Update progress reader appropriately to the latest offset + // as we read from the source. + hookReader := newHook(reader, progress) + + // Proceed to upload the part. + if partNumber == totalPartsCount { + partSize = lastPartSize + } + + var objPart ObjectPart + objPart, err = c.uploadPart(bucketName, objectName, uploadID, + io.LimitReader(hookReader, partSize), partNumber, nil, nil, partSize) + // For unknown size, Read EOF we break away. + // We do not have to upload till totalPartsCount. + if err == io.EOF && size < 0 { + break + } + + if err != nil { + return totalUploadedSize, err + } + + // Save successfully uploaded part metadata. + partsInfo[partNumber] = objPart + + // Save successfully uploaded size. + totalUploadedSize += partSize + } + + // Verify if we uploaded all the data. + if size > 0 { + if totalUploadedSize != size { + return totalUploadedSize, ErrUnexpectedEOF(totalUploadedSize, size, bucketName, objectName) + } + } + + // Complete multipart upload. + var complMultipartUpload completeMultipartUpload + + // Loop over total uploaded parts to save them in + // Parts array before completing the multipart request. + for i := 1; i < partNumber; i++ { + part, ok := partsInfo[i] + if !ok { + return 0, ErrInvalidArgument(fmt.Sprintf("Missing part number %d", i)) + } + complMultipartUpload.Parts = append(complMultipartUpload.Parts, CompletePart{ + ETag: part.ETag, + PartNumber: part.PartNumber, + }) + } + + // Sort all completed parts. + sort.Sort(completedParts(complMultipartUpload.Parts)) + _, err = c.completeMultipartUpload(bucketName, objectName, uploadID, complMultipartUpload) + if err != nil { + return totalUploadedSize, err + } + + // Return final size. + return totalUploadedSize, nil +} + // putObjectStream uploads files bigger than 64MiB, and also supports // special case where size is unknown i.e '-1'. func (c Client) putObjectMultipartStream(bucketName, objectName string, reader io.Reader, size int64, metaData map[string][]string, progress io.Reader) (n int64, err error) { diff --git a/vendor/github.com/minio/minio-go/api-put-object-progress.go b/vendor/github.com/minio/minio-go/api-put-object-progress.go index 43f39c0f..f3844127 100644 --- a/vendor/github.com/minio/minio-go/api-put-object-progress.go +++ b/vendor/github.com/minio/minio-go/api-put-object-progress.go @@ -20,6 +20,7 @@ import ( "io" "strings" + "github.com/minio/minio-go/pkg/encrypt" "github.com/minio/minio-go/pkg/s3utils" ) @@ -31,7 +32,7 @@ func (c Client) PutObjectWithProgress(bucketName, objectName string, reader io.R } // PutEncryptedObject - Encrypt and store object. -func (c Client) PutEncryptedObject(bucketName, objectName string, reader io.Reader, encryptMaterials EncryptionMaterials, metaData map[string][]string, progress io.Reader) (n int64, err error) { +func (c Client) PutEncryptedObject(bucketName, objectName string, reader io.Reader, encryptMaterials encrypt.Materials, metaData map[string][]string, progress io.Reader) (n int64, err error) { if encryptMaterials == nil { return 0, ErrInvalidArgument("Unable to recognize empty encryption properties") @@ -44,9 +45,11 @@ func (c Client) PutEncryptedObject(bucketName, objectName string, reader io.Read if metaData == nil { metaData = make(map[string][]string) } - for k, v := range encryptMaterials.GetHeaders() { - metaData[k] = v - } + + // Set the necessary encryption headers, for future decryption. + metaData[amzHeaderIV] = []string{encryptMaterials.GetIV()} + metaData[amzHeaderKey] = []string{encryptMaterials.GetKey()} + metaData[amzHeaderMatDesc] = []string{encryptMaterials.GetDesc()} return c.PutObjectWithMetadata(bucketName, objectName, encryptMaterials, metaData, progress) } @@ -96,24 +99,6 @@ func (c Client) PutObjectWithMetadata(bucketName, objectName string, reader io.R return c.putObjectNoChecksum(bucketName, objectName, reader, size, metaData, progress) } - // NOTE: S3 doesn't allow anonymous multipart requests. - if s3utils.IsAmazonEndpoint(c.endpointURL) && c.anonymous { - if size <= -1 { - return 0, ErrorResponse{ - Code: "NotImplemented", - Message: "Content-Length cannot be negative for anonymous requests.", - Key: objectName, - BucketName: bucketName, - } - } - if size > maxSinglePutObjectSize { - return 0, ErrEntityTooLarge(size, maxSinglePutObjectSize, bucketName, objectName) - } - // Do not compute MD5 for anonymous requests to Amazon - // S3. Uploads up to 5GiB in size. - return c.putObjectNoChecksum(bucketName, objectName, reader, size, metaData, progress) - } - // putSmall object. if size < minPartSize && size >= 0 { return c.putObjectSingle(bucketName, objectName, reader, size, metaData, progress) @@ -136,3 +121,81 @@ func (c Client) PutObjectWithMetadata(bucketName, objectName string, reader io.R } return n, nil } + +// PutObjectStreaming using AWS streaming signature V4 +func (c Client) PutObjectStreaming(bucketName, objectName string, reader io.Reader) (n int64, err error) { + return c.PutObjectStreamingWithProgress(bucketName, objectName, reader, nil, nil) +} + +// PutObjectStreamingWithMetadata using AWS streaming signature V4 +func (c Client) PutObjectStreamingWithMetadata(bucketName, objectName string, reader io.Reader, metadata map[string][]string) (n int64, err error) { + return c.PutObjectStreamingWithProgress(bucketName, objectName, reader, metadata, nil) +} + +// PutObjectStreamingWithProgress using AWS streaming signature V4 +func (c Client) PutObjectStreamingWithProgress(bucketName, objectName string, reader io.Reader, metadata map[string][]string, progress io.Reader) (n int64, err error) { + // NOTE: Streaming signature is not supported by GCS. + if s3utils.IsGoogleEndpoint(c.endpointURL) { + return 0, ErrorResponse{ + Code: "NotImplemented", + Message: "AWS streaming signature v4 is not supported with Google Cloud Storage", + Key: objectName, + BucketName: bucketName, + } + } + // This method should return error with signature v2 minioClient. + if c.signature.isV2() { + return 0, ErrorResponse{ + Code: "NotImplemented", + Message: "AWS streaming signature v4 is not supported with minio client initialized for AWS signature v2", + Key: objectName, + BucketName: bucketName, + } + } + + // Size of the object. + var size int64 + + // Get reader size. + size, err = getReaderSize(reader) + if err != nil { + return 0, err + } + + // Check for largest object size allowed. + if size > int64(maxMultipartPutObjectSize) { + return 0, ErrEntityTooLarge(size, maxMultipartPutObjectSize, bucketName, objectName) + } + + // If size cannot be found on a stream, it is not possible + // to upload using streaming signature, fall back to multipart. + if size < 0 { + return c.putObjectMultipartStream(bucketName, objectName, reader, size, metadata, progress) + } + + // Set signature type to streaming signature v4. + c.signature = SignatureV4Streaming + + if size < minPartSize && size >= 0 { + return c.putObjectNoChecksum(bucketName, objectName, reader, size, metadata, progress) + } + + // For all sizes greater than 64MiB do multipart. + n, err = c.putObjectMultipartStreamNoChecksum(bucketName, objectName, reader, size, metadata, progress) + if err != nil { + errResp := ToErrorResponse(err) + // Verify if multipart functionality is not available, if not + // fall back to single PutObject operation. + if errResp.Code == "AccessDenied" && strings.Contains(errResp.Message, "Access Denied") { + // Verify if size of reader is greater than '5GiB'. + if size > maxSinglePutObjectSize { + return 0, ErrEntityTooLarge(size, maxSinglePutObjectSize, bucketName, objectName) + } + // Fall back to uploading as single PutObject operation. + return c.putObjectNoChecksum(bucketName, objectName, reader, size, metadata, progress) + } + return n, err + } + + return n, nil +} diff --git a/vendor/github.com/minio/minio-go/api-put-object-readat.go b/vendor/github.com/minio/minio-go/api-put-object-readat.go index c2cf56e0..ebf42263 100644 --- a/vendor/github.com/minio/minio-go/api-put-object-readat.go +++ b/vendor/github.com/minio/minio-go/api-put-object-readat.go @@ -115,7 +115,7 @@ func (c Client) putObjectMultipartFromReadAt(bucketName, objectName string, read close(uploadPartsCh) // Receive each part number from the channel allowing three parallel uploads. - for w := 1; w <= 3; w++ { + for w := 1; w <= totalWorkers; w++ { go func() { // Read defaults to reading at 5MiB buffer. readAtBuffer := make([]byte, optimalReadBufferSize) diff --git a/vendor/github.com/minio/minio-go/api-put-object.go b/vendor/github.com/minio/minio-go/api-put-object.go index bc2eeb25..e218075d 100644 --- a/vendor/github.com/minio/minio-go/api-put-object.go +++ b/vendor/github.com/minio/minio-go/api-put-object.go @@ -143,7 +143,6 @@ func (a completedParts) Less(i, j int) bool { return a[i].PartNumber < a[j].Part // NOTE: Google Cloud Storage does not implement Amazon S3 Compatible multipart PUT. // So we fall back to single PUT operation with the maximum limit of 5GiB. // -// NOTE: For anonymous requests Amazon S3 doesn't allow multipart upload. So we fall back to single PUT operation. func (c Client) PutObject(bucketName, objectName string, reader io.Reader, contentType string) (n int64, err error) { return c.PutObjectWithProgress(bucketName, objectName, reader, contentType, nil) } diff --git a/vendor/github.com/minio/minio-go/api-remove.go b/vendor/github.com/minio/minio-go/api-remove.go index 2ca84458..68194887 100644 --- a/vendor/github.com/minio/minio-go/api-remove.go +++ b/vendor/github.com/minio/minio-go/api-remove.go @@ -208,7 +208,6 @@ func (c Client) RemoveObjects(bucketName string, objectsCh <-chan string) <-chan } // RemoveIncompleteUpload aborts an partially uploaded object. -// Requires explicit authentication, no anonymous requests are allowed for multipart API. func (c Client) RemoveIncompleteUpload(bucketName, objectName string) error { // Input validation. if err := isValidBucketName(bucketName); err != nil { diff --git a/vendor/github.com/minio/minio-go/api-s3-datatypes.go b/vendor/github.com/minio/minio-go/api-s3-datatypes.go index 5bd0bcc5..ec63d6b9 100644 --- a/vendor/github.com/minio/minio-go/api-s3-datatypes.go +++ b/vendor/github.com/minio/minio-go/api-s3-datatypes.go @@ -41,7 +41,7 @@ type commonPrefix struct { Prefix string } -// listBucketResult container for listObjects V2 response. +// ListBucketV2Result container for listObjects response version 2. type ListBucketV2Result struct { // A response can contain CommonPrefixes only if you have // specified a delimiter. @@ -70,7 +70,7 @@ type ListBucketV2Result struct { StartAfter string } -// listBucketResult container for listObjects response. +// ListBucketResult container for listObjects response. type ListBucketResult struct { // A response can contain CommonPrefixes only if you have // specified a delimiter. @@ -102,7 +102,7 @@ type ListBucketResult struct { Prefix string } -// listMultipartUploadsResult container for ListMultipartUploads response +// ListMultipartUploadsResult container for ListMultipartUploads response type ListMultipartUploadsResult struct { Bucket string KeyMarker string @@ -131,7 +131,7 @@ type copyObjectResult struct { LastModified string // time string format "2006-01-02T15:04:05.000Z" } -// objectPart container for particular part of an object. +// ObjectPart container for particular part of an object. type ObjectPart struct { // Part number identifies the part. PartNumber int @@ -147,7 +147,7 @@ type ObjectPart struct { Size int64 } -// listObjectPartsResult container for ListObjectParts response. +// ListObjectPartsResult container for ListObjectParts response. type ListObjectPartsResult struct { Bucket string Key string @@ -185,7 +185,7 @@ type completeMultipartUploadResult struct { ETag string } -// completePart sub container lists individual part numbers and their +// CompletePart sub container lists individual part numbers and their // md5sum, part of completeMultipartUpload. type CompletePart struct { XMLName xml.Name `xml:"http://s3.amazonaws.com/doc/2006-03-01/ Part" json:"-"` diff --git a/vendor/github.com/minio/minio-go/api.go b/vendor/github.com/minio/minio-go/api.go index d5821c01..c851e016 100644 --- a/vendor/github.com/minio/minio-go/api.go +++ b/vendor/github.com/minio/minio-go/api.go @@ -20,6 +20,7 @@ import ( "bytes" "encoding/base64" "encoding/hex" + "errors" "fmt" "io" "io/ioutil" @@ -198,9 +199,6 @@ func privateNew(endpoint, accessKeyID, secretAccessKey string, secure bool) (*Cl clnt := new(Client) clnt.accessKeyID = accessKeyID clnt.secretAccessKey = secretAccessKey - if clnt.accessKeyID == "" || clnt.secretAccessKey == "" { - clnt.anonymous = true - } // Remember whether we are using https or not clnt.secure = secure @@ -316,8 +314,7 @@ var regSign = regexp.MustCompile("Signature=([[0-9a-f]+)") // Filter out signature value from Authorization header. func (c Client) filterSignature(req *http.Request) { - // For anonymous requests, no need to filter. - if c.anonymous { + if _, ok := req.Header["Authorization"]; !ok { return } // Handle if Signature V2. @@ -428,7 +425,7 @@ func (c Client) do(req *http.Request) (*http.Response, error) { return nil, &url.Error{ Op: urlErr.Op, URL: urlErr.URL, - Err: fmt.Errorf("Connection closed by foreign host %s. Retry again.", urlErr.URL), + Err: errors.New("Connection closed by foreign host " + urlErr.URL + ". Retry again."), } } return nil, err @@ -477,9 +474,13 @@ func (c Client) executeMethod(method string, metadata requestMetadata) (res *htt if metadata.contentBody != nil { // Check if body is seekable then it is retryable. bodySeeker, isRetryable = metadata.contentBody.(io.Seeker) + switch bodySeeker { + case os.Stdin, os.Stdout, os.Stderr: + isRetryable = false + } } - // Create a done channel to control 'ListObjects' go routine. + // Create a done channel to control 'newRetryTimer' go routine. doneCh := make(chan struct{}, 1) // Indicate to our routine to exit cleanly upon return. @@ -488,7 +489,7 @@ func (c Client) executeMethod(method string, metadata requestMetadata) (res *htt // Blank indentifier is kept here on purpose since 'range' without // blank identifiers is only supported since go1.4 // https://golang.org/doc/go1.4#forrange. - for _ = range c.newRetryTimer(MaxRetry, time.Second, time.Second*30, MaxJitter, doneCh) { + for _ = range c.newRetryTimer(MaxRetry, DefaultRetryUnit, DefaultRetryCap, MaxJitter, doneCh) { // Retry executes the following function body if request has an // error until maxRetries have been exhausted, retry attempts are // performed after waiting for a given period of time in a @@ -537,14 +538,21 @@ func (c Client) executeMethod(method string, metadata requestMetadata) (res *htt if err != nil { return nil, err } + // Save the body. errBodySeeker := bytes.NewReader(errBodyBytes) res.Body = ioutil.NopCloser(errBodySeeker) // For errors verify if its retryable otherwise fail quickly. errResponse := ToErrorResponse(httpRespToErrorResponse(res, metadata.bucketName, metadata.objectName)) - // Bucket region if set in error response and the error code dictates invalid region, - // we can retry the request with the new region. + + // Save the body back again. + errBodySeeker.Seek(0, 0) // Seek back to starting point. + res.Body = ioutil.NopCloser(errBodySeeker) + + // Bucket region if set in error response and the error + // code dictates invalid region, we can retry the request + // with the new region. if errResponse.Code == "InvalidRegion" && errResponse.Region != "" { c.bucketLocCache.Set(metadata.bucketName, errResponse.Region) continue // Retry. @@ -560,10 +568,6 @@ func (c Client) executeMethod(method string, metadata requestMetadata) (res *htt continue // Retry. } - // Save the body back again. - errBodySeeker.Seek(0, 0) // Seek back to starting point. - res.Body = ioutil.NopCloser(errBodySeeker) - // For all other cases break out of the retry loop. break } @@ -610,15 +614,18 @@ func (c Client) newRequest(method string, metadata requestMetadata) (req *http.R return nil, err } + // Anonymous request. + anonymous := c.accessKeyID == "" || c.secretAccessKey == "" + // Generate presign url if needed, return right here. if metadata.expires != 0 && metadata.presignURL { - if c.anonymous { + if anonymous { return nil, ErrInvalidArgument("Requests cannot be presigned with anonymous credentials.") } if c.signature.isV2() { // Presign URL with signature v2. req = s3signer.PreSignV2(*req, c.accessKeyID, c.secretAccessKey, metadata.expires) - } else { + } else if c.signature.isV4() { // Presign URL with signature v4. req = s3signer.PreSignV4(*req, c.accessKeyID, c.secretAccessKey, location, metadata.expires) } @@ -638,37 +645,36 @@ func (c Client) newRequest(method string, metadata requestMetadata) (req *http.R req.ContentLength = metadata.contentLength } - // Set sha256 sum only for non anonymous credentials. - if !c.anonymous { - // set sha256 sum for signature calculation only with - // signature version '4'. - if c.signature.isV4() { - shaHeader := unsignedPayload - if !c.secure { - if metadata.contentSHA256Bytes == nil { - shaHeader = hex.EncodeToString(sum256([]byte{})) - } else { - shaHeader = hex.EncodeToString(metadata.contentSHA256Bytes) - } - } - req.Header.Set("X-Amz-Content-Sha256", shaHeader) - } - } - // set md5Sum for content protection. if metadata.contentMD5Bytes != nil { req.Header.Set("Content-Md5", base64.StdEncoding.EncodeToString(metadata.contentMD5Bytes)) } - // Sign the request for all authenticated requests. - if !c.anonymous { - if c.signature.isV2() { - // Add signature version '2' authorization header. - req = s3signer.SignV2(*req, c.accessKeyID, c.secretAccessKey) - } else if c.signature.isV4() { - // Add signature version '4' authorization header. - req = s3signer.SignV4(*req, c.accessKeyID, c.secretAccessKey, location) + if anonymous { + return req, nil + } // Sign the request for all authenticated requests. + + if c.signature.isV2() { + // Add signature version '2' authorization header. + req = s3signer.SignV2(*req, c.accessKeyID, c.secretAccessKey) + } else if c.signature.isV4() || c.signature.isStreamingV4() && + method != "PUT" { + // Set sha256 sum for signature calculation only with signature version '4'. + shaHeader := unsignedPayload + if !c.secure { + if metadata.contentSHA256Bytes == nil { + shaHeader = hex.EncodeToString(sum256([]byte{})) + } else { + shaHeader = hex.EncodeToString(metadata.contentSHA256Bytes) + } } + req.Header.Set("X-Amz-Content-Sha256", shaHeader) + + // Add signature version '4' authorization header. + req = s3signer.SignV4(*req, c.accessKeyID, c.secretAccessKey, location) + } else if c.signature.isStreamingV4() { + req = s3signer.StreamingSignV4(req, c.accessKeyID, + c.secretAccessKey, location, metadata.contentLength, time.Now().UTC()) } // Return request. diff --git a/vendor/github.com/minio/minio-go/constants.go b/vendor/github.com/minio/minio-go/constants.go index 057c3eef..6055bfda 100644 --- a/vendor/github.com/minio/minio-go/constants.go +++ b/vendor/github.com/minio/minio-go/constants.go @@ -45,8 +45,18 @@ const optimalReadBufferSize = 1024 * 1024 * 5 // we don't want to sign the request payload const unsignedPayload = "UNSIGNED-PAYLOAD" +// Total number of parallel workers used for multipart operation. +var totalWorkers = 3 + // Signature related constants. const ( signV4Algorithm = "AWS4-HMAC-SHA256" iso8601DateFormat = "20060102T150405Z" ) + +// Encryption headers stored along with the object. +const ( + amzHeaderIV = "X-Amz-Meta-X-Amz-Iv" + amzHeaderKey = "X-Amz-Meta-X-Amz-Key" + amzHeaderMatDesc = "X-Amz-Meta-X-Amz-Matdesc" +) diff --git a/vendor/github.com/minio/minio-go/core.go b/vendor/github.com/minio/minio-go/core.go index ba5f8ef7..90154d94 100644 --- a/vendor/github.com/minio/minio-go/core.go +++ b/vendor/github.com/minio/minio-go/core.go @@ -16,14 +16,20 @@ package minio -import "io" +import ( + "io" -// Inherits Client and adds new methods to expose the low level S3 APIs. + "github.com/minio/minio-go/pkg/policy" +) + +// Core - Inherits Client and adds new methods to expose the low level S3 APIs. type Core struct { *Client } -// NewCoreClient - Returns new Core. +// NewCore - Returns new initialized a Core client, this CoreClient should be +// only used under special conditions such as need to access lower primitives +// and being able to use them to write your own wrappers. func NewCore(endpoint string, accessKeyID, secretAccessKey string, secure bool) (*Core, error) { var s3Client Core client, err := NewV4(endpoint, accessKeyID, secretAccessKey, secure) @@ -34,12 +40,14 @@ func NewCore(endpoint string, accessKeyID, secretAccessKey string, secure bool) return &s3Client, nil } -// ListObjects - List the objects. +// ListObjects - List all the objects at a prefix, optionally with marker and delimiter +// you can further filter the results. func (c Core) ListObjects(bucket, prefix, marker, delimiter string, maxKeys int) (result ListBucketResult, err error) { return c.listObjectsQuery(bucket, prefix, marker, delimiter, maxKeys) } -// ListObjectsV2 - List the objects. +// ListObjectsV2 - Lists all the objects at a prefix, similar to ListObjects() but uses +// continuationToken instead of marker to further filter the results. func (c Core) ListObjectsV2(bucketName, objectPrefix, continuationToken string, fetchOwner bool, delimiter string, maxkeys int) (ListBucketV2Result, error) { return c.listObjectsV2Query(bucketName, objectPrefix, continuationToken, fetchOwner, delimiter, maxkeys) } @@ -65,7 +73,7 @@ func (c Core) PutObjectPart(bucket, object, uploadID string, partID int, size in return c.uploadPart(bucket, object, uploadID, data, partID, md5Sum, sha256Sum, size) } -// ListObjectParts - List uploaded parts of an incomplete upload. +// ListObjectParts - List uploaded parts of an incomplete upload.x func (c Core) ListObjectParts(bucket, object, uploadID string, partNumberMarker int, maxParts int) (result ListObjectPartsResult, err error) { return c.listObjectPartsQuery(bucket, object, uploadID, partNumberMarker, maxParts) } @@ -80,3 +88,13 @@ func (c Core) CompleteMultipartUpload(bucket, object, uploadID string, parts []C func (c Core) AbortMultipartUpload(bucket, object, uploadID string) error { return c.abortMultipartUpload(bucket, object, uploadID) } + +// GetBucketPolicy - fetches bucket access policy for a given bucket. +func (c Core) GetBucketPolicy(bucket string) (policy.BucketAccessPolicy, error) { + return c.getBucketPolicy(bucket) +} + +// PutBucketPolicy - applies a new bucket access policy for a given bucket. +func (c Core) PutBucketPolicy(bucket string, bucketPolicy policy.BucketAccessPolicy) error { + return c.putBucketPolicy(bucket, bucketPolicy) +} diff --git a/vendor/github.com/minio/minio-go/encryption-cbc.go b/vendor/github.com/minio/minio-go/pkg/encrypt/cbc.go similarity index 80% rename from vendor/github.com/minio/minio-go/encryption-cbc.go rename to vendor/github.com/minio/minio-go/pkg/encrypt/cbc.go index 22a2d6c2..7670e68f 100644 --- a/vendor/github.com/minio/minio-go/encryption-cbc.go +++ b/vendor/github.com/minio/minio-go/pkg/encrypt/cbc.go @@ -14,7 +14,7 @@ * limitations under the License. */ -package minio +package encrypt import ( "bytes" @@ -24,13 +24,6 @@ import ( "encoding/base64" "errors" "io" - "net/http" -) - -const ( - amzHeaderIV = "X-Amz-Meta-X-Amz-Iv" - amzHeaderKey = "X-Amz-Meta-X-Amz-Key" - amzHeaderMatDesc = "X-Amz-Meta-X-Amz-Matdesc" ) // Crypt mode - encryption or decryption @@ -60,7 +53,7 @@ type CBCSecureMaterials struct { dstBuf *bytes.Buffer // Encryption algorithm - encryptionKey EncryptionKey + encryptionKey Key // Key to encrypts/decrypts data contentKey []byte @@ -81,11 +74,11 @@ type CBCSecureMaterials struct { blockMode cipher.BlockMode } -// NewCBCSecureMaterials builds new CBC crypter module with the specified encryption key -// (symmetric or asymmetric) -func NewCBCSecureMaterials(key EncryptionKey) (*CBCSecureMaterials, error) { +// NewCBCSecureMaterials builds new CBC crypter module with +// the specified encryption key (symmetric or asymmetric) +func NewCBCSecureMaterials(key Key) (*CBCSecureMaterials, error) { if key == nil { - return nil, ErrInvalidArgument("Unable to recognize empty encryption properties") + return nil, errors.New("Unable to recognize empty encryption properties") } return &CBCSecureMaterials{ srcBuf: bytes.NewBuffer([]byte{}), @@ -96,14 +89,8 @@ func NewCBCSecureMaterials(key EncryptionKey) (*CBCSecureMaterials, error) { } -// SetInputStream - set data which needs to be encrypted or decrypted -// func (s *CBCSecureMaterials) SetInputStream(stream io.Reader) { -// s.stream = stream -// } - -// SetEncryptMode - tells CBC that we are going to encrypt data +// SetupEncryptMode - tells CBC that we are going to encrypt data func (s *CBCSecureMaterials) SetupEncryptMode(stream io.Reader) error { - // Set mode to encrypt s.cryptMode = encryptMode @@ -143,8 +130,7 @@ func (s *CBCSecureMaterials) SetupEncryptMode(stream io.Reader) error { } // SetupDecryptMode - tells CBC that we are going to decrypt data -func (s *CBCSecureMaterials) SetupDecryptMode(stream io.Reader, metadata http.Header) error { - +func (s *CBCSecureMaterials) SetupDecryptMode(stream io.Reader, iv string, key string) error { // Set mode to decrypt s.cryptMode = decryptMode @@ -159,15 +145,17 @@ func (s *CBCSecureMaterials) SetupDecryptMode(stream io.Reader, metadata http.He var err error // Get IV - s.iv, err = base64.StdEncoding.DecodeString(metadata.Get(amzHeaderIV)) + s.iv, err = base64.StdEncoding.DecodeString(iv) if err != nil { return err } + // Get encrypted content key - s.cryptedKey, err = base64.StdEncoding.DecodeString(metadata.Get(amzHeaderKey)) + s.cryptedKey, err = base64.StdEncoding.DecodeString(key) if err != nil { return err } + // Decrypt content key s.contentKey, err = s.encryptionKey.Decrypt(s.cryptedKey) if err != nil { @@ -184,17 +172,19 @@ func (s *CBCSecureMaterials) SetupDecryptMode(stream io.Reader, metadata http.He return nil } -// GetHeaders - returns headers data to be sent along with data to the S3 server -// it contains encryption information needed to decrypt later -func (s *CBCSecureMaterials) GetHeaders() http.Header { +// GetIV - return randomly generated IV (per S3 object), base64 encoded. +func (s *CBCSecureMaterials) GetIV() string { + return base64.StdEncoding.EncodeToString(s.iv) +} - m := make(http.Header) +// GetKey - return content encrypting key (cek) in encrypted form, base64 encoded. +func (s *CBCSecureMaterials) GetKey() string { + return base64.StdEncoding.EncodeToString(s.cryptedKey) +} - m.Set(amzHeaderMatDesc, string(s.matDesc)) - m.Set(amzHeaderIV, base64.StdEncoding.EncodeToString(s.iv)) - m.Set(amzHeaderKey, base64.StdEncoding.EncodeToString(s.cryptedKey)) - - return m +// GetDesc - user provided encryption material description in JSON (UTF8) format. +func (s *CBCSecureMaterials) GetDesc() string { + return string(s.matDesc) } // Fill buf with encrypted/decrypted data diff --git a/vendor/github.com/minio/minio-go/encryption.go b/vendor/github.com/minio/minio-go/pkg/encrypt/interface.go similarity index 53% rename from vendor/github.com/minio/minio-go/encryption.go rename to vendor/github.com/minio/minio-go/pkg/encrypt/interface.go index 3a7843c5..2fd75033 100644 --- a/vendor/github.com/minio/minio-go/encryption.go +++ b/vendor/github.com/minio/minio-go/pkg/encrypt/interface.go @@ -14,31 +14,37 @@ * limitations under the License. */ -package minio +// Package encrypt implements a generic interface to encrypt any stream of data. +// currently this package implements two types of encryption +// - Symmetric encryption using AES. +// - Asymmetric encrytion using RSA. +package encrypt -import ( - "io" - "net/http" -) +import "io" -// EncryptionMaterials - provides generic interface to encrypt -// any stream of data. Some crypt information can be -// save in the object metadata -type EncryptionMaterials interface { +// Materials - provides generic interface to encrypt any stream of data. +type Materials interface { - // Return encrypted/decrypted data. + // Returns encrypted/decrypted data, io.Reader compatible. Read(b []byte) (int, error) - // Metadata that will be stored with the object - GetHeaders() http.Header + // Get randomly generated IV, base64 encoded. + GetIV() (iv string) + + // Get content encrypting key (cek) in encrypted form, base64 encoded. + GetKey() (key string) + + // Get user provided encryption material description in + // JSON (UTF8) format. This is not used, kept for future. + GetDesc() (desc string) // Setup encrypt mode, further calls of Read() function // will return the encrypted form of data streamed // by the passed reader - SetupEncryptMode(io.Reader) error + SetupEncryptMode(stream io.Reader) error // Setup decrypted mode, further calls of Read() function // will return the decrypted form of data streamed // by the passed reader - SetupDecryptMode(io.Reader, http.Header) error + SetupDecryptMode(stream io.Reader, iv string, key string) error } diff --git a/vendor/github.com/minio/minio-go/encryption-keys.go b/vendor/github.com/minio/minio-go/pkg/encrypt/keys.go similarity index 94% rename from vendor/github.com/minio/minio-go/encryption-keys.go rename to vendor/github.com/minio/minio-go/pkg/encrypt/keys.go index 4d6a5a14..8814845e 100644 --- a/vendor/github.com/minio/minio-go/encryption-keys.go +++ b/vendor/github.com/minio/minio-go/pkg/encrypt/keys.go @@ -14,19 +14,20 @@ * limitations under the License. */ -package minio +package encrypt import ( "crypto/aes" "crypto/rand" "crypto/rsa" "crypto/x509" + "errors" ) -// EncryptionKey - generic interface to encrypt/decrypt a key. +// Key - generic interface to encrypt/decrypt a key. // We use it to encrypt/decrypt content key which is the key // that encrypt/decrypt object data. -type EncryptionKey interface { +type Key interface { // Encrypt data using to the set encryption key Encrypt([]byte) ([]byte, error) // Decrypt data using to the set encryption key @@ -140,7 +141,7 @@ func NewAsymmetricKey(privData []byte, pubData []byte) (*AsymmetricKey, error) { } privKey, ok := priv.(*rsa.PrivateKey) if !ok { - return nil, ErrInvalidArgument("not a valid private key") + return nil, errors.New("not a valid private key") } // Parse public key from passed data @@ -151,7 +152,7 @@ func NewAsymmetricKey(privData []byte, pubData []byte) (*AsymmetricKey, error) { pubKey, ok := pub.(*rsa.PublicKey) if !ok { - return nil, ErrInvalidArgument("not a valid public key") + return nil, errors.New("not a valid public key") } // Associate the private key with the passed public key diff --git a/vendor/github.com/minio/minio-go/pkg/policy/bucket-policy.go b/vendor/github.com/minio/minio-go/pkg/policy/bucket-policy.go index f618059c..cbb889d8 100644 --- a/vendor/github.com/minio/minio-go/pkg/policy/bucket-policy.go +++ b/vendor/github.com/minio/minio-go/pkg/policy/bucket-policy.go @@ -34,7 +34,7 @@ const ( BucketPolicyWriteOnly = "writeonly" ) -// isValidBucketPolicy - Is provided policy value supported. +// IsValidBucketPolicy - returns true if policy is valid and supported, false otherwise. func (p BucketPolicy) IsValidBucketPolicy() bool { switch p { case BucketPolicyNone, BucketPolicyReadOnly, BucketPolicyReadWrite, BucketPolicyWriteOnly: @@ -508,7 +508,7 @@ func getObjectPolicy(statement Statement) (readOnly bool, writeOnly bool) { return readOnly, writeOnly } -// Returns policy of given bucket name, prefix in given statements. +// GetPolicy - Returns policy of given bucket name, prefix in given statements. func GetPolicy(statements []Statement, bucketName string, prefix string) BucketPolicy { bucketResource := awsResourcePrefix + bucketName objectResource := awsResourcePrefix + bucketName + "/" + prefix + "*" @@ -563,7 +563,7 @@ func GetPolicy(statements []Statement, bucketName string, prefix string) BucketP return policy } -// GetPolicies returns a map of policies rules of given bucket name, prefix in given statements. +// GetPolicies - returns a map of policies rules of given bucket name, prefix in given statements. func GetPolicies(statements []Statement, bucketName string) map[string]BucketPolicy { policyRules := map[string]BucketPolicy{} objResources := set.NewStringSet() @@ -590,8 +590,7 @@ func GetPolicies(statements []Statement, bucketName string) map[string]BucketPol return policyRules } -// Returns new statements containing policy of given bucket name and -// prefix are appended. +// SetPolicy - Returns new statements containing policy of given bucket name and prefix are appended. func SetPolicy(statements []Statement, policy BucketPolicy, bucketName string, prefix string) []Statement { out := removeStatements(statements, bucketName, prefix) // fmt.Println("out = ") diff --git a/vendor/github.com/minio/minio-go/pkg/s3signer/request-signature-streaming.go b/vendor/github.com/minio/minio-go/pkg/s3signer/request-signature-streaming.go new file mode 100644 index 00000000..755fd1ac --- /dev/null +++ b/vendor/github.com/minio/minio-go/pkg/s3signer/request-signature-streaming.go @@ -0,0 +1,285 @@ +/* + * Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2017 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 s3signer + +import ( + "bytes" + "encoding/hex" + "fmt" + "io" + "net/http" + "strconv" + "strings" + "time" +) + +// Reference for constants used below - +// http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-streaming.html#example-signature-calculations-streaming +const ( + streamingSignAlgorithm = "STREAMING-AWS4-HMAC-SHA256-PAYLOAD" + streamingEncoding = "aws-chunked" + streamingPayloadHdr = "AWS4-HMAC-SHA256-PAYLOAD" + emptySHA256 = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + payloadChunkSize = 64 * 1024 + chunkSigConstLen = 17 // ";chunk-signature=" + signatureStrLen = 64 // e.g. "f2ca1bb6c7e907d06dafe4687e579fce76b37e4e93b7605022da52e6ccc26fd2" + crlfLen = 2 // CRLF +) + +// Request headers to be ignored while calculating seed signature for +// a request. +var ignoredStreamingHeaders = map[string]bool{ + "Authorization": true, + "User-Agent": true, + "Content-Type": true, +} + +// getSignedChunkLength - calculates the length of chunk metadata +func getSignedChunkLength(chunkDataSize int64) int64 { + return int64(len(fmt.Sprintf("%x", chunkDataSize))) + + chunkSigConstLen + + signatureStrLen + + crlfLen + + chunkDataSize + + crlfLen +} + +// getStreamLength - calculates the length of the overall stream (data + metadata) +func getStreamLength(dataLen, chunkSize int64) int64 { + if dataLen <= 0 { + return 0 + } + + chunksCount := int64(dataLen / chunkSize) + remainingBytes := int64(dataLen % chunkSize) + streamLen := int64(0) + streamLen += chunksCount * getSignedChunkLength(chunkSize) + if remainingBytes > 0 { + streamLen += getSignedChunkLength(remainingBytes) + } + streamLen += getSignedChunkLength(0) + return streamLen +} + +// buildChunkStringToSign - returns the string to sign given chunk data +// and previous signature. +func buildChunkStringToSign(t time.Time, region, previousSig string, chunkData []byte) string { + stringToSignParts := []string{ + streamingPayloadHdr, + t.Format(iso8601DateFormat), + getScope(region, t), + previousSig, + emptySHA256, + hex.EncodeToString(sum256(chunkData)), + } + + return strings.Join(stringToSignParts, "\n") +} + +// prepareStreamingRequest - prepares a request with appropriate +// headers before computing the seed signature. +func prepareStreamingRequest(req *http.Request, dataLen int64, timestamp time.Time) { + // Set x-amz-content-sha256 header. + req.Header.Set("X-Amz-Content-Sha256", streamingSignAlgorithm) + req.Header.Set("Content-Encoding", streamingEncoding) + req.Header.Set("X-Amz-Date", timestamp.Format(iso8601DateFormat)) + + // Set content length with streaming signature for each chunk included. + req.ContentLength = getStreamLength(dataLen, int64(payloadChunkSize)) + req.Header.Set("x-amz-decoded-content-length", strconv.FormatInt(dataLen, 10)) +} + +// buildChunkHeader - returns the chunk header. +// e.g string(IntHexBase(chunk-size)) + ";chunk-signature=" + signature + \r\n + chunk-data + \r\n +func buildChunkHeader(chunkLen int64, signature string) []byte { + return []byte(strconv.FormatInt(chunkLen, 16) + ";chunk-signature=" + signature + "\r\n") +} + +// buildChunkSignature - returns chunk signature for a given chunk and previous signature. +func buildChunkSignature(chunkData []byte, reqTime time.Time, region, + previousSignature, secretAccessKey string) string { + + chunkStringToSign := buildChunkStringToSign(reqTime, region, + previousSignature, chunkData) + signingKey := getSigningKey(secretAccessKey, region, reqTime) + return getSignature(signingKey, chunkStringToSign) +} + +// getSeedSignature - returns the seed signature for a given request. +func (s *StreamingReader) setSeedSignature(req *http.Request) { + // Get canonical request + canonicalRequest := getCanonicalRequest(*req, ignoredStreamingHeaders) + + // Get string to sign from canonical request. + stringToSign := getStringToSignV4(s.reqTime, s.region, canonicalRequest) + + signingKey := getSigningKey(s.secretAccessKey, s.region, s.reqTime) + + // Calculate signature. + s.seedSignature = getSignature(signingKey, stringToSign) +} + +// StreamingReader implements chunked upload signature as a reader on +// top of req.Body's ReaderCloser chunk header;data;... repeat +type StreamingReader struct { + accessKeyID string + secretAccessKey string + region string + prevSignature string + seedSignature string + contentLen int64 // Content-Length from req header + baseReadCloser io.ReadCloser // underlying io.Reader + bytesRead int64 // bytes read from underlying io.Reader + buf bytes.Buffer // holds signed chunk + chunkBuf []byte // holds raw data read from req Body + chunkBufLen int // no. of bytes read so far into chunkBuf + done bool // done reading the underlying reader to EOF + reqTime time.Time + chunkNum int + totalChunks int + lastChunkSize int +} + +// signChunk - signs a chunk read from s.baseReader of chunkLen size. +func (s *StreamingReader) signChunk(chunkLen int) { + // Compute chunk signature for next header + signature := buildChunkSignature(s.chunkBuf[:chunkLen], s.reqTime, + s.region, s.prevSignature, s.secretAccessKey) + + // For next chunk signature computation + s.prevSignature = signature + + // Write chunk header into streaming buffer + chunkHdr := buildChunkHeader(int64(chunkLen), signature) + s.buf.Write(chunkHdr) + + // Write chunk data into streaming buffer + s.buf.Write(s.chunkBuf[:chunkLen]) + + // Write the chunk trailer. + s.buf.Write([]byte("\r\n")) + + // Reset chunkBufLen for next chunk read. + s.chunkBufLen = 0 + s.chunkNum++ +} + +// setStreamingAuthHeader - builds and sets authorization header value +// for streaming signature. +func (s *StreamingReader) setStreamingAuthHeader(req *http.Request) { + credential := GetCredential(s.accessKeyID, s.region, s.reqTime) + authParts := []string{ + signV4Algorithm + " Credential=" + credential, + "SignedHeaders=" + getSignedHeaders(*req, ignoredStreamingHeaders), + "Signature=" + s.seedSignature, + } + + // Set authorization header. + auth := strings.Join(authParts, ",") + req.Header.Set("Authorization", auth) +} + +// StreamingSignV4 - provides chunked upload signatureV4 support by +// implementing io.Reader. +func StreamingSignV4(req *http.Request, accessKeyID, secretAccessKey, + region string, dataLen int64, reqTime time.Time) *http.Request { + + // Set headers needed for streaming signature. + prepareStreamingRequest(req, dataLen, reqTime) + + stReader := &StreamingReader{ + baseReadCloser: req.Body, + accessKeyID: accessKeyID, + secretAccessKey: secretAccessKey, + region: region, + reqTime: reqTime, + chunkBuf: make([]byte, payloadChunkSize), + contentLen: dataLen, + chunkNum: 1, + totalChunks: int((dataLen+payloadChunkSize-1)/payloadChunkSize) + 1, + lastChunkSize: int(dataLen % payloadChunkSize), + } + + // Add the request headers required for chunk upload signing. + + // Compute the seed signature. + stReader.setSeedSignature(req) + + // Set the authorization header with the seed signature. + stReader.setStreamingAuthHeader(req) + + // Set seed signature as prevSignature for subsequent + // streaming signing process. + stReader.prevSignature = stReader.seedSignature + req.Body = stReader + + return req +} + +// Read - this method performs chunk upload signature providing a +// io.Reader interface. +func (s *StreamingReader) Read(buf []byte) (int, error) { + switch { + // After the last chunk is read from underlying reader, we + // never re-fill s.buf. + case s.done: + + // s.buf will be (re-)filled with next chunk when has lesser + // bytes than asked for. + case s.buf.Len() < len(buf): + s.chunkBufLen = 0 + for { + n1, err := s.baseReadCloser.Read(s.chunkBuf[s.chunkBufLen:]) + if err == nil || err == io.ErrUnexpectedEOF { + s.chunkBufLen += n1 + s.bytesRead += int64(n1) + + if s.chunkBufLen == payloadChunkSize || + (s.chunkNum == s.totalChunks-1 && + s.chunkBufLen == s.lastChunkSize) { + // Sign the chunk and write it to s.buf. + s.signChunk(s.chunkBufLen) + break + } + + } else if err == io.EOF { + // No more data left in baseReader - last chunk. + // Done reading the last chunk from baseReader. + s.done = true + + // bytes read from baseReader different than + // content length provided. + if s.bytesRead != s.contentLen { + return 0, io.ErrUnexpectedEOF + } + + // Sign the chunk and write it to s.buf. + s.signChunk(0) + break + + } else { + return 0, err + } + } + } + return s.buf.Read(buf) +} + +// Close - this method makes underlying io.ReadCloser's Close method available. +func (s *StreamingReader) Close() error { + return s.baseReadCloser.Close() +} diff --git a/vendor/github.com/minio/minio-go/pkg/s3signer/request-signature-v4.go b/vendor/github.com/minio/minio-go/pkg/s3signer/request-signature-v4.go index 3322b67c..245fb08c 100644 --- a/vendor/github.com/minio/minio-go/pkg/s3signer/request-signature-v4.go +++ b/vendor/github.com/minio/minio-go/pkg/s3signer/request-signature-v4.go @@ -70,7 +70,7 @@ const ( /// /// Is skipped for obvious reasons /// -var ignoredHeaders = map[string]bool{ +var v4IgnoredHeaders = map[string]bool{ "Authorization": true, "Content-Type": true, "Content-Length": true, @@ -122,7 +122,7 @@ func getHashedPayload(req http.Request) string { // getCanonicalHeaders generate a list of request headers for // signature. -func getCanonicalHeaders(req http.Request) string { +func getCanonicalHeaders(req http.Request, ignoredHeaders map[string]bool) string { var headers []string vals := make(map[string][]string) for k, vv := range req.Header { @@ -161,7 +161,7 @@ func getCanonicalHeaders(req http.Request) string { // getSignedHeaders generate all signed request headers. // i.e lexically sorted, semicolon-separated list of lowercase // request header names. -func getSignedHeaders(req http.Request) string { +func getSignedHeaders(req http.Request, ignoredHeaders map[string]bool) string { var headers []string for k := range req.Header { if _, ok := ignoredHeaders[http.CanonicalHeaderKey(k)]; ok { @@ -183,14 +183,14 @@ func getSignedHeaders(req http.Request) string { // \n // \n // -func getCanonicalRequest(req http.Request) string { +func getCanonicalRequest(req http.Request, ignoredHeaders map[string]bool) string { req.URL.RawQuery = strings.Replace(req.URL.Query().Encode(), "+", "%20", -1) canonicalRequest := strings.Join([]string{ req.Method, s3utils.EncodePath(req.URL.Path), req.URL.RawQuery, - getCanonicalHeaders(req), - getSignedHeaders(req), + getCanonicalHeaders(req, ignoredHeaders), + getSignedHeaders(req, ignoredHeaders), getHashedPayload(req), }, "\n") return canonicalRequest @@ -219,7 +219,7 @@ func PreSignV4(req http.Request, accessKeyID, secretAccessKey, location string, credential := GetCredential(accessKeyID, location, t) // Get all signed headers. - signedHeaders := getSignedHeaders(req) + signedHeaders := getSignedHeaders(req, v4IgnoredHeaders) // Set URL query. query := req.URL.Query() @@ -231,7 +231,7 @@ func PreSignV4(req http.Request, accessKeyID, secretAccessKey, location string, req.URL.RawQuery = query.Encode() // Get canonical request. - canonicalRequest := getCanonicalRequest(req) + canonicalRequest := getCanonicalRequest(req, v4IgnoredHeaders) // Get string to sign from canonical request. stringToSign := getStringToSignV4(t, location, canonicalRequest) @@ -273,7 +273,7 @@ func SignV4(req http.Request, accessKeyID, secretAccessKey, location string) *ht req.Header.Set("X-Amz-Date", t.Format(iso8601DateFormat)) // Get canonical request. - canonicalRequest := getCanonicalRequest(req) + canonicalRequest := getCanonicalRequest(req, v4IgnoredHeaders) // Get string to sign from canonical request. stringToSign := getStringToSignV4(t, location, canonicalRequest) @@ -285,7 +285,7 @@ func SignV4(req http.Request, accessKeyID, secretAccessKey, location string) *ht credential := GetCredential(accessKeyID, location, t) // Get all signed headers. - signedHeaders := getSignedHeaders(req) + signedHeaders := getSignedHeaders(req, v4IgnoredHeaders) // Calculate signature. signature := getSignature(signingKey, stringToSign) diff --git a/vendor/github.com/minio/minio-go/pkg/set/stringset.go b/vendor/github.com/minio/minio-go/pkg/set/stringset.go index 55084d46..9f33488e 100644 --- a/vendor/github.com/minio/minio-go/pkg/set/stringset.go +++ b/vendor/github.com/minio/minio-go/pkg/set/stringset.go @@ -25,8 +25,8 @@ import ( // StringSet - uses map as set of strings. type StringSet map[string]struct{} -// keys - returns StringSet keys. -func (set StringSet) keys() []string { +// ToSlice - returns StringSet as string slice. +func (set StringSet) ToSlice() []string { keys := make([]string, 0, len(set)) for k := range set { keys = append(keys, k) @@ -141,7 +141,7 @@ func (set StringSet) Union(sset StringSet) StringSet { // MarshalJSON - converts to JSON data. func (set StringSet) MarshalJSON() ([]byte, error) { - return json.Marshal(set.keys()) + return json.Marshal(set.ToSlice()) } // UnmarshalJSON - parses JSON data and creates new set with it. @@ -169,7 +169,7 @@ func (set *StringSet) UnmarshalJSON(data []byte) error { // String - returns printable string of the set. func (set StringSet) String() string { - return fmt.Sprintf("%s", set.keys()) + return fmt.Sprintf("%s", set.ToSlice()) } // NewStringSet - creates new string set. diff --git a/vendor/github.com/minio/minio-go/retry.go b/vendor/github.com/minio/minio-go/retry.go index d680c6cd..1de5107e 100644 --- a/vendor/github.com/minio/minio-go/retry.go +++ b/vendor/github.com/minio/minio-go/retry.go @@ -33,8 +33,16 @@ const MaxJitter = 1.0 // NoJitter disables the use of jitter for randomizing the exponential backoff time const NoJitter = 0.0 -// newRetryTimer creates a timer with exponentially increasing delays -// until the maximum retry attempts are reached. +// DefaultRetryUnit - default unit multiplicative per retry. +// defaults to 1 second. +const DefaultRetryUnit = time.Second + +// DefaultRetryCap - Each retry attempt never waits no longer than +// this maximum time duration. +const DefaultRetryCap = time.Second * 30 + +// newRetryTimer creates a timer with exponentially increasing +// delays until the maximum retry attempts are reached. func (c Client) newRetryTimer(maxRetry int, unit time.Duration, cap time.Duration, jitter float64, doneCh chan struct{}) <-chan int { attemptCh := make(chan int) diff --git a/vendor/github.com/minio/minio-go/s3-error.go b/vendor/github.com/minio/minio-go/s3-error.go new file mode 100644 index 00000000..11b40a0f --- /dev/null +++ b/vendor/github.com/minio/minio-go/s3-error.go @@ -0,0 +1,60 @@ +/* + * Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2017 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 minio + +// Non exhaustive list of AWS S3 standard error responses - +// http://docs.aws.amazon.com/AmazonS3/latest/API/ErrorResponses.html +var s3ErrorResponseMap = map[string]string{ + "AccessDenied": "Access Denied.", + "BadDigest": "The Content-Md5 you specified did not match what we received.", + "EntityTooSmall": "Your proposed upload is smaller than the minimum allowed object size.", + "EntityTooLarge": "Your proposed upload exceeds the maximum allowed object size.", + "IncompleteBody": "You did not provide the number of bytes specified by the Content-Length HTTP header.", + "InternalError": "We encountered an internal error, please try again.", + "InvalidAccessKeyID": "The access key ID you provided does not exist in our records.", + "InvalidBucketName": "The specified bucket is not valid.", + "InvalidDigest": "The Content-Md5 you specified is not valid.", + "InvalidRange": "The requested range is not satisfiable", + "MalformedXML": "The XML you provided was not well-formed or did not validate against our published schema.", + "MissingContentLength": "You must provide the Content-Length HTTP header.", + "MissingContentMD5": "Missing required header for this request: Content-Md5.", + "MissingRequestBodyError": "Request body is empty.", + "NoSuchBucket": "The specified bucket does not exist", + "NoSuchBucketPolicy": "The bucket policy does not exist", + "NoSuchKey": "The specified key does not exist.", + "NoSuchUpload": "The specified multipart upload does not exist. The upload ID may be invalid, or the upload may have been aborted or completed.", + "NotImplemented": "A header you provided implies functionality that is not implemented", + "PreconditionFailed": "At least one of the pre-conditions you specified did not hold", + "RequestTimeTooSkewed": "The difference between the request time and the server's time is too large.", + "SignatureDoesNotMatch": "The request signature we calculated does not match the signature you provided. Check your key and signing method.", + "MethodNotAllowed": "The specified method is not allowed against this resource.", + "InvalidPart": "One or more of the specified parts could not be found.", + "InvalidPartOrder": "The list of parts was not in ascending order. The parts list must be specified in order by part number.", + "InvalidObjectState": "The operation is not valid for the current state of the object.", + "AuthorizationHeaderMalformed": "The authorization header is malformed; the region is wrong.", + "MalformedPOSTRequest": "The body of your POST request is not well-formed multipart/form-data.", + "BucketNotEmpty": "The bucket you tried to delete is not empty", + "AllAccessDisabled": "All access to this bucket has been disabled.", + "MalformedPolicy": "Policy has invalid resource.", + "MissingFields": "Missing fields in request.", + "AuthorizationQueryParametersError": "Error parsing the X-Amz-Credential parameter; the Credential is mal-formed; expecting \"/YYYYMMDD/REGION/SERVICE/aws4_request\".", + "MalformedDate": "Invalid date format header, expected to be in ISO8601, RFC1123 or RFC1123Z time format.", + "BucketAlreadyOwnedByYou": "Your previous request to create the named bucket succeeded and you already own it.", + "InvalidDuration": "Duration provided in the request is invalid.", + "XAmzContentSHA256Mismatch": "The provided 'x-amz-content-sha256' header does not match what was computed.", + // Add new API errors here. +} diff --git a/vendor/github.com/minio/minio-go/signature-type.go b/vendor/github.com/minio/minio-go/signature-type.go index cae74cd0..36e999a2 100644 --- a/vendor/github.com/minio/minio-go/signature-type.go +++ b/vendor/github.com/minio/minio-go/signature-type.go @@ -24,6 +24,7 @@ const ( Latest SignatureType = iota SignatureV4 SignatureV2 + SignatureV4Streaming ) // isV2 - is signature SignatureV2? @@ -35,3 +36,8 @@ func (s SignatureType) isV2() bool { func (s SignatureType) isV4() bool { return s == SignatureV4 || s == Latest } + +// isStreamingV4 - is signature SignatureV4Streaming? +func (s SignatureType) isStreamingV4() bool { + return s == SignatureV4Streaming +} diff --git a/vendor/vendor.json b/vendor/vendor.json index 171a2ad8..cb6d8bfe 100644 --- a/vendor/vendor.json +++ b/vendor/vendor.json @@ -50,22 +50,28 @@ "revisionTime": "2015-10-24T22:24:27-07:00" }, { - "checksumSHA1": "mDmRRka//itovrS4jtcpVdr0Weg=", + "checksumSHA1": "ymC5RhgF7MLQ7Gj1w0AcCQykQbY=", "path": "github.com/minio/minio-go", - "revision": "6d434a3827cdfa3fcf43bde6864fbdd2aad19089", - "revisionTime": "2017-04-08T08:09:03Z" + "revision": "5297a818b482fa329b3dc1a3926e3c4c6fb5d459", + "revisionTime": "2017-04-26T18:23:05Z" }, { - "checksumSHA1": "qTxOBp3GVxCC70ykb7Hxg6UgWwA=", + "checksumSHA1": "lsxCcRcNUDxhQyO999SOdvKzzfM=", + "path": "github.com/minio/minio-go/pkg/encrypt", + "revision": "5297a818b482fa329b3dc1a3926e3c4c6fb5d459", + "revisionTime": "2017-04-26T18:23:05Z" + }, + { + "checksumSHA1": "neH34/65OXeKHM/MlV8MbhcdFBc=", "path": "github.com/minio/minio-go/pkg/policy", - "revision": "583c261267bc1022bb3e046c7d01c49d3f56edaa", - "revisionTime": "2016-09-03T08:42:23Z" + "revision": "5297a818b482fa329b3dc1a3926e3c4c6fb5d459", + "revisionTime": "2017-04-26T18:23:05Z" }, { - "checksumSHA1": "m/6/na9lVtamkfmIdIOi5pdccgw=", + "checksumSHA1": "/5IXp1nGKqOfHn8Piiod3OCkG2U=", "path": "github.com/minio/minio-go/pkg/s3signer", - "revision": "532b920ff28900244a2ef7d07468003df36fe7c5", - "revisionTime": "2016-12-20T20:43:13Z" + "revision": "5297a818b482fa329b3dc1a3926e3c4c6fb5d459", + "revisionTime": "2017-04-26T18:23:05Z" }, { "checksumSHA1": "gRnCFKb4x83GBLVUZXoOjujd+U0=", @@ -74,10 +80,10 @@ "revisionTime": "2017-01-05T04:45:20Z" }, { - "checksumSHA1": "A8QOw1aWwc+RtjGozY0XeS5varo=", + "checksumSHA1": "maUy+dbN6VfTTnfErrAW2lLit1w=", "path": "github.com/minio/minio-go/pkg/set", - "revision": "9e734013294ab153b0bdbe182738bcddd46f1947", - "revisionTime": "2016-08-18T00:31:20Z" + "revision": "5297a818b482fa329b3dc1a3926e3c4c6fb5d459", + "revisionTime": "2017-04-26T18:23:05Z" }, { "checksumSHA1": "v1OEKlUTmnwiQ2RxIFfDhz77Uu0=", From f0ccc918905a6e5028e56f8fe56c58d02f3b8c2a Mon Sep 17 00:00:00 2001 From: Harshavardhana Date: Wed, 3 May 2017 11:21:02 -0700 Subject: [PATCH 22/38] fs: Allow copying to special files if possible. (#2146) Fixes #2145 --- cmd/client-fs.go | 61 +++++++++++++++++++++--------------------------- 1 file changed, 27 insertions(+), 34 deletions(-) diff --git a/cmd/client-fs.go b/cmd/client-fs.go index 19853c7b..4cb8b6c5 100644 --- a/cmd/client-fs.go +++ b/cmd/client-fs.go @@ -193,6 +193,20 @@ func (f *fsClient) Watch(params watchParams) (*watchObject, *probe.Error) { }, nil } +func isStreamFile(objectPath string) bool { + switch objectPath { + case os.DevNull: + fallthrough + case os.Stdin.Name(): + fallthrough + case os.Stdout.Name(): + fallthrough + case os.Stderr.Name(): + return true + } + return false +} + /// Object operations. func (f *fsClient) put(reader io.Reader, size int64, metadata map[string][]string, progress io.Reader) (int64, *probe.Error) { @@ -203,29 +217,15 @@ func (f *fsClient) put(reader io.Reader, size int64, metadata map[string][]strin objectDir, _ := filepath.Split(f.PathURL.Path) objectPath := f.PathURL.Path - // Verify if destination already exists. - st, e := os.Stat(objectPath) - if e == nil { - // If the destination exists and is not a regular file. - if !st.Mode().IsRegular() { - return 0, probe.NewError(PathIsNotRegular{ - Path: objectPath, - }) - } - } - - // Proceed if file does not exist. return for all other errors. - if e != nil { - if !os.IsNotExist(e) { - return 0, probe.NewError(e) - } - } - - // Write to a temporary file "object.part.mc" before commit. + avoidResumeUpload := isStreamFile(objectPath) + // Write to a temporary file "object.part.minio" before commit. objectPartPath := objectPath + partSuffix + if avoidResumeUpload { + objectPartPath = objectPath + } if objectDir != "" { // Create any missing top level directories. - if e = os.MkdirAll(objectDir, 0777); e != nil { + if e := os.MkdirAll(objectDir, 0777); e != nil { err := f.toClientError(e, f.PathURL.Path) return 0, err.Trace(f.PathURL.Path) } @@ -346,10 +346,12 @@ func (f *fsClient) put(reader io.Reader, size int64, metadata map[string][]strin }) } } - // Safely completed put. Now commit by renaming to actual filename. - if e = os.Rename(objectPartPath, objectPath); e != nil { - err := f.toClientError(e, objectPath) - return totalWritten, err.Trace(objectPartPath, objectPath) + if !avoidResumeUpload { + // Safely completed put. Now commit by renaming to actual filename. + if e = os.Rename(objectPartPath, objectPath); e != nil { + err := f.toClientError(e, objectPath) + return totalWritten, err.Trace(objectPartPath, objectPath) + } } return totalWritten, nil } @@ -397,16 +399,7 @@ func readFile(fpath string) (io.ReadCloser, error) { // createFile creates an empty file at the provided filepath // if one does not exist already. func createFile(fpath string) (io.WriteCloser, error) { - st, e := os.Stat(fpath) - // If destination exists but is not regular. - if e == nil && !st.Mode().IsRegular() { - return nil, PathIsNotRegular{Path: fpath} - } - // If file exists already. - if e != nil && !os.IsNotExist(e) { - return nil, e - } - if e = os.MkdirAll(filepath.Dir(fpath), 0777); e != nil { + if e := os.MkdirAll(filepath.Dir(fpath), 0777); e != nil { return nil, e } file, e := os.Create(fpath) From 7027211e5814221d856ff1200a0a0e3d722193d1 Mon Sep 17 00:00:00 2001 From: Harshavardhana Date: Wed, 10 May 2017 09:10:04 -0700 Subject: [PATCH 23/38] docs: Fix bash_autocomplete download link (#2150) --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 68821ae6..bb917614 100644 --- a/README.md +++ b/README.md @@ -167,10 +167,10 @@ alias pipe='mc pipe' ``` ### Shell autocompletion -You may also download [`autocomplete/bash_autocomplete`](https://raw.githubusercontent.com/minio/mc/master/autocomplete/bash_complete) into `/etc/bash_completion.d/` and rename it to `mc`. Don't forget to source the file to make it active on your current shell. +You may also download [`autocomplete/bash_autocomplete`](https://raw.githubusercontent.com/minio/mc/master/autocomplete/bash_autocomplete) into `/etc/bash_completion.d/` and rename it to `mc`. Don't forget to source the file to make it active on your current shell. ```sh -sudo wget https://raw.githubusercontent.com/minio/mc/master/autocomplete/bash_complete -O /etc/bash_completion.d/mc +sudo wget https://raw.githubusercontent.com/minio/mc/master/autocomplete/bash_autocomplete -O /etc/bash_completion.d/mc source /etc/bash_completion.d/mc ``` From 372e905dad248d5cd13eefdf6d99f022c057a97d Mon Sep 17 00:00:00 2001 From: Anis Elleuch Date: Thu, 11 May 2017 18:19:12 +0200 Subject: [PATCH 24/38] s3: Enforce virtual host style with China endpoint (#2153) --- cmd/client-s3.go | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/cmd/client-s3.go b/cmd/client-s3.go index e75f2949..279d6516 100644 --- a/cmd/client-s3.go +++ b/cmd/client-s3.go @@ -935,6 +935,10 @@ func isAmazon(host string) bool { return s3utils.IsAmazonEndpoint(url.URL{Host: host}) } +func isAmazonChina(host string) bool { + return s3utils.IsAmazonChinaEndpoint(url.URL{Host: host}) +} + func isAmazonAccelerated(host string) bool { return host == "s3-accelerate.amazonaws.com" } @@ -947,7 +951,7 @@ func isGoogle(host string) bool { // Currently only supported hosts with virtual style // are Amazon S3 and Google Cloud Storage. func isVirtualHostStyle(host string) bool { - return isAmazon(host) || isGoogle(host) || isAmazonAccelerated(host) + return isAmazon(host) && !isAmazonChina(host) || isGoogle(host) || isAmazonAccelerated(host) } // url2BucketAndObject gives bucketName and objectName from URL path. From 7f65ad495751045243618aa2223ba3bc28f6654a Mon Sep 17 00:00:00 2001 From: Harshavardhana Date: Tue, 16 May 2017 09:50:54 -0700 Subject: [PATCH 25/38] Add UTCNow() helper function (#2155) This patch adds UTCNow() function which returns current UTC time. This is equivalent of UTCNow() == time.Now().UTC() Refer https://github.com/minio/minio/pull/3931 --- cmd/api_handlers_test.go | 5 ++--- cmd/client-fs.go | 6 +++--- cmd/client-s3.go | 2 +- cmd/client-s3_test.go | 5 ++--- cmd/mirror-main.go | 3 +-- cmd/rm-main.go | 4 ++-- cmd/session-v8.go | 2 +- cmd/share-db-v1.go | 2 +- cmd/utils.go | 7 ++++++- 9 files changed, 19 insertions(+), 17 deletions(-) diff --git a/cmd/api_handlers_test.go b/cmd/api_handlers_test.go index 8f9c37ae..3a91b86d 100644 --- a/cmd/api_handlers_test.go +++ b/cmd/api_handlers_test.go @@ -25,7 +25,6 @@ import ( "strconv" "strings" "sync" - "time" ) type objectAPIHandler struct { @@ -63,7 +62,7 @@ func (h objectAPIHandler) getHandler(w http.ResponseWriter, r *http.Request) { return } w.Header().Set("Content-Length", strconv.Itoa(len(h.object[filepath.Base(r.URL.Path)]))) - w.Header().Set("Last-Modified", time.Now().UTC().Format(http.TimeFormat)) + w.Header().Set("Last-Modified", UTCNow().Format(http.TimeFormat)) w.Header().Set("ETag", "b1946ac92492d2347c6235b4d2611184") w.WriteHeader(http.StatusOK) io.Copy(w, bytes.NewReader(h.object[filepath.Base(r.URL.Path)])) @@ -83,7 +82,7 @@ func (h objectAPIHandler) headHandler(w http.ResponseWriter, r *http.Request) { return case r.URL.Path != "": w.Header().Set("Content-Length", strconv.Itoa(len(h.object[filepath.Base(r.URL.Path)]))) - w.Header().Set("Last-Modified", time.Now().UTC().Format(http.TimeFormat)) + w.Header().Set("Last-Modified", UTCNow().Format(http.TimeFormat)) w.Header().Set("ETag", "b1946ac92492d2347c6235b4d2611184") w.WriteHeader(http.StatusOK) return diff --git a/cmd/client-fs.go b/cmd/client-fs.go index 4cb8b6c5..1e761654 100644 --- a/cmd/client-fs.go +++ b/cmd/client-fs.go @@ -162,7 +162,7 @@ func (f *fsClient) Watch(params watchParams) (*watchObject, *probe.Error) { continue } eventChan <- EventInfo{ - Time: time.Now().Format(timeFormatFS), + Time: UTCNow().Format(timeFormatFS), Size: i.Size(), Path: event.Path(), Client: f, @@ -170,14 +170,14 @@ func (f *fsClient) Watch(params watchParams) (*watchObject, *probe.Error) { } } else if IsDeleteEvent(event.Event()) { eventChan <- EventInfo{ - Time: time.Now().Format(timeFormatFS), + Time: UTCNow().Format(timeFormatFS), Path: event.Path(), Client: f, Type: EventRemove, } } else if IsGetEvent(event.Event()) { eventChan <- EventInfo{ - Time: time.Now().Format(timeFormatFS), + Time: UTCNow().Format(timeFormatFS), Path: event.Path(), Client: f, Type: EventAccessed, diff --git a/cmd/client-s3.go b/cmd/client-s3.go index 279d6516..cfba9307 100644 --- a/cmd/client-s3.go +++ b/cmd/client-s3.go @@ -1538,7 +1538,7 @@ func (c *s3Client) ShareDownload(expires time.Duration) (string, *probe.Error) { func (c *s3Client) ShareUpload(isRecursive bool, expires time.Duration, contentType string) (string, map[string]string, *probe.Error) { bucket, object := c.url2BucketAndObject() p := minio.NewPostPolicy() - if e := p.SetExpires(time.Now().UTC().Add(expires)); e != nil { + if e := p.SetExpires(UTCNow().Add(expires)); e != nil { return "", nil, probe.NewError(e) } if strings.TrimSpace(contentType) != "" || contentType != "" { diff --git a/cmd/client-s3_test.go b/cmd/client-s3_test.go index c7e69361..a2f67633 100644 --- a/cmd/client-s3_test.go +++ b/cmd/client-s3_test.go @@ -23,7 +23,6 @@ import ( "net/http" "net/http/httptest" "strconv" - "time" . "gopkg.in/check.v1" ) @@ -104,7 +103,7 @@ func (h objectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { return } w.Header().Set("Content-Length", strconv.Itoa(len(h.data))) - w.Header().Set("Last-Modified", time.Now().UTC().Format(http.TimeFormat)) + w.Header().Set("Last-Modified", UTCNow().Format(http.TimeFormat)) w.Header().Set("ETag", "9af2f8218b150c351ad802c6f3d66abe") w.WriteHeader(http.StatusOK) case r.Method == "POST": @@ -151,7 +150,7 @@ func (h objectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { return } w.Header().Set("Content-Length", strconv.Itoa(len(h.data))) - w.Header().Set("Last-Modified", time.Now().UTC().Format(http.TimeFormat)) + w.Header().Set("Last-Modified", UTCNow().Format(http.TimeFormat)) w.Header().Set("ETag", "9af2f8218b150c351ad802c6f3d66abe") w.WriteHeader(http.StatusOK) io.Copy(w, bytes.NewReader(h.data)) diff --git a/cmd/mirror-main.go b/cmd/mirror-main.go index b7e096dc..d2240e69 100644 --- a/cmd/mirror-main.go +++ b/cmd/mirror-main.go @@ -24,7 +24,6 @@ import ( "strings" "sync" "syscall" - "time" "github.com/fatih/color" "github.com/minio/cli" @@ -509,7 +508,7 @@ func newMirrorJob(srcURL, dstURL string, isFake, isRemove, isWatch, isForce bool statusCh: make(chan URLs), wgStatus: new(sync.WaitGroup), watcherRunning: true, - watcher: NewWatcher(time.Now().UTC()), + watcher: NewWatcher(UTCNow()), } return &mj diff --git a/cmd/rm-main.go b/cmd/rm-main.go index 2e901b0f..6427fbdd 100644 --- a/cmd/rm-main.go +++ b/cmd/rm-main.go @@ -149,7 +149,7 @@ func removeSingle(url string, isIncomplete bool, isFake bool, older int) error { } if older > 0 { // Check whether object is created older than given time. - now := time.Now().UTC() + now := UTCNow() timeDiff := now.Sub(content.Time) if timeDiff < (time.Duration(older) * Day) { // time difference of info.Time with current time is less than older time. @@ -211,7 +211,7 @@ func removeRecursive(url string, isIncomplete bool, isFake bool, older int) erro if older > 0 { // Check whether object is created older than given time. - now := time.Now().UTC() + now := UTCNow() timeDiff := now.Sub(content.Time) if timeDiff < (time.Duration(older) * Day) { // time difference of info.Time with current time is less than older time. diff --git a/cmd/session-v8.go b/cmd/session-v8.go index 3ff3934f..32c6c895 100644 --- a/cmd/session-v8.go +++ b/cmd/session-v8.go @@ -174,7 +174,7 @@ func newSessionV8() *sessionV8 { s.Header.CommandBoolFlags = make(map[string]bool) s.Header.CommandIntFlags = make(map[string]int) s.Header.CommandStringFlags = make(map[string]string) - s.Header.When = time.Now().UTC() + s.Header.When = UTCNow() s.mutex = new(sync.Mutex) s.SessionID = newRandomID(8) diff --git a/cmd/share-db-v1.go b/cmd/share-db-v1.go index 099b73c5..978b1c3d 100644 --- a/cmd/share-db-v1.go +++ b/cmd/share-db-v1.go @@ -59,7 +59,7 @@ func (s *shareDBV1) Set(objectURL string, shareURL string, expiry time.Duration, s.Shares[shareURL] = shareEntryV1{ URL: objectURL, - Date: time.Now().UTC(), + Date: UTCNow(), Expiry: expiry, ContentType: contentType, } diff --git a/cmd/utils.go b/cmd/utils.go index 967d285d..a2212380 100644 --- a/cmd/utils.go +++ b/cmd/utils.go @@ -47,11 +47,16 @@ func isErrIgnored(err *probe.Error) (ignored bool) { return ignored } +// UTCNow - returns current UTC time. +func UTCNow() time.Time { + return time.Now().UTC() +} + var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") // newRandomID generates a random id of regular lower case and uppercase english characters. func newRandomID(n int) string { - rand.Seed(time.Now().UTC().UnixNano()) + rand.Seed(UTCNow().UnixNano()) sid := make([]rune, n) for i := range sid { sid[i] = letters[rand.Intn(len(letters))] From 320e29e03fb59845a9c1b272cada4f686205bdaa Mon Sep 17 00:00:00 2001 From: Anis Elleuch Date: Mon, 22 May 2017 08:13:35 +0100 Subject: [PATCH 26/38] info: Show info of all cluster servers (#2149) --- cmd/admin-info.go | 116 ++++++++++++------ .../github.com/minio/minio/pkg/madmin/API.md | 65 +++++++--- .../minio/minio/pkg/madmin/info-commands.go | 29 +++-- vendor/vendor.json | 6 +- 4 files changed, 144 insertions(+), 72 deletions(-) diff --git a/cmd/admin-info.go b/cmd/admin-info.go index 9ff8aa2b..3131efe1 100644 --- a/cmd/admin-info.go +++ b/cmd/admin-info.go @@ -20,6 +20,7 @@ import ( "encoding/json" "fmt" "net/url" + "time" humanize "github.com/dustin/go-humanize" "github.com/fatih/color" @@ -94,23 +95,46 @@ type ServerInfo struct { type infoMessage struct { Status string `json:"status"` Service bool `json:"service"` + Addr string `json:"address"` + Err string `json:"error"` *ServerInfo } // String colorized service status message. func (u infoMessage) String() (msg string) { defer func() { - msg = console.Colorize("Info", msg) + msg += "\n" }() + + dot := "●" + // When service is offline if !u.Service { - msg = "The server is offline." + msg += fmt.Sprintf("%s %s\n", console.Colorize("InfoFail", dot), u.Addr) + msg += fmt.Sprintf(" Uptime : Server is %s", console.Colorize("InfoFail", "offline")) return } - msg += fmt.Sprintf(" Version : %s\n", u.ServerInfo.Properties.Version) - msg += fmt.Sprintf(" Uptime : %s\n", timeDurationToHumanizedDuration(u.ServerInfo.Properties.Uptime)) - msg += fmt.Sprintf(" Region : %s\n", u.ServerInfo.Properties.Region) + // Print error if any and exit + if u.Err != "" { + msg += fmt.Sprintf("%s %s\n", console.Colorize("InfoFail", dot), u.Addr) + msg += fmt.Sprintf(" Uptime : Server is %s\n", console.Colorize("InfoFail", "offline")) + msg += fmt.Sprintf(" Error : %s", u.Err) + return + } + + // Print server title + msg += fmt.Sprintf("%s %s\n", console.Colorize("Info", dot), u.Addr) + + // Print server information + + // Uptime + msg += fmt.Sprintf(" Uptime : %s since %s\n", console.Colorize("Info", "online"), humanize.Time(time.Now().UTC().Add(-u.ServerInfo.Properties.Uptime))) + // Version + msg += fmt.Sprintf(" Version : %s\n", u.ServerInfo.Properties.Version) + // Region + msg += fmt.Sprintf(" Region : %s\n", u.ServerInfo.Properties.Region) + // ARNs sqsARNs := "" for _, v := range u.ServerInfo.Properties.SQSARN { sqsARNs += fmt.Sprintf("%s ", v) @@ -119,12 +143,11 @@ func (u infoMessage) String() (msg string) { sqsARNs = "" } msg += fmt.Sprintf(" SQS ARNs : %s\n", sqsARNs) - + // Incoming/outgoing msg += fmt.Sprintf(" Network : Incoming %s, Outgoing %s\n", humanize.IBytes(u.ServerInfo.ConnStats.TotalInputBytes), humanize.IBytes(u.ServerInfo.ConnStats.TotalOutputBytes)) - - // Online service, get backend information + // Get storage information msg += fmt.Sprintf(" Storage : Total %s, Free %s", humanize.IBytes(uint64(u.StorageInfo.Total)), humanize.IBytes(uint64(u.StorageInfo.Free)), @@ -132,6 +155,7 @@ func (u infoMessage) String() (msg string) { if v, ok := u.ServerInfo.StorageInfo.Backend.(xlBackend); ok { msg += fmt.Sprintf(", Online Disks: %d, Offline Disks: %d", v.OnlineDisks, v.OfflineDisks) } + return } @@ -156,6 +180,7 @@ func mainAdminInfo(ctx *cli.Context) error { checkAdminInfoSyntax(ctx) console.SetColor("Info", color.New(color.FgGreen, color.Bold)) + console.SetColor("InfoFail", color.New(color.FgRed, color.Bold)) // Get the alias parameter from cli args := ctx.Args() @@ -165,53 +190,68 @@ func mainAdminInfo(ctx *cli.Context) error { client, err := newAdminClient(aliasedURL) fatalIf(err, "Cannot get a configured admin connection.") - // Fetch the server info of the specified Minio server - serverInfo, e := client.ServerInfo() + // Fetch info of all servers (cluster or single server) + serversInfo, e := client.ServerInfo() // Check the availability of the server: online or offline. A server is considered // offline if we can't get any response or we get a bad format response var serviceOffline bool - switch v := e.(type) { + switch e.(type) { case *json.SyntaxError: serviceOffline = true case *url.Error: - if v.Timeout() { - serviceOffline = true - } + serviceOffline = true } + if serviceOffline { - printMsg(infoMessage{Service: false}) + printMsg(infoMessage{Addr: aliasedURL, Service: false}) return nil } // If the error is not nil and not unrecognizable, just print it and exit fatalIf(probe.NewError(e), "Cannot get service status.") - // Construct the backend status - storageInfo := backendStatus{ - Total: serverInfo.StorageInfo.Total, - Free: serverInfo.StorageInfo.Free, - } - if serverInfo.StorageInfo.Backend.Type == madmin.Erasure { - storageInfo.Backend = xlBackend{ - Type: erasureType, - OnlineDisks: serverInfo.StorageInfo.Backend.OnlineDisks, - OfflineDisks: serverInfo.StorageInfo.Backend.OfflineDisks, + for _, serverInfo := range serversInfo { + // Print the error if exists and jump to the next server + if serverInfo.Error != "" { + printMsg(infoMessage{ + Service: true, + Addr: serverInfo.Addr, + Err: serverInfo.Error, + }) + continue } - } else { - storageInfo.Backend = fsBackend{ - Type: fsType, - } - } - printMsg(infoMessage{ - Service: true, - ServerInfo: &ServerInfo{ - StorageInfo: storageInfo, - ConnStats: serverInfo.ConnStats, - Properties: serverInfo.Properties, - }, - }) + // Construct the backend status + storageInfo := backendStatus{ + Total: serverInfo.Data.StorageInfo.Total, + Free: serverInfo.Data.StorageInfo.Free, + } + + if serverInfo.Data.StorageInfo.Backend.Type == madmin.Erasure { + storageInfo.Backend = xlBackend{ + Type: erasureType, + OnlineDisks: serverInfo.Data.StorageInfo.Backend.OnlineDisks, + OfflineDisks: serverInfo.Data.StorageInfo.Backend.OfflineDisks, + } + } else { + storageInfo.Backend = fsBackend{ + Type: fsType, + } + } + + printMsg(infoMessage{ + Service: true, + Addr: serverInfo.Addr, + Err: serverInfo.Error, + ServerInfo: &ServerInfo{ + StorageInfo: storageInfo, + ConnStats: serverInfo.Data.ConnStats, + Properties: serverInfo.Data.Properties, + }, + }) + + } return nil } diff --git a/vendor/github.com/minio/minio/pkg/madmin/API.md b/vendor/github.com/minio/minio/pkg/madmin/API.md index dc09b997..8d6c3d99 100644 --- a/vendor/github.com/minio/minio/pkg/madmin/API.md +++ b/vendor/github.com/minio/minio/pkg/madmin/API.md @@ -122,7 +122,30 @@ If successful restarts the running minio service, for distributed setup restarts ``` -## 3. Lock operations +## 3. Info operations + + +### ServerInfo() ([]ServerInfo, error) +Fetch all information for all cluster nodes, such as uptime, region, network statistics, etc.. + + + __Example__ + + ```go + + serversInfo, err := madmClnt.ServerInfo() + if err != nil { + log.Fatalln(err) + } + + for _, peerInfo := range serversInfo { + log.Printf("Node: %s, Info: %v\n", peerInfo.Addr, peerInfo.Data) + } + + ``` + + +## 4. Lock operations ### ListLocks(bucket, prefix string, duration time.Duration) ([]VolumeLockInfo, error) @@ -154,7 +177,7 @@ __Example__ ``` -## 4. Heal operations +## 5. Heal operations ### ListObjectsHeal(bucket, prefix string, recursive bool, doneCh <-chan struct{}) (<-chan ObjectInfo, error) @@ -360,7 +383,7 @@ If upload is successfully healed returns nil, otherwise returns error indicating log.Println("Heal-upload result: ", healResult) ``` -## 5. Config operations +## 6. Config operations ### GetConfig() ([]byte, error) @@ -384,23 +407,6 @@ __Example__ log.Println("config received successfully: ", string(buf.Bytes())) ``` -## 6. Misc operations - - - -### SetCredentials() error -Set new credentials of a Minio setup. - -__Example__ - -``` go - err = madmClnt.SetCredentials("YOUR-NEW-ACCESSKEY", "YOUR-NEW-SECRETKEY") - if err != nil { - log.Fatalln(err) - } - log.Println("New credentials successfully set.") - -``` ### SetConfig(config io.Reader) (SetConfigResult, error) @@ -435,3 +441,22 @@ __Example__ } log.Println("SetConfig: ", string(buf.Bytes())) ``` + +## 7. Misc operations + + + +### SetCredentials() error +Set new credentials of a Minio setup. + +__Example__ + +``` go + err = madmClnt.SetCredentials("YOUR-NEW-ACCESSKEY", "YOUR-NEW-SECRETKEY") + if err != nil { + log.Fatalln(err) + } + log.Println("New credentials successfully set.") + +``` + diff --git a/vendor/github.com/minio/minio/pkg/madmin/info-commands.go b/vendor/github.com/minio/minio/pkg/madmin/info-commands.go index 1c41fdf8..f6f93265 100644 --- a/vendor/github.com/minio/minio/pkg/madmin/info-commands.go +++ b/vendor/github.com/minio/minio/pkg/madmin/info-commands.go @@ -74,17 +74,24 @@ type ServerConnStats struct { TotalOutputBytes uint64 `json:"received"` } -// ServerInfo holds the whole server information that will be -// returned by ServerInfo API. -type ServerInfo struct { +// ServerInfoData holds storage, connections and other +// information of a given server +type ServerInfoData struct { StorageInfo StorageInfo `json:"storage"` ConnStats ServerConnStats `json:"network"` Properties ServerProperties `json:"server"` } +// ServerInfo holds server information result of one node +type ServerInfo struct { + Error string `json:"error"` + Addr string `json:"addr"` + Data *ServerInfoData `json:"data"` +} + // ServerInfo - Connect to a minio server and call Server Info Management API // to fetch server's information represented by ServerInfo structure -func (adm *AdminClient) ServerInfo() (ServerInfo, error) { +func (adm *AdminClient) ServerInfo() ([]ServerInfo, error) { // Prepare web service request reqData := requestData{} reqData.queryValues = make(url.Values) @@ -94,26 +101,26 @@ func (adm *AdminClient) ServerInfo() (ServerInfo, error) { resp, err := adm.executeMethod("GET", reqData) defer closeResponse(resp) if err != nil { - return ServerInfo{}, err + return nil, err } // Check response http status code if resp.StatusCode != http.StatusOK { - return ServerInfo{}, httpRespToErrorResponse(resp) + return nil, httpRespToErrorResponse(resp) } // Unmarshal the server's json response - var info ServerInfo + var serversInfo []ServerInfo respBytes, err := ioutil.ReadAll(resp.Body) if err != nil { - return ServerInfo{}, err + return nil, err } - err = json.Unmarshal(respBytes, &info) + err = json.Unmarshal(respBytes, &serversInfo) if err != nil { - return ServerInfo{}, err + return nil, err } - return info, nil + return serversInfo, nil } diff --git a/vendor/vendor.json b/vendor/vendor.json index cb6d8bfe..a275be70 100644 --- a/vendor/vendor.json +++ b/vendor/vendor.json @@ -86,10 +86,10 @@ "revisionTime": "2017-04-26T18:23:05Z" }, { - "checksumSHA1": "v1OEKlUTmnwiQ2RxIFfDhz77Uu0=", + "checksumSHA1": "wCZlVPjuBU/D1ogLL63YdO/havo=", "path": "github.com/minio/minio/pkg/madmin", - "revision": "3032f0f505437c2f631e304cd64a7c1ed7a3479a", - "revisionTime": "2017-04-15T18:40:01Z" + "revision": "9d98bf1c0fb83ccfcf368dec52b2d19b9195b8d4", + "revisionTime": "2017-05-19T14:30:00Z" }, { "path": "github.com/minio/minio/pkg/probe", From 6c677e0d116eaf7af58ed2a3c711c96711b7c51e Mon Sep 17 00:00:00 2001 From: Anis Elleuch Date: Mon, 22 May 2017 17:21:45 +0100 Subject: [PATCH 27/38] mirror: Sync empty buckets (#2160) --- cmd/mirror-main.go | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/cmd/mirror-main.go b/cmd/mirror-main.go index d2240e69..ad7516da 100644 --- a/cmd/mirror-main.go +++ b/cmd/mirror-main.go @@ -20,6 +20,7 @@ import ( "encoding/json" "fmt" "os" + "path" "path/filepath" "strings" "sync" @@ -554,7 +555,12 @@ func runMirror(srcURL, dstURL string, ctx *cli.Context) *probe.Error { dstClt, err := newClient(dstURL) fatalIf(err, "Unable to initialize `"+srcURL+"`") - mirrorAllBuckets := (dstClt.GetURL().Type == objectStorage && dstClt.GetURL().Path == "/") + if ctx.Bool("a") && (srcClt.GetURL().Type != objectStorage || dstClt.GetURL().Type != objectStorage) { + fatalIf(errDummy(), "Synchronizing bucket policies is only possible when both source & target point to S3 servers") + } + + mirrorAllBuckets := (srcClt.GetURL().Type == objectStorage && srcClt.GetURL().Path == "/") || + (dstClt.GetURL().Type == objectStorage && dstClt.GetURL().Path == "/") if mirrorAllBuckets { // Synchronize buckets using dirDifference function @@ -569,8 +575,8 @@ func runMirror(srcURL, dstURL string, ctx *cli.Context) *probe.Error { sourceSuffix := strings.TrimPrefix(d.FirstURL, srcClt.GetURL().String()) - newSrcURL := srcURL + sourceSuffix - newTgtURL := dstURL + sourceSuffix + newSrcURL := path.Join(srcURL, sourceSuffix) + newTgtURL := path.Join(dstURL, sourceSuffix) newSrcClt, _ := newClient(newSrcURL) newDstClt, _ := newClient(newTgtURL) From fed9ebe39df6914c603ea8a7ee9a270bf441d107 Mon Sep 17 00:00:00 2001 From: Nitish Tiwari Date: Fri, 26 May 2017 10:17:50 -0700 Subject: [PATCH 28/38] - Call the progress bar Finish method once all files are updated (#2165) - Fixes https://github.com/minio/mc/issues/2161 --- cmd/mirror-main.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmd/mirror-main.go b/cmd/mirror-main.go index ad7516da..247017d1 100644 --- a/cmd/mirror-main.go +++ b/cmd/mirror-main.go @@ -229,7 +229,6 @@ func (mj *mirrorJob) startStatus() { go func() { // now we want to start the progress bar mj.status.Start() - defer mj.status.Finish() defer mj.wgStatus.Done() for sURLs := range mj.statusCh { @@ -262,6 +261,7 @@ func (mj *mirrorJob) startStatus() { func (mj *mirrorJob) stopStatus() { close(mj.statusCh) mj.wgStatus.Wait() + mj.status.Finish() } // this goroutine will watch for notifications, and add modified objects to the queue From be3370396ac273b58ecbfdf860675aea1a0662cc Mon Sep 17 00:00:00 2001 From: Harshavardhana Date: Mon, 5 Jun 2017 07:44:22 -0700 Subject: [PATCH 29/38] Remove client instance being sent back in eventInfo() (#2167) --- cmd/client-fs.go | 23 ++++++++++------------- cmd/client-s3.go | 4 ---- cmd/watch.go | 1 - 3 files changed, 10 insertions(+), 18 deletions(-) diff --git a/cmd/client-fs.go b/cmd/client-fs.go index 1e761654..75a5e0a8 100644 --- a/cmd/client-fs.go +++ b/cmd/client-fs.go @@ -162,25 +162,22 @@ func (f *fsClient) Watch(params watchParams) (*watchObject, *probe.Error) { continue } eventChan <- EventInfo{ - Time: UTCNow().Format(timeFormatFS), - Size: i.Size(), - Path: event.Path(), - Client: f, - Type: EventCreate, + Time: UTCNow().Format(timeFormatFS), + Size: i.Size(), + Path: event.Path(), + Type: EventCreate, } } else if IsDeleteEvent(event.Event()) { eventChan <- EventInfo{ - Time: UTCNow().Format(timeFormatFS), - Path: event.Path(), - Client: f, - Type: EventRemove, + Time: UTCNow().Format(timeFormatFS), + Path: event.Path(), + Type: EventRemove, } } else if IsGetEvent(event.Event()) { eventChan <- EventInfo{ - Time: UTCNow().Format(timeFormatFS), - Path: event.Path(), - Client: f, - Type: EventAccessed, + Time: UTCNow().Format(timeFormatFS), + Path: event.Path(), + Type: EventAccessed, } } } diff --git a/cmd/client-s3.go b/cmd/client-s3.go index cfba9307..4f60d009 100644 --- a/cmd/client-s3.go +++ b/cmd/client-s3.go @@ -449,7 +449,6 @@ func (c *s3Client) Watch(params watchParams) (*watchObject, *probe.Error) { Time: record.EventTime, Size: record.S3.Object.Size, Path: u.String(), - Client: c, Type: EventCreate, Host: record.Source.Host, Port: record.Source.Port, @@ -460,7 +459,6 @@ func (c *s3Client) Watch(params watchParams) (*watchObject, *probe.Error) { eventChan <- EventInfo{ Time: record.EventTime, Path: u.String(), - Client: c, Type: EventRemove, Host: record.Source.Host, Port: record.Source.Port, @@ -471,7 +469,6 @@ func (c *s3Client) Watch(params watchParams) (*watchObject, *probe.Error) { Time: record.EventTime, Size: record.S3.Object.Size, Path: u.String(), - Client: c, Type: EventAccessedRead, Host: record.Source.Host, Port: record.Source.Port, @@ -482,7 +479,6 @@ func (c *s3Client) Watch(params watchParams) (*watchObject, *probe.Error) { Time: record.EventTime, Size: record.S3.Object.Size, Path: u.String(), - Client: c, Type: EventAccessedStat, Host: record.Source.Host, Port: record.Source.Port, diff --git a/cmd/watch.go b/cmd/watch.go index 7a618c51..a5d68d7a 100644 --- a/cmd/watch.go +++ b/cmd/watch.go @@ -46,7 +46,6 @@ type EventInfo struct { Time string Size int64 Path string - Client Client Type EventType Host string Port string From 61f2595852e515553b61589c4ec37144cc590825 Mon Sep 17 00:00:00 2001 From: Anis Elleuch Date: Wed, 7 Jun 2017 05:48:08 +0100 Subject: [PATCH 30/38] fix: Set quiet when term width is unavailable (#2173) mc was asking the user to provide --quiet flag when terminal width is not available for any reason. This PR tries to fetch the terminal width at mc startup and automatically set quiet flag when it fails to fetch the width. --- cmd/globals.go | 3 +++ cmd/main.go | 11 ++++++++--- cmd/scan-bar.go | 6 +----- 3 files changed, 12 insertions(+), 8 deletions(-) diff --git a/cmd/globals.go b/cmd/globals.go index 27c93d16..37adcd68 100644 --- a/cmd/globals.go +++ b/cmd/globals.go @@ -64,6 +64,9 @@ var ( ) var ( + // Terminal width + globalTermWidth int + // CA root certificates, a nil value means system certs pool will be used globalRootCAs *x509.CertPool ) diff --git a/cmd/main.go b/cmd/main.go index 3b9b0347..932f87f0 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -77,12 +77,17 @@ func Main() { probe.SetAppInfo("Release-Tag", ReleaseTag) probe.SetAppInfo("Commit", ShortCommitID) + // Fetch terminal size, if not available, automatically + // set globalQuiet to true. + if w, e := pb.GetTerminalWidth(); e != nil { + globalQuiet = true + } else { + globalTermWidth = w + } + app := registerApp() app.Before = registerBefore app.ExtraInfo = func() map[string]string { - if _, e := pb.GetTerminalWidth(); e != nil { - globalQuiet = true - } if globalDebug { return getSystemData() } diff --git a/cmd/scan-bar.go b/cmd/scan-bar.go index 99d64b8f..d15a2244 100644 --- a/cmd/scan-bar.go +++ b/cmd/scan-bar.go @@ -20,10 +20,8 @@ import ( "fmt" "strings" - "github.com/cheggaaa/pb" "github.com/dustin/go-humanize" "github.com/minio/mc/pkg/console" - "github.com/minio/minio/pkg/probe" ) // fixateScanBar truncates or stretches text to fit within the terminal size. @@ -46,14 +44,12 @@ type scanBarFunc func(string) // scanBarFactory returns a progress bar function to report URL scanning. func scanBarFactory() scanBarFunc { fileCount := 0 - termWidth, e := pb.GetTerminalWidth() - fatalIf(probe.NewError(e), "Unable to get terminal size. Please use --quiet option.") // Cursor animate channel. cursorCh := cursorAnimate() return func(source string) { scanPrefix := fmt.Sprintf("[%s] %s ", humanize.Comma(int64(fileCount)), string(<-cursorCh)) - source = fixateScanBar(source, termWidth-len([]rune(scanPrefix))) + source = fixateScanBar(source, globalTermWidth-len([]rune(scanPrefix))) barText := scanPrefix + source console.PrintC("\r" + barText + "\r") fileCount++ From 694ab2764997f100964fd6ca935a0191d05cec3b Mon Sep 17 00:00:00 2001 From: Harshavardhana Date: Wed, 7 Jun 2017 17:09:19 -0700 Subject: [PATCH 31/38] build/release: Add sha256sums for minio client releases. (#2171) Additionally deprecate support for arm6vl platform. Fixes #2151 --- buildscripts/build.sh | 70 +++++++++++++++---------------------------- cmd/update-main.go | 2 +- 2 files changed, 25 insertions(+), 47 deletions(-) diff --git a/buildscripts/build.sh b/buildscripts/build.sh index fffaedb9..3a26d03d 100755 --- a/buildscripts/build.sh +++ b/buildscripts/build.sh @@ -28,6 +28,7 @@ _init() { ## System binaries CP=`which cp` SHASUM=`which shasum` + SHA256SUM="${SHASUM} -a 256" SED=`which sed` } @@ -43,58 +44,35 @@ go_build() { release_bin="$release_str/$os-$arch/$(basename $package).$release_tag" # Release binary downloadable name release_real_bin="$release_str/$os-$arch/$(basename $package)" - # Release shasum name - release_shasum="$release_str/$os-$arch/$(basename $package).shasum" - # Go build to build the binary. - if [ "${arch}" == "arm" ]; then - # Release binary downloadable name - release_real_bin_6="$release_str/$os-${arch}6vl/$(basename $package)" + # Release sha1sum name + release_shasum="$release_str/$os-$arch/$(basename $package).${release_tag}.shasum" + # Release sha1sum default + release_shasum_default="$release_str/$os-$arch/$(basename $package).shasum" - release_bin_6="$release_str/$os-${arch}6vl/$(basename $package).$release_tag" - ## Support building for ARM6vl - CGO_ENABLED=0 GOARM=6 GOOS=$os GOARCH=$arch go build --ldflags "${LDFLAGS}" -o $release_bin_6 + # Release sha256sum name + release_sha256sum="$release_str/$os-$arch/$(basename $package).${release_tag}.sha256sum" + # Release sha256sum default + release_sha256sum_default="$release_str/$os-$arch/$(basename $package).sha256sum" - ## Copy - $CP -p $release_bin_6 $release_real_bin_6 + CGO_ENABLED=0 GOOS=$os GOARCH=$arch go build --ldflags "${LDFLAGS}" -o $release_bin - # Release shasum name - release_shasum_6="$release_str/$os-${arch}6vl/$(basename $package).shasum" - - # Calculate shasum - shasum_str=$(${SHASUM} ${release_bin_6}) - echo ${shasum_str} | $SED "s/$release_str\/$os-${arch}6vl\///g" > $release_shasum_6 - - # Release binary downloadable name - release_real_bin_7="$release_str/$os-$arch/$(basename $package)" - - release_bin_7="$release_str/$os-$arch/$(basename $package).$release_tag" - ## Support building for ARM7vl - CGO_ENABLED=0 GOARM=7 GOOS=$os GOARCH=$arch go build --ldflags "${LDFLAGS}" -o $release_bin_7 - - ## Copy - $CP -p $release_bin_7 $release_real_bin_7 - - # Release shasum name - release_shasum_7="$release_str/$os-$arch/$(basename $package).shasum" - - # Calculate shasum - shasum_str=$(${SHASUM} ${release_bin_7}) - echo ${shasum_str} | $SED "s/$release_str\/$os-$arch\///g" > $release_shasum_7 + # Create copy + if [ $os == "windows" ]; then + $CP -p $release_bin ${release_real_bin}.exe else - CGO_ENABLED=0 GOOS=$os GOARCH=$arch go build --ldflags "${LDFLAGS}" -o $release_bin - - # Create copy - if [ $os == "windows" ]; then - $CP -p $release_bin ${release_real_bin}.exe - else - $CP -p $release_bin $release_real_bin - fi - - # Calculate shasum - shasum_str=$(${SHASUM} ${release_bin}) - echo ${shasum_str} | $SED "s/$release_str\/$os-$arch\///g" > $release_shasum + $CP -p $release_bin $release_real_bin fi + + # Calculate sha1sum + shasum_str=$(${SHASUM} ${release_bin}) + echo ${shasum_str} | $SED "s/$release_str\/$os-$arch\///g" > $release_shasum + $CP -p $release_shasum $release_shasum_default + + # Calculate sha256sum + sha256sum_str=$(${SHA256SUM} ${release_bin}) + echo ${sha256sum_str} | $SED "s/$release_str\/$os-$arch\///g" > $release_sha256sum + $CP -p $release_sha256sum $release_sha256sum_default } main() { diff --git a/cmd/update-main.go b/cmd/update-main.go index a87c6d07..2cc0a571 100644 --- a/cmd/update-main.go +++ b/cmd/update-main.go @@ -200,7 +200,7 @@ func downloadReleaseData(releaseChecksumURL string, timeout time.Duration) (data // DownloadReleaseData - downloads release data from minio official server. func DownloadReleaseData(timeout time.Duration) (data string, err *probe.Error) { - return downloadReleaseData(mcReleaseURL+"mc.shasum", timeout) + return downloadReleaseData(mcReleaseURL+"mc.sha256sum", timeout) } func parseReleaseData(data string) (releaseTime time.Time, err *probe.Error) { From cd16de763c246df5b33d55263eb7796e03cfcca9 Mon Sep 17 00:00:00 2001 From: CarterMcClellan Date: Thu, 8 Jun 2017 13:39:34 -0700 Subject: [PATCH 32/38] Updated build instructions from source. (#2177) --- README.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index bb917614..19854567 100644 --- a/README.md +++ b/README.md @@ -100,9 +100,12 @@ Source installation is intended only for developers and advanced users. `mc upda If you do not have a working Golang environment, please follow [How to install Golang](https://docs.minio.io/docs/how-to-install-golang). ```sh -go get -u github.com/minio/mc +go get -d github.com/minio/mc +cd ${GOPATH}/src/github.com/minio/mc +make ``` + ## Add a Cloud Storage Service If you are planning to use `mc` only on POSIX compatible filesystems, you may skip this step and proceed to [everyday use](#everyday-use). From 398bac82d9c503d94c9c07e95b43ff3bd2ce4047 Mon Sep 17 00:00:00 2001 From: CarterMcClellan Date: Thu, 8 Jun 2017 15:08:49 -0700 Subject: [PATCH 33/38] Changed install from source instructions. (#2178) --- docs/minio-client-complete-guide.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/minio-client-complete-guide.md b/docs/minio-client-complete-guide.md index ac8d709e..ea688081 100644 --- a/docs/minio-client-complete-guide.md +++ b/docs/minio-client-complete-guide.md @@ -52,9 +52,9 @@ Source installation is intended only for developers and advanced users. `mc upda If you do not have a working Golang environment, please follow [How to install Golang](https://docs.minio.io/docs/how-to-install-golang). ```sh - -go get -u github.com/minio/mc - +go get -d github.com/minio/mc +cd ${GOPATH}/src/github.com/minio/mc +make ``` ## 2. Run Minio Client From 800f0af04e455d345fd04d9533a9a85d6fa600d1 Mon Sep 17 00:00:00 2001 From: Anis Elleuch Date: Mon, 12 Jun 2017 22:06:50 +0100 Subject: [PATCH 34/38] config: Hosts listing cuts fields and adds '...' (#2180) New host list format when listing several hosts ``` myminiopublic : http://localhost:9000 myminios : https://minio1.duckdns.org:... Q3AM3UQ867SPQQA43P2F zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG S3v4 testazure : http://172.17.0.7:9000 myazureac Gh5543wekitnifILbZam1KYY3TGlswRminio1... S3v4 ``` New host list format when listing one host: ``` azure: http://localhost:9000 myazureac Gh5543wekitnifILbZam1KYY3TGlswRminio1u7BJ86wekitnifILbZam1K== S3v4 ``` --- cmd/config-host-list.go | 33 +++++++++------- cmd/config-host.go | 45 +++++++++++++-------- cmd/pretty-table.go | 84 ++++++++++++++++++++++++++++++++++++++++ cmd/pretty-table_test.go | 51 ++++++++++++++++++++++++ 4 files changed, 184 insertions(+), 29 deletions(-) create mode 100644 cmd/pretty-table.go create mode 100644 cmd/pretty-table_test.go diff --git a/cmd/config-host-list.go b/cmd/config-host-list.go index 2cb6cf91..86501097 100644 --- a/cmd/config-host-list.go +++ b/cmd/config-host-list.go @@ -94,7 +94,12 @@ func printHosts(hosts ...hostMessage) { } for _, host := range hosts { // Format properly for alignment based on alias length. - host.Alias = fmt.Sprintf("%-*.*s", maxAlias, maxAlias, host.Alias) + host.Alias = fmt.Sprintf("%-*.*s:", maxAlias, maxAlias, host.Alias) + if host.AccessKey == "" || host.SecretKey == "" { + host.AccessKey = "" + host.SecretKey = "" + host.API = "" + } printMsg(host) } } @@ -115,12 +120,13 @@ func listHosts(alias string) { if alias != "" { if v, ok := conf.Hosts[alias]; ok { printHosts(hostMessage{ - op: "list", - Alias: alias, - URL: v.URL, - AccessKey: v.AccessKey, - SecretKey: v.SecretKey, - API: v.API, + op: "list", + prettyPrint: false, + Alias: alias, + URL: v.URL, + AccessKey: v.AccessKey, + SecretKey: v.SecretKey, + API: v.API, }) return } @@ -130,12 +136,13 @@ func listHosts(alias string) { var hosts []hostMessage for k, v := range conf.Hosts { hosts = append(hosts, hostMessage{ - op: "list", - Alias: k, - URL: v.URL, - AccessKey: v.AccessKey, - SecretKey: v.SecretKey, - API: v.API, + op: "list", + prettyPrint: true, + Alias: k, + URL: v.URL, + AccessKey: v.AccessKey, + SecretKey: v.SecretKey, + API: v.API, }) } diff --git a/cmd/config-host.go b/cmd/config-host.go index 443dbcb6..3161a3a8 100644 --- a/cmd/config-host.go +++ b/cmd/config-host.go @@ -18,7 +18,6 @@ package cmd import ( "encoding/json" - "fmt" "github.com/minio/cli" "github.com/minio/mc/pkg/console" @@ -48,27 +47,41 @@ func mainConfigHost(ctx *cli.Context) error { // hostMessage container for content message structure type hostMessage struct { - op string - Status string `json:"status"` - Alias string `json:"alias"` - URL string `json:"URL"` - AccessKey string `json:"accessKey,omitempty"` - SecretKey string `json:"secretKey,omitempty"` - API string `json:"api,omitempty"` + op string + prettyPrint bool + Status string `json:"status"` + Alias string `json:"alias"` + URL string `json:"URL"` + AccessKey string `json:"accessKey,omitempty"` + SecretKey string `json:"secretKey,omitempty"` + API string `json:"api,omitempty"` } -// String colorized host message +// Print the config information of one alias, when prettyPrint flag +// is activated, fields contents are cut and '...' will be added to +// show a pretty table of all aliases configurations func (h hostMessage) String() string { switch h.op { case "list": - message := console.Colorize("Alias", fmt.Sprintf("%s: ", h.Alias)) - message += console.Colorize("URL", fmt.Sprintf("%-30.30s", h.URL)) - if h.AccessKey != "" || h.SecretKey != "" { - message += console.Colorize("AccessKey", fmt.Sprintf(" %-20.20s", h.AccessKey)) - message += console.Colorize("SecretKey", fmt.Sprintf(" %-40.40s", h.SecretKey)) - message += console.Colorize("API", fmt.Sprintf(" %.20s", h.API)) + urlFieldMaxLen, apiFieldMaxLen := -1, -1 + accessFieldMaxLen, secretFieldMaxLen := -1, -1 + // Set cols width if prettyPrint flag is enabled + if h.prettyPrint { + urlFieldMaxLen = 30 + accessFieldMaxLen = 20 + secretFieldMaxLen = 40 + apiFieldMaxLen = 5 } - return message + + // Create a new pretty table with cols configuration + t := newPrettyTable(" ", + Field{"Alias", -1}, + Field{"URL", urlFieldMaxLen}, + Field{"AccessKey", accessFieldMaxLen}, + Field{"SecretKey", secretFieldMaxLen}, + Field{"API", apiFieldMaxLen}, + ) + return t.buildRow(h.Alias, h.URL, h.AccessKey, h.SecretKey, h.API) case "remove": return console.Colorize("HostMessage", "Removed `"+h.Alias+"` successfully.") case "add": diff --git a/cmd/pretty-table.go b/cmd/pretty-table.go new file mode 100644 index 00000000..a3e50b55 --- /dev/null +++ b/cmd/pretty-table.go @@ -0,0 +1,84 @@ +/* + * Minio Client (C) 2017 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 cmd + +import ( + "fmt" + + "github.com/minio/mc/pkg/console" +) + +// Field configuration: color theme and max content length +type Field struct { + colorTheme string + maxLen int +} + +// PrettyTable - an easy struct to format a set of line +type PrettyTable struct { + cols []Field + separator string +} + +// newPrettyTable - creates a new pretty table +func newPrettyTable(separator string, cols ...Field) PrettyTable { + return PrettyTable{ + cols: cols, + separator: separator, + } +} + +// buildRow - creates a string which represents a line table given +// some fields contents. +func (t PrettyTable) buildRow(contents ...string) (line string) { + dots := "..." + + // totalColumns is the minimum of the number of fields config + // and the number of contents elements. + totalColumns := len(contents) + if len(t.cols) < totalColumns { + totalColumns = len(t.cols) + } + + // Format fields and construct message + for i := 0; i < totalColumns; i++ { + // Default field format without pretty effect + fieldContent := "" + fieldFormat := "%s" + if t.cols[i].maxLen >= 0 { + // Override field format + fieldFormat = fmt.Sprintf("%%-%d.%ds", t.cols[i].maxLen, t.cols[i].maxLen) + // Cut field string and add '...' if length is greater than maxLen + if len(contents[i]) > t.cols[i].maxLen { + fieldContent = contents[i][:t.cols[i].maxLen-len(dots)] + dots + } else { + fieldContent = contents[i] + } + } else { + fieldContent = contents[i] + } + + // Add separator if this is not the last column + if i < totalColumns-1 { + fieldFormat += t.separator + } + + // Add the field to the resulted message + line += console.Colorize(t.cols[i].colorTheme, fmt.Sprintf(fieldFormat, fieldContent)) + } + return +} diff --git a/cmd/pretty-table_test.go b/cmd/pretty-table_test.go new file mode 100644 index 00000000..99e56a67 --- /dev/null +++ b/cmd/pretty-table_test.go @@ -0,0 +1,51 @@ +/* + * Minio Client (C) 2017 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 cmd + +import "testing" + +// TestPrettyTable - testing the behavior of the pretty table module +func TestPrettyTable(t *testing.T) { + + testCases := []struct { + sep string + tf []Field + contents []string + expectedRow string + }{ + // Test 1: empty parameter, empty table + {"", []Field{}, []string{}, ""}, + // Test 2: one field, without any specific customization + {"", []Field{Field{"", -1}}, []string{"abcd"}, "abcd"}, + // Test 3: one field, without 5 chars len + {"", []Field{Field{"", 5}}, []string{"my-long-field"}, "my..."}, + // Test 4: one separator, one content + {" | ", []Field{Field{"", -1}}, []string{"abcd"}, "abcd"}, + // Test 5: one separtor, multiple contents + {" | ", []Field{Field{"", -1}, Field{"", -1}, Field{"", -1}}, []string{"column1", "column2", "column3"}, "column1 | column2 | column3"}, + // Test 6: multiple fields + {" | ", []Field{Field{"", 5}, Field{"", -1}}, []string{"144550032", "my long content that should not be cut"}, "14... | my long content that should not be cut"}, + } + + for idx, testCase := range testCases { + tb := newPrettyTable(testCase.sep, testCase.tf...) + row := tb.buildRow(testCase.contents...) + if row != testCase.expectedRow { + t.Fatalf("Test %d: generated row not matching, expected = `%s`, found = `%s`", idx+1, testCase.expectedRow, row) + } + } +} From 21c677fc2d1126e418af289225c009f51bd08d06 Mon Sep 17 00:00:00 2001 From: CarterMcClellan Date: Tue, 13 Jun 2017 14:50:17 -0700 Subject: [PATCH 35/38] config: default S3v2 for google endpoints (#2179) --- cmd/config-host-add.go | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/cmd/config-host-add.go b/cmd/config-host-add.go index b1b4638e..98f4290a 100644 --- a/cmd/config-host-add.go +++ b/cmd/config-host-add.go @@ -17,6 +17,8 @@ package cmd import ( + urlpkg "net/url" + "github.com/fatih/color" "github.com/minio/cli" "github.com/minio/mc/pkg/console" @@ -126,6 +128,16 @@ func mainConfigHostAdd(ctx *cli.Context) error { accessKey := args.Get(2) secretKey := args.Get(3) api := args.Get(4) + + parsedURL, _ := urlpkg.Parse(url) + + if isGoogle(parsedURL.Host) { + if api == "S3v4" { + fatalIf(errInvalidArgument().Trace(api), "Unsupported API signature for url. Please use `mc config host add "+alias+" "+url+" "+accessKey+" "+secretKey+" S3v2` instead.") + } + api = "S3v2" + } + if api == "" { api = "S3v4" } From 2d44e8c85e5896f163c6e57914ff8d6876038998 Mon Sep 17 00:00:00 2001 From: Anis Elleuch Date: Tue, 13 Jun 2017 22:51:20 +0100 Subject: [PATCH 36/38] Fix travis and some code formatting (#2181) --- .travis.yml | 1 + Makefile | 39 ++++++++++++++++++++++----------------- cmd/pretty-table_test.go | 10 +++++----- 3 files changed, 28 insertions(+), 22 deletions(-) diff --git a/.travis.yml b/.travis.yml index ab3d7297..eded8d8a 100644 --- a/.travis.yml +++ b/.travis.yml @@ -15,6 +15,7 @@ script: - make test GOFLAGS="-race" - make coverage - diff -au <(gofmt -d *.go) <(printf "") +- diff -au <(gofmt -d cmd) <(printf "") - diff -au <(gofmt -d pkg) <(printf "") after_success: diff --git a/Makefile b/Makefile index ffb3d0c2..d85c259f 100644 --- a/Makefile +++ b/Makefile @@ -4,21 +4,21 @@ BUILD_LDFLAGS := '$(LDFLAGS) -s -w' all: install checks: - @echo "Checking deps:" + @echo "Checking deps" @(env bash buildscripts/checkdeps.sh) + @echo "Checking project is in GOPATH" @(env bash buildscripts/checkgopath.sh) getdeps: checks - @go get github.com/golang/lint/golint && echo "Installed golint:" - @go get github.com/fzipp/gocyclo && echo "Installed gocyclo:" - @go get github.com/remyoudompheng/go-misc/deadcode && echo "Installed deadcode:" - @go get github.com/client9/misspell/cmd/misspell && echo "Installed misspell:" + @echo "Installing golint" && go get github.com/golang/lint/golint + @echo "Installing gocyclo" && go get github.com/fzipp/gocyclo + @echo "Installing deadcode" && go get github.com/remyoudompheng/go-misc/deadcode + @echo "Installing misspell" && go get github.com/client9/misspell/cmd/misspell -# verifiers: getdeps vet fmt lint cyclo deadcode verifiers: vet fmt lint cyclo deadcode spelling vet: - @echo "Running $@:" + @echo "Running $@" @go tool vet -all *.go @go tool vet -all ./cmd @go tool vet -all ./pkg @@ -32,39 +32,39 @@ spelling: @${GOPATH}/bin/misspell pkg/**/* fmt: - @echo "Running $@:" - @gofmt -s -l *.go - @gofmt -s -l cmd - @gofmt -s -l pkg + @echo "Running $@" + @gofmt -d *.go + @gofmt -d cmd + @gofmt -d pkg lint: - @echo "Running $@:" + @echo "Running $@" @$(GOPATH)/bin/golint . @$(GOPATH)/bin/golint github.com/minio/mc/cmd... @$(GOPATH)/bin/golint github.com/minio/mc/pkg... cyclo: - @echo "Running $@:" + @echo "Running $@" @$(GOPATH)/bin/gocyclo -over 40 cmd @$(GOPATH)/bin/gocyclo -over 40 pkg deadcode: - @echo "Running $@:" + @echo "Running $@" @$(GOPATH)/bin/deadcode build: getdeps verifiers test: getdeps verifiers - @echo "Running all testing:" + @echo "Running all testing" @go test $(GOFLAGS) github.com/minio/mc/cmd... @go test $(GOFLAGS) github.com/minio/mc/pkg... gomake-all: build - @echo "Installing mc:" + @echo "Installing mc at $(GOPATH)/bin/mc" @go build --ldflags $(BUILD_LDFLAGS) -o $(GOPATH)/bin/mc @mkdir -p $(HOME)/.mc coverage: getdeps verifiers - @echo "Running all coverage:" + @echo "Running all coverage for mc" @./buildscripts/go-coverage.sh pkg-validate-arg-%: ; @@ -73,12 +73,15 @@ ifndef PKG endif pkg-add: pkg-validate-arg-add + @echo "Adding new package $(PKG)" @$(GOPATH)/bin/govendor add $(PKG) pkg-update: pkg-validate-arg-update + @echo "Updating new package $(PKG)" @$(GOPATH)/bin/govendor update $(PKG) pkg-remove: pkg-validate-arg-remove + @echo "Remove new package $(PKG)" @$(GOPATH)/bin/govendor remove $(PKG) pkg-list: @@ -88,6 +91,7 @@ install: gomake-all all-tests: test # TODO disable them for now. + # @echo "Running all mc testing" #@./tests/test-minio.sh release: verifiers @@ -97,6 +101,7 @@ experimental: verifiers @MC_RELEASE=EXPERIMENTAL ./buildscripts/build.sh clean: + @echo "Cleaning up all the generated files" @rm -f cover.out @rm -f mc @find . -name '*.test' | xargs rm -fv diff --git a/cmd/pretty-table_test.go b/cmd/pretty-table_test.go index 99e56a67..9dec11fb 100644 --- a/cmd/pretty-table_test.go +++ b/cmd/pretty-table_test.go @@ -30,15 +30,15 @@ func TestPrettyTable(t *testing.T) { // Test 1: empty parameter, empty table {"", []Field{}, []string{}, ""}, // Test 2: one field, without any specific customization - {"", []Field{Field{"", -1}}, []string{"abcd"}, "abcd"}, + {"", []Field{{"", -1}}, []string{"abcd"}, "abcd"}, // Test 3: one field, without 5 chars len - {"", []Field{Field{"", 5}}, []string{"my-long-field"}, "my..."}, + {"", []Field{{"", 5}}, []string{"my-long-field"}, "my..."}, // Test 4: one separator, one content - {" | ", []Field{Field{"", -1}}, []string{"abcd"}, "abcd"}, + {" | ", []Field{{"", -1}}, []string{"abcd"}, "abcd"}, // Test 5: one separtor, multiple contents - {" | ", []Field{Field{"", -1}, Field{"", -1}, Field{"", -1}}, []string{"column1", "column2", "column3"}, "column1 | column2 | column3"}, + {" | ", []Field{{"", -1}, {"", -1}, {"", -1}}, []string{"column1", "column2", "column3"}, "column1 | column2 | column3"}, // Test 6: multiple fields - {" | ", []Field{Field{"", 5}, Field{"", -1}}, []string{"144550032", "my long content that should not be cut"}, "14... | my long content that should not be cut"}, + {" | ", []Field{{"", 5}, {"", -1}}, []string{"144550032", "my long content that should not be cut"}, "14... | my long content that should not be cut"}, } for idx, testCase := range testCases { From ea05fcbcf55b8e7f3266c2f45460a887c6c51001 Mon Sep 17 00:00:00 2001 From: Nitish Tiwari Date: Wed, 14 Jun 2017 20:01:32 -0700 Subject: [PATCH 37/38] Add Docker release files for mc (#2182) - New Dockerfile will be used for mc release images. - Statically built binary is downloaded from dl.minio.io website and used in the docker image. --- Dockerfile.release | 9 +++++++++ Dockerfile.release.aarch64 | 9 +++++++++ Dockerfile.release.armhf | 9 +++++++++ 3 files changed, 27 insertions(+) create mode 100644 Dockerfile.release create mode 100644 Dockerfile.release.aarch64 create mode 100644 Dockerfile.release.armhf diff --git a/Dockerfile.release b/Dockerfile.release new file mode 100644 index 00000000..b37d7c39 --- /dev/null +++ b/Dockerfile.release @@ -0,0 +1,9 @@ +FROM alpine:3.5 + +RUN \ + apk add --no-cache ca-certificates && \ + apk add --no-cache --virtual .build-deps curl && \ + curl https://dl.minio.io/client/mc/release/linux-amd64/mc > /usr/bin/mc && \ + chmod +x /usr/bin/mc && apk del .build-deps + +ENTRYPOINT ["mc"] diff --git a/Dockerfile.release.aarch64 b/Dockerfile.release.aarch64 new file mode 100644 index 00000000..78831cd3 --- /dev/null +++ b/Dockerfile.release.aarch64 @@ -0,0 +1,9 @@ +FROM resin/aarch64-alpine:3.5 + +RUN \ + apk add --no-cache ca-certificates && \ + apk add --no-cache --virtual .build-deps curl && \ + curl https://dl.minio.io/client/mc/release/linux-arm64/mc > /usr/bin/mc && \ + chmod +x /usr/bin/mc && apk del .build-deps + +ENTRYPOINT ["mc"] diff --git a/Dockerfile.release.armhf b/Dockerfile.release.armhf new file mode 100644 index 00000000..ef621967 --- /dev/null +++ b/Dockerfile.release.armhf @@ -0,0 +1,9 @@ +FROM resin/armhf-alpine:3.5 + +RUN \ + apk add --no-cache ca-certificates && \ + apk add --no-cache --virtual .build-deps curl && \ + curl https://dl.minio.io/client/mc/release/linux-arm/mc > /usr/bin/mc && \ + chmod +x /usr/bin/mc && apk del .build-deps + +ENTRYPOINT ["mc"] From c32b1ea48b651125e33015ea0d1596cb377685a4 Mon Sep 17 00:00:00 2001 From: Minio Trusted Date: Wed, 14 Jun 2017 20:34:56 -0700 Subject: [PATCH 38/38] Add -s -w for gen-ldflags.go --- Makefile | 2 +- buildscripts/gen-ldflags.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Makefile b/Makefile index d85c259f..92c72ff4 100644 --- a/Makefile +++ b/Makefile @@ -1,5 +1,5 @@ LDFLAGS := $(shell go run buildscripts/gen-ldflags.go) -BUILD_LDFLAGS := '$(LDFLAGS) -s -w' +BUILD_LDFLAGS := '$(LDFLAGS)' all: install diff --git a/buildscripts/gen-ldflags.go b/buildscripts/gen-ldflags.go index defad840..8cd989a6 100644 --- a/buildscripts/gen-ldflags.go +++ b/buildscripts/gen-ldflags.go @@ -28,7 +28,7 @@ import ( func genLDFlags(version string) string { var ldflagsStr string - ldflagsStr = "-X github.com/minio/mc/cmd.Version=" + version + " " + ldflagsStr = "-s -w -X github.com/minio/mc/cmd.Version=" + version + " " ldflagsStr = ldflagsStr + "-X github.com/minio/mc/cmd.ReleaseTag=" + releaseTag(version) + " " ldflagsStr = ldflagsStr + "-X github.com/minio/mc/cmd.CommitID=" + commitID() + " " ldflagsStr = ldflagsStr + "-X github.com/minio/mc/cmd.ShortCommitID=" + commitID()[:12]