From 0e1e954768ac939b1826c5616805d3bd5c7c03ef Mon Sep 17 00:00:00 2001 From: Anis Elleuch Date: Mon, 23 Jan 2017 00:19:06 +0100 Subject: [PATCH] Add new admin Heal command (#1958) e.g.: `mc admin heal list myminio/` and `mc admin heal myminio/testbucket` Also, some heal files that belong madmin package have been added --- cmd/admin-heal-list.go | 213 +++++++++ cmd/admin-heal.go | 174 ++++++++ cmd/admin-main.go | 1 + .../minio/pkg/madmin/examples/heal-bucket.go | 49 +++ .../minio/pkg/madmin/examples/heal-list.go | 63 +++ .../minio/pkg/madmin/examples/heal-object.go | 49 +++ .../minio/minio/pkg/madmin/heal-commands.go | 405 ++++++++++++++++++ vendor/vendor.json | 4 +- 8 files changed, 956 insertions(+), 2 deletions(-) create mode 100644 cmd/admin-heal-list.go create mode 100644 cmd/admin-heal.go create mode 100644 vendor/github.com/minio/minio/pkg/madmin/examples/heal-bucket.go create mode 100644 vendor/github.com/minio/minio/pkg/madmin/examples/heal-list.go create mode 100644 vendor/github.com/minio/minio/pkg/madmin/examples/heal-object.go create mode 100644 vendor/github.com/minio/minio/pkg/madmin/heal-commands.go diff --git a/cmd/admin-heal-list.go b/cmd/admin-heal-list.go new file mode 100644 index 00000000..ee04fb8d --- /dev/null +++ b/cmd/admin-heal-list.go @@ -0,0 +1,213 @@ +/* + * 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.", + }, + } +) + +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: + mc admin heal {{.Name}} - {{.Usage}} + +USAGE: + mc admin heal {{.Name}} ALIAS/BUCKET/PREFIX + +FLAGS: + {{range .Flags}}{{.}} + {{end}} + +EXAMPLES: + 1. List objects than need to be healed related to 'testbucket' in a Minio server represented by its alias 'play'. + $ mc admin heal {{.Name}} play/testbucket/ + 2. Recursively list objects than need to be healed. + $ mc admin heal {{.Name}} --recursive play/ + +`, +} + +// healListMessage container to hold heal information. +type healListMessage struct { + Status string `json:"status"` + Bucket string `json:"bucket"` + Object madmin.ObjectInfo `json:"object"` +} + +// String colorized service status message. +func (u healListMessage) String() string { + msg := fmt.Sprintf("Object: %s/%s, ", u.Bucket, u.Object.Key) + switch u.Object.HealObjectInfo.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 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") + + // 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{}) + 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 + } + printMsg(healListMessage{Bucket: currBucket, Object: obj}) + } + } + + return nil +} diff --git a/cmd/admin-heal.go b/cmd/admin-heal.go new file mode 100644 index 00000000..b38dcfa8 --- /dev/null +++ b/cmd/admin-heal.go @@ -0,0 +1,174 @@ +/* + * 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" + + "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 ( + adminHealFlags = []cli.Flag{ + cli.BoolFlag{ + Name: "recursive, r", + Usage: "List recursively.", + }, + cli.BoolFlag{ + Name: "fake, k", + Usage: "Issue a fake heal operation.", + }, + } +) + +var adminHealCmd = cli.Command{ + Name: "heal", + Usage: "Manage heal tasks.", + Before: setGlobalsFromContext, + Action: mainAdminHeal, + Flags: append(adminHealFlags, globalFlags...), + Subcommands: []cli.Command{ + adminHealListCmd, + }, + CustomHelpTemplate: `NAME: + {{.Name}} - {{.Usage}} + +USAGE: + {{.Name}} [FLAGS] COMMAND + +FLAGS: + {{range .Flags}}{{.}} + {{end}} +COMMANDS: + {{range .Commands}}{{join .Names ", "}}{{ "\t" }}{{.Usage}} + {{end}} + +EXAMPLES: + 1. Heal 'testbucket' in a Minio server represented by its alias 'play'. + $ mc admin {{.Name}} play/testbucket/ + 2. Heal all objects under 'dir' prefix + $ mc admin {{.Name}} --recursive play/testbucket/dir/ + 3. Issue a fake heal operation to see what the server could report + $ mc admin {{.Name}} --fake play/testbucket/dir/ + +`, +} + +// healObjectMessage container to hold repair information. +type healObjectMessage struct { + Status string `json:"status"` + Bucket string `json:"bucket"` + Object madmin.ObjectInfo `json:"object"` +} + +// String colorized service status message. +func (u healObjectMessage) String() string { + msg := fmt.Sprintf("Object %s/%s is healed.", u.Bucket, u.Object.Key) + return console.Colorize("Heal", msg) +} + +// JSON jsonified service status Message message. +func (u healObjectMessage) JSON() string { + u.Status = "success" + statusJSONBytes, e := json.Marshal(u) + fatalIf(probe.NewError(e), "Unable to marshal into JSON.") + + return string(statusJSONBytes) +} + +// checkAdminHealSyntax - validate all the passed arguments +func checkAdminHealSyntax(ctx *cli.Context) { + if len(ctx.Args()) != 1 { + cli.ShowCommandHelpAndExit(ctx, "heal", 1) // last argument is exit code + } +} + +func mainAdminHeal(ctx *cli.Context) error { + + // Check for command syntax + checkAdminHealSyntax(ctx) + + // Get the alias parameter from cli + args := ctx.Args() + aliasedURL := args.Get(0) + + isRecursive := ctx.Bool("recursive") + isFake := ctx.Bool("fake") + + console.SetColor("Heal", color.New(color.FgGreen, color.Bold)) + + // Create a new Minio Admin Client + client, err := newAdminClient(aliasedURL) + if err != nil { + return err.ToGoError() + } + + // Compute bucket and object from the aliased URL + aliasedURL = filepath.ToSlash(aliasedURL) + splits := splitStr(aliasedURL, "/", 3) + bucket, object := splits[1], splits[2] + + // Heal format if bucket is not specified + if bucket == "" { + // TBD, Heal format - not ready yet + console.Println("Healing format is not implemented yet.") + return nil + } + + // Heal the specified bucket + if e := client.HealBucket(bucket, isFake); e != nil { + fatalIf(probe.NewError(e), "Cannot repair bucket.") + } + + // Search for objects that need healing + doneCh := make(chan struct{}) + healObjectsCh, e := client.ListObjectsHeal(bucket, object, isRecursive, doneCh) + fatalIf(probe.NewError(e), "Cannot list objects that need to be healed.") + + // Iterate over objects that need healing + for obj := range healObjectsCh { + // Return for any error + if obj.Err != nil { + fatalIf(probe.NewError(e), "Cannot list objects that need to be healed.") + } + + // 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: + // Heal Object + e := client.HealObject(bucket, obj.Key, isFake) + if e != nil { + errorIf(probe.NewError(e), "Cannot repair object: `"+obj.Key+"`") + } + // Print successful message + printMsg(healObjectMessage{Bucket: bucket, Object: obj}) + + case madmin.QuorumUnavailable: + errorIf(errDummy().Trace(), obj.Key+" cannot be healed until quorum is available.") + case madmin.Corrupted: + errorIf(errDummy().Trace(), obj.Key+" cannot be healed, not enough information.") + } + } + + return nil +} diff --git a/cmd/admin-main.go b/cmd/admin-main.go index 6059b45b..60d065bd 100644 --- a/cmd/admin-main.go +++ b/cmd/admin-main.go @@ -31,6 +31,7 @@ var adminCmd = cli.Command{ Subcommands: []cli.Command{ adminServiceCmd, adminLockCmd, + adminHealCmd, }, CustomHelpTemplate: `NAME: {{.Name}} - {{.Usage}} diff --git a/vendor/github.com/minio/minio/pkg/madmin/examples/heal-bucket.go b/vendor/github.com/minio/minio/pkg/madmin/examples/heal-bucket.go new file mode 100644 index 00000000..567eb14d --- /dev/null +++ b/vendor/github.com/minio/minio/pkg/madmin/examples/heal-bucket.go @@ -0,0 +1,49 @@ +// +build ignore + +/* + * Minio 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 main + +import ( + "log" + + "github.com/minio/minio/pkg/madmin" +) + +func main() { + // Note: YOUR-ACCESSKEYID, YOUR-SECRETACCESSKEY are + // dummy values, please replace them with original values. + + // Note: YOUR-ACCESSKEYID, YOUR-SECRETACCESSKEY are + // dummy values, please replace them with original values. + + // API requests are secure (HTTPS) if secure=true and insecure (HTTPS) otherwise. + // New returns an Minio Admin client object. + madmClnt, err := madmin.New("your-minio.example.com:9000", "YOUR-ACCESSKEYID", "YOUR-SECRETACCESSKEY", true) + if err != nil { + log.Fatalln(err) + } + + // Heal bucket mybucket + err = madmClnt.HealBucket("mybucket") + if err != nil { + log.Fatalln(err) + } + + log.Println("successfully healed mybucket") +} diff --git a/vendor/github.com/minio/minio/pkg/madmin/examples/heal-list.go b/vendor/github.com/minio/minio/pkg/madmin/examples/heal-list.go new file mode 100644 index 00000000..deb60038 --- /dev/null +++ b/vendor/github.com/minio/minio/pkg/madmin/examples/heal-list.go @@ -0,0 +1,63 @@ +package main + +/* + * Minio 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. + * + */ + +import ( + "fmt" + "log" + + "github.com/minio/minio/pkg/madmin" +) + +func main() { + + // Note: YOUR-ACCESSKEYID, YOUR-SECRETACCESSKEY are + // dummy values, please replace them with original values. + + // API requests are secure (HTTPS) if secure=true and insecure (HTTPS) otherwise. + // New returns an Minio Admin client object. + madmClnt, err := madmin.New("localhost:9000", "minio", "minio123", false) + if err != nil { + log.Fatalln(err) + } + + bucket := "testbucket" + prefix := "" + + // Create a done channel to control 'ListObjectsHeal' go routine. + doneCh := make(chan struct{}) + // Indicate to our routine to exit cleanly upon return. + defer close(doneCh) + + // Set true if recursive listing is needed. + isRecursive := true + // List objects that need healing for a given bucket and + // prefix. + healObjectsCh, err := madmClnt.ListObjectsHeal(bucket, prefix, isRecursive, doneCh) + if err != nil { + log.Fatalln(err) + } + + for object := range healObjectsCh { + if object.Err != nil { + log.Fatalln(err) + return + } + fmt.Println("object: ", object) + } +} diff --git a/vendor/github.com/minio/minio/pkg/madmin/examples/heal-object.go b/vendor/github.com/minio/minio/pkg/madmin/examples/heal-object.go new file mode 100644 index 00000000..db2ecc5a --- /dev/null +++ b/vendor/github.com/minio/minio/pkg/madmin/examples/heal-object.go @@ -0,0 +1,49 @@ +// +build ignore + +/* + * Minio 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 main + +import ( + "log" + + "github.com/minio/minio/pkg/madmin" +) + +func main() { + // Note: YOUR-ACCESSKEYID, YOUR-SECRETACCESSKEY are + // dummy values, please replace them with original values. + + // Note: YOUR-ACCESSKEYID, YOUR-SECRETACCESSKEY are + // dummy values, please replace them with original values. + + // API requests are secure (HTTPS) if secure=true and insecure (HTTPS) otherwise. + // New returns an Minio Admin client object. + madmClnt, err := madmin.New("your-minio.example.com:9000", "YOUR-ACCESSKEYID", "YOUR-SECRETACCESSKEY", true) + if err != nil { + log.Fatalln(err) + } + + // Heal object mybucket/myobject. + err = madmClnt.HealObject("mybucket", "myobject") + if err != nil { + log.Fatalln(err) + } + + log.Println("successfully healed mybucket/myobject") +} diff --git a/vendor/github.com/minio/minio/pkg/madmin/heal-commands.go b/vendor/github.com/minio/minio/pkg/madmin/heal-commands.go new file mode 100644 index 00000000..e439b84d --- /dev/null +++ b/vendor/github.com/minio/minio/pkg/madmin/heal-commands.go @@ -0,0 +1,405 @@ +/* + * Minio 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 madmin + +import ( + "encoding/xml" + "errors" + "fmt" + "net/http" + "net/url" + "time" +) + +// listBucketHealResult container for listObjects response. +type listBucketHealResult struct { + // A response can contain CommonPrefixes only if you have + // specified a delimiter. + CommonPrefixes []commonPrefix + // Metadata about each object returned. + Contents []ObjectInfo + Delimiter string + + // Encoding type used to encode object keys in the response. + EncodingType string + + // A flag that indicates whether or not ListObjects returned all of the results + // that satisfied the search criteria. + IsTruncated bool + Marker string + MaxKeys int64 + Name string + + // When response is truncated (the IsTruncated element value in + // the response is true), you can use the key name in this field + // as marker in the subsequent request to get next set of objects. + // Object storage lists objects in alphabetical order Note: This + // element is returned only if you have delimiter request + // parameter specified. If response does not include the NextMaker + // and it is truncated, you can use the value of the last Key in + // the response as the marker in the subsequent request to get the + // next set of object keys. + NextMarker string + Prefix string +} + +// commonPrefix container for prefix response. +type commonPrefix struct { + Prefix string +} + +// Owner - bucket owner/principal +type Owner struct { + ID string + DisplayName string +} + +// Bucket container for bucket metadata +type Bucket struct { + Name string + CreationDate string // time string of format "2006-01-02T15:04:05.000Z" + + HealBucketInfo *HealBucketInfo `xml:"HealBucketInfo,omitempty"` +} + +// ListBucketsHealResponse - format for list buckets response +type ListBucketsHealResponse struct { + XMLName xml.Name `xml:"http://s3.amazonaws.com/doc/2006-03-01/ ListAllMyBucketsResult" json:"-"` + + Owner Owner + + // Container for one or more buckets. + Buckets struct { + Buckets []Bucket `xml:"Bucket"` + } // Buckets are nested +} + +// HealStatus - represents different states of healing an object could be in. +type healStatus int + +const ( + // Healthy - Object that is already healthy + Healthy healStatus = iota + // CanHeal - Object can be healed + CanHeal + // Corrupted - Object can't be healed + Corrupted + // QuorumUnavailable - Object can't be healed until read quorum is available + QuorumUnavailable +) + +// HealBucketInfo - represents healing related information of a bucket. +type HealBucketInfo struct { + Status healStatus +} + +// BucketInfo - represents bucket metadata. +type BucketInfo struct { + // Name of the bucket. + Name string + + // Date and time when the bucket was created. + Created time.Time + + // Healing information + HealBucketInfo *HealBucketInfo `xml:"HealBucketInfo,omitempty"` +} + +// HealObjectInfo - represents healing related information of an object. +type HealObjectInfo struct { + Status healStatus + MissingDataCount int + MissingPartityCount int +} + +// ObjectInfo container for object metadata. +type ObjectInfo struct { + // An ETag is optionally set to md5sum of an object. In case of multipart objects, + // ETag is of the form MD5SUM-N where MD5SUM is md5sum of all individual md5sums of + // each parts concatenated into one string. + ETag string `json:"etag"` + + Key string `json:"name"` // Name of the object + LastModified time.Time `json:"lastModified"` // Date and time the object was last modified. + Size int64 `json:"size"` // Size in bytes of the object. + ContentType string `json:"contentType"` // A standard MIME type describing the format of the object data. + + // Collection of additional metadata on the object. + // eg: x-amz-meta-*, content-encoding etc. + Metadata http.Header `json:"metadata"` + + // Owner name. + Owner struct { + DisplayName string `json:"name"` + ID string `json:"id"` + } `json:"owner"` + + // The class of storage used to store the object. + StorageClass string `json:"storageClass"` + + // Error + Err error `json:"-"` + HealObjectInfo *HealObjectInfo `json:"healObjectInfo,omitempty"` +} + +type healQueryKey string + +const ( + healBucket healQueryKey = "bucket" + healObject healQueryKey = "object" + healPrefix healQueryKey = "prefix" + healMarker healQueryKey = "marker" + healDelimiter healQueryKey = "delimiter" + healMaxKey healQueryKey = "max-key" + healDryRun healQueryKey = "dry-run" +) + +// mkHealQueryVal - helper function to construct heal REST API query params. +func mkHealQueryVal(bucket, prefix, marker, delimiter, maxKeyStr string) url.Values { + queryVal := make(url.Values) + queryVal.Set("heal", "") + queryVal.Set(string(healBucket), bucket) + queryVal.Set(string(healPrefix), prefix) + queryVal.Set(string(healMarker), marker) + queryVal.Set(string(healDelimiter), delimiter) + queryVal.Set(string(healMaxKey), maxKeyStr) + return queryVal +} + +// listObjectsHeal - issues heal list API request for a batch of maxKeys objects to be healed. +func (adm *AdminClient) listObjectsHeal(bucket, prefix, delimiter, marker string, maxKeys int) (listBucketHealResult, error) { + // Construct query params. + maxKeyStr := fmt.Sprintf("%d", maxKeys) + queryVal := mkHealQueryVal(bucket, prefix, marker, delimiter, maxKeyStr) + + hdrs := make(http.Header) + hdrs.Set(minioAdminOpHeader, "list-objects") + + reqData := requestData{ + queryValues: queryVal, + customHeaders: hdrs, + } + + // Empty 'list' of objects to be healed. + toBeHealedObjects := listBucketHealResult{} + + // Execute GET on /?heal to list objects needing heal. + resp, err := adm.executeMethod("GET", reqData) + + defer closeResponse(resp) + if err != nil { + return listBucketHealResult{}, err + } + + if resp.StatusCode != http.StatusOK { + return toBeHealedObjects, errors.New("Got HTTP Status: " + resp.Status) + } + + err = xml.NewDecoder(resp.Body).Decode(&toBeHealedObjects) + if err != nil { + return toBeHealedObjects, err + } + return toBeHealedObjects, nil +} + +// ListObjectsHeal - Lists upto maxKeys objects that needing heal matching bucket, prefix, marker, delimiter. +func (adm *AdminClient) ListObjectsHeal(bucket, prefix string, recursive bool, doneCh <-chan struct{}) (<-chan ObjectInfo, error) { + // Allocate new list objects channel. + objectStatCh := make(chan ObjectInfo, 1) + // Default listing is delimited at "/" + delimiter := "/" + if recursive { + // If recursive we do not delimit. + delimiter = "" + } + + // Initiate list objects goroutine here. + go func(objectStatCh chan<- ObjectInfo) { + defer close(objectStatCh) + // Save marker for next request. + var marker string + for { + // Get list of objects a maximum of 1000 per request. + result, err := adm.listObjectsHeal(bucket, prefix, marker, delimiter, 1000) + if err != nil { + objectStatCh <- ObjectInfo{ + Err: err, + } + return + } + + // If contents are available loop through and send over channel. + for _, object := range result.Contents { + // Save the marker. + marker = object.Key + select { + // Send object content. + case objectStatCh <- object: + // If receives done from the caller, return here. + case <-doneCh: + return + } + } + + // Send all common prefixes if any. + // NOTE: prefixes are only present if the request is delimited. + for _, obj := range result.CommonPrefixes { + object := ObjectInfo{} + object.Key = obj.Prefix + object.Size = 0 + select { + // Send object prefixes. + case objectStatCh <- object: + // If receives done from the caller, return here. + case <-doneCh: + return + } + } + + // If next marker present, save it for next request. + if result.NextMarker != "" { + marker = result.NextMarker + } + + // Listing ends result is not truncated, return right here. + if !result.IsTruncated { + return + } + } + }(objectStatCh) + return objectStatCh, nil +} + +const timeFormatAMZLong = "2006-01-02T15:04:05.000Z" // Reply date format with nanosecond precision. + +// ListBucketsHeal - issues heal bucket list API request +func (adm *AdminClient) ListBucketsHeal() ([]BucketInfo, error) { + queryVal := url.Values{} + queryVal.Set("heal", "") + + hdrs := make(http.Header) + hdrs.Set(minioAdminOpHeader, "list-buckets") + + reqData := requestData{ + queryValues: queryVal, + customHeaders: hdrs, + } + + // Execute GET on /?heal to list objects needing heal. + resp, err := adm.executeMethod("GET", reqData) + + defer closeResponse(resp) + if err != nil { + return []BucketInfo{}, err + } + + if resp.StatusCode != http.StatusOK { + return []BucketInfo{}, errors.New("Got HTTP Status: " + resp.Status) + } + + var listBucketsHealResult ListBucketsHealResponse + + err = xml.NewDecoder(resp.Body).Decode(&listBucketsHealResult) + if err != nil { + return []BucketInfo{}, err + } + + var bucketsToBeHealed []BucketInfo + + for _, bucket := range listBucketsHealResult.Buckets.Buckets { + creationDate, err := time.Parse(timeFormatAMZLong, bucket.CreationDate) + if err != nil { + return []BucketInfo{}, err + } + bucketsToBeHealed = append(bucketsToBeHealed, + BucketInfo{ + Name: bucket.Name, + Created: creationDate, + HealBucketInfo: bucket.HealBucketInfo, + }) + } + + return bucketsToBeHealed, nil +} + +// HealBucket - Heal the given bucket +func (adm *AdminClient) HealBucket(bucket string, dryrun bool) error { + // Construct query params. + queryVal := url.Values{} + queryVal.Set("heal", "") + queryVal.Set(string(healBucket), bucket) + if dryrun { + queryVal.Set(string(healDryRun), "yes") + } + + hdrs := make(http.Header) + hdrs.Set(minioAdminOpHeader, "bucket") + + reqData := requestData{ + queryValues: queryVal, + customHeaders: hdrs, + } + + // Execute POST on /?heal&bucket=mybucket to heal a bucket. + resp, err := adm.executeMethod("POST", reqData) + + defer closeResponse(resp) + if err != nil { + return err + } + + if resp.StatusCode != http.StatusOK { + return errors.New("Got HTTP Status: " + resp.Status) + } + + return nil +} + +// HealObject - Heal the given object. +func (adm *AdminClient) HealObject(bucket, object string, dryrun bool) error { + // Construct query params. + queryVal := url.Values{} + queryVal.Set("heal", "") + queryVal.Set(string(healBucket), bucket) + queryVal.Set(string(healObject), object) + if dryrun { + queryVal.Set(string(healDryRun), "yes") + } + + hdrs := make(http.Header) + hdrs.Set(minioAdminOpHeader, "object") + + reqData := requestData{ + queryValues: queryVal, + customHeaders: hdrs, + } + + // Execute POST on /?heal&bucket=mybucket&object=myobject to heal an object. + resp, err := adm.executeMethod("POST", reqData) + + defer closeResponse(resp) + if err != nil { + return err + } + + if resp.StatusCode != http.StatusOK { + return errors.New("Got HTTP Status: " + resp.Status) + } + + return nil +} diff --git a/vendor/vendor.json b/vendor/vendor.json index 7369ae9c..3769ae89 100644 --- a/vendor/vendor.json +++ b/vendor/vendor.json @@ -82,8 +82,8 @@ { "checksumSHA1": "gsJXCQU0qB6V7hdxCpJ64duQwn0=", "path": "github.com/minio/minio/pkg/madmin", - "revision": "a17f1e875ce5944b2cdbb2c685f1ab32ed8adff5", - "revisionTime": "2017-01-19T19:19:57Z" + "revision": "80f13878776a1944934cc8a6fb4666c145355400", + "revisionTime": "2017-01-19T19:32:13Z" }, { "path": "github.com/minio/minio/pkg/probe",