Compare commits

...
Author SHA1 Message Date
Harshavardhana 1dea194699 minio-go: Vendorize with new changes. 2016-02-05 23:10:09 -08:00
Krishna Srinivas 4569e519c5 Merge pull request #1598 from harshavardhana/query
rm: List wouldn't progress for files with special characters.
2016-02-02 15:17:04 +05:30
Harshavardhana 0236dcf780 rm: List wouldn't progress for files with special characters.
This patch addresses this problem - fixes #1591
2016-02-02 01:28:04 -08:00
Krishna Srinivas 5e5ad3367d Merge pull request #1597 from harshavardhana/progress-bar
progressBar: Finish progress bar if total is greater than 0
2016-02-02 14:54:59 +05:30
Harshavardhana 744b4728d1 progressBar: Finish progress bar if total is greater than 0
In case of 'mc mirror' => mc prints an erroneous progress bar
with 0bytes.

```
mc mirror /usr/local/Cellar/go/1.5.3/libexec play/test123/libexec
0 B / ?  ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░▓  0.00 % 0
```

This patch fixes #1592
2016-02-01 13:36:23 -08:00
Anand Babu (AB) Periasamy f811b029b1 Merge pull request #1595 from harshavardhana/path-url
url: Error out if the aliased URL has host entry.
2016-02-01 11:44:10 +01:00
Harshavardhana 8b77f918b3 url: Error out if the aliased URL has host entry.
```
mc ls http://localhost:9000/
```

ends up listing `mc ls /`, This is confusing and should be
treated as an error, allow only aliased operations.
2016-02-01 02:41:04 -08:00
Anand Babu (AB) Periasamy c5453d1528 Merge pull request #1590 from harshavardhana/url
urlAlias: Handle forward slashes on windows.
2016-01-27 23:21:48 -08:00
Harshavardhana fc668edadf urlAlias: Handle forward slashes on windows.
On windows
```
> mc ls s3/ --> Fails
```

Since most of our examples talk about '/', we should handle
this cleanly for windows.
2016-01-27 14:34:12 -08:00
Anand Babu (AB) Periasamy 01b0928989 Merge pull request #1588 from harshavardhana/handle-paths
cp/mirror: Handle path constructions properly across operating systems.
2016-01-26 18:27:13 -08:00
Harshavardhana 0a4fce57cf cp/mirror: Handle path constructions properly across operating systems.
```
mc cp -r localhost\testbucket\bin C:\destination
```

Following syntax is supposed to copy only 'bin' inside C:\destination.
Due to url construction issues this leads to 'testbucket' instead being
copied as the top level directory.

With this fix the url construction becomes more cross platform friendly.
2016-01-26 18:21:34 -08:00
Anand Babu (AB) Periasamy 257321c425 Merge pull request #1587 from harshavardhana/fix-listing-order
ls: Make recursive and non-recursive behave the same way
2016-01-26 18:16:27 -08:00
Harshavardhana 3b5dcd478a ls: Make recursive and non-recursive behave the same way
Outputs for recursive today

```
$ mc ls -r /tmp/value/
[2016-01-25 12:27:01 PST]    52B test.go
[2016-01-26 11:36:22 PST] 4.2KiB test.txt
[2016-01-26 11:45:22 PST]   102B test/
[2016-01-26 11:45:22 PST] 4.2KiB test/README.md
```

and Outputs for non recursive today differ lexically.

```
$ mc ls  /tmp/value/
[2016-01-26 11:45:22 PST]   102B test/
[2016-01-25 12:27:01 PST]    52B test.go
[2016-01-26 11:36:22 PST] 4.2KiB test.txt
```

To fix this issue we need to capture the ending '/' as
well part of the names while sorting the output. This
patch addresses this problem.
2016-01-26 18:11:24 -08:00
Anand Babu (AB) Periasamy 5c52a0adae Merge pull request #1586 from harshavardhana/ls-truncate
ls: On windows truncate the directory prefixes properly.
2016-01-26 00:29:19 -08:00
Harshavardhana d572648261 ls: On windows truncate the directory prefixes properly.
Fixes #1585
2016-01-25 21:34:16 -08:00
Anand Babu (AB) Periasamy 85e8b542de Merge pull request #1583 from harshavardhana/make-bucket
re-vendorize minio-go with new URL handling changes
2016-01-25 16:55:45 -08:00
Harshavardhana 3a3dbb2722 minio-go: vendorize to new libs.
Fixes - #1579
2016-01-25 16:39:24 -08:00
Krishna Srinivas 47cd83c71c Merge pull request #1582 from harshavardhana/add-missing
update: Add missing '/' from update url.
2016-01-25 23:19:04 +05:30
Harshavardhana 700f261b86 update: Add missing '/' from update url.
Fixes #1581
2016-01-25 09:39:56 -08:00
Anand Babu (AB) Periasamy 3f3adb1858 Merge pull request #1580 from harshavardhana/re-vendorize
mc: Vendorize to new changes.
2016-01-25 01:04:34 -08:00
Harshavardhana 9a40a67410 mc: Vendorize to new changes.
- Fix 0byte file uploads to be not uploaded as multipart.
- Fix bucket requests to have a '/' at the end
  for path style - fixes #1579
