From a769ce64395aadb636ed9b6df269960b2abf134e Mon Sep 17 00:00:00 2001 From: Harshavardhana Date: Fri, 11 Dec 2015 16:59:51 -0800 Subject: [PATCH] mc: Vendorize to new API changes. This vendorization uses the new set of API changes which we are brought in. With this new change Bucket regions are handled transparently without any region lookup or local map. This makes overall code seamless and easy to use. Fixes - #1541 (cp corruption while uploading large files to s3) Fixes - #1542 (cp checkCopySyntax failed) Fixes - #1537 (regions will be handled seamelessly now for all buckets) Fixes - #1538 (fixes access control policy for google cloud storage) Fixes - #1547 (session resume completes without copying all the files) Fixes - #1559 (poor network connectivity, causes timing out) --- .travis.yml | 16 +- CONTRIBUTING.md | 2 +- INSTALLGO.md | 4 +- MAINTAINERS.md | 5 - Makefile | 3 +- README.md | 2 +- accounting-reader.go | 41 +- appveyor.yml | 2 +- buildscripts/checkdeps.sh | 21 - cat-main.go | 4 +- common-methods.go | 45 +- config-fix.go | 2 +- cp-main.go | 179 +- cp-url.go | 8 +- mb-main.go | 44 +- mirror-main.go | 167 +- pipe-main.go | 2 +- pkg/client/client.go | 6 +- pkg/client/errors.go | 62 +- pkg/client/fs/fs-utils.go | 2 +- pkg/client/fs/fs.go | 160 +- pkg/client/fs/fs_test.go | 105 +- pkg/client/s3/s3.go | 456 +++--- pkg/client/s3/s3_test.go | 67 +- pkg/client/s3/trace_v2.go | 11 +- pkg/client/s3/trace_v4.go | 11 +- pkg/hookreader/hookreader.go | 54 + pkg/hookreader/hookreader_test.go | 55 + progress-bar.go | 216 +-- rm-main.go | 10 +- share-download-main.go | 8 +- share-upload-main.go | 3 + share.go | 1 - .../github.com/minio/minio-go/MAINTAINERS.md | 19 + vendor/github.com/minio/minio-go/README.md | 42 +- .../minio/minio-go/api-definitions.go | 74 +- .../minio/minio-go/api-error-response.go | 236 +++ .../minio/minio-go/api-get-object-file.go | 104 ++ vendor/github.com/minio/minio-go/api-get.go | 537 ++++++ vendor/github.com/minio/minio-go/api-list.go | 539 ++++++ .../minio/minio-go/api-presigned.go | 144 ++ .../minio/minio-go/api-put-bucket.go | 214 +++ .../minio/minio-go/api-put-object-common.go | 240 +++ .../minio/minio-go/api-put-object-file.go | 240 +++ .../minio-go/api-put-object-multipart.go | 379 +++++ .../minio/minio-go/api-put-object-progress.go | 105 ++ .../minio/minio-go/api-put-object-readat.go | 208 +++ .../minio/minio-go/api-put-object.go | 287 ++++ .../github.com/minio/minio-go/api-remove.go | 167 ++ ...i-definitions.go => api-s3-definitions.go} | 73 +- vendor/github.com/minio/minio-go/api-stat.go | 125 ++ vendor/github.com/minio/minio-go/api.go | 1445 +++++------------ .../minio/minio-go/api_functional_v2_test.go | 945 +++++++++++ .../minio/minio-go/api_functional_v4_test.go | 1026 ++++++++++++ .../minio/minio-go/api_handlers_test.go | 170 -- .../minio/minio-go/api_private_test.go | 128 -- .../minio/minio-go/api_public_test.go | 274 ---- .../minio/minio-go/api_unit_test.go | 583 +++++++ vendor/github.com/minio/minio-go/appveyor.yml | 9 +- .../github.com/minio/minio-go/bucket-acl.go | 14 +- .../github.com/minio/minio-go/bucket-cache.go | 154 ++ .../minio/minio-go/common-methods.go | 52 - vendor/github.com/minio/minio-go/constants.go | 42 + .../minio/minio-go/error-response.go | 170 -- .../github.com/minio/minio-go/hook-reader.go | 54 + vendor/github.com/minio/minio-go/interface.go | 49 - vendor/github.com/minio/minio-go/io.go | 146 -- .../minio/minio-go/parts-manager.go | 130 -- .../github.com/minio/minio-go/post-policy.go | 77 +- .../minio/minio-go/request-signature-v2.go | 174 +- .../minio/minio-go/request-signature-v4.go | 210 ++- vendor/github.com/minio/minio-go/request.go | 281 ---- .../minio/minio-go/s3-api-errors.go | 51 - vendor/github.com/minio/minio-go/s3-api.go | 905 ----------- .../github.com/minio/minio-go/s3-endpoints.go | 40 + .../minio/minio-go/s3-multipart-api.go | 332 ---- .../minio/minio-go/signature-type.go | 37 + vendor/github.com/minio/minio-go/tempfile.go | 60 + vendor/github.com/minio/minio-go/utils.go | 305 ++++ vendor/github.com/minio/pb/LICENSE | 2 +- vendor/github.com/minio/pb/README.md | 107 +- .../github.com/minio/pb/example_copy_test.go | 82 + .../minio/pb/example_multiple_test.go | 37 + vendor/github.com/minio/pb/example_test.go | 30 + vendor/github.com/minio/pb/pb.go | 36 +- vendor/github.com/minio/pb/pb_nix.go | 2 +- vendor/github.com/minio/pb/pb_test.go | 21 + vendor/github.com/minio/pb/pb_win.go | 5 +- vendor/github.com/minio/pb/pb_x.go | 72 +- vendor/github.com/minio/pb/pool.go | 93 ++ vendor/github.com/minio/pb/runecount.go | 17 + vendor/github.com/minio/pb/runecount_test.go | 16 + vendor/github.com/minio/pb/termios_bsd.go | 8 + vendor/github.com/minio/pb/termios_linux.go | 6 + vendor/vendor.json | 8 +- 95 files changed, 9096 insertions(+), 4816 deletions(-) create mode 100644 pkg/hookreader/hookreader.go create mode 100644 pkg/hookreader/hookreader_test.go create mode 100644 vendor/github.com/minio/minio-go/MAINTAINERS.md create mode 100644 vendor/github.com/minio/minio-go/api-error-response.go create mode 100644 vendor/github.com/minio/minio-go/api-get-object-file.go create mode 100644 vendor/github.com/minio/minio-go/api-get.go create mode 100644 vendor/github.com/minio/minio-go/api-list.go create mode 100644 vendor/github.com/minio/minio-go/api-presigned.go create mode 100644 vendor/github.com/minio/minio-go/api-put-bucket.go create mode 100644 vendor/github.com/minio/minio-go/api-put-object-common.go create mode 100644 vendor/github.com/minio/minio-go/api-put-object-file.go create mode 100644 vendor/github.com/minio/minio-go/api-put-object-multipart.go create mode 100644 vendor/github.com/minio/minio-go/api-put-object-progress.go create mode 100644 vendor/github.com/minio/minio-go/api-put-object-readat.go create mode 100644 vendor/github.com/minio/minio-go/api-put-object.go create mode 100644 vendor/github.com/minio/minio-go/api-remove.go rename vendor/github.com/minio/minio-go/{s3-api-definitions.go => api-s3-definitions.go} (72%) create mode 100644 vendor/github.com/minio/minio-go/api-stat.go create mode 100644 vendor/github.com/minio/minio-go/api_functional_v2_test.go create mode 100644 vendor/github.com/minio/minio-go/api_functional_v4_test.go delete mode 100644 vendor/github.com/minio/minio-go/api_handlers_test.go delete mode 100644 vendor/github.com/minio/minio-go/api_private_test.go delete mode 100644 vendor/github.com/minio/minio-go/api_public_test.go create mode 100644 vendor/github.com/minio/minio-go/api_unit_test.go create mode 100644 vendor/github.com/minio/minio-go/bucket-cache.go delete mode 100644 vendor/github.com/minio/minio-go/common-methods.go create mode 100644 vendor/github.com/minio/minio-go/constants.go delete mode 100644 vendor/github.com/minio/minio-go/error-response.go create mode 100644 vendor/github.com/minio/minio-go/hook-reader.go delete mode 100644 vendor/github.com/minio/minio-go/interface.go delete mode 100644 vendor/github.com/minio/minio-go/io.go delete mode 100644 vendor/github.com/minio/minio-go/parts-manager.go delete mode 100644 vendor/github.com/minio/minio-go/request.go delete mode 100644 vendor/github.com/minio/minio-go/s3-api-errors.go delete mode 100644 vendor/github.com/minio/minio-go/s3-api.go create mode 100644 vendor/github.com/minio/minio-go/s3-endpoints.go delete mode 100644 vendor/github.com/minio/minio-go/s3-multipart-api.go create mode 100644 vendor/github.com/minio/minio-go/signature-type.go create mode 100644 vendor/github.com/minio/minio-go/tempfile.go create mode 100644 vendor/github.com/minio/minio-go/utils.go create mode 100644 vendor/github.com/minio/pb/example_copy_test.go create mode 100644 vendor/github.com/minio/pb/example_multiple_test.go create mode 100644 vendor/github.com/minio/pb/example_test.go create mode 100644 vendor/github.com/minio/pb/pool.go create mode 100644 vendor/github.com/minio/pb/runecount.go create mode 100644 vendor/github.com/minio/pb/runecount_test.go create mode 100644 vendor/github.com/minio/pb/termios_bsd.go create mode 100644 vendor/github.com/minio/pb/termios_linux.go diff --git a/.travis.yml b/.travis.yml index c70bd123..9ea22375 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,9 +1,21 @@ +sudo: false language: go + script: - make test GOFLAGS="-race" + +os: +- linux +- osx + +env: +- ARCH=x86_64 +- ARCH=i686 + go: -- 1.5.1 -sudo: false +- 1.5.2 +- 1.5.3 + notifications: slack: secure: McinxQ4R/Yu2r/U8lVsdAIQ195Rf+3/Ku6DViWyqLHsTt5fTnVrSfbIKs8vy0t2A0bRLO6zv2xOSMWjfiimZLPMgMbMqLtTFEzUzB8RZyx2n2xgmL8q3gjXcLA3vkBreaRYCzJzX6DjvrxRfhyOg+BQHpLpACWik3FS/7VIdDCI= diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 7edb9535..f159067d 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -20,7 +20,7 @@ $ mc --help - Push to the branch (git push origin my-new-feature) - Create new Pull Request -* If you have additional dependencies for ``mc``, ``mc`` manages its depedencies using [govendor](https://github.com/kardianos/govendor) +* If you have additional dependencies for ``mc``, ``mc`` manages its dependencies using [govendor](https://github.com/kardianos/govendor) - Run `go get foo/bar` - Edit your code to import foo/bar - Run `make pkg-add PKG=foo/bar` from top-level folder diff --git a/INSTALLGO.md b/INSTALLGO.md index 79f49768..0aa9d206 100644 --- a/INSTALLGO.md +++ b/INSTALLGO.md @@ -28,7 +28,7 @@ export GOPATH=${HOME}/go export PATH=$PATH:${HOME}/bin/go/bin:${GOPATH}/bin ``` -##### Source the new enviornment +##### Source the new environment ```sh $ source ~/.bashrc @@ -74,7 +74,7 @@ export GOROOT=$(brew --prefix)/Cellar/go/${GOVERSION}/libexec export PATH=$PATH:${GOPATH}/bin ``` -##### Source the new enviornment +##### Source the new environment ```sh $ source ~/.bash_profile diff --git a/MAINTAINERS.md b/MAINTAINERS.md index 9de80ce9..33a4c6e4 100644 --- a/MAINTAINERS.md +++ b/MAINTAINERS.md @@ -4,11 +4,6 @@ Please go through this link [Maintainer Responsibility](https://gist.github.com/abperiasamy/f4d9b31d3186bbd26522) -## Current Maintainers - -- Harshavardhana -- Krishna Srinivas - ### Setup your mc Github Repository Fork [mc upstream](https://github.com/minio/mc/fork) source repository to your own personal repository. diff --git a/Makefile b/Makefile index d296366a..5b2c5e04 100644 --- a/Makefile +++ b/Makefile @@ -39,7 +39,8 @@ lint: cyclo: @echo "Running $@:" - @GO15VENDOREXPERIMENT=1 gocyclo -over 40 . + @GO15VENDOREXPERIMENT=1 gocyclo -over 40 *.go + @GO15VENDOREXPERIMENT=1 gocyclo -over 40 pkg deadcode: @echo "Running $@:" diff --git a/README.md b/README.md index e4e273c1..d4a51b66 100644 --- a/README.md +++ b/README.md @@ -59,7 +59,7 @@ C:\Users\Username\Downloads> mc.exe --help #### Source
-NOTE: Source installation is intended for only developers and advanced users. ‘mc update’ continous delivery mechanism is not supported for ‘go get’ based binary builds. Please download official releases from https://minio.io/#mc. +NOTE: Source installation is intended for only developers and advanced users. ‘mc update’ continuous delivery mechanism is not supported for ‘go get’ based binary builds. Please download official releases from https://minio.io/#mc.
If you do not have a working Golang environment, please follow [Install Golang](./INSTALLGO.md). diff --git a/accounting-reader.go b/accounting-reader.go index 3cd7ceae..d247ab63 100644 --- a/accounting-reader.go +++ b/accounting-reader.go @@ -17,18 +17,11 @@ package main import ( - "io" "sync" "sync/atomic" "time" ) -// accountingReader - implements and inherits io.ReadCloser interface for accounter. -type accountingReader struct { - io.ReadSeeker - acct *accounter -} - // accounter keeps tabs of ongoing data transfer information. type accounter struct { current int64 @@ -108,32 +101,20 @@ func (a *accounter) Update() { } } -// Add add to current values atomically. +// Set sets the current value atomically. +func (a *accounter) Set(n int64) *accounter { + atomic.StoreInt64(&a.current, n) + return a +} + +// Add add to current value atomically. func (a *accounter) Add(n int64) int64 { return atomic.AddInt64(&a.current, n) } -// Instantiate a new proxy reader for accounter. -func (a *accounter) NewProxyReader(r io.ReadSeeker) *accountingReader { - return &accountingReader{r, a} -} - -// Read implement Reader which internally updates current value. -func (a *accountingReader) Read(p []byte) (n int, err error) { - n, err = a.ReadSeeker.Read(p) - if err != nil { - return - } - a.acct.Add(int64(n)) - return -} - -// Seek implement Seeker. -func (a *accountingReader) Seek(offset int64, whence int) (n int64, err error) { - n, err = a.ReadSeeker.Seek(offset, whence) - if err != nil { - return - } - a.acct.Add(n) +// Read implements Reader which internally updates current value. +func (a *accounter) Read(p []byte) (n int, err error) { + n = len(p) + a.Add(int64(n)) return } diff --git a/appveyor.yml b/appveyor.yml index d08a1210..2595bbfb 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -28,7 +28,7 @@ build_script: - gofmt -s -l pkg - golint . - golint github.com/minio/mc/pkg... - - gocyclo -over 40 . + - gocyclo -over 40 pkg - deadcode - go test -race . - go test -race github.com/minio/mc/pkg... diff --git a/buildscripts/checkdeps.sh b/buildscripts/checkdeps.sh index 007741b2..245b061d 100755 --- a/buildscripts/checkdeps.sh +++ b/buildscripts/checkdeps.sh @@ -20,9 +20,6 @@ _init() { shopt -s extglob ## Minimum required versions for build dependencies - GCC_VERSION="4.0" - CLANG_VERSION="7.0.0" - YASM_VERSION="1.2.0" GIT_VERSION="1.0" GO_VERSION="1.5.1" OSX_VERSION="10.8" @@ -183,24 +180,6 @@ check_deps() { if [ $? -ge 2 ]; then MISSING="${MISSING} git(>=${GIT_VERSION})" fi - - case ${UNAME%% *} in - "Linux") - check_version "$(env gcc --version 2>/dev/null | sed 's/^.* \([0-9.]*\).*$/\1/' | head -1)" "${GCC_VERSION}" - if [ $? -ge 2 ]; then - MISSING="${MISSING} build-essential(>=${GCC_VERSION})" - fi - ;; - "Darwin") - check_version "$(env gcc --version 2>/dev/null | awk '{print $4}' | head -1)" "${CLANG_VERSION}" - if [ $? -ge 2 ]; then - MISSING="${MISSING} xcode-cli(>=${CLANG_VERSION})" - fi - ;; - "*") - ;; - esac - } main() { diff --git a/cat-main.go b/cat-main.go index 017cc071..137de275 100644 --- a/cat-main.go +++ b/cat-main.go @@ -80,7 +80,7 @@ func checkCatSyntax(ctx *cli.Context) { // catURL displays contents of a URL to stdout. func catURL(sourceURL string) *probe.Error { - var reader io.ReadSeeker + var reader io.Reader switch sourceURL { case "-": reader = os.Stdin @@ -88,7 +88,7 @@ func catURL(sourceURL string) *probe.Error { // Ignore size, since os.Stat() would not return proper size all the // time for local filesystem for example /proc files. var err *probe.Error - if reader, err = getSource(sourceURL); err != nil { + if reader, err = getSourceStream(sourceURL); err != nil { return err.Trace(sourceURL) } } diff --git a/common-methods.go b/common-methods.go index 2aeb5af1..dc2aba10 100644 --- a/common-methods.go +++ b/common-methods.go @@ -33,6 +33,10 @@ func isTargetURLDir(targetURL string) bool { targetURLParse := client.NewURL(targetURL) _, targetContent, err := url2Stat(targetURL) if err != nil { + _, aliasedTargetURL, _ := mustExpandAlias(targetURL) + if aliasedTargetURL == targetURL { + return false + } if targetURLParse.Path == string(targetURLParse.Separator) && targetURLParse.Scheme != "" { return false } @@ -48,44 +52,49 @@ func isTargetURLDir(targetURL string) bool { } // getSource gets a reader from URL. -func getSource(urlStr string) (reader io.ReadSeeker, err *probe.Error) { +func getSourceStream(urlStr string) (reader io.Reader, err *probe.Error) { alias, urlStrFull, _, err := expandAlias(urlStr) if err != nil { return nil, err.Trace(urlStr) } - return getSourceFromAlias(alias, urlStrFull) + return getSourceStreamFromAlias(alias, urlStrFull) } -// getSourceFromAlias gets a reader from URL. -func getSourceFromAlias(alias string, urlStr string) (reader io.ReadSeeker, err *probe.Error) { +// getSourceStreamFromAlias gets a reader from URL. +func getSourceStreamFromAlias(alias string, urlStr string) (reader io.Reader, err *probe.Error) { sourceClnt, err := newClientFromAlias(alias, urlStr) if err != nil { return nil, err.Trace(alias, urlStr) } - return sourceClnt.Get(0, 0) -} - -// putTarget writes to URL from reader. If length=-1, read until EOF. -func putTarget(urlStr string, reader io.ReadSeeker, size int64) *probe.Error { - alias, urlStrFull, _, err := expandAlias(urlStr) + reader, err = sourceClnt.Get() if err != nil { - return err + return nil, err.Trace(alias, urlStr) } - return putTargetFromAlias(alias, urlStrFull, reader, size) + return reader, nil } -// putTargetFromAlias writes to URL from reader. If length=-1, read until EOF. -func putTargetFromAlias(alias string, urlStr string, reader io.ReadSeeker, size int64) *probe.Error { +// putTargetStreamFromAlias writes to URL from Reader. +func putTargetStreamFromAlias(alias string, urlStr string, reader io.Reader, size int64, progress io.Reader) (int64, *probe.Error) { targetClnt, err := newClientFromAlias(alias, urlStr) if err != nil { - return err.Trace(alias, urlStr) + return 0, err.Trace(alias, urlStr) } contentType := guessURLContentType(urlStr) - err = targetClnt.Put(reader, size, contentType) + var n int64 + n, err = targetClnt.Put(reader, size, contentType, progress) if err != nil { - return err.Trace(alias, urlStr) + return n, err.Trace(alias, urlStr) } - return nil + return n, nil +} + +// putTargetStream writes to URL from reader. If length=-1, read until EOF. +func putTargetStream(urlStr string, reader io.Reader, size int64) (int64, *probe.Error) { + alias, urlStrFull, _, err := expandAlias(urlStr) + if err != nil { + return 0, err.Trace(alias, urlStr) + } + return putTargetStreamFromAlias(alias, urlStrFull, reader, size, nil) } // newClientFromAlias gives a new client interface for matching diff --git a/config-fix.go b/config-fix.go index 39998e15..3068d023 100644 --- a/config-fix.go +++ b/config-fix.go @@ -63,7 +63,7 @@ func newBrokenConfigV3() *brokenConfigV3 { // Fix config version ‘3’. Some v3 config files are written without // proper hostConfig JSON tags. They may also contain unused ACL and // Access fields. Rewrite the hostConfig with proper fields using JSON -// tags and drop the unsed (ACL, Access) fields. +// tags and drop the unused (ACL, Access) fields. func fixConfigV3() { if !isMcConfigExists() { return diff --git a/cp-main.go b/cp-main.go index f916d6fd..f2b3edb1 100644 --- a/cp-main.go +++ b/cp-main.go @@ -21,10 +21,8 @@ import ( "encoding/json" "fmt" "io" - "math" "os" "path/filepath" - "runtime" "strings" "sync" "syscall" @@ -129,20 +127,14 @@ func (c copyStatMessage) String() string { } // doCopy - Copy a singe file from source to destination -func doCopy(cpURLs copyURLs, progressReader *barSend, accountingReader *accounter, cpQueue <-chan bool, wg *sync.WaitGroup, statusCh chan<- copyURLs) { - defer wg.Done() // Notify that this copy routine is done. - defer func() { - <-cpQueue - }() - +func doCopy(cpURLs copyURLs, progressReader *progressBar, accountingReader *accounter) copyURLs { if cpURLs.Error != nil { - cpURLs.Error.Trace() - statusCh <- cpURLs - return + cpURLs.Error = cpURLs.Error.Trace() + return cpURLs } if !globalQuiet && !globalJSON { - progressReader.SetCaption(cpURLs.SourceContent.URL.String() + ": ") + progressReader = progressReader.SetCaption(cpURLs.SourceContent.URL.String() + ": ") } sourceAlias := cpURLs.SourceAlias @@ -151,17 +143,13 @@ func doCopy(cpURLs copyURLs, progressReader *barSend, accountingReader *accounte targetURL := cpURLs.TargetContent.URL length := cpURLs.SourceContent.Size - reader, err := getSourceFromAlias(sourceAlias, sourceURL.String()) + reader, err := getSourceStreamFromAlias(sourceAlias, sourceURL.String()) if err != nil { - if !globalQuiet && !globalJSON { - progressReader.ErrorGet(length) - } cpURLs.Error = err.Trace(sourceURL.String()) - statusCh <- cpURLs - return + return cpURLs } - var newReader io.ReadSeeker + var progress io.Reader if globalQuiet || globalJSON { sourcePath := filepath.Join(sourceAlias, sourceURL.Path) targetPath := filepath.Join(targetAlias, targetURL.Path) @@ -169,37 +157,29 @@ func doCopy(cpURLs copyURLs, progressReader *barSend, accountingReader *accounte Source: sourcePath, Target: targetPath, }) - // No accounting necessary for JSON output. - if globalJSON { - newReader = reader - } // Proxy reader to accounting reader only during quiet mode. - if globalQuiet { - newReader = accountingReader.NewProxyReader(reader) + if globalQuiet || globalJSON { + progress = accountingReader } } else { - // set up progress - newReader = progressReader.NewProxyReader(reader) + // Set up progress reader. + progress = progressReader.ProgressBar } - err = putTargetFromAlias(targetAlias, targetURL.String(), newReader, length) + _, err = putTargetStreamFromAlias(targetAlias, targetURL.String(), reader, length, progress) if err != nil { - if !globalQuiet && !globalJSON { - progressReader.ErrorPut(length) - } cpURLs.Error = err.Trace(targetURL.String()) - statusCh <- cpURLs - return + return cpURLs } - cpURLs.Error = nil // just for safety - statusCh <- cpURLs + return cpURLs } // doCopyFake - Perform a fake copy to update the progress bar appropriately. -func doCopyFake(cURLs copyURLs, progressReader *barSend) { +func doCopyFake(cpURLs copyURLs, progressReader *progressBar) copyURLs { if !globalQuiet && !globalJSON { - progressReader.Progress(cURLs.SourceContent.Size) + progressReader.ProgressBar.Add64(cpURLs.SourceContent.Size) } + return cpURLs } // doPrepareCopyURLs scans the source URL and prepares a list of objects for copying. @@ -229,7 +209,7 @@ func doPrepareCopyURLs(session *sessionV6, trapCh <-chan bool) { for done == false { select { case cpURLs, ok := <-URLsCh: - if !ok { // Done with URL prepration + if !ok { // Done with URL preparation done = true break } @@ -282,61 +262,57 @@ func doCopySession(session *sessionV6) { // Enable accounting reader by default. accntReader := newAccounter(session.Header.TotalBytes) - // Enable progress bar reader only during default mode. - var progressReader *barSend - if !globalQuiet && !globalJSON { // set up progress bar - progressReader = newProgressBar(session.Header.TotalBytes) - } - // Prepare URL scanner from session data file. - scanner := bufio.NewScanner(session.NewDataReader()) + urlScanner := bufio.NewScanner(session.NewDataReader()) // isCopied returns true if an object has been already copied // or not. This is useful when we resume from a session. isCopied := isCopiedFactory(session.Header.LastCopied) - wg := new(sync.WaitGroup) - // Limit number of copy routines based on available CPU resources. - cpQueue := make(chan bool, int(math.Max(float64(runtime.NumCPU())-1, 1))) - defer close(cpQueue) + // Enable progress bar reader only during default mode. + var progressReader *progressBar + if !globalQuiet && !globalJSON { // set up progress bar + progressReader = newProgressBar(session.Header.TotalBytes) + } - // Status channel for receiveing copy return status. - statusCh := make(chan copyURLs) + // Wait on status of doCopy() operation. + var statusCh = make(chan copyURLs) - // Go routine to monitor doCopy status and signal traps. + // 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 cpURLs, ok := <-statusCh: // Receive status. - if !ok { // We are done here. Top level function has returned. - if !globalQuiet && !globalJSON { - progressReader.Finish() - } - if globalQuiet { - accntStat := accntReader.Stat() - cpStatMessage := copyStatMessage{ - Total: accntStat.Total, - Transferred: accntStat.Transferred, - Speed: accntStat.Speed, - } - console.Println(console.Colorize("Copy", cpStatMessage.String())) - } + 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 { 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 + // 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())) - // for all non critical errors we can continue for the remaining files + // For all non critical errors we can continue for the + // remaining files. switch cpURLs.Error.ToGoError().(type) { - // handle this specifically for filesystem related errors. + // Handle this specifically for filesystem related + // errors. case client.BrokenSymlink: continue case client.TooManyLevelsSymlink: @@ -345,45 +321,52 @@ func doCopySession(session *sessionV6) { continue case client.PathInsufficientPermission: continue + case client.ObjectAlreadyExists: + continue + case client.BucketDoesNotExist: + continue } - // for critical errors we should exit. Session can be resumed after the user figures out the problem + // For critical errors we should exit. Session + // can be resumed after the user figures out + // the problem. session.CloseAndDie() } - case <-trapCh: // Receive interrupt notification. - if !globalQuiet && !globalJSON { - console.Eraseline() - } - session.CloseAndDie() } } }() - // Go routine to perform concurrently copying. - wg.Add(1) - go func() { - defer wg.Done() - copyWg := new(sync.WaitGroup) - defer close(statusCh) + // Loop through all urls. + for urlScanner.Scan() { + var cpURLs copyURLs + // Unmarshal copyURLs from each line. + json.Unmarshal([]byte(urlScanner.Text()), &cpURLs) - for scanner.Scan() { - var cpURLs copyURLs - json.Unmarshal([]byte(scanner.Text()), &cpURLs) - if isCopied(cpURLs.SourceContent.URL.String()) { - doCopyFake(cpURLs, progressReader) - } else { - // Wait for other copy routines to - // complete. We only have limited CPU - // and network resources. - cpQueue <- true - // Account for each copy routines we start. - copyWg.Add(1) - // Do copying in background concurrently. - go doCopy(cpURLs, progressReader, accntReader, cpQueue, copyWg, statusCh) - } + // Verify if previously copied, notify progress bar. + if isCopied(cpURLs.SourceContent.URL.String()) { + statusCh <- doCopyFake(cpURLs, progressReader) + } else { + statusCh <- doCopy(cpURLs, progressReader, accntReader) } - copyWg.Wait() - }() + } + + // Close the goroutine. + close(statusCh) + + // Wait for the goroutines to finish. wg.Wait() + + if !globalQuiet && !globalJSON { + progressReader.ProgressBar.Finish() + } + if globalQuiet { + accntStat := accntReader.Stat() + cpStatMessage := copyStatMessage{ + Total: accntStat.Total, + Transferred: accntStat.Transferred, + Speed: accntStat.Speed, + } + console.Println(console.Colorize("Copy", cpStatMessage.String())) + } } // mainCopy is the entry point for cp command. diff --git a/cp-url.go b/cp-url.go index 63278c93..732760ea 100644 --- a/cp-url.go +++ b/cp-url.go @@ -97,10 +97,6 @@ func prepareCopyURLsTypeA(sourceURL string, targetURL string) copyURLs { // Find alias and expanded URL. targetAlias, targetURL, _ := mustExpandAlias(targetURL) - if sourceURL == targetURL { - // source and target can not be same - return copyURLs{Error: errSourceTargetSame(sourceURL).Trace(sourceURL)} - } _, sourceContent, err := url2Stat(sourceURL) if err != nil { // Source does not exist or insufficient privileges. @@ -110,6 +106,10 @@ func prepareCopyURLsTypeA(sourceURL string, targetURL string) copyURLs { // Source is not a regular file return copyURLs{Error: errInvalidSource(sourceURL).Trace(sourceURL)} } + if sourceContent.URL.String() == targetURL { + // source and target can not be same + return copyURLs{Error: errSourceTargetSame(sourceURL).Trace(sourceURL)} + } // All OK.. We can proceed. Type A return makeCopyContentTypeA(sourceAlias, sourceContent, targetAlias, targetURL) diff --git a/mb-main.go b/mb-main.go index 0e93fc2b..498bc52d 100644 --- a/mb-main.go +++ b/mb-main.go @@ -18,7 +18,6 @@ package main import ( "encoding/json" - "strings" "github.com/fatih/color" "github.com/minio/cli" @@ -32,6 +31,11 @@ var ( Name: "help, h", Usage: "Help of mb.", }, + cli.StringFlag{ + Name: "region", + Value: "us-east-1", + Usage: "Specify bucket region. Defaults to ‘us-east-1’.", + }, } ) @@ -57,7 +61,10 @@ EXAMPLES: 2. Create a new bucket on Google Cloud Storage. $ mc {{.Name}} gcs/miniocloud - 3. Create a new directory including its missing parents (equivalent to ‘mkdir -p’). + 4. Create a new bucket on Amazon S3 cloud storage in region ‘us-west-2’. + $ mc {{.Name}} --region=us-west-2 s3/myregionbucket + + 5. Create a new directory including its missing parents (equivalent to ‘mkdir -p’). $ mc {{.Name}} /tmp/this/new/dir1 `, } @@ -66,6 +73,7 @@ EXAMPLES: type makeBucketMessage struct { Status string `json:"status"` Bucket string `json:"bucket"` + Region string `json:"region"` } // String colorized make bucket message. @@ -86,10 +94,8 @@ func checkMakeBucketSyntax(ctx *cli.Context) { if !ctx.Args().Present() { cli.ShowCommandHelpAndExit(ctx, "mb", 1) // last argument is exit code } - for _, arg := range ctx.Args() { - if strings.TrimSpace(arg) == "" { - fatalIf(errInvalidArgument().Trace(), "Unable to validate empty argument.") - } + if len(ctx.Args()) != 1 { + fatalIf(errInvalidArgument().Trace(ctx.Args()...), "Incorrect number of arguments for mb command.") } } @@ -104,20 +110,18 @@ func mainMakeBucket(ctx *cli.Context) { // Additional command speific theme customization. console.SetColor("MakeBucket", color.New(color.FgGreen, color.Bold)) - for _, targetURL := range ctx.Args() { - // Instantiate client for URL. - clnt, err := newClient(targetURL) - fatalIf(err.Trace(targetURL), "Invalid target ‘"+targetURL+"’.") + // save region. + region := ctx.String("region") - // Make bucket. - err = clnt.MakeBucket() - // Upon error print error and continue. - if err != nil { - errorIf(err.Trace(targetURL), "Unable to make bucket ‘"+targetURL+"’.") - continue - } + targetURL := ctx.Args().First() + // Instantiate client for URL. + clnt, err := newClient(targetURL) + fatalIf(err.Trace(targetURL), "Invalid target ‘"+targetURL+"’.") - // Successfully created a bucket. - printMsg(makeBucketMessage{Status: "success", Bucket: targetURL}) - } + // Make bucket. + err = clnt.MakeBucket(region) + fatalIf(err.Trace(targetURL), "Unable to make bucket ‘"+targetURL+"’.") + + // Successfully created a bucket. + printMsg(makeBucketMessage{Status: "success", Bucket: targetURL}) } diff --git a/mirror-main.go b/mirror-main.go index c9ae1c2c..a3340778 100644 --- a/mirror-main.go +++ b/mirror-main.go @@ -21,10 +21,8 @@ import ( "encoding/json" "fmt" "io" - "math" "os" "path/filepath" - "runtime" "sync" "syscall" @@ -119,16 +117,10 @@ func (c mirrorStatMessage) String() string { } // doMirror - Mirror an object to multiple destination. mirrorURLs status contains a copy of sURLs and error if any. -func doMirror(sURLs mirrorURLs, progressReader *barSend, accountingReader *accounter, mirrorQueueCh <-chan bool, wg *sync.WaitGroup, statusCh chan<- mirrorURLs) { - defer wg.Done() // Notify that this copy routine is done. - defer func() { - <-mirrorQueueCh - }() - +func doMirror(sURLs mirrorURLs, progressReader *progressBar, accountingReader *accounter) mirrorURLs { if sURLs.Error != nil { // Errorneous sURLs passed. sURLs.Error = sURLs.Error.Trace() - statusCh <- sURLs - return + return sURLs } sourceAlias := sURLs.SourceAlias @@ -138,20 +130,16 @@ func doMirror(sURLs mirrorURLs, progressReader *barSend, accountingReader *accou length := sURLs.SourceContent.Size if !globalQuiet && !globalJSON { - progressReader.SetCaption(sourceURL.String() + ": ") + progressReader = progressReader.SetCaption(sourceURL.String() + ": ") } - reader, err := getSourceFromAlias(sourceAlias, sourceURL.String()) + reader, err := getSourceStreamFromAlias(sourceAlias, sourceURL.String()) if err != nil { - if !globalQuiet && !globalJSON { - progressReader.ErrorGet(length) - } sURLs.Error = err.Trace(sourceURL.String()) - statusCh <- sURLs - return + return sURLs } - var newReader io.ReadSeeker + var progress io.Reader if globalQuiet || globalJSON { sourcePath := filepath.Join(sourceAlias, sourceURL.Path) targetPath := filepath.Join(targetAlias, targetURL.Path) @@ -159,35 +147,29 @@ func doMirror(sURLs mirrorURLs, progressReader *barSend, accountingReader *accou Source: sourcePath, Target: targetPath, }) - if globalJSON { - newReader = reader - } - if globalQuiet { - newReader = accountingReader.NewProxyReader(reader) + if globalQuiet || globalJSON { + progress = accountingReader } } else { - // set up progress - newReader = progressReader.NewProxyReader(reader) + // Set up progress bar. + progress = progressReader.ProgressBar } - err = putTargetFromAlias(targetAlias, targetURL.String(), newReader, length) + _, err = putTargetStreamFromAlias(targetAlias, targetURL.String(), reader, length, progress) if err != nil { - if !globalQuiet && !globalJSON { - progressReader.ErrorPut(length) - } sURLs.Error = err.Trace(targetURL.String()) - statusCh <- sURLs - return + return sURLs } sURLs.Error = nil // just for safety - statusCh <- sURLs + return sURLs } // doMirrorFake - Perform a fake mirror to update the progress bar appropriately. -func doMirrorFake(sURLs mirrorURLs, progressReader *barSend) { +func doMirrorFake(sURLs mirrorURLs, progressReader *progressBar) mirrorURLs { if !globalDebug && !globalJSON { - progressReader.Progress(sURLs.SourceContent.Size) + progressReader.ProgressBar.Add64(sURLs.SourceContent.Size) } + return sURLs } // doPrepareMirrorURLs scans the source URL and prepares a list of objects for mirroring. @@ -264,57 +246,57 @@ func doMirrorSession(session *sessionV6) { accntReader := newAccounter(session.Header.TotalBytes) // Set up progress bar. - var progressReader *barSend + var progressReader *progressBar if !globalQuiet && !globalJSON { progressReader = newProgressBar(session.Header.TotalBytes) } // Prepare URL scanner from session data file. - scanner := bufio.NewScanner(session.NewDataReader()) + urlScanner := bufio.NewScanner(session.NewDataReader()) + // isCopied returns true if an object has been already copied // or not. This is useful when we resume from a session. isCopied := isCopiedFactory(session.Header.LastCopied) - wg := new(sync.WaitGroup) - // Limit numner of mirror routines based on available CPU resources. - mirrorQueue := make(chan bool, int(math.Max(float64(runtime.NumCPU())-1, 1))) - defer close(mirrorQueue) - // Status channel for receiveing mirror return status. - statusCh := make(chan mirrorURLs) + // Wait on status of doMirror() operation. + var statusCh = make(chan mirrorURLs) - // Go routine to monitor doMirror status and signal traps. + // Add a wait group for the below go-routine. + var wg = new(sync.WaitGroup) wg.Add(1) + + // Go routine to monitor signal traps if any. go func() { defer wg.Done() for { select { - case sURLs, ok := <-statusCh: // Receive status. - if !ok { // We are done here. Top level function has returned. - if !globalQuiet && !globalJSON { - progressReader.Finish() - } else { - accntStat := accntReader.Stat() - mrStatMessage := mirrorStatMessage{ - Total: accntStat.Total, - Transferred: accntStat.Transferred, - Speed: accntStat.Speed, - } - console.Println(console.Colorize("Mirror", mrStatMessage.String())) - } + case <-trapCh: + // Receive interrupt notification. + if !globalQuiet && !globalJSON { + console.Eraseline() + } + session.CloseAndDie() + case sURLs, ok := <-statusCh: + // Status channel is closed, we should return. + if !ok { return } if sURLs.Error == nil { session.Header.LastCopied = sURLs.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 + // 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(sURLs.Error.Trace(), fmt.Sprintf("Failed to mirror ‘%s’.", sURLs.SourceContent.URL.String())) - // for all non critical errors we can continue for the remaining files + errorIf(sURLs.Error.Trace(sURLs.SourceContent.URL.String()), + fmt.Sprintf("Failed to copy ‘%s’.", sURLs.SourceContent.URL.String())) + // For all non critical errors we can continue for the + // remaining files. switch sURLs.Error.ToGoError().(type) { - // handle this specifically for filesystem related errors. + // Handle this specifically for filesystem related + // errors. case client.BrokenSymlink: continue case client.TooManyLevelsSymlink: @@ -323,47 +305,50 @@ func doMirrorSession(session *sessionV6) { continue case client.PathInsufficientPermission: continue + case client.ObjectAlreadyExists: + continue + case client.BucketDoesNotExist: + continue } - // for critical errors we should exit. Session can be resumed after the user figures out the problem + // For critical errors we should exit. Session + // can be resumed after the user figures out + // the problem. session.CloseAndDie() } - case <-trapCh: // Receive interrupt notification. - // Print in new line and adjust to top so that we don't print over the ongoing progress bar - if !globalQuiet && !globalJSON { - console.Eraseline() - } - session.CloseAndDie() } } }() - // Go routine to perform concurrently mirroring. - wg.Add(1) - go func() { - defer wg.Done() - mirrorWg := new(sync.WaitGroup) - defer close(statusCh) - - for scanner.Scan() { - var sURLs mirrorURLs - json.Unmarshal([]byte(scanner.Text()), &sURLs) - if isCopied(sURLs.SourceContent.URL.String()) { - doMirrorFake(sURLs, progressReader) - } else { - // Wait for other mirror routines to - // complete. We only have limited CPU - // and network resources. - mirrorQueue <- true - // Account for each mirror routines we start. - mirrorWg.Add(1) - // Do mirroring in background concurrently. - go doMirror(sURLs, progressReader, accntReader, mirrorQueue, mirrorWg, statusCh) - } + // Loop through all urls. + for urlScanner.Scan() { + var sURLs mirrorURLs + // Unmarshal copyURLs from each line. + json.Unmarshal([]byte(urlScanner.Text()), &sURLs) + // Verify if previously copied, notify progress bar. + if isCopied(sURLs.SourceContent.URL.String()) { + statusCh <- doMirrorFake(sURLs, progressReader) + } else { + statusCh <- doMirror(sURLs, progressReader, accntReader) } - mirrorWg.Wait() - }() + } + // Close the goroutine. + close(statusCh) + + // Wait for the goroutines to finish. wg.Wait() + + if !globalQuiet && !globalJSON { + progressReader.ProgressBar.Finish() + } else { + accntStat := accntReader.Stat() + mrStatMessage := mirrorStatMessage{ + Total: accntStat.Total, + Transferred: accntStat.Transferred, + Speed: accntStat.Speed, + } + console.Println(console.Colorize("Mirror", mrStatMessage.String())) + } } // Main entry point for mirror command. diff --git a/pipe-main.go b/pipe-main.go index 8384d026..4855c337 100644 --- a/pipe-main.go +++ b/pipe-main.go @@ -72,7 +72,7 @@ func pipe(targetURL string) *probe.Error { // Stream from stdin to multiple objects until EOF. // Ignore size, since os.Stat() would not return proper size all the time // for local filesystem for example /proc files. - err := putTarget(targetURL, os.Stdin, -1) + _, err := putTargetStream(targetURL, os.Stdin, -1) // TODO: See if this check is necessary. switch e := err.ToGoError().(type) { case *os.PathError: diff --git a/pkg/client/client.go b/pkg/client/client.go index e3e11ac6..9d3879d5 100644 --- a/pkg/client/client.go +++ b/pkg/client/client.go @@ -31,13 +31,13 @@ type Client interface { List(recursive, incomplete bool) <-chan *Content // Bucket operations - MakeBucket() *probe.Error + MakeBucket(region string) *probe.Error GetBucketAccess() (access string, error *probe.Error) SetBucketAccess(access string) *probe.Error // I/O operations - Get(offset, length int64) (body io.ReadSeeker, err *probe.Error) - Put(data io.ReadSeeker, size int64, contentType string) *probe.Error + Get() (reader io.Reader, err *probe.Error) + Put(reader io.Reader, size int64, contentType string, progress io.Reader) (n int64, err *probe.Error) // I/O operations with expiration ShareDownload(expires time.Duration) (string, *probe.Error) diff --git a/pkg/client/errors.go b/pkg/client/errors.go index 9151dea2..bb20dfe5 100644 --- a/pkg/client/errors.go +++ b/pkg/client/errors.go @@ -16,7 +16,10 @@ package client -import "strconv" +import ( + "fmt" + "strconv" +) /// Collection of standard errors @@ -36,7 +39,7 @@ type InvalidRange struct { } func (e InvalidRange) Error() string { - return "Invalid range offset: " + strconv.FormatInt(e.Offset, 10) + " ." + return "Invalid range offset: ‘" + strconv.FormatInt(e.Offset, 10) + "’." } // GenericBucketError - generic bucket operations error @@ -44,18 +47,25 @@ type GenericBucketError struct { Bucket string } -// BucketExists - bucket exists +// BucketDoesNotExist - bucket does not exist. +type BucketDoesNotExist GenericBucketError + +func (e BucketDoesNotExist) Error() string { + return "Bucket ‘" + e.Bucket + "’ does not exist." +} + +// BucketExists - bucket exists. type BucketExists GenericBucketError func (e BucketExists) Error() string { - return "Bucket #" + e.Bucket + " exists." + return "Bucket ‘" + e.Bucket + "’ exists." } // InvalidBucketName - bucket name invalid (http://goo.gl/wJlzDz) type InvalidBucketName GenericBucketError func (e InvalidBucketName) Error() string { - return "Invalid bucketname [" + e.Bucket + "], please read http://goo.gl/wJlzDz." + return "Invalid bucketname [‘" + e.Bucket + "’], please read http://goo.gl/wJlzDz." } // BucketNameEmpty - bucket name empty (http://goo.gl/wJlzDz) @@ -77,14 +87,14 @@ type ObjectAlreadyExists struct { } func (e ObjectAlreadyExists) Error() string { - return "Object #" + e.Object + " already exists." + return "Object ‘" + e.Object + "’ already exists." } // InvalidObjectName - object requested is invalid type InvalidObjectName GenericObjectError func (e InvalidObjectName) Error() string { - return "Object #" + e.Object + " at " + e.Bucket + " is invalid." + return "Object ‘" + e.Object + "’ at ‘" + e.Bucket + "’ is invalid." } // BucketNameTopLevel - generic error @@ -106,11 +116,11 @@ func (e PathNotFound) Error() string { return "Requested file ‘" + e.Path + "’ not found" } -// PathIsDir (EISDIR) - file is a folder. -type PathIsDir GenericFileError +// PathIsNotRegular (ENOTREG) - file is not a regular file. +type PathIsNotRegular GenericFileError -func (e PathIsDir) Error() string { - return "Requested file ‘" + e.Path + "’ is folder." +func (e PathIsNotRegular) Error() string { + return "Requested file ‘" + e.Path + "’ is not a regular file." } // PathInsufficientPermission (EPERM) - permission denied. @@ -147,3 +157,33 @@ type ObjectMissing struct{} func (e ObjectMissing) Error() string { return "Object key is missing, object key cannot be empty" } + +// UnexpectedShortWrite - write wrote less bytes than expected. +type UnexpectedShortWrite struct { + InputSize int + WriteSize int +} + +func (e UnexpectedShortWrite) Error() string { + msg := fmt.Sprintf("Wrote less data than requested. Expected ‘%d’ bytes, but only wrote ‘%d’ bytes.", e.InputSize, e.WriteSize) + return msg +} + +// UnexpectedEOF (EPIPE) - reader closed prematurely. +type UnexpectedEOF struct { + TotalSize int64 + TotalWritten int64 +} + +func (e UnexpectedEOF) Error() string { + msg := fmt.Sprintf("Input reader closed pre-maturely. Expected ‘%d’ bytes, but only received ‘%d’ bytes.", e.TotalSize, e.TotalWritten) + return msg +} + +// UnexpectedExcessRead - reader wrote more data than requested. +type UnexpectedExcessRead UnexpectedEOF + +func (e UnexpectedExcessRead) Error() string { + msg := fmt.Sprintf("Received excess data on input reader. Expected only ‘%d’ bytes, but received ‘%d’ bytes.", e.TotalSize, e.TotalWritten) + return msg +} diff --git a/pkg/client/fs/fs-utils.go b/pkg/client/fs/fs-utils.go index 0af48b7f..c56e7754 100644 --- a/pkg/client/fs/fs-utils.go +++ b/pkg/client/fs/fs-utils.go @@ -112,7 +112,7 @@ func walk(path string, info os.FileInfo, walkFn WalkFunc) error { filename := filepath.Join(path, name) fileInfo, err := os.Lstat(filename) if err != nil { - if err := walkFn(filename, fileInfo, err); err != nil && err != ErrSkipDir && err != ErrSkipFile { + if err = walkFn(filename, fileInfo, err); err != nil && err != ErrSkipDir && err != ErrSkipFile { return err } } else { diff --git a/pkg/client/fs/fs.go b/pkg/client/fs/fs.go index fc859a07..7b2caf37 100644 --- a/pkg/client/fs/fs.go +++ b/pkg/client/fs/fs.go @@ -27,6 +27,7 @@ import ( "io/ioutil" "github.com/minio/mc/pkg/client" + "github.com/minio/mc/pkg/hookreader" "github.com/minio/minio-xl/pkg/probe" ) @@ -57,7 +58,7 @@ func (f *fsClient) GetURL() client.URL { /// Object operations. // Put - create a new file. -func (f *fsClient) Put(data io.ReadSeeker, size int64, contentType string) *probe.Error { +func (f *fsClient) Put(reader io.Reader, size int64, contentType string, progress io.Reader) (int64, *probe.Error) { // ContentType is not handled on purpose. // For filesystem this is a redundant information. @@ -68,9 +69,9 @@ func (f *fsClient) Put(data io.ReadSeeker, size int64, contentType string) *prob // Verify if destination already exists. st, e := os.Stat(objectPath) if e == nil { - // If the destination exists and is a directory. - if st.IsDir() { - return probe.NewError(client.PathIsDir{ + // If the destination exists and is not a regular file. + if !st.Mode().IsRegular() { + return 0, probe.NewError(client.PathIsNotRegular{ Path: objectPath, }) } @@ -79,17 +80,17 @@ func (f *fsClient) Put(data io.ReadSeeker, size int64, contentType string) *prob // Proceed if file does not exist. return for all other errors. if e != nil { if !os.IsNotExist(e) { - return probe.NewError(e) + return 0, probe.NewError(e) } } - // Write to a temporary file "object.part.mc" before commiting. + // Write to a temporary file "object.part.mc" before committ. objectPartPath := objectPath + partSuffix if objectDir != "" { // Create any missing top level directories. if e := os.MkdirAll(objectDir, 0700); e != nil { err := f.toClientError(e, f.PathURL.Path) - return err.Trace(f.PathURL.Path) + return 0, err.Trace(f.PathURL.Path) } } @@ -97,37 +98,121 @@ func (f *fsClient) Put(data io.ReadSeeker, size int64, contentType string) *prob partFile, e := os.OpenFile(objectPartPath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600) if e != nil { err := f.toClientError(e, f.PathURL.Path) - return err.Trace(f.PathURL.Path) + return 0, err.Trace(f.PathURL.Path) } // Get stat to get the current size. partSt, e := partFile.Stat() - if e != nil { - return probe.NewError(e) - } - - // Seek to current position for incoming reader. - data.Seek(partSt.Size(), 0) - - // Write to the part file. - if size < 0 { // Read till EOF. - _, e = io.Copy(partFile, data) - } else { // Read till N bytes. - _, e = io.CopyN(partFile, data, size-partSt.Size()) - } if e != nil { err := f.toClientError(e, objectPartPath) - return err.Trace(objectPartPath) + return 0, err.Trace(objectPartPath) } - // Close the file before rename. - partFile.Close() + var totalWritten int64 + // Current file offset. + var currentOffset = partSt.Size() + + // Reflect and verify if incoming reader implements ReaderAt. + readerAt, ok := reader.(io.ReaderAt) + if ok { + // Notify the progress bar if any till current size. + if progress != nil { + if _, e = io.CopyN(ioutil.Discard, progress, currentOffset); e != nil { + return 0, probe.NewError(e) + } + } + // Allocate buffer of 10MiB once. + readAtBuffer := make([]byte, 10*1024*1024) + + // Loop through all offsets on incoming io.ReaderAt and write + // to the destination. + for { + readAtSize, re := readerAt.ReadAt(readAtBuffer, currentOffset) + if re != nil && re != io.EOF { + // For any errors other than io.EOF, we return error + // and breakout. + err := f.toClientError(re, objectPartPath) + return 0, err.Trace(objectPartPath) + } + writtenSize, we := partFile.Write(readAtBuffer[:readAtSize]) + if we != nil { + err := f.toClientError(we, objectPartPath) + return 0, err.Trace(objectPartPath) + } + // read size and subsequent write differ, a possible + // corruption return here. + if readAtSize != writtenSize { + // Unexpected write (less data was written than expected). + return 0, probe.NewError(client.UnexpectedShortWrite{ + InputSize: readAtSize, + WriteSize: writtenSize, + }) + } + // Notify the progress bar if any for written size. + if progress != nil { + if _, e = io.CopyN(ioutil.Discard, progress, int64(writtenSize)); e != nil { + return totalWritten, probe.NewError(e) + } + } + currentOffset += int64(writtenSize) + // Once we see io.EOF we break out of the loop. + if re == io.EOF { + break + } + } + // Save currently copied total into totalWritten. + totalWritten = currentOffset + } else { + reader = hookreader.NewHook(reader, progress) + // Discard bytes until currentOffset. + if _, e = io.CopyN(ioutil.Discard, reader, currentOffset); e != nil { + return 0, probe.NewError(e) + } + var n int64 + n, e = io.Copy(partFile, reader) + if e != nil { + return 0, probe.NewError(e) + } + // Save currently copied total into totalWritten. + totalWritten = n + currentOffset + } + + // Close the input reader as well, if possible. + closer, ok := reader.(io.Closer) + if ok { + if e := closer.Close(); e != nil { + return totalWritten, probe.NewError(e) + } + } + + // Close the file before rename. + if e := partFile.Close(); e != nil { + return totalWritten, probe.NewError(e) + } + + // Following verification is needed only for input size greater than '0'. + if size > 0 { + // Unexpected EOF reached (less data was written than expected). + if totalWritten < size { + return totalWritten, probe.NewError(client.UnexpectedEOF{ + TotalSize: size, + TotalWritten: totalWritten, + }) + } + // Unexpected ExcessRead (more data was written than expected). + if totalWritten > size { + return totalWritten, probe.NewError(client.UnexpectedExcessRead{ + TotalSize: size, + TotalWritten: totalWritten, + }) + } + } // Safely completed put. Now commit by renaming to actual filename. if e = os.Rename(objectPartPath, objectPath); e != nil { err := f.toClientError(e, objectPath) - return err.Trace(objectPartPath, objectPath) + return totalWritten, err.Trace(objectPartPath, objectPath) } - return nil + return totalWritten, nil } // ShareDownload - share download not implemented for filesystem. @@ -146,13 +231,9 @@ func (f *fsClient) ShareUpload(startsWith bool, expires time.Duration, contentTy }) } -// Get download an full or part object from bucket. -// returns a reader, length and nil for no errors. -func (f *fsClient) Get(offset, length int64) (io.ReadSeeker, *probe.Error) { - if offset < 0 || length < 0 { - return nil, probe.NewError(client.InvalidRange{Offset: offset}) - } - +// GetPartial download a part object from bucket. +// sets err for any errors, reader is nil for errors. +func (f *fsClient) Get() (io.Reader, *probe.Error) { tmppath := f.PathURL.Path // Golang strips trailing / if you clean(..) or // EvalSymlinks(..). Adding '.' prevents it from doing so. @@ -166,15 +247,12 @@ func (f *fsClient) Get(offset, length int64) (io.ReadSeeker, *probe.Error) { err := f.toClientError(e, f.PathURL.Path) return nil, err.Trace(f.PathURL.Path) } - body, e := os.Open(f.PathURL.Path) + fileData, e := os.Open(f.PathURL.Path) if e != nil { err := f.toClientError(e, f.PathURL.Path) return nil, err.Trace(f.PathURL.Path) } - if offset == 0 && length == 0 { - return body, nil - } - return io.NewSectionReader(body, offset, length), nil + return fileData, nil } // Remove - remove the path. @@ -379,7 +457,7 @@ func (f *fsClient) listInRoutine(contentCh chan<- *client.Content, incomplete bo continue } } - pathURL := *f.PathURL + pathURL = *f.PathURL pathURL.Path = filepath.Join(pathURL.Path, lfi.Name()) contentCh <- &client.Content{ URL: pathURL, @@ -419,7 +497,7 @@ func (f *fsClient) listInRoutine(contentCh chan<- *client.Content, incomplete bo continue } } - pathURL := *f.PathURL + pathURL = *f.PathURL pathURL.Path = filepath.Join(pathURL.Path, fi.Name()) contentCh <- &client.Content{ URL: pathURL, @@ -634,7 +712,7 @@ func (f *fsClient) listRecursiveInRoutine(contentCh chan *client.Content, incomp } // MakeBucket - create a new bucket. -func (f *fsClient) MakeBucket() *probe.Error { +func (f *fsClient) MakeBucket(region string) *probe.Error { e := os.MkdirAll(f.PathURL.Path, 0775) if e != nil { return probe.NewError(e) diff --git a/pkg/client/fs/fs_test.go b/pkg/client/fs/fs_test.go index 2205352d..26416c92 100644 --- a/pkg/client/fs/fs_test.go +++ b/pkg/client/fs/fs_test.go @@ -35,32 +35,40 @@ type MySuite struct{} var _ = Suite(&MySuite{}) +// Test list files in a folder. func (s *MySuite) TestList(c *C) { root, e := ioutil.TempDir(os.TempDir(), "fs-") c.Assert(e, IsNil) defer os.RemoveAll(root) + // Create multiple files. objectPath := filepath.Join(root, "object1") - fsc, err := fs.New(objectPath) + fsClient, err := fs.New(objectPath) c.Assert(err, IsNil) data := "hello" - err = fsc.Put(bytes.NewReader([]byte(data)), int64(len(data)), "application/octet-stream") + reader := bytes.NewReader([]byte(data)) + var n int64 + n, err = fsClient.Put(reader, int64(len(data)), "application/octet-stream", nil) c.Assert(err, IsNil) + c.Assert(n, Equals, int64(len(data))) objectPath = filepath.Join(root, "object2") - fsc, err = fs.New(objectPath) + fsClient, err = fs.New(objectPath) c.Assert(err, IsNil) - err = fsc.Put(bytes.NewReader([]byte(data)), int64(len(data)), "application/octet-stream") + reader = bytes.NewReader([]byte(data)) + n, err = fsClient.Put(reader, int64(len(data)), "application/octet-stream", nil) c.Assert(err, IsNil) + c.Assert(n, Equals, int64(len(data))) - fsc, err = fs.New(root) + fsClient, err = fs.New(root) c.Assert(err, IsNil) + // Verify previously create files and list them. var contents []*client.Content - for content := range fsc.List(false, false) { + for content := range fsClient.List(false, false) { if content.Err != nil { err = content.Err break @@ -71,18 +79,22 @@ func (s *MySuite) TestList(c *C) { c.Assert(len(contents), Equals, 1) c.Assert(contents[0].Type.IsDir(), Equals, true) + // Create another file. objectPath = filepath.Join(root, "test1/newObject1") - fsc, err = fs.New(objectPath) + fsClient, err = fs.New(objectPath) c.Assert(err, IsNil) - err = fsc.Put(bytes.NewReader([]byte(data)), int64(len(data)), "application/octet-stream") + reader = bytes.NewReader([]byte(data)) + n, err = fsClient.Put(reader, int64(len(data)), "application/octet-stream", nil) c.Assert(err, IsNil) + c.Assert(n, Equals, int64(len(data))) - fsc, err = fs.New(root) + fsClient, err = fs.New(root) c.Assert(err, IsNil) contents = nil - for content := range fsc.List(false, false) { + // List non recursive to list only top level files. + for content := range fsClient.List(false, false) { if content.Err != nil { err = content.Err break @@ -93,11 +105,12 @@ func (s *MySuite) TestList(c *C) { c.Assert(len(contents), Equals, 1) c.Assert(contents[0].Type.IsDir(), Equals, true) - fsc, err = fs.New(root) + fsClient, err = fs.New(root) c.Assert(err, IsNil) contents = nil - for content := range fsc.List(true, false) { + // List recursively all files and verify. + for content := range fsClient.List(true, false) { if content.Err != nil { err = content.Err break @@ -110,6 +123,7 @@ func (s *MySuite) TestList(c *C) { var regularFiles int var regularDirs int + // Test number of expected files and directories. for _, content := range contents { if content.Type.IsRegular() { regularFiles++ @@ -124,18 +138,20 @@ func (s *MySuite) TestList(c *C) { c.Assert(regularFiles, Equals, 3) } +// Test put bucket aka 'mkdir()' operation. func (s *MySuite) TestPutBucket(c *C) { root, e := ioutil.TempDir(os.TempDir(), "fs-") c.Assert(e, IsNil) defer os.RemoveAll(root) bucketPath := filepath.Join(root, "bucket") - fsc, err := fs.New(bucketPath) + fsClient, err := fs.New(bucketPath) c.Assert(err, IsNil) - err = fsc.MakeBucket() + err = fsClient.MakeBucket("us-east-1") c.Assert(err, IsNil) } +// Test stat bucket aka 'stat()' operation. func (s *MySuite) TestStatBucket(c *C) { root, e := ioutil.TempDir(os.TempDir(), "fs-") c.Assert(e, IsNil) @@ -143,61 +159,69 @@ func (s *MySuite) TestStatBucket(c *C) { bucketPath := filepath.Join(root, "bucket") - fsc, err := fs.New(bucketPath) + fsClient, err := fs.New(bucketPath) c.Assert(err, IsNil) - err = fsc.MakeBucket() + err = fsClient.MakeBucket("us-east-1") c.Assert(err, IsNil) - _, err = fsc.Stat() + _, err = fsClient.Stat() c.Assert(err, IsNil) } +// Test bucket acl fails for directories. func (s *MySuite) TestBucketACLFails(c *C) { root, e := ioutil.TempDir(os.TempDir(), "fs-") c.Assert(e, IsNil) defer os.RemoveAll(root) bucketPath := filepath.Join(root, "bucket") - fsc, err := fs.New(bucketPath) + fsClient, err := fs.New(bucketPath) c.Assert(err, IsNil) - err = fsc.MakeBucket() + err = fsClient.MakeBucket("us-east-1") c.Assert(err, IsNil) - err = fsc.SetBucketAccess("private") + err = fsClient.SetBucketAccess("private") c.Assert(err, Not(IsNil)) - _, err = fsc.GetBucketAccess() + _, err = fsClient.GetBucketAccess() c.Assert(err, Not(IsNil)) } +// Test creating a file. func (s *MySuite) TestPut(c *C) { root, e := ioutil.TempDir(os.TempDir(), "fs-") c.Assert(e, IsNil) defer os.RemoveAll(root) objectPath := filepath.Join(root, "object") - fsc, err := fs.New(objectPath) + fsClient, err := fs.New(objectPath) c.Assert(err, IsNil) data := "hello" - err = fsc.Put(bytes.NewReader([]byte(data)), int64(len(data)), "application/octet-stream") + reader := bytes.NewReader([]byte(data)) + var n int64 + n, err = fsClient.Put(reader, int64(len(data)), "application/octet-stream", nil) c.Assert(err, IsNil) + c.Assert(n, Equals, int64(len(data))) } +// Test read a file. func (s *MySuite) TestGet(c *C) { root, e := ioutil.TempDir(os.TempDir(), "fs-") c.Assert(e, IsNil) defer os.RemoveAll(root) objectPath := filepath.Join(root, "object") - fsc, err := fs.New(objectPath) + fsClient, err := fs.New(objectPath) c.Assert(err, IsNil) data := "hello" - - err = fsc.Put(bytes.NewReader([]byte(data)), int64(len(data)), "application/octet-stream") + var reader io.Reader + reader = bytes.NewReader([]byte(data)) + n, err := fsClient.Put(reader, int64(len(data)), "application/octet-stream", nil) c.Assert(err, IsNil) + c.Assert(n, Equals, int64(len(data))) - reader, err := fsc.Get(0, 0) + reader, err = fsClient.Get() c.Assert(err, IsNil) var results bytes.Buffer _, e = io.Copy(&results, reader) @@ -206,44 +230,53 @@ func (s *MySuite) TestGet(c *C) { } +// Test get range in a file. func (s *MySuite) TestGetRange(c *C) { root, e := ioutil.TempDir(os.TempDir(), "fs-") c.Assert(e, IsNil) defer os.RemoveAll(root) objectPath := filepath.Join(root, "object") - fsc, err := fs.New(objectPath) + fsClient, err := fs.New(objectPath) c.Assert(err, IsNil) data := "hello world" - - err = fsc.Put(bytes.NewReader([]byte(data)), int64(len(data)), "application/octet-stream") + var reader io.Reader + reader = bytes.NewReader([]byte(data)) + n, err := fsClient.Put(reader, int64(len(data)), "application/octet-stream", nil) c.Assert(err, IsNil) + c.Assert(n, Equals, int64(len(data))) - reader, err := fsc.Get(0, 5) + reader, err = fsClient.Get() c.Assert(err, IsNil) var results bytes.Buffer - _, e = io.Copy(&results, reader) + buf := make([]byte, 5) + m, e := reader.(io.ReaderAt).ReadAt(buf, 0) + c.Assert(e, IsNil) + c.Assert(m, Equals, 5) + _, e = results.Write(buf) c.Assert(e, IsNil) c.Assert([]byte("hello"), DeepEquals, results.Bytes()) } +// Test stat file. func (s *MySuite) TestStatObject(c *C) { root, e := ioutil.TempDir(os.TempDir(), "fs-") c.Assert(e, IsNil) defer os.RemoveAll(root) objectPath := filepath.Join(root, "object") - fsc, err := fs.New(objectPath) + fsClient, err := fs.New(objectPath) c.Assert(err, IsNil) data := "hello" dataLen := len(data) - - err = fsc.Put(bytes.NewReader([]byte(data)), int64(len(data)), "application/octet-stream") + reader := bytes.NewReader([]byte(data)) + n, err := fsClient.Put(reader, int64(dataLen), "application/octet-stream", nil) c.Assert(err, IsNil) + c.Assert(n, Equals, int64(len(data))) - content, err := fsc.Stat() + content, err := fsClient.Stat() c.Assert(err, IsNil) c.Assert(content.Size, Equals, int64(dataLen)) } diff --git a/pkg/client/s3/s3.go b/pkg/client/s3/s3.go index fea0d891..c7199417 100644 --- a/pkg/client/s3/s3.go +++ b/pkg/client/s3/s3.go @@ -36,20 +36,21 @@ import ( // S3 client type s3Client struct { - mu *sync.Mutex - api minio.CloudStorageAPI - hostURL *client.URL + mutex *sync.Mutex + targetURL *client.URL + api minio.CloudStorageClient virtualStyle bool } // newFactory encloses New function with client cache. func newFactory() func(config *client.Config) (client.Client, *probe.Error) { - clientCache := make(map[uint32]minio.CloudStorageAPI) + clientCache := make(map[uint32]minio.CloudStorageClient) mutex := &sync.Mutex{} // Return New function. return func(config *client.Config) (client.Client, *probe.Error) { - u := client.NewURL(config.HostURL) + // Creates a parsed URL. + targetURL := client.NewURL(config.HostURL) transport := http.DefaultTransport if config.Debug == true { if config.Signature == "S3v4" { @@ -59,50 +60,68 @@ func newFactory() func(config *client.Config) (client.Client, *probe.Error) { transport = httptracer.GetNewTraceTransport(NewTraceV2(), http.DefaultTransport) } } - - // New S3 configuration. - s3Conf := minio.Config{ - AccessKeyID: config.AccessKey, - SecretAccessKey: config.SecretKey, - Transport: transport, - Endpoint: u.Scheme + u.SchemeSeparator + u.Host, - Signature: func() minio.SignatureType { - if config.Signature == "S3v2" { - return minio.SignatureV2 - } - return minio.SignatureV4 - }(), + // By default enable HTTPs. + inSecure := false + if targetURL.Scheme == "http" { + inSecure = true } - s3Conf.SetUserAgent(config.AppName, config.AppVersion, config.AppComments...) + // Instantiate s3 client. + s3Clnt := &s3Client{} + // Allocate a new mutex. + s3Clnt.mutex = new(sync.Mutex) + // Save the target URL. + s3Clnt.targetURL = targetURL + + // Save if target supports virtual host style. + hostName := targetURL.Host + s3Clnt.virtualStyle = isVirtualHostStyle(hostName) + + if s3Clnt.virtualStyle { + // If Amazon URL replace it with 's3.amazonaws.com' + if isAmazon(hostName) { + hostName = "s3.amazonaws.com" + } + // If Google URL replace it with 'storage.googleapis.com' + if isGoogle(hostName) { + hostName = "storage.googleapis.com" + } + } // Generate a hash out of s3Conf. confHash := fnv.New32a() - confHash.Write([]byte(s3Conf.Endpoint + s3Conf.AccessKeyID + s3Conf.SecretAccessKey)) + confHash.Write([]byte(hostName + config.AccessKey + config.SecretKey)) confSum := confHash.Sum32() // Lookup previous cache by hash. mutex.Lock() defer mutex.Unlock() - var api minio.CloudStorageAPI + var api minio.CloudStorageClient found := false if api, found = clientCache[confSum]; !found { // Not found. Instantiate a new minio client. var e error - api, e = minio.New(s3Conf) + if config.Signature == "S3v2" { + // if Signature version '2' use NewV2 directly. + api, e = minio.NewV2(hostName, config.AccessKey, config.SecretKey, inSecure) + } else { + // if Signature version '4' use NewV4 directly. + api, e = minio.NewV4(hostName, config.AccessKey, config.SecretKey, inSecure) + } if e != nil { return nil, probe.NewError(e) } // Cache the new minio client with hash of config as key. clientCache[confSum] = api } + // Set app info. + api.SetAppInfo(config.AppName, config.AppVersion) + // Set custom transport. + api.SetCustomTransport(transport) + + // Store the new api object. + s3Clnt.api = api - s3Clnt := &s3Client{ - mu: new(sync.Mutex), - api: api, - hostURL: u, - virtualStyle: isVirtualHostStyle(u.Host), - } return s3Clnt, nil } } @@ -113,31 +132,72 @@ var New = newFactory() // GetURL get url. func (c *s3Client) GetURL() client.URL { - return *c.hostURL + return *c.targetURL } // Get - get object. -func (c *s3Client) Get(offset, length int64) (io.ReadSeeker, *probe.Error) { +func (c *s3Client) Get() (io.Reader, *probe.Error) { bucket, object := c.url2BucketAndObject() - reader, e := c.api.GetPartialObject(bucket, object, offset, length) + reader, e := c.api.GetObject(bucket, object) if e != nil { errResponse := minio.ToErrorResponse(e) - if errResponse != nil { - if errResponse.Code == "AccessDenied" { - return nil, probe.NewError(client.PathInsufficientPermission{Path: c.hostURL.String()}) - } + if errResponse.Code == "AccessDenied" { + return nil, probe.NewError(client.PathInsufficientPermission{Path: c.targetURL.String()}) } return nil, probe.NewError(e) } return reader, nil } +// Put - put object. +func (c *s3Client) Put(reader io.Reader, size int64, contentType string, progress io.Reader) (int64, *probe.Error) { + // md5 is purposefully ignored since AmazonS3 does not return proper md5sum + // for a multipart upload and there is no need to cross verify, + // invidual parts are properly verified fully in transit and also upon completion + // of the multipart request. + bucket, object := c.url2BucketAndObject() + if contentType == "" { + contentType = "application/octet-stream" + } + n, e := c.api.PutObjectWithProgress(bucket, object, reader, contentType, progress) + if e != nil { + errResponse := minio.ToErrorResponse(e) + if errResponse.Code == "UnexpectedEOF" || e == io.EOF { + return n, probe.NewError(client.UnexpectedEOF{ + TotalSize: size, + TotalWritten: n, + }) + } + if errResponse.Code == "AccessDenied" { + return n, probe.NewError(client.PathInsufficientPermission{ + Path: c.targetURL.String(), + }) + } + if errResponse.Code == "MethodNotAllowed" { + return n, probe.NewError(client.ObjectAlreadyExists{ + Object: object, + }) + } + if errResponse.Code == "NoSuchBucket" { + return n, probe.NewError(client.BucketDoesNotExist{ + Bucket: bucket, + }) + } + if errResponse.Code == "InvalidArgument" { + return n, probe.NewError(client.ObjectMissing{}) + } + return n, probe.NewError(e) + } + return n, nil +} + // Remove - remove object or bucket. func (c *s3Client) Remove(incomplete bool) *probe.Error { bucket, object := c.url2BucketAndObject() - if incomplete { - errCh := c.api.RemoveIncompleteUpload(bucket, object) - return probe.NewError(<-errCh) + // Remove only incomplete object. + if incomplete && object != "" { + e := c.api.RemoveIncompleteUpload(bucket, object) + return probe.NewError(e) } var e error if object == "" { @@ -148,91 +208,35 @@ func (c *s3Client) Remove(incomplete bool) *probe.Error { return probe.NewError(e) } -// ShareDownload - get a usable presigned object url to share. -func (c *s3Client) ShareDownload(expires time.Duration) (string, *probe.Error) { - bucket, object := c.url2BucketAndObject() - presignedURL, e := c.api.PresignedGetObject(bucket, object, expires) - if e != nil { - return "", probe.NewError(e) - } - return presignedURL, nil -} +// We support '.' with bucket names but we fallback to using path +// style requests instead for such buckets +var validBucketName = regexp.MustCompile(`^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$`) -// ShareUpload - get data for presigned post http form upload. -func (c *s3Client) ShareUpload(isRecursive bool, expires time.Duration, contentType string) (map[string]string, *probe.Error) { - bucket, object := c.url2BucketAndObject() - p := minio.NewPostPolicy() - if e := p.SetExpires(time.Now().UTC().Add(expires)); e != nil { - return nil, probe.NewError(e) +// isValidBucketName - verify bucket name in accordance with +// - http://docs.aws.amazon.com/AmazonS3/latest/dev/UsingBucket.html +func isValidBucketName(bucketName string) *probe.Error { + if strings.TrimSpace(bucketName) == "" { + return probe.NewError(errors.New("Bucket name cannot be empty.")) } - if strings.TrimSpace(contentType) != "" || contentType != "" { - // No need to verify for error here, since we have stripped out spaces. - p.SetContentType(contentType) + if len(bucketName) < 3 || len(bucketName) > 63 { + return probe.NewError(errors.New("Bucket name should be more than 3 characters and less than 64 characters")) } - if e := p.SetBucket(bucket); e != nil { - return nil, probe.NewError(e) - } - if isRecursive { - if e := p.SetKeyStartsWith(object); e != nil { - return nil, probe.NewError(e) - } - } else { - if e := p.SetKey(object); e != nil { - return nil, probe.NewError(e) - } - } - m, e := c.api.PresignedPostPolicy(p) - return m, probe.NewError(e) -} - -// Put - put object. -func (c *s3Client) Put(data io.ReadSeeker, size int64, contentType string) *probe.Error { - // md5 is purposefully ignored since AmazonS3 does not return proper md5sum - // for a multipart upload and there is no need to cross verify, - // invidual parts are properly verified fully in transit and also upon completion - // of the multipart request. - bucket, object := c.url2BucketAndObject() - if contentType == "" { - contentType = "application/octet-stream" - } - e := c.api.PutObject(bucket, object, data, size, contentType) - if e != nil { - errResponse := minio.ToErrorResponse(e) - if errResponse != nil { - if errResponse.Code == "AccessDenied" { - return probe.NewError(client.PathInsufficientPermission{ - Path: c.hostURL.String(), - }) - } - if errResponse.Code == "MethodNotAllowed" { - return probe.NewError(client.ObjectAlreadyExists{ - Object: object, - }) - } - if errResponse.Code == "InvalidArgument" { - return probe.NewError(client.ObjectMissing{}) - } - } - return probe.NewError(e) + 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 nil } // MakeBucket - make a new bucket. -func (c *s3Client) MakeBucket() *probe.Error { +func (c *s3Client) MakeBucket(region string) *probe.Error { bucket, object := c.url2BucketAndObject() if object != "" { return probe.NewError(client.BucketNameTopLevel{}) } - if len(bucket) < 3 || len(bucket) > 63 { - return probe.NewError(errors.New("Bucket name should be more than 3 characters and less than 64 characters")) + if err := isValidBucketName(bucket); err != nil { + return err.Trace(bucket) } - match, _ := regexp.MatchString("^[a-zA-Z][a-zA-Z0-9\\-]+[a-zA-Z0-9]$", bucket) - if !match { - return probe.NewError(errors.New("Bucket name can contain alphabet, '-' and numbers, but first character should be an alphabet")) - } - - e := c.api.MakeBucket(bucket, minio.BucketACL("private")) + e := c.api.MakeBucket(bucket, minio.BucketACL("private"), region) if e != nil { return probe.NewError(e) } @@ -273,77 +277,83 @@ func (c *s3Client) SetBucketAccess(acl string) *probe.Error { // Stat - send a 'HEAD' on a bucket or object to fetch its metadata. func (c *s3Client) Stat() (*client.Content, *probe.Error) { - c.mu.Lock() + c.mutex.Lock() objectMetadata := new(client.Content) bucket, object := c.url2BucketAndObject() switch { // valid case for 'ls -r s3/' case bucket == "" && object == "": - for bucket := range c.api.ListBuckets() { - if bucket.Err != nil { - c.mu.Unlock() - return nil, probe.NewError(bucket.Err) - } + _, err := c.api.ListBuckets() + if err != nil { + c.mutex.Unlock() + return nil, probe.NewError(err) } - c.mu.Unlock() - return &client.Content{URL: *c.hostURL, Type: os.ModeDir}, nil + c.mutex.Unlock() + return &client.Content{URL: *c.targetURL, Type: os.ModeDir}, nil } if object != "" { metadata, e := c.api.StatObject(bucket, object) if e != nil { - c.mu.Unlock() + c.mutex.Unlock() errResponse := minio.ToErrorResponse(e) - if errResponse != nil { - if errResponse.Code == "NoSuchKey" { - // Append "/" to the object name proactively and see if the Listing - // produces an output. If yes, then we treat it as a directory. - prefixName := object - // Trim any trailing separators and add it. - prefixName = strings.TrimSuffix(prefixName, string(c.hostURL.Separator)) + string(c.hostURL.Separator) - for objectStat := range c.api.ListObjects(bucket, prefixName, false) { - if objectStat.Err != nil { - return nil, probe.NewError(objectStat.Err) - } - content := client.Content{} - content.URL = *c.hostURL - content.Type = os.ModeDir - return &content, nil + if errResponse.Code == "NoSuchKey" { + // Append "/" to the object name proactively and see if the Listing + // produces an output. If yes, then we treat it as a directory. + prefixName := object + // Trim any trailing separators and add it. + prefixName = strings.TrimSuffix(prefixName, string(c.targetURL.Separator)) + string(c.targetURL.Separator) + isRecursive := false + for objectStat := range c.api.ListObjects(bucket, prefixName, isRecursive, nil) { + if objectStat.Err != nil { + return nil, probe.NewError(objectStat.Err) } - return nil, probe.NewError(client.PathNotFound{Path: c.hostURL.Path}) + content := client.Content{} + content.URL = *c.targetURL + content.Type = os.ModeDir + return &content, nil } + return nil, probe.NewError(client.PathNotFound{Path: c.targetURL.Path}) } return nil, probe.NewError(e) } - objectMetadata.URL = *c.hostURL + objectMetadata.URL = *c.targetURL objectMetadata.Time = metadata.LastModified objectMetadata.Size = metadata.Size objectMetadata.Type = os.FileMode(0664) - c.mu.Unlock() + c.mutex.Unlock() return objectMetadata, nil } e := c.api.BucketExists(bucket) if e != nil { - c.mu.Unlock() + c.mutex.Unlock() return nil, probe.NewError(e) } bucketMetadata := new(client.Content) - bucketMetadata.URL = *c.hostURL + bucketMetadata.URL = *c.targetURL bucketMetadata.Type = os.ModeDir - c.mu.Unlock() + c.mutex.Unlock() return bucketMetadata, nil } +func isAmazon(host string) bool { + matchAmazon, _ := filepath.Match("*.s3*.amazonaws.com", host) + return matchAmazon +} + +func isGoogle(host string) bool { + matchGoogle, _ := filepath.Match("*.storage.googleapis.com", host) + return matchGoogle +} + // Figure out if the URL is of 'virtual host' style. // Currently only supported hosts with virtual style are Amazon S3 and Google Cloud Storage. -func isVirtualHostStyle(hostURL string) bool { - matchS3, _ := filepath.Match("*.s3*.amazonaws.com", hostURL) - matchGoogle, _ := filepath.Match("*.storage.googleapis.com", hostURL) - return matchS3 || matchGoogle +func isVirtualHostStyle(host string) bool { + return isAmazon(host) || isGoogle(host) } // url2BucketAndObject gives bucketName and objectName from URL path. func (c *s3Client) url2BucketAndObject() (bucketName, objectName string) { - path := c.hostURL.Path + path := c.targetURL.Path // Convert any virtual host styled requests. // // For the time being this check is introduced for S3, @@ -351,16 +361,16 @@ func (c *s3Client) url2BucketAndObject() (bucketName, objectName string) { // List them below. if c.virtualStyle { var bucket string - hostIndex := strings.Index(c.hostURL.Host, "s3") + hostIndex := strings.Index(c.targetURL.Host, "s3") if hostIndex == -1 { - hostIndex = strings.Index(c.hostURL.Host, "storage.googleapis") + hostIndex = strings.Index(c.targetURL.Host, "storage.googleapis") } if hostIndex > 0 { - bucket = c.hostURL.Host[:hostIndex-1] - path = string(c.hostURL.Separator) + bucket + c.hostURL.Path + bucket = c.targetURL.Host[:hostIndex-1] + path = string(c.targetURL.Separator) + bucket + c.targetURL.Path } } - splits := strings.SplitN(path, string(c.hostURL.Separator), 3) + splits := strings.SplitN(path, string(c.targetURL.Separator), 3) switch len(splits) { case 0, 1: bucketName = "" @@ -379,8 +389,8 @@ func (c *s3Client) url2BucketAndObject() (bucketName, objectName string) { // List - list at delimited path, if not recursive. func (c *s3Client) List(recursive, incomplete bool) <-chan *client.Content { - c.mu.Lock() - defer c.mu.Unlock() + c.mutex.Lock() + defer c.mutex.Unlock() contentCh := make(chan *client.Content) if incomplete { @@ -405,14 +415,16 @@ func (c *s3Client) listIncompleteInRoutine(contentCh chan *client.Content) { b, o := c.url2BucketAndObject() switch { case b == "" && o == "": - for bucket := range c.api.ListBuckets() { - if bucket.Err != nil { - contentCh <- &client.Content{ - Err: probe.NewError(bucket.Err), - } - return + buckets, err := c.api.ListBuckets() + if err != nil { + contentCh <- &client.Content{ + Err: probe.NewError(err), } - for object := range c.api.ListIncompleteUploads(bucket.Name, o, false) { + return + } + isRecursive := false + for _, bucket := range buckets { + for object := range c.api.ListIncompleteUploads(bucket.Name, o, isRecursive, nil) { if object.Err != nil { contentCh <- &client.Content{ Err: probe.NewError(object.Err), @@ -420,14 +432,14 @@ func (c *s3Client) listIncompleteInRoutine(contentCh chan *client.Content) { return } content := new(client.Content) - url := *c.hostURL + url := *c.targetURL // Join bucket with - incoming object key. url.Path = filepath.Join(string(url.Separator), bucket.Name, object.Key) if c.virtualStyle { url.Path = filepath.Join(string(url.Separator), object.Key) } switch { - case strings.HasSuffix(object.Key, string(c.hostURL.Separator)): + case strings.HasSuffix(object.Key, string(c.targetURL.Separator)): // We need to keep the trailing Separator, do not use filepath.Join(). content.URL = url content.Time = time.Now() @@ -442,7 +454,8 @@ func (c *s3Client) listIncompleteInRoutine(contentCh chan *client.Content) { } } default: - for object := range c.api.ListIncompleteUploads(b, o, false) { + isRecursive := false + for object := range c.api.ListIncompleteUploads(b, o, isRecursive, nil) { if object.Err != nil { contentCh <- &client.Content{ Err: probe.NewError(object.Err), @@ -450,14 +463,14 @@ func (c *s3Client) listIncompleteInRoutine(contentCh chan *client.Content) { return } content := new(client.Content) - url := *c.hostURL + url := *c.targetURL // Join bucket with - incoming object key. url.Path = filepath.Join(string(url.Separator), b, object.Key) if c.virtualStyle { url.Path = filepath.Join(string(url.Separator), object.Key) } switch { - case strings.HasSuffix(object.Key, string(c.hostURL.Separator)): + case strings.HasSuffix(object.Key, string(c.targetURL.Separator)): // We need to keep the trailing Separator, do not use filepath.Join(). content.URL = url content.Time = time.Now() @@ -479,23 +492,25 @@ func (c *s3Client) listIncompleteRecursiveInRoutine(contentCh chan *client.Conte b, o := c.url2BucketAndObject() switch { case b == "" && o == "": - for bucket := range c.api.ListBuckets() { - if bucket.Err != nil { - contentCh <- &client.Content{ - Err: probe.NewError(bucket.Err), - } - return + buckets, err := c.api.ListBuckets() + if err != nil { + contentCh <- &client.Content{ + Err: probe.NewError(err), } - for object := range c.api.ListIncompleteUploads(bucket.Name, o, true) { + return + } + isRecursive := true + for _, bucket := range buckets { + for object := range c.api.ListIncompleteUploads(bucket.Name, o, isRecursive, nil) { if object.Err != nil { contentCh <- &client.Content{ Err: probe.NewError(object.Err), } return } - content := new(client.Content) - url := *c.hostURL + url := *c.targetURL url.Path = filepath.Join(url.Path, bucket.Name, object.Key) + content := new(client.Content) content.URL = url content.Size = object.Size content.Time = object.Initiated @@ -504,14 +519,15 @@ func (c *s3Client) listIncompleteRecursiveInRoutine(contentCh chan *client.Conte } } default: - for object := range c.api.ListIncompleteUploads(b, o, true) { + isRecursive := true + for object := range c.api.ListIncompleteUploads(b, o, isRecursive, nil) { if object.Err != nil { contentCh <- &client.Content{ Err: probe.NewError(object.Err), } return } - url := *c.hostURL + url := *c.targetURL // Join bucket and incoming object key. url.Path = filepath.Join(string(url.Separator), b, object.Key) if c.virtualStyle { @@ -533,14 +549,15 @@ func (c *s3Client) listInRoutine(contentCh chan *client.Content) { b, o := c.url2BucketAndObject() switch { case b == "" && o == "": - for bucket := range c.api.ListBuckets() { - if bucket.Err != nil { - contentCh <- &client.Content{ - Err: probe.NewError(bucket.Err), - } - return + buckets, err := c.api.ListBuckets() + if err != nil { + contentCh <- &client.Content{ + Err: probe.NewError(err), } - url := *c.hostURL + return + } + for _, bucket := range buckets { + url := *c.targetURL url.Path = filepath.Join(url.Path, bucket.Name) content := new(client.Content) content.URL = url @@ -549,7 +566,7 @@ func (c *s3Client) listInRoutine(contentCh chan *client.Content) { content.Type = os.ModeDir contentCh <- content } - case b != "" && !strings.HasSuffix(c.hostURL.Path, string(c.hostURL.Separator)) && o == "": + case b != "" && !strings.HasSuffix(c.targetURL.Path, string(c.targetURL.Separator)) && o == "": e := c.api.BucketExists(b) if e != nil { contentCh <- &client.Content{ @@ -557,7 +574,7 @@ func (c *s3Client) listInRoutine(contentCh chan *client.Content) { } } content := new(client.Content) - content.URL = *c.hostURL + content.URL = *c.targetURL content.Type = os.ModeDir contentCh <- content default: @@ -565,13 +582,14 @@ func (c *s3Client) listInRoutine(contentCh chan *client.Content) { switch e.(type) { case nil: content := new(client.Content) - content.URL = *c.hostURL + content.URL = *c.targetURL content.Time = metadata.LastModified content.Size = metadata.Size content.Type = os.FileMode(0664) contentCh <- content default: - for object := range c.api.ListObjects(b, o, false) { + isRecursive := false + for object := range c.api.ListObjects(b, o, isRecursive, nil) { if object.Err != nil { contentCh <- &client.Content{ Err: probe.NewError(object.Err), @@ -579,14 +597,14 @@ func (c *s3Client) listInRoutine(contentCh chan *client.Content) { return } content := new(client.Content) - url := *c.hostURL + url := *c.targetURL // Join bucket and incoming object key. url.Path = filepath.Join(string(url.Separator), b, object.Key) if c.virtualStyle { url.Path = filepath.Join(string(url.Separator), object.Key) } switch { - case strings.HasSuffix(object.Key, string(c.hostURL.Separator)): + case strings.HasSuffix(object.Key, string(c.targetURL.Separator)): // We need to keep the trailing Separator, do not use filepath.Join(). content.URL = url content.Time = time.Now() @@ -609,21 +627,23 @@ func (c *s3Client) listRecursiveInRoutine(contentCh chan *client.Content) { b, o := c.url2BucketAndObject() switch { case b == "" && o == "": - for bucket := range c.api.ListBuckets() { - if bucket.Err != nil { - contentCh <- &client.Content{ - Err: probe.NewError(bucket.Err), - } - return + buckets, err := c.api.ListBuckets() + if err != nil { + contentCh <- &client.Content{ + Err: probe.NewError(err), } - bucketURL := *c.hostURL + return + } + for _, bucket := range buckets { + bucketURL := *c.targetURL bucketURL.Path = filepath.Join(bucketURL.Path, bucket.Name) contentCh <- &client.Content{ URL: bucketURL, Type: os.ModeDir, Time: bucket.CreationDate, } - for object := range c.api.ListObjects(bucket.Name, o, true) { + isRecursive := true + for object := range c.api.ListObjects(bucket.Name, o, isRecursive, nil) { if object.Err != nil { contentCh <- &client.Content{ Err: probe.NewError(object.Err), @@ -631,7 +651,7 @@ func (c *s3Client) listRecursiveInRoutine(contentCh chan *client.Content) { continue } content := new(client.Content) - objectURL := *c.hostURL + objectURL := *c.targetURL objectURL.Path = filepath.Join(objectURL.Path, bucket.Name, object.Key) content.URL = objectURL content.Size = object.Size @@ -641,7 +661,8 @@ func (c *s3Client) listRecursiveInRoutine(contentCh chan *client.Content) { } } default: - for object := range c.api.ListObjects(b, o, true) { + isRecursive := true + for object := range c.api.ListObjects(b, o, isRecursive, nil) { if object.Err != nil { contentCh <- &client.Content{ Err: probe.NewError(object.Err), @@ -649,7 +670,7 @@ func (c *s3Client) listRecursiveInRoutine(contentCh chan *client.Content) { continue } content := new(client.Content) - url := *c.hostURL + url := *c.targetURL // Join bucket and incoming object key. url.Path = filepath.Join(string(url.Separator), b, object.Key) // If virtualStyle replace the url.Path back. @@ -664,3 +685,40 @@ func (c *s3Client) listRecursiveInRoutine(contentCh chan *client.Content) { } } } + +// ShareDownload - get a usable presigned object url to share. +func (c *s3Client) ShareDownload(expires time.Duration) (string, *probe.Error) { + bucket, object := c.url2BucketAndObject() + presignedURL, e := c.api.PresignedGetObject(bucket, object, expires) + if e != nil { + return "", probe.NewError(e) + } + return presignedURL, nil +} + +// ShareUpload - get data for presigned post http form upload. +func (c *s3Client) ShareUpload(isRecursive bool, expires time.Duration, contentType string) (map[string]string, *probe.Error) { + bucket, object := c.url2BucketAndObject() + p := minio.NewPostPolicy() + if e := p.SetExpires(time.Now().UTC().Add(expires)); e != nil { + return nil, probe.NewError(e) + } + if strings.TrimSpace(contentType) != "" || contentType != "" { + // No need to verify for error here, since we have stripped out spaces. + p.SetContentType(contentType) + } + if e := p.SetBucket(bucket); e != nil { + return nil, probe.NewError(e) + } + if isRecursive { + if e := p.SetKeyStartsWith(object); e != nil { + return nil, probe.NewError(e) + } + } else { + if e := p.SetKey(object); e != nil { + return nil, probe.NewError(e) + } + } + m, e := c.api.PresignedPostPolicy(p) + return m, probe.NewError(e) +} diff --git a/pkg/client/s3/s3_test.go b/pkg/client/s3/s3_test.go index a2f5d5fe..ae356bd5 100644 --- a/pkg/client/s3/s3_test.go +++ b/pkg/client/s3/s3_test.go @@ -38,12 +38,21 @@ type bucketHandler struct { func (h bucketHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { switch { case r.Method == "GET": + // Handler for incoming getBucketLocation request. + if _, ok := r.URL.Query()["location"]; ok { + response := []byte("") + w.Header().Set("Content-Length", strconv.Itoa(len(response))) + w.Write(response) + return + } switch { case r.URL.Path == "/": + // Handler for incoming ListBuckets request. response := []byte("bucket2015-05-20T23:05:09.230Zminiominio") w.Header().Set("Content-Length", strconv.Itoa(len(response))) w.Write(response) case r.URL.Path == "/bucket": + // Handler for incoming ListObjects request. response := []byte("259d04a13802ae09c7e41be50ccc6baaobject2015-05-21T18:24:21.097Z22061miniominioSTANDARDfalse1000testbucket") w.Header().Set("Content-Length", strconv.Itoa(len(response))) w.Write(response) @@ -51,6 +60,7 @@ func (h bucketHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { case r.Method == "PUT": switch { case r.URL.Path == h.resource: + // Handler for incoming SetBucketACL request. _, ok := r.URL.Query()["acl"] if ok { if r.Header.Get("x-amz-acl") != "public-read-write" { @@ -80,6 +90,7 @@ type objectHandler struct { func (h objectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { switch { case r.Method == "PUT": + // Handler for PUT object request. length, err := strconv.Atoi(r.Header.Get("Content-Length")) if err != nil { w.WriteHeader(http.StatusBadRequest) @@ -98,6 +109,7 @@ func (h objectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { w.Header().Set("ETag", "9af2f8218b150c351ad802c6f3d66abe") w.WriteHeader(http.StatusOK) case r.Method == "HEAD": + // Handler for Stat object request. if r.URL.Path != h.resource { w.WriteHeader(http.StatusNotFound) return @@ -106,7 +118,45 @@ func (h objectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { w.Header().Set("Last-Modified", time.Now().UTC().Format(http.TimeFormat)) w.Header().Set("ETag", "9af2f8218b150c351ad802c6f3d66abe") w.WriteHeader(http.StatusOK) + case r.Method == "POST": + // Handler for multipart upload request. + if _, ok := r.URL.Query()["uploads"]; ok { + if r.URL.Path == h.resource { + response := []byte("bucketobjectEXAMPLEJZ6e0YupT2h66iePQCc9IEbYbDUy4RTpMeoSMLPRp8Z5o1u8feSRonpvnWsKKG35tI2LB9VDPiCgTy.Gq2VxQLYjrue4Nq.NBdqI-") + w.Header().Set("Content-Length", strconv.Itoa(len(response))) + w.Write(response) + return + } + } + if _, ok := r.URL.Query()["uploadId"]; ok { + if r.URL.Path == h.resource { + response := []byte("http://bucket.s3.amazonaws.com/objectbucketobject\"3858f62230ac3c915f300c664312c11f-9\"") + w.Header().Set("Content-Length", strconv.Itoa(len(response))) + w.Write(response) + return + } + } + if r.URL.Path != h.resource { + w.WriteHeader(http.StatusNotFound) + return + } case r.Method == "GET": + // Handler for get bucket location request. + if _, ok := r.URL.Query()["location"]; ok { + response := []byte("") + w.Header().Set("Content-Length", strconv.Itoa(len(response))) + w.Write(response) + return + } + // Handler for list multipart upload request. + if _, ok := r.URL.Query()["uploads"]; ok { + if r.URL.Path == "/bucket" { + response := []byte("bucket1000false") + w.Header().Set("Content-Length", strconv.Itoa(len(response))) + w.Write(response) + return + } + } if r.URL.Path != h.resource { w.WriteHeader(http.StatusNotFound) return @@ -125,6 +175,7 @@ type MySuite struct{} var _ = Suite(&MySuite{}) +// Test bucket operations. func (s *MySuite) TestBucketOperations(c *C) { bucket := bucketHandler(bucketHandler{ resource: "/bucket", @@ -134,10 +185,13 @@ func (s *MySuite) TestBucketOperations(c *C) { conf := new(client.Config) conf.HostURL = server.URL + bucket.resource + conf.AccessKey = "WLGDGYAQYIGI833EV05A" + conf.SecretKey = "BYvgJM101sHngl2uzjXS/OBF/aMxAN06JrJ3qJlF" + conf.Signature = "S3v4" s3c, err := New(conf) c.Assert(err, IsNil) - err = s3c.MakeBucket() + err = s3c.MakeBucket("us-east-1") c.Assert(err, IsNil) err = s3c.SetBucketAccess("public-read-write") @@ -171,6 +225,7 @@ func (s *MySuite) TestBucketOperations(c *C) { } } +// Test all object operations. func (s *MySuite) TestObjectOperations(c *C) { object := objectHandler(objectHandler{ resource: "/bucket/object", @@ -181,18 +236,24 @@ func (s *MySuite) TestObjectOperations(c *C) { conf := new(client.Config) conf.HostURL = server.URL + object.resource + conf.AccessKey = "WLGDGYAQYIGI833EV05A" + conf.SecretKey = "BYvgJM101sHngl2uzjXS/OBF/aMxAN06JrJ3qJlF" + conf.Signature = "S3v4" s3c, err := New(conf) c.Assert(err, IsNil) - err = s3c.Put(bytes.NewReader(object.data), int64(len(object.data)), "application/octet-stream") + var reader io.Reader + reader = bytes.NewReader(object.data) + n, err := s3c.Put(reader, int64(len(object.data)), "application/octet-stream", nil) c.Assert(err, IsNil) + c.Assert(n, Equals, int64(len(object.data))) content, err := s3c.Stat() c.Assert(err, IsNil) c.Assert(content.Size, Equals, int64(len(object.data))) c.Assert(content.Type.IsRegular(), Equals, true) - reader, err := s3c.Get(0, 0) + reader, err = s3c.Get() var buffer bytes.Buffer { _, err := io.Copy(&buffer, reader) diff --git a/pkg/client/s3/trace_v2.go b/pkg/client/s3/trace_v2.go index a396061d..e67e32aa 100644 --- a/pkg/client/s3/trace_v2.go +++ b/pkg/client/s3/trace_v2.go @@ -58,7 +58,16 @@ func (t TraceV2) Request(req *http.Request) (err error) { // Response - Trace HTTP Response func (t TraceV2) Response(res *http.Response) (err error) { - resTrace, err := httputil.DumpResponse(res, false) // Only display header + var resTrace []byte + // For errors we make sure to dump response body as well. + if res.StatusCode != http.StatusOK && + res.StatusCode != http.StatusPartialContent && + res.StatusCode != http.StatusNoContent { + resTrace, err = httputil.DumpResponse(res, true) + } else { + // Only display header + resTrace, err = httputil.DumpResponse(res, false) + } if err == nil { console.Debug(string(resTrace)) } diff --git a/pkg/client/s3/trace_v4.go b/pkg/client/s3/trace_v4.go index 777ed5c1..27c07d59 100644 --- a/pkg/client/s3/trace_v4.go +++ b/pkg/client/s3/trace_v4.go @@ -67,7 +67,16 @@ func (t TraceV4) Request(req *http.Request) (err error) { // Response - Trace HTTP Response func (t TraceV4) Response(res *http.Response) (err error) { - resTrace, err := httputil.DumpResponse(res, false) // Only display header + var resTrace []byte + // For errors we make sure to dump response body as well. + if res.StatusCode != http.StatusOK && + res.StatusCode != http.StatusPartialContent && + res.StatusCode != http.StatusNoContent { + resTrace, err = httputil.DumpResponse(res, true) + } else { + // Only display header + resTrace, err = httputil.DumpResponse(res, false) + } if err == nil { console.Debug(string(resTrace)) } diff --git a/pkg/hookreader/hookreader.go b/pkg/hookreader/hookreader.go new file mode 100644 index 00000000..adea3436 --- /dev/null +++ b/pkg/hookreader/hookreader.go @@ -0,0 +1,54 @@ +/* + * Minio Client (C) 2016 Minio, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Package hookreader hooks additional reader in the source +// stream. It is useful for making progress bars. Second reader is +// appropriately notified about the exact number of bytes read from +// the primary source on each Read operation. +package hookreader + +import "io" + +type hookReader struct { + source io.Reader + hook io.Reader +} + +// Read implements io.Reader. Always reads from the source, the return +// value 'n' number of bytes are reported through the hook. Returns +// error for all non io.EOF conditions. +func (hr *hookReader) Read(b []byte) (n int, err error) { + n, err = hr.source.Read(b) + if err != nil && err != io.EOF { + return n, err + } + // Progress the hook with the total read bytes from the source. + if _, herr := hr.hook.Read(b[:n]); herr != nil { + if herr != io.EOF { + return n, herr + } + } + return n, err +} + +// NewHook returns a io.Reader which implements hookReader that +// reports the data read from the source to the hook. +func NewHook(source, hook io.Reader) io.Reader { + if hook == nil { + return source + } + return &hookReader{source, hook} +} diff --git a/pkg/hookreader/hookreader_test.go b/pkg/hookreader/hookreader_test.go new file mode 100644 index 00000000..6df86778 --- /dev/null +++ b/pkg/hookreader/hookreader_test.go @@ -0,0 +1,55 @@ +/* + * Minio Client (C) 2016 Minio, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package hookreader + +import ( + "bytes" + "testing" + + . "gopkg.in/check.v1" +) + +func Test(t *testing.T) { TestingT(t) } + +type MySuite struct{} + +var _ = Suite(&MySuite{}) + +// customReader - implements custom progress reader. +type customReader struct { + readBytes int +} + +func (c *customReader) Read(b []byte) (n int, err error) { + c.readBytes += len(b) + return len(b), nil +} + +// Tests hook reader implementation. +func (s *MySuite) TestHookReader(c *C) { + var buffer bytes.Buffer + writer := &buffer + _, err := writer.Write([]byte("Hello")) + c.Assert(err, IsNil) + progress := &customReader{} + reader := NewHook(&buffer, progress) + b := make([]byte, 3) + n, err := reader.Read(b) + c.Assert(err, IsNil) + c.Assert(n, Equals, 3) + c.Assert(progress.readBytes, Equals, 3) +} diff --git a/progress-bar.go b/progress-bar.go index b4399aba..34ba148f 100644 --- a/progress-bar.go +++ b/progress-bar.go @@ -28,87 +28,77 @@ import ( "github.com/minio/mc/pkg/console" ) -// pbBar type of operation. -type pbBar int - -// collection of different progress bar operations. -const ( - pbBarProgress pbBar = iota - pbBarFinish - pbBarPutError - pbBarGetError - pbBarSetCaption -) - -// proxyReader progress bar proxy reader for barSend inherits io.ReadCloser. -type proxyReader struct { - io.ReadSeeker - bar *barSend +// progress extender. +type progressBar struct { + ProgressBar *pb.ProgressBar + reader io.Reader + readerLength int64 + bytesRead int64 + isResume bool } -// Read proxy Read sends progress for each Read operation. -func (r *proxyReader) Read(p []byte) (n int, err error) { - n, err = r.ReadSeeker.Read(p) - if err != nil { - if err != io.EOF { - return - } +// newProgressBar - instantiate a progress bar. +func newProgressBar(total int64) *progressBar { + // Progress bar speific theme customization. + console.SetColor("Bar", color.New(color.FgGreen, color.Bold)) + + pgbar := progressBar{} + + // get the new original progress bar. + bar := pb.New64(total) + + // Set new human friendly print units. + bar.SetUnits(pb.U_BYTES) + + // Refresh rate for progress bar is set to 125 milliseconds. + bar.SetRefreshRate(time.Millisecond * 125) + + // Do not print a newline by default handled, it is handled manually. + bar.NotPrint = true + + // Show current speed is true. + bar.ShowSpeed = true + + // Custom callback with colorized bar. + bar.Callback = func(s string) { + console.Print(console.Colorize("Bar", "\r"+s)) } - r.bar.Progress(int64(n)) - return -} -func (r *proxyReader) Seek(offset int64, whence int) (n int64, err error) { - n, err = r.ReadSeeker.Seek(offset, whence) - if err != nil { - return + // Use different unicodes for Linux, OS X and Windows. + switch runtime.GOOS { + case "linux": + // Need to add '\x00' as delimiter for unicode characters. + bar.Format("┃\x00▓\x00█\x00░\x00┃") + case "darwin": + // Need to add '\x00' as delimiter for unicode characters. + bar.Format(" \x00▓\x00 \x00░\x00 ") + default: + // Default to non unicode characters. + bar.Format("[=> ]") } - r.bar.Progress(n) - return + + // Start the progress bar. + if bar.Total > 0 { + bar.Start() + } + + // Copy for future + pgbar.ProgressBar = bar + + // Return new progress bar here. + return &pgbar } -// barMsg progress bar message for a given operation. -type barMsg struct { - Op pbBar - Arg interface{} +// Set caption. +func (p *progressBar) SetCaption(caption string) *progressBar { + caption = fixateBarCaption(caption, getFixedWidth(p.ProgressBar.GetWidth(), 18)) + p.ProgressBar.Prefix(caption) + return p } -// barSend implements various methods for progress bar operation. -type barSend struct { - opCh chan<- barMsg - finishCh <-chan bool -} - -// Instantiate a new progress bar proxy reader. -func (b *barSend) NewProxyReader(r io.ReadSeeker) *proxyReader { - return &proxyReader{r, b} -} - -// Progress send current progress message. -func (b barSend) Progress(progress int64) { - b.opCh <- barMsg{Op: pbBarProgress, Arg: progress} -} - -// ErrorPut send message for error in put operation. -func (b barSend) ErrorPut(size int64) { - b.opCh <- barMsg{Op: pbBarPutError, Arg: size} -} - -// ErrorGet send message for error in get operation. -func (b barSend) ErrorGet(size int64) { - b.opCh <- barMsg{Op: pbBarGetError, Arg: size} -} - -// SetCaption set an additional prefix/caption for an active progress bar. -func (b *barSend) SetCaption(c string) { - b.opCh <- barMsg{Op: pbBarSetCaption, Arg: c} -} - -// Finish finishes the progress bar and closes the message channel. -func (b barSend) Finish() { - defer close(b.opCh) - b.opCh <- barMsg{Op: pbBarFinish} - <-b.finishCh +func (p *progressBar) Set64(length int64) *progressBar { + p.ProgressBar = p.ProgressBar.Set64(length) + return p } // cursorAnimate - returns a animated rune through read channel for every read. @@ -124,9 +114,9 @@ func cursorAnimate() <-chan rune { // cursors = "←↖↑↗→↘↓↙" // cursors = "◴◷◶◵" // cursors = "◰◳◲◱" + //cursors = "⣾⣽⣻⢿⡿⣟⣯⣷" case "darwin": cursors = "◐◓◑◒" - //cursors = "⣾⣽⣻⢿⡿⣟⣯⣷" default: cursors = "|/-\\" } @@ -159,83 +149,3 @@ func fixateBarCaption(caption string, width int) string { func getFixedWidth(width, percent int) int { return width * percent / 100 } - -// newProgressBar - instantiate a progress bar. -func newProgressBar(total int64) *barSend { - // Progress bar speific theme customization. - console.SetColor("Bar", color.New(color.FgGreen, color.Bold)) - - cmdCh := make(chan barMsg) - finishCh := make(chan bool) - go func(total int64, cmdCh <-chan barMsg, finishCh chan<- bool) { - var started bool // has the progress bar started? default is false. - var totalBytesRead int64 // total amounts of bytes read - - // get the new original progress bar. - bar := pb.New64(total) - bar.SetUnits(pb.U_BYTES) - - // refresh rate for progress bar is set to 125 milliseconds. - bar.SetRefreshRate(time.Millisecond * 125) - - // Do not print a newline by default handled, it is handled manually. - bar.NotPrint = true - - // Show current speed is true. - bar.ShowSpeed = true - - // Custom callback with colorized bar. - bar.Callback = func(s string) { - console.Print(console.Colorize("Bar", "\r"+s)) - } - - // Use different unicodes for Linux, OS X and Windows. - switch runtime.GOOS { - case "linux": - bar.Format("┃▓█░┃") - // bar.Format("█▓▒░█") - case "darwin": - bar.Format(" ▓ ░ ") - default: - bar.Format("[=> ]") - } - - // Look for incoming progress bar messages. - for msg := range cmdCh { - switch msg.Op { - case pbBarSetCaption: - // Sets a new caption prefixed along with progress bar. - bar.Prefix(fixateBarCaption(msg.Arg.(string), getFixedWidth(bar.GetWidth(), 18))) - case pbBarProgress: - // Initializes the progerss bar, if already started bumps up the totalBytes. - if bar.Total > 0 && !started { - started = true - bar.Start() - } - if msg.Arg.(int64) > 0 { - totalBytesRead += msg.Arg.(int64) - bar.Add64(msg.Arg.(int64)) - } - case pbBarPutError: - // Negates any put error of size from totalBytes. - if totalBytesRead > msg.Arg.(int64) { - bar.Set64(totalBytesRead - msg.Arg.(int64)) - } - case pbBarGetError: - // Retains any size transferred but failed. - if msg.Arg.(int64) > 0 { - bar.Add64(msg.Arg.(int64)) - } - case pbBarFinish: - // Progress finishes here. - if started { - bar.Finish() - } - // All done send true. - finishCh <- true - return - } - } - }(total, cmdCh, finishCh) - return &barSend{cmdCh, finishCh} -} diff --git a/rm-main.go b/rm-main.go index 9a5eb118..5ffbe6d5 100644 --- a/rm-main.go +++ b/rm-main.go @@ -113,21 +113,13 @@ func checkRmSyntax(ctx *cli.Context) { // Set command flags from context. isForce := ctx.Bool("force") isRecursive := ctx.Bool("recursive") - isIncomplete := ctx.Bool("incomplete") if !ctx.Args().Present() { exitCode := 1 cli.ShowCommandHelpAndExit(ctx, "rm", exitCode) } - if !isRecursive && !isIncomplete { - for _, url := range ctx.Args() { - if _, _, err := url2Stat(url); err != nil { - fatalIf(err.Trace(url), "Unable to stat.") - } - } - } - + // For all recursive operations make sure to check for 'force' flag. if isRecursive && !isForce { fatalIf(errDummy().Trace(), "Recursive removal requires --force option. Please review carefully before performing this *DANGEROUS* operation.") diff --git a/share-download-main.go b/share-download-main.go index 4e5d62e3..679ea40e 100644 --- a/share-download-main.go +++ b/share-download-main.go @@ -99,7 +99,11 @@ func checkShareDownloadSyntax(ctx *cli.Context) { // doShareURL share files from target. func doShareDownloadURL(targetURL string, isRecursive bool, expiry time.Duration) *probe.Error { - clnt, err := newClient(targetURL) + targetAlias, targetURLFull, _, err := expandAlias(targetURL) + if err != nil { + return err.Trace(targetURL) + } + clnt, err := newClientFromAlias(targetAlias, targetURLFull) if err != nil { return err.Trace(targetURL) } @@ -123,7 +127,7 @@ func doShareDownloadURL(targetURL string, isRecursive bool, expiry time.Duration continue } objectURL := content.URL.String() - newClnt, err := newClient(objectURL) + newClnt, err := newClientFromAlias(targetAlias, objectURL) if err != nil { return err.Trace(objectURL) } diff --git a/share-upload-main.go b/share-upload-main.go index 7ef3f6fe..d43bdc3d 100644 --- a/share-upload-main.go +++ b/share-upload-main.go @@ -163,6 +163,9 @@ func doShareUploadURL(objectURL string, isRecursive bool, expiry time.Duration, return err.Trace(objectURL, "expiry="+expiry.String(), "contentType="+contentType) } + // Get the new expanded url. + objectURL = clnt.GetURL().String() + // Generate curl command. curlCmd := makeCurlCmd(objectURL, isRecursive, uploadInfo) diff --git a/share.go b/share.go index 11e67e65..128f9d7e 100644 --- a/share.go +++ b/share.go @@ -100,7 +100,6 @@ func shareSetColor() { console.SetColor("Content-type", color.New(color.FgBlue)) console.SetColor("Share", color.New(color.FgGreen)) console.SetColor("File", color.New(color.FgRed, color.Bold)) - } // Get share dir name. diff --git a/vendor/github.com/minio/minio-go/MAINTAINERS.md b/vendor/github.com/minio/minio-go/MAINTAINERS.md new file mode 100644 index 00000000..6dbef626 --- /dev/null +++ b/vendor/github.com/minio/minio-go/MAINTAINERS.md @@ -0,0 +1,19 @@ +# For maintainers only + +## Responsibilities + +Please go through this link [Maintainer Responsibility](https://gist.github.com/abperiasamy/f4d9b31d3186bbd26522) + +### Making new releases + +Edit `libraryVersion` constant in `api.go`. + +``` +$ grep libraryVersion api.go + libraryVersion = "0.3.0" +``` + +``` +$ git tag 0.3.0 +$ git push --tags +``` \ No newline at end of file diff --git a/vendor/github.com/minio/minio-go/README.md b/vendor/github.com/minio/minio-go/README.md index e8ad533e..8e4da431 100644 --- a/vendor/github.com/minio/minio-go/README.md +++ b/vendor/github.com/minio/minio-go/README.md @@ -40,23 +40,20 @@ import ( ) func main() { - config := minio.Config{ - Endpoint: "https://s3.amazonaws.com", - AccessKeyID: "YOUR-ACCESS-KEY-HERE", - SecretAccessKey: "YOUR-PASSWORD-HERE", - } + // Requests are always secure (HTTPS) by default. Set insecure=true to enable insecure (HTTP) access. + // This boolean value is the last argument for New(). - // Default is Signature Version 4. To enable Signature Version 2 do the following. - // config.Signature = minio.SignatureV2 - - s3Client, err := minio.New(config) + // New returns an Amazon S3 compatible client object. API copatibality (v2 or v4) is automatically + // determined based on the Endpoint value. + s3Client, err := minio.New("s3.amazonaws.com", "YOUR-ACCESS-KEY-HERE", "YOUR-SECRET-KEY-HERE", false) if err != nil { log.Fatalln(err) } - for bucket := range s3Client.ListBuckets() { - if bucket.Err != nil { - log.Fatalln(bucket.Err) - } + buckets, err := s3Client.ListBuckets() + if err != nil { + log.Fatalln(err) + } + for _, bucket := range buckets { log.Println(bucket) } } @@ -65,23 +62,26 @@ func main() { ## Documentation ### Bucket Operations. -* [MakeBucket(bucketName, BucketACL) error](examples/s3/makebucket.go) +* [MakeBucket(bucketName, BucketACL, location) error](examples/s3/makebucket.go) * [BucketExists(bucketName) error](examples/s3/bucketexists.go) * [RemoveBucket(bucketName) error](examples/s3/removebucket.go) * [GetBucketACL(bucketName) (BucketACL, error)](examples/s3/getbucketacl.go) * [SetBucketACL(bucketName, BucketACL) error)](examples/s3/setbucketacl.go) -* [ListBuckets() <-chan BucketStat](examples/s3/listbuckets.go) -* [ListObjects(bucketName, prefix, recursive) <-chan ObjectStat](examples/s3/listobjects.go) -* [ListIncompleteUploads(bucketName, prefix, recursive) <-chan ObjectMultipartStat](examples/s3/listincompleteuploads.go) +* [ListBuckets() []BucketInfo](examples/s3/listbuckets.go) +* [ListObjects(bucketName, objectPrefix, recursive, chan<- struct{}) <-chan ObjectInfo](examples/s3/listobjects.go) +* [ListIncompleteUploads(bucketName, prefix, recursive, chan<- struct{}) <-chan ObjectMultipartInfo](examples/s3/listincompleteuploads.go) ### Object Operations. -* [PutObject(bucketName, objectName, contentType, io.ReadSeeker) error](examples/s3/putobject.go) -* [GetObject(bucketName, objectName) (io.ReadSeeker, error)](examples/s3/getobject.go) -* [GetPartialObject(bucketName, objectName, offset, length) (io.ReadSeeker, error)](examples/s3/getpartialobject.go) -* [StatObject(bucketName, objectName) (ObjectStat, error)](examples/s3/statobject.go) +* [PutObject(bucketName, objectName, io.Reader, contentType) error](examples/s3/putobject.go) +* [GetObject(bucketName, objectName) (*Object, error)](examples/s3/getobject.go) +* [StatObject(bucketName, objectName) (ObjectInfo, error)](examples/s3/statobject.go) * [RemoveObject(bucketName, objectName) error](examples/s3/removeobject.go) * [RemoveIncompleteUpload(bucketName, objectName) <-chan error](examples/s3/removeincompleteupload.go) +### File Object Operations. +* [FPutObject(bucketName, objectName, filePath, contentType) (size, error)](examples/s3/fputobject.go) +* [FGetObject(bucketName, objectName, filePath) error](examples/s3/fgetobject.go) + ### Presigned Operations. * [PresignedGetObject(bucketName, objectName, time.Duration) (string, error)](examples/s3/presignedgetobject.go) * [PresignedPutObject(bucketName, objectName, time.Duration) (string, error)](examples/s3/presignedputobject.go) diff --git a/vendor/github.com/minio/minio-go/api-definitions.go b/vendor/github.com/minio/minio-go/api-definitions.go index a33dd01b..43532de6 100644 --- a/vendor/github.com/minio/minio-go/api-definitions.go +++ b/vendor/github.com/minio/minio-go/api-definitions.go @@ -16,53 +16,56 @@ package minio -import ( - "io" - "time" -) +import "time" -// BucketStat container for bucket metadata. -type BucketStat struct { +// BucketInfo container for bucket metadata. +type BucketInfo struct { // The name of the bucket. - Name string + Name string `json:"name"` // Date the bucket was created. - CreationDate time.Time - // Error - Err error + CreationDate time.Time `json:"creationDate"` } -// ObjectStat container for object metadata. -type ObjectStat struct { - ETag string - Key string - LastModified time.Time - Size int64 - ContentType string +// 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. + + // Owner name. Owner struct { - DisplayName string - ID string - } + DisplayName string `json:"name"` + ID string `json:"id"` + } `json:"owner"` // The class of storage used to store the object. - StorageClass string + StorageClass string `json:"storageClass"` // Error - Err error + Err error `json:"-"` } -// ObjectMultipartStat container for multipart object metadata. -type ObjectMultipartStat struct { +// ObjectMultipartInfo container for multipart object metadata. +type ObjectMultipartInfo struct { // Date and time at which the multipart upload was initiated. Initiated time.Time `type:"timestamp" timestampFormat:"iso8601"` Initiator initiator Owner owner + // The type of storage to use for the object. Defaults to 'STANDARD'. StorageClass string // Key of the object for which the multipart upload was initiated. - Key string + Key string + + // Size in bytes of the object. Size int64 // Upload ID that identifies the multipart upload. @@ -71,24 +74,3 @@ type ObjectMultipartStat struct { // Error Err error } - -// partMetadata - container for each partMetadata. -type partMetadata struct { - MD5Sum []byte - Sha256Sum []byte - ReadCloser io.ReadCloser - Size int64 - Number int // partMetadata number. - - // Error - Err error -} - -// putObjectMetadata - container for each single PUT operation. -type putObjectMetadata struct { - MD5Sum []byte - Sha256Sum []byte - ReadCloser io.ReadCloser - Size int64 - ContentType string -} diff --git a/vendor/github.com/minio/minio-go/api-error-response.go b/vendor/github.com/minio/minio-go/api-error-response.go new file mode 100644 index 00000000..64716511 --- /dev/null +++ b/vendor/github.com/minio/minio-go/api-error-response.go @@ -0,0 +1,236 @@ +/* + * Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2015 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 + +import ( + "encoding/xml" + "fmt" + "net/http" + "strconv" +) + +/* **** SAMPLE ERROR RESPONSE **** + + + AccessDenied + Access Denied + bucketName + objectName + F19772218238A85A + GuWkjyviSiGHizehqpmsD1ndz5NClSP19DOT+s2mv7gXGQ8/X1lhbDGiIJEXpGFD + +*/ + +// ErrorResponse - Is the typed error returned by all API operations. +type ErrorResponse struct { + XMLName xml.Name `xml:"Error" json:"-"` + Code string + Message string + BucketName string + Key string + RequestID string `xml:"RequestId"` + HostID string `xml:"HostId"` + + // Region where the bucket is located. This header is returned + // only in HEAD bucket and ListObjects response. + AmzBucketRegion string +} + +// ToErrorResponse - Returns parsed ErrorResponse struct from body and +// http headers. +// +// For example: +// +// import s3 "github.com/minio/minio-go" +// ... +// ... +// reader, stat, err := s3.GetObject(...) +// if err != nil { +// resp := s3.ToErrorResponse(err) +// } +// ... +func ToErrorResponse(err error) ErrorResponse { + switch err := err.(type) { + case ErrorResponse: + return err + default: + return ErrorResponse{} + } +} + +// Error - Returns HTTP error string +func (e ErrorResponse) Error() string { + return e.Message +} + +// Common string for errors to report issue location in unexpected +// cases. +const ( + reportIssue = "Please report this issue at https://github.com/minio/minio-go/issues." +) + +// httpRespToErrorResponse returns a new encoded ErrorResponse +// structure as error. +func httpRespToErrorResponse(resp *http.Response, bucketName, objectName string) error { + if resp == nil { + msg := "Response is empty. " + reportIssue + 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 { + switch resp.StatusCode { + case http.StatusNotFound: + if objectName == "" { + errResp = ErrorResponse{ + 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"), + AmzBucketRegion: resp.Header.Get("x-amz-bucket-region"), + } + } else { + errResp = ErrorResponse{ + Code: "NoSuchKey", + 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"), + AmzBucketRegion: resp.Header.Get("x-amz-bucket-region"), + } + } + case http.StatusForbidden: + errResp = ErrorResponse{ + Code: "AccessDenied", + Message: "Access Denied.", + BucketName: bucketName, + Key: objectName, + RequestID: resp.Header.Get("x-amz-request-id"), + HostID: resp.Header.Get("x-amz-id-2"), + AmzBucketRegion: 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"), + AmzBucketRegion: 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"), + AmzBucketRegion: resp.Header.Get("x-amz-bucket-region"), + } + } + } + + // AccessDenied without a signature mismatch code, usually means + // that the bucket policy has certain restrictions where some API + // operations are not allowed. Handle this case so that top level + // callers can interpret this easily and fall back if needed to a + // lower functionality call. Read each individual API specific + // code for such fallbacks. + if errResp.Code == "AccessDenied" && errResp.Message == "Access Denied" { + errResp.Code = "NotImplemented" + errResp.Message = "Operation is not allowed according to your bucket policy." + } + return errResp +} + +// ErrEntityTooLarge - Input size is larger than supported maximum. +func ErrEntityTooLarge(totalSize, maxObjectSize int64, bucketName, objectName string) error { + msg := fmt.Sprintf("Your proposed upload size ‘%d’ exceeds the maximum allowed object size ‘%d’ for single PUT operation.", totalSize, maxObjectSize) + return ErrorResponse{ + Code: "EntityTooLarge", + Message: msg, + BucketName: bucketName, + Key: objectName, + } +} + +// ErrEntityTooSmall - Input size is smaller than supported minimum. +func ErrEntityTooSmall(totalSize int64, bucketName, objectName string) error { + msg := fmt.Sprintf("Your proposed upload size ‘%d’ is below the minimum allowed object size '0B' for single PUT operation.", totalSize) + return ErrorResponse{ + Code: "EntityTooLarge", + Message: msg, + BucketName: bucketName, + Key: objectName, + } +} + +// ErrUnexpectedEOF - Unexpected end of file reached. +func ErrUnexpectedEOF(totalRead, totalSize int64, bucketName, objectName string) error { + msg := fmt.Sprintf("Data read ‘%s’ is not equal to the size ‘%s’ of the input Reader.", + strconv.FormatInt(totalRead, 10), strconv.FormatInt(totalSize, 10)) + return ErrorResponse{ + Code: "UnexpectedEOF", + Message: msg, + BucketName: bucketName, + Key: objectName, + } +} + +// ErrInvalidBucketName - Invalid bucket name response. +func ErrInvalidBucketName(message string) error { + return ErrorResponse{ + Code: "InvalidBucketName", + Message: message, + RequestID: "minio", + } +} + +// ErrInvalidObjectName - Invalid object name response. +func ErrInvalidObjectName(message string) error { + return ErrorResponse{ + Code: "NoSuchKey", + Message: message, + RequestID: "minio", + } +} + +// ErrInvalidParts - Invalid number of parts. +func ErrInvalidParts(expectedParts, uploadedParts int) error { + msg := fmt.Sprintf("Unexpected number of parts found Want %d, Got %d", expectedParts, uploadedParts) + return ErrorResponse{ + Code: "InvalidParts", + Message: msg, + RequestID: "minio", + } +} + +// ErrInvalidObjectPrefix - Invalid object prefix response is +// similar to object name response. +var ErrInvalidObjectPrefix = ErrInvalidObjectName + +// ErrInvalidArgument - Invalid argument response. +func ErrInvalidArgument(message string) error { + return ErrorResponse{ + Code: "InvalidArgument", + Message: message, + RequestID: "minio", + } +} diff --git a/vendor/github.com/minio/minio-go/api-get-object-file.go b/vendor/github.com/minio/minio-go/api-get-object-file.go new file mode 100644 index 00000000..265a58ee --- /dev/null +++ b/vendor/github.com/minio/minio-go/api-get-object-file.go @@ -0,0 +1,104 @@ +/* + * Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2015 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 + +import ( + "io" + "os" + "path/filepath" +) + +// FGetObject - download contents of an object to a local file. +func (c Client) FGetObject(bucketName, objectName, filePath string) error { + // Input validation. + if err := isValidBucketName(bucketName); err != nil { + return err + } + if err := isValidObjectName(objectName); err != nil { + return err + } + + // Verify if destination already exists. + st, err := os.Stat(filePath) + if err == nil { + // If the destination exists and is a directory. + if st.IsDir() { + return ErrInvalidArgument("fileName is a directory.") + } + } + + // Proceed if file does not exist. return for all other errors. + if err != nil { + if !os.IsNotExist(err) { + return err + } + } + + // Extract top level direcotry. + objectDir, _ := filepath.Split(filePath) + if objectDir != "" { + // Create any missing top level directories. + if err := os.MkdirAll(objectDir, 0700); err != nil { + return err + } + } + + // Gather md5sum. + objectStat, err := c.StatObject(bucketName, objectName) + if err != nil { + return err + } + + // Write to a temporary file "fileName.part.minio" before saving. + filePartPath := filePath + objectStat.ETag + ".part.minio" + + // If exists, open in append mode. If not create it as a part file. + filePart, err := os.OpenFile(filePartPath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600) + if err != nil { + return err + } + + // Issue Stat to get the current offset. + st, err = filePart.Stat() + if err != nil { + return err + } + + // Seek to current position for incoming reader. + objectReader, objectStat, err := c.getObject(bucketName, objectName, st.Size(), 0) + if err != nil { + return err + } + + // Write to the part file. + if _, err = io.CopyN(filePart, objectReader, objectStat.Size); err != nil { + return err + } + + // Close the file before rename, this is specifically needed for Windows users. + if err = filePart.Close(); err != nil { + return err + } + + // Safely completed. Now commit by renaming to actual filename. + if err = os.Rename(filePartPath, filePath); err != nil { + return err + } + + // Return. + return nil +} diff --git a/vendor/github.com/minio/minio-go/api-get.go b/vendor/github.com/minio/minio-go/api-get.go new file mode 100644 index 00000000..56d44c9f --- /dev/null +++ b/vendor/github.com/minio/minio-go/api-get.go @@ -0,0 +1,537 @@ +/* + * Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2015 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 + +import ( + "errors" + "fmt" + "io" + "math" + "net/http" + "net/url" + "strings" + "sync" + "time" +) + +// GetBucketACL - Get the permissions on an existing bucket. +// +// Returned values are: +// +// private - Owner gets full access. +// public-read - Owner gets full access, others get read access. +// public-read-write - Owner gets full access, others get full access +// too. +// authenticated-read - Owner gets full access, authenticated users +// get read access. +func (c Client) GetBucketACL(bucketName string) (BucketACL, error) { + // Input validation. + if err := isValidBucketName(bucketName); err != nil { + return "", err + } + + // Set acl query. + urlValues := make(url.Values) + urlValues.Set("acl", "") + + // Instantiate a new request. + req, err := c.newRequest("GET", requestMetadata{ + bucketName: bucketName, + queryValues: urlValues, + }) + if err != nil { + return "", err + } + + // Initiate the request. + resp, err := c.do(req) + defer closeResponse(resp) + if err != nil { + return "", err + } + if resp != nil { + if resp.StatusCode != http.StatusOK { + return "", httpRespToErrorResponse(resp, bucketName, "") + } + } + + // Decode access control policy. + policy := accessControlPolicy{} + err = xmlDecoder(resp.Body, &policy) + if err != nil { + return "", err + } + + // We need to avoid following de-serialization check for Google + // Cloud Storage. On Google Cloud Storage "private" canned ACL's + // policy do not have grant list. Treat it as a valid case, check + // for all other vendors. + if !isGoogleEndpoint(c.endpointURL) { + if policy.AccessControlList.Grant == nil { + errorResponse := ErrorResponse{ + Code: "InternalError", + Message: "Access control Grant list is empty. " + reportIssue, + BucketName: bucketName, + RequestID: resp.Header.Get("x-amz-request-id"), + HostID: resp.Header.Get("x-amz-id-2"), + AmzBucketRegion: resp.Header.Get("x-amz-bucket-region"), + } + return "", errorResponse + } + } + + // Boolean cues to indentify right canned acls. + var publicRead, publicWrite, authenticatedRead bool + + // Handle grants. + grants := policy.AccessControlList.Grant + for _, g := range grants { + if g.Grantee.URI == "" && g.Permission == "FULL_CONTROL" { + continue + } + if g.Grantee.URI == "http://acs.amazonaws.com/groups/global/AuthenticatedUsers" && g.Permission == "READ" { + authenticatedRead = true + break + } else if g.Grantee.URI == "http://acs.amazonaws.com/groups/global/AllUsers" && g.Permission == "WRITE" { + publicWrite = true + } else if g.Grantee.URI == "http://acs.amazonaws.com/groups/global/AllUsers" && g.Permission == "READ" { + publicRead = true + } + } + + // Verify if acl is authenticated read. + if authenticatedRead { + return BucketACL("authenticated-read"), nil + } + // Verify if acl is private. + if !publicWrite && !publicRead { + return BucketACL("private"), nil + } + // Verify if acl is public-read. + if !publicWrite && publicRead { + return BucketACL("public-read"), nil + } + // Verify if acl is public-read-write. + if publicRead && publicWrite { + return BucketACL("public-read-write"), nil + } + + return "", ErrorResponse{ + Code: "NoSuchBucketPolicy", + Message: "The specified bucket does not have a bucket policy.", + BucketName: bucketName, + RequestID: "minio", + } +} + +// GetObject - returns an seekable, readable object. +func (c Client) GetObject(bucketName, objectName string) (*Object, error) { + // Input validation. + if err := isValidBucketName(bucketName); err != nil { + return nil, err + } + if err := isValidObjectName(objectName); err != nil { + return nil, err + } + // Send an explicit info to get the actual object size. + objectInfo, err := c.StatObject(bucketName, objectName) + if err != nil { + return nil, err + } + + // Create request channel. + reqCh := make(chan readRequest) + // Create response channel. + resCh := make(chan readResponse) + // Create done channel. + doneCh := make(chan struct{}) + + // This routine feeds partial object data as and when the caller + // reads. + go func() { + defer close(reqCh) + defer close(resCh) + + // Loop through the incoming control messages and read data. + for { + select { + // When the done channel is closed exit our routine. + case <-doneCh: + return + // Request message. + case req := <-reqCh: + // Get shortest length. + // NOTE: Last remaining bytes are usually smaller than + // req.Buffer size. Use that as the final length. + length := math.Min(float64(len(req.Buffer)), float64(objectInfo.Size-req.Offset)) + httpReader, _, err := c.getObject(bucketName, objectName, req.Offset, int64(length)) + if err != nil { + resCh <- readResponse{ + Error: err, + } + return + } + size, err := io.ReadFull(httpReader, req.Buffer) + if err == io.ErrUnexpectedEOF { + // If an EOF happens after reading some but not + // all the bytes ReadFull returns ErrUnexpectedEOF + err = io.EOF + } + resCh <- readResponse{ + Size: int(size), + Error: err, + } + } + } + }() + // Return the readerAt backed by routine. + return newObject(reqCh, resCh, doneCh, objectInfo), nil +} + +// Read response message container to reply back for the request. +type readResponse struct { + Size int + Error error +} + +// Read request message container to communicate with internal +// go-routine. +type readRequest struct { + Buffer []byte + Offset int64 // readAt offset. +} + +// Object represents an open object. It implements Read, ReadAt, +// Seeker, Close for a HTTP stream. +type Object struct { + // Mutex. + mutex *sync.Mutex + + // User allocated and defined. + reqCh chan<- readRequest + resCh <-chan readResponse + doneCh chan<- struct{} + currOffset int64 + objectInfo ObjectInfo + + // Keeps track of closed call. + isClosed bool + + // Previous error saved for future calls. + prevErr error +} + +// Read reads up to len(p) bytes into p. It returns the number of +// bytes read (0 <= n <= len(p)) and any error encountered. Returns +// io.EOF upon end of file. +func (o *Object) Read(b []byte) (n int, err error) { + if o == nil { + return 0, ErrInvalidArgument("Object is nil") + } + + // Locking. + o.mutex.Lock() + defer o.mutex.Unlock() + + // Previous prevErr is which was saved in previous operation. + if o.prevErr != nil || o.isClosed { + return 0, o.prevErr + } + + // If current offset has reached Size limit, return EOF. + if o.currOffset >= o.objectInfo.Size { + return 0, io.EOF + } + + // Send current information over control channel to indicate we + // are ready. + reqMsg := readRequest{} + + // Send the offset and pointer to the buffer over the channel. + reqMsg.Buffer = b + reqMsg.Offset = o.currOffset + + // Send read request over the control channel. + o.reqCh <- reqMsg + + // Get data over the response channel. + dataMsg := <-o.resCh + + // Bytes read. + bytesRead := int64(dataMsg.Size) + + // Update current offset. + o.currOffset += bytesRead + + if dataMsg.Error == nil { + // If currOffset read is equal to objectSize + // We have reached end of file, we return io.EOF. + if o.currOffset >= o.objectInfo.Size { + return dataMsg.Size, io.EOF + } + return dataMsg.Size, nil + } + + // Save any error. + o.prevErr = dataMsg.Error + return dataMsg.Size, dataMsg.Error +} + +// Stat returns the ObjectInfo structure describing object. +func (o *Object) Stat() (ObjectInfo, error) { + if o == nil { + return ObjectInfo{}, ErrInvalidArgument("Object is nil") + } + // Locking. + o.mutex.Lock() + defer o.mutex.Unlock() + + if o.prevErr != nil || o.isClosed { + return ObjectInfo{}, o.prevErr + } + + return o.objectInfo, nil +} + +// ReadAt reads len(b) bytes from the File starting at byte offset +// off. It returns the number of bytes read and the error, if any. +// ReadAt always returns a non-nil error when n < len(b). At end of +// file, that error is io.EOF. +func (o *Object) ReadAt(b []byte, offset int64) (n int, err error) { + if o == nil { + return 0, ErrInvalidArgument("Object is nil") + } + + // Locking. + o.mutex.Lock() + defer o.mutex.Unlock() + + // prevErr is which was saved in previous operation. + if o.prevErr != nil || o.isClosed { + return 0, o.prevErr + } + + // If offset is negative and offset is greater than or equal to + // object size we return EOF. + if offset < 0 || offset >= o.objectInfo.Size { + return 0, io.EOF + } + + // Send current information over control channel to indicate we + // are ready. + reqMsg := readRequest{} + + // Send the offset and pointer to the buffer over the channel. + reqMsg.Buffer = b + reqMsg.Offset = offset + + // Send read request over the control channel. + o.reqCh <- reqMsg + + // Get data over the response channel. + dataMsg := <-o.resCh + + // Bytes read. + bytesRead := int64(dataMsg.Size) + + if dataMsg.Error == nil { + // If offset+bytes read is equal to objectSize + // we have reached end of file, we return io.EOF. + if offset+bytesRead == o.objectInfo.Size { + return dataMsg.Size, io.EOF + } + return dataMsg.Size, nil + } + + // Save any error. + o.prevErr = dataMsg.Error + return dataMsg.Size, dataMsg.Error +} + +// Seek sets the offset for the next Read or Write to offset, +// interpreted according to whence: 0 means relative to the +// origin of the file, 1 means relative to the current offset, +// and 2 means relative to the end. +// Seek returns the new offset and an error, if any. +// +// Seeking to a negative offset is an error. Seeking to any positive +// offset is legal, subsequent io operations succeed until the +// underlying object is not closed. +func (o *Object) Seek(offset int64, whence int) (n int64, err error) { + if o == nil { + return 0, ErrInvalidArgument("Object is nil") + } + + // Locking. + o.mutex.Lock() + defer o.mutex.Unlock() + + if o.prevErr != nil { + // At EOF seeking is legal, for any other errors we return. + if o.prevErr != io.EOF { + return 0, o.prevErr + } + } + + // Negative offset is valid for whence of '2'. + if offset < 0 && whence != 2 { + return 0, ErrInvalidArgument(fmt.Sprintf("Negative position not allowed for %d.", whence)) + } + switch whence { + default: + return 0, ErrInvalidArgument(fmt.Sprintf("Invalid whence %d", whence)) + case 0: + if offset > o.objectInfo.Size { + return 0, io.EOF + } + o.currOffset = offset + case 1: + if o.currOffset+offset > o.objectInfo.Size { + return 0, io.EOF + } + o.currOffset += offset + case 2: + // Seeking to positive offset is valid for whence '2', but + // since we are backing a Reader we have reached 'EOF' if + // offset is positive. + if offset > 0 { + return 0, io.EOF + } + // Seeking to negative position not allowed for whence. + if o.objectInfo.Size+offset < 0 { + return 0, ErrInvalidArgument(fmt.Sprintf("Seeking at negative offset not allowed for %d", whence)) + } + o.currOffset += offset + } + // Return the effective offset. + return o.currOffset, nil +} + +// Close - The behavior of Close after the first call returns error +// for subsequent Close() calls. +func (o *Object) Close() (err error) { + if o == nil { + return ErrInvalidArgument("Object is nil") + } + // Locking. + o.mutex.Lock() + defer o.mutex.Unlock() + + // if already closed return an error. + if o.isClosed { + return o.prevErr + } + + // Close successfully. + close(o.doneCh) + + // Save for future operations. + errMsg := "Object is already closed. Bad file descriptor." + o.prevErr = errors.New(errMsg) + // Save here that we closed done channel successfully. + o.isClosed = true + return nil +} + +// newObject instantiates a new *minio.Object* +func newObject(reqCh chan<- readRequest, resCh <-chan readResponse, doneCh chan<- struct{}, objectInfo ObjectInfo) *Object { + return &Object{ + mutex: &sync.Mutex{}, + reqCh: reqCh, + resCh: resCh, + doneCh: doneCh, + objectInfo: objectInfo, + } +} + +// getObject - retrieve object from Object Storage. +// +// Additionally this function also takes range arguments to download the specified +// range bytes of an object. Setting offset and length = 0 will download the full object. +// +// For more information about the HTTP Range header. +// go to http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35. +func (c Client) getObject(bucketName, objectName string, offset, length int64) (io.ReadCloser, ObjectInfo, error) { + // Validate input arguments. + if err := isValidBucketName(bucketName); err != nil { + return nil, ObjectInfo{}, err + } + if err := isValidObjectName(objectName); err != nil { + return nil, ObjectInfo{}, err + } + + customHeader := make(http.Header) + // Set ranges if length and offset are valid. + if length > 0 && offset >= 0 { + customHeader.Set("Range", fmt.Sprintf("bytes=%d-%d", offset, offset+length-1)) + } else if offset > 0 && length == 0 { + customHeader.Set("Range", fmt.Sprintf("bytes=%d-", offset)) + } else if length < 0 && offset == 0 { + customHeader.Set("Range", fmt.Sprintf("bytes=%d", length)) + } + + // Instantiate a new request. + req, err := c.newRequest("GET", requestMetadata{ + bucketName: bucketName, + objectName: objectName, + customHeader: customHeader, + }) + if err != nil { + return nil, ObjectInfo{}, err + } + // Execute the request. + resp, err := c.do(req) + if err != nil { + return nil, ObjectInfo{}, err + } + if resp != nil { + if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusPartialContent { + return nil, ObjectInfo{}, httpRespToErrorResponse(resp, bucketName, objectName) + } + } + + // Trim off the odd double quotes from ETag in the beginning and end. + md5sum := strings.TrimPrefix(resp.Header.Get("ETag"), "\"") + md5sum = strings.TrimSuffix(md5sum, "\"") + + // Parse the date. + date, err := time.Parse(http.TimeFormat, resp.Header.Get("Last-Modified")) + if err != nil { + msg := "Last-Modified time format not recognized. " + reportIssue + return nil, ObjectInfo{}, ErrorResponse{ + Code: "InternalError", + Message: msg, + RequestID: resp.Header.Get("x-amz-request-id"), + HostID: resp.Header.Get("x-amz-id-2"), + AmzBucketRegion: resp.Header.Get("x-amz-bucket-region"), + } + } + // Get content-type. + contentType := strings.TrimSpace(resp.Header.Get("Content-Type")) + if contentType == "" { + contentType = "application/octet-stream" + } + var objectStat ObjectInfo + objectStat.ETag = md5sum + objectStat.Key = objectName + objectStat.Size = resp.ContentLength + objectStat.LastModified = date + objectStat.ContentType = contentType + + // do not close body here, caller will close + return resp.Body, objectStat, nil +} diff --git a/vendor/github.com/minio/minio-go/api-list.go b/vendor/github.com/minio/minio-go/api-list.go new file mode 100644 index 00000000..534ac4eb --- /dev/null +++ b/vendor/github.com/minio/minio-go/api-list.go @@ -0,0 +1,539 @@ +/* + * Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2015 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 + +import ( + "fmt" + "net/http" + "net/url" + "strings" +) + +// ListBuckets list all buckets owned by this authenticated user. +// +// This call requires explicit authentication, no anonymous requests are +// allowed for listing buckets. +// +// api := client.New(....) +// for message := range api.ListBuckets() { +// fmt.Println(message) +// } +// +func (c Client) ListBuckets() ([]BucketInfo, error) { + // Instantiate a new request. + req, err := c.newRequest("GET", requestMetadata{}) + if err != nil { + return nil, err + } + // Initiate the request. + resp, err := c.do(req) + defer closeResponse(resp) + if err != nil { + return nil, err + } + if resp != nil { + if resp.StatusCode != http.StatusOK { + return nil, httpRespToErrorResponse(resp, "", "") + } + } + listAllMyBucketsResult := listAllMyBucketsResult{} + err = xmlDecoder(resp.Body, &listAllMyBucketsResult) + if err != nil { + return nil, err + } + return listAllMyBucketsResult.Buckets.Bucket, nil +} + +// ListObjects - (List Objects) - List some objects or all recursively. +// +// ListObjects lists all objects matching the objectPrefix from +// the specified bucket. If recursion is enabled it would list +// all subdirectories and all its contents. +// +// Your input parameters are just bucketName, objectPrefix, recursive +// and a done channel for pro-actively closing the internal go +// routine. If you enable recursive as 'true' this function will +// return back all the objects in a given bucket name and object +// prefix. +// +// api := client.New(....) +// // Create a done channel. +// doneCh := make(chan struct{}) +// defer close(doneCh) +// // Recurively list all objects in 'mytestbucket' +// recursive := true +// for message := range api.ListObjects("mytestbucket", "starthere", recursive, doneCh) { +// fmt.Println(message) +// } +// +func (c Client) ListObjects(bucketName, objectPrefix string, recursive bool, doneCh <-chan struct{}) <-chan ObjectInfo { + // Allocate new list objects channel. + objectStatCh := make(chan ObjectInfo, 1000) + // Default listing is delimited at "/" + delimiter := "/" + if recursive { + // If recursive we do not delimit. + delimiter = "" + } + // Validate bucket name. + if err := isValidBucketName(bucketName); err != nil { + defer close(objectStatCh) + objectStatCh <- ObjectInfo{ + Err: err, + } + return objectStatCh + } + // Validate incoming object prefix. + if err := isValidObjectPrefix(objectPrefix); err != nil { + defer close(objectStatCh) + objectStatCh <- ObjectInfo{ + Err: err, + } + return objectStatCh + } + + // 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 := c.listObjectsQuery(bucketName, objectPrefix, 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 +} + +/// Bucket Read Operations. + +// listObjects - (List Objects) - List some or all (up to 1000) of the objects in a bucket. +// +// You can use the request parameters as selection criteria to return a subset of the objects in a bucket. +// request parameters :- +// --------- +// ?marker - Specifies the key to start with when listing objects in a bucket. +// ?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) listObjectsQuery(bucketName, objectPrefix, objectMarker, delimiter string, maxkeys int) (listBucketResult, error) { + // Validate bucket name. + if err := isValidBucketName(bucketName); err != nil { + return listBucketResult{}, err + } + // Validate object prefix. + if err := isValidObjectPrefix(objectPrefix); err != nil { + return listBucketResult{}, err + } + // Get resources properly escaped and lined up before + // using them in http request. + urlValues := make(url.Values) + // Set object prefix. + if objectPrefix != "" { + urlValues.Set("prefix", urlEncodePath(objectPrefix)) + } + // Set object marker. + if objectMarker != "" { + urlValues.Set("marker", urlEncodePath(objectMarker)) + } + // Set delimiter. + if delimiter != "" { + urlValues.Set("delimiter", delimiter) + } + + // maxkeys should default to 1000 or less. + if maxkeys == 0 || maxkeys > 1000 { + maxkeys = 1000 + } + // Set max keys. + urlValues.Set("max-keys", fmt.Sprintf("%d", maxkeys)) + + // Initialize a new request. + req, err := c.newRequest("GET", requestMetadata{ + bucketName: bucketName, + queryValues: urlValues, + }) + if err != nil { + return listBucketResult{}, err + } + // Execute list buckets. + resp, err := c.do(req) + defer closeResponse(resp) + if err != nil { + return listBucketResult{}, err + } + if resp != nil { + if resp.StatusCode != http.StatusOK { + return listBucketResult{}, httpRespToErrorResponse(resp, bucketName, "") + } + } + // Decode listBuckets XML. + listBucketResult := listBucketResult{} + err = xmlDecoder(resp.Body, &listBucketResult) + if err != nil { + return listBucketResult, err + } + return listBucketResult, nil +} + +// ListIncompleteUploads - List incompletely uploaded multipart objects. +// +// ListIncompleteUploads lists all incompleted objects matching the +// objectPrefix from the specified bucket. If recursion is enabled +// it would list all subdirectories and all its contents. +// +// Your input parameters are just bucketName, objectPrefix, recursive +// and a done channel to pro-actively close the internal go routine. +// If you enable recursive as 'true' this function will return back all +// the multipart objects in a given bucket name. +// +// api := client.New(....) +// // Create a done channel. +// doneCh := make(chan struct{}) +// defer close(doneCh) +// // Recurively list all objects in 'mytestbucket' +// recursive := true +// for message := range api.ListIncompleteUploads("mytestbucket", "starthere", recursive) { +// fmt.Println(message) +// } +// +func (c Client) ListIncompleteUploads(bucketName, objectPrefix string, recursive bool, doneCh <-chan struct{}) <-chan ObjectMultipartInfo { + // Turn on size aggregation of individual parts. + isAggregateSize := true + return c.listIncompleteUploads(bucketName, objectPrefix, recursive, isAggregateSize, doneCh) +} + +// listIncompleteUploads lists all incomplete uploads. +func (c Client) listIncompleteUploads(bucketName, objectPrefix string, recursive, aggregateSize bool, doneCh <-chan struct{}) <-chan ObjectMultipartInfo { + // Allocate channel for multipart uploads. + objectMultipartStatCh := make(chan ObjectMultipartInfo, 1000) + // Delimiter is set to "/" by default. + delimiter := "/" + if recursive { + // If recursive do not delimit. + delimiter = "" + } + // Validate bucket name. + if err := isValidBucketName(bucketName); err != nil { + defer close(objectMultipartStatCh) + objectMultipartStatCh <- ObjectMultipartInfo{ + Err: err, + } + return objectMultipartStatCh + } + // Validate incoming object prefix. + if err := isValidObjectPrefix(objectPrefix); err != nil { + defer close(objectMultipartStatCh) + objectMultipartStatCh <- ObjectMultipartInfo{ + Err: err, + } + return objectMultipartStatCh + } + go func(objectMultipartStatCh chan<- ObjectMultipartInfo) { + defer close(objectMultipartStatCh) + // object and upload ID marker for future requests. + var objectMarker string + var uploadIDMarker string + for { + // list all multipart uploads. + result, err := c.listMultipartUploadsQuery(bucketName, objectMarker, uploadIDMarker, objectPrefix, delimiter, 1000) + if err != nil { + objectMultipartStatCh <- ObjectMultipartInfo{ + Err: err, + } + return + } + // Save objectMarker and uploadIDMarker for next request. + objectMarker = result.NextKeyMarker + uploadIDMarker = result.NextUploadIDMarker + // Send all multipart uploads. + for _, obj := range result.Uploads { + // Calculate total size of the uploaded parts if 'aggregateSize' is enabled. + if aggregateSize { + // Get total multipart size. + obj.Size, err = c.getTotalMultipartSize(bucketName, obj.Key, obj.UploadID) + if err != nil { + objectMultipartStatCh <- ObjectMultipartInfo{ + Err: err, + } + } + } + select { + // Send individual uploads here. + case objectMultipartStatCh <- obj: + // If done channel 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 := ObjectMultipartInfo{} + object.Key = obj.Prefix + object.Size = 0 + select { + // Send delimited prefixes here. + case objectMultipartStatCh <- object: + // If done channel return here. + case <-doneCh: + return + } + } + // Listing ends if result not truncated, return right here. + if !result.IsTruncated { + return + } + } + }(objectMultipartStatCh) + // return. + return objectMultipartStatCh +} + +// listMultipartUploads - (List Multipart Uploads). +// - Lists some or all (up to 1000) in-progress multipart uploads in a bucket. +// +// You can use the request parameters as selection criteria to return a subset of the uploads in a bucket. +// request parameters. :- +// --------- +// ?key-marker - Specifies the multipart upload after which listing should begin. +// ?upload-id-marker - Together with key-marker specifies the multipart upload after which listing should begin. +// ?delimiter - A delimiter is a character you use to group keys. +// ?prefix - Limits the response to keys that begin with the specified prefix. +// ?max-uploads - Sets the maximum number of multipart uploads returned in the response body. +func (c Client) listMultipartUploadsQuery(bucketName, keyMarker, uploadIDMarker, prefix, delimiter string, maxUploads int) (listMultipartUploadsResult, error) { + // Get resources properly escaped and lined up before using them in http request. + urlValues := make(url.Values) + // Set uploads. + urlValues.Set("uploads", "") + // Set object key marker. + if keyMarker != "" { + urlValues.Set("key-marker", urlEncodePath(keyMarker)) + } + // Set upload id marker. + if uploadIDMarker != "" { + urlValues.Set("upload-id-marker", uploadIDMarker) + } + // Set prefix marker. + if prefix != "" { + urlValues.Set("prefix", urlEncodePath(prefix)) + } + // Set delimiter. + if delimiter != "" { + urlValues.Set("delimiter", delimiter) + } + + // maxUploads should be 1000 or less. + if maxUploads == 0 || maxUploads > 1000 { + maxUploads = 1000 + } + // Set max-uploads. + urlValues.Set("max-uploads", fmt.Sprintf("%d", maxUploads)) + + // Instantiate a new request. + req, err := c.newRequest("GET", requestMetadata{ + bucketName: bucketName, + queryValues: urlValues, + }) + if err != nil { + return listMultipartUploadsResult{}, err + } + // Execute list multipart uploads request. + resp, err := c.do(req) + defer closeResponse(resp) + if err != nil { + return listMultipartUploadsResult{}, err + } + if resp != nil { + if resp.StatusCode != http.StatusOK { + return listMultipartUploadsResult{}, httpRespToErrorResponse(resp, bucketName, "") + } + } + // Decode response body. + listMultipartUploadsResult := listMultipartUploadsResult{} + err = xmlDecoder(resp.Body, &listMultipartUploadsResult) + if err != nil { + return listMultipartUploadsResult, err + } + return listMultipartUploadsResult, nil +} + +// listObjectParts list all object parts recursively. +func (c Client) listObjectParts(bucketName, objectName, uploadID string) (partsInfo map[int]objectPart, err error) { + // Part number marker for the next batch of request. + var nextPartNumberMarker int + partsInfo = make(map[int]objectPart) + for { + // Get list of uploaded parts a maximum of 1000 per request. + listObjPartsResult, err := c.listObjectPartsQuery(bucketName, objectName, uploadID, nextPartNumberMarker, 1000) + if err != nil { + return nil, err + } + // Append to parts info. + for _, part := range listObjPartsResult.ObjectParts { + // Trim off the odd double quotes from ETag in the beginning and end. + part.ETag = strings.TrimPrefix(part.ETag, "\"") + part.ETag = strings.TrimSuffix(part.ETag, "\"") + partsInfo[part.PartNumber] = part + } + // Keep part number marker, for the next iteration. + nextPartNumberMarker = listObjPartsResult.NextPartNumberMarker + // Listing ends result is not truncated, return right here. + if !listObjPartsResult.IsTruncated { + break + } + } + + // Return all the parts. + return partsInfo, nil +} + +// findUploadID lists all incomplete uploads and finds the uploadID of the matching object name. +func (c Client) findUploadID(bucketName, objectName string) (uploadID string, err error) { + // Make list incomplete uploads recursive. + isRecursive := true + // Turn off size aggregation of individual parts, in this request. + isAggregateSize := false + // latestUpload to track the latest multipart info for objectName. + var latestUpload ObjectMultipartInfo + // Create done channel to cleanup the routine. + doneCh := make(chan struct{}) + defer close(doneCh) + // List all incomplete uploads. + for mpUpload := range c.listIncompleteUploads(bucketName, objectName, isRecursive, isAggregateSize, doneCh) { + if mpUpload.Err != nil { + return "", mpUpload.Err + } + if objectName == mpUpload.Key { + if mpUpload.Initiated.Sub(latestUpload.Initiated) > 0 { + latestUpload = mpUpload + } + } + } + // Return the latest upload id. + return latestUpload.UploadID, nil +} + +// getTotalMultipartSize - calculate total uploaded size for the a given multipart object. +func (c Client) getTotalMultipartSize(bucketName, objectName, uploadID string) (size int64, err error) { + // Iterate over all parts and aggregate the size. + partsInfo, err := c.listObjectParts(bucketName, objectName, uploadID) + if err != nil { + return 0, err + } + for _, partInfo := range partsInfo { + size += partInfo.Size + } + return size, nil +} + +// listObjectPartsQuery (List Parts query) +// - lists some or all (up to 1000) parts that have been uploaded +// for a specific multipart upload +// +// You can use the request parameters as selection criteria to return +// a subset of the uploads in a bucket, request parameters :- +// --------- +// ?part-number-marker - Specifies the part after which listing should +// begin. +// ?max-parts - Maximum parts to be listed per request. +func (c Client) listObjectPartsQuery(bucketName, objectName, uploadID string, partNumberMarker, maxParts int) (listObjectPartsResult, error) { + // Get resources properly escaped and lined up before using them in http request. + urlValues := make(url.Values) + // Set part number marker. + urlValues.Set("part-number-marker", fmt.Sprintf("%d", partNumberMarker)) + // Set upload id. + urlValues.Set("uploadId", uploadID) + + // maxParts should be 1000 or less. + if maxParts == 0 || maxParts > 1000 { + maxParts = 1000 + } + // Set max parts. + urlValues.Set("max-parts", fmt.Sprintf("%d", maxParts)) + + req, err := c.newRequest("GET", requestMetadata{ + bucketName: bucketName, + objectName: objectName, + queryValues: urlValues, + }) + if err != nil { + return listObjectPartsResult{}, err + } + // Exectue list object parts. + resp, err := c.do(req) + defer closeResponse(resp) + if err != nil { + return listObjectPartsResult{}, err + } + if resp != nil { + if resp.StatusCode != http.StatusOK { + return listObjectPartsResult{}, httpRespToErrorResponse(resp, bucketName, objectName) + } + } + // Decode list object parts XML. + listObjectPartsResult := listObjectPartsResult{} + err = xmlDecoder(resp.Body, &listObjectPartsResult) + if err != nil { + return listObjectPartsResult, err + } + return listObjectPartsResult, nil +} diff --git a/vendor/github.com/minio/minio-go/api-presigned.go b/vendor/github.com/minio/minio-go/api-presigned.go new file mode 100644 index 00000000..0f350d22 --- /dev/null +++ b/vendor/github.com/minio/minio-go/api-presigned.go @@ -0,0 +1,144 @@ +/* + * Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2015 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 + +import ( + "errors" + "time" +) + +// presignURL - Returns a presigned URL for an input 'method'. +// Expires maximum is 7days - ie. 604800 and minimum is 1. +func (c Client) presignURL(method string, bucketName string, objectName string, expires time.Duration) (url string, err error) { + // Input validation. + if err := isValidBucketName(bucketName); err != nil { + return "", err + } + if err := isValidObjectName(objectName); err != nil { + return "", err + } + if err := isValidExpiry(expires); err != nil { + return "", err + } + + if method == "" { + return "", ErrInvalidArgument("method cannot be empty.") + } + + expireSeconds := int64(expires / time.Second) + // Instantiate a new request. + // Since expires is set newRequest will presign the request. + req, err := c.newRequest(method, requestMetadata{ + presignURL: true, + bucketName: bucketName, + objectName: objectName, + expires: expireSeconds, + }) + if err != nil { + return "", err + } + return req.URL.String(), nil +} + +// PresignedGetObject - Returns a presigned URL to access an object without credentials. +// Expires maximum is 7days - ie. 604800 and minimum is 1. +func (c Client) PresignedGetObject(bucketName string, objectName string, expires time.Duration) (url string, err error) { + return c.presignURL("GET", bucketName, objectName, expires) +} + +// PresignedPutObject - Returns a presigned URL to upload an object without credentials. +// Expires maximum is 7days - ie. 604800 and minimum is 1. +func (c Client) PresignedPutObject(bucketName string, objectName string, expires time.Duration) (url string, err error) { + return c.presignURL("PUT", bucketName, objectName, expires) +} + +// PresignedPostPolicy - Returns POST form data to upload an object at a location. +func (c Client) PresignedPostPolicy(p *PostPolicy) (map[string]string, error) { + // Validate input arguments. + if p.expiration.IsZero() { + return nil, errors.New("Expiration time must be specified") + } + if _, ok := p.formData["key"]; !ok { + return nil, errors.New("object key must be specified") + } + if _, ok := p.formData["bucket"]; !ok { + return nil, errors.New("bucket name must be specified") + } + + bucketName := p.formData["bucket"] + // Fetch the bucket location. + location, err := c.getBucketLocation(bucketName) + if err != nil { + return nil, err + } + + // Keep time. + t := time.Now().UTC() + // For signature version '2' handle here. + if c.signature.isV2() { + policyBase64 := p.base64() + p.formData["policy"] = policyBase64 + // For Google endpoint set this value to be 'GoogleAccessId'. + if isGoogleEndpoint(c.endpointURL) { + p.formData["GoogleAccessId"] = c.accessKeyID + } else { + // For all other endpoints set this value to be 'AWSAccessKeyId'. + p.formData["AWSAccessKeyId"] = c.accessKeyID + } + // Sign the policy. + p.formData["signature"] = postPresignSignatureV2(policyBase64, c.secretAccessKey) + return p.formData, nil + } + + // Add date policy. + if err = p.addNewPolicy(policyCondition{ + matchType: "eq", + condition: "$x-amz-date", + value: t.Format(iso8601DateFormat), + }); err != nil { + return nil, err + } + + // Add algorithm policy. + if err = p.addNewPolicy(policyCondition{ + matchType: "eq", + condition: "$x-amz-algorithm", + value: signV4Algorithm, + }); err != nil { + return nil, err + } + + // Add a credential policy. + credential := getCredential(c.accessKeyID, location, t) + if err = p.addNewPolicy(policyCondition{ + matchType: "eq", + condition: "$x-amz-credential", + value: credential, + }); err != nil { + return nil, err + } + + // Get base64 encoded policy. + policyBase64 := p.base64() + // Fill in the form data. + p.formData["policy"] = policyBase64 + p.formData["x-amz-algorithm"] = signV4Algorithm + p.formData["x-amz-credential"] = credential + p.formData["x-amz-date"] = t.Format(iso8601DateFormat) + p.formData["x-amz-signature"] = postPresignSignatureV4(policyBase64, t, c.secretAccessKey, location) + return p.formData, nil +} diff --git a/vendor/github.com/minio/minio-go/api-put-bucket.go b/vendor/github.com/minio/minio-go/api-put-bucket.go new file mode 100644 index 00000000..f9431136 --- /dev/null +++ b/vendor/github.com/minio/minio-go/api-put-bucket.go @@ -0,0 +1,214 @@ +/* + * Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2015 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 + +import ( + "bytes" + "encoding/hex" + "encoding/xml" + "io/ioutil" + "net/http" + "net/url" +) + +/// Bucket operations + +// MakeBucket makes a new bucket. +// +// Optional arguments are acl and location - by default all buckets are created +// with ``private`` acl and in US Standard region. +// +// ACL valid values - http://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html +// +// private - owner gets full access [default]. +// public-read - owner gets full access, all others get read access. +// public-read-write - owner gets full access, all others get full access too. +// authenticated-read - owner gets full access, authenticated users get read access. +// +// 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, acl BucketACL, location string) error { + // Validate the input arguments. + if err := isValidBucketName(bucketName); err != nil { + return err + } + if !acl.isValidBucketACL() { + return ErrInvalidArgument("Unrecognized ACL " + acl.String()) + } + + // If location is empty, treat is a default region 'us-east-1'. + if location == "" { + location = "us-east-1" + } + + // Instantiate the request. + req, err := c.makeBucketRequest(bucketName, acl, location) + if err != nil { + return err + } + + // Execute the request. + resp, err := c.do(req) + defer closeResponse(resp) + if err != nil { + return err + } + + if resp != nil { + if resp.StatusCode != http.StatusOK { + return httpRespToErrorResponse(resp, bucketName, "") + } + } + + // Save the location into cache on a successfull makeBucket response. + c.bucketLocCache.Set(bucketName, location) + + // Return. + return nil +} + +// makeBucketRequest constructs request for makeBucket. +func (c Client) makeBucketRequest(bucketName string, acl BucketACL, location string) (*http.Request, error) { + // Validate input arguments. + if err := isValidBucketName(bucketName); err != nil { + return nil, err + } + if !acl.isValidBucketACL() { + return nil, ErrInvalidArgument("Unrecognized ACL " + acl.String()) + } + + // Set get bucket location always as path style. + targetURL := *c.endpointURL + if bucketName != "" { + // If endpoint supports virtual host style use that always. + // Currently only S3 and Google Cloud Storage would support this. + if isVirtualHostSupported(c.endpointURL, bucketName) { + targetURL.Host = bucketName + "." + c.endpointURL.Host + targetURL.Path = "/" + } else { + // If not fall back to using path style. + targetURL.Path = "/" + bucketName + } + } + + // get a new HTTP request for the method. + req, err := http.NewRequest("PUT", targetURL.String(), nil) + if err != nil { + return nil, err + } + + // by default bucket acl is set to private. + req.Header.Set("x-amz-acl", "private") + if acl != "" { + req.Header.Set("x-amz-acl", string(acl)) + } + + // set UserAgent for the request. + c.setUserAgent(req) + + // 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{}))) + } + + // If location is not 'us-east-1' create bucket location config. + if location != "us-east-1" && location != "" { + createBucketConfig := createBucketConfiguration{} + createBucketConfig.Location = location + var createBucketConfigBytes []byte + createBucketConfigBytes, err = xml.Marshal(createBucketConfig) + if err != nil { + return nil, err + } + createBucketConfigBuffer := bytes.NewBuffer(createBucketConfigBytes) + req.Body = ioutil.NopCloser(createBucketConfigBuffer) + req.ContentLength = int64(createBucketConfigBuffer.Len()) + if c.signature.isV4() { + req.Header.Set("X-Amz-Content-Sha256", hex.EncodeToString(sum256(createBucketConfigBuffer.Bytes()))) + } + } + + // Sign the request. + if c.signature.isV4() { + // Signature calculated for MakeBucket request should be for 'us-east-1', + // regardless of the bucket's location constraint. + req = signV4(*req, c.accessKeyID, c.secretAccessKey, "us-east-1") + } else if c.signature.isV2() { + req = signV2(*req, c.accessKeyID, c.secretAccessKey) + } + + // Return signed request. + return req, nil +} + +// SetBucketACL set the permissions on an existing bucket using access control lists (ACL). +// +// For example +// +// private - owner gets full access [default]. +// public-read - owner gets full access, all others get read access. +// public-read-write - owner gets full access, all others get full access too. +// authenticated-read - owner gets full access, authenticated users get read access. +func (c Client) SetBucketACL(bucketName string, acl BucketACL) error { + // Input validation. + if err := isValidBucketName(bucketName); err != nil { + return err + } + if !acl.isValidBucketACL() { + return ErrInvalidArgument("Unrecognized ACL " + acl.String()) + } + + // Set acl query. + urlValues := make(url.Values) + urlValues.Set("acl", "") + + // Add misc headers. + customHeader := make(http.Header) + + if acl != "" { + customHeader.Set("x-amz-acl", acl.String()) + } else { + customHeader.Set("x-amz-acl", "private") + } + + // Instantiate a new request. + req, err := c.newRequest("PUT", requestMetadata{ + bucketName: bucketName, + queryValues: urlValues, + customHeader: customHeader, + }) + if err != nil { + return err + } + + // Initiate the request. + resp, err := c.do(req) + defer closeResponse(resp) + if err != nil { + return err + } + + if resp != nil { + // if error return. + if resp.StatusCode != http.StatusOK { + return httpRespToErrorResponse(resp, bucketName, "") + } + } + + // return + return nil +} diff --git a/vendor/github.com/minio/minio-go/api-put-object-common.go b/vendor/github.com/minio/minio-go/api-put-object-common.go new file mode 100644 index 00000000..beab6d6c --- /dev/null +++ b/vendor/github.com/minio/minio-go/api-put-object-common.go @@ -0,0 +1,240 @@ +/* + * Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2015 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 + +import ( + "crypto/md5" + "crypto/sha256" + "hash" + "io" + "math" + "os" +) + +// Verify if reader is *os.File +func isFile(reader io.Reader) (ok bool) { + _, ok = reader.(*os.File) + return +} + +// Verify if reader is *minio.Object +func isObject(reader io.Reader) (ok bool) { + _, ok = reader.(*Object) + return +} + +// Verify if reader is a generic ReaderAt +func isReadAt(reader io.Reader) (ok bool) { + _, ok = reader.(io.ReaderAt) + return +} + +// shouldUploadPart - verify if part should be uploaded. +func shouldUploadPart(objPart objectPart, objectParts map[int]objectPart) bool { + // If part not found should upload the part. + uploadedPart, found := objectParts[objPart.PartNumber] + if !found { + return true + } + // if size mismatches should upload the part. + if objPart.Size != uploadedPart.Size { + return true + } + // if md5sum mismatches should upload the part. + if objPart.ETag == uploadedPart.ETag { + return true + } + return false +} + +// optimalPartInfo - calculate the optimal part info for a given +// object size. +// +// NOTE: Assumption here is that for any object to be uploaded to any S3 compatible +// object storage it will have the following parameters as constants. +// +// maxPartsCount - 10000 +// minPartSize - 5MiB +// maxMultipartPutObjectSize - 5TiB +// +func optimalPartInfo(objectSize int64) (totalPartsCount int, partSize int64, lastPartSize int64, err error) { + // object size is '-1' set it to 5TiB. + if objectSize == -1 { + objectSize = maxMultipartPutObjectSize + } + // object size is larger than supported maximum. + if objectSize > maxMultipartPutObjectSize { + err = ErrEntityTooLarge(objectSize, maxMultipartPutObjectSize, "", "") + return + } + // Use floats for part size for all calculations to avoid + // overflows during float64 to int64 conversions. + partSizeFlt := math.Ceil(float64(objectSize / maxPartsCount)) + partSizeFlt = math.Ceil(partSizeFlt/minPartSize) * minPartSize + // Total parts count. + totalPartsCount = int(math.Ceil(float64(objectSize) / partSizeFlt)) + // Part size. + partSize = int64(partSizeFlt) + // Last part size. + lastPartSize = objectSize - int64(totalPartsCount-1)*partSize + return totalPartsCount, partSize, lastPartSize, nil +} + +// hashCopyBuffer is identical to hashCopyN except that it stages +// through the provided buffer (if one is required) rather than +// allocating a temporary one. If buf is nil, one is allocated for 5MiB. +func (c Client) hashCopyBuffer(writer io.Writer, reader io.Reader, buf []byte) (md5Sum, sha256Sum []byte, size int64, err error) { + // MD5 and SHA256 hasher. + var hashMD5, hashSHA256 hash.Hash + // MD5 and SHA256 hasher. + hashMD5 = md5.New() + hashWriter := io.MultiWriter(writer, hashMD5) + if c.signature.isV4() { + hashSHA256 = sha256.New() + hashWriter = io.MultiWriter(writer, hashMD5, hashSHA256) + } + + // Allocate buf if not initialized. + if buf == nil { + buf = make([]byte, optimalReadBufferSize) + } + + // Using io.CopyBuffer to copy in large buffers, default buffer + // for io.Copy of 32KiB is too small. + size, err = io.CopyBuffer(hashWriter, reader, buf) + if err != nil { + return nil, nil, 0, err + } + + // Finalize md5 sum and sha256 sum. + md5Sum = hashMD5.Sum(nil) + if c.signature.isV4() { + sha256Sum = hashSHA256.Sum(nil) + } + return md5Sum, sha256Sum, size, err +} + +// hashCopyN - Calculates Md5sum and SHA256sum for up to partSize amount of bytes. +func (c Client) hashCopyN(writer io.Writer, reader io.Reader, partSize int64) (md5Sum, sha256Sum []byte, size int64, err error) { + // MD5 and SHA256 hasher. + var hashMD5, hashSHA256 hash.Hash + // MD5 and SHA256 hasher. + hashMD5 = md5.New() + hashWriter := io.MultiWriter(writer, hashMD5) + if c.signature.isV4() { + hashSHA256 = sha256.New() + hashWriter = io.MultiWriter(writer, hashMD5, hashSHA256) + } + + // Copies to input at writer. + size, err = io.CopyN(hashWriter, reader, partSize) + if err != nil { + // If not EOF return error right here. + if err != io.EOF { + return nil, nil, 0, err + } + } + + // Finalize md5shum and sha256 sum. + md5Sum = hashMD5.Sum(nil) + if c.signature.isV4() { + sha256Sum = hashSHA256.Sum(nil) + } + return md5Sum, sha256Sum, size, err +} + +// getUploadID - fetch upload id if already present for an object name +// or initiate a new request to fetch a new upload id. +func (c Client) getUploadID(bucketName, objectName, contentType string) (uploadID string, isNew bool, err error) { + // Input validation. + if err := isValidBucketName(bucketName); err != nil { + return "", false, err + } + if err := isValidObjectName(objectName); err != nil { + return "", false, err + } + + // Set content Type to default if empty string. + if contentType == "" { + contentType = "application/octet-stream" + } + + // Find upload id for previous upload for an object. + uploadID, err = c.findUploadID(bucketName, objectName) + if err != nil { + return "", false, err + } + if uploadID == "" { + // Initiate multipart upload for an object. + initMultipartUploadResult, err := c.initiateMultipartUpload(bucketName, objectName, contentType) + if err != nil { + return "", false, err + } + // Save the new upload id. + uploadID = initMultipartUploadResult.UploadID + // Indicate that this is a new upload id. + isNew = true + } + return uploadID, isNew, nil +} + +// computeHashBuffer - Calculates MD5 and SHA256 for an input read +// Seeker is identical to computeHash except that it stages +// through the provided buffer (if one is required) rather than +// allocating a temporary one. If buf is nil, it uses a temporary +// buffer. +func (c Client) computeHashBuffer(reader io.ReadSeeker, buf []byte) (md5Sum, sha256Sum []byte, size int64, err error) { + // MD5 and SHA256 hasher. + var hashMD5, hashSHA256 hash.Hash + // MD5 and SHA256 hasher. + hashMD5 = md5.New() + hashWriter := io.MultiWriter(hashMD5) + if c.signature.isV4() { + hashSHA256 = sha256.New() + hashWriter = io.MultiWriter(hashMD5, hashSHA256) + } + + // If no buffer is provided, no need to allocate just use io.Copy. + if buf == nil { + size, err = io.Copy(hashWriter, reader) + if err != nil { + return nil, nil, 0, err + } + } else { + size, err = io.CopyBuffer(hashWriter, reader, buf) + if err != nil { + return nil, nil, 0, err + } + } + + // Seek back reader to the beginning location. + if _, err := reader.Seek(0, 0); err != nil { + return nil, nil, 0, err + } + + // Finalize md5shum and sha256 sum. + md5Sum = hashMD5.Sum(nil) + if c.signature.isV4() { + sha256Sum = hashSHA256.Sum(nil) + } + return md5Sum, sha256Sum, size, nil +} + +// computeHash - Calculates MD5 and SHA256 for an input read Seeker. +func (c Client) computeHash(reader io.ReadSeeker) (md5Sum, sha256Sum []byte, size int64, err error) { + return c.computeHashBuffer(reader, nil) +} 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 new file mode 100644 index 00000000..b7fa86fd --- /dev/null +++ b/vendor/github.com/minio/minio-go/api-put-object-file.go @@ -0,0 +1,240 @@ +/* + * Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2015 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 + +import ( + "encoding/hex" + "fmt" + "io" + "io/ioutil" + "os" + "sort" +) + +// FPutObject - Create an object in a bucket, with contents from file at filePath. +func (c Client) FPutObject(bucketName, objectName, filePath, contentType string) (n int64, err error) { + // Input validation. + if err := isValidBucketName(bucketName); err != nil { + return 0, err + } + if err := isValidObjectName(objectName); err != nil { + return 0, err + } + + // Open the referenced file. + fileReader, err := os.Open(filePath) + // If any error fail quickly here. + if err != nil { + return 0, err + } + defer fileReader.Close() + + // Save the file stat. + fileStat, err := fileReader.Stat() + if err != nil { + return 0, err + } + + // Save the file size. + fileSize := fileStat.Size() + + // Check for largest object size allowed. + if fileSize > int64(maxMultipartPutObjectSize) { + return 0, ErrEntityTooLarge(fileSize, maxMultipartPutObjectSize, bucketName, objectName) + } + + // NOTE: Google Cloud Storage multipart Put is not compatible with Amazon S3 APIs. + // Current implementation will only upload a maximum of 5GiB to Google Cloud Storage servers. + if isGoogleEndpoint(c.endpointURL) { + if fileSize > int64(maxSinglePutObjectSize) { + return 0, ErrorResponse{ + Code: "NotImplemented", + Message: fmt.Sprintf("Invalid Content-Length %d for file uploads to Google Cloud Storage.", fileSize), + Key: objectName, + BucketName: bucketName, + } + } + // Do not compute MD5 for Google Cloud Storage. Uploads up to 5GiB in size. + return c.putObjectNoChecksum(bucketName, objectName, fileReader, fileSize, contentType, nil) + } + + // NOTE: S3 doesn't allow anonymous multipart requests. + if 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, contentType, nil) + } + + // Small object upload is initiated for uploads for input data size smaller than 5MiB. + if fileSize < minPartSize { + return c.putObjectSingle(bucketName, objectName, fileReader, fileSize, contentType, nil) + } + // Upload all large objects as multipart. + n, err = c.putObjectMultipartFromFile(bucketName, objectName, fileReader, fileSize, contentType, nil) + if err != nil { + errResp := ToErrorResponse(err) + // Verify if multipart functionality is not available, if not + // fall back to single PutObject operation. + if errResp.Code == "NotImplemented" { + // If size of file is greater than '5GiB' fail. + if fileSize > maxSinglePutObjectSize { + return 0, ErrEntityTooLarge(fileSize, maxSinglePutObjectSize, bucketName, objectName) + } + // Fall back to uploading as single PutObject operation. + return c.putObjectSingle(bucketName, objectName, fileReader, fileSize, contentType, nil) + } + return n, err + } + return n, nil +} + +// putObjectMultipartFromFile - Creates object from contents of *os.File +// +// NOTE: This function is meant to be used for readers with local +// file as in *os.File. This function resumes by skipping all the +// necessary parts which were already uploaded by verifying them +// against MD5SUM of each individual parts. This function also +// effectively utilizes file system capabilities of reading from +// specific sections and not having to create temporary files. +func (c Client) putObjectMultipartFromFile(bucketName, objectName string, fileReader io.ReaderAt, fileSize int64, contentType 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 upload id for an object, initiates a new multipart request + // if it cannot find any previously partially uploaded object. + uploadID, isNew, err := c.getUploadID(bucketName, objectName, contentType) + 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 + + // Complete multipart upload. + var completeMultipartUpload completeMultipartUpload + + // A map of all uploaded parts. + var partsInfo = make(map[int]objectPart) + + // If this session is a continuation of a previous session fetch all + // previously uploaded parts info. + if !isNew { + // Fetch previously upload parts and maximum part size. + partsInfo, err = c.listObjectParts(bucketName, objectName, uploadID) + if err != nil { + return 0, err + } + } + + // Calculate the optimal parts info for a given size. + totalPartsCount, partSize, _, err := optimalPartInfo(fileSize) + if err != nil { + return 0, err + } + + // Part number always starts with '1'. + partNumber := 1 + + for partNumber <= totalPartsCount { + // Get a section reader on a particular offset. + sectionReader := io.NewSectionReader(fileReader, totalUploadedSize, partSize) + + // Calculates MD5 and SHA256 sum for a section reader. + var md5Sum, sha256Sum []byte + var prtSize int64 + md5Sum, sha256Sum, prtSize, err = c.computeHash(sectionReader) + if err != nil { + return 0, err + } + + var reader io.Reader + // Update progress reader appropriately to the latest offset + // as we read from the source. + reader = newHook(sectionReader, progress) + + // Verify if part should be uploaded. + if shouldUploadPart(objectPart{ + ETag: hex.EncodeToString(md5Sum), + PartNumber: partNumber, + Size: prtSize, + }, partsInfo) { + // Proceed to upload the part. + var objPart objectPart + objPart, err = c.uploadPart(bucketName, objectName, uploadID, ioutil.NopCloser(reader), partNumber, + md5Sum, sha256Sum, prtSize) + if err != nil { + return totalUploadedSize, err + } + // Save successfully uploaded part metadata. + partsInfo[partNumber] = objPart + } else { + // Update the progress reader for the skipped part. + if progress != nil { + if _, err = io.CopyN(ioutil.Discard, progress, prtSize); err != nil { + return totalUploadedSize, err + } + } + } + + // Save successfully uploaded size. + totalUploadedSize += prtSize + + // Increment part number. + partNumber++ + } + + // Verify if we uploaded all data. + if totalUploadedSize != fileSize { + return totalUploadedSize, ErrUnexpectedEOF(totalUploadedSize, fileSize, bucketName, objectName) + } + + // Loop over uploaded parts to save them in a Parts array before completing the multipart request. + for _, part := range partsInfo { + var complPart completePart + complPart.ETag = part.ETag + complPart.PartNumber = part.PartNumber + completeMultipartUpload.Parts = append(completeMultipartUpload.Parts, complPart) + } + + // Verify if totalPartsCount is not equal to total list of parts. + if totalPartsCount != len(completeMultipartUpload.Parts) { + return totalUploadedSize, ErrInvalidParts(partNumber, len(completeMultipartUpload.Parts)) + } + + // Sort all completed parts. + sort.Sort(completedParts(completeMultipartUpload.Parts)) + _, err = c.completeMultipartUpload(bucketName, objectName, uploadID, completeMultipartUpload) + if err != nil { + return totalUploadedSize, err + } + + // Return final size. + return totalUploadedSize, nil +} 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 new file mode 100644 index 00000000..ee001916 --- /dev/null +++ b/vendor/github.com/minio/minio-go/api-put-object-multipart.go @@ -0,0 +1,379 @@ +/* + * Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2015 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 + +import ( + "bytes" + "encoding/hex" + "encoding/xml" + "io" + "io/ioutil" + "net/http" + "net/url" + "os" + "sort" + "strconv" + "strings" +) + +// Comprehensive put object operation involving multipart resumable uploads. +// +// Following code handles these types of readers. +// +// - *os.File +// - *minio.Object +// - Any reader which has a method 'ReadAt()' +// +// If we exhaust all the known types, code proceeds to use stream as +// is where each part is re-downloaded, checksummed and verified +// before upload. +func (c Client) putObjectMultipart(bucketName, objectName string, reader io.Reader, size int64, contentType string, progress io.Reader) (n int64, err error) { + if size > 0 && size >= minPartSize { + // Verify if reader is *os.File, then use file system functionalities. + if isFile(reader) { + return c.putObjectMultipartFromFile(bucketName, objectName, reader.(*os.File), size, contentType, progress) + } + // Verify if reader is *minio.Object or io.ReaderAt. + // NOTE: Verification of object is kept for a specific purpose + // while it is going to be duck typed similar to io.ReaderAt. + // It is to indicate that *minio.Object implements io.ReaderAt. + // and such a functionality is used in the subsequent code + // path. + if isObject(reader) || isReadAt(reader) { + return c.putObjectMultipartFromReadAt(bucketName, objectName, reader.(io.ReaderAt), size, contentType, progress) + } + } + // For any other data size and reader type we do generic multipart + // approach by staging data in temporary files and uploading them. + return c.putObjectMultipartStream(bucketName, objectName, reader, size, contentType, progress) +} + +// putObjectStream uploads files bigger than 5MiB, and also supports +// special case where size is unknown i.e '-1'. +func (c Client) putObjectMultipartStream(bucketName, objectName string, reader io.Reader, size int64, contentType string, progress io.Reader) (n int64, err error) { + // Input validation. + if err := isValidBucketName(bucketName); err != nil { + return 0, err + } + if err := isValidObjectName(objectName); 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 + + // Complete multipart upload. + var complMultipartUpload completeMultipartUpload + + // A map of all previously uploaded parts. + var partsInfo = make(map[int]objectPart) + + // getUploadID for an object, initiates a new multipart request + // if it cannot find any previously partially uploaded object. + uploadID, isNew, err := c.getUploadID(bucketName, objectName, contentType) + if err != nil { + return 0, err + } + + // If This session is a continuation of a previous session fetch all + // previously uploaded parts info. + if !isNew { + // Fetch previously uploaded parts and maximum part size. + partsInfo, err = c.listObjectParts(bucketName, objectName, uploadID) + if err != nil { + return 0, err + } + } + + // Calculate the optimal parts info for a given size. + totalPartsCount, partSize, _, err := optimalPartInfo(size) + if err != nil { + return 0, err + } + + // Part number always starts with '1'. + partNumber := 1 + + // Initialize a temporary buffer. + tmpBuffer := new(bytes.Buffer) + + for partNumber <= totalPartsCount { + // Calculates MD5 and SHA256 sum while copying partSize bytes + // into tmpBuffer. + md5Sum, sha256Sum, prtSize, rErr := c.hashCopyN(tmpBuffer, reader, partSize) + if rErr != nil { + if rErr != io.EOF { + return 0, rErr + } + } + + var reader io.Reader + // Update progress reader appropriately to the latest offset + // as we read from the source. + reader = newHook(tmpBuffer, progress) + + // Verify if part should be uploaded. + if shouldUploadPart(objectPart{ + ETag: hex.EncodeToString(md5Sum), + PartNumber: partNumber, + Size: prtSize, + }, partsInfo) { + // Proceed to upload the part. + var objPart objectPart + objPart, err = c.uploadPart(bucketName, objectName, uploadID, ioutil.NopCloser(reader), partNumber, + md5Sum, sha256Sum, prtSize) + if err != nil { + // Reset the temporary buffer upon any error. + tmpBuffer.Reset() + return totalUploadedSize, err + } + // Save successfully uploaded part metadata. + partsInfo[partNumber] = objPart + } else { + // Update the progress reader for the skipped part. + if progress != nil { + if _, err = io.CopyN(ioutil.Discard, progress, prtSize); err != nil { + return totalUploadedSize, err + } + } + } + + // Reset the temporary buffer. + tmpBuffer.Reset() + + // Save successfully uploaded size. + totalUploadedSize += prtSize + + // For unknown size, Read EOF we break away. + // We do not have to upload till totalPartsCount. + if size < 0 && rErr == io.EOF { + break + } + + // Increment part number. + partNumber++ + } + + // Verify if we uploaded all the data. + if size > 0 { + if totalUploadedSize != size { + return totalUploadedSize, ErrUnexpectedEOF(totalUploadedSize, size, bucketName, objectName) + } + } + + // Loop over uploaded parts to save them in a Parts array before completing the multipart request. + for _, part := range partsInfo { + var complPart completePart + complPart.ETag = part.ETag + complPart.PartNumber = part.PartNumber + complMultipartUpload.Parts = append(complMultipartUpload.Parts, complPart) + } + + if size > 0 { + // Verify if totalPartsCount is not equal to total list of parts. + if totalPartsCount != len(complMultipartUpload.Parts) { + return totalUploadedSize, ErrInvalidParts(partNumber, len(complMultipartUpload.Parts)) + } + } + + // 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 +} + +// initiateMultipartUpload - Initiates a multipart upload and returns an upload ID. +func (c Client) initiateMultipartUpload(bucketName, objectName, contentType string) (initiateMultipartUploadResult, error) { + // Input validation. + if err := isValidBucketName(bucketName); err != nil { + return initiateMultipartUploadResult{}, err + } + if err := isValidObjectName(objectName); err != nil { + return initiateMultipartUploadResult{}, err + } + + // Initialize url queries. + urlValues := make(url.Values) + urlValues.Set("uploads", "") + + if contentType == "" { + contentType = "application/octet-stream" + } + + // Set ContentType header. + customHeader := make(http.Header) + customHeader.Set("Content-Type", contentType) + + reqMetadata := requestMetadata{ + bucketName: bucketName, + objectName: objectName, + queryValues: urlValues, + customHeader: customHeader, + } + + // Instantiate the request. + req, err := c.newRequest("POST", reqMetadata) + if err != nil { + return initiateMultipartUploadResult{}, err + } + + // Execute the request. + resp, err := c.do(req) + defer closeResponse(resp) + if err != nil { + return initiateMultipartUploadResult{}, err + } + if resp != nil { + if resp.StatusCode != http.StatusOK { + return initiateMultipartUploadResult{}, httpRespToErrorResponse(resp, bucketName, objectName) + } + } + // Decode xml for new multipart upload. + initiateMultipartUploadResult := initiateMultipartUploadResult{} + err = xmlDecoder(resp.Body, &initiateMultipartUploadResult) + if err != nil { + return initiateMultipartUploadResult, err + } + return initiateMultipartUploadResult, nil +} + +// uploadPart - Uploads a part in a multipart upload. +func (c Client) uploadPart(bucketName, objectName, uploadID string, reader io.ReadCloser, partNumber int, md5Sum, sha256Sum []byte, size int64) (objectPart, error) { + // Input validation. + if err := isValidBucketName(bucketName); err != nil { + return objectPart{}, err + } + if err := isValidObjectName(objectName); err != nil { + return objectPart{}, err + } + if size > maxPartSize { + return objectPart{}, ErrEntityTooLarge(size, maxPartSize, bucketName, objectName) + } + if size <= -1 { + return objectPart{}, ErrEntityTooSmall(size, bucketName, objectName) + } + if partNumber <= 0 { + return objectPart{}, ErrInvalidArgument("Part number cannot be negative or equal to zero.") + } + if uploadID == "" { + return objectPart{}, ErrInvalidArgument("UploadID cannot be empty.") + } + + // Get resources properly escaped and lined up before using them in http request. + urlValues := make(url.Values) + // Set part number. + urlValues.Set("partNumber", strconv.Itoa(partNumber)) + // Set upload id. + urlValues.Set("uploadId", uploadID) + + reqMetadata := requestMetadata{ + bucketName: bucketName, + objectName: objectName, + queryValues: urlValues, + contentBody: reader, + contentLength: size, + contentMD5Bytes: md5Sum, + contentSHA256Bytes: sha256Sum, + } + + // Instantiate a request. + req, err := c.newRequest("PUT", reqMetadata) + if err != nil { + return objectPart{}, err + } + // Execute the request. + resp, err := c.do(req) + defer closeResponse(resp) + if err != nil { + return objectPart{}, err + } + if resp != nil { + if resp.StatusCode != http.StatusOK { + return objectPart{}, httpRespToErrorResponse(resp, bucketName, objectName) + } + } + // Once successfully uploaded, return completed part. + objPart := objectPart{} + objPart.Size = size + objPart.PartNumber = partNumber + // Trim off the odd double quotes from ETag in the beginning and end. + objPart.ETag = strings.TrimPrefix(resp.Header.Get("ETag"), "\"") + objPart.ETag = strings.TrimSuffix(objPart.ETag, "\"") + return objPart, nil +} + +// completeMultipartUpload - Completes a multipart upload by assembling previously uploaded parts. +func (c Client) completeMultipartUpload(bucketName, objectName, uploadID string, complete completeMultipartUpload) (completeMultipartUploadResult, error) { + // Input validation. + if err := isValidBucketName(bucketName); err != nil { + return completeMultipartUploadResult{}, err + } + if err := isValidObjectName(objectName); err != nil { + return completeMultipartUploadResult{}, err + } + + // Initialize url queries. + urlValues := make(url.Values) + urlValues.Set("uploadId", uploadID) + + // Marshal complete multipart body. + completeMultipartUploadBytes, err := xml.Marshal(complete) + if err != nil { + return completeMultipartUploadResult{}, err + } + + // Instantiate all the complete multipart buffer. + completeMultipartUploadBuffer := bytes.NewBuffer(completeMultipartUploadBytes) + reqMetadata := requestMetadata{ + bucketName: bucketName, + objectName: objectName, + queryValues: urlValues, + contentBody: ioutil.NopCloser(completeMultipartUploadBuffer), + contentLength: int64(completeMultipartUploadBuffer.Len()), + contentSHA256Bytes: sum256(completeMultipartUploadBuffer.Bytes()), + } + + // Instantiate the request. + req, err := c.newRequest("POST", reqMetadata) + if err != nil { + return completeMultipartUploadResult{}, err + } + + // Execute the request. + resp, err := c.do(req) + defer closeResponse(resp) + if err != nil { + return completeMultipartUploadResult{}, err + } + if resp != nil { + if resp.StatusCode != http.StatusOK { + return completeMultipartUploadResult{}, httpRespToErrorResponse(resp, bucketName, objectName) + } + } + // Decode completed multipart upload response on success. + completeMultipartUploadResult := completeMultipartUploadResult{} + err = xmlDecoder(resp.Body, &completeMultipartUploadResult) + if err != nil { + return completeMultipartUploadResult, err + } + return completeMultipartUploadResult, nil +} 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 new file mode 100644 index 00000000..de3b348f --- /dev/null +++ b/vendor/github.com/minio/minio-go/api-put-object-progress.go @@ -0,0 +1,105 @@ +/* + * Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2015 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 + +import "io" + +// PutObjectWithProgress - With progress. +func (c Client) PutObjectWithProgress(bucketName, objectName string, reader io.Reader, contentType string, progress io.Reader) (n int64, err error) { + // Input validation. + if err := isValidBucketName(bucketName); err != nil { + return 0, err + } + if err := isValidObjectName(objectName); err != nil { + return 0, err + } + if reader == nil { + return 0, ErrInvalidArgument("Input reader is invalid, cannot be nil.") + } + + // 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) + } + + // 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. + if isGoogleEndpoint(c.endpointURL) { + if size <= -1 { + return 0, ErrorResponse{ + Code: "NotImplemented", + Message: "Content-Length cannot be negative for file uploads to Google Cloud Storage.", + Key: objectName, + BucketName: bucketName, + } + } + if size > maxSinglePutObjectSize { + return 0, ErrEntityTooLarge(size, maxSinglePutObjectSize, bucketName, objectName) + } + // Do not compute MD5 for Google Cloud Storage. Uploads up to 5GiB in size. + return c.putObjectNoChecksum(bucketName, objectName, reader, size, contentType, progress) + } + + // NOTE: S3 doesn't allow anonymous multipart requests. + if 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, contentType, progress) + } + + // putSmall object. + if size < minPartSize && size > 0 { + return c.putObjectSingle(bucketName, objectName, reader, size, contentType, progress) + } + // For all sizes greater than 5MiB do multipart. + n, err = c.putObjectMultipart(bucketName, objectName, reader, size, contentType, 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 == "NotImplemented" { + // 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.putObjectSingle(bucketName, objectName, reader, size, contentType, 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 new file mode 100644 index 00000000..ddb1ab3d --- /dev/null +++ b/vendor/github.com/minio/minio-go/api-put-object-readat.go @@ -0,0 +1,208 @@ +/* + * Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2015 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 + +import ( + "bytes" + "io" + "io/ioutil" + "sort" +) + +// shouldUploadPartReadAt - verify if part should be uploaded. +func shouldUploadPartReadAt(objPart objectPart, objectParts map[int]objectPart) bool { + // If part not found part should be uploaded. + uploadedPart, found := objectParts[objPart.PartNumber] + if !found { + return true + } + // if size mismatches part should be uploaded. + if uploadedPart.Size != objPart.Size { + return true + } + return false +} + +// putObjectMultipartFromReadAt - Uploads files bigger than 5MiB. Supports reader +// of type which implements io.ReaderAt interface (ReadAt method). +// +// NOTE: This function is meant to be used for all readers which +// implement io.ReaderAt which allows us for resuming multipart +// uploads but reading at an offset, which would avoid re-read the +// data which was already uploaded. Internally this function uses +// temporary files for staging all the data, these temporary files are +// cleaned automatically when the caller i.e http client closes the +// stream after uploading all the contents successfully. +func (c Client) putObjectMultipartFromReadAt(bucketName, objectName string, reader io.ReaderAt, size int64, contentType string, progress io.Reader) (n int64, err error) { + // Input validation. + if err := isValidBucketName(bucketName); err != nil { + return 0, err + } + if err := isValidObjectName(objectName); err != nil { + return 0, err + } + + // Get upload id for an object, initiates a new multipart request + // if it cannot find any previously partially uploaded object. + uploadID, isNew, err := c.getUploadID(bucketName, objectName, contentType) + 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 + + // Complete multipart upload. + var complMultipartUpload completeMultipartUpload + + // A map of all uploaded parts. + var partsInfo = make(map[int]objectPart) + + // Fetch all parts info previously uploaded. + if !isNew { + partsInfo, err = c.listObjectParts(bucketName, objectName, uploadID) + 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 + } + + // Used for readability, lastPartNumber is always + // totalPartsCount. + lastPartNumber := totalPartsCount + + // partNumber always starts with '1'. + partNumber := 1 + + // Initialize a temporary buffer. + tmpBuffer := new(bytes.Buffer) + + // Read defaults to reading at 5MiB buffer. + readBuffer := make([]byte, optimalReadBufferSize) + + // Upload all the missing parts. + for partNumber <= lastPartNumber { + // Verify object if its uploaded. + verifyObjPart := objectPart{ + PartNumber: partNumber, + Size: partSize, + } + // Special case if we see a last part number, save last part + // size as the proper part size. + if partNumber == lastPartNumber { + verifyObjPart = objectPart{ + PartNumber: lastPartNumber, + Size: lastPartSize, + } + } + + // Verify if part should be uploaded. + if !shouldUploadPartReadAt(verifyObjPart, partsInfo) { + // Increment part number when not uploaded. + partNumber++ + if progress != nil { + // Update the progress reader for the skipped part. + if _, err = io.CopyN(ioutil.Discard, progress, verifyObjPart.Size); err != nil { + return 0, err + } + } + continue + } + + // If partNumber was not uploaded we calculate the missing + // part offset and size. For all other part numbers we + // calculate offset based on multiples of partSize. + readOffset := int64(partNumber-1) * partSize + missingPartSize := partSize + + // As a special case if partNumber is lastPartNumber, we + // calculate the offset based on the last part size. + if partNumber == lastPartNumber { + readOffset = (size - lastPartSize) + missingPartSize = lastPartSize + } + + // Get a section reader on a particular offset. + sectionReader := io.NewSectionReader(reader, readOffset, missingPartSize) + + // Calculates MD5 and SHA256 sum for a section reader. + var md5Sum, sha256Sum []byte + var prtSize int64 + md5Sum, sha256Sum, prtSize, err = c.hashCopyBuffer(tmpBuffer, sectionReader, readBuffer) + if err != nil { + return 0, err + } + + var reader io.Reader + // Update progress reader appropriately to the latest offset + // as we read from the source. + reader = newHook(tmpBuffer, progress) + + // Proceed to upload the part. + var objPart objectPart + objPart, err = c.uploadPart(bucketName, objectName, uploadID, ioutil.NopCloser(reader), + partNumber, md5Sum, sha256Sum, prtSize) + if err != nil { + // Reset the buffer upon any error. + tmpBuffer.Reset() + return 0, err + } + + // Save successfully uploaded part metadata. + partsInfo[partNumber] = objPart + + // Increment part number here after successful part upload. + partNumber++ + + // Reset the buffer. + tmpBuffer.Reset() + } + + // Loop over uploaded parts to save them in a Parts array before completing the multipart request. + for _, part := range partsInfo { + var complPart completePart + complPart.ETag = part.ETag + complPart.PartNumber = part.PartNumber + totalUploadedSize += part.Size + complMultipartUpload.Parts = append(complMultipartUpload.Parts, complPart) + } + + // Verify if we uploaded all the data. + if totalUploadedSize != size { + return totalUploadedSize, ErrUnexpectedEOF(totalUploadedSize, size, bucketName, objectName) + } + + // Verify if totalPartsCount is not equal to total list of parts. + if totalPartsCount != len(complMultipartUpload.Parts) { + return totalUploadedSize, ErrInvalidParts(totalPartsCount, len(complMultipartUpload.Parts)) + } + + // 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 +} diff --git a/vendor/github.com/minio/minio-go/api-put-object.go b/vendor/github.com/minio/minio-go/api-put-object.go new file mode 100644 index 00000000..a09e658f --- /dev/null +++ b/vendor/github.com/minio/minio-go/api-put-object.go @@ -0,0 +1,287 @@ +/* + * Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2015 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 + +import ( + "bytes" + "io" + "io/ioutil" + "net/http" + "os" + "reflect" + "runtime" + "strings" +) + +// getReaderSize - Determine the size of Reader if available. +func getReaderSize(reader io.Reader) (size int64, err error) { + var result []reflect.Value + size = -1 + if reader != nil { + // Verify if there is a method by name 'Size'. + lenFn := reflect.ValueOf(reader).MethodByName("Size") + if lenFn.IsValid() { + if lenFn.Kind() == reflect.Func { + // Call the 'Size' function and save its return value. + result = lenFn.Call([]reflect.Value{}) + if result != nil && len(result) == 1 { + lenValue := result[0] + if lenValue.IsValid() { + switch lenValue.Kind() { + case reflect.Int: + fallthrough + case reflect.Int8: + fallthrough + case reflect.Int16: + fallthrough + case reflect.Int32: + fallthrough + case reflect.Int64: + size = lenValue.Int() + } + } + } + } + } else { + // Fallback to Stat() method, two possible Stat() structs + // exist. + switch v := reader.(type) { + case *os.File: + var st os.FileInfo + st, err = v.Stat() + if err != nil { + // Handle this case specially for "windows", + // certain files for example 'Stdin', 'Stdout' and + // 'Stderr' it is not allowed to fetch file information. + if runtime.GOOS == "windows" { + if strings.Contains(err.Error(), "GetFileInformationByHandle") { + return -1, nil + } + } + return + } + // Ignore if input is a directory, throw an error. + if st.Mode().IsDir() { + return -1, ErrInvalidArgument("Input file cannot be a directory.") + } + // Ignore 'Stdin', 'Stdout' and 'Stderr', since they + // represent *os.File type but internally do not + // 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": + return + } + size = st.Size() + case *Object: + var st ObjectInfo + st, err = v.Stat() + if err != nil { + return + } + size = st.Size + } + } + } + // Returns the size here. + return size, err +} + +// completedParts is a collection of parts sortable by their part numbers. +// used for sorting the uploaded parts before completing the multipart request. +type completedParts []completePart + +func (a completedParts) Len() int { return len(a) } +func (a completedParts) Swap(i, j int) { a[i], a[j] = a[j], a[i] } +func (a completedParts) Less(i, j int) bool { return a[i].PartNumber < a[j].PartNumber } + +// PutObject creates an object in a bucket. +// +// You must have WRITE permissions on a bucket to create an object. +// +// - For size smaller than 5MiB PutObject automatically does a single atomic Put operation. +// - For size larger than 5MiB PutObject automatically does a resumable multipart Put operation. +// - For size input as -1 PutObject does a multipart Put operation until input stream reaches EOF. +// Maximum object size that can be uploaded through this operation will be 5TiB. +// +// 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) +} + +// putObjectNoChecksum special function used Google Cloud Storage. This special function +// is used for Google Cloud Storage since Google's multipart API is not S3 compatible. +func (c Client) putObjectNoChecksum(bucketName, objectName string, reader io.Reader, size int64, contentType string, progress io.Reader) (n int64, err error) { + // Input validation. + if err := isValidBucketName(bucketName); err != nil { + return 0, err + } + if err := isValidObjectName(objectName); err != nil { + return 0, err + } + if size > maxSinglePutObjectSize { + return 0, ErrEntityTooLarge(size, maxSinglePutObjectSize, bucketName, objectName) + } + + // Update progress reader appropriately to the latest offset as we + // read from the source. + reader = newHook(reader, progress) + + // This function does not calculate sha256 and md5sum for payload. + // Execute put object. + st, err := c.putObjectDo(bucketName, objectName, ioutil.NopCloser(reader), nil, nil, size, contentType) + if err != nil { + return 0, err + } + if st.Size != size { + return 0, ErrUnexpectedEOF(st.Size, size, bucketName, objectName) + } + return size, nil +} + +// putObjectSingle is a special function for uploading single put object request. +// This special function is used as a fallback when multipart upload fails. +func (c Client) putObjectSingle(bucketName, objectName string, reader io.Reader, size int64, contentType string, progress io.Reader) (n int64, err error) { + // Input validation. + if err := isValidBucketName(bucketName); err != nil { + return 0, err + } + if err := isValidObjectName(objectName); err != nil { + return 0, err + } + if size > maxSinglePutObjectSize { + return 0, ErrEntityTooLarge(size, maxSinglePutObjectSize, bucketName, objectName) + } + // If size is a stream, upload up to 5GiB. + if size <= -1 { + size = maxSinglePutObjectSize + } + var md5Sum, sha256Sum []byte + var readCloser io.ReadCloser + if size <= minPartSize { + // Initialize a new temporary buffer. + tmpBuffer := new(bytes.Buffer) + md5Sum, sha256Sum, size, err = c.hashCopyN(tmpBuffer, reader, size) + readCloser = ioutil.NopCloser(tmpBuffer) + } else { + // Initialize a new temporary file. + var tmpFile *tempFile + tmpFile, err = newTempFile("single$-putobject-single") + if err != nil { + return 0, err + } + md5Sum, sha256Sum, size, err = c.hashCopyN(tmpFile, reader, size) + // Seek back to beginning of the temporary file. + if _, err = tmpFile.Seek(0, 0); err != nil { + return 0, err + } + readCloser = tmpFile + } + // Return error if its not io.EOF. + if err != nil { + if err != io.EOF { + return 0, err + } + } + // Progress the reader to the size. + if progress != nil { + if _, err = io.CopyN(ioutil.Discard, progress, size); err != nil { + return size, err + } + } + // Execute put object. + st, err := c.putObjectDo(bucketName, objectName, readCloser, md5Sum, sha256Sum, size, contentType) + if err != nil { + return 0, err + } + if st.Size != size { + return 0, ErrUnexpectedEOF(st.Size, size, bucketName, objectName) + } + return size, nil +} + +// putObjectDo - executes the put object http operation. +// NOTE: You must have WRITE permissions on a bucket to add an object to it. +func (c Client) putObjectDo(bucketName, objectName string, reader io.ReadCloser, md5Sum []byte, sha256Sum []byte, size int64, contentType string) (ObjectInfo, error) { + // Input validation. + if err := isValidBucketName(bucketName); err != nil { + return ObjectInfo{}, err + } + if err := isValidObjectName(objectName); err != nil { + return ObjectInfo{}, err + } + + if size <= -1 { + return ObjectInfo{}, ErrEntityTooSmall(size, bucketName, objectName) + } + + if size > maxSinglePutObjectSize { + return ObjectInfo{}, ErrEntityTooLarge(size, maxSinglePutObjectSize, bucketName, objectName) + } + + if strings.TrimSpace(contentType) == "" { + contentType = "application/octet-stream" + } + + // Set headers. + customHeader := make(http.Header) + customHeader.Set("Content-Type", contentType) + + // Populate request metadata. + reqMetadata := requestMetadata{ + bucketName: bucketName, + objectName: objectName, + customHeader: customHeader, + contentBody: reader, + contentLength: size, + contentMD5Bytes: md5Sum, + contentSHA256Bytes: sha256Sum, + } + // Initiate new request. + req, err := c.newRequest("PUT", reqMetadata) + if err != nil { + return ObjectInfo{}, err + } + // Execute the request. + resp, err := c.do(req) + defer closeResponse(resp) + if err != nil { + return ObjectInfo{}, err + } + if resp != nil { + if resp.StatusCode != http.StatusOK { + return ObjectInfo{}, httpRespToErrorResponse(resp, bucketName, objectName) + } + } + + var metadata ObjectInfo + // Trim off the odd double quotes from ETag in the beginning and end. + metadata.ETag = strings.TrimPrefix(resp.Header.Get("ETag"), "\"") + metadata.ETag = strings.TrimSuffix(metadata.ETag, "\"") + // A success here means data was written to server successfully. + metadata.Size = size + + // Return here. + return metadata, nil +} diff --git a/vendor/github.com/minio/minio-go/api-remove.go b/vendor/github.com/minio/minio-go/api-remove.go new file mode 100644 index 00000000..8f59c15e --- /dev/null +++ b/vendor/github.com/minio/minio-go/api-remove.go @@ -0,0 +1,167 @@ +/* + * Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2015 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 + +import ( + "net/http" + "net/url" +) + +// RemoveBucket deletes the bucket name. +// +// All objects (including all object versions and delete markers). +// in the bucket must be deleted before successfully attempting this request. +func (c Client) RemoveBucket(bucketName string) error { + // Input validation. + if err := isValidBucketName(bucketName); err != nil { + return err + } + // Instantiate a new request. + req, err := c.newRequest("DELETE", requestMetadata{ + bucketName: bucketName, + }) + if err != nil { + return err + } + // Initiate the request. + resp, err := c.do(req) + defer closeResponse(resp) + if err != nil { + return err + } + if resp != nil { + if resp.StatusCode != http.StatusNoContent { + return httpRespToErrorResponse(resp, bucketName, "") + } + } + + // Remove the location from cache on a successful delete. + c.bucketLocCache.Delete(bucketName) + + return nil +} + +// RemoveObject remove an object from a bucket. +func (c Client) RemoveObject(bucketName, objectName string) error { + // Input validation. + if err := isValidBucketName(bucketName); err != nil { + return err + } + if err := isValidObjectName(objectName); err != nil { + return err + } + // Instantiate the request. + req, err := c.newRequest("DELETE", requestMetadata{ + bucketName: bucketName, + objectName: objectName, + }) + if err != nil { + return err + } + // Initiate the request. + resp, err := c.do(req) + defer closeResponse(resp) + if err != nil { + return err + } + // DeleteObject always responds with http '204' even for + // objects which do not exist. So no need to handle them + // specifically. + return nil +} + +// 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 { + return err + } + if err := isValidObjectName(objectName); err != nil { + return err + } + // Find multipart upload id of the object to be aborted. + uploadID, err := c.findUploadID(bucketName, objectName) + if err != nil { + return err + } + if uploadID != "" { + // Upload id found, abort the incomplete multipart upload. + err := c.abortMultipartUpload(bucketName, objectName, uploadID) + if err != nil { + return err + } + } + return nil +} + +// abortMultipartUpload aborts a multipart upload for the given +// uploadID, all previously uploaded parts are deleted. +func (c Client) abortMultipartUpload(bucketName, objectName, uploadID string) error { + // Input validation. + if err := isValidBucketName(bucketName); err != nil { + return err + } + if err := isValidObjectName(objectName); err != nil { + return err + } + + // Initialize url queries. + urlValues := make(url.Values) + urlValues.Set("uploadId", uploadID) + + // Instantiate a new DELETE request. + req, err := c.newRequest("DELETE", requestMetadata{ + bucketName: bucketName, + objectName: objectName, + queryValues: urlValues, + }) + if err != nil { + return err + } + + // Initiate the request. + resp, err := c.do(req) + defer closeResponse(resp) + if err != nil { + return err + } + if resp != nil { + if resp.StatusCode != http.StatusNoContent { + // Abort has no response body, handle it for any errors. + var errorResponse ErrorResponse + switch resp.StatusCode { + case http.StatusNotFound: + // This is needed specifically for abort and it cannot + // be converged into default case. + errorResponse = ErrorResponse{ + Code: "NoSuchUpload", + Message: "The specified multipart upload does not exist.", + BucketName: bucketName, + Key: objectName, + RequestID: resp.Header.Get("x-amz-request-id"), + HostID: resp.Header.Get("x-amz-id-2"), + AmzBucketRegion: resp.Header.Get("x-amz-bucket-region"), + } + default: + return httpRespToErrorResponse(resp, bucketName, objectName) + } + return errorResponse + } + } + return nil +} diff --git a/vendor/github.com/minio/minio-go/s3-api-definitions.go b/vendor/github.com/minio/minio-go/api-s3-definitions.go similarity index 72% rename from vendor/github.com/minio/minio-go/s3-api-definitions.go rename to vendor/github.com/minio/minio-go/api-s3-definitions.go index 5aa618b6..de562e47 100644 --- a/vendor/github.com/minio/minio-go/s3-api-definitions.go +++ b/vendor/github.com/minio/minio-go/api-s3-definitions.go @@ -21,31 +21,34 @@ import ( "time" ) -// listAllMyBucketsResult container for listBuckets response +// listAllMyBucketsResult container for listBuckets response. type listAllMyBucketsResult struct { // Container for one or more buckets. Buckets struct { - Bucket []BucketStat + Bucket []BucketInfo } Owner owner } -// owner container for bucket owner information +// owner container for bucket owner information. type owner struct { DisplayName string ID string } -// commonPrefix container for prefix response +// commonPrefix container for prefix response. type commonPrefix struct { Prefix string } -// listBucketResult container for listObjects response +// listBucketResult container for listObjects response. type listBucketResult struct { - CommonPrefixes []commonPrefix // A response can contain CommonPrefixes only if you have specified a delimiter - Contents []ObjectStat // Metadata about each object returned - Delimiter string + // 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 @@ -57,13 +60,15 @@ type listBucketResult struct { 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. + // 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 } @@ -78,34 +83,33 @@ type listMultipartUploadsResult struct { EncodingType string MaxUploads int64 IsTruncated bool - Uploads []ObjectMultipartStat `xml:"Upload"` + Uploads []ObjectMultipartInfo `xml:"Upload"` Prefix string Delimiter string - CommonPrefixes []commonPrefix // A response can contain CommonPrefixes only if you specify a delimiter + // A response can contain CommonPrefixes only if you specify a delimiter. + CommonPrefixes []commonPrefix } -// initiator container for who initiated multipart upload +// initiator container for who initiated multipart upload. type initiator struct { ID string DisplayName string } -// objectPartMetadata container for particular part of an object -type objectPartMetadata struct { +// objectPart container for particular part of an object. +type objectPart struct { // Part number identifies the part. PartNumber int // Date and time the part was uploaded. LastModified time.Time - // Entity tag returned when the part was uploaded, usually md5sum of the part + // Entity tag returned when the part was uploaded, usually md5sum + // of the part. ETag string // Size of the uploaded part data. Size int64 - - // Error - Err error } // listObjectPartsResult container for ListObjectParts response. @@ -124,19 +128,21 @@ type listObjectPartsResult struct { // Indicates whether the returned list of parts is truncated. IsTruncated bool - ObjectParts []objectPartMetadata `xml:"Part"` + ObjectParts []objectPart `xml:"Part"` EncodingType string } -// initiateMultipartUploadResult container for InitiateMultiPartUpload response. +// initiateMultipartUploadResult container for InitiateMultiPartUpload +// response. type initiateMultipartUploadResult struct { Bucket string Key string UploadID string `xml:"UploadId"` } -// completeMultipartUploadResult container for completed multipart upload response. +// completeMultipartUploadResult container for completed multipart +// upload response. type completeMultipartUploadResult struct { Location string Bucket string @@ -144,7 +150,8 @@ type completeMultipartUploadResult struct { ETag string } -// completePart sub container lists individual part numbers and their md5sum, part of completeMultipartUpload. +// 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:"-"` @@ -153,13 +160,13 @@ type completePart struct { ETag string } -// completeMultipartUpload container for completing multipart upload +// completeMultipartUpload container for completing multipart upload. type completeMultipartUpload struct { XMLName xml.Name `xml:"http://s3.amazonaws.com/doc/2006-03-01/ CompleteMultipartUpload" json:"-"` Parts []completePart `xml:"Part"` } -// createBucketConfiguration container for bucket configuration +// createBucketConfiguration container for bucket configuration. type createBucketConfiguration struct { XMLName xml.Name `xml:"http://s3.amazonaws.com/doc/2006-03-01/ CreateBucketConfiguration" json:"-"` Location string `xml:"LocationConstraint"` @@ -167,7 +174,8 @@ type createBucketConfiguration struct { // grant container for the grantee and his or her permissions. type grant struct { - // grantee container for DisplayName and ID of the person being granted permissions. + // grantee container for DisplayName and ID of the person being + // granted permissions. Grantee struct { ID string DisplayName string @@ -178,7 +186,8 @@ type grant struct { Permission string } -// accessControlPolicy contains the elements providing ACL permissions for a bucket. +// accessControlPolicy contains the elements providing ACL permissions +// for a bucket. type accessControlPolicy struct { // accessControlList container for ACL information. AccessControlList struct { diff --git a/vendor/github.com/minio/minio-go/api-stat.go b/vendor/github.com/minio/minio-go/api-stat.go new file mode 100644 index 00000000..20f66e8f --- /dev/null +++ b/vendor/github.com/minio/minio-go/api-stat.go @@ -0,0 +1,125 @@ +/* + * Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2015 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 + +import ( + "net/http" + "strconv" + "strings" + "time" +) + +// BucketExists verify if bucket exists and you have permission to access it. +func (c Client) BucketExists(bucketName string) error { + // Input validation. + if err := isValidBucketName(bucketName); err != nil { + return err + } + // Instantiate a new request. + req, err := c.newRequest("HEAD", requestMetadata{ + bucketName: bucketName, + }) + if err != nil { + return err + } + // Initiate the request. + resp, err := c.do(req) + defer closeResponse(resp) + if err != nil { + return err + } + if resp != nil { + if resp.StatusCode != http.StatusOK { + return httpRespToErrorResponse(resp, bucketName, "") + } + } + return nil +} + +// StatObject verifies if object exists and you have permission to access. +func (c Client) StatObject(bucketName, objectName string) (ObjectInfo, error) { + // Input validation. + if err := isValidBucketName(bucketName); err != nil { + return ObjectInfo{}, err + } + if err := isValidObjectName(objectName); err != nil { + return ObjectInfo{}, err + } + // Instantiate a new request. + req, err := c.newRequest("HEAD", requestMetadata{ + bucketName: bucketName, + objectName: objectName, + }) + if err != nil { + return ObjectInfo{}, err + } + // Initiate the request. + resp, err := c.do(req) + defer closeResponse(resp) + if err != nil { + return ObjectInfo{}, err + } + if resp != nil { + if resp.StatusCode != http.StatusOK { + return ObjectInfo{}, httpRespToErrorResponse(resp, bucketName, objectName) + } + } + + // Trim off the odd double quotes from ETag in the beginning and end. + md5sum := strings.TrimPrefix(resp.Header.Get("ETag"), "\"") + md5sum = strings.TrimSuffix(md5sum, "\"") + + // Parse content length. + size, err := strconv.ParseInt(resp.Header.Get("Content-Length"), 10, 64) + if err != nil { + return ObjectInfo{}, ErrorResponse{ + Code: "InternalError", + Message: "Content-Length is invalid. " + reportIssue, + BucketName: bucketName, + Key: objectName, + RequestID: resp.Header.Get("x-amz-request-id"), + HostID: resp.Header.Get("x-amz-id-2"), + AmzBucketRegion: resp.Header.Get("x-amz-bucket-region"), + } + } + // Parse Last-Modified has http time format. + date, err := time.Parse(http.TimeFormat, resp.Header.Get("Last-Modified")) + if err != nil { + return ObjectInfo{}, ErrorResponse{ + Code: "InternalError", + Message: "Last-Modified time format is invalid. " + reportIssue, + BucketName: bucketName, + Key: objectName, + RequestID: resp.Header.Get("x-amz-request-id"), + HostID: resp.Header.Get("x-amz-id-2"), + AmzBucketRegion: resp.Header.Get("x-amz-bucket-region"), + } + } + // Fetch content type if any present. + contentType := strings.TrimSpace(resp.Header.Get("Content-Type")) + if contentType == "" { + contentType = "application/octet-stream" + } + // Save object metadata info. + var objectStat ObjectInfo + objectStat.ETag = md5sum + objectStat.Key = objectName + objectStat.Size = size + objectStat.LastModified = date + objectStat.ContentType = contentType + return objectStat, nil +} diff --git a/vendor/github.com/minio/minio-go/api.go b/vendor/github.com/minio/minio-go/api.go index c69080dc..b3993460 100644 --- a/vendor/github.com/minio/minio-go/api.go +++ b/vendor/github.com/minio/minio-go/api.go @@ -18,1107 +18,516 @@ package minio import ( "bytes" - "errors" + "encoding/base64" + "encoding/hex" + "fmt" "io" - "io/ioutil" "net/http" + "net/http/httputil" "net/url" - "path/filepath" + "os" + "regexp" "runtime" - "sort" - "strconv" "strings" - "sync" "time" ) -// s3 region map used by bucket location constraint if necessary. -var regions = map[string]string{ - "s3-fips-us-gov-west-1.amazonaws.com": "us-gov-west-1", - "s3.amazonaws.com": "us-east-1", - "s3-us-west-1.amazonaws.com": "us-west-1", - "s3-us-west-2.amazonaws.com": "us-west-2", - "s3-eu-west-1.amazonaws.com": "eu-west-1", - "s3-eu-central-1.amazonaws.com": "eu-central-1", - "s3-ap-southeast-1.amazonaws.com": "ap-southeast-1", - "s3-ap-southeast-2.amazonaws.com": "ap-southeast-2", - "s3-ap-northeast-1.amazonaws.com": "ap-northeast-1", - "s3-sa-east-1.amazonaws.com": "sa-east-1", - "s3.cn-north-1.amazonaws.com.cn": "cn-north-1", +// Client implements Amazon S3 compatible methods. +type Client struct { + /// Standard options. - // Add google cloud storage as one of the regions - "storage.googleapis.com": "google", -} + // AccessKeyID required for authorized requests. + accessKeyID string + // SecretAccessKey required for authorized requests. + secretAccessKey string + // Choose a signature type if necessary. + signature SignatureType + // Set to 'true' if Client has no access and secret keys. + anonymous bool -// getRegion returns a region based on its endpoint mapping. -func getRegion(host string) (region string) { - if _, ok := regions[host]; ok { - return regions[host] + // User supplied. + appInfo struct { + appName string + appVersion string } - // Region cannot be empty according to Amazon S3 for AWS Signature Version 4. - return "us-east-1" + endpointURL *url.URL + + // Needs allocation. + httpClient *http.Client + bucketLocCache *bucketLocationCache + + // Advanced functionality + isTraceEnabled bool + traceOutput io.Writer } -// getEndpoint returns a endpoint based on its region. -func getEndpoint(region string) (endpoint string) { - for h, r := range regions { - if r == region { - return h - } - } - return "s3.amazonaws.com" -} - -// SignatureType is type of Authorization requested for a given HTTP request. -type SignatureType int - -// Different types of supported signatures - default is Latest i.e SignatureV4. +// Global constants. const ( - Latest SignatureType = iota - SignatureV4 - SignatureV2 + libraryName = "minio-go" + libraryVersion = "0.2.5" ) -// isV2 - is signature SignatureV2? -func (s SignatureType) isV2() bool { - return s == SignatureV2 +// User Agent should always following the below style. +// Please open an issue to discuss any new changes here. +// +// Minio (OS; ARCH) LIB/VER APP/VER +const ( + libraryUserAgentPrefix = "Minio (" + runtime.GOOS + "; " + runtime.GOARCH + ") " + libraryUserAgent = libraryUserAgentPrefix + libraryName + "/" + libraryVersion +) + +// NewV2 - instantiate minio client with Amazon S3 signature version +// '2' compatibility. +func NewV2(endpoint string, accessKeyID, secretAccessKey string, insecure bool) (CloudStorageClient, error) { + clnt, err := privateNew(endpoint, accessKeyID, secretAccessKey, insecure) + if err != nil { + return nil, err + } + // Set to use signature version '2'. + clnt.signature = SignatureV2 + return clnt, nil } -// isV4 - is signature SignatureV4? -func (s SignatureType) isV4() bool { - return s == SignatureV4 +// NewV4 - instantiate minio client with Amazon S3 signature version +// '4' compatibility. +func NewV4(endpoint string, accessKeyID, secretAccessKey string, insecure bool) (CloudStorageClient, error) { + clnt, err := privateNew(endpoint, accessKeyID, secretAccessKey, insecure) + if err != nil { + return nil, err + } + // Set to use signature version '4'. + clnt.signature = SignatureV4 + return clnt, nil } -// isLatest - is signature Latest? -func (s SignatureType) isLatest() bool { - return s == Latest +// New - instantiate minio client Client, adds automatic verification +// of signature. +func New(endpoint string, accessKeyID, secretAccessKey string, insecure bool) (CloudStorageClient, error) { + clnt, err := privateNew(endpoint, accessKeyID, secretAccessKey, insecure) + if err != nil { + return nil, err + } + // Google cloud storage should be set to signature V2, force it if + // not. + if isGoogleEndpoint(clnt.endpointURL) { + clnt.signature = SignatureV2 + } + // If Amazon S3 set to signature v2. + if isAmazonEndpoint(clnt.endpointURL) { + clnt.signature = SignatureV4 + } + return clnt, nil } -// Config - main configuration struct used to set endpoint, credentials, and other options for requests. -type Config struct { - /// Standard options - AccessKeyID string // AccessKeyID required for authorized requests. - SecretAccessKey string // SecretAccessKey required for authorized requests. - Endpoint string // host endpoint eg:- https://s3.amazonaws.com - Signature SignatureType // choose a signature type if necessary. +func privateNew(endpoint, accessKeyID, secretAccessKey string, insecure bool) (*Client, error) { + // construct endpoint. + endpointURL, err := getEndpointURL(endpoint, insecure) + if err != nil { + return nil, err + } - /// Advanced options - // Optional field. If empty, region is determined automatically. - // Set to override default behavior. - Region string + // instantiate new Client. + clnt := new(Client) + clnt.accessKeyID = accessKeyID + clnt.secretAccessKey = secretAccessKey + if clnt.accessKeyID == "" || clnt.secretAccessKey == "" { + clnt.anonymous = true + } - /// Really Advanced options + // Save endpoint URL, user agent for future uses. + clnt.endpointURL = endpointURL + + // Instantiate http client and bucket location cache. + clnt.httpClient = &http.Client{} + clnt.bucketLocCache = newBucketLocationCache() + + // Return. + return clnt, nil +} + +// SetAppInfo - add application details to user agent. +func (c *Client) SetAppInfo(appName string, appVersion string) { + // if app name and version is not set, we do not a new user + // agent. + if appName != "" && appVersion != "" { + c.appInfo = struct { + appName string + appVersion string + }{} + c.appInfo.appName = appName + c.appInfo.appVersion = appVersion + } +} + +// SetCustomTransport - set new custom transport. +func (c *Client) SetCustomTransport(customHTTPTransport http.RoundTripper) { + // Set this to override default transport + // ``http.DefaultTransport``. // - // Set this to override default transport ``http.DefaultTransport`` - // - // This transport is usually needed for debugging OR to add your own - // custom TLS certificates on the client transport, for custom CA's and - // certs which are not part of standard certificate authority follow this - // example:- + // This transport is usually needed for debugging OR to add your + // own custom TLS certificates on the client transport, for custom + // CA's and certs which are not part of standard certificate + // authority follow this example :- // // tr := &http.Transport{ // TLSClientConfig: &tls.Config{RootCAs: pool}, // DisableCompression: true, // } + // api.SetTransport(tr) // - Transport http.RoundTripper - - /// Internal options - // use SetUserAgent append to default, useful when minio-go is used with in your application - userAgent string - isUserAgentSet bool // allow user agent's to be set only once - isVirtualHostedStyle bool // set when virtual hostnames are on + if c.httpClient != nil { + c.httpClient.Transport = customHTTPTransport + } } -// Global constants -const ( - LibraryName = "minio-go" - LibraryVersion = "0.2.5" -) +// TraceOn - enable HTTP tracing. +func (c *Client) TraceOn(outputStream io.Writer) error { + // if outputStream is nil then default to os.Stdout. + if outputStream == nil { + outputStream = os.Stdout + } + // Sets a new output stream. + c.traceOutput = outputStream -// isAnonymous - True if config doesn't have access and secret keys. -func (c *Config) isAnonymous() bool { - if c.AccessKeyID != "" && c.SecretAccessKey != "" { - return false - } - return true -} - -// setBucketRegion fetches the region and updates config, -// additionally it also constructs a proper endpoint based on that region. -func (c *Config) setBucketRegion() error { - u, err := url.Parse(c.Endpoint) - if err != nil { - return err - } - - if !c.isVirtualHostedStyle { - c.Region = getRegion(u.Host) - return nil - } - - var bucket, host string - hostIndex := strings.Index(u.Host, "s3") - if hostIndex == -1 { - hostIndex = strings.Index(u.Host, "storage.googleapis.com") - } - if hostIndex > 0 { - host = u.Host[hostIndex:] - bucket = u.Host[:hostIndex-1] - } - - genericGoogle, _ := filepath.Match("*.storage.googleapis.com", u.Host) - if genericGoogle { - // returning standard region for google for now, can be changed in future - // to query for region in case it is useful - c.Region = getRegion(host) - return nil - } - genericS3, _ := filepath.Match("*.s3.amazonaws.com", u.Host) - if !genericS3 { - c.Region = getRegion(host) - return nil - } - - // query aws s3 for the region for case of bucketName.s3.amazonaws.com - u.Host = host - tempConfig := Config{} - tempConfig.AccessKeyID = c.AccessKeyID - tempConfig.SecretAccessKey = c.SecretAccessKey - tempConfig.Endpoint = u.String() - tempConfig.Region = getRegion(u.Host) - tempConfig.isVirtualHostedStyle = false - s3API := API{s3API{&tempConfig}} - region, err := s3API.getBucketLocation(bucket) - if err != nil { - return err - } - // if region returned from getBucketLocation is null - // and if genericS3 is enabled - set back to 'us-east-1'. - if region == "" { - if genericS3 { - region = "us-east-1" - } - } - c.Region = region - c.setEndpoint(region, bucket, u.Scheme) + // Enable tracing. + c.isTraceEnabled = true return nil } -// setEndpoint - construct final endpoint based on region, bucket and scheme -func (c *Config) setEndpoint(region, bucket, scheme string) { - var host string - for k, v := range regions { - if region == v { - host = k - } +// TraceOff - disable HTTP tracing. +func (c *Client) TraceOff() { + // Disable tracing. + c.isTraceEnabled = false +} + +// requestMetadata - is container for all the values to make a +// request. +type requestMetadata struct { + // If set newRequest presigns the URL. + presignURL bool + + // User supplied. + bucketName string + objectName string + queryValues url.Values + customHeader http.Header + expires int64 + + // Generated by our internal code. + bucketLocation string + contentBody io.ReadCloser + contentLength int64 + contentSHA256Bytes []byte + contentMD5Bytes []byte +} + +// Filter out signature value from Authorization header. +func (c Client) filterSignature(req *http.Request) { + // For anonymous requests, no need to filter. + if c.anonymous { + return } - // construct the new URL endpoint based on the region. - newURL := new(url.URL) - newURL.Host = bucket + "." + host - newURL.Scheme = scheme - c.Endpoint = newURL.String() + // Handle if Signature V2. + if c.signature.isV2() { + // Set a temporary redacted auth + req.Header.Set("Authorization", "AWS **REDACTED**:**REDACTED**") + return + } + + /// Signature V4 authorization header. + + // Save the original auth. + origAuth := req.Header.Get("Authorization") + // Strip out accessKeyID from: + // Credential=////aws4_request + regCred := regexp.MustCompile("Credential=([A-Z0-9]+)/") + newAuth := regCred.ReplaceAllString(origAuth, "Credential=**REDACTED**/") + + // Strip out 256-bit signature from: Signature=<256-bit signature> + regSign := regexp.MustCompile("Signature=([[0-9a-f]+)") + newAuth = regSign.ReplaceAllString(newAuth, "Signature=**REDACTED**") + + // Set a temporary redacted auth + req.Header.Set("Authorization", newAuth) return } -// SetUserAgent - append to a default user agent -func (c *Config) SetUserAgent(name string, version string, comments ...string) { - if c.isUserAgentSet { - // if user agent already set do not set it - return - } - // if no name and version is set we do not add new user agents - if name != "" && version != "" { - c.userAgent = c.userAgent + " " + name + "/" + version + " (" + strings.Join(comments, "; ") + ") " - c.isUserAgentSet = true - } -} - -// API is a container which delegates methods that comply with CloudStorageAPI interface. -type API struct { - s3API -} - -func isVirtualHostedStyle(host string) bool { - isS3VirtualHost, _ := filepath.Match("*.s3*.amazonaws.com", host) - isGoogleVirtualHost, _ := filepath.Match("*.storage.googleapis.com", host) - return isS3VirtualHost || isGoogleVirtualHost -} - -// New - instantiate minio client API with your input Config{}. -func New(config Config) (CloudStorageAPI, error) { - u, err := url.Parse(config.Endpoint) - if err != nil { - return API{}, err - } - config.isVirtualHostedStyle = isVirtualHostedStyle(u.Host) - // if not region is set, procure it from getBucketRegion if possible. - if config.Region == "" { - if err := config.setBucketRegion(); err != nil { - return API{}, err - } - } - /// Google cloud storage should be set to signature V2, force it if not. - if config.Region == "google" && config.Signature != SignatureV2 { - config.Signature = SignatureV2 - } - config.SetUserAgent(LibraryName, LibraryVersion, runtime.GOOS, runtime.GOARCH) - config.isUserAgentSet = false // default - return API{s3API{&config}}, nil -} - -// PresignedPostPolicy return POST form data that can be used for object upload. -func (a API) PresignedPostPolicy(p *PostPolicy) (map[string]string, error) { - if p.expiration.IsZero() { - return nil, errors.New("Expiration time must be specified") - } - if _, ok := p.formData["key"]; !ok { - return nil, errors.New("object key must be specified") - } - if _, ok := p.formData["bucket"]; !ok { - return nil, errors.New("bucket name must be specified") - } - return a.presignedPostPolicy(p), nil -} - -/// Object operations. - -// PresignedPutObject get a presigned URL to upload an object. -// Expires maximum is 7days - ie. 604800 and minimum is 1. -func (a API) PresignedPutObject(bucket, object string, expires time.Duration) (string, error) { - expireSeconds := int64(expires / time.Second) - if expireSeconds < 1 || expireSeconds > 604800 { - return "", invalidArgumentError("") - } - return a.presignedPutObject(bucket, object, expireSeconds) -} - -// PresignedGetObject get a presigned URL to retrieve an object for third party apps. -func (a API) PresignedGetObject(bucket, object string, expires time.Duration) (string, error) { - expireSeconds := int64(expires / time.Second) - if expireSeconds < 1 || expireSeconds > 604800 { - return "", invalidArgumentError("") - } - return a.presignedGetObject(bucket, object, expireSeconds, 0, 0) -} - -// GetObject retrieve object. retrieves full object, if you need ranges use GetPartialObject. -func (a API) GetObject(bucket, object string) (io.ReadSeeker, error) { - if err := invalidBucketError(bucket); err != nil { - return nil, err - } - if err := invalidObjectError(object); err != nil { - return nil, err - } - // get object - return newObjectReadSeeker(a, bucket, object), nil -} - -// GetPartialObject retrieve partial object. -// -// Takes range arguments to download the specified range bytes of an object. -// Setting offset and length = 0 will download the full object. -// For more information about the HTTP Range header, go to http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35. -func (a API) GetPartialObject(bucket, object string, offset, length int64) (io.ReadSeeker, error) { - if err := invalidBucketError(bucket); err != nil { - return nil, err - } - if err := invalidObjectError(object); err != nil { - return nil, err - } - // get partial object. - return newObjectReadSeeker(a, bucket, object), nil -} - -// completedParts is a wrapper to make parts sortable by their part numbers. -// multi part completion requires list of multi parts to be sorted. -type completedParts []completePart - -func (a completedParts) Len() int { return len(a) } -func (a completedParts) Swap(i, j int) { a[i], a[j] = a[j], a[i] } -func (a completedParts) Less(i, j int) bool { return a[i].PartNumber < a[j].PartNumber } - -// minimumPartSize minimum part size per object after which PutObject behaves internally as multipart. -var minimumPartSize int64 = 1024 * 1024 * 5 - -// maxParts - maximum parts for a single multipart session. -var maxParts = int64(10000) - -// maxPartSize - maximum part size for a single multipart upload operation. -var maxPartSize int64 = 1024 * 1024 * 1024 * 5 - -// maxConcurrentQueue - max concurrent upload queue. -var maxConcurrentQueue int64 = 4 - -// calculatePartSize - calculate the optimal part size for the given objectSize. -// -// NOTE: Assumption here is that for any given object upload to a S3 compatible object -// storage it will have the following parameters as constants. -// -// maxParts -// maximumPartSize -// minimumPartSize -// -// if the partSize after division with maxParts is greater than minimumPartSize -// then choose miniumPartSize as the new part size, if not return minimumPartSize. -// -// special case where it happens to be that partSize is indeed bigger than the -// maximum part size just return maxPartSize. -func calculatePartSize(objectSize int64) int64 { - // if object size is -1 choose part size as 5GB. - if objectSize == -1 { - return maxPartSize - } - // make sure last part has enough buffer and handle this poperly. - partSize := (objectSize / (maxParts - 1)) - if partSize > minimumPartSize { - if partSize > maxPartSize { - return maxPartSize - } - return partSize - } - return minimumPartSize -} - -// Initiate a fresh multipart upload -func (a API) newObjectUpload(bucket, object, contentType string, size int64, data io.ReadSeeker) error { - // Initiate a new multipart upload request. - initMultipartUploadResult, err := a.initiateMultipartUpload(bucket, object) +// dumpHTTP - dump HTTP request and response. +func (c Client) dumpHTTP(req *http.Request, resp *http.Response) error { + // Starts http dump. + _, err := fmt.Fprintln(c.traceOutput, "---------START-HTTP---------") if err != nil { return err } - uploadID := initMultipartUploadResult.UploadID - complMultipartUpload := completeMultipartUpload{} - // Calculate optimal part size for a given size. - partSize := calculatePartSize(size) - // Allocate bufferred error channel for maximum parts. - errCh := make(chan error, maxParts) - // Limit multi part queue size to concurrent. - mpQueueCh := make(chan struct{}, maxConcurrentQueue) - defer close(errCh) - defer close(mpQueueCh) - // Allocate a new wait group - wg := new(sync.WaitGroup) + // Filter out Signature field from Authorization header. + c.filterSignature(req) - partNumber := 1 - var isEnableSha256Sum bool - if a.config.Signature.isV4() { - isEnableSha256Sum = true - } - for part := range partsManager(data, partSize, isEnableSha256Sum) { - // Limit to 4 parts a given time. - mpQueueCh <- struct{}{} - // Account for all parts uploaded simultaneousy. - wg.Add(1) - part.Number = partNumber - go func(errCh chan<- error, mpQueueCh <-chan struct{}, part partMetadata) { - defer wg.Done() - defer func() { - <-mpQueueCh - }() - if part.Err != nil { - errCh <- part.Err - return - } - var complPart completePart - complPart, err = a.uploadPart(bucket, object, uploadID, part) - if err != nil { - errCh <- err - return - } - complMultipartUpload.Parts = append(complMultipartUpload.Parts, complPart) - errCh <- nil - }(errCh, mpQueueCh, part) - partNumber++ - } - wg.Wait() - if err := <-errCh; err != nil { - return err - } - sort.Sort(completedParts(complMultipartUpload.Parts)) - _, err = a.completeMultipartUpload(bucket, object, uploadID, complMultipartUpload) + // Only display request header. + reqTrace, err := httputil.DumpRequestOut(req, false) if err != nil { return err } - return nil -} -func (a API) listObjectPartsRecursive(bucket, object, uploadID string) <-chan objectPartMetadata { - objectPartCh := make(chan objectPartMetadata, 1000) - go a.listObjectPartsRecursiveInRoutine(bucket, object, uploadID, objectPartCh) - return objectPartCh -} - -func (a API) listObjectPartsRecursiveInRoutine(bucket, object, uploadID string, ch chan<- objectPartMetadata) { - defer close(ch) - listObjPartsResult, err := a.listObjectParts(bucket, object, uploadID, 0, 1000) + // Write request to trace output. + _, err = fmt.Fprint(c.traceOutput, string(reqTrace)) if err != nil { - ch <- objectPartMetadata{ - Err: err, - } - return + return err } - for _, uploadedObjectPart := range listObjPartsResult.ObjectParts { - ch <- uploadedObjectPart - } - for { - if !listObjPartsResult.IsTruncated { - break - } - nextPartNumberMarker := listObjPartsResult.NextPartNumberMarker - listObjPartsResult, err = a.listObjectParts(bucket, object, uploadID, nextPartNumberMarker, 1000) + + // Only display response header. + var respTrace []byte + + // For errors we make sure to dump response body as well. + if resp.StatusCode != http.StatusOK && + resp.StatusCode != http.StatusPartialContent && + resp.StatusCode != http.StatusNoContent { + respTrace, err = httputil.DumpResponse(resp, true) if err != nil { - ch <- objectPartMetadata{ - Err: err, - } - return + return err } - for _, uploadedObjectPart := range listObjPartsResult.ObjectParts { - ch <- uploadedObjectPart - } - } -} - -// getTotalMultipartSize - calculate total uploaded size for the a given multipart object. -func (a API) getTotalMultipartSize(bucket, object, uploadID string) (int64, error) { - var size int64 - for part := range a.listObjectPartsRecursive(bucket, object, uploadID) { - if part.Err != nil { - return 0, part.Err - } - size += part.Size - } - return size, nil -} - -// continue previously interrupted multipart upload object at `uploadID` -func (a API) continueObjectUpload(bucket, object, uploadID string, size int64, data io.ReadSeeker) error { - var seekOffset int64 - partNumber := 1 - completeMultipartUpload := completeMultipartUpload{} - for objPart := range a.listObjectPartsRecursive(bucket, object, uploadID) { - if objPart.Err != nil { - return objPart.Err - } - // partNumbers are sorted in listObjectParts. - if partNumber != objPart.PartNumber { - break - } - var completedPart completePart - completedPart.PartNumber = objPart.PartNumber - completedPart.ETag = objPart.ETag - completeMultipartUpload.Parts = append(completeMultipartUpload.Parts, completedPart) - seekOffset += objPart.Size // Add seek Offset for future Seek to skip entries. - partNumber++ // Update partNumber sequentially to verify and skip. - } - - // Calculate the optimal part size for a given size. - partSize := calculatePartSize(size) - // Allocate bufferred error channel for maximum parts. - errCh := make(chan error, maxParts) - // Limit multipart queue size to maxConcurrentQueue. - mpQueueCh := make(chan struct{}, maxConcurrentQueue) - defer close(errCh) - defer close(mpQueueCh) - // Allocate a new wait group. - wg := new(sync.WaitGroup) - - if _, err := data.Seek(seekOffset, 0); err != nil { - return err - } - var isEnableSha256Sum bool - if a.config.Signature.isV4() { - isEnableSha256Sum = true - } - for part := range partsManager(data, partSize, isEnableSha256Sum) { - // Limit to 4 parts a given time. - mpQueueCh <- struct{}{} - // Account for all parts uploaded simultaneousy. - wg.Add(1) - part.Number = partNumber - go func(errCh chan<- error, mpQueueCh <-chan struct{}, part partMetadata) { - defer wg.Done() - defer func() { - <-mpQueueCh - }() - if part.Err != nil { - errCh <- part.Err - return + } else { + // WORKAROUND for https://github.com/golang/go/issues/13942. + // httputil.DumpResponse does not print response headers for + // all successful calls which have response ContentLength set + // to zero. Keep this workaround until the above bug is fixed. + if resp.ContentLength == 0 { + var buffer bytes.Buffer + if err := resp.Header.Write(&buffer); err != nil { + return err } - complPart, err := a.uploadPart(bucket, object, uploadID, part) - if err != nil { - errCh <- err - return - } - completeMultipartUpload.Parts = append(completeMultipartUpload.Parts, complPart) - errCh <- nil - }(errCh, mpQueueCh, part) - partNumber++ - } - wg.Wait() - if err := <-errCh; err != nil { - return err - } - sort.Sort(completedParts(completeMultipartUpload.Parts)) - _, err := a.completeMultipartUpload(bucket, object, uploadID, completeMultipartUpload) - if err != nil { - return err - } - return nil -} - -// PutObject create an object in a bucket. -// -// You must have WRITE permissions on a bucket to create an object. -// -// - For size lesser than 5MB PutObject automatically does single Put operation. -// - For size equal to 0Bytes PutObject automatically does single Put operation. -// - For size larger than 5MB PutObject automatically does resumable multipart operation. -// - For size input as -1 PutObject treats it as a stream and does multipart operation until -// input stream reaches EOF. Maximum object size that can be uploaded through this operation -// will be 5TB. -// -// NOTE: if you are using Google Cloud Storage. Then there is no resumable multipart -// upload support yet. Currently PutObject will behave like a single PUT operation and would -// only upload for file sizes upto maximum 5GB. (maximum limit for single PUT operation). -// -// For un-authenticated requests S3 doesn't allow multipart upload, so we fall back to single -// PUT operation. -func (a API) PutObject(bucket, object string, data io.ReadSeeker, size int64, contentType string) error { - if err := invalidBucketError(bucket); err != nil { - return err - } - if err := invalidArgumentError(object); err != nil { - return err - } - // NOTE: S3 doesn't allow anonymous multipart requests. - if strings.Contains(a.config.Endpoint, "amazonaws.com") || strings.Contains(a.config.Endpoint, "googleapis.com") { - if a.config.isAnonymous() { - if size == -1 { - return ErrorResponse{ - Code: "NotImplemented", - Message: "For Anonymous requests Content-Length cannot be '-1'.", - Resource: separator + bucket + separator + object, - } - } - if size > maxPartSize { - return ErrorResponse{ - Code: "EntityTooLarge", - Message: "Your proposed upload exceeds the maximum allowed object size '5GB' for single PUT operation.", - Resource: separator + bucket + separator + object, - } - } - // For anonymous requests, we will not calculate sha256 and md5sum. - putObjMetadata := putObjectMetadata{ - MD5Sum: nil, - Sha256Sum: nil, - ReadCloser: ioutil.NopCloser(data), - Size: size, - ContentType: contentType, - } - _, err := a.putObject(bucket, object, putObjMetadata) + respTrace = buffer.Bytes() + respTrace = append(respTrace, []byte("\r\n")...) + } else { + respTrace, err = httputil.DumpResponse(resp, false) if err != nil { return err } } } - // Special handling just for Google Cloud Storage. - // TODO - we should remove this in future when we fully implement Resumable object upload. - if strings.Contains(a.config.Endpoint, "googleapis.com") { - if size > maxPartSize { - return ErrorResponse{ - Code: "EntityTooLarge", - Message: "Your proposed upload exceeds the maximum allowed object size '5GB' for single PUT operation.", - Resource: separator + bucket + separator + object, - } - } - putObjMetadata := putObjectMetadata{ - MD5Sum: nil, - Sha256Sum: nil, - ReadCloser: ioutil.NopCloser(data), - Size: size, - ContentType: contentType, - } - // NOTE: with Google Cloud Storage, Content-MD5 is deliberately skipped. - if _, err := a.putObject(bucket, object, putObjMetadata); err != nil { - return err - } - return nil - } - switch { - case size < minimumPartSize && size >= 0: - dataBytes, err := ioutil.ReadAll(data) - if err != nil { - return err - } - if int64(len(dataBytes)) != size { - return ErrorResponse{ - Code: "UnexpectedShortRead", - Message: "Data read ‘" + strconv.FormatInt(int64(len(dataBytes)), 10) + "’ is not equal to expected size ‘" + strconv.FormatInt(size, 10) + "’", - Resource: separator + bucket + separator + object, - } - } - putObjMetadata := putObjectMetadata{ - MD5Sum: sumMD5(dataBytes), - Sha256Sum: sum256(dataBytes), - ReadCloser: ioutil.NopCloser(bytes.NewReader(dataBytes)), - Size: size, - ContentType: contentType, - } - // Single Part use case, use PutObject directly. - _, err = a.putObject(bucket, object, putObjMetadata) - if err != nil { - return err - } - return nil - case size >= minimumPartSize || size == -1: - var inProgress bool - var inProgressUploadID string - for mpUpload := range a.listMultipartUploadsRecursive(bucket, object) { - if mpUpload.Err != nil { - return mpUpload.Err - } - if mpUpload.Key == object { - inProgress = true - inProgressUploadID = mpUpload.UploadID - break - } - } - if !inProgress { - return a.newObjectUpload(bucket, object, contentType, size, data) - } - return a.continueObjectUpload(bucket, object, inProgressUploadID, size, data) - } - return errors.New("Unexpected control flow, please report this error at https://github.com/minio/minio-go/issues") -} - -// StatObject verify if object exists and you have permission to access it. -func (a API) StatObject(bucket, object string) (ObjectStat, error) { - if err := invalidBucketError(bucket); err != nil { - return ObjectStat{}, err - } - if err := invalidObjectError(object); err != nil { - return ObjectStat{}, err - } - return a.headObject(bucket, object) -} - -// RemoveObject remove an object from a bucket. -func (a API) RemoveObject(bucket, object string) error { - if err := invalidBucketError(bucket); err != nil { - return err - } - if err := invalidObjectError(object); err != nil { - return err - } - return a.deleteObject(bucket, object) -} - -/// Bucket operations - -// MakeBucket makes a new bucket. -// -// Optional arguments are acl - by default all buckets are created -// with ``private`` acl. -// -// ACL valid values -// -// private - owner gets full access [default]. -// public-read - owner gets full access, all others get read access. -// public-read-write - owner gets full access, all others get full access too. -// authenticated-read - owner gets full access, authenticated users get read access. -// -func (a API) MakeBucket(bucket string, acl BucketACL) error { - if err := invalidBucketError(bucket); err != nil { - return err - } - if !acl.isValidBucketACL() { - return invalidArgumentError("") - } - location := a.config.Region - if location == "us-east-1" { - location = "" - } - if location == "google" { - location = "" - } - return a.putBucket(bucket, string(acl), location) -} - -// SetBucketACL set the permissions on an existing bucket using access control lists (ACL). -// -// For example -// -// private - owner gets full access [default]. -// public-read - owner gets full access, all others get read access. -// public-read-write - owner gets full access, all others get full access too. -// authenticated-read - owner gets full access, authenticated users get read access. -// -func (a API) SetBucketACL(bucket string, acl BucketACL) error { - if err := invalidBucketError(bucket); err != nil { - return err - } - if !acl.isValidBucketACL() { - return invalidArgumentError("") - } - return a.putBucketACL(bucket, string(acl)) -} - -// GetBucketACL get the permissions on an existing bucket. -// -// Returned values are: -// -// private - owner gets full access. -// public-read - owner gets full access, others get read access. -// public-read-write - owner gets full access, others get full access too. -// authenticated-read - owner gets full access, authenticated users get read access. -// -func (a API) GetBucketACL(bucket string) (BucketACL, error) { - if err := invalidBucketError(bucket); err != nil { - return "", err - } - policy, err := a.getBucketACL(bucket) + // Write response to trace output. + _, err = fmt.Fprint(c.traceOutput, strings.TrimSuffix(string(respTrace), "\r\n")) if err != nil { - return "", err - } - grants := policy.AccessControlList.Grant - switch { - case len(grants) == 1: - if grants[0].Grantee.URI == "" && grants[0].Permission == "FULL_CONTROL" { - return BucketACL("private"), nil - } - case len(grants) == 2: - for _, g := range grants { - if g.Grantee.URI == "http://acs.amazonaws.com/groups/global/AuthenticatedUsers" && g.Permission == "READ" { - return BucketACL("authenticated-read"), nil - } - if g.Grantee.URI == "http://acs.amazonaws.com/groups/global/AllUsers" && g.Permission == "READ" { - return BucketACL("public-read"), nil - } - } - case len(grants) == 3: - for _, g := range grants { - if g.Grantee.URI == "http://acs.amazonaws.com/groups/global/AllUsers" && g.Permission == "WRITE" { - return BucketACL("public-read-write"), nil - } - } - } - return "", ErrorResponse{ - Code: "NoSuchBucketPolicy", - Message: "The specified bucket does not have a bucket policy.", - Resource: "/" + bucket, - RequestID: "minio", - } -} - -// BucketExists verify if bucket exists and you have permission to access it. -func (a API) BucketExists(bucket string) error { - if err := invalidBucketError(bucket); err != nil { return err } - return a.headBucket(bucket) -} -// RemoveBucket deletes the bucket named in the URI. -// -// All objects (including all object versions and delete markers). -// in the bucket must be deleted before successfully attempting this request. -func (a API) RemoveBucket(bucket string) error { - if err := invalidBucketError(bucket); err != nil { + // Ends the http dump. + _, err = fmt.Fprintln(c.traceOutput, "---------END-HTTP---------") + if err != nil { return err } - return a.deleteBucket(bucket) + + // Returns success. + return nil } -func (a API) listMultipartUploadsRecursive(bucket, object string) <-chan ObjectMultipartStat { - ch := make(chan ObjectMultipartStat, 1000) - go a.listMultipartUploadsRecursiveInRoutine(bucket, object, ch) - return ch -} - -func (a API) listMultipartUploadsRecursiveInRoutine(bucket, object string, ch chan<- ObjectMultipartStat) { - defer close(ch) - listMultipartUplResult, err := a.listMultipartUploads(bucket, "", "", object, "", 1000) +// do - execute http request. +func (c Client) do(req *http.Request) (*http.Response, error) { + // execute the request. + resp, err := c.httpClient.Do(req) if err != nil { - ch <- ObjectMultipartStat{ - Err: err, - } - return + return resp, err } - for _, multiPartUpload := range listMultipartUplResult.Uploads { - ch <- multiPartUpload - } - for { - if !listMultipartUplResult.IsTruncated { - break - } - listMultipartUplResult, err = a.listMultipartUploads(bucket, - listMultipartUplResult.NextKeyMarker, listMultipartUplResult.NextUploadIDMarker, object, "", 1000) + // If trace is enabled, dump http request and response. + if c.isTraceEnabled { + err = c.dumpHTTP(req, resp) if err != nil { - ch <- ObjectMultipartStat{ - Err: err, - } - return - } - for _, multiPartUpload := range listMultipartUplResult.Uploads { - ch <- multiPartUpload + return nil, err } } + return resp, nil } -// listIncompleteUploadsInRoutine is an internal goroutine function called for listing objects. -func (a API) listIncompleteUploadsInRoutine(bucket, prefix string, recursive bool, ch chan<- ObjectMultipartStat) { - defer close(ch) - if err := invalidBucketError(bucket); err != nil { - ch <- ObjectMultipartStat{ - Err: err, - } - return +// newRequest - instantiate a new HTTP request for a given method. +func (c Client) newRequest(method string, metadata requestMetadata) (req *http.Request, err error) { + // If no method is supplied default to 'POST'. + if method == "" { + method = "POST" } - switch { - case recursive == true: - var multipartMarker string - var uploadIDMarker string - for { - result, err := a.listMultipartUploads(bucket, multipartMarker, uploadIDMarker, prefix, "", 1000) - if err != nil { - ch <- ObjectMultipartStat{ - Err: err, - } - return - } - for _, objectSt := range result.Uploads { - // NOTE: getTotalMultipartSize can make listing incomplete uploads slower. - objectSt.Size, err = a.getTotalMultipartSize(bucket, objectSt.Key, objectSt.UploadID) - if err != nil { - ch <- ObjectMultipartStat{ - Err: err, - } - } - ch <- objectSt - multipartMarker = result.NextKeyMarker - uploadIDMarker = result.NextUploadIDMarker - } - if !result.IsTruncated { - break - } - } - default: - var multipartMarker string - var uploadIDMarker string - for { - result, err := a.listMultipartUploads(bucket, multipartMarker, uploadIDMarker, prefix, "/", 1000) - if err != nil { - ch <- ObjectMultipartStat{ - Err: err, - } - return - } - multipartMarker = result.NextKeyMarker - uploadIDMarker = result.NextUploadIDMarker - for _, objectSt := range result.Uploads { - objectSt.Size, err = a.getTotalMultipartSize(bucket, objectSt.Key, objectSt.UploadID) - if err != nil { - ch <- ObjectMultipartStat{ - Err: err, - } - } - ch <- objectSt - } - for _, prefix := range result.CommonPrefixes { - object := ObjectMultipartStat{} - object.Key = prefix.Prefix - object.Size = 0 - ch <- object - } - if !result.IsTruncated { - break - } - } - } -} -// ListIncompleteUploads - List incompletely uploaded multipart objects. -// -// ListIncompleteUploads is a channel based API implemented to facilitate ease of usage of S3 API ListMultipartUploads() -// by automatically recursively traversing all multipart objects on a given bucket if specified. -// -// Your input paramters are just bucket, prefix and recursive. -// If you enable recursive as 'true' this function will return back all the multipart objects in a given bucket. -// -// api := client.New(....) -// recursive := true -// for message := range api.ListIncompleteUploads("mytestbucket", "starthere", recursive) { -// fmt.Println(message) -// } -// -func (a API) ListIncompleteUploads(bucket, prefix string, recursive bool) <-chan ObjectMultipartStat { - objectMultipartStatCh := make(chan ObjectMultipartStat, 1000) - go a.listIncompleteUploadsInRoutine(bucket, prefix, recursive, objectMultipartStatCh) - return objectMultipartStatCh -} - -// listObjectsInRoutine is an internal goroutine function called for listing objects. -// This function feeds data into channel. -func (a API) listObjectsInRoutine(bucket, prefix string, recursive bool, ch chan<- ObjectStat) { - defer close(ch) - if err := invalidBucketError(bucket); err != nil { - ch <- ObjectStat{ - Err: err, - } - return - } - switch { - case recursive == true: - var marker string - for { - result, err := a.listObjects(bucket, marker, prefix, "", 1000) - if err != nil { - ch <- ObjectStat{ - Err: err, - } - return - } - for _, object := range result.Contents { - ch <- object - marker = object.Key - } - if !result.IsTruncated { - break - } - } - default: - var marker string - for { - result, err := a.listObjects(bucket, marker, prefix, "/", 1000) - if err != nil { - ch <- ObjectStat{ - Err: err, - } - return - } - marker = result.NextMarker - for _, object := range result.Contents { - ch <- object - } - for _, prefix := range result.CommonPrefixes { - object := ObjectStat{} - object.Key = prefix.Prefix - object.Size = 0 - ch <- object - } - if !result.IsTruncated { - break - } - } - } -} - -// ListObjects - (List Objects) - List some objects or all recursively. -// -// ListObjects is a channel based API implemented to facilitate ease of usage of S3 API ListObjects() -// by automatically recursively traversing all objects on a given bucket if specified. -// -// Your input paramters are just bucket, prefix and recursive. -// If you enable recursive as 'true' this function will return back all the objects in a given bucket. -// -// api := client.New(....) -// recursive := true -// for message := range api.ListObjects("mytestbucket", "starthere", recursive) { -// fmt.Println(message) -// } -// -func (a API) ListObjects(bucket string, prefix string, recursive bool) <-chan ObjectStat { - ch := make(chan ObjectStat, 1000) - go a.listObjectsInRoutine(bucket, prefix, recursive, ch) - return ch -} - -// listBucketsInRoutine is an internal go routine function called for listing buckets -// This function feeds data into channel -func (a API) listBucketsInRoutine(ch chan<- BucketStat) { - defer close(ch) - listAllMyBucketListResults, err := a.listBuckets() - if err != nil { - ch <- BucketStat{ - Err: err, - } - return - } - for _, bucket := range listAllMyBucketListResults.Buckets.Bucket { - ch <- bucket - } -} - -// ListBuckets list of all buckets owned by the authenticated sender of the request. -// -// This call requires explicit authentication, no anonymous requests are allowed for listing buckets. -// -// api := client.New(....) -// for message := range api.ListBuckets() { -// fmt.Println(message) -// } -// -func (a API) ListBuckets() <-chan BucketStat { - ch := make(chan BucketStat, 100) - go a.listBucketsInRoutine(ch) - return ch -} - -func (a API) removeIncompleteUploadInRoutine(bucket, object string, errorCh chan<- error) { - defer close(errorCh) - if err := invalidBucketError(bucket); err != nil { - errorCh <- err - return - } - if err := invalidObjectError(object); err != nil { - errorCh <- err - return - } - listMultipartUplResult, err := a.listMultipartUploads(bucket, "", "", object, "", 1000) - if err != nil { - errorCh <- err - return - } - for _, multiPartUpload := range listMultipartUplResult.Uploads { - if object == multiPartUpload.Key { - err := a.abortMultipartUpload(bucket, multiPartUpload.Key, multiPartUpload.UploadID) - if err != nil { - errorCh <- err - return - } - return - } - } - for { - if !listMultipartUplResult.IsTruncated { - break - } - listMultipartUplResult, err = a.listMultipartUploads(bucket, - listMultipartUplResult.NextKeyMarker, listMultipartUplResult.NextUploadIDMarker, object, "", 1000) + // Gather location only if bucketName is present. + location := "us-east-1" // Default all other requests to "us-east-1". + if metadata.bucketName != "" { + location, err = c.getBucketLocation(metadata.bucketName) if err != nil { - errorCh <- err - return + return nil, err } - for _, multiPartUpload := range listMultipartUplResult.Uploads { - if object == multiPartUpload.Key { - err := a.abortMultipartUpload(bucket, multiPartUpload.Key, multiPartUpload.UploadID) - if err != nil { - errorCh <- err - return - } - return + } + + // Save location. + metadata.bucketLocation = location + + // Construct a new target URL. + targetURL, err := c.makeTargetURL(metadata.bucketName, metadata.objectName, metadata.bucketLocation, metadata.queryValues) + if err != nil { + return nil, err + } + + // Initialize a new HTTP request for the method. + req, err = http.NewRequest(method, targetURL.String(), nil) + if err != nil { + return nil, err + } + + // Generate presign url if needed, return right here. + if metadata.expires != 0 && metadata.presignURL { + if c.anonymous { + return nil, ErrInvalidArgument("Requests cannot be presigned with anonymous credentials.") + } + if c.signature.isV2() { + // Presign URL with signature v2. + req = preSignV2(*req, c.accessKeyID, c.secretAccessKey, metadata.expires) + } else { + // Presign URL with signature v4. + req = preSignV4(*req, c.accessKeyID, c.secretAccessKey, location, metadata.expires) + } + return req, nil + } + + // Set content body if available. + if metadata.contentBody != nil { + req.Body = metadata.contentBody + } + + // set UserAgent for the request. + c.setUserAgent(req) + + // Set all headers. + for k, v := range metadata.customHeader { + req.Header.Set(k, v[0]) + } + + // set incoming content-length. + if metadata.contentLength > 0 { + 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() { + req.Header.Set("X-Amz-Content-Sha256", hex.EncodeToString(sum256([]byte{}))) + if metadata.contentSHA256Bytes != nil { + req.Header.Set("X-Amz-Content-Sha256", hex.EncodeToString(metadata.contentSHA256Bytes)) } } + } + // 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 = signV2(*req, c.accessKeyID, c.secretAccessKey) + } else if c.signature.isV4() { + // Add signature version '4' authorization header. + req = signV4(*req, c.accessKeyID, c.secretAccessKey, location) + } + } + + // Return request. + return req, nil +} + +// set User agent. +func (c Client) setUserAgent(req *http.Request) { + req.Header.Set("User-Agent", libraryUserAgent) + if c.appInfo.appName != "" && c.appInfo.appVersion != "" { + req.Header.Set("User-Agent", libraryUserAgent+" "+c.appInfo.appName+"/"+c.appInfo.appVersion) } } -// RemoveIncompleteUpload - abort a specific in progress active multipart upload. -// Requires explicit authentication, no anonymous requests are allowed for multipart API. -func (a API) RemoveIncompleteUpload(bucket, object string) <-chan error { - errorCh := make(chan error) - go a.removeIncompleteUploadInRoutine(bucket, object, errorCh) - return errorCh +// makeTargetURL make a new target url. +func (c Client) makeTargetURL(bucketName, objectName, bucketLocation string, queryValues url.Values) (*url.URL, error) { + // Save host. + host := c.endpointURL.Host + // For Amazon S3 endpoint, try to fetch location based endpoint. + if isAmazonEndpoint(c.endpointURL) { + // Fetch new host based on the bucket location. + host = getS3Endpoint(bucketLocation) + } + // Save scheme. + scheme := c.endpointURL.Scheme + + urlStr := scheme + "://" + host + "/" + // Make URL only if bucketName is available, otherwise use the + // endpoint URL. + if bucketName != "" { + // Save if target url will have buckets which suppport virtual host. + isVirtualHostStyle := isVirtualHostSupported(c.endpointURL, bucketName) + + // If endpoint supports virtual host style use that always. + // Currently only S3 and Google Cloud Storage would support + // virtual host style. + if isVirtualHostStyle { + urlStr = scheme + "://" + bucketName + "." + host + "/" + if objectName != "" { + urlStr = urlStr + urlEncodePath(objectName) + } + } else { + // If not fall back to using path style. + urlStr = urlStr + bucketName + if objectName != "" { + urlStr = urlStr + "/" + urlEncodePath(objectName) + } + } + } + // If there are any query values, add them to the end. + if len(queryValues) > 0 { + urlStr = urlStr + "?" + queryValues.Encode() + } + u, err := url.Parse(urlStr) + if err != nil { + return nil, err + } + + return u, nil +} + +// CloudStorageClient - Cloud Storage Client interface. +type CloudStorageClient interface { + // Bucket Read/Write/Stat operations. + MakeBucket(bucketName string, cannedACL BucketACL, location string) error + BucketExists(bucketName string) error + RemoveBucket(bucketName string) error + SetBucketACL(bucketName string, cannedACL BucketACL) error + GetBucketACL(bucketName string) (BucketACL, error) + + ListBuckets() ([]BucketInfo, error) + ListObjects(bucket, prefix string, recursive bool, doneCh <-chan struct{}) <-chan ObjectInfo + ListIncompleteUploads(bucket, prefix string, recursive bool, doneCh <-chan struct{}) <-chan ObjectMultipartInfo + + // Object Read/Write/Stat operations. + GetObject(bucketName, objectName string) (reader *Object, err error) + PutObject(bucketName, objectName string, reader io.Reader, contentType string) (n int64, err error) + StatObject(bucketName, objectName string) (ObjectInfo, error) + RemoveObject(bucketName, objectName string) error + RemoveIncompleteUpload(bucketName, objectName string) error + + // File to Object API. + FPutObject(bucketName, objectName, filePath, contentType string) (n int64, err error) + FGetObject(bucketName, objectName, filePath string) error + + // PutObjectWithProgress for progress. + PutObjectWithProgress(bucketName, objectName string, reader io.Reader, contentType string, progress io.Reader) (n int64, err error) + + // Presigned operations. + PresignedGetObject(bucketName, objectName string, expires time.Duration) (presignedURL string, err error) + PresignedPutObject(bucketName, objectName string, expires time.Duration) (presignedURL string, err error) + PresignedPostPolicy(*PostPolicy) (formData map[string]string, err error) + + // Application info. + SetAppInfo(appName, appVersion string) + + // Set custom transport. + SetCustomTransport(customTransport http.RoundTripper) + + // HTTP tracing methods. + TraceOn(traceOutput io.Writer) error + TraceOff() } diff --git a/vendor/github.com/minio/minio-go/api_functional_v2_test.go b/vendor/github.com/minio/minio-go/api_functional_v2_test.go new file mode 100644 index 00000000..1c7da682 --- /dev/null +++ b/vendor/github.com/minio/minio-go/api_functional_v2_test.go @@ -0,0 +1,945 @@ +/* + * Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2015 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_test + +import ( + "bytes" + crand "crypto/rand" + "errors" + "io" + "io/ioutil" + "math/rand" + "net/http" + "os" + "testing" + "time" + + "github.com/minio/minio-go" +) + +func TestGetObjectClosedTwiceV2(t *testing.T) { + if testing.Short() { + t.Skip("skipping functional tests for short runs") + } + + // Seed random based on current time. + rand.Seed(time.Now().Unix()) + + // Connect and make sure bucket exists. + c, err := minio.New( + "s3.amazonaws.com", + os.Getenv("ACCESS_KEY"), + os.Getenv("SECRET_KEY"), + false, + ) + if err != nil { + t.Fatal("Error:", err) + } + + // Enable tracing, write to stderr. + // c.TraceOn(os.Stderr) + + // Set user agent. + c.SetAppInfo("Minio-go-FunctionalTest", "0.1.0") + + // Generate a new random bucket name. + bucketName := randString(60, rand.NewSource(time.Now().UnixNano())) + + // Make a new bucket. + err = c.MakeBucket(bucketName, "private", "us-east-1") + if err != nil { + t.Fatal("Error:", err, bucketName) + } + + // Generate data more than 32K + buf := make([]byte, rand.Intn(1<<20)+32*1024) + + _, err = io.ReadFull(crand.Reader, buf) + if err != nil { + t.Fatal("Error:", err) + } + + // Save the data + objectName := randString(60, rand.NewSource(time.Now().UnixNano())) + n, err := c.PutObject(bucketName, objectName, bytes.NewReader(buf), "binary/octet-stream") + if err != nil { + t.Fatal("Error:", err, bucketName, objectName) + } + + if n != int64(len(buf)) { + t.Fatalf("Error: number of bytes does not match, want %v, got %v\n", len(buf), n) + } + + // Read the data back + r, err := c.GetObject(bucketName, objectName) + if err != nil { + t.Fatal("Error:", err, bucketName, objectName) + } + + st, err := r.Stat() + if err != nil { + t.Fatal("Error:", err, bucketName, objectName) + } + if st.Size != int64(len(buf)) { + t.Fatalf("Error: number of bytes in stat does not match, want %v, got %v\n", + len(buf), st.Size) + } + if err := r.Close(); err != nil { + t.Fatal("Error:", err) + } + if err := r.Close(); err == nil { + t.Fatal("Error: object is already closed, should return error") + } + + err = c.RemoveObject(bucketName, objectName) + if err != nil { + t.Fatal("Error: ", err) + } + err = c.RemoveBucket(bucketName) + if err != nil { + t.Fatal("Error:", err) + } +} + +// Tests removing partially uploaded objects. +func TestRemovePartiallyUploadedV2(t *testing.T) { + if testing.Short() { + t.Skip("skipping function tests for short runs") + } + + // Seed random based on current time. + rand.Seed(time.Now().Unix()) + + // Connect and make sure bucket exists. + c, err := minio.NewV2( + "s3.amazonaws.com", + os.Getenv("ACCESS_KEY"), + os.Getenv("SECRET_KEY"), + false, + ) + if err != nil { + t.Fatal("Error:", err) + } + + // Set user agent. + c.SetAppInfo("Minio-go-FunctionalTest", "0.1.0") + + // Enable tracing, write to stdout. + // c.TraceOn(os.Stderr) + + // Generate a new random bucket name. + bucketName := randString(60, rand.NewSource(time.Now().UnixNano())) + + // make a new bucket. + err = c.MakeBucket(bucketName, "private", "us-east-1") + if err != nil { + t.Fatal("Error:", err, bucketName) + } + + reader, writer := io.Pipe() + go func() { + i := 0 + for i < 25 { + _, err = io.CopyN(writer, crand.Reader, 128*1024) + if err != nil { + t.Fatal("Error:", err, bucketName) + } + i++ + } + writer.CloseWithError(errors.New("Proactively closed to be verified later.")) + }() + + objectName := bucketName + "-resumable" + _, err = c.PutObject(bucketName, objectName, reader, "application/octet-stream") + if err == nil { + t.Fatal("Error: PutObject should fail.") + } + if err.Error() != "Proactively closed to be verified later." { + t.Fatal("Error:", err) + } + err = c.RemoveIncompleteUpload(bucketName, objectName) + if err != nil { + t.Fatal("Error:", err) + } + err = c.RemoveBucket(bucketName) + if err != nil { + t.Fatal("Error:", err) + } +} + +// Tests resumable put object cloud to cloud. +func TestResumbalePutObjectV2(t *testing.T) { + // By passing 'go test -short' skips these tests. + if testing.Short() { + t.Skip("skipping functional tests for the short runs") + } + + // Seed random based on current time. + rand.Seed(time.Now().Unix()) + + // Connect and make sure bucket exists. + c, err := minio.New( + "s3.amazonaws.com", + os.Getenv("ACCESS_KEY"), + os.Getenv("SECRET_KEY"), + false, + ) + if err != nil { + t.Fatal("Error:", err) + } + + // Set user agent. + c.SetAppInfo("Minio-go-FunctionalTest", "0.1.0") + + // Enable tracing, write to stdout. + // c.TraceOn(os.Stderr) + + // Generate a new random bucket name. + bucketName := randString(60, rand.NewSource(time.Now().UnixNano())) + + // Make a new bucket. + err = c.MakeBucket(bucketName, "private", "us-east-1") + if err != nil { + t.Fatal("Error:", err, bucketName) + } + + // Create a temporary file. + file, err := ioutil.TempFile(os.TempDir(), "resumable") + if err != nil { + t.Fatal("Error:", err) + } + + // Copy 11MiB worth of random data. + n, err := io.CopyN(file, crand.Reader, 11*1024*1024) + if err != nil { + t.Fatal("Error:", err) + } + if n != int64(11*1024*1024) { + t.Fatalf("Error: number of bytes does not match, want %v, got %v\n", 11*1024*1024, n) + } + + // Close the file pro-actively for windows. + if err = file.Close(); err != nil { + t.Fatal("Error:", err) + } + + // New object name. + objectName := bucketName + "-resumable" + + // Upload the file. + n, err = c.FPutObject(bucketName, objectName, file.Name(), "application/octet-stream") + if err != nil { + t.Fatal("Error:", err) + } + if n != int64(11*1024*1024) { + t.Fatalf("Error: number of bytes does not match, want %v, got %v\n", 11*1024*1024, n) + } + + // Get the uploaded object. + reader, err := c.GetObject(bucketName, objectName) + if err != nil { + t.Fatal("Error:", err) + } + + // Upload now cloud to cloud. + n, err = c.PutObject(bucketName, objectName+"-put", reader, "application/octest-stream") + if err != nil { + t.Fatal("Error:", err) + } + + // Get object info. + objInfo, err := reader.Stat() + if err != nil { + t.Fatal("Error:", err) + } + if n != objInfo.Size { + t.Fatalf("Error: number of bytes does not match, want %v, got %v\n", objInfo.Size, n) + } + + // Remove all temp files, objects and bucket. + err = c.RemoveObject(bucketName, objectName) + if err != nil { + t.Fatal("Error: ", err) + } + + err = c.RemoveObject(bucketName, objectName+"-put") + if err != nil { + t.Fatal("Error: ", err) + } + + err = c.RemoveBucket(bucketName) + if err != nil { + t.Fatal("Error:", err) + } + + err = os.Remove(file.Name()) + if err != nil { + t.Fatal("Error:", err) + } + +} + +// Tests resumable file based put object multipart upload. +func TestResumableFPutObjectV2(t *testing.T) { + if testing.Short() { + t.Skip("skipping functional tests for the short runs") + } + + // Seed random based on current time. + rand.Seed(time.Now().Unix()) + + // Connect and make sure bucket exists. + c, err := minio.New( + "s3.amazonaws.com", + os.Getenv("ACCESS_KEY"), + os.Getenv("SECRET_KEY"), + false, + ) + if err != nil { + t.Fatal("Error:", err) + } + + // Set user agent. + c.SetAppInfo("Minio-go-FunctionalTest", "0.1.0") + + // Enable tracing, write to stdout. + // c.TraceOn(os.Stderr) + + // Generate a new random bucket name. + bucketName := randString(60, rand.NewSource(time.Now().UnixNano())) + + // make a new bucket. + err = c.MakeBucket(bucketName, "private", "us-east-1") + if err != nil { + t.Fatal("Error:", err, bucketName) + } + + file, err := ioutil.TempFile(os.TempDir(), "resumable") + if err != nil { + t.Fatal("Error:", err) + } + + n, err := io.CopyN(file, crand.Reader, 11*1024*1024) + if err != nil { + t.Fatal("Error:", err) + } + if n != int64(11*1024*1024) { + t.Fatalf("Error: number of bytes does not match, want %v, got %v\n", 11*1024*1024, n) + } + + objectName := bucketName + "-resumable" + + n, err = c.FPutObject(bucketName, objectName, file.Name(), "application/octet-stream") + if err != nil { + t.Fatal("Error:", err) + } + if n != int64(11*1024*1024) { + t.Fatalf("Error: number of bytes does not match, want %v, got %v\n", 11*1024*1024, n) + } + + // Close the file pro-actively for windows. + file.Close() + + err = c.RemoveObject(bucketName, objectName) + if err != nil { + t.Fatal("Error: ", err) + } + + err = c.RemoveBucket(bucketName) + if err != nil { + t.Fatal("Error:", err) + } + + err = os.Remove(file.Name()) + if err != nil { + t.Fatal("Error:", err) + } +} + +// Tests resumable put object multipart upload. +func TestResumablePutObjectV2(t *testing.T) { + if testing.Short() { + t.Skip("skipping functional tests for the short runs") + } + + // Seed random based on current time. + rand.Seed(time.Now().Unix()) + + // Connect and make sure bucket exists. + c, err := minio.New( + "s3.amazonaws.com", + os.Getenv("ACCESS_KEY"), + os.Getenv("SECRET_KEY"), + false, + ) + if err != nil { + t.Fatal("Error:", err) + } + + // Enable tracing, write to stderr. + // c.TraceOn(os.Stderr) + + // Set user agent. + c.SetAppInfo("Minio-go-FunctionalTest", "0.1.0") + + // Generate a new random bucket name. + bucketName := randString(60, rand.NewSource(time.Now().UnixNano())) + + // make a new bucket. + err = c.MakeBucket(bucketName, "private", "us-east-1") + if err != nil { + t.Fatal("Error:", err, bucketName) + } + + // generate 11MB + buf := make([]byte, 11*1024*1024) + + _, err = io.ReadFull(crand.Reader, buf) + if err != nil { + t.Fatal("Error:", err) + } + + objectName := bucketName + "-resumable" + reader := bytes.NewReader(buf) + n, err := c.PutObject(bucketName, objectName, reader, "application/octet-stream") + if err != nil { + t.Fatal("Error:", err, bucketName, objectName) + } + if n != int64(len(buf)) { + t.Fatalf("Error: number of bytes does not match, want %v, got %v\n", len(buf), n) + } + + err = c.RemoveObject(bucketName, objectName) + if err != nil { + t.Fatal("Error: ", err) + } + + err = c.RemoveBucket(bucketName) + if err != nil { + t.Fatal("Error:", err) + } +} + +// Tests get object ReaderSeeker interface methods. +func TestGetObjectReadSeekFunctionalV2(t *testing.T) { + if testing.Short() { + t.Skip("skipping functional tests for short runs") + } + + // Seed random based on current time. + rand.Seed(time.Now().Unix()) + + // Connect and make sure bucket exists. + c, err := minio.New( + "s3.amazonaws.com", + os.Getenv("ACCESS_KEY"), + os.Getenv("SECRET_KEY"), + false, + ) + if err != nil { + t.Fatal("Error:", err) + } + + // Enable tracing, write to stderr. + // c.TraceOn(os.Stderr) + + // Set user agent. + c.SetAppInfo("Minio-go-FunctionalTest", "0.1.0") + + // Generate a new random bucket name. + bucketName := randString(60, rand.NewSource(time.Now().UnixNano())) + + // Make a new bucket. + err = c.MakeBucket(bucketName, "private", "us-east-1") + if err != nil { + t.Fatal("Error:", err, bucketName) + } + + // Generate data more than 32K + buf := make([]byte, rand.Intn(1<<20)+32*1024) + + _, err = io.ReadFull(crand.Reader, buf) + if err != nil { + t.Fatal("Error:", err) + } + + // Save the data + objectName := randString(60, rand.NewSource(time.Now().UnixNano())) + n, err := c.PutObject(bucketName, objectName, bytes.NewReader(buf), "binary/octet-stream") + if err != nil { + t.Fatal("Error:", err, bucketName, objectName) + } + + if n != int64(len(buf)) { + t.Fatalf("Error: number of bytes does not match, want %v, got %v\n", len(buf), n) + } + + // Read the data back + r, err := c.GetObject(bucketName, objectName) + if err != nil { + t.Fatal("Error:", err, bucketName, objectName) + } + + st, err := r.Stat() + if err != nil { + t.Fatal("Error:", err, bucketName, objectName) + } + if st.Size != int64(len(buf)) { + t.Fatalf("Error: number of bytes in stat does not match, want %v, got %v\n", + len(buf), st.Size) + } + + offset := int64(2048) + n, err = r.Seek(offset, 0) + if err != nil { + t.Fatal("Error:", err, offset) + } + if n != offset { + t.Fatalf("Error: number of bytes seeked does not match, want %v, got %v\n", + offset, n) + } + n, err = r.Seek(0, 1) + if err != nil { + t.Fatal("Error:", err) + } + if n != offset { + t.Fatalf("Error: number of current seek does not match, want %v, got %v\n", + offset, n) + } + _, err = r.Seek(offset, 2) + if err == nil { + t.Fatal("Error: seek on positive offset for whence '2' should error out") + } + n, err = r.Seek(-offset, 2) + if err != nil { + t.Fatal("Error:", err) + } + if n != 0 { + t.Fatalf("Error: number of bytes seeked back does not match, want 0, got %v\n", n) + } + var buffer bytes.Buffer + if _, err = io.CopyN(&buffer, r, st.Size); err != nil { + t.Fatal("Error:", err) + } + if !bytes.Equal(buf, buffer.Bytes()) { + t.Fatal("Error: Incorrect read bytes v/s original buffer.") + } + err = c.RemoveObject(bucketName, objectName) + if err != nil { + t.Fatal("Error: ", err) + } + err = c.RemoveBucket(bucketName) + if err != nil { + t.Fatal("Error:", err) + } +} + +// Tests get object ReaderAt interface methods. +func TestGetObjectReadAtFunctionalV2(t *testing.T) { + if testing.Short() { + t.Skip("skipping functional tests for the short runs") + } + + // Seed random based on current time. + rand.Seed(time.Now().Unix()) + + // Connect and make sure bucket exists. + c, err := minio.New( + "s3.amazonaws.com", + os.Getenv("ACCESS_KEY"), + os.Getenv("SECRET_KEY"), + false, + ) + if err != nil { + t.Fatal("Error:", err) + } + + // Enable tracing, write to stderr. + // c.TraceOn(os.Stderr) + + // Set user agent. + c.SetAppInfo("Minio-go-FunctionalTest", "0.1.0") + + // Generate a new random bucket name. + bucketName := randString(60, rand.NewSource(time.Now().UnixNano())) + + // Make a new bucket. + err = c.MakeBucket(bucketName, "private", "us-east-1") + if err != nil { + t.Fatal("Error:", err, bucketName) + } + + // Generate data more than 32K + buf := make([]byte, rand.Intn(1<<20)+32*1024) + + _, err = io.ReadFull(crand.Reader, buf) + if err != nil { + t.Fatal("Error:", err) + } + + // Save the data + objectName := randString(60, rand.NewSource(time.Now().UnixNano())) + n, err := c.PutObject(bucketName, objectName, bytes.NewReader(buf), "binary/octet-stream") + if err != nil { + t.Fatal("Error:", err, bucketName, objectName) + } + + if n != int64(len(buf)) { + t.Fatalf("Error: number of bytes does not match, want %v, got %v\n", len(buf), n) + } + + // Read the data back + r, err := c.GetObject(bucketName, objectName) + if err != nil { + t.Fatal("Error:", err, bucketName, objectName) + } + + st, err := r.Stat() + if err != nil { + t.Fatal("Error:", err, bucketName, objectName) + } + if st.Size != int64(len(buf)) { + t.Fatalf("Error: number of bytes in stat does not match, want %v, got %v\n", + len(buf), st.Size) + } + + offset := int64(2048) + + // Read directly + buf2 := make([]byte, 512) + buf3 := make([]byte, 512) + buf4 := make([]byte, 512) + + m, err := r.ReadAt(buf2, offset) + if err != nil { + t.Fatal("Error:", err, st.Size, len(buf2), offset) + } + if m != len(buf2) { + t.Fatalf("Error: ReadAt read shorter bytes before reaching EOF, want %v, got %v\n", m, len(buf2)) + } + if !bytes.Equal(buf2, buf[offset:offset+512]) { + t.Fatal("Error: Incorrect read between two ReadAt from same offset.") + } + offset += 512 + m, err = r.ReadAt(buf3, offset) + if err != nil { + t.Fatal("Error:", err, st.Size, len(buf3), offset) + } + if m != len(buf3) { + t.Fatalf("Error: ReadAt read shorter bytes before reaching EOF, want %v, got %v\n", m, len(buf3)) + } + if !bytes.Equal(buf3, buf[offset:offset+512]) { + t.Fatal("Error: Incorrect read between two ReadAt from same offset.") + } + offset += 512 + m, err = r.ReadAt(buf4, offset) + if err != nil { + t.Fatal("Error:", err, st.Size, len(buf4), offset) + } + if m != len(buf4) { + t.Fatalf("Error: ReadAt read shorter bytes before reaching EOF, want %v, got %v\n", m, len(buf4)) + } + if !bytes.Equal(buf4, buf[offset:offset+512]) { + t.Fatal("Error: Incorrect read between two ReadAt from same offset.") + } + + buf5 := make([]byte, n) + // Read the whole object. + m, err = r.ReadAt(buf5, 0) + if err != nil { + if err != io.EOF { + t.Fatal("Error:", err, len(buf5)) + } + } + if m != len(buf5) { + t.Fatalf("Error: ReadAt read shorter bytes before reaching EOF, want %v, got %v\n", m, len(buf5)) + } + if !bytes.Equal(buf, buf5) { + t.Fatal("Error: Incorrect data read in GetObject, than what was previously upoaded.") + } + + buf6 := make([]byte, n+1) + // Read the whole object and beyond. + _, err = r.ReadAt(buf6, 0) + if err != nil { + if err != io.EOF { + t.Fatal("Error:", err, len(buf6)) + } + } + err = c.RemoveObject(bucketName, objectName) + if err != nil { + t.Fatal("Error: ", err) + } + err = c.RemoveBucket(bucketName) + if err != nil { + t.Fatal("Error:", err) + } +} + +// Tests comprehensive list of all methods. +func TestFunctionalV2(t *testing.T) { + if testing.Short() { + t.Skip("skipping functional tests for the short runs") + } + + // Seed random based on current time. + rand.Seed(time.Now().Unix()) + + c, err := minio.New( + "s3.amazonaws.com", + os.Getenv("ACCESS_KEY"), + os.Getenv("SECRET_KEY"), + false, + ) + if err != nil { + t.Fatal("Error:", err) + } + + // Enable to debug + // c.TraceOn(os.Stderr) + + // Set user agent. + c.SetAppInfo("Minio-go-FunctionalTest", "0.1.0") + + // Generate a new random bucket name. + bucketName := randString(60, rand.NewSource(time.Now().UnixNano())) + + // Make a new bucket. + err = c.MakeBucket(bucketName, "private", "us-east-1") + if err != nil { + t.Fatal("Error:", err, bucketName) + } + + // Generate a random file name. + fileName := randString(60, rand.NewSource(time.Now().UnixNano())) + file, err := os.Create(fileName) + if err != nil { + t.Fatal("Error:", err) + } + for i := 0; i < 3; i++ { + buf := make([]byte, rand.Intn(1<<19)) + _, err = file.Write(buf) + if err != nil { + t.Fatal("Error:", err) + } + } + file.Close() + + // Verify if bucket exits and you have access. + err = c.BucketExists(bucketName) + if err != nil { + t.Fatal("Error:", err, bucketName) + } + + // Make the bucket 'public read/write'. + err = c.SetBucketACL(bucketName, "public-read-write") + if err != nil { + t.Fatal("Error:", err) + } + + // Get the previously set acl. + acl, err := c.GetBucketACL(bucketName) + if err != nil { + t.Fatal("Error:", err) + } + + // ACL must be 'public read/write'. + if acl != minio.BucketACL("public-read-write") { + t.Fatal("Error:", acl) + } + + // List all buckets. + buckets, err := c.ListBuckets() + if len(buckets) == 0 { + t.Fatal("Error: list buckets cannot be empty", buckets) + } + if err != nil { + t.Fatal("Error:", err) + } + + // Verify if previously created bucket is listed in list buckets. + bucketFound := false + for _, bucket := range buckets { + if bucket.Name == bucketName { + bucketFound = true + } + } + + // If bucket not found error out. + if !bucketFound { + t.Fatal("Error: bucket ", bucketName, "not found") + } + + objectName := bucketName + "unique" + + // Generate data + buf := make([]byte, rand.Intn(1<<19)) + _, err = io.ReadFull(crand.Reader, buf) + if err != nil { + t.Fatal("Error: ", err) + } + + n, err := c.PutObject(bucketName, objectName, bytes.NewReader(buf), "") + if err != nil { + t.Fatal("Error: ", err) + } + if n != int64(len(buf)) { + t.Fatal("Error: bad length ", n, len(buf)) + } + + n, err = c.PutObject(bucketName, objectName+"-nolength", bytes.NewReader(buf), "binary/octet-stream") + if err != nil { + t.Fatal("Error:", err, bucketName, objectName+"-nolength") + } + + if n != int64(len(buf)) { + t.Fatalf("Error: number of bytes does not match, want %v, got %v\n", len(buf), n) + } + + // Instantiate a done channel to close all listing. + doneCh := make(chan struct{}) + defer close(doneCh) + + objFound := false + isRecursive := true // Recursive is true. + for obj := range c.ListObjects(bucketName, objectName, isRecursive, doneCh) { + if obj.Key == objectName { + objFound = true + break + } + } + if !objFound { + t.Fatal("Error: object " + objectName + " not found.") + } + + incompObjNotFound := true + for objIncompl := range c.ListIncompleteUploads(bucketName, objectName, isRecursive, doneCh) { + if objIncompl.Key != "" { + incompObjNotFound = false + break + } + } + if !incompObjNotFound { + t.Fatal("Error: unexpected dangling incomplete upload found.") + } + + newReader, err := c.GetObject(bucketName, objectName) + if err != nil { + t.Fatal("Error: ", err) + } + + newReadBytes, err := ioutil.ReadAll(newReader) + if err != nil { + t.Fatal("Error: ", err) + } + + if !bytes.Equal(newReadBytes, buf) { + t.Fatal("Error: bytes mismatch.") + } + + err = c.FGetObject(bucketName, objectName, fileName+"-f") + if err != nil { + t.Fatal("Error: ", err) + } + + presignedGetURL, err := c.PresignedGetObject(bucketName, objectName, 3600*time.Second) + if err != nil { + t.Fatal("Error: ", err) + } + + resp, err := http.Get(presignedGetURL) + if err != nil { + t.Fatal("Error: ", err) + } + if resp.StatusCode != http.StatusOK { + t.Fatal("Error: ", resp.Status) + } + newPresignedBytes, err := ioutil.ReadAll(resp.Body) + if err != nil { + t.Fatal("Error: ", err) + } + if !bytes.Equal(newPresignedBytes, buf) { + t.Fatal("Error: bytes mismatch.") + } + + presignedPutURL, err := c.PresignedPutObject(bucketName, objectName+"-presigned", 3600*time.Second) + if err != nil { + t.Fatal("Error: ", err) + } + buf = make([]byte, rand.Intn(1<<20)) + _, err = io.ReadFull(crand.Reader, buf) + if err != nil { + t.Fatal("Error: ", err) + } + req, err := http.NewRequest("PUT", presignedPutURL, bytes.NewReader(buf)) + if err != nil { + t.Fatal("Error: ", err) + } + httpClient := &http.Client{} + resp, err = httpClient.Do(req) + if err != nil { + t.Fatal("Error: ", err) + } + + newReader, err = c.GetObject(bucketName, objectName+"-presigned") + if err != nil { + t.Fatal("Error: ", err) + } + + newReadBytes, err = ioutil.ReadAll(newReader) + if err != nil { + t.Fatal("Error: ", err) + } + + if !bytes.Equal(newReadBytes, buf) { + t.Fatal("Error: bytes mismatch.") + } + + err = c.RemoveObject(bucketName, objectName) + if err != nil { + t.Fatal("Error: ", err) + } + err = c.RemoveObject(bucketName, objectName+"-f") + if err != nil { + t.Fatal("Error: ", err) + } + err = c.RemoveObject(bucketName, objectName+"-nolength") + if err != nil { + t.Fatal("Error: ", err) + } + err = c.RemoveObject(bucketName, objectName+"-presigned") + if err != nil { + t.Fatal("Error: ", err) + } + err = c.RemoveBucket(bucketName) + if err != nil { + t.Fatal("Error:", err) + } + err = c.RemoveBucket(bucketName) + if err == nil { + t.Fatal("Error:") + } + if err.Error() != "The specified bucket does not exist" { + t.Fatal("Error: ", err) + } + if err = os.Remove(fileName); err != nil { + t.Fatal("Error: ", err) + } + if err = os.Remove(fileName + "-f"); err != nil { + t.Fatal("Error: ", err) + } +} diff --git a/vendor/github.com/minio/minio-go/api_functional_v4_test.go b/vendor/github.com/minio/minio-go/api_functional_v4_test.go new file mode 100644 index 00000000..ba7b7614 --- /dev/null +++ b/vendor/github.com/minio/minio-go/api_functional_v4_test.go @@ -0,0 +1,1026 @@ +/* + * Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2015 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_test + +import ( + "bytes" + crand "crypto/rand" + "errors" + "io" + "io/ioutil" + "math/rand" + "net/http" + "os" + "testing" + "time" + + "github.com/minio/minio-go" +) + +const letterBytes = "abcdefghijklmnopqrstuvwxyz01234569" +const ( + letterIdxBits = 6 // 6 bits to represent a letter index + letterIdxMask = 1<= 0; { + if remain == 0 { + cache, remain = src.Int63(), letterIdxMax + } + if idx := int(cache & letterIdxMask); idx < len(letterBytes) { + b[i] = letterBytes[idx] + i-- + } + cache >>= letterIdxBits + remain-- + } + return string(b[0:30]) +} + +// Tests various bucket supported formats. +func TestMakeBucketRegions(t *testing.T) { + if testing.Short() { + t.Skip("skipping functional tests for short runs") + } + + // Seed random based on current time. + rand.Seed(time.Now().Unix()) + + // Connect and make sure bucket exists. + c, err := minio.New( + "s3.amazonaws.com", + os.Getenv("ACCESS_KEY"), + os.Getenv("SECRET_KEY"), + false, + ) + if err != nil { + t.Fatal("Error:", err) + } + + // Enable tracing, write to stderr. + // c.TraceOn(os.Stderr) + + // Set user agent. + c.SetAppInfo("Minio-go-FunctionalTest", "0.1.0") + + // Generate a new random bucket name. + bucketName := randString(60, rand.NewSource(time.Now().UnixNano())) + + // Make a new bucket in 'eu-central-1'. + if err = c.MakeBucket(bucketName, "private", "eu-central-1"); err != nil { + t.Fatal("Error:", err, bucketName) + } + + if err = c.RemoveBucket(bucketName); err != nil { + t.Fatal("Error:", err, bucketName) + } + + // Make a new bucket with '.' in its name, in 'us-west-2'. This + // request is internally staged into a path style instead of + // virtual host style. + if err = c.MakeBucket(bucketName+".withperiod", "private", "us-west-2"); err != nil { + t.Fatal("Error:", err, bucketName+".withperiod") + } + + // Remove the newly created bucket. + if err = c.RemoveBucket(bucketName + ".withperiod"); err != nil { + t.Fatal("Error:", err, bucketName+".withperiod") + } +} + +// Test get object reader to not throw error on being closed twice. +func TestGetObjectClosedTwice(t *testing.T) { + if testing.Short() { + t.Skip("skipping functional tests for short runs") + } + + // Seed random based on current time. + rand.Seed(time.Now().Unix()) + + // Connect and make sure bucket exists. + c, err := minio.New( + "s3.amazonaws.com", + os.Getenv("ACCESS_KEY"), + os.Getenv("SECRET_KEY"), + false, + ) + if err != nil { + t.Fatal("Error:", err) + } + + // Enable tracing, write to stderr. + // c.TraceOn(os.Stderr) + + // Set user agent. + c.SetAppInfo("Minio-go-FunctionalTest", "0.1.0") + + // Generate a new random bucket name. + bucketName := randString(60, rand.NewSource(time.Now().UnixNano())) + + // Make a new bucket. + err = c.MakeBucket(bucketName, "private", "us-east-1") + if err != nil { + t.Fatal("Error:", err, bucketName) + } + + // Generate data more than 32K + buf := make([]byte, rand.Intn(1<<20)+32*1024) + + _, err = io.ReadFull(crand.Reader, buf) + if err != nil { + t.Fatal("Error:", err) + } + + // Save the data + objectName := randString(60, rand.NewSource(time.Now().UnixNano())) + n, err := c.PutObject(bucketName, objectName, bytes.NewReader(buf), "binary/octet-stream") + if err != nil { + t.Fatal("Error:", err, bucketName, objectName) + } + + if n != int64(len(buf)) { + t.Fatalf("Error: number of bytes does not match, want %v, got %v\n", len(buf), n) + } + + // Read the data back + r, err := c.GetObject(bucketName, objectName) + if err != nil { + t.Fatal("Error:", err, bucketName, objectName) + } + + st, err := r.Stat() + if err != nil { + t.Fatal("Error:", err, bucketName, objectName) + } + if st.Size != int64(len(buf)) { + t.Fatalf("Error: number of bytes in stat does not match, want %v, got %v\n", + len(buf), st.Size) + } + if err := r.Close(); err != nil { + t.Fatal("Error:", err) + } + if err := r.Close(); err == nil { + t.Fatal("Error: object is already closed, should return error") + } + + err = c.RemoveObject(bucketName, objectName) + if err != nil { + t.Fatal("Error: ", err) + } + err = c.RemoveBucket(bucketName) + if err != nil { + t.Fatal("Error:", err) + } +} + +// Tests removing partially uploaded objects. +func TestRemovePartiallyUploaded(t *testing.T) { + if testing.Short() { + t.Skip("skipping function tests for short runs") + } + + // Seed random based on current time. + rand.Seed(time.Now().Unix()) + + // Connect and make sure bucket exists. + c, err := minio.New( + "s3.amazonaws.com", + os.Getenv("ACCESS_KEY"), + os.Getenv("SECRET_KEY"), + false, + ) + if err != nil { + t.Fatal("Error:", err) + } + + // Set user agent. + c.SetAppInfo("Minio-go-FunctionalTest", "0.1.0") + + // Enable tracing, write to stdout. + // c.TraceOn(os.Stderr) + + // Generate a new random bucket name. + bucketName := randString(60, rand.NewSource(time.Now().UnixNano())) + + // Make a new bucket. + err = c.MakeBucket(bucketName, "private", "us-east-1") + if err != nil { + t.Fatal("Error:", err, bucketName) + } + + reader, writer := io.Pipe() + go func() { + i := 0 + for i < 25 { + _, err = io.CopyN(writer, crand.Reader, 128*1024) + if err != nil { + t.Fatal("Error:", err, bucketName) + } + i++ + } + err = writer.CloseWithError(errors.New("Proactively closed to be verified later.")) + if err != nil { + t.Fatal("Error:", err) + } + }() + + objectName := bucketName + "-resumable" + _, err = c.PutObject(bucketName, objectName, reader, "application/octet-stream") + if err == nil { + t.Fatal("Error: PutObject should fail.") + } + if err.Error() != "Proactively closed to be verified later." { + t.Fatal("Error:", err) + } + err = c.RemoveIncompleteUpload(bucketName, objectName) + if err != nil { + t.Fatal("Error:", err) + } + err = c.RemoveBucket(bucketName) + if err != nil { + t.Fatal("Error:", err) + } +} + +// Tests resumable put object cloud to cloud. +func TestResumbalePutObject(t *testing.T) { + // By passing 'go test -short' skips these tests. + if testing.Short() { + t.Skip("skipping functional tests for the short runs") + } + + // Seed random based on current time. + rand.Seed(time.Now().Unix()) + + // Connect and make sure bucket exists. + c, err := minio.New( + "s3.amazonaws.com", + os.Getenv("ACCESS_KEY"), + os.Getenv("SECRET_KEY"), + false, + ) + if err != nil { + t.Fatal("Error:", err) + } + + // Set user agent. + c.SetAppInfo("Minio-go-FunctionalTest", "0.1.0") + + // Enable tracing, write to stdout. + // c.TraceOn(os.Stderr) + + // Generate a new random bucket name. + bucketName := randString(60, rand.NewSource(time.Now().UnixNano())) + + // Make a new bucket. + err = c.MakeBucket(bucketName, "private", "us-east-1") + if err != nil { + t.Fatal("Error:", err, bucketName) + } + + // Create a temporary file. + file, err := ioutil.TempFile(os.TempDir(), "resumable") + if err != nil { + t.Fatal("Error:", err) + } + + // Copy 11MiB worth of random data. + n, err := io.CopyN(file, crand.Reader, 11*1024*1024) + if err != nil { + t.Fatal("Error:", err) + } + if n != int64(11*1024*1024) { + t.Fatalf("Error: number of bytes does not match, want %v, got %v\n", 11*1024*1024, n) + } + + // Close the file pro-actively for windows. + if err = file.Close(); err != nil { + t.Fatal("Error:", err) + } + + // New object name. + objectName := bucketName + "-resumable" + + // Upload the file. + n, err = c.FPutObject(bucketName, objectName, file.Name(), "application/octet-stream") + if err != nil { + t.Fatal("Error:", err) + } + if n != int64(11*1024*1024) { + t.Fatalf("Error: number of bytes does not match, want %v, got %v\n", 11*1024*1024, n) + } + + // Get the uploaded object. + reader, err := c.GetObject(bucketName, objectName) + if err != nil { + t.Fatal("Error:", err) + } + + // Upload now cloud to cloud. + n, err = c.PutObject(bucketName, objectName+"-put", reader, "application/octest-stream") + if err != nil { + t.Fatal("Error:", err) + } + + // Get object info. + objInfo, err := reader.Stat() + if err != nil { + t.Fatal("Error:", err) + } + if n != objInfo.Size { + t.Fatalf("Error: number of bytes does not match, want %v, got %v\n", objInfo.Size, n) + } + + // Remove all temp files, objects and bucket. + err = c.RemoveObject(bucketName, objectName) + if err != nil { + t.Fatal("Error: ", err) + } + + err = c.RemoveObject(bucketName, objectName+"-put") + if err != nil { + t.Fatal("Error: ", err) + } + + err = c.RemoveBucket(bucketName) + if err != nil { + t.Fatal("Error:", err) + } + + err = os.Remove(file.Name()) + if err != nil { + t.Fatal("Error:", err) + } +} + +// Tests resumable file based put object multipart upload. +func TestResumableFPutObject(t *testing.T) { + if testing.Short() { + t.Skip("skipping functional tests for the short runs") + } + + // Seed random based on current time. + rand.Seed(time.Now().Unix()) + + // Connect and make sure bucket exists. + c, err := minio.New( + "s3.amazonaws.com", + os.Getenv("ACCESS_KEY"), + os.Getenv("SECRET_KEY"), + false, + ) + if err != nil { + t.Fatal("Error:", err) + } + + // Set user agent. + c.SetAppInfo("Minio-go-FunctionalTest", "0.1.0") + + // Enable tracing, write to stdout. + // c.TraceOn(os.Stderr) + + // Generate a new random bucket name. + bucketName := randString(60, rand.NewSource(time.Now().UnixNano())) + + // Make a new bucket. + err = c.MakeBucket(bucketName, "private", "us-east-1") + if err != nil { + t.Fatal("Error:", err, bucketName) + } + + file, err := ioutil.TempFile(os.TempDir(), "resumable") + if err != nil { + t.Fatal("Error:", err) + } + + n, err := io.CopyN(file, crand.Reader, 11*1024*1024) + if err != nil { + t.Fatal("Error:", err) + } + if n != int64(11*1024*1024) { + t.Fatalf("Error: number of bytes does not match, want %v, got %v\n", 11*1024*1024, n) + } + + // Close the file pro-actively for windows. + err = file.Close() + if err != nil { + t.Fatal("Error:", err) + } + + objectName := bucketName + "-resumable" + + n, err = c.FPutObject(bucketName, objectName, file.Name(), "application/octet-stream") + if err != nil { + t.Fatal("Error:", err) + } + if n != int64(11*1024*1024) { + t.Fatalf("Error: number of bytes does not match, want %v, got %v\n", 11*1024*1024, n) + } + + err = c.RemoveObject(bucketName, objectName) + if err != nil { + t.Fatal("Error: ", err) + } + + err = c.RemoveBucket(bucketName) + if err != nil { + t.Fatal("Error:", err) + } + + err = os.Remove(file.Name()) + if err != nil { + t.Fatal("Error:", err) + } +} + +// Tests resumable put object multipart upload. +func TestResumablePutObject(t *testing.T) { + if testing.Short() { + t.Skip("skipping functional tests for the short runs") + } + + // Seed random based on current time. + rand.Seed(time.Now().Unix()) + + // Connect and make sure bucket exists. + c, err := minio.New( + "s3.amazonaws.com", + os.Getenv("ACCESS_KEY"), + os.Getenv("SECRET_KEY"), + false, + ) + if err != nil { + t.Fatal("Error:", err) + } + + // Enable tracing, write to stderr. + // c.TraceOn(os.Stderr) + + // Set user agent. + c.SetAppInfo("Minio-go-FunctionalTest", "0.1.0") + + // Generate a new random bucket name. + bucketName := randString(60, rand.NewSource(time.Now().UnixNano())) + + // Make a new bucket. + err = c.MakeBucket(bucketName, "private", "us-east-1") + if err != nil { + t.Fatal("Error:", err, bucketName) + } + + // Generate 11MB + buf := make([]byte, 11*1024*1024) + + _, err = io.ReadFull(crand.Reader, buf) + if err != nil { + t.Fatal("Error:", err) + } + + objectName := bucketName + "-resumable" + reader := bytes.NewReader(buf) + n, err := c.PutObject(bucketName, objectName, reader, "application/octet-stream") + if err != nil { + t.Fatal("Error:", err, bucketName, objectName) + } + if n != int64(len(buf)) { + t.Fatalf("Error: number of bytes does not match, want %v, got %v\n", len(buf), n) + } + + err = c.RemoveObject(bucketName, objectName) + if err != nil { + t.Fatal("Error: ", err) + } + + err = c.RemoveBucket(bucketName) + if err != nil { + t.Fatal("Error:", err) + } +} + +// Tests get object ReaderSeeker interface methods. +func TestGetObjectReadSeekFunctional(t *testing.T) { + if testing.Short() { + t.Skip("skipping functional tests for short runs") + } + + // Seed random based on current time. + rand.Seed(time.Now().Unix()) + + // Connect and make sure bucket exists. + c, err := minio.New( + "s3.amazonaws.com", + os.Getenv("ACCESS_KEY"), + os.Getenv("SECRET_KEY"), + false, + ) + if err != nil { + t.Fatal("Error:", err) + } + + // Enable tracing, write to stderr. + // c.TraceOn(os.Stderr) + + // Set user agent. + c.SetAppInfo("Minio-go-FunctionalTest", "0.1.0") + + // Generate a new random bucket name. + bucketName := randString(60, rand.NewSource(time.Now().UnixNano())) + + // Make a new bucket. + err = c.MakeBucket(bucketName, "private", "us-east-1") + if err != nil { + t.Fatal("Error:", err, bucketName) + } + + // Generate data more than 32K + buf := make([]byte, rand.Intn(1<<20)+32*1024) + + _, err = io.ReadFull(crand.Reader, buf) + if err != nil { + t.Fatal("Error:", err) + } + + // Save the data + objectName := randString(60, rand.NewSource(time.Now().UnixNano())) + n, err := c.PutObject(bucketName, objectName, bytes.NewReader(buf), "binary/octet-stream") + if err != nil { + t.Fatal("Error:", err, bucketName, objectName) + } + + if n != int64(len(buf)) { + t.Fatalf("Error: number of bytes does not match, want %v, got %v\n", len(buf), n) + } + + // Read the data back + r, err := c.GetObject(bucketName, objectName) + if err != nil { + t.Fatal("Error:", err, bucketName, objectName) + } + + st, err := r.Stat() + if err != nil { + t.Fatal("Error:", err, bucketName, objectName) + } + if st.Size != int64(len(buf)) { + t.Fatalf("Error: number of bytes in stat does not match, want %v, got %v\n", + len(buf), st.Size) + } + + offset := int64(2048) + n, err = r.Seek(offset, 0) + if err != nil { + t.Fatal("Error:", err, offset) + } + if n != offset { + t.Fatalf("Error: number of bytes seeked does not match, want %v, got %v\n", + offset, n) + } + n, err = r.Seek(0, 1) + if err != nil { + t.Fatal("Error:", err) + } + if n != offset { + t.Fatalf("Error: number of current seek does not match, want %v, got %v\n", + offset, n) + } + _, err = r.Seek(offset, 2) + if err == nil { + t.Fatal("Error: seek on positive offset for whence '2' should error out") + } + n, err = r.Seek(-offset, 2) + if err != nil { + t.Fatal("Error:", err) + } + if n != 0 { + t.Fatalf("Error: number of bytes seeked back does not match, want 0, got %v\n", n) + } + var buffer bytes.Buffer + if _, err = io.CopyN(&buffer, r, st.Size); err != nil { + t.Fatal("Error:", err) + } + if !bytes.Equal(buf, buffer.Bytes()) { + t.Fatal("Error: Incorrect read bytes v/s original buffer.") + } + err = c.RemoveObject(bucketName, objectName) + if err != nil { + t.Fatal("Error: ", err) + } + err = c.RemoveBucket(bucketName) + if err != nil { + t.Fatal("Error:", err) + } +} + +// Tests get object ReaderAt interface methods. +func TestGetObjectReadAtFunctional(t *testing.T) { + if testing.Short() { + t.Skip("skipping functional tests for the short runs") + } + + // Seed random based on current time. + rand.Seed(time.Now().Unix()) + + // Connect and make sure bucket exists. + c, err := minio.New( + "s3.amazonaws.com", + os.Getenv("ACCESS_KEY"), + os.Getenv("SECRET_KEY"), + false, + ) + if err != nil { + t.Fatal("Error:", err) + } + + // Enable tracing, write to stderr. + // c.TraceOn(os.Stderr) + + // Set user agent. + c.SetAppInfo("Minio-go-FunctionalTest", "0.1.0") + + // Generate a new random bucket name. + bucketName := randString(60, rand.NewSource(time.Now().UnixNano())) + + // Make a new bucket. + err = c.MakeBucket(bucketName, "private", "us-east-1") + if err != nil { + t.Fatal("Error:", err, bucketName) + } + + // Generate data more than 32K + buf := make([]byte, rand.Intn(1<<20)+32*1024) + + _, err = io.ReadFull(crand.Reader, buf) + if err != nil { + t.Fatal("Error:", err) + } + + // Save the data + objectName := randString(60, rand.NewSource(time.Now().UnixNano())) + n, err := c.PutObject(bucketName, objectName, bytes.NewReader(buf), "binary/octet-stream") + if err != nil { + t.Fatal("Error:", err, bucketName, objectName) + } + + if n != int64(len(buf)) { + t.Fatalf("Error: number of bytes does not match, want %v, got %v\n", len(buf), n) + } + + // read the data back + r, err := c.GetObject(bucketName, objectName) + if err != nil { + t.Fatal("Error:", err, bucketName, objectName) + } + + st, err := r.Stat() + if err != nil { + t.Fatal("Error:", err, bucketName, objectName) + } + if st.Size != int64(len(buf)) { + t.Fatalf("Error: number of bytes in stat does not match, want %v, got %v\n", + len(buf), st.Size) + } + + offset := int64(2048) + + // read directly + buf2 := make([]byte, 512) + buf3 := make([]byte, 512) + buf4 := make([]byte, 512) + + m, err := r.ReadAt(buf2, offset) + if err != nil { + t.Fatal("Error:", err, st.Size, len(buf2), offset) + } + if m != len(buf2) { + t.Fatalf("Error: ReadAt read shorter bytes before reaching EOF, want %v, got %v\n", m, len(buf2)) + } + if !bytes.Equal(buf2, buf[offset:offset+512]) { + t.Fatal("Error: Incorrect read between two ReadAt from same offset.") + } + offset += 512 + m, err = r.ReadAt(buf3, offset) + if err != nil { + t.Fatal("Error:", err, st.Size, len(buf3), offset) + } + if m != len(buf3) { + t.Fatalf("Error: ReadAt read shorter bytes before reaching EOF, want %v, got %v\n", m, len(buf3)) + } + if !bytes.Equal(buf3, buf[offset:offset+512]) { + t.Fatal("Error: Incorrect read between two ReadAt from same offset.") + } + offset += 512 + m, err = r.ReadAt(buf4, offset) + if err != nil { + t.Fatal("Error:", err, st.Size, len(buf4), offset) + } + if m != len(buf4) { + t.Fatalf("Error: ReadAt read shorter bytes before reaching EOF, want %v, got %v\n", m, len(buf4)) + } + if !bytes.Equal(buf4, buf[offset:offset+512]) { + t.Fatal("Error: Incorrect read between two ReadAt from same offset.") + } + + buf5 := make([]byte, n) + // Read the whole object. + m, err = r.ReadAt(buf5, 0) + if err != nil { + if err != io.EOF { + t.Fatal("Error:", err, len(buf5)) + } + } + if m != len(buf5) { + t.Fatalf("Error: ReadAt read shorter bytes before reaching EOF, want %v, got %v\n", m, len(buf5)) + } + if !bytes.Equal(buf, buf5) { + t.Fatal("Error: Incorrect data read in GetObject, than what was previously upoaded.") + } + + buf6 := make([]byte, n+1) + // Read the whole object and beyond. + _, err = r.ReadAt(buf6, 0) + if err != nil { + if err != io.EOF { + t.Fatal("Error:", err, len(buf6)) + } + } + err = c.RemoveObject(bucketName, objectName) + if err != nil { + t.Fatal("Error: ", err) + } + err = c.RemoveBucket(bucketName) + if err != nil { + t.Fatal("Error:", err) + } +} + +// Tests comprehensive list of all methods. +func TestFunctional(t *testing.T) { + if testing.Short() { + t.Skip("skipping functional tests for the short runs") + } + + // Seed random based on current time. + rand.Seed(time.Now().Unix()) + + c, err := minio.New( + "s3.amazonaws.com", + os.Getenv("ACCESS_KEY"), + os.Getenv("SECRET_KEY"), + false, + ) + if err != nil { + t.Fatal("Error:", err) + } + + // Enable to debug + // c.TraceOn(os.Stderr) + + // Set user agent. + c.SetAppInfo("Minio-go-FunctionalTest", "0.1.0") + + // Generate a new random bucket name. + bucketName := randString(60, rand.NewSource(time.Now().UnixNano())) + + // Make a new bucket. + err = c.MakeBucket(bucketName, "private", "us-east-1") + if err != nil { + t.Fatal("Error:", err, bucketName) + } + + // Generate a random file name. + fileName := randString(60, rand.NewSource(time.Now().UnixNano())) + file, err := os.Create(fileName) + if err != nil { + t.Fatal("Error:", err) + } + for i := 0; i < 3; i++ { + buf := make([]byte, rand.Intn(1<<19)) + _, err = file.Write(buf) + if err != nil { + t.Fatal("Error:", err) + } + } + file.Close() + + // Verify if bucket exits and you have access. + err = c.BucketExists(bucketName) + if err != nil { + t.Fatal("Error:", err, bucketName) + } + + // Make the bucket 'public read/write'. + err = c.SetBucketACL(bucketName, "public-read-write") + if err != nil { + t.Fatal("Error:", err) + } + + // Get the previously set acl. + acl, err := c.GetBucketACL(bucketName) + if err != nil { + t.Fatal("Error:", err) + } + + // ACL must be 'public read/write'. + if acl != minio.BucketACL("public-read-write") { + t.Fatal("Error:", acl) + } + + // List all buckets. + buckets, err := c.ListBuckets() + if len(buckets) == 0 { + t.Fatal("Error: list buckets cannot be empty", buckets) + } + if err != nil { + t.Fatal("Error:", err) + } + + // Verify if previously created bucket is listed in list buckets. + bucketFound := false + for _, bucket := range buckets { + if bucket.Name == bucketName { + bucketFound = true + } + } + + // If bucket not found error out. + if !bucketFound { + t.Fatal("Error: bucket ", bucketName, "not found") + } + + objectName := bucketName + "unique" + + // Generate data + buf := make([]byte, rand.Intn(1<<19)) + _, err = io.ReadFull(crand.Reader, buf) + if err != nil { + t.Fatal("Error: ", err) + } + + n, err := c.PutObject(bucketName, objectName, bytes.NewReader(buf), "") + if err != nil { + t.Fatal("Error: ", err) + } + if n != int64(len(buf)) { + t.Fatal("Error: bad length ", n, len(buf)) + } + + n, err = c.PutObject(bucketName, objectName+"-nolength", bytes.NewReader(buf), "binary/octet-stream") + if err != nil { + t.Fatal("Error:", err, bucketName, objectName+"-nolength") + } + + if n != int64(len(buf)) { + t.Fatalf("Error: number of bytes does not match, want %v, got %v\n", len(buf), n) + } + + // Instantiate a done channel to close all listing. + doneCh := make(chan struct{}) + defer close(doneCh) + + objFound := false + isRecursive := true // Recursive is true. + for obj := range c.ListObjects(bucketName, objectName, isRecursive, doneCh) { + if obj.Key == objectName { + objFound = true + break + } + } + if !objFound { + t.Fatal("Error: object " + objectName + " not found.") + } + + incompObjNotFound := true + for objIncompl := range c.ListIncompleteUploads(bucketName, objectName, isRecursive, doneCh) { + if objIncompl.Key != "" { + incompObjNotFound = false + break + } + } + if !incompObjNotFound { + t.Fatal("Error: unexpected dangling incomplete upload found.") + } + + newReader, err := c.GetObject(bucketName, objectName) + if err != nil { + t.Fatal("Error: ", err) + } + + newReadBytes, err := ioutil.ReadAll(newReader) + if err != nil { + t.Fatal("Error: ", err) + } + + if !bytes.Equal(newReadBytes, buf) { + t.Fatal("Error: bytes mismatch.") + } + + err = c.FGetObject(bucketName, objectName, fileName+"-f") + if err != nil { + t.Fatal("Error: ", err) + } + + presignedGetURL, err := c.PresignedGetObject(bucketName, objectName, 3600*time.Second) + if err != nil { + t.Fatal("Error: ", err) + } + + resp, err := http.Get(presignedGetURL) + if err != nil { + t.Fatal("Error: ", err) + } + if resp.StatusCode != http.StatusOK { + t.Fatal("Error: ", resp.Status) + } + newPresignedBytes, err := ioutil.ReadAll(resp.Body) + if err != nil { + t.Fatal("Error: ", err) + } + if !bytes.Equal(newPresignedBytes, buf) { + t.Fatal("Error: bytes mismatch.") + } + + presignedPutURL, err := c.PresignedPutObject(bucketName, objectName+"-presigned", 3600*time.Second) + if err != nil { + t.Fatal("Error: ", err) + } + buf = make([]byte, rand.Intn(1<<20)) + _, err = io.ReadFull(crand.Reader, buf) + if err != nil { + t.Fatal("Error: ", err) + } + req, err := http.NewRequest("PUT", presignedPutURL, bytes.NewReader(buf)) + if err != nil { + t.Fatal("Error: ", err) + } + httpClient := &http.Client{} + resp, err = httpClient.Do(req) + if err != nil { + t.Fatal("Error: ", err) + } + + newReader, err = c.GetObject(bucketName, objectName+"-presigned") + if err != nil { + t.Fatal("Error: ", err) + } + + newReadBytes, err = ioutil.ReadAll(newReader) + if err != nil { + t.Fatal("Error: ", err) + } + + if !bytes.Equal(newReadBytes, buf) { + t.Fatal("Error: bytes mismatch.") + } + + err = c.RemoveObject(bucketName, objectName) + if err != nil { + t.Fatal("Error: ", err) + } + err = c.RemoveObject(bucketName, objectName+"-f") + if err != nil { + t.Fatal("Error: ", err) + } + err = c.RemoveObject(bucketName, objectName+"-nolength") + if err != nil { + t.Fatal("Error: ", err) + } + err = c.RemoveObject(bucketName, objectName+"-presigned") + if err != nil { + t.Fatal("Error: ", err) + } + err = c.RemoveBucket(bucketName) + if err != nil { + t.Fatal("Error:", err) + } + err = c.RemoveBucket(bucketName) + if err == nil { + t.Fatal("Error:") + } + if err.Error() != "The specified bucket does not exist" { + t.Fatal("Error: ", err) + } + if err = os.Remove(fileName); err != nil { + t.Fatal("Error: ", err) + } + if err = os.Remove(fileName + "-f"); err != nil { + t.Fatal("Error: ", err) + } +} diff --git a/vendor/github.com/minio/minio-go/api_handlers_test.go b/vendor/github.com/minio/minio-go/api_handlers_test.go deleted file mode 100644 index 146f4d6e..00000000 --- a/vendor/github.com/minio/minio-go/api_handlers_test.go +++ /dev/null @@ -1,170 +0,0 @@ -/* - * Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2015 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_test - -// bucketHandler is an http.Handler that verifies bucket responses and validates incoming requests -import ( - "bytes" - "io" - "net/http" - "strconv" - "time" -) - -type bucketHandler struct { - resource string -} - -func (h bucketHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { - switch { - case r.Method == "GET": - switch { - case r.URL.Path == "/": - response := []byte("bucket2015-05-20T23:05:09.230Zminiominio") - w.Header().Set("Content-Length", strconv.Itoa(len(response))) - w.Write(response) - case r.URL.Path == "/bucket": - _, ok := r.URL.Query()["acl"] - if ok { - response := []byte("75aa57f09aa0c8caeab4f8c24e99d10f8e7faeebf76c078efc7c6caea54ba06aCustomersName@amazon.com75aa57f09aa0c8caeab4f8c24e99d10f8e7faeebf76c078efc7c6caea54ba06aCustomersName@amazon.comFULL_CONTROL") - w.Header().Set("Content-Length", strconv.Itoa(len(response))) - w.Write(response) - return - } - fallthrough - case r.URL.Path == "/bucket": - response := []byte("\"259d04a13802ae09c7e41be50ccc6baa\"object2015-05-21T18:24:21.097Z22061miniominioSTANDARDfalse1000testbucket") - w.Header().Set("Content-Length", strconv.Itoa(len(response))) - w.Write(response) - } - case r.Method == "PUT": - switch { - case r.URL.Path == h.resource: - _, ok := r.URL.Query()["acl"] - if ok { - switch r.Header.Get("x-amz-acl") { - case "public-read-write": - fallthrough - case "public-read": - fallthrough - case "private": - fallthrough - case "authenticated-read": - w.WriteHeader(http.StatusOK) - return - default: - w.WriteHeader(http.StatusNotImplemented) - return - } - } - w.WriteHeader(http.StatusOK) - default: - w.WriteHeader(http.StatusBadRequest) - } - case r.Method == "HEAD": - switch { - case r.URL.Path == h.resource: - w.WriteHeader(http.StatusOK) - default: - w.WriteHeader(http.StatusForbidden) - } - case r.Method == "DELETE": - switch { - case r.URL.Path != h.resource: - w.WriteHeader(http.StatusNotFound) - default: - h.resource = "" - w.WriteHeader(http.StatusNoContent) - } - } -} - -// objectHandler is an http.Handler that verifies object responses and validates incoming requests -type objectHandler struct { - resource string - data []byte -} - -func (h objectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { - switch { - case r.Method == "PUT": - length, err := strconv.Atoi(r.Header.Get("Content-Length")) - if err != nil { - w.WriteHeader(http.StatusBadRequest) - return - } - var buffer bytes.Buffer - _, err = io.CopyN(&buffer, r.Body, int64(length)) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - return - } - if !bytes.Equal(h.data, buffer.Bytes()) { - w.WriteHeader(http.StatusInternalServerError) - return - } - w.Header().Set("ETag", "\"9af2f8218b150c351ad802c6f3d66abe\"") - w.WriteHeader(http.StatusOK) - case r.Method == "HEAD": - if r.URL.Path != h.resource { - w.WriteHeader(http.StatusNotFound) - 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("ETag", "\"9af2f8218b150c351ad802c6f3d66abe\"") - w.WriteHeader(http.StatusOK) - case r.Method == "POST": - _, ok := r.URL.Query()["uploads"] - if ok { - response := []byte("example-bucketobjectXXBsb2FkIElEIGZvciBlbHZpbmcncyVcdS1tb3ZpZS5tMnRzEEEwbG9hZA") - w.Header().Set("Content-Length", strconv.Itoa(len(response))) - w.Write(response) - return - } - case r.Method == "GET": - _, ok := r.URL.Query()["uploadId"] - if ok { - uploadID := r.URL.Query().Get("uploadId") - if uploadID != "XXBsb2FkIElEIGZvciBlbHZpbmcncyVcdS1tb3ZpZS5tMnRzEEEwbG9hZA" { - w.WriteHeader(http.StatusNotFound) - return - } - response := []byte("example-bucketexample-objectXXBsb2FkIElEIGZvciBlbHZpbmcncyVcdS1tb3ZpZS5tMnRzEEEwbG9hZAarn:aws:iam::111122223333:user/some-user-11116a31-17b5-4fb7-9df5-b288870f11xxumat-user-11116a31-17b5-4fb7-9df5-b288870f11xx75aa57f09aa0c8caeab4f8c24e99d10f8e7faeebf76c078efc7c6caea54ba06asomeNameSTANDARD132true22010-11-10T20:48:34.000Z\"7778aef83f66abc1fa1e8477f296d394\"1048576032010-11-10T20:48:33.000Z\"aaaa18db4cc2f85cedef654fccc4a4x8\"10485760") - w.Header().Set("Content-Length", strconv.Itoa(len(response))) - w.Write(response) - return - } - if r.URL.Path != h.resource { - w.WriteHeader(http.StatusNotFound) - 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("ETag", "\"9af2f8218b150c351ad802c6f3d66abe\"") - w.WriteHeader(http.StatusOK) - io.Copy(w, bytes.NewReader(h.data)) - case r.Method == "DELETE": - if r.URL.Path != h.resource { - w.WriteHeader(http.StatusNotFound) - return - } - h.resource = "" - h.data = nil - w.WriteHeader(http.StatusNoContent) - } -} diff --git a/vendor/github.com/minio/minio-go/api_private_test.go b/vendor/github.com/minio/minio-go/api_private_test.go deleted file mode 100644 index f9cd9f43..00000000 --- a/vendor/github.com/minio/minio-go/api_private_test.go +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2015 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 - -import ( - "strings" - "testing" -) - -func TestSignature(t *testing.T) { - conf := new(Config) - if !conf.Signature.isLatest() { - t.Fatalf("Error") - } - conf.Signature = SignatureV2 - if !conf.Signature.isV2() { - t.Fatalf("Error") - } - if conf.Signature.isV4() { - t.Fatalf("Error") - } - conf.Signature = SignatureV4 - if !conf.Signature.isV4() { - t.Fatalf("Error") - } -} - -func TestACLTypes(t *testing.T) { - want := map[string]bool{ - "private": true, - "public-read": true, - "public-read-write": true, - "authenticated-read": true, - "invalid": false, - } - for acl, ok := range want { - if BucketACL(acl).isValidBucketACL() != ok { - t.Fatal("Error") - } - } -} - -func TestUserAgent(t *testing.T) { - conf := new(Config) - conf.SetUserAgent("minio", "1.0", "amd64") - if !strings.Contains(conf.userAgent, "minio") { - t.Fatalf("Error") - } -} - -func TestGetRegion(t *testing.T) { - region := getRegion("s3.amazonaws.com") - if region != "us-east-1" { - t.Fatalf("Error") - } - region = getRegion("localhost:9000") - if region != "us-east-1" { - t.Fatalf("Error") - } -} - -func TestPartSize(t *testing.T) { - var maxPartSize int64 = 1024 * 1024 * 1024 * 5 - partSize := calculatePartSize(5000000000000000000) - if partSize > minimumPartSize { - if partSize > maxPartSize { - t.Fatal("invalid result, cannot be bigger than maxPartSize 5GB") - } - } - partSize = calculatePartSize(50000000000) - if partSize > minimumPartSize { - t.Fatal("invalid result, cannot be bigger than minimumPartSize 5MB") - } -} - -func TestURLEncoding(t *testing.T) { - type urlStrings struct { - name string - encodedName string - } - - want := []urlStrings{ - { - name: "bigfile-1._%", - encodedName: "bigfile-1._%25", - }, - { - name: "本語", - encodedName: "%E6%9C%AC%E8%AA%9E", - }, - { - name: "本語.1", - encodedName: "%E6%9C%AC%E8%AA%9E.1", - }, - { - name: ">123>3123123", - encodedName: "%3E123%3E3123123", - }, - { - name: "test 1 2.txt", - encodedName: "test%201%202.txt", - }, - { - name: "test++ 1.txt", - encodedName: "test%2B%2B%201.txt", - }, - } - - for _, u := range want { - if u.encodedName != getURLEncodedPath(u.name) { - t.Errorf("Error") - } - } -} diff --git a/vendor/github.com/minio/minio-go/api_public_test.go b/vendor/github.com/minio/minio-go/api_public_test.go deleted file mode 100644 index bf029419..00000000 --- a/vendor/github.com/minio/minio-go/api_public_test.go +++ /dev/null @@ -1,274 +0,0 @@ -/* - * Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2015 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_test - -import ( - "bytes" - "io" - "net/http/httptest" - "testing" - "time" - - "github.com/minio/minio-go" -) - -func TestBucketOperations(t *testing.T) { - bucket := bucketHandler(bucketHandler{ - resource: "/bucket", - }) - server := httptest.NewServer(bucket) - defer server.Close() - - a, err := minio.New(minio.Config{Endpoint: server.URL}) - if err != nil { - t.Fatal("Error") - } - err = a.MakeBucket("bucket", "private") - if err != nil { - t.Fatal("Error") - } - - err = a.BucketExists("bucket") - if err != nil { - t.Fatal("Error") - } - - err = a.BucketExists("bucket1") - if err == nil { - t.Fatal("Error") - } - if err.Error() != "Access Denied." { - t.Fatal("Error") - } - - err = a.SetBucketACL("bucket", "public-read-write") - if err != nil { - t.Fatal("Error") - } - - acl, err := a.GetBucketACL("bucket") - if err != nil { - t.Fatal("Error") - } - if acl != minio.BucketACL("private") { - t.Fatal("Error") - } - - for b := range a.ListBuckets() { - if b.Err != nil { - t.Fatal(b.Err.Error()) - } - if b.Name != "bucket" { - t.Fatal("Error") - } - } - - for o := range a.ListObjects("bucket", "", true) { - if o.Err != nil { - t.Fatal(o.Err.Error()) - } - if o.Key != "object" { - t.Fatal("Error") - } - } - - err = a.RemoveBucket("bucket") - if err != nil { - t.Fatal("Error") - } - - err = a.RemoveBucket("bucket1") - if err == nil { - t.Fatal("Error") - } - if err.Error() != "The specified bucket does not exist." { - t.Fatal("Error") - } -} - -func TestBucketOperationsFail(t *testing.T) { - bucket := bucketHandler(bucketHandler{ - resource: "/bucket", - }) - server := httptest.NewServer(bucket) - defer server.Close() - - a, err := minio.New(minio.Config{Endpoint: server.URL}) - if err != nil { - t.Fatal("Error") - } - err = a.MakeBucket("bucket$$$", "private") - if err == nil { - t.Fatal("Error") - } - - err = a.BucketExists("bucket.") - if err == nil { - t.Fatal("Error") - } - - err = a.SetBucketACL("bucket-.", "public-read-write") - if err == nil { - t.Fatal("Error") - } - - _, err = a.GetBucketACL("bucket??") - if err == nil { - t.Fatal("Error") - } - - for o := range a.ListObjects("bucket??", "", true) { - if o.Err == nil { - t.Fatal(o.Err.Error()) - } - } - - err = a.RemoveBucket("bucket??") - if err == nil { - t.Fatal("Error") - } - - if err.Error() != "The specified bucket is not valid." { - t.Fatal("Error") - } -} - -func TestObjectOperations(t *testing.T) { - object := objectHandler(objectHandler{ - resource: "/bucket/object", - data: []byte("Hello, World"), - }) - server := httptest.NewServer(object) - defer server.Close() - - a, err := minio.New(minio.Config{Endpoint: server.URL}) - if err != nil { - t.Fatal("Error") - } - data := []byte("Hello, World") - err = a.PutObject("bucket", "object", bytes.NewReader(data), int64(len(data)), "") - if err != nil { - t.Fatal("Error") - } - metadata, err := a.StatObject("bucket", "object") - if err != nil { - t.Fatal("Error") - } - if metadata.Key != "object" { - t.Fatal("Error") - } - if metadata.ETag != "9af2f8218b150c351ad802c6f3d66abe" { - t.Fatal("Error") - } - - reader, err := a.GetObject("bucket", "object") - if err != nil { - t.Fatal("Error") - } - - var buffer bytes.Buffer - _, err = io.Copy(&buffer, reader) - if !bytes.Equal(buffer.Bytes(), data) { - t.Fatal("Error") - } - - err = a.RemoveObject("bucket", "object") - if err != nil { - t.Fatal("Error") - } -} - -func TestPresignedURL(t *testing.T) { - object := objectHandler(objectHandler{ - resource: "/bucket/object", - data: []byte("Hello, World"), - }) - server := httptest.NewServer(object) - defer server.Close() - - a, err := minio.New(minio.Config{Endpoint: server.URL}) - if err != nil { - t.Fatal("Error") - } - // should error out for invalid access keys - _, err = a.PresignedGetObject("bucket", "object", time.Duration(1000)*time.Second) - if err == nil { - t.Fatal("Error") - } - - a, err = minio.New(minio.Config{ - Endpoint: server.URL, - AccessKeyID: "accessKey", - SecretAccessKey: "secretKey", - }) - if err != nil { - t.Fatal("Error") - } - url, err := a.PresignedGetObject("bucket", "object", time.Duration(1000)*time.Second) - if err != nil { - t.Fatal("Error") - } - if url == "" { - t.Fatal("Error") - } - _, err = a.PresignedGetObject("bucket", "object", time.Duration(0)*time.Second) - if err == nil { - t.Fatal("Error") - } - _, err = a.PresignedGetObject("bucket", "object", time.Duration(604801)*time.Second) - if err == nil { - t.Fatal("Error") - } -} - -func TestErrorResponse(t *testing.T) { - errorResponse := []byte("AccessDeniedAccess Denied/mybucket/myphoto.jpgF19772218238A85AGuWkjyviSiGHizehqpmsD1ndz5NClSP19DOT+s2mv7gXGQ8/X1lhbDGiIJEXpGFD") - errorReader := bytes.NewReader(errorResponse) - err := minio.BodyToErrorResponse(errorReader) - if err == nil { - t.Fatal("Error") - } - if err.Error() != "Access Denied" { - t.Fatal("Error") - } - resp := minio.ToErrorResponse(err) - // valid all fields - if resp == nil { - t.Fatal("Error") - } - if resp.Code != "AccessDenied" { - t.Fatal("Error") - } - if resp.RequestID != "F19772218238A85A" { - t.Fatal("Error") - } - if resp.Message != "Access Denied" { - t.Fatal("Error") - } - if resp.Resource != "/mybucket/myphoto.jpg" { - t.Fatal("Error") - } - if resp.HostID != "GuWkjyviSiGHizehqpmsD1ndz5NClSP19DOT+s2mv7gXGQ8/X1lhbDGiIJEXpGFD" { - t.Fatal("Error") - } - if resp.ToXML() == "" { - t.Fatal("Error") - } - if resp.ToJSON() == "" { - t.Fatal("Error") - } -} diff --git a/vendor/github.com/minio/minio-go/api_unit_test.go b/vendor/github.com/minio/minio-go/api_unit_test.go new file mode 100644 index 00000000..2afc666d --- /dev/null +++ b/vendor/github.com/minio/minio-go/api_unit_test.go @@ -0,0 +1,583 @@ +/* + * Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2015 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 + +import ( + "bytes" + "fmt" + "io" + "io/ioutil" + "net/http" + "net/url" + "os" + "strings" + "testing" +) + +type customReader struct{} + +func (c *customReader) Read(p []byte) (n int, err error) { + return 0, nil +} + +func (c *customReader) Size() (n int64) { + return 10 +} + +// Tests getReaderSize() for various Reader types. +func TestGetReaderSize(t *testing.T) { + var reader io.Reader + size, err := getReaderSize(reader) + if err != nil { + t.Fatal("Error:", err) + } + if size != -1 { + t.Fatal("Reader shouldn't have any length.") + } + + bytesReader := bytes.NewReader([]byte("Hello World")) + size, err = getReaderSize(bytesReader) + if err != nil { + t.Fatal("Error:", err) + } + if size != int64(len("Hello World")) { + t.Fatalf("Reader length doesn't match got: %v, want: %v", size, len("Hello World")) + } + + size, err = getReaderSize(new(customReader)) + if err != nil { + t.Fatal("Error:", err) + } + if size != int64(10) { + t.Fatalf("Reader length doesn't match got: %v, want: %v", size, 10) + } + + stringsReader := strings.NewReader("Hello World") + size, err = getReaderSize(stringsReader) + if err != nil { + t.Fatal("Error:", err) + } + if size != int64(len("Hello World")) { + t.Fatalf("Reader length doesn't match got: %v, want: %v", size, len("Hello World")) + } + + // Create request channel. + reqCh := make(chan readRequest) + // Create response channel. + resCh := make(chan readResponse) + // Create done channel. + doneCh := make(chan struct{}) + // objectInfo. + objectInfo := ObjectInfo{Size: 10} + objectReader := newObject(reqCh, resCh, doneCh, objectInfo) + defer objectReader.Close() + + size, err = getReaderSize(objectReader) + if err != nil { + t.Fatal("Error:", err) + } + if size != int64(10) { + t.Fatalf("Reader length doesn't match got: %v, want: %v", size, 10) + } + + fileReader, err := ioutil.TempFile(os.TempDir(), "prefix") + if err != nil { + t.Fatal("Error:", err) + } + defer fileReader.Close() + defer os.RemoveAll(fileReader.Name()) + + size, err = getReaderSize(fileReader) + if err != nil { + t.Fatal("Error:", err) + } + if size == -1 { + t.Fatal("Reader length for file cannot be -1.") + } + + // Verify for standard input, output and error file descriptors. + size, err = getReaderSize(os.Stdin) + if err != nil { + t.Fatal("Error:", err) + } + if size != -1 { + t.Fatal("Stdin should have length of -1.") + } + size, err = getReaderSize(os.Stdout) + if err != nil { + t.Fatal("Error:", err) + } + if size != -1 { + t.Fatal("Stdout should have length of -1.") + } + size, err = getReaderSize(os.Stderr) + if err != nil { + t.Fatal("Error:", err) + } + if size != -1 { + t.Fatal("Stderr should have length of -1.") + } + file, err := os.Open(os.TempDir()) + if err != nil { + t.Fatal("Error:", err) + } + defer file.Close() + _, err = getReaderSize(file) + if err == nil { + t.Fatal("Input file as directory should throw an error.") + } +} + +// Tests valid hosts for location. +func TestValidBucketLocation(t *testing.T) { + s3Hosts := []struct { + bucketLocation string + endpoint string + }{ + {"us-east-1", "s3.amazonaws.com"}, + {"unknown", "s3.amazonaws.com"}, + {"ap-southeast-1", "s3-ap-southeast-1.amazonaws.com"}, + } + for _, s3Host := range s3Hosts { + endpoint := getS3Endpoint(s3Host.bucketLocation) + if endpoint != s3Host.endpoint { + t.Fatal("Error: invalid bucket location", endpoint) + } + } +} + +// Tests valid bucket names. +func TestBucketNames(t *testing.T) { + buckets := []struct { + name string + valid error + }{ + {".mybucket", ErrInvalidBucketName("Bucket name cannot start or end with a '.' dot.")}, + {"mybucket.", ErrInvalidBucketName("Bucket name cannot start or end with a '.' dot.")}, + {"mybucket-", ErrInvalidBucketName("Bucket name contains invalid characters.")}, + {"my", ErrInvalidBucketName("Bucket name cannot be smaller than 3 characters.")}, + {"", ErrInvalidBucketName("Bucket name cannot be empty.")}, + {"my..bucket", ErrInvalidBucketName("Bucket name cannot have successive periods.")}, + {"my.bucket.com", nil}, + {"my-bucket", nil}, + {"123my-bucket", nil}, + } + + for _, b := range buckets { + err := isValidBucketName(b.name) + if err != b.valid { + t.Fatal("Error:", err) + } + } +} + +// Tests temp file. +func TestTempFile(t *testing.T) { + tmpFile, err := newTempFile("testing") + if err != nil { + t.Fatal("Error:", err) + } + fileName := tmpFile.Name() + // Closing temporary file purges the file. + err = tmpFile.Close() + if err != nil { + t.Fatal("Error:", err) + } + st, err := os.Stat(fileName) + if err != nil && !os.IsNotExist(err) { + t.Fatal("Error:", err) + } + if err == nil && st != nil { + t.Fatal("Error: file should be deleted and should not exist.") + } +} + +// Tests url encoding. +func TestEncodeURL2Path(t *testing.T) { + type urlStrings struct { + objName string + encodedObjName string + } + + bucketName := "bucketName" + want := []urlStrings{ + { + objName: "本語", + encodedObjName: "%E6%9C%AC%E8%AA%9E", + }, + { + objName: "本語.1", + encodedObjName: "%E6%9C%AC%E8%AA%9E.1", + }, + { + objName: ">123>3123123", + encodedObjName: "%3E123%3E3123123", + }, + { + objName: "test 1 2.txt", + encodedObjName: "test%201%202.txt", + }, + { + objName: "test++ 1.txt", + encodedObjName: "test%2B%2B%201.txt", + }, + } + + for _, o := range want { + u, err := url.Parse(fmt.Sprintf("https://%s.s3.amazonaws.com/%s", bucketName, o.objName)) + if err != nil { + t.Fatal("Error:", err) + } + urlPath := "/" + bucketName + "/" + o.encodedObjName + if urlPath != encodeURL2Path(u) { + t.Fatal("Error") + } + } +} + +// Tests error response structure. +func TestErrorResponse(t *testing.T) { + var err error + err = ErrorResponse{ + Code: "Testing", + } + errResp := ToErrorResponse(err) + if errResp.Code != "Testing" { + t.Fatal("Type conversion failed, we have an empty struct.") + } + + // Test http response decoding. + var httpResponse *http.Response + // Set empty variables + httpResponse = nil + var bucketName, objectName string + + // Should fail with invalid argument. + err = httpRespToErrorResponse(httpResponse, bucketName, objectName) + errResp = ToErrorResponse(err) + if errResp.Code != "InvalidArgument" { + t.Fatal("Empty response input should return invalid argument.") + } +} + +// Tests signature calculation. +func TestSignatureCalculation(t *testing.T) { + req, err := http.NewRequest("GET", "https://s3.amazonaws.com", nil) + if err != nil { + t.Fatal("Error:", err) + } + req = signV4(*req, "", "", "us-east-1") + if req.Header.Get("Authorization") != "" { + t.Fatal("Error: anonymous credentials should not have Authorization header.") + } + + req = preSignV4(*req, "", "", "us-east-1", 0) + if strings.Contains(req.URL.RawQuery, "X-Amz-Signature") { + t.Fatal("Error: anonymous credentials should not have Signature query resource.") + } + + req = signV2(*req, "", "") + if req.Header.Get("Authorization") != "" { + t.Fatal("Error: anonymous credentials should not have Authorization header.") + } + + req = preSignV2(*req, "", "", 0) + if strings.Contains(req.URL.RawQuery, "Signature") { + t.Fatal("Error: anonymous credentials should not have Signature query resource.") + } + + req = signV4(*req, "ACCESS-KEY", "SECRET-KEY", "us-east-1") + if req.Header.Get("Authorization") == "" { + t.Fatal("Error: normal credentials should have Authorization header.") + } + + req = preSignV4(*req, "ACCESS-KEY", "SECRET-KEY", "us-east-1", 0) + if !strings.Contains(req.URL.RawQuery, "X-Amz-Signature") { + t.Fatal("Error: normal credentials should have Signature query resource.") + } + + req = signV2(*req, "ACCESS-KEY", "SECRET-KEY") + if req.Header.Get("Authorization") == "" { + t.Fatal("Error: normal credentials should have Authorization header.") + } + + req = preSignV2(*req, "ACCESS-KEY", "SECRET-KEY", 0) + if !strings.Contains(req.URL.RawQuery, "Signature") { + t.Fatal("Error: normal credentials should not have Signature query resource.") + } +} + +// Tests signature type. +func TestSignatureType(t *testing.T) { + clnt := Client{} + if !clnt.signature.isV4() { + t.Fatal("Error") + } + clnt.signature = SignatureV2 + if !clnt.signature.isV2() { + t.Fatal("Error") + } + if clnt.signature.isV4() { + t.Fatal("Error") + } + clnt.signature = SignatureV4 + if !clnt.signature.isV4() { + t.Fatal("Error") + } +} + +// Tests bucket acl types. +func TestBucketACLTypes(t *testing.T) { + want := map[string]bool{ + "private": true, + "public-read": true, + "public-read-write": true, + "authenticated-read": true, + "invalid": false, + } + for acl, ok := range want { + if BucketACL(acl).isValidBucketACL() != ok { + t.Fatal("Error") + } + } +} + +// Tests optimal part size. +func TestPartSize(t *testing.T) { + totalPartsCount, partSize, lastPartSize, err := optimalPartInfo(5000000000000000000) + if err == nil { + t.Fatal("Error: should fail") + } + totalPartsCount, partSize, lastPartSize, err = optimalPartInfo(5497558138880) + if err != nil { + t.Fatal("Error: ", err) + } + if totalPartsCount != 9987 { + t.Fatalf("Error: expecting total parts count of 9987: got %v instead", totalPartsCount) + } + if partSize != 550502400 { + t.Fatalf("Error: expecting part size of 550502400: got %v instead", partSize) + } + if lastPartSize != 241172480 { + t.Fatalf("Error: expecting last part size of 241172480: got %v instead", lastPartSize) + } + totalPartsCount, partSize, lastPartSize, err = optimalPartInfo(5000000000) + if err != nil { + t.Fatal("Error:", err) + } + if partSize != minPartSize { + t.Fatalf("Error: expecting part size of %v: got %v instead", minPartSize, partSize) + } + totalPartsCount, partSize, lastPartSize, err = optimalPartInfo(-1) + if err != nil { + t.Fatal("Error:", err) + } + if totalPartsCount != 9987 { + t.Fatalf("Error: expecting total parts count of 9987: got %v instead", totalPartsCount) + } + if partSize != 550502400 { + t.Fatalf("Error: expecting part size of 550502400: got %v instead", partSize) + } + if lastPartSize != 241172480 { + t.Fatalf("Error: expecting last part size of 241172480: got %v instead", lastPartSize) + } +} + +// Tests url encoding. +func TestURLEncoding(t *testing.T) { + type urlStrings struct { + name string + encodedName string + } + + want := []urlStrings{ + { + name: "bigfile-1._%", + encodedName: "bigfile-1._%25", + }, + { + name: "本語", + encodedName: "%E6%9C%AC%E8%AA%9E", + }, + { + name: "本語.1", + encodedName: "%E6%9C%AC%E8%AA%9E.1", + }, + { + name: ">123>3123123", + encodedName: "%3E123%3E3123123", + }, + { + name: "test 1 2.txt", + encodedName: "test%201%202.txt", + }, + { + name: "test++ 1.txt", + encodedName: "test%2B%2B%201.txt", + }, + } + + for _, u := range want { + if u.encodedName != urlEncodePath(u.name) { + t.Fatal("Error") + } + } +} + +// Tests constructing valid endpoint url. +func TestGetEndpointURL(t *testing.T) { + if _, err := getEndpointURL("s3.amazonaws.com", false); err != nil { + t.Fatal("Error:", err) + } + if _, err := getEndpointURL("192.168.1.1", false); err != nil { + t.Fatal("Error:", err) + } + if _, err := getEndpointURL("13333.123123.-", false); err == nil { + t.Fatal("Error") + } + if _, err := getEndpointURL("s3.aamzza.-", false); err == nil { + t.Fatal("Error") + } + if _, err := getEndpointURL("s3.amazonaws.com:443", false); err == nil { + t.Fatal("Error") + } +} + +// Tests valid ip address. +func TestValidIPAddr(t *testing.T) { + type validIP struct { + ip string + valid bool + } + + want := []validIP{ + { + ip: "192.168.1.1", + valid: true, + }, + { + ip: "192.1.8", + valid: false, + }, + { + ip: "..192.", + valid: false, + }, + { + ip: "192.168.1.1.1", + valid: false, + }, + } + for _, w := range want { + valid := isValidIP(w.ip) + if valid != w.valid { + t.Fatal("Error") + } + } +} + +// Tests valid endpoint domain. +func TestValidEndpointDomain(t *testing.T) { + type validEndpoint struct { + endpointDomain string + valid bool + } + + want := []validEndpoint{ + { + endpointDomain: "s3.amazonaws.com", + valid: true, + }, + { + endpointDomain: "s3.amazonaws.com_", + valid: false, + }, + { + endpointDomain: "%$$$", + valid: false, + }, + { + endpointDomain: "s3.amz.test.com", + valid: true, + }, + { + endpointDomain: "s3.%%", + valid: false, + }, + { + endpointDomain: "localhost", + valid: true, + }, + { + endpointDomain: "-localhost", + valid: false, + }, + { + endpointDomain: "", + valid: false, + }, + { + endpointDomain: "\n \t", + valid: false, + }, + { + endpointDomain: " ", + valid: false, + }, + } + for _, w := range want { + valid := isValidDomain(w.endpointDomain) + if valid != w.valid { + t.Fatal("Error:", w.endpointDomain) + } + } +} + +// Tests valid endpoint url. +func TestValidEndpointURL(t *testing.T) { + type validURL struct { + url string + valid bool + } + want := []validURL{ + { + url: "https://s3.amazonaws.com", + valid: true, + }, + { + url: "https://s3.amazonaws.com/bucket/object", + valid: false, + }, + { + url: "192.168.1.1", + valid: false, + }, + } + for _, w := range want { + u, err := url.Parse(w.url) + if err != nil { + t.Fatal("Error:", err) + } + valid := false + if err := isValidEndpointURL(u); err == nil { + valid = true + } + if valid != w.valid { + t.Fatal("Error") + } + } +} diff --git a/vendor/github.com/minio/minio-go/appveyor.yml b/vendor/github.com/minio/minio-go/appveyor.yml index 1d140afd..5b8824d4 100644 --- a/vendor/github.com/minio/minio-go/appveyor.yml +++ b/vendor/github.com/minio/minio-go/appveyor.yml @@ -14,14 +14,10 @@ environment: # scripts that run after cloning repository install: - set PATH=%GOPATH%\bin;c:\go\bin;%PATH% - - rd C:\Go /s /q - - appveyor DownloadFile https://storage.googleapis.com/golang/go1.5.1.windows-amd64.zip - - 7z x go1.5.1.windows-amd64.zip -oC:\ >nul - go version - go env - go get -u github.com/golang/lint/golint - go get -u golang.org/x/tools/cmd/vet - - go get -u github.com/fzipp/gocyclo - go get -u github.com/remyoudompheng/go-misc/deadcode # to run your custom scripts instead of automatic MSBuild @@ -29,10 +25,9 @@ build_script: - go vet ./... - gofmt -s -l . - golint github.com/minio/minio-go... - - gocyclo -over 30 . - deadcode - - go test - - go test -race + - go test -short -v + - go test -short -race -v # to disable automatic tests test: off diff --git a/vendor/github.com/minio/minio-go/bucket-acl.go b/vendor/github.com/minio/minio-go/bucket-acl.go index 89c386ca..d8eda0f5 100644 --- a/vendor/github.com/minio/minio-go/bucket-acl.go +++ b/vendor/github.com/minio/minio-go/bucket-acl.go @@ -16,7 +16,7 @@ package minio -// BucketACL - bucket level access control. +// BucketACL - Bucket level access control. type BucketACL string // Different types of ACL's currently supported for buckets. @@ -35,7 +35,7 @@ func (b BucketACL) String() string { return string(b) } -// isValidBucketACL - is provided acl string supported. +// isValidBucketACL - Is provided acl string supported. func (b BucketACL) isValidBucketACL() bool { switch true { case b.isPrivate(): @@ -47,29 +47,29 @@ func (b BucketACL) isValidBucketACL() bool { case b.isAuthenticated(): return true case b.String() == "private": - // by default its "private" + // By default its "private" return true default: return false } } -// isPrivate - is acl Private. +// isPrivate - Is acl Private. func (b BucketACL) isPrivate() bool { return b == bucketPrivate } -// isPublicRead - is acl PublicRead. +// isPublicRead - Is acl PublicRead. func (b BucketACL) isReadOnly() bool { return b == bucketReadOnly } -// isPublicReadWrite - is acl PublicReadWrite. +// isPublicReadWrite - Is acl PublicReadWrite. func (b BucketACL) isPublic() bool { return b == bucketPublic } -// isAuthenticated - is acl AuthenticatedRead. +// isAuthenticated - Is acl AuthenticatedRead. func (b BucketACL) isAuthenticated() bool { return b == bucketAuthenticated } diff --git a/vendor/github.com/minio/minio-go/bucket-cache.go b/vendor/github.com/minio/minio-go/bucket-cache.go new file mode 100644 index 00000000..4af161c1 --- /dev/null +++ b/vendor/github.com/minio/minio-go/bucket-cache.go @@ -0,0 +1,154 @@ +/* + * Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2015 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 + +import ( + "encoding/hex" + "net/http" + "net/url" + "path/filepath" + "sync" +) + +// bucketLocationCache - Provides simple mechansim to hold bucket +// locations in memory. +type bucketLocationCache struct { + // mutex is used for handling the concurrent + // read/write requests for cache. + sync.RWMutex + + // items holds the cached bucket locations. + items map[string]string +} + +// newBucketLocationCache - Provides a new bucket location cache to be +// used internally with the client object. +func newBucketLocationCache() *bucketLocationCache { + return &bucketLocationCache{ + items: make(map[string]string), + } +} + +// Get - Returns a value of a given key if it exists. +func (r *bucketLocationCache) Get(bucketName string) (location string, ok bool) { + r.RLock() + defer r.RUnlock() + location, ok = r.items[bucketName] + return +} + +// Set - Will persist a value into cache. +func (r *bucketLocationCache) Set(bucketName string, location string) { + r.Lock() + defer r.Unlock() + r.items[bucketName] = location +} + +// Delete - Deletes a bucket name from cache. +func (r *bucketLocationCache) Delete(bucketName string) { + r.Lock() + defer r.Unlock() + delete(r.items, bucketName) +} + +// getBucketLocation - Get location for the bucketName from location map cache. +func (c Client) getBucketLocation(bucketName string) (string, error) { + // For anonymous requests, default to "us-east-1" and let other calls + // move forward. + if c.anonymous { + return "us-east-1", nil + } + if location, ok := c.bucketLocCache.Get(bucketName); ok { + return location, nil + } + + // Initialize a new request. + req, err := c.getBucketLocationRequest(bucketName) + if err != nil { + return "", err + } + + // Initiate the request. + resp, err := c.do(req) + defer closeResponse(resp) + if err != nil { + return "", err + } + if resp != nil { + if resp.StatusCode != http.StatusOK { + return "", httpRespToErrorResponse(resp, bucketName, "") + } + } + + // Extract location. + var locationConstraint string + err = xmlDecoder(resp.Body, &locationConstraint) + if err != nil { + return "", err + } + + location := locationConstraint + // Location is empty will be 'us-east-1'. + if location == "" { + location = "us-east-1" + } + + // Location can be 'EU' convert it to meaningful 'eu-west-1'. + if location == "EU" { + location = "eu-west-1" + } + + // Save the location into cache. + c.bucketLocCache.Set(bucketName, location) + + // Return. + return location, nil +} + +// getBucketLocationRequest - Wrapper creates a new getBucketLocation request. +func (c Client) getBucketLocationRequest(bucketName string) (*http.Request, error) { + // Set location query. + urlValues := make(url.Values) + urlValues.Set("location", "") + + // Set get bucket location always as path style. + targetURL := c.endpointURL + targetURL.Path = filepath.Join(bucketName, "") + targetURL.RawQuery = urlValues.Encode() + + // Get a new HTTP request for the method. + req, err := http.NewRequest("GET", targetURL.String(), nil) + if err != nil { + return nil, err + } + + // Set UserAgent for the request. + c.setUserAgent(req) + + // 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{}))) + } + + // Sign the request. + if c.signature.isV4() { + req = signV4(*req, c.accessKeyID, c.secretAccessKey, "us-east-1") + } else if c.signature.isV2() { + req = signV2(*req, c.accessKeyID, c.secretAccessKey) + } + return req, nil +} diff --git a/vendor/github.com/minio/minio-go/common-methods.go b/vendor/github.com/minio/minio-go/common-methods.go deleted file mode 100644 index 636e06f6..00000000 --- a/vendor/github.com/minio/minio-go/common-methods.go +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2015 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 - -import ( - "crypto/hmac" - "crypto/md5" - "crypto/sha256" - "encoding/xml" - "io" -) - -// xmlDecoder provide decoded value in xml. -func xmlDecoder(body io.Reader, v interface{}) error { - d := xml.NewDecoder(body) - return d.Decode(v) -} - -// sum256 calculate sha256 sum for an input byte array. -func sum256(data []byte) []byte { - hash := sha256.New() - hash.Write(data) - return hash.Sum(nil) -} - -// sumMD5 calculate md5 sum for an input byte array. -func sumMD5(data []byte) []byte { - hash := md5.New() - hash.Write(data) - return hash.Sum(nil) -} - -// sumHMAC calculate hmac between two input byte array. -func sumHMAC(key []byte, data []byte) []byte { - hash := hmac.New(sha256.New, key) - hash.Write(data) - return hash.Sum(nil) -} diff --git a/vendor/github.com/minio/minio-go/constants.go b/vendor/github.com/minio/minio-go/constants.go new file mode 100644 index 00000000..b0aa009d --- /dev/null +++ b/vendor/github.com/minio/minio-go/constants.go @@ -0,0 +1,42 @@ +/* + * Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2015 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 + +/// Multipart upload defaults. + +// miniPartSize - minimum part size 5MiB per object after which +// putObject behaves internally as multipart. +const minPartSize = 1024 * 1024 * 5 + +// maxPartsCount - maximum number of parts for a single multipart session. +const maxPartsCount = 10000 + +// maxPartSize - maximum part size 5GiB for a single multipart upload +// operation. +const maxPartSize = 1024 * 1024 * 1024 * 5 + +// maxSinglePutObjectSize - maximum size 5GiB of object per PUT +// operation. +const maxSinglePutObjectSize = 1024 * 1024 * 1024 * 5 + +// maxMultipartPutObjectSize - maximum size 5TiB of object for +// Multipart operation. +const maxMultipartPutObjectSize = 1024 * 1024 * 1024 * 1024 * 5 + +// optimalReadBufferSize - optimal buffer 5MiB used for reading +// through Read operation. +const optimalReadBufferSize = 1024 * 1024 * 5 diff --git a/vendor/github.com/minio/minio-go/error-response.go b/vendor/github.com/minio/minio-go/error-response.go deleted file mode 100644 index 8159375c..00000000 --- a/vendor/github.com/minio/minio-go/error-response.go +++ /dev/null @@ -1,170 +0,0 @@ -/* - * Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2015 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 - -import ( - "encoding/json" - "encoding/xml" - "io" - "regexp" - "strings" - "unicode/utf8" -) - -/* **** SAMPLE ERROR RESPONSE **** - - - AccessDenied - Access Denied - /mybucket/myphoto.jpg - F19772218238A85A - GuWkjyviSiGHizehqpmsD1ndz5NClSP19DOT+s2mv7gXGQ8/X1lhbDGiIJEXpGFD - -*/ - -// ErrorResponse is the type error returned by some API operations. -type ErrorResponse struct { - XMLName xml.Name `xml:"Error" json:"-"` - Code string - Message string - Resource string - RequestID string `xml:"RequestId"` - HostID string `xml:"HostId"` - - // This is a new undocumented field, set only if available. - AmzBucketRegion string -} - -// ToErrorResponse returns parsed ErrorResponse struct, if input is nil or not ErrorResponse return value is nil -// this fuction is useful when some one wants to dig deeper into the error structures over the network. -// -// For example: -// -// import s3 "github.com/minio/minio-go" -// ... -// ... -// reader, stat, err := s3.GetObject(...) -// if err != nil { -// resp := s3.ToErrorResponse(err) -// fmt.Println(resp.ToXML()) -// } -// ... -func ToErrorResponse(err error) *ErrorResponse { - switch err := err.(type) { - case ErrorResponse: - return &err - default: - return nil - } -} - -// ToXML send raw xml marshalled as string -func (e ErrorResponse) ToXML() string { - b, err := xml.Marshal(&e) - if err != nil { - panic(err) - } - return string(b) -} - -// ToJSON send raw json marshalled as string -func (e ErrorResponse) ToJSON() string { - b, err := json.Marshal(&e) - if err != nil { - panic(err) - } - return string(b) -} - -// Error formats HTTP error string -func (e ErrorResponse) Error() string { - return e.Message -} - -// BodyToErrorResponse returns a new encoded ErrorResponse structure -func BodyToErrorResponse(errBody io.Reader) error { - var errorResponse ErrorResponse - err := xmlDecoder(errBody, &errorResponse) - if err != nil { - return err - } - return errorResponse -} - -// invalidBucketToError - invalid bucket to errorResponse -func invalidBucketError(bucket string) error { - // verify bucket name in accordance with - // - http://docs.aws.amazon.com/AmazonS3/latest/dev/UsingBucket.html - isValidBucket := func(bucket string) bool { - if len(bucket) < 3 || len(bucket) > 63 { - return false - } - if bucket[0] == '.' || bucket[len(bucket)-1] == '.' { - return false - } - if match, _ := regexp.MatchString("\\.\\.", bucket); match == true { - return false - } - // We don't support buckets with '.' in them - match, _ := regexp.MatchString("^[a-zA-Z][a-zA-Z0-9\\-]+[a-zA-Z0-9]$", bucket) - return match - } - - if !isValidBucket(strings.TrimSpace(bucket)) { - // no resource since bucket is empty string - errorResponse := ErrorResponse{ - Code: "InvalidBucketName", - Message: "The specified bucket is not valid.", - RequestID: "minio", - } - return errorResponse - } - return nil -} - -// invalidObjectError invalid object name to errorResponse -func invalidObjectError(object string) error { - if strings.TrimSpace(object) == "" || object == "" { - // no resource since object name is empty - errorResponse := ErrorResponse{ - Code: "NoSuchKey", - Message: "The specified key does not exist.", - RequestID: "minio", - } - return errorResponse - } - return nil -} - -// invalidArgumentError invalid argument to errorResponse -func invalidArgumentError(arg string) error { - errorResponse := ErrorResponse{ - Code: "InvalidArgument", - Message: "Invalid Argument.", - RequestID: "minio", - } - if strings.TrimSpace(arg) == "" || arg == "" { - // no resource since arg is empty string - return errorResponse - } - if !utf8.ValidString(arg) { - // add resource to reply back with invalid string - errorResponse.Resource = arg - return errorResponse - } - return nil -} diff --git a/vendor/github.com/minio/minio-go/hook-reader.go b/vendor/github.com/minio/minio-go/hook-reader.go new file mode 100644 index 00000000..043425f2 --- /dev/null +++ b/vendor/github.com/minio/minio-go/hook-reader.go @@ -0,0 +1,54 @@ +/* + * Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2015 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 + +import "io" + +// hookReader hooks additional reader in the source stream. It is +// useful for making progress bars. Second reader is appropriately +// notified about the exact number of bytes read from the primary +// source on each Read operation. +type hookReader struct { + source io.Reader + hook io.Reader +} + +// Read implements io.Reader. Always reads from the source, the return +// value 'n' number of bytes are reported through the hook. Returns +// error for all non io.EOF conditions. +func (hr *hookReader) Read(b []byte) (n int, err error) { + n, err = hr.source.Read(b) + if err != nil && err != io.EOF { + return n, err + } + // Progress the hook with the total read bytes from the source. + if _, herr := hr.hook.Read(b[:n]); herr != nil { + if herr != io.EOF { + return n, herr + } + } + return n, err +} + +// newHook returns a io.Reader which implements hookReader that +// reports the data read from the source to the hook. +func newHook(source, hook io.Reader) io.Reader { + if hook == nil { + return source + } + return &hookReader{source, hook} +} diff --git a/vendor/github.com/minio/minio-go/interface.go b/vendor/github.com/minio/minio-go/interface.go deleted file mode 100644 index 16d01833..00000000 --- a/vendor/github.com/minio/minio-go/interface.go +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2015 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 - -import ( - "io" - "time" -) - -// CloudStorageAPI - Cloud Storage API interface -type CloudStorageAPI interface { - // Bucket Read/Write/Stat operations - MakeBucket(bucket string, cannedACL BucketACL) error - BucketExists(bucket string) error - RemoveBucket(bucket string) error - SetBucketACL(bucket string, cannedACL BucketACL) error - GetBucketACL(bucket string) (BucketACL, error) - - ListBuckets() <-chan BucketStat - ListObjects(bucket, prefix string, recursive bool) <-chan ObjectStat - ListIncompleteUploads(bucket, prefix string, recursive bool) <-chan ObjectMultipartStat - - // Object Read/Write/Stat operations - GetObject(bucket, object string) (io.ReadSeeker, error) - GetPartialObject(bucket, object string, offset, length int64) (io.ReadSeeker, error) - PutObject(bucket, object string, data io.ReadSeeker, size int64, contentType string) error - StatObject(bucket, object string) (ObjectStat, error) - RemoveObject(bucket, object string) error - RemoveIncompleteUpload(bucket, object string) <-chan error - - // Presigned operations - PresignedGetObject(bucket, object string, expires time.Duration) (string, error) - PresignedPutObject(bucket, object string, expires time.Duration) (string, error) - PresignedPostPolicy(*PostPolicy) (map[string]string, error) -} diff --git a/vendor/github.com/minio/minio-go/io.go b/vendor/github.com/minio/minio-go/io.go deleted file mode 100644 index 912a6a77..00000000 --- a/vendor/github.com/minio/minio-go/io.go +++ /dev/null @@ -1,146 +0,0 @@ -/* - * Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2015 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 - -import ( - "io" - "io/ioutil" - "os" - "sync" -) - -type objectReadSeeker struct { - // mutex. - mutex *sync.Mutex - - s3API API - reader io.ReadCloser - isRead bool - stat ObjectStat - offset int64 - bucketName string - objectName string -} - -// newObjectReadSeeker wraps getObject request returning a io.ReadSeeker. -func newObjectReadSeeker(api API, bucket, object string) *objectReadSeeker { - return &objectReadSeeker{ - mutex: new(sync.Mutex), - reader: nil, - isRead: false, - s3API: api, - offset: 0, - bucketName: bucket, - objectName: object, - } -} - -// Read reads up to len(p) bytes into p. It returns the number of bytes -// read (0 <= n <= len(p)) and any error encountered. Even if Read -// returns n < len(p), it may use all of p as scratch space during the call. -// If some data is available but not len(p) bytes, Read conventionally -// returns what is available instead of waiting for more. -// -// When Read encounters an error or end-of-file condition after -// successfully reading n > 0 bytes, it returns the number of -// bytes read. It may return the (non-nil) error from the same call -// or return the error (and n == 0) from a subsequent call. -// An instance of this general case is that a Reader returning -// a non-zero number of bytes at the end of the input stream may -// return either err == EOF or err == nil. The next Read should -// return 0, EOF. -func (r *objectReadSeeker) Read(p []byte) (int, error) { - r.mutex.Lock() - defer r.mutex.Unlock() - - if !r.isRead { - reader, _, err := r.s3API.getObject(r.bucketName, r.objectName, r.offset, 0) - if err != nil { - return 0, err - } - r.reader = reader - r.isRead = true - } - n, err := r.reader.Read(p) - if err == io.EOF { - io.Copy(ioutil.Discard, r.reader) - r.reader.Close() - return n, err - } - if err != nil { - io.Copy(ioutil.Discard, r.reader) - r.reader.Close() - return 0, err - } - return n, nil -} - -// Seek sets the offset for the next Read or Write to offset, -// interpreted according to whence: 0 means relative to the start of -// the file, 1 means relative to the current offset, and 2 means -// relative to the end. Seek returns the new offset relative to the -// start of the file and an error, if any. -// -// Seeking to an offset before the start of the file is an error. -// TODO: whence value of '1' and '2' are not implemented yet. -func (r *objectReadSeeker) Seek(offset int64, whence int) (int64, error) { - r.mutex.Lock() - defer r.mutex.Unlock() - r.offset = offset - return offset, nil -} - -// Stat returns the ObjectStat structure describing object. If there is any error it will be of type ErrorResponse. -func (r *objectReadSeeker) Stat() (ObjectStat, error) { - objectSt, err := r.s3API.headObject(r.bucketName, r.objectName) - r.stat = objectSt - return r.stat, err -} - -// tempFile - temporary file. -type tempFile struct { - *os.File - mutex *sync.Mutex -} - -// newTemplFile returns a new unused file. -func newTempFile(prefix string) (*tempFile, error) { - file, err := ioutil.TempFile(os.TempDir(), prefix) - if err != nil { - return nil, err - } - return &tempFile{ - File: file, - mutex: new(sync.Mutex), - }, nil -} - -// Close - closer. -func (t *tempFile) Close() error { - t.mutex.Lock() - defer t.mutex.Unlock() - if t.File != nil { - if err := t.File.Close(); err != nil { - return err - } - if err := os.Remove(t.File.Name()); err != nil { - return err - } - t.File = nil - } - return nil -} diff --git a/vendor/github.com/minio/minio-go/parts-manager.go b/vendor/github.com/minio/minio-go/parts-manager.go deleted file mode 100644 index 739d8d80..00000000 --- a/vendor/github.com/minio/minio-go/parts-manager.go +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2015 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 - -import ( - "crypto/md5" - "crypto/sha256" - "hash" - "io" -) - -// partsManager reads from io.Reader, partitions data into individual partMetadata{}, backed by a -// temporary file which deletes itself upon Close(). -// -// This method runs until an EOF or an error occurs. Before returning, the channel is always closed. -func partsManager(reader io.Reader, partSize int64, isEnableSha256Sum bool) <-chan partMetadata { - ch := make(chan partMetadata, 3) - go partsManagerInRoutine(reader, partSize, isEnableSha256Sum, ch) - return ch -} - -func partsManagerInRoutine(reader io.Reader, partSize int64, isEnableSha256Sum bool, ch chan<- partMetadata) { - defer close(ch) - tmpFile, err := newTempFile("multiparts$") - if err != nil { - ch <- partMetadata{ - Err: err, - } - return - } - var hashMD5 hash.Hash - var hashSha256 hash.Hash - var writer io.Writer - hashMD5 = md5.New() - mwwriter := io.MultiWriter(hashMD5) - if isEnableSha256Sum { - hashSha256 = sha256.New() - mwwriter = io.MultiWriter(hashMD5, hashSha256) - } - writer = io.MultiWriter(tmpFile, mwwriter) - n, err := io.CopyN(writer, reader, partSize) - if err == io.EOF || err == io.ErrUnexpectedEOF { - // Seek back to beginning. - tmpFile.Seek(0, 0) - - // short read, only single partMetadata return. - partMdata := partMetadata{ - MD5Sum: hashMD5.Sum(nil), - ReadCloser: tmpFile, - Size: n, - Err: nil, - } - if isEnableSha256Sum { - partMdata.Sha256Sum = hashSha256.Sum(nil) - } - ch <- partMdata - return - } - // unknown error considered catastrophic error, return here. - if err != nil { - ch <- partMetadata{ - Err: err, - } - return - } - // Seek back to beginning. - tmpFile.Seek(0, 0) - partMdata := partMetadata{ - MD5Sum: hashMD5.Sum(nil), - ReadCloser: tmpFile, - Size: n, - Err: nil, - } - if isEnableSha256Sum { - partMdata.Sha256Sum = hashSha256.Sum(nil) - } - ch <- partMdata - for err == nil { - var n int64 - tmpFile, err = newTempFile("multiparts$") - if err != nil { - ch <- partMetadata{ - Err: err, - } - return - } - hashMD5 = md5.New() - mwwriter := io.MultiWriter(hashMD5) - if isEnableSha256Sum { - hashSha256 = sha256.New() - mwwriter = io.MultiWriter(hashMD5, hashSha256) - } - writer = io.MultiWriter(tmpFile, mwwriter) - n, err = io.CopyN(writer, reader, partSize) - if err != nil { - if err != io.EOF && err != io.ErrUnexpectedEOF { // catastrophic error - ch <- partMetadata{ - Err: err, - } - return - } - } - // Seek back to beginning. - tmpFile.Seek(0, 0) - partMdata := partMetadata{ - MD5Sum: hashMD5.Sum(nil), - ReadCloser: tmpFile, - Size: n, - Err: nil, - } - if isEnableSha256Sum { - partMdata.Sha256Sum = hashSha256.Sum(nil) - } - ch <- partMdata - } -} diff --git a/vendor/github.com/minio/minio-go/post-policy.go b/vendor/github.com/minio/minio-go/post-policy.go index b2b34d7a..2a675d77 100644 --- a/vendor/github.com/minio/minio-go/post-policy.go +++ b/vendor/github.com/minio/minio-go/post-policy.go @@ -2,16 +2,16 @@ package minio import ( "encoding/base64" - "errors" "fmt" "strings" "time" ) -// expirationDateFormat date format for expiration key in json policy +// expirationDateFormat date format for expiration key in json policy. const expirationDateFormat = "2006-01-02T15:04:05.999Z" -// policyCondition explanation: http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-HTTPPOSTConstructPolicy.html +// policyCondition explanation: +// http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-HTTPPOSTConstructPolicy.html // // Example: // @@ -27,21 +27,25 @@ type policyCondition struct { value string } -// PostPolicy provides strict static type conversion and validation for Amazon S3's POST policy JSON string. +// PostPolicy - Provides strict static type conversion and validation +// for Amazon S3's POST policy JSON string. type PostPolicy struct { - expiration time.Time // expiration date and time of the POST policy. - conditions []policyCondition // collection of different policy conditions. - // contentLengthRange minimum and maximum allowable size for the uploaded content. + // Expiration date and time of the POST policy. + expiration time.Time + // Collection of different policy conditions. + conditions []policyCondition + // ContentLengthRange minimum and maximum allowable size for the + // uploaded content. contentLengthRange struct { - min int - max int + min int64 + max int64 } - // Post form data + // Post form data. formData map[string]string } -// NewPostPolicy instantiate new post policy +// NewPostPolicy - Instantiate new post policy. func NewPostPolicy() *PostPolicy { p := &PostPolicy{} p.conditions = make([]policyCondition, 0) @@ -49,19 +53,19 @@ func NewPostPolicy() *PostPolicy { return p } -// SetExpires expiration time +// SetExpires - Sets expiration time for the new policy. func (p *PostPolicy) SetExpires(t time.Time) error { if t.IsZero() { - return errors.New("No expiry time set.") + return ErrInvalidArgument("No expiry time set.") } p.expiration = t return nil } -// SetKey Object name +// SetKey - Sets an object name for the policy based upload. func (p *PostPolicy) SetKey(key string) error { if strings.TrimSpace(key) == "" || key == "" { - return errors.New("Object name is not specified.") + return ErrInvalidArgument("Object name is empty.") } policyCond := policyCondition{ matchType: "eq", @@ -75,10 +79,11 @@ func (p *PostPolicy) SetKey(key string) error { return nil } -// SetKeyStartsWith Object name that can start with +// SetKeyStartsWith - Sets an object name that an policy based upload +// can start with. func (p *PostPolicy) SetKeyStartsWith(keyStartsWith string) error { if strings.TrimSpace(keyStartsWith) == "" || keyStartsWith == "" { - return errors.New("Object prefix is not specified.") + return ErrInvalidArgument("Object prefix is empty.") } policyCond := policyCondition{ matchType: "starts-with", @@ -92,27 +97,28 @@ func (p *PostPolicy) SetKeyStartsWith(keyStartsWith string) error { return nil } -// SetBucket bucket name -func (p *PostPolicy) SetBucket(bucket string) error { - if strings.TrimSpace(bucket) == "" || bucket == "" { - return errors.New("Bucket name is not specified.") +// SetBucket - Sets bucket at which objects will be uploaded to. +func (p *PostPolicy) SetBucket(bucketName string) error { + if strings.TrimSpace(bucketName) == "" || bucketName == "" { + return ErrInvalidArgument("Bucket name is empty.") } policyCond := policyCondition{ matchType: "eq", condition: "$bucket", - value: bucket, + value: bucketName, } if err := p.addNewPolicy(policyCond); err != nil { return err } - p.formData["bucket"] = bucket + p.formData["bucket"] = bucketName return nil } -// SetContentType content-type +// SetContentType - Sets content-type of the object for this policy +// based upload. func (p *PostPolicy) SetContentType(contentType string) error { if strings.TrimSpace(contentType) == "" || contentType == "" { - return errors.New("No content type specified.") + return ErrInvalidArgument("No content type specified.") } policyCond := policyCondition{ matchType: "eq", @@ -126,37 +132,38 @@ func (p *PostPolicy) SetContentType(contentType string) error { return nil } -// SetContentLength - set new min and max content length condition -func (p *PostPolicy) SetContentLength(min, max int) error { +// SetContentLengthRange - Set new min and max content length +// condition for all incoming uploads. +func (p *PostPolicy) SetContentLengthRange(min, max int64) error { if min > max { - return errors.New("Content length minimum-limit is larger than maximum-limit.") + return ErrInvalidArgument("Minimum limit is larger than maximum limit.") } if min < 0 { - return errors.New("Content length minimum-limit is negative.") + return ErrInvalidArgument("Minimum limit cannot be negative.") } if max < 0 { - return errors.New("Content length maximum-limit is negative") + return ErrInvalidArgument("Maximum limit cannot be negative.") } p.contentLengthRange.min = min p.contentLengthRange.max = max return nil } -// addNewPolicy - internal helper to validate adding new policies +// addNewPolicy - internal helper to validate adding new policies. func (p *PostPolicy) addNewPolicy(policyCond policyCondition) error { if policyCond.matchType == "" || policyCond.condition == "" || policyCond.value == "" { - return errors.New("Policy fields empty.") + return ErrInvalidArgument("Policy fields are empty.") } p.conditions = append(p.conditions, policyCond) return nil } -// Stringer interface for printing in pretty manner +// Stringer interface for printing policy in json formatted string. func (p PostPolicy) String() string { return string(p.marshalJSON()) } -// marshalJSON provides Marshalled JSON +// marshalJSON - Provides Marshalled JSON in bytes. func (p PostPolicy) marshalJSON() []byte { expirationStr := `"expiration":"` + p.expiration.Format(expirationDateFormat) + `"` var conditionsStr string @@ -178,7 +185,7 @@ func (p PostPolicy) marshalJSON() []byte { return []byte(retStr) } -// base64 produces base64 of PostPolicy's Marshalled json +// base64 - Produces base64 of PostPolicy's Marshalled json. func (p PostPolicy) base64() string { return base64.StdEncoding.EncodeToString(p.marshalJSON()) } diff --git a/vendor/github.com/minio/minio-go/request-signature-v2.go b/vendor/github.com/minio/minio-go/request-signature-v2.go index 4b583799..69682818 100644 --- a/vendor/github.com/minio/minio-go/request-signature-v2.go +++ b/vendor/github.com/minio/minio-go/request-signature-v2.go @@ -21,7 +21,6 @@ import ( "crypto/hmac" "crypto/sha1" "encoding/base64" - "errors" "fmt" "net/http" "net/url" @@ -31,61 +30,78 @@ import ( "time" ) -// PreSignV2 - presign the request in following style. -// https://${S3_BUCKET}.s3.amazonaws.com/${S3_OBJECT}?AWSAccessKeyId=${S3_ACCESS_KEY}&Expires=${TIMESTAMP}&Signature=${SIGNATURE} -func (r *Request) PreSignV2() (string, error) { - if r.config.isAnonymous() { - return "", errors.New("presigning cannot be done with anonymous credentials") +// Signature and API related constants. +const ( + signV2Algorithm = "AWS" +) + +// Encode input URL path to URL encoded path. +func encodeURL2Path(u *url.URL) (path string) { + // Encode URL path. + if strings.HasSuffix(u.Host, ".s3.amazonaws.com") { + path = "/" + strings.TrimSuffix(u.Host, ".s3.amazonaws.com") + path += u.Path + path = urlEncodePath(path) + return + } + if strings.HasSuffix(u.Host, ".storage.googleapis.com") { + path = "/" + strings.TrimSuffix(u.Host, ".storage.googleapis.com") + path += u.Path + path = urlEncodePath(path) + return + } + path = urlEncodePath(u.Path) + return +} + +// preSignV2 - presign the request in following style. +// https://${S3_BUCKET}.s3.amazonaws.com/${S3_OBJECT}?AWSAccessKeyId=${S3_ACCESS_KEY}&Expires=${TIMESTAMP}&Signature=${SIGNATURE}. +func preSignV2(req http.Request, accessKeyID, secretAccessKey string, expires int64) *http.Request { + // Presign is not needed for anonymous credentials. + if accessKeyID == "" || secretAccessKey == "" { + return &req } d := time.Now().UTC() - // Add date if not present - if date := r.Get("Date"); date == "" { - r.Set("Date", d.Format(http.TimeFormat)) - } - var path string - // Encode URL path. - if r.config.isVirtualHostedStyle { - for k, v := range regions { - if v == r.config.Region { - path = "/" + strings.TrimSuffix(r.req.URL.Host, "."+k) - path += r.req.URL.Path - path = getURLEncodedPath(path) - break - } - } - } else { - path = getURLEncodedPath(r.req.URL.Path) + // Add date if not present. + if date := req.Header.Get("Date"); date == "" { + req.Header.Set("Date", d.Format(http.TimeFormat)) } + // Get encoded URL path. + path := encodeURL2Path(req.URL) + // Find epoch expires when the request will expire. - epochExpires := d.Unix() + r.expires + epochExpires := d.Unix() + expires - // get string to sign. - stringToSign := fmt.Sprintf("%s\n\n\n%d\n%s", r.req.Method, epochExpires, path) - hm := hmac.New(sha1.New, []byte(r.config.SecretAccessKey)) + // Get string to sign. + stringToSign := fmt.Sprintf("%s\n\n\n%d\n%s", req.Method, epochExpires, path) + hm := hmac.New(sha1.New, []byte(secretAccessKey)) hm.Write([]byte(stringToSign)) - // calculate signature. + + // Calculate signature. signature := base64.StdEncoding.EncodeToString(hm.Sum(nil)) - query := r.req.URL.Query() + query := req.URL.Query() // Handle specially for Google Cloud Storage. - if r.config.Region == "google" { - query.Set("GoogleAccessId", r.config.AccessKeyID) + if strings.Contains(req.URL.Host, ".storage.googleapis.com") { + query.Set("GoogleAccessId", accessKeyID) } else { - query.Set("AWSAccessKeyId", r.config.AccessKeyID) + query.Set("AWSAccessKeyId", accessKeyID) } // Fill in Expires and Signature for presigned query. query.Set("Expires", strconv.FormatInt(epochExpires, 10)) query.Set("Signature", signature) - r.req.URL.RawQuery = query.Encode() - return r.req.URL.String(), nil + // Encode query and save. + req.URL.RawQuery = query.Encode() + return &req } -// PostPresignSignatureV2 - presigned signature for PostPolicy request -func (r *Request) PostPresignSignatureV2(policyBase64 string) string { - hm := hmac.New(sha1.New, []byte(r.config.SecretAccessKey)) +// postPresignSignatureV2 - presigned signature for PostPolicy +// request. +func postPresignSignatureV2(policyBase64, secretAccessKey string) string { + hm := hmac.New(sha1.New, []byte(secretAccessKey)) hm.Write([]byte(policyBase64)) signature := base64.StdEncoding.EncodeToString(hm.Sum(nil)) return signature @@ -107,30 +123,37 @@ func (r *Request) PostPresignSignatureV2(policyBase64 string) string { // // CanonicalizedProtocolHeaders = -// SignV2 sign the request before Do() (AWS Signature Version 2). -func (r *Request) SignV2() { +// signV2 sign the request before Do() (AWS Signature Version 2). +func signV2(req http.Request, accessKeyID, secretAccessKey string) *http.Request { + // Signature calculation is not needed for anonymous credentials. + if accessKeyID == "" || secretAccessKey == "" { + return &req + } + // Initial time. d := time.Now().UTC() // Add date if not present. - if date := r.Get("Date"); date == "" { - r.Set("Date", d.Format(http.TimeFormat)) + if date := req.Header.Get("Date"); date == "" { + req.Header.Set("Date", d.Format(http.TimeFormat)) } // Calculate HMAC for secretAccessKey. - stringToSign := r.getStringToSignV2() - hm := hmac.New(sha1.New, []byte(r.config.SecretAccessKey)) + stringToSign := getStringToSignV2(req) + hm := hmac.New(sha1.New, []byte(secretAccessKey)) hm.Write([]byte(stringToSign)) // Prepare auth header. authHeader := new(bytes.Buffer) - authHeader.WriteString(fmt.Sprintf("AWS %s:", r.config.AccessKeyID)) + authHeader.WriteString(fmt.Sprintf("%s %s:", signV2Algorithm, accessKeyID)) encoder := base64.NewEncoder(base64.StdEncoding, authHeader) encoder.Write(hm.Sum(nil)) encoder.Close() // Set Authorization header. - r.req.Header.Set("Authorization", authHeader.String()) + req.Header.Set("Authorization", authHeader.String()) + + return &req } // From the Amazon docs: @@ -141,35 +164,35 @@ func (r *Request) SignV2() { // Date + "\n" + // CanonicalizedProtocolHeaders + // CanonicalizedResource; -func (r *Request) getStringToSignV2() string { +func getStringToSignV2(req http.Request) string { buf := new(bytes.Buffer) - // write standard headers. - r.writeDefaultHeaders(buf) - // write canonicalized protocol headers if any. - r.writeCanonicalizedHeaders(buf) - // write canonicalized Query resources if any. - r.writeCanonicalizedResource(buf) + // Write standard headers. + writeDefaultHeaders(buf, req) + // Write canonicalized protocol headers if any. + writeCanonicalizedHeaders(buf, req) + // Write canonicalized Query resources if any. + writeCanonicalizedResource(buf, req) return buf.String() } // writeDefaultHeader - write all default necessary headers -func (r *Request) writeDefaultHeaders(buf *bytes.Buffer) { - buf.WriteString(r.req.Method) +func writeDefaultHeaders(buf *bytes.Buffer, req http.Request) { + buf.WriteString(req.Method) buf.WriteByte('\n') - buf.WriteString(r.req.Header.Get("Content-MD5")) + buf.WriteString(req.Header.Get("Content-MD5")) buf.WriteByte('\n') - buf.WriteString(r.req.Header.Get("Content-Type")) + buf.WriteString(req.Header.Get("Content-Type")) buf.WriteByte('\n') - buf.WriteString(r.req.Header.Get("Date")) + buf.WriteString(req.Header.Get("Date")) buf.WriteByte('\n') } // writeCanonicalizedHeaders - write canonicalized headers. -func (r *Request) writeCanonicalizedHeaders(buf *bytes.Buffer) { +func writeCanonicalizedHeaders(buf *bytes.Buffer, req http.Request) { var protoHeaders []string vals := make(map[string][]string) - for k, vv := range r.req.Header { - // all the AMZ and GOOG headers should be lowercase + for k, vv := range req.Header { + // All the AMZ headers should be lowercase lk := strings.ToLower(k) if strings.HasPrefix(lk, "x-amz") { protoHeaders = append(protoHeaders, lk) @@ -228,38 +251,33 @@ var resourceList = []string{ // CanonicalizedResource = [ "/" + Bucket ] + // + // [ sub-resource, if present. For example "?acl", "?location", "?logging", or "?torrent"]; -func (r *Request) writeCanonicalizedResource(buf *bytes.Buffer) error { - requestURL := r.req.URL - if r.config.isVirtualHostedStyle { - for k, v := range regions { - if v == r.config.Region { - path := "/" + strings.TrimSuffix(requestURL.Host, "."+k) - path += requestURL.Path - buf.WriteString(getURLEncodedPath(path)) - break - } - } - } else { - buf.WriteString(getURLEncodedPath(requestURL.Path)) - } +func writeCanonicalizedResource(buf *bytes.Buffer, req http.Request) error { + // Save request URL. + requestURL := req.URL + + // Get encoded URL path. + path := encodeURL2Path(requestURL) + buf.WriteString(path) + sort.Strings(resourceList) if requestURL.RawQuery != "" { var n int vals, _ := url.ParseQuery(requestURL.RawQuery) - // loop through all the supported resourceList. + // Verify if any sub resource queries are present, if yes + // canonicallize them. for _, resource := range resourceList { if vv, ok := vals[resource]; ok && len(vv) > 0 { n++ - // first element + // First element switch n { case 1: buf.WriteByte('?') - // the rest + // The rest default: buf.WriteByte('&') } buf.WriteString(resource) - // request parameters + // Request parameters if len(vv[0]) > 0 { buf.WriteByte('=') buf.WriteString(url.QueryEscape(vv[0])) diff --git a/vendor/github.com/minio/minio-go/request-signature-v4.go b/vendor/github.com/minio/minio-go/request-signature-v4.go index bd02f22c..dfd11e9e 100644 --- a/vendor/github.com/minio/minio-go/request-signature-v4.go +++ b/vendor/github.com/minio/minio-go/request-signature-v4.go @@ -19,7 +19,6 @@ package minio import ( "bytes" "encoding/hex" - "errors" "net/http" "sort" "strconv" @@ -27,36 +26,43 @@ import ( "time" ) -// signature and API related constants. +// Signature and API related constants. const ( - authHeader = "AWS4-HMAC-SHA256" + signV4Algorithm = "AWS4-HMAC-SHA256" iso8601DateFormat = "20060102T150405Z" yyyymmdd = "20060102" ) /// -/// Excerpts from @lsegal - https://github.com/aws/aws-sdk-js/issues/659#issuecomment-120477258. +/// Excerpts from @lsegal - +/// https://github.com/aws/aws-sdk-js/issues/659#issuecomment-120477258. /// /// User-Agent: /// -/// This is ignored from signing because signing this causes problems with generating pre-signed URLs -/// (that are executed by other agents) or when customers pass requests through proxies, which may -/// modify the user-agent. +/// This is ignored from signing because signing this causes +/// problems with generating pre-signed URLs (that are executed +/// by other agents) or when customers pass requests through +/// proxies, which may modify the user-agent. /// /// Content-Length: /// -/// This is ignored from signing because generating a pre-signed URL should not provide a content-length -/// constraint, specifically when vending a S3 pre-signed PUT URL. The corollary to this is that when -/// sending regular requests (non-pre-signed), the signature contains a checksum of the body, which -/// implicitly validates the payload length (since changing the number of bytes would change the checksum) +/// This is ignored from signing because generating a pre-signed +/// URL should not provide a content-length constraint, +/// specifically when vending a S3 pre-signed PUT URL. The +/// corollary to this is that when sending regular requests +/// (non-pre-signed), the signature contains a checksum of the +/// body, which implicitly validates the payload length (since +/// changing the number of bytes would change the checksum) /// and therefore this header is not valuable in the signature. /// /// Content-Type: /// -/// Signing this header causes quite a number of problems in browser environments, where browsers -/// like to modify and normalize the content-type header in different ways. There is more information -/// on this in https://github.com/aws/aws-sdk-js/issues/244. Avoiding this field simplifies logic -/// and reduces the possibility of future bugs +/// Signing this header causes quite a number of problems in +/// browser environments, where browsers like to modify and +/// normalize the content-type header in different ways. There is +/// more information on this in https://goo.gl/2E9gyy. Avoiding +/// this field simplifies logic and reduces the possibility of +/// future bugs. /// /// Authorization: /// @@ -69,51 +75,55 @@ var ignoredHeaders = map[string]bool{ "User-Agent": true, } -// getSigningKey hmac seed to calculate final signature -func getSigningKey(secret, region string, t time.Time) []byte { +// getSigningKey hmac seed to calculate final signature. +func getSigningKey(secret, loc string, t time.Time) []byte { date := sumHMAC([]byte("AWS4"+secret), []byte(t.Format(yyyymmdd))) - regionbytes := sumHMAC(date, []byte(region)) - service := sumHMAC(regionbytes, []byte("s3")) + location := sumHMAC(date, []byte(loc)) + service := sumHMAC(location, []byte("s3")) signingKey := sumHMAC(service, []byte("aws4_request")) return signingKey } -// getSignature final signature in hexadecimal form +// getSignature final signature in hexadecimal form. func getSignature(signingKey []byte, stringToSign string) string { return hex.EncodeToString(sumHMAC(signingKey, []byte(stringToSign))) } -// getScope generate a string of a specific date, an AWS region, and a service -func getScope(region string, t time.Time) string { +// getScope generate a string of a specific date, an AWS region, and a +// service. +func getScope(location string, t time.Time) string { scope := strings.Join([]string{ t.Format(yyyymmdd), - region, + location, "s3", "aws4_request", }, "/") return scope } -// getCredential generate a credential string -func getCredential(accessKeyID, region string, t time.Time) string { - scope := getScope(region, t) +// getCredential generate a credential string. +func getCredential(accessKeyID, location string, t time.Time) string { + scope := getScope(location, t) return accessKeyID + "/" + scope } -// getHashedPayload get the hexadecimal value of the SHA256 hash of the request payload -func (r *Request) getHashedPayload() string { - if r.expires != 0 { - return "UNSIGNED-PAYLOAD" +// getHashedPayload get the hexadecimal value of the SHA256 hash of +// the request payload. +func getHashedPayload(req http.Request) string { + hashedPayload := req.Header.Get("X-Amz-Content-Sha256") + if hashedPayload == "" { + // Presign does not have a payload, use S3 recommended value. + hashedPayload = "UNSIGNED-PAYLOAD" } - hashedPayload := r.req.Header.Get("X-Amz-Content-Sha256") return hashedPayload } -// getCanonicalHeaders generate a list of request headers for signature. -func (r *Request) getCanonicalHeaders() string { +// getCanonicalHeaders generate a list of request headers for +// signature. +func getCanonicalHeaders(req http.Request) string { var headers []string vals := make(map[string][]string) - for k, vv := range r.req.Header { + for k, vv := range req.Header { if _, ok := ignoredHeaders[http.CanonicalHeaderKey(k)]; ok { continue // ignored header } @@ -124,12 +134,14 @@ func (r *Request) getCanonicalHeaders() string { sort.Strings(headers) var buf bytes.Buffer + // Save all the headers in canonical form
: newline + // separated for each header. for _, k := range headers { buf.WriteString(k) buf.WriteByte(':') switch { case k == "host": - buf.WriteString(r.req.URL.Host) + buf.WriteString(req.URL.Host) fallthrough default: for idx, v := range vals[k] { @@ -145,12 +157,13 @@ func (r *Request) getCanonicalHeaders() string { } // getSignedHeaders generate all signed request headers. -// i.e alphabetically sorted, semicolon-separated list of lowercase request header names -func (r *Request) getSignedHeaders() string { +// i.e lexically sorted, semicolon-separated list of lowercase +// request header names. +func getSignedHeaders(req http.Request) string { var headers []string - for k := range r.req.Header { + for k := range req.Header { if _, ok := ignoredHeaders[http.CanonicalHeaderKey(k)]; ok { - continue // ignored header + continue // Ignored header found continue. } headers = append(headers, strings.ToLower(k)) } @@ -168,96 +181,123 @@ func (r *Request) getSignedHeaders() string { // \n // \n // -// -func (r *Request) getCanonicalRequest() string { - r.req.URL.RawQuery = strings.Replace(r.req.URL.Query().Encode(), "+", "%20", -1) +func getCanonicalRequest(req http.Request) string { + req.URL.RawQuery = strings.Replace(req.URL.Query().Encode(), "+", "%20", -1) canonicalRequest := strings.Join([]string{ - r.req.Method, - getURLEncodedPath(r.req.URL.Path), - r.req.URL.RawQuery, - r.getCanonicalHeaders(), - r.getSignedHeaders(), - r.getHashedPayload(), + req.Method, + urlEncodePath(req.URL.Path), + req.URL.RawQuery, + getCanonicalHeaders(req), + getSignedHeaders(req), + getHashedPayload(req), }, "\n") return canonicalRequest } // getStringToSign a string based on selected query values. -func (r *Request) getStringToSignV4(canonicalRequest string, t time.Time) string { - stringToSign := authHeader + "\n" + t.Format(iso8601DateFormat) + "\n" - stringToSign = stringToSign + getScope(r.config.Region, t) + "\n" +func getStringToSignV4(t time.Time, location, canonicalRequest string) string { + stringToSign := signV4Algorithm + "\n" + t.Format(iso8601DateFormat) + "\n" + stringToSign = stringToSign + getScope(location, t) + "\n" stringToSign = stringToSign + hex.EncodeToString(sum256([]byte(canonicalRequest))) return stringToSign } -// PreSignV4 presign the request, in accordance with +// preSignV4 presign the request, in accordance with // http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-query-string-auth.html. -func (r *Request) PreSignV4() (string, error) { - if r.config.isAnonymous() { - return "", errors.New("presigning cannot be done with anonymous credentials") +func preSignV4(req http.Request, accessKeyID, secretAccessKey, location string, expires int64) *http.Request { + // Presign is not needed for anonymous credentials. + if accessKeyID == "" || secretAccessKey == "" { + return &req } + // Initial time. t := time.Now().UTC() - // get credential string. - credential := getCredential(r.config.AccessKeyID, r.config.Region, t) - // get hmac signing key. - signingKey := getSigningKey(r.config.SecretAccessKey, r.config.Region, t) + // Get credential string. + credential := getCredential(accessKeyID, location, t) // Get all signed headers. - signedHeaders := r.getSignedHeaders() + signedHeaders := getSignedHeaders(req) - query := r.req.URL.Query() - query.Set("X-Amz-Algorithm", authHeader) + // Set URL query. + query := req.URL.Query() + query.Set("X-Amz-Algorithm", signV4Algorithm) query.Set("X-Amz-Date", t.Format(iso8601DateFormat)) - query.Set("X-Amz-Expires", strconv.FormatInt(r.expires, 10)) + query.Set("X-Amz-Expires", strconv.FormatInt(expires, 10)) query.Set("X-Amz-SignedHeaders", signedHeaders) query.Set("X-Amz-Credential", credential) - r.req.URL.RawQuery = query.Encode() + req.URL.RawQuery = query.Encode() + + // Get canonical request. + canonicalRequest := getCanonicalRequest(req) // Get string to sign from canonical request. - stringToSign := r.getStringToSignV4(r.getCanonicalRequest(), t) - // calculate signature. + stringToSign := getStringToSignV4(t, location, canonicalRequest) + + // Gext hmac signing key. + signingKey := getSigningKey(secretAccessKey, location, t) + + // Calculate signature. signature := getSignature(signingKey, stringToSign) - r.req.URL.RawQuery += "&X-Amz-Signature=" + signature + // Add signature header to RawQuery. + req.URL.RawQuery += "&X-Amz-Signature=" + signature - return r.req.URL.String(), nil + return &req } -// PostPresignSignatureV4 - presigned signature for PostPolicy requests. -func (r *Request) PostPresignSignatureV4(policyBase64 string, t time.Time) string { - signingkey := getSigningKey(r.config.SecretAccessKey, r.config.Region, t) +// postPresignSignatureV4 - presigned signature for PostPolicy +// requests. +func postPresignSignatureV4(policyBase64 string, t time.Time, secretAccessKey, location string) string { + // Get signining key. + signingkey := getSigningKey(secretAccessKey, location, t) + // Calculate signature. signature := getSignature(signingkey, policyBase64) return signature } -// SignV4 sign the request before Do(), in accordance with +// signV4 sign the request before Do(), in accordance with // http://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-authenticating-requests.html. -func (r *Request) SignV4(presign bool) { +func signV4(req http.Request, accessKeyID, secretAccessKey, location string) *http.Request { + // Signature calculation is not needed for anonymous credentials. + if accessKeyID == "" || secretAccessKey == "" { + return &req + } + // Initial time. t := time.Now().UTC() + // Set x-amz-date. - r.Set("X-Amz-Date", t.Format(iso8601DateFormat)) + req.Header.Set("X-Amz-Date", t.Format(iso8601DateFormat)) + + // Get canonical request. + canonicalRequest := getCanonicalRequest(req) + + // Get string to sign from canonical request. + stringToSign := getStringToSignV4(t, location, canonicalRequest) + + // Get hmac signing key. + signingKey := getSigningKey(secretAccessKey, location, t) + + // Get credential string. + credential := getCredential(accessKeyID, location, t) // Get all signed headers. - signedHeaders := r.getSignedHeaders() - // Get string to sign from canonical request. - stringToSign := r.getStringToSignV4(r.getCanonicalRequest(), t) + signedHeaders := getSignedHeaders(req) - // get credential string. - credential := getCredential(r.config.AccessKeyID, r.config.Region, t) - // get hmac signing key. - signingKey := getSigningKey(r.config.SecretAccessKey, r.config.Region, t) - // calculate signature. + // Calculate signature. signature := getSignature(signingKey, stringToSign) - // if regular request, construct the final authorization header. + // If regular request, construct the final authorization header. parts := []string{ - authHeader + " Credential=" + credential, + signV4Algorithm + " Credential=" + credential, "SignedHeaders=" + signedHeaders, "Signature=" + signature, } + + // Set authorization header. auth := strings.Join(parts, ", ") - r.Set("Authorization", auth) + req.Header.Set("Authorization", auth) + + return &req } diff --git a/vendor/github.com/minio/minio-go/request.go b/vendor/github.com/minio/minio-go/request.go deleted file mode 100644 index 98792b1f..00000000 --- a/vendor/github.com/minio/minio-go/request.go +++ /dev/null @@ -1,281 +0,0 @@ -/* - * Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2015 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 - -import ( - "encoding/base64" - "encoding/hex" - "io" - "net/http" - "regexp" - "strings" - "unicode/utf8" -) - -// operation - rest operation. -type operation struct { - HTTPServer string - HTTPMethod string - HTTPPath string -} - -// Request - a http request. -type Request struct { - req *http.Request - config *Config - expires int64 -} - -// requestMetadata a http request metadata. -type requestMetadata struct { - body io.ReadCloser - contentType string - contentLength int64 - sha256PayloadBytes []byte - md5SumPayloadBytes []byte -} - -// Do - start the request. -func (r *Request) Do() (resp *http.Response, err error) { - // if not an anonymous request, calculate relevant signature. - if !r.config.isAnonymous() { - if r.config.Signature.isV2() { - // if signature version '2' requested, use that. - r.SignV2() - } - if r.config.Signature.isV4() || r.config.Signature.isLatest() { - // Not a presigned request, set behavior to default. - presign := false - r.SignV4(presign) - } - } - transport := http.DefaultTransport - if r.config.Transport != nil { - transport = r.config.Transport - } - // do not use http.Client{}, while it may seem intuitive but the problem seems to be - // that http.Client{} internally follows redirects and there is no easier way to disable - // it from outside using a configuration parameter - - // this auto redirect causes complications in verifying subsequent errors - // - // The best is to use RoundTrip() directly, so the request comes back to the caller where - // we are going to handle such replies. And indeed that is the right thing to do here. - // - return transport.RoundTrip(r.req) -} - -// Set - set additional headers if any. -func (r *Request) Set(key, value string) { - r.req.Header.Set(key, value) -} - -// Get - get header values. -func (r *Request) Get(key string) string { - return r.req.Header.Get(key) -} - -// path2BucketAndObject - extract bucket and object names from URL path. -func path2BucketAndObject(path string) (bucketName, objectName string) { - pathSplits := strings.SplitN(path, "?", 2) - splits := strings.SplitN(pathSplits[0], separator, 3) - switch len(splits) { - case 0, 1: - bucketName = "" - objectName = "" - case 2: - bucketName = splits[1] - objectName = "" - case 3: - bucketName = splits[1] - objectName = splits[2] - } - return bucketName, objectName -} - -// path2Object gives objectName from URL path -func path2Object(path string) (objectName string) { - _, objectName = path2BucketAndObject(path) - return -} - -// path2Bucket gives bucketName from URL path -func path2Bucket(path string) (bucketName string) { - bucketName, _ = path2BucketAndObject(path) - return -} - -// path2Query gives query part from URL path -func path2Query(path string) (query string) { - pathSplits := strings.SplitN(path, "?", 2) - if len(pathSplits) > 1 { - query = pathSplits[1] - } - return -} - -// getURLEncodedPath encode the strings from UTF-8 byte representations to HTML hex escape sequences -// -// This is necessary since regular url.Parse() and url.Encode() functions do not support UTF-8 -// non english characters cannot be parsed due to the nature in which url.Encode() is written -// -// This function on the other hand is a direct replacement for url.Encode() technique to support -// pretty much every UTF-8 character. -func getURLEncodedPath(pathName string) string { - // if object matches reserved string, no need to encode them - reservedNames := regexp.MustCompile("^[a-zA-Z0-9-_.~/]+$") - if reservedNames.MatchString(pathName) { - return pathName - } - var encodedPathname string - for _, s := range pathName { - if 'A' <= s && s <= 'Z' || 'a' <= s && s <= 'z' || '0' <= s && s <= '9' { // §2.3 Unreserved characters (mark) - encodedPathname = encodedPathname + string(s) - continue - } - switch s { - case '-', '_', '.', '~', '/': // §2.3 Unreserved characters (mark) - encodedPathname = encodedPathname + string(s) - continue - default: - len := utf8.RuneLen(s) - if len < 0 { - // if utf8 cannot convert return the same string as is - return pathName - } - u := make([]byte, len) - utf8.EncodeRune(u, s) - for _, r := range u { - hex := hex.EncodeToString([]byte{r}) - encodedPathname = encodedPathname + "%" + strings.ToUpper(hex) - } - } - } - return encodedPathname -} - -// getRequetURL - get a properly encoded request URL. -func (op *operation) getRequestURL(config Config) (url string) { - // parse URL for the combination of HTTPServer + HTTPPath - url = op.HTTPServer + separator - if !config.isVirtualHostedStyle { - url += path2Bucket(op.HTTPPath) - } - objectName := getURLEncodedPath(path2Object(op.HTTPPath)) - queryPath := path2Query(op.HTTPPath) - if objectName == "" && queryPath != "" { - url += "?" + queryPath - return - } - if objectName != "" && queryPath == "" { - if strings.HasSuffix(url, separator) { - url += objectName - } else { - url += separator + objectName - } - return - } - if objectName != "" && queryPath != "" { - if strings.HasSuffix(url, separator) { - url += objectName + "?" + queryPath - } else { - url += separator + objectName + "?" + queryPath - } - } - return -} - -func newPresignedRequest(op *operation, config *Config, expires int64) (*Request, error) { - // if no method default to POST - method := op.HTTPMethod - if method == "" { - method = "POST" - } - - u := op.getRequestURL(*config) - - // get a new HTTP request, for the requested method - req, err := http.NewRequest(method, u, nil) - if err != nil { - return nil, err - } - - // set UserAgent - req.Header.Set("User-Agent", config.userAgent) - - // save for subsequent use - r := new(Request) - r.config = config - r.expires = expires - r.req = req - - return r, nil -} - -// newRequest - instantiate a new request -func newRequest(op *operation, config *Config, metadata requestMetadata) (*Request, error) { - // if no method default to POST - method := op.HTTPMethod - if method == "" { - method = "POST" - } - - u := op.getRequestURL(*config) - // get a new HTTP request, for the requested method - req, err := http.NewRequest(method, u, nil) - if err != nil { - return nil, err - } - - // set UserAgent - req.Header.Set("User-Agent", config.userAgent) - - // add body - switch { - case metadata.body == nil: - req.Body = nil - default: - req.Body = metadata.body - } - - // save for subsequent use - r := new(Request) - r.config = config - r.req = req - - // Set contentType for the request. - if metadata.contentType != "" { - r.Set("Content-Type", metadata.contentType) - } - - // set incoming content-length. - if metadata.contentLength > 0 { - r.req.ContentLength = metadata.contentLength - } - - // set sha256 sum for signature calculation only with signature version '4'. - if r.config.Signature.isV4() || r.config.Signature.isLatest() { - r.Set("X-Amz-Content-Sha256", hex.EncodeToString(sum256([]byte{}))) - if metadata.sha256PayloadBytes != nil { - r.Set("X-Amz-Content-Sha256", hex.EncodeToString(metadata.sha256PayloadBytes)) - } - } - // set md5Sum for in transit corruption detection. - if metadata.md5SumPayloadBytes != nil { - r.Set("Content-MD5", base64.StdEncoding.EncodeToString(metadata.md5SumPayloadBytes)) - } - return r, nil -} diff --git a/vendor/github.com/minio/minio-go/s3-api-errors.go b/vendor/github.com/minio/minio-go/s3-api-errors.go deleted file mode 100644 index 0a63f7e6..00000000 --- a/vendor/github.com/minio/minio-go/s3-api-errors.go +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2015 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 - -import "net/http" - -// TODO - handle this automatically by re-writing the request as virtual style. -// -// For path style requests on buckets with wrong endpoint s3 returns back a -// generic error. Following block of code tries to make this meaningful for -// the user by fetching the proper endpoint. Additionally also sets AmzBucketRegion. -func (a s3API) handleStatusMovedPermanently(resp *http.Response, bucket, object string) ErrorResponse { - errorResponse := ErrorResponse{ - Code: "PermanentRedirect", - RequestID: resp.Header.Get("x-amz-request-id"), - HostID: resp.Header.Get("x-amz-id-2"), - AmzBucketRegion: resp.Header.Get("x-amz-bucket-region"), - } - errorResponse.Resource = separator + bucket - if object != "" { - errorResponse.Resource = separator + bucket + separator + object - } - var endPoint string - if errorResponse.AmzBucketRegion != "" { - region := errorResponse.AmzBucketRegion - endPoint = getEndpoint(region) - } else { - region, err := a.getBucketLocation(bucket) - if err != nil { - return *ToErrorResponse(err) - } - endPoint = getEndpoint(region) - } - msg := "The bucket you are attempting to access must be addressed using the specified endpoint https://" + endPoint + ". Send all future requests to this endpoint." - errorResponse.Message = msg - return errorResponse -} diff --git a/vendor/github.com/minio/minio-go/s3-api.go b/vendor/github.com/minio/minio-go/s3-api.go deleted file mode 100644 index fc3973c3..00000000 --- a/vendor/github.com/minio/minio-go/s3-api.go +++ /dev/null @@ -1,905 +0,0 @@ -/* - * Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2015 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 - -import ( - "bytes" - "encoding/xml" - "fmt" - "io" - "io/ioutil" - "net/http" - "strconv" - "strings" - "time" -) - -const ( - separator = "/" -) - -// s3API container to hold unexported internal functions. -type s3API struct { - config *Config -} - -// closeResp close non nil response with any response Body. -// convenient wrapper to drain any remaining data on response body. -// -// Subsequently this allows golang http RoundTripper -// to re-use the same connection for future requests. -func closeResp(resp *http.Response) { - // Callers should close resp.Body when done reading from it. - // If resp.Body is not closed, the Client's underlying RoundTripper - // (typically Transport) may not be able to re-use a persistent TCP - // connection to the server for a subsequent "keep-alive" request. - if resp != nil && resp.Body != nil { - // Drain any remaining Body and then close the connection. - // Without this closing connection would disallow re-using - // the same connection for future uses. - // - http://stackoverflow.com/a/17961593/4465767 - io.Copy(ioutil.Discard, resp.Body) - resp.Body.Close() - } -} - -// putBucketRequest wrapper creates a new putBucket request. -func (a s3API) putBucketRequest(bucket, acl, location string) (*Request, error) { - var r *Request - var err error - op := &operation{ - HTTPServer: a.config.Endpoint, - HTTPMethod: "PUT", - HTTPPath: separator + bucket, - } - var createBucketConfigBuffer *bytes.Buffer - // If location is set use it and create proper bucket configuration. - switch { - case location != "": - createBucketConfig := new(createBucketConfiguration) - createBucketConfig.Location = location - createBucketConfigBytes, err := xml.Marshal(createBucketConfig) - if err != nil { - return nil, err - } - createBucketConfigBuffer = bytes.NewBuffer(createBucketConfigBytes) - } - switch { - case createBucketConfigBuffer == nil: - r, err = newRequest(op, a.config, requestMetadata{}) - if err != nil { - return nil, err - } - default: - rmetadata := requestMetadata{ - body: ioutil.NopCloser(createBucketConfigBuffer), - contentLength: int64(createBucketConfigBuffer.Len()), - sha256PayloadBytes: sum256(createBucketConfigBuffer.Bytes()), - } - r, err = newRequest(op, a.config, rmetadata) - if err != nil { - return nil, err - } - } - // by default bucket is private - switch { - case acl != "": - r.Set("x-amz-acl", acl) - default: - r.Set("x-amz-acl", "private") - } - - return r, nil -} - -/// Bucket Write Operations - -// putBucket create a new bucket. -// -// Requires valid AWS Access Key ID to authenticate requests. -// Anonymous requests are never allowed to create buckets. -// -// optional arguments are acl and location - by default all buckets are created -// with ``private`` acl and location set to US Standard if one wishes to set -// different ACLs and Location one can set them properly. -// -// ACL valid values -// ------------------ -// private - owner gets full access [DEFAULT]. -// public-read - owner gets full access, others get read access. -// public-read-write - owner gets full access, others get full access too. -// authenticated-read - owner gets full access, authenticated users get read access. -// ------------------ -// -// Location valid values. -// ------------------ -// [ us-west-1 | us-west-2 | eu-west-1 | eu-central-1 | ap-southeast-1 | ap-northeast-1 | ap-southeast-2 | sa-east-1 ] -// Default - US standard -func (a s3API) putBucket(bucket, acl, location string) error { - req, err := a.putBucketRequest(bucket, acl, location) - if err != nil { - return err - } - resp, err := req.Do() - defer closeResp(resp) - if err != nil { - return err - } - if resp != nil { - if resp.StatusCode != http.StatusOK { - return BodyToErrorResponse(resp.Body) - } - } - return nil -} - -// putBucketRequestACL wrapper creates a new putBucketACL request. -func (a s3API) putBucketACLRequest(bucket, acl string) (*Request, error) { - op := &operation{ - HTTPServer: a.config.Endpoint, - HTTPMethod: "PUT", - HTTPPath: separator + bucket + "?acl", - } - req, err := newRequest(op, a.config, requestMetadata{}) - if err != nil { - return nil, err - } - req.Set("x-amz-acl", acl) - return req, nil -} - -// putBucketACL set the permissions on an existing bucket using Canned ACL's. -func (a s3API) putBucketACL(bucket, acl string) error { - req, err := a.putBucketACLRequest(bucket, acl) - if err != nil { - return err - } - resp, err := req.Do() - defer closeResp(resp) - if err != nil { - return err - } - if resp != nil { - if resp.StatusCode != http.StatusOK { - if resp.StatusCode == http.StatusMovedPermanently { - return a.handleStatusMovedPermanently(resp, bucket, "") - } - return BodyToErrorResponse(resp.Body) - } - } - return nil -} - -// getBucketACLRequest wrapper creates a new getBucketACL request. -func (a s3API) getBucketACLRequest(bucket string) (*Request, error) { - op := &operation{ - HTTPServer: a.config.Endpoint, - HTTPMethod: "GET", - HTTPPath: separator + bucket + "?acl", - } - req, err := newRequest(op, a.config, requestMetadata{}) - if err != nil { - return nil, err - } - return req, nil -} - -// getBucketACL get the acl information on an existing bucket. -func (a s3API) getBucketACL(bucket string) (accessControlPolicy, error) { - req, err := a.getBucketACLRequest(bucket) - if err != nil { - return accessControlPolicy{}, err - } - resp, err := req.Do() - defer closeResp(resp) - if err != nil { - return accessControlPolicy{}, err - } - if resp != nil { - if resp.StatusCode != http.StatusOK { - if resp.StatusCode == http.StatusMovedPermanently { - errorResponse := a.handleStatusMovedPermanently(resp, bucket, "") - return accessControlPolicy{}, errorResponse - } - return accessControlPolicy{}, BodyToErrorResponse(resp.Body) - } - } - policy := accessControlPolicy{} - err = xmlDecoder(resp.Body, &policy) - if err != nil { - return accessControlPolicy{}, err - } - // In-case of google private bucket policy doesn't have any Grant list. - if a.config.Region == "google" { - return policy, nil - } - if policy.AccessControlList.Grant == nil { - errorResponse := ErrorResponse{ - Code: "InternalError", - Message: "Access control Grant list is empty, please report this at https://github.com/minio/minio-go/issues.", - Resource: separator + bucket, - RequestID: resp.Header.Get("x-amz-request-id"), - HostID: resp.Header.Get("x-amz-id-2"), - AmzBucketRegion: resp.Header.Get("x-amz-bucket-region"), - } - return accessControlPolicy{}, errorResponse - } - return policy, nil -} - -// getBucketLocationRequest wrapper creates a new getBucketLocation request. -func (a s3API) getBucketLocationRequest(bucket string) (*Request, error) { - op := &operation{ - HTTPServer: a.config.Endpoint, - HTTPMethod: "GET", - HTTPPath: separator + bucket + "?location", - } - req, err := newRequest(op, a.config, requestMetadata{}) - if err != nil { - return nil, err - } - return req, nil -} - -// getBucketLocation uses location subresource to return a bucket's region. -func (a s3API) getBucketLocation(bucket string) (string, error) { - req, err := a.getBucketLocationRequest(bucket) - if err != nil { - return "", err - } - resp, err := req.Do() - defer closeResp(resp) - if err != nil { - return "", err - } - if resp != nil { - if resp.StatusCode != http.StatusOK { - return "", BodyToErrorResponse(resp.Body) - } - } - var locationConstraint string - err = xmlDecoder(resp.Body, &locationConstraint) - if err != nil { - return "", err - } - return locationConstraint, nil -} - -// listObjectsRequest wrapper creates a new listObjects request. -func (a s3API) listObjectsRequest(bucket, marker, prefix, delimiter string, maxkeys int) (*Request, error) { - // resourceQuery - get resources properly escaped and lined up before using them in http request. - resourceQuery := func() (*string, error) { - switch { - case marker != "": - marker = fmt.Sprintf("&marker=%s", getURLEncodedPath(marker)) - fallthrough - case prefix != "": - prefix = fmt.Sprintf("&prefix=%s", getURLEncodedPath(prefix)) - fallthrough - case delimiter != "": - delimiter = fmt.Sprintf("&delimiter=%s", delimiter) - } - query := fmt.Sprintf("?max-keys=%d", maxkeys) + marker + prefix + delimiter - return &query, nil - } - query, err := resourceQuery() - if err != nil { - return nil, err - } - op := &operation{ - HTTPServer: a.config.Endpoint, - HTTPMethod: "GET", - HTTPPath: separator + bucket + *query, - } - r, err := newRequest(op, a.config, requestMetadata{}) - if err != nil { - return nil, err - } - return r, nil -} - -/// Bucket Read Operations. - -// listObjects - (List Objects) - List some or all (up to 1000) of the objects in a bucket. -// -// You can use the request parameters as selection criteria to return a subset of the objects in a bucket. -// request paramters :- -// --------- -// ?marker - Specifies the key to start with when listing objects in a bucket. -// ?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 (a s3API) listObjects(bucket, marker, prefix, delimiter string, maxkeys int) (listBucketResult, error) { - if err := invalidBucketError(bucket); err != nil { - return listBucketResult{}, err - } - req, err := a.listObjectsRequest(bucket, marker, prefix, delimiter, maxkeys) - if err != nil { - return listBucketResult{}, err - } - resp, err := req.Do() - defer closeResp(resp) - if err != nil { - return listBucketResult{}, err - } - if resp != nil { - if resp.StatusCode != http.StatusOK { - if resp.StatusCode == http.StatusMovedPermanently { - errorResponse := a.handleStatusMovedPermanently(resp, bucket, "") - return listBucketResult{}, errorResponse - } - return listBucketResult{}, BodyToErrorResponse(resp.Body) - } - } - listBucketResult := listBucketResult{} - err = xmlDecoder(resp.Body, &listBucketResult) - if err != nil { - return listBucketResult, err - } - // close body while returning, along with any error. - return listBucketResult, nil -} - -// headBucketRequest wrapper creates a new headBucket request. -func (a s3API) headBucketRequest(bucket string) (*Request, error) { - op := &operation{ - HTTPServer: a.config.Endpoint, - HTTPMethod: "HEAD", - HTTPPath: separator + bucket, - } - return newRequest(op, a.config, requestMetadata{}) -} - -// headBucket useful to determine if a bucket exists and you have permission to access it. -func (a s3API) headBucket(bucket string) error { - if err := invalidBucketError(bucket); err != nil { - return err - } - req, err := a.headBucketRequest(bucket) - if err != nil { - return err - } - resp, err := req.Do() - defer closeResp(resp) - if err != nil { - return err - } - if resp != nil { - if resp.StatusCode != http.StatusOK { - // Head has no response body, handle it. - var errorResponse ErrorResponse - switch resp.StatusCode { - case http.StatusMovedPermanently: - errorResponse = a.handleStatusMovedPermanently(resp, bucket, "") - case http.StatusNotFound: - errorResponse = ErrorResponse{ - Code: "NoSuchBucket", - Message: "The specified bucket does not exist.", - Resource: separator + bucket, - RequestID: resp.Header.Get("x-amz-request-id"), - HostID: resp.Header.Get("x-amz-id-2"), - AmzBucketRegion: resp.Header.Get("x-amz-bucket-region"), - } - case http.StatusForbidden: - errorResponse = ErrorResponse{ - Code: "AccessDenied", - Message: "Access Denied.", - Resource: separator + bucket, - RequestID: resp.Header.Get("x-amz-request-id"), - HostID: resp.Header.Get("x-amz-id-2"), - AmzBucketRegion: resp.Header.Get("x-amz-bucket-region"), - } - default: - errorResponse = ErrorResponse{ - Code: resp.Status, - Message: resp.Status, - Resource: separator + bucket, - RequestID: resp.Header.Get("x-amz-request-id"), - HostID: resp.Header.Get("x-amz-id-2"), - AmzBucketRegion: resp.Header.Get("x-amz-bucket-region"), - } - } - return errorResponse - } - } - return nil -} - -// deleteBucketRequest wrapper creates a new deleteBucket request. -func (a s3API) deleteBucketRequest(bucket string) (*Request, error) { - op := &operation{ - HTTPServer: a.config.Endpoint, - HTTPMethod: "DELETE", - HTTPPath: separator + bucket, - } - return newRequest(op, a.config, requestMetadata{}) -} - -// deleteBucket deletes the bucket named in the URI. -// -// NOTE: - -// All objects (including all object versions and delete markers) -// in the bucket must be deleted before successfully attempting this request. -func (a s3API) deleteBucket(bucket string) error { - if err := invalidBucketError(bucket); err != nil { - return err - } - req, err := a.deleteBucketRequest(bucket) - if err != nil { - return err - } - resp, err := req.Do() - defer closeResp(resp) - if err != nil { - return err - } - if resp != nil { - if resp.StatusCode != http.StatusNoContent { - var errorResponse ErrorResponse - switch resp.StatusCode { - case http.StatusMovedPermanently: - errorResponse = a.handleStatusMovedPermanently(resp, bucket, "") - case http.StatusNotFound: - errorResponse = ErrorResponse{ - Code: "NoSuchBucket", - Message: "The specified bucket does not exist.", - Resource: separator + bucket, - RequestID: resp.Header.Get("x-amz-request-id"), - HostID: resp.Header.Get("x-amz-id-2"), - AmzBucketRegion: resp.Header.Get("x-amz-bucket-region"), - } - case http.StatusForbidden: - errorResponse = ErrorResponse{ - Code: "AccessDenied", - Message: "Access Denied.", - Resource: separator + bucket, - RequestID: resp.Header.Get("x-amz-request-id"), - HostID: resp.Header.Get("x-amz-id-2"), - AmzBucketRegion: resp.Header.Get("x-amz-bucket-region"), - } - case http.StatusConflict: - errorResponse = ErrorResponse{ - Code: "Conflict", - Message: "Bucket not empty.", - Resource: separator + bucket, - RequestID: resp.Header.Get("x-amz-request-id"), - HostID: resp.Header.Get("x-amz-id-2"), - AmzBucketRegion: resp.Header.Get("x-amz-bucket-region"), - } - default: - errorResponse = ErrorResponse{ - Code: resp.Status, - Message: resp.Status, - Resource: separator + bucket, - RequestID: resp.Header.Get("x-amz-request-id"), - HostID: resp.Header.Get("x-amz-id-2"), - AmzBucketRegion: resp.Header.Get("x-amz-bucket-region"), - } - } - return errorResponse - } - } - return nil -} - -/// Object Read/Write/Stat Operations - -// putObjectRequest wrapper creates a new PutObject request. -func (a s3API) putObjectRequest(bucket, object string, putObjMetadata putObjectMetadata) (*Request, error) { - if strings.TrimSpace(putObjMetadata.ContentType) == "" { - putObjMetadata.ContentType = "application/octet-stream" - } - op := &operation{ - HTTPServer: a.config.Endpoint, - HTTPMethod: "PUT", - HTTPPath: separator + bucket + separator + object, - } - rmetadata := requestMetadata{ - body: putObjMetadata.ReadCloser, - contentLength: putObjMetadata.Size, - contentType: putObjMetadata.ContentType, - sha256PayloadBytes: putObjMetadata.Sha256Sum, - md5SumPayloadBytes: putObjMetadata.MD5Sum, - } - r, err := newRequest(op, a.config, rmetadata) - if err != nil { - return nil, err - } - return r, nil -} - -// putObject - add an object to a bucket. -// NOTE: You must have WRITE permissions on a bucket to add an object to it. -func (a s3API) putObject(bucket, object string, putObjMetadata putObjectMetadata) (ObjectStat, error) { - req, err := a.putObjectRequest(bucket, object, putObjMetadata) - if err != nil { - return ObjectStat{}, err - } - resp, err := req.Do() - defer closeResp(resp) - if err != nil { - return ObjectStat{}, err - } - if resp != nil { - if resp.StatusCode != http.StatusOK { - if resp.StatusCode == http.StatusMovedPermanently { - errorResponse := a.handleStatusMovedPermanently(resp, bucket, object) - return ObjectStat{}, errorResponse - } - return ObjectStat{}, BodyToErrorResponse(resp.Body) - } - } - var metadata ObjectStat - metadata.ETag = strings.Trim(resp.Header.Get("ETag"), "\"") // trim off the odd double quotes - return metadata, nil -} - -// presignedPostPolicy - generate post form data. -func (a s3API) presignedPostPolicy(p *PostPolicy) map[string]string { - t := time.Now().UTC() - r := new(Request) - r.config = a.config - if r.config.Signature.isV2() { - policyBase64 := p.base64() - p.formData["policy"] = policyBase64 - // for all other regions set this value to be 'AWSAccessKeyId'. - if r.config.Region != "google" { - p.formData["AWSAccessKeyId"] = r.config.AccessKeyID - } else { - p.formData["GoogleAccessId"] = r.config.AccessKeyID - } - p.formData["signature"] = r.PostPresignSignatureV2(policyBase64) - return p.formData - } - credential := getCredential(r.config.AccessKeyID, r.config.Region, t) - p.addNewPolicy(policyCondition{ - matchType: "eq", - condition: "$x-amz-date", - value: t.Format(iso8601DateFormat), - }) - p.addNewPolicy(policyCondition{ - matchType: "eq", - condition: "$x-amz-algorithm", - value: authHeader, - }) - p.addNewPolicy(policyCondition{ - matchType: "eq", - condition: "$x-amz-credential", - value: credential, - }) - policyBase64 := p.base64() - p.formData["policy"] = policyBase64 - p.formData["x-amz-algorithm"] = authHeader - p.formData["x-amz-credential"] = credential - p.formData["x-amz-date"] = t.Format(iso8601DateFormat) - p.formData["x-amz-signature"] = r.PostPresignSignatureV4(policyBase64, t) - return p.formData -} - -// presignedPutObject - generate presigned PUT url. -func (a s3API) presignedPutObject(bucket, object string, expires int64) (string, error) { - op := &operation{ - HTTPServer: a.config.Endpoint, - HTTPMethod: "PUT", - HTTPPath: separator + bucket + separator + object, - } - r, err := newPresignedRequest(op, a.config, expires) - if err != nil { - return "", err - } - if r.config.Signature.isV2() { - return r.PreSignV2() - } - return r.PreSignV4() -} - -// presignedGetObjectRequest - presigned get object request -func (a s3API) presignedGetObjectRequest(bucket, object string, expires, offset, length int64) (*Request, error) { - op := &operation{ - HTTPServer: a.config.Endpoint, - HTTPMethod: "GET", - HTTPPath: separator + bucket + separator + object, - } - r, err := newPresignedRequest(op, a.config, expires) - if err != nil { - return nil, err - } - switch { - case length > 0 && offset > 0: - r.Set("Range", fmt.Sprintf("bytes=%d-%d", offset, offset+length-1)) - case offset > 0 && length == 0: - r.Set("Range", fmt.Sprintf("bytes=%d-", offset)) - case length > 0 && offset == 0: - r.Set("Range", fmt.Sprintf("bytes=-%d", length)) - } - return r, nil -} - -// presignedGetObject - generate presigned get object URL. -func (a s3API) presignedGetObject(bucket, object string, expires, offset, length int64) (string, error) { - if err := invalidArgumentError(object); err != nil { - return "", err - } - r, err := a.presignedGetObjectRequest(bucket, object, expires, offset, length) - if err != nil { - return "", err - } - if r.config.Signature.isV2() { - return r.PreSignV2() - } - return r.PreSignV4() -} - -// getObjectRequest wrapper creates a new getObject request. -func (a s3API) getObjectRequest(bucket, object string, offset, length int64) (*Request, error) { - op := &operation{ - HTTPServer: a.config.Endpoint, - HTTPMethod: "GET", - HTTPPath: separator + bucket + separator + object, - } - r, err := newRequest(op, a.config, requestMetadata{}) - if err != nil { - return nil, err - } - switch { - case length > 0 && offset >= 0: - r.Set("Range", fmt.Sprintf("bytes=%d-%d", offset, offset+length-1)) - case offset > 0 && length == 0: - r.Set("Range", fmt.Sprintf("bytes=%d-", offset)) - // The final length bytes - case length < 0 && offset == 0: - r.Set("Range", fmt.Sprintf("bytes=%d", length)) - } - return r, nil -} - -// getObject - retrieve object from Object Storage. -// -// Additionally this function also takes range arguments to download the specified -// range bytes of an object. Setting offset and length = 0 will download the full object. -// -// For more information about the HTTP Range header. -// go to http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35. -func (a s3API) getObject(bucket, object string, offset, length int64) (io.ReadCloser, ObjectStat, error) { - if err := invalidArgumentError(object); err != nil { - return nil, ObjectStat{}, err - } - req, err := a.getObjectRequest(bucket, object, offset, length) - if err != nil { - return nil, ObjectStat{}, err - } - resp, err := req.Do() - if err != nil { - return nil, ObjectStat{}, err - } - if resp != nil { - switch resp.StatusCode { - // for HTTP status 200 and 204 are valid cases. - case http.StatusOK: - case http.StatusPartialContent: - // handle 301 sepcifically in case of wrong regions during path style. - case http.StatusMovedPermanently: - errorResponse := a.handleStatusMovedPermanently(resp, bucket, object) - return nil, ObjectStat{}, errorResponse - default: - return nil, ObjectStat{}, BodyToErrorResponse(resp.Body) - } - } - md5sum := strings.Trim(resp.Header.Get("ETag"), "\"") // trim off the odd double quotes - date, err := time.Parse(http.TimeFormat, resp.Header.Get("Last-Modified")) - if err != nil { - return nil, ObjectStat{}, ErrorResponse{ - Code: "InternalError", - Message: "Last-Modified time format not recognized, please report this issue at https://github.com/minio/minio-go/issues.", - RequestID: resp.Header.Get("x-amz-request-id"), - HostID: resp.Header.Get("x-amz-id-2"), - AmzBucketRegion: resp.Header.Get("x-amz-bucket-region"), - } - } - contentType := strings.TrimSpace(resp.Header.Get("Content-Type")) - if contentType == "" { - contentType = "application/octet-stream" - } - var objectstat ObjectStat - objectstat.ETag = md5sum - objectstat.Key = object - objectstat.Size = resp.ContentLength - objectstat.LastModified = date - objectstat.ContentType = contentType - - // do not close body here, caller will close - return resp.Body, objectstat, nil -} - -// deleteObjectRequest wrapper creates a new deleteObject request. -func (a s3API) deleteObjectRequest(bucket, object string) (*Request, error) { - op := &operation{ - HTTPServer: a.config.Endpoint, - HTTPMethod: "DELETE", - HTTPPath: separator + bucket + separator + object, - } - return newRequest(op, a.config, requestMetadata{}) -} - -// deleteObject deletes a given object from a bucket. -func (a s3API) deleteObject(bucket, object string) error { - if err := invalidBucketError(bucket); err != nil { - return err - } - if err := invalidArgumentError(object); err != nil { - return err - } - req, err := a.deleteObjectRequest(bucket, object) - if err != nil { - return err - } - resp, err := req.Do() - defer closeResp(resp) - if err != nil { - return err - } - // DeleteObject always responds with http '204' even for - // objects which do not exist. So no need to handle them - // specifically. - return nil -} - -// headObjectRequest wrapper creates a new headObject request. -func (a s3API) headObjectRequest(bucket, object string) (*Request, error) { - op := &operation{ - HTTPServer: a.config.Endpoint, - HTTPMethod: "HEAD", - HTTPPath: separator + bucket + separator + object, - } - return newRequest(op, a.config, requestMetadata{}) -} - -// headObject retrieves metadata from an object without returning the object itself. -func (a s3API) headObject(bucket, object string) (ObjectStat, error) { - if err := invalidBucketError(bucket); err != nil { - return ObjectStat{}, err - } - if err := invalidArgumentError(object); err != nil { - return ObjectStat{}, err - } - req, err := a.headObjectRequest(bucket, object) - if err != nil { - return ObjectStat{}, err - } - resp, err := req.Do() - defer closeResp(resp) - if err != nil { - return ObjectStat{}, err - } - if resp != nil { - if resp.StatusCode != http.StatusOK { - var errorResponse ErrorResponse - switch resp.StatusCode { - case http.StatusMovedPermanently: - errorResponse = a.handleStatusMovedPermanently(resp, bucket, object) - case http.StatusNotFound: - errorResponse = ErrorResponse{ - Code: "NoSuchKey", - Message: "The specified key does not exist.", - Resource: separator + bucket + separator + object, - RequestID: resp.Header.Get("x-amz-request-id"), - HostID: resp.Header.Get("x-amz-id-2"), - AmzBucketRegion: resp.Header.Get("x-amz-bucket-region"), - } - case http.StatusForbidden: - errorResponse = ErrorResponse{ - Code: "AccessDenied", - Message: "Access Denied.", - Resource: separator + bucket + separator + object, - RequestID: resp.Header.Get("x-amz-request-id"), - HostID: resp.Header.Get("x-amz-id-2"), - AmzBucketRegion: resp.Header.Get("x-amz-bucket-region"), - } - default: - errorResponse = ErrorResponse{ - Code: resp.Status, - Message: resp.Status, - Resource: separator + bucket + separator + object, - RequestID: resp.Header.Get("x-amz-request-id"), - HostID: resp.Header.Get("x-amz-id-2"), - AmzBucketRegion: resp.Header.Get("x-amz-bucket-region"), - } - - } - return ObjectStat{}, errorResponse - } - } - md5sum := strings.Trim(resp.Header.Get("ETag"), "\"") // trim off the odd double quotes - size, err := strconv.ParseInt(resp.Header.Get("Content-Length"), 10, 64) - if err != nil { - return ObjectStat{}, ErrorResponse{ - Code: "InternalError", - Message: "Content-Length not recognized, please report this issue at https://github.com/minio/minio-go/issues.", - RequestID: resp.Header.Get("x-amz-request-id"), - HostID: resp.Header.Get("x-amz-id-2"), - AmzBucketRegion: resp.Header.Get("x-amz-bucket-region"), - } - } - date, err := time.Parse(http.TimeFormat, resp.Header.Get("Last-Modified")) - if err != nil { - return ObjectStat{}, ErrorResponse{ - Code: "InternalError", - Message: "Last-Modified time format not recognized, please report this issue at https://github.com/minio/minio-go/issues.", - RequestID: resp.Header.Get("x-amz-request-id"), - HostID: resp.Header.Get("x-amz-id-2"), - AmzBucketRegion: resp.Header.Get("x-amz-bucket-region"), - } - } - contentType := strings.TrimSpace(resp.Header.Get("Content-Type")) - if contentType == "" { - contentType = "application/octet-stream" - } - - var objectstat ObjectStat - objectstat.ETag = md5sum - objectstat.Key = object - objectstat.Size = size - objectstat.LastModified = date - objectstat.ContentType = contentType - return objectstat, nil -} - -/// Service Operations. - -// listBucketRequest wrapper creates a new listBuckets request. -func (a s3API) listBucketsRequest() (*Request, error) { - op := &operation{ - HTTPServer: a.config.Endpoint, - HTTPMethod: "GET", - HTTPPath: separator, - } - return newRequest(op, a.config, requestMetadata{}) -} - -// listBuckets list of all buckets owned by the authenticated sender of the request. -func (a s3API) listBuckets() (listAllMyBucketsResult, error) { - req, err := a.listBucketsRequest() - if err != nil { - return listAllMyBucketsResult{}, err - } - resp, err := req.Do() - defer closeResp(resp) - if err != nil { - return listAllMyBucketsResult{}, err - } - if resp != nil { - // for un-authenticated requests, amazon sends a redirect handle it. - if resp.StatusCode == http.StatusTemporaryRedirect { - return listAllMyBucketsResult{}, ErrorResponse{ - Code: "AccessDenied", - Message: "Anonymous access is forbidden for this operation.", - RequestID: resp.Header.Get("x-amz-request-id"), - HostID: resp.Header.Get("x-amz-id-2"), - AmzBucketRegion: resp.Header.Get("x-amz-bucket-region"), - } - } - if resp.StatusCode != http.StatusOK { - return listAllMyBucketsResult{}, BodyToErrorResponse(resp.Body) - } - } - listAllMyBucketsResult := listAllMyBucketsResult{} - err = xmlDecoder(resp.Body, &listAllMyBucketsResult) - if err != nil { - return listAllMyBucketsResult, err - } - return listAllMyBucketsResult, nil -} diff --git a/vendor/github.com/minio/minio-go/s3-endpoints.go b/vendor/github.com/minio/minio-go/s3-endpoints.go new file mode 100644 index 00000000..8c9ff5e8 --- /dev/null +++ b/vendor/github.com/minio/minio-go/s3-endpoints.go @@ -0,0 +1,40 @@ +/* + * Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2015 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 + +// awsS3EndpointMap Amazon S3 endpoint map. +var awsS3EndpointMap = map[string]string{ + "us-east-1": "s3.amazonaws.com", + "us-west-2": "s3-us-west-2.amazonaws.com", + "us-west-1": "s3-us-west-1.amazonaws.com", + "eu-west-1": "s3-eu-west-1.amazonaws.com", + "eu-central-1": "s3-eu-central-1.amazonaws.com", + "ap-southeast-1": "s3-ap-southeast-1.amazonaws.com", + "ap-northeast-1": "s3-ap-northeast-1.amazonaws.com", + "ap-northeast-2": "s3-ap-northeast-2.amazonaws.com", + "sa-east-1": "s3-sa-east-1.amazonaws.com", +} + +// getS3Endpoint get Amazon S3 endpoint based on the bucket location. +func getS3Endpoint(bucketLocation string) (s3Endpoint string) { + s3Endpoint, ok := awsS3EndpointMap[bucketLocation] + if !ok { + // Default to 's3.amazonaws.com' endpoint. + s3Endpoint = "s3.amazonaws.com" + } + return s3Endpoint +} diff --git a/vendor/github.com/minio/minio-go/s3-multipart-api.go b/vendor/github.com/minio/minio-go/s3-multipart-api.go deleted file mode 100644 index cb402f96..00000000 --- a/vendor/github.com/minio/minio-go/s3-multipart-api.go +++ /dev/null @@ -1,332 +0,0 @@ -/* - * Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2015 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 - -import ( - "bytes" - "encoding/xml" - "fmt" - "io/ioutil" - "net/http" - "strconv" -) - -// listMultipartUploadsRequest wrapper creates a new listMultipartUploads request. -func (a s3API) listMultipartUploadsRequest(bucket, keymarker, uploadIDMarker, prefix, delimiter string, maxuploads int) (*Request, error) { - // resourceQuery get resources properly escaped and lined up before using them in http request. - resourceQuery := func() (string, error) { - switch { - case keymarker != "": - keymarker = fmt.Sprintf("&key-marker=%s", getURLEncodedPath(keymarker)) - fallthrough - case uploadIDMarker != "": - uploadIDMarker = fmt.Sprintf("&upload-id-marker=%s", uploadIDMarker) - fallthrough - case prefix != "": - prefix = fmt.Sprintf("&prefix=%s", getURLEncodedPath(prefix)) - fallthrough - case delimiter != "": - delimiter = fmt.Sprintf("&delimiter=%s", delimiter) - } - query := fmt.Sprintf("?uploads&max-uploads=%d", maxuploads) + keymarker + uploadIDMarker + prefix + delimiter - return query, nil - } - query, err := resourceQuery() - if err != nil { - return nil, err - } - op := &operation{ - HTTPServer: a.config.Endpoint, - HTTPMethod: "GET", - HTTPPath: separator + bucket + query, - } - r, err := newRequest(op, a.config, requestMetadata{}) - if err != nil { - return nil, err - } - return r, nil -} - -// listMultipartUploads - (List Multipart Uploads). -// - Lists some or all (up to 1000) in-progress multipart uploads in a bucket. -// -// You can use the request parameters as selection criteria to return a subset of the uploads in a bucket. -// request paramters. :- -// --------- -// ?key-marker - Specifies the multipart upload after which listing should begin. -// ?upload-id-marker - Together with key-marker specifies the multipart upload after which listing should begin. -// ?delimiter - A delimiter is a character you use to group keys. -// ?prefix - Limits the response to keys that begin with the specified prefix. -// ?max-uploads - Sets the maximum number of multipart uploads returned in the response body. -func (a s3API) listMultipartUploads(bucket, keymarker, uploadIDMarker, prefix, delimiter string, maxuploads int) (listMultipartUploadsResult, error) { - req, err := a.listMultipartUploadsRequest(bucket, keymarker, uploadIDMarker, prefix, delimiter, maxuploads) - if err != nil { - return listMultipartUploadsResult{}, err - } - resp, err := req.Do() - defer closeResp(resp) - if err != nil { - return listMultipartUploadsResult{}, err - } - if resp != nil { - if resp.StatusCode != http.StatusOK { - return listMultipartUploadsResult{}, BodyToErrorResponse(resp.Body) - } - } - listMultipartUploadsResult := listMultipartUploadsResult{} - err = xmlDecoder(resp.Body, &listMultipartUploadsResult) - if err != nil { - return listMultipartUploadsResult, err - } - return listMultipartUploadsResult, nil -} - -// initiateMultipartRequest wrapper creates a new initiateMultiPart request. -func (a s3API) initiateMultipartRequest(bucket, object string) (*Request, error) { - op := &operation{ - HTTPServer: a.config.Endpoint, - HTTPMethod: "POST", - HTTPPath: separator + bucket + separator + object + "?uploads", - } - return newRequest(op, a.config, requestMetadata{}) -} - -// initiateMultipartUpload initiates a multipart upload and returns an upload ID. -func (a s3API) initiateMultipartUpload(bucket, object string) (initiateMultipartUploadResult, error) { - req, err := a.initiateMultipartRequest(bucket, object) - if err != nil { - return initiateMultipartUploadResult{}, err - } - resp, err := req.Do() - defer closeResp(resp) - if err != nil { - return initiateMultipartUploadResult{}, err - } - if resp != nil { - if resp.StatusCode != http.StatusOK { - return initiateMultipartUploadResult{}, BodyToErrorResponse(resp.Body) - } - } - initiateMultipartUploadResult := initiateMultipartUploadResult{} - err = xmlDecoder(resp.Body, &initiateMultipartUploadResult) - if err != nil { - return initiateMultipartUploadResult, err - } - return initiateMultipartUploadResult, nil -} - -// completeMultipartUploadRequest wrapper creates a new CompleteMultipartUpload request. -func (a s3API) completeMultipartUploadRequest(bucket, object, uploadID string, complete completeMultipartUpload) (*Request, error) { - op := &operation{ - HTTPServer: a.config.Endpoint, - HTTPMethod: "POST", - HTTPPath: separator + bucket + separator + object + "?uploadId=" + uploadID, - } - completeMultipartUploadBytes, err := xml.Marshal(complete) - if err != nil { - return nil, err - } - completeMultipartUploadBuffer := bytes.NewBuffer(completeMultipartUploadBytes) - rmetadata := requestMetadata{ - body: ioutil.NopCloser(completeMultipartUploadBuffer), - contentLength: int64(completeMultipartUploadBuffer.Len()), - sha256PayloadBytes: sum256(completeMultipartUploadBuffer.Bytes()), - } - r, err := newRequest(op, a.config, rmetadata) - if err != nil { - return nil, err - } - return r, nil -} - -// completeMultipartUpload completes a multipart upload by assembling previously uploaded parts. -func (a s3API) completeMultipartUpload(bucket, object, uploadID string, c completeMultipartUpload) (completeMultipartUploadResult, error) { - req, err := a.completeMultipartUploadRequest(bucket, object, uploadID, c) - if err != nil { - return completeMultipartUploadResult{}, err - } - resp, err := req.Do() - defer closeResp(resp) - if err != nil { - return completeMultipartUploadResult{}, err - } - if resp != nil { - if resp.StatusCode != http.StatusOK { - return completeMultipartUploadResult{}, BodyToErrorResponse(resp.Body) - } - } - completeMultipartUploadResult := completeMultipartUploadResult{} - err = xmlDecoder(resp.Body, &completeMultipartUploadResult) - if err != nil { - return completeMultipartUploadResult, err - } - return completeMultipartUploadResult, nil -} - -// abortMultipartUploadRequest wrapper creates a new AbortMultipartUpload request. -func (a s3API) abortMultipartUploadRequest(bucket, object, uploadID string) (*Request, error) { - op := &operation{ - HTTPServer: a.config.Endpoint, - HTTPMethod: "DELETE", - HTTPPath: separator + bucket + separator + object + "?uploadId=" + uploadID, - } - return newRequest(op, a.config, requestMetadata{}) -} - -// abortMultipartUpload aborts a multipart upload for the given uploadID, all parts are deleted. -func (a s3API) abortMultipartUpload(bucket, object, uploadID string) error { - req, err := a.abortMultipartUploadRequest(bucket, object, uploadID) - if err != nil { - return err - } - resp, err := req.Do() - defer closeResp(resp) - if err != nil { - return err - } - if resp != nil { - if resp.StatusCode != http.StatusNoContent { - // Abort has no response body, handle it. - var errorResponse ErrorResponse - switch resp.StatusCode { - case http.StatusNotFound: - errorResponse = ErrorResponse{ - Code: "NoSuchUpload", - Message: "The specified multipart upload does not exist.", - Resource: separator + bucket + separator + object, - RequestID: resp.Header.Get("x-amz-request-id"), - HostID: resp.Header.Get("x-amz-id-2"), - AmzBucketRegion: resp.Header.Get("x-amz-bucket-region"), - } - case http.StatusForbidden: - errorResponse = ErrorResponse{ - Code: "AccessDenied", - Message: "Access Denied.", - Resource: separator + bucket + separator + object, - RequestID: resp.Header.Get("x-amz-request-id"), - HostID: resp.Header.Get("x-amz-id-2"), - AmzBucketRegion: resp.Header.Get("x-amz-bucket-region"), - } - default: - errorResponse = ErrorResponse{ - Code: resp.Status, - Message: "Unknown error, please report this at https://github.com/minio/minio-go-legacy/issues.", - Resource: separator + bucket + separator + object, - RequestID: resp.Header.Get("x-amz-request-id"), - HostID: resp.Header.Get("x-amz-id-2"), - AmzBucketRegion: resp.Header.Get("x-amz-bucket-region"), - } - } - return errorResponse - } - } - return nil -} - -// listObjectPartsRequest wrapper creates a new ListObjectParts request. -func (a s3API) listObjectPartsRequest(bucket, object, uploadID string, partNumberMarker, maxParts int) (*Request, error) { - // resourceQuery - get resources properly escaped and lined up before using them in http request. - resourceQuery := func() string { - var partNumberMarkerStr string - switch { - case partNumberMarker != 0: - partNumberMarkerStr = fmt.Sprintf("&part-number-marker=%d", partNumberMarker) - } - return fmt.Sprintf("?uploadId=%s&max-parts=%d", uploadID, maxParts) + partNumberMarkerStr - } - op := &operation{ - HTTPServer: a.config.Endpoint, - HTTPMethod: "GET", - HTTPPath: separator + bucket + separator + object + resourceQuery(), - } - return newRequest(op, a.config, requestMetadata{}) -} - -// listObjectParts (List Parts) -// - lists some or all (up to 1000) parts that have been uploaded for a specific multipart upload -// -// You can use the request parameters as selection criteria to return a subset of the uploads in a bucket. -// request paramters :- -// --------- -// ?part-number-marker - Specifies the part after which listing should begin. -func (a s3API) listObjectParts(bucket, object, uploadID string, partNumberMarker, maxParts int) (listObjectPartsResult, error) { - req, err := a.listObjectPartsRequest(bucket, object, uploadID, partNumberMarker, maxParts) - if err != nil { - return listObjectPartsResult{}, err - } - resp, err := req.Do() - defer closeResp(resp) - if err != nil { - return listObjectPartsResult{}, err - } - if resp != nil { - if resp.StatusCode != http.StatusOK { - return listObjectPartsResult{}, BodyToErrorResponse(resp.Body) - } - } - listObjectPartsResult := listObjectPartsResult{} - err = xmlDecoder(resp.Body, &listObjectPartsResult) - if err != nil { - return listObjectPartsResult, err - } - return listObjectPartsResult, nil -} - -// uploadPartRequest wrapper creates a new UploadPart request. -func (a s3API) uploadPartRequest(bucket, object, uploadID string, uploadingPart partMetadata) (*Request, error) { - op := &operation{ - HTTPServer: a.config.Endpoint, - HTTPMethod: "PUT", - HTTPPath: separator + bucket + separator + object + - "?partNumber=" + strconv.Itoa(uploadingPart.Number) + "&uploadId=" + uploadID, - } - rmetadata := requestMetadata{ - body: uploadingPart.ReadCloser, - contentLength: uploadingPart.Size, - sha256PayloadBytes: uploadingPart.Sha256Sum, - md5SumPayloadBytes: uploadingPart.MD5Sum, - } - r, err := newRequest(op, a.config, rmetadata) - if err != nil { - return nil, err - } - return r, nil -} - -// uploadPart uploads a part in a multipart upload. -func (a s3API) uploadPart(bucket, object, uploadID string, uploadingPart partMetadata) (completePart, error) { - req, err := a.uploadPartRequest(bucket, object, uploadID, uploadingPart) - if err != nil { - return completePart{}, err - } - - // initiate the request. - resp, err := req.Do() - defer closeResp(resp) - if err != nil { - return completePart{}, err - } - if resp != nil { - if resp.StatusCode != http.StatusOK { - return completePart{}, BodyToErrorResponse(resp.Body) - } - } - cPart := completePart{} - cPart.PartNumber = uploadingPart.Number - cPart.ETag = resp.Header.Get("ETag") - return cPart, nil -} diff --git a/vendor/github.com/minio/minio-go/signature-type.go b/vendor/github.com/minio/minio-go/signature-type.go new file mode 100644 index 00000000..cae74cd0 --- /dev/null +++ b/vendor/github.com/minio/minio-go/signature-type.go @@ -0,0 +1,37 @@ +/* + * Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2015 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 + +// SignatureType is type of Authorization requested for a given HTTP request. +type SignatureType int + +// Different types of supported signatures - default is Latest i.e SignatureV4. +const ( + Latest SignatureType = iota + SignatureV4 + SignatureV2 +) + +// isV2 - is signature SignatureV2? +func (s SignatureType) isV2() bool { + return s == SignatureV2 +} + +// isV4 - is signature SignatureV4? +func (s SignatureType) isV4() bool { + return s == SignatureV4 || s == Latest +} diff --git a/vendor/github.com/minio/minio-go/tempfile.go b/vendor/github.com/minio/minio-go/tempfile.go new file mode 100644 index 00000000..65c7b0da --- /dev/null +++ b/vendor/github.com/minio/minio-go/tempfile.go @@ -0,0 +1,60 @@ +/* + * Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2015 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 + +import ( + "io/ioutil" + "os" + "sync" +) + +// tempFile - temporary file container. +type tempFile struct { + *os.File + mutex *sync.Mutex +} + +// newTempFile returns a new temporary file, once closed it automatically deletes itself. +func newTempFile(prefix string) (*tempFile, error) { + // use platform specific temp directory. + file, err := ioutil.TempFile(os.TempDir(), prefix) + if err != nil { + return nil, err + } + return &tempFile{ + File: file, + mutex: &sync.Mutex{}, + }, nil +} + +// Close - closer wrapper to close and remove temporary file. +func (t *tempFile) Close() error { + t.mutex.Lock() + defer t.mutex.Unlock() + if t.File != nil { + // Close the file. + if err := t.File.Close(); err != nil { + return err + } + // Remove file. + if err := os.Remove(t.File.Name()); err != nil { + return err + } + t.File = nil + } + return nil +} diff --git a/vendor/github.com/minio/minio-go/utils.go b/vendor/github.com/minio/minio-go/utils.go new file mode 100644 index 00000000..63966c30 --- /dev/null +++ b/vendor/github.com/minio/minio-go/utils.go @@ -0,0 +1,305 @@ +/* + * Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2015 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 + +import ( + "crypto/hmac" + "crypto/sha256" + "encoding/hex" + "encoding/xml" + "io" + "io/ioutil" + "net" + "net/http" + "net/url" + "regexp" + "strings" + "time" + "unicode/utf8" +) + +// xmlDecoder provide decoded value in xml. +func xmlDecoder(body io.Reader, v interface{}) error { + d := xml.NewDecoder(body) + return d.Decode(v) +} + +// sum256 calculate sha256 sum for an input byte array. +func sum256(data []byte) []byte { + hash := sha256.New() + hash.Write(data) + return hash.Sum(nil) +} + +// sumHMAC calculate hmac between two input byte array. +func sumHMAC(key []byte, data []byte) []byte { + hash := hmac.New(sha256.New, key) + hash.Write(data) + return hash.Sum(nil) +} + +// getEndpointURL - construct a new endpoint. +func getEndpointURL(endpoint string, inSecure bool) (*url.URL, error) { + if strings.Contains(endpoint, ":") { + host, _, err := net.SplitHostPort(endpoint) + if err != nil { + return nil, err + } + if !isValidIP(host) && !isValidDomain(host) { + msg := "Endpoint: " + endpoint + " does not follow ip address or domain name standards." + return nil, ErrInvalidArgument(msg) + } + } else { + if !isValidIP(endpoint) && !isValidDomain(endpoint) { + msg := "Endpoint: " + endpoint + " does not follow ip address or domain name standards." + return nil, ErrInvalidArgument(msg) + } + } + // if inSecure is true, use 'http' scheme. + scheme := "https" + if inSecure { + scheme = "http" + } + + // Construct a secured endpoint URL. + endpointURLStr := scheme + "://" + endpoint + endpointURL, err := url.Parse(endpointURLStr) + if err != nil { + return nil, err + } + + // Validate incoming endpoint URL. + if err := isValidEndpointURL(endpointURL); err != nil { + return nil, err + } + return endpointURL, nil +} + +// isValidDomain validates if input string is a valid domain name. +func isValidDomain(host string) bool { + // See RFC 1035, RFC 3696. + host = strings.TrimSpace(host) + if len(host) == 0 || len(host) > 255 { + return false + } + // host cannot start or end with "-" + if host[len(host)-1:] == "-" || host[:1] == "-" { + return false + } + // host cannot start or end with "_" + if host[len(host)-1:] == "_" || host[:1] == "_" { + return false + } + // host cannot start or end with a "." + if host[len(host)-1:] == "." || host[:1] == "." { + return false + } + // All non alphanumeric characters are invalid. + if strings.ContainsAny(host, "`~!@#$%^&*()+={}[]|\\\"';:> 604800 { + return ErrInvalidArgument("Expires cannot be greater than 7 days.") + } + return nil +} + +// We support '.' with bucket names but we fallback to using path +// style requests instead for such buckets. +var validBucketName = regexp.MustCompile(`^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$`) + +// isValidBucketName - verify bucket name in accordance with +// - http://docs.aws.amazon.com/AmazonS3/latest/dev/UsingBucket.html +func isValidBucketName(bucketName string) error { + if strings.TrimSpace(bucketName) == "" { + return ErrInvalidBucketName("Bucket name cannot be empty.") + } + if len(bucketName) < 3 { + return ErrInvalidBucketName("Bucket name cannot be smaller than 3 characters.") + } + if len(bucketName) > 63 { + return ErrInvalidBucketName("Bucket name cannot be greater than 63 characters.") + } + if bucketName[0] == '.' || bucketName[len(bucketName)-1] == '.' { + return ErrInvalidBucketName("Bucket name cannot start or end with a '.' dot.") + } + if match, _ := regexp.MatchString("\\.\\.", bucketName); match == true { + return ErrInvalidBucketName("Bucket name cannot have successive periods.") + } + if !validBucketName.MatchString(bucketName) { + return ErrInvalidBucketName("Bucket name contains invalid characters.") + } + return nil +} + +// isValidObjectName - verify object name in accordance with +// - http://docs.aws.amazon.com/AmazonS3/latest/dev/UsingMetadata.html +func isValidObjectName(objectName string) error { + if strings.TrimSpace(objectName) == "" { + return ErrInvalidObjectName("Object name cannot be empty.") + } + if len(objectName) > 1024 { + return ErrInvalidObjectName("Object name cannot be greater than 1024 characters.") + } + if !utf8.ValidString(objectName) { + return ErrInvalidBucketName("Object name with non UTF-8 strings are not supported.") + } + return nil +} + +// isValidObjectPrefix - verify if object prefix is valid. +func isValidObjectPrefix(objectPrefix string) error { + if len(objectPrefix) > 1024 { + return ErrInvalidObjectPrefix("Object prefix cannot be greater than 1024 characters.") + } + if !utf8.ValidString(objectPrefix) { + return ErrInvalidObjectPrefix("Object prefix with non UTF-8 strings are not supported.") + } + return nil +} + +// urlEncodePath encode the strings from UTF-8 byte representations to HTML hex escape sequences +// +// This is necessary since regular url.Parse() and url.Encode() functions do not support UTF-8 +// non english characters cannot be parsed due to the nature in which url.Encode() is written +// +// This function on the other hand is a direct replacement for url.Encode() technique to support +// pretty much every UTF-8 character. +func urlEncodePath(pathName string) string { + // if object matches reserved string, no need to encode them + reservedNames := regexp.MustCompile("^[a-zA-Z0-9-_.~/]+$") + if reservedNames.MatchString(pathName) { + return pathName + } + var encodedPathname string + for _, s := range pathName { + if 'A' <= s && s <= 'Z' || 'a' <= s && s <= 'z' || '0' <= s && s <= '9' { // §2.3 Unreserved characters (mark) + encodedPathname = encodedPathname + string(s) + continue + } + switch s { + case '-', '_', '.', '~', '/': // §2.3 Unreserved characters (mark) + encodedPathname = encodedPathname + string(s) + continue + default: + len := utf8.RuneLen(s) + if len < 0 { + // if utf8 cannot convert return the same string as is + return pathName + } + u := make([]byte, len) + utf8.EncodeRune(u, s) + for _, r := range u { + hex := hex.EncodeToString([]byte{r}) + encodedPathname = encodedPathname + "%" + strings.ToUpper(hex) + } + } + } + return encodedPathname +} diff --git a/vendor/github.com/minio/pb/LICENSE b/vendor/github.com/minio/pb/LICENSE index 13ef3fe5..51197033 100644 --- a/vendor/github.com/minio/pb/LICENSE +++ b/vendor/github.com/minio/pb/LICENSE @@ -1,4 +1,4 @@ -Copyright (c) 2012, Sergey Cherepanov +Copyright (c) 2012-2015, Sergey Cherepanov All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: diff --git a/vendor/github.com/minio/pb/README.md b/vendor/github.com/minio/pb/README.md index af5c4bd5..0493dade 100644 --- a/vendor/github.com/minio/pb/README.md +++ b/vendor/github.com/minio/pb/README.md @@ -1,14 +1,16 @@ -## Terminal progress bar for Go +# Terminal progress bar for Go -Simple progress bar for console programms. +Simple progress bar for console programs. -### Installation +## Installation + ``` go get github.com/cheggaaa/pb ``` -### Usage +## Usage + ```Go package main @@ -26,15 +28,18 @@ func main() { } bar.FinishPrint("The End!") } -``` + +``` + Result will be like this: + ``` > go run test.go 37158 / 100000 [================>_______________________________] 37.16% 1m11s ``` +## Customization -More functions? ```Go // create bar bar := pb.New(count) @@ -48,13 +53,13 @@ bar.ShowPercent = true // show bar (by default already true) bar.ShowBar = true -// no need counters +// no counters bar.ShowCounters = false // show "time left" bar.ShowTimeLeft = true -// show average speed +// show average speed bar.ShowSpeed = true // sets the width of the progress bar @@ -63,15 +68,35 @@ bar.SetWidth(80) // sets the width of the progress bar, but if terminal size smaller will be ignored bar.SetMaxWidth(80) -// convert output to readable format (like KB, MB) +// convert output to readable format (like KB, MB) bar.SetUnits(pb.U_BYTES) // and start bar.Start() ``` -Want handle progress of io operations? -```Go +## Progress bar for IO Operations + +```go +// create and start bar +bar := pb.New(myDataLen).SetUnits(pb.U_BYTES) +bar.Start() + +// my io.Reader +r := myReader + +// my io.Writer +w := myWriter + +// create proxy reader +reader := bar.NewProxyReader(r) + +// and copy from pb reader +io.Copy(w, reader) + +``` + +```go // create and start bar bar := pb.New(myDataLen).SetUnits(pb.U_BYTES) bar.Start() @@ -87,12 +112,62 @@ writer := io.MultiWriter(w, bar) // and copy io.Copy(writer, r) - -// show example/copy/copy.go for advanced example - ``` -Not like the looks? -```Go +## Custom Progress Bar Look-and-feel + +```go bar.Format("<.- >") ``` + +## Multiple Progress Bars (experimental and unstable) + +#####Multiple bars do not works at Windows!!! + +Do not print to terminal while pool is active. + +```go +package main + +import ( + "math/rand" + "github.com/cheggaaa/pb" + "sync" + "time" +) + +// create bars +first := pb.New(200).Prefix("First ") +second := pb.New(200).Prefix("Second ") +third := pb.New(200).Prefix("Third ") +// start pool +pool, err := pb.StartPool(first, second, third) +if err != nil { + panic(err) +} +// update bars +wg := new(sync.WaitGroup) +for _, bar := range []*pb.ProgressBar{first, second, third} { + wg.Add(1) + go func(cb *pb.ProgressBar) { + for n := 0; n < 200; n++ { + cb.Increment() + time.Sleep(time.Millisecond * time.Duration(rand.Intn(100))) + } + cb.Finish() + wg.Done() + }(bar) +} +wg.Wait() +// close pool +pool.Stop() +``` + +The result will be as follows: + +``` +$ go run example/multiple.go +First 141 / 1000 [===============>---------------------------------------] 14.10 % 44s +Second 139 / 1000 [==============>---------------------------------------] 13.90 % 44s +Third 152 / 1000 [================>--------------------------------------] 15.20 % 40s +``` diff --git a/vendor/github.com/minio/pb/example_copy_test.go b/vendor/github.com/minio/pb/example_copy_test.go new file mode 100644 index 00000000..85662d03 --- /dev/null +++ b/vendor/github.com/minio/pb/example_copy_test.go @@ -0,0 +1,82 @@ +package pb_test + +import ( + "fmt" + "io" + "net/http" + "os" + "strconv" + "strings" + "time" + + "github.com/cheggaaa/pb" +) + +func Example_copy() { + // check args + if len(os.Args) < 3 { + printUsage() + return + } + sourceName, destName := os.Args[1], os.Args[2] + + // check source + var source io.Reader + var sourceSize int64 + if strings.HasPrefix(sourceName, "http://") { + // open as url + resp, err := http.Get(sourceName) + if err != nil { + fmt.Printf("Can't get %s: %v\n", sourceName, err) + return + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + fmt.Printf("Server return non-200 status: %v\n", resp.Status) + return + } + i, _ := strconv.Atoi(resp.Header.Get("Content-Length")) + sourceSize = int64(i) + source = resp.Body + } else { + // open as file + s, err := os.Open(sourceName) + if err != nil { + fmt.Printf("Can't open %s: %v\n", sourceName, err) + return + } + defer s.Close() + // get source size + sourceStat, err := s.Stat() + if err != nil { + fmt.Printf("Can't stat %s: %v\n", sourceName, err) + return + } + sourceSize = sourceStat.Size() + source = s + } + + // create dest + dest, err := os.Create(destName) + if err != nil { + fmt.Printf("Can't create %s: %v\n", destName, err) + return + } + defer dest.Close() + + // create bar + bar := pb.New(int(sourceSize)).SetUnits(pb.U_BYTES).SetRefreshRate(time.Millisecond * 10) + bar.ShowSpeed = true + bar.Start() + + // create proxy reader + reader := bar.NewProxyReader(source) + + // and copy from reader + io.Copy(dest, reader) + bar.Finish() +} + +func printUsage() { + fmt.Println("copy [source file or url] [dest file]") +} diff --git a/vendor/github.com/minio/pb/example_multiple_test.go b/vendor/github.com/minio/pb/example_multiple_test.go new file mode 100644 index 00000000..d3396f4a --- /dev/null +++ b/vendor/github.com/minio/pb/example_multiple_test.go @@ -0,0 +1,37 @@ +package pb_test + +import ( + "math/rand" + "sync" + "time" + + "github.com/cheggaaa/pb" +) + +func Example_multiple() { + // create bars + first := pb.New(200).Prefix("First ") + second := pb.New(200).Prefix("Second ") + third := pb.New(200).Prefix("Third ") + // start pool + pool, err := pb.StartPool(first, second, third) + if err != nil { + panic(err) + } + // update bars + wg := new(sync.WaitGroup) + for _, bar := range []*pb.ProgressBar{first, second, third} { + wg.Add(1) + go func(cb *pb.ProgressBar) { + for n := 0; n < 200; n++ { + cb.Increment() + time.Sleep(time.Millisecond * time.Duration(rand.Intn(100))) + } + cb.Finish() + wg.Done() + }(bar) + } + wg.Wait() + // close pool + pool.Stop() +} diff --git a/vendor/github.com/minio/pb/example_test.go b/vendor/github.com/minio/pb/example_test.go new file mode 100644 index 00000000..fe00f688 --- /dev/null +++ b/vendor/github.com/minio/pb/example_test.go @@ -0,0 +1,30 @@ +package pb_test + +import ( + "time" + + "github.com/cheggaaa/pb" +) + +func Example() { + count := 5000 + bar := pb.New(count) + + // show percents (by default already true) + bar.ShowPercent = true + + // show bar (by default already true) + bar.ShowBar = true + + bar.ShowCounters = true + + bar.ShowTimeLeft = true + + // and start + bar.Start() + for i := 0; i < count; i++ { + bar.Increment() + time.Sleep(time.Millisecond) + } + bar.FinishPrint("The End!") +} diff --git a/vendor/github.com/minio/pb/pb.go b/vendor/github.com/minio/pb/pb.go index c668ef9d..92523264 100644 --- a/vendor/github.com/minio/pb/pb.go +++ b/vendor/github.com/minio/pb/pb.go @@ -1,3 +1,4 @@ +// Simple console progress bars package pb import ( @@ -42,7 +43,7 @@ func New64(total int64) *ProgressBar { ShowFinalTime: true, Units: U_NO, ManualUpdate: false, - isFinish: make(chan struct{}), + finish: make(chan struct{}), currentValue: -1, } return pb.Format(FORMAT) @@ -78,7 +79,8 @@ type ProgressBar struct { ManualUpdate bool finishOnce sync.Once //Guards isFinish - isFinish chan struct{} + finish chan struct{} + isFinish bool startTime time.Time startValue int64 @@ -86,11 +88,15 @@ type ProgressBar struct { prefix, postfix string + lastPrint string + BarStart string BarEnd string Empty string Current string CurrentN string + + AlwaysUpdate bool } // Start print @@ -146,8 +152,14 @@ func (pb *ProgressBar) Postfix(postfix string) *ProgressBar { // Set custom format for bar // Example: bar.Format("[=>_]") +// Example: bar.Format("[\x00=\x00>\x00-\x00]") // \x00 is the delimiter func (pb *ProgressBar) Format(format string) *ProgressBar { - formatEntries := strings.Split(format, "") + var formatEntries []string + if len(format) == 5 { + formatEntries = strings.Split(format, "") + } else { + formatEntries = strings.Split(format, "\x00") + } if len(formatEntries) == 5 { pb.BarStart = formatEntries[0] pb.BarEnd = formatEntries[4] @@ -190,11 +202,12 @@ func (pb *ProgressBar) SetWidth(width int) *ProgressBar { func (pb *ProgressBar) Finish() { //Protect multiple calls pb.finishOnce.Do(func() { - close(pb.isFinish) + close(pb.finish) pb.write(atomic.LoadInt64(&pb.current)) if !pb.NotPrint { fmt.Println() } + pb.isFinish = true }) } @@ -247,7 +260,7 @@ func (pb *ProgressBar) write(current int64) { fromStart := time.Now().Sub(pb.startTime) currentFromStart := current - pb.startValue select { - case <-pb.isFinish: + case <-pb.finish: if pb.ShowFinalTime { left := (fromStart / time.Second) * time.Second timeLeftBox = left.String() @@ -268,7 +281,7 @@ func (pb *ProgressBar) write(current int64) { speedBox = Format(int64(speed), pb.Units) + "/s " } - barWidth := utf8.RuneCountInString(countersBox + pb.BarStart + pb.BarEnd + percentBox + timeLeftBox + speedBox + pb.prefix + pb.postfix) + barWidth := escapeAwareRuneCountInString(countersBox + pb.BarStart + pb.BarEnd + percentBox + timeLeftBox + speedBox + pb.prefix + pb.postfix) // bar if pb.ShowBar { size := width - barWidth @@ -308,11 +321,12 @@ func (pb *ProgressBar) write(current int64) { // check len out = pb.prefix + countersBox + barBox + percentBox + speedBox + timeLeftBox + pb.postfix - if utf8.RuneCountInString(out) < width { + if escapeAwareRuneCountInString(out) < width { end = strings.Repeat(" ", width-utf8.RuneCountInString(out)) } // and print! + pb.lastPrint = out + end switch { case pb.Output != nil: fmt.Fprint(pb.Output, "\r"+out+end) @@ -340,18 +354,22 @@ func (pb *ProgressBar) GetWidth() int { // Write the current state of the progressbar func (pb *ProgressBar) Update() { c := atomic.LoadInt64(&pb.current) - if c != pb.currentValue { + if pb.AlwaysUpdate || c != pb.currentValue { pb.write(c) pb.currentValue = c } } +func (pb *ProgressBar) GOString() string { + return pb.lastPrint +} + // Internal loop for writing progressbar func (pb *ProgressBar) writer() { pb.Update() for { select { - case <-pb.isFinish: + case <-pb.finish: return case <-time.After(pb.RefreshRate): pb.Update() diff --git a/vendor/github.com/minio/pb/pb_nix.go b/vendor/github.com/minio/pb/pb_nix.go index 5db4e523..d6584368 100644 --- a/vendor/github.com/minio/pb/pb_nix.go +++ b/vendor/github.com/minio/pb/pb_nix.go @@ -1,4 +1,4 @@ -// +build linux darwin freebsd netbsd openbsd +// +build linux darwin freebsd netbsd openbsd dragonfly package pb diff --git a/vendor/github.com/minio/pb/pb_test.go b/vendor/github.com/minio/pb/pb_test.go index dfe394fd..2505068f 100644 --- a/vendor/github.com/minio/pb/pb_test.go +++ b/vendor/github.com/minio/pb/pb_test.go @@ -1,7 +1,11 @@ package pb import ( + "strings" "testing" + + "github.com/fatih/color" + "github.com/mattn/go-colorable" ) func Test_IncrementAddsOne(t *testing.T) { @@ -35,3 +39,20 @@ func Test_MultipleFinish(t *testing.T) { bar.Finish() bar.Finish() } + +func Test_Format(t *testing.T) { + bar := New(5000).Format(strings.Join([]string{ + color.GreenString("["), + color.New(color.BgGreen).SprintFunc()("o"), + color.New(color.BgHiGreen).SprintFunc()("o"), + color.New(color.BgRed).SprintFunc()("o"), + color.GreenString("]"), + }, "\x00")) + w := colorable.NewColorableStdout() + bar.Callback = func(out string) { + w.Write([]byte(out)) + } + bar.Add(2000) + bar.Finish() + bar.Finish() +} diff --git a/vendor/github.com/minio/pb/pb_win.go b/vendor/github.com/minio/pb/pb_win.go index eb36190c..31715cc7 100644 --- a/vendor/github.com/minio/pb/pb_win.go +++ b/vendor/github.com/minio/pb/pb_win.go @@ -4,11 +4,10 @@ package pb import ( "github.com/olekukonko/ts" + "os" ) -func bold(str string) string { - return str -} +var tty = os.Stdin func terminalWidth() (int, error) { size, err := ts.GetSize() diff --git a/vendor/github.com/minio/pb/pb_x.go b/vendor/github.com/minio/pb/pb_x.go index dd5f906e..f2f3ed96 100644 --- a/vendor/github.com/minio/pb/pb_x.go +++ b/vendor/github.com/minio/pb/pb_x.go @@ -1,10 +1,14 @@ -// +build linux darwin freebsd netbsd openbsd solaris +// +build linux darwin freebsd netbsd openbsd solaris dragonfly package pb import ( + "errors" + "fmt" "os" + "os/signal" "runtime" + "sync" "syscall" "unsafe" ) @@ -16,6 +20,11 @@ const ( var tty *os.File +var ErrPoolWasStarted = errors.New("Bar pool was started") + +var echoLocked bool +var echoLockMutex sync.Mutex + func init() { var err error tty, err = os.Open("/dev/tty") @@ -24,10 +33,6 @@ func init() { } } -func bold(str string) string { - return "\033[1m" + str + "\033[0m" -} - func terminalWidth() (int, error) { w := new(window) tio := syscall.TIOCGWINSZ @@ -44,3 +49,60 @@ func terminalWidth() (int, error) { } return int(w.Col), nil } + +var oldState syscall.Termios + +func lockEcho() (quit chan int, err error) { + echoLockMutex.Lock() + defer echoLockMutex.Unlock() + if echoLocked { + err = ErrPoolWasStarted + return + } + echoLocked = true + + fd := tty.Fd() + if _, _, e := syscall.Syscall6(syscall.SYS_IOCTL, fd, ioctlReadTermios, uintptr(unsafe.Pointer(&oldState)), 0, 0, 0); e != 0 { + err = fmt.Errorf("Can't get terminal settings: %v", e) + return + } + + newState := oldState + newState.Lflag &^= syscall.ECHO + newState.Lflag |= syscall.ICANON | syscall.ISIG + newState.Iflag |= syscall.ICRNL + if _, _, e := syscall.Syscall6(syscall.SYS_IOCTL, fd, ioctlWriteTermios, uintptr(unsafe.Pointer(&newState)), 0, 0, 0); e != 0 { + err = fmt.Errorf("Can't set terminal settings: %v", e) + return + } + quit = make(chan int, 1) + go catchTerminate(quit) + return +} + +func unlockEcho() (err error) { + echoLockMutex.Lock() + defer echoLockMutex.Unlock() + if !echoLocked { + return + } + echoLocked = false + fd := tty.Fd() + if _, _, e := syscall.Syscall6(syscall.SYS_IOCTL, fd, ioctlWriteTermios, uintptr(unsafe.Pointer(&oldState)), 0, 0, 0); e != 0 { + err = fmt.Errorf("Can't set terminal settings") + } + return +} + +// listen exit signals and restore terminal state +func catchTerminate(quit chan int) { + sig := make(chan os.Signal, 1) + signal.Notify(sig, os.Interrupt, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGKILL) + defer signal.Stop(sig) + select { + case <-quit: + unlockEcho() + case <-sig: + unlockEcho() + } +} diff --git a/vendor/github.com/minio/pb/pool.go b/vendor/github.com/minio/pb/pool.go new file mode 100644 index 00000000..45effed9 --- /dev/null +++ b/vendor/github.com/minio/pb/pool.go @@ -0,0 +1,93 @@ +// +build linux darwin freebsd netbsd openbsd solaris dragonfly + +package pb + +import ( + "fmt" + "sync" + "time" +) + +// Create and start new pool with given bars +// You need call pool.Stop() after work +func StartPool(pbs ...*ProgressBar) (pool *Pool, err error) { + pool = new(Pool) + if err = pool.start(); err != nil { + return + } + pool.add(pbs...) + return +} + +type Pool struct { + RefreshRate time.Duration + bars []*ProgressBar + quit chan int + finishOnce sync.Once +} + +func (p *Pool) add(pbs ...*ProgressBar) { + for _, bar := range pbs { + bar.ManualUpdate = true + bar.NotPrint = true + bar.Start() + p.bars = append(p.bars, bar) + } +} + +func (p *Pool) start() (err error) { + p.RefreshRate = DefaultRefreshRate + quit, err := lockEcho() + if err != nil { + return + } + p.quit = make(chan int) + go p.writer(quit) + return +} + +func (p *Pool) writer(finish chan int) { + var first = true + for { + select { + case <-time.After(p.RefreshRate): + if p.print(first) { + p.print(false) + finish <- 1 + return + } + first = false + case <-p.quit: + finish <- 1 + return + } + } +} + +func (p *Pool) print(first bool) bool { + var out string + if !first { + out = fmt.Sprintf("\033[%dA", len(p.bars)) + } + isFinished := true + for _, bar := range p.bars { + if !bar.isFinish { + isFinished = false + } + bar.Update() + out += fmt.Sprintf("\r%s\n", bar.GOString()) + } + fmt.Print(out) + return isFinished +} + +// Restore terminal state and close pool +func (p *Pool) Stop() error { + // Wait until one final refresh has passed. + time.Sleep(p.RefreshRate) + + p.finishOnce.Do(func() { + close(p.quit) + }) + return unlockEcho() +} diff --git a/vendor/github.com/minio/pb/runecount.go b/vendor/github.com/minio/pb/runecount.go new file mode 100644 index 00000000..c5a4925a --- /dev/null +++ b/vendor/github.com/minio/pb/runecount.go @@ -0,0 +1,17 @@ +package pb + +import ( + "regexp" + "unicode/utf8" +) + +// Finds the control character sequences (like colors) +var ctrlFinder = regexp.MustCompile("\x1b\x5b[0-9]+\x6d") + +func escapeAwareRuneCountInString(s string) int { + n := utf8.RuneCountInString(s) + for _, sm := range ctrlFinder.FindAllString(s, -1) { + n -= len(sm) + } + return n +} diff --git a/vendor/github.com/minio/pb/runecount_test.go b/vendor/github.com/minio/pb/runecount_test.go new file mode 100644 index 00000000..c37b2a87 --- /dev/null +++ b/vendor/github.com/minio/pb/runecount_test.go @@ -0,0 +1,16 @@ +package pb + +import "testing" + +func Test_RuneCount(t *testing.T) { + s := string([]byte{ + 27, 91, 51, 49, 109, // {Red} + 72, 101, 108, 108, 111, // Hello + 44, 32, // , + 112, 108, 97, 121, 103, 114, 111, 117, 110, 100, // Playground + 27, 91, 48, 109, // {Reset} + }) + if e, l := 17, escapeAwareRuneCountInString(s); l != e { + t.Errorf("Invalid length %d, expected %d", l, e) + } +} diff --git a/vendor/github.com/minio/pb/termios_bsd.go b/vendor/github.com/minio/pb/termios_bsd.go new file mode 100644 index 00000000..a0c5f05d --- /dev/null +++ b/vendor/github.com/minio/pb/termios_bsd.go @@ -0,0 +1,8 @@ +// +build darwin freebsd netbsd openbsd solaris dragonfly + +package pb + +import "syscall" + +const ioctlReadTermios = syscall.TIOCGETA +const ioctlWriteTermios = syscall.TIOCSETA diff --git a/vendor/github.com/minio/pb/termios_linux.go b/vendor/github.com/minio/pb/termios_linux.go new file mode 100644 index 00000000..53909f0f --- /dev/null +++ b/vendor/github.com/minio/pb/termios_linux.go @@ -0,0 +1,6 @@ +// +build linux + +package pb + +const ioctlReadTermios = 0x5401 // syscall.TCGETS +const ioctlWriteTermios = 0x5402 // syscall.TCSETS diff --git a/vendor/vendor.json b/vendor/vendor.json index e2fc297d..99cd2328 100644 --- a/vendor/vendor.json +++ b/vendor/vendor.json @@ -29,8 +29,8 @@ }, { "path": "github.com/minio/minio-go", - "revision": "5c338d70100554bb199702ffaad9b947ef08c40e", - "revisionTime": "2015-12-02T08:25:01-08:00" + "revision": "412df729f2c19ce60895770403f266cf5eac56f7", + "revisionTime": "2016-01-22T16:23:42-08:00" }, { "path": "github.com/minio/minio-xl/pkg/atomic", @@ -59,8 +59,8 @@ }, { "path": "github.com/minio/pb", - "revision": "6a97c3b0da073f974e0b8d1ac1bc42c0a7adca46", - "revisionTime": "2015-08-12T18:13:54-07:00" + "revision": "f078cde702e9e2548c47ec71b889381954dd4063", + "revisionTime": "2016-01-12T19:37:35-08:00" }, { "path": "github.com/olekukonko/ts",