From cf89d74561867d319b43dfe21a7252bf021af33d Mon Sep 17 00:00:00 2001 From: Harshavardhana Date: Sun, 20 Nov 2016 16:31:53 -0800 Subject: [PATCH] Vendorize new minio-go code. (#1891) This fixes #1889. ```sh mc mirror -w ``` Now runs continous even when the source is not available. Reconnects indefinitely in a binomially increasing fashion and also allows jitter so that the retry has a nice distribution as well. This allows for 'mc mirror -w' to run continously without further monitoring. --- .travis.yml | 2 +- cmd/client-fs.go | 5 -- cmd/client-s3.go | 11 ---- cmd/client.go | 1 - cmd/diff-main.go | 4 +- cmd/difference.go | 12 ++-- cmd/mirror-main.go | 63 ++++++++----------- cmd/mirror-url.go | 33 +++++----- cmd/rm-main.go | 34 +++++----- cmd/session-v8.go | 2 + cmd/utils.go | 13 ++-- cmd/watch-main.go | 2 - cmd/watch.go | 12 ---- .../minio/minio-go/api-notification.go | 25 ++++---- .../minio/minio-go/api-put-object.go | 9 ++- vendor/github.com/minio/minio-go/api.go | 54 ++++++++++++---- .../github.com/minio/minio-go/post-policy.go | 18 ++++++ .../minio/minio-go/retry-continous.go | 52 +++++++++++++++ vendor/vendor.json | 6 +- 19 files changed, 215 insertions(+), 143 deletions(-) create mode 100644 vendor/github.com/minio/minio-go/retry-continous.go diff --git a/.travis.yml b/.travis.yml index 3aa5d421..5657b5b6 100644 --- a/.travis.yml +++ b/.travis.yml @@ -5,7 +5,7 @@ os: - linux - osx -osx_image: xcode7.2 +osx_image: xcode7.3 env: - ARCH=x86_64 diff --git a/cmd/client-fs.go b/cmd/client-fs.go index 174316e2..82746113 100644 --- a/cmd/client-fs.go +++ b/cmd/client-fs.go @@ -86,11 +86,6 @@ func (f *fsClient) GetURL() clientURL { return *f.PathURL } -// Unwatch - not implemented for fs, on purpose. -func (f *fsClient) Unwatch(params watchParams) *probe.Error { - return nil -} - // Watches for all fs events on an input path. func (f *fsClient) Watch(params watchParams) (*watchObject, *probe.Error) { eventChan := make(chan Event) diff --git a/cmd/client-s3.go b/cmd/client-s3.go index af11438e..2740a508 100644 --- a/cmd/client-s3.go +++ b/cmd/client-s3.go @@ -336,17 +336,6 @@ func (c *s3Client) ListNotificationConfigs(arn string) ([]notificationConfig, *p return configs, nil } -// Unwatch de-registers all bucket notification events for a given accountID. -func (c *s3Client) Unwatch(params watchParams) *probe.Error { - // Extract bucket and object. - bucket, _ := c.url2BucketAndObject() - if err := isValidBucketName(bucket); err != nil { - return err - } - // Success. - return nil -} - // Start watching on all bucket events for a given account ID. func (c *s3Client) Watch(params watchParams) (*watchObject, *probe.Error) { eventChan := make(chan Event) diff --git a/cmd/client.go b/cmd/client.go index 8c4a6f85..2a9ba72e 100644 --- a/cmd/client.go +++ b/cmd/client.go @@ -61,7 +61,6 @@ type Client interface { // Watch events Watch(params watchParams) (*watchObject, *probe.Error) - Unwatch(params watchParams) *probe.Error // Delete operations Remove(isIncomplete bool, contentCh <-chan *clientContent) (errorCh <-chan *probe.Error) diff --git a/cmd/diff-main.go b/cmd/diff-main.go index d4745b0f..2dedb195 100644 --- a/cmd/diff-main.go +++ b/cmd/diff-main.go @@ -175,8 +175,10 @@ func doDiffMain(firstURL, secondURL string) { fmt.Sprintf("Failed to diff '%s' and '%s'", firstURL, secondURL)) } + watchMode := false + // Diff first and second urls. - for diffMsg := range objectDifference(firstClient, secondClient, firstURL, secondURL) { + for diffMsg := range objectDifference(firstClient, secondClient, firstURL, secondURL, watchMode) { printMsg(diffMsg) } } diff --git a/cmd/difference.go b/cmd/difference.go index e5377fda..0a972d6b 100644 --- a/cmd/difference.go +++ b/cmd/difference.go @@ -50,7 +50,7 @@ func (d differType) String() string { // objectDifference function finds the difference between all objects // recursively in sorted order from source and target. -func objectDifference(sourceClnt, targetClnt Client, sourceURL, targetURL string) (diffCh chan diffMessage) { +func objectDifference(sourceClnt, targetClnt Client, sourceURL, targetURL string, watchMode bool) (diffCh chan diffMessage) { var ( srcEOF, tgtEOF bool srcOk, tgtOk bool @@ -77,15 +77,17 @@ func objectDifference(sourceClnt, targetClnt Client, sourceURL, targetURL string // No objects from source AND target: Finish if srcEOF && tgtEOF { - close(diffCh) - break + if !watchMode { + close(diffCh) + break + } } if !srcEOF && srcCtnt.Err != nil { if isErrIgnored(srcCtnt.Err) { errorIf(srcCtnt.Err.Trace(sourceURL, targetURL), fmt.Sprintf("Failed on '%s'", sourceURL)) } else { - fatalIf(srcCtnt.Err.Trace(sourceURL, targetURL), fmt.Sprintf("Failed on '%s'", sourceURL)) + errorIf(srcCtnt.Err.Trace(sourceURL, targetURL), fmt.Sprintf("Failed on '%s'", sourceURL)) } srcCtnt, srcOk = <-srcCh continue @@ -95,7 +97,7 @@ func objectDifference(sourceClnt, targetClnt Client, sourceURL, targetURL string if isErrIgnored(tgtCtnt.Err) { errorIf(tgtCtnt.Err.Trace(sourceURL, targetURL), fmt.Sprintf("Failed on '%s'", targetURL)) } else { - fatalIf(tgtCtnt.Err.Trace(sourceURL, targetURL), fmt.Sprintf("Failed on '%s'", targetURL)) + errorIf(tgtCtnt.Err.Trace(sourceURL, targetURL), fmt.Sprintf("Failed on '%s'", targetURL)) } tgtCtnt, tgtOk = <-tgtCh continue diff --git a/cmd/mirror-main.go b/cmd/mirror-main.go index 447cecc4..496326e8 100644 --- a/cmd/mirror-main.go +++ b/cmd/mirror-main.go @@ -296,7 +296,9 @@ func (ms *mirrorSession) startStatus() { errorIf(sURLs.Error.Trace(sURLs.TargetContent.URL.String()), fmt.Sprintf("Failed to remove ‘%s’.", sURLs.TargetContent.URL.String())) } - + if ms.Header.CommandBoolFlags["watch"] { + continue + } // For all non critical errors we can continue for the remaining files. if isErrIgnored(sURLs.Error) { continue @@ -362,6 +364,12 @@ func (ms *mirrorSession) startMirror(wait bool) { fatalIf(errInvalidArgument(), fmt.Sprintf("URLs type not found, %#v", v)) } + // Save total count. + sURLs.TotalCount = ms.Header.TotalObjects + + // Save totalSize. + sURLs.TotalSize = ms.Header.TotalBytes + if sURLs.SourceContent != nil { ms.statusCh <- ms.doMirror(sURLs) } else if sURLs.TargetContent != nil && isRemove { @@ -449,6 +457,8 @@ func (ms *mirrorSession) watch() { shouldQueue = true } if shouldQueue || isForce { + mirrorURL.TotalCount = ms.Header.TotalObjects + mirrorURL.TotalSize = ms.Header.TotalBytes if e := ms.queue.Push(mirrorURL); e != nil { // will throw an error if already queue, ignoring this error continue @@ -475,6 +485,8 @@ func (ms *mirrorSession) watch() { } if shouldQueue || isForce { mirrorURL.SourceContent.Size = event.Size + mirrorURL.TotalCount = ms.Header.TotalObjects + mirrorURL.TotalSize = ms.Header.TotalBytes if e := ms.queue.Push(mirrorURL); e != nil { // will throw an error if already queue, ignoring this error continue @@ -489,6 +501,8 @@ func (ms *mirrorSession) watch() { TargetAlias: targetAlias, TargetContent: &clientContent{URL: *targetURL}, } + mirrorURL.TotalCount = ms.Header.TotalObjects + mirrorURL.TotalSize = ms.Header.TotalBytes if err := ms.queue.Push(mirrorURL); err != nil { // will throw an error if already queue, ignoring this error continue @@ -501,14 +515,6 @@ func (ms *mirrorSession) watch() { } } -func (ms *mirrorSession) unwatchSourceURL(recursive bool) *probe.Error { - sourceClient, err := newClient(ms.sourceURL) - if err == nil { - return ms.watcher.Unjoin(sourceClient, recursive) - } // Failed to initialize client. - return err -} - func (ms *mirrorSession) watchSourceURL(recursive bool) *probe.Error { sourceClient, err := newClient(ms.sourceURL) if err == nil { @@ -529,12 +535,6 @@ func (ms *mirrorSession) harvestSessionUrls() { continue } - // Save total count. - urls.TotalCount = ms.Header.TotalObjects - - // Save totalSize. - urls.TotalSize = ms.Header.TotalBytes - // Send harvested urls. ms.harvestCh <- urls } @@ -548,11 +548,13 @@ func (ms *mirrorSession) harvestSourceUrls(recursive bool) { isForce := ms.Header.CommandBoolFlags["force"] isFake := ms.Header.CommandBoolFlags["fake"] isRemove := ms.Header.CommandBoolFlags["remove"] + isWatch := ms.Header.CommandBoolFlags["watch"] defer close(ms.harvestCh) - URLsCh := prepareMirrorURLs(ms.sourceURL, ms.targetURL, isForce, isFake, isRemove) + URLsCh := prepareMirrorURLs(ms.sourceURL, ms.targetURL, isForce, isFake, isRemove, isWatch) for url := range URLsCh { + // Send harvested urls. ms.harvestCh <- url } } @@ -585,7 +587,6 @@ loop: } else { ms.status.errorIf(sURLs.Error.Trace(), "Unable to prepare URL for copying.") } - continue } @@ -602,7 +603,8 @@ loop: totalObjects++ case err := <-ms.errorCh: - ms.status.fatalIf(err, "Unable to harvest URL for copying.") + ms.status.errorIf(err, "Unable to harvest URL for copying.") + continue case <-ms.trapCh: ms.status.Println(console.Colorize("Mirror", "Abort")) return @@ -651,18 +653,10 @@ func (ms *mirrorSession) mirror() { // on SIGTERM shutdown and stop <-ms.trapCh + // Shutdown gracefully. ms.shutdown() - // Remove watches on source url. - ms.unwatchSourceURL(true) - - // no items left, just stop - if ms.queue.Count() == 0 { - ms.Delete() - os.Exit(0) - return - } - + // Save session and die. ms.CloseAndDie() }() @@ -677,10 +671,6 @@ func (ms *mirrorSession) mirror() { ms.startMirror(true) ms.watch() - - // don't let monitor finish, only on SIGTERM - done := make(chan bool) - <-done } else { ms.startMirror(false) @@ -770,7 +760,6 @@ func mainMirror(ctx *cli.Context) { session.Header.RootPath = v } else { session.Delete() - fatalIf(probe.NewError(err), "Unable to get current working folder.") } @@ -785,9 +774,9 @@ func mainMirror(ctx *cli.Context) { ms := newMirrorSession(session) - // delete will be run when terminating normally, - // on SIGTERM it won't execute - defer ms.Delete() - + // Mirroring. ms.mirror() + + // delete will be run when terminating normally, + ms.Delete() } diff --git a/cmd/mirror-url.go b/cmd/mirror-url.go index 818cd6b8..7e0d8f41 100644 --- a/cmd/mirror-url.go +++ b/cmd/mirror-url.go @@ -40,15 +40,17 @@ func checkMirrorSyntax(ctx *cli.Context) { tgtURL := URLs[1] /****** Generic rules *******/ - _, srcContent, err := url2Stat(srcURL) - // incomplete uploads are not necessary for copy operation, no need to verify for them. - isIncomplete := false - if err != nil && !isURLPrefixExists(srcURL, isIncomplete) { - fatalIf(err.Trace(srcURL), "Unable to stat source ‘"+srcURL+"’.") - } + if !ctx.Bool("watch") { + _, srcContent, err := url2Stat(srcURL) + // incomplete uploads are not necessary for copy operation, no need to verify for them. + isIncomplete := false + if err != nil && !isURLPrefixExists(srcURL, isIncomplete) { + errorIf(err.Trace(srcURL), "Unable to stat source ‘"+srcURL+"’.") + } - if err == nil && !srcContent.Type.IsDir() { - fatalIf(errInvalidArgument().Trace(srcContent.URL.String(), srcContent.Type.String()), fmt.Sprintf("Source ‘%s’ is not a folder. Only folders are supported by mirror command.", srcURL)) + if err == nil && !srcContent.Type.IsDir() { + fatalIf(errInvalidArgument().Trace(srcContent.URL.String(), srcContent.Type.String()), fmt.Sprintf("Source ‘%s’ is not a folder. Only folders are supported by mirror command.", srcURL)) + } } if len(tgtURL) == 0 && tgtURL == "" { @@ -64,14 +66,17 @@ func checkMirrorSyntax(ctx *cli.Context) { } } } - _, _, err = url2Stat(tgtURL) + _, _, err := url2Stat(tgtURL) // we die on any error other than PathNotFound - destination directory need not exist. - if _, ok := err.ToGoError().(PathNotFound); !ok { + switch err.ToGoError().(type) { + case PathNotFound: + case ObjectMissing: + default: fatalIf(err.Trace(tgtURL), fmt.Sprintf("Unable to stat target ‘%s’.", tgtURL)) } } -func deltaSourceTarget(sourceURL string, targetURL string, isForce bool, isFake bool, isRemove bool, URLsCh chan<- URLs) { +func deltaSourceTarget(sourceURL string, targetURL string, isForce bool, isFake bool, isRemove bool, isWatch bool, URLsCh chan<- URLs) { // source and targets are always directories sourceSeparator := string(newClientURL(sourceURL).Separator) if !strings.HasSuffix(sourceURL, sourceSeparator) { @@ -101,7 +106,7 @@ func deltaSourceTarget(sourceURL string, targetURL string, isForce bool, isFake } // List both source and target, compare and return values through channel. - for diffMsg := range objectDifference(sourceClnt, targetClnt, sourceURL, targetURL) { + for diffMsg := range objectDifference(sourceClnt, targetClnt, sourceURL, targetURL, isWatch) { switch diffMsg.Diff { case differInNone: // No difference, continue. @@ -165,8 +170,8 @@ func deltaSourceTarget(sourceURL string, targetURL string, isForce bool, isFake } // Prepares urls that need to be copied or removed based on requested options. -func prepareMirrorURLs(sourceURL string, targetURL string, isForce bool, isFake bool, isRemove bool) <-chan URLs { +func prepareMirrorURLs(sourceURL string, targetURL string, isForce bool, isFake bool, isWatch bool, isRemove bool) <-chan URLs { URLsCh := make(chan URLs) - go deltaSourceTarget(sourceURL, targetURL, isForce, isFake, isRemove, URLsCh) + go deltaSourceTarget(sourceURL, targetURL, isForce, isFake, isRemove, isWatch, URLsCh) return URLsCh } diff --git a/cmd/rm-main.go b/cmd/rm-main.go index 809fa3e1..20752015 100644 --- a/cmd/rm-main.go +++ b/cmd/rm-main.go @@ -101,7 +101,8 @@ EXAMPLES: // Structured message depending on the type of console. type rmMessage struct { - Key string `json:"key"` + Key string `json:"key"` + Size int64 `json:"size"` } // Colorized message for console printing. @@ -143,13 +144,12 @@ func removeSingle(url string, isIncomplete bool, isFake bool, older int) { return // End of journey. } + content, pErr := clnt.Stat(isIncomplete) + if pErr != nil { + errorIf(pErr.Trace(url), "Failed to remove ‘"+url+"’.") + return + } if older > 0 { - content, pErr := clnt.Stat(isIncomplete) - if pErr != nil { - errorIf(pErr.Trace(url), "Failed to remove ‘"+url+"’.") - return - } - // Check whether object is created older than given time. now := time.Now().UTC() timeDiff := now.Sub(content.Time) @@ -159,7 +159,11 @@ func removeSingle(url string, isIncomplete bool, isFake bool, older int) { } } - printMsg(rmMessage{Key: url}) + printMsg(rmMessage{ + Key: url, + Size: content.Size, + }) + if !isFake { contentCh := make(chan *clientContent, 1) contentCh <- &clientContent{URL: *newClientURL(targetURL)} @@ -195,15 +199,13 @@ func removeRecursive(url string, isIncomplete bool, isFake bool, older int) { isRecursive := true for content := range clnt.List(isRecursive, isIncomplete, DirLast) { isEmpty = false - pErr := content.Err - if pErr != nil { - errorIf(pErr.Trace(url), "Failed to remove ‘"+url+"’ recursively.") - switch pErr.ToGoError().(type) { + if content.Err != nil { + errorIf(content.Err.Trace(url), "Failed to remove ‘"+url+"’ recursively.") + switch content.Err.ToGoError().(type) { case PathInsufficientPermission: // Ignore Permission error. continue } - close(contentCh) return } @@ -219,7 +221,11 @@ func removeRecursive(url string, isIncomplete bool, isFake bool, older int) { } urlString := content.URL.Path - printMsg(rmMessage{Key: targetAlias + urlString}) + printMsg(rmMessage{ + Key: targetAlias + urlString, + Size: content.Size, + }) + if !isFake { sent := false for sent == false { diff --git a/cmd/session-v8.go b/cmd/session-v8.go index 1a38f158..d0c1a79e 100644 --- a/cmd/session-v8.go +++ b/cmd/session-v8.go @@ -23,6 +23,7 @@ import ( "fmt" "io" "os" + "runtime/debug" "strings" "sync" "time" @@ -357,6 +358,7 @@ func (s *sessionV8) Delete() *probe.Error { // Close a session and exit. func (s sessionV8) CloseAndDie() { s.Close() + fmt.Println(string(debug.Stack())) console.Fatalln("Session safely terminated. To resume session ‘mc session resume " + s.SessionID + "’") } diff --git a/cmd/utils.go b/cmd/utils.go index a71770d7..7103d98d 100644 --- a/cmd/utils.go +++ b/cmd/utils.go @@ -28,18 +28,21 @@ import ( "github.com/minio/minio/pkg/probe" ) -func isErrIgnored(err *probe.Error) bool { +func isErrIgnored(err *probe.Error) (ignored bool) { // For all non critical errors we can continue for the remaining files. switch err.ToGoError().(type) { + // Handle these specifically for filesystem related errors. case BrokenSymlink, TooManyLevelsSymlink, PathNotFound, PathInsufficientPermission: - return true + ignored = true // Handle these specifically for object storage related errors. case BucketNameEmpty, ObjectMissing, ObjectAlreadyExists: - return true + ignored = true case ObjectAlreadyExistsAsDirectory, BucketDoesNotExist, BucketInvalid, ObjectOnGlacier: - return true + ignored = true + default: + ignored = false } - return false + return ignored } var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") diff --git a/cmd/watch-main.go b/cmd/watch-main.go index ea0ccfd7..a7b05a55 100644 --- a/cmd/watch-main.go +++ b/cmd/watch-main.go @@ -172,8 +172,6 @@ func mainWatch(ctx *cli.Context) { for { select { case <-trapCh: - s3Client.Unwatch(params) - return case event, ok := <-wo.Events(): if !ok { return diff --git a/cmd/watch.go b/cmd/watch.go index fd581fa6..363ec0a3 100644 --- a/cmd/watch.go +++ b/cmd/watch.go @@ -134,18 +134,6 @@ func (w *Watcher) Wait() { w.wg.Wait() } -// Unjoin the watcher from client. -func (w *Watcher) Unjoin(client Client, recursive bool) *probe.Error { - err := client.Unwatch(watchParams{ - recursive: recursive, - accountID: fmt.Sprintf("%d", w.sessionStartTime.Unix()), - }) - if err != nil { - return err - } - return nil -} - // Join the watcher with client func (w *Watcher) Join(client Client, recursive bool) *probe.Error { wo, err := client.Watch(watchParams{ diff --git a/vendor/github.com/minio/minio-go/api-notification.go b/vendor/github.com/minio/minio-go/api-notification.go index 85e57805..15ac779e 100644 --- a/vendor/github.com/minio/minio-go/api-notification.go +++ b/vendor/github.com/minio/minio-go/api-notification.go @@ -22,6 +22,7 @@ import ( "io" "net/http" "net/url" + "time" ) // GetBucketNotification - get bucket notification at a given path. @@ -143,7 +144,14 @@ func (c Client) ListenBucketNotification(bucketName, prefix, suffix string, even } // Continously run and listen on bucket notification. - for { + // Create a done channel to control 'ListObjects' go routine. + retryDoneCh := make(chan struct{}, 1) + + // Indicate to our routine to exit cleanly upon return. + defer close(retryDoneCh) + + // Wait on the jitter retry loop. + for range c.newRetryTimerContinous(time.Second, time.Second*30, MaxJitter, retryDoneCh) { urlValues := make(url.Values) urlValues.Set("prefix", prefix) urlValues.Set("suffix", suffix) @@ -155,10 +163,7 @@ func (c Client) ListenBucketNotification(bucketName, prefix, suffix string, even queryValues: urlValues, }) if err != nil { - notificationInfoCh <- NotificationInfo{ - Err: err, - } - return + continue } // Validate http response, upon error return quickly. @@ -180,10 +185,7 @@ func (c Client) ListenBucketNotification(bucketName, prefix, suffix string, even for bio.Scan() { var notificationInfo NotificationInfo if err = json.Unmarshal(bio.Bytes(), ¬ificationInfo); err != nil { - notificationInfoCh <- NotificationInfo{ - Err: err, - } - return + continue } // Send notifications on channel only if there are events received. if len(notificationInfo.Records) > 0 { @@ -200,12 +202,7 @@ func (c Client) ListenBucketNotification(bucketName, prefix, suffix string, even // and re-connect. if err == io.ErrUnexpectedEOF { resp.Body.Close() - continue } - notificationInfoCh <- NotificationInfo{ - Err: err, - } - return } } }(notificationInfoCh) 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 f7dd2daf..41d6326c 100644 --- a/vendor/github.com/minio/minio-go/api-put-object.go +++ b/vendor/github.com/minio/minio-go/api-put-object.go @@ -103,11 +103,10 @@ func getReaderSize(reader io.Reader) (size int64, err error) { // implement Seekable calls. Ignore them and treat // them like a stream with unknown length. switch st.Name() { - case "stdin": - fallthrough - case "stdout": - fallthrough - case "stderr": + case "stdin", "stdout", "stderr": + return + // Ignore read/write stream of os.Pipe() which have unknown length too. + case "|0", "|1": return } size = st.Size() diff --git a/vendor/github.com/minio/minio-go/api.go b/vendor/github.com/minio/minio-go/api.go index 95492708..71c77490 100644 --- a/vendor/github.com/minio/minio-go/api.go +++ b/vendor/github.com/minio/minio-go/api.go @@ -151,6 +151,18 @@ func (r *lockedRandSource) Seed(seed int64) { r.lk.Unlock() } +// redirectHeaders copies all headers when following a redirect URL. +// This won't be needed anymore from go 1.8 (https://github.com/golang/go/issues/4800) +func redirectHeaders(req *http.Request, via []*http.Request) error { + if len(via) == 0 { + return nil + } + for key, val := range via[0].Header { + req.Header[key] = val + } + return nil +} + func privateNew(endpoint, accessKeyID, secretAccessKey string, secure bool) (*Client, error) { // construct endpoint. endpointURL, err := getEndpointURL(endpoint, secure) @@ -174,7 +186,8 @@ func privateNew(endpoint, accessKeyID, secretAccessKey string, secure bool) (*Cl // Instantiate http client and bucket location cache. clnt.httpClient = &http.Client{ - Transport: http.DefaultTransport, + Transport: http.DefaultTransport, + CheckRedirect: redirectHeaders, } // Instantiae bucket location cache. @@ -364,20 +377,35 @@ func (c Client) dumpHTTP(req *http.Request, resp *http.Response) error { // do - execute http request. func (c Client) do(req *http.Request) (*http.Response, error) { - // do the request. - resp, err := c.httpClient.Do(req) - if err != nil { - // Handle this specifically for now until future Golang - // versions fix this issue properly. - urlErr, ok := err.(*url.Error) - if ok && strings.Contains(urlErr.Err.Error(), "EOF") { - return nil, &url.Error{ - Op: urlErr.Op, - URL: urlErr.URL, - Err: fmt.Errorf("Connection closed by foreign host %s. Retry again.", urlErr.URL), + var resp *http.Response + var err error + // Do the request in a loop in case of 307 http is met since golang still doesn't + // handle properly this situation (https://github.com/golang/go/issues/7912) + for { + resp, err = c.httpClient.Do(req) + if err != nil { + // Handle this specifically for now until future Golang + // versions fix this issue properly. + urlErr, ok := err.(*url.Error) + if ok && strings.Contains(urlErr.Err.Error(), "EOF") { + return nil, &url.Error{ + Op: urlErr.Op, + URL: urlErr.URL, + Err: fmt.Errorf("Connection closed by foreign host %s. Retry again.", urlErr.URL), + } } + return nil, err + } + // Redo the request with the new redirect url if http 307 is returned, quit the loop otherwise + if resp != nil && resp.StatusCode == http.StatusTemporaryRedirect { + newURL, err := url.Parse(resp.Header.Get("Location")) + if err != nil { + break + } + req.URL = newURL + } else { + break } - return nil, err } // Response cannot be non-nil, report if its the case. diff --git a/vendor/github.com/minio/minio-go/post-policy.go b/vendor/github.com/minio/minio-go/post-policy.go index 2a675d77..5e716124 100644 --- a/vendor/github.com/minio/minio-go/post-policy.go +++ b/vendor/github.com/minio/minio-go/post-policy.go @@ -149,6 +149,24 @@ func (p *PostPolicy) SetContentLengthRange(min, max int64) error { return nil } +// SetSuccessStatusAction - Sets the status success code of the object for this policy +// based upload. +func (p *PostPolicy) SetSuccessStatusAction(status string) error { + if strings.TrimSpace(status) == "" || status == "" { + return ErrInvalidArgument("Status is empty") + } + policyCond := policyCondition{ + matchType: "eq", + condition: "$success_action_status", + value: status, + } + if err := p.addNewPolicy(policyCond); err != nil { + return err + } + p.formData["success_action_status"] = status + return nil +} + // addNewPolicy - internal helper to validate adding new policies. func (p *PostPolicy) addNewPolicy(policyCond policyCondition) error { if policyCond.matchType == "" || policyCond.condition == "" || policyCond.value == "" { diff --git a/vendor/github.com/minio/minio-go/retry-continous.go b/vendor/github.com/minio/minio-go/retry-continous.go new file mode 100644 index 00000000..e300af69 --- /dev/null +++ b/vendor/github.com/minio/minio-go/retry-continous.go @@ -0,0 +1,52 @@ +package minio + +import "time" + +// newRetryTimerContinous creates a timer with exponentially increasing delays forever. +func (c Client) newRetryTimerContinous(unit time.Duration, cap time.Duration, jitter float64, doneCh chan struct{}) <-chan int { + attemptCh := make(chan int) + + // normalize jitter to the range [0, 1.0] + if jitter < NoJitter { + jitter = NoJitter + } + if jitter > MaxJitter { + jitter = MaxJitter + } + + // computes the exponential backoff duration according to + // https://www.awsarchitectureblog.com/2015/03/backoff.html + exponentialBackoffWait := func(attempt int) time.Duration { + // 1< maxAttempt { + attempt = maxAttempt + } + //sleep = random_between(0, min(cap, base * 2 ** attempt)) + sleep := unit * time.Duration(1< cap { + sleep = cap + } + if jitter != NoJitter { + sleep -= time.Duration(c.random.Float64() * float64(sleep) * jitter) + } + return sleep + } + + go func() { + defer close(attemptCh) + var nextBackoff int + for { + select { + // Attempts starts. + case attemptCh <- nextBackoff: + nextBackoff++ + case <-doneCh: + // Stop the routine. + return + } + time.Sleep(exponentialBackoffWait(nextBackoff)) + } + }() + return attemptCh +} diff --git a/vendor/vendor.json b/vendor/vendor.json index 061bbda6..0f0a008d 100644 --- a/vendor/vendor.json +++ b/vendor/vendor.json @@ -49,10 +49,10 @@ "revisionTime": "2015-10-24T22:24:27-07:00" }, { - "checksumSHA1": "jIqpnAmNq8z/T8PTQeVV5T51KNw=", + "checksumSHA1": "LOqBhL9Sc2QMob0uT1cwvexNzLQ=", "path": "github.com/minio/minio-go", - "revision": "88cd2fcfc8f7dad4c586918348e986cf6095bfad", - "revisionTime": "2016-10-31T15:51:08Z" + "revision": "0cd90f4c44c5e86f4cf8faf865ae5388df2843fb", + "revisionTime": "2016-11-20T22:51:24Z" }, { "checksumSHA1": "qTxOBp3GVxCC70ykb7Hxg6UgWwA=",