- Handle progress bar, if pb.Total is '0'.
2016-01-25 01:00:47 -08:00
Anand Babu (AB) Periasamy cfac37f53b Merge pull request #1544 from harshavardhana/merge-vendorize
mc: Vendorize to new API changes.
2016-01-23 23:57:59 -08:00
Harshavardhana a769ce6439 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)
2016-01-23 23:53:27 -08:00
Harshavardhana 951067295e Merge pull request #1575 from fwessels/master
Added alias argument for adding host with config
2016-01-18 08:58:33 -08:00
frankw bd97054b93 Added alias argument for adding host with config 2016-01-18 14:02:34 +01:00
Harshavardhana 796d36083d Merge pull request #1573 from vadmeste/did_you_mean
Add Damerau Levenshtein algo to suggest more alternatives to mistyped…
2016-01-13 12:57:19 -08:00
Anis Elleuch acc4b97483 Add Damerau Levenshtein algo to suggest more alternatives to mistyped commmands 2016-01-13 21:32:23 +01:00
Harshavardhana d92a93566b Merge pull request #1572 from vadmeste/host_add_api_optional
Make API argument in config host add cmd optional
2016-01-10 11:18:21 -08:00
Anis Elleuch 244d377f0a Make API argument in config host add cmd optional 2016-01-10 14:47:48 +01:00
Harshavardhana e958557d28 Merge pull request #1571 from vadmeste/fix_error_reporting_issue
Fix ls error msg
2016-01-09 09:52:35 -08:00
Anis Elleuch 3b35f44eba Fix ls error msg 2016-01-09 15:46:52 +01:00
Anand Babu (AB) Periasamy c26c61d3c4 Merge pull request #1570 from harshavardhana/diff-alias
diff/mirror: Handle aliases properly now.
2016-01-08 21:27:11 -08:00
Harshavardhana b347137d88 diff/mirror: Handle aliases properly now. 2016-01-08 21:24:07 -08:00
Anand Babu (AB) Periasamy 99e12696eb Merge pull request #1569 from harshavardhana/rm-all
rm: Fix alias URL handling in rm.
2016-01-08 20:59:17 -08:00
Harshavardhana f01dc5b60c rm: Fix alias URL handling in rm. 2016-01-08 20:51:28 -08:00
Anand Babu (AB) Periasamy 50240b0a1e Merge pull request #1568 from harshavardhana/mirror
mirror/cp: Remove aliases from being printed in json output. - fixes #1563
2016-01-08 19:23:14 -08:00
Harshavardhana 11b286c149 mirror/cp: Remove aliases from being printed in json output. - fixes #1563
Additionally save expanded targetURL also part of session.
2016-01-08 18:44:39 -08:00
Harshavardhana fa87ad6b37 Merge pull request #1566 from vadmeste/subcommands_has_help_flag
Emphasize that subcommands have a help flag
2016-01-08 11:09:26 -08:00
Harshavardhana dd50ad532e Merge pull request #1565 from koolhead17/patch-4
Update README.md
2016-01-08 10:32:09 -08:00
Anis Elleuch 31b07812cb Emphasize that subcommands have a help flag 2016-01-08 19:14:47 +01:00
koolhead17 e59ba922bd Update README.md
minor change with adding "--help" option
2016-01-08 23:38:34 +05:30
Harshavardhana 008a5f00de Merge pull request #1564 from abperiasamy/as60-exit-bug
return non-zero exit code in case of session failure
2016-01-08 10:00:19 -08:00
Anand Babu (AB) Periasamy 8a91ec65ce return non-zero exit code in case of session failure 2016-01-08 09:55:13 -08:00
Harshavardhana 35cdba2204 Merge pull request #1561 from vadmeste/trivial_fixes
Trivial fix of cmd error message, the same for missing dependencies in checkdeps.sh
2016-01-07 15:04:52 -08:00
Anis Elleuch 664f982833 Trivial fix of cmd error message, the same for missing dependencies in checkdeps.sh 2016-01-07 22:49:47 +01:00
Harshavardhana c08ebb25cd Merge pull request #1558 from abperiasamy/cache-client
cache and re-use minio S3 client
2015-12-31 17:22:53 -08:00
Anand Babu (AB) Periasamy f7cdbc2583 cache and re-use minio S3 client 2015-12-31 17:02:08 -08:00
Harshavardhana d47faa3256 Merge pull request #1556 from koolhead17/patch-3
Update INSTALLGO.md
2015-12-29 23:52:36 -08:00
koolhead17 9cd535a6cd Update INSTALLGO.md
minor fix.
2015-12-30 12:14:35 +05:30
Harshavardhana b6fe0d2529 Merge pull request #1555 from abperiasamy/config-v7
new alias style and numerous cleanups.
2015-12-28 15:35:21 -08:00
Anand Babu (AB) Periasamy 0bd1edfd8f new alias style and numerous cleanups. 2015-12-28 15:31:52 -08:00
141 changed files with 11051 additions and 7123 deletions
+18 -2
View File
@@ -1,9 +1,25 @@
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
script:
- diff -au <(gofmt -d *.go) <(printf "")
- diff -au <(gofmt -d pkg) <(printf "")
notifications:
slack:
secure: McinxQ4R/Yu2r/U8lVsdAIQ195Rf+3/Ku6DViWyqLHsTt5fTnVrSfbIKs8vy0t2A0bRLO6zv2xOSMWjfiimZLPMgMbMqLtTFEzUzB8RZyx2n2xgmL8q3gjXcLA3vkBreaRYCzJzX6DjvrxRfhyOg+BQHpLpACWik3FS/7VIdDCI=
+1 -1
View File
@@ -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
+4 -1
View File
@@ -27,6 +27,9 @@ export GOROOT=${HOME}/bin/go
export GOPATH=${HOME}/go
export PATH=$PATH:${HOME}/bin/go/bin:${GOPATH}/bin
```
##### Source the new environment
```sh
$ source ~/.bashrc
```
@@ -71,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
-5
View File
@@ -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.
+2 -1
View File
@@ -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 $@:"
+7 -7
View File
@@ -34,7 +34,7 @@ Download ``mc`` for:
~~~
$ chmod +x mc
$ ./mc help
$ ./mc --help
~~~
#### OS X
@@ -43,7 +43,7 @@ Download ``mc`` from https://dl.minio.io/client/mc/release/darwin-amd64/mc
~~~
$ chmod 755 mc
$ ./mc help
$ ./mc --help
~~~
#### Microsoft Windows
@@ -54,12 +54,12 @@ Download ``mc`` for:
- ``32-bit`` from https://dl.minio.io/client/mc/release/windows-386/mc.exe
~~~
C:\Users\Username\Downloads> mc.exe help
C:\Users\Username\Downloads> mc.exe --help
~~~
#### Source
<blockquote>
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.
</blockquote>
If you do not have a working Golang environment, please follow [Install Golang](./INSTALLGO.md).
@@ -78,12 +78,12 @@ Get your AccessKeyID and SecretAccessKey by following [AWS Credentials Guide](ht
Once you have them update your ``~/.mc/config.json`` configuration file.
```
$ mc config host add <YOUR-S3-ENDPOINT> <YOUR-ACCESS-KEY> <YOUR-SECRET-KEY> S3v4
$ mc config host add <ALIAS> <YOUR-S3-ENDPOINT> <YOUR-ACCESS-KEY> <YOUR-SECRET-KEY> S3v4
```
Example
```
$ mc config host add https://s3.amazonaws.com BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12
$ mc config host add mys3 https://s3.amazonaws.com BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12
```
NOTE: ``S3v4`` is default if not specified.
@@ -94,7 +94,7 @@ Get your AccessKeyID and SecretAccessKey by following [Google Credentials Guide]
Once you have them update your ``~/.mc/config.json`` configuration file.
```
$ mc config host add https://storage.googleapis.com <YOUR-ACCESS-KEY> <YOUR-SECRET-KEY> S3v2
$ mc config host add <ALIAS> https://storage.googleapis.com <YOUR-ACCESS-KEY> <YOUR-SECRET-KEY> S3v2
```
NOTE: Google Cloud Storage only supports Legacy Signature Version ``2``, so you have to pick - ``S3v2``
+11 -16
View File
@@ -56,19 +56,19 @@ FLAGS:
{{end}}
EXAMPLES:
1. Set bucket to "private" on Amazon S3 cloud storage.
$ mc {{.Name}} set private s3.amazonaws.com/burningman2011
$ mc {{.Name}} set private s3/burningman2011
2. Set bucket to "public" on Amazon S3 cloud storage.
$ mc {{.Name}} set public s3.amazonaws.com/shared
$ mc {{.Name}} set public s3/shared
3. Set bucket to "authenticated" on Amazon S3 cloud storage to provide read access to IAM Authenticated Users group.
$ mc {{.Name}} set authorized s3.amazonaws.com/shared-authenticated
$ mc {{.Name}} set authorized s3/shared-authenticated
4. Get bucket permissions.
$ mc {{.Name}} get s3.amazonaws.com/shared
$ mc {{.Name}} get s3/shared
5. Get bucket permissions.
$ mc {{.Name}} get storage.googleapis.com/miniocloud
$ mc {{.Name}} get gcs/miniocloud
`,
}
@@ -96,8 +96,8 @@ func (s accessMessage) String() string {
// JSON jsonified access message.
func (s accessMessage) JSON() string {
accessJSONBytes, err := json.Marshal(s)
fatalIf(probe.NewError(err), "Unable to marshal into JSON.")
accessJSONBytes, e := json.Marshal(s)
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(accessJSONBytes)
}
@@ -134,7 +134,7 @@ func checkAccessSyntax(ctx *cli.Context) {
// doSetAccess do set access.
func doSetAccess(targetURL string, targetPERMS accessPerms) *probe.Error {
clnt, err := url2Client(targetURL)
clnt, err := newClient(targetURL)
if err != nil {
return err.Trace(targetURL)
}
@@ -146,7 +146,7 @@ func doSetAccess(targetURL string, targetPERMS accessPerms) *probe.Error {
// doGetAccess do get access.
func doGetAccess(targetURL string) (perms accessPerms, err *probe.Error) {
clnt, err := url2Client(targetURL)
clnt, err := newClient(targetURL)
if err != nil {
return "", err.Trace(targetURL)
}
@@ -170,10 +170,7 @@ func mainAccess(ctx *cli.Context) {
switch ctx.Args().First() {
case "set":
perms := accessPerms(ctx.Args().Tail().First())
URLs, err := args2URLs(ctx.Args().Tail().Tail())
fatalIf(err.Trace(ctx.Args().Tail().Tail()...), "Unable to convert args 2 URLs.")
URLs := ctx.Args().Tail().Tail()
for _, targetURL := range URLs {
err := doSetAccess(targetURL, perms)
// Upon error, print and continue.
@@ -190,9 +187,7 @@ func mainAccess(ctx *cli.Context) {
})
}
case "get":
URLs, err := args2URLs(ctx.Args().Tail())
fatalIf(err.Trace(ctx.Args().Tail()...), "Unable to convert args 2 URLs.")
URLs := ctx.Args().Tail()
for _, targetURL := range URLs {
perms, err := doGetAccess(targetURL)
if err != nil {
+11 -30
View File
@@ -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
}
-74
View File
@@ -1,74 +0,0 @@
/*
* Minio Client (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 main
import (
"os"
"regexp"
"runtime"
"strings"
"github.com/minio/mc/pkg/client"
"github.com/minio/minio-xl/pkg/probe"
)
// isValidAliasName - Check if aliasName is a valid alias.
func isValidAliasName(aliasName string) bool {
return regexp.MustCompile("^[a-zA-Z][a-zA-Z0-9-]+$").MatchString(aliasName)
}
// normalizeAliasedURL - remove any preceding separators.
func normalizeAliasedURL(aliasedURL string) string {
if runtime.GOOS == "windows" {
aliasedURL = strings.Replace(aliasedURL, "/", "\\", -1)
}
aliasedURL = strings.TrimPrefix(aliasedURL, string(os.PathSeparator))
return aliasedURL
}
// getAliasURL expands aliased (name/path) to full URL, used by url-parser.
func getAliasURL(aliasedURL string) (string, *probe.Error) {
config, err := loadMcConfig()
if err != nil {
return aliasedURL, err.Trace(aliasedURL)
}
if strings.HasPrefix(aliasedURL, "https") || strings.HasPrefix(aliasedURL, "http") {
return aliasedURL, nil
}
for hostURL := range config.Hosts {
url := client.NewURL(hostURL)
if strings.Contains(aliasedURL, url.Host) {
return url.Scheme + url.SchemeSeparator + aliasedURL, nil
}
}
normalizedAliasURL := normalizeAliasedURL(aliasedURL)
for aliasName, aliasValue := range config.Aliases {
if strings.HasPrefix(normalizedAliasURL, aliasName) {
// Match found. Expand it.
if !strings.Contains(normalizedAliasURL, string(os.PathSeparator)) {
return aliasValue, nil
}
splits := strings.SplitN(normalizedAliasURL, string(os.PathSeparator), 2)
if len(splits) == 1 {
return aliasedURL, nil // Not an aliased URL. Return as is.
}
// Matched, but path needs to be joined.
return urlJoinPath(aliasValue, splits[1]), nil
}
}
return aliasedURL, nil // No matching alias found. Return as is.
}
+3 -4
View File
@@ -138,14 +138,13 @@ func (h objectAPIHandler) putHandler(w http.ResponseWriter, r *http.Request) {
return
}
length, err := strconv.Atoi(r.Header.Get("Content-Length"))
if err != nil {
length, e := strconv.Atoi(r.Header.Get("Content-Length"))
if e != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
var buffer bytes.Buffer
_, err = io.CopyN(&buffer, r.Body, int64(length))
if err != nil {
if _, e = io.CopyN(&buffer, r.Body, int64(length)); e != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
+4 -1
View File
@@ -20,6 +20,8 @@ install:
- 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
- go get -u github.com/alecthomas/gometalinter
- go get -u github.com/client9/misspell
# to run your custom scripts instead of automatic MSBuild
build_script:
@@ -28,7 +30,8 @@ build_script:
- gofmt -s -l pkg
- golint .
- golint github.com/minio/mc/pkg...
- gocyclo -over 40 .
- gometalinter --disable-all --linter='misspell:misspell ./*.go:PATH:LINE:COL:MESSAGE' --enable=misspell ./...
- gocyclo -over 40 pkg
- deadcode
- go test -race .
- go test -race github.com/minio/mc/pkg...
+2 -23
View File
@@ -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"
@@ -176,31 +173,13 @@ is_supported_arch() {
check_deps() {
check_version "$(env go version 2>/dev/null | sed 's/^.* go\([0-9.]*\).*$/\1/')" "${GO_VERSION}"
if [ $? -ge 2 ]; then
MISSING="${MISSING} golang(${GO_VERSION})"
MISSING="${MISSING} golang(>=${GO_VERSION})"
fi
check_version "$(env git --version 2>/dev/null | sed -e 's/^.* \([0-9.\].*\).*$/\1/' -e 's/^\([0-9.\]*\).*/\1/g')" "${GIT_VERSION}"
if [ $? -ge 2 ]; then
MISSING="${MISSING} git(${GIT_VERSION})"
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() {
+9 -16
View File
@@ -54,7 +54,7 @@ FLAGS:
{{end}}
EXAMPLES:
1. Stream an object from Amazon S3 cloud storage to mplayer standard input.
$ mc {{.Name}} s3.amazonaws.com/ferenginar/klingon_opera_aktuh_maylotah.ogg | mplayer -
$ mc {{.Name}} s3/ferenginar/klingon_opera_aktuh_maylotah.ogg | mplayer -
2. Concantenate contents of file1.txt and stdin to standard output.
$ mc {{.Name}} file1.txt - > file.txt
@@ -80,19 +80,15 @@ 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
default:
sourceClnt, err := url2Client(sourceURL)
if err != nil {
return err.Trace(sourceURL)
}
// Ignore size, since os.Stat() would not return proper size all the
// time for local filesystem for example /proc files.
reader, err = sourceClnt.Get(0, 0)
if err != nil {
var err *probe.Error
if reader, err = getSourceStream(sourceURL); err != nil {
return err.Trace(sourceURL)
}
}
@@ -102,16 +98,16 @@ func catURL(sourceURL string) *probe.Error {
// catOut reads from reader stream and writes to stdout.
func catOut(r io.Reader) *probe.Error {
// Read till EOF.
if _, err := io.Copy(os.Stdout, r); err != nil {
switch e := err.(type) {
if _, e := io.Copy(os.Stdout, r); e != nil {
switch e := e.(type) {
case *os.PathError:
if e.Err == syscall.EPIPE {
// stdout closed by the user. Gracefully exit.
return nil
}
return probe.NewError(err)
return probe.NewError(e)
default:
return probe.NewError(err)
return probe.NewError(e)
}
}
return nil
@@ -150,10 +146,7 @@ func mainCat(ctx *cli.Context) {
}
// Convert arguments to URLs: expand alias, fix format.
URLs, err := args2URLs(args)
fatalIf(err.Trace(args...), "Unable to parse arguments.")
for _, url := range URLs {
for _, url := range args {
fatalIf(catURL(url).Trace(url), "Unable to read from ‘"+url+"’.")
}
}
-54
View File
@@ -1,54 +0,0 @@
/*
* Minio Client (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 main
import (
"bytes"
"io/ioutil"
"os"
"path/filepath"
"github.com/minio/minio-xl/pkg/probe"
. "gopkg.in/check.v1"
)
func (s *TestSuite) TestCat(c *C) {
/// filesystem
root, e := ioutil.TempDir(os.TempDir(), "cmd-")
c.Assert(e, IsNil)
defer os.RemoveAll(root)
objectPath := filepath.Join(root, "object1")
objectPathServer := server.URL + "/bucket/object1"
data := "hello"
var err *probe.Error
err = putTarget(objectPath, bytes.NewReader([]byte(data)), int64(len(data)))
c.Assert(err, IsNil)
err = putTarget(objectPathServer, bytes.NewReader([]byte(data)), int64(len(data)))
c.Assert(err, IsNil)
var sourceURLs []string
sourceURLs = append(sourceURLs, objectPath)
sourceURLs = append(sourceURLs, objectPathServer)
for _, sourceURL := range sourceURLs {
c.Assert(catURL(sourceURL), IsNil)
}
objectPath = filepath.Join(root, "object2")
c.Assert(catURL(objectPath), Not(IsNil))
}
+84 -45
View File
@@ -19,6 +19,7 @@ package main
import (
"io"
"os"
"regexp"
"runtime"
"strings"
@@ -33,6 +34,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
}
@@ -47,65 +52,99 @@ func isTargetURLDir(targetURL string) bool {
return true
}
// getSource gets a reader from URL
func getSource(sourceURL string) (reader io.ReadSeeker, err *probe.Error) {
sourceClnt, err := url2Client(sourceURL)
// getSource gets a reader from URL.
func getSourceStream(urlStr string) (reader io.Reader, err *probe.Error) {
alias, urlStrFull, _, err := expandAlias(urlStr)
if err != nil {
return nil, err.Trace(sourceURL)
return nil, err.Trace(urlStr)
}
return sourceClnt.Get(0, 0)
return getSourceStreamFromAlias(alias, urlStrFull)
}
// putTarget writes to URL from reader. If length=-1, read until EOF.
func putTarget(targetURL string, reader io.ReadSeeker, size int64) *probe.Error {
targetClnt, err := url2Client(targetURL)
// 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 err.Trace(targetURL)
return nil, err.Trace(alias, urlStr)
}
contentType := guessURLContentType(targetURL)
err = targetClnt.Put(reader, size, contentType)
reader, err = sourceClnt.Get()
if err != nil {
return err.Trace(targetURL)
return nil, err.Trace(alias, urlStr)
}
return nil
return reader, nil
}
// getNewClient gives a new client interface
func getNewClient(urlStr string, auth hostConfig) (client.Client, *probe.Error) {
url := client.NewURL(urlStr)
switch url.Type {
case client.Object: // Minio and S3 compatible cloud storage
s3Config := new(client.Config)
s3Config.AccessKeyID = func() string {
if auth.AccessKeyID == globalAccessKeyID {
return ""
}
return auth.AccessKeyID
}()
s3Config.SecretAccessKey = func() string {
if auth.SecretAccessKey == globalSecretAccessKey {
return ""
}
return auth.SecretAccessKey
}()
s3Config.Signature = auth.API
s3Config.AppName = "Minio"
s3Config.AppVersion = mcVersion
s3Config.AppComments = []string{os.Args[0], runtime.GOOS, runtime.GOARCH}
s3Config.HostURL = urlStr
s3Config.Debug = globalDebug
// 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 0, err.Trace(alias, urlStr)
}
contentType := guessURLContentType(urlStr)
var n int64
n, err = targetClnt.Put(reader, size, contentType, progress)
if err != nil {
return n, err.Trace(alias, urlStr)
}
return n, nil
}
s3Client, err := s3.New(s3Config)
if err != nil {
return nil, err.Trace(urlStr)
}
return s3Client, nil
case client.Filesystem:
// 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
// alias entry in the mc config file. If no matching host config entry
// is found, fs client is returned.
func newClientFromAlias(alias string, urlStr string) (client.Client, *probe.Error) {
hostCfg := mustGetHostConfig(alias)
if hostCfg == nil {
// No matching host config. So we treat it like a
// filesystem.
fsClient, err := fs.New(urlStr)
if err != nil {
return nil, err.Trace(urlStr)
return nil, err.Trace(alias, urlStr)
}
return fsClient, nil
}
return nil, errInitClient(urlStr).Trace(urlStr)
// We have a valid alias and hostConfig. We populate the
// credentials from the match found in the config file.
s3Config := new(client.Config)
s3Config.AccessKey = hostCfg.AccessKey
s3Config.SecretKey = hostCfg.SecretKey
s3Config.Signature = hostCfg.API
s3Config.AppName = "mc"
s3Config.AppVersion = mcVersion
s3Config.AppComments = []string{os.Args[0], runtime.GOOS, runtime.GOARCH}
s3Config.HostURL = urlStr
s3Config.Debug = globalDebug
s3Client, err := s3.New(s3Config)
if err != nil {
return nil, err.Trace(alias, urlStr)
}
return s3Client, nil
}
// urlRgx - verify if aliased url is real URL.
var urlRgx = regexp.MustCompile("^https?://")
// newClient gives a new client interface
func newClient(aliasedURL string) (client.Client, *probe.Error) {
alias, urlStrFull, hostCfg, err := expandAlias(aliasedURL)
if err != nil {
return nil, err.Trace(aliasedURL)
}
// Verify if the aliasedURL is a real URL, fail in those cases
// indicating the user to add alias.
if hostCfg == nil && urlRgx.MatchString(aliasedURL) {
return nil, errInvalidAliasedURL(aliasedURL).Trace(aliasedURL)
}
return newClientFromAlias(alias, urlStrFull)
}
-69
View File
@@ -1,69 +0,0 @@
/*
* Minio Client (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 main
import (
"bytes"
"io"
"io/ioutil"
"os"
"path/filepath"
. "gopkg.in/check.v1"
)
func (s *TestSuite) TestCommonMethods(c *C) {
/// filesystem
root, e := ioutil.TempDir(os.TempDir(), "cmd-")
c.Assert(e, IsNil)
defer os.RemoveAll(root)
objectPath := filepath.Join(root, "object1")
c.Assert(isTargetURLDir(root), Equals, true)
c.Assert(isTargetURLDir(objectPath), Equals, false)
objectPathServer := server.URL + "/bucket/object1"
data := "hello"
err := putTarget(objectPath, bytes.NewReader([]byte(data)), int64(len(data)))
c.Assert(err, IsNil)
err = putTarget(objectPathServer, bytes.NewReader([]byte(data)), int64(len(data)))
c.Assert(err, IsNil)
c.Assert(isTargetURLDir(objectPathServer), Equals, false)
c.Assert(isTargetURLDir(server.URL+"/bucket"), Equals, true)
reader, err := getSource(objectPathServer)
c.Assert(err, IsNil)
var results bytes.Buffer
_, e = io.Copy(&results, reader)
c.Assert(e, IsNil)
c.Assert([]byte(data), DeepEquals, results.Bytes())
_, content, err := url2Stat(objectPathServer)
c.Assert(err, IsNil)
c.Assert(content.Type.IsRegular(), Equals, true)
_, _, err = url2Stat(objectPath + "invalid")
c.Assert(err, Not(IsNil))
_, err = url2Client(objectPathServer)
c.Assert(err, IsNil)
_, err = url2Client(objectPathServer)
c.Assert(err, IsNil)
}
-232
View File
@@ -1,232 +0,0 @@
/*
* Minio Client (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 main
import (
"encoding/json"
"fmt"
"strings"
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/console"
"github.com/minio/minio-xl/pkg/probe"
)
var (
configAliasFlags = []cli.Flag{
cli.BoolFlag{
Name: "help, h",
Usage: "Help of config alias.",
},
}
)
var configAliasCmd = cli.Command{
Name: "alias",
Usage: "List, modify and remove aliases in configuration file.",
Action: mainConfigAlias,
Flags: append(configAliasFlags, globalFlags...),
CustomHelpTemplate: `NAME:
mc config {{.Name}} - {{.Usage}}
USAGE:
mc config {{.Name}} [FLAGS] OPERATION [ARGS...]
OPERATION:
remove Remove a alias.
list List all aliases.
add Add new alias.
FLAGS:
{{range .Flags}}{{.}}
{{end}}
EXAMPLES:
1. Add aliases for Amazon S3.
$ mc config {{.Name}} add mcloud https://miniocloud.s3.amazonaws.com
$ mc ls mcloud
2. Add aliases for Google Cloud Storage.
$ mc config {{.Name}} add gcscloud https://miniocloud.storage.googleapis.com
$ mc ls gcscloud
3. List all aliased URLs.
$ mc config {{.Name}} list
4. Remove an alias
$ mc config {{.Name}} remove mcloud
`,
}
// aliasMessage container for content message structure
type aliasMessage struct {
op string
Status string `json:"status"`
Alias string `json:"alias"`
URL string `json:"url,omitempty"`
}
// String colorized alias message
func (a aliasMessage) String() string {
if a.op == "list" {
message := console.Colorize("Alias", fmt.Sprintf("[%s] <- ", a.Alias))
message += console.Colorize("URL", fmt.Sprintf("%s", a.URL))
return message
}
if a.op == "remove" {
return console.Colorize("AliasMessage", "Removed alias ‘"+a.Alias+"’ successfully.")
}
if a.op == "add" {
return console.Colorize("AliasMessage", "Added alias ‘"+a.Alias+"’ successfully.")
}
// should never come here
return ""
}
// JSON jsonified alias message
func (a aliasMessage) JSON() string {
a.Status = "success"
jsonMessageBytes, e := json.Marshal(a)
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(jsonMessageBytes)
}
// checkConfigAliasAddSyntax validate 'config alias add' input arguments.
func checkConfigAliasAddSyntax(ctx *cli.Context) {
if len(ctx.Args().Tail()) != 2 {
fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...),
"Incorrect number of arguments for add alias command.")
}
aliasName := ctx.Args().Tail().Get(0)
aliasedURL := ctx.Args().Tail().Get(1)
if aliasName == "" || aliasedURL == "" {
fatalIf(errDummy().Trace(), "Alias or URL cannot be empty.")
}
aliasedURL = strings.TrimSuffix(aliasedURL, "/")
if !strings.HasPrefix(aliasedURL, "http") {
fatalIf(errDummy().Trace(aliasedURL),
fmt.Sprintf("Invalid alias URL ‘%s’. Valid examples are: http://s3.amazonaws.com, https://yourbucket.example.com.", aliasedURL))
}
if !isValidAliasName(aliasName) {
fatalIf(errDummy().Trace(aliasName),
fmt.Sprintf("Alias name ‘%s’ is invalid, valid examples are: mybucket, Area51, Grand-Nagus", aliasName))
}
}
// checkConfigAliasRemoveSyntax validate 'config alias remove' input argument.
func checkConfigAliasRemoveSyntax(ctx *cli.Context) {
if len(ctx.Args().Tail()) != 1 {
fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...),
"Incorrect number of arguments for remove alias command.")
}
aliasName := ctx.Args().Tail().Get(0)
if strings.TrimSpace(aliasName) == "" {
fatalIf(errDummy().Trace(), "Alias or URL cannot be empty.")
}
if !isValidAliasName(aliasName) {
fatalIf(errDummy().Trace(aliasName),
fmt.Sprintf("Alias name ‘%s’ is invalid, valid examples are: mybucket, Area51, Grand-Nagus", aliasName))
}
}
func checkConfigAliasSyntax(ctx *cli.Context) {
// show help if nothing is set
if !ctx.Args().Present() || ctx.Args().First() == "help" {
cli.ShowCommandHelpAndExit(ctx, "alias", 1) // last argument is exit code
}
if strings.TrimSpace(ctx.Args().First()) == "" {
cli.ShowCommandHelpAndExit(ctx, "alias", 1) // last argument is exit code
}
if len(ctx.Args().Tail()) > 2 {
fatalIf(errDummy().Trace(ctx.Args().Tail()...), "Incorrect number of arguments to alias command")
}
switch strings.TrimSpace(ctx.Args().Get(0)) {
case "add":
checkConfigAliasAddSyntax(ctx)
case "remove":
checkConfigAliasRemoveSyntax(ctx)
case "list":
default:
cli.ShowCommandHelpAndExit(ctx, "alias", 1) // last argument is exit code
}
}
// addAlias - adds an alias entry.
func addAlias(aliasName, aliasedURL string) {
conf, err := loadMcConfig()
fatalIf(err.Trace(globalMCConfigVersion), "Unable to load config version ‘"+globalMCConfigVersion+"’.")
conf.Aliases[aliasName] = aliasedURL
err = saveMcConfig(conf)
fatalIf(err.Trace(aliasName, aliasedURL), "Unable to update aliases in config version ‘"+globalMCConfigVersion+"’.")
printMsg(aliasMessage{op: "add", Alias: aliasName, URL: aliasedURL})
}
// removeAlias - remove a alias.
func removeAlias(aliasName string) {
conf, err := loadMcConfig()
fatalIf(err.Trace(globalMCConfigVersion), "Unable to load config version ‘"+globalMCConfigVersion+"’.")
delete(conf.Aliases, aliasName)
err = saveMcConfig(conf)
fatalIf(err.Trace(aliasName), "Unable to save deleted alias in config version ‘"+globalMCConfigVersion+"’.")
printMsg(aliasMessage{op: "remove", Alias: aliasName})
}
// listAliases - list aliases.
func listAliases() {
conf, err := loadMcConfig()
fatalIf(err.Trace(globalMCConfigVersion), "Unable to load config version ‘"+globalMCConfigVersion+"’")
for aliasName, aliasedURL := range conf.Aliases {
printMsg(aliasMessage{op: "list", Alias: aliasName, URL: aliasedURL})
}
}
func mainConfigAlias(ctx *cli.Context) {
// Set global flags from context.
setGlobalsFromContext(ctx)
// check 'config alias' cli arguments.
checkConfigAliasSyntax(ctx)
// Additional customization speific to each command.
console.SetColor("Alias", color.New(color.FgCyan, color.Bold))
console.SetColor("AliasMessage", color.New(color.FgGreen, color.Bold))
console.SetColor("URL", color.New(color.FgWhite, color.Bold))
arg := ctx.Args().First()
tailArgs := ctx.Args().Tail()
switch strings.TrimSpace(arg) {
case "add":
aliasName := tailArgs.Get(0)
aliasedURL := tailArgs.Get(1)
addAlias(aliasName, aliasedURL) // add alias name for aliased URL.
case "remove":
aliasName := tailArgs.Get(0)
removeAlias(aliasName) // remove alias name.
case "list":
listAliases() // list all aliases.
}
}
+242
View File
@@ -0,0 +1,242 @@
/*
* Minio Client (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 main
import (
"fmt"
"strings"
"github.com/minio/mc/pkg/client"
"github.com/minio/mc/pkg/console"
"github.com/minio/minio-xl/pkg/quick"
)
func fixConfig() {
// Fix config V3
fixConfigV3()
// Fix config V6
fixConfigV6()
// Fix config V6 for hosts
fixConfigV6ForHosts()
/* No more fixing job. Here after we bump the version for changes always.
*/
}
/////////////////// Broken Config V3 ///////////////////
type brokenHostConfigV3 struct {
AccessKeyID string
SecretAccessKey string
}
type brokenConfigV3 struct {
Version string
ACL string
Access string
Aliases map[string]string
Hosts map[string]brokenHostConfigV3
}
// newConfigV3 - get new config broken version 3.
func newBrokenConfigV3() *brokenConfigV3 {
conf := new(brokenConfigV3)
conf.Version = "3"
conf.Aliases = make(map[string]string)
conf.Hosts = make(map[string]brokenHostConfigV3)
return conf
}
// 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 unused (ACL, Access) fields.
func fixConfigV3() {
if !isMcConfigExists() {
return
}
brokenCfgV3 := newBrokenConfigV3()
brokenMcCfgV3, err := quick.Load(mustGetMcConfigPath(), brokenCfgV3)
fatalIf(err.Trace(), "Unable to load config.")
if brokenMcCfgV3.Version() != "3" {
return
}
cfgV3 := newConfigV3()
isMutated := false
for k, v := range brokenMcCfgV3.Data().(*brokenConfigV3).Aliases {
cfgV3.Aliases[k] = v
}
for host, brokenHostCfgV3 := range brokenMcCfgV3.Data().(*brokenConfigV3).Hosts {
// If any of these fields contains any real value anytime,
// it means we have already fixed the broken configuration.
// We don't have to regenerate again.
if brokenHostCfgV3.AccessKeyID != "" && brokenHostCfgV3.SecretAccessKey != "" {
isMutated = true
}
// Use the correct hostConfig with JSON tags in it.
cfgV3.Hosts[host] = hostConfigV3{
AccessKeyID: brokenHostCfgV3.AccessKeyID,
SecretAccessKey: brokenHostCfgV3.SecretAccessKey,
}
}
// We blindly drop ACL and Access fields from the broken config v3.
if isMutated {
mcNewConfigV3, err := quick.New(cfgV3)
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘3’.")
err = mcNewConfigV3.Save(mustGetMcConfigPath())
fatalIf(err.Trace(), "Unable to save config version ‘3’.")
console.Infof("Successfully fixed %s broken config for version ‘3’.\n", mustGetMcConfigPath())
}
}
// If the host key does not have http(s), fix it.
func fixConfigV6ForHosts() {
if !isMcConfigExists() {
return
}
brokenMcCfgV6, err := quick.Load(mustGetMcConfigPath(), newConfigV6())
fatalIf(err.Trace(), "Unable to load config.")
if brokenMcCfgV6.Version() != "6" {
return
}
newCfgV6 := newConfigV6()
isMutated := false
// Copy aliases.
for k, v := range brokenMcCfgV6.Data().(*configV6).Aliases {
newCfgV6.Aliases[k] = v
}
url := new(client.URL)
// Copy hosts.
for host, hostCfgV6 := range brokenMcCfgV6.Data().(*configV6).Hosts {
// Already fixed - Copy and move on.
if strings.HasPrefix(host, "https") || strings.HasPrefix(host, "http") {
newCfgV6.Hosts[host] = hostCfgV6
continue
}
// If host entry does not contain "http(s)", introduce a new entry and delete the old one.
if host == "s3.amazonaws.com" || host == "storage.googleapis.com" ||
host == "localhost:9000" || host == "127.0.0.1:9000" ||
host == "play.minio.io:9000" || host == "dl.minio.io:9000" {
console.Infoln("Found broken host entries, replacing " + host + " with https://" + host + ".")
url.Host = host
url.Scheme = "https"
url.SchemeSeparator = "://"
newCfgV6.Hosts[url.String()] = hostCfgV6
isMutated = true
continue
}
}
if isMutated {
// Save the new config back to the disk.
mcCfgV6, err := quick.New(newCfgV6)
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘v6’.")
err = mcCfgV6.Save(mustGetMcConfigPath())
fatalIf(err.Trace(), "Unable to save config version ‘v6’.")
}
}
// fixConfigV6 - fix all the unnecessary glob URLs present in existing config version 6.
func fixConfigV6() {
if !isMcConfigExists() {
return
}
config, err := quick.New(newConfigV6())
fatalIf(err.Trace(), "Unable to initialize config.")
err = config.Load(mustGetMcConfigPath())
fatalIf(err.Trace(mustGetMcConfigPath()), "Unable to load config.")
if config.Data().(*configV6).Version != "6" {
return
}
newConfig := new(configV6)
isMutated := false
newConfig.Aliases = make(map[string]string)
newConfig.Hosts = make(map[string]hostConfigV6)
newConfig.Version = "6"
newConfig.Aliases = config.Data().(*configV6).Aliases
for host, hostCfg := range config.Data().(*configV6).Hosts {
if strings.Contains(host, "*") {
fatalIf(err.Trace(),
fmt.Sprintf("Glob style ‘*’ pattern matching is no longer supported. Please fix ‘%s’ entry manually.", host))
}
if strings.Contains(host, "*s3*") || strings.Contains(host, "*.s3*") {
console.Infoln("Found glob url, replacing " + host + " with s3.amazonaws.com")
newConfig.Hosts["s3.amazonaws.com"] = hostCfg
isMutated = true
continue
}
if strings.Contains(host, "s3*") {
console.Infoln("Found glob url, replacing " + host + " with s3.amazonaws.com")
newConfig.Hosts["s3.amazonaws.com"] = hostCfg
isMutated = true
continue
}
if strings.Contains(host, "*amazonaws.com") || strings.Contains(host, "*.amazonaws.com") {
console.Infoln("Found glob url, replacing " + host + " with s3.amazonaws.com")
newConfig.Hosts["s3.amazonaws.com"] = hostCfg
isMutated = true
continue
}
if strings.Contains(host, "*storage.googleapis.com") {
console.Infoln("Found glob url, replacing " + host + " with storage.googleapis.com")
newConfig.Hosts["storage.googleapis.com"] = hostCfg
isMutated = true
continue
}
if strings.Contains(host, "localhost:*") {
console.Infoln("Found glob url, replacing " + host + " with localhost:9000")
newConfig.Hosts["localhost:9000"] = hostCfg
isMutated = true
continue
}
if strings.Contains(host, "127.0.0.1:*") {
console.Infoln("Found glob url, replacing " + host + " with 127.0.0.1:9000")
newConfig.Hosts["127.0.0.1:9000"] = hostCfg
isMutated = true
continue
}
// Other entries are hopefully OK. Copy them blindly.
newConfig.Hosts[host] = hostCfg
}
if isMutated {
newConf, err := quick.New(newConfig)
fatalIf(err.Trace(), "Unable to initialize newly fixed config.")
err = newConf.Save(mustGetMcConfigPath())
fatalIf(err.Trace(mustGetMcConfigPath()), "Unable to save newly fixed config path.")
console.Infof("Successfully fixed %s broken config for version ‘6’.\n", mustGetMcConfigPath())
}
}
+118 -157
View File
@@ -45,95 +45,84 @@ var configHostCmd = cli.Command{
mc config {{.Name}} - {{.Usage}}
USAGE:
mc config {{.Name}} OPERATION [ARGS...]
mc config {{.Name}} OPERATION
OPERATION:
remove Remove a host.
list list all hosts.
add Add new host.
add ALIAS URL ACCESS-KEY SECRET-KEY [API]
remove ALIAS
list
FLAGS:
{{range .Flags}}{{.}}
{{end}}
EXAMPLES:
1. Add host configuration for a URL, using default signature V4. For security reasons turn off bash history
1. Add Amazon S3 storage service under "myphotos" alias. For security reasons turn off bash history momentarily.
$ set +o history
$ mc config {{.Name}} add https://s3.amazonaws.com BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12
$ mc config {{.Name}} add myphotos https://s3.amazonaws.com BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12
$ set -o history
2. Add host configuration for a URL, using signature V2. For security reasons turn off bash history
$ set +o history
$ mc config {{.Name}} add https://storage.googleapis.com BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 S3v2
$ set -o history
2. Add Google Cloud Storage service under "goodisk" alias.
$ mc config {{.Name}} add goodisk https://storage.googleapis.com BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 S3v2
3. Add host configuration for a URL by importing credentials csv file.
$ mc config {{.Name}} import https://s3.amazonaws.com credentials.csv
4. List all hosts.
3. List all hosts.
$ mc config {{.Name}} list
5. Remove host config.
$ mc config {{.Name}} remove https://s3.amazonaws.com
4. Remove "goodisk" config.
$ mc config {{.Name}} remove goodisk
`,
}
// hostMessage container for content message structure
type hostMessage struct {
op string
Status string `json:"status"`
Host string `json:"host"`
AccessKeyID string `json:"accessKeyId,omitempty"`
SecretAccessKey string `json:"secretAccessKey,omitempty"`
API string `json:"api,omitempty"`
op string
Status string `json:"status"`
Alias string `json:"alias"`
URL string `json:"URL"`
AccessKey string `json:"accessKey,omitempty"`
SecretKey string `json:"secretKey,omitempty"`
API string `json:"api,omitempty"`
}
// String colorized host message
func (a hostMessage) String() string {
if a.op == "list" {
message := console.Colorize("Host", fmt.Sprintf("[%s] ", a.Host))
if a.AccessKeyID != "" || a.SecretAccessKey != "" {
message += console.Colorize("AccessKeyID", fmt.Sprintf("<- %s,", a.AccessKeyID))
message += console.Colorize("SecretAccessKey", fmt.Sprintf(" %s,", a.SecretAccessKey))
message += console.Colorize("API", fmt.Sprintf(" %s", a.API))
func (h hostMessage) String() string {
switch h.op {
case "list":
message := console.Colorize("Alias", fmt.Sprintf("%s: ", h.Alias))
message += console.Colorize("URL", fmt.Sprintf("%s", h.URL))
if h.AccessKey != "" || h.SecretKey != "" {
message += " | " + console.Colorize("AccessKey", fmt.Sprintf("<- %s,", h.AccessKey))
message += " | " + console.Colorize("SecretKey", fmt.Sprintf(" %s,", h.SecretKey))
message += " | " + console.Colorize("API", fmt.Sprintf(" %s", h.API))
}
return message
case "remove":
return console.Colorize("HostMessage", "Removed ‘"+h.Alias+"’ successfully.")
case "add":
return console.Colorize("HostMessage", "Added ‘"+h.Alias+"’ successfully.")
default:
return ""
}
if a.op == "remove" {
return console.Colorize("HostMessage", "Removed host ‘"+a.Host+"’ successfully.")
}
if a.op == "add" {
return console.Colorize("HostMessage", "Added host ‘"+a.Host+"’ successfully.")
}
// should never reach here
return ""
}
// JSON jsonified host message
func (a hostMessage) JSON() string {
a.Status = "success"
jsonMessageBytes, e := json.Marshal(a)
func (h hostMessage) JSON() string {
h.Status = "success"
jsonMessageBytes, e := json.Marshal(h)
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(jsonMessageBytes)
}
// Validate command-line input args.
func checkConfigHostSyntax(ctx *cli.Context) {
// show help if nothing is set
if !ctx.Args().Present() || ctx.Args().First() == "help" {
if !ctx.Args().Present() {
cli.ShowCommandHelpAndExit(ctx, "host", 1) // last argument is exit code
}
if strings.TrimSpace(ctx.Args().First()) == "" {
cli.ShowCommandHelpAndExit(ctx, "host", 1) // last argument is exit code
}
if len(ctx.Args().Tail()) > 4 {
fatalIf(errDummy().Trace(ctx.Args().Tail()...), "Incorrect number of arguments to host command")
}
switch strings.TrimSpace(ctx.Args().First()) {
case "add":
checkConfigHostAddSyntax(ctx)
case "import":
checkConfigHostImportSyntax(ctx)
case "remove":
checkConfigHostRemoveSyntax(ctx)
case "list":
@@ -142,76 +131,60 @@ func checkConfigHostSyntax(ctx *cli.Context) {
}
}
// checkConfigHostImportSyntax - verifies input arguments to 'config host import'.
func checkConfigHostImportSyntax(ctx *cli.Context) {
tailArgs := ctx.Args().Tail()
if len(ctx.Args().Tail()) < 2 || len(ctx.Args().Tail()) > 3 {
fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...),
"Incorrect number of arguments for import host command.")
}
newHostURL := tailArgs.Get(0)
credentialsFile := tailArgs.Get(1)
api := tailArgs.Get(2)
if !isValidHostURL(newHostURL) {
fatalIf(errDummy().Trace(newHostURL),
"Invalid host ‘"+newHostURL+"’. Valid options are [http://example.test.io, https://bucket.s3.amazonaws.com].")
}
if strings.TrimSpace(credentialsFile) == "" {
fatalIf(errDummy().Trace(), "Credentials file cannot be empty.")
}
if strings.TrimSpace(api) == "" {
api = "S3v4"
}
if strings.TrimSpace(api) != "S3v2" && strings.TrimSpace(api) != "S3v4" {
fatalIf(errInvalidArgument().Trace(api),
"Unrecognized api version. Valid options are ‘[ S3v4, S3v2 ]’.")
}
}
// checkConfigHostAddSyntax - verifies input arguments to 'config host add'.
func checkConfigHostAddSyntax(ctx *cli.Context) {
tailArgs := ctx.Args().Tail()
if len(ctx.Args().Tail()) < 3 || len(ctx.Args().Tail()) > 4 {
tailsArgsNr := len(tailArgs)
if tailsArgsNr < 4 || tailsArgsNr > 5 {
fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...),
"Incorrect number of arguments for host add command.")
}
newHostURL := tailArgs.Get(0)
accessKeyID := tailArgs.Get(1)
secretAccessKey := tailArgs.Get(2)
api := tailArgs.Get(3)
if !isValidHostURL(newHostURL) {
fatalIf(errDummy().Trace(newHostURL),
"Invalid host URL: ‘"+newHostURL+"’. Valid options are [http://example.test.io, https://bucket.s3.amazonaws.com].")
alias := tailArgs.Get(0)
url := tailArgs.Get(1)
accessKey := tailArgs.Get(2)
secretKey := tailArgs.Get(3)
api := tailArgs.Get(4)
if !isValidAlias(alias) {
fatalIf(errDummy().Trace(alias), "Invalid alias ‘"+alias+"’.")
}
if !isValidKeys(accessKeyID, secretAccessKey) {
fatalIf(errInvalidArgument().Trace(accessKeyID, secretAccessKey),
"Invalid access key id/secret access key for ‘"+newHostURL+"’")
if !isValidHostURL(url) {
fatalIf(errDummy().Trace(url),
"Invalid URL ‘"+url+"’.")
}
if strings.TrimSpace(api) == "" {
api = "S3v4"
if !isValidAccessKey(accessKey) {
fatalIf(errInvalidArgument().Trace(accessKey),
"Invalid access key ‘"+accessKey+"’.")
}
if strings.TrimSpace(api) != "S3v2" && strings.TrimSpace(api) != "S3v4" {
if !isValidSecretKey(secretKey) {
fatalIf(errInvalidArgument().Trace(secretKey),
"Invalid secret key ‘"+secretKey+"’.")
}
switch api {
case "S3v2", "S3v4", "":
default:
fatalIf(errInvalidArgument().Trace(api),
"Unrecognized api version. Valid options are ‘[ S3v4, S3v2 ]’.")
"Unrecognized API signature. Valid options are ‘[ S3v4, S3v2 ]’.")
}
}
// checkConfigHostRemoveSyntax - verifies input arguments to 'config host remove'.
func checkConfigHostRemoveSyntax(ctx *cli.Context) {
tailArgs := ctx.Args().Tail()
if len(ctx.Args().Tail()) != 1 {
fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...),
fatalIf(errInvalidArgument().Trace(tailArgs...),
"Incorrect number of arguments for remove host command.")
}
if !isValidHostURL(tailArgs.Get(0)) {
if !isValidAlias(tailArgs.Get(0)) {
fatalIf(errDummy().Trace(tailArgs.Get(0)),
"Invalid host ‘"+tailArgs.Get(0)+"’. Valid options are [http://example.test.io, https://bucket.s3.amazonaws.com].")
}
if strings.TrimSpace(tailArgs.Get(0)) == "https://dl.minio.io:9000" {
fatalIf(errDummy().Trace(tailArgs.Get(0)),
"‘"+tailArgs.Get(0)+"’ is reserved hostname and cannot be removed.")
"Invalid alias ‘"+tailArgs.Get(0)+"’.")
}
}
@@ -223,102 +196,90 @@ func mainConfigHost(ctx *cli.Context) {
checkConfigHostSyntax(ctx)
// Additional command speific theme customization.
console.SetColor("Host", color.New(color.FgCyan, color.Bold))
console.SetColor("API", color.New(color.FgYellow, color.Bold))
console.SetColor("HostMessage", color.New(color.FgGreen, color.Bold))
console.SetColor("AccessKeyID", color.New(color.FgBlue, color.Bold))
console.SetColor("SecretAccessKey", color.New(color.FgRed, color.Bold))
console.SetColor("HostMessage", color.New(color.FgGreen))
console.SetColor("Alias", color.New(color.FgCyan, color.Bold))
console.SetColor("URL", color.New(color.FgCyan))
console.SetColor("AccessKey", color.New(color.FgBlue))
console.SetColor("SecretKey", color.New(color.FgBlue))
console.SetColor("API", color.New(color.FgYellow))
arg := ctx.Args().First()
tailArgs := ctx.Args().Tail()
cmd := ctx.Args().First()
args := ctx.Args().Tail()
// Switch case through commands.
switch strings.TrimSpace(arg) {
switch strings.TrimSpace(cmd) {
case "add":
hostURL := tailArgs.Get(0)
accessKeyID := tailArgs.Get(1)
secretAccessKey := tailArgs.Get(2)
api := tailArgs.Get(3)
alias := args.Get(0)
url := args.Get(1)
accessKey := args.Get(2)
secretKey := args.Get(3)
api := args.Get(4)
if strings.TrimSpace(api) == "" {
api = "S3v4"
}
hostCfg := hostConfig{
AccessKeyID: accessKeyID,
SecretAccessKey: secretAccessKey,
API: api,
hostCfg := hostConfigV7{
URL: url,
AccessKey: accessKey,
SecretKey: secretKey,
API: api,
}
addHost(hostURL, hostCfg) // Add a host with specified credentials.
case "import":
hostURL := tailArgs.Get(0)
credentialsFile := tailArgs.Get(1)
api := tailArgs.Get(2)
if strings.TrimSpace(api) == "" {
api = "S3v4"
}
creds, err := getCredentials(credentialsFile)
fatalIf(err.Trace(credentialsFile), "Unable to unmarshal CSV credentials file ‘"+credentialsFile+"’")
var hostCfg hostConfig
hostCfg = hostConfig{
AccessKeyID: creds[0].AccessKeyID,
SecretAccessKey: creds[0].SecretAccessKey,
API: api,
}
addHost(hostURL, hostCfg) // Import credentials through a CSV file for a host.
addHost(alias, hostCfg) // Add a host with specified credentials.
case "remove":
hostURL := tailArgs.Get(0)
removeHost(hostURL) // Remove a host.
alias := args.Get(0)
removeHost(alias) // Remove a host.
case "list":
listHosts() // List all configured hosts.
}
}
// addHost - add a host config.
func addHost(hostURL string, hostCfg hostConfig) {
conf, err := loadMcConfig()
fatalIf(err.Trace(globalMCConfigVersion), "Unable to load config version ‘"+globalMCConfigVersion+"’.")
func addHost(alias string, hostCfgV7 hostConfigV7) {
mcCfgV7, err := loadMcConfig()
fatalIf(err.Trace(globalMCConfigVersion), "Unable to load config ‘"+mustGetMcConfigPath()+"’.")
// Add new host.
conf.Hosts[hostURL] = hostCfg
mcCfgV7.Hosts[alias] = hostCfgV7
err = saveMcConfig(conf)
fatalIf(err.Trace(hostURL), "Unable to update hosts in config version ‘"+globalMCConfigVersion+"’.")
err = saveMcConfig(mcCfgV7)
fatalIf(err.Trace(alias), "Unable to update hosts in config version ‘"+mustGetMcConfigPath()+"’.")
printMsg(hostMessage{
op: "add",
Host: hostURL,
AccessKeyID: hostCfg.AccessKeyID,
SecretAccessKey: hostCfg.SecretAccessKey,
API: hostCfg.API,
op: "add",
Alias: alias,
URL: hostCfgV7.URL,
AccessKey: hostCfgV7.AccessKey,
SecretKey: hostCfgV7.SecretKey,
API: hostCfgV7.API,
})
}
// removeHost - removes a host.
func removeHost(hostURL string) {
func removeHost(alias string) {
conf, err := loadMcConfig()
fatalIf(err.Trace(globalMCConfigVersion), "Unable to load config version ‘"+globalMCConfigVersion+"’.")
// Remove host.
delete(conf.Hosts, hostURL)
delete(conf.Hosts, alias)
err = saveMcConfig(conf)
fatalIf(err.Trace(hostURL), "Unable to save deleted hosts in config version ‘"+globalMCConfigVersion+"’.")
fatalIf(err.Trace(alias), "Unable to save deleted hosts in config version ‘"+globalMCConfigVersion+"’.")
printMsg(hostMessage{op: "remove", Host: hostURL})
printMsg(hostMessage{op: "remove", Alias: alias})
}
// listHosts - list all host URLs.
func listHosts() {
conf, err := loadMcConfig()
fatalIf(err.Trace(globalMCConfigVersion), "Unable to load config version ‘"+globalMCConfigVersion+"’")
fatalIf(err.Trace(globalMCConfigVersion), "Unable to load config version ‘"+globalMCConfigVersion+"’.")
for k, v := range conf.Hosts {
printMsg(hostMessage{
op: "list",
Host: k,
AccessKeyID: v.AccessKeyID,
SecretAccessKey: v.SecretAccessKey,
API: v.API,
op: "list",
Alias: k,
URL: v.URL,
AccessKey: v.AccessKey,
SecretKey: v.SecretKey,
API: v.API,
})
}
}
-2
View File
@@ -44,9 +44,7 @@ var configCmd = cli.Command{
Action: mainConfig,
Flags: append(configFlags, globalFlags...),
Subcommands: []cli.Command{
configAliasCmd,
configHostCmd,
configVersionCmd,
},
CustomHelpTemplate: `NAME:
{{.Name}} - {{.Usage}}
+273 -473
View File
@@ -17,13 +17,14 @@
package main
import (
"fmt"
"strings"
"github.com/minio/mc/pkg/client"
"github.com/minio/mc/pkg/console"
"github.com/minio/minio-xl/pkg/quick"
)
// migrate config files from the any older version to the latest.
func migrateConfig() {
// Migrate config V1 to V101
migrateConfigV1ToV101()
@@ -37,544 +38,343 @@ func migrateConfig() {
migrateConfigV4ToV5()
// Migrate config V5 to V6
migrateConfigV5ToV6()
// Migrate config V6 to V7
migrateConfigV6ToV7()
}
func fixConfig() {
// Fix config V3
fixConfigV3()
// Fix config V6
fixConfigV6()
// Fix config V6 for hosts
fixConfigV6ForHosts()
}
func fixConfigV6ForHosts() {
if !isMcConfigExists() {
return
}
config, err := quick.New(newConfigV6())
fatalIf(err.Trace(), "Unable to initialize config.")
err = config.Load(mustGetMcConfigPath())
fatalIf(err.Trace(), "Unable to load config.")
if config.Data().(*configV6).Version == "6" {
newConfig := new(configV6)
newConfig.Aliases = make(map[string]string)
newConfig.Hosts = make(map[string]hostConfig)
newConfig.Version = "6"
newConfig.Aliases = config.Data().(*configV6).Aliases
url := new(client.URL)
for host, hostCfg := range config.Data().(*configV6).Hosts {
// Already fixed - move on.
if strings.HasPrefix(host, "https") || strings.HasPrefix(host, "http") {
newConfig.Hosts[host] = hostCfg
continue
}
if host == "s3.amazonaws.com" || host == "storage.googleapis.com" {
console.Infoln("Found hosts, replacing " + host + " with https://" + host)
url.Host = host
url.Scheme = "https"
url.SchemeSeparator = "://"
newConfig.Hosts[url.String()] = hostCfg
delete(newConfig.Hosts, host)
}
if host == "localhost:9000" || host == "127.0.0.1:9000" {
console.Infoln("Found hosts, replacing " + host + " with http://" + host)
url.Host = host
url.Scheme = "http"
url.SchemeSeparator = "://"
newConfig.Hosts[url.String()] = hostCfg
delete(newConfig.Hosts, host)
}
if host == "play.minio.io:9000" || host == "dl.minio.io:9000" {
console.Infoln("Found hosts, replacing " + host + " with https://" + host)
url.Host = host
url.Scheme = "https"
url.SchemeSeparator = "://"
newConfig.Hosts[url.String()] = hostCfg
delete(newConfig.Hosts, host)
}
}
newConf, err := quick.New(newConfig)
fatalIf(err.Trace(), "Unable to initialize newly fixed config.")
err = newConf.Save(mustGetMcConfigPath())
fatalIf(err.Trace(mustGetMcConfigPath()), "Unable to save newly fixed config path.")
}
}
// fixConfigV6 - fix all the unnecessary glob URLs present in existing config version 6.
func fixConfigV6() {
if !isMcConfigExists() {
return
}
config, err := quick.New(newConfigV6())
fatalIf(err.Trace(), "Unable to initialize config.")
err = config.Load(mustGetMcConfigPath())
fatalIf(err.Trace(mustGetMcConfigPath()), "Unable to load config.")
if config.Data().(*configV6).Version == "6" {
newConfig := new(configV6)
newConfig.Aliases = make(map[string]string)
newConfig.Hosts = make(map[string]hostConfig)
newConfig.Version = "6"
newConfig.Aliases = config.Data().(*configV6).Aliases
for host, hostCfg := range config.Data().(*configV6).Hosts {
if strings.HasPrefix(host, "https") || strings.HasPrefix(host, "http") {
newConfig.Hosts[host] = hostCfg
continue
}
if strings.Contains(host, "*s3*") || strings.Contains(host, "*.s3*") {
console.Infoln("Found glob url, replacing " + host + " with s3.amazonaws.com")
newConfig.Hosts["s3.amazonaws.com"] = hostCfg
continue
}
if strings.Contains(host, "s3*") {
console.Infoln("Found glob url, replacing " + host + " with s3.amazonaws.com")
newConfig.Hosts["s3.amazonaws.com"] = hostCfg
continue
}
if strings.Contains(host, "*amazonaws.com") || strings.Contains(host, "*.amazonaws.com") {
console.Infoln("Found glob url, replacing " + host + " with s3.amazonaws.com")
newConfig.Hosts["s3.amazonaws.com"] = hostCfg
continue
}
if strings.Contains(host, "*storage.googleapis.com") {
console.Infoln("Found glob url, replacing " + host + " with storage.googleapis.com")
newConfig.Hosts["storage.googleapis.com"] = hostCfg
continue
}
if strings.Contains(host, "localhost:*") {
console.Infoln("Found glob url, replacing " + host + " with localhost:9000")
newConfig.Hosts["localhost:9000"] = hostCfg
continue
}
if strings.Contains(host, "127.0.0.1:*") {
console.Infoln("Found glob url, replacing " + host + " with 127.0.0.1:9000")
newConfig.Hosts["127.0.0.1:9000"] = hostCfg
continue
}
newConfig.Hosts[host] = hostCfg
}
newConf, err := quick.New(newConfig)
fatalIf(err.Trace(), "Unable to initialize newly fixed config.")
err = newConf.Save(mustGetMcConfigPath())
fatalIf(err.Trace(mustGetMcConfigPath()), "Unable to save newly fixed config path.")
}
}
type configV5 struct {
Version string `json:"version"`
Aliases map[string]string `json:"alias"`
Hosts map[string]hostConfig `json:"hosts"`
}
type configV4 struct {
Version string `json:"version"`
Aliases map[string]string `json:"alias"`
Hosts map[string]struct {
AccessKeyID string `json:"accessKeyId"`
SecretAccessKey string `json:"secretAccessKey"`
Signature string `json:"signature"`
} `json:"hosts"`
}
type configV3 struct {
Version string `json:"version"`
Aliases map[string]string `json:"alias"`
// custom anonymous struct is necessary from version to 3 to version 4
// since hostConfig{} has changed to camelcase fields for unmarshal
Hosts map[string]struct {
AccessKeyID string `json:"access-key-id"`
SecretAccessKey string `json:"secret-access-key"`
} `json:"hosts"`
}
type configV2 struct {
Version string
Aliases map[string]string
// custom anonymous struct is necessary from version to 2 to version 3
// since hostConfig{} has changed to lower case fields for unmarshal
Hosts map[string]struct {
AccessKeyID string
SecretAccessKey string
}
}
// for backward compatibility
type configV101 configV2
type configV1 configV2
// Migrate from config version ‘1.0’ to ‘1.0.1’
// Migrate from config version 1.0 to 1.0.1. Populate example entries and save it back.
func migrateConfigV1ToV101() {
if !isMcConfigExists() {
return
}
mcConfigV1, err := quick.Load(mustGetMcConfigPath(), newConfigV1())
mcCfgV1, err := quick.Load(mustGetMcConfigPath(), newConfigV1())
fatalIf(err.Trace(), "Unable to load config version ‘1’.")
// update to newer version
if mcConfigV1.Version() == "1.0.0" {
confV101 := mcConfigV1.Data().(*configV1)
confV101.Version = "1.0.1"
localHostConfig := struct {
AccessKeyID string
SecretAccessKey string
}{}
localHostConfig.AccessKeyID = ""
localHostConfig.SecretAccessKey = ""
s3HostConf := struct {
AccessKeyID string
SecretAccessKey string
}{}
s3HostConf.AccessKeyID = globalAccessKeyID
s3HostConf.SecretAccessKey = globalSecretAccessKey
if _, ok := confV101.Hosts["localhost:*"]; !ok {
confV101.Hosts["localhost:*"] = localHostConfig
}
if _, ok := confV101.Hosts["127.0.0.1:*"]; !ok {
confV101.Hosts["127.0.0.1:*"] = localHostConfig
}
if _, ok := confV101.Hosts["*.s3*.amazonaws.com"]; !ok {
confV101.Hosts["*.s3*.amazonaws.com"] = s3HostConf
}
mcNewConfigV101, err := quick.New(confV101)
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘1.0.1’.")
err = mcNewConfigV101.Save(mustGetMcConfigPath())
fatalIf(err.Trace(), "Unable to save config version ‘1.0.1’.")
console.Infof("Successfully migrated %s from version ‘1.0.0’ to version ‘1.0.1’.\n", mustGetMcConfigPath())
// If loaded config version does not match 1.0.0, we do nothing.
if mcCfgV1.Version() != "1.0.0" {
return
}
// 1.0.1 is compatible to 1.0.0. We are just adding new entries.
cfgV101 := newConfigV101()
// Copy aliases.
for k, v := range mcCfgV1.Data().(*configV1).Aliases {
cfgV101.Aliases[k] = v
}
// Copy hosts.
for k, hostCfgV1 := range mcCfgV1.Data().(*configV1).Hosts {
cfgV101.Hosts[k] = hostConfigV101{
AccessKeyID: hostCfgV1.AccessKeyID,
SecretAccessKey: hostCfgV1.SecretAccessKey,
}
}
// Example localhost entry.
if _, ok := cfgV101.Hosts["localhost:*"]; !ok {
cfgV101.Hosts["localhost:*"] = hostConfigV101{}
}
// Example loopback IP entry.
if _, ok := cfgV101.Hosts["127.0.0.1:*"]; !ok {
cfgV101.Hosts["127.0.0.1:*"] = hostConfigV101{}
}
// Example AWS entry.
// Look for glob string (not glob match). We used to support glob based key matching earlier.
if _, ok := cfgV101.Hosts["*.s3*.amazonaws.com"]; !ok {
cfgV101.Hosts["*.s3*.amazonaws.com"] = hostConfigV101{
AccessKeyID: "YOUR-ACCESS-KEY-ID-HERE",
SecretAccessKey: "YOUR-SECRET-ACCESS-KEY-HERE",
}
}
// Save the new config back to the disk.
mcCfgV101, err := quick.New(cfgV101)
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘1.0.1’.")
err = mcCfgV101.Save(mustGetMcConfigPath())
fatalIf(err.Trace(), "Unable to save config version ‘1.0.1’.")
console.Infof("Successfully migrated %s from version ‘1.0.0’ to version ‘1.0.1’.\n", mustGetMcConfigPath())
}
// Migrate from config ‘1.0.1’ to ‘2’
// Migrate from config ‘1.0.1’ to ‘2’. Drop semantic versioning and move to integer versioning. No other changes.
func migrateConfigV101ToV2() {
if !isMcConfigExists() {
return
}
mcConfigV101, err := quick.Load(mustGetMcConfigPath(), newConfigV101())
mcCfgV101, err := quick.Load(mustGetMcConfigPath(), newConfigV101())
fatalIf(err.Trace(), "Unable to load config version ‘1.0.1’.")
// update to newer version
if mcConfigV101.Version() == "1.0.1" {
confV2 := mcConfigV101.Data().(*configV101)
confV2.Version = "2"
mcNewConfigV2, err := quick.New(confV2)
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘2’.")
err = mcNewConfigV2.Save(mustGetMcConfigPath())
fatalIf(err.Trace(), "Unable to save config version ‘2’.")
console.Infof("Successfully migrated %s from version ‘1.0.1’ to version ‘2’.\n", mustGetMcConfigPath())
if mcCfgV101.Version() != "1.0.1" {
return
}
cfgV2 := newConfigV2()
// Copy aliases.
for k, v := range mcCfgV101.Data().(*configV101).Aliases {
cfgV2.Aliases[k] = v
}
// Copy hosts.
for k, hostCfgV101 := range mcCfgV101.Data().(*configV101).Hosts {
cfgV2.Hosts[k] = hostConfigV2{
AccessKeyID: hostCfgV101.AccessKeyID,
SecretAccessKey: hostCfgV101.SecretAccessKey,
}
}
mcCfgV2, err := quick.New(cfgV2)
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘2’.")
err = mcCfgV2.Save(mustGetMcConfigPath())
fatalIf(err.Trace(), "Unable to save config version ‘2’.")
console.Infof("Successfully migrated %s from version ‘1.0.1’ to version ‘2’.\n", mustGetMcConfigPath())
}
// Migrate from config ‘2’ to ‘3’
// Migrate from config ‘2’ to ‘3’. Use ‘-’ separated names for
// hostConfig using struct json tags.
func migrateConfigV2ToV3() {
if !isMcConfigExists() {
return
}
mcConfigV2, err := quick.Load(mustGetMcConfigPath(), newConfigV2())
mcCfgV2, err := quick.Load(mustGetMcConfigPath(), newConfigV2())
fatalIf(err.Trace(), "Unable to load mc config V2.")
// update to newer version
if mcConfigV2.Version() == "2" {
confV3 := new(configV3)
confV3.Aliases = mcConfigV2.Data().(*configV2).Aliases
confV3.Hosts = make(map[string]struct {
AccessKeyID string `json:"access-key-id"`
SecretAccessKey string `json:"secret-access-key"`
})
for host, hostConf := range mcConfigV2.Data().(*configV2).Hosts {
newHostConf := struct {
AccessKeyID string `json:"access-key-id"`
SecretAccessKey string `json:"secret-access-key"`
}{}
newHostConf.AccessKeyID = hostConf.AccessKeyID
newHostConf.SecretAccessKey = hostConf.SecretAccessKey
confV3.Hosts[host] = newHostConf
}
confV3.Version = "3"
mcNewConfigV3, err := quick.New(confV3)
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘3’.")
err = mcNewConfigV3.Save(mustGetMcConfigPath())
fatalIf(err.Trace(), "Unable to save config version ‘3’.")
console.Infof("Successfully migrated %s from version ‘2’ to version ‘3’.\n", mustGetMcConfigPath())
if mcCfgV2.Version() != "2" {
return
}
cfgV3 := newConfigV3()
// Copy aliases.
for k, v := range mcCfgV2.Data().(*configV2).Aliases {
cfgV3.Aliases[k] = v
}
// Copy hosts.
for k, hostCfgV2 := range mcCfgV2.Data().(*configV2).Hosts {
// New hostConfV3 uses struct json tags.
cfgV3.Hosts[k] = hostConfigV3{
AccessKeyID: hostCfgV2.AccessKeyID,
SecretAccessKey: hostCfgV2.SecretAccessKey,
}
}
mcNewCfgV3, err := quick.New(cfgV3)
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘3’.")
err = mcNewCfgV3.Save(mustGetMcConfigPath())
fatalIf(err.Trace(), "Unable to save config version ‘3’.")
console.Infof("Successfully migrated %s from version ‘2’ to version ‘3’.\n", mustGetMcConfigPath())
}
// Migrate from config version ‘3’ to ‘4’
// Migrate from config version ‘3’ to ‘4’. Introduce API Signature
// field in host config. Also Use JavaScript notation for field names.
func migrateConfigV3ToV4() {
if !isMcConfigExists() {
return
}
mcConfigV3, err := quick.Load(mustGetMcConfigPath(), newConfigV3())
mcCfgV3, err := quick.Load(mustGetMcConfigPath(), newConfigV3())
fatalIf(err.Trace(), "Unable to load mc config V2.")
// update to newer version
if mcConfigV3.Version() == "3" {
confV4 := new(configV4)
confV4.Aliases = mcConfigV3.Data().(*configV3).Aliases
confV4.Hosts = make(map[string]struct {
AccessKeyID string `json:"accessKeyId"`
SecretAccessKey string `json:"secretAccessKey"`
Signature string `json:"signature"`
})
for host, hostConf := range mcConfigV3.Data().(*configV3).Hosts {
confV4.Hosts[host] = struct {
AccessKeyID string `json:"accessKeyId"`
SecretAccessKey string `json:"secretAccessKey"`
Signature string `json:"signature"`
}{
AccessKeyID: hostConf.AccessKeyID,
SecretAccessKey: hostConf.SecretAccessKey,
Signature: "v4",
}
}
confV4.Version = "4"
mcNewConfigV4, err := quick.New(confV4)
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘4’.")
err = mcNewConfigV4.Save(mustGetMcConfigPath())
fatalIf(err.Trace(), "Unable to save config version ‘4’.")
console.Infof("Successfully migrated %s from version ‘3’ to version ‘4’.\n", mustGetMcConfigPath())
if mcCfgV3.Version() != "3" {
return
}
cfgV4 := newConfigV4()
for k, v := range mcCfgV3.Data().(*configV3).Aliases {
cfgV4.Aliases[k] = v
}
// New hostConfig has API signature. All older entries were V4
// only. So it is safe to assume V4 as default for all older
// entries.
// HostConfigV4 als uses JavaScript naming notation for struct JSON tags.
for host, hostCfgV3 := range mcCfgV3.Data().(*configV3).Hosts {
cfgV4.Hosts[host] = hostConfigV4{
AccessKeyID: hostCfgV3.AccessKeyID,
SecretAccessKey: hostCfgV3.SecretAccessKey,
Signature: "v4",
}
}
mcNewCfgV4, err := quick.New(cfgV4)
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘4’.")
err = mcNewCfgV4.Save(mustGetMcConfigPath())
fatalIf(err.Trace(), "Unable to save config version ‘4’.")
console.Infof("Successfully migrated %s from version ‘3’ to version ‘4’.\n", mustGetMcConfigPath())
}
// Migrate config version ‘4’ to ‘5’
// Migrate config version ‘4’ to ‘5’. Rename hostConfigV4.Signature -> hostConfigV5.API.
func migrateConfigV4ToV5() {
if !isMcConfigExists() {
return
}
mcConfigV4, err := quick.Load(mustGetMcConfigPath(), newConfigV4())
mcCfgV4, err := quick.Load(mustGetMcConfigPath(), newConfigV4())
fatalIf(err.Trace(), "Unable to load mc config V4.")
// update to newer version
if mcConfigV4.Version() == "4" {
confV5 := new(configV5)
confV5.Aliases = mcConfigV4.Data().(*configV4).Aliases
confV5.Hosts = make(map[string]hostConfig)
for host, hostConf := range mcConfigV4.Data().(*configV4).Hosts {
confV5.Hosts[host] = hostConfig{
AccessKeyID: hostConf.AccessKeyID,
SecretAccessKey: hostConf.SecretAccessKey,
API: "S3v4",
}
}
confV5.Version = "5"
mcNewConfigV5, err := quick.New(confV5)
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘5’.")
err = mcNewConfigV5.Save(mustGetMcConfigPath())
fatalIf(err.Trace(), "Unable to save config version ‘5’.")
console.Infof("Successfully migrated %s from version ‘4’ to version ‘5’.\n", mustGetMcConfigPath())
if mcCfgV4.Version() != "4" {
return
}
cfgV5 := newConfigV5()
for k, v := range mcCfgV4.Data().(*configV4).Aliases {
cfgV5.Aliases[k] = v
}
for host, hostCfgV4 := range mcCfgV4.Data().(*configV4).Hosts {
cfgV5.Hosts[host] = hostConfigV5{
AccessKeyID: hostCfgV4.AccessKeyID,
SecretAccessKey: hostCfgV4.SecretAccessKey,
API: "v4", // Rename from .Signature to .API
}
}
mcNewCfgV5, err := quick.New(cfgV5)
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘5’.")
err = mcNewCfgV5.Save(mustGetMcConfigPath())
fatalIf(err.Trace(), "Unable to save config version ‘5’.")
console.Infof("Successfully migrated %s from version ‘4’ to version ‘5’.\n", mustGetMcConfigPath())
}
// Migrate config version ‘4’ to ‘5’
// Migrate config version ‘5’ to ‘6’. Add google cloud storage servers
// to host config. Also remove "." from s3 aws glob rule.
func migrateConfigV5ToV6() {
if !isMcConfigExists() {
return
}
mcConfigV5, err := quick.Load(mustGetMcConfigPath(), newConfigV5())
mcCfgV5, err := quick.Load(mustGetMcConfigPath(), newConfigV5())
fatalIf(err.Trace(), "Unable to load mc config V5.")
// update to newer version
if mcConfigV5.Version() == "5" {
confV6 := new(configV6)
confV6.Aliases = mcConfigV5.Data().(*configV5).Aliases
confV6.Aliases["gcs"] = "https://storage.googleapis.com"
confV6.Hosts = make(map[string]hostConfig)
for host, hostConf := range mcConfigV5.Data().(*configV5).Hosts {
confV6.Hosts[host] = hostConfig{
AccessKeyID: hostConf.AccessKeyID,
SecretAccessKey: hostConf.SecretAccessKey,
API: hostConf.API,
}
}
var s3Conf hostConfig
for host, hostConf := range confV6.Hosts {
if strings.Contains(host, "s3") {
if (hostConf.AccessKeyID == globalAccessKeyID) ||
(hostConf.SecretAccessKey == globalSecretAccessKey) {
delete(confV6.Hosts, host)
}
if hostConf.AccessKeyID == "" || hostConf.SecretAccessKey == "" {
delete(confV6.Hosts, host)
}
s3Conf = hostConfig{
AccessKeyID: hostConf.AccessKeyID,
SecretAccessKey: hostConf.SecretAccessKey,
API: hostConf.API,
}
break
}
}
confV6.Hosts["*s3*amazonaws.com"] = s3Conf
confV6.Hosts["*storage.googleapis.com"] = hostConfig{
AccessKeyID: globalAccessKeyID,
SecretAccessKey: globalSecretAccessKey,
API: "S3v2",
}
confV6.Version = globalMCConfigVersion
mcNewConfigV6, err := quick.New(confV6)
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘6’.")
err = mcNewConfigV6.Save(mustGetMcConfigPath())
fatalIf(err.Trace(), "Unable to save config version ‘6’.")
console.Infof("Successfully migrated %s from version ‘5’ to version ‘6’.\n", mustGetMcConfigPath())
if mcCfgV5.Version() != "5" {
return
}
cfgV6 := newConfigV6()
// Add new Google Cloud Storage alias.
cfgV6.Aliases["gcs"] = "https://storage.googleapis.com"
for k, v := range mcCfgV5.Data().(*configV5).Aliases {
cfgV6.Aliases[k] = v
}
// Add defaults.
cfgV6.Hosts["*s3*amazonaws.com"] = hostConfigV6{
AccessKeyID: "YOUR-ACCESS-KEY-ID-HERE",
SecretAccessKey: "YOUR-SECRET-ACCESS-KEY-HERE",
API: "S3v4",
}
cfgV6.Hosts["*storage.googleapis.com"] = hostConfigV6{
AccessKeyID: "YOUR-ACCESS-KEY-ID-HERE",
SecretAccessKey: "YOUR-SECRET-ACCESS-KEY-HERE",
API: "S3v2",
}
for host, hostCfgV5 := range mcCfgV5.Data().(*configV5).Hosts {
// Find any matching s3 entry and copy keys from it to newer generalized glob entry.
if strings.Contains(host, "s3") {
if (hostCfgV5.AccessKeyID == "YOUR-ACCESS-KEY-ID-HERE") ||
(hostCfgV5.SecretAccessKey == "YOUR-SECRET-ACCESS-KEY-HERE") ||
hostCfgV5.AccessKeyID == "" ||
hostCfgV5.SecretAccessKey == "" {
continue // Skip defaults.
}
// Now we have real keys set by the user. Copy
// them over to newer glob rule.
// Original host entry has "." in the glob rule.
host = "*s3*amazonaws.com" // Use this glob entry.
}
cfgV6.Hosts[host] = hostConfigV6{
AccessKeyID: hostCfgV5.AccessKeyID,
SecretAccessKey: hostCfgV5.SecretAccessKey,
API: hostCfgV5.API,
}
}
mcNewCfgV6, err := quick.New(cfgV6)
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘6’.")
err = mcNewCfgV6.Save(mustGetMcConfigPath())
fatalIf(err.Trace(), "Unable to save config version ‘6’.")
console.Infof("Successfully migrated %s from version ‘5’ to version ‘6’.\n", mustGetMcConfigPath())
}
// Fix config version ‘3’, by removing broken struct tags.
func fixConfigV3() {
// Migrate config version ‘6’ to ‘7'. Remove alias map and introduce
// named Host config. Also no more glob match for host config entries.
func migrateConfigV6ToV7() {
if !isMcConfigExists() {
return
}
// brokenConfigV3 broken config between version 3.
type brokenConfigV3 struct {
Version string
ACL string
Access string
Aliases map[string]string
Hosts map[string]struct {
AccessKeyID string
SecretAccessKey string
mcCfgV6, err := quick.Load(mustGetMcConfigPath(), newConfigV6())
fatalIf(err.Trace(), "Unable to load mc config V6.")
if mcCfgV6.Version() != "6" {
return
}
cfgV7 := newConfigV7()
aliasIndex := 0
// We dropped alias support in v7. We only need to migrate host configs.
for host, hostCfgV6 := range mcCfgV6.Data().(*configV6).Hosts {
if hostCfgV6.AccessKeyID == "YOUR-ACCESS-KEY-ID-HERE" ||
hostCfgV6.SecretAccessKey == "YOUR-SECRET-ACCESS-KEY-HERE" ||
hostCfgV6.AccessKeyID == "" ||
hostCfgV6.SecretAccessKey == "" {
// Ignore default entries. configV7.loadDefaults() will re-insert them back.
} else if host == "https://s3.amazonaws.com" {
// Only one entry can exist for "s3" domain.
cfgV7.Hosts["s3"] = hostConfigV7{
URL: host,
AccessKey: hostCfgV6.AccessKeyID,
SecretKey: hostCfgV6.SecretAccessKey,
API: hostCfgV6.API,
}
} else if host == "https://storage.googleapis.com" {
// Only one entry can exist for "gcs" domain.
cfgV7.Hosts["gcs"] = hostConfigV7{
URL: host,
AccessKey: hostCfgV6.AccessKeyID,
SecretKey: hostCfgV6.SecretAccessKey,
API: hostCfgV6.API,
}
} else {
// Assign a generic "cloud1", cloud2..." key
// for all other entries that has valid keys set.
alias := fmt.Sprintf("cloud%d", aliasIndex)
aliasIndex++
cfgV7.Hosts[alias] = hostConfigV7{
URL: host,
AccessKey: hostCfgV6.AccessKeyID,
SecretKey: hostCfgV6.SecretAccessKey,
API: hostCfgV6.API,
}
}
}
conf := new(brokenConfigV3)
conf.Aliases = make(map[string]string)
conf.Hosts = make(map[string]struct {
AccessKeyID string
SecretAccessKey string
})
// Load default settings.
cfgV7.loadDefaults()
mcNewCfgV7, err := quick.New(cfgV7)
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘7’.")
mcConfigV3, err := quick.Load(mustGetMcConfigPath(), conf)
fatalIf(err.Trace(), "Unable to load config.")
err = mcNewCfgV7.Save(mustGetMcConfigPath())
fatalIf(err.Trace(), "Unable to save config version ‘7’.")
// Update to newer version.
if len(mcConfigV3.Data().(*brokenConfigV3).Aliases) != 0 || mcConfigV3.Data().(*brokenConfigV3).ACL != "" || mcConfigV3.Data().(*brokenConfigV3).Access != "" && mcConfigV3.Version() == "3" {
confV3 := new(configV3)
confV3.Aliases = mcConfigV3.Data().(*brokenConfigV3).Aliases
confV3.Hosts = make(map[string]struct {
AccessKeyID string `json:"access-key-id"`
SecretAccessKey string `json:"secret-access-key"`
})
for host, hostConf := range mcConfigV3.Data().(*brokenConfigV3).Hosts {
newHostConf := struct {
AccessKeyID string `json:"access-key-id"`
SecretAccessKey string `json:"secret-access-key"`
}{}
newHostConf.AccessKeyID = hostConf.AccessKeyID
newHostConf.SecretAccessKey = hostConf.SecretAccessKey
confV3.Hosts[host] = newHostConf
}
confV3.Version = "3"
mcNewConfigV3, err := quick.New(confV3)
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘3’.")
err = mcNewConfigV3.Save(mustGetMcConfigPath())
fatalIf(err.Trace(), "Unable to save config version ‘3’.")
console.Infof("Successfully fixed %s broken config for version ‘3’.\n", mustGetMcConfigPath())
}
}
// newConfigV1() - get new config version 1.0.0
func newConfigV1() *configV1 {
conf := new(configV1)
conf.Version = "1.0.0"
// make sure to allocate map's otherwise Golang
// exits silently without providing any errors
conf.Hosts = make(map[string]struct {
AccessKeyID string
SecretAccessKey string
})
conf.Aliases = make(map[string]string)
return conf
}
// newConfigV101() - get new config version 1.0.1
func newConfigV101() *configV101 {
conf := new(configV101)
conf.Version = "1.0.1"
// make sure to allocate map's otherwise Golang
// exits silently without providing any errors
conf.Hosts = make(map[string]struct {
AccessKeyID string
SecretAccessKey string
})
conf.Aliases = make(map[string]string)
return conf
}
// newConfigV2() - get new config version 2
func newConfigV2() *configV2 {
conf := new(configV2)
conf.Version = "2"
// make sure to allocate map's otherwise Golang
// exits silently without providing any errors
conf.Hosts = make(map[string]struct {
AccessKeyID string
SecretAccessKey string
})
conf.Aliases = make(map[string]string)
return conf
}
// newConfigV3 - get new config version 3
func newConfigV3() *configV3 {
conf := new(configV3)
conf.Version = "3"
// make sure to allocate map's otherwise Golang
// exits silently without providing any errors
conf.Hosts = make(map[string]struct {
AccessKeyID string `json:"access-key-id"`
SecretAccessKey string `json:"secret-access-key"`
})
conf.Aliases = make(map[string]string)
return conf
}
func newConfigV4() *configV4 {
conf := new(configV4)
conf.Version = "4"
// make sure to allocate map's otherwise Golang
// exits silently without providing any errors
conf.Hosts = make(map[string]struct {
AccessKeyID string `json:"accessKeyId"`
SecretAccessKey string `json:"secretAccessKey"`
Signature string `json:"signature"`
})
conf.Aliases = make(map[string]string)
return conf
}
func newConfigV5() *configV5 {
conf := new(configV5)
conf.Version = "5"
// make sure to allocate map's otherwise Golang
// exits silently without providing any errors
conf.Hosts = make(map[string]hostConfig)
conf.Aliases = make(map[string]string)
return conf
console.Infof("Successfully migrated %s from version ‘6’ to version ‘7’.\n", mustGetMcConfigPath())
}
+164
View File
@@ -0,0 +1,164 @@
/*
* Minio Client (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 main
/////////////////// Config V1 ///////////////////
type hostConfigV1 struct {
AccessKeyID string
SecretAccessKey string
}
type configV1 struct {
Version string
Aliases map[string]string
Hosts map[string]hostConfigV1
}
// newConfigV1() - get new config version 1.0.0
func newConfigV1() *configV1 {
conf := new(configV1)
conf.Version = "1.0.0"
// make sure to allocate map's otherwise Golang
// exits silently without providing any errors
conf.Aliases = make(map[string]string)
conf.Hosts = make(map[string]hostConfigV1)
return conf
}
/////////////////// Config V101 ///////////////////
type hostConfigV101 hostConfigV1
type configV101 struct {
Version string
Aliases map[string]string
Hosts map[string]hostConfigV101
}
// newConfigV101() - get new config version 1.0.1
func newConfigV101() *configV101 {
conf := new(configV101)
conf.Version = "1.0.1"
conf.Aliases = make(map[string]string)
conf.Hosts = make(map[string]hostConfigV101)
return conf
}
/////////////////// Config V2 ///////////////////
type hostConfigV2 hostConfigV1
type configV2 struct {
Version string
Aliases map[string]string
Hosts map[string]hostConfigV2
}
// newConfigV2() - get new config version 2
func newConfigV2() *configV2 {
conf := new(configV2)
conf.Version = "2"
conf.Aliases = make(map[string]string)
conf.Hosts = make(map[string]hostConfigV2)
return conf
}
/////////////////// Config V3 ///////////////////
type hostConfigV3 struct {
AccessKeyID string `json:"access-key-id"`
SecretAccessKey string `json:"secret-access-key"`
}
type configV3 struct {
Version string `json:"version"`
Aliases map[string]string `json:"alias"`
Hosts map[string]hostConfigV3 `json:"hosts"`
}
// newConfigV3 - get new config version 3.
func newConfigV3() *configV3 {
conf := new(configV3)
conf.Version = "3"
conf.Aliases = make(map[string]string)
conf.Hosts = make(map[string]hostConfigV3)
return conf
}
/////////////////// Config V4 ///////////////////
type hostConfigV4 struct {
AccessKeyID string `json:"accessKeyId"`
SecretAccessKey string `json:"secretAccessKey"`
Signature string `json:"signature"`
}
type configV4 struct {
Version string `json:"version"`
Aliases map[string]string `json:"alias"`
Hosts map[string]hostConfigV4 `json:"hosts"`
}
func newConfigV4() *configV4 {
conf := new(configV4)
conf.Version = "4"
conf.Aliases = make(map[string]string)
conf.Hosts = make(map[string]hostConfigV4)
return conf
}
/////////////////// Config V5 ///////////////////
type hostConfigV5 struct {
AccessKeyID string `json:"accessKeyId"`
SecretAccessKey string `json:"secretAccessKey"`
API string `json:"api"`
}
type configV5 struct {
Version string `json:"version"`
Aliases map[string]string `json:"alias"`
Hosts map[string]hostConfigV5 `json:"hosts"`
}
func newConfigV5() *configV5 {
conf := new(configV5)
conf.Version = "5"
conf.Aliases = make(map[string]string)
conf.Hosts = make(map[string]hostConfigV5)
return conf
}
/////////////////// Config V6 ///////////////////
type hostConfigV6 struct {
AccessKeyID string `json:"accessKeyId"`
SecretAccessKey string `json:"secretAccessKey"`
API string `json:"api"`
}
type configV6 struct {
Version string `json:"version"`
Aliases map[string]string `json:"alias"`
Hosts map[string]hostConfigV6 `json:"hosts"`
}
// newConfigV6 - new config version '6'.
func newConfigV6() *configV6 {
conf := new(configV6)
conf.Version = "6"
conf.Aliases = make(map[string]string)
conf.Hosts = make(map[string]hostConfigV6)
return conf
}
/////////////////// Config V7 ///////////////////
// RESERVED FOR FUTURE
+6 -14
View File
@@ -8,29 +8,21 @@ import (
)
// isValidSecretKey - validate secret key.
func isValidSecretKey(secretAccessKey string) bool {
if secretAccessKey == "" {
func isValidSecretKey(secretKey string) bool {
if secretKey == "" {
return true
}
regex := regexp.MustCompile("^.{40}$")
return regex.MatchString(secretAccessKey)
return regex.MatchString(secretKey)
}
// isValidAccessKey - validate access key.
func isValidAccessKey(accessKeyID string) bool {
if accessKeyID == "" {
func isValidAccessKey(accessKey string) bool {
if accessKey == "" {
return true
}
regex := regexp.MustCompile("^[A-Z0-9\\-\\.\\_\\~]{20}$")
return regex.MatchString(accessKeyID)
}
// isValidKeys validates both access and secret key.
func isValidKeys(accessKeyID, secretAccessKey string) bool {
if isValidAccessKey(accessKeyID) && isValidSecretKey(secretAccessKey) {
return true
}
return false
return regex.MatchString(accessKey)
}
// isValidHostURL - validate input host url.
-142
View File
@@ -1,142 +0,0 @@
/*
* Minio Client (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 main
import (
"sync"
"github.com/minio/minio-xl/pkg/probe"
"github.com/minio/minio-xl/pkg/quick"
)
// configV6 config version '6'.
type configV6 struct {
Version string `json:"version"`
Aliases map[string]string `json:"alias"`
Hosts map[string]hostConfig `json:"hosts"`
}
// cached variables should *NEVER* be accessed directly from outside this file.
var cache sync.Pool
// newConfigV6 - new config version '6'.
func newConfigV6() *configV6 {
conf := new(configV6)
conf.Version = globalMCConfigVersion
// make sure to allocate map's otherwise Golang
// exits silently without providing any errors.
conf.Hosts = make(map[string]hostConfig)
conf.Aliases = make(map[string]string)
localHostConfig := hostConfig{
AccessKeyID: "",
SecretAccessKey: "",
API: "S3v4",
}
s3HostConf := hostConfig{
AccessKeyID: globalAccessKeyID,
SecretAccessKey: globalSecretAccessKey,
API: "S3v4",
}
googlHostConf := hostConfig{
AccessKeyID: globalAccessKeyID,
SecretAccessKey: globalSecretAccessKey,
API: "S3v2",
}
// Your example host config.
exampleHostConf := hostConfig{
AccessKeyID: globalAccessKeyID,
SecretAccessKey: globalSecretAccessKey,
API: "S3v4",
}
playHostConfig := hostConfig{
AccessKeyID: "",
SecretAccessKey: "",
API: "S3v4",
}
dlHostConfig := hostConfig{
AccessKeyID: "",
SecretAccessKey: "",
API: "S3v4",
}
conf.Hosts[globalExampleHostURL] = exampleHostConf
conf.Hosts["http://localhost:9000"] = localHostConfig
conf.Hosts["https://dl.minio.io:9000"] = dlHostConfig
conf.Hosts["https://s3.amazonaws.com"] = s3HostConf
conf.Hosts["https://play.minio.io:9000"] = playHostConfig
conf.Hosts["https://storage.googleapis.com"] = googlHostConf
aliases := make(map[string]string)
aliases["s3"] = "https://s3.amazonaws.com"
aliases["dl"] = "https://dl.minio.io:9000"
aliases["gcs"] = "https://storage.googleapis.com"
aliases["play"] = "https://play.minio.io:9000"
aliases["local"] = "http://localhost:9000"
conf.Aliases = aliases
return conf
}
// saveConfigV6 - saves an updated config.
func saveConfigV6(config *configV6) *probe.Error {
qs, err := quick.New(config)
if err != nil {
return err.Trace()
}
return qs.Save(mustGetMcConfigPath()).Trace(mustGetMcConfigPath())
}
// loadConfigV6 - loads a new config.
func loadConfigV6() (*configV6, *probe.Error) {
if !isMcConfigExists() {
return nil, errInvalidArgument().Trace()
}
configFile, err := getMcConfigPath()
if err != nil {
return nil, err.Trace()
}
// Cached in private global variable.
if v := cache.Get(); v != nil { // Use previously cached config.
return v.(*configV6), nil
}
conf := new(configV6)
conf.Version = globalMCConfigVersion
qconf, err := quick.New(conf)
if err != nil {
return nil, err.Trace()
}
err = qconf.Load(configFile)
if err != nil {
return nil, err.Trace()
}
config := qconf.Data().(*configV6)
// Save in sync pool.
cache.Put(config)
return config, nil
}
+157
View File
@@ -0,0 +1,157 @@
/*
* Minio Client (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 main
import (
"sync"
"github.com/minio/minio-xl/pkg/probe"
"github.com/minio/minio-xl/pkg/quick"
)
const (
defaultAccessKey = "YOUR-ACCESS-KEY-HERE"
defaultSecretKey = "YOUR-SECRET-KEY-HERE"
)
var (
// set once during first load.
cacheCfgV7 *configV7
// All access to mc config file should be synchronized.
cfgMutex = &sync.RWMutex{}
)
// hostConfig configuration of a host.
type hostConfigV7 struct {
URL string `json:"url"`
AccessKey string `json:"accessKey"`
SecretKey string `json:"secretKey"`
API string `json:"api"`
}
// configV7 config version.
type configV7 struct {
Version string `json:"version"`
Hosts map[string]hostConfigV7 `json:"hosts"`
}
// newConfigV7 - new config version.
func newConfigV7() *configV7 {
cfg := new(configV7)
cfg.Version = globalMCConfigVersion
cfg.Hosts = make(map[string]hostConfigV7)
return cfg
}
// SetHost sets host config if not empty.
func (c *configV7) setHost(alias string, cfg hostConfigV7) {
if _, ok := c.Hosts[alias]; !ok {
c.Hosts[alias] = cfg
}
}
// load default values for missing entries.
func (c *configV7) loadDefaults() {
// Minio server running locally.
c.setHost("local", hostConfigV7{
URL: "http://localhost:9000",
AccessKey: "",
SecretKey: "",
API: "S3v4",
})
// Amazon S3 cloud storage service.
c.setHost("s3", hostConfigV7{
URL: "https://s3.amazonaws.com",
AccessKey: defaultAccessKey,
SecretKey: defaultSecretKey,
API: "S3v4",
})
// Google cloud storage service.
c.setHost("gcs", hostConfigV7{
URL: "https://storage.googleapis.com",
AccessKey: defaultAccessKey,
SecretKey: defaultSecretKey,
API: "S3v2",
})
// Minio anonymous server for demo.
c.setHost("play", hostConfigV7{
URL: "https://play.minio.io:9000",
AccessKey: "",
SecretKey: "",
API: "S3v4",
})
// Minio demo server with public secret and access keys.
c.setHost("player", hostConfigV7{
URL: "https://play.minio.io:9002",
AccessKey: "Q3AM3UQ867SPQQA43P2F",
SecretKey: "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG",
API: "S3v4",
})
// Minio public download service.
c.setHost("dl", hostConfigV7{
URL: "https://dl.minio.io:9000",
AccessKey: "",
SecretKey: "",
API: "S3v4",
})
}
// loadConfigV7 - loads a new config.
func loadConfigV7() (*configV7, *probe.Error) {
cfgMutex.RLock()
defer cfgMutex.RUnlock()
// Cached in private global variable.
if cacheCfgV7 != nil {
return cacheCfgV7, nil
}
if !isMcConfigExists() {
return nil, errInvalidArgument().Trace()
}
mcCfgV7, err := quick.Load(mustGetMcConfigPath(), newConfigV7())
fatalIf(err.Trace(), "Unable to load mc config file ‘"+mustGetMcConfigPath()+"’.")
cfgV7 := mcCfgV7.Data().(*configV7)
// cache it.
cacheCfgV7 = cfgV7
return cfgV7, nil
}
// saveConfigV7 - saves an updated config.
func saveConfigV7(cfgV7 *configV7) *probe.Error {
cfgMutex.Lock()
defer cfgMutex.Unlock()
qs, err := quick.New(cfgV7)
if err != nil {
return err.Trace()
}
// update the cache.
cacheCfgV7 = cfgV7
return qs.Save(mustGetMcConfigPath()).Trace(mustGetMcConfigPath())
}
-69
View File
@@ -1,69 +0,0 @@
/*
* Minio Client (C) 2014, 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 main
import (
"encoding/json"
"github.com/minio/cli"
"github.com/minio/mc/pkg/console"
"github.com/minio/minio-xl/pkg/probe"
)
var (
configVersionFlags = []cli.Flag{
cli.BoolFlag{
Name: "help, h",
Usage: "Help of config version",
},
}
)
// Print config version.
var configVersionCmd = cli.Command{
Name: "version",
Usage: "Print config version.",
Action: mainConfigVersion,
Flags: append(configVersionFlags, globalFlags...),
CustomHelpTemplate: `NAME:
mc config {{.Name}} - {{.Usage}}
USAGE:
mc config {{.Name}}
`,
}
func mainConfigVersion(ctx *cli.Context) {
// Set global flags from context.
setGlobalsFromContext(ctx)
config, err := loadMcConfig()
fatalIf(err.Trace(), "Unable to load config version ‘"+globalMCConfigVersion+"’.")
type Version string
if globalJSON {
tB, e := json.Marshal(
struct {
Version Version `json:"version"`
}{Version: Version(config.Version)},
)
fatalIf(probe.NewError(e), "Unable to construct version string.")
console.Println(string(tB))
return
}
console.Println(config.Version)
}
+75 -13
View File
@@ -19,6 +19,7 @@ package main
import (
"os"
"path/filepath"
"regexp"
"runtime"
"github.com/minio/minio-xl/pkg/probe"
@@ -68,8 +69,8 @@ func createMcConfigDir() *probe.Error {
if err != nil {
return err.Trace()
}
if err := os.MkdirAll(p, 0700); err != nil {
return probe.NewError(err)
if e := os.MkdirAll(p, 0700); e != nil {
return probe.NewError(e)
}
return nil
}
@@ -95,29 +96,44 @@ func mustGetMcConfigPath() string {
}
// newMcConfig - initializes a new version '6' config.
func newMcConfig() *configV6 {
return newConfigV6()
func newMcConfig() *configV7 {
cfg := newConfigV7()
cfg.loadDefaults()
return cfg
}
// loadMcConfig - reads configuration file and returns config.
func loadMcConfig() (*configV6, *probe.Error) {
conf, err := loadConfigV6()
if err != nil {
return nil, err.Trace()
// loadMcConfigCached - returns loadMcConfig with a closure for config cache.
func loadMcConfigFactory() func() (*configV7, *probe.Error) {
// Load once and cache in a closure.
cfgCache, err := loadConfigV7()
// loadMcConfig - reads configuration file and returns config.
return func() (*configV7, *probe.Error) {
return cfgCache, err
}
return conf, nil
}
var loadMcConfig = loadMcConfigFactory()
// saveMcConfig - saves configuration file and returns error if any.
func saveMcConfig(config *configV6) *probe.Error {
func saveMcConfig(config *configV7) *probe.Error {
if config == nil {
return errInvalidArgument().Trace()
}
err := createMcConfigDir()
if err != nil {
return err.Trace(mustGetMcConfigDir())
}
return saveConfigV6(config).Trace(mustGetMcConfigPath())
// Save the config.
if err := saveConfigV7(config); err != nil {
return err.Trace(mustGetMcConfigPath())
}
// Refresh the config cache.
loadMcConfig = loadMcConfigFactory()
return nil
}
// isMcConfigExists returns err if config doesn't exist.
@@ -126,8 +142,54 @@ func isMcConfigExists() bool {
if err != nil {
return false
}
if _, err := os.Stat(configFile); err != nil {
if _, e := os.Stat(configFile); e != nil {
return false
}
return true
}
// isValidAlias - Check if alias valid.
func isValidAlias(alias string) bool {
return regexp.MustCompile("^[a-zA-Z][a-zA-Z0-9-]+$").MatchString(alias)
}
// getHostConfig retrieves host specific configuration such as access keys, signature type.
func getHostConfig(alias string) (*hostConfigV7, *probe.Error) {
mcCfg, err := loadMcConfig()
if err != nil {
return nil, err.Trace(alias)
}
// if host is exact return quickly.
if _, ok := mcCfg.Hosts[alias]; ok {
hostCfg := mcCfg.Hosts[alias]
return &hostCfg, nil
}
// return error if cannot be matched.
return nil, errNoMatchingHost(alias).Trace(alias)
}
// mustGetHostConfig retrieves host specific configuration such as access keys, signature type.
func mustGetHostConfig(alias string) *hostConfigV7 {
hostCfg, _ := getHostConfig(alias)
return hostCfg
}
// expandAlias expands aliased URL if any match is found, returns as is otherwise.
func expandAlias(aliasedURL string) (alias string, urlStr string, hostCfg *hostConfigV7, err *probe.Error) {
// Extract alias from the URL.
alias, path := url2Alias(aliasedURL)
// Find the matching alias entry and expand the URL.
if hostCfg = mustGetHostConfig(alias); hostCfg != nil {
return alias, urlJoinPath(hostCfg.URL, path), hostCfg, nil
}
return "", aliasedURL, nil, nil // No matching entry found. Return original URL as is.
}
// mustExpandAlias expands aliased URL if any match is found, returns as is otherwise.
func mustExpandAlias(aliasedURL string) (alias string, urlStr string, hostCfg *hostConfigV7) {
alias, urlStr, hostCfg, _ = expandAlias(aliasedURL)
return alias, urlStr, hostCfg
}
+109 -122
View File
@@ -21,9 +21,8 @@ import (
"encoding/json"
"fmt"
"io"
"math"
"os"
"runtime"
"path/filepath"
"strings"
"sync"
"syscall"
@@ -67,16 +66,16 @@ FLAGS:
{{end}}
EXAMPLES:
1. Copy a list of objects from local file system to Amazon S3 cloud storage.
$ mc {{.Name}} Music/*.ogg s3.amazonaws.com/jukebox/
$ mc {{.Name}} Music/*.ogg s3/jukebox/
2. Copy a folder recursively from Minio cloud storage to Amazon S3 cloud storage.
$ mc {{.Name}} --recursive play.minio.io:9000/mybucket/burningman2011/ s3.amazonaws.com/mybucket/
$ mc {{.Name}} --recursive play/mybucket/burningman2011/ s3/mybucket/
3. Copy multiple local folders recursively to Minio cloud storage.
$ mc {{.Name}} --recursive backup/2014/ backup/2015/ play.minio.io:9000/archive/
$ mc {{.Name}} --recursive backup/2014/ backup/2015/ play/archive/
4. Copy a bucket recursively from aliased Amazon S3 cloud storage to local filesystem on Windows.
$ mc {{.Name}} --recursive s3/documents/2014/ C:\Backups\2014
$ mc {{.Name}} --recursive s3\documents\2014\ C:\Backups\2014
5. Copy an object with name containing unicode characters to Amazon S3 cloud storage.
$ mc {{.Name}} 本語 s3/andoria/
@@ -91,7 +90,6 @@ type copyMessage struct {
Status string `json:"status"`
Source string `json:"source"`
Target string `json:"target"`
Length int64 `json:"length"`
}
// String colorized copy message
@@ -102,8 +100,8 @@ func (c copyMessage) String() string {
// JSON jsonified copy message
func (c copyMessage) JSON() string {
c.Status = "success"
copyMessageBytes, err := json.Marshal(c)
fatalIf(probe.NewError(err), "Failed to marshal copy message.")
copyMessageBytes, e := json.Marshal(c)
fatalIf(probe.NewError(e), "Failed to marshal copy message.")
return string(copyMessageBytes)
}
@@ -129,73 +127,63 @@ 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() + ": ")
}
reader, err := getSource(cpURLs.SourceContent.URL.String())
sourceAlias := cpURLs.SourceAlias
sourceURL := cpURLs.SourceContent.URL
targetAlias := cpURLs.TargetAlias
targetURL := cpURLs.TargetContent.URL
length := cpURLs.SourceContent.Size
reader, err := getSourceStreamFromAlias(sourceAlias, sourceURL.String())
if err != nil {
if !globalQuiet && !globalJSON {
progressReader.ErrorGet(cpURLs.SourceContent.Size)
}
cpURLs.Error = err.Trace(cpURLs.SourceContent.URL.String())
statusCh <- cpURLs
return
cpURLs.Error = err.Trace(sourceURL.String())
return cpURLs
}
var newReader io.ReadSeeker
var progress io.Reader
if globalQuiet || globalJSON {
sourcePath := filepath.ToSlash(filepath.Join(sourceAlias, sourceURL.Path))
targetPath := filepath.ToSlash(filepath.Join(targetAlias, targetURL.Path))
printMsg(copyMessage{
Source: cpURLs.SourceContent.URL.String(),
Target: cpURLs.TargetContent.URL.String(),
Length: cpURLs.SourceContent.Size,
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
}
if err := putTarget(cpURLs.TargetContent.URL.String(), newReader, cpURLs.SourceContent.Size); err != nil {
if !globalQuiet && !globalJSON {
progressReader.ErrorPut(cpURLs.SourceContent.Size)
}
cpURLs.Error = err.Trace(cpURLs.TargetContent.URL.String())
statusCh <- cpURLs
return
_, err = putTargetStreamFromAlias(targetAlias, targetURL.String(), reader, length, progress)
if err != nil {
cpURLs.Error = err.Trace(targetURL.String())
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.
func doPrepareCopyURLs(session *sessionV5, trapCh <-chan bool) {
func doPrepareCopyURLs(session *sessionV6, trapCh <-chan bool) {
// Separate source and target. 'cp' can take only one target,
// but any number of sources.
sourceURLs := session.Header.CommandArgs[:len(session.Header.CommandArgs)-1]
@@ -221,7 +209,7 @@ func doPrepareCopyURLs(session *sessionV5, 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
}
@@ -238,10 +226,10 @@ func doPrepareCopyURLs(session *sessionV5, trapCh <-chan bool) {
break
}
jsonData, err := json.Marshal(cpURLs)
if err != nil {
jsonData, e := json.Marshal(cpURLs)
if e != nil {
session.Delete()
fatalIf(probe.NewError(err), "Unable to prepare URL for copying. Error in JSON marshaling.")
fatalIf(probe.NewError(e), "Unable to prepare URL for copying. Error in JSON marshaling.")
}
fmt.Fprintln(dataFP, string(jsonData))
if !globalQuiet && !globalJSON {
@@ -264,7 +252,7 @@ func doPrepareCopyURLs(session *sessionV5, trapCh <-chan bool) {
session.Save()
}
func doCopySession(session *sessionV5) {
func doCopySession(session *sessionV6) {
trapCh := signalTrap(os.Interrupt, syscall.SIGTERM)
if !session.HasData() {
@@ -274,61 +262,57 @@ func doCopySession(session *sessionV5) {
// 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:
@@ -337,45 +321,53 @@ func doCopySession(session *sessionV5) {
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 {
if progressReader.ProgressBar.Total > 0 {
progressReader.ProgressBar.Finish()
}
} else {
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.
@@ -389,7 +381,7 @@ func mainCopy(ctx *cli.Context) {
// Additional command speific theme customization.
console.SetColor("Copy", color.New(color.FgGreen, color.Bold))
session := newSessionV5()
session := newSessionV6()
session.Header.CommandType = "cp"
session.Header.CommandBoolFlags["recursive"] = ctx.Bool("recursive")
@@ -400,12 +392,7 @@ func mainCopy(ctx *cli.Context) {
}
// extract URLs.
var err *probe.Error
if session.Header.CommandArgs, err = args2URLs(ctx.Args()); err != nil {
session.Delete()
fatalIf(err.Trace(ctx.Args()...), "One or more unknown URL types passed.")
}
session.Header.CommandArgs = ctx.Args()
doCopySession(session)
session.Delete()
}
+7 -6
View File
@@ -29,11 +29,9 @@ func checkCopySyntax(ctx *cli.Context) {
}
// extract URLs.
URLs, err := args2URLs(ctx.Args())
fatalIf(err.Trace(ctx.Args()...), fmt.Sprintf("Argument parsing failed."))
URLs := ctx.Args()
if len(URLs) < 2 {
fatalIf(err.Trace(ctx.Args()...), fmt.Sprintf("Unable to parse source and target arguments."))
fatalIf(errDummy().Trace(ctx.Args()...), fmt.Sprintf("Unable to parse source and target arguments."))
}
srcURLs := URLs[:len(URLs)-1]
@@ -53,7 +51,10 @@ func checkCopySyntax(ctx *cli.Context) {
}
// Guess CopyURLsType based on source and target URLs.
copyURLsType := guessCopyURLType(srcURLs, tgtURL, isRecursive)
copyURLsType, err := guessCopyURLType(srcURLs, tgtURL, isRecursive)
if err != nil {
fatalIf(errInvalidArgument().Trace(), "Unable to guess the type of copy operation.")
}
switch copyURLsType {
case copyURLsTypeA: // File -> File.
checkCopySyntaxTypeA(srcURLs, tgtURL)
@@ -64,7 +65,7 @@ func checkCopySyntax(ctx *cli.Context) {
case copyURLsTypeD: // File1...FileN -> Folder.
checkCopySyntaxTypeD(srcURLs, tgtURL)
default:
fatalIf(errInvalidArgument().Trace(), "Guessing CopyURLsType failed, Invalid arguments provided.")
fatalIf(errInvalidArgument().Trace(), "Unable to guess the type of copy operation.")
}
}
+51 -25
View File
@@ -25,7 +25,9 @@ import (
)
type copyURLs struct {
SourceAlias string
SourceContent *client.Content
TargetAlias string
TargetContent *client.Content
Error *probe.Error `json:"-"`
}
@@ -57,43 +59,44 @@ const (
// guessCopyURLType guesses the type of URL. This approach all allows prepareURL
// functions to accurately report failure causes.
func guessCopyURLType(sourceURLs []string, targetURL string, isRecursive bool) copyURLsType {
func guessCopyURLType(sourceURLs []string, targetURL string, isRecursive bool) (copyURLsType, *probe.Error) {
if len(sourceURLs) == 1 { // 1 Source, 1 Target
sourceURL := sourceURLs[0]
_, sourceContent, err := url2Stat(sourceURL)
if err != nil {
return copyURLsTypeInvalid
return copyURLsTypeInvalid, err
}
// If recursion is ON, it is type C.
// If source is a folder, it is Type C.
if sourceContent.Type.IsDir() || isRecursive {
return copyURLsTypeC
return copyURLsTypeC, nil
}
// If target is a folder, it is Type B.
if isTargetURLDir(targetURL) {
return copyURLsTypeB
return copyURLsTypeB, nil
}
// else Type A.
return copyURLsTypeA
return copyURLsTypeA, nil
}
// Multiple source args and target is a folder. It is Type D.
if isTargetURLDir(targetURL) {
return copyURLsTypeD
return copyURLsTypeD, nil
}
return copyURLsTypeInvalid
return copyURLsTypeInvalid, errInvalidArgument().Trace()
}
// SINGLE SOURCE - Type A: copy(f, f) -> copy(f, f)
// prepareCopyURLsTypeA - prepares target and source URLs for copying.
func prepareCopyURLsTypeA(sourceURL string, targetURL string) copyURLs {
if sourceURL == targetURL {
// source and target can not be same
return copyURLs{Error: errSourceTargetSame(sourceURL).Trace(sourceURL)}
}
// Extract alias before fiddling with the URL.
sourceAlias, _, _ := mustExpandAlias(sourceURL)
// Find alias and expanded URL.
targetAlias, targetURL, _ := mustExpandAlias(targetURL)
_, sourceContent, err := url2Stat(sourceURL)
if err != nil {
// Source does not exist or insufficient privileges.
@@ -103,18 +106,33 @@ 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(sourceContent, targetURL)
return makeCopyContentTypeA(sourceAlias, sourceContent, targetAlias, targetURL)
}
// prepareCopyContentTypeA - makes CopyURLs content for copying.
func makeCopyContentTypeA(sourceContent *client.Content, targetURL string) copyURLs {
return copyURLs{SourceContent: sourceContent, TargetContent: &client.Content{URL: *client.NewURL(targetURL)}}
func makeCopyContentTypeA(sourceAlias string, sourceContent *client.Content, targetAlias string, targetURL string) copyURLs {
return copyURLs{
SourceAlias: sourceAlias,
SourceContent: sourceContent,
TargetAlias: targetAlias,
TargetContent: &client.Content{URL: *client.NewURL(targetURL)},
}
}
// SINGLE SOURCE - Type B: copy(f, d) -> copy(f, d/f) -> A
// prepareCopyURLsTypeB - prepares target and source URLs for copying.
func prepareCopyURLsTypeB(sourceURL string, targetURL string) copyURLs {
// Extract alias before fiddling with the URL.
sourceAlias, _, _ := mustExpandAlias(sourceURL)
// Find alias and expanded URL.
targetAlias, targetURL, _ := mustExpandAlias(targetURL)
_, sourceContent, err := url2Stat(sourceURL)
if err != nil {
// Source does not exist or insufficient privileges.
@@ -130,24 +148,29 @@ func prepareCopyURLsTypeB(sourceURL string, targetURL string) copyURLs {
}
// All OK.. We can proceed. Type B: source is a file, target is a folder and exists.
return makeCopyContentTypeB(sourceContent, targetURL)
return makeCopyContentTypeB(sourceAlias, sourceContent, targetAlias, targetURL)
}
// makeCopyContentTypeB - CopyURLs content for copying.
func makeCopyContentTypeB(sourceContent *client.Content, targetURL string) copyURLs {
func makeCopyContentTypeB(sourceAlias string, sourceContent *client.Content, targetAlias string, targetURL string) copyURLs {
// All OK.. We can proceed. Type B: source is a file, target is a folder and exists.
targetURLParse := client.NewURL(targetURL)
targetURLParse.Path = filepath.Join(targetURLParse.Path, filepath.Base(sourceContent.URL.Path))
return makeCopyContentTypeA(sourceContent, targetURLParse.String())
targetURLParse.Path = filepath.ToSlash(filepath.Join(targetURLParse.Path, filepath.Base(sourceContent.URL.Path)))
return makeCopyContentTypeA(sourceAlias, sourceContent, targetAlias, targetURLParse.String())
}
// SINGLE SOURCE - Type C: copy(d1..., d2) -> []copy(d1/f, d1/d2/f) -> []A
// prepareCopyRecursiveURLTypeC - prepares target and source URLs for copying.
func prepareCopyURLsTypeC(sourceURL, targetURL string, isRecursive bool) <-chan copyURLs {
// Extract alias before fiddling with the URL.
sourceAlias, _, _ := mustExpandAlias(sourceURL)
// Find alias and expanded URL.
targetAlias, targetURL, _ := mustExpandAlias(targetURL)
copyURLsCh := make(chan copyURLs)
go func(sourceURL, targetURL string, copyURLsCh chan copyURLs) {
defer close(copyURLsCh)
sourceClient, err := url2Client(sourceURL)
sourceClient, err := newClient(sourceURL)
if err != nil {
// Source initialization failed.
copyURLsCh <- copyURLs{Error: err.Trace(sourceURL)}
@@ -167,22 +190,23 @@ func prepareCopyURLsTypeC(sourceURL, targetURL string, isRecursive bool) <-chan
}
// All OK.. We can proceed. Type B: source is a file, target is a folder and exists.
copyURLsCh <- makeCopyContentTypeC(sourceClient.GetURL(), sourceContent, targetURL)
copyURLsCh <- makeCopyContentTypeC(sourceAlias, sourceClient.GetURL(), sourceContent, targetAlias, targetURL)
}
}(sourceURL, targetURL, copyURLsCh)
return copyURLsCh
}
// makeCopyContentTypeC - CopyURLs content for copying.
func makeCopyContentTypeC(sourceURL client.URL, sourceContent *client.Content, targetURL string) copyURLs {
func makeCopyContentTypeC(sourceAlias string, sourceURL client.URL, sourceContent *client.Content, targetAlias string, targetURL string) copyURLs {
newSourceURL := sourceContent.URL
pathSeparatorIndex := strings.LastIndex(sourceURL.Path, string(sourceURL.Separator))
newSourceSuffix := newSourceURL.Path
newSourceSuffix := filepath.ToSlash(newSourceURL.Path)
if pathSeparatorIndex > 1 {
newSourceSuffix = strings.TrimPrefix(newSourceURL.Path, sourceURL.Path[:pathSeparatorIndex])
sourcePrefix := filepath.ToSlash(sourceURL.Path[:pathSeparatorIndex])
newSourceSuffix = strings.TrimPrefix(newSourceSuffix, sourcePrefix)
}
newTargetURL := urlJoinPath(targetURL, newSourceSuffix)
return makeCopyContentTypeA(sourceContent, newTargetURL)
return makeCopyContentTypeA(sourceAlias, sourceContent, targetAlias, newTargetURL)
}
// MULTI-SOURCE - Type D: copy([](f|d...), d) -> []B
@@ -205,7 +229,9 @@ func prepareCopyURLs(sourceURLs []string, targetURL string, isRecursive bool) <-
copyURLsCh := make(chan copyURLs)
go func(sourceURLs []string, targetURL string, copyURLsCh chan copyURLs) {
defer close(copyURLsCh)
switch guessCopyURLType(sourceURLs, targetURL, isRecursive) {
cpType, err := guessCopyURLType(sourceURLs, targetURL, isRecursive)
fatalIf(err.Trace(), "Unable to guess the type of copy operation.")
switch cpType {
case copyURLsTypeA:
copyURLsCh <- prepareCopyURLsTypeA(sourceURLs[0], targetURL)
case copyURLsTypeB:
-68
View File
@@ -1,68 +0,0 @@
/*
* Minio Client (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 main
import . "gopkg.in/check.v1"
func (s *TestSuite) TestCopyURLType(c *C) {
// Valid Types.
sourceURLs := []string{server.URL + "/bucket/object1"}
targetURL := server.URL + "/bucket/test"
isRecursive := false
c.Assert(guessCopyURLType(sourceURLs, targetURL, isRecursive), Equals, copyURLsTypeA)
sourceURLs = []string{server.URL + "/bucket/object1"}
targetURL = server.URL + "/bucket"
isRecursive = false
c.Assert(guessCopyURLType(sourceURLs, targetURL, isRecursive), Equals, copyURLsTypeB)
sourceURLs = []string{server.URL + "/bucket/"}
targetURL = server.URL + "/bucket"
isRecursive = true
c.Assert(guessCopyURLType(sourceURLs, targetURL, isRecursive), Equals, copyURLsTypeC)
sourceURLs = []string{server.URL + "/bucket/test1.txt", server.URL + "/bucket/test2.txt"}
targetURL = server.URL + "/bucket"
isRecursive = false
c.Assert(guessCopyURLType(sourceURLs, targetURL, isRecursive), Equals, copyURLsTypeD)
// * INVALID RULES
// =========================
// copy(d, f)
// copy(d..., f)
// copy([]f, f)
sourceURLs = []string{"/test/"}
targetURL = server.URL + "/bucket/test.txt"
isRecursive = false
c.Assert(guessCopyURLType(sourceURLs, targetURL, isRecursive), Equals, copyURLsTypeInvalid)
sourceURLs = []string{"/test/"}
targetURL = server.URL + "/bucket/test.txt"
isRecursive = true
c.Assert(guessCopyURLType(sourceURLs, targetURL, isRecursive), Equals, copyURLsTypeInvalid)
sourceURLs = []string{"/test/test1.txt", "/test/test2.txt"}
targetURL = server.URL + "/bucket/test.txt"
isRecursive = false
c.Assert(guessCopyURLType(sourceURLs, targetURL, isRecursive), Equals, copyURLsTypeInvalid)
sourceURLs = []string{server.URL + "/bucket/", server.URL + "/bucket/"}
targetURL = ""
isRecursive = false
c.Assert(guessCopyURLType(sourceURLs, targetURL, isRecursive), Equals, copyURLsTypeInvalid)
}
-202
View File
@@ -1,202 +0,0 @@
/*
* Minio Client (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.
*/
// Copyright 2010 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//
// Some of the code here is borrowed from 'encoding/json' package.
package main
import (
"encoding/csv"
"io"
"os"
"reflect"
"runtime"
"strconv"
"github.com/minio/minio-xl/pkg/probe"
)
// csvReader reads records from a CSV-encoded file.
type csvReader struct {
*csv.Reader
}
// newCSVReader returns a new csv Reader.
// additionally one can provide a line that needs to be skipped.
func newCSVReader(r io.Reader) *csvReader {
return &csvReader{
csv.NewReader(r),
}
}
// credential - struct to read from a CSV file.
type credential struct {
Name string
AccessKeyID string
SecretAccessKey string
}
// getCredentials - get credentials file.
func getCredentials(credentialsFile string) ([]credential, *probe.Error) {
reader, e := os.Open(credentialsFile)
if e != nil {
return nil, probe.NewError(e)
}
creds := []credential{}
// skip the first line of the csv file, usually csv header.
skipLine := 1
if err := newCSVReader(reader).Unmarshal(&creds, skipLine); err != nil {
return nil, err.Trace(credentialsFile)
}
if len(creds) == 0 {
return nil, errInvalidArgument().Trace(credentialsFile)
}
return creds, nil
}
//// CSV reader block.
/// CSV read errors.
// An invalidUnmarshalError describes an invalid argument passed to Unmarshal.
// (The argument to Unmarshal must be a non-nil pointer.)
type invalidUnmarshalError struct {
Type reflect.Type
}
func (e *invalidUnmarshalError) Error() string {
if e.Type == nil {
return "csv: Unmarshal(nil)"
}
if e.Type.Kind() != reflect.Ptr {
return "csv: Unmarshal(non-pointer " + e.Type.String() + ")"
}
return "csv: Unmarshal(nil " + e.Type.String() + ")"
}
// An unmarshalTypeError describes a CSV value that was
// not appropriate for a value of a specific Go type.
type unmarshalTypeError struct {
Type reflect.Type // type of Go value it could not be assigned to
}
func (e *unmarshalTypeError) Error() string {
return "csv: cannot unmarshal into Go value of type " + e.Type.String()
}
/// CSV Unmarshaler.
// Unmarshal - unmarshal everything into the input struct.
func (r *csvReader) Unmarshal(v interface{}, skipLine int) (err *probe.Error) {
// Handler for runtime errors.
defer func() {
if r := recover(); r != nil {
if _, ok := r.(runtime.Error); ok {
panic(r)
}
e := r.(error)
err = probe.NewError(e)
}
}()
{
// Check if incoming interface{} is nil.
rv := reflect.ValueOf(v)
if rv.Kind() != reflect.Ptr || rv.IsNil() {
return probe.NewError(&invalidUnmarshalError{reflect.TypeOf(v)})
}
}
rv := reflect.ValueOf(v).Elem()
rt := reflect.TypeOf(v).Elem().Elem()
records := reflect.MakeSlice(reflect.TypeOf(v).Elem(), 0, 0)
var e error
var lineCount int
for {
record := reflect.New(rt)
{
var csvRecord []string
csvRecord, e = r.Read()
if e != nil {
break
}
lineCount++
// Skip a particular line
if lineCount == skipLine {
continue
}
rvInternal := reflect.ValueOf(record.Interface()).Elem()
for s := 0; s < rvInternal.NumField(); s++ {
val := rvInternal.Field(s)
x := csvRecord[s]
setValue(&val, x)
}
}
records = reflect.Append(records, record.Elem())
}
if e == io.EOF {
rv.Set(records)
return nil
}
if e != nil {
return probe.NewError(e)
}
return nil
}
// setValue - following reflect.Value sets the actual value based on the Golang type.
// If no native type found throws an UnmarshalTypeError.
func setValue(v *reflect.Value, x string) *probe.Error {
switch v.Kind() {
case reflect.Bool:
val, e := strconv.ParseBool(x)
if e != nil {
return probe.NewError(e)
}
v.SetBool(val)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
val, e := strconv.ParseInt(x, 10, v.Type().Bits())
if e != nil {
return probe.NewError(e)
}
v.SetInt(val)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
val, e := strconv.ParseUint(x, 10, v.Type().Bits())
if e != nil {
return probe.NewError(e)
}
v.SetUint(val)
case reflect.Float32, reflect.Float64:
val, e := strconv.ParseFloat(x, v.Type().Bits())
if e != nil {
return probe.NewError(e)
}
v.SetFloat(val)
case reflect.String:
v.SetString(x)
case reflect.Struct:
case reflect.Map:
case reflect.Slice:
case reflect.Array:
case reflect.Interface, reflect.Ptr:
default:
return probe.NewError(&unmarshalTypeError{v.Type()})
}
return nil
}
+66
View File
@@ -0,0 +1,66 @@
/*
* Minio Client (C) 2014-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 main
import (
"math"
)
// Returns the minimum value of a slice of integers
func minimum(integers []int) (minVal int) {
minVal = math.MaxInt32
for _, v := range integers {
if v < minVal {
minVal = v
}
}
return
}
// DamerauLevenshteinDistance calculates distance between two strings using an algorithm
// described in https://en.wikipedia.org/wiki/Damerau-Levenshtein_distance
func DamerauLevenshteinDistance(a string, b string) int {
d := make([][]int, len(a)+1)
for i := 1; i <= len(a)+1; i++ {
d[i-1] = make([]int, len(b)+1)
}
for i := 0; i <= len(a); i++ {
d[i][0] = i
}
for j := 0; j <= len(b); j++ {
d[0][j] = j
}
for i := 1; i <= len(a); i++ {
for j := 1; j <= len(b); j++ {
cost := 0
if a[i-1] == b[j-1] {
cost = 0
} else {
cost = 1
}
d[i][j] = minimum([]int{
d[i-1][j] + 1,
d[i][j-1] + 1,
d[i-1][j-1] + cost,
})
if i > 1 && j > 1 && a[i-1] == b[j-2] && a[i-2] == b[j-1] {
d[i][j] = minimum([]int{d[i][j], d[i-2][j-2] + cost}) // transposition
}
}
}
return d[len(a)][len(b)]
}
+52 -37
View File
@@ -59,24 +59,13 @@ DESCRIPTION:
EXAMPLES:
1. Compare a local folder with a folder on Amazon S3 cloud storage.
$ mc {{.Name}} ~/Photos s3.amazonaws.com/MyBucket/Photos
$ mc {{.Name}} ~/Photos s3/MyBucket/Photos
2. Compare two different folders on a local filesystem.
$ mc {{.Name}} ~/Photos /Media/Backup/Photos
`,
}
func checkDiffSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 2 {
cli.ShowCommandHelpAndExit(ctx, "diff", 1) // last argument is exit code
}
for _, arg := range ctx.Args() {
if strings.TrimSpace(arg) == "" {
fatalIf(errInvalidArgument().Trace(ctx.Args()...), "Unable to validate empty argument.")
}
}
}
// diffMessage json container for diff messages
type diffMessage struct {
Status string `json:"status"`
@@ -110,15 +99,51 @@ func (d diffMessage) String() string {
// JSON jsonified diff message
func (d diffMessage) JSON() string {
d.Status = "success"
diffJSONBytes, err := json.Marshal(d)
fatalIf(probe.NewError(err),
diffJSONBytes, e := json.Marshal(d)
fatalIf(probe.NewError(e),
"Unable to marshal diff message ‘"+d.FirstURL+"’, ‘"+d.SecondURL+"’ and ‘"+d.Diff+"’.")
return string(diffJSONBytes)
}
func checkDiffSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 2 {
cli.ShowCommandHelpAndExit(ctx, "diff", 1) // last argument is exit code
}
for _, arg := range ctx.Args() {
if strings.TrimSpace(arg) == "" {
fatalIf(errInvalidArgument().Trace(ctx.Args()...), "Unable to validate empty argument.")
}
}
URLs := ctx.Args()
firstURL := URLs[0]
secondURL := URLs[1]
// Diff only works between two directories, verify them below.
// Verify if firstURL is accessible.
_, firstContent, err := url2Stat(firstURL)
if err != nil {
fatalIf(err.Trace(firstURL), fmt.Sprintf("Unable to stat '%s'.", firstURL))
}
// Verify if its a directory.
if !firstContent.Type.IsDir() {
fatalIf(errInvalidArgument().Trace(firstURL), fmt.Sprintf("‘%s’ is not a folder.", firstURL))
}
// Verify if secondURL is accessible.
_, secondContent, err := url2Stat(secondURL)
if err != nil {
fatalIf(err.Trace(secondURL), fmt.Sprintf("Unable to stat '%s'.", secondURL))
}
// Verify if its a directory.
if !secondContent.Type.IsDir() {
fatalIf(errInvalidArgument().Trace(secondURL), fmt.Sprintf("‘%s’ is not a folder.", secondURL))
}
}
// doDiffMain runs the diff.
func doDiffMain(firstURL, secondURL string) {
// source and targets are always directories
// Source and targets are always directories
sourceSeparator := string(client.NewURL(firstURL).Separator)
if !strings.HasSuffix(firstURL, sourceSeparator) {
firstURL = firstURL + sourceSeparator
@@ -128,20 +153,26 @@ func doDiffMain(firstURL, secondURL string) {
secondURL = secondURL + targetSeparator
}
firstClient, err := url2Client(firstURL)
// Expand aliased urls.
firstAlias, firstURL, _ := mustExpandAlias(firstURL)
secondAlias, secondURL, _ := mustExpandAlias(secondURL)
firstClient, err := newClientFromAlias(firstAlias, firstURL)
if err != nil {
fatalIf(err.Trace(firstURL, secondURL), fmt.Sprintf("Failed to diff '%s' and '%s'", firstURL, secondURL))
fatalIf(err.Trace(firstAlias, firstURL, secondAlias, secondURL),
fmt.Sprintf("Failed to diff '%s' and '%s'", firstURL, secondURL))
}
difference, err := objectDifferenceFactory(secondURL)
difference, err := objectDifferenceFactory(secondAlias, secondURL)
if err != nil {
fatalIf(err.Trace(firstURL, secondURL), fmt.Sprintf("Failed to diff '%s' and '%s'", firstURL, secondURL))
fatalIf(err.Trace(firstAlias, firstURL, secondAlias, secondURL),
fmt.Sprintf("Failed to diff '%s' and '%s'", firstURL, secondURL))
}
isRecursive := true
isIncomplete := false
for sourceContent := range firstClient.List(isRecursive, isIncomplete) {
if sourceContent.Err != nil {
switch sourceContent.Err.ToGoError().(type) {
// handle this specifically for filesystem related errors.
// Handle this specifically for filesystem related errors.
case client.BrokenSymlink, client.TooManyLevelsSymlink, client.PathNotFound, client.PathInsufficientPermission:
errorIf(sourceContent.Err.Trace(firstURL, secondURL), fmt.Sprintf("Failed on '%s'", firstURL))
default:
@@ -184,25 +215,9 @@ func mainDiff(ctx *cli.Context) {
console.SetColor("DiffType", color.New(color.FgYellow, color.Bold))
console.SetColor("DiffSize", color.New(color.FgMagenta, color.Bold))
URLs, err := args2URLs(ctx.Args())
fatalIf(err.Trace(ctx.Args()...), "Unable to convert args 2 URLs")
URLs := ctx.Args()
firstURL := URLs[0]
secondURL := URLs[1]
_, firstContent, err := url2Stat(firstURL)
if err != nil {
fatalIf(err.Trace(firstURL), fmt.Sprintf("Unable to stat '%s'.", firstURL))
}
if !firstContent.Type.IsDir() {
fatalIf(errInvalidArgument().Trace(firstURL), fmt.Sprintf("‘%s’ is not a folder.", firstURL))
}
_, secondContent, err := url2Stat(secondURL)
if err != nil {
fatalIf(err.Trace(secondURL), fmt.Sprintf("Unable to stat '%s'.", secondURL))
}
if !secondContent.Type.IsDir() {
fatalIf(errInvalidArgument().Trace(secondURL), fmt.Sprintf("‘%s’ is not a folder.", secondURL))
}
doDiffMain(firstURL, secondURL)
}
+3 -3
View File
@@ -38,10 +38,10 @@ const (
// objectDifferenceFactory returns objectDifference function to check for difference
// between sourceURL and targetURL
// for usage reference check diff and mirror commands
func objectDifferenceFactory(targetURL string) (objectDifference, *probe.Error) {
clnt, err := url2Client(targetURL)
func objectDifferenceFactory(targetAlias, targetURL string) (objectDifference, *probe.Error) {
clnt, err := newClientFromAlias(targetAlias, targetURL)
if err != nil {
return nil, err.Trace(targetURL)
return nil, err.Trace(targetAlias, targetURL)
}
isIncomplete := false
isRecursive := true
+6 -6
View File
@@ -57,15 +57,15 @@ func fatalIf(err *probe.Error, msg string) {
if globalDebug {
errorMsg.CallTrace = err.CallTrace
}
json, err := json.Marshal(struct {
json, e := json.Marshal(struct {
Status string `json:"status"`
Error errorMessage `json:"error"`
}{
Status: "error",
Error: errorMsg,
})
if err != nil {
console.Fatalln(probe.NewError(err))
if e != nil {
console.Fatalln(probe.NewError(e))
}
console.Println(string(json))
console.Fatalln()
@@ -94,15 +94,15 @@ func errorIf(err *probe.Error, msg string) {
if globalDebug {
errorMsg.CallTrace = err.CallTrace
}
json, err := json.Marshal(struct {
json, e := json.Marshal(struct {
Status string `json:"status"`
Error errorMessage `json:"error"`
}{
Status: "error",
Error: errorMsg,
})
if err != nil {
console.Fatalln(probe.NewError(err))
if e != nil {
console.Fatalln(probe.NewError(e))
}
console.Println(string(json))
return
+1 -10
View File
@@ -24,7 +24,7 @@ import (
// mc configuration related constants.
const (
globalMCConfigVersion = "6"
globalMCConfigVersion = "7"
globalMCConfigDir = ".mc/"
globalMCConfigWindowsDir = "mc\\"
@@ -33,15 +33,6 @@ const (
// session config and shared urls related constants
globalSessionDir = "session"
globalSharedURLsDataDir = "share"
// default access and secret key
// do not pass accesskeyid and secretaccesskey through cli
// users should manually edit them, add a stub entry
globalAccessKeyID = "YOUR-ACCESS-KEY-ID-HERE"
globalSecretAccessKey = "YOUR-SECRET-ACCESS-KEY-HERE"
// default host
globalExampleHostURL = "http://YOUR-EXAMPLE.COM"
)
var (
-62
View File
@@ -1,62 +0,0 @@
/*
* Minio Client (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 main
import (
"strings"
"github.com/minio/mc/pkg/client"
"github.com/minio/minio-xl/pkg/probe"
)
// hostConfig configuration of a host.
type hostConfig struct {
AccessKeyID string `json:"accessKeyId"`
SecretAccessKey string `json:"secretAccessKey"`
API string `json:"api"`
}
// getHostConfig retrieves host specific configuration such as access keys, signature type.
func getHostConfig(URL string) (hostConfig, *probe.Error) {
config, err := loadMcConfig()
if err != nil {
return hostConfig{}, err.Trace(URL)
}
url := client.NewURL(URL)
// No host matching or keys needed for filesystem requests.
if url.Type == client.Filesystem {
hostCfg := hostConfig{
AccessKeyID: "",
SecretAccessKey: "",
API: "fs",
}
return hostCfg, nil
}
// if host is exact return quickly.
if _, ok := config.Hosts[url.String()]; ok {
return config.Hosts[url.String()], nil
}
// if host matches a suffix return.
for savedURLStr, hostCfg := range config.Hosts {
savedURL := client.NewURL(savedURLStr)
if strings.HasSuffix(url.Host, savedURL.Host) {
return hostCfg, nil
}
}
// return error if cannot be matched.
return hostConfig{}, errNoMatchingHost(URL).Trace(URL)
}
+12 -17
View File
@@ -17,7 +17,6 @@
package main
import (
"fmt"
"strings"
"github.com/fatih/color"
@@ -61,20 +60,20 @@ FLAGS:
{{end}}
EXAMPLES:
1. List buckets on Amazon S3 cloud storage.
$ mc {{.Name}} s3.amazonaws.com
$ mc {{.Name}} s3
2. List buckets and all its contents from Amazon S3 cloud storage recursively.
$ mc {{.Name}} --recursive s3.amazonaws.com
$ mc {{.Name}} --recursive s3
3. List files recursively on a local filesystem on Microsoft Windows.
3. List all contents of mybucket on Amazon S3 cloud storage.
$ mc {{.Name}} s3/mybucket/
4. List all contents of mybucket on Amazon S3 cloud storage on Microsoft Windows.
$ mc {{.Name}} s3\mybucket\
5. List files recursively on a local filesystem on Microsoft Windows.
$ mc {{.Name}} --recursive C:\Users\Worf\
4. List files with non-English characters on Amazon S3 cloud storage.
$ mc {{.Name}} s3/andoria/本
5. List folders with space separated names on Amazon S3 cloud storage.
$ mc {{.Name}} 's3/miniocloud/Community Files/'
6. List incomplete (previously failed) uploads of objects on Amazon S3.
$ mc {{.Name}} --incomplete s3/mybucket
`,
@@ -92,9 +91,7 @@ func checkListSyntax(ctx *cli.Context) {
}
}
// extract URLs.
URLs, err := args2URLs(ctx.Args())
fatalIf(err.Trace(ctx.Args()...), fmt.Sprintf("One or more unknown URL types passed."))
URLs := ctx.Args()
isIncomplete := ctx.Bool("incomplete")
for _, url := range URLs {
@@ -129,11 +126,9 @@ func mainList(ctx *cli.Context) {
args = []string{"."}
}
targetURLs, err := args2URLs(args)
fatalIf(err.Trace(args...), "One or more unknown URL types passed.")
for _, targetURL := range targetURLs {
for _, targetURL := range args {
var clnt client.Client
clnt, err = url2Client(targetURL)
clnt, err := newClient(targetURL)
fatalIf(err.Trace(targetURL), "Unable to initialize target ‘"+targetURL+"’.")
err = doList(clnt, isRecursive, isIncomplete)
+7 -3
View File
@@ -19,6 +19,7 @@ package main
import (
"encoding/json"
"fmt"
"path/filepath"
"runtime"
"strings"
"time"
@@ -111,7 +112,6 @@ func doList(clnt client.Client, isRecursive, isIncomplete bool) *probe.Error {
prefixPath = prefixPath[:strings.LastIndex(prefixPath, separator)+1]
}
for content := range clnt.List(isRecursive, isIncomplete) {
// fmt.Println(content)
if content.Err != nil {
switch content.Err.ToGoError().(type) {
// handle this specifically for filesystem related errors.
@@ -131,11 +131,15 @@ func doList(clnt client.Client, isRecursive, isIncomplete bool) *probe.Error {
errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list folder.")
continue
}
contentURL := content.URL.Path
// Convert any os specific delimiters to "/".
contentURL := filepath.ToSlash(content.URL.Path)
prefixPath = filepath.ToSlash(prefixPath)
// Trim prefix path from the content path.
contentURL = strings.TrimPrefix(contentURL, prefixPath)
content.URL.Path = contentURL
parsedContent := parseContent(content)
// print colorized or jsonized content info.
// Print colorized or jsonized content info.
printMsg(parsedContent)
}
return nil
+16 -2
View File
@@ -31,6 +31,7 @@ import (
)
var (
// global flags for mc.
mcFlags = []cli.Flag{
cli.BoolFlag{
Name: "help, h",
@@ -44,7 +45,7 @@ var mcHelpTemplate = `NAME:
{{.Name}} - {{.Usage}}
USAGE:
{{.Name}} {{if .Flags}}[FLAGS] {{end}}COMMAND{{if .Flags}} [COMMAND FLAGS]{{end}} [ARGUMENTS...]
{{.Name}} {{if .Flags}}[FLAGS] {{end}}COMMAND{{if .Flags}} [COMMAND FLAGS | -h]{{end}} [ARGUMENTS...]
COMMANDS:
{{range .Commands}}{{join .Names ", "}}{{ "\t" }}{{.Usage}}
@@ -61,7 +62,7 @@ VERSION:
// Function invoked when invalid command is passed.
func commandNotFound(ctx *cli.Context, command string) {
msg := fmt.Sprintf("‘%s’ is not a mc command. See ‘mc help’.", command)
msg := fmt.Sprintf("‘%s’ is not a mc command. See ‘mc --help’.", command)
closestCommands := findClosestCommands(command)
if len(closestCommands) > 0 {
msg += fmt.Sprintf("\n\nDid you mean one of these?\n")
@@ -87,10 +88,13 @@ func checkConfig() {
func migrate() {
// Fix broken config files if any.
fixConfig()
// Migrate config files if any.
migrateConfig()
// Migrate session files if any.
migrateSession()
// Migrate shared urls if any.
migrateShare()
}
@@ -142,6 +146,16 @@ func findClosestCommands(command string) []string {
closestCommands = append(closestCommands, value.(string))
}
sort.Strings(closestCommands)
// Suggest other close commands - allow missed, wrongly added and even transposed characters
for _, value := range commandsTree.walk(commandsTree.root) {
if sort.SearchStrings(closestCommands, value.(string)) < len(closestCommands) {
continue
}
// 2 is arbitrary and represents the max allowed number of typed errors
if DamerauLevenshteinDistance(command, value.(string)) < 2 {
closestCommands = append(closestCommands, value.(string))
}
}
return closestCommands
}
+26 -28
View File
@@ -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’.",
},
}
)
@@ -52,15 +56,15 @@ FLAGS:
{{end}}
EXAMPLES:
1. Create a bucket on Amazon S3 cloud storage.
$ mc {{.Name}} s3.amazonaws.com/mynewbucket
$ mc {{.Name}} s3/mynewbucket
2. Create a new bucket on Google Cloud Storage.
$ mc {{.Name}} storage.googleapis.com/miniocloud
$ mc {{.Name}} gcs/miniocloud
3. Create a new bucket on Amazon S3 cloud storage, using virtual bucket request.
$ mc {{.Name}} ferenginar.s3.amazonaws.com
4. Create a new bucket on Amazon S3 cloud storage in region ‘us-west-2’.
$ mc {{.Name}} --region=us-west-2 s3/myregionbucket
3. Create a new directory including its missing parents (equivalent to ‘mkdir -p’).
5. Create a new directory including its missing parents (equivalent to ‘mkdir -p’).
$ mc {{.Name}} /tmp/this/new/dir1
`,
}
@@ -69,6 +73,7 @@ EXAMPLES:
type makeBucketMessage struct {
Status string `json:"status"`
Bucket string `json:"bucket"`
Region string `json:"region"`
}
// String colorized make bucket message.
@@ -78,8 +83,8 @@ func (s makeBucketMessage) String() string {
// JSON jsonified make bucket message.
func (s makeBucketMessage) JSON() string {
makeBucketJSONBytes, err := json.Marshal(s)
fatalIf(probe.NewError(err), "Unable to marshal into JSON.")
makeBucketJSONBytes, e := json.Marshal(s)
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(makeBucketJSONBytes)
}
@@ -89,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.")
}
}
@@ -107,23 +110,18 @@ func mainMakeBucket(ctx *cli.Context) {
// Additional command speific theme customization.
console.SetColor("MakeBucket", color.New(color.FgGreen, color.Bold))
URLs, err := args2URLs(ctx.Args())
fatalIf(err.Trace(ctx.Args()...), "Unable to convert args to URLs.")
// save region.
region := ctx.String("region")
for _, targetURL := range URLs {
// Instantiate client for URL.
clnt, err := url2Client(targetURL)
fatalIf(err.Trace(targetURL), "Invalid target ‘"+targetURL+"’.")
targetURL := ctx.Args().First()
// Instantiate client for URL.
clnt, err := newClient(targetURL)
fatalIf(err.Trace(targetURL), "Invalid target ‘"+targetURL+"’.")
// Make bucket.
err = clnt.MakeBucket()
// Upon error print error and continue.
if err != nil {
errorIf(err.Trace(targetURL), "Unable to make bucket ‘"+targetURL+"’.")
continue
}
// 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})
}
// Successfully created a bucket.
printMsg(makeBucketMessage{Status: "success", Bucket: targetURL})
}
+9 -161
View File
@@ -17,11 +17,8 @@
package main
import (
"io/ioutil"
"os"
"path/filepath"
"runtime"
"sync"
"testing"
"time"
@@ -43,120 +40,9 @@ var server *httptest.Server
var app *cli.App
func (s *TestSuite) SetUpSuite(c *C) {
objectAPI := objectAPIHandler(objectAPIHandler{lock: &sync.Mutex{}, bucket: "bucket", object: make(map[string][]byte)})
server = httptest.NewServer(objectAPI)
// do not set it elsewhere, leads to data races since this is a global flag
globalQuiet = true // quiet is set to turn of progress bar
tmpDir, e := ioutil.TempDir(os.TempDir(), "cmd-")
c.Assert(e, IsNil)
// For windows the path is slightly different.
if runtime.GOOS == "windows" {
customConfigDir = filepath.Join(tmpDir, globalMCConfigWindowsDir)
} else {
customConfigDir = filepath.Join(tmpDir, globalMCConfigDir)
}
setMcConfigDir(customConfigDir)
err := createMcConfigDir()
c.Assert(err, IsNil)
config := newMcConfig()
config.Hosts[server.URL] = hostConfig{
AccessKeyID: "WLGDGYAQYIGI833EV05A",
SecretAccessKey: "BYvgJM101sHngl2uzjXS/OBF/aMxAN06JrJ3qJlF",
API: "S3v4",
}
err = saveMcConfig(config)
c.Assert(err, IsNil)
err = createSessionDir()
c.Assert(err, IsNil)
app = registerApp()
}
func (s *TestSuite) TearDownSuite(c *C) {
os.RemoveAll(customConfigDir)
if server != nil {
server.Close()
}
}
func (s *TestSuite) TestGetNewClient(c *C) {
_, err := getNewClient("http://example.com/bucket1", hostConfig{})
c.Assert(err, IsNil)
_, err = getNewClient("https://example.com/bucket1", hostConfig{})
c.Assert(err, IsNil)
_, err = getNewClient("C:\\Users\\Administrator\\MyDocuments", hostConfig{})
c.Assert(err, IsNil)
_, err = getNewClient("/usr/bin/pandoc", hostConfig{})
c.Assert(err, IsNil)
_, err = getNewClient("pkg/client", hostConfig{})
c.Assert(err, IsNil)
}
// setMcConfigPath - set a custom minio client config path.
func setMcConfigPath(configPath string) {
mcCustomConfigPath = configPath
}
func (s *TestSuite) TestNewConfigV6(c *C) {
root, e := ioutil.TempDir(os.TempDir(), "mc-")
c.Assert(e, IsNil)
defer os.RemoveAll(root)
conf := newMcConfig()
configFile := filepath.Join(root, globalMCConfigFile)
setMcConfigPath(configFile)
err := saveMcConfig(conf)
c.Assert(err, IsNil)
data, err := loadMcConfig()
c.Assert(err, IsNil)
setMcConfigPath("")
type aliases struct {
name string
url string
}
wantAliases := []aliases{
{
"s3",
"https://s3.amazonaws.com",
},
{
"play",
"https://play.minio.io:9000",
},
{
"local",
"http://localhost:9000",
},
}
for _, alias := range wantAliases {
url, ok := data.Aliases[alias.name]
c.Assert(ok, Equals, true)
c.Assert(url, Equals, alias.url)
}
wantHosts := []string{
"http://localhost:9000",
"https://play.minio.io:9000",
"https://dl.minio.io:9000",
"https://s3.amazonaws.com",
"https://storage.googleapis.com",
}
for _, host := range wantHosts {
_, ok := data.Hosts[host]
c.Assert(ok, Equals, true)
}
}
func (s *TestSuite) TestValidPERMS(c *C) {
@@ -182,18 +68,7 @@ func (s *TestSuite) TestInvalidPERMS(c *C) {
func (s *TestSuite) TestGetMcConfigDir(c *C) {
dir, err := getMcConfigDir()
c.Assert(err, IsNil)
switch runtime.GOOS {
case "linux":
fallthrough
case "freebsd":
fallthrough
case "darwin":
c.Assert(dir, Equals, customConfigDir)
case "windows":
c.Assert(dir, Equals, customConfigDir)
default:
c.Fail()
}
c.Assert(dir, Not(Equals), "")
c.Assert(mustGetMcConfigDir(), Equals, dir)
}
@@ -216,36 +91,14 @@ func (s *TestSuite) TestGetMcConfigPath(c *C) {
}
func (s *TestSuite) TestIsvalidAliasName(c *C) {
c.Check(isValidAliasName("helloWorld0"), Equals, true)
c.Check(isValidAliasName("h0SFD2k24Fdsa"), Equals, true)
c.Check(isValidAliasName("fdslka-4"), Equals, true)
c.Check(isValidAliasName("fdslka-"), Equals, true)
c.Check(isValidAliasName("helloWorld$"), Equals, false)
c.Check(isValidAliasName("h0SFD2k2#Fdsa"), Equals, false)
c.Check(isValidAliasName("0dslka-4"), Equals, false)
c.Check(isValidAliasName("-fdslka"), Equals, false)
}
func (s *TestSuite) TestEmptyExpansions(c *C) {
url, err := getAliasURL("hello")
c.Assert(err, IsNil)
c.Assert(url, Equals, "hello")
url, err = getAliasURL("minio://hello")
c.Assert(err, IsNil)
c.Assert(url, Equals, "minio://hello")
url, err = getAliasURL("$#\\")
c.Assert(err, IsNil)
c.Assert(url, Equals, "$#\\")
url, err = getAliasURL("myfoo/bar")
c.Assert(err, IsNil)
c.Assert(url, Equals, "myfoo/bar")
url, err = getAliasURL("")
c.Assert(err, IsNil)
c.Assert(url, Equals, "")
c.Check(isValidAlias("helloWorld0"), Equals, true)
c.Check(isValidAlias("h0SFD2k24Fdsa"), Equals, true)
c.Check(isValidAlias("fdslka-4"), Equals, true)
c.Check(isValidAlias("fdslka-"), Equals, true)
c.Check(isValidAlias("helloWorld$"), Equals, false)
c.Check(isValidAlias("h0SFD2k2#Fdsa"), Equals, false)
c.Check(isValidAlias("0dslka-4"), Equals, false)
c.Check(isValidAlias("-fdslka"), Equals, false)
}
func (s *TestSuite) TestHumanizedTime(c *C) {
@@ -277,8 +130,3 @@ func (s *TestSuite) TestVersions(c *C) {
c.Assert(v2.LessThan(v1), Equals, true)
c.Assert(v1.LessThan(v2), Equals, false)
}
func (s *TestSuite) TestApp(c *C) {
err := app.Run([]string{""})
c.Assert(err, IsNil)
}
+99 -113
View File
@@ -21,9 +21,8 @@ import (
"encoding/json"
"fmt"
"io"
"math"
"os"
"runtime"
"path/filepath"
"sync"
"syscall"
@@ -66,13 +65,13 @@ FLAGS:
{{end}}
EXAMPLES:
1. Mirror a bucket recursively from Minio cloud storage to a bucket on Amazon S3 cloud storage.
$ mc {{.Name}} play.minio.io:9000/photos/2014 s3.amazonaws.com/backup-photos
$ mc {{.Name}} play/photos/2014 s3/backup-photos
2. Mirror a local folder recursively to Amazon S3 cloud storage.
$ mc {{.Name}} backup/ s3.amazonaws.com/archive
$ mc {{.Name}} backup/ s3/archive
3. Mirror a bucket from aliased Amazon S3 cloud storage to a folder on Windows.
$ mc {{.Name}} s3/documents/2014/ C:\backup\2014
$ mc {{.Name}} s3\documents\2014\ C:\backup\2014
`,
}
@@ -118,75 +117,63 @@ 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
}
targetURL := sURLs.TargetContent.URL.String()
sourceURL := sURLs.SourceContent.URL.String()
sourceAlias := sURLs.SourceAlias
sourceURL := sURLs.SourceContent.URL
targetAlias := sURLs.TargetAlias
targetURL := sURLs.TargetContent.URL
length := sURLs.SourceContent.Size
if !globalQuiet && !globalJSON {
progressReader.SetCaption(sourceURL + ": ")
progressReader = progressReader.SetCaption(sourceURL.String() + ": ")
}
reader, err := getSource(sourceURL)
reader, err := getSourceStreamFromAlias(sourceAlias, sourceURL.String())
if err != nil {
if !globalQuiet && !globalJSON {
progressReader.ErrorGet(length)
}
sURLs.Error = err.Trace(sourceURL)
statusCh <- sURLs
return
sURLs.Error = err.Trace(sourceURL.String())
return sURLs
}
var newReader io.ReadSeeker
var progress io.Reader
if globalQuiet || globalJSON {
sourcePath := filepath.ToSlash(filepath.Join(sourceAlias, sourceURL.Path))
targetPath := filepath.ToSlash(filepath.Join(targetAlias, targetURL.Path))
printMsg(mirrorMessage{
Source: sourceURL,
Target: targetURL,
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 = putTarget(targetURL, newReader, length)
_, err = putTargetStreamFromAlias(targetAlias, targetURL.String(), reader, length, progress)
if err != nil {
if !globalQuiet && !globalJSON {
progressReader.ErrorPut(length)
}
sURLs.Error = err.Trace(targetURL)
statusCh <- sURLs
return
sURLs.Error = err.Trace(targetURL.String())
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.
func doPrepareMirrorURLs(session *sessionV5, isForce bool, trapCh <-chan bool) {
func doPrepareMirrorURLs(session *sessionV6, isForce bool, trapCh <-chan bool) {
sourceURL := session.Header.CommandArgs[0] // first one is source.
targetURL := session.Header.CommandArgs[1]
var totalBytes int64
@@ -220,10 +207,10 @@ func doPrepareMirrorURLs(session *sessionV5, isForce bool, trapCh <-chan bool) {
if sURLs.isEmpty() {
break
}
jsonData, err := json.Marshal(sURLs)
if err != nil {
jsonData, e := json.Marshal(sURLs)
if e != nil {
session.Delete()
fatalIf(probe.NewError(err), "Unable to marshal URLs into JSON.")
fatalIf(probe.NewError(e), "Unable to marshal URLs into JSON.")
}
fmt.Fprintln(dataFP, string(jsonData))
if !globalQuiet && !globalJSON {
@@ -247,7 +234,7 @@ func doPrepareMirrorURLs(session *sessionV5, isForce bool, trapCh <-chan bool) {
}
// Session'fied mirror command.
func doMirrorSession(session *sessionV5) {
func doMirrorSession(session *sessionV6) {
isForce := session.Header.CommandBoolFlags["force"]
trapCh := signalTrap(os.Interrupt, syscall.SIGTERM)
@@ -259,57 +246,57 @@ func doMirrorSession(session *sessionV5) {
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:
@@ -318,47 +305,52 @@ func doMirrorSession(session *sessionV5) {
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 {
if progressReader.ProgressBar.Total > 0 {
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.
@@ -373,7 +365,7 @@ func mainMirror(ctx *cli.Context) {
console.SetColor("Mirror", color.New(color.FgGreen, color.Bold))
var e error
session := newSessionV5()
session := newSessionV6()
session.Header.CommandType = "mirror"
session.Header.RootPath, e = os.Getwd()
if e != nil {
@@ -386,13 +378,7 @@ func mainMirror(ctx *cli.Context) {
session.Header.CommandBoolFlags["force"] = isForce
// extract URLs.
var err *probe.Error
session.Header.CommandArgs, err = args2URLs(ctx.Args())
if err != nil {
session.Delete()
fatalIf(err.Trace(ctx.Args()...), fmt.Sprintf("One or more unknown argument types found in ‘%s’.", ctx.Args()))
}
session.Header.CommandArgs = ctx.Args()
doMirrorSession(session)
session.Delete()
}
+18 -10
View File
@@ -26,7 +26,9 @@ import (
)
type mirrorURLs struct {
SourceAlias string
SourceContent *client.Content
TargetAlias string
TargetContent *client.Content
Error *probe.Error `json:"-"`
}
@@ -53,9 +55,7 @@ func checkMirrorSyntax(ctx *cli.Context) {
}
// extract URLs.
URLs, err := args2URLs(ctx.Args())
fatalIf(err.Trace(ctx.Args()...), "Unable to parse arguments.")
URLs := ctx.Args()
srcURL := URLs[0]
tgtURL := URLs[1]
@@ -92,8 +92,6 @@ func checkMirrorSyntax(ctx *cli.Context) {
}
func deltaSourceTargets(sourceURL string, targetURL string, isForce bool, mirrorURLsCh chan<- mirrorURLs) {
defer close(mirrorURLsCh)
// source and targets are always directories
sourceSeparator := string(client.NewURL(sourceURL).Separator)
if !strings.HasSuffix(sourceURL, sourceSeparator) {
@@ -104,21 +102,29 @@ func deltaSourceTargets(sourceURL string, targetURL string, isForce bool, mirror
targetURL = targetURL + targetSeparator
}
objectDifferenceTarget, err := objectDifferenceFactory(targetURL)
// Extract alias and expanded URL
sourceAlias, sourceURL, _ := mustExpandAlias(sourceURL)
targetAlias, targetURL, _ := mustExpandAlias(targetURL)
defer close(mirrorURLsCh)
objectDifferenceTarget, err := objectDifferenceFactory(targetAlias, targetURL)
if err != nil {
mirrorURLsCh <- mirrorURLs{Error: err.Trace(targetURL)}
mirrorURLsCh <- mirrorURLs{Error: err.Trace(targetAlias, targetURL)}
return
}
sourceClient, err := url2Client(sourceURL)
sourceClient, err := newClientFromAlias(sourceAlias, sourceURL)
if err != nil {
mirrorURLsCh <- mirrorURLs{Error: err.Trace(sourceURL)}
mirrorURLsCh <- mirrorURLs{Error: err.Trace(sourceAlias, sourceURL)}
return
}
for sourceContent := range sourceClient.List(true, false) {
if sourceContent.Err != nil {
mirrorURLsCh <- mirrorURLs{Error: sourceContent.Err.Trace(sourceClient.GetURL().String())}
mirrorURLsCh <- mirrorURLs{
Error: sourceContent.Err.Trace(sourceClient.GetURL().String()),
}
continue
}
if sourceContent.Type.IsDir() {
@@ -147,7 +153,9 @@ func deltaSourceTargets(sourceURL string, targetURL string, isForce bool, mirror
targetPath := urlJoinPath(targetURL, suffix)
targetContent := &client.Content{URL: *client.NewURL(targetPath)}
mirrorURLsCh <- mirrorURLs{
SourceAlias: sourceAlias,
SourceContent: sourceContent,
TargetAlias: targetAlias,
TargetContent: targetContent,
}
}
+3 -3
View File
@@ -50,9 +50,9 @@ func colorizeUpdateMessage(updateString string) (string, *probe.Error) {
line2Rest := maxContentWidth - line2Length
// Fetch terminal size to calculate optimal box size.
terminal, err := ts.GetSize()
if err != nil {
return "", probe.NewError(err)
terminal, e := ts.GetSize()
if e != nil {
return "", probe.NewError(e)
}
var message string
+6 -7
View File
@@ -53,13 +53,13 @@ EXAMPLES:
$ mc {{.Name}} /tmp/hello-world.go
2. Write contents of stdin to an object on Amazon S3 cloud storage.
$ mc {{.Name}} s3.amazonaws.com/personalbuck/meeting-notes.txt
$ mc {{.Name}} s3/personalbuck/meeting-notes.txt
3. Copy an ISO image to an object on Amazon S3 cloud storage and Google Cloud Storage simultaneously.
$ cat debian-8.2.iso | mc {{.Name}} s3.amazonaws.com/ferenginar/gnuos.iso
$ cat debian-8.2.iso | mc {{.Name}} s3/ferenginar/gnuos.iso
4. Stream MySQL database dump to Amazon S3 directly.
$ mysqldump -u root -p ******* accountsdb | mc {{.Name}} s3.amazonaws.com/ferenginar/backups/accountsdb-oct-9-2015.sql
$ mysqldump -u root -p ******* accountsdb | mc {{.Name}} s3/ferenginar/backups/accountsdb-oct-9-2015.sql
`,
}
@@ -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:
@@ -104,9 +104,8 @@ func mainPipe(ctx *cli.Context) {
fatalIf(err.Trace("stdout"), "Unable to write to one or more targets.")
} else {
// extract URLs.
URLs, err := args2URLs(ctx.Args())
fatalIf(err.Trace(ctx.Args()...), "Unable to parse arguments.")
err = pipe(URLs[0])
URLs := ctx.Args()
err := pipe(URLs[0])
fatalIf(err.Trace(URLs[0]), "Unable to write to one or more targets.")
}
}
+11 -11
View File
@@ -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)
@@ -61,12 +61,12 @@ type Content struct {
// Config - see http://docs.amazonwebservices.com/AmazonS3/latest/dev/index.html?RESTAuthentication.html
type Config struct {
AccessKeyID string
SecretAccessKey string
Signature string
HostURL string
AppName string
AppVersion string
AppComments []string
Debug bool
AccessKey string
SecretKey string
Signature string
HostURL string
AppName string
AppVersion string
AppComments []string
Debug bool
}
+51 -11
View File
@@ -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
}
+3 -3
View File
@@ -62,11 +62,11 @@ func (f *fsClient) fsStat() (os.FileInfo, *probe.Error) {
if e != nil {
if os.IsPermission(e) {
if runtime.GOOS == "windows" {
return f.handleWindowsSymlinks(fpath)
return f.handleWindowsSymlinks(f.PathURL.Path)
}
return nil, probe.NewError(client.PathInsufficientPermission{Path: fpath})
return nil, probe.NewError(client.PathInsufficientPermission{Path: f.PathURL.Path})
}
err := f.toClientError(e, fpath)
err := f.toClientError(e, f.PathURL.Path)
return nil, err.Trace(fpath)
}
st, e := os.Stat(fpath)
+77 -38
View File
@@ -23,12 +23,47 @@ import (
"sort"
)
// byDirName implements sort.Interface.
type byDirName []os.FileInfo
func (f byDirName) Len() int { return len(f) }
func (f byDirName) Less(i, j int) bool {
// For directory add an ending separator fortrue lexical order.
if f[i].Mode().IsDir() {
return f[i].Name()+string(filepath.Separator) < f[j].Name()
}
// For directory add an ending separator for true lexical order.
if f[j].Mode().IsDir() {
return f[i].Name() < f[j].Name()+string(filepath.Separator)
}
return f[i].Name() < f[j].Name()
}
func (f byDirName) Swap(i, j int) { f[i], f[j] = f[j], f[i] }
// readDir reads the directory named by dirname and returns
// a list of sorted directory entries.
func readDir(dirname string) ([]os.FileInfo, error) {
f, e := os.Open(dirname)
if e != nil {
return nil, e
}
list, e := f.Readdir(-1)
if e != nil {
return nil, e
}
if e = f.Close(); e != nil {
return nil, e
}
sort.Sort(byDirName(list))
return list, nil
}
// readDirNames reads the directory named by dirname and returns
// a sorted list of directory entries.
func readDirNames(dirname string) ([]string, error) {
names, err := readDirUnsortedNames(dirname)
if err != nil {
return nil, err
names, e := readDirUnsortedNames(dirname)
if e != nil {
return nil, e
}
sort.Strings(names)
return names, nil
@@ -40,20 +75,24 @@ func readDirNames(dirname string) ([]string, error) {
func getRealName(info os.FileInfo) string {
if info.IsDir() {
// Make sure directory has its end separator.
return info.Name() + string(os.PathSeparator)
return info.Name() + string(filepath.Separator)
}
return info.Name()
}
// readDirUnsortedNames reads the directory named by dirname and
// return a unsorted list of directory entries.
func readDirUnsortedNames(dirname string) ([]string, error) {
f, err := os.Open(dirname)
if err != nil {
return nil, err
f, e := os.Open(dirname)
if e != nil {
return nil, e
}
nameInfos, err := f.Readdir(-1)
f.Close()
if err != nil {
return nil, err
nameInfos, e := f.Readdir(-1)
if e != nil {
return nil, e
}
if e = f.Close(); e != nil {
return nil, e
}
var names []string
for _, nameInfo := range nameInfos {
@@ -62,14 +101,14 @@ func readDirUnsortedNames(dirname string) ([]string, error) {
return names, nil
}
// Walk walks the file tree rooted at root, calling walkFn for each file or
// walk walks the file tree rooted at root, calling walkFn for each file or
// directory in the tree, including root.
func Walk(root string, walkFn WalkFunc) error {
info, err := os.Lstat(root)
if err != nil {
return walkFn(root, nil, err)
func walk(root string, walkFn walkFunc) error {
info, e := os.Lstat(root)
if e != nil {
return walkFn(root, nil, e)
}
return walk(root, info, walkFn)
return walkInternal(root, info, walkFn)
}
// WalkFunc is the type of the function called for each file or directory
@@ -77,51 +116,51 @@ func Walk(root string, walkFn WalkFunc) error {
// prefix; that is, if Walk is called with "dir", which is a directory
// containing the file "a", the walk function will be called with argument
// "dir/a". The info argument is the os.FileInfo for the named path.
type WalkFunc func(path string, info os.FileInfo, err error) error
type walkFunc func(path string, info os.FileInfo, e error) error
// ErrSkipDir is used as a return value from WalkFuncs to indicate that
// the directory named in the call is to be skipped. It is not returned
// as an error by any function.
var ErrSkipDir = errors.New("skip this directory")
var errSkipDir = errors.New("skip this directory")
// ErrSkipFile is used as a return value from WalkFuncs to indicate that
// the file named in the call is to be skipped. It is not returned
// as an error by any function.
var ErrSkipFile = errors.New("skip this file")
var errSkipFile = errors.New("skip this file")
// walk recursively descends path, calling w.
func walk(path string, info os.FileInfo, walkFn WalkFunc) error {
err := walkFn(path, info, nil)
if err != nil {
if info.Mode().IsDir() && err == ErrSkipDir {
// walkInternal recursively descends path, calling w.
func walkInternal(path string, info os.FileInfo, walkFn walkFunc) error {
e := walkFn(path, info, nil)
if e != nil {
if info.Mode().IsDir() && e == errSkipDir {
return nil
}
if info.Mode().IsRegular() && err == ErrSkipFile {
if info.Mode().IsRegular() && e == errSkipFile {
return nil
}
return err
return e
}
if !info.IsDir() {
return nil
}
names, err := readDirNames(path)
if err != nil {
return walkFn(path, info, err)
names, e := readDirNames(path)
if e != nil {
return walkFn(path, info, e)
}
for _, name := range names {
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 {
return err
fileInfo, e := os.Lstat(filename)
if e != nil {
if e = walkFn(filename, fileInfo, e); e != nil && e != errSkipDir && e != errSkipFile {
return e
}
} else {
err = walk(filename, fileInfo, walkFn)
if err != nil {
if err == ErrSkipDir || err == ErrSkipFile {
e = walkInternal(filename, fileInfo, walkFn)
if e != nil {
if e == errSkipDir || e == errSkipFile {
return nil
}
return err
return e
}
}
}
+127 -49
View File
@@ -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.
@@ -202,7 +280,7 @@ func (f *fsClient) List(recursive, incomplete bool) <-chan *client.Content {
// listPrefixes - list all files for any given prefix.
func (f *fsClient) listPrefixes(prefix string, contentCh chan<- *client.Content, incomplete bool) {
dirName := filepath.Dir(prefix)
files, e := ioutil.ReadDir(dirName)
files, e := readDir(dirName)
if e != nil {
err := f.toClientError(e, dirName)
contentCh <- &client.Content{
@@ -347,7 +425,7 @@ func (f *fsClient) listInRoutine(contentCh chan<- *client.Content, incomplete bo
// If we really see the directory.
switch fst.Mode().IsDir() {
case true:
files, e := ioutil.ReadDir(fpath)
files, e := readDir(fpath)
if err != nil {
contentCh <- &client.Content{Err: probe.NewError(e)}
return
@@ -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,
@@ -457,7 +535,7 @@ func (f *fsClient) listRecursiveInRoutine(contentCh chan *client.Content, incomp
var filePrefix string
pathURL := *f.PathURL
visitFS := func(fp string, fi os.FileInfo, e error) error {
// If file path ends with os.PathSeparator and equals to root path, skip it.
// If file path ends with filepath.Separator and equals to root path, skip it.
if strings.HasSuffix(fp, string(pathURL.Separator)) {
if fp == dirName {
return nil
@@ -477,7 +555,7 @@ func (f *fsClient) listRecursiveInRoutine(contentCh chan *client.Content, incomp
!strings.HasPrefix(filePrefix, fp) {
if e == nil {
if fi.IsDir() {
return ErrSkipDir
return errSkipDir
}
return nil
}
@@ -610,22 +688,22 @@ func (f *fsClient) listRecursiveInRoutine(contentCh chan *client.Content, incomp
}
// No prefix to be filtered by default.
filePrefix = ""
// if f.Path ends with os.PathSeparator - assuming it to be a directory and moving on.
// if f.Path ends with filepath.Separator - assuming it to be a directory and moving on.
if strings.HasSuffix(pathURL.Path, string(pathURL.Separator)) {
dirName = pathURL.Path
} else {
// if not a directory, take base path to navigate through WalkFunc.
dirName = filepath.Dir(pathURL.Path)
if !strings.HasSuffix(dirName, string(pathURL.Separator)) {
// basepath truncates the os.PathSeparator,
// basepath truncates the filepath.Separator,
// add it deligently useful for trimming file path inside WalkFunc
dirName = dirName + string(pathURL.Separator)
}
// filePrefix is kept for filtering incoming contents through WalkFunc.
filePrefix = pathURL.Path
}
// Walks invokes our custom function.
e := Walk(dirName, visitFS)
// walks invokes our custom function.
e := walk(dirName, visitFS)
if e != nil {
contentCh <- &client.Content{
Err: probe.NewError(e),
@@ -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)
+69 -36
View File
@@ -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))
}
@@ -1,4 +1,4 @@
// +build darwin dragonfly freebsd linux nacl netbsd openbsd solaris
// +build !windows
/*
* Minio Client (C) 2015 Minio, Inc.
+298 -207
View File
@@ -18,6 +18,7 @@ package s3
import (
"errors"
"hash/fnv"
"io"
"net/http"
"os"
@@ -35,77 +36,169 @@ 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
}
// New returns an initialized s3Client structure. if debug use a internal trace transport.
func New(config *client.Config) (client.Client, *probe.Error) {
u := client.NewURL(config.HostURL)
transport := http.DefaultTransport
if config.Debug == true {
if config.Signature == "S3v4" {
transport = httptracer.GetNewTraceTransport(NewTraceV4(), http.DefaultTransport)
// newFactory encloses New function with client cache.
func newFactory() func(config *client.Config) (client.Client, *probe.Error) {
clientCache := make(map[uint32]minio.CloudStorageClient)
mutex := &sync.Mutex{}
// Return New function.
return func(config *client.Config) (client.Client, *probe.Error) {
// Creates a parsed URL.
targetURL := client.NewURL(config.HostURL)
// By default enable HTTPs.
inSecure := false
if targetURL.Scheme == "http" {
inSecure = true
}
if config.Signature == "S3v2" {
transport = httptracer.GetNewTraceTransport(NewTraceV2(), http.DefaultTransport)
}
}
s3Conf := minio.Config{
AccessKeyID: config.AccessKeyID,
SecretAccessKey: config.SecretAccessKey,
Transport: transport,
Endpoint: u.Scheme + u.SchemeSeparator + u.Host,
Signature: func() minio.SignatureType {
if config.Signature == "S3v2" {
return minio.SignatureV2
// 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"
}
return minio.SignatureV4
}(),
// 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(hostName + config.AccessKey + config.SecretKey))
confSum := confHash.Sum32()
// Lookup previous cache by hash.
mutex.Lock()
defer mutex.Unlock()
var api minio.CloudStorageClient
found := false
if api, found = clientCache[confSum]; !found {
// Not found. Instantiate a new minio client.
var e error
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)
if config.Debug {
transport := http.DefaultTransport
if config.Signature == "S3v4" {
transport = httptracer.GetNewTraceTransport(NewTraceV4(), http.DefaultTransport)
}
if config.Signature == "S3v2" {
transport = httptracer.GetNewTraceTransport(NewTraceV2(), http.DefaultTransport)
}
// Set custom transport.
api.SetCustomTransport(transport)
}
// Store the new api object.
s3Clnt.api = api
return s3Clnt, nil
}
s3Conf.SetUserAgent(config.AppName, config.AppVersion, config.AppComments...)
api, e := minio.New(s3Conf)
if e != nil {
return nil, probe.NewError(e)
}
s3Clnt := &s3Client{
mu: new(sync.Mutex),
api: api,
hostURL: u,
virtualStyle: isVirtualHostStyle(u.Host),
}
return s3Clnt, nil
}
// New returns an initialized s3Client structure. If debug is enabled,
// it also enables an internal trace transport.
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 == "" {
@@ -116,91 +209,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)
}
@@ -241,77 +278,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)
}
_, e := c.api.ListBuckets()
if e != nil {
c.mutex.Unlock()
return nil, probe.NewError(e)
}
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,
@@ -319,16 +362,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 = ""
@@ -347,8 +390,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 {
@@ -373,14 +416,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),
@@ -388,14 +433,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()
@@ -410,7 +455,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),
@@ -418,14 +464,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()
@@ -447,23 +493,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
@@ -472,14 +520,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 {
@@ -501,14 +550,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
@@ -517,7 +567,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{
@@ -525,7 +575,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:
@@ -533,13 +583,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),
@@ -547,14 +598,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()
@@ -577,21 +628,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),
@@ -599,7 +652,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
@@ -609,7 +662,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),
@@ -617,7 +671,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.
@@ -632,3 +686,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)
}
+69 -9
View File
@@ -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("<LocationConstraint xmlns=\"http://doc.s3.amazonaws.com/2006-03-01\"></LocationConstraint>")
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("<ListAllMyBucketsResult xmlns=\"http://doc.s3.amazonaws.com/2006-03-01\"><Buckets><Bucket><Name>bucket</Name><CreationDate>2015-05-20T23:05:09.230Z</CreationDate></Bucket></Buckets><Owner><ID>minio</ID><DisplayName>minio</DisplayName></Owner></ListAllMyBucketsResult>")
w.Header().Set("Content-Length", strconv.Itoa(len(response)))
w.Write(response)
case r.URL.Path == "/bucket":
case r.URL.Path == "/bucket/":
// Handler for incoming ListObjects request.
response := []byte("<ListBucketResult xmlns=\"http://doc.s3.amazonaws.com/2006-03-01\"><Contents><ETag>259d04a13802ae09c7e41be50ccc6baa</ETag><Key>object</Key><LastModified>2015-05-21T18:24:21.097Z</LastModified><Size>22061</Size><Owner><ID>minio</ID><DisplayName>minio</DisplayName></Owner><StorageClass>STANDARD</StorageClass></Contents><Delimiter></Delimiter><EncodingType></EncodingType><IsTruncated>false</IsTruncated><Marker></Marker><MaxKeys>1000</MaxKeys><Name>testbucket</Name><NextMarker></NextMarker><Prefix></Prefix></ListBucketResult>")
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,14 +90,14 @@ type objectHandler struct {
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 {
// Handler for PUT object request.
length, e := strconv.Atoi(r.Header.Get("Content-Length"))
if e != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
var buffer bytes.Buffer
_, err = io.CopyN(&buffer, r.Body, int64(length))
if err != nil {
if _, e = io.CopyN(&buffer, r.Body, int64(length)); e != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
@@ -98,6 +108,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 +117,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("<InitiateMultipartUploadResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\"><Bucket>bucket</Bucket><Key>object</Key><UploadId>EXAMPLEJZ6e0YupT2h66iePQCc9IEbYbDUy4RTpMeoSMLPRp8Z5o1u8feSRonpvnWsKKG35tI2LB9VDPiCgTy.Gq2VxQLYjrue4Nq.NBdqI-</UploadId></InitiateMultipartUploadResult>")
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("<CompleteMultipartUploadResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\"><Location>http://bucket.s3.amazonaws.com/object</Location><Bucket>bucket</Bucket><Key>object</Key><ETag>\"3858f62230ac3c915f300c664312c11f-9\"</ETag></CompleteMultipartUploadResult>")
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("<LocationConstraint xmlns=\"http://doc.s3.amazonaws.com/2006-03-01\"></LocationConstraint>")
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("<ListMultipartUploadsResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\"><Bucket>bucket</Bucket><KeyMarker/><UploadIdMarker/><NextKeyMarker/><NextUploadIdMarker/><EncodingType/><MaxUploads>1000</MaxUploads><IsTruncated>false</IsTruncated><Prefix/><Delimiter/></ListMultipartUploadsResult>")
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,19 +174,23 @@ type MySuite struct{}
var _ = Suite(&MySuite{})
// Test bucket operations.
func (s *MySuite) TestBucketOperations(c *C) {
bucket := bucketHandler(bucketHandler{
resource: "/bucket",
resource: "/bucket/",
})
server := httptest.NewServer(bucket)
defer server.Close()
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 +224,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 +235,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)
+10 -1
View File
@@ -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))
}
+10 -1
View File
@@ -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))
}
+6 -22
View File
@@ -120,28 +120,12 @@ func NewURL(urlStr string) *URL {
// JoinURLs join two input urls and returns a url
func JoinURLs(url1, url2 *URL) *URL {
var url1Path, url2Path string
url1Path = url1.Path
url2Path = url2.Path
if runtime.GOOS == "windows" {
url1Path = strings.Replace(url1.Path, "\\", "/", -1)
url2Path = strings.Replace(url2.Path, "\\", "/", -1)
}
if url1.Type == Object {
if strings.HasSuffix(url1Path, "/") {
url1.Path = url1Path + strings.TrimPrefix(url2Path, "/")
} else {
url1.Path = url1Path + "/" + strings.TrimPrefix(url2Path, "/")
}
}
if url1.Type == Filesystem {
if strings.HasSuffix(url1Path, "/") {
url1.Path = url1Path + strings.TrimPrefix(url2Path, "/")
} else {
url1.Path = url1Path + "/" + strings.TrimPrefix(url2Path, "/")
}
if runtime.GOOS == "windows" {
url1.Path = strings.Replace(url1.Path, "/", "\\", -1)
}
url1Path = filepath.ToSlash(url1.Path)
url2Path = filepath.ToSlash(url2.Path)
if strings.HasSuffix(url1Path, "/") {
url1.Path = url1Path + strings.TrimPrefix(url2Path, "/")
} else {
url1.Path = url1Path + "/" + strings.TrimPrefix(url2Path, "/")
}
return url1
}
+54
View File
@@ -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}
}
+55
View File
@@ -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)
}
+63 -151
View File
@@ -28,85 +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 {
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.
@@ -122,9 +114,9 @@ func cursorAnimate() <-chan rune {
// cursors = "←↖↑↗→↘↓↙"
// cursors = "◴◷◶◵"
// cursors = "◰◳◲◱"
//cursors = "⣾⣽⣻⢿⡿⣟⣯⣷"
case "darwin":
cursors = "◐◓◑◒"
//cursors = "⣾⣽⣻⢿⡿⣟⣯⣷"
default:
cursors = "|/-\\"
}
@@ -157,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}
}
+24 -34
View File
@@ -19,6 +19,7 @@ package main
import (
"encoding/json"
"fmt"
"path/filepath"
"strings"
"github.com/fatih/color"
@@ -73,19 +74,19 @@ EXAMPLES:
$ mc {{.Name}} 1999/old-backup.tgz
2. Remove contents of a folder, excluding its sub-folders.
$ mc {{.Name}} --force s3.amazonaws.com/jazz-songs/louis/
$ mc {{.Name}} --force s3/jazz-songs/louis/
3. Remove contents of a folder recursively.
$ mc {{.Name}} --force --recursive s3.amazonaws.com/jazz-songs/louis/
$ mc {{.Name}} --force --recursive s3/jazz-songs/louis/
4. Remove all matching objects with this prefix.
$ mc {{.Name}} --force s3.amazonaws.com/ogg/gunmetal
$ mc {{.Name}} --force s3/ogg/gunmetal
5. Drop an incomplete upload of an object.
$ mc {{.Name}} --incomplete s3.amazonaws.com/jazz-songs/louis/file01.mp3
$ mc {{.Name}} --incomplete s3/jazz-songs/louis/file01.mp3
6. Drop all incomplete uploads recursively matching this prefix.
$ mc {{.Name}} --incomplete --force --recursive s3.amazonaws.com/jazz-songs/louis/
$ mc {{.Name}} --incomplete --force --recursive s3/jazz-songs/louis/
`,
}
@@ -112,23 +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 {
URLs, err := args2URLs(ctx.Args())
fatalIf(err.Trace(ctx.Args()...), "Unable to parse arguments.")
for _, url := range URLs {
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.")
@@ -136,10 +127,10 @@ func checkRmSyntax(ctx *cli.Context) {
}
// Remove a single object.
func rm(url string, isIncomplete, isFake bool) *probe.Error {
clnt, err := url2Client(url)
func rm(targetAlias, targetURL string, isIncomplete, isFake bool) *probe.Error {
clnt, err := newClientFromAlias(targetAlias, targetURL)
if err != nil {
return err.Trace(url)
return err.Trace(targetURL)
}
if isFake { // It is a fake remove. Return success.
@@ -147,18 +138,18 @@ func rm(url string, isIncomplete, isFake bool) *probe.Error {
}
if err = clnt.Remove(isIncomplete); err != nil {
return err.Trace(url)
return err.Trace(targetURL)
}
return nil
}
// Remove all objects recursively.
func rmAll(url string, isRecursive, isIncomplete, isFake bool) {
func rmAll(targetAlias, targetURL string, isRecursive, isIncomplete, isFake bool) {
// Initialize new client.
clnt, err := url2Client(url)
clnt, err := newClientFromAlias(targetAlias, targetURL)
if err != nil {
errorIf(err.Trace(url), "Invalid URL ‘"+url+"’.")
errorIf(err.Trace(targetURL), "Invalid URL ‘"+targetURL+"’.")
return // End of journey.
}
@@ -167,7 +158,7 @@ func rmAll(url string, isRecursive, isIncomplete, isFake bool) {
nonRecursive := false
for entry := range clnt.List(nonRecursive, isIncomplete) {
if entry.Err != nil {
errorIf(entry.Err.Trace(url), "Unable to list ‘"+url+"’.")
errorIf(entry.Err.Trace(targetURL), "Unable to list ‘"+targetURL+"’.")
return // End of journey.
}
@@ -177,15 +168,17 @@ func rmAll(url string, isRecursive, isIncomplete, isFake bool) {
url.Path = strings.TrimSuffix(entry.URL.Path, string(entry.URL.Separator)) + string(entry.URL.Separator)
// Recursively remove contents of this directory.
rmAll(url.String(), isRecursive, isIncomplete, isFake)
rmAll(targetAlias, url.String(), isRecursive, isIncomplete, isFake)
}
// Regular type.
if err = rm(entry.URL.String(), isIncomplete, isFake); err != nil {
if err = rm(targetAlias, entry.URL.String(), isIncomplete, isFake); err != nil {
errorIf(err.Trace(entry.URL.String()), "Unable to remove ‘"+entry.URL.String()+"’.")
continue
}
printMsg(rmMessage{Status: "success", URL: entry.URL.String()})
// Construct user facing message and path.
entryPath := filepath.ToSlash(filepath.Join(targetAlias, entry.URL.Path))
printMsg(rmMessage{Status: "success", URL: entryPath})
}
}
@@ -206,16 +199,13 @@ func mainRm(ctx *cli.Context) {
// Set color.
console.SetColor("Remove", color.New(color.FgGreen, color.Bold))
// Parse args.
URLs, err := args2URLs(ctx.Args())
fatalIf(err.Trace(ctx.Args()...), "Unable to parse arguments.")
// Support multiple targets.
for _, url := range URLs {
for _, url := range ctx.Args() {
targetAlias, targetURL, _ := mustExpandAlias(url)
if isRecursive && isForce {
rmAll(url, isRecursive, isIncomplete, isFake)
rmAll(targetAlias, targetURL, isRecursive, isIncomplete, isFake)
} else {
if err := rm(url, isIncomplete, isFake); err != nil {
if err := rm(targetAlias, targetURL, isIncomplete, isFake); err != nil {
errorIf(err.Trace(url), "Unable to remove ‘"+url+"’.")
continue
}
+3 -3
View File
@@ -47,9 +47,9 @@ func scanBarFactory() scanBarFunc {
prevLineSize := 0
prevSource := ""
fileCount := 0
termSize, err := ts.GetSize()
if err != nil {
fatalIf(probe.NewError(err), "Unable to get terminal size. Please use --quiet option.")
termSize, e := ts.GetSize()
if e != nil {
fatalIf(probe.NewError(e), "Unable to get terminal size. Please use --quiet option.")
}
termWidth := termSize.Col()
cursorCh := cursorAnimate()
+9 -9
View File
@@ -77,7 +77,7 @@ EXAMPLES:
}
// bySessionWhen is a type for sorting session metadata by time.
type bySessionWhen []*sessionV5
type bySessionWhen []*sessionV6
func (b bySessionWhen) Len() int { return len(b) }
func (b bySessionWhen) Swap(i, j int) { b[i], b[j] = b[j], b[i] }
@@ -85,9 +85,9 @@ func (b bySessionWhen) Less(i, j int) bool { return b[i].Header.When.Before(b[j]
// listSessions list all current sessions.
func listSessions() *probe.Error {
var bySessions []*sessionV5
var bySessions []*sessionV6
for _, sid := range getSessionIDs() {
s, err := loadSessionV5(sid)
s, err := loadSessionV6(sid)
if err != nil {
return err.Trace(sid)
}
@@ -115,8 +115,8 @@ func (c clearSessionMessage) String() string {
// JSON jsonified clear session message.
func (c clearSessionMessage) JSON() string {
clearSessionJSONBytes, err := json.Marshal(c)
fatalIf(probe.NewError(err), "Unable to marshal into JSON.")
clearSessionJSONBytes, e := json.Marshal(c)
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(clearSessionJSONBytes)
}
@@ -125,7 +125,7 @@ func (c clearSessionMessage) JSON() string {
func clearSession(sid string) {
if sid == "all" {
for _, sid := range getSessionIDs() {
session, err := loadSessionV5(sid)
session, err := loadSessionV6(sid)
fatalIf(err.Trace(sid), "Unable to load session ‘"+sid+"’.")
fatalIf(session.Delete().Trace(sid), "Unable to load session ‘"+sid+"’.")
@@ -139,7 +139,7 @@ func clearSession(sid string) {
fatalIf(errDummy().Trace(sid), "Session ‘"+sid+"’ not found.")
}
session, err := loadSessionV5(sid)
session, err := loadSessionV6(sid)
fatalIf(err.Trace(sid), "Unable to load session ‘"+sid+"’.")
if session != nil {
@@ -148,7 +148,7 @@ func clearSession(sid string) {
}
}
func sessionExecute(s *sessionV5) {
func sessionExecute(s *sessionV6) {
switch s.Header.CommandType {
case "cp":
doCopySession(s)
@@ -230,7 +230,7 @@ func mainSession(ctx *cli.Context) {
}
fatalIf(errDummy().Trace(sid), errorMsg)
}
s, err := loadSessionV5(sid)
s, err := loadSessionV6(sid)
fatalIf(err.Trace(sid), "Unable to load session.")
// Restore the state of global variables from this previous session.
+41 -43
View File
@@ -32,14 +32,14 @@ import (
"github.com/minio/minio-xl/pkg/quick"
)
func migrateSessionV4ToV5() {
func migrateSessionV5ToV6() {
for _, sid := range getSessionIDs() {
sessionV5, err := loadSessionV5(sid)
fatalIf(err.Trace(sid), "Unable to load version ‘5’. Migration failed please report this issue at https://github.com/minio/mc/issues.")
if sessionV5.Header.Version == "5" { // It is new format.
sessionV6, err := loadSessionV6(sid)
fatalIf(err.Trace(sid), "Unable to load version ‘6’. Migration failed please report this issue at https://github.com/minio/mc/issues.")
if sessionV6.Header.Version == "6" { // It is new format.
return
}
/*** Remove all session files older than v5 ***/
/*** Remove all session files older than v6 ***/
sessionFile, err := getSessionFile(sid)
fatalIf(err.Trace(sid), "Unable to get session file.")
@@ -47,18 +47,18 @@ func migrateSessionV4ToV5() {
sessionDataFile, err := getSessionDataFile(sid)
fatalIf(err.Trace(sid), "Unable to get session data file.")
console.Println("Removing unsupported session file ‘" + sessionFile + "’ version ‘" + sessionV5.Header.Version + "’.")
console.Println("Removing unsupported session file ‘" + sessionFile + "’ version ‘" + sessionV6.Header.Version + "’.")
if e := os.Remove(sessionFile); e != nil {
fatalIf(probe.NewError(e), "Unable to remove version ‘"+sessionV5.Header.Version+"’ session file ‘"+sessionFile+"’.")
fatalIf(probe.NewError(e), "Unable to remove version ‘"+sessionV6.Header.Version+"’ session file ‘"+sessionFile+"’.")
}
if e := os.Remove(sessionDataFile); e != nil {
fatalIf(probe.NewError(e), "Unable to remove version ‘"+sessionV5.Header.Version+"’ session data file ‘"+sessionDataFile+"’.")
fatalIf(probe.NewError(e), "Unable to remove version ‘"+sessionV6.Header.Version+"’ session data file ‘"+sessionDataFile+"’.")
}
}
}
// sessionV5Header for resumable sessions.
type sessionV5Header struct {
// sessionV6Header for resumable sessions.
type sessionV6Header struct {
Version string `json:"version"`
When time.Time `json:"time"`
RootPath string `json:"workingFolder"`
@@ -84,9 +84,9 @@ type sessionMessage struct {
CommandArgs []string `json:"commandArgs"`
}
// sessionV5 resumable session container.
type sessionV5 struct {
Header *sessionV5Header
// sessionV6 resumable session container.
type sessionV6 struct {
Header *sessionV6Header
SessionID string
mutex *sync.Mutex
DataFP *sessionDataFP
@@ -105,7 +105,7 @@ func (file *sessionDataFP) Write(p []byte) (int, error) {
}
// String colorized session message.
func (s sessionV5) String() string {
func (s sessionV6) String() string {
message := console.Colorize("SessionID", fmt.Sprintf("%s -> ", s.SessionID))
message = message + console.Colorize("SessionTime", fmt.Sprintf("[%s]", s.Header.When.Local().Format(printDate)))
message = message + console.Colorize("Command", fmt.Sprintf(" %s %s", s.Header.CommandType, strings.Join(s.Header.CommandArgs, " ")))
@@ -113,7 +113,7 @@ func (s sessionV5) String() string {
}
// JSON jsonified session message.
func (s sessionV5) JSON() string {
func (s sessionV6) JSON() string {
sessionMsg := sessionMessage{
SessionID: s.SessionID,
Time: s.Header.When.Local(),
@@ -127,8 +127,8 @@ func (s sessionV5) JSON() string {
return string(sessionBytes)
}
// loadSessionV5 - reads session file if exists and re-initiates internal variables
func loadSessionV5(sid string) (*sessionV5, *probe.Error) {
// loadSessionV6 - reads session file if exists and re-initiates internal variables
func loadSessionV6(sid string) (*sessionV6, *probe.Error) {
if !isSessionDirExists() {
return nil, errInvalidArgument().Trace()
}
@@ -137,12 +137,12 @@ func loadSessionV5(sid string) (*sessionV5, *probe.Error) {
return nil, err.Trace(sid)
}
if _, err := os.Stat(sessionFile); err != nil {
return nil, probe.NewError(err)
if _, e := os.Stat(sessionFile); e != nil {
return nil, probe.NewError(e)
}
s := &sessionV5{}
s.Header = &sessionV5Header{}
s := &sessionV6{}
s.Header = &sessionV6Header{}
s.SessionID = sid
s.Header.Version = "5"
qs, err := quick.New(s.Header)
@@ -155,7 +155,7 @@ func loadSessionV5(sid string) (*sessionV5, *probe.Error) {
}
s.mutex = new(sync.Mutex)
s.Header = qs.Data().(*sessionV5Header)
s.Header = qs.Data().(*sessionV6Header)
sessionDataFile, err := getSessionDataFile(s.SessionID)
if err != nil {
@@ -171,11 +171,11 @@ func loadSessionV5(sid string) (*sessionV5, *probe.Error) {
return s, nil
}
// newSessionV5 provides a new session.
func newSessionV5() *sessionV5 {
s := &sessionV5{}
s.Header = &sessionV5Header{}
s.Header.Version = "5"
// newSessionV6 provides a new session.
func newSessionV6() *sessionV6 {
s := &sessionV6{}
s.Header = &sessionV6Header{}
s.Header.Version = "6"
// map of command and files copied.
s.Header.GlobalBoolFlags = make(map[string]bool)
s.Header.GlobalIntFlags = make(map[string]int)
@@ -203,7 +203,7 @@ func newSessionV5() *sessionV5 {
}
// HasData provides true if this is a session resume, false otherwise.
func (s sessionV5) HasData() bool {
func (s sessionV6) HasData() bool {
if s.Header.LastCopied == "" {
return false
}
@@ -211,21 +211,21 @@ func (s sessionV5) HasData() bool {
}
// NewDataReader provides reader interface to session data file.
func (s *sessionV5) NewDataReader() io.Reader {
func (s *sessionV6) NewDataReader() io.Reader {
// DataFP is always intitialized, either via new or load functions.
s.DataFP.Seek(0, os.SEEK_SET)
return io.Reader(s.DataFP)
}
// NewDataReader provides writer interface to session data file.
func (s *sessionV5) NewDataWriter() io.Writer {
func (s *sessionV6) NewDataWriter() io.Writer {
// DataFP is always intitialized, either via new or load functions.
s.DataFP.Seek(0, os.SEEK_SET)
return io.Writer(s.DataFP)
}
// Save this session.
func (s *sessionV5) Save() *probe.Error {
func (s *sessionV6) Save() *probe.Error {
s.mutex.Lock()
defer s.mutex.Unlock()
@@ -250,7 +250,7 @@ func (s *sessionV5) Save() *probe.Error {
// setGlobals captures the state of global variables into session header.
// Used by newSession.
func (s *sessionV5) setGlobals() {
func (s *sessionV6) setGlobals() {
s.Header.GlobalBoolFlags["quiet"] = globalQuiet
s.Header.GlobalBoolFlags["debug"] = globalDebug
s.Header.GlobalBoolFlags["json"] = globalJSON
@@ -259,7 +259,7 @@ func (s *sessionV5) setGlobals() {
// RestoreGlobals restores the state of global variables.
// Used by resumeSession.
func (s sessionV5) restoreGlobals() {
func (s sessionV6) restoreGlobals() {
quiet := s.Header.GlobalBoolFlags["quiet"]
debug := s.Header.GlobalBoolFlags["debug"]
json := s.Header.GlobalBoolFlags["json"]
@@ -268,7 +268,7 @@ func (s sessionV5) restoreGlobals() {
}
// Close ends this session and removes all associated session files.
func (s *sessionV5) Close() *probe.Error {
func (s *sessionV6) Close() *probe.Error {
s.mutex.Lock()
defer s.mutex.Unlock()
@@ -289,7 +289,7 @@ func (s *sessionV5) Close() *probe.Error {
}
// Delete removes all the session files.
func (s *sessionV5) Delete() *probe.Error {
func (s *sessionV6) Delete() *probe.Error {
s.mutex.Lock()
defer s.mutex.Unlock()
@@ -300,9 +300,8 @@ func (s *sessionV5) Delete() *probe.Error {
// the file is closed already
s.DataFP.Close()
err := os.Remove(name)
if err != nil {
return probe.NewError(err)
if e := os.Remove(name); e != nil {
return probe.NewError(e)
}
}
@@ -311,18 +310,17 @@ func (s *sessionV5) Delete() *probe.Error {
return err.Trace(s.SessionID)
}
if err := os.Remove(sessionFile); err != nil {
return probe.NewError(err)
if e := os.Remove(sessionFile); e != nil {
return probe.NewError(e)
}
return nil
}
// Close a session and exit.
func (s sessionV5) CloseAndDie() {
func (s sessionV6) CloseAndDie() {
s.Close()
console.Infoln("Session safely terminated. To resume session ‘mc session resume " + s.SessionID + "’")
os.Exit(0)
console.Fatalln("Session safely terminated. To resume session ‘mc session resume " + s.SessionID + "’")
}
// Create a factory function to simplify checking if an
+3 -3
View File
@@ -27,7 +27,7 @@ import (
// migrateSession migrates all previous migration to latest.
func migrateSession() {
// We no longer support sessions older than v5. They will be removed.
migrateSessionV4ToV5()
migrateSessionV5ToV6()
}
// createSessionDir - create session directory.
@@ -37,8 +37,8 @@ func createSessionDir() *probe.Error {
return err.Trace()
}
if err := os.MkdirAll(sessionDir, 0700); err != nil {
return probe.NewError(err)
if e := os.MkdirAll(sessionDir, 0700); e != nil {
return probe.NewError(e)
}
return nil
}
+2 -2
View File
@@ -34,14 +34,14 @@ func (s *TestSuite) TestSession(c *C) {
c.Assert(err, IsNil)
c.Assert(isSessionDirExists(), Equals, true)
session := newSessionV5()
session := newSessionV6()
c.Assert(session.Header.CommandArgs, IsNil)
c.Assert(len(session.SessionID), Equals, 8)
err = session.Close()
c.Assert(err, IsNil)
savedSession, err := loadSessionV5(session.SessionID)
savedSession, err := loadSessionV6(session.SessionID)
c.Assert(err, IsNil)
c.Assert(session.SessionID, Equals, savedSession.SessionID)
+2 -2
View File
@@ -89,8 +89,8 @@ func (s *shareDBV1) Load(filename string) *probe.Error {
defer s.mutex.Unlock()
// Check if the db file exist.
if _, err := os.Stat(filename); err != nil {
return probe.NewError(err)
if _, e := os.Stat(filename); e != nil {
return probe.NewError(e)
}
// Initialize and load using quick package.
+12 -14
View File
@@ -54,16 +54,16 @@ OPTIONS:
{{end}}
EXAMPLES:
1. Share this object with 7 days default expiry.
$ mc share {{.Name}} s3.amazonaws.com/backup/2006-Mar-1/backup.tar.gz
$ mc share {{.Name}} s3/backup/2006-Mar-1/backup.tar.gz
2. Share this object with 10 minutes expiry.
$ mc share {{.Name}} --expire=10m s3.amazonaws.com/backup/2006-Mar-1/backup.tar.gz
$ mc share {{.Name}} --expire=10m s3/backup/2006-Mar-1/backup.tar.gz
3. Share all objects under this folder with 5 days expiry.
$ mc share {{.Name}} --expire=120h s3.amazonaws.com/backup/
$ mc share {{.Name}} --expire=120h s3/backup/
4. Share all objects under this folder and all its sub-folders with 5 days expiry.
$ mc share {{.Name}} --recursive --expire=120h s3.amazonaws.com/backup/
$ mc share {{.Name}} --recursive --expire=120h s3/backup/
`,
}
@@ -91,10 +91,7 @@ func checkShareDownloadSyntax(ctx *cli.Context) {
fatalIf(errDummy().Trace(expiry.String()), "Expiry cannot be larger than 7 days.")
}
URLs, err := args2URLs(ctx.Args()) // expand alias.
fatalIf(err.Trace(ctx.Args()...), "Unable to convert args to URLs.")
for _, url := range URLs {
for _, url := range ctx.Args() {
_, _, err := url2Stat(url)
fatalIf(err.Trace(url), "Unable to stat ‘"+url+"’.")
}
@@ -102,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 := url2Client(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)
}
@@ -126,7 +127,7 @@ func doShareDownloadURL(targetURL string, isRecursive bool, expiry time.Duration
continue
}
objectURL := content.URL.String()
newClnt, err := url2Client(objectURL)
newClnt, err := newClientFromAlias(targetAlias, objectURL)
if err != nil {
return err.Trace(objectURL)
}
@@ -176,10 +177,7 @@ func mainShareDownload(ctx *cli.Context) {
fatalIf(probe.NewError(e), "Unable to parse expire=‘"+ctx.String("expire")+"’.")
}
URLs, err := args2URLs(ctx.Args()) // expand alias.
fatalIf(err.Trace(ctx.Args()...), "Unable to convert args to URLs.")
for _, targetURL := range URLs {
for _, targetURL := range ctx.Args() {
err := doShareDownloadURL(targetURL, isRecursive, expiry)
fatalIf(err.Trace(targetURL), "Unable to share target ‘"+targetURL+"’.")
}
+10 -13
View File
@@ -58,16 +58,16 @@ OPTIONS:
{{end}}
EXAMPLES:
1. Generate a curl command to allow upload access for a single object. Command expires in 7 days (default).
$ mc share {{.Name}} s3.amazonaws.com/backup/2006-Mar-1/backup.tar.gz
$ mc share {{.Name}} s3/backup/2006-Mar-1/backup.tar.gz
2. Generate a curl command to allow upload access to a folder. Command expires in 120 hours.
$ mc share {{.Name}} --expire=120h s3.amazonaws.com/backup/2007-Mar-2/
$ mc share {{.Name}} --expire=120h s3/backup/2007-Mar-2/
3. Generate a curl command to allow upload access of only '.png' images to a folder. Command expires in 2 hours.
$ mc share {{.Name}} --expire=2h --content-type=image/png s3.amazonaws.com/backup/2007-Mar-2/
$ mc share {{.Name}} --expire=2h --content-type=image/png s3/backup/2007-Mar-2/
4. Generate a curl command to allow upload access to any objects matching the key prefix 'backup/'. Command expires in 2 hours.
$ mc share {{.Name}} --recursive --expire=2h s3.amazonaws.com/backup/2007-Mar-2/backup/
$ mc share {{.Name}} --recursive --expire=2h s3/backup/2007-Mar-2/backup/
`,
}
@@ -100,10 +100,7 @@ func checkShareUploadSyntax(ctx *cli.Context) {
"Expiry cannot be larger than 7 days.")
}
URLs, err := args2URLs(ctx.Args()) // expand alias.
fatalIf(err.Trace(ctx.Args()...), "Unable to convert args to URLs.")
for _, targetURL := range URLs {
for _, targetURL := range ctx.Args() {
url := client.NewURL(targetURL)
if strings.HasSuffix(targetURL, string(url.Separator)) && !isRecursive {
fatalIf(errInvalidArgument().Trace(targetURL),
@@ -155,7 +152,7 @@ func saveSharedURL(objectURL string, shareURL string, expiry time.Duration, cont
// doShareUploadURL uploads files to the target.
func doShareUploadURL(objectURL string, isRecursive bool, expiry time.Duration, contentType string) *probe.Error {
clnt, err := url2Client(objectURL)
clnt, err := newClient(objectURL)
if err != nil {
return err.Trace(objectURL)
}
@@ -166,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)
@@ -205,10 +205,7 @@ func mainShareUpload(ctx *cli.Context) {
fatalIf(probe.NewError(e), "Unable to parse expire=‘"+expireArg+"’.")
}
URLs, err := args2URLs(ctx.Args()) // expand alias.
fatalIf(err.Trace(ctx.Args()...), "Unable to convert args to URLs.")
for _, targetURL := range URLs {
for _, targetURL := range ctx.Args() {
err := doShareUploadURL(targetURL, isRecursive, expiry, contentType)
fatalIf(err.Trace(targetURL), "Unable to generate curl command for upload ‘"+targetURL+"’.")
}
+2 -3
View File
@@ -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.
@@ -131,8 +130,8 @@ func isShareDirExists() bool {
// Create config share dir.
func createShareDir() *probe.Error {
if err := os.MkdirAll(mustGetShareDir(), 0700); err != nil {
return probe.NewError(err)
if e := os.MkdirAll(mustGetShareDir(), 0700); e != nil {
return probe.NewError(e)
}
return nil
}
+4 -4
View File
@@ -31,12 +31,12 @@ var (
return probe.NewError(errors.New("Invalid arguments provided, cannot proceed.")).Untrace()
}
errNoMatchingHost = func(URL string) *probe.Error {
return probe.NewError(errors.New("No matching host found for the given URL ‘" + URL + "’.")).Untrace()
errInvalidAliasedURL = func(URL string) *probe.Error {
return probe.NewError(errors.New("Use ‘mc config host add mycloud " + URL + " ...’ to add an alias. Use the alias for S3 operations.")).Untrace()
}
errInitClient = func(URL string) *probe.Error {
return probe.NewError(errors.New("Unable to initialize client for URL ‘" + URL + "’.")).Untrace()
errNoMatchingHost = func(URL string) *probe.Error {
return probe.NewError(errors.New("No matching host found for the given URL ‘" + URL + "’.")).Untrace()
}
errInvalidSource = func(URL string) *probe.Error {
+4 -4
View File
@@ -102,8 +102,8 @@ func (u updateMessage) String() string {
// JSON jsonified update message.
func (u updateMessage) JSON() string {
u.Status = "success"
updateMessageJSONBytes, err := json.Marshal(u)
fatalIf(probe.NewError(err), "Unable to marshal into JSON.")
updateMessageJSONBytes, e := json.Marshal(u)
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(updateMessageJSONBytes)
}
@@ -170,9 +170,9 @@ func getReleaseUpdate(updateURL string) {
var downloadURL string
if runtime.GOOS == "windows" {
downloadURL = updateURL + runtime.GOOS + "-" + runtime.GOARCH + "/mc.exe"
downloadURL = updateURL + "/" + runtime.GOOS + "-" + runtime.GOARCH + "/mc.exe"
} else {
downloadURL = updateURL + runtime.GOOS + "-" + runtime.GOARCH + "/mc"
downloadURL = updateURL + "/" + runtime.GOOS + "-" + runtime.GOARCH + "/mc"
}
updateMsg := updateMessage{
Download: downloadURL,
+23 -29
View File
@@ -38,36 +38,9 @@ func urlJoinPath(url1, url2 string) string {
return client.JoinURLs(u1, u2).String()
}
// args2URLs extracts source and target URLs from command-line args.
func args2URLs(args []string) ([]string, *probe.Error) {
// convert arguments to URLs: expand alias, fix format...
URLs := []string{}
for _, arg := range args {
aliasedURL, err := getAliasURL(arg)
if err != nil {
return nil, err.Trace(arg)
}
URLs = append(URLs, aliasedURL)
}
return URLs, nil
}
// url2Client convenience wrapper for getNewClient.
func url2Client(urlStr string) (client.Client, *probe.Error) {
urlConfig, err := getHostConfig(urlStr)
if err != nil {
return nil, err.Trace(urlStr)
}
client, err := getNewClient(urlStr, urlConfig)
if err != nil {
return nil, err.Trace(urlStr)
}
return client, nil
}
// url2Stat returns stat info for URL.
func url2Stat(urlStr string) (client client.Client, content *client.Content, err *probe.Error) {
client, err = url2Client(urlStr)
client, err = newClient(urlStr)
if err != nil {
return nil, nil, err.Trace(urlStr)
}
@@ -78,9 +51,30 @@ func url2Stat(urlStr string) (client client.Client, content *client.Content, err
return client, content, nil
}
// url2Alias separates alias and path from the URL. Aliased URL is of
// the form [/]alias/path/to/blah.
func url2Alias(aliasedURL string) (alias, path string) {
// Save aliased url.
urlStr := aliasedURL
// Convert '/' on windows to filepath.Separator.
urlStr = filepath.FromSlash(urlStr)
// Remove '/' prefix before alias, if any.
urlStr = strings.TrimPrefix(urlStr, string(filepath.Separator))
// Remove everything after alias (i.e. after '/').
urlParts := strings.SplitN(urlStr, string(filepath.Separator), 2)
if len(urlParts) == 2 {
// Convert windows style path separator to Unix style.
return urlParts[0], urlParts[1]
}
return urlParts[0], ""
}
// isURLPrefixExists - check if object key prefix exists.
func isURLPrefixExists(urlPrefix string, incomplete bool) bool {
clnt, err := url2Client(urlPrefix)
clnt, err := newClient(urlPrefix)
if err != nil {
return false
}
+1 -1
View File
@@ -14,7 +14,7 @@
- Have test cases for the new code. If you have questions about how to do it, please ask in your pull request.
- Run `go fmt`
- Squash your commits into a single commit. `git rebase -i`. It's okay to force update your pull request.
- Make sure `go test -race ./...` and `go build` completes.
- Make sure `go test -short -race ./...` and `go build` completes.
* Read [Effective Go](https://github.com/golang/go/wiki/CodeReviewComments) article from Golang project
- `minio-go` project is strictly conformant with Golang style
+19
View File
@@ -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
```
+21 -21
View File
@@ -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)
+28 -46
View File
@@ -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
}
+236
View File
@@ -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 ****
<?xml version="1.0" encoding="UTF-8"?>
<Error>
<Code>AccessDenied</Code>
<Message>Access Denied</Message>
<BucketName>bucketName</BucketName>
<Key>objectName</Key>
<RequestId>F19772218238A85A</RequestId>
<HostId>GuWkjyviSiGHizehqpmsD1ndz5NClSP19DOT+s2mv7gXGQ8/X1lhbDGiIJEXpGFD</HostId>
</Error>
*/
// 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",
}
}
+104
View File
@@ -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
}
+537
View File
@@ -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
}
+539
View File
@@ -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", objectPrefix)
}
// Set object marker.
if objectMarker != "" {
urlValues.Set("marker", 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", keyMarker)
}
// Set upload id marker.
if uploadIDMarker != "" {
urlValues.Set("upload-id-marker", uploadIDMarker)
}
// Set prefix marker.
if prefix != "" {
urlValues.Set("prefix", 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
}
+144
View File
@@ -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
}
+209
View File
@@ -0,0 +1,209 @@
/*
* 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())
}
// In case of Amazon S3. The make bucket issued on already
// existing bucket would fail with 'AuthorizationMalformed' error
// if virtual style is used. So we default to 'path style' as that
// is the preferred method here. The final location of the
// 'bucket' is provided through XML LocationConstraint data with
// the request.
targetURL := *c.endpointURL
targetURL.Path = "/" + 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
}
+292
View File
@@ -0,0 +1,292 @@
/*
* 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
}
// Compatibility code for Golang < 1.5.x.
// copyBuffer is identical to io.CopyBuffer, since such a function is
// not available/implemented in Golang version < 1.5.x, we use a
// custom call exactly implementng io.CopyBuffer from Golang > 1.5.x
// version does.
//
// copyBuffer stages through the provided buffer (if one is required)
// rather than allocating a temporary one. If buf is nil, one is
// allocated; otherwise if it has zero length, copyBuffer panics.
//
// FIXME: Remove this code when distributions move to newer Golang versions.
func copyBuffer(writer io.Writer, reader io.Reader, buf []byte) (written int64, err error) {
// If the reader has a WriteTo method, use it to do the copy.
// Avoids an allocation and a copy.
if wt, ok := reader.(io.WriterTo); ok {
return wt.WriteTo(writer)
}
// Similarly, if the writer has a ReadFrom method, use it to do
// the copy.
if rt, ok := writer.(io.ReaderFrom); ok {
return rt.ReadFrom(reader)
}
if buf == nil {
buf = make([]byte, 32*1024)
}
for {
nr, er := reader.Read(buf)
if nr > 0 {
nw, ew := writer.Write(buf[0:nr])
if nw > 0 {
written += int64(nw)
}
if ew != nil {
err = ew
break
}
if nr != nw {
err = io.ErrShortWrite
break
}
}
if er == io.EOF {
break
}
if er != nil {
err = er
break
}
}
return written, err
}
// 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 copyBuffer to copy in large buffers, default buffer
// for io.Copy of 32KiB is too small.
size, err = 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 = 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)
}
+240
View File
@@ -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 && fileSize >= 0 {
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
}
+379
View File
@@ -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
}
+105
View File
@@ -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
}
+208
View File
@@ -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
}
+287
View File
@@ -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
}
+167
View File
@@ -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
}
@@ -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 {
+125
View File
@@ -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
}
+430 -1016
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
-170
View File
@@ -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("<?xml version=\"1.0\" encoding=\"UTF-8\"?><ListAllMyBucketsResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\"><Buckets><Bucket><Name>bucket</Name><CreationDate>2015-05-20T23:05:09.230Z</CreationDate></Bucket></Buckets><Owner><ID>minio</ID><DisplayName>minio</DisplayName></Owner></ListAllMyBucketsResult>")
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("<?xml version=\"1.0\" encoding=\"UTF-8\"?><AccessControlPolicy><Owner><ID>75aa57f09aa0c8caeab4f8c24e99d10f8e7faeebf76c078efc7c6caea54ba06a</ID><DisplayName>CustomersName@amazon.com</DisplayName></Owner><AccessControlList><Grant><Grantee xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"CanonicalUser\"><ID>75aa57f09aa0c8caeab4f8c24e99d10f8e7faeebf76c078efc7c6caea54ba06a</ID><DisplayName>CustomersName@amazon.com</DisplayName></Grantee><Permission>FULL_CONTROL</Permission></Grant></AccessControlList></AccessControlPolicy>")
w.Header().Set("Content-Length", strconv.Itoa(len(response)))
w.Write(response)
return
}
fallthrough
case r.URL.Path == "/bucket":
response := []byte("<?xml version=\"1.0\" encoding=\"UTF-8\"?><ListBucketResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\"><Contents><ETag>\"259d04a13802ae09c7e41be50ccc6baa\"</ETag><Key>object</Key><LastModified>2015-05-21T18:24:21.097Z</LastModified><Size>22061</Size><Owner><ID>minio</ID><DisplayName>minio</DisplayName></Owner><StorageClass>STANDARD</StorageClass></Contents><Delimiter></Delimiter><EncodingType></EncodingType><IsTruncated>false</IsTruncated><Marker></Marker><MaxKeys>1000</MaxKeys><Name>testbucket</Name><NextMarker></NextMarker><Prefix></Prefix></ListBucketResult>")
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("<?xml version=\"1.0\" encoding=\"UTF-8\"?><InitiateMultipartUploadResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\"><Bucket>example-bucket</Bucket><Key>object</Key><UploadId>XXBsb2FkIElEIGZvciBlbHZpbmcncyVcdS1tb3ZpZS5tMnRzEEEwbG9hZA</UploadId></InitiateMultipartUploadResult>")
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("<?xml version=\"1.0\" encoding=\"UTF-8\"?><ListPartsResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\"><Bucket>example-bucket</Bucket><Key>example-object</Key><UploadId>XXBsb2FkIElEIGZvciBlbHZpbmcncyVcdS1tb3ZpZS5tMnRzEEEwbG9hZA</UploadId><Initiator><ID>arn:aws:iam::111122223333:user/some-user-11116a31-17b5-4fb7-9df5-b288870f11xx</ID><DisplayName>umat-user-11116a31-17b5-4fb7-9df5-b288870f11xx</DisplayName></Initiator><Owner><ID>75aa57f09aa0c8caeab4f8c24e99d10f8e7faeebf76c078efc7c6caea54ba06a</ID><DisplayName>someName</DisplayName></Owner><StorageClass>STANDARD</StorageClass><PartNumberMarker>1</PartNumberMarker><NextPartNumberMarker>3</NextPartNumberMarker><MaxParts>2</MaxParts><IsTruncated>true</IsTruncated><Part><PartNumber>2</PartNumber><LastModified>2010-11-10T20:48:34.000Z</LastModified><ETag>\"7778aef83f66abc1fa1e8477f296d394\"</ETag><Size>10485760</Size></Part><Part><PartNumber>3</PartNumber><LastModified>2010-11-10T20:48:33.000Z</LastModified><ETag>\"aaaa18db4cc2f85cedef654fccc4a4x8\"</ETag><Size>10485760</Size></Part></ListPartsResult>")
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)
}
}
-128
View File
@@ -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")
}
}
}

Some files were not shown because too many files have changed in this diff Show More