Merge branch 'master' into release

This commit is contained in:
Minio Trusted
2017-06-14 20:38:23 -07:00
91 changed files with 2270 additions and 1043 deletions
+1
View File
@@ -15,6 +15,7 @@ script:
- make test GOFLAGS="-race"
- make coverage
- diff -au <(gofmt -d *.go) <(printf "")
- diff -au <(gofmt -d cmd) <(printf "")
- diff -au <(gofmt -d pkg) <(printf "")
after_success:
+1 -1
View File
@@ -7,7 +7,7 @@ COPY . /go/src/app
RUN \
apk add --no-cache git && \
go-wrapper download && \
go-wrapper install -ldflags "-X github.com/minio/mc/cmd.Version=2017-04-03T18:35:01Z -X github.com/minio/mc/cmd.ReleaseTag=RELEASE.2017-04-03T18-35-01Z -X github.com/minio/mc/cmd.CommitID=81d17d28ec28987ba3c57349fc57b4c064bb5b37" && \
go-wrapper install -ldflags "$(go run buildscripts/gen-ldflags.go)" && \
rm -rf /go/pkg /go/src && \
apk del git
+9
View File
@@ -0,0 +1,9 @@
FROM alpine:3.5
RUN \
apk add --no-cache ca-certificates && \
apk add --no-cache --virtual .build-deps curl && \
curl https://dl.minio.io/client/mc/release/linux-amd64/mc > /usr/bin/mc && \
chmod +x /usr/bin/mc && apk del .build-deps
ENTRYPOINT ["mc"]
+9
View File
@@ -0,0 +1,9 @@
FROM resin/aarch64-alpine:3.5
RUN \
apk add --no-cache ca-certificates && \
apk add --no-cache --virtual .build-deps curl && \
curl https://dl.minio.io/client/mc/release/linux-arm64/mc > /usr/bin/mc && \
chmod +x /usr/bin/mc && apk del .build-deps
ENTRYPOINT ["mc"]
+9
View File
@@ -0,0 +1,9 @@
FROM resin/armhf-alpine:3.5
RUN \
apk add --no-cache ca-certificates && \
apk add --no-cache --virtual .build-deps curl && \
curl https://dl.minio.io/client/mc/release/linux-arm/mc > /usr/bin/mc && \
chmod +x /usr/bin/mc && apk del .build-deps
ENTRYPOINT ["mc"]
+24 -18
View File
@@ -1,23 +1,24 @@
LDFLAGS := $(shell go run buildscripts/gen-ldflags.go)
BUILD_LDFLAGS := '$(LDFLAGS)'
all: install
checks:
@echo "Checking deps:"
@echo "Checking deps"
@(env bash buildscripts/checkdeps.sh)
@echo "Checking project is in GOPATH"
@(env bash buildscripts/checkgopath.sh)
getdeps: checks
@go get github.com/golang/lint/golint && echo "Installed golint:"
@go get github.com/fzipp/gocyclo && echo "Installed gocyclo:"
@go get github.com/remyoudompheng/go-misc/deadcode && echo "Installed deadcode:"
@go get github.com/client9/misspell/cmd/misspell && echo "Installed misspell:"
@echo "Installing golint" && go get github.com/golang/lint/golint
@echo "Installing gocyclo" && go get github.com/fzipp/gocyclo
@echo "Installing deadcode" && go get github.com/remyoudompheng/go-misc/deadcode
@echo "Installing misspell" && go get github.com/client9/misspell/cmd/misspell
# verifiers: getdeps vet fmt lint cyclo deadcode
verifiers: vet fmt lint cyclo deadcode spelling
vet:
@echo "Running $@:"
@echo "Running $@"
@go tool vet -all *.go
@go tool vet -all ./cmd
@go tool vet -all ./pkg
@@ -31,39 +32,39 @@ spelling:
@${GOPATH}/bin/misspell pkg/**/*
fmt:
@echo "Running $@:"
@gofmt -s -l *.go
@gofmt -s -l cmd
@gofmt -s -l pkg
@echo "Running $@"
@gofmt -d *.go
@gofmt -d cmd
@gofmt -d pkg
lint:
@echo "Running $@:"
@echo "Running $@"
@$(GOPATH)/bin/golint .
@$(GOPATH)/bin/golint github.com/minio/mc/cmd...
@$(GOPATH)/bin/golint github.com/minio/mc/pkg...
cyclo:
@echo "Running $@:"
@echo "Running $@"
@$(GOPATH)/bin/gocyclo -over 40 cmd
@$(GOPATH)/bin/gocyclo -over 40 pkg
deadcode:
@echo "Running $@:"
@echo "Running $@"
@$(GOPATH)/bin/deadcode
build: getdeps verifiers
test: getdeps verifiers
@echo "Running all testing:"
@echo "Running all testing"
@go test $(GOFLAGS) github.com/minio/mc/cmd...
@go test $(GOFLAGS) github.com/minio/mc/pkg...
gomake-all: build
@echo "Installing mc:"
@go build --ldflags "$(LDFLAGS)" -o $(GOPATH)/bin/mc
@echo "Installing mc at $(GOPATH)/bin/mc"
@go build --ldflags $(BUILD_LDFLAGS) -o $(GOPATH)/bin/mc
@mkdir -p $(HOME)/.mc
coverage: getdeps verifiers
@echo "Running all coverage:"
@echo "Running all coverage for mc"
@./buildscripts/go-coverage.sh
pkg-validate-arg-%: ;
@@ -72,12 +73,15 @@ ifndef PKG
endif
pkg-add: pkg-validate-arg-add
@echo "Adding new package $(PKG)"
@$(GOPATH)/bin/govendor add $(PKG)
pkg-update: pkg-validate-arg-update
@echo "Updating new package $(PKG)"
@$(GOPATH)/bin/govendor update $(PKG)
pkg-remove: pkg-validate-arg-remove
@echo "Remove new package $(PKG)"
@$(GOPATH)/bin/govendor remove $(PKG)
pkg-list:
@@ -87,6 +91,7 @@ install: gomake-all
all-tests: test
# TODO disable them for now.
# @echo "Running all mc testing"
#@./tests/test-minio.sh
release: verifiers
@@ -96,6 +101,7 @@ experimental: verifiers
@MC_RELEASE=EXPERIMENTAL ./buildscripts/build.sh
clean:
@echo "Cleaning up all the generated files"
@rm -f cover.out
@rm -f mc
@find . -name '*.test' | xargs rm -fv
+16 -6
View File
@@ -31,17 +31,24 @@ docker run minio/mc ls play
### Edge
```
docker pull minio/mc:edge
docker run minio/mc ls play
docker run minio/mc:edge ls play
```
**Note:** Above examples run `mc` against Minio [_play_ environment](#test-your-setup) by default. To run `mc` against other S3 compatible servers, start the container this way:
```sh
docker run -it --entrypoint=/bin/sh minio/mc
```
then use the [`mc config` command](#add-a-cloud-storage-service).
## macOS
### Homebrew
Install mc packages using [Homebrew](http://brew.sh/)
```sh
brew install minio-mc
brew install minio/stable/mc
mc --help
```
## GNU/Linux
@@ -93,9 +100,12 @@ Source installation is intended only for developers and advanced users. `mc upda
If you do not have a working Golang environment, please follow [How to install Golang](https://docs.minio.io/docs/how-to-install-golang).
```sh
go get -u github.com/minio/mc
go get -d github.com/minio/mc
cd ${GOPATH}/src/github.com/minio/mc
make
```
## Add a Cloud Storage Service
If you are planning to use `mc` only on POSIX compatible filesystems, you may skip this step and proceed to [everyday use](#everyday-use).
@@ -160,10 +170,10 @@ alias pipe='mc pipe'
```
### Shell autocompletion
You may also download [`autocomplete/bash_autocomplete`](https://raw.githubusercontent.com/minio/mc/master/autocomplete/bash_complete) into `/etc/bash_completion.d/` and rename it to `mc`. Don't forget to source the file to make it active on your current shell.
You may also download [`autocomplete/bash_autocomplete`](https://raw.githubusercontent.com/minio/mc/master/autocomplete/bash_autocomplete) into `/etc/bash_completion.d/` and rename it to `mc`. Don't forget to source the file to make it active on your current shell.
```sh
sudo wget https://raw.githubusercontent.com/minio/mc/master/autocomplete/bash_complete -O /etc/bash_completion.d/mc
sudo wget https://raw.githubusercontent.com/minio/mc/master/autocomplete/bash_autocomplete -O /etc/bash_completion.d/mc
source /etc/bash_completion.d/mc
```
+24 -46
View File
@@ -28,6 +28,7 @@ _init() {
## System binaries
CP=`which cp`
SHASUM=`which shasum`
SHA256SUM="${SHASUM} -a 256"
SED=`which sed`
}
@@ -43,58 +44,35 @@ go_build() {
release_bin="$release_str/$os-$arch/$(basename $package).$release_tag"
# Release binary downloadable name
release_real_bin="$release_str/$os-$arch/$(basename $package)"
# Release shasum name
release_shasum="$release_str/$os-$arch/$(basename $package).shasum"
# Go build to build the binary.
if [ "${arch}" == "arm" ]; then
# Release binary downloadable name
release_real_bin_6="$release_str/$os-${arch}6vl/$(basename $package)"
# Release sha1sum name
release_shasum="$release_str/$os-$arch/$(basename $package).${release_tag}.shasum"
# Release sha1sum default
release_shasum_default="$release_str/$os-$arch/$(basename $package).shasum"
release_bin_6="$release_str/$os-${arch}6vl/$(basename $package).$release_tag"
## Support building for ARM6vl
CGO_ENABLED=0 GOARM=6 GOOS=$os GOARCH=$arch go build --ldflags "${LDFLAGS}" -o $release_bin_6
# Release sha256sum name
release_sha256sum="$release_str/$os-$arch/$(basename $package).${release_tag}.sha256sum"
# Release sha256sum default
release_sha256sum_default="$release_str/$os-$arch/$(basename $package).sha256sum"
## Copy
$CP -p $release_bin_6 $release_real_bin_6
CGO_ENABLED=0 GOOS=$os GOARCH=$arch go build --ldflags "${LDFLAGS}" -o $release_bin
# Release shasum name
release_shasum_6="$release_str/$os-${arch}6vl/$(basename $package).shasum"
# Calculate shasum
shasum_str=$(${SHASUM} ${release_bin_6})
echo ${shasum_str} | $SED "s/$release_str\/$os-${arch}6vl\///g" > $release_shasum_6
# Release binary downloadable name
release_real_bin_7="$release_str/$os-$arch/$(basename $package)"
release_bin_7="$release_str/$os-$arch/$(basename $package).$release_tag"
## Support building for ARM7vl
CGO_ENABLED=0 GOARM=7 GOOS=$os GOARCH=$arch go build --ldflags "${LDFLAGS}" -o $release_bin_7
## Copy
$CP -p $release_bin_7 $release_real_bin_7
# Release shasum name
release_shasum_7="$release_str/$os-$arch/$(basename $package).shasum"
# Calculate shasum
shasum_str=$(${SHASUM} ${release_bin_7})
echo ${shasum_str} | $SED "s/$release_str\/$os-$arch\///g" > $release_shasum_7
# Create copy
if [ $os == "windows" ]; then
$CP -p $release_bin ${release_real_bin}.exe
else
CGO_ENABLED=0 GOOS=$os GOARCH=$arch go build --ldflags "${LDFLAGS}" -o $release_bin
# Create copy
if [ $os == "windows" ]; then
$CP -p $release_bin ${release_real_bin}.exe
else
$CP -p $release_bin $release_real_bin
fi
# Calculate shasum
shasum_str=$(${SHASUM} ${release_bin})
echo ${shasum_str} | $SED "s/$release_str\/$os-$arch\///g" > $release_shasum
$CP -p $release_bin $release_real_bin
fi
# Calculate sha1sum
shasum_str=$(${SHASUM} ${release_bin})
echo ${shasum_str} | $SED "s/$release_str\/$os-$arch\///g" > $release_shasum
$CP -p $release_shasum $release_shasum_default
# Calculate sha256sum
sha256sum_str=$(${SHA256SUM} ${release_bin})
echo ${sha256sum_str} | $SED "s/$release_str\/$os-$arch\///g" > $release_sha256sum
$CP -p $release_sha256sum $release_sha256sum_default
}
main() {
+1 -1
View File
@@ -28,7 +28,7 @@ import (
func genLDFlags(version string) string {
var ldflagsStr string
ldflagsStr = "-X github.com/minio/mc/cmd.Version=" + version + " "
ldflagsStr = "-s -w -X github.com/minio/mc/cmd.Version=" + version + " "
ldflagsStr = ldflagsStr + "-X github.com/minio/mc/cmd.ReleaseTag=" + releaseTag(version) + " "
ldflagsStr = ldflagsStr + "-X github.com/minio/mc/cmd.CommitID=" + commitID() + " "
ldflagsStr = ldflagsStr + "-X github.com/minio/mc/cmd.ShortCommitID=" + commitID()[:12]
+1 -1
View File
@@ -33,7 +33,7 @@ var adminConfigGetCmd = cli.Command{
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} ALIAS/
{{.HelpName}} TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
+1 -1
View File
@@ -38,7 +38,7 @@ var adminConfigSetCmd = cli.Command{
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} ALIAS/
{{.HelpName}} TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
@@ -36,7 +36,7 @@ var adminCredsCmd = cli.Command{
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} ALIAS ACCESS_KEY SECRET_KEY
{{.HelpName}} TARGET ACCESS_KEY SECRET_KEY
FLAGS:
{{range .VisibleFlags}}{{.}}
-256
View File
@@ -1,256 +0,0 @@
/*
* Minio Client (C) 2017 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cmd
import (
"encoding/json"
"fmt"
"path/filepath"
"strings"
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/console"
"github.com/minio/minio/pkg/madmin"
"github.com/minio/minio/pkg/probe"
)
var (
adminHealListFlags = []cli.Flag{
cli.BoolFlag{
Name: "recursive, r",
Usage: "List recursively.",
},
cli.BoolFlag{
Name: "incomplete, I",
Usage: "List incomplete uploads",
},
}
)
var adminHealListCmd = cli.Command{
Name: "list",
Usage: "Get the list of buckets or objects that need to be healed.",
Before: setGlobalsFromContext,
Action: mainAdminHealList,
Flags: append(adminHealListFlags, globalFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} ALIAS/[BUCKET/][PREFIX/]
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. List objects than need to be healed related to 'testbucket' in a Minio server represented by its alias 'play'.
$ {{.HelpName}} play/testbucket/
2. Recursively list objects than need to be healed.
$ {{.HelpName}} --recursive play/
3. Recursively list incomplete uploads than need to be healed.
$ {{.HelpName}} --incomplete --recursive play/
`,
}
// healListMessage container to hold heal information.
type healListMessage struct {
Status string `json:"status"`
Bucket string `json:"bucket"`
Object *madmin.ObjectInfo `json:"object"`
Upload *madmin.UploadInfo `json:"upload"`
}
// String colorized service status message.
func (u healListMessage) String() string {
msg := ""
var healStatus madmin.HealStatus
// Check if we have object heal information
if u.Object != nil {
msg += fmt.Sprintf("Object: %s/%s, ", u.Bucket, u.Object.Key)
healStatus = u.Object.HealObjectInfo.Status
} else {
msg += fmt.Sprintf("Upload: %s/%s, ", u.Bucket, u.Upload.Key)
healStatus = u.Upload.HealUploadInfo.Status
}
// Print heal status
switch healStatus {
case madmin.CanHeal:
msg += "can be healed."
case madmin.Corrupted:
msg += "cannot be healed."
case madmin.QuorumUnavailable:
msg += "quorum not available for healing."
}
return console.Colorize("Heal", msg)
}
// JSON jsonified service status Message message.
func (u healListMessage) JSON() string {
u.Status = "success"
statusJSONBytes, e := json.Marshal(u)
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(statusJSONBytes)
}
// healBucketListMessage container to hold heal information.
type healBucketListMessage struct {
Status string `json:"status"`
Bucket madmin.BucketInfo `json:"bucket"`
}
// String colorized service status message.
func (u healBucketListMessage) String() string {
msg := fmt.Sprintf("Bucket: `%s`, ", u.Bucket.Name)
switch u.Bucket.HealBucketInfo.Status {
case madmin.CanHeal:
msg += "can be healed"
case madmin.Corrupted:
msg += "cannot be healed"
case madmin.QuorumUnavailable:
msg += "quorum not available for healing"
}
msg += ".\n"
return console.Colorize("Heal", msg)
}
// JSON jsonified service status Message message.
func (u healBucketListMessage) JSON() string {
u.Status = "success"
statusJSONBytes, e := json.Marshal(u)
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(statusJSONBytes)
}
// checkAdminHealListSyntax - validate all the passed arguments
func checkAdminHealListSyntax(ctx *cli.Context) {
if len(ctx.Args()) == 0 || len(ctx.Args()) > 2 {
cli.ShowCommandHelpAndExit(ctx, "list", 1) // last argument is exit code
}
}
func mainAdminHealList(ctx *cli.Context) error {
// Check for heal list syntax
checkAdminHealListSyntax(ctx)
// Set console theme for heal command
console.SetColor("Heal", color.New(color.FgGreen, color.Bold))
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
isRecursive := ctx.Bool("recursive")
isIncomplete := ctx.Bool("incomplete")
// Create a new Minio Admin Client
client, err := newAdminClient(aliasedURL)
if err != nil {
return err.ToGoError()
}
// Transform windows backslash to the regular slash in the aliased url
aliasedURL = filepath.ToSlash(aliasedURL)
// Compute bucket and object from aliased url
splits := splitStr(aliasedURL, "/", 3)
bucket, object := splits[1], splits[2]
// If bucket is not specified, list buckets that need to be healed
if bucket == "" {
bucketsToHeal, e := client.ListBucketsHeal()
fatalIf(probe.NewError(e), "Cannot list buckets that need healing.")
// Iterate over buckets that need healing and print them
for _, bucketHeal := range bucketsToHeal {
printMsg(healBucketListMessage{Bucket: bucketHeal})
}
}
// When bucket is not specified and recursive flag is not activated,
// it means we will not scan inside buckets
if bucket == "" && !isRecursive {
return nil
}
// Now, it is time to examine for objects that need to be healed
var buckets []string
if bucket == "" {
// Bucket is not specified, so we target all buckets so we need to list them.
s3Client, err := newClient(aliasedURL)
if err != nil {
fatalIf(err, "Cannot resolve the provided path.")
}
recursive := false
incomplete := false
listCh := s3Client.List(recursive, incomplete, DirFirst)
for content := range listCh {
// Trim the leading slash and add to the list of buckets
buckets = append(buckets,
strings.TrimPrefix(content.URL.Path, string(content.URL.Separator)))
}
} else {
// Bucket is passed in argument, so we will only search for objects in the specified bucket
buckets = append(buckets, bucket)
}
// Iterate over all computed buckets
for _, currBucket := range buckets {
// Search for objects that need to be healed in the current bucket
doneCh := make(chan struct{})
if isIncomplete {
listCh, e := client.ListUploadsHeal(currBucket, object, isRecursive, doneCh)
fatalIf(probe.NewError(e), "Cannot list heal uploads.")
// Iterate over uploads and print them when not errors
for upload := range listCh {
if upload.Err != nil {
errorIf(probe.NewError(upload.Err), "Cannot heal upload `"+upload.Key+"`.")
continue
}
// Skip for non-recursive use case.
if upload.HealUploadInfo == nil {
continue
}
printMsg(healListMessage{Bucket: currBucket, Upload: &upload})
}
} else {
listCh, e := client.ListObjectsHeal(currBucket, object, isRecursive, doneCh)
fatalIf(probe.NewError(e), "Cannot list heal objects.")
// Iterate over objects and print them when not errors
for obj := range listCh {
if obj.Err != nil {
errorIf(probe.NewError(obj.Err), "Cannot heal object `"+obj.Key+"`.")
continue
}
// Skip for non-recursive use case.
if obj.HealObjectInfo == nil {
continue
}
printMsg(healListMessage{Bucket: currBucket, Object: &obj})
}
}
}
return nil
}
+210 -32
View File
@@ -19,8 +19,8 @@ package cmd
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/fatih/color"
"github.com/minio/cli"
@@ -46,47 +46,54 @@ var (
}
)
var adminHealHelpTemplate = `NAME:
var adminHealCmd = cli.Command{
Name: "heal",
Usage: "Manage heal tasks",
Before: setGlobalsFromContext,
Action: mainAdminHeal,
Flags: append(adminHealFlags, globalFlags...),
HideHelpCommand: true,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} [FLAGS] [COMMAND]
{{.HelpName}} [FLAGS] TARGET
COMMANDS:
{{range .VisibleCommands}}{{join .Names ", "}}{{ "\t" }}{{.Usage}}
{{end}}
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Heal 'testbucket' in a Minio server represented by its alias 'play'.
1. To format newly replaced disks in a Minio server with alias 'play'
$ {{.HelpName}} play
2. Heal 'testbucket' in a Minio server with alias 'play'
$ {{.HelpName}} play/testbucket/
2. Heal all objects under 'dir' prefix
3. Heal all objects under 'dir' prefix
$ {{.HelpName}} --recursive play/testbucket/dir/
3. Heal all uploads under 'dir' prefix
4. Heal all uploads under 'dir' prefix
$ {{.HelpName}} --incomplete --recursive play/testbucket/dir/
4. Issue a fake heal operation to see what the server could report
$ {{.HelpName}} --fake play/testbucket/dir/
5. Issue a fake heal operation to list all objects to be healed
$ {{.HelpName}} --fake play
`
var adminHealCmd = cli.Command{
Name: "heal",
Usage: "Manage heal tasks",
Before: setGlobalsFromContext,
Action: mainAdminHeal,
Flags: append(adminHealFlags, globalFlags...),
Subcommands: []cli.Command{
adminHealListCmd,
},
HideHelpCommand: true,
6. Issue a fake heal operation to list all uploads to be healed
$ {{.HelpName}} --fake --incomplete play
7. Issue a fake heal operation to list all objects to be healed under 'dir' prefix
$ {{.HelpName}} --recursive --fake play/testbucket/dir/
8. Issue a fake heal operation to list all uploads to be healed under 'dir' prefix
$ {{.HelpName}} --incomplete --recursive --fake play/testbucket/dir/
`,
}
// healMessage container to hold repair information.
type healMessage struct {
Status string `json:"status"`
Result madmin.HealResult `json:"result"`
Bucket string `json:"bucket"`
Object *madmin.ObjectInfo `json:"object"`
Upload *madmin.UploadInfo `json:"upload"`
@@ -94,12 +101,26 @@ type healMessage struct {
// String colorized service status message.
func (u healMessage) String() string {
allOfflineTmpl := "is not healed since many disks were offline"
allHealedTmpl := "is healed on all disks"
someHealedTmpl := "is healed on some disks while other disks were offline"
msg := ""
if u.Object != nil {
msg += fmt.Sprintf("Object %s/%s is healed.", u.Bucket, u.Object.Key)
msg = fmt.Sprintf("Object %s/%s ", u.Bucket, u.Object.Key)
} else {
msg += fmt.Sprintf("Upload %s/%s/%s is healed.", u.Bucket, u.Upload.Key, u.Upload.UploadID)
msg = fmt.Sprintf("Upload %s/%s/%s ", u.Bucket, u.Upload.Key, u.Upload.UploadID)
}
switch u.Result.State {
case madmin.HealNone:
msg += allOfflineTmpl
case madmin.HealPartial:
msg += someHealedTmpl
case madmin.HealOK:
msg += allHealedTmpl
}
return console.Colorize("Heal", msg)
}
@@ -112,6 +133,81 @@ func (u healMessage) JSON() string {
return string(statusJSONBytes)
}
// healListMessage container to hold heal information.
type healListMessage struct {
Status string `json:"status"`
Bucket string `json:"bucket"`
Object *madmin.ObjectInfo `json:"object"`
Upload *madmin.UploadInfo `json:"upload"`
}
// String colorized service status message.
func (u healListMessage) String() string {
msg := ""
var healStatus madmin.HealStatus
// Check if we have object heal information
if u.Object != nil {
msg += fmt.Sprintf("Object: %s/%s, ", u.Bucket, u.Object.Key)
healStatus = u.Object.HealObjectInfo.Status
} else {
msg += fmt.Sprintf("Upload: %s/%s, ", u.Bucket, u.Upload.Key)
healStatus = u.Upload.HealUploadInfo.Status
}
// Print heal status
switch healStatus {
case madmin.CanHeal:
msg += "can be healed."
case madmin.CanPartiallyHeal:
msg += "can be partially healed."
case madmin.Corrupted:
msg += "cannot be healed."
case madmin.QuorumUnavailable:
msg += "quorum not available for healing."
}
return console.Colorize("Heal", msg)
}
// JSON jsonified service status Message message.
func (u healListMessage) JSON() string {
u.Status = "success"
statusJSONBytes, e := json.Marshal(u)
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(statusJSONBytes)
}
// healBucketListMessage container to hold heal information.
type healBucketListMessage struct {
Status string `json:"status"`
Bucket madmin.BucketInfo `json:"bucket"`
}
// String colorized service status message.
func (u healBucketListMessage) String() string {
msg := fmt.Sprintf("Bucket: `%s`, ", u.Bucket.Name)
switch u.Bucket.HealBucketInfo.Status {
case madmin.CanHeal:
msg += "can be healed"
case madmin.Corrupted:
msg += "cannot be healed"
case madmin.QuorumUnavailable:
msg += "quorum not available for healing"
}
msg += ".\n"
return console.Colorize("Heal", msg)
}
// JSON jsonified service status Message message.
func (u healBucketListMessage) JSON() string {
u.Status = "success"
statusJSONBytes, e := json.Marshal(u)
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(statusJSONBytes)
}
func healObjects(client *madmin.AdminClient, bucket, object string, isRecursive, isFake bool) {
// Search for objects that need healing
doneCh := make(chan struct{})
@@ -132,15 +228,20 @@ func healObjects(client *madmin.AdminClient, bucket, object string, isRecursive,
// Check the heal status, and call heal object API only when an object can be healed
switch healInfo := *obj.HealObjectInfo; healInfo.Status {
case madmin.CanHeal:
case madmin.CanHeal, madmin.CanPartiallyHeal:
// Heal Object
if e = client.HealObject(bucket, obj.Key, isFake); e != nil {
var healResult madmin.HealResult
if healResult, e = client.HealObject(bucket, obj.Key, isFake); e != nil {
errorIf(probe.NewError(e), "Cannot repair object: `"+obj.Key+"`")
continue
}
// Print successful message
printMsg(healMessage{Bucket: bucket, Object: &obj})
if isFake {
printMsg(healListMessage{Bucket: bucket, Object: &obj})
} else {
printMsg(healMessage{Bucket: bucket, Object: &obj, Result: healResult})
}
case madmin.QuorumUnavailable:
errorIf(errDummy().Trace(), obj.Key+" cannot be healed until quorum is available.")
case madmin.Corrupted:
@@ -169,14 +270,19 @@ func healUploads(client *madmin.AdminClient, bucket, object string, isRecursive,
// Check the heal status, and call heal upload API only when an upload can be healed
switch healInfo := *upload.HealUploadInfo; healInfo.Status {
case madmin.CanHeal:
case madmin.CanHeal, madmin.CanPartiallyHeal:
// Heal Upload
if e = client.HealUpload(bucket, upload.Key, upload.UploadID, isFake); e != nil {
var healResult madmin.HealResult
if healResult, e = client.HealUpload(bucket, upload.Key, upload.UploadID, isFake); e != nil {
errorIf(probe.NewError(e), "Cannot repair upload: `"+upload.Key+"`")
continue
}
// Print successful message
printMsg(healMessage{Bucket: bucket, Upload: &upload})
if isFake {
printMsg(healListMessage{Bucket: bucket, Upload: &upload})
} else {
printMsg(healMessage{Bucket: bucket, Upload: &upload, Result: healResult})
}
case madmin.QuorumUnavailable:
errorIf(errDummy().Trace(), upload.Key+" cannot be healed until quorum is available.")
case madmin.Corrupted:
@@ -188,11 +294,76 @@ func healUploads(client *madmin.AdminClient, bucket, object string, isRecursive,
// checkAdminHealSyntax - validate all the passed arguments
func checkAdminHealSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 1 {
cli.HelpPrinter(ctx.App.Writer, adminHealHelpTemplate, ctx.App)
os.Exit(1)
cli.ShowCommandHelpAndExit(ctx, "heal", 1) // last argument is exit code
}
}
// listAllToBeHealed - list objects/uploads to be healed in the object
// store with alias `aliasedURL`
// - isIncomplete - if true we list uploads to be healed otherwise
// list objects to be healed
func listAllToBeHealed(client *madmin.AdminClient, aliasedURL string, isIncomplete bool) *probe.Error {
s3Client, err := newClient(aliasedURL)
if err != nil {
return err
}
recursive := false
incomplete := false
listCh := s3Client.List(recursive, incomplete, DirFirst)
var buckets []string
for content := range listCh {
// Trim the leading slash and add to the list of buckets
buckets = append(buckets,
strings.TrimPrefix(content.URL.Path, string(content.URL.Separator)))
}
// isRecursive is always true since we have empty object names
// when `mc admin heal --fake [-r] s1/` is invoked.
isRecursive := true
// Iterate over all computed buckets
for _, currBucket := range buckets {
// Search for objects that need to be healed in the current bucket
doneCh := make(chan struct{})
if isIncomplete {
listCh, e := client.ListUploadsHeal(currBucket, "", isRecursive, doneCh)
fatalIf(probe.NewError(e), "Cannot list heal uploads.")
// Iterate over uploads and print them when not errors
for upload := range listCh {
if upload.Err != nil {
errorIf(probe.NewError(upload.Err), "Cannot heal upload `"+upload.Key+"`.")
continue
}
// Skip for non-recursive use case.
if upload.HealUploadInfo == nil {
continue
}
printMsg(healListMessage{Bucket: currBucket, Upload: &upload})
}
} else {
listCh, e := client.ListObjectsHeal(currBucket, "", isRecursive, doneCh)
fatalIf(probe.NewError(e), "Cannot list heal objects.")
// Iterate over objects and print them when not errors
for obj := range listCh {
if obj.Err != nil {
errorIf(probe.NewError(obj.Err), "Cannot heal object `"+obj.Key+"`.")
continue
}
// Skip for non-recursive use case.
if obj.HealObjectInfo == nil {
continue
}
printMsg(healListMessage{Bucket: currBucket, Object: &obj})
}
}
}
return nil
}
// mainAdminHeal - the entry function of heal command
func mainAdminHeal(ctx *cli.Context) error {
@@ -225,6 +396,13 @@ func mainAdminHeal(ctx *cli.Context) error {
// Heal format if bucket is not specified and quit immediately
if bucket == "" {
// If --fake was given, print all objects/uploads that
// need to be healed.
if isFake {
lErr := listAllToBeHealed(client, aliasedURL, isIncomplete)
fatalIf(lErr, "Unable to list all objects to be healed")
return nil
}
e = client.HealFormat(isFake)
fatalIf(probe.NewError(e), "Cannot heal the disks.")
return nil
+79 -39
View File
@@ -20,6 +20,7 @@ import (
"encoding/json"
"fmt"
"net/url"
"time"
humanize "github.com/dustin/go-humanize"
"github.com/fatih/color"
@@ -43,7 +44,7 @@ var adminInfoCmd = cli.Command{
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} ALIAS
{{.HelpName}} TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
@@ -94,23 +95,46 @@ type ServerInfo struct {
type infoMessage struct {
Status string `json:"status"`
Service bool `json:"service"`
Addr string `json:"address"`
Err string `json:"error"`
*ServerInfo
}
// String colorized service status message.
func (u infoMessage) String() (msg string) {
defer func() {
msg = console.Colorize("Info", msg)
msg += "\n"
}()
dot := "●"
// When service is offline
if !u.Service {
msg = "The server is offline."
msg += fmt.Sprintf("%s %s\n", console.Colorize("InfoFail", dot), u.Addr)
msg += fmt.Sprintf(" Uptime : Server is %s", console.Colorize("InfoFail", "offline"))
return
}
msg += fmt.Sprintf(" Version : %s\n", u.ServerInfo.Properties.Version)
msg += fmt.Sprintf(" Uptime : %s\n", timeDurationToHumanizedDuration(u.ServerInfo.Properties.Uptime))
msg += fmt.Sprintf(" Region : %s\n", u.ServerInfo.Properties.Region)
// Print error if any and exit
if u.Err != "" {
msg += fmt.Sprintf("%s %s\n", console.Colorize("InfoFail", dot), u.Addr)
msg += fmt.Sprintf(" Uptime : Server is %s\n", console.Colorize("InfoFail", "offline"))
msg += fmt.Sprintf(" Error : %s", u.Err)
return
}
// Print server title
msg += fmt.Sprintf("%s %s\n", console.Colorize("Info", dot), u.Addr)
// Print server information
// Uptime
msg += fmt.Sprintf(" Uptime : %s since %s\n", console.Colorize("Info", "online"), humanize.Time(time.Now().UTC().Add(-u.ServerInfo.Properties.Uptime)))
// Version
msg += fmt.Sprintf(" Version : %s\n", u.ServerInfo.Properties.Version)
// Region
msg += fmt.Sprintf(" Region : %s\n", u.ServerInfo.Properties.Region)
// ARNs
sqsARNs := ""
for _, v := range u.ServerInfo.Properties.SQSARN {
sqsARNs += fmt.Sprintf("%s ", v)
@@ -119,12 +143,11 @@ func (u infoMessage) String() (msg string) {
sqsARNs = "<none>"
}
msg += fmt.Sprintf(" SQS ARNs : %s\n", sqsARNs)
// Incoming/outgoing
msg += fmt.Sprintf(" Network : Incoming %s, Outgoing %s\n",
humanize.IBytes(u.ServerInfo.ConnStats.TotalInputBytes),
humanize.IBytes(u.ServerInfo.ConnStats.TotalOutputBytes))
// Online service, get backend information
// Get storage information
msg += fmt.Sprintf(" Storage : Total %s, Free %s",
humanize.IBytes(uint64(u.StorageInfo.Total)),
humanize.IBytes(uint64(u.StorageInfo.Free)),
@@ -132,6 +155,7 @@ func (u infoMessage) String() (msg string) {
if v, ok := u.ServerInfo.StorageInfo.Backend.(xlBackend); ok {
msg += fmt.Sprintf(", Online Disks: %d, Offline Disks: %d", v.OnlineDisks, v.OfflineDisks)
}
return
}
@@ -156,6 +180,7 @@ func mainAdminInfo(ctx *cli.Context) error {
checkAdminInfoSyntax(ctx)
console.SetColor("Info", color.New(color.FgGreen, color.Bold))
console.SetColor("InfoFail", color.New(color.FgRed, color.Bold))
// Get the alias parameter from cli
args := ctx.Args()
@@ -165,53 +190,68 @@ func mainAdminInfo(ctx *cli.Context) error {
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Cannot get a configured admin connection.")
// Fetch the server info of the specified Minio server
serverInfo, e := client.ServerInfo()
// Fetch info of all servers (cluster or single server)
serversInfo, e := client.ServerInfo()
// Check the availability of the server: online or offline. A server is considered
// offline if we can't get any response or we get a bad format response
var serviceOffline bool
switch v := e.(type) {
switch e.(type) {
case *json.SyntaxError:
serviceOffline = true
case *url.Error:
if v.Timeout() {
serviceOffline = true
}
serviceOffline = true
}
if serviceOffline {
printMsg(infoMessage{Service: false})
printMsg(infoMessage{Addr: aliasedURL, Service: false})
return nil
}
// If the error is not nil and not unrecognizable, just print it and exit
fatalIf(probe.NewError(e), "Cannot get service status.")
// Construct the backend status
storageInfo := backendStatus{
Total: serverInfo.StorageInfo.Total,
Free: serverInfo.StorageInfo.Free,
}
if serverInfo.StorageInfo.Backend.Type == madmin.Erasure {
storageInfo.Backend = xlBackend{
Type: erasureType,
OnlineDisks: serverInfo.StorageInfo.Backend.OnlineDisks,
OfflineDisks: serverInfo.StorageInfo.Backend.OfflineDisks,
for _, serverInfo := range serversInfo {
// Print the error if exists and jump to the next server
if serverInfo.Error != "" {
printMsg(infoMessage{
Service: true,
Addr: serverInfo.Addr,
Err: serverInfo.Error,
})
continue
}
} else {
storageInfo.Backend = fsBackend{
Type: fsType,
}
}
printMsg(infoMessage{
Service: true,
ServerInfo: &ServerInfo{
StorageInfo: storageInfo,
ConnStats: serverInfo.ConnStats,
Properties: serverInfo.Properties,
},
})
// Construct the backend status
storageInfo := backendStatus{
Total: serverInfo.Data.StorageInfo.Total,
Free: serverInfo.Data.StorageInfo.Free,
}
if serverInfo.Data.StorageInfo.Backend.Type == madmin.Erasure {
storageInfo.Backend = xlBackend{
Type: erasureType,
OnlineDisks: serverInfo.Data.StorageInfo.Backend.OnlineDisks,
OfflineDisks: serverInfo.Data.StorageInfo.Backend.OfflineDisks,
}
} else {
storageInfo.Backend = fsBackend{
Type: fsType,
}
}
printMsg(infoMessage{
Service: true,
Addr: serverInfo.Addr,
Err: serverInfo.Error,
ServerInfo: &ServerInfo{
StorageInfo: storageInfo,
ConnStats: serverInfo.Data.ConnStats,
Properties: serverInfo.Data.Properties,
},
})
}
return nil
}
+1 -1
View File
@@ -51,7 +51,7 @@ var adminLockClearCmd = cli.Command{
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} ALIAS/BUCKET/PREFIX
{{.HelpName}} [FLAGS] TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
+1 -1
View File
@@ -47,7 +47,7 @@ var adminLockListCmd = cli.Command{
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} ALIAS/BUCKET/PREFIX
{{.HelpName}} [FLAGS] TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
+1 -1
View File
@@ -35,7 +35,7 @@ var adminServiceRestartCmd = cli.Command{
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} ALIAS
{{.HelpName}} TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
+1 -1
View File
@@ -42,7 +42,7 @@ var adminServiceStatusCmd = cli.Command{
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} ALIAS
{{.HelpName}} TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
+2 -3
View File
@@ -25,7 +25,6 @@ import (
"strconv"
"strings"
"sync"
"time"
)
type objectAPIHandler struct {
@@ -63,7 +62,7 @@ func (h objectAPIHandler) getHandler(w http.ResponseWriter, r *http.Request) {
return
}
w.Header().Set("Content-Length", strconv.Itoa(len(h.object[filepath.Base(r.URL.Path)])))
w.Header().Set("Last-Modified", time.Now().UTC().Format(http.TimeFormat))
w.Header().Set("Last-Modified", UTCNow().Format(http.TimeFormat))
w.Header().Set("ETag", "b1946ac92492d2347c6235b4d2611184")
w.WriteHeader(http.StatusOK)
io.Copy(w, bytes.NewReader(h.object[filepath.Base(r.URL.Path)]))
@@ -83,7 +82,7 @@ func (h objectAPIHandler) headHandler(w http.ResponseWriter, r *http.Request) {
return
case r.URL.Path != "":
w.Header().Set("Content-Length", strconv.Itoa(len(h.object[filepath.Base(r.URL.Path)])))
w.Header().Set("Last-Modified", time.Now().UTC().Format(http.TimeFormat))
w.Header().Set("Last-Modified", UTCNow().Format(http.TimeFormat))
w.Header().Set("ETag", "b1946ac92492d2347c6235b4d2611184")
w.WriteHeader(http.StatusOK)
return
+1 -1
View File
@@ -150,7 +150,7 @@ func (e EmptyPath) Error() string {
type ObjectMissing struct{}
func (e ObjectMissing) Error() string {
return "Object key is missing, object key cannot be empty"
return "Object does not exist"
}
// UnexpectedShortWrite - write wrote less bytes than expected.
+56 -54
View File
@@ -96,12 +96,12 @@ func (f *fsClient) GetURL() clientURL {
// Watches for all fs events on an input path.
func (f *fsClient) Watch(params watchParams) (*watchObject, *probe.Error) {
eventChan := make(chan Event)
eventChan := make(chan EventInfo)
errorChan := make(chan *probe.Error)
doneChan := make(chan bool)
// Make the channel buffered to ensure no event is dropped. Notify will drop
// an event if the receiver is not able to keep up the sending pace.
neventChan := make(chan notify.EventInfo, 1)
in, out := PipeChan(1000)
var fsEvents []notify.Event
for _, event := range params.events {
@@ -110,6 +110,8 @@ func (f *fsClient) Watch(params watchParams) (*watchObject, *probe.Error) {
fsEvents = append(fsEvents, EventTypePut...)
case "delete":
fsEvents = append(fsEvents, EventTypeDelete...)
case "get":
fsEvents = append(fsEvents, EventTypeGet...)
default:
return nil, errInvalidArgument().Trace(event)
}
@@ -121,7 +123,7 @@ func (f *fsClient) Watch(params watchParams) (*watchObject, *probe.Error) {
if params.recursive {
recursivePath = f.PathURL.Path + "..."
}
if e := notify.Watch(recursivePath, neventChan, fsEvents...); e != nil {
if e := notify.Watch(recursivePath, in, fsEvents...); e != nil {
return nil, probe.NewError(e)
}
@@ -131,7 +133,7 @@ func (f *fsClient) Watch(params watchParams) (*watchObject, *probe.Error) {
close(eventChan)
close(errorChan)
notify.Stop(neventChan)
notify.Stop(in)
}()
timeFormatFS := "2006-01-02T15:04:05.000Z"
@@ -139,7 +141,7 @@ func (f *fsClient) Watch(params watchParams) (*watchObject, *probe.Error) {
// Get fsnotify notifications for events and errors, and sent them
// using eventChan and errorChan
go func() {
for event := range neventChan {
for event := range out {
if isIgnoredFile(event.Path()) {
continue
}
@@ -159,31 +161,49 @@ func (f *fsClient) Watch(params watchParams) (*watchObject, *probe.Error) {
// we want files
continue
}
eventChan <- Event{
Time: time.Now().Format(timeFormatFS),
Size: i.Size(),
Path: event.Path(),
Client: f,
Type: EventCreate,
eventChan <- EventInfo{
Time: UTCNow().Format(timeFormatFS),
Size: i.Size(),
Path: event.Path(),
Type: EventCreate,
}
} else if IsDeleteEvent(event.Event()) {
eventChan <- Event{
Time: time.Now().Format(timeFormatFS),
Path: event.Path(),
Client: f,
Type: EventRemove,
eventChan <- EventInfo{
Time: UTCNow().Format(timeFormatFS),
Path: event.Path(),
Type: EventRemove,
}
} else if IsGetEvent(event.Event()) {
eventChan <- EventInfo{
Time: UTCNow().Format(timeFormatFS),
Path: event.Path(),
Type: EventAccessed,
}
}
}
}()
return &watchObject{
events: eventChan,
errors: errorChan,
done: doneChan,
eventInfoChan: eventChan,
errorChan: errorChan,
doneChan: doneChan,
}, nil
}
func isStreamFile(objectPath string) bool {
switch objectPath {
case os.DevNull:
fallthrough
case os.Stdin.Name():
fallthrough
case os.Stdout.Name():
fallthrough
case os.Stderr.Name():
return true
}
return false
}
/// Object operations.
func (f *fsClient) put(reader io.Reader, size int64, metadata map[string][]string, progress io.Reader) (int64, *probe.Error) {
@@ -194,29 +214,15 @@ func (f *fsClient) put(reader io.Reader, size int64, metadata map[string][]strin
objectDir, _ := filepath.Split(f.PathURL.Path)
objectPath := f.PathURL.Path
// Verify if destination already exists.
st, e := os.Stat(objectPath)
if e == nil {
// If the destination exists and is not a regular file.
if !st.Mode().IsRegular() {
return 0, probe.NewError(PathIsNotRegular{
Path: objectPath,
})
}
}
// Proceed if file does not exist. return for all other errors.
if e != nil {
if !os.IsNotExist(e) {
return 0, probe.NewError(e)
}
}
// Write to a temporary file "object.part.mc" before commit.
avoidResumeUpload := isStreamFile(objectPath)
// Write to a temporary file "object.part.minio" before commit.
objectPartPath := objectPath + partSuffix
if avoidResumeUpload {
objectPartPath = objectPath
}
if objectDir != "" {
// Create any missing top level directories.
if e = os.MkdirAll(objectDir, 0777); e != nil {
if e := os.MkdirAll(objectDir, 0777); e != nil {
err := f.toClientError(e, f.PathURL.Path)
return 0, err.Trace(f.PathURL.Path)
}
@@ -337,10 +343,12 @@ func (f *fsClient) put(reader io.Reader, size int64, metadata map[string][]strin
})
}
}
// Safely completed put. Now commit by renaming to actual filename.
if e = os.Rename(objectPartPath, objectPath); e != nil {
err := f.toClientError(e, objectPath)
return totalWritten, err.Trace(objectPartPath, objectPath)
if !avoidResumeUpload {
// Safely completed put. Now commit by renaming to actual filename.
if e = os.Rename(objectPartPath, objectPath); e != nil {
err := f.toClientError(e, objectPath)
return totalWritten, err.Trace(objectPartPath, objectPath)
}
}
return totalWritten, nil
}
@@ -388,16 +396,7 @@ func readFile(fpath string) (io.ReadCloser, error) {
// createFile creates an empty file at the provided filepath
// if one does not exist already.
func createFile(fpath string) (io.WriteCloser, error) {
st, e := os.Stat(fpath)
// If destination exists but is not regular.
if e == nil && !st.Mode().IsRegular() {
return nil, PathIsNotRegular{Path: fpath}
}
// If file exists already.
if e != nil && !os.IsNotExist(e) {
return nil, e
}
if e = os.MkdirAll(filepath.Dir(fpath), 0777); e != nil {
if e := os.MkdirAll(filepath.Dir(fpath), 0777); e != nil {
return nil, e
}
file, e := os.Create(fpath)
@@ -933,7 +932,10 @@ func (f *fsClient) listRecursiveInRoutine(contentCh chan *clientContent) {
}
// MakeBucket - create a new bucket.
func (f *fsClient) MakeBucket(region string) *probe.Error {
func (f *fsClient) MakeBucket(region string, ignoreExisting bool) *probe.Error {
// TODO: ignoreExisting has no effect currently. In the future, we want
// to call os.Mkdir() when ignoredExisting is disabled and os.MkdirAll()
// otherwise.
e := os.MkdirAll(f.PathURL.Path, 0777)
if e != nil {
return probe.NewError(e)
+23 -17
View File
@@ -1,7 +1,7 @@
// +build linux
/*
* Minio Client (C) 2015 Minio, Inc.
* Minio Client (C) 2015, 2016, 2017 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this fs except in compliance with the License.
@@ -23,34 +23,40 @@ import (
)
var (
// EventTypePut contains the notify events that will cause a put
// EventTypePut contains the notify events that will cause a put (write)
EventTypePut = []notify.Event{notify.InCloseWrite | notify.InMovedTo}
// EventTypeDelete contains the notify events that will cause a delete
// EventTypeDelete contains the notify events that will cause a delete (remove)
EventTypeDelete = []notify.Event{notify.InDelete | notify.InDeleteSelf | notify.InMovedFrom}
// EventTypeGet contains the notify events that will cause a get (read)
EventTypeGet = []notify.Event{notify.InAccess | notify.InOpen}
)
// IsGetEvent checks if the event return is a get event.
func IsGetEvent(event notify.Event) bool {
for _, ev := range EventTypeGet {
if event&ev != 0 {
return true
}
}
return false
}
// IsPutEvent checks if the event returned is a put event
func IsPutEvent(event notify.Event) bool {
switch event {
case notify.InCloseWrite:
return true
case notify.InMovedTo:
return true
for _, ev := range EventTypePut {
if event&ev != 0 {
return true
}
}
return false
}
// IsDeleteEvent checks if the event returned is a delete event
func IsDeleteEvent(event notify.Event) bool {
switch event {
case notify.InDelete:
return true
case notify.InDeleteSelf:
return true
case notify.InMovedFrom:
return true
for _, ev := range EventTypeDelete {
if event&ev != 0 {
return true
}
}
return false
}
+16 -18
View File
@@ -1,7 +1,7 @@
// +build !linux
// +build darwin freebsd solaris
/*
* Minio Client (C) 2015 Minio, Inc.
* Minio Client (C) 2015, 2016, 2017 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this fs except in compliance with the License.
@@ -21,32 +21,30 @@ package cmd
import "github.com/rjeczalik/notify"
var (
// EventTypePut contains the notify events that will cause a put
// EventTypePut contains the notify events that will cause a put (writer)
EventTypePut = []notify.Event{notify.Create, notify.Write, notify.Rename}
// EventTypeDelete contains the notify events that will cause a delete
// EventTypeDelete contains the notify events that will cause a delete (remove)
EventTypeDelete = []notify.Event{notify.Remove}
// EventTypeGet contains the notify events that will cause a get (read)
EventTypeGet = []notify.Event{} // On macOS, FreeBSD, Solaris this is not available.
)
// IsGetEvent checks if the event return is a get event.
func IsGetEvent(event notify.Event) bool {
return false
}
// IsPutEvent checks if the event returned is a put event
func IsPutEvent(event notify.Event) bool {
switch event {
case notify.Create:
return true
case notify.Rename:
return true
case notify.Write:
return true
for _, ev := range EventTypePut {
if event&ev != 0 {
return true
}
}
return false
}
// IsDeleteEvent checks if the event returned is a delete event
func IsDeleteEvent(event notify.Event) bool {
switch event {
case notify.Remove:
return true
}
return false
return event&notify.Remove != 0
}
+3 -3
View File
@@ -193,7 +193,7 @@ func (s *TestSuite) TestPutBucket(c *C) {
bucketPath := filepath.Join(root, "bucket")
fsClient, err := fsNew(bucketPath)
c.Assert(err, IsNil)
err = fsClient.MakeBucket("us-east-1")
err = fsClient.MakeBucket("us-east-1", true)
c.Assert(err, IsNil)
}
@@ -207,7 +207,7 @@ func (s *TestSuite) TestStatBucket(c *C) {
fsClient, err := fsNew(bucketPath)
c.Assert(err, IsNil)
err = fsClient.MakeBucket("us-east-1")
err = fsClient.MakeBucket("us-east-1", true)
c.Assert(err, IsNil)
_, err = fsClient.Stat(false)
c.Assert(err, IsNil)
@@ -222,7 +222,7 @@ func (s *TestSuite) TestBucketACLFails(c *C) {
bucketPath := filepath.Join(root, "bucket")
fsClient, err := fsNew(bucketPath)
c.Assert(err, IsNil)
err = fsClient.MakeBucket("us-east-1")
err = fsClient.MakeBucket("us-east-1", true)
c.Assert(err, IsNil)
// On windows setting permissions is not supported.
+50
View File
@@ -0,0 +1,50 @@
// +build windows
/*
* Minio Client (C) 2017 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this fs except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cmd
import "github.com/rjeczalik/notify"
var (
// EventTypePut contains the notify events that will cause a put (writer)
EventTypePut = []notify.Event{notify.Create, notify.Write, notify.Rename}
// EventTypeDelete contains the notify events that will cause a delete (remove)
EventTypeDelete = []notify.Event{notify.Remove}
// EventTypeGet contains the notify events that will cause a get (read)
EventTypeGet = []notify.Event{notify.FileNotifyChangeLastAccess}
)
// IsGetEvent checks if the event return is a get event.
func IsGetEvent(event notify.Event) bool {
return event&notify.FileNotifyChangeLastAccess != 0
}
// IsPutEvent checks if the event returned is a put event
func IsPutEvent(event notify.Event) bool {
for _, ev := range EventTypePut {
if event&ev != 0 {
return true
}
}
return false
}
// IsDeleteEvent checks if the event returned is a delete event
func IsDeleteEvent(event notify.Event) bool {
return event&notify.Remove != 0
}
+62 -22
View File
@@ -1,5 +1,5 @@
/*
* Minio Client (C) 2015 Minio, Inc.
* Minio Client (C) 2015, 2016, 2017 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -206,6 +206,8 @@ func (c *s3Client) AddNotificationConfig(arn string, events []string, prefix, su
nc.AddEvents(minio.ObjectCreatedAll)
case "delete":
nc.AddEvents(minio.ObjectRemovedAll)
case "get":
nc.AddEvents(minio.ObjectAccessedAll)
default:
return errInvalidArgument().Trace(events...)
}
@@ -366,7 +368,7 @@ func (c *s3Client) ListNotificationConfigs(arn string) ([]notificationConfig, *p
// Start watching on all bucket events for a given account ID.
func (c *s3Client) Watch(params watchParams) (*watchObject, *probe.Error) {
eventChan := make(chan Event)
eventChan := make(chan EventInfo)
errorChan := make(chan *probe.Error)
doneChan := make(chan bool)
@@ -384,6 +386,8 @@ func (c *s3Client) Watch(params watchParams) (*watchObject, *probe.Error) {
events = append(events, string(minio.ObjectCreatedAll))
case "delete":
events = append(events, string(minio.ObjectRemovedAll))
case "get":
events = append(events, string(minio.ObjectAccessedAll))
default:
return nil, errInvalidArgument().Trace(event)
}
@@ -410,9 +414,9 @@ func (c *s3Client) Watch(params watchParams) (*watchObject, *probe.Error) {
eventsCh := c.api.ListenBucketNotification(bucket, params.prefix, params.suffix, events, doneCh)
wo := &watchObject{
events: eventChan,
errors: errorChan,
done: doneChan,
eventInfoChan: eventChan,
errorChan: errorChan,
doneChan: doneChan,
}
// wait for events to occur and sent them through the eventChan and errorChan
@@ -441,22 +445,45 @@ func (c *s3Client) Watch(params watchParams) (*watchObject, *probe.Error) {
u := *c.targetURL
u.Path = path.Join(string(u.Separator), bucketName, key)
if strings.HasPrefix(record.EventName, "s3:ObjectCreated:") {
eventChan <- Event{
Time: record.EventTime,
Size: record.S3.Object.Size,
Path: u.String(),
Client: c,
Type: EventCreate,
eventChan <- EventInfo{
Time: record.EventTime,
Size: record.S3.Object.Size,
Path: u.String(),
Type: EventCreate,
Host: record.Source.Host,
Port: record.Source.Port,
UserAgent: record.Source.UserAgent,
}
} else if strings.HasPrefix(record.EventName, "s3:ObjectRemoved:") {
eventChan <- Event{
Time: record.EventTime,
Path: u.String(),
Client: c,
Type: EventRemove,
eventChan <- EventInfo{
Time: record.EventTime,
Path: u.String(),
Type: EventRemove,
Host: record.Source.Host,
Port: record.Source.Port,
UserAgent: record.Source.UserAgent,
}
} else if record.EventName == minio.ObjectAccessedGet {
eventChan <- EventInfo{
Time: record.EventTime,
Size: record.S3.Object.Size,
Path: u.String(),
Type: EventAccessedRead,
Host: record.Source.Host,
Port: record.Source.Port,
UserAgent: record.Source.UserAgent,
}
} else if record.EventName == minio.ObjectAccessedHead {
eventChan <- EventInfo{
Time: record.EventTime,
Size: record.S3.Object.Size,
Path: u.String(),
Type: EventAccessedStat,
Host: record.Source.Host,
Port: record.Source.Port,
UserAgent: record.Source.UserAgent,
}
} else {
// ignore other events
}
}
}
@@ -715,13 +742,13 @@ func isValidBucketName(bucketName string) *probe.Error {
return probe.NewError(errors.New("Bucket name should be more than 3 characters and less than 64 characters"))
}
if !validBucketName.MatchString(bucketName) {
return probe.NewError(errors.New("Bucket name can contain alphabet, '-' and numbers, but first character should be an alphabet or number"))
return probe.NewError(errors.New("Bucket names can only contain lowercase alpha characters `a-z`, numbers '0-9', or '-'. First/last character cannot be a '-'"))
}
return nil
}
// MakeBucket - make a new bucket.
func (c *s3Client) MakeBucket(region string) *probe.Error {
func (c *s3Client) MakeBucket(region string, ignoreExisting bool) *probe.Error {
bucket, object := c.url2BucketAndObject()
if object != "" {
return probe.NewError(BucketNameTopLevel{})
@@ -731,6 +758,15 @@ func (c *s3Client) MakeBucket(region string) *probe.Error {
}
e := c.api.MakeBucket(bucket, region)
if e != nil {
// Ignore bucket already existing error when ignoreExisting flag is enabled
if ignoreExisting {
switch minio.ToErrorResponse(e).Code {
case "BucketAlreadyOwnedByYou":
fallthrough
case "BucketAlreadyExists":
return nil
}
}
return probe.NewError(e)
}
return nil
@@ -895,6 +931,10 @@ func isAmazon(host string) bool {
return s3utils.IsAmazonEndpoint(url.URL{Host: host})
}
func isAmazonChina(host string) bool {
return s3utils.IsAmazonChinaEndpoint(url.URL{Host: host})
}
func isAmazonAccelerated(host string) bool {
return host == "s3-accelerate.amazonaws.com"
}
@@ -907,7 +947,7 @@ func isGoogle(host string) bool {
// Currently only supported hosts with virtual style
// are Amazon S3 and Google Cloud Storage.
func isVirtualHostStyle(host string) bool {
return isAmazon(host) || isGoogle(host) || isAmazonAccelerated(host)
return isAmazon(host) && !isAmazonChina(host) || isGoogle(host) || isAmazonAccelerated(host)
}
// url2BucketAndObject gives bucketName and objectName from URL path.
@@ -1494,7 +1534,7 @@ func (c *s3Client) ShareDownload(expires time.Duration) (string, *probe.Error) {
func (c *s3Client) ShareUpload(isRecursive bool, expires time.Duration, contentType string) (string, map[string]string, *probe.Error) {
bucket, object := c.url2BucketAndObject()
p := minio.NewPostPolicy()
if e := p.SetExpires(time.Now().UTC().Add(expires)); e != nil {
if e := p.SetExpires(UTCNow().Add(expires)); e != nil {
return "", nil, probe.NewError(e)
}
if strings.TrimSpace(contentType) != "" || contentType != "" {
+3 -4
View File
@@ -23,7 +23,6 @@ import (
"net/http"
"net/http/httptest"
"strconv"
"time"
. "gopkg.in/check.v1"
)
@@ -104,7 +103,7 @@ func (h objectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
return
}
w.Header().Set("Content-Length", strconv.Itoa(len(h.data)))
w.Header().Set("Last-Modified", time.Now().UTC().Format(http.TimeFormat))
w.Header().Set("Last-Modified", UTCNow().Format(http.TimeFormat))
w.Header().Set("ETag", "9af2f8218b150c351ad802c6f3d66abe")
w.WriteHeader(http.StatusOK)
case r.Method == "POST":
@@ -151,7 +150,7 @@ func (h objectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
return
}
w.Header().Set("Content-Length", strconv.Itoa(len(h.data)))
w.Header().Set("Last-Modified", time.Now().UTC().Format(http.TimeFormat))
w.Header().Set("Last-Modified", UTCNow().Format(http.TimeFormat))
w.Header().Set("ETag", "9af2f8218b150c351ad802c6f3d66abe")
w.WriteHeader(http.StatusOK)
io.Copy(w, bytes.NewReader(h.data))
@@ -174,7 +173,7 @@ func (s *TestSuite) TestBucketOperations(c *C) {
s3c, err := s3New(conf)
c.Assert(err, IsNil)
err = s3c.MakeBucket("us-east-1")
err = s3c.MakeBucket("us-east-1", true)
c.Assert(err, IsNil)
conf.HostURL = server.URL + string(s3c.GetURL().Separator)
+1 -1
View File
@@ -43,7 +43,7 @@ type Client interface {
List(isRecursive, isIncomplete bool, showDir DirOpt) <-chan *clientContent
// Bucket operations
MakeBucket(region string) *probe.Error
MakeBucket(region string, ignoreExisting bool) *probe.Error
// Access policy operations.
GetAccess() (access string, error *probe.Error)
+12
View File
@@ -17,6 +17,8 @@
package cmd
import (
urlpkg "net/url"
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/console"
@@ -126,6 +128,16 @@ func mainConfigHostAdd(ctx *cli.Context) error {
accessKey := args.Get(2)
secretKey := args.Get(3)
api := args.Get(4)
parsedURL, _ := urlpkg.Parse(url)
if isGoogle(parsedURL.Host) {
if api == "S3v4" {
fatalIf(errInvalidArgument().Trace(api), "Unsupported API signature for url. Please use `mc config host add "+alias+" "+url+" "+accessKey+" "+secretKey+" S3v2` instead.")
}
api = "S3v2"
}
if api == "" {
api = "S3v4"
}
+20 -13
View File
@@ -94,7 +94,12 @@ func printHosts(hosts ...hostMessage) {
}
for _, host := range hosts {
// Format properly for alignment based on alias length.
host.Alias = fmt.Sprintf("%-*.*s", maxAlias, maxAlias, host.Alias)
host.Alias = fmt.Sprintf("%-*.*s:", maxAlias, maxAlias, host.Alias)
if host.AccessKey == "" || host.SecretKey == "" {
host.AccessKey = ""
host.SecretKey = ""
host.API = ""
}
printMsg(host)
}
}
@@ -115,12 +120,13 @@ func listHosts(alias string) {
if alias != "" {
if v, ok := conf.Hosts[alias]; ok {
printHosts(hostMessage{
op: "list",
Alias: alias,
URL: v.URL,
AccessKey: v.AccessKey,
SecretKey: v.SecretKey,
API: v.API,
op: "list",
prettyPrint: false,
Alias: alias,
URL: v.URL,
AccessKey: v.AccessKey,
SecretKey: v.SecretKey,
API: v.API,
})
return
}
@@ -130,12 +136,13 @@ func listHosts(alias string) {
var hosts []hostMessage
for k, v := range conf.Hosts {
hosts = append(hosts, hostMessage{
op: "list",
Alias: k,
URL: v.URL,
AccessKey: v.AccessKey,
SecretKey: v.SecretKey,
API: v.API,
op: "list",
prettyPrint: true,
Alias: k,
URL: v.URL,
AccessKey: v.AccessKey,
SecretKey: v.SecretKey,
API: v.API,
})
}
+29 -16
View File
@@ -18,7 +18,6 @@ package cmd
import (
"encoding/json"
"fmt"
"github.com/minio/cli"
"github.com/minio/mc/pkg/console"
@@ -48,27 +47,41 @@ func mainConfigHost(ctx *cli.Context) error {
// hostMessage container for content message structure
type hostMessage struct {
op string
Status string `json:"status"`
Alias string `json:"alias"`
URL string `json:"URL"`
AccessKey string `json:"accessKey,omitempty"`
SecretKey string `json:"secretKey,omitempty"`
API string `json:"api,omitempty"`
op string
prettyPrint bool
Status string `json:"status"`
Alias string `json:"alias"`
URL string `json:"URL"`
AccessKey string `json:"accessKey,omitempty"`
SecretKey string `json:"secretKey,omitempty"`
API string `json:"api,omitempty"`
}
// String colorized host message
// Print the config information of one alias, when prettyPrint flag
// is activated, fields contents are cut and '...' will be added to
// show a pretty table of all aliases configurations
func (h hostMessage) String() string {
switch h.op {
case "list":
message := console.Colorize("Alias", fmt.Sprintf("%s: ", h.Alias))
message += console.Colorize("URL", fmt.Sprintf("%-30.30s", h.URL))
if h.AccessKey != "" || h.SecretKey != "" {
message += console.Colorize("AccessKey", fmt.Sprintf(" %-20.20s", h.AccessKey))
message += console.Colorize("SecretKey", fmt.Sprintf(" %-40.40s", h.SecretKey))
message += console.Colorize("API", fmt.Sprintf(" %.20s", h.API))
urlFieldMaxLen, apiFieldMaxLen := -1, -1
accessFieldMaxLen, secretFieldMaxLen := -1, -1
// Set cols width if prettyPrint flag is enabled
if h.prettyPrint {
urlFieldMaxLen = 30
accessFieldMaxLen = 20
secretFieldMaxLen = 40
apiFieldMaxLen = 5
}
return message
// Create a new pretty table with cols configuration
t := newPrettyTable(" ",
Field{"Alias", -1},
Field{"URL", urlFieldMaxLen},
Field{"AccessKey", accessFieldMaxLen},
Field{"SecretKey", secretFieldMaxLen},
Field{"API", apiFieldMaxLen},
)
return t.buildRow(h.Alias, h.URL, h.AccessKey, h.SecretKey, h.API)
case "remove":
return console.Colorize("HostMessage", "Removed `"+h.Alias+"` successfully.")
case "add":
+1 -1
View File
@@ -149,7 +149,7 @@ func isMcConfigExists() bool {
// isValidAlias - Check if alias valid.
func isValidAlias(alias string) bool {
return regexp.MustCompile("^[a-zA-Z][a-zA-Z0-9-]+$").MatchString(alias)
return regexp.MustCompile("^[a-zA-Z][a-zA-Z0-9-_]+$").MatchString(alias)
}
// getHostConfig retrieves host specific configuration such as access keys, signature type.
+64 -64
View File
@@ -24,7 +24,6 @@ import (
"os"
"path/filepath"
"strings"
"sync"
"syscall"
"github.com/cheggaaa/pb"
@@ -242,7 +241,7 @@ func doPrepareCopyURLs(session *sessionV8, trapCh <-chan bool) {
session.Save()
}
func doCopySession(session *sessionV8) {
func doCopySession(session *sessionV8) error {
trapCh := signalTrap(os.Interrupt, syscall.SIGTERM, syscall.SIGKILL)
if !session.HasData() {
@@ -267,75 +266,74 @@ func doCopySession(session *sessionV8) {
// Wait on status of doCopy() operation.
var statusCh = make(chan URLs)
// Add a wait group.
var wg = new(sync.WaitGroup)
wg.Add(1)
// Go routine to monitor signal traps if any.
go func() {
defer wg.Done()
for {
select {
case <-trapCh:
// Receive interrupt notification.
// Loop through all urls.
for urlScanner.Scan() {
var cpURLs URLs
// Unmarshal copyURLs from each line.
json.Unmarshal([]byte(urlScanner.Text()), &cpURLs)
// Save total count.
cpURLs.TotalCount = session.Header.TotalObjects
// Save totalSize.
cpURLs.TotalSize = session.Header.TotalBytes
// Verify if previously copied, notify progress bar.
if isCopied(cpURLs.SourceContent.URL.String()) {
statusCh <- doCopyFake(cpURLs, progressReader)
} else {
statusCh <- doCopy(cpURLs, progressReader, accntReader)
}
}
// URLs feeding finished
close(statusCh)
}()
var retErr error
loop:
for {
select {
case <-trapCh:
// Receive interrupt notification.
if !globalQuiet && !globalJSON {
console.Eraseline()
}
session.CloseAndDie()
case cpURLs, ok := <-statusCh:
// Status channel is closed, we should return.
if !ok {
break loop
}
if cpURLs.Error == nil {
session.Header.LastCopied = cpURLs.SourceContent.URL.String()
session.Save()
} else {
// Set exit status for any copy error
retErr = exitStatus(globalErrorExitStatus)
// Print in new line and adjust to top so that we
// don't print over the ongoing progress bar.
if !globalQuiet && !globalJSON {
console.Eraseline()
}
errorIf(cpURLs.Error.Trace(cpURLs.SourceContent.URL.String()),
fmt.Sprintf("Failed to copy `%s`.", cpURLs.SourceContent.URL.String()))
if isErrIgnored(cpURLs.Error) {
continue loop
}
// For critical errors we should exit. Session
// can be resumed after the user figures out
// the problem.
session.CloseAndDie()
case cpURLs, ok := <-statusCh:
// Status channel is closed, we should return.
if !ok {
return
}
if cpURLs.Error == nil {
session.Header.LastCopied = cpURLs.SourceContent.URL.String()
session.Save()
} else {
// Print in new line and adjust to top so that we
// don't print over the ongoing progress bar.
if !globalQuiet && !globalJSON {
console.Eraseline()
}
errorIf(cpURLs.Error.Trace(cpURLs.SourceContent.URL.String()),
fmt.Sprintf("Failed to copy `%s`.", cpURLs.SourceContent.URL.String()))
if isErrIgnored(cpURLs.Error) {
continue
}
// For critical errors we should exit. Session
// can be resumed after the user figures out
// the problem.
session.CloseAndDie()
}
}
}
}()
// Loop through all urls.
for urlScanner.Scan() {
var cpURLs URLs
// Unmarshal copyURLs from each line.
json.Unmarshal([]byte(urlScanner.Text()), &cpURLs)
// Save total count.
cpURLs.TotalCount = session.Header.TotalObjects
// Save totalSize.
cpURLs.TotalSize = session.Header.TotalBytes
// Verify if previously copied, notify progress bar.
if isCopied(cpURLs.SourceContent.URL.String()) {
statusCh <- doCopyFake(cpURLs, progressReader)
} else {
statusCh <- doCopy(cpURLs, progressReader, accntReader)
}
}
// Close the goroutine.
close(statusCh)
// Wait for the goroutines to finish.
wg.Wait()
if !globalQuiet && !globalJSON {
if progressReader.ProgressBar.Get() > 0 {
progressReader.ProgressBar.Finish()
@@ -345,6 +343,8 @@ func doCopySession(session *sessionV8) {
console.Println(console.Colorize("Copy", accntReader.Stat().String()))
}
}
return retErr
}
// mainCopy is the entry point for cp command.
@@ -368,8 +368,8 @@ func mainCopy(ctx *cli.Context) error {
// extract URLs.
session.Header.CommandArgs = ctx.Args()
doCopySession(session)
e = doCopySession(session)
session.Delete()
return nil
return e
}
+3 -3
View File
@@ -30,7 +30,7 @@ var (
eventsAddFlags = []cli.Flag{
cli.StringFlag{
Name: "events",
Value: "put,delete",
Value: "put,delete,get",
Usage: "Filter specific type of events. Defaults to all events.",
},
cli.StringFlag{
@@ -54,7 +54,7 @@ var eventsAddCmd = cli.Command{
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} ALIAS/BUCKET ARN [FLAGS]
{{.HelpName}} TARGET ARN [FLAGS]
FLAGS:
{{range .VisibleFlags}}{{.}}
@@ -64,7 +64,7 @@ EXAMPLES:
$ {{.HelpName}} myminio/mybucket arn:aws:sqs:us-west-2:444455556666:your-queue
2. Enable bucket notification with filters parameters
$ {{.HelpName}} s3/mybucket arn:aws:sqs:us-west-2:444455556666:your-queue --events put,delete --prefix photos/ --suffix .jpg
$ {{.HelpName}} s3/mybucket arn:aws:sqs:us-west-2:444455556666:your-queue --events put,delete,get --prefix photos/ --suffix .jpg
`,
}
+1 -1
View File
@@ -40,7 +40,7 @@ var eventsListCmd = cli.Command{
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} ALIAS/BUCKET ARN [FLAGS]
{{.HelpName}} TARGET ARN [FLAGS]
FLAGS:
{{range .VisibleFlags}}{{.}}
+1 -1
View File
@@ -45,7 +45,7 @@ var eventsRemoveCmd = cli.Command{
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} ALIAS/BUCKET [ARN] [FLAGS]
{{.HelpName}} TARGET [ARN] [FLAGS]
FLAGS:
{{range .VisibleFlags}}{{.}}
+3
View File
@@ -64,6 +64,9 @@ var (
)
var (
// Terminal width
globalTermWidth int
// CA root certificates, a nil value means system certs pool will be used
globalRootCAs *x509.CertPool
)
+8 -3
View File
@@ -77,12 +77,17 @@ func Main() {
probe.SetAppInfo("Release-Tag", ReleaseTag)
probe.SetAppInfo("Commit", ShortCommitID)
// Fetch terminal size, if not available, automatically
// set globalQuiet to true.
if w, e := pb.GetTerminalWidth(); e != nil {
globalQuiet = true
} else {
globalTermWidth = w
}
app := registerApp()
app.Before = registerBefore
app.ExtraInfo = func() map[string]string {
if _, e := pb.GetTerminalWidth(); e != nil {
globalQuiet = true
}
if globalDebug {
return getSystemData()
}
+6 -1
View File
@@ -32,6 +32,10 @@ var (
Value: "us-east-1",
Usage: "Specify bucket region. Defaults to `us-east-1`.",
},
cli.BoolFlag{
Name: "ignore-existing, p",
Usage: "Ignore if bucket/directory already exists",
},
}
)
@@ -108,6 +112,7 @@ func mainMakeBucket(ctx *cli.Context) error {
// Save region.
region := ctx.String("region")
ignoreExisting := ctx.Bool("p")
var cErr error
for i := range ctx.Args() {
@@ -121,7 +126,7 @@ func mainMakeBucket(ctx *cli.Context) error {
}
// Make bucket.
err = clnt.MakeBucket(region)
err = clnt.MakeBucket(region, ignoreExisting)
if err != nil {
errorIf(err.Trace(targetURL), "Unable to make bucket `"+targetURL+"`.")
cErr = exitStatus(globalErrorExitStatus)
+1
View File
@@ -89,6 +89,7 @@ func (s *TestSuite) TestGetMcConfigPath(c *C) {
func (s *TestSuite) TestIsvalidAliasName(c *C) {
c.Check(isValidAlias("helloWorld0"), Equals, true)
c.Check(isValidAlias("hello_World0"), Equals, true)
c.Check(isValidAlias("h0SFD2k24Fdsa"), Equals, true)
c.Check(isValidAlias("fdslka-4"), Equals, true)
c.Check(isValidAlias("fdslka-"), Equals, true)
+12 -7
View File
@@ -20,11 +20,11 @@ import (
"encoding/json"
"fmt"
"os"
"path"
"path/filepath"
"strings"
"sync"
"syscall"
"time"
"github.com/fatih/color"
"github.com/minio/cli"
@@ -229,7 +229,6 @@ func (mj *mirrorJob) startStatus() {
go func() {
// now we want to start the progress bar
mj.status.Start()
defer mj.status.Finish()
defer mj.wgStatus.Done()
for sURLs := range mj.statusCh {
@@ -262,6 +261,7 @@ func (mj *mirrorJob) startStatus() {
func (mj *mirrorJob) stopStatus() {
close(mj.statusCh)
mj.wgStatus.Wait()
mj.status.Finish()
}
// this goroutine will watch for notifications, and add modified objects to the queue
@@ -509,7 +509,7 @@ func newMirrorJob(srcURL, dstURL string, isFake, isRemove, isWatch, isForce bool
statusCh: make(chan URLs),
wgStatus: new(sync.WaitGroup),
watcherRunning: true,
watcher: NewWatcher(time.Now().UTC()),
watcher: NewWatcher(UTCNow()),
}
return &mj
@@ -555,7 +555,12 @@ func runMirror(srcURL, dstURL string, ctx *cli.Context) *probe.Error {
dstClt, err := newClient(dstURL)
fatalIf(err, "Unable to initialize `"+srcURL+"`")
mirrorAllBuckets := (dstClt.GetURL().Type == objectStorage && dstClt.GetURL().Path == "/")
if ctx.Bool("a") && (srcClt.GetURL().Type != objectStorage || dstClt.GetURL().Type != objectStorage) {
fatalIf(errDummy(), "Synchronizing bucket policies is only possible when both source & target point to S3 servers")
}
mirrorAllBuckets := (srcClt.GetURL().Type == objectStorage && srcClt.GetURL().Path == "/") ||
(dstClt.GetURL().Type == objectStorage && dstClt.GetURL().Path == "/")
if mirrorAllBuckets {
// Synchronize buckets using dirDifference function
@@ -570,15 +575,15 @@ func runMirror(srcURL, dstURL string, ctx *cli.Context) *probe.Error {
sourceSuffix := strings.TrimPrefix(d.FirstURL, srcClt.GetURL().String())
newSrcURL := srcURL + sourceSuffix
newTgtURL := dstURL + sourceSuffix
newSrcURL := path.Join(srcURL, sourceSuffix)
newTgtURL := path.Join(dstURL, sourceSuffix)
newSrcClt, _ := newClient(newSrcURL)
newDstClt, _ := newClient(newTgtURL)
if d.Diff == differInFirst {
// Bucket only exists in the source, create the same bucket in the destination
err := newDstClt.MakeBucket(ctx.String("region"))
err := newDstClt.MakeBucket(ctx.String("region"), false)
if err != nil {
mj.mirrorErr = err
errorIf(err, "Cannot created bucket in `"+newTgtURL+"`")
+89
View File
@@ -0,0 +1,89 @@
/*
* Minio Client (C) 2017 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cmd
import "github.com/rjeczalik/notify"
// Dynamically sized logical channel: a pipe which never blocks even when
// it receives too many elements. Memory consumption is increased and decresed
// on the fly following the number of elements. Here is the benchmark which
// compares a regular channel which a large capacity (like 1 Million) in
// contrast to a PipeChan with an realtime increasing/decreasing capacity.
//
// BenchmarkRegular1M-4 200 172809399 ns/op
// BenchmarkPipeChan1M-4 100 316668338 ns/op
// BenchmarkRegular100K-4 2000 16540648 ns/op
// BenchmarkPipeChan100K-4 1000 31905966 ns/op
// BenchmarkRegular10K-4 20000 1637665 ns/op
// BenchmarkPipeChan10K-4 10000 3324329 ns/op
// BenchmarkRegular1K-4 200000 168512 ns/op
// BenchmarkPipeChan1K-4 100000 550623 ns/op
// PipeChan builds a new dynamically sized channel
func PipeChan(capacity int) (inputCh chan notify.EventInfo, outputCh chan notify.EventInfo) {
// A set of channels which store all elements received from input
channels := make(chan chan notify.EventInfo, 1000)
inputCh = make(chan notify.EventInfo, capacity)
// A goroutine which receives elements from inputCh and creates
// new channels when needed.
go func() {
// Create the first channel
currCh := make(chan notify.EventInfo, capacity)
channels <- currCh
for elem := range inputCh {
// Prepare next channel with a double capacity when
// half of the current channel is already filled.
if len(currCh) >= cap(currCh)/2 {
close(currCh)
currCh = make(chan notify.EventInfo, cap(currCh)*2)
channels <- currCh
}
// Prepare next channel with half capacity when
// current channel is 1/4 filled
if len(currCh) >= capacity && len(currCh) <= cap(currCh)/4 {
close(currCh)
currCh = make(chan notify.EventInfo, cap(currCh)/2)
channels <- currCh
}
// Send element to current channel
currCh <- elem
}
close(currCh)
close(channels)
}()
// Copy elements from infinite channel set to the output
outputCh = make(chan notify.EventInfo, capacity)
go func() {
for {
currCh, ok := <-channels
if !ok {
break
}
for v := range currCh {
outputCh <- v
}
}
close(outputCh)
}()
return inputCh, outputCh
}
+141
View File
@@ -0,0 +1,141 @@
/*
* Minio Client (C) 2017 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cmd
import (
"fmt"
"sync"
"testing"
"github.com/rjeczalik/notify"
)
func testPipeChan(inputCh, outputCh chan notify.EventInfo, totalMsgs int) error {
var wg sync.WaitGroup
msgCtnt := notify.EventInfo(nil)
// Send messages up to totalMsgs
wg.Add(1)
go func() {
defer wg.Done()
for i := 0; i < totalMsgs; i++ {
select {
case inputCh <- msgCtnt:
}
}
close(inputCh)
}()
// Goroutine to receive and check messages
var recvMsgs int
var recvErr error
wg.Add(1)
go func() {
defer wg.Done()
for msg := range outputCh {
recvMsgs++
if msg != msgCtnt {
recvErr = fmt.Errorf("Corrupted message, expected = `%s`, found = `%s`", msgCtnt, msg)
return
}
}
}()
// Wait until we finish sending and receiving messages
wg.Wait()
if recvErr != nil {
return recvErr
}
// Check if all messages are received
if recvMsgs != totalMsgs {
return fmt.Errorf("unable to receive all messages, expected: %d, lost: %d", totalMsgs, totalMsgs-recvMsgs)
}
return nil
}
// Testing code
func TestPipeChannel(t *testing.T) {
fastCh, slowCh := PipeChan(1000)
err := testPipeChan(fastCh, slowCh, 10*1000)
if err != nil {
t.Errorf("ERR: %v\n", err)
}
}
func TestRegularChannel(t *testing.T) {
ch := make(chan notify.EventInfo, 1000)
err := testPipeChan(ch, ch, 10*1000)
if err != nil {
t.Errorf("ERR: %v\n", err)
}
}
// Benchmark code
func benchmarkRegular(b *testing.B, msgsNum int) {
for n := 0; n < b.N; n++ {
ch := make(chan notify.EventInfo, msgsNum)
testPipeChan(ch, ch, msgsNum)
}
}
func benchmarkPipeChan(b *testing.B, msgsNum int) {
for n := 0; n < b.N; n++ {
fastCh, slowCh := PipeChan(1000)
testPipeChan(fastCh, slowCh, msgsNum)
}
}
func BenchmarkRegular1M(b *testing.B) {
benchmarkRegular(b, 1*1000*1000)
}
func BenchmarkPipeChan1M(b *testing.B) {
benchmarkPipeChan(b, 1*1000*1000)
}
func BenchmarkRegular100K(b *testing.B) {
benchmarkRegular(b, 100*1000)
}
func BenchmarkPipeChan100K(b *testing.B) {
benchmarkPipeChan(b, 100*1000)
}
func BenchmarkRegular10K(b *testing.B) {
benchmarkRegular(b, 10*1000)
}
func BenchmarkPipeChan10K(b *testing.B) {
benchmarkPipeChan(b, 10*1000)
}
func BenchmarkRegular1K(b *testing.B) {
benchmarkRegular(b, 1*1000)
}
func BenchmarkPipeChan1K(b *testing.B) {
benchmarkPipeChan(b, 1*1000)
}
+1
View File
@@ -49,6 +49,7 @@ var policyCmd = cli.Command{
USAGE:
{{.HelpName}} [FLAGS] PERMISSION TARGET
{{.HelpName}} [FLAGS] TARGET
{{.HelpName}} list [FLAGS] TARGET
PERMISSION:
Allowed policies are: [none, download, upload, public].
+84
View File
@@ -0,0 +1,84 @@
/*
* Minio Client (C) 2017 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cmd
import (
"fmt"
"github.com/minio/mc/pkg/console"
)
// Field configuration: color theme and max content length
type Field struct {
colorTheme string
maxLen int
}
// PrettyTable - an easy struct to format a set of line
type PrettyTable struct {
cols []Field
separator string
}
// newPrettyTable - creates a new pretty table
func newPrettyTable(separator string, cols ...Field) PrettyTable {
return PrettyTable{
cols: cols,
separator: separator,
}
}
// buildRow - creates a string which represents a line table given
// some fields contents.
func (t PrettyTable) buildRow(contents ...string) (line string) {
dots := "..."
// totalColumns is the minimum of the number of fields config
// and the number of contents elements.
totalColumns := len(contents)
if len(t.cols) < totalColumns {
totalColumns = len(t.cols)
}
// Format fields and construct message
for i := 0; i < totalColumns; i++ {
// Default field format without pretty effect
fieldContent := ""
fieldFormat := "%s"
if t.cols[i].maxLen >= 0 {
// Override field format
fieldFormat = fmt.Sprintf("%%-%d.%ds", t.cols[i].maxLen, t.cols[i].maxLen)
// Cut field string and add '...' if length is greater than maxLen
if len(contents[i]) > t.cols[i].maxLen {
fieldContent = contents[i][:t.cols[i].maxLen-len(dots)] + dots
} else {
fieldContent = contents[i]
}
} else {
fieldContent = contents[i]
}
// Add separator if this is not the last column
if i < totalColumns-1 {
fieldFormat += t.separator
}
// Add the field to the resulted message
line += console.Colorize(t.cols[i].colorTheme, fmt.Sprintf(fieldFormat, fieldContent))
}
return
}
+51
View File
@@ -0,0 +1,51 @@
/*
* Minio Client (C) 2017 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cmd
import "testing"
// TestPrettyTable - testing the behavior of the pretty table module
func TestPrettyTable(t *testing.T) {
testCases := []struct {
sep string
tf []Field
contents []string
expectedRow string
}{
// Test 1: empty parameter, empty table
{"", []Field{}, []string{}, ""},
// Test 2: one field, without any specific customization
{"", []Field{{"", -1}}, []string{"abcd"}, "abcd"},
// Test 3: one field, without 5 chars len
{"", []Field{{"", 5}}, []string{"my-long-field"}, "my..."},
// Test 4: one separator, one content
{" | ", []Field{{"", -1}}, []string{"abcd"}, "abcd"},
// Test 5: one separtor, multiple contents
{" | ", []Field{{"", -1}, {"", -1}, {"", -1}}, []string{"column1", "column2", "column3"}, "column1 | column2 | column3"},
// Test 6: multiple fields
{" | ", []Field{{"", 5}, {"", -1}}, []string{"144550032", "my long content that should not be cut"}, "14... | my long content that should not be cut"},
}
for idx, testCase := range testCases {
tb := newPrettyTable(testCase.sep, testCase.tf...)
row := tb.buildRow(testCase.contents...)
if row != testCase.expectedRow {
t.Fatalf("Test %d: generated row not matching, expected = `%s`, found = `%s`", idx+1, testCase.expectedRow, row)
}
}
}
+2 -2
View File
@@ -149,7 +149,7 @@ func removeSingle(url string, isIncomplete bool, isFake bool, older int) error {
}
if older > 0 {
// Check whether object is created older than given time.
now := time.Now().UTC()
now := UTCNow()
timeDiff := now.Sub(content.Time)
if timeDiff < (time.Duration(older) * Day) {
// time difference of info.Time with current time is less than older time.
@@ -211,7 +211,7 @@ func removeRecursive(url string, isIncomplete bool, isFake bool, older int) erro
if older > 0 {
// Check whether object is created older than given time.
now := time.Now().UTC()
now := UTCNow()
timeDiff := now.Sub(content.Time)
if timeDiff < (time.Duration(older) * Day) {
// time difference of info.Time with current time is less than older time.
+1 -5
View File
@@ -20,10 +20,8 @@ import (
"fmt"
"strings"
"github.com/cheggaaa/pb"
"github.com/dustin/go-humanize"
"github.com/minio/mc/pkg/console"
"github.com/minio/minio/pkg/probe"
)
// fixateScanBar truncates or stretches text to fit within the terminal size.
@@ -46,14 +44,12 @@ type scanBarFunc func(string)
// scanBarFactory returns a progress bar function to report URL scanning.
func scanBarFactory() scanBarFunc {
fileCount := 0
termWidth, e := pb.GetTerminalWidth()
fatalIf(probe.NewError(e), "Unable to get terminal size. Please use --quiet option.")
// Cursor animate channel.
cursorCh := cursorAnimate()
return func(source string) {
scanPrefix := fmt.Sprintf("[%s] %s ", humanize.Comma(int64(fileCount)), string(<-cursorCh))
source = fixateScanBar(source, termWidth-len([]rune(scanPrefix)))
source = fixateScanBar(source, globalTermWidth-len([]rune(scanPrefix)))
barText := scanPrefix + source
console.PrintC("\r" + barText + "\r")
fileCount++
+3 -3
View File
@@ -45,7 +45,7 @@ var sessionCmd = cli.Command{
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} [FLAGS] OPERATION [ARG]
{{.HelpName}} [FLAGS] OPERATION [SESSION-ID]
OPERATION:
resume Resume a previously saved session.
@@ -134,7 +134,7 @@ func clearSession(sid string) {
session, err := loadSessionV8(sid)
fatalIf(err.Trace(sid), "Unable to load session `"+sid+"`.")
fatalIf(session.Delete().Trace(sid), "Unable to load session `"+sid+"`.")
fatalIf(session.Delete().Trace(sid), "Unable to remove session `"+sid+"`.")
printMsg(clearSessionMessage{Status: "success", SessionID: sid})
}
@@ -156,7 +156,7 @@ func clearSession(sid string) {
}
if session != nil {
fatalIf(session.Delete().Trace(sid), "Unable to load session `"+sid+"`.")
fatalIf(session.Delete().Trace(sid), "Unable to remove session `"+sid+"`.")
printMsg(clearSessionMessage{Status: "success", SessionID: sid})
}
}
+3
View File
@@ -37,6 +37,9 @@ func migrateSessionV7ToV8() {
fatalIf(err.Trace(sid), "Unable to load version `7`. Migration failed please report this issue at https://github.com/minio/mc/issues.")
}
// Close underlying session data file.
sV7.DataFP.Close()
sessionVersion, e := strconv.Atoi(sV7.Header.Version)
fatalIf(probe.NewError(e), "Unable to load version `7`. Migration failed please report this issue at https://github.com/minio/mc/issues.")
if sessionVersion > 7 { // It is new format.
+1 -1
View File
@@ -174,7 +174,7 @@ func newSessionV8() *sessionV8 {
s.Header.CommandBoolFlags = make(map[string]bool)
s.Header.CommandIntFlags = make(map[string]int)
s.Header.CommandStringFlags = make(map[string]string)
s.Header.When = time.Now().UTC()
s.Header.When = UTCNow()
s.mutex = new(sync.Mutex)
s.SessionID = newRandomID(8)
+1 -1
View File
@@ -59,7 +59,7 @@ func (s *shareDBV1) Set(objectURL string, shareURL string, expiry time.Duration,
s.Shares[shareURL] = shareEntryV1{
URL: objectURL,
Date: time.Now().UTC(),
Date: UTCNow(),
Expiry: expiry,
ContentType: contentType,
}
+10 -4
View File
@@ -44,7 +44,7 @@ var shareDownload = cli.Command{
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} [OPTIONS] TARGET [TARGET...]
{{.HelpName}} [FLAGS] TARGET [TARGET...]
OPTIONS:
{{range .VisibleFlags}}{{.}}
@@ -89,9 +89,15 @@ func checkShareDownloadSyntax(ctx *cli.Context) {
fatalIf(errDummy().Trace(expiry.String()), "Expiry cannot be larger than 7 days.")
}
for _, url := range ctx.Args() {
_, _, err := url2Stat(url)
fatalIf(err.Trace(url), "Unable to stat `"+url+"`.")
// Validate if object exists only if the `--recursive` option was NOT specified
isRecursive := ctx.Bool("recursive")
if !isRecursive {
for _, url := range ctx.Args() {
_, _, err := url2Stat(url)
if err != nil {
fatalIf(err.Trace(url), "Unable to stat `"+url+"`.")
}
}
}
}
+1 -1
View File
@@ -47,7 +47,7 @@ var shareUpload = cli.Command{
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} [OPTIONS] TARGET [TARGET...]
{{.HelpName}} [FLAGS] TARGET [TARGET...]
OPTIONS:
{{range .VisibleFlags}}{{.}}
+1 -1
View File
@@ -200,7 +200,7 @@ func downloadReleaseData(releaseChecksumURL string, timeout time.Duration) (data
// DownloadReleaseData - downloads release data from minio official server.
func DownloadReleaseData(timeout time.Duration) (data string, err *probe.Error) {
return downloadReleaseData(mcReleaseURL+"mc.shasum", timeout)
return downloadReleaseData(mcReleaseURL+"mc.sha256sum", timeout)
}
func parseReleaseData(data string) (releaseTime time.Time, err *probe.Error) {
+6 -1
View File
@@ -47,11 +47,16 @@ func isErrIgnored(err *probe.Error) (ignored bool) {
return ignored
}
// UTCNow - returns current UTC time.
func UTCNow() time.Time {
return time.Now().UTC()
}
var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
// newRandomID generates a random id of regular lower case and uppercase english characters.
func newRandomID(n int) string {
rand.Seed(time.Now().UTC().UnixNano())
rand.Seed(UTCNow().UnixNano())
sid := make([]rune, n)
for i := range sid {
sid[i] = letters[rand.Intn(len(letters))]
+22 -5
View File
@@ -36,7 +36,7 @@ var (
watchFlags = []cli.Flag{
cli.StringFlag{
Name: "events",
Value: "put,delete",
Value: "put,delete,get",
Usage: "Filter specific type of events. Defaults to all events by default.",
},
cli.StringFlag{
@@ -64,7 +64,7 @@ var watchCmd = cli.Command{
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} [FLAGS]
{{.HelpName}} PATH [FLAGS]
{{if .VisibleFlags}}
FLAGS:
{{range .VisibleFlags}}{{.}}
@@ -97,7 +97,17 @@ func checkWatchSyntax(ctx *cli.Context) {
// watchMessage container to hold one event notification
type watchMessage struct {
Status string `json:"status"`
Event Event `json:"events"`
Event struct {
Time string `json:"time"`
Size int64 `json:"size"`
Path string `json:"path"`
Type EventType `json:"type"`
} `json:"events"`
Source struct {
Host string `json:"host,omitempty"`
Port string `json:"port,omitempty"`
UserAgent string `json:"userAgent,omitempty"`
} `json:"source,omitempty"`
}
func (u watchMessage) JSON() string {
@@ -169,13 +179,20 @@ func mainWatch(ctx *cli.Context) error {
select {
case <-trapCh:
// Signal received we are done.
close(wo.done)
close(wo.doneChan)
return
case event, ok := <-wo.Events():
if !ok {
return
}
msg := watchMessage{Event: event}
msg := watchMessage{}
msg.Event.Path = event.Path
msg.Event.Size = event.Size
msg.Event.Time = event.Time
msg.Event.Type = event.Type
msg.Source.Host = event.Host
msg.Source.Port = event.Port
msg.Source.UserAgent = event.UserAgent
printMsg(msg)
case err, ok := <-wo.Errors():
if !ok {
+39 -30
View File
@@ -24,23 +24,32 @@ import (
"github.com/minio/minio/pkg/probe"
)
// EventType is the type of the event that occurred
// EventType represents the type of the event occurred.
type EventType string
const (
// EventCreate notifies when a new object has been created
// EventCreate notifies when a new object is created
EventCreate EventType = "ObjectCreated"
// EventRemove notifies when a new object has been deleted
// EventRemove notifies when a new object is deleted
EventRemove = "ObjectRemoved"
// EventAccessed notifies when an object is accessed.
EventAccessed = "ObjectAccessed"
// EventAccessedRead notifies when an object is accessed (specifically read).
EventAccessedRead = "ObjectAccessed:Read"
// EventAccessedStat notifies when an object is accessed (specifically stat).
EventAccessedStat = "ObjectAccessed:Stat"
)
// Event contains the information of the event that occurred
type Event struct {
Time string `json:"time"`
Size int64 `json:"size"`
Path string `json:"path"`
Client Client `json:"-"`
Type EventType `json:"type"`
// EventInfo contains the information of the event that occurred and the source
// IP:PORT of the client which triggerred the event.
type EventInfo struct {
Time string
Size int64
Path string
Type EventType
Host string
Port string
UserAgent string
}
type watchParams struct {
@@ -52,37 +61,37 @@ type watchParams struct {
}
type watchObject struct {
// events will be put on this chan
events chan Event
// eventInfo will be put on this chan
eventInfoChan chan EventInfo
// errors will be put on this chan
errors chan *probe.Error
errorChan chan *probe.Error
// will stop the watcher goroutines
done chan bool
doneChan chan bool
}
// Events returns the chan receiving events
func (w *watchObject) Events() chan Event {
return w.events
func (w *watchObject) Events() chan EventInfo {
return w.eventInfoChan
}
// Errors returns the chan receiving errors
func (w *watchObject) Errors() chan *probe.Error {
return w.errors
return w.errorChan
}
// Close the watcher, will stop all goroutines
func (w *watchObject) Close() {
close(w.done)
close(w.doneChan)
}
// Watcher can be used to have one or multiple clients watch for notifications
type Watcher struct {
sessionStartTime time.Time
// all errors will be added to this chan
errorsChan chan *probe.Error
// all error will be added to this chan
errorChan chan *probe.Error
// all events will be added to this chan
eventsChan chan Event
eventInfoChan chan EventInfo
// array of watchers joined
o []*watchObject
@@ -95,20 +104,20 @@ type Watcher struct {
func NewWatcher(sessionStartTime time.Time) *Watcher {
return &Watcher{
sessionStartTime: sessionStartTime,
errorsChan: make(chan *probe.Error),
eventsChan: make(chan Event),
errorChan: make(chan *probe.Error),
eventInfoChan: make(chan EventInfo),
o: []*watchObject{},
}
}
// Errors returns a channel which will receive errors
func (w *Watcher) Errors() chan *probe.Error {
return w.errorsChan
return w.errorChan
}
// Events returns a channel which will receive events
func (w *Watcher) Events() chan Event {
return w.eventsChan
func (w *Watcher) Events() chan EventInfo {
return w.eventInfoChan
}
// Stop watcher
@@ -120,8 +129,8 @@ func (w *Watcher) Stop() {
w.wg.Wait()
close(w.errorsChan)
close(w.eventsChan)
close(w.errorChan)
close(w.eventInfoChan)
}
// Watching returns if the watcher is watching for notifications
@@ -162,13 +171,13 @@ func (w *Watcher) Join(client Client, recursive bool) *probe.Error {
return
}
w.eventsChan <- event
w.eventInfoChan <- event
case err, ok := <-wo.Errors():
if !ok {
return
}
w.errorsChan <- err
w.errorChan <- err
}
}
}()
+4 -4
View File
@@ -41,7 +41,7 @@ version Print version.
Install minio packages using [Homebrew](http://brew.sh/)
```sh
brew install minio-mc
brew install minio/stable/mc
mc --help
```
@@ -52,9 +52,9 @@ Source installation is intended only for developers and advanced users. `mc upda
If you do not have a working Golang environment, please follow [How to install Golang](https://docs.minio.io/docs/how-to-install-golang).
```sh
go get -u github.com/minio/mc
go get -d github.com/minio/mc
cd ${GOPATH}/src/github.com/minio/mc
make
```
## 2. Run Minio Client
+29 -17
View File
@@ -1,5 +1,5 @@
/*
* Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2015 Minio, Inc.
* Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2015, 2016, 2017 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -48,6 +48,9 @@ type ErrorResponse struct {
// Region where the bucket is located. This header is returned
// only in HEAD bucket and ListObjects response.
Region string
// Headers of the returned S3 XML error
Headers http.Header `xml:"-" json:"-"`
}
// ToErrorResponse - Returns parsed ErrorResponse struct from body and
@@ -72,8 +75,15 @@ func ToErrorResponse(err error) ErrorResponse {
}
}
// Error - Returns HTTP error string
// Error - Returns S3 error string.
func (e ErrorResponse) Error() string {
if e.Message == "" {
msg, ok := s3ErrorResponseMap[e.Code]
if !ok {
msg = fmt.Sprintf("Error response code %s.", e.Code)
}
return msg
}
return e.Message
}
@@ -91,6 +101,7 @@ func httpRespToErrorResponse(resp *http.Response, bucketName, objectName string)
return ErrInvalidArgument(msg)
}
var errResp ErrorResponse
err := xmlDecoder(resp.Body, &errResp)
// Xml decoding failed with no body, fall back to HTTP headers.
if err != nil {
@@ -101,9 +112,6 @@ func httpRespToErrorResponse(resp *http.Response, bucketName, objectName string)
Code: "NoSuchBucket",
Message: "The specified bucket does not exist.",
BucketName: bucketName,
RequestID: resp.Header.Get("x-amz-request-id"),
HostID: resp.Header.Get("x-amz-id-2"),
Region: resp.Header.Get("x-amz-bucket-region"),
}
} else {
errResp = ErrorResponse{
@@ -111,9 +119,6 @@ func httpRespToErrorResponse(resp *http.Response, bucketName, objectName string)
Message: "The specified key does not exist.",
BucketName: bucketName,
Key: objectName,
RequestID: resp.Header.Get("x-amz-request-id"),
HostID: resp.Header.Get("x-amz-id-2"),
Region: resp.Header.Get("x-amz-bucket-region"),
}
}
case http.StatusForbidden:
@@ -122,30 +127,37 @@ func httpRespToErrorResponse(resp *http.Response, bucketName, objectName string)
Message: "Access Denied.",
BucketName: bucketName,
Key: objectName,
RequestID: resp.Header.Get("x-amz-request-id"),
HostID: resp.Header.Get("x-amz-id-2"),
Region: resp.Header.Get("x-amz-bucket-region"),
}
case http.StatusConflict:
errResp = ErrorResponse{
Code: "Conflict",
Message: "Bucket not empty.",
BucketName: bucketName,
RequestID: resp.Header.Get("x-amz-request-id"),
HostID: resp.Header.Get("x-amz-id-2"),
Region: resp.Header.Get("x-amz-bucket-region"),
}
default:
errResp = ErrorResponse{
Code: resp.Status,
Message: resp.Status,
BucketName: bucketName,
RequestID: resp.Header.Get("x-amz-request-id"),
HostID: resp.Header.Get("x-amz-id-2"),
Region: resp.Header.Get("x-amz-bucket-region"),
}
}
}
// Save hodID, requestID and region information
// from headers if not available through error XML.
if errResp.RequestID == "" {
errResp.RequestID = resp.Header.Get("x-amz-request-id")
}
if errResp.HostID == "" {
errResp.HostID = resp.Header.Get("x-amz-id-2")
}
if errResp.Region == "" {
errResp.Region = resp.Header.Get("x-amz-bucket-region")
}
// Save headers returned in the API XML error
errResp.Headers = resp.Header
return errResp
}
+7 -2
View File
@@ -24,10 +24,12 @@ import (
"strings"
"sync"
"time"
"github.com/minio/minio-go/pkg/encrypt"
)
// GetEncryptedObject deciphers and streams data stored in the server after applying a specifed encryption materiels
func (c Client) GetEncryptedObject(bucketName, objectName string, encryptMaterials EncryptionMaterials) (io.Reader, error) {
func (c Client) GetEncryptedObject(bucketName, objectName string, encryptMaterials encrypt.Materials) (io.Reader, error) {
if encryptMaterials == nil {
return nil, ErrInvalidArgument("Unable to recognize empty encryption properties")
@@ -44,8 +46,11 @@ func (c Client) GetEncryptedObject(bucketName, objectName string, encryptMateria
return nil, err
}
encryptMaterials.SetupDecryptMode(encReader, st.Metadata)
// Setup object for decrytion, object is transparently
// decrypted as the consumer starts reading.
encryptMaterials.SetupDecryptMode(encReader, st.Metadata.Get(amzHeaderIV), st.Metadata.Get(amzHeaderKey))
// Success.
return encryptMaterials, nil
}
+20 -10
View File
@@ -34,8 +34,12 @@ func (c Client) GetBucketPolicy(bucketName, objectPrefix string) (bucketPolicy p
if err := isValidObjectPrefix(objectPrefix); err != nil {
return policy.BucketPolicyNone, err
}
policyInfo, err := c.getBucketPolicy(bucketName, objectPrefix)
policyInfo, err := c.getBucketPolicy(bucketName)
if err != nil {
errResponse := ToErrorResponse(err)
if errResponse.Code == "NoSuchBucketPolicy" {
return policy.BucketPolicyNone, nil
}
return policy.BucketPolicyNone, err
}
return policy.GetPolicy(policyInfo.Statements, bucketName, objectPrefix), nil
@@ -50,15 +54,24 @@ func (c Client) ListBucketPolicies(bucketName, objectPrefix string) (bucketPolic
if err := isValidObjectPrefix(objectPrefix); err != nil {
return map[string]policy.BucketPolicy{}, err
}
policyInfo, err := c.getBucketPolicy(bucketName, objectPrefix)
policyInfo, err := c.getBucketPolicy(bucketName)
if err != nil {
errResponse := ToErrorResponse(err)
if errResponse.Code == "NoSuchBucketPolicy" {
return map[string]policy.BucketPolicy{}, nil
}
return map[string]policy.BucketPolicy{}, err
}
return policy.GetPolicies(policyInfo.Statements, bucketName), nil
}
// Default empty bucket access policy.
var emptyBucketAccessPolicy = policy.BucketAccessPolicy{
Version: "2012-10-17",
}
// Request server for current bucket policy.
func (c Client) getBucketPolicy(bucketName string, objectPrefix string) (policy.BucketAccessPolicy, error) {
func (c Client) getBucketPolicy(bucketName string) (policy.BucketAccessPolicy, error) {
// Get resources properly escaped and lined up before
// using them in http request.
urlValues := make(url.Values)
@@ -72,21 +85,18 @@ func (c Client) getBucketPolicy(bucketName string, objectPrefix string) (policy.
defer closeResponse(resp)
if err != nil {
return policy.BucketAccessPolicy{}, err
return emptyBucketAccessPolicy, err
}
if resp != nil {
if resp.StatusCode != http.StatusOK {
errResponse := httpRespToErrorResponse(resp, bucketName, "")
if ToErrorResponse(errResponse).Code == "NoSuchBucketPolicy" {
return policy.BucketAccessPolicy{Version: "2012-10-17"}, nil
}
return policy.BucketAccessPolicy{}, errResponse
return emptyBucketAccessPolicy, httpRespToErrorResponse(resp, bucketName, "")
}
}
bucketPolicyBuf, err := ioutil.ReadAll(resp.Body)
if err != nil {
return policy.BucketAccessPolicy{}, err
return emptyBucketAccessPolicy, err
}
policy := policy.BucketAccessPolicy{}
+6 -6
View File
@@ -168,14 +168,14 @@ func (c Client) ListObjectsV2(bucketName, objectPrefix string, recursive bool, d
// ?delimiter - A delimiter is a character you use to group keys.
// ?prefix - Limits the response to keys that begin with the specified prefix.
// ?max-keys - Sets the maximum number of keys returned in the response body.
func (c Client) listObjectsV2Query(bucketName, objectPrefix, continuationToken string, fetchOwner bool, delimiter string, maxkeys int) (listBucketV2Result, error) {
func (c Client) listObjectsV2Query(bucketName, objectPrefix, continuationToken string, fetchOwner bool, delimiter string, maxkeys int) (ListBucketV2Result, error) {
// Validate bucket name.
if err := isValidBucketName(bucketName); err != nil {
return listBucketV2Result{}, err
return ListBucketV2Result{}, err
}
// Validate object prefix.
if err := isValidObjectPrefix(objectPrefix); err != nil {
return listBucketV2Result{}, err
return ListBucketV2Result{}, err
}
// Get resources properly escaped and lined up before
// using them in http request.
@@ -216,16 +216,16 @@ func (c Client) listObjectsV2Query(bucketName, objectPrefix, continuationToken s
})
defer closeResponse(resp)
if err != nil {
return listBucketV2Result{}, err
return ListBucketV2Result{}, err
}
if resp != nil {
if resp.StatusCode != http.StatusOK {
return listBucketV2Result{}, httpRespToErrorResponse(resp, bucketName, "")
return ListBucketV2Result{}, httpRespToErrorResponse(resp, bucketName, "")
}
}
// Decode listBuckets XML.
listBucketResult := listBucketV2Result{}
listBucketResult := ListBucketV2Result{}
err = xmlDecoder(resp.Body, &listBucketResult)
if err != nil {
return listBucketResult, err
+9
View File
@@ -102,6 +102,14 @@ type eventMeta struct {
Object objectMeta `json:"object"`
}
// sourceInfo represents information on the client that
// triggered the event notification.
type sourceInfo struct {
Host string `json:"host"`
Port string `json:"port"`
UserAgent string `json:"userAgent"`
}
// NotificationEvent represents an Amazon an S3 bucket notification event.
type NotificationEvent struct {
EventVersion string `json:"eventVersion"`
@@ -113,6 +121,7 @@ type NotificationEvent struct {
RequestParameters map[string]string `json:"requestParameters"`
ResponseElements map[string]string `json:"responseElements"`
S3 eventMeta `json:"s3"`
Source sourceInfo `json:"source"`
}
// NotificationInfo - represents the collection of notification events, additionally
+65 -29
View File
@@ -41,7 +41,14 @@ import (
//
// For Amazon S3 for more supported regions - http://docs.aws.amazon.com/general/latest/gr/rande.html
// For Google Cloud Storage for more supported regions - https://cloud.google.com/storage/docs/bucket-locations
func (c Client) MakeBucket(bucketName string, location string) error {
func (c Client) MakeBucket(bucketName string, location string) (err error) {
defer func() {
// Save the location into cache on a successful makeBucket response.
if err == nil {
c.bucketLocCache.Set(bucketName, location)
}
}()
// Validate the input arguments.
if err := isValidBucketName(bucketName); err != nil {
return err
@@ -52,45 +59,70 @@ func (c Client) MakeBucket(bucketName string, location string) error {
location = "us-east-1"
}
// Instantiate the request.
req, err := c.makeBucketRequest(bucketName, location)
if err != nil {
return err
}
// Try creating bucket with the provided region, in case of
// invalid region error let's guess the appropriate region
// from S3 API headers
// Execute the request.
resp, err := c.do(req)
defer closeResponse(resp)
if err != nil {
return err
}
// Create a done channel to control 'newRetryTimer' go routine.
doneCh := make(chan struct{}, 1)
if resp != nil {
if resp.StatusCode != http.StatusOK {
return httpRespToErrorResponse(resp, bucketName, "")
// Indicate to our routine to exit cleanly upon return.
defer close(doneCh)
// Blank indentifier is kept here on purpose since 'range' without
// blank identifiers is only supported since go1.4
// https://golang.org/doc/go1.4#forrange.
for _ = range c.newRetryTimer(MaxRetry, DefaultRetryUnit, DefaultRetryCap, MaxJitter, doneCh) {
// Initialize the makeBucket request.
req, err := c.makeBucketRequest(bucketName, location)
if err != nil {
return err
}
// Execute make bucket request.
resp, err := c.do(req)
defer closeResponse(resp)
if err != nil {
return err
}
if resp.StatusCode != http.StatusOK {
err := httpRespToErrorResponse(resp, bucketName, "")
errResp := ToErrorResponse(err)
if errResp.Code == "InvalidRegion" && errResp.Region != "" {
// Fetch bucket region found in headers
// of S3 error response, attempt bucket
// create again.
location = errResp.Region
continue
}
// Nothing to retry, fail.
return err
}
// Control reaches here when bucket create was successful,
// break out.
break
}
// Save the location into cache on a successful makeBucket response.
c.bucketLocCache.Set(bucketName, location)
// Return.
// Success.
return nil
}
// makeBucketRequest constructs request for makeBucket.
// Low level wrapper API For makeBucketRequest.
func (c Client) makeBucketRequest(bucketName string, location string) (*http.Request, error) {
// Validate input arguments.
if err := isValidBucketName(bucketName); err != nil {
return nil, err
}
// In case of Amazon S3. The make bucket issued on already
// existing bucket would fail with 'AuthorizationMalformed' error
// if virtual style is used. So we default to 'path style' as that
// is the preferred method here. The final location of the
// 'bucket' is provided through XML LocationConstraint data with
// the request.
// In case of Amazon S3. The make bucket issued on
// already existing bucket would fail with
// 'AuthorizationMalformed' error if virtual style is
// used. So we default to 'path style' as that is the
// preferred method here. The final location of the
// 'bucket' is provided through XML LocationConstraint
// data with the request.
targetURL := c.endpointURL
targetURL.Path = path.Join(bucketName, "") + "/"
@@ -103,7 +135,8 @@ func (c Client) makeBucketRequest(bucketName string, location string) (*http.Req
// set UserAgent for the request.
c.setUserAgent(req)
// set sha256 sum for signature calculation only with signature version '4'.
// set sha256 sum for signature calculation only with
// signature version '4'.
if c.signature.isV4() {
req.Header.Set("X-Amz-Content-Sha256", hex.EncodeToString(sum256([]byte{})))
}
@@ -157,11 +190,14 @@ func (c Client) SetBucketPolicy(bucketName string, objectPrefix string, bucketPo
if err := isValidObjectPrefix(objectPrefix); err != nil {
return err
}
if !bucketPolicy.IsValidBucketPolicy() {
return ErrInvalidArgument(fmt.Sprintf("Invalid bucket policy provided. %s", bucketPolicy))
}
policyInfo, err := c.getBucketPolicy(bucketName, objectPrefix)
if err != nil {
policyInfo, err := c.getBucketPolicy(bucketName)
errResponse := ToErrorResponse(err)
if err != nil && errResponse.Code != "NoSuchBucketPolicy" {
return err
}
+2 -16
View File
@@ -91,25 +91,11 @@ func (c Client) FPutObject(bucketName, objectName, filePath, contentType string)
return c.putObjectNoChecksum(bucketName, objectName, fileReader, fileSize, objMetadata, nil)
}
// NOTE: S3 doesn't allow anonymous multipart requests.
if s3utils.IsAmazonEndpoint(c.endpointURL) && c.anonymous {
if fileSize > int64(maxSinglePutObjectSize) {
return 0, ErrorResponse{
Code: "NotImplemented",
Message: fmt.Sprintf("For anonymous requests Content-Length cannot be %d.", fileSize),
Key: objectName,
BucketName: bucketName,
}
}
// Do not compute MD5 for anonymous requests to Amazon
// S3. Uploads up to 5GiB in size.
return c.putObjectNoChecksum(bucketName, objectName, fileReader, fileSize, objMetadata, nil)
}
// Small object upload is initiated for uploads for input data size smaller than 5MiB.
if fileSize < minPartSize && fileSize >= 0 {
return c.putObjectSingle(bucketName, objectName, fileReader, fileSize, objMetadata, nil)
}
// Upload all large objects as multipart.
n, err = c.putObjectMultipartFromFile(bucketName, objectName, fileReader, fileSize, objMetadata, nil)
if err != nil {
@@ -187,7 +173,7 @@ func (c Client) putObjectMultipartFromFile(bucketName, objectName string, fileRe
close(uploadPartsCh)
// Use three 'workers' to upload parts in parallel.
for w := 1; w <= 3; w++ {
for w := 1; w <= totalWorkers; w++ {
go func() {
// Deal with each part as it comes through the channel.
for uploadReq := range uploadPartsCh {
+106
View File
@@ -66,6 +66,112 @@ func (c Client) putObjectMultipart(bucketName, objectName string, reader io.Read
return c.putObjectMultipartStream(bucketName, objectName, reader, size, metaData, progress)
}
// putObjectMultipartStreamNoChecksum - upload a large object using
// multipart upload and streaming signature for signing payload.
// N B We don't resume an incomplete multipart upload, we overwrite
// existing parts of an incomplete upload.
func (c Client) putObjectMultipartStreamNoChecksum(bucketName, objectName string,
reader io.Reader, size int64, metadata map[string][]string, progress io.Reader) (int64, error) {
// Input validation.
if err := isValidBucketName(bucketName); err != nil {
return 0, err
}
if err := isValidObjectName(objectName); err != nil {
return 0, err
}
// Get the upload id of a previously partially uploaded object or initiate a new multipart upload
uploadID, err := c.findUploadID(bucketName, objectName)
if err != nil {
return 0, err
}
if uploadID == "" {
// Initiates a new multipart request
uploadID, err = c.newUploadID(bucketName, objectName, metadata)
if err != nil {
return 0, err
}
}
// Calculate the optimal parts info for a given size.
totalPartsCount, partSize, lastPartSize, err := optimalPartInfo(size)
if err != nil {
return 0, err
}
// Total data read and written to server. should be equal to 'size' at the end of the call.
var totalUploadedSize int64
// Initialize parts uploaded map.
partsInfo := make(map[int]ObjectPart)
// Part number always starts with '1'.
var partNumber int
for partNumber = 1; partNumber <= totalPartsCount; partNumber++ {
// Update progress reader appropriately to the latest offset
// as we read from the source.
hookReader := newHook(reader, progress)
// Proceed to upload the part.
if partNumber == totalPartsCount {
partSize = lastPartSize
}
var objPart ObjectPart
objPart, err = c.uploadPart(bucketName, objectName, uploadID,
io.LimitReader(hookReader, partSize), partNumber, nil, nil, partSize)
// For unknown size, Read EOF we break away.
// We do not have to upload till totalPartsCount.
if err == io.EOF && size < 0 {
break
}
if err != nil {
return totalUploadedSize, err
}
// Save successfully uploaded part metadata.
partsInfo[partNumber] = objPart
// Save successfully uploaded size.
totalUploadedSize += partSize
}
// Verify if we uploaded all the data.
if size > 0 {
if totalUploadedSize != size {
return totalUploadedSize, ErrUnexpectedEOF(totalUploadedSize, size, bucketName, objectName)
}
}
// Complete multipart upload.
var complMultipartUpload completeMultipartUpload
// Loop over total uploaded parts to save them in
// Parts array before completing the multipart request.
for i := 1; i < partNumber; i++ {
part, ok := partsInfo[i]
if !ok {
return 0, ErrInvalidArgument(fmt.Sprintf("Missing part number %d", i))
}
complMultipartUpload.Parts = append(complMultipartUpload.Parts, CompletePart{
ETag: part.ETag,
PartNumber: part.PartNumber,
})
}
// Sort all completed parts.
sort.Sort(completedParts(complMultipartUpload.Parts))
_, err = c.completeMultipartUpload(bucketName, objectName, uploadID, complMultipartUpload)
if err != nil {
return totalUploadedSize, err
}
// Return final size.
return totalUploadedSize, nil
}
// putObjectStream uploads files bigger than 64MiB, and also supports
// special case where size is unknown i.e '-1'.
func (c Client) putObjectMultipartStream(bucketName, objectName string, reader io.Reader, size int64, metaData map[string][]string, progress io.Reader) (n int64, err error) {
+85 -22
View File
@@ -20,6 +20,7 @@ import (
"io"
"strings"
"github.com/minio/minio-go/pkg/encrypt"
"github.com/minio/minio-go/pkg/s3utils"
)
@@ -31,7 +32,7 @@ func (c Client) PutObjectWithProgress(bucketName, objectName string, reader io.R
}
// PutEncryptedObject - Encrypt and store object.
func (c Client) PutEncryptedObject(bucketName, objectName string, reader io.Reader, encryptMaterials EncryptionMaterials, metaData map[string][]string, progress io.Reader) (n int64, err error) {
func (c Client) PutEncryptedObject(bucketName, objectName string, reader io.Reader, encryptMaterials encrypt.Materials, metaData map[string][]string, progress io.Reader) (n int64, err error) {
if encryptMaterials == nil {
return 0, ErrInvalidArgument("Unable to recognize empty encryption properties")
@@ -44,9 +45,11 @@ func (c Client) PutEncryptedObject(bucketName, objectName string, reader io.Read
if metaData == nil {
metaData = make(map[string][]string)
}
for k, v := range encryptMaterials.GetHeaders() {
metaData[k] = v
}
// Set the necessary encryption headers, for future decryption.
metaData[amzHeaderIV] = []string{encryptMaterials.GetIV()}
metaData[amzHeaderKey] = []string{encryptMaterials.GetKey()}
metaData[amzHeaderMatDesc] = []string{encryptMaterials.GetDesc()}
return c.PutObjectWithMetadata(bucketName, objectName, encryptMaterials, metaData, progress)
}
@@ -96,24 +99,6 @@ func (c Client) PutObjectWithMetadata(bucketName, objectName string, reader io.R
return c.putObjectNoChecksum(bucketName, objectName, reader, size, metaData, progress)
}
// NOTE: S3 doesn't allow anonymous multipart requests.
if s3utils.IsAmazonEndpoint(c.endpointURL) && c.anonymous {
if size <= -1 {
return 0, ErrorResponse{
Code: "NotImplemented",
Message: "Content-Length cannot be negative for anonymous requests.",
Key: objectName,
BucketName: bucketName,
}
}
if size > maxSinglePutObjectSize {
return 0, ErrEntityTooLarge(size, maxSinglePutObjectSize, bucketName, objectName)
}
// Do not compute MD5 for anonymous requests to Amazon
// S3. Uploads up to 5GiB in size.
return c.putObjectNoChecksum(bucketName, objectName, reader, size, metaData, progress)
}
// putSmall object.
if size < minPartSize && size >= 0 {
return c.putObjectSingle(bucketName, objectName, reader, size, metaData, progress)
@@ -136,3 +121,81 @@ func (c Client) PutObjectWithMetadata(bucketName, objectName string, reader io.R
}
return n, nil
}
// PutObjectStreaming using AWS streaming signature V4
func (c Client) PutObjectStreaming(bucketName, objectName string, reader io.Reader) (n int64, err error) {
return c.PutObjectStreamingWithProgress(bucketName, objectName, reader, nil, nil)
}
// PutObjectStreamingWithMetadata using AWS streaming signature V4
func (c Client) PutObjectStreamingWithMetadata(bucketName, objectName string, reader io.Reader, metadata map[string][]string) (n int64, err error) {
return c.PutObjectStreamingWithProgress(bucketName, objectName, reader, metadata, nil)
}
// PutObjectStreamingWithProgress using AWS streaming signature V4
func (c Client) PutObjectStreamingWithProgress(bucketName, objectName string, reader io.Reader, metadata map[string][]string, progress io.Reader) (n int64, err error) {
// NOTE: Streaming signature is not supported by GCS.
if s3utils.IsGoogleEndpoint(c.endpointURL) {
return 0, ErrorResponse{
Code: "NotImplemented",
Message: "AWS streaming signature v4 is not supported with Google Cloud Storage",
Key: objectName,
BucketName: bucketName,
}
}
// This method should return error with signature v2 minioClient.
if c.signature.isV2() {
return 0, ErrorResponse{
Code: "NotImplemented",
Message: "AWS streaming signature v4 is not supported with minio client initialized for AWS signature v2",
Key: objectName,
BucketName: bucketName,
}
}
// Size of the object.
var size int64
// Get reader size.
size, err = getReaderSize(reader)
if err != nil {
return 0, err
}
// Check for largest object size allowed.
if size > int64(maxMultipartPutObjectSize) {
return 0, ErrEntityTooLarge(size, maxMultipartPutObjectSize, bucketName, objectName)
}
// If size cannot be found on a stream, it is not possible
// to upload using streaming signature, fall back to multipart.
if size < 0 {
return c.putObjectMultipartStream(bucketName, objectName, reader, size, metadata, progress)
}
// Set signature type to streaming signature v4.
c.signature = SignatureV4Streaming
if size < minPartSize && size >= 0 {
return c.putObjectNoChecksum(bucketName, objectName, reader, size, metadata, progress)
}
// For all sizes greater than 64MiB do multipart.
n, err = c.putObjectMultipartStreamNoChecksum(bucketName, objectName, reader, size, metadata, progress)
if err != nil {
errResp := ToErrorResponse(err)
// Verify if multipart functionality is not available, if not
// fall back to single PutObject operation.
if errResp.Code == "AccessDenied" && strings.Contains(errResp.Message, "Access Denied") {
// Verify if size of reader is greater than '5GiB'.
if size > maxSinglePutObjectSize {
return 0, ErrEntityTooLarge(size, maxSinglePutObjectSize, bucketName, objectName)
}
// Fall back to uploading as single PutObject operation.
return c.putObjectNoChecksum(bucketName, objectName, reader, size, metadata, progress)
}
return n, err
}
return n, nil
}
+1 -1
View File
@@ -115,7 +115,7 @@ func (c Client) putObjectMultipartFromReadAt(bucketName, objectName string, read
close(uploadPartsCh)
// Receive each part number from the channel allowing three parallel uploads.
for w := 1; w <= 3; w++ {
for w := 1; w <= totalWorkers; w++ {
go func() {
// Read defaults to reading at 5MiB buffer.
readAtBuffer := make([]byte, optimalReadBufferSize)
-1
View File
@@ -143,7 +143,6 @@ func (a completedParts) Less(i, j int) bool { return a[i].PartNumber < a[j].Part
// NOTE: Google Cloud Storage does not implement Amazon S3 Compatible multipart PUT.
// So we fall back to single PUT operation with the maximum limit of 5GiB.
//
// NOTE: For anonymous requests Amazon S3 doesn't allow multipart upload. So we fall back to single PUT operation.
func (c Client) PutObject(bucketName, objectName string, reader io.Reader, contentType string) (n int64, err error) {
return c.PutObjectWithProgress(bucketName, objectName, reader, contentType, nil)
}
-1
View File
@@ -208,7 +208,6 @@ func (c Client) RemoveObjects(bucketName string, objectsCh <-chan string) <-chan
}
// RemoveIncompleteUpload aborts an partially uploaded object.
// Requires explicit authentication, no anonymous requests are allowed for multipart API.
func (c Client) RemoveIncompleteUpload(bucketName, objectName string) error {
// Input validation.
if err := isValidBucketName(bucketName); err != nil {
+7 -7
View File
@@ -41,8 +41,8 @@ type commonPrefix struct {
Prefix string
}
// listBucketResult container for listObjects V2 response.
type listBucketV2Result struct {
// ListBucketV2Result container for listObjects response version 2.
type ListBucketV2Result struct {
// A response can contain CommonPrefixes only if you have
// specified a delimiter.
CommonPrefixes []commonPrefix
@@ -70,7 +70,7 @@ type listBucketV2Result struct {
StartAfter string
}
// listBucketResult container for listObjects response.
// ListBucketResult container for listObjects response.
type ListBucketResult struct {
// A response can contain CommonPrefixes only if you have
// specified a delimiter.
@@ -102,7 +102,7 @@ type ListBucketResult struct {
Prefix string
}
// listMultipartUploadsResult container for ListMultipartUploads response
// ListMultipartUploadsResult container for ListMultipartUploads response
type ListMultipartUploadsResult struct {
Bucket string
KeyMarker string
@@ -131,7 +131,7 @@ type copyObjectResult struct {
LastModified string // time string format "2006-01-02T15:04:05.000Z"
}
// objectPart container for particular part of an object.
// ObjectPart container for particular part of an object.
type ObjectPart struct {
// Part number identifies the part.
PartNumber int
@@ -147,7 +147,7 @@ type ObjectPart struct {
Size int64
}
// listObjectPartsResult container for ListObjectParts response.
// ListObjectPartsResult container for ListObjectParts response.
type ListObjectPartsResult struct {
Bucket string
Key string
@@ -185,7 +185,7 @@ type completeMultipartUploadResult struct {
ETag string
}
// completePart sub container lists individual part numbers and their
// CompletePart sub container lists individual part numbers and their
// md5sum, part of completeMultipartUpload.
type CompletePart struct {
XMLName xml.Name `xml:"http://s3.amazonaws.com/doc/2006-03-01/ Part" json:"-"`
+48 -50
View File
@@ -20,6 +20,7 @@ import (
"bytes"
"encoding/base64"
"encoding/hex"
"errors"
"fmt"
"io"
"io/ioutil"
@@ -198,9 +199,6 @@ func privateNew(endpoint, accessKeyID, secretAccessKey string, secure bool) (*Cl
clnt := new(Client)
clnt.accessKeyID = accessKeyID
clnt.secretAccessKey = secretAccessKey
if clnt.accessKeyID == "" || clnt.secretAccessKey == "" {
clnt.anonymous = true
}
// Remember whether we are using https or not
clnt.secure = secure
@@ -316,8 +314,7 @@ var regSign = regexp.MustCompile("Signature=([[0-9a-f]+)")
// Filter out signature value from Authorization header.
func (c Client) filterSignature(req *http.Request) {
// For anonymous requests, no need to filter.
if c.anonymous {
if _, ok := req.Header["Authorization"]; !ok {
return
}
// Handle if Signature V2.
@@ -428,7 +425,7 @@ func (c Client) do(req *http.Request) (*http.Response, error) {
return nil, &url.Error{
Op: urlErr.Op,
URL: urlErr.URL,
Err: fmt.Errorf("Connection closed by foreign host %s. Retry again.", urlErr.URL),
Err: errors.New("Connection closed by foreign host " + urlErr.URL + ". Retry again."),
}
}
return nil, err
@@ -477,9 +474,13 @@ func (c Client) executeMethod(method string, metadata requestMetadata) (res *htt
if metadata.contentBody != nil {
// Check if body is seekable then it is retryable.
bodySeeker, isRetryable = metadata.contentBody.(io.Seeker)
switch bodySeeker {
case os.Stdin, os.Stdout, os.Stderr:
isRetryable = false
}
}
// Create a done channel to control 'ListObjects' go routine.
// Create a done channel to control 'newRetryTimer' go routine.
doneCh := make(chan struct{}, 1)
// Indicate to our routine to exit cleanly upon return.
@@ -488,7 +489,7 @@ func (c Client) executeMethod(method string, metadata requestMetadata) (res *htt
// Blank indentifier is kept here on purpose since 'range' without
// blank identifiers is only supported since go1.4
// https://golang.org/doc/go1.4#forrange.
for _ = range c.newRetryTimer(MaxRetry, time.Second, time.Second*30, MaxJitter, doneCh) {
for _ = range c.newRetryTimer(MaxRetry, DefaultRetryUnit, DefaultRetryCap, MaxJitter, doneCh) {
// Retry executes the following function body if request has an
// error until maxRetries have been exhausted, retry attempts are
// performed after waiting for a given period of time in a
@@ -537,15 +538,22 @@ func (c Client) executeMethod(method string, metadata requestMetadata) (res *htt
if err != nil {
return nil, err
}
// Save the body.
errBodySeeker := bytes.NewReader(errBodyBytes)
res.Body = ioutil.NopCloser(errBodySeeker)
// For errors verify if its retryable otherwise fail quickly.
errResponse := ToErrorResponse(httpRespToErrorResponse(res, metadata.bucketName, metadata.objectName))
// Bucket region if set in error response, we can retry the
// request with the new region.
if errResponse.Region != "" {
// Save the body back again.
errBodySeeker.Seek(0, 0) // Seek back to starting point.
res.Body = ioutil.NopCloser(errBodySeeker)
// Bucket region if set in error response and the error
// code dictates invalid region, we can retry the request
// with the new region.
if errResponse.Code == "InvalidRegion" && errResponse.Region != "" {
c.bucketLocCache.Set(metadata.bucketName, errResponse.Region)
continue // Retry.
}
@@ -560,10 +568,6 @@ func (c Client) executeMethod(method string, metadata requestMetadata) (res *htt
continue // Retry.
}
// Save the body back again.
errBodySeeker.Seek(0, 0) // Seek back to starting point.
res.Body = ioutil.NopCloser(errBodySeeker)
// For all other cases break out of the retry loop.
break
}
@@ -610,29 +614,24 @@ func (c Client) newRequest(method string, metadata requestMetadata) (req *http.R
return nil, err
}
// Anonymous request.
anonymous := c.accessKeyID == "" || c.secretAccessKey == ""
// Generate presign url if needed, return right here.
if metadata.expires != 0 && metadata.presignURL {
if c.anonymous {
if anonymous {
return nil, ErrInvalidArgument("Requests cannot be presigned with anonymous credentials.")
}
if c.signature.isV2() {
// Presign URL with signature v2.
req = s3signer.PreSignV2(*req, c.accessKeyID, c.secretAccessKey, metadata.expires)
} else {
} else if c.signature.isV4() {
// Presign URL with signature v4.
req = s3signer.PreSignV4(*req, c.accessKeyID, c.secretAccessKey, location, metadata.expires)
}
return req, nil
}
// FIXME: Enable this when Google Cloud Storage properly supports 100-continue.
// Skip setting 'expect' header for Google Cloud Storage, there
// are some known issues - https://github.com/restic/restic/issues/520
if !s3utils.IsGoogleEndpoint(c.endpointURL) && c.s3AccelerateEndpoint == "" {
// Set 'Expect' header for the request.
req.Header.Set("Expect", "100-continue")
}
// Set 'User-Agent' header for the request.
c.setUserAgent(req)
@@ -646,37 +645,36 @@ func (c Client) newRequest(method string, metadata requestMetadata) (req *http.R
req.ContentLength = metadata.contentLength
}
// Set sha256 sum only for non anonymous credentials.
if !c.anonymous {
// set sha256 sum for signature calculation only with
// signature version '4'.
if c.signature.isV4() {
shaHeader := unsignedPayload
if !c.secure {
if metadata.contentSHA256Bytes == nil {
shaHeader = hex.EncodeToString(sum256([]byte{}))
} else {
shaHeader = hex.EncodeToString(metadata.contentSHA256Bytes)
}
}
req.Header.Set("X-Amz-Content-Sha256", shaHeader)
}
}
// set md5Sum for content protection.
if metadata.contentMD5Bytes != nil {
req.Header.Set("Content-Md5", base64.StdEncoding.EncodeToString(metadata.contentMD5Bytes))
}
// Sign the request for all authenticated requests.
if !c.anonymous {
if c.signature.isV2() {
// Add signature version '2' authorization header.
req = s3signer.SignV2(*req, c.accessKeyID, c.secretAccessKey)
} else if c.signature.isV4() {
// Add signature version '4' authorization header.
req = s3signer.SignV4(*req, c.accessKeyID, c.secretAccessKey, location)
if anonymous {
return req, nil
} // Sign the request for all authenticated requests.
if c.signature.isV2() {
// Add signature version '2' authorization header.
req = s3signer.SignV2(*req, c.accessKeyID, c.secretAccessKey)
} else if c.signature.isV4() || c.signature.isStreamingV4() &&
method != "PUT" {
// Set sha256 sum for signature calculation only with signature version '4'.
shaHeader := unsignedPayload
if !c.secure {
if metadata.contentSHA256Bytes == nil {
shaHeader = hex.EncodeToString(sum256([]byte{}))
} else {
shaHeader = hex.EncodeToString(metadata.contentSHA256Bytes)
}
}
req.Header.Set("X-Amz-Content-Sha256", shaHeader)
// Add signature version '4' authorization header.
req = s3signer.SignV4(*req, c.accessKeyID, c.secretAccessKey, location)
} else if c.signature.isStreamingV4() {
req = s3signer.StreamingSignV4(req, c.accessKeyID,
c.secretAccessKey, location, metadata.contentLength, time.Now().UTC())
}
// Return request.
+10
View File
@@ -45,8 +45,18 @@ const optimalReadBufferSize = 1024 * 1024 * 5
// we don't want to sign the request payload
const unsignedPayload = "UNSIGNED-PAYLOAD"
// Total number of parallel workers used for multipart operation.
var totalWorkers = 3
// Signature related constants.
const (
signV4Algorithm = "AWS4-HMAC-SHA256"
iso8601DateFormat = "20060102T150405Z"
)
// Encryption headers stored along with the object.
const (
amzHeaderIV = "X-Amz-Meta-X-Amz-Iv"
amzHeaderKey = "X-Amz-Meta-X-Amz-Key"
amzHeaderMatDesc = "X-Amz-Meta-X-Amz-Matdesc"
)
+32 -40
View File
@@ -16,15 +16,20 @@
package minio
import "io"
import "encoding/hex"
import (
"io"
// Inherits Client and adds new methods to expose the low level S3 APIs.
"github.com/minio/minio-go/pkg/policy"
)
// Core - Inherits Client and adds new methods to expose the low level S3 APIs.
type Core struct {
*Client
}
// NewCoreClient - Returns new Core.
// NewCore - Returns new initialized a Core client, this CoreClient should be
// only used under special conditions such as need to access lower primitives
// and being able to use them to write your own wrappers.
func NewCore(endpoint string, accessKeyID, secretAccessKey string, secure bool) (*Core, error) {
var s3Client Core
client, err := NewV4(endpoint, accessKeyID, secretAccessKey, secure)
@@ -35,29 +40,21 @@ func NewCore(endpoint string, accessKeyID, secretAccessKey string, secure bool)
return &s3Client, nil
}
// ListObjects - List the objects.
// ListObjects - List all the objects at a prefix, optionally with marker and delimiter
// you can further filter the results.
func (c Core) ListObjects(bucket, prefix, marker, delimiter string, maxKeys int) (result ListBucketResult, err error) {
return c.listObjectsQuery(bucket, prefix, marker, delimiter, maxKeys)
}
// ListObjectsV2 - Lists all the objects at a prefix, similar to ListObjects() but uses
// continuationToken instead of marker to further filter the results.
func (c Core) ListObjectsV2(bucketName, objectPrefix, continuationToken string, fetchOwner bool, delimiter string, maxkeys int) (ListBucketV2Result, error) {
return c.listObjectsV2Query(bucketName, objectPrefix, continuationToken, fetchOwner, delimiter, maxkeys)
}
// PutObject - Upload object. Uploads using single PUT call.
func (c Core) PutObject(bucket, object string, size int64, data io.Reader, md5Sum string, sha256Sum string, metadata map[string][]string) (ObjectInfo, error) {
var md5SumBytes []byte
var sha256SumBytes []byte
var err error
if md5Sum != "" {
md5SumBytes, err = hex.DecodeString(md5Sum)
if err != nil {
return ObjectInfo{}, err
}
}
if sha256Sum != "" {
sha256SumBytes, err = hex.DecodeString(sha256Sum)
if err != nil {
return ObjectInfo{}, err
}
}
return c.putObjectDo(bucket, object, data, md5SumBytes, sha256SumBytes, size, metadata)
func (c Core) PutObject(bucket, object string, size int64, data io.Reader, md5Sum, sha256Sum []byte, metadata map[string][]string) (ObjectInfo, error) {
return c.putObjectDo(bucket, object, data, md5Sum, sha256Sum, size, metadata)
}
// NewMultipartUpload - Initiates new multipart upload and returns the new uploaID.
@@ -72,26 +69,11 @@ func (c Core) ListMultipartUploads(bucket, prefix, keyMarker, uploadIDMarker, de
}
// PutObjectPart - Upload an object part.
func (c Core) PutObjectPart(bucket, object, uploadID string, partID int, size int64, data io.Reader, md5Sum, sha256Sum string) (ObjectPart, error) {
var md5SumBytes []byte
var sha256SumBytes []byte
var err error
if md5Sum != "" {
md5SumBytes, err = hex.DecodeString(md5Sum)
if err != nil {
return ObjectPart{}, err
}
}
if sha256Sum != "" {
sha256SumBytes, err = hex.DecodeString(sha256Sum)
if err != nil {
return ObjectPart{}, err
}
}
return c.uploadPart(bucket, object, uploadID, data, partID, md5SumBytes, sha256SumBytes, size)
func (c Core) PutObjectPart(bucket, object, uploadID string, partID int, size int64, data io.Reader, md5Sum, sha256Sum []byte) (ObjectPart, error) {
return c.uploadPart(bucket, object, uploadID, data, partID, md5Sum, sha256Sum, size)
}
// ListObjectParts - List uploaded parts of an incomplete upload.
// ListObjectParts - List uploaded parts of an incomplete upload.x
func (c Core) ListObjectParts(bucket, object, uploadID string, partNumberMarker int, maxParts int) (result ListObjectPartsResult, err error) {
return c.listObjectPartsQuery(bucket, object, uploadID, partNumberMarker, maxParts)
}
@@ -106,3 +88,13 @@ func (c Core) CompleteMultipartUpload(bucket, object, uploadID string, parts []C
func (c Core) AbortMultipartUpload(bucket, object, uploadID string) error {
return c.abortMultipartUpload(bucket, object, uploadID)
}
// GetBucketPolicy - fetches bucket access policy for a given bucket.
func (c Core) GetBucketPolicy(bucket string) (policy.BucketAccessPolicy, error) {
return c.getBucketPolicy(bucket)
}
// PutBucketPolicy - applies a new bucket access policy for a given bucket.
func (c Core) PutBucketPolicy(bucket string, bucketPolicy policy.BucketAccessPolicy) error {
return c.putBucketPolicy(bucket, bucketPolicy)
}
@@ -14,7 +14,7 @@
* limitations under the License.
*/
package minio
package encrypt
import (
"bytes"
@@ -24,13 +24,6 @@ import (
"encoding/base64"
"errors"
"io"
"net/http"
)
const (
amzHeaderIV = "X-Amz-Meta-X-Amz-Iv"
amzHeaderKey = "X-Amz-Meta-X-Amz-Key"
amzHeaderMatDesc = "X-Amz-Meta-X-Amz-Matdesc"
)
// Crypt mode - encryption or decryption
@@ -60,7 +53,7 @@ type CBCSecureMaterials struct {
dstBuf *bytes.Buffer
// Encryption algorithm
encryptionKey EncryptionKey
encryptionKey Key
// Key to encrypts/decrypts data
contentKey []byte
@@ -81,11 +74,11 @@ type CBCSecureMaterials struct {
blockMode cipher.BlockMode
}
// NewCBCSecureMaterials builds new CBC crypter module with the specified encryption key
// (symmetric or asymmetric)
func NewCBCSecureMaterials(key EncryptionKey) (*CBCSecureMaterials, error) {
// NewCBCSecureMaterials builds new CBC crypter module with
// the specified encryption key (symmetric or asymmetric)
func NewCBCSecureMaterials(key Key) (*CBCSecureMaterials, error) {
if key == nil {
return nil, ErrInvalidArgument("Unable to recognize empty encryption properties")
return nil, errors.New("Unable to recognize empty encryption properties")
}
return &CBCSecureMaterials{
srcBuf: bytes.NewBuffer([]byte{}),
@@ -96,14 +89,8 @@ func NewCBCSecureMaterials(key EncryptionKey) (*CBCSecureMaterials, error) {
}
// SetInputStream - set data which needs to be encrypted or decrypted
// func (s *CBCSecureMaterials) SetInputStream(stream io.Reader) {
// s.stream = stream
// }
// SetEncryptMode - tells CBC that we are going to encrypt data
// SetupEncryptMode - tells CBC that we are going to encrypt data
func (s *CBCSecureMaterials) SetupEncryptMode(stream io.Reader) error {
// Set mode to encrypt
s.cryptMode = encryptMode
@@ -143,8 +130,7 @@ func (s *CBCSecureMaterials) SetupEncryptMode(stream io.Reader) error {
}
// SetupDecryptMode - tells CBC that we are going to decrypt data
func (s *CBCSecureMaterials) SetupDecryptMode(stream io.Reader, metadata http.Header) error {
func (s *CBCSecureMaterials) SetupDecryptMode(stream io.Reader, iv string, key string) error {
// Set mode to decrypt
s.cryptMode = decryptMode
@@ -159,15 +145,17 @@ func (s *CBCSecureMaterials) SetupDecryptMode(stream io.Reader, metadata http.He
var err error
// Get IV
s.iv, err = base64.StdEncoding.DecodeString(metadata.Get(amzHeaderIV))
s.iv, err = base64.StdEncoding.DecodeString(iv)
if err != nil {
return err
}
// Get encrypted content key
s.cryptedKey, err = base64.StdEncoding.DecodeString(metadata.Get(amzHeaderKey))
s.cryptedKey, err = base64.StdEncoding.DecodeString(key)
if err != nil {
return err
}
// Decrypt content key
s.contentKey, err = s.encryptionKey.Decrypt(s.cryptedKey)
if err != nil {
@@ -184,17 +172,19 @@ func (s *CBCSecureMaterials) SetupDecryptMode(stream io.Reader, metadata http.He
return nil
}
// GetHeaders - returns headers data to be sent along with data to the S3 server
// it contains encryption information needed to decrypt later
func (s *CBCSecureMaterials) GetHeaders() http.Header {
// GetIV - return randomly generated IV (per S3 object), base64 encoded.
func (s *CBCSecureMaterials) GetIV() string {
return base64.StdEncoding.EncodeToString(s.iv)
}
m := make(http.Header)
// GetKey - return content encrypting key (cek) in encrypted form, base64 encoded.
func (s *CBCSecureMaterials) GetKey() string {
return base64.StdEncoding.EncodeToString(s.cryptedKey)
}
m.Set(amzHeaderMatDesc, string(s.matDesc))
m.Set(amzHeaderIV, base64.StdEncoding.EncodeToString(s.iv))
m.Set(amzHeaderKey, base64.StdEncoding.EncodeToString(s.cryptedKey))
return m
// GetDesc - user provided encryption material description in JSON (UTF8) format.
func (s *CBCSecureMaterials) GetDesc() string {
return string(s.matDesc)
}
// Fill buf with encrypted/decrypted data
@@ -14,31 +14,37 @@
* limitations under the License.
*/
package minio
// Package encrypt implements a generic interface to encrypt any stream of data.
// currently this package implements two types of encryption
// - Symmetric encryption using AES.
// - Asymmetric encrytion using RSA.
package encrypt
import (
"io"
"net/http"
)
import "io"
// EncryptionMaterials - provides generic interface to encrypt
// any stream of data. Some crypt information can be
// save in the object metadata
type EncryptionMaterials interface {
// Materials - provides generic interface to encrypt any stream of data.
type Materials interface {
// Return encrypted/decrypted data.
// Returns encrypted/decrypted data, io.Reader compatible.
Read(b []byte) (int, error)
// Metadata that will be stored with the object
GetHeaders() http.Header
// Get randomly generated IV, base64 encoded.
GetIV() (iv string)
// Get content encrypting key (cek) in encrypted form, base64 encoded.
GetKey() (key string)
// Get user provided encryption material description in
// JSON (UTF8) format. This is not used, kept for future.
GetDesc() (desc string)
// Setup encrypt mode, further calls of Read() function
// will return the encrypted form of data streamed
// by the passed reader
SetupEncryptMode(io.Reader) error
SetupEncryptMode(stream io.Reader) error
// Setup decrypted mode, further calls of Read() function
// will return the decrypted form of data streamed
// by the passed reader
SetupDecryptMode(io.Reader, http.Header) error
SetupDecryptMode(stream io.Reader, iv string, key string) error
}
@@ -14,19 +14,20 @@
* limitations under the License.
*/
package minio
package encrypt
import (
"crypto/aes"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"errors"
)
// EncryptionKey - generic interface to encrypt/decrypt a key.
// Key - generic interface to encrypt/decrypt a key.
// We use it to encrypt/decrypt content key which is the key
// that encrypt/decrypt object data.
type EncryptionKey interface {
type Key interface {
// Encrypt data using to the set encryption key
Encrypt([]byte) ([]byte, error)
// Decrypt data using to the set encryption key
@@ -140,7 +141,7 @@ func NewAsymmetricKey(privData []byte, pubData []byte) (*AsymmetricKey, error) {
}
privKey, ok := priv.(*rsa.PrivateKey)
if !ok {
return nil, ErrInvalidArgument("not a valid private key")
return nil, errors.New("not a valid private key")
}
// Parse public key from passed data
@@ -151,7 +152,7 @@ func NewAsymmetricKey(privData []byte, pubData []byte) (*AsymmetricKey, error) {
pubKey, ok := pub.(*rsa.PublicKey)
if !ok {
return nil, ErrInvalidArgument("not a valid public key")
return nil, errors.New("not a valid public key")
}
// Associate the private key with the passed public key
+4 -5
View File
@@ -34,7 +34,7 @@ const (
BucketPolicyWriteOnly = "writeonly"
)
// isValidBucketPolicy - Is provided policy value supported.
// IsValidBucketPolicy - returns true if policy is valid and supported, false otherwise.
func (p BucketPolicy) IsValidBucketPolicy() bool {
switch p {
case BucketPolicyNone, BucketPolicyReadOnly, BucketPolicyReadWrite, BucketPolicyWriteOnly:
@@ -508,7 +508,7 @@ func getObjectPolicy(statement Statement) (readOnly bool, writeOnly bool) {
return readOnly, writeOnly
}
// Returns policy of given bucket name, prefix in given statements.
// GetPolicy - Returns policy of given bucket name, prefix in given statements.
func GetPolicy(statements []Statement, bucketName string, prefix string) BucketPolicy {
bucketResource := awsResourcePrefix + bucketName
objectResource := awsResourcePrefix + bucketName + "/" + prefix + "*"
@@ -563,7 +563,7 @@ func GetPolicy(statements []Statement, bucketName string, prefix string) BucketP
return policy
}
// GetPolicies returns a map of policies rules of given bucket name, prefix in given statements.
// GetPolicies - returns a map of policies rules of given bucket name, prefix in given statements.
func GetPolicies(statements []Statement, bucketName string) map[string]BucketPolicy {
policyRules := map[string]BucketPolicy{}
objResources := set.NewStringSet()
@@ -590,8 +590,7 @@ func GetPolicies(statements []Statement, bucketName string) map[string]BucketPol
return policyRules
}
// Returns new statements containing policy of given bucket name and
// prefix are appended.
// SetPolicy - Returns new statements containing policy of given bucket name and prefix are appended.
func SetPolicy(statements []Statement, policy BucketPolicy, bucketName string, prefix string) []Statement {
out := removeStatements(statements, bucketName, prefix)
// fmt.Println("out = ")
@@ -0,0 +1,285 @@
/*
* Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2017 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package s3signer
import (
"bytes"
"encoding/hex"
"fmt"
"io"
"net/http"
"strconv"
"strings"
"time"
)
// Reference for constants used below -
// http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-streaming.html#example-signature-calculations-streaming
const (
streamingSignAlgorithm = "STREAMING-AWS4-HMAC-SHA256-PAYLOAD"
streamingEncoding = "aws-chunked"
streamingPayloadHdr = "AWS4-HMAC-SHA256-PAYLOAD"
emptySHA256 = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
payloadChunkSize = 64 * 1024
chunkSigConstLen = 17 // ";chunk-signature="
signatureStrLen = 64 // e.g. "f2ca1bb6c7e907d06dafe4687e579fce76b37e4e93b7605022da52e6ccc26fd2"
crlfLen = 2 // CRLF
)
// Request headers to be ignored while calculating seed signature for
// a request.
var ignoredStreamingHeaders = map[string]bool{
"Authorization": true,
"User-Agent": true,
"Content-Type": true,
}
// getSignedChunkLength - calculates the length of chunk metadata
func getSignedChunkLength(chunkDataSize int64) int64 {
return int64(len(fmt.Sprintf("%x", chunkDataSize))) +
chunkSigConstLen +
signatureStrLen +
crlfLen +
chunkDataSize +
crlfLen
}
// getStreamLength - calculates the length of the overall stream (data + metadata)
func getStreamLength(dataLen, chunkSize int64) int64 {
if dataLen <= 0 {
return 0
}
chunksCount := int64(dataLen / chunkSize)
remainingBytes := int64(dataLen % chunkSize)
streamLen := int64(0)
streamLen += chunksCount * getSignedChunkLength(chunkSize)
if remainingBytes > 0 {
streamLen += getSignedChunkLength(remainingBytes)
}
streamLen += getSignedChunkLength(0)
return streamLen
}
// buildChunkStringToSign - returns the string to sign given chunk data
// and previous signature.
func buildChunkStringToSign(t time.Time, region, previousSig string, chunkData []byte) string {
stringToSignParts := []string{
streamingPayloadHdr,
t.Format(iso8601DateFormat),
getScope(region, t),
previousSig,
emptySHA256,
hex.EncodeToString(sum256(chunkData)),
}
return strings.Join(stringToSignParts, "\n")
}
// prepareStreamingRequest - prepares a request with appropriate
// headers before computing the seed signature.
func prepareStreamingRequest(req *http.Request, dataLen int64, timestamp time.Time) {
// Set x-amz-content-sha256 header.
req.Header.Set("X-Amz-Content-Sha256", streamingSignAlgorithm)
req.Header.Set("Content-Encoding", streamingEncoding)
req.Header.Set("X-Amz-Date", timestamp.Format(iso8601DateFormat))
// Set content length with streaming signature for each chunk included.
req.ContentLength = getStreamLength(dataLen, int64(payloadChunkSize))
req.Header.Set("x-amz-decoded-content-length", strconv.FormatInt(dataLen, 10))
}
// buildChunkHeader - returns the chunk header.
// e.g string(IntHexBase(chunk-size)) + ";chunk-signature=" + signature + \r\n + chunk-data + \r\n
func buildChunkHeader(chunkLen int64, signature string) []byte {
return []byte(strconv.FormatInt(chunkLen, 16) + ";chunk-signature=" + signature + "\r\n")
}
// buildChunkSignature - returns chunk signature for a given chunk and previous signature.
func buildChunkSignature(chunkData []byte, reqTime time.Time, region,
previousSignature, secretAccessKey string) string {
chunkStringToSign := buildChunkStringToSign(reqTime, region,
previousSignature, chunkData)
signingKey := getSigningKey(secretAccessKey, region, reqTime)
return getSignature(signingKey, chunkStringToSign)
}
// getSeedSignature - returns the seed signature for a given request.
func (s *StreamingReader) setSeedSignature(req *http.Request) {
// Get canonical request
canonicalRequest := getCanonicalRequest(*req, ignoredStreamingHeaders)
// Get string to sign from canonical request.
stringToSign := getStringToSignV4(s.reqTime, s.region, canonicalRequest)
signingKey := getSigningKey(s.secretAccessKey, s.region, s.reqTime)
// Calculate signature.
s.seedSignature = getSignature(signingKey, stringToSign)
}
// StreamingReader implements chunked upload signature as a reader on
// top of req.Body's ReaderCloser chunk header;data;... repeat
type StreamingReader struct {
accessKeyID string
secretAccessKey string
region string
prevSignature string
seedSignature string
contentLen int64 // Content-Length from req header
baseReadCloser io.ReadCloser // underlying io.Reader
bytesRead int64 // bytes read from underlying io.Reader
buf bytes.Buffer // holds signed chunk
chunkBuf []byte // holds raw data read from req Body
chunkBufLen int // no. of bytes read so far into chunkBuf
done bool // done reading the underlying reader to EOF
reqTime time.Time
chunkNum int
totalChunks int
lastChunkSize int
}
// signChunk - signs a chunk read from s.baseReader of chunkLen size.
func (s *StreamingReader) signChunk(chunkLen int) {
// Compute chunk signature for next header
signature := buildChunkSignature(s.chunkBuf[:chunkLen], s.reqTime,
s.region, s.prevSignature, s.secretAccessKey)
// For next chunk signature computation
s.prevSignature = signature
// Write chunk header into streaming buffer
chunkHdr := buildChunkHeader(int64(chunkLen), signature)
s.buf.Write(chunkHdr)
// Write chunk data into streaming buffer
s.buf.Write(s.chunkBuf[:chunkLen])
// Write the chunk trailer.
s.buf.Write([]byte("\r\n"))
// Reset chunkBufLen for next chunk read.
s.chunkBufLen = 0
s.chunkNum++
}
// setStreamingAuthHeader - builds and sets authorization header value
// for streaming signature.
func (s *StreamingReader) setStreamingAuthHeader(req *http.Request) {
credential := GetCredential(s.accessKeyID, s.region, s.reqTime)
authParts := []string{
signV4Algorithm + " Credential=" + credential,
"SignedHeaders=" + getSignedHeaders(*req, ignoredStreamingHeaders),
"Signature=" + s.seedSignature,
}
// Set authorization header.
auth := strings.Join(authParts, ",")
req.Header.Set("Authorization", auth)
}
// StreamingSignV4 - provides chunked upload signatureV4 support by
// implementing io.Reader.
func StreamingSignV4(req *http.Request, accessKeyID, secretAccessKey,
region string, dataLen int64, reqTime time.Time) *http.Request {
// Set headers needed for streaming signature.
prepareStreamingRequest(req, dataLen, reqTime)
stReader := &StreamingReader{
baseReadCloser: req.Body,
accessKeyID: accessKeyID,
secretAccessKey: secretAccessKey,
region: region,
reqTime: reqTime,
chunkBuf: make([]byte, payloadChunkSize),
contentLen: dataLen,
chunkNum: 1,
totalChunks: int((dataLen+payloadChunkSize-1)/payloadChunkSize) + 1,
lastChunkSize: int(dataLen % payloadChunkSize),
}
// Add the request headers required for chunk upload signing.
// Compute the seed signature.
stReader.setSeedSignature(req)
// Set the authorization header with the seed signature.
stReader.setStreamingAuthHeader(req)
// Set seed signature as prevSignature for subsequent
// streaming signing process.
stReader.prevSignature = stReader.seedSignature
req.Body = stReader
return req
}
// Read - this method performs chunk upload signature providing a
// io.Reader interface.
func (s *StreamingReader) Read(buf []byte) (int, error) {
switch {
// After the last chunk is read from underlying reader, we
// never re-fill s.buf.
case s.done:
// s.buf will be (re-)filled with next chunk when has lesser
// bytes than asked for.
case s.buf.Len() < len(buf):
s.chunkBufLen = 0
for {
n1, err := s.baseReadCloser.Read(s.chunkBuf[s.chunkBufLen:])
if err == nil || err == io.ErrUnexpectedEOF {
s.chunkBufLen += n1
s.bytesRead += int64(n1)
if s.chunkBufLen == payloadChunkSize ||
(s.chunkNum == s.totalChunks-1 &&
s.chunkBufLen == s.lastChunkSize) {
// Sign the chunk and write it to s.buf.
s.signChunk(s.chunkBufLen)
break
}
} else if err == io.EOF {
// No more data left in baseReader - last chunk.
// Done reading the last chunk from baseReader.
s.done = true
// bytes read from baseReader different than
// content length provided.
if s.bytesRead != s.contentLen {
return 0, io.ErrUnexpectedEOF
}
// Sign the chunk and write it to s.buf.
s.signChunk(0)
break
} else {
return 0, err
}
}
}
return s.buf.Read(buf)
}
// Close - this method makes underlying io.ReadCloser's Close method available.
func (s *StreamingReader) Close() error {
return s.baseReadCloser.Close()
}
+10 -10
View File
@@ -70,7 +70,7 @@ const (
///
/// Is skipped for obvious reasons
///
var ignoredHeaders = map[string]bool{
var v4IgnoredHeaders = map[string]bool{
"Authorization": true,
"Content-Type": true,
"Content-Length": true,
@@ -122,7 +122,7 @@ func getHashedPayload(req http.Request) string {
// getCanonicalHeaders generate a list of request headers for
// signature.
func getCanonicalHeaders(req http.Request) string {
func getCanonicalHeaders(req http.Request, ignoredHeaders map[string]bool) string {
var headers []string
vals := make(map[string][]string)
for k, vv := range req.Header {
@@ -161,7 +161,7 @@ func getCanonicalHeaders(req http.Request) string {
// getSignedHeaders generate all signed request headers.
// i.e lexically sorted, semicolon-separated list of lowercase
// request header names.
func getSignedHeaders(req http.Request) string {
func getSignedHeaders(req http.Request, ignoredHeaders map[string]bool) string {
var headers []string
for k := range req.Header {
if _, ok := ignoredHeaders[http.CanonicalHeaderKey(k)]; ok {
@@ -183,14 +183,14 @@ func getSignedHeaders(req http.Request) string {
// <CanonicalHeaders>\n
// <SignedHeaders>\n
// <HashedPayload>
func getCanonicalRequest(req http.Request) string {
func getCanonicalRequest(req http.Request, ignoredHeaders map[string]bool) string {
req.URL.RawQuery = strings.Replace(req.URL.Query().Encode(), "+", "%20", -1)
canonicalRequest := strings.Join([]string{
req.Method,
s3utils.EncodePath(req.URL.Path),
req.URL.RawQuery,
getCanonicalHeaders(req),
getSignedHeaders(req),
getCanonicalHeaders(req, ignoredHeaders),
getSignedHeaders(req, ignoredHeaders),
getHashedPayload(req),
}, "\n")
return canonicalRequest
@@ -219,7 +219,7 @@ func PreSignV4(req http.Request, accessKeyID, secretAccessKey, location string,
credential := GetCredential(accessKeyID, location, t)
// Get all signed headers.
signedHeaders := getSignedHeaders(req)
signedHeaders := getSignedHeaders(req, v4IgnoredHeaders)
// Set URL query.
query := req.URL.Query()
@@ -231,7 +231,7 @@ func PreSignV4(req http.Request, accessKeyID, secretAccessKey, location string,
req.URL.RawQuery = query.Encode()
// Get canonical request.
canonicalRequest := getCanonicalRequest(req)
canonicalRequest := getCanonicalRequest(req, v4IgnoredHeaders)
// Get string to sign from canonical request.
stringToSign := getStringToSignV4(t, location, canonicalRequest)
@@ -273,7 +273,7 @@ func SignV4(req http.Request, accessKeyID, secretAccessKey, location string) *ht
req.Header.Set("X-Amz-Date", t.Format(iso8601DateFormat))
// Get canonical request.
canonicalRequest := getCanonicalRequest(req)
canonicalRequest := getCanonicalRequest(req, v4IgnoredHeaders)
// Get string to sign from canonical request.
stringToSign := getStringToSignV4(t, location, canonicalRequest)
@@ -285,7 +285,7 @@ func SignV4(req http.Request, accessKeyID, secretAccessKey, location string) *ht
credential := GetCredential(accessKeyID, location, t)
// Get all signed headers.
signedHeaders := getSignedHeaders(req)
signedHeaders := getSignedHeaders(req, v4IgnoredHeaders)
// Calculate signature.
signature := getSignature(signingKey, stringToSign)
+4 -4
View File
@@ -25,8 +25,8 @@ import (
// StringSet - uses map as set of strings.
type StringSet map[string]struct{}
// keys - returns StringSet keys.
func (set StringSet) keys() []string {
// ToSlice - returns StringSet as string slice.
func (set StringSet) ToSlice() []string {
keys := make([]string, 0, len(set))
for k := range set {
keys = append(keys, k)
@@ -141,7 +141,7 @@ func (set StringSet) Union(sset StringSet) StringSet {
// MarshalJSON - converts to JSON data.
func (set StringSet) MarshalJSON() ([]byte, error) {
return json.Marshal(set.keys())
return json.Marshal(set.ToSlice())
}
// UnmarshalJSON - parses JSON data and creates new set with it.
@@ -169,7 +169,7 @@ func (set *StringSet) UnmarshalJSON(data []byte) error {
// String - returns printable string of the set.
func (set StringSet) String() string {
return fmt.Sprintf("%s", set.keys())
return fmt.Sprintf("%s", set.ToSlice())
}
// NewStringSet - creates new string set.
+10 -2
View File
@@ -33,8 +33,16 @@ const MaxJitter = 1.0
// NoJitter disables the use of jitter for randomizing the exponential backoff time
const NoJitter = 0.0
// newRetryTimer creates a timer with exponentially increasing delays
// until the maximum retry attempts are reached.
// DefaultRetryUnit - default unit multiplicative per retry.
// defaults to 1 second.
const DefaultRetryUnit = time.Second
// DefaultRetryCap - Each retry attempt never waits no longer than
// this maximum time duration.
const DefaultRetryCap = time.Second * 30
// newRetryTimer creates a timer with exponentially increasing
// delays until the maximum retry attempts are reached.
func (c Client) newRetryTimer(maxRetry int, unit time.Duration, cap time.Duration, jitter float64, doneCh chan struct{}) <-chan int {
attemptCh := make(chan int)
+60
View File
@@ -0,0 +1,60 @@
/*
* Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2017 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package minio
// Non exhaustive list of AWS S3 standard error responses -
// http://docs.aws.amazon.com/AmazonS3/latest/API/ErrorResponses.html
var s3ErrorResponseMap = map[string]string{
"AccessDenied": "Access Denied.",
"BadDigest": "The Content-Md5 you specified did not match what we received.",
"EntityTooSmall": "Your proposed upload is smaller than the minimum allowed object size.",
"EntityTooLarge": "Your proposed upload exceeds the maximum allowed object size.",
"IncompleteBody": "You did not provide the number of bytes specified by the Content-Length HTTP header.",
"InternalError": "We encountered an internal error, please try again.",
"InvalidAccessKeyID": "The access key ID you provided does not exist in our records.",
"InvalidBucketName": "The specified bucket is not valid.",
"InvalidDigest": "The Content-Md5 you specified is not valid.",
"InvalidRange": "The requested range is not satisfiable",
"MalformedXML": "The XML you provided was not well-formed or did not validate against our published schema.",
"MissingContentLength": "You must provide the Content-Length HTTP header.",
"MissingContentMD5": "Missing required header for this request: Content-Md5.",
"MissingRequestBodyError": "Request body is empty.",
"NoSuchBucket": "The specified bucket does not exist",
"NoSuchBucketPolicy": "The bucket policy does not exist",
"NoSuchKey": "The specified key does not exist.",
"NoSuchUpload": "The specified multipart upload does not exist. The upload ID may be invalid, or the upload may have been aborted or completed.",
"NotImplemented": "A header you provided implies functionality that is not implemented",
"PreconditionFailed": "At least one of the pre-conditions you specified did not hold",
"RequestTimeTooSkewed": "The difference between the request time and the server's time is too large.",
"SignatureDoesNotMatch": "The request signature we calculated does not match the signature you provided. Check your key and signing method.",
"MethodNotAllowed": "The specified method is not allowed against this resource.",
"InvalidPart": "One or more of the specified parts could not be found.",
"InvalidPartOrder": "The list of parts was not in ascending order. The parts list must be specified in order by part number.",
"InvalidObjectState": "The operation is not valid for the current state of the object.",
"AuthorizationHeaderMalformed": "The authorization header is malformed; the region is wrong.",
"MalformedPOSTRequest": "The body of your POST request is not well-formed multipart/form-data.",
"BucketNotEmpty": "The bucket you tried to delete is not empty",
"AllAccessDisabled": "All access to this bucket has been disabled.",
"MalformedPolicy": "Policy has invalid resource.",
"MissingFields": "Missing fields in request.",
"AuthorizationQueryParametersError": "Error parsing the X-Amz-Credential parameter; the Credential is mal-formed; expecting \"<YOUR-AKID>/YYYYMMDD/REGION/SERVICE/aws4_request\".",
"MalformedDate": "Invalid date format header, expected to be in ISO8601, RFC1123 or RFC1123Z time format.",
"BucketAlreadyOwnedByYou": "Your previous request to create the named bucket succeeded and you already own it.",
"InvalidDuration": "Duration provided in the request is invalid.",
"XAmzContentSHA256Mismatch": "The provided 'x-amz-content-sha256' header does not match what was computed.",
// Add new API errors here.
}
+6
View File
@@ -24,6 +24,7 @@ const (
Latest SignatureType = iota
SignatureV4
SignatureV2
SignatureV4Streaming
)
// isV2 - is signature SignatureV2?
@@ -35,3 +36,8 @@ func (s SignatureType) isV2() bool {
func (s SignatureType) isV4() bool {
return s == SignatureV4 || s == Latest
}
// isStreamingV4 - is signature SignatureV4Streaming?
func (s SignatureType) isStreamingV4() bool {
return s == SignatureV4Streaming
}
+76 -27
View File
@@ -122,7 +122,30 @@ If successful restarts the running minio service, for distributed setup restarts
```
## 3. Lock operations
## 3. Info operations
<a name="ServerInfo"></a>
### ServerInfo() ([]ServerInfo, error)
Fetch all information for all cluster nodes, such as uptime, region, network statistics, etc..
__Example__
```go
serversInfo, err := madmClnt.ServerInfo()
if err != nil {
log.Fatalln(err)
}
for _, peerInfo := range serversInfo {
log.Printf("Node: %s, Info: %v\n", peerInfo.Addr, peerInfo.Data)
}
```
## 4. Lock operations
<a name="ListLocks"></a>
### ListLocks(bucket, prefix string, duration time.Duration) ([]VolumeLockInfo, error)
@@ -154,7 +177,7 @@ __Example__
```
## 4. Heal operations
## 5. Heal operations
<a name="ListObjectsHeal"></a>
### ListObjectsHeal(bucket, prefix string, recursive bool, doneCh <-chan struct{}) (<-chan ObjectInfo, error)
@@ -242,18 +265,31 @@ __Example__
```
<a name="HealObject"></a>
### HealObject(bucket, object string, isDryRun bool) error
### HealObject(bucket, object string, isDryRun bool) (HealResult, error)
If object is successfully healed returns nil, otherwise returns error indicating the reason for failure. If isDryRun is true, then the object is not healed, but heal object request is validated by the server. e.g, if the object exists, if object name is valid etc.
| Param | Type | Description |
|---|---|---|
|`h.State` | _HealState_ | Represents the result of heal operation. It could be one of `HealNone`, `HealPartial` or `HealOK`. |
| Value | Description |
|---|---|
|`HealNone` | Object/Upload wasn't healed on any of the disks |
|`HealPartial` | Object/Upload was healed on some of the disks needing heal |
| `HealOK` | Object/Upload was healed on all the disks needing heal |
__Example__
``` go
isDryRun := false
err := madmClnt.HealObject("mybucket", "myobject", isDryRun)
isDryRun = false
healResult, err := madmClnt.HealObject("mybucket", "myobject", isDryRun)
if err != nil {
log.Fatalln(err)
}
log.Println("successfully healed mybucket/myobject")
log.Println("Heal-object result: ", healResult)
```
@@ -323,20 +359,31 @@ __Example__
```
<a name="HealUpload"></a>
### HealUpload(bucket, object, uploadID string, isDryRun bool) error
### HealUpload(bucket, object, uploadID string, isDryRun bool) (HealResult, error)
If upload is successfully healed returns nil, otherwise returns error indicating the reason for failure. If isDryRun is true, then the upload is not healed, but heal upload request is validated by the server. e.g, if the upload exists, if upload name is valid etc.
| Param | Type | Description |
|---|---|---|
|`h.State` | _HealState_ | Represents the result of heal operation. It could be one of `HealNone`, `HealPartial` or `HealOK`. |
| Value | Description |
|---|---|
| `HealNone` | Object/Upload wasn't healed on any of the disks |
| `HealPartial` | Object/Upload was healed on some of the disks needing heal |
| `HealOK` | Object/Upload was healed on all the disks needing heal |
``` go
isDryRun = false
err = madmClnt.HealUpload("mybucket", "myobject", "myuploadID", isDryRun)
healResult, err := madmClnt.HealUpload("mybucket", "myobject", "myUploadID", isDryRun)
if err != nil {
log.Fatalln(err)
}
log.Println("successfully healed mybucket/myobject/myuploadID")
log.Println("Heal-upload result: ", healResult)
```
## 5. Config operations
## 6. Config operations
<a name="GetConfig"></a>
### GetConfig() ([]byte, error)
@@ -360,23 +407,6 @@ __Example__
log.Println("config received successfully: ", string(buf.Bytes()))
```
## 6. Misc operations
<a name="SetCredentials"></a>
### SetCredentials() error
Set new credentials of a Minio setup.
__Example__
``` go
err = madmClnt.SetCredentials("YOUR-NEW-ACCESSKEY", "YOUR-NEW-SECRETKEY")
if err != nil {
log.Fatalln(err)
}
log.Println("New credentials successfully set.")
```
<a name="SetConfig"></a>
### SetConfig(config io.Reader) (SetConfigResult, error)
@@ -411,3 +441,22 @@ __Example__
}
log.Println("SetConfig: ", string(buf.Bytes()))
```
## 7. Misc operations
<a name="SetCredentials"></a>
### SetCredentials() error
Set new credentials of a Minio setup.
__Example__
``` go
err = madmClnt.SetCredentials("YOUR-NEW-ACCESSKEY", "YOUR-NEW-SECRETKEY")
if err != nil {
log.Fatalln(err)
}
log.Println("New credentials successfully set.")
```
+67 -12
View File
@@ -20,8 +20,10 @@
package madmin
import (
"encoding/json"
"encoding/xml"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"time"
@@ -104,8 +106,12 @@ const (
CanHeal
// Corrupted - Object can't be healed
Corrupted
// QuorumUnavailable - Object can't be healed until read quorum is available
// QuorumUnavailable - Object can't be healed until read
// quorum is available
QuorumUnavailable
// CanPartiallyHeal - Object can't be healed completely until
// disks with missing parts come online
CanPartiallyHeal
)
// HealBucketInfo - represents healing related information of a bucket.
@@ -127,9 +133,9 @@ type BucketInfo struct {
// HealObjectInfo - represents healing related information of an object.
type HealObjectInfo struct {
Status HealStatus
MissingDataCount int
MissingPartityCount int
Status HealStatus
MissingDataCount int
MissingParityCount int
}
// ObjectInfo container for object metadata.
@@ -434,7 +440,7 @@ func (adm *AdminClient) HealBucket(bucket string, dryrun bool) error {
}
// HealUpload - Heal the given upload.
func (adm *AdminClient) HealUpload(bucket, object, uploadID string, dryrun bool) error {
func (adm *AdminClient) HealUpload(bucket, object, uploadID string, dryrun bool) (HealResult, error) {
// Construct query params.
queryVal := url.Values{}
queryVal.Set("heal", "")
@@ -460,18 +466,51 @@ func (adm *AdminClient) HealUpload(bucket, object, uploadID string, dryrun bool)
defer closeResponse(resp)
if err != nil {
return err
return HealResult{}, err
}
if resp.StatusCode != http.StatusOK {
return httpRespToErrorResponse(resp)
return HealResult{}, httpRespToErrorResponse(resp)
}
return nil
// Healing is not performed so heal object result is empty.
if dryrun {
return HealResult{}, nil
}
jsonBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return HealResult{}, err
}
healResult := HealResult{}
err = json.Unmarshal(jsonBytes, &healResult)
if err != nil {
return HealResult{}, err
}
return healResult, nil
}
// HealResult - represents result of heal-object admin API.
type HealResult struct {
State HealState `json:"state"`
}
// HealState - different states of heal operation
type HealState int
const (
// HealNone - none of the disks healed
HealNone HealState = iota
// HealPartial - some disks were healed, others were offline
HealPartial
// HealOK - all disks were healed
HealOK
)
// HealObject - Heal the given object.
func (adm *AdminClient) HealObject(bucket, object string, dryrun bool) error {
func (adm *AdminClient) HealObject(bucket, object string, dryrun bool) (HealResult, error) {
// Construct query params.
queryVal := url.Values{}
queryVal.Set("heal", "")
@@ -494,14 +533,30 @@ func (adm *AdminClient) HealObject(bucket, object string, dryrun bool) error {
defer closeResponse(resp)
if err != nil {
return err
return HealResult{}, err
}
if resp.StatusCode != http.StatusOK {
return httpRespToErrorResponse(resp)
return HealResult{}, httpRespToErrorResponse(resp)
}
return nil
// Healing is not performed so heal object result is empty.
if dryrun {
return HealResult{}, nil
}
jsonBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return HealResult{}, err
}
healResult := HealResult{}
err = json.Unmarshal(jsonBytes, &healResult)
if err != nil {
return HealResult{}, err
}
return healResult, nil
}
// HealFormat - heal storage format on available disks.
+18 -11
View File
@@ -74,17 +74,24 @@ type ServerConnStats struct {
TotalOutputBytes uint64 `json:"received"`
}
// ServerInfo holds the whole server information that will be
// returned by ServerInfo API.
type ServerInfo struct {
// ServerInfoData holds storage, connections and other
// information of a given server
type ServerInfoData struct {
StorageInfo StorageInfo `json:"storage"`
ConnStats ServerConnStats `json:"network"`
Properties ServerProperties `json:"server"`
}
// ServerInfo holds server information result of one node
type ServerInfo struct {
Error string `json:"error"`
Addr string `json:"addr"`
Data *ServerInfoData `json:"data"`
}
// ServerInfo - Connect to a minio server and call Server Info Management API
// to fetch server's information represented by ServerInfo structure
func (adm *AdminClient) ServerInfo() (ServerInfo, error) {
func (adm *AdminClient) ServerInfo() ([]ServerInfo, error) {
// Prepare web service request
reqData := requestData{}
reqData.queryValues = make(url.Values)
@@ -94,26 +101,26 @@ func (adm *AdminClient) ServerInfo() (ServerInfo, error) {
resp, err := adm.executeMethod("GET", reqData)
defer closeResponse(resp)
if err != nil {
return ServerInfo{}, err
return nil, err
}
// Check response http status code
if resp.StatusCode != http.StatusOK {
return ServerInfo{}, httpRespToErrorResponse(resp)
return nil, httpRespToErrorResponse(resp)
}
// Unmarshal the server's json response
var info ServerInfo
var serversInfo []ServerInfo
respBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return ServerInfo{}, err
return nil, err
}
err = json.Unmarshal(respBytes, &info)
err = json.Unmarshal(respBytes, &serversInfo)
if err != nil {
return ServerInfo{}, err
return nil, err
}
return info, nil
return serversInfo, nil
}
+5 -6
View File
@@ -42,12 +42,11 @@ const (
// OpsLockState - represents lock specific details.
type OpsLockState struct {
OperationID string `json:"id"` // String containing operation ID.
LockSource string `json:"source"` // Operation type (GetObject, PutObject...)
LockType lockType `json:"type"` // Lock type (RLock, WLock)
Status statusType `json:"status"` // Status can be Running/Ready/Blocked.
Since time.Time `json:"since"` // Time when the lock was initially held.
Duration time.Duration `json:"duration"` // Duration since the lock was held.
OperationID string `json:"id"` // String containing operation ID.
LockSource string `json:"source"` // Operation type (GetObject, PutObject...)
LockType lockType `json:"type"` // Lock type (RLock, WLock)
Status statusType `json:"status"` // Status can be Running/Ready/Blocked.
Since time.Time `json:"since"` // Time when the lock was initially held.
}
// VolumeLockInfo - represents summary and individual lock details of all
+21 -15
View File
@@ -50,22 +50,28 @@
"revisionTime": "2015-10-24T22:24:27-07:00"
},
{
"checksumSHA1": "q2mnNtdkxvuzEx8d5W0uCO0wmgI=",
"checksumSHA1": "ymC5RhgF7MLQ7Gj1w0AcCQykQbY=",
"path": "github.com/minio/minio-go",
"revision": "ef0dc7e81b008739bd2ab9cb5b5cfbdc22bf32a5",
"revisionTime": "2017-04-01T21:28:19Z"
"revision": "5297a818b482fa329b3dc1a3926e3c4c6fb5d459",
"revisionTime": "2017-04-26T18:23:05Z"
},
{
"checksumSHA1": "qTxOBp3GVxCC70ykb7Hxg6UgWwA=",
"checksumSHA1": "lsxCcRcNUDxhQyO999SOdvKzzfM=",
"path": "github.com/minio/minio-go/pkg/encrypt",
"revision": "5297a818b482fa329b3dc1a3926e3c4c6fb5d459",
"revisionTime": "2017-04-26T18:23:05Z"
},
{
"checksumSHA1": "neH34/65OXeKHM/MlV8MbhcdFBc=",
"path": "github.com/minio/minio-go/pkg/policy",
"revision": "583c261267bc1022bb3e046c7d01c49d3f56edaa",
"revisionTime": "2016-09-03T08:42:23Z"
"revision": "5297a818b482fa329b3dc1a3926e3c4c6fb5d459",
"revisionTime": "2017-04-26T18:23:05Z"
},
{
"checksumSHA1": "m/6/na9lVtamkfmIdIOi5pdccgw=",
"checksumSHA1": "/5IXp1nGKqOfHn8Piiod3OCkG2U=",
"path": "github.com/minio/minio-go/pkg/s3signer",
"revision": "532b920ff28900244a2ef7d07468003df36fe7c5",
"revisionTime": "2016-12-20T20:43:13Z"
"revision": "5297a818b482fa329b3dc1a3926e3c4c6fb5d459",
"revisionTime": "2017-04-26T18:23:05Z"
},
{
"checksumSHA1": "gRnCFKb4x83GBLVUZXoOjujd+U0=",
@@ -74,16 +80,16 @@
"revisionTime": "2017-01-05T04:45:20Z"
},
{
"checksumSHA1": "A8QOw1aWwc+RtjGozY0XeS5varo=",
"checksumSHA1": "maUy+dbN6VfTTnfErrAW2lLit1w=",
"path": "github.com/minio/minio-go/pkg/set",
"revision": "9e734013294ab153b0bdbe182738bcddd46f1947",
"revisionTime": "2016-08-18T00:31:20Z"
"revision": "5297a818b482fa329b3dc1a3926e3c4c6fb5d459",
"revisionTime": "2017-04-26T18:23:05Z"
},
{
"checksumSHA1": "M7IzPNZncWn7ve14/YPF2HKhCko=",
"checksumSHA1": "wCZlVPjuBU/D1ogLL63YdO/havo=",
"path": "github.com/minio/minio/pkg/madmin",
"revision": "97dc34fe06274894316a68e0e86e6c8cf498e21a",
"revisionTime": "2017-03-21T19:02:39Z"
"revision": "9d98bf1c0fb83ccfcf368dec52b2d19b9195b8d4",
"revisionTime": "2017-05-19T14:30:00Z"
},
{
"path": "github.com/minio/minio/pkg/probe",