diff --git a/.travis.yml b/.travis.yml index 30f8ccc0..ab3d7297 100644 --- a/.travis.yml +++ b/.travis.yml @@ -9,7 +9,7 @@ env: - ARCH=i686 go: -- 1.7.3 +- 1.8 script: - make test GOFLAGS="-race" diff --git a/CONFLICT.md b/CONFLICT.md new file mode 100644 index 00000000..a315b3b3 --- /dev/null +++ b/CONFLICT.md @@ -0,0 +1,11 @@ +## mc (Minio Client) v/s Midnight Commander (mc) + +There has been some amount of [requests](https://github.com/minio/mc/issues?q=is%3Aissue+midnight+commander+is%3Aclosed) on renaming this project to avoid the conflict with Midnight Commander for Unix distributions. We struggled with this, it is harder to find a name sweeter and shorter than `mc` for Minio Client. + +Besides `mc` is a single static binary and can reside inside your application and is fully self contained. Midnight Commander (mc) is a free software clone of Norton Commander (nc). Minio and Midnight shares no code or ideas. Only their abbreviation matches. + +Package managers are free to choose a different name if they like. One such solution [pointed out](https://github.com/minio/mc/issues/873#issuecomment-267583013) by one of our community members. + +```sh +mv ./mc ./mcli +``` \ No newline at end of file diff --git a/Dockerfile b/Dockerfile index 48697892..638300a4 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -FROM golang:1.7-alpine +FROM golang:1.8-alpine WORKDIR /go/src/app diff --git a/README.md b/README.md index 75f28802..3f56bb95 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,6 @@ Minio Client (mc) provides a modern alternative to UNIX commands like ls, cat, cp, mirror, diff etc. It supports filesystems and Amazon S3 compatible cloud storage service (AWS Signature v2 and v4). ``` - ls List files and folders. mb Make a bucket or folder. cat Display contents of a file. @@ -20,7 +19,6 @@ session Manage saved sessions of cp and mirror operations. config Manage configuration file. update Check for a new software update. version Print version. - ``` ## Docker Container @@ -50,51 +48,43 @@ mc --help ### Binary Download | Platform | Architecture | URL | | ---------- | -------- |------| -|GNU/Linux|64-bit Intel|https://dl.minio.io/client/mc/release/linux-amd64/mc| -||32-bit Intel|https://dl.minio.io/client/mc/release/linux-386/mc| -||32-bit ARM|https://dl.minio.io/client/mc/release/linux-arm/mc| +|GNU/Linux|64-bit Intel|https://dl.minio.io/client/mc/release/linux-amd64/mc | +| |32-bit Intel|https://dl.minio.io/client/mc/release/linux-386/mc | +| |32-bit ARM|https://dl.minio.io/client/mc/release/linux-arm/mc | ```sh - chmod +x mc ./mc --help - ``` ## Microsoft Windows ### Binary Download | Platform | Architecture | URL | | ---------- | -------- |------| -|Microsoft Windows|64-bit|https://dl.minio.io/client/mc/release/windows-amd64/mc.exe| -||32-bit|https://dl.minio.io/client/mc/release/windows-386/mc.exe | +|Microsoft Windows|64-bit|https://dl.minio.io/client/mc/release/windows-amd64/mc.exe | +| |32-bit|https://dl.minio.io/client/mc/release/windows-386/mc.exe | ```sh - mc.exe --help - ``` ## FreeBSD ### Binary Download | Platform | Architecture | URL | | ---------- | -------- |------| -|FreeBSD|64-bit|https://dl.minio.io/client/mc/release/freebsd-amd64/mc| +|FreeBSD|64-bit|https://dl.minio.io/client/mc/release/freebsd-amd64/mc | ```sh - chmod 755 mc ./mc --help - ``` ## Solaris/Illumos ### From Source ```sh - go get -u github.com/minio/mc mc --help - ``` ## Install from Source @@ -103,9 +93,7 @@ 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 - ``` ## Add a Cloud Storage Service @@ -114,9 +102,7 @@ If you are planning to use `mc` only on POSIX compatible filesystems, you may sk To add one or more Amazon S3 compatible hosts, please follow the instructions below. `mc` stores all its configuration information in ``~/.mc/config.json`` file. ```sh - mc config host add - ``` Alias is simply a short name to you cloud storage service. S3 end-point, access and secret keys are supplied by your cloud storage provider. API signature is an optional argument. By default, it is set to "S3v4". @@ -125,27 +111,21 @@ Alias is simply a short name to you cloud storage service. S3 end-point, access Minio server displays URL, access and secret keys. ```sh - mc config host add minio http://192.168.1.51 BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 S3v4 - ``` ### Example - Amazon S3 Cloud Storage -Get your AccessKeyID and SecretAccessKey by following [AWS Credentials Guide](http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSGettingStartedGuide/AWSCredentials.html). +Get your AccessKeyID and SecretAccessKey by following [AWS Credentials Guide](http://docs.aws.amazon.com/general/latest/gr/aws-security-credentials.html). ```sh - mc config host add s3 https://s3.amazonaws.com BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 S3v4 - ``` ### Example - Google Cloud Storage Get your AccessKeyID and SecretAccessKey by following [Google Credentials Guide](https://cloud.google.com/storage/docs/migrating?hl=en#keys) ```sh - mc config host add gcs https://storage.googleapis.com BKIKJAA5BMMU2RHO6IBB V8f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 S3v2 - ``` NOTE: Google Cloud Storage only supports Legacy Signature Version 2, so you have to pick - S3v2 @@ -158,27 +138,39 @@ NOTE: Google Cloud Storage only supports Legacy Signature Version 2, so you have List all buckets from https://play.minio.io:9000 ```sh - mc ls play [2016-03-22 19:47:48 PDT] 0B my-bucketname/ [2016-03-22 22:01:07 PDT] 0B mytestbucket/ [2016-03-22 20:04:39 PDT] 0B mybucketname/ [2016-01-28 17:23:11 PST] 0B newbucket/ [2016-03-20 09:08:36 PDT] 0B s3git-test/ - ``` ## Everyday Use + +### Shell aliases You may add shell aliases to override your common Unix tools. ```sh - alias ls='mc ls' alias cp='mc cp' alias cat='mc cat' alias mkdir='mc mb' 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. + +```sh +sudo wget https://raw.githubusercontent.com/minio/mc/master/autocomplete/bash_complete -O /etc/bash_completion.d/mc +source /etc/bash_completion.d/mc +``` + +```sh +mc +admin config diff ls mirror policy session update watch +cat cp events mb pipe rm share version ``` ## Explore Further diff --git a/appveyor.yml b/appveyor.yml index 3e16dd95..d8947223 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -8,11 +8,15 @@ clone_folder: c:\gopath\src\github.com\minio\mc # environment variables environment: + GOVERSION: 1.8 GOPATH: c:\gopath # scripts that run after cloning repository install: - set PATH=%GOPATH%\bin;c:\go\bin;%PATH% + - rmdir c:\go /s /q + - appveyor DownloadFile https://storage.googleapis.com/golang/go%GOVERSION%.windows-amd64.zip + - 7z x go%GOVERSION%.windows-amd64.zip -y -oC:\ > NUL - go version - go env diff --git a/autocomplete/bash_autocomplete b/autocomplete/bash_autocomplete new file mode 100644 index 00000000..d93add85 --- /dev/null +++ b/autocomplete/bash_autocomplete @@ -0,0 +1,14 @@ +#!/bin/bash + +: ${PROG:=$(basename ${BASH_SOURCE})} + +_cli_bash_autocomplete() { + local cur opts base + COMPREPLY=() + cur="${COMP_WORDS[COMP_CWORD]}" + opts=$( ${COMP_WORDS[@]:0:$COMP_CWORD} --compgen ) + COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) ) + return 0 + } + + complete -F _cli_bash_autocomplete $PROG -q diff --git a/autocomplete/zsh_autocomplete b/autocomplete/zsh_autocomplete new file mode 100644 index 00000000..5430a18f --- /dev/null +++ b/autocomplete/zsh_autocomplete @@ -0,0 +1,5 @@ +autoload -U compinit && compinit +autoload -U bashcompinit && bashcompinit + +script_dir=$(dirname $0) +source ${script_dir}/bash_autocomplete diff --git a/buildscripts/checkdeps.sh b/buildscripts/checkdeps.sh index 1f4670db..bc498148 100755 --- a/buildscripts/checkdeps.sh +++ b/buildscripts/checkdeps.sh @@ -1,6 +1,6 @@ #!/usr/bin/env bash # -# 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. @@ -25,14 +25,17 @@ _init() { OSX_VERSION="10.8" KNAME=$(uname -s) ARCH=$(uname -m) - - ## Check all dependencies are present - MISSING="" - - ## Documentation sources - DOC_GO_INSTALL_URL="https://docs.minio.io/docs/how-to-install-golang" } +## FIXME: +## In OSX, 'readlink -f' option does not exist, hence +## we have our own readlink -f behaviour here. +## Once OSX has the option, below function is good enough. +## +## readlink() { +## return /bin/readlink -f "$1" +## } +## readlink() { TARGET_FILE=$1 @@ -54,121 +57,31 @@ readlink() { echo $RESULT } -### -# -# Takes two arguments -# arg1: version number in `x.x.x` format or `devel` -# arg2: version number in `x.x.x` format or `devel` -# -# example: check_version "$version1" "$version2" -# -# returns: -# 0 - Installed version is equal to required -# 1 - Installed version is greater than required -# 2 - Installed version is lesser than required -# 3 - If args have length zero -# -#### -check_version() { - ## validate args - [[ -z "$1" ]] && return 3 - [[ -z "$2" ]] && return 3 +## FIXME: +## In OSX, 'sort -V' option does not exist, hence +## we have our own version compare function. +## Once OSX has the option, below function is good enough. +## +## check_minimum_version() { +## versions=($(echo -e "$1\n$2" | sort -V)) +## return [ "$1" == "${versions[0]}" ] +## } +## +check_minimum_version() { + IFS='.' read -r -a varray1 <<< "$1" + IFS='.' read -r -a varray2 <<< "$2" - if [[ $1 == $2 ]]; then - return 0 - fi - - local IFS=. - local i ver1=($1) ver2=($2) - - if [ "$ver1" = "devel" ]; then - return 1 - fi - if [ "$ver2" = "devel" ]; then - return 2 - fi - - # fill empty fields in ver1 with zeros - for ((i=${#ver1[@]}; i<${#ver2[@]}; i++)); do - ver1[i]=0 - done - for ((i=0; i<${#ver1[@]}; i++)); do - if [[ -z ${ver2[i]} ]]; then - # fill empty fields in ver2 with zeros - ver2[i]=0 - fi - if ((10#${ver1[i]} > 10#${ver2[i]})); then + for i in "${!varray1[@]}"; do + if [[ ${varray1[i]} -lt ${varray2[i]} ]]; then + return 0 + elif [[ ${varray1[i]} -gt ${varray2[i]} ]]; then return 1 fi - if ((10#${ver1[i]} < 10#${ver2[i]})); then - ## Installed version is lesser than required - Bad condition - return 2 - fi done + return 0 } -check_golang_env() { - echo ${GOROOT:?} 2>&1 >/dev/null - if [ $? -eq 1 ]; then - echo "ERROR" - echo "GOROOT environment variable missing, please refer to Go installation document" - echo "${DOC_GO_INSTALL_URL}" - exit 1 - fi - - echo ${GOPATH:?} 2>&1 >/dev/null - if [ $? -eq 1 ]; then - echo "ERROR" - echo "GOPATH environment variable missing, please refer to Go installation document" - echo "${DOC_GO_INSTALL_URL}" - exit 1 - fi - - local go_binary_path=$(which go) - - if [ -z "${go_binary_path}" ] ; then - echo "Cannot find go binary in your PATH configuration, please refer to Go installation document" - echo "${DOC_GO_INSTALL_URL}" - exit -1 - fi - - local new_go_binary_path=${go_binary_path} - if [ -h "${go_binary_path}" ]; then - new_go_binary_path=$(readlink ${go_binary_path}) - fi - - if [[ ! "$(dirname ${new_go_binary_path})" =~ "${GOROOT}"* ]] ; then - echo "The go binary found in your PATH configuration does not belong to the Go installation pointed by your GOROOT environment," \ - "please refer to Go installation document" - echo "${DOC_GO_INSTALL_URL}" - exit -1 - fi -} - -assert_is_supported_os() { - case "${KNAME}" in - Linux | FreeBSD ) - return - ;; - Darwin ) - osx_host_version=$(env sw_vers -productVersion) - if ! check_minimum_version "${OSX_VERSION}" "${osx_host_version}"; then - echo "ERROR" - echo "OSX version '${osx_host_version}' not supported." - echo "Minimum supported version: ${OSX_VERSION}" - exit 1 - fi - return - ;; - *) - echo "ERROR" - echo "OS '${KNAME}' is not supported." - echo "Supported OS: [Linux, FreeBSD, Darwin]" - exit 1 - esac -} - assert_is_supported_arch() { case "${ARCH}" in x86_64 | amd64 | aarch64 | arm* ) @@ -182,49 +95,77 @@ assert_is_supported_arch() { esac } -check_deps() { - check_version "$(env go version 2>/dev/null | awk '{print $3}' | sed 's/go\([0-9.]*\)$/\1/')" "${GO_VERSION}" - if [ $? -ge 2 ]; then - MISSING="${MISSING} golang(>=${GO_VERSION})" +assert_is_supported_os() { + case "${KNAME}" in + Linux | FreeBSD | OpenBSD | NetBSD | DragonFly ) + return + ;; + Darwin ) + osx_host_version=$(env sw_vers -productVersion) + if ! check_minimum_version "${OSX_VERSION}" "${osx_host_version}"; then + echo "ERROR" + echo "OSX version '${osx_host_version}' not supported." + echo "Minimum supported version: ${OSX_VERSION}" + exit 1 + fi + return + ;; + *) + echo "ERROR" + echo "OS '${KNAME}' is not supported." + echo "Supported OS: [Linux, FreeBSD, OpenBSD, NetBSD, Darwin, DragonFly]" + exit 1 + esac +} + +assert_check_golang_env() { + if ! which go >/dev/null 2>&1; then + echo "ERROR" + echo "Cannot find go binary in your PATH configuration, please refer to Go installation document at" + echo "https://docs.minio.io/docs/how-to-install-golang" + exit 1 fi - check_version "$(env git --version 2>/dev/null | sed -e 's/^.* \([0-9.\].*\).*$/\1/' -e 's/^\([0-9.\]*\).*/\1/g')" "${GIT_VERSION}" - if [ $? -ge 2 ]; then - MISSING="${MISSING} git(>=${GIT_VERSION})" + installed_go_version=$(go version | sed 's/^.* go\([0-9.]*\).*$/\1/') + if ! check_minimum_version "${GO_VERSION}" "${installed_go_version}"; then + echo "ERROR" + echo "Go version '${installed_go_version}' not supported." + echo "Minimum supported version: ${GO_VERSION}" + exit 1 + fi + + if [ -z "${GOPATH}" ]; then + echo "ERROR" + echo "GOPATH environment variable missing, please refer to Go installation document" + echo "https://docs.minio.io/docs/how-to-install-golang" + exit 1 + fi + +} + +assert_check_deps() { + # support unusual Git versions such as: 2.7.4 (Apple Git-66) + installed_git_version=$(git version | perl -ne '$_ =~ m/git version (.*?)( |$)/; print "$1\n";') + if ! check_minimum_version "${GIT_VERSION}" "${installed_git_version}"; then + echo "ERROR" + echo "Git version '${installed_git_version}' not supported." + echo "Minimum supported version: ${GIT_VERSION}" + exit 1 fi } main() { - echo -n "Check for supported arch.. " + ## Check for supported arch assert_is_supported_arch - echo -n "Check for supported os.. " + ## Check for supported os assert_is_supported_os - echo -n "Checking if proper environment variables are set.. " - check_golang_env + ## Check for Go environment + assert_check_golang_env - echo "Done" - echo "Using GOPATH=${GOPATH} and GOROOT=${GOROOT}" - - echo -n "Checking dependencies for Minio Client.. " - check_deps - - ## If dependencies are missing, warn the user and abort - if [ "x${MISSING}" != "x" ]; then - echo "ERROR" - echo - echo "The following build tools are missing:" - echo - echo "** ${MISSING} **" - echo - echo "Please install them " - echo "${MISSING}" - echo - echo "Follow ${DOC_GO_INSTALL_URL} for further instructions" - exit 1 - fi - echo "Done" + ## Check for dependencies + assert_check_deps } _init && main "$@" diff --git a/buildscripts/checkgopath.sh b/buildscripts/checkgopath.sh index 61e61c14..8c4321c1 100644 --- a/buildscripts/checkgopath.sh +++ b/buildscripts/checkgopath.sh @@ -1,6 +1,6 @@ #!/usr/bin/env bash # -# Minio Cloud Storage, (C) 2015, 2016 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. diff --git a/cmd/accounting-reader.go b/cmd/accounting-reader.go index ad3ce6e4..fd433bdd 100644 --- a/cmd/accounting-reader.go +++ b/cmd/accounting-reader.go @@ -17,9 +17,12 @@ package cmd import ( + "fmt" "sync" "sync/atomic" "time" + + "github.com/cheggaaa/pb" ) // accounter keeps tabs of ongoing data transfer information. @@ -51,7 +54,7 @@ func newAccounter(total int64) *accounter { // write calculate the final speed. func (a *accounter) write(current int64) float64 { - fromStart := time.Now().Sub(a.startTime) + fromStart := time.Since(a.startTime) currentFromStart := current - a.startValue if currentFromStart > 0 { speed := float64(currentFromStart) / (float64(fromStart) / float64(time.Second)) @@ -80,6 +83,18 @@ type accountStat struct { Speed float64 } +func (c accountStat) String() string { + speedBox := pb.Format(int64(c.Speed)).To(pb.U_BYTES).String() + if speedBox == "" { + speedBox = "0 MB" + } else { + speedBox = speedBox + "/s" + } + message := fmt.Sprintf("Total: %s, Transferred: %s, Speed: %s", pb.Format(c.Total).To(pb.U_BYTES), + pb.Format(c.Transferred).To(pb.U_BYTES), speedBox) + return message +} + // Stat provides current stats captured. func (a *accounter) Stat() accountStat { var acntStat accountStat diff --git a/cmd/admin-config-get.go b/cmd/admin-config-get.go new file mode 100644 index 00000000..5370357e --- /dev/null +++ b/cmd/admin-config-get.go @@ -0,0 +1,95 @@ +/* + * 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" + + "github.com/minio/cli" + "github.com/minio/minio/pkg/probe" +) + +var adminConfigGetCmd = cli.Command{ + Name: "get", + Usage: "Get config of a Minio server/cluster.", + Before: setGlobalsFromContext, + Action: mainAdminConfigGet, + Flags: globalFlags, + CustomHelpTemplate: `NAME: + {{.HelpName}} - {{.Usage}} + +USAGE: + {{.HelpName}} ALIAS/ + +FLAGS: + {{range .VisibleFlags}}{{.}} + {{end}} +EXAMPLES: + 1. Get server configuration of a Minio server/cluster. + $ {{.HelpName}} play/ + +`, +} + +// configGetMessage container to hold locks information. +type configGetMessage struct { + Status string `json:"status"` + Config []byte `json:"config"` +} + +// String colorized service status message. +func (u configGetMessage) String() string { + return string(u.Config) +} + +// JSON jsonified service status Message message. +func (u configGetMessage) JSON() string { + u.Status = "success" + statusJSONBytes, e := json.Marshal(u) + fatalIf(probe.NewError(e), "Unable to marshal into JSON.") + + return string(statusJSONBytes) +} + +// checkAdminConfigGetSyntax - validate all the passed arguments +func checkAdminConfigGetSyntax(ctx *cli.Context) { + if len(ctx.Args()) == 0 || len(ctx.Args()) > 2 { + cli.ShowCommandHelpAndExit(ctx, "get", 1) // last argument is exit code + } +} + +func mainAdminConfigGet(ctx *cli.Context) error { + + checkAdminConfigGetSyntax(ctx) + + // Get the alias parameter from cli + args := ctx.Args() + aliasedURL := args.Get(0) + + // Create a new Minio Admin Client + client, err := newAdminClient(aliasedURL) + fatalIf(err, "Cannot get a configured admin connection.") + + // Call get config API + c, e := client.GetConfig() + fatalIf(probe.NewError(e), "Cannot get server configuration file.") + + // Print + printMsg(configGetMessage{Config: c}) + + return nil +} diff --git a/cmd/admin-config-set.go b/cmd/admin-config-set.go new file mode 100644 index 00000000..3ca717b7 --- /dev/null +++ b/cmd/admin-config-set.go @@ -0,0 +1,134 @@ +/* + * 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" + "os" + + "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 adminConfigSetCmd = cli.Command{ + Name: "set", + Usage: "Set new config file to a Minio server/cluster.", + Before: setGlobalsFromContext, + Action: mainAdminConfigSet, + Flags: globalFlags, + CustomHelpTemplate: `NAME: + {{.HelpName}} - {{.Usage}} + +USAGE: + {{.HelpName}} ALIAS/ + +FLAGS: + {{range .VisibleFlags}}{{.}} + {{end}} +EXAMPLES: + 1. Set server configuration of a Minio server/cluster. + $ cat myconfig | {{.HelpName}} myminio/ + +`, +} + +// configSetMessage container to hold locks information. +type configSetMessage struct { + Status string `json:"status"` + setConfigStatus bool + SetConfigNodeSummary []madmin.NodeSummary `json:"nodesSummary"` +} + +// String colorized service status message. +func (u configSetMessage) String() (msg string) { + // For each node, print if set config was successful or not + for _, s := range u.SetConfigNodeSummary { + if s.ErrSet { + // An error occurred when setting the new config + msg += console.Colorize("SetConfigFailure", + fmt.Sprintf("Failed to apply the new configuration to `%s` (%s).", s.Name, s.ErrMsg)) + } else { + msg += console.Colorize("SetConfigSuccess", + fmt.Sprintf("New configuration applied to `%s` successfully.", s.Name)) + } + msg += "\n" + } + // Print the general set config status + if u.setConfigStatus { + msg += console.Colorize("SetConfigSuccess", + "Setting new Minio configuration file has been successful.\n") + } else { + msg += console.Colorize("SetConfigFailure", + "Setting new Minio configuration file has failed.\n") + } + return +} + +// JSON jsonified service status Message message. +func (u configSetMessage) JSON() string { + if u.setConfigStatus { + u.Status = "success" + } else { + u.Status = "error" + } + statusJSONBytes, e := json.Marshal(u) + fatalIf(probe.NewError(e), "Unable to marshal into JSON.") + + return string(statusJSONBytes) +} + +// checkAdminConfigSetSyntax - validate all the passed arguments +func checkAdminConfigSetSyntax(ctx *cli.Context) { + if len(ctx.Args()) == 0 || len(ctx.Args()) > 2 { + cli.ShowCommandHelpAndExit(ctx, "set", 1) // last argument is exit code + } +} + +// main config set function +func mainAdminConfigSet(ctx *cli.Context) error { + + // Check command arguments + checkAdminConfigSetSyntax(ctx) + + // Set color preference of command outputs + console.SetColor("SetConfigSuccess", color.New(color.FgGreen, color.Bold)) + console.SetColor("SetConfigFailure", color.New(color.FgRed, color.Bold)) + + // Get the alias parameter from cli + args := ctx.Args() + aliasedURL := args.Get(0) + + // Create a new Minio Admin Client + client, err := newAdminClient(aliasedURL) + fatalIf(err, "Cannot get a configured admin connection.") + + // Call get config API + c, e := client.SetConfig(os.Stdin) + fatalIf(probe.NewError(e), "Cannot get server configuration file.") + + // Print set config result + printMsg(configSetMessage{ + setConfigStatus: c.Status, + SetConfigNodeSummary: c.NodeResults, + }) + + return nil +} diff --git a/cmd/admin-config.go b/cmd/admin-config.go new file mode 100644 index 00000000..df5e278b --- /dev/null +++ b/cmd/admin-config.go @@ -0,0 +1,39 @@ +/* + * 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/minio/cli" + +var adminConfigCmd = cli.Command{ + Name: "config", + Usage: "Manage configuration file", + Action: mainAdminConfig, + Before: setGlobalsFromContext, + Flags: globalFlags, + Subcommands: []cli.Command{ + adminConfigGetCmd, + adminConfigSetCmd, + }, + HideHelpCommand: true, +} + +// mainAdminConfig is the handle for "mc admin config" command. +func mainAdminConfig(ctx *cli.Context) error { + cli.ShowCommandHelp(ctx, ctx.Args().First()) + return nil + // Sub-commands like "get", "set" have their own main. +} diff --git a/cmd/admin-heal-list.go b/cmd/admin-heal-list.go index ee04fb8d..4abaa76d 100644 --- a/cmd/admin-heal-list.go +++ b/cmd/admin-heal-list.go @@ -35,6 +35,10 @@ var ( Name: "recursive, r", Usage: "List recursively.", }, + cli.BoolFlag{ + Name: "incomplete, I", + Usage: "List incomplete uploads", + }, } ) @@ -45,43 +49,58 @@ var adminHealListCmd = cli.Command{ Action: mainAdminHealList, Flags: append(adminHealListFlags, globalFlags...), CustomHelpTemplate: `NAME: - mc admin heal {{.Name}} - {{.Usage}} + {{.HelpName}} - {{.Usage}} USAGE: - mc admin heal {{.Name}} ALIAS/BUCKET/PREFIX + {{.HelpName}} ALIAS/[BUCKET/][PREFIX/] FLAGS: - {{range .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'. - $ mc admin heal {{.Name}} play/testbucket/ + $ {{.HelpName}} play/testbucket/ + 2. Recursively list objects than need to be healed. - $ mc admin heal {{.Name}} --recursive play/ + $ {{.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"` + 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 := fmt.Sprintf("Object: %s/%s, ", u.Bucket, u.Object.Key) - switch u.Object.HealObjectInfo.Status { + 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" + msg += "can be healed." case madmin.Corrupted: - msg += "cannot be healed" + msg += "cannot be healed." case madmin.QuorumUnavailable: - msg += "quorum not available for healing" + msg += "quorum not available for healing." } - msg += ".\n" return console.Colorize("Heal", msg) } @@ -142,6 +161,7 @@ func mainAdminHealList(ctx *cli.Context) error { 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) @@ -197,15 +217,38 @@ func mainAdminHealList(ctx *cli.Context) error { for _, currBucket := range buckets { // Search for objects that need to be healed in the current bucket doneCh := make(chan struct{}) - listCh, e := client.ListObjectsHeal(currBucket, object, isRecursive, doneCh) - fatalIf(probe.NewError(e), "Cannot list heal objects.") - // Iterate over objects and print them when not errors - for obj := range listCh { - if obj.Err != nil { - errorIf(probe.NewError(obj.Err), "Cannot heal object `"+obj.Key+"`.") - continue + + 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}) } - printMsg(healListMessage{Bucket: currBucket, Object: obj}) } } diff --git a/cmd/admin-heal.go b/cmd/admin-heal.go index 8b2f8db0..0cf2d5af 100644 --- a/cmd/admin-heal.go +++ b/cmd/admin-heal.go @@ -33,64 +33,78 @@ var ( adminHealFlags = []cli.Flag{ cli.BoolFlag{ Name: "recursive, r", - Usage: "List recursively.", + Usage: "Heal recursively", }, cli.BoolFlag{ Name: "fake, k", - Usage: "Issue a fake heal operation.", + Usage: "Issue a fake heal operation", + }, + cli.BoolFlag{ + Name: "incomplete, I", + Usage: "Heal uploads recursively", }, } ) +var adminHealHelpTemplate = `NAME: + {{.HelpName}} - {{.Usage}} + +USAGE: + {{.HelpName}} [FLAGS] [COMMAND] + +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'. + $ {{.HelpName}} play/testbucket/ + + 2. Heal all objects under 'dir' prefix + $ {{.HelpName}} --recursive play/testbucket/dir/ + + 3. 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/ + +` var adminHealCmd = cli.Command{ Name: "heal", - Usage: "Manage heal tasks.", + Usage: "Manage heal tasks", Before: setGlobalsFromContext, Action: mainAdminHeal, Flags: append(adminHealFlags, globalFlags...), Subcommands: []cli.Command{ adminHealListCmd, }, - CustomHelpTemplate: `NAME: - {{.Name}} - {{.Usage}} - -USAGE: - {{.Name}} [FLAGS] COMMAND - -FLAGS: - {{range .Flags}}{{.}} - {{end}} - -COMMANDS: - {{range .Commands}}{{join .Names ", "}}{{ "\t" }}{{.Usage}} - {{end}} - -EXAMPLES: - 1. Heal 'testbucket' in a Minio server represented by its alias 'play'. - $ mc admin {{.Name}} play/testbucket/ - 2. Heal all objects under 'dir' prefix - $ mc admin {{.Name}} --recursive play/testbucket/dir/ - 3. Issue a fake heal operation to see what the server could report - $ mc admin {{.Name}} --fake play/testbucket/dir/ - -`, + HideHelpCommand: true, } -// healObjectMessage container to hold repair information. -type healObjectMessage struct { - Status string `json:"status"` - Bucket string `json:"bucket"` - Object madmin.ObjectInfo `json:"object"` +// healMessage container to hold repair information. +type healMessage 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 healObjectMessage) String() string { - msg := fmt.Sprintf("Object %s/%s is healed.", u.Bucket, u.Object.Key) +func (u healMessage) String() string { + msg := "" + if u.Object != nil { + msg += fmt.Sprintf("Object %s/%s is healed.", u.Bucket, u.Object.Key) + } else { + msg += fmt.Sprintf("Upload %s/%s/%s is healed.", u.Bucket, u.Upload.Key, u.Upload.UploadID) + } return console.Colorize("Heal", msg) } // JSON jsonified service status Message message. -func (u healObjectMessage) JSON() string { +func (u healMessage) JSON() string { u.Status = "success" statusJSONBytes, e := json.Marshal(u) fatalIf(probe.NewError(e), "Unable to marshal into JSON.") @@ -98,10 +112,83 @@ func (u healObjectMessage) JSON() string { return string(statusJSONBytes) } +func healObjects(client *madmin.AdminClient, bucket, object string, isRecursive, isFake bool) { + // Search for objects that need healing + doneCh := make(chan struct{}) + healObjectsCh, e := client.ListObjectsHeal(bucket, object, isRecursive, doneCh) + fatalIf(probe.NewError(e), "Cannot list objects to be healed.") + + // Iterate over objects that need healing + for obj := range healObjectsCh { + // Continue to next object upon any error. + if obj.Err != nil { + errorIf(probe.NewError(obj.Err), "Cannot list objects to be healed.") + continue + } + // Heal object info is nil skip it, must be a directory. + if obj.HealObjectInfo == nil { + continue + } + + // Check the heal status, and call heal object API only when an object can be healed + switch healInfo := *obj.HealObjectInfo; healInfo.Status { + case madmin.CanHeal: + // Heal Object + if 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}) + case madmin.QuorumUnavailable: + errorIf(errDummy().Trace(), obj.Key+" cannot be healed until quorum is available.") + case madmin.Corrupted: + errorIf(errDummy().Trace(), obj.Key+" cannot be healed, not enough information.") + } + } +} + +func healUploads(client *madmin.AdminClient, bucket, object string, isRecursive, isFake bool) { + // Search for uploads that need healing + doneCh := make(chan struct{}) + healUploadsCh, e := client.ListUploadsHeal(bucket, object, isRecursive, doneCh) + fatalIf(probe.NewError(e), "Cannot list uploads to be healed.") + + // Iterate over uploads that need healing + for upload := range healUploadsCh { + // Continue to next upload upon any error. + if upload.Err != nil { + errorIf(probe.NewError(upload.Err), "Cannot list uploads to be healed.") + continue + } + // Heal upload info is nil skip it, must be a directory. + if upload.HealUploadInfo == nil { + continue + } + + // 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: + // Heal Upload + if 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}) + case madmin.QuorumUnavailable: + errorIf(errDummy().Trace(), upload.Key+" cannot be healed until quorum is available.") + case madmin.Corrupted: + errorIf(errDummy().Trace(), upload.Key+" cannot be healed, not enough information.") + } + } +} + // checkAdminHealSyntax - validate all the passed arguments func checkAdminHealSyntax(ctx *cli.Context) { if len(ctx.Args()) != 1 { - cli.ShowSubcommandHelp(ctx) + cli.HelpPrinter(ctx.App.Writer, adminHealHelpTemplate, ctx.App) os.Exit(1) } } @@ -117,6 +204,7 @@ func mainAdminHeal(ctx *cli.Context) error { aliasedURL := args.Get(0) isRecursive := ctx.Bool("recursive") + isIncomplete := ctx.Bool("incomplete") isFake := ctx.Bool("fake") console.SetColor("Heal", color.New(color.FgGreen, color.Bold)) @@ -124,7 +212,8 @@ func mainAdminHeal(ctx *cli.Context) error { // Create a new Minio Admin Client client, err := newAdminClient(aliasedURL) if err != nil { - return err.ToGoError() + fatalIf(err.Trace(aliasedURL), "Cannot initialize admin client.") + return nil } // Compute bucket and object from the aliased URL @@ -137,42 +226,18 @@ func mainAdminHeal(ctx *cli.Context) error { // Heal format if bucket is not specified and quit immediately if bucket == "" { e = client.HealFormat(isFake) - fatalIf(probe.NewError(e), "Cannot heal the specified storage format.") + fatalIf(probe.NewError(e), "Cannot heal the disks.") return nil } // Heal the specified bucket e = client.HealBucket(bucket, isFake) - fatalIf(probe.NewError(e), "Cannot repair bucket.") + fatalIf(probe.NewError(e), "Cannot heal bucket.") - // Search for objects that need healing - doneCh := make(chan struct{}) - healObjectsCh, e := client.ListObjectsHeal(bucket, object, isRecursive, doneCh) - fatalIf(probe.NewError(e), "Cannot list objects that need to be healed.") - - // Iterate over objects that need healing - for obj := range healObjectsCh { - // Return for any error - fatalIf(probe.NewError(obj.Err), "Cannot list objects that need to be healed.") - - // Check the heal status, and call heal object API only when an object can be healed - switch healInfo := *obj.HealObjectInfo; healInfo.Status { - case madmin.CanHeal: - // Heal Object - e = client.HealObject(bucket, obj.Key, isFake) - if e != nil { - errorIf(probe.NewError(e), "Cannot repair object: `"+obj.Key+"`") - continue - } - - // Print successful message - printMsg(healObjectMessage{Bucket: bucket, Object: obj}) - - case madmin.QuorumUnavailable: - errorIf(errDummy().Trace(), obj.Key+" cannot be healed until quorum is available.") - case madmin.Corrupted: - errorIf(errDummy().Trace(), obj.Key+" cannot be healed, not enough information.") - } + if !isIncomplete { + healObjects(client, bucket, object, isRecursive, isFake) + } else { + healUploads(client, bucket, object, isRecursive, isFake) } return nil diff --git a/cmd/admin-info.go b/cmd/admin-info.go new file mode 100644 index 00000000..8c26865e --- /dev/null +++ b/cmd/admin-info.go @@ -0,0 +1,217 @@ +/* + * Minio Client (C) 2016 Minio, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cmd + +import ( + "encoding/json" + "fmt" + "net/url" + + humanize "github.com/dustin/go-humanize" + "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 ( + adminInfoFlags = []cli.Flag{} +) + +var adminInfoCmd = cli.Command{ + Name: "info", + Usage: "Get Minio server information", + Action: mainAdminInfo, + Before: setGlobalsFromContext, + Flags: append(adminInfoFlags, globalFlags...), + CustomHelpTemplate: `NAME: + {{.HelpName}} - {{.Usage}} + +USAGE: + {{.HelpName}} ALIAS + +FLAGS: + {{range .VisibleFlags}}{{.}} + {{end}} +EXAMPLES: + 1. Get server information of the 'play' Minio server. + $ {{.HelpName}} play/ + +`, +} + +// backendType - indicates the type of backend storage +type backendType string + +const ( + fsType = backendType("FS") + erasureType = backendType("Erasure") +) + +// fsBackend contains specific FS storage information +type fsBackend struct { + Type backendType `json:"backendType"` +} + +// xlBackend contains specific erasure storage information +type xlBackend struct { + Type backendType `json:"backendType"` + OnlineDisks int `json:"onlineDisks"` + OfflineDisks int `json:"offlineDisks"` +} + +// backendStatus represents the overall information of all backend storage types +type backendStatus struct { + Total int64 `json:"total"` + Free int64 `json:"free"` + Backend interface{} `json:"backend"` +} + +// ServerInfo holds the whole server information that will be +// returned by ServerInfo API. +type ServerInfo struct { + StorageInfo backendStatus `json:"storage"` + ConnStats madmin.ServerConnStats `json:"network"` + Properties madmin.ServerProperties `json:"server"` +} + +// infoMessage container to hold service status information. +type infoMessage struct { + Status string `json:"status"` + Service bool `json:"service"` + *ServerInfo +} + +// String colorized service status message. +func (u infoMessage) String() (msg string) { + defer func() { + msg = console.Colorize("Info", msg) + }() + // When service is offline + if !u.Service { + msg = "The server is 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) + + sqsARNs := "" + for _, v := range u.ServerInfo.Properties.SQSARN { + sqsARNs += fmt.Sprintf("%s ", v) + } + if sqsARNs == "" { + sqsARNs = "" + } + msg += fmt.Sprintf(" SQS ARNs : %s\n", sqsARNs) + + 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 + msg += fmt.Sprintf(" Storage : Total %s, Free %s", + humanize.IBytes(uint64(u.StorageInfo.Total)), + humanize.IBytes(uint64(u.StorageInfo.Free)), + ) + if v, ok := u.ServerInfo.StorageInfo.Backend.(xlBackend); ok { + msg += fmt.Sprintf(", Online Disks: %d, Offline Disks: %d", v.OnlineDisks, v.OfflineDisks) + } + return +} + +// JSON jsonified service status Message message. +func (u infoMessage) JSON() string { + u.Status = "success" + statusJSONBytes, e := json.Marshal(u) + fatalIf(probe.NewError(e), "Unable to marshal into JSON.") + + return string(statusJSONBytes) +} + +// checkAdminInfoSyntax - validate all the passed arguments +func checkAdminInfoSyntax(ctx *cli.Context) { + if len(ctx.Args()) == 0 || len(ctx.Args()) > 2 { + cli.ShowCommandHelpAndExit(ctx, "info", 1) // last argument is exit code + } +} + +func mainAdminInfo(ctx *cli.Context) error { + // Validate service status syntax. + checkAdminInfoSyntax(ctx) + + console.SetColor("Info", color.New(color.FgGreen, color.Bold)) + + // Get the alias parameter from cli + args := ctx.Args() + aliasedURL := args.Get(0) + + // Create a new Minio Admin Client + 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() + + // 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) { + case *json.SyntaxError: + serviceOffline = true + case *url.Error: + if v.Timeout() { + serviceOffline = true + } + } + if serviceOffline { + printMsg(infoMessage{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, + } + } else { + storageInfo.Backend = fsBackend{ + Type: fsType, + } + } + + printMsg(infoMessage{ + Service: true, + ServerInfo: &ServerInfo{ + StorageInfo: storageInfo, + ConnStats: serverInfo.ConnStats, + Properties: serverInfo.Properties, + }, + }) + + return nil +} diff --git a/cmd/admin-lock-clear.go b/cmd/admin-lock-clear.go index 1d74fe0f..126173aa 100644 --- a/cmd/admin-lock-clear.go +++ b/cmd/admin-lock-clear.go @@ -31,37 +31,40 @@ var ( adminLockClearFlags = []cli.Flag{ cli.StringFlag{ Name: "duration, d", - Usage: "Only show locks that are hold for longer than NN[h|m|s].", + Usage: "Only clear locks held for longer than NN[h|m|s]", Value: "0s", }, + cli.BoolFlag{ + Name: "force", + Usage: "Force a clear lock operation", + }, } ) var adminLockClearCmd = cli.Command{ Name: "clear", - Usage: "Clear locks hold in a given Minio server", + Usage: "Clear locks held in a given Minio server", Before: setGlobalsFromContext, Action: mainAdminLockClear, Flags: append(adminLockClearFlags, globalFlags...), CustomHelpTemplate: `NAME: - mc admin lock {{.Name}} - {{.Usage}} + {{.HelpName}} - {{.Usage}} USAGE: - mc admin lock {{.Name}} ALIAS/BUCKET/PREFIX + {{.HelpName}} ALIAS/BUCKET/PREFIX FLAGS: - {{range .Flags}}{{.}} + {{range .VisibleFlags}}{{.}} {{end}} - EXAMPLES: - 1. Clear all locks hold by 'testbucket' in a Minio server represented by its alias 'play'. - $ mc admin lock {{.Name}} play/testbucket + 1. Clear all locks held on 'testbucket' in a Minio server with alias 'play'. + $ {{.HelpName}} --force play/testbucket - 2. Clear all 'testbucket' locks that are older than 15 minutes. - $ mc admin lock {{.Name}} --duration 15m play/testbucket/ + 2. Clear all 'testbucket' locks older than 15 minutes. + $ {{.HelpName}} --force --duration 15m play/testbucket/ - 3. Clear all locks hold by all objects under 'dir' prefix - $ mc admin lock {{.Name}} play/testbucket/dir/ + 3. Clear all locks held on all objects under prefix 'dir'. + $ {{.HelpName}} --force play/testbucket/dir/ `, } @@ -99,8 +102,17 @@ func (u lockClearMessage) JSON() string { // checkAdminLockClearSyntax - validate all the passed arguments func checkAdminLockClearSyntax(ctx *cli.Context) { if len(ctx.Args()) == 0 || len(ctx.Args()) > 2 { - cli.ShowCommandHelpAndExit(ctx, "clear", 1) // last argument is exit code + cli.ShowCommandHelpAndExit(ctx, "clear", 1) } + + if isForce := ctx.Bool("force"); isForce { + return + } + + fatalIf(errDummy().Trace(), + "Clearing locks requires --force option. This operation is "+ + "*IRREVERSIBLE*. Please review carefully before"+ + " performing this *DANGEROUS* operation.") } func mainAdminLockClear(ctx *cli.Context) error { diff --git a/cmd/admin-lock-list.go b/cmd/admin-lock-list.go index d6103843..a926c9c5 100644 --- a/cmd/admin-lock-list.go +++ b/cmd/admin-lock-list.go @@ -31,7 +31,7 @@ var ( adminLockListFlags = []cli.Flag{ cli.StringFlag{ Name: "duration, d", - Usage: "Only show locks that are hold for longer than NN[h|m|s].", + Usage: "Only show locks that are held for longer than NN[h|m|s]", Value: "24h", }, } @@ -39,29 +39,28 @@ var ( var adminLockListCmd = cli.Command{ Name: "list", - Usage: "Get the list of locks hold in a given Minio server", + Usage: "List locks held in a given Minio server", Action: mainAdminLockList, Before: setGlobalsFromContext, Flags: append(adminLockListFlags, globalFlags...), CustomHelpTemplate: `NAME: - mc admin lock {{.Name}} - {{.Usage}} + {{.HelpName}} - {{.Usage}} USAGE: - mc admin lock {{.Name}} ALIAS/BUCKET/PREFIX + {{.HelpName}} ALIAS/BUCKET/PREFIX FLAGS: - {{range .Flags}}{{.}} + {{range .VisibleFlags}}{{.}} {{end}} - EXAMPLES: - 1. List hold locks related to testbucket in a Minio server represented by its alias 'play'. - $ mc admin lock {{.Name}} play/testbucket/ + 1. List locks held on 'testbucket' in a Minio server with alias 'play'. + $ {{.HelpName}} play/testbucket/ - 2. List locks that are hold for more than 15 minutes. - $ mc admin lock {{.Name}} --duration 15m play/testbucket/ + 2. List locks held on 'testbucket' for more than 15 minutes. + $ {{.HelpName}} --duration 15m play/testbucket/ - 3. List locks hold by all objects under dir prefix - $ mc admin lock {{.Name}} play/testbucket/dir/ + 3. List locks held on all objects under prefix 'dir'. + $ {{.HelpName}} play/testbucket/dir/ `, } diff --git a/cmd/admin-lock.go b/cmd/admin-lock.go index 2e895e22..b188127e 100644 --- a/cmd/admin-lock.go +++ b/cmd/admin-lock.go @@ -24,7 +24,7 @@ var ( var adminLockCmd = cli.Command{ Name: "lock", - Usage: "Control locks in servers.", + Usage: "Control locks in servers", Action: mainAdminLock, Before: setGlobalsFromContext, Flags: append(adminLockFlags, globalFlags...), @@ -32,31 +32,12 @@ var adminLockCmd = cli.Command{ adminLockListCmd, adminLockClearCmd, }, - CustomHelpTemplate: `NAME: - {{.Name}} - {{.Usage}} - -USAGE: - {{.Name}} [FLAGS] COMMAND - -FLAGS: - {{range .Flags}}{{.}} - {{end}} -COMMANDS: - {{range .Commands}}{{join .Names ", "}}{{ "\t" }}{{.Usage}} - {{end}} -`, + HideHelpCommand: true, } // mainAdminLock is the handle for "mc admin lock" command. func mainAdminLock(ctx *cli.Context) error { - - if ctx.Args().First() != "" { // command help. - cli.ShowCommandHelp(ctx, ctx.Args().First()) - } else { - // command with Subcommands is an App. - cli.ShowAppHelp(ctx) - } - + cli.ShowCommandHelp(ctx, ctx.Args().First()) return nil // Sub-commands like "list", "unlock" have their own main. } diff --git a/cmd/admin-main.go b/cmd/admin-main.go index 60d065bd..73e64947 100644 --- a/cmd/admin-main.go +++ b/cmd/admin-main.go @@ -1,5 +1,5 @@ /* - * Minio Client (C) 2016 Minio, Inc. + * Minio Client (C) 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. @@ -23,41 +23,25 @@ var ( ) var adminCmd = cli.Command{ - Name: "admin", - Usage: "Manage Minio servers.", - Action: mainAdmin, - Before: setGlobalsFromContext, - Flags: append(adminFlags, globalFlags...), + Name: "admin", + Usage: "Manage Minio servers", + Action: mainAdmin, + HideHelpCommand: true, + Before: setGlobalsFromContext, + Flags: append(adminFlags, globalFlags...), Subcommands: []cli.Command{ adminServiceCmd, + adminInfoCmd, + adminCredsCmd, + adminConfigCmd, adminLockCmd, adminHealCmd, }, - CustomHelpTemplate: `NAME: - {{.Name}} - {{.Usage}} - -USAGE: - {{.Name}} [FLAGS] COMMAND - -FLAGS: - {{range .Flags}}{{.}} - {{end}} -COMMANDS: - {{range .Commands}}{{join .Names ", "}}{{ "\t" }}{{.Usage}} - {{end}} -`, } // mainAdmin is the handle for "mc admin" command. func mainAdmin(ctx *cli.Context) error { - - if ctx.Args().First() != "" { // command help. - cli.ShowCommandHelp(ctx, ctx.Args().First()) - } else { - // command with Subcommands is an App. - cli.ShowAppHelp(ctx) - } - + cli.ShowCommandHelp(ctx, ctx.Args().First()) return nil // Sub-commands like "service", "heal", "lock" have their own main. } diff --git a/cmd/admin-service-creds.go b/cmd/admin-password.go similarity index 52% rename from cmd/admin-service-creds.go rename to cmd/admin-password.go index b68d2bf1..e40f9b3d 100644 --- a/cmd/admin-service-creds.go +++ b/cmd/admin-password.go @@ -1,5 +1,5 @@ /* - * Minio Client (C) 2016 Minio, Inc. + * Minio Client (C) 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. @@ -22,54 +22,58 @@ import ( ) var ( - adminServiceCredsFlags = []cli.Flag{} + adminCredsFlags = []cli.Flag{} ) -var adminServiceCredsCmd = cli.Command{ - Name: "creds", - Usage: "Change credentials of a minio server or cluster", - Action: mainAdminServiceCreds, - Flags: append(adminServiceCredsFlags, globalFlags...), +const credsCmdName = "credentials" + +var adminCredsCmd = cli.Command{ + Name: credsCmdName, + Usage: "Change server access and secret keys", + Action: mainAdminCreds, + Flags: append(adminCredsFlags, globalFlags...), CustomHelpTemplate: `NAME: - mc admin service {{.Name}} - {{.Usage}} + {{.HelpName}} - {{.Usage}} USAGE: - mc admin service {{.Name}} ALIAS ACCESS_KEY SECRET_KEY + {{.HelpName}} ALIAS ACCESS_KEY SECRET_KEY FLAGS: - {{range .Flags}}{{.}} + {{range .VisibleFlags}}{{.}} {{end}} EXAMPLES: 1. Set new credentials of a Minio server represented by its alias 'play'. - $ mc admin service {{.Name}} play/ minio minio123 + $ {{.HelpName}} play/ minio minio123 + `, } -// checkAdminServiceCredsSyntax - validate all the passed arguments -func checkAdminServiceCredsSyntax(ctx *cli.Context) { +// checkAdminCredsSyntax - validate all the passed arguments +func checkAdminCredsSyntax(ctx *cli.Context) { if len(ctx.Args()) != 3 { - cli.ShowCommandHelpAndExit(ctx, "creds", 1) // last argument is exit code + cli.ShowCommandHelpAndExit(ctx, credsCmdName, 1) // last argument is exit code } } -func mainAdminServiceCreds(ctx *cli.Context) error { +func mainAdminCreds(ctx *cli.Context) error { setGlobalsFromContext(ctx) - checkAdminServiceCredsSyntax(ctx) + checkAdminCredsSyntax(ctx) // Get the alias parameter from cli args := ctx.Args() - aliasedURL := args.Get(0) - accessKey := args.Get(1) - secretKey := args.Get(2) + // TODO: if accessKey and secretKey are not supplied we should + // display the existing credentials. This needs GetCredentials + // support from Minio server. + accessKey, secretKey, aliasedURL := args.Get(0), args.Get(1), args.Get(2) // Create a new Minio Admin Client client, err := newAdminClient(aliasedURL) fatalIf(err, "Cannot get a configured admin connection.") - // Stop the specified Minio server - e := client.ServiceSetCredentials(accessKey, secretKey) + // Change the credentials of the specified Minio server + e := client.SetCredentials(accessKey, secretKey) fatalIf(probe.NewError(e), "Unable to set new credentials to '"+aliasedURL+"'") return nil diff --git a/cmd/admin-service-restart.go b/cmd/admin-service-restart.go index 6dd37ae4..6ba7d880 100644 --- a/cmd/admin-service-restart.go +++ b/cmd/admin-service-restart.go @@ -32,17 +32,18 @@ var adminServiceRestartCmd = cli.Command{ Before: setGlobalsFromContext, Flags: globalFlags, CustomHelpTemplate: `NAME: - mc admin service {{.Name}} - {{.Usage}} + {{.HelpName}} - {{.Usage}} USAGE: - mc admin service {{.Name}} ALIAS + {{.HelpName}} ALIAS FLAGS: - {{range .Flags}}{{.}} + {{range .VisibleFlags}}{{.}} {{end}} EXAMPLES: 1. Restart a Minio server represented by its alias 'play'. - $ mc admin service {{.Name}} play/ + $ {{.HelpName}} play/ + `, } @@ -54,7 +55,7 @@ type serviceRestartMessage struct { // String colorized make bucket message. func (s serviceRestartMessage) String() string { - return console.Colorize("ServiceRestart", "Server restarted ‘"+s.ServerURL+"’ successfully.") + return console.Colorize("ServiceRestart", "Restarted `"+s.ServerURL+"` successfully.") } // JSON jsonified make bucket message. diff --git a/cmd/admin-service-status.go b/cmd/admin-service-status.go index 3765625b..c61782ee 100644 --- a/cmd/admin-service-status.go +++ b/cmd/admin-service-status.go @@ -1,5 +1,5 @@ /* - * Minio Client (C) 2016 Minio, Inc. + * Minio Client (C) 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. @@ -20,12 +20,11 @@ import ( "encoding/json" "fmt" "net/url" + "time" - humanize "github.com/dustin/go-humanize" "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" ) @@ -40,58 +39,25 @@ var adminServiceStatusCmd = cli.Command{ Before: setGlobalsFromContext, Flags: append(adminServiceStatusFlags, globalFlags...), CustomHelpTemplate: `NAME: - mc admin service {{.Name}} - {{.Usage}} + {{.HelpName}} - {{.Usage}} USAGE: - mc admin service {{.Name}} ALIAS + {{.HelpName}} ALIAS FLAGS: - {{range .Flags}}{{.}} + {{range .VisibleFlags}}{{.}} {{end}} EXAMPLES: - 1. Get storage information of a Minio server represented by its alias 'play'. - $ mc admin service {{.Name}} play/ + 1. Check if the 'play' Minio server is online and show its uptime. + $ {{.HelpName}} play/ `, } -// backendType - indicates the type of backend storage -type backendType string - -const ( - fsType = backendType("FS") - xlType = backendType("XL") -) - -// fsBackend contains specific FS storage information -type fsBackend struct { - Type backendType `json:"backendType"` -} - -// xlBackend contains specific XL storage information -type xlBackend struct { - Type backendType `json:"backendType"` - OnlineDisks int `json:"onlineDisks"` - OfflineDisks int `json:"offlineDisks"` -} - -// backendStatus represents the overall information of all backend storage types -type backendStatus struct { - Total int64 `json:"total"` - Free int64 `json:"free"` - Backend interface{} `json:"backend"` -} - -type serverVersion struct { - Version string `json:"version"` - CommitID string `json:"commitID"` -} - // serviceStatusMessage container to hold service status information. type serviceStatusMessage struct { - Status string `json:"status"` - Service bool `json:"service"` - StorageInfo backendStatus `json:"storageInfo"` - ServerVersion serverVersion `json:"server"` + Status string `json:"status"` + Service bool `json:"service"` + Uptime time.Duration `json:"uptime"` } // String colorized service status message. @@ -104,14 +70,7 @@ func (u serviceStatusMessage) String() (msg string) { msg = "The server is offline." return } - // Online service, get backend information - msg = fmt.Sprintf("Total: %s, Free: %s.", - humanize.IBytes(uint64(u.StorageInfo.Total)), - humanize.IBytes(uint64(u.StorageInfo.Free)), - ) - if v, ok := u.StorageInfo.Backend.(xlBackend); ok { - msg += fmt.Sprintf(" Online Disks: %d, Offline Disks: %d.\n", v.OnlineDisks, v.OfflineDisks) - } + msg = fmt.Sprintf("Uptime: %s.", timeDurationToHumanizedDuration(u.Uptime)) return } @@ -146,7 +105,7 @@ func mainAdminServiceStatus(ctx *cli.Context) error { client, err := newAdminClient(aliasedURL) fatalIf(err, "Cannot get a configured admin connection.") - // Fetch the storage info of the specified Minio server + // Fetch the service status of the specified Minio server st, e := client.ServiceStatus() // Check the availability of the server: online or offline. A server is considered @@ -168,34 +127,10 @@ func mainAdminServiceStatus(ctx *cli.Context) error { // If the error is not nil and not unrecognizable, just print it and exit fatalIf(probe.NewError(e), "Cannot get service status.") - // Construct the version response - version := serverVersion{ - Version: st.ServerVersion.Version, - CommitID: st.ServerVersion.CommitID, - } - - // Construct the backend status - storageInfo := backendStatus{ - Total: st.StorageInfo.Total, - Free: st.StorageInfo.Free, - } - if st.StorageInfo.Backend.Type == madmin.XL { - storageInfo.Backend = xlBackend{ - Type: xlType, - OnlineDisks: st.StorageInfo.Backend.OnlineDisks, - OfflineDisks: st.StorageInfo.Backend.OfflineDisks, - } - } else { - storageInfo.Backend = fsBackend{ - Type: fsType, - } - } - // Print the whole response printMsg(serviceStatusMessage{ - Service: true, - StorageInfo: storageInfo, - ServerVersion: version, + Service: true, + Uptime: st.Uptime, }) return nil diff --git a/cmd/admin-service.go b/cmd/admin-service.go index 8e306b16..ad86e0eb 100644 --- a/cmd/admin-service.go +++ b/cmd/admin-service.go @@ -1,5 +1,5 @@ /* - * Minio Client (C) 2016 Minio, Inc. + * Minio Client (C) 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. @@ -19,41 +19,21 @@ package cmd import "github.com/minio/cli" var adminServiceCmd = cli.Command{ - Name: "service", - Usage: "Control servers.", - Action: mainAdminService, - Before: setGlobalsFromContext, - Flags: globalFlags, + Name: "service", + Usage: "Control servers", + Action: mainAdminService, + Before: setGlobalsFromContext, + Flags: globalFlags, + HideHelpCommand: true, Subcommands: []cli.Command{ adminServiceRestartCmd, - adminServiceCredsCmd, adminServiceStatusCmd, }, - CustomHelpTemplate: `NAME: - {{.Name}} - {{.Usage}} - -USAGE: - {{.Name}} [FLAGS] COMMAND - -FLAGS: - {{range .Flags}}{{.}} - {{end}} -COMMANDS: - {{range .Commands}}{{join .Names ", "}}{{ "\t" }}{{.Usage}} - {{end}} -`, } // mainAdmin is the handle for "mc admin service" command. func mainAdminService(ctx *cli.Context) error { - - if ctx.Args().First() != "" { // command help. - cli.ShowCommandHelp(ctx, ctx.Args().First()) - } else { - // command with Subcommands is an App. - cli.ShowAppHelp(ctx) - } - + cli.ShowCommandHelp(ctx, ctx.Args().First()) return nil - // Sub-commands like "status", "stop", "restart" have their own main. + // Sub-commands like "status", "restart" have their own main. } diff --git a/cmd/cat-main.go b/cmd/cat-main.go index 4f7213df..247a0eee 100644 --- a/cmd/cat-main.go +++ b/cmd/cat-main.go @@ -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. @@ -40,23 +40,23 @@ var catCmd = cli.Command{ Before: setGlobalsFromContext, Flags: append(catFlags, globalFlags...), CustomHelpTemplate: `NAME: - mc {{.Name}} - {{.Usage}} + {{.HelpName}} - {{.Usage}} USAGE: - mc {{.Name}} [FLAGS] SOURCE [SOURCE...] + {{.HelpName}} [FLAGS] SOURCE [SOURCE...] FLAGS: - {{range .Flags}}{{.}} + {{range .VisibleFlags}}{{.}} {{end}} EXAMPLES: 1. Stream an object from Amazon S3 cloud storage to mplayer standard input. - $ mc {{.Name}} s3/ferenginar/klingon_opera_aktuh_maylotah.ogg | mplayer - + $ {{.HelpName}} s3/ferenginar/klingon_opera_aktuh_maylotah.ogg | mplayer - 2. Concantenate contents of file1.txt and stdin to standard output. - $ mc {{.Name}} file1.txt - > file.txt + $ {{.HelpName}} file1.txt - > file.txt 3. Concantenate multiple files to one. - $ mc {{.Name}} part.* > complete.img + $ {{.HelpName}} part.* > complete.img `, } @@ -69,7 +69,7 @@ func checkCatSyntax(ctx *cli.Context) { } for _, arg := range args { if strings.HasPrefix(arg, "-") && len(arg) > 1 { - fatalIf(probe.NewError(errors.New("")), fmt.Sprintf("Unknown flag ‘%s’ passed.", arg)) + fatalIf(probe.NewError(errors.New("")), fmt.Sprintf("Unknown flag `%s` passed.", arg)) } } } @@ -151,7 +151,7 @@ func mainCat(ctx *cli.Context) error { return nil } - // if Args contain ‘-’, we need to preserve its order specially. + // if Args contain `-`, we need to preserve its order specially. args := []string(ctx.Args()) if ctx.Args().First() == "-" { for i, arg := range os.Args { @@ -165,7 +165,7 @@ func mainCat(ctx *cli.Context) error { // Convert arguments to URLs: expand alias, fix format. for _, url := range args { - fatalIf(catURL(url).Trace(url), "Unable to read from ‘"+url+"’.") + fatalIf(catURL(url).Trace(url), "Unable to read from `"+url+"`.") } return nil } diff --git a/cmd/client-errors.go b/cmd/client-errors.go index f088328b..2a22f2a3 100644 --- a/cmd/client-errors.go +++ b/cmd/client-errors.go @@ -27,7 +27,7 @@ type APINotImplemented struct { } func (e APINotImplemented) Error() string { - return "‘" + e.API + "’ is not supported for ‘" + e.APIType + "’." + return "`" + e.API + "` is not supported for `" + e.APIType + "`." } // GenericBucketError - generic bucket operations error @@ -39,14 +39,14 @@ type GenericBucketError struct { type BucketDoesNotExist GenericBucketError func (e BucketDoesNotExist) Error() string { - return "Bucket ‘" + e.Bucket + "’ does not exist." + return "Bucket `" + e.Bucket + "` does not exist." } // BucketExists - bucket exists. type BucketExists GenericBucketError func (e BucketExists) Error() string { - return "Bucket ‘" + e.Bucket + "’ exists." + return "Bucket `" + e.Bucket + "` exists." } // BucketNameEmpty - bucket name empty (http://goo.gl/wJlzDz) @@ -71,7 +71,7 @@ type ObjectAlreadyExists struct { } func (e ObjectAlreadyExists) Error() string { - return "Object ‘" + e.Object + "’ already exists." + return "Object `" + e.Object + "` already exists." } // ObjectAlreadyExistsAsDirectory - typed return for XMinioObjectExistsAsDirectory @@ -80,7 +80,7 @@ type ObjectAlreadyExistsAsDirectory struct { } func (e ObjectAlreadyExistsAsDirectory) Error() string { - return "Object ‘" + e.Object + "’ already exists as directory." + return "Object `" + e.Object + "` already exists as directory." } // ObjectOnGlacier - object is of storage class glacier. @@ -89,7 +89,7 @@ type ObjectOnGlacier struct { } func (e ObjectOnGlacier) Error() string { - return "Object ‘" + e.Object + "’ is on Glacier storage." + return "Object `" + e.Object + "` is on Glacier storage." } // BucketNameTopLevel - generic error @@ -108,35 +108,35 @@ type GenericFileError struct { type PathNotFound GenericFileError func (e PathNotFound) Error() string { - return "Requested file ‘" + e.Path + "’ not found" + return "Requested file `" + e.Path + "` not found" } // PathIsNotRegular (ENOTREG) - file is not a regular file. type PathIsNotRegular GenericFileError func (e PathIsNotRegular) Error() string { - return "Requested file ‘" + e.Path + "’ is not a regular file." + return "Requested file `" + e.Path + "` is not a regular file." } // PathInsufficientPermission (EPERM) - permission denied. type PathInsufficientPermission GenericFileError func (e PathInsufficientPermission) Error() string { - return "Insufficient permissions to access this file ‘" + e.Path + "’" + return "Insufficient permissions to access this file `" + e.Path + "`" } // BrokenSymlink (ENOTENT) - file has broken symlink. type BrokenSymlink GenericFileError func (e BrokenSymlink) Error() string { - return "Requested file ‘" + e.Path + "’ has broken symlink" + return "Requested file `" + e.Path + "` has broken symlink" } // TooManyLevelsSymlink (ELOOP) - file has too many levels of symlinks. type TooManyLevelsSymlink GenericFileError func (e TooManyLevelsSymlink) Error() string { - return "Requested file ‘" + e.Path + "’ has too many levels of symlinks" + return "Requested file `" + e.Path + "` has too many levels of symlinks" } // EmptyPath (EINVAL) - invalid argument. @@ -160,7 +160,7 @@ type UnexpectedShortWrite struct { } func (e UnexpectedShortWrite) Error() string { - msg := fmt.Sprintf("Wrote less data than requested. Expected ‘%d’ bytes, but only wrote ‘%d’ bytes.", e.InputSize, e.WriteSize) + msg := fmt.Sprintf("Wrote less data than requested. Expected `%d` bytes, but only wrote `%d` bytes.", e.InputSize, e.WriteSize) return msg } @@ -171,7 +171,7 @@ type UnexpectedEOF struct { } func (e UnexpectedEOF) Error() string { - msg := fmt.Sprintf("Input reader closed pre-maturely. Expected ‘%d’ bytes, but only received ‘%d’ bytes.", e.TotalSize, e.TotalWritten) + msg := fmt.Sprintf("Input reader closed pre-maturely. Expected `%d` bytes, but only received `%d` bytes.", e.TotalSize, e.TotalWritten) return msg } @@ -179,6 +179,6 @@ func (e UnexpectedEOF) Error() string { type UnexpectedExcessRead UnexpectedEOF func (e UnexpectedExcessRead) Error() string { - msg := fmt.Sprintf("Received excess data on input reader. Expected only ‘%d’ bytes, but received ‘%d’ bytes.", e.TotalSize, e.TotalWritten) + msg := fmt.Sprintf("Received excess data on input reader. Expected only `%d` bytes, but received `%d` bytes.", e.TotalSize, e.TotalWritten) return msg } diff --git a/cmd/client-fs.go b/cmd/client-fs.go index b077a1a2..da820946 100644 --- a/cmd/client-fs.go +++ b/cmd/client-fs.go @@ -46,7 +46,7 @@ const ( var ( // GOOS specific ignore list. ignoreFiles = map[string][]string{ "darwin": {"*.DS_Store"}, - "default": {"*.part.minio"}, + "default": {""}, } ) @@ -139,45 +139,39 @@ 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 { - select { - case event, ok := <-neventChan: - if !ok { - return - } - if isIgnoredFile(event.Path()) { + for event := range neventChan { + if isIgnoredFile(event.Path()) { + continue + } + var i os.FileInfo + if IsPutEvent(event.Event()) { + // Look for any writes, send a response to indicate a full copy. + var e error + i, e = os.Stat(event.Path()) + if e != nil { + if os.IsNotExist(e) { + continue + } + errorChan <- probe.NewError(e) continue } - var i os.FileInfo - if IsPutEvent(event.Event()) { - // Look for any writes, send a response to indicate a full copy. - var e error - i, e = os.Stat(event.Path()) - if e != nil { - if os.IsNotExist(e) { - continue - } - errorChan <- probe.NewError(e) - continue - } - if i.IsDir() { - // we want files - continue - } - eventChan <- Event{ - Time: time.Now().Format(timeFormatFS), - Size: i.Size(), - Path: event.Path(), - Client: f, - Type: EventCreate, - } - } else if IsDeleteEvent(event.Event()) { - eventChan <- Event{ - Time: time.Now().Format(timeFormatFS), - Path: event.Path(), - Client: f, - Type: EventRemove, - } + if i.IsDir() { + // we want files + continue + } + eventChan <- Event{ + Time: time.Now().Format(timeFormatFS), + Size: i.Size(), + Path: event.Path(), + Client: f, + Type: EventCreate, + } + } else if IsDeleteEvent(event.Event()) { + eventChan <- Event{ + Time: time.Now().Format(timeFormatFS), + Path: event.Path(), + Client: f, + Type: EventRemove, } } } @@ -222,14 +216,14 @@ func (f *fsClient) put(reader io.Reader, size int64, metadata map[string][]strin objectPartPath := objectPath + partSuffix if objectDir != "" { // Create any missing top level directories. - if e = os.MkdirAll(objectDir, 0700); e != nil { + if e = os.MkdirAll(objectDir, 0777); e != nil { err := f.toClientError(e, f.PathURL.Path) return 0, err.Trace(f.PathURL.Path) } } // If exists, open in append mode. If not create it the part file. - partFile, e := os.OpenFile(objectPartPath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600) + partFile, e := os.OpenFile(objectPartPath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0666) if e != nil { err := f.toClientError(e, f.PathURL.Path) return 0, err.Trace(f.PathURL.Path) @@ -403,7 +397,7 @@ func createFile(fpath string) (io.WriteCloser, error) { if e != nil && !os.IsNotExist(e) { return nil, e } - if e = os.MkdirAll(filepath.Dir(fpath), 0775); e != nil { + if e = os.MkdirAll(filepath.Dir(fpath), 0777); e != nil { return nil, e } file, e := os.Create(fpath) @@ -517,17 +511,41 @@ func (f *fsClient) Remove(isIncomplete bool, contentCh <-chan *clientContent) <- // List - list files and folders. func (f *fsClient) List(isRecursive, isIncomplete bool, showDir DirOpt) <-chan *clientContent { contentCh := make(chan *clientContent) + filteredCh := make(chan *clientContent) + if isRecursive { if showDir == DirNone { - go f.listRecursiveInRoutine(contentCh, isIncomplete) + go f.listRecursiveInRoutine(contentCh) } else { go f.listDirOpt(contentCh, isIncomplete, showDir) } } else { - go f.listInRoutine(contentCh, isIncomplete) + go f.listInRoutine(contentCh) } - return contentCh + // This function filters entries from any listing go routine + // created previously. If isIncomplete is activated, we will + // only show partly uploaded files, + go func() { + for c := range contentCh { + if isIncomplete { + if !strings.HasSuffix(c.URL.Path, partSuffix) { + continue + } + // Strip part suffix + c.URL.Path = strings.Split(c.URL.Path, partSuffix)[0] + } else { + if strings.HasSuffix(c.URL.Path, partSuffix) { + continue + } + } + // Send to filtered channel + filteredCh <- c + } + defer close(filteredCh) + }() + + return filteredCh } // byDirName implements sort.Interface. @@ -568,7 +586,7 @@ func readDir(dirname string) ([]os.FileInfo, error) { } // listPrefixes - list all files for any given prefix. -func (f *fsClient) listPrefixes(prefix string, contentCh chan<- *clientContent, incomplete bool) { +func (f *fsClient) listPrefixes(prefix string, contentCh chan<- *clientContent) { dirName := filepath.Dir(prefix) files, e := readDir(dirName) if e != nil { @@ -590,47 +608,12 @@ func (f *fsClient) listPrefixes(prefix string, contentCh chan<- *clientContent, st, e := os.Stat(file) if e != nil { if os.IsPermission(e) { - // On windows there are folder symlinks - // which are called junction files which - // carry special meaning on windows - // - which cannot be accessed with regular operations - if runtime.GOOS == "windows" { - newPath := filepath.Join(prefix, fi.Name()) - lfi, le := f.handleWindowsSymlinks(newPath) - if le != nil { - contentCh <- &clientContent{ - Err: le.Trace(newPath), - } - continue - } - if incomplete { - if !strings.HasSuffix(lfi.Name(), partSuffix) { - continue - } - } else { - if strings.HasSuffix(lfi.Name(), partSuffix) { - continue - } - } - pathURL.Path = filepath.Join(pathURL.Path, lfi.Name()) - contentCh <- &clientContent{ - URL: pathURL, - Time: lfi.ModTime(), - Size: lfi.Size(), - Type: lfi.Mode(), - Err: probe.NewError(PathInsufficientPermission{ - Path: pathURL.Path, - }), - } - continue - } else { - contentCh <- &clientContent{ - Err: probe.NewError(PathInsufficientPermission{ - Path: pathURL.Path, - }), - } - continue + contentCh <- &clientContent{ + Err: probe.NewError(PathInsufficientPermission{ + Path: pathURL.Path, + }), } + continue } if os.IsNotExist(e) { contentCh <- &clientContent{ @@ -648,15 +631,6 @@ func (f *fsClient) listPrefixes(prefix string, contentCh chan<- *clientContent, } } if strings.HasPrefix(file, prefix) { - if incomplete { - if !strings.HasSuffix(st.Name(), partSuffix) { - continue - } - } else { - if strings.HasSuffix(st.Name(), partSuffix) { - continue - } - } contentCh <- &clientContent{ URL: *newClientURL(file), Time: st.ModTime(), @@ -668,15 +642,6 @@ func (f *fsClient) listPrefixes(prefix string, contentCh chan<- *clientContent, } } if strings.HasPrefix(file, prefix) { - if incomplete { - if !strings.HasSuffix(fi.Name(), partSuffix) { - continue - } - } else { - if strings.HasSuffix(fi.Name(), partSuffix) { - continue - } - } contentCh <- &clientContent{ URL: *newClientURL(file), Time: fi.ModTime(), @@ -689,7 +654,7 @@ func (f *fsClient) listPrefixes(prefix string, contentCh chan<- *clientContent, return } -func (f *fsClient) listInRoutine(contentCh chan<- *clientContent, incomplete bool) { +func (f *fsClient) listInRoutine(contentCh chan<- *clientContent) { // close the channel when the function returns. defer close(contentCh) @@ -702,7 +667,7 @@ func (f *fsClient) listInRoutine(contentCh chan<- *clientContent, incomplete boo if _, ok := err.ToGoError().(PathNotFound); ok { // If file does not exist treat it like a prefix and list all prefixes if any. prefix := fpath - f.listPrefixes(prefix, contentCh, incomplete) + f.listPrefixes(prefix, contentCh) return } // For all other errors we return genuine error back to the caller. @@ -713,7 +678,7 @@ func (f *fsClient) listInRoutine(contentCh chan<- *clientContent, incomplete boo // Now if the file exists and doesn't end with a separator ('/') do not traverse it. // If the directory doesn't end with a separator, do not traverse it. if !strings.HasSuffix(fpath, string(pathURL.Separator)) && fst.Mode().IsDir() && fpath != "." { - f.listPrefixes(fpath, contentCh, incomplete) + f.listPrefixes(fpath, contentCh) return } @@ -730,44 +695,10 @@ func (f *fsClient) listInRoutine(contentCh chan<- *clientContent, incomplete boo if fi.Mode()&os.ModeSymlink == os.ModeSymlink { fi, e = os.Stat(filepath.Join(fpath, fi.Name())) if os.IsPermission(e) { - // On windows there are folder symlinks - // which are called junction files which - // carry special meaning on windows - // - which cannot be accessed with regular operations - if runtime.GOOS == "windows" { - newPath := filepath.Join(fpath, fi.Name()) - lfi, le := f.handleWindowsSymlinks(newPath) - if le != nil { - contentCh <- &clientContent{ - Err: le.Trace(newPath), - } - continue - } - if incomplete { - if !strings.HasSuffix(lfi.Name(), partSuffix) { - continue - } - } else { - if strings.HasSuffix(lfi.Name(), partSuffix) { - continue - } - } - pathURL = *f.PathURL - pathURL.Path = filepath.Join(pathURL.Path, lfi.Name()) - contentCh <- &clientContent{ - URL: pathURL, - Time: lfi.ModTime(), - Size: lfi.Size(), - Type: lfi.Mode(), - Err: probe.NewError(PathInsufficientPermission{Path: pathURL.Path}), - } - continue - } else { - contentCh <- &clientContent{ - Err: probe.NewError(PathInsufficientPermission{Path: pathURL.Path}), - } - continue + contentCh <- &clientContent{ + Err: probe.NewError(PathInsufficientPermission{Path: pathURL.Path}), } + continue } if os.IsNotExist(e) { contentCh <- &clientContent{ @@ -783,15 +714,6 @@ func (f *fsClient) listInRoutine(contentCh chan<- *clientContent, incomplete boo } } if fi.Mode().IsRegular() || fi.Mode().IsDir() { - if incomplete { - if !strings.HasSuffix(fi.Name(), partSuffix) { - continue - } - } else { - if strings.HasSuffix(fi.Name(), partSuffix) { - continue - } - } pathURL = *f.PathURL pathURL.Path = filepath.Join(pathURL.Path, fi.Name()) @@ -810,15 +732,6 @@ func (f *fsClient) listInRoutine(contentCh chan<- *clientContent, incomplete boo } } default: - if incomplete { - if !strings.HasSuffix(fst.Name(), partSuffix) { - return - } - } else { - if strings.HasSuffix(fst.Name(), partSuffix) { - return - } - } contentCh <- &clientContent{ URL: pathURL, Time: fst.ModTime(), @@ -877,17 +790,6 @@ func (f *fsClient) listDirOpt(contentCh chan *clientContent, isIncomplete bool, continue } - if isIncomplete { - // Ignore if file name does not end with partSuffix. - if !strings.HasSuffix(file.Name(), partSuffix) { - continue - } - - // Strip partSuffix - name = strings.SplitAfter(name, partSuffix)[0] - content.URL = *newClientURL(name) - } - contentCh <- &content } @@ -907,7 +809,7 @@ func (f *fsClient) listDirOpt(contentCh chan *clientContent, isIncomplete bool, } } -func (f *fsClient) listRecursiveInRoutine(contentCh chan *clientContent, incomplete bool) { +func (f *fsClient) listRecursiveInRoutine(contentCh chan *clientContent) { // close channels upon return. defer close(contentCh) var dirName string @@ -961,36 +863,8 @@ func (f *fsClient) listRecursiveInRoutine(contentCh chan *clientContent, incompl return nil } if os.IsPermission(e) { - if runtime.GOOS == "windows" { - lfi, le := f.handleWindowsSymlinks(fp) - if le != nil { - contentCh <- &clientContent{ - Err: le.Trace(fp), - } - return nil - } - pathURL = *f.PathURL - pathURL.Path = filepath.Join(pathURL.Path, dirName) - if incomplete { - if !strings.HasSuffix(lfi.Name(), partSuffix) { - return nil - } - } else { - if strings.HasSuffix(lfi.Name(), partSuffix) { - return nil - } - } - contentCh <- &clientContent{ - URL: pathURL, - Time: lfi.ModTime(), - Size: lfi.Size(), - Type: lfi.Mode(), - Err: probe.NewError(e), - } - } else { - contentCh <- &clientContent{ - Err: probe.NewError(PathInsufficientPermission{Path: fp}), - } + contentCh <- &clientContent{ + Err: probe.NewError(PathInsufficientPermission{Path: fp}), } return nil } @@ -1000,34 +874,6 @@ func (f *fsClient) listRecursiveInRoutine(contentCh chan *clientContent, incompl fi, e = os.Stat(fp) if e != nil { if os.IsPermission(e) { - if runtime.GOOS == "windows" { - lfi, le := f.handleWindowsSymlinks(fp) - if le != nil { - contentCh <- &clientContent{ - Err: le.Trace(fp), - } - return nil - } - pathURL = *f.PathURL - pathURL.Path = filepath.Join(pathURL.Path, dirName) - if incomplete { - if !strings.HasSuffix(lfi.Name(), partSuffix) { - return nil - } - } else { - if !strings.HasSuffix(lfi.Name(), partSuffix) { - return nil - } - } - contentCh <- &clientContent{ - URL: pathURL, - Time: lfi.ModTime(), - Size: lfi.Size(), - Type: lfi.Mode(), - Err: probe.NewError(e), - } - return nil - } contentCh <- &clientContent{ Err: probe.NewError(e), } @@ -1051,15 +897,6 @@ func (f *fsClient) listRecursiveInRoutine(contentCh chan *clientContent, incompl } } if fi.Mode().IsRegular() { - if incomplete { - if !strings.HasSuffix(fi.Name(), partSuffix) { - return nil - } - } else { - if strings.HasSuffix(fi.Name(), partSuffix) { - return nil - } - } contentCh <- &clientContent{ URL: *newClientURL(fp), Time: fi.ModTime(), @@ -1097,7 +934,7 @@ func (f *fsClient) listRecursiveInRoutine(contentCh chan *clientContent, incompl // MakeBucket - create a new bucket. func (f *fsClient) MakeBucket(region string) *probe.Error { - e := os.MkdirAll(f.PathURL.Path, 0775) + e := os.MkdirAll(f.PathURL.Path, 0777) if e != nil { return probe.NewError(e) } @@ -1193,47 +1030,38 @@ func (f *fsClient) toClientError(e error, fpath string) *probe.Error { return probe.NewError(e) } -// handle windows symlinks - eg: junction files. -func (f *fsClient) handleWindowsSymlinks(fpath string) (os.FileInfo, *probe.Error) { - // On windows there are directory symlinks which are called junction files. - // These files carry special meaning on windows they cannot be, - // accessed with regular operations. - file, e := os.Lstat(fpath) - if e != nil { - err := f.toClientError(e, fpath) - return nil, err.Trace(fpath) - } - return file, nil -} - // fsStat - wrapper function to get file stat. func (f *fsClient) fsStat(isIncomplete bool) (os.FileInfo, *probe.Error) { fpath := f.PathURL.Path + + // Check if the path corresponds to a directory and returns + // the successful result whether isIncomplete is specified or not. + st, e := os.Stat(fpath) + if e == nil && st.IsDir() { + return st, nil + } + if isIncomplete { fpath += partSuffix } + // Golang strips trailing / if you clean(..) or // EvalSymlinks(..). Adding '.' prevents it from doing so. if strings.HasSuffix(fpath, string(f.PathURL.Separator)) { fpath = fpath + "." } - fpath, e := filepath.EvalSymlinks(fpath) + fpath, e = filepath.EvalSymlinks(fpath) if e != nil { if os.IsPermission(e) { - if runtime.GOOS == "windows" { - return f.handleWindowsSymlinks(f.PathURL.Path) - } return nil, probe.NewError(PathInsufficientPermission{Path: f.PathURL.Path}) } err := f.toClientError(e, f.PathURL.Path) return nil, err.Trace(fpath) } - st, e := os.Stat(fpath) + + st, e = os.Stat(fpath) if e != nil { if os.IsPermission(e) { - if runtime.GOOS == "windows" { - return f.handleWindowsSymlinks(fpath) - } return nil, probe.NewError(PathInsufficientPermission{Path: f.PathURL.Path}) } if os.IsNotExist(e) { diff --git a/cmd/client-s3.go b/cmd/client-s3.go index c65c91de..a253a18e 100644 --- a/cmd/client-s3.go +++ b/cmd/client-s3.go @@ -1427,13 +1427,6 @@ func (c *s3Client) listRecursiveInRoutine(contentCh chan *clientContent) { return } for _, bucket := range buckets { - bucketURL := *c.targetURL - bucketURL.Path = c.joinPath(bucket.Name) - contentCh <- &clientContent{ - URL: bucketURL, - Type: os.ModeDir, - Time: bucket.CreationDate, - } isRecursive := true for object := range c.listObjectWrapper(bucket.Name, o, isRecursive, nil) { // Return error if we encountered glacier object and continue. diff --git a/cmd/client-url_test.go b/cmd/client-url_test.go index b1a26d93..9e72d038 100644 --- a/cmd/client-url_test.go +++ b/cmd/client-url_test.go @@ -45,7 +45,7 @@ func (s *TestSuite) TestURLJoinPath(c *C) { url = urlJoinPath(url1, url2) c.Assert(url, Equals, "http://s3.mycompany.io/dev/mybucket/bin/zgrep") - // Check if it strips URL2's tailing ‘/’ + // Check if it strips URL2's tailing `/` url1 = "http://s3.mycompany.io/dev" url2 = "mybucket/bin/" url = urlJoinPath(url1, url2) diff --git a/cmd/common-methods.go b/cmd/common-methods.go index a3c8fa26..1af4d6a1 100644 --- a/cmd/common-methods.go +++ b/cmd/common-methods.go @@ -25,28 +25,43 @@ import ( "github.com/minio/minio/pkg/probe" ) -// Check if the target URL represents folder. It may or may not exist yet. -func isTargetURLDir(targetURL string) bool { - _, targetContent, err := url2Stat(targetURL) +// Check if the passed URL represents a folder. It may or may not exist yet. +// If it exists, we can easily check if it is a folder, if it doesn't exist, +// we can guess if the url is a folder from how it looks. +func isAliasURLDir(aliasURL string) bool { + // If the target url exists, check if it is a directory + // and return immediately. + _, targetContent, err := url2Stat(aliasURL) if err == nil { return targetContent.Type.IsDir() } - _, aliasedTargetURL, _ := mustExpandAlias(targetURL) - if aliasedTargetURL == targetURL { - return false + + _, expandedURL, _ := mustExpandAlias(aliasURL) + + // Check if targetURL is an FS or S3 aliased url + if expandedURL == aliasURL { + // This is an FS url, check if the url has a separator at the end + return strings.HasSuffix(aliasURL, string(filepath.Separator)) } - // targetURL is an aliased path, continue guessing if the path - // is meant to point to a bucket or directory - pathURL := filepath.FromSlash(targetURL) - fields := strings.Split(pathURL, string(filepath.Separator)) + + // This is an S3 url, then: + // *) If alias format is specified, return false + // *) If alias/bucket is specified, return true + // *) If alias/bucket/prefix, check if prefix has + // has a trailing slash. + pathURL := filepath.ToSlash(aliasURL) + fields := strings.Split(pathURL, "/") switch len(fields) { + // Nothing or alias format case 0, 1: return false + // alias/bucket format case 2: return true - default: - return strings.HasSuffix(pathURL, string(filepath.Separator)) - } + } // default case.. + + // alias/bucket/prefix format + return strings.HasSuffix(pathURL, "/") } // getSource gets a reader from URL. diff --git a/cmd/config-fix.go b/cmd/config-fix.go index 87426420..0a63756b 100644 --- a/cmd/config-fix.go +++ b/cmd/config-fix.go @@ -60,7 +60,7 @@ func newBrokenConfigV3() *brokenConfigV3 { return conf } -// Fix config version ‘3’. Some v3 config files are written without +// Fix config version `3`. Some v3 config files are written without // proper hostConfig JSON tags. They may also contain unused ACL and // Access fields. Rewrite the hostConfig with proper fields using JSON // tags and drop the unused (ACL, Access) fields. @@ -102,12 +102,12 @@ func fixConfigV3() { if isMutated { mcNewConfigV3, e := quick.New(cfgV3) - fatalIf(probe.NewError(e), "Unable to initialize quick config for config version ‘3’.") + fatalIf(probe.NewError(e), "Unable to initialize quick config for config version `3`.") e = mcNewConfigV3.Save(mustGetMcConfigPath()) - fatalIf(probe.NewError(e), "Unable to save config version ‘3’.") + fatalIf(probe.NewError(e), "Unable to save config version `3`.") - console.Infof("Successfully fixed %s broken config for version ‘3’.\n", mustGetMcConfigPath()) + console.Infof("Successfully fixed %s broken config for version `3`.\n", mustGetMcConfigPath()) } } @@ -158,10 +158,10 @@ func fixConfigV6ForHosts() { if isMutated { // Save the new config back to the disk. mcCfgV6, e := quick.New(newCfgV6) - fatalIf(probe.NewError(e), "Unable to initialize quick config for config version ‘v6’.") + fatalIf(probe.NewError(e), "Unable to initialize quick config for config version `v6`.") e = mcCfgV6.Save(mustGetMcConfigPath()) - fatalIf(probe.NewError(e), "Unable to save config version ‘v6’.") + fatalIf(probe.NewError(e), "Unable to save config version `v6`.") } } @@ -189,7 +189,7 @@ func fixConfigV6() { for host, hostCfg := range config.Data().(*configV6).Hosts { if strings.Contains(host, "*") { fatalIf(errInvalidArgument(), - fmt.Sprintf("Glob style ‘*’ pattern matching is no longer supported. Please fix ‘%s’ entry manually.", host)) + fmt.Sprintf("Glob style `*` pattern matching is no longer supported. Please fix `%s` entry manually.", host)) } if strings.Contains(host, "*s3*") || strings.Contains(host, "*.s3*") { console.Infoln("Found glob url, replacing " + host + " with s3.amazonaws.com") @@ -237,6 +237,6 @@ func fixConfigV6() { e = newConf.Save(mustGetMcConfigPath()) fatalIf(probe.NewError(e).Trace(mustGetMcConfigPath()), "Unable to save newly fixed config path.") - console.Infof("Successfully fixed %s broken config for version ‘6’.\n", mustGetMcConfigPath()) + console.Infof("Successfully fixed %s broken config for version `6`.\n", mustGetMcConfigPath()) } } diff --git a/cmd/config-host-add.go b/cmd/config-host-add.go new file mode 100644 index 00000000..b1b4638e --- /dev/null +++ b/cmd/config-host-add.go @@ -0,0 +1,140 @@ +/* + * 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/fatih/color" + "github.com/minio/cli" + "github.com/minio/mc/pkg/console" +) + +var configHostAddCmd = cli.Command{ + Name: "add", + ShortName: "a", + Usage: "Add a new host to configuration file.", + Action: mainConfigHostAdd, + Before: setGlobalsFromContext, + Flags: globalFlags, + HideHelpCommand: true, + CustomHelpTemplate: `NAME: + {{.HelpName}} - {{.Usage}} + +USAGE: + {{.HelpName}} ALIAS URL ACCESS-KEY SECRET-KEY [API] + +FLAGS: + {{range .VisibleFlags}}{{.}} + {{end}} +EXAMPLES: + 1. Add Amazon S3 storage service under "mys3" alias. For security reasons turn off bash history momentarily. + $ set +o history + $ {{.HelpName}} mys3 https://s3.amazonaws.com \ + BKIKJAA5BMMU2RHO6IBB V8f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 + $ set -o history + + 2. Add Amazon S3 accelerated storage service under "mys3-accel" alias. For security reasons turn off bash history momentarily. + $ set +o history + $ {{.HelpName}} mys3-accel https://s3-accelerate.amazonaws.com \ + BKIKJAA5BMMU2RHO6IBB V8f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 + $ set -o history +`, +} + +// checkConfigHostAddSyntax - verifies input arguments to 'config host add'. +func checkConfigHostAddSyntax(ctx *cli.Context) { + args := ctx.Args() + argsNr := len(args) + if argsNr < 4 || argsNr > 5 { + fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...), + "Incorrect number of arguments for host add command.") + } + + alias := args.Get(0) + url := args.Get(1) + accessKey := args.Get(2) + secretKey := args.Get(3) + api := args.Get(4) + + if !isValidAlias(alias) { + fatalIf(errDummy().Trace(alias), "Invalid alias `"+alias+"`.") + } + + if !isValidHostURL(url) { + fatalIf(errDummy().Trace(url), + "Invalid URL `"+url+"`.") + } + + if !isValidAccessKey(accessKey) { + fatalIf(errInvalidArgument().Trace(accessKey), + "Invalid access key `"+accessKey+"`.") + } + + if !isValidSecretKey(secretKey) { + fatalIf(errInvalidArgument().Trace(secretKey), + "Invalid secret key `"+secretKey+"`.") + } + + if api != "" && !isValidAPI(api) { // Empty value set to default "S3v4". + fatalIf(errInvalidArgument().Trace(api), + "Unrecognized API signature. Valid options are `[S3v4, S3v2]`.") + } +} + +// addHost - add a host config. +func addHost(alias string, hostCfgV8 hostConfigV8) { + mcCfgV8, err := loadMcConfig() + fatalIf(err.Trace(globalMCConfigVersion), "Unable to load config `"+mustGetMcConfigPath()+"`.") + + // Add new host. + mcCfgV8.Hosts[alias] = hostCfgV8 + + err = saveMcConfig(mcCfgV8) + fatalIf(err.Trace(alias), "Unable to update hosts in config version `"+mustGetMcConfigPath()+"`.") + + printMsg(hostMessage{ + op: "add", + Alias: alias, + URL: hostCfgV8.URL, + AccessKey: hostCfgV8.AccessKey, + SecretKey: hostCfgV8.SecretKey, + API: hostCfgV8.API, + }) +} + +func mainConfigHostAdd(ctx *cli.Context) error { + checkConfigHostAddSyntax(ctx) + + console.SetColor("HostMessage", color.New(color.FgGreen)) + + args := ctx.Args() + alias := args.Get(0) + url := args.Get(1) + accessKey := args.Get(2) + secretKey := args.Get(3) + api := args.Get(4) + if api == "" { + api = "S3v4" + } + hostCfg := hostConfigV8{ + URL: url, + AccessKey: accessKey, + SecretKey: secretKey, + API: api, + } + addHost(alias, hostCfg) // Add a host with specified credentials. + return nil +} diff --git a/cmd/config-host-list.go b/cmd/config-host-list.go new file mode 100644 index 00000000..2cb6cf91 --- /dev/null +++ b/cmd/config-host-list.go @@ -0,0 +1,147 @@ +/* + * 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" + "sort" + + "github.com/fatih/color" + "github.com/minio/cli" + "github.com/minio/mc/pkg/console" +) + +var configHostListCmd = cli.Command{ + Name: "list", + ShortName: "ls", + Usage: "Lists hosts in configuration file.", + Action: mainConfigHostList, + Before: setGlobalsFromContext, + Flags: globalFlags, + HideHelpCommand: true, + CustomHelpTemplate: `NAME: + {{.HelpName}} - {{.Usage}} + +USAGE: + {{.HelpName}} [ALIAS] + +FLAGS: + {{range .VisibleFlags}}{{.}} + {{end}} +EXAMPLES: + 1. List all hosts. + $ {{.HelpName}} + + 2. List a specific host. + $ {{.HelpName}} s3 +`, +} + +// Input argument validator.. +func checkConfigHostListSyntax(ctx *cli.Context) { + args := ctx.Args() + + if len(ctx.Args()) > 1 { + fatalIf(errInvalidArgument().Trace(args...), + "Incorrect number of arguments to list hosts.") + } + + if args.Get(0) != "" { + if !isValidAlias(args.Get(0)) { + fatalIf(errDummy().Trace(args.Get(0)), + "Invalid alias `"+args.Get(0)+"`.") + } + } +} + +func mainConfigHostList(ctx *cli.Context) error { + checkConfigHostListSyntax(ctx) + + // Additional command speific theme customization. + console.SetColor("HostMessage", color.New(color.FgGreen)) + console.SetColor("Alias", color.New(color.FgCyan, color.Bold)) + console.SetColor("URL", color.New(color.FgCyan)) + console.SetColor("AccessKey", color.New(color.FgBlue)) + console.SetColor("SecretKey", color.New(color.FgBlue)) + console.SetColor("API", color.New(color.FgYellow)) + + args := ctx.Args() + listHosts(args.Get(0)) // List all configured hosts. + return nil +} + +// Prints all the hosts. +func printHosts(hosts ...hostMessage) { + var maxAlias = 0 + for _, host := range hosts { + if len(host.Alias) > maxAlias { + maxAlias = len(host.Alias) + } + } + for _, host := range hosts { + // Format properly for alignment based on alias length. + host.Alias = fmt.Sprintf("%-*.*s", maxAlias, maxAlias, host.Alias) + printMsg(host) + } +} + +// byAlias is a collection satisfying sort.Interface +type byAlias []hostMessage + +func (d byAlias) Len() int { return len(d) } +func (d byAlias) Swap(i, j int) { d[i], d[j] = d[j], d[i] } +func (d byAlias) Less(i, j int) bool { return d[i].Alias < d[j].Alias } + +// listHosts - list all host URLs or a requested host. +func listHosts(alias string) { + conf, err := loadMcConfig() + fatalIf(err.Trace(globalMCConfigVersion), "Unable to load config version `"+globalMCConfigVersion+"`.") + + // If specific alias is requested, look for it and print. + 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, + }) + return + } + fatalIf(errInvalidAliasedURL(alias), "No such alias `"+alias+"` found") + } + + 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, + }) + } + + // Sort hosts by alias names lexically. + sort.Sort(byAlias(hosts)) + + // Display all the hosts. + printHosts(hosts...) +} diff --git a/cmd/config-host-main.go b/cmd/config-host-main.go deleted file mode 100644 index 336f3e12..00000000 --- a/cmd/config-host-main.go +++ /dev/null @@ -1,308 +0,0 @@ -/* - * Minio Client (C) 2015 Minio, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package cmd - -import ( - "encoding/json" - "fmt" - "sort" - "strings" - - "github.com/fatih/color" - "github.com/minio/cli" - "github.com/minio/mc/pkg/console" - "github.com/minio/minio/pkg/probe" -) - -var ( - configHostFlags = []cli.Flag{} -) - -var configHostCmd = cli.Command{ - Name: "host", - Usage: "List, modify and remove hosts in configuration file.", - Flags: append(configHostFlags, globalFlags...), - Action: mainConfigHost, - Before: setGlobalsFromContext, - CustomHelpTemplate: `NAME: - mc config {{.Name}} - {{.Usage}} - -USAGE: - mc config {{.Name}} OPERATION - -OPERATION: - add ALIAS URL ACCESS-KEY SECRET-KEY [API] - remove ALIAS - list - -FLAGS: - {{range .Flags}}{{.}} - {{end}} -EXAMPLES: - 1. Add Amazon S3 storage service under "myphotos" alias. For security reasons turn off bash history momentarily. - $ set +o history - $ mc config {{.Name}} add myphotos https://s3.amazonaws.com \ - BKIKJAA5BMMU2RHO6IBB V8f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 - $ set -o history - - 2. Add Amazon S3 accelerated storage service under "accel" alias. For security reasons turn off bash history momentarily. - $ set +o history - $ mc config {{.Name}} add accel https://s3-accelerate.amazonaws.com \ - BKIKJAA5BMMU2RHO6IBB V8f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 - $ set -o history - - 3. List all hosts. - $ mc config {{.Name}} list - - 4. Remove "goodisk" config. - $ mc config {{.Name}} remove goodisk -`, -} - -// 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"` -} - -// String colorized host message -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)) - } - return message - case "remove": - return console.Colorize("HostMessage", "Removed ‘"+h.Alias+"’ successfully.") - case "add": - return console.Colorize("HostMessage", "Added ‘"+h.Alias+"’ successfully.") - default: - return "" - } -} - -// JSON jsonified host message -func (h hostMessage) JSON() string { - h.Status = "success" - jsonMessageBytes, e := json.Marshal(h) - fatalIf(probe.NewError(e), "Unable to marshal into JSON.") - - return string(jsonMessageBytes) -} - -// Validate command-line input args. -func checkConfigHostSyntax(ctx *cli.Context) { - // show help if nothing is set - if !ctx.Args().Present() { - cli.ShowCommandHelpAndExit(ctx, "host", 1) // last argument is exit code - } - - switch strings.TrimSpace(ctx.Args().First()) { - case "add": - checkConfigHostAddSyntax(ctx) - case "remove": - checkConfigHostRemoveSyntax(ctx) - case "list": - default: - cli.ShowCommandHelpAndExit(ctx, "host", 1) // last argument is exit code - } -} - -// checkConfigHostAddSyntax - verifies input arguments to 'config host add'. -func checkConfigHostAddSyntax(ctx *cli.Context) { - tailArgs := ctx.Args().Tail() - tailsArgsNr := len(tailArgs) - if tailsArgsNr < 4 || tailsArgsNr > 5 { - fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...), - "Incorrect number of arguments for host add command.") - } - - alias := tailArgs.Get(0) - url := tailArgs.Get(1) - accessKey := tailArgs.Get(2) - secretKey := tailArgs.Get(3) - api := tailArgs.Get(4) - - if !isValidAlias(alias) { - fatalIf(errDummy().Trace(alias), "Invalid alias ‘"+alias+"’.") - } - - if !isValidHostURL(url) { - fatalIf(errDummy().Trace(url), - "Invalid URL ‘"+url+"’.") - } - - if !isValidAccessKey(accessKey) { - fatalIf(errInvalidArgument().Trace(accessKey), - "Invalid access key ‘"+accessKey+"’.") - } - - if !isValidSecretKey(secretKey) { - fatalIf(errInvalidArgument().Trace(secretKey), - "Invalid secret key ‘"+secretKey+"’.") - } - - if api != "" && !isValidAPI(api) { // Empty value set to default "S3v4". - fatalIf(errInvalidArgument().Trace(api), - "Unrecognized API signature. Valid options are ‘[S3v4, S3v2]’.") - } -} - -// checkConfigHostRemoveSyntax - verifies input arguments to 'config host remove'. -func checkConfigHostRemoveSyntax(ctx *cli.Context) { - tailArgs := ctx.Args().Tail() - - if len(ctx.Args().Tail()) != 1 { - fatalIf(errInvalidArgument().Trace(tailArgs...), - "Incorrect number of arguments for remove host command.") - } - - if !isValidAlias(tailArgs.Get(0)) { - fatalIf(errDummy().Trace(tailArgs.Get(0)), - "Invalid alias ‘"+tailArgs.Get(0)+"’.") - } -} - -func mainConfigHost(ctx *cli.Context) error { - - // check 'config host' cli arguments. - checkConfigHostSyntax(ctx) - - // Additional command speific theme customization. - console.SetColor("HostMessage", color.New(color.FgGreen)) - console.SetColor("Alias", color.New(color.FgCyan, color.Bold)) - console.SetColor("URL", color.New(color.FgCyan)) - console.SetColor("AccessKey", color.New(color.FgBlue)) - console.SetColor("SecretKey", color.New(color.FgBlue)) - console.SetColor("API", color.New(color.FgYellow)) - - cmd := ctx.Args().First() - args := ctx.Args().Tail() - - // Switch case through commands. - switch strings.TrimSpace(cmd) { - case "add": - alias := args.Get(0) - url := args.Get(1) - accessKey := args.Get(2) - secretKey := args.Get(3) - api := args.Get(4) - if api == "" { - api = "S3v4" - } - hostCfg := hostConfigV8{ - URL: url, - AccessKey: accessKey, - SecretKey: secretKey, - API: api, - } - addHost(alias, hostCfg) // Add a host with specified credentials. - case "remove": - alias := args.Get(0) - removeHost(alias) // Remove a host. - case "list": - listHosts() // List all configured hosts. - } - return nil -} - -// addHost - add a host config. -func addHost(alias string, hostCfgV8 hostConfigV8) { - mcCfgV8, err := loadMcConfig() - fatalIf(err.Trace(globalMCConfigVersion), "Unable to load config ‘"+mustGetMcConfigPath()+"’.") - - // Add new host. - mcCfgV8.Hosts[alias] = hostCfgV8 - - err = saveMcConfig(mcCfgV8) - fatalIf(err.Trace(alias), "Unable to update hosts in config version ‘"+mustGetMcConfigPath()+"’.") - - printMsg(hostMessage{ - op: "add", - Alias: alias, - URL: hostCfgV8.URL, - AccessKey: hostCfgV8.AccessKey, - SecretKey: hostCfgV8.SecretKey, - API: hostCfgV8.API, - }) -} - -// removeHost - removes a host. -func removeHost(alias string) { - conf, err := loadMcConfig() - fatalIf(err.Trace(globalMCConfigVersion), "Unable to load config version ‘"+globalMCConfigVersion+"’.") - - // Remove host. - delete(conf.Hosts, alias) - - err = saveMcConfig(conf) - fatalIf(err.Trace(alias), "Unable to save deleted hosts in config version ‘"+globalMCConfigVersion+"’.") - - printMsg(hostMessage{op: "remove", Alias: alias}) -} - -//byAlias is a collection satisfying sort.Interface -type byAlias []hostMessage - -func (d byAlias) Len() int { return len(d) } -func (d byAlias) Swap(i, j int) { d[i], d[j] = d[j], d[i] } -func (d byAlias) Less(i, j int) bool { return d[i].Alias < d[j].Alias } - -// listHosts - list all host URLs. -func listHosts() { - conf, err := loadMcConfig() - fatalIf(err.Trace(globalMCConfigVersion), "Unable to load config version ‘"+globalMCConfigVersion+"’.") - - var maxAlias = 0 - for k := range conf.Hosts { - if len(k) > maxAlias { - maxAlias = len(k) - } - } - - 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, - }) - } - - // Sort hosts by alias names lexically. - sort.Sort(byAlias(hosts)) - - // Display all the hosts. - for _, host := range hosts { - // Format properly for alignment based on alias length. - host.Alias = fmt.Sprintf("%-*.*s", maxAlias, maxAlias, host.Alias) - printMsg(host) - } -} diff --git a/cmd/config-host-remove.go b/cmd/config-host-remove.go new file mode 100644 index 00000000..080fe7ae --- /dev/null +++ b/cmd/config-host-remove.go @@ -0,0 +1,88 @@ +/* + * 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/fatih/color" + "github.com/minio/cli" + "github.com/minio/mc/pkg/console" +) + +var configHostRemoveCmd = cli.Command{ + Name: "remove", + ShortName: "rm", + Usage: "Remove a host from configuration file.", + Action: mainConfigHostRemove, + Before: setGlobalsFromContext, + Flags: globalFlags, + HideHelpCommand: true, + CustomHelpTemplate: `NAME: + {{.HelpName}} - {{.Usage}} + +USAGE: + {{.HelpName}} ALIAS + +FLAGS: + {{range .VisibleFlags}}{{.}} + {{end}} +EXAMPLES: + 1. Remove "goodisk" from config. + $ {{.HelpName}} goodisk + +`, +} + +// checkConfigHostRemoveSyntax - verifies input arguments to 'config host remove'. +func checkConfigHostRemoveSyntax(ctx *cli.Context) { + args := ctx.Args() + + if len(ctx.Args()) != 1 { + fatalIf(errInvalidArgument().Trace(args...), + "Incorrect number of arguments for remove host command.") + } + + if !isValidAlias(args.Get(0)) { + fatalIf(errDummy().Trace(args.Get(0)), + "Invalid alias `"+args.Get(0)+"`.") + } +} + +// mainConfigHost is the handle for "mc config host rm" command. +func mainConfigHostRemove(ctx *cli.Context) error { + checkConfigHostRemoveSyntax(ctx) + + console.SetColor("HostMessage", color.New(color.FgGreen)) + + args := ctx.Args() + alias := args.Get(0) + removeHost(alias) // Remove a host. + return nil +} + +// removeHost - removes a host. +func removeHost(alias string) { + conf, err := loadMcConfig() + fatalIf(err.Trace(globalMCConfigVersion), "Unable to load config version `"+globalMCConfigVersion+"`.") + + // Remove host. + delete(conf.Hosts, alias) + + err = saveMcConfig(conf) + fatalIf(err.Trace(alias), "Unable to save deleted hosts in config version `"+globalMCConfigVersion+"`.") + + printMsg(hostMessage{op: "remove", Alias: alias}) +} diff --git a/cmd/config-host.go b/cmd/config-host.go new file mode 100644 index 00000000..443dbcb6 --- /dev/null +++ b/cmd/config-host.go @@ -0,0 +1,88 @@ +/* + * 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" + + "github.com/minio/cli" + "github.com/minio/mc/pkg/console" + "github.com/minio/minio/pkg/probe" +) + +var configHostCmd = cli.Command{ + Name: "host", + Usage: "List, modify and remove hosts in configuration file.", + Action: mainConfigHost, + Before: setGlobalsFromContext, + Flags: globalFlags, + Subcommands: []cli.Command{ + configHostAddCmd, + configHostRemoveCmd, + configHostListCmd, + }, + HideHelpCommand: true, +} + +// mainConfigHost is the handle for "mc config host" command. +func mainConfigHost(ctx *cli.Context) error { + cli.ShowCommandHelp(ctx, ctx.Args().First()) + return nil + // Sub-commands like "remove", "list" have their own main. +} + +// 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"` +} + +// String colorized host message +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)) + } + return message + case "remove": + return console.Colorize("HostMessage", "Removed `"+h.Alias+"` successfully.") + case "add": + return console.Colorize("HostMessage", "Added `"+h.Alias+"` successfully.") + default: + return "" + } +} + +// JSON jsonified host message +func (h hostMessage) JSON() string { + h.Status = "success" + jsonMessageBytes, e := json.Marshal(h) + fatalIf(probe.NewError(e), "Unable to marshal into JSON.") + + return string(jsonMessageBytes) +} diff --git a/cmd/config-main.go b/cmd/config-main.go index 1e5aff6c..b7502025 100644 --- a/cmd/config-main.go +++ b/cmd/config-main.go @@ -34,39 +34,20 @@ var ( ) var configCmd = cli.Command{ - Name: "config", - Usage: "Manage mc configuration file.", - Action: mainConfig, - Before: setGlobalsFromContext, - Flags: append(configFlags, globalFlags...), + Name: "config", + Usage: "Manage mc configuration file.", + Action: mainConfig, + Before: setGlobalsFromContext, + HideHelpCommand: true, + Flags: append(configFlags, globalFlags...), Subcommands: []cli.Command{ configHostCmd, }, - CustomHelpTemplate: `NAME: - {{.Name}} - {{.Usage}} - -USAGE: - {{.Name}} [FLAGS] COMMAND - -FLAGS: - {{range .Flags}}{{.}} - {{end}} -COMMANDS: - {{range .Commands}}{{join .Names ", "}}{{ "\t" }}{{.Usage}} - {{end}} -`, } // mainConfig is the handle for "mc config" command. provides sub-commands which write configuration data in json format to config file. func mainConfig(ctx *cli.Context) error { - - if ctx.Args().First() != "" { // command help. - cli.ShowCommandHelp(ctx, ctx.Args().First()) - } else { - // command with Subcommands is an App. - cli.ShowAppHelp(ctx) - } - + cli.ShowCommandHelp(ctx, ctx.Args().First()) return nil // Sub-commands like "host" and "alias" have their own main. } diff --git a/cmd/config-migrate.go b/cmd/config-migrate.go index ae5e15fe..f2c20e8d 100644 --- a/cmd/config-migrate.go +++ b/cmd/config-migrate.go @@ -51,7 +51,7 @@ func migrateConfigV1ToV101() { return } mcCfgV1, e := quick.Load(mustGetMcConfigPath(), newConfigV1()) - fatalIf(probe.NewError(e), "Unable to load config version ‘1’.") + fatalIf(probe.NewError(e), "Unable to load config version `1`.") // If loaded config version does not match 1.0.0, we do nothing. if mcCfgV1.Version() != "1.0.0" { @@ -95,20 +95,20 @@ func migrateConfigV1ToV101() { // Save the new config back to the disk. mcCfgV101, e := quick.New(cfgV101) - fatalIf(probe.NewError(e), "Unable to initialize quick config for config version ‘1.0.1’.") + fatalIf(probe.NewError(e), "Unable to initialize quick config for config version `1.0.1`.") e = mcCfgV101.Save(mustGetMcConfigPath()) - fatalIf(probe.NewError(e), "Unable to save config version ‘1.0.1’.") + fatalIf(probe.NewError(e), "Unable to save config version `1.0.1`.") - console.Infof("Successfully migrated %s from version ‘1.0.0’ to version ‘1.0.1’.\n", mustGetMcConfigPath()) + console.Infof("Successfully migrated %s from version `1.0.0` to version `1.0.1`.\n", mustGetMcConfigPath()) } -// Migrate from config ‘1.0.1’ to ‘2’. Drop semantic versioning and move to integer versioning. No other changes. +// Migrate from config `1.0.1` to `2`. Drop semantic versioning and move to integer versioning. No other changes. func migrateConfigV101ToV2() { if !isMcConfigExists() { return } mcCfgV101, e := quick.Load(mustGetMcConfigPath(), newConfigV101()) - fatalIf(probe.NewError(e), "Unable to load config version ‘1.0.1’.") + fatalIf(probe.NewError(e), "Unable to load config version `1.0.1`.") // update to newer version if mcCfgV101.Version() != "1.0.1" { @@ -131,15 +131,15 @@ func migrateConfigV101ToV2() { } mcCfgV2, e := quick.New(cfgV2) - fatalIf(probe.NewError(e), "Unable to initialize quick config for config version ‘2’.") + fatalIf(probe.NewError(e), "Unable to initialize quick config for config version `2`.") e = mcCfgV2.Save(mustGetMcConfigPath()) - fatalIf(probe.NewError(e), "Unable to save config version ‘2’.") + fatalIf(probe.NewError(e), "Unable to save config version `2`.") - console.Infof("Successfully migrated %s from version ‘1.0.1’ to version ‘2’.\n", mustGetMcConfigPath()) + console.Infof("Successfully migrated %s from version `1.0.1` to version `2`.\n", mustGetMcConfigPath()) } -// Migrate from config ‘2’ to ‘3’. Use ‘-’ separated names for +// Migrate from config `2` to `3`. Use `-` separated names for // hostConfig using struct json tags. func migrateConfigV2ToV3() { if !isMcConfigExists() { @@ -171,15 +171,15 @@ func migrateConfigV2ToV3() { } mcNewCfgV3, e := quick.New(cfgV3) - fatalIf(probe.NewError(e), "Unable to initialize quick config for config version ‘3’.") + fatalIf(probe.NewError(e), "Unable to initialize quick config for config version `3`.") e = mcNewCfgV3.Save(mustGetMcConfigPath()) - fatalIf(probe.NewError(e), "Unable to save config version ‘3’.") + fatalIf(probe.NewError(e), "Unable to save config version `3`.") - console.Infof("Successfully migrated %s from version ‘2’ to version ‘3’.\n", mustGetMcConfigPath()) + console.Infof("Successfully migrated %s from version `2` to version `3`.\n", mustGetMcConfigPath()) } -// Migrate from config version ‘3’ to ‘4’. Introduce API Signature +// Migrate from config version `3` to `4`. Introduce API Signature // field in host config. Also Use JavaScript notation for field names. func migrateConfigV3ToV4() { if !isMcConfigExists() { @@ -210,16 +210,16 @@ func migrateConfigV3ToV4() { } mcNewCfgV4, e := quick.New(cfgV4) - fatalIf(probe.NewError(e), "Unable to initialize quick config for config version ‘4’.") + fatalIf(probe.NewError(e), "Unable to initialize quick config for config version `4`.") e = mcNewCfgV4.Save(mustGetMcConfigPath()) - fatalIf(probe.NewError(e), "Unable to save config version ‘4’.") + fatalIf(probe.NewError(e), "Unable to save config version `4`.") - console.Infof("Successfully migrated %s from version ‘3’ to version ‘4’.\n", mustGetMcConfigPath()) + console.Infof("Successfully migrated %s from version `3` to version `4`.\n", mustGetMcConfigPath()) } -// Migrate config version ‘4’ to ‘5’. Rename hostConfigV4.Signature -> hostConfigV5.API. +// Migrate config version `4` to `5`. Rename hostConfigV4.Signature -> hostConfigV5.API. func migrateConfigV4ToV5() { if !isMcConfigExists() { return @@ -245,15 +245,15 @@ func migrateConfigV4ToV5() { } mcNewCfgV5, e := quick.New(cfgV5) - fatalIf(probe.NewError(e), "Unable to initialize quick config for config version ‘5’.") + fatalIf(probe.NewError(e), "Unable to initialize quick config for config version `5`.") e = mcNewCfgV5.Save(mustGetMcConfigPath()) - fatalIf(probe.NewError(e), "Unable to save config version ‘5’.") + fatalIf(probe.NewError(e), "Unable to save config version `5`.") - console.Infof("Successfully migrated %s from version ‘4’ to version ‘5’.\n", mustGetMcConfigPath()) + console.Infof("Successfully migrated %s from version `4` to version `5`.\n", mustGetMcConfigPath()) } -// Migrate config version ‘5’ to ‘6’. Add google cloud storage servers +// Migrate config version `5` to `6`. Add google cloud storage servers // to host config. Also remove "." from s3 aws glob rule. func migrateConfigV5ToV6() { if !isMcConfigExists() { @@ -311,15 +311,15 @@ func migrateConfigV5ToV6() { } mcNewCfgV6, e := quick.New(cfgV6) - fatalIf(probe.NewError(e), "Unable to initialize quick config for config version ‘6’.") + fatalIf(probe.NewError(e), "Unable to initialize quick config for config version `6`.") e = mcNewCfgV6.Save(mustGetMcConfigPath()) - fatalIf(probe.NewError(e), "Unable to save config version ‘6’.") + fatalIf(probe.NewError(e), "Unable to save config version `6`.") - console.Infof("Successfully migrated %s from version ‘5’ to version ‘6’.\n", mustGetMcConfigPath()) + console.Infof("Successfully migrated %s from version `5` to version `6`.\n", mustGetMcConfigPath()) } -// Migrate config version ‘6’ to ‘7'. Remove alias map and introduce +// Migrate config version `6` to `7'. Remove alias map and introduce // named Host config. Also no more glob match for host config entries. func migrateConfigV6ToV7() { if !isMcConfigExists() { @@ -390,15 +390,15 @@ func migrateConfigV6ToV7() { // Load default settings. cfgV7.loadDefaults() mcNewCfgV7, e := quick.New(cfgV7) - fatalIf(probe.NewError(e), "Unable to initialize quick config for config version ‘7’.") + fatalIf(probe.NewError(e), "Unable to initialize quick config for config version `7`.") e = mcNewCfgV7.Save(mustGetMcConfigPath()) - fatalIf(probe.NewError(e), "Unable to save config version ‘7’.") + fatalIf(probe.NewError(e), "Unable to save config version `7`.") - console.Infof("Successfully migrated %s from version ‘6’ to version ‘7’.\n", mustGetMcConfigPath()) + console.Infof("Successfully migrated %s from version `6` to version `7`.\n", mustGetMcConfigPath()) } -// Migrate config version ‘7’ to ‘8'. Remove hosts +// Migrate config version `7` to `8'. Remove hosts // 'play.minio.io:9002' and 'dl.minio.io:9000'. func migrateConfigV7ToV8() { if !isMcConfigExists() { @@ -429,10 +429,10 @@ func migrateConfigV7ToV8() { // Load default settings. cfgV8.loadDefaults() mcNewCfgV8, e := quick.New(cfgV8) - fatalIf(probe.NewError(e), "Unable to initialize quick config for config version ‘8’.") + fatalIf(probe.NewError(e), "Unable to initialize quick config for config version `8`.") e = mcNewCfgV8.Save(mustGetMcConfigPath()) - fatalIf(probe.NewError(e), "Unable to save config version ‘8’.") + fatalIf(probe.NewError(e), "Unable to save config version `8`.") - console.Infof("Successfully migrated %s from version ‘7’ to version ‘8’.\n", mustGetMcConfigPath()) + console.Infof("Successfully migrated %s from version `7` to version `8`.\n", mustGetMcConfigPath()) } diff --git a/cmd/config-utils.go b/cmd/config-utils.go index fd33bb68..4aa18ac7 100644 --- a/cmd/config-utils.go +++ b/cmd/config-utils.go @@ -24,7 +24,7 @@ const ( accessKeyMinLen = 5 accessKeyMaxLen = 20 secretKeyMinLen = 8 - secretKeyMaxLen = 40 + secretKeyMaxLen = 100 ) // isValidAccessKey - validate access key for right length. diff --git a/cmd/cp-main.go b/cmd/cp-main.go index 2bf1bf14..d4d07fac 100644 --- a/cmd/cp-main.go +++ b/cmd/cp-main.go @@ -52,32 +52,33 @@ var cpCmd = cli.Command{ Before: setGlobalsFromContext, Flags: append(cpFlags, globalFlags...), CustomHelpTemplate: `NAME: - mc {{.Name}} - {{.Usage}} + {{.HelpName}} - {{.Usage}} USAGE: - mc {{.Name}} [FLAGS] SOURCE [SOURCE...] TARGET + {{.HelpName}} [FLAGS] SOURCE [SOURCE...] TARGET FLAGS: - {{range .Flags}}{{.}} + {{range .VisibleFlags}}{{.}} {{end}} EXAMPLES: 1. Copy a list of objects from local file system to Amazon S3 cloud storage. - $ mc {{.Name}} Music/*.ogg s3/jukebox/ + $ {{.HelpName}} Music/*.ogg s3/jukebox/ 2. Copy a folder recursively from Minio cloud storage to Amazon S3 cloud storage. - $ mc {{.Name}} --recursive play/mybucket/burningman2011/ s3/mybucket/ + $ {{.HelpName}} --recursive play/mybucket/burningman2011/ s3/mybucket/ 3. Copy multiple local folders recursively to Minio cloud storage. - $ mc {{.Name}} --recursive backup/2014/ backup/2015/ play/archive/ + $ {{.HelpName}} --recursive backup/2014/ backup/2015/ play/archive/ 4. Copy a bucket recursively from aliased Amazon S3 cloud storage to local filesystem on Windows. - $ mc {{.Name}} --recursive s3\documents\2014\ C:\Backups\2014 + $ {{.HelpName}} --recursive s3\documents\2014\ C:\Backups\2014 5. Copy an object with name containing unicode characters to Amazon S3 cloud storage. - $ mc {{.Name}} 本語 s3/andoria/ + $ {{.HelpName}} 本語 s3/andoria/ 6. Copy a local folder with space separated characters to Amazon S3 cloud storage. - $ mc {{.Name}} --recursive 'workdir/documents/May 2014/' s3/miniocloud + $ {{.HelpName}} --recursive 'workdir/documents/May 2014/' s3/miniocloud + `, } @@ -93,7 +94,7 @@ type copyMessage struct { // String colorized copy message func (c copyMessage) String() string { - return console.Colorize("Copy", fmt.Sprintf("‘%s’ -> ‘%s’", c.Source, c.Target)) + return console.Colorize("Copy", fmt.Sprintf("`%s` -> `%s`", c.Source, c.Target)) } // JSON jsonified copy message @@ -208,7 +209,7 @@ func doPrepareCopyURLs(session *sessionV8, trapCh <-chan bool) { console.Eraseline() } if strings.Contains(cpURLs.Error.ToGoError().Error(), " is a folder.") { - errorIf(cpURLs.Error.Trace(), "Folder cannot be copied. Please use ‘...’ suffix.") + errorIf(cpURLs.Error.Trace(), "Folder cannot be copied. Please use `...` suffix.") } else { errorIf(cpURLs.Error.Trace(), "Unable to prepare URL for copying.") } @@ -296,7 +297,7 @@ func doCopySession(session *sessionV8) { console.Eraseline() } errorIf(cpURLs.Error.Trace(cpURLs.SourceContent.URL.String()), - fmt.Sprintf("Failed to copy ‘%s’.", cpURLs.SourceContent.URL.String())) + fmt.Sprintf("Failed to copy `%s`.", cpURLs.SourceContent.URL.String())) if isErrIgnored(cpURLs.Error) { continue } @@ -341,13 +342,7 @@ func doCopySession(session *sessionV8) { } } else { if !globalJSON && globalQuiet { - accntStat := accntReader.Stat() - cpStatMessage := copyStatMessage{ - Total: accntStat.Total, - Transferred: accntStat.Transferred, - Speed: accntStat.Speed, - } - console.Println(console.Colorize("Copy", cpStatMessage.String())) + console.Println(console.Colorize("Copy", accntReader.Stat().String())) } } } diff --git a/cmd/cp-url-syntax.go b/cmd/cp-url-syntax.go index af434dfb..61a9edae 100644 --- a/cmd/cp-url-syntax.go +++ b/cmd/cp-url-syntax.go @@ -50,7 +50,7 @@ func checkCopySyntax(ctx *cli.Context) { url := newClientURL(tgtURL) if url.Host != "" { if url.Path == string(url.Separator) { - fatalIf(errInvalidArgument().Trace(), fmt.Sprintf("Target ‘%s’ does not contain bucket name.", tgtURL)) + fatalIf(errInvalidArgument().Trace(), fmt.Sprintf("Target `%s` does not contain bucket name.", tgtURL)) } } @@ -81,10 +81,10 @@ func checkCopySyntaxTypeA(srcURLs []string, tgtURL string) { } srcURL := srcURLs[0] _, srcContent, err := url2Stat(srcURL) - fatalIf(err.Trace(srcURL), "Unable to stat source ‘"+srcURL+"’.") + fatalIf(err.Trace(srcURL), "Unable to stat source `"+srcURL+"`.") if !srcContent.Type.IsRegular() { - fatalIf(errInvalidArgument().Trace(), "Source ‘"+srcURL+"’ is not a file.") + fatalIf(errInvalidArgument().Trace(), "Source `"+srcURL+"` is not a file.") } } @@ -96,16 +96,16 @@ func checkCopySyntaxTypeB(srcURLs []string, tgtURL string) { } srcURL := srcURLs[0] _, srcContent, err := url2Stat(srcURL) - fatalIf(err.Trace(srcURL), "Unable to stat source ‘"+srcURL+"’.") + fatalIf(err.Trace(srcURL), "Unable to stat source `"+srcURL+"`.") if !srcContent.Type.IsRegular() { - fatalIf(errInvalidArgument().Trace(srcURL), "Source ‘"+srcURL+"’ is not a file.") + fatalIf(errInvalidArgument().Trace(srcURL), "Source `"+srcURL+"` is not a file.") } // Check target. if _, tgtContent, err := url2Stat(tgtURL); err == nil { if !tgtContent.Type.IsDir() { - fatalIf(errInvalidArgument().Trace(tgtURL), "Target ‘"+tgtURL+"’ is not a folder.") + fatalIf(errInvalidArgument().Trace(tgtURL), "Target `"+tgtURL+"` is not a folder.") } } } @@ -122,7 +122,7 @@ func checkCopySyntaxTypeC(srcURLs []string, tgtURL string, isRecursive bool) { // incomplete uploads are not necessary for copy operation, no need to verify for them. isIncomplete := false if err != nil && !isURLPrefixExists(srcURL, isIncomplete) { - fatalIf(err.Trace(srcURL), "Unable to stat source ‘"+srcURL+"’.") + fatalIf(err.Trace(srcURL), "Unable to stat source `"+srcURL+"`.") } if srcContent.Type.IsDir() && !isRecursive { @@ -132,7 +132,7 @@ func checkCopySyntaxTypeC(srcURLs []string, tgtURL string, isRecursive bool) { // Check target. if _, tgtContent, err := url2Stat(tgtURL); err == nil { if !tgtContent.Type.IsDir() { - fatalIf(errInvalidArgument().Trace(tgtURL), "Target ‘"+tgtURL+"’ is not a folder.") + fatalIf(errInvalidArgument().Trace(tgtURL), "Target `"+tgtURL+"` is not a folder.") } } } @@ -143,7 +143,7 @@ func checkCopySyntaxTypeD(srcURLs []string, tgtURL string) { // Check target if it is a dir if _, tgtContent, err := url2Stat(tgtURL); err == nil { if !tgtContent.Type.IsDir() { - fatalIf(errInvalidArgument().Trace(tgtURL), "Target ‘"+tgtURL+"’ is not a folder.") + fatalIf(errInvalidArgument().Trace(tgtURL), "Target `"+tgtURL+"` is not a folder.") } } } diff --git a/cmd/cp-url.go b/cmd/cp-url.go index baa48289..1f41125a 100644 --- a/cmd/cp-url.go +++ b/cmd/cp-url.go @@ -65,7 +65,7 @@ func guessCopyURLType(sourceURLs []string, targetURL string, isRecursive bool) ( } // If target is a folder, it is Type B. - if isTargetURLDir(targetURL) { + if isAliasURLDir(targetURL) { return copyURLsTypeB, nil } // else Type A. @@ -73,7 +73,7 @@ func guessCopyURLType(sourceURLs []string, targetURL string, isRecursive bool) ( } // Multiple source args and target is a folder. It is Type D. - if isTargetURLDir(targetURL) { + if isAliasURLDir(targetURL) { return copyURLsTypeD, nil } diff --git a/cmd/diff-main.go b/cmd/diff-main.go index b6f313bb..64953d94 100644 --- a/cmd/diff-main.go +++ b/cmd/diff-main.go @@ -41,23 +41,30 @@ var diffCmd = cli.Command{ Before: setGlobalsFromContext, Flags: append(diffFlags, globalFlags...), CustomHelpTemplate: `NAME: - mc {{.Name}} - {{.Usage}} + {{.HelpName}} - {{.Usage}} USAGE: - mc {{.Name}} [FLAGS] FIRST SECOND + {{.HelpName}} [FLAGS] FIRST SECOND FLAGS: - {{range .Flags}}{{.}} + {{range .VisibleFlags}}{{.}} {{end}} DESCRIPTION: - {{.Description}} + {{.Description}} + +OUTPUT: + Differences between source and destination are represented by mark notations with following meaning: + > - indicates file should be copied. + < - indicates file should be deleted. + ! - indicates file differs in size or type. EXAMPLES: - 1. Compare a local folder with a folder on Amazon S3 cloud storage. - $ mc {{.Name}} ~/Photos s3/MyBucket/Photos + 1. Compare a local folder with a folder on Amazon S3 cloud storage. + $ {{.HelpName}} ~/Photos s3/MyBucket/Photos + + 2. Compare two different folders on a local filesystem. + $ {{.HelpName}} ~/Photos /Media/Backup/Photos - 2. Compare two different folders on a local filesystem. - $ mc {{.Name}} ~/Photos /Media/Backup/Photos `, } @@ -77,20 +84,16 @@ func (d diffMessage) String() string { msg := "" switch d.Diff { case differInFirst: - msg = console.Colorize("DiffMessage", - "‘"+d.FirstURL+"’") + console.Colorize("DiffOnlyInFirst", " - only in first.") + msg = console.Colorize("DiffOnlyInFirst", "< "+d.FirstURL) case differInSecond: - msg = console.Colorize("DiffMessage", - "‘"+d.SecondURL+"’") + console.Colorize("DiffOnlyInSecond", " - only in second.") + msg = console.Colorize("DiffOnlyInSecond", "> "+d.SecondURL) case differInType: - msg = console.Colorize("DiffMessage", - "‘"+d.FirstURL+"’"+" and "+"‘"+d.SecondURL+"’") + console.Colorize("DiffType", " - differ in type.") + msg = console.Colorize("DiffType", "! "+d.SecondURL) case differInSize: - msg = console.Colorize("DiffMessage", - "‘"+d.FirstURL+"’"+" and "+"‘"+d.SecondURL+"’") + console.Colorize("DiffSize", " - differ in size.") + msg = console.Colorize("DiffSize", "! "+d.SecondURL) default: fatalIf(errDummy().Trace(d.FirstURL, d.SecondURL), - "Unhandled difference between ‘"+d.FirstURL+"’ and ‘"+d.SecondURL+"’.") + "Unhandled difference between `"+d.FirstURL+"` and `"+d.SecondURL+"`.") } return msg @@ -101,7 +104,7 @@ func (d diffMessage) JSON() string { d.Status = "success" diffJSONBytes, e := json.Marshal(d) fatalIf(probe.NewError(e), - "Unable to marshal diff message ‘"+d.FirstURL+"’, ‘"+d.SecondURL+"’ and ‘"+string(d.Diff)+"’.") + "Unable to marshal diff message `"+d.FirstURL+"`, `"+d.SecondURL+"` and `"+string(d.Diff)+"`.") return string(diffJSONBytes) } @@ -128,7 +131,7 @@ func checkDiffSyntax(ctx *cli.Context) { // Verify if its a directory. if !firstContent.Type.IsDir() { - fatalIf(errInvalidArgument().Trace(firstURL), fmt.Sprintf("‘%s’ is not a folder.", firstURL)) + fatalIf(errInvalidArgument().Trace(firstURL), fmt.Sprintf("`%s` is not a folder.", firstURL)) } // Verify if secondURL is accessible. @@ -139,7 +142,7 @@ func checkDiffSyntax(ctx *cli.Context) { // Verify if its a directory. if !secondContent.Type.IsDir() { - fatalIf(errInvalidArgument().Trace(secondURL), fmt.Sprintf("‘%s’ is not a folder.", secondURL)) + fatalIf(errInvalidArgument().Trace(secondURL), fmt.Sprintf("`%s` is not a folder.", secondURL)) } } @@ -173,6 +176,10 @@ func doDiffMain(firstURL, secondURL string) error { // Diff first and second urls. for diffMsg := range objectDifference(firstClient, secondClient, firstURL, secondURL) { + if diffMsg.Error != nil { + errorIf(diffMsg.Error, "Unable to calculate objects difference.") + break + } printMsg(diffMsg) } @@ -187,10 +194,10 @@ func mainDiff(ctx *cli.Context) error { // Additional command specific theme customization. console.SetColor("DiffMessage", color.New(color.FgGreen, color.Bold)) - console.SetColor("DiffOnlyInFirst", color.New(color.FgRed, color.Bold)) - console.SetColor("DiffType", color.New(color.FgYellow, color.Bold)) - console.SetColor("DiffSize", color.New(color.FgMagenta, color.Bold)) - console.SetColor("DiffTime", color.New(color.FgYellow, color.Bold)) + console.SetColor("DiffOnlyInFirst", color.New(color.FgRed)) + console.SetColor("DiffOnlyInSecond", color.New(color.FgGreen)) + console.SetColor("DiffType", color.New(color.FgMagenta)) + console.SetColor("DiffSize", color.New(color.FgYellow, color.Bold)) URLs := ctx.Args() firstURL := URLs.Get(0) diff --git a/cmd/difference.go b/cmd/difference.go index 05b562aa..a7f09530 100644 --- a/cmd/difference.go +++ b/cmd/difference.go @@ -17,7 +17,6 @@ package cmd import ( - "fmt" "strings" "unicode/utf8" @@ -51,9 +50,17 @@ func (d differType) String() string { return "unknown" } +func objectDifference(sourceClnt, targetClnt Client, sourceURL, targetURL string) (diffCh chan diffMessage) { + return difference(sourceClnt, targetClnt, sourceURL, targetURL, true, false, DirNone) +} + +func dirDifference(sourceClnt, targetClnt Client, sourceURL, targetURL string) (diffCh chan diffMessage) { + return difference(sourceClnt, targetClnt, sourceURL, targetURL, false, true, DirFirst) +} + // objectDifference function finds the difference between all objects // recursively in sorted order from source and target. -func objectDifference(sourceClnt, targetClnt Client, sourceURL, targetURL string) (diffCh chan diffMessage) { +func difference(sourceClnt, targetClnt Client, sourceURL, targetURL string, isRecursive, returnSimilar bool, dirOpt DirOpt) (diffCh chan diffMessage) { var ( srcEOF, tgtEOF bool srcOk, tgtOk bool @@ -62,10 +69,9 @@ func objectDifference(sourceClnt, targetClnt Client, sourceURL, targetURL string ) // Set default values for listing. - isRecursive := true // recursive is always true for diff. isIncomplete := false // we will not compare any incomplete objects. - srcCh := sourceClnt.List(isRecursive, isIncomplete, DirNone) - tgtCh := targetClnt.List(isRecursive, isIncomplete, DirNone) + srcCh := sourceClnt.List(isRecursive, isIncomplete, dirOpt) + tgtCh := targetClnt.List(isRecursive, isIncomplete, dirOpt) diffCh = make(chan diffMessage, 1000) @@ -74,24 +80,25 @@ func objectDifference(sourceClnt, targetClnt Client, sourceURL, targetURL string srcCtnt, srcOk = <-srcCh tgtCtnt, tgtOk = <-tgtCh + defer close(diffCh) + for { srcEOF = !srcOk tgtEOF = !tgtOk // No objects from source AND target: Finish if srcEOF && tgtEOF { - close(diffCh) break } if !srcEOF && srcCtnt.Err != nil { - errorIf(srcCtnt.Err.Trace(sourceURL, targetURL), fmt.Sprintf("Failed on '%s'", sourceURL)) + diffCh <- diffMessage{Error: srcCtnt.Err.Trace(sourceURL, targetURL)} srcCtnt, srcOk = <-srcCh continue } if !tgtEOF && tgtCtnt.Err != nil { - errorIf(tgtCtnt.Err.Trace(sourceURL, targetURL), fmt.Sprintf("Failed on '%s'", targetURL)) + diffCh <- diffMessage{Error: tgtCtnt.Err.Trace(sourceURL, targetURL)} tgtCtnt, tgtOk = <-tgtCh continue } @@ -125,13 +132,13 @@ func objectDifference(sourceClnt, targetClnt Client, sourceURL, targetURL string expected := urlJoinPath(targetURL, tgtSuffix) if !utf8.ValidString(srcSuffix) { // Error. Keys must be valid UTF-8. - errorIf(errInvalidSource(current), fmt.Sprintf("'%s' is not valid UTF-8", srcSuffix)) + diffCh <- diffMessage{Error: errInvalidSource(current).Trace()} srcCtnt, srcOk = <-srcCh continue } if !utf8.ValidString(tgtSuffix) { // Error. Keys must be valid UTF-8. - errorIf(errInvalidTarget(expected), fmt.Sprintf("'%s' is not valid UTF-8", tgtSuffix)) + diffCh <- diffMessage{Error: errInvalidTarget(expected).Trace()} tgtCtnt, tgtOk = <-tgtCh continue } @@ -175,6 +182,15 @@ func objectDifference(sourceClnt, targetClnt Client, sourceURL, targetURL string } } // No differ + if returnSimilar { + diffCh <- diffMessage{ + FirstURL: srcCtnt.URL.String(), + SecondURL: tgtCtnt.URL.String(), + Diff: differInNone, + firstContent: srcCtnt, + secondContent: tgtCtnt, + } + } srcCtnt, srcOk = <-srcCh tgtCtnt, tgtOk = <-tgtCh continue diff --git a/cmd/events-add.go b/cmd/events-add.go index e508a1e4..764258ea 100644 --- a/cmd/events-add.go +++ b/cmd/events-add.go @@ -51,19 +51,21 @@ var eventsAddCmd = cli.Command{ Before: setGlobalsFromContext, Flags: append(eventsAddFlags, globalFlags...), CustomHelpTemplate: `NAME: - mc events {{.Name}} - {{.Usage}} + {{.HelpName}} - {{.Usage}} USAGE: - mc events {{.Name}} ALIAS/BUCKET ARN [FLAGS] + {{.HelpName}} ALIAS/BUCKET ARN [FLAGS] FLAGS: - {{range .Flags}}{{.}} + {{range .VisibleFlags}}{{.}} {{end}} EXAMPLES: 1. Enable bucket notification with a specific arn - $ mc events {{.Name}} myminio/mybucket arn:aws:sqs:us-west-2:444455556666:your-queue + $ {{.HelpName}} myminio/mybucket arn:aws:sqs:us-west-2:444455556666:your-queue + 2. Enable bucket notification with filters parameters - $ mc events {{.Name}} 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 --prefix photos/ --suffix .jpg + `, } diff --git a/cmd/events-list.go b/cmd/events-list.go index 344b3056..f7d3a56a 100644 --- a/cmd/events-list.go +++ b/cmd/events-list.go @@ -37,19 +37,21 @@ var eventsListCmd = cli.Command{ Before: setGlobalsFromContext, Flags: append(eventsListFlags, globalFlags...), CustomHelpTemplate: `NAME: - mc events {{.Name}} - {{.Usage}} + {{.HelpName}} - {{.Usage}} USAGE: - mc events {{.Name}} ALIAS/BUCKET ARN [FLAGS] + {{.HelpName}} ALIAS/BUCKET ARN [FLAGS] FLAGS: - {{range .Flags}}{{.}} + {{range .VisibleFlags}}{{.}} {{end}} EXAMPLES: 1. List notification configurations associated to a specific arn - $ mc events {{.Name}} myminio/mybucket arn:aws:sqs:us-west-2:444455556666:your-queue + $ {{.HelpName}} myminio/mybucket arn:aws:sqs:us-west-2:444455556666:your-queue + 2. List all notification configurations - $ mc events {{.Name}} s3/mybucket + $ {{.HelpName}} s3/mybucket + `, } diff --git a/cmd/events-main.go b/cmd/events-main.go index 4afc08ed..4b44207b 100644 --- a/cmd/events-main.go +++ b/cmd/events-main.go @@ -23,41 +23,22 @@ var ( ) var eventsCmd = cli.Command{ - Name: "events", - Usage: "Manage object notifications.", - Action: mainEvents, - Before: setGlobalsFromContext, - Flags: append(eventsFlags, globalFlags...), + Name: "events", + Usage: "Manage object notifications.", + HideHelpCommand: true, + Action: mainEvents, + Before: setGlobalsFromContext, + Flags: append(eventsFlags, globalFlags...), Subcommands: []cli.Command{ eventsAddCmd, eventsRemoveCmd, eventsListCmd, }, - CustomHelpTemplate: `NAME: - {{.Name}} - {{.Usage}} - -USAGE: - {{.Name}} [FLAGS] COMMAND - -FLAGS: - {{range .Flags}}{{.}} - {{end}} -COMMANDS: - {{range .Commands}}{{join .Names ", "}}{{ "\t" }}{{.Usage}} - {{end}} -`, } // mainEvents is the handle for "mc events" command. func mainEvents(ctx *cli.Context) error { - - if ctx.Args().First() != "" { // command help. - cli.ShowCommandHelp(ctx, ctx.Args().First()) - } else { - // command with Subcommands is an App. - cli.ShowAppHelp(ctx) - } - + cli.ShowCommandHelp(ctx, ctx.Args().First()) return nil // Sub-commands like "add", "remove", "list" have their own main. } diff --git a/cmd/events-remove.go b/cmd/events-remove.go index 319a8092..caa80e03 100644 --- a/cmd/events-remove.go +++ b/cmd/events-remove.go @@ -42,19 +42,21 @@ var eventsRemoveCmd = cli.Command{ Before: setGlobalsFromContext, Flags: append(eventsRemoveFlags, globalFlags...), CustomHelpTemplate: `NAME: - mc events {{.Name}} - {{.Usage}} + {{.HelpName}} - {{.Usage}} USAGE: - mc events {{.Name}} ALIAS/BUCKET [ARN] [FLAGS] + {{.HelpName}} ALIAS/BUCKET [ARN] [FLAGS] FLAGS: - {{range .Flags}}{{.}} + {{range .VisibleFlags}}{{.}} {{end}} EXAMPLES: 1. Remove bucket notification associated to a specific arn - $ mc events {{.Name}} myminio/mybucket arn:aws:sqs:us-west-2:444455556666:your-queue + $ {{.HelpName}} myminio/mybucket arn:aws:sqs:us-west-2:444455556666:your-queue + 2. Remove all bucket notifications. --force flag is mandatory here - $ mc events {{.Name}} myminio/mybucket --force + $ {{.HelpName}} myminio/mybucket --force + `, } diff --git a/cmd/flags.go b/cmd/flags.go index 0e56913d..520efecf 100644 --- a/cmd/flags.go +++ b/cmd/flags.go @@ -16,13 +16,16 @@ package cmd -import "github.com/minio/cli" +import ( + "github.com/minio/cli" + "github.com/minio/minio/pkg/trie" +) // Collection of mc commands currently supported var commands = []cli.Command{} // Collection of mc commands currently supported in a trie tree -var commandsTree = newTrie() +var commandsTree = trie.NewTrie() // Collection of mc flags currently supported var globalFlags = []cli.Flag{ diff --git a/cmd/globals.go b/cmd/globals.go index 272500f1..27c93d16 100644 --- a/cmd/globals.go +++ b/cmd/globals.go @@ -26,7 +26,7 @@ import ( // mc configuration related constants. const ( - minGoVersion = ">= 1.7.1" // mc requires at least Go v1.7.1 + minGoVersion = ">= 1.7.5" // mc requires at least Go v1.7.5 ) const ( @@ -51,6 +51,7 @@ const ( // Maximum size for a single PUT operation. globalMaximumPutSize = 5 * 1024 * 1024 * 1024 // 5GiB. + ) var ( diff --git a/cmd/time.go b/cmd/humanized-duration.go similarity index 70% rename from cmd/time.go rename to cmd/humanized-duration.go index bb0658d2..a8306c36 100644 --- a/cmd/time.go +++ b/cmd/humanized-duration.go @@ -1,5 +1,5 @@ /* - * Minio Client (C) 2014, 2015 Minio, Inc. + * 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. @@ -22,16 +22,28 @@ import ( "time" ) -// humanizedTime container to capture humanized time. -type humanizedTime struct { +// humanizedDuration container to capture humanized time. +type humanizedDuration struct { Days int64 `json:"days,omitempty"` Hours int64 `json:"hours,omitempty"` Minutes int64 `json:"minutes,omitempty"` Seconds int64 `json:"seconds,omitempty"` } -// String() humanizes humanizedTime to human readable, -func (r humanizedTime) String() string { +// StringShort() humanizes humanizedDuration to human readable short format. +// This does not print at seconds. +func (r humanizedDuration) StringShort() string { + if r.Days == 0 && r.Hours == 0 { + return fmt.Sprintf("%d minutes", r.Minutes) + } + if r.Days == 0 { + return fmt.Sprintf("%d hours %d minutes", r.Hours, r.Minutes) + } + return fmt.Sprintf("%d days %d hours %d minutes", r.Days, r.Hours, r.Minutes) +} + +// String() humanizes humanizedDuration to human readable, +func (r humanizedDuration) String() string { if r.Days == 0 && r.Hours == 0 && r.Minutes == 0 { return fmt.Sprintf("%d seconds", r.Seconds) } @@ -44,9 +56,9 @@ func (r humanizedTime) String() string { return fmt.Sprintf("%d days %d hours %d minutes %d seconds", r.Days, r.Hours, r.Minutes, r.Seconds) } -// timeDurationToHumanizedTime convert golang time.Duration to a custom more readable humanizedTime. -func timeDurationToHumanizedTime(duration time.Duration) humanizedTime { - r := humanizedTime{} +// timeDurationToHumanizedDuration convert golang time.Duration to a custom more readable humanizedDuration. +func timeDurationToHumanizedDuration(duration time.Duration) humanizedDuration { + r := humanizedDuration{} if duration.Seconds() < 60.0 { r.Seconds = int64(duration.Seconds()) return r diff --git a/cmd/ls-main.go b/cmd/ls-main.go index a2932b20..f7e96857 100644 --- a/cmd/ls-main.go +++ b/cmd/ls-main.go @@ -46,32 +46,33 @@ var lsCmd = cli.Command{ Before: setGlobalsFromContext, Flags: append(lsFlags, globalFlags...), CustomHelpTemplate: `NAME: - mc {{.Name}} - {{.Usage}} + {{.HelpName}} - {{.Usage}} USAGE: - mc {{.Name}} [FLAGS] TARGET [TARGET ...] + {{.HelpName}} [FLAGS] TARGET [TARGET ...] FLAGS: - {{range .Flags}}{{.}} + {{range .VisibleFlags}}{{.}} {{end}} EXAMPLES: 1. List buckets on Amazon S3 cloud storage. - $ mc {{.Name}} s3 + $ {{.HelpName}} s3 2. List buckets and all its contents from Amazon S3 cloud storage recursively. - $ mc {{.Name}} --recursive s3 + $ {{.HelpName}} --recursive s3 3. List all contents of mybucket on Amazon S3 cloud storage. - $ mc {{.Name}} s3/mybucket/ + $ {{.HelpName}} s3/mybucket/ 4. List all contents of mybucket on Amazon S3 cloud storage on Microsoft Windows. - $ mc {{.Name}} s3\mybucket\ + $ {{.HelpName}} s3\mybucket\ 5. List files recursively on a local filesystem on Microsoft Windows. - $ mc {{.Name}} --recursive C:\Users\Worf\ + $ {{.HelpName}} --recursive C:\Users\Worf\ 6. List incomplete (previously failed) uploads of objects on Amazon S3. - $ mc {{.Name}} --incomplete s3/mybucket + $ {{.HelpName}} --incomplete s3/mybucket + `, } @@ -98,7 +99,7 @@ func checkListSyntax(ctx *cli.Context) { if _, ok := err.ToGoError().(BucketNameEmpty); ok { continue } - fatalIf(err.Trace(url), "Unable to stat ‘"+url+"’.") + fatalIf(err.Trace(url), "Unable to stat `"+url+"`.") } } } @@ -128,7 +129,7 @@ func mainList(ctx *cli.Context) error { for _, targetURL := range args { var clnt Client clnt, err := newClient(targetURL) - fatalIf(err.Trace(targetURL), "Unable to initialize target ‘"+targetURL+"’.") + fatalIf(err.Trace(targetURL), "Unable to initialize target `"+targetURL+"`.") var st *clientContent if st, err = clnt.Stat(isIncomplete); err != nil { @@ -137,14 +138,14 @@ func mainList(ctx *cli.Context) error { // For aliases like ``mc ls s3`` it's acceptable to receive BucketNameEmpty error. // Nothing to do. default: - fatalIf(err.Trace(targetURL), "Unable to initialize target ‘"+targetURL+"’.") + fatalIf(err.Trace(targetURL), "Unable to initialize target `"+targetURL+"`.") } } else if st.Type.IsDir() { if !strings.HasSuffix(targetURL, string(clnt.GetURL().Separator)) { targetURL = targetURL + string(clnt.GetURL().Separator) } clnt, err = newClient(targetURL) - fatalIf(err.Trace(targetURL), "Unable to initialize target ‘"+targetURL+"’.") + fatalIf(err.Trace(targetURL), "Unable to initialize target `"+targetURL+"`.") } if e := doList(clnt, isRecursive, isIncomplete); e != nil { cErr = e diff --git a/cmd/main.go b/cmd/main.go index f5c6914c..dc9e4574 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -1,5 +1,5 @@ /* - * Minio Client (C) 2014, 2015 Minio, Inc. + * Minio Client (C) 2014, 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. @@ -25,11 +25,13 @@ import ( "sort" "strconv" "strings" + "time" "github.com/cheggaaa/pb" "github.com/minio/cli" "github.com/minio/mc/pkg/console" "github.com/minio/minio/pkg/probe" + "github.com/minio/minio/pkg/words" "github.com/pkg/profile" ) @@ -43,13 +45,13 @@ var mcHelpTemplate = `NAME: {{.Name}} - {{.Usage}} USAGE: - {{.Name}} {{if .Flags}}[FLAGS] {{end}}COMMAND{{if .Flags}} [COMMAND FLAGS | -h]{{end}} [ARGUMENTS...] + {{.Name}} {{if .VisibleFlags}}[FLAGS] {{end}}COMMAND{{if .VisibleFlags}} [COMMAND FLAGS | -h]{{end}} [ARGUMENTS...] COMMANDS: - {{range .Commands}}{{join .Names ", "}}{{ "\t" }}{{.Usage}} - {{end}}{{if .Flags}} + {{range .VisibleCommands}}{{join .Names ", "}}{{ "\t" }}{{.Usage}} + {{end}}{{if .VisibleFlags}} GLOBAL FLAGS: - {{range .Flags}}{{.}} + {{range .VisibleFlags}}{{.}} {{end}}{{end}} VERSION: ` + Version + @@ -91,16 +93,16 @@ func Main() { // Function invoked when invalid command is passed. func commandNotFound(ctx *cli.Context, command string) { - msg := fmt.Sprintf("‘%s’ is not a mc command. See ‘mc --help’.", command) + msg := fmt.Sprintf("`%s` is not a mc command. See `mc --help`.", command) closestCommands := findClosestCommands(command) if len(closestCommands) > 0 { msg += fmt.Sprintf("\n\nDid you mean one of these?\n") if len(closestCommands) == 1 { cmd := closestCommands[0] - msg += fmt.Sprintf(" ‘%s’", cmd) + msg += fmt.Sprintf(" `%s`", cmd) } else { for _, cmd := range closestCommands { - msg += fmt.Sprintf(" ‘%s’\n", cmd) + msg += fmt.Sprintf(" `%s`\n", cmd) } } } @@ -174,7 +176,7 @@ func initMC() { err := saveMcConfig(newMcConfig()) fatalIf(err.Trace(), "Unable to save new mc config.") - console.Infoln("Configuration written to ‘" + mustGetMcConfigPath() + "’. Please update your access credentials.") + console.Infoln("Configuration written to `" + mustGetMcConfigPath() + "`. Please update your access credentials.") } // Check if mc session folder exists. @@ -231,18 +233,33 @@ func findClosestCommands(command string) []string { } sort.Strings(closestCommands) // Suggest other close commands - allow missed, wrongly added and even transposed characters - for _, value := range commandsTree.walk(commandsTree.root) { + for _, value := range commandsTree.Walk(commandsTree.Root()) { if sort.SearchStrings(closestCommands, value.(string)) < len(closestCommands) { continue } // 2 is arbitrary and represents the max allowed number of typed errors - if DamerauLevenshteinDistance(command, value.(string)) < 2 { + if words.DamerauLevenshteinDistance(command, value.(string)) < 2 { closestCommands = append(closestCommands, value.(string)) } } return closestCommands } +// Check for updates and print a notification message +func checkUpdate(ctx *cli.Context) { + // Do not print update messages, if quiet flag is set. + if ctx.Bool("quiet") || ctx.GlobalBool("quiet") { + older, downloadURL, err := getUpdateInfo(1 * time.Second) + if err != nil { + // Its OK to ignore any errors during getUpdateInfo() here. + return + } + if older > time.Duration(0) { + console.Println(colorizeUpdateMessage(downloadURL, older)) + } + } +} + func registerApp() *cli.App { // Register all the commands (refer flags.go) registerCmd(lsCmd) // List contents of a bucket. @@ -263,21 +280,28 @@ func registerApp() *cli.App { registerCmd(updateCmd) // Check for new software updates. registerCmd(versionCmd) // Print version. + cli.HelpFlag = cli.BoolFlag{ + Name: "help, h", + Usage: "Show help.", + } + + cli.BashCompletionFlag = cli.BoolFlag{ + Name: "compgen", + Usage: "Enables bash-completion for all commands and subcommands.", + Hidden: true, + } + app := cli.NewApp() app.Action = func(ctx *cli.Context) { if strings.HasPrefix(Version, "RELEASE.") { - updateMsg, _, err := getReleaseUpdate(mcUpdateStableURL) - if err != nil { - // Ignore any errors during getReleaseUpdate() because - // the internet might not be available. - return - } - if updateMsg.Update { - printMsg(updateMsg) - } + // Check for new updates from dl.minio.io. + checkUpdate(ctx) } cli.ShowAppHelp(ctx) } + + app.HideVersion = true + app.HideHelpCommand = true app.Usage = "Minio Client for cloud storage and filesystems." app.Commands = commands app.Author = "Minio.io" @@ -285,6 +309,8 @@ func registerApp() *cli.App { app.Flags = append(mcFlags, globalFlags...) app.CustomAppHelpTemplate = mcHelpTemplate app.CommandNotFound = commandNotFound // handler function declared above. + app.EnableBashCompletion = true + return app } diff --git a/cmd/mb-main.go b/cmd/mb-main.go index b33d75c1..7bda23fe 100644 --- a/cmd/mb-main.go +++ b/cmd/mb-main.go @@ -30,7 +30,7 @@ var ( cli.StringFlag{ Name: "region", Value: "us-east-1", - Usage: "Specify bucket region. Defaults to ‘us-east-1’.", + Usage: "Specify bucket region. Defaults to `us-east-1`.", }, } ) @@ -43,29 +43,30 @@ var mbCmd = cli.Command{ Before: setGlobalsFromContext, Flags: append(mbFlags, globalFlags...), CustomHelpTemplate: `NAME: - mc {{.Name}} - {{.Usage}} + {{.HelpName}} - {{.Usage}} USAGE: - mc {{.Name}} [FLAGS] TARGET [TARGET...] - + {{.HelpName}} [FLAGS] TARGET [TARGET...] +{{if .VisibleFlags}} FLAGS: - {{range .Flags}}{{.}} - {{end}} + {{range .VisibleFlags}}{{.}} + {{end}}{{end}} EXAMPLES: 1. Create a bucket on Amazon S3 cloud storage. - $ mc {{.Name}} s3/mynewbucket + $ {{.HelpName}} s3/mynewbucket 2. Create a new bucket on Google Cloud Storage. - $ mc {{.Name}} gcs/miniocloud + $ {{.HelpName}} gcs/miniocloud - 4. Create a new bucket on Amazon S3 cloud storage in region ‘us-west-2’. - $ mc {{.Name}} --region=us-west-2 s3/myregionbucket + 4. Create a new bucket on Amazon S3 cloud storage in region 'us-west-2'. + $ {{.HelpName}} --region=us-west-2 s3/myregionbucket - 5. Create a new directory including its missing parents (equivalent to ‘mkdir -p’). - $ mc {{.Name}} /tmp/this/new/dir1 + 5. Create a new directory including its missing parents (equivalent to 'mkdir -p'). + $ {{.HelpName}} /tmp/this/new/dir1 + + 6. Create multiple directories including its missing parents (behavior similar to 'mkdir -p'). + $ {{.HelpName}} /mnt/sdb/mydisk /mnt/sdc/mydisk /mnt/sdd/mydisk - 6. Create multiple directories including its missing parents (behavior similar to ‘mkdir -p’). - $ mc {{.Name}} /mnt/sdb/mydisk /mnt/sdc/mydisk /mnt/sdd/mydisk `, } @@ -78,7 +79,7 @@ type makeBucketMessage struct { // String colorized make bucket message. func (s makeBucketMessage) String() string { - return console.Colorize("MakeBucket", "Bucket created successfully ‘"+s.Bucket+"’.") + return console.Colorize("MakeBucket", "Bucket created successfully `"+s.Bucket+"`.") } // JSON jsonified make bucket message. @@ -114,7 +115,7 @@ func mainMakeBucket(ctx *cli.Context) error { // Instantiate client for URL. clnt, err := newClient(targetURL) if err != nil { - errorIf(err.Trace(targetURL), "Invalid target ‘"+targetURL+"’.") + errorIf(err.Trace(targetURL), "Invalid target `"+targetURL+"`.") cErr = exitStatus(globalErrorExitStatus) continue } @@ -122,7 +123,7 @@ func mainMakeBucket(ctx *cli.Context) error { // Make bucket. err = clnt.MakeBucket(region) if err != nil { - errorIf(err.Trace(targetURL), "Unable to make bucket ‘"+targetURL+"’.") + errorIf(err.Trace(targetURL), "Unable to make bucket `"+targetURL+"`.") cErr = exitStatus(globalErrorExitStatus) continue } diff --git a/cmd/mc_test.go b/cmd/mc_test.go index 11aee25c..7327410a 100644 --- a/cmd/mc_test.go +++ b/cmd/mc_test.go @@ -99,27 +99,27 @@ func (s *TestSuite) TestIsvalidAliasName(c *C) { } func (s *TestSuite) TestHumanizedTime(c *C) { - hTime := timeDurationToHumanizedTime(time.Duration(10) * time.Second) + hTime := timeDurationToHumanizedDuration(time.Duration(10) * time.Second) c.Assert(hTime.Minutes, Equals, int64(0)) c.Assert(hTime.Hours, Equals, int64(0)) c.Assert(hTime.Days, Equals, int64(0)) - hTime = timeDurationToHumanizedTime(time.Duration(10) * time.Minute) + hTime = timeDurationToHumanizedDuration(time.Duration(10) * time.Minute) c.Assert(hTime.Hours, Equals, int64(0)) c.Assert(hTime.Days, Equals, int64(0)) - hTime = timeDurationToHumanizedTime(time.Duration(10) * time.Hour) + hTime = timeDurationToHumanizedDuration(time.Duration(10) * time.Hour) c.Assert(hTime.Days, Equals, int64(0)) - hTime = timeDurationToHumanizedTime(time.Duration(24) * time.Hour) + hTime = timeDurationToHumanizedDuration(time.Duration(24) * time.Hour) c.Assert(hTime.Days, Not(Equals), int64(0)) } func (s *TestSuite) TestVersions(c *C) { - v1, e := version.NewVersion("1.7.1") - v2, e := version.NewVersion("1.6.3") + v1, e := version.NewVersion("1.8") + v2, e := version.NewVersion("1.7") c.Assert(e, IsNil) - constraint, e := version.NewConstraint(">= 1.7.1") + constraint, e := version.NewConstraint(">= 1.8") c.Assert(e, IsNil) c.Assert(constraint.Check(v1), Equals, true) c.Assert(constraint.Check(v2), Equals, false) diff --git a/cmd/mirror-main.go b/cmd/mirror-main.go index 03168bbd..8f38d8f1 100644 --- a/cmd/mirror-main.go +++ b/cmd/mirror-main.go @@ -26,7 +26,6 @@ import ( "syscall" "time" - "github.com/cheggaaa/pb" "github.com/fatih/color" "github.com/minio/cli" "github.com/minio/mc/pkg/console" @@ -52,6 +51,15 @@ var ( Name: "remove", Usage: "Remove extraneous file(s) on target.", }, + cli.StringFlag{ + Name: "region", + Usage: "Specify which region to select when creating new buckets.", + Value: "us-east-1", + }, + cli.BoolFlag{ + Name: "a", + Usage: "Preserve bucket policies rules.", + }, } ) @@ -63,34 +71,35 @@ var mirrorCmd = cli.Command{ Before: setGlobalsFromContext, Flags: append(mirrorFlags, globalFlags...), CustomHelpTemplate: `NAME: - mc {{.Name}} - {{.Usage}} + {{.HelpName}} - {{.Usage}} USAGE: - mc {{.Name}} [FLAGS] SOURCE TARGET + {{.HelpName}} [FLAGS] SOURCE TARGET FLAGS: - {{range .Flags}}{{.}} + {{range .VisibleFlags}}{{.}} {{end}} EXAMPLES: 1. Mirror a bucket recursively from Minio cloud storage to a bucket on Amazon S3 cloud storage. - $ mc {{.Name}} play/photos/2014 s3/backup-photos + $ {{.HelpName}} play/photos/2014 s3/backup-photos 2. Mirror a local folder recursively to Amazon S3 cloud storage. - $ mc {{.Name}} backup/ s3/archive + $ {{.HelpName}} backup/ s3/archive 3. Mirror a bucket from aliased Amazon S3 cloud storage to a folder on Windows. - $ mc {{.Name}} s3\documents\2014\ C:\backup\2014 + $ {{.HelpName}} s3\documents\2014\ C:\backup\2014 4. Mirror a bucket from aliased Amazon S3 cloud storage to a local folder use '--force' to overwrite destination. - $ mc {{.Name}} --force s3/miniocloud miniocloud-backup + $ {{.HelpName}} --force s3/miniocloud miniocloud-backup 5. Mirror a bucket from Minio cloud storage to a bucket on Amazon S3 cloud storage and remove any extraneous files on Amazon S3 cloud storage. NOTE: '--remove' is only supported with '--force'. - $ mc {{.Name}} --force --remove play/photos/2014 s3/backup-photos/2014 + $ {{.HelpName}} --force --remove play/photos/2014 s3/backup-photos/2014 6. Continuously mirror a local folder recursively to Minio cloud storage. '--watch' continuously watches for new objects and uploads them. - $ mc {{.Name}} --force --remove --watch /var/lib/backups play/backups + $ {{.HelpName}} --force --remove --watch /var/lib/backups play/backups + `, } @@ -99,9 +108,6 @@ type mirrorJob struct { // the channel to trap SIGKILL signals trapCh <-chan bool - // Hold context information - context *cli.Context - // mutex for shutdown, this prevents the shutdown // to be initiated multiple times m *sync.Mutex @@ -126,11 +132,18 @@ type mirrorJob struct { // channel for status messages statusCh chan URLs + // Store last watch error + watchErr *probe.Error + // Store last mirror error + mirrorErr *probe.Error + TotalObjects int64 TotalBytes int64 sourceURL string targetURL string + + isFake, isForce, isRemove, isWatch bool } // mirrorMessage container for file mirror messages @@ -145,7 +158,7 @@ type mirrorMessage struct { // String colorized mirror message func (m mirrorMessage) String() string { - return console.Colorize("Mirror", fmt.Sprintf("‘%s’ -> ‘%s’", m.Source, m.Target)) + return console.Colorize("Mirror", fmt.Sprintf("`%s` -> `%s`", m.Source, m.Target)) } // JSON jsonified mirror message @@ -157,30 +170,9 @@ func (m mirrorMessage) JSON() string { return string(mirrorMessageBytes) } -// mirrorStatMessage container for mirror accounting message -type mirrorStatMessage struct { - Total int64 - Transferred int64 - Speed float64 -} - -// mirrorStatMessage mirror accounting message -func (c mirrorStatMessage) String() string { - speedBox := pb.Format(int64(c.Speed)).To(pb.U_BYTES).String() - if speedBox == "" { - speedBox = "0 MB" - } else { - speedBox = speedBox + "/s" - } - message := fmt.Sprintf("Total: %s, Transferred: %s, Speed: %s", pb.Format(c.Total).To(pb.U_BYTES), - pb.Format(c.Transferred).To(pb.U_BYTES), speedBox) - return message -} - // doRemove - removes files on target. func (mj *mirrorJob) doRemove(sURLs URLs) URLs { - isFake := mj.context.Bool("fake") - if isFake { + if mj.isFake { return sURLs.WithError(nil) } @@ -191,13 +183,12 @@ func (mj *mirrorJob) doRemove(sURLs URLs) URLs { targetWithAlias := filepath.Join(sURLs.TargetAlias, sURLs.TargetContent.URL.Path) // Remove extraneous file on target. - err := probe.NewError(removeSingle(targetWithAlias, isIncomplete, isFake, 0)) + err := probe.NewError(removeSingle(targetWithAlias, isIncomplete, mj.isFake, 0)) return sURLs.WithError(err) } // doMirror - Mirror an object to multiple destination. URLs status contains a copy of sURLs and error if any. func (mj *mirrorJob) doMirror(sURLs URLs) URLs { - isFake := mj.context.Bool("fake") if sURLs.Error != nil { // Erroneous sURLs passed. return sURLs.WithError(sURLs.Error.Trace()) @@ -205,7 +196,7 @@ func (mj *mirrorJob) doMirror(sURLs URLs) URLs { //s For a fake mirror make sure we update respective progress bars // and accounting readers under relevant conditions. - if isFake { + if mj.isFake { mj.status.Add(sURLs.SourceContent.Size) return sURLs.WithError(nil) } @@ -243,15 +234,17 @@ func (mj *mirrorJob) startStatus() { for sURLs := range mj.statusCh { if sURLs.Error != nil { + // Save last mirror error + mj.mirrorErr = sURLs.Error // Print in new line and adjust to top so that we // don't print over the ongoing progress bar. if sURLs.SourceContent != nil { errorIf(sURLs.Error.Trace(sURLs.SourceContent.URL.String()), - fmt.Sprintf("Failed to copy ‘%s’.", sURLs.SourceContent.URL.String())) + fmt.Sprintf("Failed to copy `%s`.", sURLs.SourceContent.URL.String())) } else { // When sURLs.SourceContent is nil, we know that we have an error related to removing errorIf(sURLs.Error.Trace(sURLs.TargetContent.URL.String()), - fmt.Sprintf("Failed to remove ‘%s’.", sURLs.TargetContent.URL.String())) + fmt.Sprintf("Failed to remove `%s`.", sURLs.TargetContent.URL.String())) } } @@ -265,10 +258,14 @@ func (mj *mirrorJob) startStatus() { }() } +// Stop status go routine, further updates could lead to a crash +func (mj *mirrorJob) stopStatus() { + close(mj.statusCh) + mj.wgStatus.Wait() +} + // this goroutine will watch for notifications, and add modified objects to the queue func (mj *mirrorJob) watchMirror() { - isForce := mj.context.Bool("force") - isRemove := mj.context.Bool("remove") for { select { @@ -333,14 +330,14 @@ func (mj *mirrorJob) watchMirror() { return } shouldQueue := false - if !isForce { + if !mj.isForce { _, err = targetClient.Stat(false) if err == nil { continue } // doesn't exist shouldQueue = true } - if shouldQueue || isForce { + if shouldQueue || mj.isForce { mirrorURL.TotalCount = mj.TotalObjects mirrorURL.TotalSize = mj.TotalBytes // adjust total, because we want to show progress of the item still queued to be copied. @@ -350,7 +347,7 @@ func (mj *mirrorJob) watchMirror() { continue } shouldQueue := false - if !isForce { + if !mj.isForce { targetClient, err := newClient(targetPath) if err != nil { // cannot create targetclient @@ -363,7 +360,7 @@ func (mj *mirrorJob) watchMirror() { } // doesn't exist shouldQueue = true } - if shouldQueue || isForce { + if shouldQueue || mj.isForce { mirrorURL.SourceContent.Size = event.Size mirrorURL.TotalCount = mj.TotalObjects mirrorURL.TotalSize = mj.TotalBytes @@ -380,12 +377,13 @@ func (mj *mirrorJob) watchMirror() { } mirrorURL.TotalCount = mj.TotalObjects mirrorURL.TotalSize = mj.TotalBytes - if mirrorURL.TargetContent != nil && isRemove && isForce { + if mirrorURL.TargetContent != nil && mj.isRemove && mj.isForce { mj.statusCh <- mj.doRemove(mirrorURL) } } case err := <-mj.watcher.Errors(): + mj.watchErr = err switch err.ToGoError().(type) { case APINotImplemented: // Ignore error if API is not implemented. @@ -406,16 +404,16 @@ func (mj *mirrorJob) watchSourceURL(recursive bool) *probe.Error { return err } +func (mj *mirrorJob) watchURL(sourceClient Client) *probe.Error { + return mj.watcher.Join(sourceClient, true) +} + // Fetch urls that need to be mirrored func (mj *mirrorJob) startMirror() { var totalBytes int64 var totalObjects int64 - isForce := mj.context.Bool("force") - isFake := mj.context.Bool("fake") - isRemove := mj.context.Bool("remove") - - URLsCh := prepareMirrorURLs(mj.sourceURL, mj.targetURL, isForce, isFake, isRemove) + URLsCh := prepareMirrorURLs(mj.sourceURL, mj.targetURL, mj.isForce, mj.isFake, mj.isRemove) for { select { case sURLs, ok := <-URLsCh: @@ -425,7 +423,7 @@ func (mj *mirrorJob) startMirror() { } if sURLs.Error != nil { if strings.Contains(sURLs.Error.ToGoError().Error(), " is a folder.") { - mj.status.errorIf(sURLs.Error.Trace(), "Folder cannot be copied. Please use ‘...’ suffix.") + mj.status.errorIf(sURLs.Error.Trace(), "Folder cannot be copied. Please use `...` suffix.") } else { mj.status.errorIf(sURLs.Error.Trace(), "Unable to prepare URL for copying.") } @@ -448,7 +446,7 @@ func (mj *mirrorJob) startMirror() { if sURLs.SourceContent != nil { mj.statusCh <- mj.doMirror(sURLs) - } else if sURLs.TargetContent != nil && isRemove && isForce { + } else if sURLs.TargetContent != nil && mj.isRemove && mj.isForce { mj.statusCh <- mj.doRemove(sURLs) } case <-mj.trapCh: @@ -469,31 +467,22 @@ func (mj *mirrorJob) mirror() { mj.startStatus() // Starts additional watcher thread for watching for new events. - isWatch := mj.context.Bool("watch") - if isWatch { - // monitor mode will watch the source folders for changes, - // and queue them for copying. Monitor mode can be stopped - // only by SIGTERM. - if err := mj.watchSourceURL(true); err != nil { - mj.status.fatalIf(err, fmt.Sprintf("Failed to start monitoring.")) - } - - // Start watching and mirroring. + if mj.isWatch { go mj.watchMirror() } // Start mirroring. mj.startMirror() - // Wait if watcher is running. - if mj.watcherRunning && isWatch { + if mj.isWatch { <-mj.trapCh } + + // Wait until all progress bar updates are actually shown and quit. + mj.stopStatus() } -func newMirrorJob(ctx *cli.Context) *mirrorJob { - args := ctx.Args() - +func newMirrorJob(srcURL, dstURL string, isFake, isRemove, isWatch, isForce bool) *mirrorJob { // we'll define the status to use here, // do we want the quiet status? or the progressbar var status = NewProgressStatus() @@ -504,12 +493,16 @@ func newMirrorJob(ctx *cli.Context) *mirrorJob { } mj := mirrorJob{ - context: ctx, - trapCh: signalTrap(os.Interrupt, syscall.SIGTERM, syscall.SIGKILL), - m: new(sync.Mutex), + trapCh: signalTrap(os.Interrupt, syscall.SIGTERM, syscall.SIGKILL), + m: new(sync.Mutex), - sourceURL: args[0], - targetURL: args[len(args)-1], // Last one is target + sourceURL: srcURL, + targetURL: dstURL, + + isFake: isFake, + isRemove: isRemove, + isWatch: isWatch, + isForce: isForce, status: status, scanBar: func(s string) {}, @@ -522,16 +515,134 @@ func newMirrorJob(ctx *cli.Context) *mirrorJob { return &mj } +// copyBucketPolicies - copy policies from source to dest +func copyBucketPolicies(srcClt, dstClt Client, isForce bool) *probe.Error { + rules, err := srcClt.GetAccessRules() + if err != nil { + return err + } + // Set found rules to target bucket if permitted + for _, r := range rules { + originalRule, err := dstClt.GetAccess() + if err != nil { + return err + } + // Set rule only if it doesn't exist in the target bucket + // or force flag is activated + if originalRule == "none" || isForce { + err = dstClt.SetAccess(r) + if err != nil { + return err + } + } + } + return nil +} + +// runMirror - mirrors all buckets to another S3 server +func runMirror(srcURL, dstURL string, ctx *cli.Context) *probe.Error { + + // Create a new mirror job and execute it + mj := newMirrorJob(srcURL, dstURL, + ctx.Bool("fake"), + ctx.Bool("remove"), + ctx.Bool("watch"), + ctx.Bool("force")) + + srcClt, err := newClient(srcURL) + fatalIf(err, "Unable to initialize `"+srcURL+"`") + + dstClt, err := newClient(dstURL) + fatalIf(err, "Unable to initialize `"+srcURL+"`") + + mirrorAllBuckets := (dstClt.GetURL().Type == objectStorage && dstClt.GetURL().Path == "/") + + if mirrorAllBuckets { + // Synchronize buckets using dirDifference function + for d := range dirDifference(srcClt, dstClt, srcURL, dstURL) { + if d.Error != nil { + mj.status.fatalIf(d.Error, fmt.Sprintf("Failed to start monitoring.")) + } + if d.Diff == differInSecond { + // Ignore buckets that only exist in target instance + continue + } + + sourceSuffix := strings.TrimPrefix(d.FirstURL, srcClt.GetURL().String()) + + newSrcURL := srcURL + sourceSuffix + newTgtURL := 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")) + if err != nil { + mj.mirrorErr = err + errorIf(err, "Cannot created bucket in `"+newTgtURL+"`") + continue + } + // Copy policy rules from source to dest if flag is activated + if ctx.Bool("a") { + err := copyBucketPolicies(srcClt, dstClt, ctx.Bool("force")) + if err != nil { + mj.mirrorErr = err + errorIf(err, "Cannot copy bucket policies to `"+newDstClt.GetURL().String()+"`") + } + } + } + + if mj.isWatch { + // monitor mode will watch the source folders for changes, + // and queue them for copying. + if err := mj.watchURL(newSrcClt); err != nil { + mj.status.fatalIf(err, fmt.Sprintf("Failed to start monitoring.")) + } + } + } + } + + if !mirrorAllBuckets && mj.isWatch { + // monitor mode will watch the source folders for changes, + // and queue them for copying. + if err := mj.watchURL(srcClt); err != nil { + mj.status.fatalIf(err, fmt.Sprintf("Failed to start monitoring.")) + } + } + + // Start mirroring job + mj.mirror() + + // Check for errors during mirroring or watching to return + if mj.mirrorErr != nil { + return mj.mirrorErr + } + if mj.watchErr != nil { + return mj.watchErr + } + + return nil +} + // Main entry point for mirror command. func mainMirror(ctx *cli.Context) error { + // check 'mirror' cli arguments. checkMirrorSyntax(ctx) // Additional command specific theme customization. console.SetColor("Mirror", color.New(color.FgGreen, color.Bold)) - mj := newMirrorJob(ctx) - mj.mirror() + args := ctx.Args() + + srcURL := args[0] + tgtURL := args[1] + + if err := runMirror(srcURL, tgtURL, ctx); err != nil { + return exitStatus(globalErrorExitStatus) + } return nil } diff --git a/cmd/mirror-url.go b/cmd/mirror-url.go index 2c32e72a..6a6e096b 100644 --- a/cmd/mirror-url.go +++ b/cmd/mirror-url.go @@ -45,11 +45,11 @@ func checkMirrorSyntax(ctx *cli.Context) { // incomplete uploads are not necessary for copy operation, no need to verify for them. isIncomplete := false if err != nil && !isURLPrefixExists(srcURL, isIncomplete) { - errorIf(err.Trace(srcURL), "Unable to stat source ‘"+srcURL+"’.") + errorIf(err.Trace(srcURL), "Unable to stat source `"+srcURL+"`.") } if err == nil && !srcContent.Type.IsDir() { - fatalIf(errInvalidArgument().Trace(srcContent.URL.String(), srcContent.Type.String()), fmt.Sprintf("Source ‘%s’ is not a folder. Only folders are supported by mirror command.", srcURL)) + fatalIf(errInvalidArgument().Trace(srcContent.URL.String(), srcContent.Type.String()), fmt.Sprintf("Source `%s` is not a folder. Only folders are supported by mirror command.", srcURL)) } } @@ -61,17 +61,9 @@ func checkMirrorSyntax(ctx *cli.Context) { if url.Host != "" { if url.Path == string(url.Separator) { fatalIf(errInvalidArgument().Trace(tgtURL), - fmt.Sprintf("Target ‘%s’ does not contain bucket name.", tgtURL)) + fmt.Sprintf("Target `%s` does not contain bucket name.", tgtURL)) } } - _, _, err := url2Stat(tgtURL) - // we die on any error other than PathNotFound - destination directory need not exist. - switch err.ToGoError().(type) { - case PathNotFound: - case ObjectMissing: - default: - fatalIf(err.Trace(tgtURL), fmt.Sprintf("Unable to stat target ‘%s’.", tgtURL)) - } } func deltaSourceTarget(sourceURL string, targetURL string, isForce bool, isFake bool, isRemove bool, URLsCh chan<- URLs) { @@ -105,6 +97,10 @@ func deltaSourceTarget(sourceURL string, targetURL string, isForce bool, isFake // List both source and target, compare and return values through channel. for diffMsg := range objectDifference(sourceClnt, targetClnt, sourceURL, targetURL) { + if diffMsg.Error != nil { + errorIf(diffMsg.Error, "Unable to mirror objects.") + break + } switch diffMsg.Diff { case differInNone: // No difference, continue. diff --git a/cmd/notifier.go b/cmd/notifier.go index a571b7e2..881a5fd9 100644 --- a/cmd/notifier.go +++ b/cmd/notifier.go @@ -1,5 +1,5 @@ /* - * Minio Client (C) 2015 Minio, Inc. + * 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. @@ -21,38 +21,44 @@ import ( "math" "runtime" "strings" + "time" "github.com/cheggaaa/pb" "github.com/fatih/color" - "github.com/minio/minio/pkg/probe" ) -// colorizeUpdateMessage - inspired from Yeoman project npm package https://github.com/yeoman/update-notifier. -func colorizeUpdateMessage(updateString string) (string, *probe.Error) { - // initialize coloring +// colorizeUpdateMessage - inspired from Yeoman project npm package https://github.com/yeoman/update-notifier +func colorizeUpdateMessage(updateString string, newerThan time.Duration) string { + // Initialize coloring. cyan := color.New(color.FgCyan, color.Bold).SprintFunc() yellow := color.New(color.FgYellow, color.Bold).SprintfFunc() - // calculate length without color coding, due to ANSI color characters padded to actual - // string the final length is wrong than the original string length. - line1Str := fmt.Sprintf(" New update available, please execute the following command to update: ") - line2Str := fmt.Sprintf(" %s ", updateString) + // Calculate length without color coding, due to ANSI color + // characters padded to actual string the final length is wrong + // than the original string length. + hTime := timeDurationToHumanizedDuration(newerThan) + line1Str := fmt.Sprintf(" mc is %s old ", hTime.StringShort()) + line2Str := fmt.Sprintf(" Update: %s ", updateString) line1Length := len(line1Str) line2Length := len(line2Str) - // populate lines with color coding. - line1InColor := line1Str - line2InColor := fmt.Sprintf(" %s ", cyan(updateString)) + // Populate lines with color coding. + line1InColor := fmt.Sprintf(" mc is %s old ", yellow(hTime.StringShort())) + line2InColor := fmt.Sprintf(" Update: %s ", cyan(updateString)) // calculate the rectangular box size. maxContentWidth := int(math.Max(float64(line1Length), float64(line2Length))) line1Rest := maxContentWidth - line1Length line2Rest := maxContentWidth - line2Length - termWidth, e := pb.GetTerminalWidth() - if e != nil { - return "", probe.NewError(e) + // termWidth is set to a default one to use when we are + // not able to calculate terminal width via OS syscalls + termWidth := 25 + + if width, err := pb.GetTerminalWidth(); err == nil { + termWidth = width } + var message string switch { case len(line2Str) > termWidth: @@ -80,6 +86,6 @@ func colorizeUpdateMessage(updateString string) (string, *probe.Error) { sideBar + line2InColor + spacePaddingLine2 + sideBar + "\n" + bottom + "\n" } - // return the final message - return message, nil + // Return the final message. + return message } diff --git a/cmd/pipe-main.go b/cmd/pipe-main.go index c5b80166..5db6b0ae 100644 --- a/cmd/pipe-main.go +++ b/cmd/pipe-main.go @@ -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. @@ -36,26 +36,26 @@ var pipeCmd = cli.Command{ Before: setGlobalsFromContext, Flags: append(pipeFlags, globalFlags...), CustomHelpTemplate: `NAME: - mc {{.Name}} - {{.Usage}} + {{.HelpName}} - {{.Usage}} USAGE: - mc {{.Name}} [FLAGS] [TARGET] + {{.HelpName}} [FLAGS] [TARGET] FLAGS: - {{range .Flags}}{{.}} + {{range .VisibleFlags}}{{.}} {{end}} EXAMPLES: 1. Write contents of stdin to a file on local filesystem. - $ mc {{.Name}} /tmp/hello-world.go + $ {{.HelpName}} /tmp/hello-world.go 2. Write contents of stdin to an object on Amazon S3 cloud storage. - $ mc {{.Name}} s3/personalbuck/meeting-notes.txt + $ {{.HelpName}} s3/personalbuck/meeting-notes.txt 3. Copy an ISO image to an object on Amazon S3 cloud storage. - $ cat debian-8.2.iso | mc {{.Name}} s3/ferenginar/gnuos.iso + $ cat debian-8.2.iso | {{.HelpName}} s3/ferenginar/gnuos.iso 4. Stream MySQL database dump to Amazon S3 directly. - $ mysqldump -u root -p ******* accountsdb | mc {{.Name}} s3/ferenginar/backups/accountsdb-oct-9-2015.sql + $ mysqldump -u root -p ******* accountsdb | {{.HelpName}} s3/ferenginar/backups/accountsdb-oct-9-2015.sql `, } diff --git a/cmd/policy-main.go b/cmd/policy-main.go index fb8a3438..edb57865 100644 --- a/cmd/policy-main.go +++ b/cmd/policy-main.go @@ -44,39 +44,39 @@ var policyCmd = cli.Command{ Before: setGlobalsFromContext, Flags: append(policyFlags, globalFlags...), CustomHelpTemplate: `Name: - mc {{.Name}} - {{.Usage}} + {{.HelpName}} - {{.Usage}} USAGE: - mc {{.Name}} [FLAGS] PERMISSION TARGET - mc {{.Name}} [FLAGS] TARGET + {{.HelpName}} [FLAGS] PERMISSION TARGET + {{.HelpName}} [FLAGS] TARGET PERMISSION: - Allowed policies are: [none, download, upload, public]. - + Allowed policies are: [none, download, upload, public]. +{{if .VisibleFlags}} FLAGS: - {{range .Flags}}{{.}} - {{end}} + {{range .VisibleFlags}}{{.}} + {{end}}{{end}} EXAMPLES: 1. Set bucket to "download" on Amazon S3 cloud storage. - $ mc {{.Name}} download s3/burningman2011 + $ {{.HelpName}} download s3/burningman2011 2. Set bucket to "public" on Amazon S3 cloud storage. - $ mc {{.Name}} public s3/shared + $ {{.HelpName}} public s3/shared 3. Set bucket to "upload" on Amazon S3 cloud storage. - $ mc {{.Name}} upload s3/incoming + $ {{.HelpName}} upload s3/incoming 4. Set a prefix to "public" on Amazon S3 cloud storage. - $ mc {{.Name}} public s3/public-commons/images + $ {{.HelpName}} public s3/public-commons/images 5. Get bucket permissions. - $ mc {{.Name}} s3/shared + $ {{.HelpName}} s3/shared 6. List policies set to a specified bucket. - $ mc {{.Name}} list s3/shared + $ {{.HelpName}} list s3/shared 7. List public object URLs recursively. - $ mc {{.Name}} --recursive links s3/shared/ + $ {{.HelpName}} --recursive links s3/shared/ `, } @@ -111,11 +111,11 @@ type policyMessage struct { func (s policyMessage) String() string { if s.Operation == "set" { return console.Colorize("Policy", - "Access permission for ‘"+s.Bucket+"’ is set to ‘"+string(s.Perms)+"’") + "Access permission for `"+s.Bucket+"` is set to `"+string(s.Perms)+"`") } if s.Operation == "get" { return console.Colorize("Policy", - "Access permission for ‘"+s.Bucket+"’"+" is ‘"+string(s.Perms)+"’") + "Access permission for `"+s.Bucket+"`"+" is `"+string(s.Perms)+"`") } // nothing to print return "" @@ -183,7 +183,7 @@ func checkPolicySyntax(ctx *cli.Context) { default: if argsLength == 2 { fatalIf(errDummy().Trace(), - "Unrecognized permission ‘"+string(firstArg)+"’. Allowed values are [none, download, upload, public].") + "Unrecognized permission `"+string(firstArg)+"`. Allowed values are [none, download, upload, public].") } } } @@ -262,9 +262,9 @@ func runPolicyListCmd(ctx *cli.Context) { if err != nil { switch err.ToGoError().(type) { case APINotImplemented: - fatalIf(err.Trace(), "Unable to list policies of a non S3 url ‘"+targetURL+"’.") + fatalIf(err.Trace(), "Unable to list policies of a non S3 url `"+targetURL+"`.") default: - fatalIf(err.Trace(targetURL), "Unable to list policies of target ‘"+targetURL+"’.") + fatalIf(err.Trace(targetURL), "Unable to list policies of target `"+targetURL+"`.") } } for k, v := range policies { @@ -282,9 +282,9 @@ func runPolicyLinksCmd(ctx *cli.Context) { if err != nil { switch err.ToGoError().(type) { case APINotImplemented: - fatalIf(err.Trace(), "Unable to list policies of a non S3 url ‘"+targetURL+"’.") + fatalIf(err.Trace(), "Unable to list policies of a non S3 url `"+targetURL+"`.") default: - fatalIf(err.Trace(targetURL), "Unable to list policies of target ‘"+targetURL+"’.") + fatalIf(err.Trace(targetURL), "Unable to list policies of target `"+targetURL+"`.") } } @@ -312,7 +312,7 @@ func runPolicyLinksCmd(ctx *cli.Context) { // Construct the new path to search for public objects newURL := alias + "/" + policyPath clnt, err := newClient(newURL) - fatalIf(err.Trace(newURL), "Unable to initialize target ‘"+targetURL+"’.") + fatalIf(err.Trace(newURL), "Unable to initialize target `"+targetURL+"`.") // Search for public objects for content := range clnt.List(isRecursive, isIncomplete, DirFirst) { if content.Err != nil { @@ -320,6 +320,10 @@ func runPolicyLinksCmd(ctx *cli.Context) { continue } + if content.Type.IsDir() && isRecursive { + continue + } + // Encode public URL u, e := url.Parse(content.URL.String()) errorIf(probe.NewError(e), "Unable to parse url `"+content.URL.String()+"`") @@ -346,10 +350,10 @@ func runPolicyCmd(ctx *cli.Context) { if err != nil { switch err.ToGoError().(type) { case APINotImplemented: - fatalIf(err.Trace(), "Unable to set policy of a non S3 url ‘"+targetURL+"’.") + fatalIf(err.Trace(), "Unable to set policy of a non S3 url `"+targetURL+"`.") default: fatalIf(err.Trace(targetURL, string(perms)), - "Unable to set policy ‘"+string(perms)+"’ for ‘"+targetURL+"’.") + "Unable to set policy `"+string(perms)+"` for `"+targetURL+"`.") } } @@ -366,9 +370,9 @@ func runPolicyCmd(ctx *cli.Context) { if err != nil { switch err.ToGoError().(type) { case APINotImplemented: - fatalIf(err.Trace(), "Unable to get policy of a non S3 url ‘"+targetURL+"’.") + fatalIf(err.Trace(), "Unable to get policy of a non S3 url `"+targetURL+"`.") default: - fatalIf(err.Trace(targetURL), "Unable to get policy for ‘"+targetURL+"’.") + fatalIf(err.Trace(targetURL), "Unable to get policy for `"+targetURL+"`.") } } diff --git a/cmd/rm-main.go b/cmd/rm-main.go index 6df51dbb..2e901b0f 100644 --- a/cmd/rm-main.go +++ b/cmd/rm-main.go @@ -70,29 +70,30 @@ var rmCmd = cli.Command{ Before: setGlobalsFromContext, Flags: append(rmFlags, globalFlags...), CustomHelpTemplate: `NAME: - mc {{.Name}} - {{.Usage}} + {{.HelpName}} - {{.Usage}} USAGE: - mc {{.Name}} [FLAGS] TARGET [TARGET ...] + {{.HelpName}} [FLAGS] TARGET [TARGET ...] FLAGS: - {{range .Flags}}{{.}} + {{range .VisibleFlags}}{{.}} {{end}} EXAMPLES: 1. Remove a file. - $ mc {{.Name}} 1999/old-backup.tgz + $ {{.HelpName}} 1999/old-backup.tgz 2. Remove all objects recursively. - $ mc {{.Name}} --recursive s3/jazz-songs/louis/ + $ {{.HelpName}} --recursive s3/jazz-songs/louis/ 3. Remove all objects older than '90' days. - $ mc {{.Name}} --recursive --older-than=90 s3/jazz-songs/louis/ + $ {{.HelpName}} --recursive --older-than=90 s3/jazz-songs/louis/ 4. Remove all objects read from STDIN. - $ mc {{.Name}} --force --stdin + $ {{.HelpName}} --force --stdin 5. Drop all incomplete uploads on 'jazz-songs' bucket. - $ mc {{.Name}} --incomplete --recursive s3/jazz-songs/ + $ {{.HelpName}} --incomplete --recursive s3/jazz-songs/ + `, } @@ -104,7 +105,7 @@ type rmMessage struct { // Colorized message for console printing. func (r rmMessage) String() string { - return console.Colorize("Remove", fmt.Sprintf("Removing ‘%s’.", r.Key)) + return console.Colorize("Remove", fmt.Sprintf("Removing `%s`.", r.Key)) } // JSON'ified message for scripting. @@ -129,7 +130,7 @@ func checkRmSyntax(ctx *cli.Context) { // For all recursive operations make sure to check for 'force' flag. if (isRecursive || isStdin) && !isForce { fatalIf(errDummy().Trace(), - "Removal requires --force option. This operational is *IRREVERSIBLE*. Please review carefully before performing this *DANGEROUS* operation.") + "Removal requires --force option. This operation is *IRREVERSIBLE*. Please review carefully before performing this *DANGEROUS* operation.") } } @@ -137,13 +138,13 @@ func removeSingle(url string, isIncomplete bool, isFake bool, older int) error { targetAlias, targetURL, _ := mustExpandAlias(url) clnt, pErr := newClientFromAlias(targetAlias, targetURL) if pErr != nil { - errorIf(pErr.Trace(url), "Invalid argument ‘"+url+"’.") + errorIf(pErr.Trace(url), "Invalid argument `"+url+"`.") return exitStatus(globalErrorExitStatus) // End of journey. } content, pErr := clnt.Stat(isIncomplete) if pErr != nil { - errorIf(pErr.Trace(url), "Failed to remove ‘"+url+"’.") + errorIf(pErr.Trace(url), "Failed to remove `"+url+"`.") return exitStatus(globalErrorExitStatus) } if older > 0 { @@ -169,7 +170,7 @@ func removeSingle(url string, isIncomplete bool, isFake bool, older int) error { errorCh := clnt.Remove(isIncomplete, contentCh) for pErr := range errorCh { if pErr != nil { - errorIf(pErr.Trace(url), "Failed to remove ‘"+url+"’.") + errorIf(pErr.Trace(url), "Failed to remove `"+url+"`.") switch pErr.ToGoError().(type) { case PathInsufficientPermission: // Ignore Permission error. @@ -186,7 +187,7 @@ func removeRecursive(url string, isIncomplete bool, isFake bool, older int) erro targetAlias, targetURL, _ := mustExpandAlias(url) clnt, pErr := newClientFromAlias(targetAlias, targetURL) if pErr != nil { - errorIf(pErr.Trace(url), "Failed to remove ‘"+url+"’ recursively.") + errorIf(pErr.Trace(url), "Failed to remove `"+url+"` recursively.") return exitStatus(globalErrorExitStatus) // End of journey. } @@ -198,7 +199,7 @@ func removeRecursive(url string, isIncomplete bool, isFake bool, older int) erro for content := range clnt.List(isRecursive, isIncomplete, DirLast) { isEmpty = false if content.Err != nil { - errorIf(content.Err.Trace(url), "Failed to remove ‘"+url+"’ recursively.") + errorIf(content.Err.Trace(url), "Failed to remove `"+url+"` recursively.") switch content.Err.ToGoError().(type) { case PathInsufficientPermission: // Ignore Permission error. @@ -226,12 +227,12 @@ func removeRecursive(url string, isIncomplete bool, isFake bool, older int) erro if !isFake { sent := false - for sent == false { + for !sent { select { case contentCh <- content: sent = true case pErr := <-errorCh: - errorIf(pErr.Trace(urlString), "Failed to remove ‘"+urlString+"’.") + errorIf(pErr.Trace(urlString), "Failed to remove `"+urlString+"`.") switch pErr.ToGoError().(type) { case PathInsufficientPermission: // Ignore Permission error. @@ -247,7 +248,7 @@ func removeRecursive(url string, isIncomplete bool, isFake bool, older int) erro close(contentCh) for pErr := range errorCh { - errorIf(pErr.Trace(url), "Failed to remove ‘"+url+"’ recursively.") + errorIf(pErr.Trace(url), "Failed to remove `"+url+"` recursively.") switch pErr.ToGoError().(type) { case PathInsufficientPermission: // Ignore Permission error. @@ -279,25 +280,38 @@ func mainRm(ctx *cli.Context) error { // Set color. console.SetColor("Remove", color.New(color.FgGreen, color.Bold)) + var rerr error + var err error // Support multiple targets. for _, url := range ctx.Args() { if isRecursive { - return removeRecursive(url, isIncomplete, isFake, older) - } // else { - return removeSingle(url, isIncomplete, isFake, older) + err = removeRecursive(url, isIncomplete, isFake, older) + } else { + err = removeSingle(url, isIncomplete, isFake, older) + } + + if rerr == nil { + rerr = err + } } if !isStdin { - return nil + return rerr } scanner := bufio.NewScanner(os.Stdin) for scanner.Scan() { url := scanner.Text() if isRecursive { - return removeRecursive(url, isIncomplete, isFake, older) - } // else { - return removeSingle(url, isIncomplete, isFake, older) + err = removeRecursive(url, isIncomplete, isFake, older) + } else { + err = removeSingle(url, isIncomplete, isFake, older) + } + + if rerr == nil { + rerr = err + } } - return nil + + return rerr } diff --git a/cmd/session-main.go b/cmd/session-main.go index df408e2c..6b8e4815 100644 --- a/cmd/session-main.go +++ b/cmd/session-main.go @@ -27,6 +27,7 @@ import ( "github.com/minio/cli" "github.com/minio/mc/pkg/console" "github.com/minio/minio/pkg/probe" + "github.com/minio/minio/pkg/trie" ) var ( @@ -41,34 +42,35 @@ var sessionCmd = cli.Command{ Flags: append(sessionFlags, globalFlags...), Before: setGlobalsFromContext, CustomHelpTemplate: `NAME: - mc {{.Name}} - {{.Usage}} + {{.HelpName}} - {{.Usage}} USAGE: - mc {{.Name}} [FLAGS] OPERATION [ARG] + {{.HelpName}} [FLAGS] OPERATION [ARG] OPERATION: - resume Resume a previously saved session. - clear Clear a previously saved session. - list List all previously saved sessions. + resume Resume a previously saved session. + clear Clear a previously saved session. + list List all previously saved sessions. SESSION-ID: - SESSION - Session can either be $SESSION-ID or "all". - + SESSION - Session can either be $SESSION-ID or "all". +{{if .VisibleFlags}} FLAGS: - {{range .Flags}}{{.}} - {{end}} + {{range .VisibleFlags}}{{.}} + {{end}}{{end}} EXAMPLES: 1. List sessions. - $ mc {{.Name}} list + $ {{.HelpName}} list 2. Resume session. - $ mc {{.Name}} resume ygVIpSJs + $ {{.HelpName}} resume ygVIpSJs 3. Clear session. - $ mc {{.Name}} clear ygVIpSJs + $ {{.HelpName}} clear ygVIpSJs 4. Clear all sessions. - $ mc {{.Name}} clear all + $ {{.HelpName}} clear all + `, } @@ -106,7 +108,7 @@ type clearSessionMessage struct { // String colorized clear session message. func (c clearSessionMessage) String() string { - msg := "Session ‘" + c.SessionID + "’" + msg := "Session `" + c.SessionID + "`" var colorizedMsg string switch c.Status { case "success": @@ -130,9 +132,9 @@ func clearSession(sid string) { if sid == "all" { for _, sid := range getSessionIDs() { session, err := loadSessionV8(sid) - fatalIf(err.Trace(sid), "Unable to load session ‘"+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 load session `"+sid+"`.") printMsg(clearSessionMessage{Status: "success", SessionID: sid}) } @@ -140,7 +142,7 @@ func clearSession(sid string) { } if !isSessionExists(sid) { - fatalIf(errDummy().Trace(sid), "Session ‘"+sid+"’ not found.") + fatalIf(errDummy().Trace(sid), "Session `"+sid+"` not found.") } session, err := loadSessionV8(sid) @@ -154,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 load session `"+sid+"`.") printMsg(clearSessionMessage{Status: "success", SessionID: sid}) } } @@ -191,7 +193,7 @@ func checkSessionSyntax(ctx *cli.Context) { // findClosestSessions to match a given string with sessions trie tree. func findClosestSessions(session string) []string { - sessionsTree := newTrie() // Allocate a new trie for sessions strings. + sessionsTree := trie.NewTrie() // Allocate a new trie for sessions strings. for _, sid := range getSessionIDs() { sessionsTree.Insert(sid) } @@ -226,11 +228,11 @@ func mainSession(ctx *cli.Context) error { sid := strings.TrimSpace(ctx.Args().Tail().First()) if !isSessionExists(sid) { closestSessions := findClosestSessions(sid) - errorMsg := "Session ‘" + sid + "’ not found." + errorMsg := "Session `" + sid + "` not found." if len(closestSessions) > 0 { errorMsg += fmt.Sprintf("\n\nDid you mean?\n") for _, session := range closestSessions { - errorMsg += fmt.Sprintf(" ‘mc resume session %s’", session) + errorMsg += fmt.Sprintf(" `mc resume session %s`", session) // break on the first one, it is good enough. break } @@ -260,7 +262,7 @@ func mainSession(ctx *cli.Context) error { // change folder back to saved path. e = os.Chdir(savedCwd) - fatalIf(probe.NewError(e), "Unable to change working folder to saved path ‘"+savedCwd+"’.") + fatalIf(probe.NewError(e), "Unable to change working folder to saved path `"+savedCwd+"`.") // purge a requested pending session, if "all" purge everything. case "clear": clearSession(strings.TrimSpace(ctx.Args().Tail().First())) diff --git a/cmd/session-migrate.go b/cmd/session-migrate.go index ac999fbb..dbc8fb55 100644 --- a/cmd/session-migrate.go +++ b/cmd/session-migrate.go @@ -34,11 +34,11 @@ func migrateSessionV7ToV8() { if os.IsNotExist(err.ToGoError()) { continue } - fatalIf(err.Trace(sid), "Unable to load version ‘7’. Migration failed please report this issue at https://github.com/minio/mc/issues.") + fatalIf(err.Trace(sid), "Unable to load version `7`. Migration failed please report this issue at https://github.com/minio/mc/issues.") } 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.") + 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. continue } @@ -73,7 +73,7 @@ func migrateSessionV7ToV8() { e = qs.Save(sessionFile) fatalIf(probe.NewError(e).Trace(sid, sessionFile), "Unable to migrate session from '7' to '8'.") - console.Println("Successfully migrated ‘" + sessionFile + "’ from version ‘" + sV7.Header.Version + "’ to " + "‘" + sV8Header.Version + "’.") + console.Println("Successfully migrated `" + sessionFile + "` from version `" + sV7.Header.Version + "` to " + "`" + sV8Header.Version + "`.") } } @@ -86,11 +86,11 @@ func migrateSessionV6ToV7() { if os.IsNotExist(err.ToGoError()) { continue } - fatalIf(err.Trace(sid), "Unable to load version ‘6’. Migration failed please report this issue at https://github.com/minio/mc/issues.") + fatalIf(err.Trace(sid), "Unable to load version `6`. Migration failed please report this issue at https://github.com/minio/mc/issues.") } sessionVersion, e := strconv.Atoi(sV6Header.Version) - fatalIf(probe.NewError(e), "Unable to load version ‘6’. Migration failed please report this issue at https://github.com/minio/mc/issues.") + fatalIf(probe.NewError(e), "Unable to load version `6`. Migration failed please report this issue at https://github.com/minio/mc/issues.") if sessionVersion > 6 { // It is new format. continue } @@ -122,7 +122,7 @@ func migrateSessionV6ToV7() { e = qs.Save(sessionFile) fatalIf(probe.NewError(e).Trace(sid, sessionFile), "Unable to migrate session from '6' to '7'.") - console.Println("Successfully migrated ‘" + sessionFile + "’ from version ‘" + sV6Header.Version + "’ to " + "‘" + sV7Header.Version + "’.") + console.Println("Successfully migrated `" + sessionFile + "` from version `" + sV6Header.Version + "` to " + "`" + sV7Header.Version + "`.") } } @@ -136,11 +136,11 @@ func migrateSessionV5ToV6() { if os.IsNotExist(err.ToGoError()) { continue } - fatalIf(err.Trace(sid), "Unable to load version ‘6’. Migration failed please report this issue at https://github.com/minio/mc/issues.") + fatalIf(err.Trace(sid), "Unable to load version `6`. Migration failed please report this issue at https://github.com/minio/mc/issues.") } sessionVersion, e := strconv.Atoi(sV6Header.Version) - fatalIf(probe.NewError(e), "Unable to load version ‘6’. Migration failed please report this issue at https://github.com/minio/mc/issues.") + fatalIf(probe.NewError(e), "Unable to load version `6`. Migration failed please report this issue at https://github.com/minio/mc/issues.") if sessionVersion > 5 { // It is new format. continue } @@ -153,12 +153,12 @@ func migrateSessionV5ToV6() { sessionDataFile, err := getSessionDataFile(sid) fatalIf(err.Trace(sid), "Unable to get session data file.") - console.Println("Removing unsupported session file ‘" + sessionFile + "’ version ‘" + sV6Header.Version + "’.") + console.Println("Removing unsupported session file `" + sessionFile + "` version `" + sV6Header.Version + "`.") if e := os.Remove(sessionFile); e != nil { - fatalIf(probe.NewError(e), "Unable to remove version ‘"+sV6Header.Version+"’ session file ‘"+sessionFile+"’.") + fatalIf(probe.NewError(e), "Unable to remove version `"+sV6Header.Version+"` session file `"+sessionFile+"`.") } if e := os.Remove(sessionDataFile); e != nil { - fatalIf(probe.NewError(e), "Unable to remove version ‘"+sV6Header.Version+"’ session data file ‘"+sessionDataFile+"’.") + fatalIf(probe.NewError(e), "Unable to remove version `"+sV6Header.Version+"` session data file `"+sessionDataFile+"`.") } } } diff --git a/cmd/session-v8.go b/cmd/session-v8.go index 467570fc..3ff3934f 100644 --- a/cmd/session-v8.go +++ b/cmd/session-v8.go @@ -371,7 +371,7 @@ func (s *sessionV8) Delete() *probe.Error { // Close a session and exit. func (s sessionV8) CloseAndDie() { s.Close() - console.Fatalln("Session safely terminated. To resume session ‘mc session resume " + s.SessionID + "’") + console.Fatalln("Session safely terminated. To resume session `mc session resume " + s.SessionID + "`") } // Create a factory function to simplify checking if diff --git a/cmd/session.go b/cmd/session.go index 22fed4d9..18ec927e 100644 --- a/cmd/session.go +++ b/cmd/session.go @@ -85,7 +85,7 @@ func getSessionFile(sid string) (string, *probe.Error) { // isSessionExists verifies if given session exists. func isSessionExists(sid string) bool { sessionFile, err := getSessionFile(sid) - fatalIf(err.Trace(sid), "Unable to determine session filename for ‘"+sid+"’.") + fatalIf(err.Trace(sid), "Unable to determine session filename for `"+sid+"`.") if _, e := os.Stat(sessionFile); e != nil { return false @@ -111,7 +111,7 @@ func getSessionIDs() (sids []string) { fatalIf(err.Trace(), "Unable to access session folder.") sessionList, e := filepath.Glob(sessionDir + "/*.json") - fatalIf(probe.NewError(e), "Unable to access session folder ‘"+sessionDir+"’.") + fatalIf(probe.NewError(e), "Unable to access session folder `"+sessionDir+"`.") for _, path := range sessionList { sids = append(sids, strings.TrimSuffix(filepath.Base(path), ".json")) diff --git a/cmd/share-download-main.go b/cmd/share-download-main.go index 682f6854..58268adc 100644 --- a/cmd/share-download-main.go +++ b/cmd/share-download-main.go @@ -41,26 +41,27 @@ var shareDownload = cli.Command{ Before: setGlobalsFromContext, Flags: append(shareDownloadFlags, globalFlags...), CustomHelpTemplate: `NAME: - mc share {{.Name}} - {{.Usage}} + {{.HelpName}} - {{.Usage}} USAGE: - mc share {{.Name}} [OPTIONS] TARGET [TARGET...] + {{.HelpName}} [OPTIONS] TARGET [TARGET...] OPTIONS: - {{range .Flags}}{{.}} + {{range .VisibleFlags}}{{.}} {{end}} EXAMPLES: 1. Share this object with 7 days default expiry. - $ mc share {{.Name}} s3/backup/2006-Mar-1/backup.tar.gz + $ {{.HelpName}} s3/backup/2006-Mar-1/backup.tar.gz 2. Share this object with 10 minutes expiry. - $ mc share {{.Name}} --expire=10m s3/backup/2006-Mar-1/backup.tar.gz + $ {{.HelpName}} --expire=10m s3/backup/2006-Mar-1/backup.tar.gz 3. Share all objects under this folder with 5 days expiry. - $ mc share {{.Name}} --expire=120h s3/backup/ + $ {{.HelpName}} --expire=120h s3/backup/ 4. Share all objects under this folder and all its sub-folders with 5 days expiry. - $ mc share {{.Name}} --recursive --expire=120h s3/backup/ + $ {{.HelpName}} --recursive --expire=120h s3/backup/ + `, } @@ -77,7 +78,7 @@ func checkShareDownloadSyntax(ctx *cli.Context) { if expireArg != "" { var e error expiry, e = time.ParseDuration(expireArg) - fatalIf(probe.NewError(e), "Unable to parse expire=‘"+expireArg+"’.") + fatalIf(probe.NewError(e), "Unable to parse expire=`"+expireArg+"`.") } // Validate expiry. @@ -90,7 +91,7 @@ func checkShareDownloadSyntax(ctx *cli.Context) { for _, url := range ctx.Args() { _, _, err := url2Stat(url) - fatalIf(err.Trace(url), "Unable to stat ‘"+url+"’.") + fatalIf(err.Trace(url), "Unable to stat `"+url+"`.") } } @@ -115,7 +116,32 @@ func doShareDownloadURL(targetURL string, isRecursive bool, expiry time.Duration // Generate share URL for each target. isIncomplete := false - for content := range clnt.List(isRecursive, isIncomplete, DirNone) { + + // Channel which will receive objects whose URLs need to be shared + objectsCh := make(chan *clientContent) + + if !isRecursive { + // Share thr url of only one exact prefix if it exists + content, err := clnt.Stat(isIncomplete) + if err != nil { + return err.Trace(clnt.GetURL().String()) + } + go func() { + defer close(objectsCh) + objectsCh <- content + }() + } else { + // Recursive mode: Share list of objects + go func() { + defer close(objectsCh) + for content := range clnt.List(isRecursive, isIncomplete, DirNone) { + objectsCh <- content + } + }() + } + + // Iterate over all objects to generate share URL + for content := range objectsCh { if content.Err != nil { return content.Err.Trace(clnt.GetURL().String()) } @@ -169,7 +195,7 @@ func mainShareDownload(ctx *cli.Context) error { if ctx.String("expire") != "" { var e error expiry, e = time.ParseDuration(ctx.String("expire")) - fatalIf(probe.NewError(e), "Unable to parse expire=‘"+ctx.String("expire")+"’.") + fatalIf(probe.NewError(e), "Unable to parse expire=`"+ctx.String("expire")+"`.") } for _, targetURL := range ctx.Args() { @@ -177,9 +203,9 @@ func mainShareDownload(ctx *cli.Context) error { if err != nil { switch err.ToGoError().(type) { case APINotImplemented: - fatalIf(err.Trace(), "Unable to share a non S3 url ‘"+targetURL+"’.") + fatalIf(err.Trace(), "Unable to share a non S3 url `"+targetURL+"`.") default: - fatalIf(err.Trace(targetURL), "Unable to share target ‘"+targetURL+"’.") + fatalIf(err.Trace(targetURL), "Unable to share target `"+targetURL+"`.") } } } diff --git a/cmd/share-list-main.go b/cmd/share-list-main.go index 02190f80..4dae58df 100644 --- a/cmd/share-list-main.go +++ b/cmd/share-list-main.go @@ -36,20 +36,21 @@ var shareList = cli.Command{ Before: setGlobalsFromContext, Flags: append(shareListFlags, globalFlags...), CustomHelpTemplate: `NAME: - mc share {{.Name}} COMMAND - {{.Usage}} + {{.HelpName}} COMMAND - {{.Usage}} COMMAND: upload: list previously shared access to uploads. download: list previously shared access to downloads. USAGE: - mc share {{.Name}} + {{.HelpName}} COMMAND EXAMPLES: 1. List previously shared downloads, that haven't expired yet. - $ mc share {{.Name}} download + $ {{.HelpName}} download 2. List previously shared uploads, that haven't expired yet. - $ mc share {{.Name}} upload + $ {{.HelpName}} upload + `, } @@ -64,7 +65,7 @@ func checkShareListSyntax(ctx *cli.Context) { // doShareList list shared url's. func doShareList(cmd string) *probe.Error { if cmd != "upload" && cmd != "download" { - return probe.NewError(fmt.Errorf("Unknown argument ‘%s’ passed", cmd)) + return probe.NewError(fmt.Errorf("Unknown argument `%s` passed", cmd)) } // Fetch defaults. diff --git a/cmd/share-main.go b/cmd/share-main.go index 9b694e99..0a70a2ff 100644 --- a/cmd/share-main.go +++ b/cmd/share-main.go @@ -31,29 +31,17 @@ var ( // Share documents via URL. var shareCmd = cli.Command{ - Name: "share", - Usage: "Generate URL for sharing.", - Action: mainShare, - Before: setGlobalsFromContext, - Flags: append(shareFlags, globalFlags...), + Name: "share", + Usage: "Generate URL for sharing.", + Action: mainShare, + Before: setGlobalsFromContext, + Flags: append(shareFlags, globalFlags...), + HideHelpCommand: true, Subcommands: []cli.Command{ shareDownload, shareUpload, shareList, }, - CustomHelpTemplate: `NAME: - {{.Name}} - {{.Usage}} - -USAGE: - {{.Name}} [FLAGS] COMMAND - -FLAGS: - {{range .Flags}}{{.}} - {{end}} -COMMANDS: - {{range .Commands}}{{join .Names ", "}}{{ "\t" }}{{.Usage}} - {{end}} -`, } // migrateShare migrate to newest version sequentially. @@ -67,20 +55,14 @@ func migrateShare() { if _, e := os.Stat(oldShareFile); e == nil { // Old file exits. e := os.Remove(oldShareFile) - fatalIf(probe.NewError(e), "Unable to delete old ‘"+oldShareFile+"’.") - console.Infof("Removed older version of share ‘%s’ file.\n", oldShareFile) + fatalIf(probe.NewError(e), "Unable to delete old `"+oldShareFile+"`.") + console.Infof("Removed older version of share `%s` file.\n", oldShareFile) } } // mainShare - main handler for mc share command. func mainShare(ctx *cli.Context) error { - - if ctx.Args().First() != "" { // command help. - cli.ShowCommandHelp(ctx, ctx.Args().First()) - } else { // mc help. - cli.ShowAppHelp(ctx) - } - + cli.ShowCommandHelp(ctx, ctx.Args().First()) return nil // Sub-commands like "upload" and "download" have their own main. } diff --git a/cmd/share-upload-main.go b/cmd/share-upload-main.go index 110ba5a7..46a5bbbe 100644 --- a/cmd/share-upload-main.go +++ b/cmd/share-upload-main.go @@ -39,31 +39,32 @@ var ( // Share documents via URL. var shareUpload = cli.Command{ Name: "upload", - Usage: "Generate ‘curl’ command to upload objects without requiring access/secret keys.", + Usage: "Generate `curl` command to upload objects without requiring access/secret keys.", Action: mainShareUpload, Before: setGlobalsFromContext, Flags: append(shareUploadFlags, globalFlags...), CustomHelpTemplate: `NAME: - mc share {{.Name}} - {{.Usage}} + {{.HelpName}} - {{.Usage}} USAGE: - mc share {{.Name}} [OPTIONS] TARGET [TARGET...] + {{.HelpName}} [OPTIONS] TARGET [TARGET...] OPTIONS: - {{range .Flags}}{{.}} + {{range .VisibleFlags}}{{.}} {{end}} EXAMPLES: 1. Generate a curl command to allow upload access for a single object. Command expires in 7 days (default). - $ mc share {{.Name}} s3/backup/2006-Mar-1/backup.tar.gz + $ {{.HelpName}} s3/backup/2006-Mar-1/backup.tar.gz 2. Generate a curl command to allow upload access to a folder. Command expires in 120 hours. - $ mc share {{.Name}} --expire=120h s3/backup/2007-Mar-2/ + $ {{.HelpName}} --expire=120h s3/backup/2007-Mar-2/ 3. Generate a curl command to allow upload access of only '.png' images to a folder. Command expires in 2 hours. - $ mc share {{.Name}} --expire=2h --content-type=image/png s3/backup/2007-Mar-2/ + $ {{.HelpName}} --expire=2h --content-type=image/png s3/backup/2007-Mar-2/ 4. Generate a curl command to allow upload access to any objects matching the key prefix 'backup/'. Command expires in 2 hours. - $ mc share {{.Name}} --recursive --expire=2h s3/backup/2007-Mar-2/backup/ + $ {{.HelpName}} --recursive --expire=2h s3/backup/2007-Mar-2/backup/ + `, } @@ -83,7 +84,7 @@ func checkShareUploadSyntax(ctx *cli.Context) { if expireArg != "" { var e error expiry, e = time.ParseDuration(expireArg) - fatalIf(probe.NewError(e), "Unable to parse expire=‘"+expireArg+"’.") + fatalIf(probe.NewError(e), "Unable to parse expire=`"+expireArg+"`.") } // Validate expiry. @@ -194,7 +195,7 @@ func mainShareUpload(ctx *cli.Context) error { if expireArg != "" { var e error expiry, e = time.ParseDuration(expireArg) - fatalIf(probe.NewError(e), "Unable to parse expire=‘"+expireArg+"’.") + fatalIf(probe.NewError(e), "Unable to parse expire=`"+expireArg+"`.") } for _, targetURL := range ctx.Args() { @@ -202,9 +203,9 @@ func mainShareUpload(ctx *cli.Context) error { if err != nil { switch err.ToGoError().(type) { case APINotImplemented: - fatalIf(err.Trace(), "Unable to share a non S3 url ‘"+targetURL+"’.") + fatalIf(err.Trace(), "Unable to share a non S3 url `"+targetURL+"`.") default: - fatalIf(err.Trace(targetURL), "Unable to generate curl command for upload ‘"+targetURL+"’.") + fatalIf(err.Trace(targetURL), "Unable to generate curl command for upload `"+targetURL+"`.") } } } diff --git a/cmd/share.go b/cmd/share.go index d1293dc0..c070847c 100644 --- a/cmd/share.go +++ b/cmd/share.go @@ -61,7 +61,7 @@ type shareMesssage struct { // String - Themefied string message for console printing. func (s shareMesssage) String() string { msg := console.Colorize("URL", fmt.Sprintf("URL: %s\n", s.ObjectURL)) - msg += console.Colorize("Expire", fmt.Sprintf("Expire: %s\n", timeDurationToHumanizedTime(s.TimeLeft))) + msg += console.Colorize("Expire", fmt.Sprintf("Expire: %s\n", timeDurationToHumanizedDuration(s.TimeLeft))) if s.ContentType != "" { msg += console.Colorize("Content-type", fmt.Sprintf("Content-Type: %s\n", s.ContentType)) } @@ -113,7 +113,7 @@ func getShareDir() (string, *probe.Error) { return sharedURLsDataDir, nil } -// Get share dir name or die. (NOTE: This ‘Die’ approach is only OK for mc like tools.). +// Get share dir name or die. (NOTE: This `Die` approach is only OK for mc like tools.). func mustGetShareDir() string { shareDir, err := getShareDir() fatalIf(err.Trace(), "Unable to determine share folder.") @@ -177,21 +177,21 @@ func initShareConfig() { // Share directory. if !isShareDirExists() { fatalIf(createShareDir().Trace(mustGetShareDir()), - "Failed to create share ‘"+mustGetShareDir()+"’ folder.") - console.Infof("Successfully created ‘%s’.\n", mustGetShareDir()) + "Failed to create share `"+mustGetShareDir()+"` folder.") + console.Infof("Successfully created `%s`.\n", mustGetShareDir()) } // Uploads share file. if !isShareUploadsExists() { fatalIf(initShareUploadsFile().Trace(getShareUploadsFile()), - "Failed to initialize share uploads ‘"+getShareUploadsFile()+"’ file.") - console.Infof("Initialized share uploads ‘%s’ file.\n", getShareUploadsFile()) + "Failed to initialize share uploads `"+getShareUploadsFile()+"` file.") + console.Infof("Initialized share uploads `%s` file.\n", getShareUploadsFile()) } // Downloads share file. if !isShareDownloadsExists() { fatalIf(initShareDownloadsFile().Trace(getShareDownloadsFile()), - "Failed to initialize share downloads ‘"+getShareDownloadsFile()+"’ file.") - console.Infof("Initialized share downloads ‘%s’ file.\n", getShareDownloadsFile()) + "Failed to initialize share downloads `"+getShareDownloadsFile()+"` file.") + console.Infof("Initialized share downloads `%s` file.\n", getShareDownloadsFile()) } } diff --git a/cmd/status.go b/cmd/status.go index b4a9704d..fef5836b 100644 --- a/cmd/status.go +++ b/cmd/status.go @@ -158,14 +158,7 @@ func (qs *QuietStatus) Start() { // Finish displays the accounting summary func (qs *QuietStatus) Finish() { - accntStat := qs.accounter.Stat() - cpStatMessage := mirrorStatMessage{ - Total: accntStat.Total, - Transferred: accntStat.Transferred, - Speed: accntStat.Speed, - } - - console.Println(console.Colorize("Mirror", cpStatMessage.String())) + console.Println(console.Colorize("Mirror", qs.accounter.Stat().String())) } // Update is ignored for quietstatus diff --git a/cmd/typed-errors.go b/cmd/typed-errors.go index 247698e4..37d08549 100644 --- a/cmd/typed-errors.go +++ b/cmd/typed-errors.go @@ -36,30 +36,30 @@ var ( } errInvalidAliasedURL = func(URL string) *probe.Error { - return probe.NewError(errors.New("Use ‘mc config host add mycloud " + URL + " ...’ to add an alias. Use the alias for S3 operations.")).Untrace() + return probe.NewError(errors.New("Use `mc config host add mycloud " + URL + " ...` to add an alias. Use the alias for S3 operations.")).Untrace() } errNoMatchingHost = func(URL string) *probe.Error { - return probe.NewError(errors.New("No matching host found for the given URL ‘" + URL + "’.")).Untrace() + return probe.NewError(errors.New("No matching host found for the given URL `" + URL + "`.")).Untrace() } errInvalidSource = func(URL string) *probe.Error { - return probe.NewError(errors.New("Invalid source ‘" + URL + "’.")).Untrace() + return probe.NewError(errors.New("Invalid source `" + URL + "`.")).Untrace() } errInvalidTarget = func(URL string) *probe.Error { - return probe.NewError(errors.New("Invalid target ‘" + URL + "’.")).Untrace() + return probe.NewError(errors.New("Invalid target `" + URL + "`.")).Untrace() } errOverWriteNotAllowed = func(URL string) *probe.Error { - return probe.NewError(errors.New("Overwrite not allowed for ‘" + URL + "’. Use ‘--force’ to override this behavior.")) + return probe.NewError(errors.New("Overwrite not allowed for `" + URL + "`. Use `--force` to override this behavior.")) } errDeleteNotAllowed = func(URL string) *probe.Error { - return probe.NewError(errors.New("Delete not allowed for ‘" + URL + "’. Use ‘--force’ to override this behavior.")) + return probe.NewError(errors.New("Delete not allowed for `" + URL + "`. Use `--force` to override this behavior.")) } errSourceIsDir = func(URL string) *probe.Error { - return probe.NewError(errors.New("Source ‘" + URL + "’ is a folder.")).Untrace() + return probe.NewError(errors.New("Source `" + URL + "` is a folder.")).Untrace() } errSourceTargetSame = func(URL string) *probe.Error { diff --git a/cmd/update-main.go b/cmd/update-main.go index c2d441ef..a87c6d07 100644 --- a/cmd/update-main.go +++ b/cmd/update-main.go @@ -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. @@ -17,10 +17,13 @@ package cmd import ( + "bytes" "encoding/json" - "errors" + "fmt" "io/ioutil" "net/http" + "os" + "os/exec" "runtime" "strings" "time" @@ -31,203 +34,257 @@ import ( "github.com/minio/minio/pkg/probe" ) -// command specific flags. -var ( - updateFlags = []cli.Flag{ - cli.BoolFlag{ - Name: "experimental, E", - Usage: "Check experimental update.", - }, - } -) - // Check for new software updates. var updateCmd = cli.Command{ Name: "update", - Usage: "Check for new mc update.", + Usage: "Check for a new software update.", Action: mainUpdate, Before: setGlobalsFromContext, - Flags: append(updateFlags, globalFlags...), + Flags: []cli.Flag{ + cli.BoolFlag{ + Name: "quiet, q", + Usage: "Suppress chatty console output.", + }, + cli.BoolFlag{ + Name: "json", + Usage: "Enable JSON formatted output.", + }, + }, CustomHelpTemplate: `Name: - mc {{.Name}} - {{.Usage}} + {{.HelpName}} - {{.Usage}} USAGE: - mc {{.Name}} [FLAGS] - + {{.HelpName}}{{if .VisibleFlags}} [FLAGS]{{end}} +{{if .VisibleFlags}} FLAGS: - {{range .Flags}}{{.}} - {{end}} + {{range .VisibleFlags}}{{.}} + {{end}}{{end}} EXAMPLES: - 1. Check for any new official release. - $ mc {{.Name}} - - 2. Check for any new experimental release. - $ mc {{.Name}} --experimental + 1. Check if there is a new update available: + $ {{.HelpName}} `, } -// update URL endpoints. -const ( - mcUpdateStableURL = "https://dl.minio.io/client/mc/release" - mcUpdateExperimentalURL = "https://dl.minio.io/client/mc/experimental" -) - // updateMessage container to hold update messages. type updateMessage struct { - Status string `json:"status"` - Update bool `json:"update"` - Download string `json:"downloadURL"` - Version string `json:"version"` + Status string `json:"status"` + Update bool `json:"update"` + Download string `json:"downloadURL,omitempty"` + Version string `json:"version"` + olderThan time.Duration } // String colorized update message. func (u updateMessage) String() string { - if !u.Update { - return console.Colorize("Update", "You are already running the most recent version of ‘mc’.") + if u.olderThan == time.Duration(0) { + return console.Colorize("Update", "You are already running the most recent version of `mc`.") } - var msg string - if runtime.GOOS == "windows" { - msg = "Download " + u.Download - } else { - msg = "Download " + u.Download - } - msg, err := colorizeUpdateMessage(msg) - fatalIf(err.Trace(msg), "Unable to colorize experimental update notification string ‘"+msg+"’.") - return msg + return colorizeUpdateMessage(u.Download, u.olderThan) } // JSON jsonified update message. func (u updateMessage) JSON() string { u.Status = "success" + u.Update = u.olderThan != time.Duration(0) updateMessageJSONBytes, e := json.Marshal(u) fatalIf(probe.NewError(e), "Unable to marshal into JSON.") return string(updateMessageJSONBytes) } -func parseReleaseData(data string) (time.Time, *probe.Error) { - releaseStr := strings.Fields(data) - if len(releaseStr) < 2 { - return time.Time{}, probe.NewError(errors.New("Update data malformed")) - } - releaseDate := releaseStr[1] - releaseDateSplits := strings.SplitN(releaseDate, ".", 3) - if len(releaseDateSplits) < 3 { - return time.Time{}, probe.NewError(errors.New("Update data malformed")) - } - if releaseDateSplits[0] != "mc" { - return time.Time{}, probe.NewError(errors.New("Update data malformed, missing mc tag")) - } - // "OFFICIAL" tag is still kept for backward compatibility, we should remove this for the next release. - if releaseDateSplits[1] != "RELEASE" && releaseDateSplits[1] != "OFFICIAL" { - return time.Time{}, probe.NewError(errors.New("Update data malformed, missing RELEASE tag")) - } - dateSplits := strings.SplitN(releaseDateSplits[2], "T", 2) - if len(dateSplits) < 2 { - return time.Time{}, probe.NewError(errors.New("Update data malformed, not in modified RFC3359 form")) - } - dateSplits[1] = strings.Replace(dateSplits[1], "-", ":", -1) - date := strings.Join(dateSplits, "T") +const releaseTagTimeLayout = "2006-01-02T15-04-05Z" +const mcReleaseURL = "https://dl.minio.io/client/mc/release/" + runtime.GOOS + "-" + runtime.GOARCH + "/" - parsedDate, e := time.Parse(time.RFC3339, date) - if e != nil { - return time.Time{}, probe.NewError(e) +func getCurrentReleaseTime(mcVersion, mcBinaryPath string) (releaseTime time.Time, err *probe.Error) { + var e error + if releaseTime, e = time.Parse(time.RFC3339, mcVersion); e == nil { + return releaseTime, probe.NewError(e) } - return parsedDate, nil + + mcBinaryPath, e = exec.LookPath(mcBinaryPath) + if e != nil { + return releaseTime, probe.NewError(e) + } + + fi, e := os.Stat(mcBinaryPath) + if e != nil { + e = fmt.Errorf("Unable to get ModTime of %s. %s", mcBinaryPath, e) + } else { + releaseTime = fi.ModTime().UTC() + } + + return releaseTime, probe.NewError(e) } -// verify updates for releases. -func getReleaseUpdate(updateURL string) (updateMsg updateMessage, errMsg string, err *probe.Error) { - // Construct a new update url. - newUpdateURLPrefix := updateURL + "/" + runtime.GOOS + "-" + runtime.GOARCH - newUpdateURL := newUpdateURLPrefix + "/mc.shasum" +// GetCurrentReleaseTime - returns this process's release time. If it is official minio version, +// parsed version is returned else minio binary's mod time is returned. +func GetCurrentReleaseTime() (releaseTime time.Time, err *probe.Error) { + return getCurrentReleaseTime(Version, os.Args[0]) +} + +func isDocker(cgroupFile string) (bool, *probe.Error) { + cgroup, e := ioutil.ReadFile(cgroupFile) + if os.IsNotExist(e) { + e = nil + } + + return bytes.Contains(cgroup, []byte("docker")), probe.NewError(e) +} + +// IsDocker - returns if the environment is docker or not. +func IsDocker() bool { + found, err := isDocker("/proc/self/cgroup") + fatalIf(err.Trace("/proc/self/cgroup"), "Unable to validate if this is a docker container") + return found +} + +func isSourceBuild(mcVersion string) bool { + _, e := time.Parse(time.RFC3339, mcVersion) + return e != nil +} + +// IsSourceBuild - returns if this binary is made from source or not. +func IsSourceBuild() bool { + return isSourceBuild(Version) +} + +// DO NOT CHANGE USER AGENT STYLE. +// The style should be +// Minio (; [; docker][; source]) mc/ mc/ mc/ +// +// For any change here should be discussed by openning an issue at https://github.com/minio/mc/issues. +func getUserAgent() string { + userAgent := "Minio (" + runtime.GOOS + "; " + runtime.GOARCH + if IsDocker() { + userAgent += "; docker" + } + if IsSourceBuild() { + userAgent += "; source" + } + userAgent += ") " + " mc/" + Version + " mc/" + ReleaseTag + " mc/" + CommitID + + return userAgent +} + +func downloadReleaseData(releaseChecksumURL string, timeout time.Duration) (data string, err *probe.Error) { + req, e := http.NewRequest("GET", releaseChecksumURL, nil) + if e != nil { + return data, probe.NewError(e) + } + req.Header.Set("User-Agent", getUserAgent()) - // Instantiate a new client with 3 sec timeout. client := &http.Client{ - Timeout: 3 * time.Second, + Timeout: timeout, } - // Get the downloadURL. - var downloadURL string - switch runtime.GOOS { - case "windows": - // For windows and darwin. - downloadURL = newUpdateURLPrefix + "/mc.exe" - default: - // For all other operating systems. - downloadURL = newUpdateURLPrefix + "/mc" - } - - data, e := client.Get(newUpdateURL) - if e != nil { - err = probe.NewError(e) - errMsg = "Unable to read from update URL ‘" + newUpdateURL + "’." - return updateMessage{}, errMsg, err - } - if strings.HasPrefix(Version, "DEVELOPMENT.GOGET") { - err = errDummy().Trace(newUpdateURL) - errMsg = "Update mechanism is not supported for ‘go get’ based binary builds. Please download official releases from https://minio.io/#minio" - return updateMessage{}, errMsg, err - } - - current, e := time.Parse(time.RFC3339, Version) - if e != nil { - err = probe.NewError(e) - errMsg = "Unable to parse version string as time." - return updateMessage{}, errMsg, err - } - - if current.IsZero() { - err = errDummy().Trace(newUpdateURL) - errMsg = "Updates not supported for custom builds. Version field is empty. Please download official releases from https://minio.io/#minio" - return updateMessage{}, errMsg, err - } - - body, e := ioutil.ReadAll(data.Body) - if e != nil { - err = probe.NewError(e) - errMsg = "Fetching updates failed. Please try again." - return updateMessage{}, errMsg, err - } - - latest, err := parseReleaseData(string(body)) + resp, e := client.Do(req) if err != nil { - errMsg = "Please report this issue at https://github.com/minio/mc/issues." - return updateMessage{}, errMsg, err.Trace(newUpdateURL) + return data, probe.NewError(e) + } + if resp == nil { + return data, probe.NewError(fmt.Errorf("No response from server to download URL %s", releaseChecksumURL)) } - if latest.IsZero() { - err = errDummy().Trace(newUpdateURL) - errMsg = "Unable to validate any update available at this time. Please open an issue at https://github.com/minio/mc/issues" - return updateMessage{}, errMsg, err + if resp.StatusCode != http.StatusOK { + return data, probe.NewError(fmt.Errorf("Error downloading URL %s. Response: %v", releaseChecksumURL, resp.Status)) } - updateMsg = updateMessage{ - Download: downloadURL, - Version: Version, + dataBytes, e := ioutil.ReadAll(resp.Body) + if e != nil { + return data, probe.NewError(fmt.Errorf("Error reading response. %s", e)) } - if latest.After(current) { - updateMsg.Update = true - } - return updateMsg, "", nil + + data = string(dataBytes) + return data, nil } -// main entry point for update command. -func mainUpdate(ctx *cli.Context) error { +// DownloadReleaseData - downloads release data from minio official server. +func DownloadReleaseData(timeout time.Duration) (data string, err *probe.Error) { + return downloadReleaseData(mcReleaseURL+"mc.shasum", timeout) +} + +func parseReleaseData(data string) (releaseTime time.Time, err *probe.Error) { + fields := strings.Fields(data) + if len(fields) != 2 { + e := fmt.Errorf("Unknown release data `%s`", data) + return releaseTime, probe.NewError(e) + } + + releaseInfo := fields[1] + if fields = strings.Split(releaseInfo, "."); len(fields) != 3 { + e := fmt.Errorf("Unknown release information `%s`", releaseInfo) + return releaseTime, probe.NewError(e) + } + + if !(fields[0] == "mc" && fields[1] == "RELEASE") { + e := fmt.Errorf("Unknown release '%s'", releaseInfo) + return releaseTime, probe.NewError(e) + } + + var e error + releaseTime, e = time.Parse(releaseTagTimeLayout, fields[2]) + if e != nil { + e = fmt.Errorf("Unknown release time format. %s", err) + } + + return releaseTime, probe.NewError(e) +} + +func getLatestReleaseTime(timeout time.Duration) (releaseTime time.Time, err *probe.Error) { + data, err := DownloadReleaseData(timeout) + if err != nil { + return releaseTime, err.Trace() + } + return parseReleaseData(data) +} + +func getDownloadURL() (downloadURL string) { + if IsDocker() { + return "docker pull minio/mc" + } + + if runtime.GOOS == "windows" { + return mcReleaseURL + "mc.exe" + } + + return mcReleaseURL + "mc" +} + +func getUpdateInfo(timeout time.Duration) (older time.Duration, downloadURL string, err *probe.Error) { + currentReleaseTime, err := GetCurrentReleaseTime() + if err != nil { + return older, downloadURL, err.Trace() + } + + latestReleaseTime, err := getLatestReleaseTime(timeout) + if err != nil { + return older, downloadURL, err.Trace() + } + + if latestReleaseTime.After(currentReleaseTime) { + older = latestReleaseTime.Sub(currentReleaseTime) + downloadURL = getDownloadURL() + } + + return older, downloadURL, nil +} + +func mainUpdate(ctx *cli.Context) { + if len(ctx.Args()) != 0 { + cli.ShowCommandHelpAndExit(ctx, "update", -1) + } // Additional command speific theme customization. console.SetColor("Update", color.New(color.FgGreen, color.Bold)) - var updateMsg updateMessage - var errMsg string - var err *probe.Error - // Check for update. - if ctx.Bool("experimental") { - updateMsg, errMsg, err = getReleaseUpdate(mcUpdateExperimentalURL) - } else { - updateMsg, errMsg, err = getReleaseUpdate(mcUpdateStableURL) + older, downloadURL, err := getUpdateInfo(10 * time.Second) + fatalIf(err.Trace(downloadURL), "Unable to fetch update info for mc") + + if !globalQuiet { + printMsg(updateMessage{ + olderThan: older, + Download: downloadURL, + Version: Version, + }) } - fatalIf(err, errMsg) - printMsg(updateMsg) - return nil } diff --git a/cmd/utils.go b/cmd/utils.go index c57330db..967d285d 100644 --- a/cmd/utils.go +++ b/cmd/utils.go @@ -18,7 +18,7 @@ package cmd import ( "crypto/tls" - "errors" + "fmt" "io" "math/rand" "os" @@ -95,7 +95,7 @@ func splitStr(path, sep string, n int) []string { func buildS3Config(alias, urlStr string) (*Config, *probe.Error) { hostCfg := mustGetHostConfig(alias) if hostCfg == nil { - return nil, probe.NewError(errors.New("The specified alias cannot be found")) + return nil, probe.NewError(fmt.Errorf("The specified alias: %s not found", urlStr)) } // We have a valid alias and hostConfig. We populate the diff --git a/cmd/version-main.go b/cmd/version-main.go index fbd6ac44..2f6e8967 100644 --- a/cmd/version-main.go +++ b/cmd/version-main.go @@ -1,5 +1,5 @@ /* - * Minio Client (C) 2014, 2015 Minio, Inc. + * Minio Client (C) 2014, 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. @@ -26,26 +26,34 @@ import ( "github.com/minio/minio/pkg/probe" ) -var ( - versionFlags = []cli.Flag{} -) - // Print version. var versionCmd = cli.Command{ Name: "version", Usage: "Print version info.", Action: mainVersion, Before: setGlobalsFromContext, - Flags: append(versionFlags, globalFlags...), + Flags: []cli.Flag{ + cli.BoolFlag{ + Name: "quiet, q", + Usage: "Suppress chatty console output.", + }, + cli.BoolFlag{ + Name: "json", + Usage: "Enable JSON formatted output.", + }, + }, CustomHelpTemplate: `NAME: - mc {{.Name}} - {{.Usage}} + {{.HelpName}} - {{.Usage}} USAGE: - mc {{.Name}} [FLAGS] - + {{.HelpName}}{{if .VisibleFlags}} [FLAGS]{{end}} +{{if .VisibleFlags}} FLAGS: - {{range .Flags}}{{.}} - {{end}} + {{range .VisibleFlags}}{{.}} + {{end}}{{end}} +EXAMPLES: + 1. Prints the minio client version: + $ {{.HelpName}} `, } @@ -88,6 +96,8 @@ func mainVersion(ctx *cli.Context) error { verMsg.Version.Value = Version verMsg.Version.Format = "RFC3339" - printMsg(verMsg) + if !globalQuiet { + printMsg(verMsg) + } return nil } diff --git a/cmd/watch-main.go b/cmd/watch-main.go index 4beb6463..0bc4f1ce 100644 --- a/cmd/watch-main.go +++ b/cmd/watch-main.go @@ -61,29 +61,29 @@ var watchCmd = cli.Command{ Before: setGlobalsFromContext, Flags: append(watchFlags, globalFlags...), CustomHelpTemplate: `NAME: - mc {{.Name}} - {{.Usage}} + {{.HelpName}} - {{.Usage}} USAGE: - mc {{.Name}} [FLAGS] - + {{.HelpName}} [FLAGS] +{{if .VisibleFlags}} FLAGS: - {{range .Flags}}{{.}} - {{end}} + {{range .VisibleFlags}}{{.}} + {{end}}{{end}} EXAMPLES: 1. Watch new S3 operations on a minio server - $ mc {{.Name}} play/testbucket + $ {{.HelpName}} play/testbucket 2. Watch new events for a specific prefix "output/" on minio server. - $ mc {{.Name}} play/testbucket --prefix "output/" + $ {{.HelpName}} play/testbucket --prefix "output/" 3. Watch new events for a specific suffix ".jpg" on minio server. - $ mc {{.Name}} play/testbucket --suffix ".jpg" + $ {{.HelpName}} play/testbucket --suffix ".jpg" 4. Watch new events on a specific prefix and suffix on minio server. - $ mc {{.Name}} play/testbucket --suffix ".jpg" --prefix "photos/" + $ {{.HelpName}} play/testbucket --suffix ".jpg" --prefix "photos/" 5. Watch for events on local directory. - $ mc {{.Name}} /usr/share + $ {{.HelpName}} /usr/share `, } diff --git a/vendor/github.com/minio/cli/app.go b/vendor/github.com/minio/cli/app.go index 26a4d4d9..ce5f89f9 100644 --- a/vendor/github.com/minio/cli/app.go +++ b/vendor/github.com/minio/cli/app.go @@ -45,8 +45,10 @@ type App struct { Flags []Flag // Boolean to enable bash completion commands EnableBashCompletion bool - // Boolean to hide built-in help command + // Boolean to hide built-in help flag HideHelp bool + // Boolean to hide built-in help command + HideHelpCommand bool // Boolean to hide built-in version flag and the VERSION section of help HideVersion bool // Populate on app startup, only gettable through method Categories() @@ -144,9 +146,11 @@ func (a *App) Setup() { } a.Commands = newCmds - if a.Command(helpCommand.Name) == nil && !a.HideHelp { - a.Commands = append(a.Commands, helpCommand) - if (HelpFlag != BoolFlag{}) { + if a.Command(helpCommand.Name) == nil { + if !a.HideHelpCommand { + a.Commands = append(a.Commands, helpCommand) + } + if !a.HideHelp && (HelpFlag != BoolFlag{}) { a.appendFlag(HelpFlag) } } @@ -285,9 +289,11 @@ func (a *App) RunAndExitOnError() { func (a *App) RunAsSubcommand(ctx *Context) (err error) { // append help to commands if len(a.Commands) > 0 { - if a.Command(helpCommand.Name) == nil && !a.HideHelp { - a.Commands = append(a.Commands, helpCommand) - if (HelpFlag != BoolFlag{}) { + if a.Command(helpCommand.Name) == nil { + if !a.HideHelpCommand { + a.Commands = append(a.Commands, helpCommand) + } + if !a.HideHelp && (HelpFlag != BoolFlag{}) { a.appendFlag(HelpFlag) } } diff --git a/vendor/github.com/minio/cli/command.go b/vendor/github.com/minio/cli/command.go index e1e49917..e10e6881 100644 --- a/vendor/github.com/minio/cli/command.go +++ b/vendor/github.com/minio/cli/command.go @@ -51,8 +51,10 @@ type Command struct { // removed n version 2 since it only works under specific conditions so we // backport here by exposing it as an option for compatibility. SkipArgReorder bool - // Boolean to hide built-in help command + // Boolean to hide built-in help flag HideHelp bool + // Boolean to hide built-in help command + HideHelpCommand bool // Boolean to hide this command from help or completion Hidden bool @@ -249,11 +251,9 @@ func (c Command) startApp(ctx *Context) error { app.HelpName = app.Name } - if c.Description != "" { - app.Usage = c.Description - } else { - app.Usage = c.Usage - } + app.Usage = c.Usage + app.Description = c.Description + app.ArgsUsage = c.ArgsUsage // set CommandNotFound app.CommandNotFound = ctx.App.CommandNotFound @@ -263,6 +263,7 @@ func (c Command) startApp(ctx *Context) error { app.Commands = c.Subcommands app.Flags = c.Flags app.HideHelp = c.HideHelp + app.HideHelpCommand = c.HideHelpCommand app.Version = ctx.App.Version app.HideVersion = ctx.App.HideVersion @@ -270,6 +271,7 @@ func (c Command) startApp(ctx *Context) error { app.Author = ctx.App.Author app.Email = ctx.App.Email app.Writer = ctx.App.Writer + app.ErrWriter = ctx.App.ErrWriter app.categories = CommandCategories{} for _, command := range c.Subcommands { @@ -302,5 +304,13 @@ func (c Command) startApp(ctx *Context) error { // VisibleFlags returns a slice of the Flags with Hidden=false func (c Command) VisibleFlags() []Flag { - return visibleFlags(c.Flags) + flags := c.Flags + if !c.HideHelp && (HelpFlag != BoolFlag{}) { + // append help to flags + flags = append( + flags, + HelpFlag, + ) + } + return visibleFlags(flags) } diff --git a/vendor/github.com/minio/cli/errors.go b/vendor/github.com/minio/cli/errors.go index 0206ff49..f9d648e6 100644 --- a/vendor/github.com/minio/cli/errors.go +++ b/vendor/github.com/minio/cli/errors.go @@ -74,7 +74,7 @@ func (ee *ExitError) ExitCode() int { // HandleExitCoder checks if the error fulfills the ExitCoder interface, and if // so prints the error to stderr (if it is non-empty) and calls OsExiter with the // given exit code. If the given error is a MultiError, then this func is -// called on all members of the Errors slice. +// called on all members of the Errors slice and calls OsExiter with the last exit code. func HandleExitCoder(err error) { if err == nil { return @@ -93,9 +93,8 @@ func HandleExitCoder(err error) { } if multiErr, ok := err.(MultiError); ok { - for _, merr := range multiErr.Errors { - HandleExitCoder(merr) - } + code := handleMultiError(multiErr) + OsExiter(code) return } @@ -108,3 +107,18 @@ func HandleExitCoder(err error) { } OsExiter(1) } + +func handleMultiError(multiErr MultiError) int { + code := 1 + for _, merr := range multiErr.Errors { + if multiErr2, ok := merr.(MultiError); ok { + code = handleMultiError(multiErr2) + } else { + fmt.Fprintln(ErrWriter, merr) + if exitErr, ok := merr.(ExitCoder); ok { + code = exitErr.ExitCode() + } + } + } + return code +} diff --git a/vendor/github.com/minio/cli/help.go b/vendor/github.com/minio/cli/help.go index 5ed544f6..ff35ea11 100644 --- a/vendor/github.com/minio/cli/help.go +++ b/vendor/github.com/minio/cli/help.go @@ -13,69 +13,68 @@ import ( // cli.go uses text/template to render templates. You can // render custom help text by setting this variable. var AppHelpTemplate = `NAME: - {{.Name}}{{if .Usage}} - {{.Usage}}{{end}} + {{.Name}}{{if .Usage}} - {{.Usage}}{{end}} USAGE: - {{if .UsageText}}{{.UsageText}}{{else}}{{.HelpName}} {{if .VisibleFlags}}[global options]{{end}}{{if .Commands}} command [command options]{{end}} {{if .ArgsUsage}}{{.ArgsUsage}}{{else}}[arguments...]{{end}}{{end}}{{if .Version}}{{if not .HideVersion}} + {{if .UsageText}}{{.UsageText}}{{else}}{{.HelpName}} {{if .VisibleFlags}}[global options]{{end}}{{if .Commands}} command [command options]{{end}} {{if .ArgsUsage}}{{.ArgsUsage}}{{else}}[arguments...]{{end}}{{end}}{{if .Version}}{{if not .HideVersion}} VERSION: - {{.Version}}{{end}}{{end}}{{if .Description}} + {{.Version}}{{end}}{{end}}{{if .Description}} DESCRIPTION: - {{.Description}}{{end}}{{if len .Authors}} + {{.Description}}{{end}}{{if len .Authors}} AUTHOR{{with $length := len .Authors}}{{if ne 1 $length}}S{{end}}{{end}}: - {{range $index, $author := .Authors}}{{if $index}} - {{end}}{{$author}}{{end}}{{end}}{{if .VisibleCommands}} + {{range $index, $author := .Authors}}{{if $index}} + {{end}}{{$author}}{{end}}{{end}}{{if .VisibleCommands}} COMMANDS:{{range .VisibleCategories}}{{if .Name}} - {{.Name}}:{{end}}{{range .VisibleCommands}} - {{join .Names ", "}}{{"\t"}}{{.Usage}}{{end}}{{end}}{{end}}{{if .VisibleFlags}} + {{.Name}}:{{end}}{{range .VisibleCommands}} + {{join .Names ", "}}{{"\t"}}{{.Usage}}{{end}}{{end}}{{end}}{{if .VisibleFlags}} -GLOBAL OPTIONS: - {{range $index, $option := .VisibleFlags}}{{if $index}} - {{end}}{{$option}}{{end}}{{end}}{{if .Copyright}} +GLOBAL FLAGS: + {{range $index, $option := .VisibleFlags}}{{if $index}} + {{end}}{{$option}}{{end}}{{end}}{{if .Copyright}} COPYRIGHT: - {{.Copyright}}{{end}} + {{.Copyright}}{{end}} ` // CommandHelpTemplate is the text template for the command help topic. // cli.go uses text/template to render templates. You can // render custom help text by setting this variable. var CommandHelpTemplate = `NAME: - {{.HelpName}} - {{.Usage}} + {{.HelpName}} - {{.Usage}} USAGE: - {{.HelpName}}{{if .VisibleFlags}} [command options]{{end}} {{if .ArgsUsage}}{{.ArgsUsage}}{{else}}[arguments...]{{end}}{{if .Category}} + {{.HelpName}}{{if .VisibleFlags}} [command options]{{end}} {{if .ArgsUsage}}{{.ArgsUsage}}{{else}}[arguments...]{{end}}{{if .Category}} CATEGORY: - {{.Category}}{{end}}{{if .Description}} + {{.Category}}{{end}}{{if .Description}} DESCRIPTION: - {{.Description}}{{end}}{{if .VisibleFlags}} + {{.Description}}{{end}}{{if .VisibleFlags}} -OPTIONS: - {{range .VisibleFlags}}{{.}} - {{end}}{{end}} +FLAGS: + {{range .VisibleFlags}}{{.}} + {{end}}{{end}} ` // SubcommandHelpTemplate is the text template for the subcommand help topic. // cli.go uses text/template to render templates. You can // render custom help text by setting this variable. var SubcommandHelpTemplate = `NAME: - {{.HelpName}} - {{.Usage}} + {{.HelpName}} - {{if .Description}}{{.Description}}{{else}}{{.Usage}}{{end}} USAGE: - {{.HelpName}} command{{if .VisibleFlags}} [command options]{{end}} {{if .ArgsUsage}}{{.ArgsUsage}}{{else}}[arguments...]{{end}} + {{.HelpName}} COMMAND{{if .VisibleFlags}} [COMMAND FLAGS | -h]{{end}} [ARGUMENTS...] -COMMANDS:{{range .VisibleCategories}}{{if .Name}} - {{.Name}}:{{end}}{{range .VisibleCommands}} - {{join .Names ", "}}{{"\t"}}{{.Usage}}{{end}} -{{end}}{{if .VisibleFlags}} -OPTIONS: - {{range .VisibleFlags}}{{.}} - {{end}}{{end}} +COMMANDS: + {{range .VisibleCommands}}{{join .Names ", "}}{{ "\t" }}{{.Usage}} + {{end}}{{if .VisibleFlags}} +FLAGS: + {{range .VisibleFlags}}{{.}} + {{end}}{{end}} ` var helpCommand = Command{ @@ -120,7 +119,7 @@ type helpPrinterCustom func(w io.Writer, templ string, data interface{}, customF // func(w io.Writer, templ string, data interface{}) var HelpPrinter helpPrinter = printHelp -// HelPrinterCustom is same as HelpPrinter but +// HelpPrinterCustom is same as HelpPrinter but // takes a custom function for template function map. var HelpPrinterCustom helpPrinterCustom = printHelpCustom @@ -134,18 +133,20 @@ func ShowAppHelpAndExit(c *Context, exitCode int) { } // ShowAppHelp is an action that displays the help. -func ShowAppHelp(c *Context) error { - if c.App.CustomAppHelpTemplate != "" { - if c.App.ExtraInfo != nil { - HelpPrinterCustom(c.App.Writer, c.App.CustomAppHelpTemplate, c.App, map[string]interface{}{ - "ExtraInfo": c.App.ExtraInfo, - }) - } else { - HelpPrinter(c.App.Writer, c.App.CustomAppHelpTemplate, c.App) - } - } else { +func ShowAppHelp(c *Context) (err error) { + if c.App.CustomAppHelpTemplate == "" { HelpPrinter(c.App.Writer, AppHelpTemplate, c.App) + return } + customAppData := func() map[string]interface{} { + if c.App.ExtraInfo == nil { + return nil + } + return map[string]interface{}{ + "ExtraInfo": c.App.ExtraInfo, + } + } + HelpPrinterCustom(c.App.Writer, c.App.CustomAppHelpTemplate, c.App, customAppData()) return nil } diff --git a/vendor/github.com/minio/minio-go/api-get-object.go b/vendor/github.com/minio/minio-go/api-get-object.go index c9b4dced..ade94c2d 100644 --- a/vendor/github.com/minio/minio-go/api-get-object.go +++ b/vendor/github.com/minio/minio-go/api-get-object.go @@ -26,6 +26,29 @@ import ( "time" ) +// 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) { + + if encryptMaterials == nil { + return nil, ErrInvalidArgument("Unable to recognize empty encryption properties") + } + + // Fetch encrypted object + encReader, err := c.GetObject(bucketName, objectName) + if err != nil { + return nil, err + } + // Stat object to get its encryption metadata + st, err := encReader.Stat() + if err != nil { + return nil, err + } + + encryptMaterials.SetupDecryptMode(encReader, st.Metadata) + + return encryptMaterials, nil +} + // GetObject - returns an seekable, readable object. func (c Client) GetObject(bucketName, objectName string) (*Object, error) { // Input validation. @@ -212,10 +235,12 @@ type Object struct { reqCh chan<- getRequest resCh <-chan getResponse doneCh chan<- struct{} - prevOffset int64 currOffset int64 objectInfo ObjectInfo + // Ask lower level to initiate data fetching based on currOffset + seekData bool + // Keeps track of closed call. isClosed bool @@ -258,6 +283,10 @@ func (o *Object) doGetRequest(request getRequest) (getResponse, error) { if response.Error != nil { return response, response.Error } + + // Data are ready on the wire, no need to reinitiate connection in lower level + o.seekData = false + return response, nil } @@ -266,8 +295,6 @@ func (o *Object) doGetRequest(request getRequest) (getResponse, error) { func (o *Object) setOffset(bytesRead int64) error { // Update the currentOffset. o.currOffset += bytesRead - // Save the current offset as previous offset. - o.prevOffset = o.currOffset if o.currOffset >= o.objectInfo.Size { return io.EOF @@ -303,22 +330,9 @@ func (o *Object) Read(b []byte) (n int, err error) { readReq.isFirstReq = true } - // Verify if offset has changed and currOffset is greater than - // previous offset. Perhaps due to Seek(). - offsetChange := o.prevOffset - o.currOffset - if offsetChange < 0 { - offsetChange = -offsetChange - } - if offsetChange > 0 { - // Fetch the new reader at the current offset again. - readReq.Offset = o.currOffset - readReq.DidOffsetChange = true - } else { - // No offset changes no need to fetch new reader, continue - // reading. - readReq.DidOffsetChange = false - readReq.Offset = 0 - } + // Ask to establish a new data fetch routine based on seekData flag + readReq.DidOffsetChange = o.seekData + readReq.Offset = o.currOffset // Send and receive from the first request. response, err := o.doGetRequest(readReq) @@ -430,8 +444,6 @@ func (o *Object) ReadAt(b []byte, offset int64) (n int, err error) { if !o.objectInfoSet { // Update the currentOffset. o.currOffset += bytesRead - // Save the current offset as previous offset. - o.prevOffset = o.currOffset } else { // If this was not the first request update // the offsets and compare against objectInfo @@ -492,8 +504,6 @@ func (o *Object) Seek(offset int64, whence int) (n int64, err error) { return 0, err } } - // Save current offset as previous offset. - o.prevOffset = o.currOffset // Switch through whence. switch whence { @@ -527,6 +537,10 @@ func (o *Object) Seek(offset int64, whence int) (n int64, err error) { if o.prevErr == io.EOF { o.prevErr = nil } + + // Ask lower level to fetch again from source + o.seekData = true + // Return the effective offset. return o.currOffset, nil } diff --git a/vendor/github.com/minio/minio-go/api-list.go b/vendor/github.com/minio/minio-go/api-list.go index adfaa0a7..25bea39e 100644 --- a/vendor/github.com/minio/minio-go/api-list.go +++ b/vendor/github.com/minio/minio-go/api-list.go @@ -347,14 +347,14 @@ func (c Client) ListObjects(bucketName, objectPrefix string, recursive bool, don // ?delimiter - A delimiter is a character you use to group keys. // ?prefix - Limits the response to keys that begin with the specified prefix. // ?max-keys - Sets the maximum number of keys returned in the response body. -func (c Client) listObjectsQuery(bucketName, objectPrefix, objectMarker, delimiter string, maxkeys int) (listBucketResult, error) { +func (c Client) listObjectsQuery(bucketName, objectPrefix, objectMarker, delimiter string, maxkeys int) (ListBucketResult, error) { // Validate bucket name. if err := isValidBucketName(bucketName); err != nil { - return listBucketResult{}, err + return ListBucketResult{}, err } // Validate object prefix. if err := isValidObjectPrefix(objectPrefix); err != nil { - return listBucketResult{}, err + return ListBucketResult{}, err } // Get resources properly escaped and lined up before // using them in http request. @@ -386,15 +386,15 @@ func (c Client) listObjectsQuery(bucketName, objectPrefix, objectMarker, delimit }) defer closeResponse(resp) if err != nil { - return listBucketResult{}, err + return ListBucketResult{}, err } if resp != nil { if resp.StatusCode != http.StatusOK { - return listBucketResult{}, httpRespToErrorResponse(resp, bucketName, "") + return ListBucketResult{}, httpRespToErrorResponse(resp, bucketName, "") } } // Decode listBuckets XML. - listBucketResult := listBucketResult{} + listBucketResult := ListBucketResult{} err = xmlDecoder(resp.Body, &listBucketResult) if err != nil { return listBucketResult, err @@ -528,7 +528,7 @@ func (c Client) listIncompleteUploads(bucketName, objectPrefix string, recursive // ?delimiter - A delimiter is a character you use to group keys. // ?prefix - Limits the response to keys that begin with the specified prefix. // ?max-uploads - Sets the maximum number of multipart uploads returned in the response body. -func (c Client) listMultipartUploadsQuery(bucketName, keyMarker, uploadIDMarker, prefix, delimiter string, maxUploads int) (listMultipartUploadsResult, error) { +func (c Client) listMultipartUploadsQuery(bucketName, keyMarker, uploadIDMarker, prefix, delimiter string, maxUploads int) (ListMultipartUploadsResult, error) { // Get resources properly escaped and lined up before using them in http request. urlValues := make(url.Values) // Set uploads. @@ -564,15 +564,15 @@ func (c Client) listMultipartUploadsQuery(bucketName, keyMarker, uploadIDMarker, }) defer closeResponse(resp) if err != nil { - return listMultipartUploadsResult{}, err + return ListMultipartUploadsResult{}, err } if resp != nil { if resp.StatusCode != http.StatusOK { - return listMultipartUploadsResult{}, httpRespToErrorResponse(resp, bucketName, "") + return ListMultipartUploadsResult{}, httpRespToErrorResponse(resp, bucketName, "") } } // Decode response body. - listMultipartUploadsResult := listMultipartUploadsResult{} + listMultipartUploadsResult := ListMultipartUploadsResult{} err = xmlDecoder(resp.Body, &listMultipartUploadsResult) if err != nil { return listMultipartUploadsResult, err @@ -581,10 +581,10 @@ func (c Client) listMultipartUploadsQuery(bucketName, keyMarker, uploadIDMarker, } // listObjectParts list all object parts recursively. -func (c Client) listObjectParts(bucketName, objectName, uploadID string) (partsInfo map[int]objectPart, err error) { +func (c Client) listObjectParts(bucketName, objectName, uploadID string) (partsInfo map[int]ObjectPart, err error) { // Part number marker for the next batch of request. var nextPartNumberMarker int - partsInfo = make(map[int]objectPart) + partsInfo = make(map[int]ObjectPart) for { // Get list of uploaded parts a maximum of 1000 per request. listObjPartsResult, err := c.listObjectPartsQuery(bucketName, objectName, uploadID, nextPartNumberMarker, 1000) @@ -659,7 +659,7 @@ func (c Client) getTotalMultipartSize(bucketName, objectName, uploadID string) ( // ?part-number-marker - Specifies the part after which listing should // begin. // ?max-parts - Maximum parts to be listed per request. -func (c Client) listObjectPartsQuery(bucketName, objectName, uploadID string, partNumberMarker, maxParts int) (listObjectPartsResult, error) { +func (c Client) listObjectPartsQuery(bucketName, objectName, uploadID string, partNumberMarker, maxParts int) (ListObjectPartsResult, error) { // Get resources properly escaped and lined up before using them in http request. urlValues := make(url.Values) // Set part number marker. @@ -682,15 +682,15 @@ func (c Client) listObjectPartsQuery(bucketName, objectName, uploadID string, pa }) defer closeResponse(resp) if err != nil { - return listObjectPartsResult{}, err + return ListObjectPartsResult{}, err } if resp != nil { if resp.StatusCode != http.StatusOK { - return listObjectPartsResult{}, httpRespToErrorResponse(resp, bucketName, objectName) + return ListObjectPartsResult{}, httpRespToErrorResponse(resp, bucketName, objectName) } } // Decode list object parts XML. - listObjectPartsResult := listObjectPartsResult{} + listObjectPartsResult := ListObjectPartsResult{} err = xmlDecoder(resp.Body, &listObjectPartsResult) if err != nil { return listObjectPartsResult, err diff --git a/vendor/github.com/minio/minio-go/api-put-object-common.go b/vendor/github.com/minio/minio-go/api-put-object-common.go index 5f5f568e..68a459f4 100644 --- a/vendor/github.com/minio/minio-go/api-put-object-common.go +++ b/vendor/github.com/minio/minio-go/api-put-object-common.go @@ -44,7 +44,7 @@ func isReadAt(reader io.Reader) (ok bool) { } // shouldUploadPart - verify if part should be uploaded. -func shouldUploadPart(objPart objectPart, uploadReq uploadPartReq) bool { +func shouldUploadPart(objPart ObjectPart, uploadReq uploadPartReq) bool { // If part not found should upload the part. if uploadReq.Part == nil { return true @@ -185,9 +185,9 @@ func (c Client) newUploadID(bucketName, objectName string, metaData map[string][ // getMpartUploadSession returns the upload id and the uploaded parts to continue a previous upload session // or initiate a new multipart session if no current one found -func (c Client) getMpartUploadSession(bucketName, objectName string, metaData map[string][]string) (string, map[int]objectPart, error) { +func (c Client) getMpartUploadSession(bucketName, objectName string, metaData map[string][]string) (string, map[int]ObjectPart, error) { // A map of all uploaded parts. - var partsInfo map[int]objectPart + var partsInfo map[int]ObjectPart var err error uploadID, err := c.findUploadID(bucketName, objectName) @@ -220,7 +220,7 @@ func (c Client) getMpartUploadSession(bucketName, objectName string, metaData ma // Allocate partsInfo if not done yet if partsInfo == nil { - partsInfo = make(map[int]objectPart) + partsInfo = make(map[int]ObjectPart) } return uploadID, partsInfo, nil diff --git a/vendor/github.com/minio/minio-go/api-put-object-file.go b/vendor/github.com/minio/minio-go/api-put-object-file.go index aa554b32..f67999f9 100644 --- a/vendor/github.com/minio/minio-go/api-put-object-file.go +++ b/vendor/github.com/minio/minio-go/api-put-object-file.go @@ -228,7 +228,7 @@ func (c Client) putObjectMultipartFromFile(bucketName, objectName string, fileRe } // Create the part to be uploaded. - verifyObjPart := objectPart{ + verifyObjPart := ObjectPart{ ETag: hex.EncodeToString(hashSums["md5"]), PartNumber: uploadReq.PartNum, Size: partSize, @@ -242,7 +242,7 @@ func (c Client) putObjectMultipartFromFile(bucketName, objectName string, fileRe // Verify if part should be uploaded. if shouldUploadPart(verifyObjPart, uploadReq) { // Proceed to upload the part. - var objPart objectPart + var objPart ObjectPart objPart, err = c.uploadPart(bucketName, objectName, uploadID, sectionReader, uploadReq.PartNum, hashSums["md5"], hashSums["sha256"], prtSize) if err != nil { uploadedPartsCh <- uploadedPartRes{ @@ -285,7 +285,7 @@ func (c Client) putObjectMultipartFromFile(bucketName, objectName string, fileRe } } // Store the part to be completed. - complMultipartUpload.Parts = append(complMultipartUpload.Parts, completePart{ + complMultipartUpload.Parts = append(complMultipartUpload.Parts, CompletePart{ ETag: part.ETag, PartNumber: part.PartNumber, }) diff --git a/vendor/github.com/minio/minio-go/api-put-object-multipart.go b/vendor/github.com/minio/minio-go/api-put-object-multipart.go index f74eae62..6ca44b21 100644 --- a/vendor/github.com/minio/minio-go/api-put-object-multipart.go +++ b/vendor/github.com/minio/minio-go/api-put-object-multipart.go @@ -113,10 +113,8 @@ func (c Client) putObjectMultipartStream(bucketName, objectName string, reader i // Calculates hash sums while copying partSize bytes into tmpBuffer. prtSize, rErr := hashCopyN(hashAlgos, hashSums, tmpBuffer, reader, partSize) - if rErr != nil { - if rErr != io.EOF { - return 0, rErr - } + if rErr != nil && rErr != io.EOF { + return 0, rErr } var reader io.Reader @@ -127,13 +125,13 @@ func (c Client) putObjectMultipartStream(bucketName, objectName string, reader i part, ok := partsInfo[partNumber] // Verify if part should be uploaded. - if !ok || shouldUploadPart(objectPart{ + if !ok || shouldUploadPart(ObjectPart{ ETag: hex.EncodeToString(hashSums["md5"]), PartNumber: partNumber, Size: prtSize, }, uploadPartReq{PartNum: partNumber, Part: &part}) { // Proceed to upload the part. - var objPart objectPart + var objPart ObjectPart objPart, err = c.uploadPart(bucketName, objectName, uploadID, reader, partNumber, hashSums["md5"], hashSums["sha256"], prtSize) if err != nil { // Reset the temporary buffer upon any error. @@ -181,7 +179,7 @@ func (c Client) putObjectMultipartStream(bucketName, objectName string, reader i if !ok { return 0, ErrInvalidArgument(fmt.Sprintf("Missing part number %d", i)) } - complMultipartUpload.Parts = append(complMultipartUpload.Parts, completePart{ + complMultipartUpload.Parts = append(complMultipartUpload.Parts, CompletePart{ ETag: part.ETag, PartNumber: part.PartNumber, }) @@ -253,25 +251,25 @@ func (c Client) initiateMultipartUpload(bucketName, objectName string, metaData } // uploadPart - Uploads a part in a multipart upload. -func (c Client) uploadPart(bucketName, objectName, uploadID string, reader io.Reader, partNumber int, md5Sum, sha256Sum []byte, size int64) (objectPart, error) { +func (c Client) uploadPart(bucketName, objectName, uploadID string, reader io.Reader, partNumber int, md5Sum, sha256Sum []byte, size int64) (ObjectPart, error) { // Input validation. if err := isValidBucketName(bucketName); err != nil { - return objectPart{}, err + return ObjectPart{}, err } if err := isValidObjectName(objectName); err != nil { - return objectPart{}, err + return ObjectPart{}, err } if size > maxPartSize { - return objectPart{}, ErrEntityTooLarge(size, maxPartSize, bucketName, objectName) + return ObjectPart{}, ErrEntityTooLarge(size, maxPartSize, bucketName, objectName) } if size <= -1 { - return objectPart{}, ErrEntityTooSmall(size, bucketName, objectName) + return ObjectPart{}, ErrEntityTooSmall(size, bucketName, objectName) } if partNumber <= 0 { - return objectPart{}, ErrInvalidArgument("Part number cannot be negative or equal to zero.") + return ObjectPart{}, ErrInvalidArgument("Part number cannot be negative or equal to zero.") } if uploadID == "" { - return objectPart{}, ErrInvalidArgument("UploadID cannot be empty.") + return ObjectPart{}, ErrInvalidArgument("UploadID cannot be empty.") } // Get resources properly escaped and lined up before using them in http request. @@ -295,15 +293,15 @@ func (c Client) uploadPart(bucketName, objectName, uploadID string, reader io.Re resp, err := c.executeMethod("PUT", reqMetadata) defer closeResponse(resp) if err != nil { - return objectPart{}, err + return ObjectPart{}, err } if resp != nil { if resp.StatusCode != http.StatusOK { - return objectPart{}, httpRespToErrorResponse(resp, bucketName, objectName) + return ObjectPart{}, httpRespToErrorResponse(resp, bucketName, objectName) } } // Once successfully uploaded, return completed part. - objPart := objectPart{} + objPart := ObjectPart{} objPart.Size = size objPart.PartNumber = partNumber // Trim off the odd double quotes from ETag in the beginning and end. diff --git a/vendor/github.com/minio/minio-go/api-put-object-progress.go b/vendor/github.com/minio/minio-go/api-put-object-progress.go index 42f8ce4d..43f39c0f 100644 --- a/vendor/github.com/minio/minio-go/api-put-object-progress.go +++ b/vendor/github.com/minio/minio-go/api-put-object-progress.go @@ -30,6 +30,27 @@ func (c Client) PutObjectWithProgress(bucketName, objectName string, reader io.R return c.PutObjectWithMetadata(bucketName, objectName, reader, metaData, progress) } +// 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) { + + if encryptMaterials == nil { + return 0, ErrInvalidArgument("Unable to recognize empty encryption properties") + } + + if err := encryptMaterials.SetupEncryptMode(reader); err != nil { + return 0, err + } + + if metaData == nil { + metaData = make(map[string][]string) + } + for k, v := range encryptMaterials.GetHeaders() { + metaData[k] = v + } + + return c.PutObjectWithMetadata(bucketName, objectName, encryptMaterials, metaData, progress) +} + // PutObjectWithMetadata - with metadata. func (c Client) PutObjectWithMetadata(bucketName, objectName string, reader io.Reader, metaData map[string][]string, progress io.Reader) (n int64, err error) { // Input validation. diff --git a/vendor/github.com/minio/minio-go/api-put-object-readat.go b/vendor/github.com/minio/minio-go/api-put-object-readat.go index 4ab1095f..c2cf56e0 100644 --- a/vendor/github.com/minio/minio-go/api-put-object-readat.go +++ b/vendor/github.com/minio/minio-go/api-put-object-readat.go @@ -32,16 +32,16 @@ type uploadedPartRes struct { Error error // Any error encountered while uploading the part. PartNum int // Number of the part uploaded. Size int64 // Size of the part uploaded. - Part *objectPart + Part *ObjectPart } type uploadPartReq struct { PartNum int // Number of the part uploaded. - Part *objectPart // Size of the part uploaded. + Part *ObjectPart // Size of the part uploaded. } // shouldUploadPartReadAt - verify if part should be uploaded. -func shouldUploadPartReadAt(objPart objectPart, uploadReq uploadPartReq) bool { +func shouldUploadPartReadAt(objPart ObjectPart, uploadReq uploadPartReq) bool { // If part not found part should be uploaded. if uploadReq.Part == nil { return true @@ -164,7 +164,7 @@ func (c Client) putObjectMultipartFromReadAt(bucketName, objectName string, read } // Verify object if its uploaded. - verifyObjPart := objectPart{ + verifyObjPart := ObjectPart{ PartNumber: uploadReq.PartNum, Size: partSize, } @@ -178,7 +178,7 @@ func (c Client) putObjectMultipartFromReadAt(bucketName, objectName string, read // to update any progress bar. if shouldUploadPartReadAt(verifyObjPart, uploadReq) { // Proceed to upload the part. - var objPart objectPart + var objPart ObjectPart objPart, err = c.uploadPart(bucketName, objectName, uploadID, tmpBuffer, uploadReq.PartNum, hashSums["md5"], hashSums["sha256"], prtSize) if err != nil { uploadedPartsCh <- uploadedPartRes{ @@ -224,7 +224,7 @@ func (c Client) putObjectMultipartFromReadAt(bucketName, objectName string, read } } // Store the parts to be completed in order. - complMultipartUpload.Parts = append(complMultipartUpload.Parts, completePart{ + complMultipartUpload.Parts = append(complMultipartUpload.Parts, CompletePart{ ETag: part.ETag, PartNumber: part.PartNumber, }) diff --git a/vendor/github.com/minio/minio-go/api-put-object.go b/vendor/github.com/minio/minio-go/api-put-object.go index a779fbeb..bc2eeb25 100644 --- a/vendor/github.com/minio/minio-go/api-put-object.go +++ b/vendor/github.com/minio/minio-go/api-put-object.go @@ -125,7 +125,7 @@ func getReaderSize(reader io.Reader) (size int64, err error) { // completedParts is a collection of parts sortable by their part numbers. // used for sorting the uploaded parts before completing the multipart request. -type completedParts []completePart +type completedParts []CompletePart func (a completedParts) Len() int { return len(a) } func (a completedParts) Swap(i, j int) { a[i], a[j] = a[j], a[i] } @@ -230,10 +230,8 @@ func (c Client) putObjectSingle(bucketName, objectName string, reader io.Reader, reader = tmpFile } // Return error if its not io.EOF. - if err != nil { - if err != io.EOF { - return 0, err - } + if err != nil && err != io.EOF { + return 0, err } // Execute put object. st, err := c.putObjectDo(bucketName, objectName, reader, hashSums["md5"], hashSums["sha256"], size, metaData) diff --git a/vendor/github.com/minio/minio-go/api-s3-datatypes.go b/vendor/github.com/minio/minio-go/api-s3-datatypes.go index a34f82e9..fd9fc7fd 100644 --- a/vendor/github.com/minio/minio-go/api-s3-datatypes.go +++ b/vendor/github.com/minio/minio-go/api-s3-datatypes.go @@ -71,7 +71,7 @@ type listBucketV2Result struct { } // listBucketResult container for listObjects response. -type listBucketResult struct { +type ListBucketResult struct { // A response can contain CommonPrefixes only if you have // specified a delimiter. CommonPrefixes []commonPrefix @@ -103,7 +103,7 @@ type listBucketResult struct { } // listMultipartUploadsResult container for ListMultipartUploads response -type listMultipartUploadsResult struct { +type ListMultipartUploadsResult struct { Bucket string KeyMarker string UploadIDMarker string `xml:"UploadIdMarker"` @@ -132,7 +132,7 @@ type copyObjectResult struct { } // objectPart container for particular part of an object. -type objectPart struct { +type ObjectPart struct { // Part number identifies the part. PartNumber int @@ -148,7 +148,7 @@ type objectPart struct { } // listObjectPartsResult container for ListObjectParts response. -type listObjectPartsResult struct { +type ListObjectPartsResult struct { Bucket string Key string UploadID string `xml:"UploadId"` @@ -163,7 +163,7 @@ type listObjectPartsResult struct { // Indicates whether the returned list of parts is truncated. IsTruncated bool - ObjectParts []objectPart `xml:"Part"` + ObjectParts []ObjectPart `xml:"Part"` EncodingType string } @@ -187,7 +187,7 @@ type completeMultipartUploadResult struct { // completePart sub container lists individual part numbers and their // md5sum, part of completeMultipartUpload. -type completePart struct { +type CompletePart struct { XMLName xml.Name `xml:"http://s3.amazonaws.com/doc/2006-03-01/ Part" json:"-"` // Part number identifies the part. @@ -198,7 +198,7 @@ type completePart struct { // completeMultipartUpload container for completing multipart upload. type completeMultipartUpload struct { XMLName xml.Name `xml:"http://s3.amazonaws.com/doc/2006-03-01/ CompleteMultipartUpload" json:"-"` - Parts []completePart `xml:"Part"` + Parts []CompletePart `xml:"Part"` } // createBucketConfiguration container for bucket configuration. diff --git a/vendor/github.com/minio/minio-go/api.go b/vendor/github.com/minio/minio-go/api.go index 1231ddf4..2beba77b 100644 --- a/vendor/github.com/minio/minio-go/api.go +++ b/vendor/github.com/minio/minio-go/api.go @@ -74,6 +74,9 @@ type Client struct { // S3 specific accelerated endpoint. s3AccelerateEndpoint string + // Region endpoint + region string + // Random seed. random *rand.Rand } @@ -81,7 +84,7 @@ type Client struct { // Global constants. const ( libraryName = "minio-go" - libraryVersion = "2.0.3" + libraryVersion = "2.0.4" ) // User Agent should always following the below style. @@ -100,6 +103,7 @@ func NewV2(endpoint string, accessKeyID, secretAccessKey string, secure bool) (* if err != nil { return nil, err } + // Set to use signature version '2'. clnt.signature = SignatureV2 return clnt, nil @@ -112,26 +116,40 @@ func NewV4(endpoint string, accessKeyID, secretAccessKey string, secure bool) (* if err != nil { return nil, err } + // Set to use signature version '4'. clnt.signature = SignatureV4 return clnt, nil } -// New - instantiate minio client Client, adds automatic verification -// of signature. -func New(endpoint string, accessKeyID, secretAccessKey string, secure bool) (*Client, error) { +// New - instantiate minio client Client, adds automatic verification of signature. +func New(endpoint, accessKeyID, secretAccessKey string, secure bool) (*Client, error) { + return NewWithRegion(endpoint, accessKeyID, secretAccessKey, secure, "") +} + +// NewWithRegion - instantiate minio client, with region configured. Unlike New(), +// NewWithRegion avoids bucket-location lookup operations and it is slightly faster. +// Use this function when if your application deals with single region. +func NewWithRegion(endpoint, accessKeyID, secretAccessKey string, secure bool, region string) (*Client, error) { clnt, err := privateNew(endpoint, accessKeyID, secretAccessKey, secure) if err != nil { return nil, err } + // Google cloud storage should be set to signature V2, force it if not. if s3utils.IsGoogleEndpoint(clnt.endpointURL) { clnt.signature = SignatureV2 } + // If Amazon S3 set to signature v2.n if s3utils.IsAmazonEndpoint(clnt.endpointURL) { clnt.signature = SignatureV4 } + + // Sets custom region, if region is empty bucket location cache is used automatically. + clnt.region = region + + // Success.. return clnt, nil } @@ -141,8 +159,7 @@ type lockedRandSource struct { src rand.Source } -// Int63 returns a non-negative pseudo-random 63-bit integer as an -// int64. +// Int63 returns a non-negative pseudo-random 63-bit integer as an int64. func (r *lockedRandSource) Int63() (n int64) { r.lk.Lock() n = r.src.Int63() @@ -588,7 +605,7 @@ func (c Client) newRequest(method string, metadata requestMetadata) (req *http.R } // Initialize a new HTTP request for the method. - req, err = http.NewRequest(method, targetURL.String(), nil) + req, err = http.NewRequest(method, targetURL.String(), metadata.contentBody) if err != nil { return nil, err } @@ -608,11 +625,6 @@ func (c Client) newRequest(method string, metadata requestMetadata) (req *http.R return req, nil } - // Set content body if available. - if metadata.contentBody != nil { - req.Body = ioutil.NopCloser(metadata.contentBody) - } - // 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 diff --git a/vendor/github.com/minio/minio-go/bucket-cache.go b/vendor/github.com/minio/minio-go/bucket-cache.go index c35e26b7..28799c69 100644 --- a/vendor/github.com/minio/minio-go/bucket-cache.go +++ b/vendor/github.com/minio/minio-go/bucket-cache.go @@ -21,7 +21,6 @@ import ( "net/http" "net/url" "path" - "strings" "sync" "github.com/minio/minio-go/pkg/s3signer" @@ -84,9 +83,6 @@ func (c Client) getBucketLocation(bucketName string) (string, error) { if err := isValidBucketName(bucketName); err != nil { return "", err } - if location, ok := c.bucketLocCache.Get(bucketName); ok { - return location, nil - } if s3utils.IsAmazonChinaEndpoint(c.endpointURL) { // For china specifically we need to set everything to @@ -96,6 +92,15 @@ func (c Client) getBucketLocation(bucketName string) (string, error) { return "cn-north-1", nil } + // Region set then no need to fetch bucket location. + if c.region != "" { + return c.region, nil + } + + if location, ok := c.bucketLocCache.Get(bucketName); ok { + return location, nil + } + // Initialize a new request. req, err := c.getBucketLocationRequest(bucketName) if err != nil { @@ -125,7 +130,7 @@ func processBucketLocationResponse(resp *http.Response, bucketName string) (buck // For access denied error, it could be an anonymous // request. Move forward and let the top level callers // succeed if possible based on their policy. - if errResp.Code == "AccessDenied" && strings.Contains(errResp.Message, "Access Denied") { + if errResp.Code == "AccessDenied" { return "us-east-1", nil } return "", err diff --git a/vendor/github.com/minio/minio-go/bucket-notification.go b/vendor/github.com/minio/minio-go/bucket-notification.go index 4f60f1c8..5ac52e5f 100644 --- a/vendor/github.com/minio/minio-go/bucket-notification.go +++ b/vendor/github.com/minio/minio-go/bucket-notification.go @@ -28,10 +28,13 @@ type NotificationEventType string // http://docs.aws.amazon.com/AmazonS3/latest/dev/NotificationHowTo.html#notification-how-to-event-types-and-destinations const ( ObjectCreatedAll NotificationEventType = "s3:ObjectCreated:*" - ObjectCreatePut = "s3:ObjectCreated:Put" + ObjectCreatedPut = "s3:ObjectCreated:Put" ObjectCreatedPost = "s3:ObjectCreated:Post" ObjectCreatedCopy = "s3:ObjectCreated:Copy" - ObjectCreatedCompleteMultipartUpload = "sh:ObjectCreated:CompleteMultipartUpload" + ObjectCreatedCompleteMultipartUpload = "s3:ObjectCreated:CompleteMultipartUpload" + ObjectAccessedGet = "s3:ObjectAccessed:Get" + ObjectAccessedHead = "s3:ObjectAccessed:Head" + ObjectAccessedAll = "s3:ObjectAccessed:*" ObjectRemovedAll = "s3:ObjectRemoved:*" ObjectRemovedDelete = "s3:ObjectRemoved:Delete" ObjectRemovedDeleteMarkerCreated = "s3:ObjectRemoved:DeleteMarkerCreated" diff --git a/vendor/github.com/minio/minio-go/copy-conditions.go b/vendor/github.com/minio/minio-go/copy-conditions.go index 5dcdfaef..65018aa0 100644 --- a/vendor/github.com/minio/minio-go/copy-conditions.go +++ b/vendor/github.com/minio/minio-go/copy-conditions.go @@ -41,11 +41,13 @@ type CopyConditions struct { conditions []copyCondition } -// NewCopyConditions - Instantiate new list of conditions. +// NewCopyConditions - Instantiate new list of conditions. This +// function is left behind for backward compatibility. The idiomatic +// way to set an empty set of copy conditions is, +// ``copyConditions := CopyConditions{}``. +// func NewCopyConditions() CopyConditions { - return CopyConditions{ - conditions: make([]copyCondition, 0), - } + return CopyConditions{} } // SetMatchETag - set match etag. diff --git a/vendor/github.com/minio/minio-go/core.go b/vendor/github.com/minio/minio-go/core.go new file mode 100644 index 00000000..ba12d3b8 --- /dev/null +++ b/vendor/github.com/minio/minio-go/core.go @@ -0,0 +1,108 @@ +/* + * 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 + +import "io" +import "encoding/hex" + +// Inherits Client and adds new methods to expose the low level S3 APIs. +type Core struct { + *Client +} + +// NewCoreClient - Returns new Core. +func NewCore(endpoint string, accessKeyID, secretAccessKey string, secure bool) (*Core, error) { + var s3Client Core + client, err := NewV4(endpoint, accessKeyID, secretAccessKey, secure) + if err != nil { + return nil, err + } + s3Client.Client = client + return &s3Client, nil +} + +// ListObjects - List the objects. +func (c Core) ListObjects(bucket, prefix, marker, delimiter string, maxKeys int) (result ListBucketResult, err error) { + return c.listObjectsQuery(bucket, prefix, marker, 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) +} + +// NewMultipartUpload - Initiates new multipart upload and returns the new uploaID. +func (c Core) NewMultipartUpload(bucket, object string, metadata map[string][]string) (uploadID string, err error) { + result, err := c.initiateMultipartUpload(bucket, object, metadata) + return result.UploadID, err +} + +// ListMultipartUploads - List incomplete uploads. +func (c Core) ListMultipartUploads(bucket, prefix, keyMarker, uploadIDMarker, delimiter string, maxUploads int) (result ListMultipartUploadsResult, err error) { + return c.listMultipartUploadsQuery(bucket, keyMarker, uploadIDMarker, prefix, delimiter, maxUploads) +} + +// 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) +} + +// ListObjectParts - List uploaded parts of an incomplete upload. +func (c Core) ListObjectParts(bucket, object, uploadID string, partNumberMarker int, maxParts int) (result ListObjectPartsResult, err error) { + return c.listObjectPartsQuery(bucket, object, uploadID, partNumberMarker, maxParts) +} + +// CompleteMultipartUpload - Concatenate uploaded parts and commit to an object. +func (c Core) CompleteMultipartUpload(bucket, object, uploadID string, parts []CompletePart) error { + _, err := c.completeMultipartUpload(bucket, object, uploadID, completeMultipartUpload{Parts: parts}) + return err +} + +// AbortMultipartUpload - Abort an incomplete upload. +func (c Core) AbortMultipartUpload(bucket, object, uploadID string) error { + return c.abortMultipartUpload(bucket, object, uploadID) +} diff --git a/vendor/github.com/minio/minio-go/encryption-cbc.go b/vendor/github.com/minio/minio-go/encryption-cbc.go new file mode 100644 index 00000000..22a2d6c2 --- /dev/null +++ b/vendor/github.com/minio/minio-go/encryption-cbc.go @@ -0,0 +1,294 @@ +/* + * 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 + +import ( + "bytes" + "crypto/aes" + "crypto/cipher" + "crypto/rand" + "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 +type cryptMode int + +const ( + encryptMode cryptMode = iota + decryptMode +) + +// CBCSecureMaterials encrypts/decrypts data using AES CBC algorithm +type CBCSecureMaterials struct { + + // Data stream to encrypt/decrypt + stream io.Reader + + // Last internal error + err error + + // End of file reached + eof bool + + // Holds initial data + srcBuf *bytes.Buffer + + // Holds transformed data (encrypted or decrypted) + dstBuf *bytes.Buffer + + // Encryption algorithm + encryptionKey EncryptionKey + + // Key to encrypts/decrypts data + contentKey []byte + + // Encrypted form of contentKey + cryptedKey []byte + + // Initialization vector + iv []byte + + // matDesc - currently unused + matDesc []byte + + // Indicate if we are going to encrypt or decrypt + cryptMode cryptMode + + // Helper that encrypts/decrypts data + blockMode cipher.BlockMode +} + +// NewCBCSecureMaterials builds new CBC crypter module with the specified encryption key +// (symmetric or asymmetric) +func NewCBCSecureMaterials(key EncryptionKey) (*CBCSecureMaterials, error) { + if key == nil { + return nil, ErrInvalidArgument("Unable to recognize empty encryption properties") + } + return &CBCSecureMaterials{ + srcBuf: bytes.NewBuffer([]byte{}), + dstBuf: bytes.NewBuffer([]byte{}), + encryptionKey: key, + matDesc: []byte("{}"), + }, nil + +} + +// 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 +func (s *CBCSecureMaterials) SetupEncryptMode(stream io.Reader) error { + + // Set mode to encrypt + s.cryptMode = encryptMode + + // Set underlying reader + s.stream = stream + + s.eof = false + s.srcBuf.Reset() + s.dstBuf.Reset() + + var err error + + // Generate random content key + s.contentKey = make([]byte, aes.BlockSize*2) + if _, err := rand.Read(s.contentKey); err != nil { + return err + } + // Encrypt content key + s.cryptedKey, err = s.encryptionKey.Encrypt(s.contentKey) + if err != nil { + return err + } + // Generate random IV + s.iv = make([]byte, aes.BlockSize) + if _, err = rand.Read(s.iv); err != nil { + return err + } + // New cipher + encryptContentBlock, err := aes.NewCipher(s.contentKey) + if err != nil { + return err + } + + s.blockMode = cipher.NewCBCEncrypter(encryptContentBlock, s.iv) + + return nil +} + +// SetupDecryptMode - tells CBC that we are going to decrypt data +func (s *CBCSecureMaterials) SetupDecryptMode(stream io.Reader, metadata http.Header) error { + + // Set mode to decrypt + s.cryptMode = decryptMode + + // Set underlying reader + s.stream = stream + + // Reset + s.eof = false + s.srcBuf.Reset() + s.dstBuf.Reset() + + var err error + + // Get IV + s.iv, err = base64.StdEncoding.DecodeString(metadata.Get(amzHeaderIV)) + if err != nil { + return err + } + // Get encrypted content key + s.cryptedKey, err = base64.StdEncoding.DecodeString(metadata.Get(amzHeaderKey)) + if err != nil { + return err + } + // Decrypt content key + s.contentKey, err = s.encryptionKey.Decrypt(s.cryptedKey) + if err != nil { + return err + } + + // New cipher + decryptContentBlock, err := aes.NewCipher(s.contentKey) + if err != nil { + return err + } + + s.blockMode = cipher.NewCBCDecrypter(decryptContentBlock, s.iv) + 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 { + + m := make(http.Header) + + m.Set(amzHeaderMatDesc, string(s.matDesc)) + m.Set(amzHeaderIV, base64.StdEncoding.EncodeToString(s.iv)) + m.Set(amzHeaderKey, base64.StdEncoding.EncodeToString(s.cryptedKey)) + + return m +} + +// Fill buf with encrypted/decrypted data +func (s *CBCSecureMaterials) Read(buf []byte) (n int, err error) { + // Always fill buf from bufChunk at the end of this function + defer func() { + if s.err != nil { + n, err = 0, s.err + } else { + n, err = s.dstBuf.Read(buf) + } + }() + + // Return + if s.eof { + return + } + + // Fill dest buffer if its length is less than buf + for !s.eof && s.dstBuf.Len() < len(buf) { + + srcPart := make([]byte, aes.BlockSize) + dstPart := make([]byte, aes.BlockSize) + + // Fill src buffer + for s.srcBuf.Len() < aes.BlockSize*2 { + _, err = io.CopyN(s.srcBuf, s.stream, aes.BlockSize) + if err != nil { + break + } + } + + // Quit immediately for errors other than io.EOF + if err != nil && err != io.EOF { + s.err = err + return + } + + // Mark current encrypting/decrypting as finished + s.eof = (err == io.EOF) + + if s.eof && s.cryptMode == encryptMode { + if srcPart, err = pkcs5Pad(s.srcBuf.Bytes(), aes.BlockSize); err != nil { + s.err = err + return + } + } else { + _, _ = s.srcBuf.Read(srcPart) + } + + // Crypt srcPart content + for len(srcPart) > 0 { + + // Crypt current part + s.blockMode.CryptBlocks(dstPart, srcPart[:aes.BlockSize]) + + // Unpad when this is the last part and we are decrypting + if s.eof && s.cryptMode == decryptMode { + dstPart, err = pkcs5Unpad(dstPart, aes.BlockSize) + if err != nil { + s.err = err + return + } + } + + // Send crypted data to dstBuf + if _, wErr := s.dstBuf.Write(dstPart); wErr != nil { + s.err = wErr + return + } + // Move to the next part + srcPart = srcPart[aes.BlockSize:] + } + } + return +} + +// Unpad a set of bytes following PKCS5 algorithm +func pkcs5Unpad(buf []byte, blockSize int) ([]byte, error) { + len := len(buf) + if len == 0 { + return nil, errors.New("buffer is empty") + } + pad := int(buf[len-1]) + if pad > len || pad > blockSize { + return nil, errors.New("invalid padding size") + } + return buf[:len-pad], nil +} + +// Pad a set of bytes following PKCS5 algorithm +func pkcs5Pad(buf []byte, blockSize int) ([]byte, error) { + len := len(buf) + pad := blockSize - (len % blockSize) + padText := bytes.Repeat([]byte{byte(pad)}, pad) + return append(buf, padText...), nil +} diff --git a/vendor/github.com/minio/minio-go/encryption-keys.go b/vendor/github.com/minio/minio-go/encryption-keys.go new file mode 100644 index 00000000..4d6a5a14 --- /dev/null +++ b/vendor/github.com/minio/minio-go/encryption-keys.go @@ -0,0 +1,164 @@ +/* + * 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 + +import ( + "crypto/aes" + "crypto/rand" + "crypto/rsa" + "crypto/x509" +) + +// EncryptionKey - 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 { + // Encrypt data using to the set encryption key + Encrypt([]byte) ([]byte, error) + // Decrypt data using to the set encryption key + Decrypt([]byte) ([]byte, error) +} + +// SymmetricKey - encrypts data with a symmetric master key +type SymmetricKey struct { + masterKey []byte +} + +// Encrypt passed bytes +func (s *SymmetricKey) Encrypt(plain []byte) ([]byte, error) { + // Initialize an AES encryptor using a master key + keyBlock, err := aes.NewCipher(s.masterKey) + if err != nil { + return []byte{}, err + } + + // Pad the key before encryption + plain, _ = pkcs5Pad(plain, aes.BlockSize) + + encKey := []byte{} + encPart := make([]byte, aes.BlockSize) + + // Encrypt the passed key by block + for { + if len(plain) < aes.BlockSize { + break + } + // Encrypt the passed key + keyBlock.Encrypt(encPart, plain[:aes.BlockSize]) + // Add the encrypted block to the total encrypted key + encKey = append(encKey, encPart...) + // Pass to the next plain block + plain = plain[aes.BlockSize:] + } + return encKey, nil +} + +// Decrypt passed bytes +func (s *SymmetricKey) Decrypt(cipher []byte) ([]byte, error) { + // Initialize AES decrypter + keyBlock, err := aes.NewCipher(s.masterKey) + if err != nil { + return nil, err + } + + var plain []byte + plainPart := make([]byte, aes.BlockSize) + + // Decrypt the encrypted data block by block + for { + if len(cipher) < aes.BlockSize { + break + } + keyBlock.Decrypt(plainPart, cipher[:aes.BlockSize]) + // Add the decrypted block to the total result + plain = append(plain, plainPart...) + // Pass to the next cipher block + cipher = cipher[aes.BlockSize:] + } + + // Unpad the resulted plain data + plain, err = pkcs5Unpad(plain, aes.BlockSize) + if err != nil { + return nil, err + } + + return plain, nil +} + +// NewSymmetricKey generates a new encrypt/decrypt crypto using +// an AES master key password +func NewSymmetricKey(b []byte) *SymmetricKey { + return &SymmetricKey{masterKey: b} +} + +// AsymmetricKey - struct which encrypts/decrypts data +// using RSA public/private certificates +type AsymmetricKey struct { + publicKey *rsa.PublicKey + privateKey *rsa.PrivateKey +} + +// Encrypt data using public key +func (a *AsymmetricKey) Encrypt(plain []byte) ([]byte, error) { + cipher, err := rsa.EncryptPKCS1v15(rand.Reader, a.publicKey, plain) + if err != nil { + return nil, err + } + return cipher, nil +} + +// Decrypt data using public key +func (a *AsymmetricKey) Decrypt(cipher []byte) ([]byte, error) { + cipher, err := rsa.DecryptPKCS1v15(rand.Reader, a.privateKey, cipher) + if err != nil { + return nil, err + } + return cipher, nil +} + +// NewAsymmetricKey - generates a crypto module able to encrypt/decrypt +// data using a pair for private and public key +func NewAsymmetricKey(privData []byte, pubData []byte) (*AsymmetricKey, error) { + // Parse private key from passed data + priv, err := x509.ParsePKCS8PrivateKey(privData) + if err != nil { + return nil, err + } + privKey, ok := priv.(*rsa.PrivateKey) + if !ok { + return nil, ErrInvalidArgument("not a valid private key") + } + + // Parse public key from passed data + pub, err := x509.ParsePKIXPublicKey(pubData) + if err != nil { + return nil, err + } + + pubKey, ok := pub.(*rsa.PublicKey) + if !ok { + return nil, ErrInvalidArgument("not a valid public key") + } + + // Associate the private key with the passed public key + privKey.PublicKey = *pubKey + + return &AsymmetricKey{ + publicKey: pubKey, + privateKey: privKey, + }, nil +} diff --git a/vendor/github.com/minio/minio-go/encryption.go b/vendor/github.com/minio/minio-go/encryption.go new file mode 100644 index 00000000..3a7843c5 --- /dev/null +++ b/vendor/github.com/minio/minio-go/encryption.go @@ -0,0 +1,44 @@ +/* + * 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 + +import ( + "io" + "net/http" +) + +// EncryptionMaterials - provides generic interface to encrypt +// any stream of data. Some crypt information can be +// save in the object metadata +type EncryptionMaterials interface { + + // Return encrypted/decrypted data. + Read(b []byte) (int, error) + + // Metadata that will be stored with the object + GetHeaders() http.Header + + // Setup encrypt mode, further calls of Read() function + // will return the encrypted form of data streamed + // by the passed reader + SetupEncryptMode(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 +} diff --git a/vendor/github.com/minio/minio-go/pkg/s3signer/request-signature-v2.go b/vendor/github.com/minio/minio-go/pkg/s3signer/request-signature-v2.go index e1ec6c02..af0e9151 100644 --- a/vendor/github.com/minio/minio-go/pkg/s3signer/request-signature-v2.go +++ b/vendor/github.com/minio/minio-go/pkg/s3signer/request-signature-v2.go @@ -316,7 +316,7 @@ func writeCanonicalizedResource(buf *bytes.Buffer, req http.Request, isPreSign b // Request parameters if len(vv[0]) > 0 { buf.WriteByte('=') - buf.WriteString(strings.Replace(url.QueryEscape(vv[0]), "+", "%20", -1)) + buf.WriteString(vv[0]) } } } diff --git a/vendor/github.com/minio/minio-go/retry.go b/vendor/github.com/minio/minio-go/retry.go index 41b70e47..d680c6cd 100644 --- a/vendor/github.com/minio/minio-go/retry.go +++ b/vendor/github.com/minio/minio-go/retry.go @@ -78,6 +78,9 @@ func (c Client) newRetryTimer(maxRetry int, unit time.Duration, cap time.Duratio // isNetErrorRetryable - is network error retryable. func isNetErrorRetryable(err error) bool { + if err == nil { + return false + } switch err.(type) { case net.Error: switch err.(type) { @@ -96,6 +99,9 @@ func isNetErrorRetryable(err error) bool { } else if strings.Contains(err.Error(), "i/o timeout") { // If error is - tcp timeoutError, retry. return true + } else if strings.Contains(err.Error(), "connection timed out") { + // If err is a net.Dial timeout, retry. + return true } } } diff --git a/vendor/github.com/minio/minio/LICENSE b/vendor/github.com/minio/minio/LICENSE new file mode 100644 index 00000000..d6456956 --- /dev/null +++ b/vendor/github.com/minio/minio/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. diff --git a/vendor/github.com/minio/minio/NOTICE b/vendor/github.com/minio/minio/NOTICE new file mode 100644 index 00000000..f98d3d67 --- /dev/null +++ b/vendor/github.com/minio/minio/NOTICE @@ -0,0 +1,9 @@ +Minio Cloud Storage, (C) 2014,2015 Minio, Inc. + +This product includes software developed at Minio, Inc. +(https://minio.io/). + +The Minio project contains unmodified/modified subcomponents too with +separate copyright notices and license terms. Your use of the source +code for these subcomponents is subject to the terms and conditions +of the following licenses. diff --git a/vendor/github.com/minio/minio/pkg/madmin/API.md b/vendor/github.com/minio/minio/pkg/madmin/API.md index 36c79b1a..ad9af656 100644 --- a/vendor/github.com/minio/minio/pkg/madmin/API.md +++ b/vendor/github.com/minio/minio/pkg/madmin/API.md @@ -36,13 +36,15 @@ func main() { ``` -| Service operations|LockInfo operations|Healing operations| -|:---|:---|:---| -|[`ServiceStatus`](#ServiceStatus)| [`ListLocks`](#ListLocks)| [`ListObjectsHeal`](#ListObjectsHeal)| -|[`ServiceRestart`](#ServiceRestart)| [`ClearLocks`](#ClearLocks)| [`ListBucketsHeal`](#ListBucketsHeal)| -| | |[`HealBucket`](#HealBucket) | -| | |[`HealObject`](#HealObject)| -| | |[`HealFormat`](#HealFormat)| +| Service operations|LockInfo operations|Healing operations|Config operations| Misc | +|:---|:---|:---|:---|:---| +|[`ServiceStatus`](#ServiceStatus)| [`ListLocks`](#ListLocks)| [`ListObjectsHeal`](#ListObjectsHeal)|[`GetConfig`](#GetConfig)| [`SetCredentials`](#SetCredentials)| +|[`ServiceRestart`](#ServiceRestart)| [`ClearLocks`](#ClearLocks)| [`ListBucketsHeal`](#ListBucketsHeal)|[`SetConfig`](#SetConfig)|| +| | |[`HealBucket`](#HealBucket) ||| +| | |[`HealObject`](#HealObject)||| +| | |[`HealFormat`](#HealFormat)||| +| | |[`ListUploadsHeal`](#ListUploadsHeal)||| +| | |[`HealUpload`](#HealUpload)||| ## 1. Constructor @@ -82,9 +84,9 @@ Fetch service status, replies disk space used, backend type and total disks offl | Param | Type | Description | |---|---|---| -|`backend.Type` | _BackendType_ | Type of backend used by the server currently only FS or XL. | -|`backend.OnlineDisks`| _int_ | Total number of disks online (only applies to XL backend), is empty for FS. | -|`backend.OfflineDisks` | _int_ | Total number of disks offline (only applies to XL backend), is empty for FS. | +|`backend.Type` | _BackendType_ | Type of backend used by the server currently only FS or Erasure. | +|`backend.OnlineDisks`| _int_ | Total number of disks online (only applies to Erasure backend), is empty for FS. | +|`backend.OfflineDisks` | _int_ | Total number of disks offline (only applies to Erasure backend), is empty for FS. | |`backend.ReadQuorum` | _int_ | Current total read quorum threshold before reads will be unavailable, is empty for FS. | |`backend.WriteQuorum` | _int_ | Current total write quorum threshold before writes will be unavailable, is empty for FS. | @@ -119,6 +121,9 @@ If successful restarts the running minio service, for distributed setup restarts log.Printf("Success") ``` + +## 3. Lock operations + ### ListLocks(bucket, prefix string, duration time.Duration) ([]VolumeLockInfo, error) If successful returns information on the list of locks held on ``bucket`` matching ``prefix`` for longer than ``duration`` seconds. @@ -149,6 +154,8 @@ __Example__ ``` +## 4. Heal operations + ### ListObjectsHeal(bucket, prefix string, recursive bool, doneCh <-chan struct{}) (<-chan ObjectInfo, error) If successful returns information on the list of objects that need healing in ``bucket`` matching ``prefix``. @@ -272,3 +279,135 @@ __Example__ log.Println("successfully healed storage format on available disks.") ``` + +### ListUploadsHeal(bucket, prefix string, recursive bool, doneCh <-chan struct{}) (<-chan UploadInfo, error) +List ongoing multipart uploads that need healing. + +| Param | Type | Description | +|---|---|---| +|`ui.Key` | _string_ | Name of the object being uploaded | +|`ui.UploadID` | _string_ | UploadID of the ongoing multipart upload | +|`ui.HealUploadInfo.Status` | _HealStatus_| One of `Healthy`, `CanHeal`, `Corrupted`, `QuorumUnavailable`| +|`ui.Err`| _error_ | non-nil if fetching fetching healing information failed | + +__Example__ + +``` go + + // Set true if recursive listing is needed. + isRecursive := true + // List objects that need healing for a given bucket and + // prefix. + healUploadsCh, err := madmClnt.ListUploadsHeal(bucket, prefix, isRecursive, doneCh) + if err != nil { + log.Fatalln("Failed to get list of uploads to be healed: ", err) + } + + for upload := range healUploadsCh { + if upload.Err != nil { + log.Println("upload listing error: ", upload.Err) + } + + if upload.HealUploadInfo != nil { + switch healInfo := *upload.HealUploadInfo; healInfo.Status { + case madmin.CanHeal: + fmt.Println(upload.Key, " can be healed.") + case madmin.QuorumUnavailable: + fmt.Println(upload.Key, " can't be healed until quorum is available.") + case madmin.Corrupted: + fmt.Println(upload.Key, " can't be healed, not enough information.") + } + } + } + +``` + + +### HealUpload(bucket, object, uploadID string, isDryRun bool) 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. + +``` go + isDryRun = false + err = madmClnt.HealUpload("mybucket", "myobject", "myuploadID", isDryRun) + if err != nil { + log.Fatalln(err) + } + + log.Println("successfully healed mybucket/myobject/myuploadID") +``` + +## 5. Config operations + + +### GetConfig() ([]byte, error) +Get config.json of a minio setup. + +__Example__ + +``` go + configBytes, err := madmClnt.GetConfig() + if err != nil { + log.Fatalf("failed due to: %v", err) + } + + // Pretty-print config received as json. + var buf bytes.Buffer + err = json.Indent(buf, configBytes, "", "\t") + if err != nil { + log.Fatalf("failed due to: %v", err) + } + + log.Println("config received successfully: ", string(buf.Bytes())) +``` + +## 6. Misc operations + + + +### 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.") + +``` + + +### SetConfig(config io.Reader) (SetConfigResult, error) +Set config.json of a minio setup and restart setup for configuration +change to take effect. + + +| Param | Type | Description | +|---|---|---| +|`st.Status` | _bool_ | true if set-config succeeded, false otherwise. | +|`st.NodeSummary.Name` | _string_ | Network address of the node. | +|`st.NodeSummary.ErrSet` | _bool_ | Bool representation indicating if an error is encountered with the node.| +|`st.NodeSummary.ErrMsg` | _string_ | String representation of the error (if any) on the node.| + + +__Example__ + +``` go + config := bytes.NewReader([]byte(`config.json contents go here`)) + result, err := madmClnt.SetConfig(config) + if err != nil { + log.Fatalf("failed due to: %v", err) + } + + var buf bytes.Buffer + enc := json.NewEncoder(&buf) + enc.SetEscapeHTML(false) + enc.SetIndent("", "\t") + err = enc.Encode(result) + if err != nil { + log.Fatalln(err) + } + log.Println("SetConfig: ", string(buf.Bytes())) +``` diff --git a/vendor/github.com/minio/minio/pkg/madmin/api.go b/vendor/github.com/minio/minio/pkg/madmin/api.go index 2bf06b8b..ef010583 100644 --- a/vendor/github.com/minio/minio/pkg/madmin/api.go +++ b/vendor/github.com/minio/minio/pkg/madmin/api.go @@ -1,5 +1,5 @@ /* - * Minio Cloud Storage, (C) 2016 Minio, Inc. + * Minio Cloud Storage, (C) 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. @@ -276,12 +276,7 @@ func (c AdminClient) dumpHTTP(req *http.Request, resp *http.Response) error { // Ends the http dump. _, err = fmt.Fprintln(c.traceOutput, "---------END-HTTP---------") - if err != nil { - return err - } - - // Returns success. - return nil + return err } // do - execute http request. diff --git a/vendor/github.com/minio/minio/pkg/madmin/config-commands.go b/vendor/github.com/minio/minio/pkg/madmin/config-commands.go new file mode 100644 index 00000000..e4f8afb5 --- /dev/null +++ b/vendor/github.com/minio/minio/pkg/madmin/config-commands.go @@ -0,0 +1,124 @@ +/* + * Minio Cloud Storage, (C) 2017 Minio, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package madmin + +import ( + "bytes" + "encoding/json" + "io" + "io/ioutil" + "net/http" + "net/url" +) + +const ( + configQueryParam = "config" +) + +// NodeSummary - represents the result of an operation part of +// set-config on a node. +type NodeSummary struct { + Name string `json:"name"` + ErrSet bool `json:"errSet"` + ErrMsg string `json:"errMsg"` +} + +// SetConfigResult - represents detailed results of a set-config +// operation. +type SetConfigResult struct { + NodeResults []NodeSummary `json:"nodeResults"` + Status bool `json:"status"` +} + +// GetConfig - returns the config.json of a minio setup. +func (adm *AdminClient) GetConfig() ([]byte, error) { + queryVal := make(url.Values) + queryVal.Set(configQueryParam, "") + + hdrs := make(http.Header) + hdrs.Set(minioAdminOpHeader, "get") + + reqData := requestData{ + queryValues: queryVal, + customHeaders: hdrs, + } + + // Execute GET on /?config to get config of a setup. + resp, err := adm.executeMethod("GET", reqData) + + defer closeResponse(resp) + if err != nil { + return nil, err + } + + if resp.StatusCode != http.StatusOK { + return nil, httpRespToErrorResponse(resp) + } + + // Return the JSON marshalled bytes to user. + return ioutil.ReadAll(resp.Body) +} + +// SetConfig - set config supplied as config.json for the setup. +func (adm *AdminClient) SetConfig(config io.Reader) (SetConfigResult, error) { + queryVal := url.Values{} + queryVal.Set(configQueryParam, "") + + // Set x-minio-operation to set. + hdrs := make(http.Header) + hdrs.Set(minioAdminOpHeader, "set") + + // Read config bytes to calculate MD5, SHA256 and content length. + configBytes, err := ioutil.ReadAll(config) + if err != nil { + return SetConfigResult{}, err + } + + reqData := requestData{ + queryValues: queryVal, + customHeaders: hdrs, + contentBody: bytes.NewReader(configBytes), + contentMD5Bytes: sumMD5(configBytes), + contentSHA256Bytes: sum256(configBytes), + } + + // Execute PUT on /?config to set config. + resp, err := adm.executeMethod("PUT", reqData) + + defer closeResponse(resp) + if err != nil { + return SetConfigResult{}, err + } + + if resp.StatusCode != http.StatusOK { + return SetConfigResult{}, httpRespToErrorResponse(resp) + } + + var result SetConfigResult + jsonBytes, err := ioutil.ReadAll(resp.Body) + if err != nil { + return SetConfigResult{}, err + } + + err = json.Unmarshal(jsonBytes, &result) + if err != nil { + return SetConfigResult{}, err + } + + return result, nil +} diff --git a/vendor/github.com/minio/minio/pkg/madmin/generic-commands.go b/vendor/github.com/minio/minio/pkg/madmin/generic-commands.go new file mode 100644 index 00000000..384b74ce --- /dev/null +++ b/vendor/github.com/minio/minio/pkg/madmin/generic-commands.go @@ -0,0 +1,66 @@ +/* + * Minio Cloud Storage, (C) 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. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package madmin + +import ( + "bytes" + "encoding/xml" + "net/http" + "net/url" +) + +// setCredsReq - xml to send to the server to set new credentials +type setCredsReq struct { + Username string `xml:"username"` + Password string `xml:"password"` +} + +// SetCredentials - Call Set Credentials API to set new access and secret keys in the specified Minio server +func (adm *AdminClient) SetCredentials(access, secret string) error { + + // Setup new request + reqData := requestData{} + reqData.queryValues = make(url.Values) + reqData.queryValues.Set("service", "") + reqData.customHeaders = make(http.Header) + reqData.customHeaders.Set(minioAdminOpHeader, "set-credentials") + + // Setup request's body + body, err := xml.Marshal(setCredsReq{Username: access, Password: secret}) + if err != nil { + return err + } + reqData.contentBody = bytes.NewReader(body) + reqData.contentLength = int64(len(body)) + reqData.contentMD5Bytes = sumMD5(body) + reqData.contentSHA256Bytes = sum256(body) + + // Execute GET on bucket to list objects. + resp, err := adm.executeMethod("POST", reqData) + + defer closeResponse(resp) + if err != nil { + return err + } + + // Return error to the caller if http response code is different from 200 + if resp.StatusCode != http.StatusOK { + return httpRespToErrorResponse(resp) + } + return nil +} diff --git a/vendor/github.com/minio/minio/pkg/madmin/heal-commands.go b/vendor/github.com/minio/minio/pkg/madmin/heal-commands.go index 7544a8f8..cbedf9a5 100644 --- a/vendor/github.com/minio/minio/pkg/madmin/heal-commands.go +++ b/vendor/github.com/minio/minio/pkg/madmin/heal-commands.go @@ -3,6 +3,8 @@ * * 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 @@ -25,6 +27,10 @@ import ( "time" ) +const ( + maxUploadsList = 1000 +) + // listBucketHealResult container for listObjects response. type listBucketHealResult struct { // A response can contain CommonPrefixes only if you have @@ -89,11 +95,11 @@ type ListBucketsHealResponse struct { } // HealStatus - represents different states of healing an object could be in. -type healStatus int +type HealStatus int const ( // Healthy - Object that is already healthy - Healthy healStatus = iota + Healthy HealStatus = iota // CanHeal - Object can be healed CanHeal // Corrupted - Object can't be healed @@ -104,7 +110,7 @@ const ( // HealBucketInfo - represents healing related information of a bucket. type HealBucketInfo struct { - Status healStatus + Status HealStatus } // BucketInfo - represents bucket metadata. @@ -121,7 +127,7 @@ type BucketInfo struct { // HealObjectInfo - represents healing related information of an object. type HealObjectInfo struct { - Status healStatus + Status HealStatus MissingDataCount int MissingPartityCount int } @@ -156,16 +162,76 @@ type ObjectInfo struct { HealObjectInfo *HealObjectInfo `json:"healObjectInfo,omitempty"` } +// UploadInfo - represents an ongoing upload that needs to be healed. +type UploadInfo struct { + Key string `json:"name"` // Name of the object being uploaded. + + UploadID string `json:"uploadId"` // UploadID + // Owner name. + Owner struct { + DisplayName string `json:"name"` + ID string `json:"id"` + } `json:"owner"` + + // The class of storage used to store the object. + StorageClass string `json:"storageClass"` + + Initiated time.Time `json:"initiated"` // Time at which upload was initiated. + + // Error + Err error `json:"-"` + HealUploadInfo *HealObjectInfo `json:"healObjectInfo,omitempty"` +} + +// Initiator - has same properties as Owner. +type Initiator Owner + +// upload - represents an ongoing multipart upload. +type upload struct { + Key string + UploadID string `xml:"UploadId"` + Initiator Initiator + Owner Owner + StorageClass string + Initiated time.Time + HealUploadInfo *HealObjectInfo `xml:"HealObjectInfo,omitempty"` +} + +// listUploadsHealResponse - represents ListUploadsHeal response. +type listUploadsHealResponse struct { + XMLName xml.Name `xml:"http://s3.amazonaws.com/doc/2006-03-01/ ListMultipartUploadsResult" json:"-"` + + Bucket string + KeyMarker string + UploadIDMarker string `xml:"UploadIdMarker"` + NextKeyMarker string + NextUploadIDMarker string `xml:"NextUploadIdMarker"` + Delimiter string + Prefix string + EncodingType string `xml:"EncodingType,omitempty"` + MaxUploads int + IsTruncated bool + + // List of pending uploads. + Uploads []upload `xml:"Upload"` + + // Delimed common prefixes. + CommonPrefixes []commonPrefix +} + type healQueryKey string const ( - healBucket healQueryKey = "bucket" - healObject healQueryKey = "object" - healPrefix healQueryKey = "prefix" - healMarker healQueryKey = "marker" - healDelimiter healQueryKey = "delimiter" - healMaxKey healQueryKey = "max-key" - healDryRun healQueryKey = "dry-run" + healBucket healQueryKey = "bucket" + healObject healQueryKey = "object" + healPrefix healQueryKey = "prefix" + healMarker healQueryKey = "marker" + healDelimiter healQueryKey = "delimiter" + healMaxKey healQueryKey = "max-key" + healDryRun healQueryKey = "dry-run" + healUploadIDMarker healQueryKey = "upload-id-marker" + healMaxUpload healQueryKey = "max-uploads" + healUploadID healQueryKey = "upload-id" ) // mkHealQueryVal - helper function to construct heal REST API query params. @@ -211,10 +277,7 @@ func (adm *AdminClient) listObjectsHeal(bucket, prefix, marker, delimiter string } err = xml.NewDecoder(resp.Body).Decode(&toBeHealedObjects) - if err != nil { - return toBeHealedObjects, err - } - return toBeHealedObjects, nil + return toBeHealedObjects, err } // ListObjectsHeal - Lists upto maxKeys objects that needing heal matching bucket, prefix, marker, delimiter. @@ -370,6 +433,43 @@ func (adm *AdminClient) HealBucket(bucket string, dryrun bool) error { return nil } +// HealUpload - Heal the given upload. +func (adm *AdminClient) HealUpload(bucket, object, uploadID string, dryrun bool) error { + // Construct query params. + queryVal := url.Values{} + queryVal.Set("heal", "") + queryVal.Set(string(healBucket), bucket) + queryVal.Set(string(healObject), object) + queryVal.Set(string(healUploadID), uploadID) + if dryrun { + queryVal.Set(string(healDryRun), "") + } + + hdrs := make(http.Header) + hdrs.Set(minioAdminOpHeader, "upload") + + reqData := requestData{ + queryValues: queryVal, + customHeaders: hdrs, + } + + // Execute POST on + // /?heal&bucket=mybucket&object=myobject&upload-id=uploadID + // to heal an upload. + resp, err := adm.executeMethod("POST", reqData) + + defer closeResponse(resp) + if err != nil { + return err + } + + if resp.StatusCode != http.StatusOK { + return httpRespToErrorResponse(resp) + } + + return nil +} + // HealObject - Heal the given object. func (adm *AdminClient) HealObject(bucket, object string, dryrun bool) error { // Construct query params. @@ -435,3 +535,140 @@ func (adm *AdminClient) HealFormat(dryrun bool) error { return nil } + +// mkUploadsHealQuery - helper function to construct query params for +// ListUploadsHeal API. +func mkUploadsHealQuery(bucket, prefix, marker, uploadIDMarker, delimiter, maxUploadsStr string) url.Values { + + queryVal := make(url.Values) + queryVal.Set("heal", "") + queryVal.Set(string(healBucket), bucket) + queryVal.Set(string(healPrefix), prefix) + queryVal.Set(string(healMarker), marker) + queryVal.Set(string(healUploadIDMarker), uploadIDMarker) + queryVal.Set(string(healDelimiter), delimiter) + queryVal.Set(string(healMaxUpload), maxUploadsStr) + return queryVal +} + +func (adm *AdminClient) listUploadsHeal(bucket, prefix, marker, uploadIDMarker, delimiter string, maxUploads int) (listUploadsHealResponse, error) { + // Construct query params. + maxUploadsStr := fmt.Sprintf("%d", maxUploads) + queryVal := mkUploadsHealQuery(bucket, prefix, marker, uploadIDMarker, delimiter, maxUploadsStr) + + hdrs := make(http.Header) + hdrs.Set(minioAdminOpHeader, "list-uploads") + + reqData := requestData{ + queryValues: queryVal, + customHeaders: hdrs, + } + + // Empty 'list' of objects to be healed. + toBeHealedUploads := listUploadsHealResponse{} + + // Execute GET on /?heal to list objects needing heal. + resp, err := adm.executeMethod("GET", reqData) + + defer closeResponse(resp) + if err != nil { + return listUploadsHealResponse{}, err + } + + if resp.StatusCode != http.StatusOK { + return toBeHealedUploads, httpRespToErrorResponse(resp) + + } + + err = xml.NewDecoder(resp.Body).Decode(&toBeHealedUploads) + if err != nil { + return listUploadsHealResponse{}, err + } + + return toBeHealedUploads, nil +} + +// ListUploadsHeal - issues list heal uploads API request +func (adm *AdminClient) ListUploadsHeal(bucket, prefix string, recursive bool, + doneCh <-chan struct{}) (<-chan UploadInfo, error) { + + // Default listing is delimited at "/" + delimiter := "/" + if recursive { + // If recursive we do not delimit. + delimiter = "" + } + + uploadIDMarker := "" + + // Allocate new list objects channel. + uploadStatCh := make(chan UploadInfo, maxUploadsList) + + // Initiate list objects goroutine here. + go func(uploadStatCh chan<- UploadInfo) { + defer close(uploadStatCh) + // Save marker for next request. + var marker string + for { + // Get list of objects a maximum of 1000 per request. + result, err := adm.listUploadsHeal(bucket, prefix, marker, + uploadIDMarker, delimiter, maxUploadsList) + if err != nil { + uploadStatCh <- UploadInfo{ + Err: err, + } + return + } + + // If contents are available loop through and + // send over channel. + for _, upload := range result.Uploads { + select { + // Send upload info. + case uploadStatCh <- UploadInfo{ + Key: upload.Key, + UploadID: upload.UploadID, + Initiated: upload.Initiated, + HealUploadInfo: upload.HealUploadInfo, + }: + // If receives done from the caller, return here. + case <-doneCh: + return + } + } + + // Send all common prefixes if any. NOTE: + // prefixes are only present if the request is + // delimited. + for _, prefix := range result.CommonPrefixes { + upload := UploadInfo{} + upload.Key = prefix.Prefix + select { + // Send object prefixes. + case uploadStatCh <- upload: + // If receives done from the caller, return here. + case <-doneCh: + return + } + } + + // If next uploadID marker is present, set it + // for the next request. + if result.NextUploadIDMarker != "" { + uploadIDMarker = result.NextUploadIDMarker + } + + // If next marker present, save it for next request. + if result.KeyMarker != "" { + marker = result.KeyMarker + } + + // Listing ends result is not truncated, + // return right here. + if !result.IsTruncated { + return + } + } + }(uploadStatCh) + return uploadStatCh, nil +} diff --git a/vendor/github.com/minio/minio/pkg/madmin/info-commands.go b/vendor/github.com/minio/minio/pkg/madmin/info-commands.go new file mode 100644 index 00000000..1c41fdf8 --- /dev/null +++ b/vendor/github.com/minio/minio/pkg/madmin/info-commands.go @@ -0,0 +1,119 @@ +/* + * Minio Cloud Storage, (C) 2017 Minio, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package madmin + +import ( + "encoding/json" + "io/ioutil" + "net/http" + "net/url" + "time" +) + +// BackendType - represents different backend types. +type BackendType int + +// Enum for different backend types. +const ( + Unknown BackendType = iota + // Filesystem backend. + FS + // Multi disk Erasure (single, distributed) backend. + Erasure + + // Add your own backend. +) + +// StorageInfo - represents total capacity of underlying storage. +type StorageInfo struct { + // Total disk space. + Total int64 + // Free available disk space. + Free int64 + // Backend type. + Backend struct { + // Represents various backend types, currently on FS and Erasure. + Type BackendType + + // Following fields are only meaningful if BackendType is Erasure. + OnlineDisks int // Online disks during server startup. + OfflineDisks int // Offline disks during server startup. + ReadQuorum int // Minimum disks required for successful read operations. + WriteQuorum int // Minimum disks required for successful write operations. + } +} + +// ServerProperties holds some of the server's information such as uptime, +// version, region, .. +type ServerProperties struct { + Uptime time.Duration `json:"uptime"` + Version string `json:"version"` + CommitID string `json:"commitID"` + Region string `json:"region"` + SQSARN []string `json:"sqsARN"` +} + +// ServerConnStats holds network information +type ServerConnStats struct { + TotalInputBytes uint64 `json:"transferred"` + TotalOutputBytes uint64 `json:"received"` +} + +// ServerInfo holds the whole server information that will be +// returned by ServerInfo API. +type ServerInfo struct { + StorageInfo StorageInfo `json:"storage"` + ConnStats ServerConnStats `json:"network"` + Properties ServerProperties `json:"server"` +} + +// 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) { + // Prepare web service request + reqData := requestData{} + reqData.queryValues = make(url.Values) + reqData.queryValues.Set("info", "") + reqData.customHeaders = make(http.Header) + + resp, err := adm.executeMethod("GET", reqData) + defer closeResponse(resp) + if err != nil { + return ServerInfo{}, err + } + + // Check response http status code + if resp.StatusCode != http.StatusOK { + return ServerInfo{}, httpRespToErrorResponse(resp) + } + + // Unmarshal the server's json response + var info ServerInfo + + respBytes, err := ioutil.ReadAll(resp.Body) + if err != nil { + return ServerInfo{}, err + } + + err = json.Unmarshal(respBytes, &info) + if err != nil { + return ServerInfo{}, err + } + + return info, nil +} diff --git a/vendor/github.com/minio/minio/pkg/madmin/service-commands.go b/vendor/github.com/minio/minio/pkg/madmin/service-commands.go index 37869cd6..62bf8cb4 100644 --- a/vendor/github.com/minio/minio/pkg/madmin/service-commands.go +++ b/vendor/github.com/minio/minio/pkg/madmin/service-commands.go @@ -1,5 +1,5 @@ /* - * Minio Cloud Storage, (C) 2016 Minio, Inc. + * Minio Cloud Storage, (C) 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. @@ -18,58 +18,16 @@ package madmin import ( - "bytes" "encoding/json" - "encoding/xml" - "errors" "io/ioutil" "net/http" "net/url" + "time" ) -// BackendType - represents different backend types. -type BackendType int - -// Enum for different backend types. -const ( - Unknown BackendType = iota - // Filesystem backend. - FS - // Multi disk XL (single, distributed) backend. - XL - - // Add your own backend. -) - -// StorageInfo - represents total capacity of underlying storage. -type StorageInfo struct { - // Total disk space. - Total int64 - // Free available disk space. - Free int64 - // Backend type. - Backend struct { - // Represents various backend types, currently on FS and XL. - Type BackendType - - // Following fields are only meaningful if BackendType is XL. - OnlineDisks int // Online disks during server startup. - OfflineDisks int // Offline disks during server startup. - ReadQuorum int // Minimum disks required for successful read operations. - WriteQuorum int // Minimum disks required for successful write operations. - } -} - -// ServerVersion - server version -type ServerVersion struct { - Version string `json:"version"` - CommitID string `json:"commitID"` -} - // ServiceStatusMetadata - contains the response of service status API type ServiceStatusMetadata struct { - StorageInfo StorageInfo `json:"storageInfo"` - ServerVersion ServerVersion `json:"serverVersion"` + Uptime time.Duration `json:"uptime"` } // ServiceStatus - Connect to a minio server and call Service Status Management API @@ -133,49 +91,3 @@ func (adm *AdminClient) ServiceRestart() error { } return nil } - -// setCredsReq - xml to send to the server to set new credentials -type setCredsReq struct { - Username string `xml:"username"` - Password string `xml:"password"` -} - -// ServiceSetCredentials - Call Service Set Credentials API to set new access and secret keys in the specified Minio server -func (adm *AdminClient) ServiceSetCredentials(access, secret string) error { - - // Disallow sending with the server if the connection is not secure - if !adm.secure { - return errors.New("setting new credentials requires HTTPS connection to the server") - } - - // Setup new request - reqData := requestData{} - reqData.queryValues = make(url.Values) - reqData.queryValues.Set("service", "") - reqData.customHeaders = make(http.Header) - reqData.customHeaders.Set(minioAdminOpHeader, "set-credentials") - - // Setup request's body - body, err := xml.Marshal(setCredsReq{Username: access, Password: secret}) - if err != nil { - return err - } - reqData.contentBody = bytes.NewReader(body) - reqData.contentLength = int64(len(body)) - reqData.contentMD5Bytes = sumMD5(body) - reqData.contentSHA256Bytes = sum256(body) - - // Execute GET on bucket to list objects. - resp, err := adm.executeMethod("POST", reqData) - - defer closeResponse(resp) - if err != nil { - return err - } - - // Return error to the caller if http response code is different from 200 - if resp.StatusCode != http.StatusOK { - return httpRespToErrorResponse(resp) - } - return nil -} diff --git a/cmd/trie.go b/vendor/github.com/minio/minio/pkg/trie/trie.go similarity index 66% rename from cmd/trie.go rename to vendor/github.com/minio/minio/pkg/trie/trie.go index 764c23a4..d32858c1 100644 --- a/cmd/trie.go +++ b/vendor/github.com/minio/minio/pkg/trie/trie.go @@ -1,5 +1,5 @@ /* - * Minio Client (C) 2014, 2015, 2016 Minio, Inc. + * Minio Cloud Storage, (C) 2014, 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. @@ -14,39 +14,35 @@ * limitations under the License. */ -// Package cmd - This file implements a simple trie tree to be used for 'mc' cli commands. -package cmd +// Package trie implements a simple trie tree for minio server/tools borrows +// idea from - https://godoc.org/golang.org/x/text/internal/triegen. +package trie -// This package borrows idea from - https://godoc.org/golang.org/x/text/internal/triegen. +// Node trie tree node container carries value and children. +type Node struct { + exists bool + value interface{} + child map[rune]*Node // runes as child. +} + +// newNode create a new trie node. +func newNode() *Node { + return &Node{ + exists: false, + value: nil, + child: make(map[rune]*Node), + } +} // Trie is a trie container. type Trie struct { - root *trieNode + root *Node size int } -// newTrie create a new trie. -func newTrie() *Trie { - return &Trie{ - root: newTrieNode(), - size: 0, - } -} - -// trieNode trie tree node container carries value and children. -type trieNode struct { - exists bool - value interface{} - child map[rune]*trieNode // runes as child. -} - -// newTrieNode create a new trie node. -func newTrieNode() *trieNode { - return &trieNode{ - exists: false, - value: nil, - child: make(map[rune]*trieNode), - } +// Root returns root node. +func (t *Trie) Root() *Node { + return t.root } // Insert insert a key. @@ -54,7 +50,7 @@ func (t *Trie) Insert(key string) { curNode := t.root for _, v := range key { if curNode.child[v] == nil { - curNode.child[v] = newTrieNode() + curNode.child[v] = newNode() } curNode = curNode.child[v] } @@ -72,24 +68,24 @@ func (t *Trie) Insert(key string) { func (t *Trie) PrefixMatch(key string) []interface{} { node, _ := t.findNode(key) if node != nil { - return t.walk(node) + return t.Walk(node) } return []interface{}{} } -// walk the tree. -func (t *Trie) walk(node *trieNode) (ret []interface{}) { +// Walk the tree. +func (t *Trie) Walk(node *Node) (ret []interface{}) { if node.exists { ret = append(ret, node.value) } for _, v := range node.child { - ret = append(ret, t.walk(v)...) + ret = append(ret, t.Walk(v)...) } return } // find nodes corresponding to key. -func (t *Trie) findNode(key string) (node *trieNode, index int) { +func (t *Trie) findNode(key string) (node *Node, index int) { curNode := t.root f := false for k, v := range key { @@ -112,3 +108,11 @@ func (t *Trie) findNode(key string) (node *trieNode, index int) { return curNode, index } + +// NewTrie create a new trie. +func NewTrie() *Trie { + return &Trie{ + root: newNode(), + size: 0, + } +} diff --git a/cmd/damerau-levenshtein.go b/vendor/github.com/minio/minio/pkg/words/damerau-levenshtein.go similarity index 95% rename from cmd/damerau-levenshtein.go rename to vendor/github.com/minio/minio/pkg/words/damerau-levenshtein.go index 55383d1c..f8bf1eb1 100644 --- a/cmd/damerau-levenshtein.go +++ b/vendor/github.com/minio/minio/pkg/words/damerau-levenshtein.go @@ -1,5 +1,5 @@ /* - * Minio Client (C) 2014-2016 Minio, Inc. + * Minio Client (C) 2014, 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. @@ -14,11 +14,9 @@ * limitations under the License. */ -package cmd +package words -import ( - "math" -) +import "math" // Returns the minimum value of a slice of integers func minimum(integers []int) (minVal int) { diff --git a/vendor/github.com/rjeczalik/notify/event.go b/vendor/github.com/rjeczalik/notify/event.go index e045edce..c1288419 100644 --- a/vendor/github.com/rjeczalik/notify/event.go +++ b/vendor/github.com/rjeczalik/notify/event.go @@ -73,7 +73,7 @@ func (e Event) String() string { // // https://developer.apple.com/library/mac/documentation/Darwin/Reference/FSEvents_Ref/index.html#//apple_ref/doc/constant_group/FSEventStreamEventFlags // -// Under Linux (inotify) Sys() always returns a non-nil *syscall.InotifyEvent +// Under Linux (inotify) Sys() always returns a non-nil *unix.InotifyEvent // value, defined as: // // type InotifyEvent struct { diff --git a/vendor/github.com/rjeczalik/notify/event_fen.go b/vendor/github.com/rjeczalik/notify/event_fen.go index 0f161994..767f04fa 100644 --- a/vendor/github.com/rjeczalik/notify/event_fen.go +++ b/vendor/github.com/rjeczalik/notify/event_fen.go @@ -20,27 +20,27 @@ const ( ) const ( - // FileAccess is an event reported when monitored file/directory was accessed. - FileAccess = fileAccess - // FileModified is an event reported when monitored file/directory was modified. - FileModified = fileModified - // FileAttrib is an event reported when monitored file/directory's ATTRIB - // was changed. - FileAttrib = fileAttrib - // FileDelete is an event reported when monitored file/directory was deleted. - FileDelete = fileDelete - // FileRenameTo to is an event reported when monitored file/directory was renamed. - FileRenameTo = fileRenameTo - // FileRenameFrom is an event reported when monitored file/directory was renamed. + // FileAccess is an event reported when monitored file/directory was accessed. + FileAccess = fileAccess + // FileModified is an event reported when monitored file/directory was modified. + FileModified = fileModified + // FileAttrib is an event reported when monitored file/directory's ATTRIB + // was changed. + FileAttrib = fileAttrib + // FileDelete is an event reported when monitored file/directory was deleted. + FileDelete = fileDelete + // FileRenameTo to is an event reported when monitored file/directory was renamed. + FileRenameTo = fileRenameTo + // FileRenameFrom is an event reported when monitored file/directory was renamed. FileRenameFrom = fileRenameFrom - // FileTrunc is an event reported when monitored file/directory was truncated. - FileTrunc = fileTrunc - // FileNoFollow is an flag to indicate not to follow symbolic links. - FileNoFollow = fileNoFollow - // Unmounted is an event reported when monitored filesystem was unmounted. - Unmounted = unmounted - // MountedOver is an event reported when monitored file/directory was mounted on. - MountedOver = mountedOver + // FileTrunc is an event reported when monitored file/directory was truncated. + FileTrunc = fileTrunc + // FileNoFollow is an flag to indicate not to follow symbolic links. + FileNoFollow = fileNoFollow + // Unmounted is an event reported when monitored filesystem was unmounted. + Unmounted = unmounted + // MountedOver is an event reported when monitored file/directory was mounted on. + MountedOver = mountedOver ) var osestr = map[Event]string{ diff --git a/vendor/github.com/rjeczalik/notify/event_inotify.go b/vendor/github.com/rjeczalik/notify/event_inotify.go index 82954a9b..1f32bb73 100644 --- a/vendor/github.com/rjeczalik/notify/event_inotify.go +++ b/vendor/github.com/rjeczalik/notify/event_inotify.go @@ -6,7 +6,7 @@ package notify -import "syscall" +import "golang.org/x/sys/unix" // Platform independent event values. const ( @@ -25,18 +25,18 @@ const ( // Inotify specific masks are legal, implemented events that are guaranteed to // work with notify package on linux-based systems. const ( - InAccess = Event(syscall.IN_ACCESS) // File was accessed - InModify = Event(syscall.IN_MODIFY) // File was modified - InAttrib = Event(syscall.IN_ATTRIB) // Metadata changed - InCloseWrite = Event(syscall.IN_CLOSE_WRITE) // Writtable file was closed - InCloseNowrite = Event(syscall.IN_CLOSE_NOWRITE) // Unwrittable file closed - InOpen = Event(syscall.IN_OPEN) // File was opened - InMovedFrom = Event(syscall.IN_MOVED_FROM) // File was moved from X - InMovedTo = Event(syscall.IN_MOVED_TO) // File was moved to Y - InCreate = Event(syscall.IN_CREATE) // Subfile was created - InDelete = Event(syscall.IN_DELETE) // Subfile was deleted - InDeleteSelf = Event(syscall.IN_DELETE_SELF) // Self was deleted - InMoveSelf = Event(syscall.IN_MOVE_SELF) // Self was moved + InAccess = Event(unix.IN_ACCESS) // File was accessed + InModify = Event(unix.IN_MODIFY) // File was modified + InAttrib = Event(unix.IN_ATTRIB) // Metadata changed + InCloseWrite = Event(unix.IN_CLOSE_WRITE) // Writtable file was closed + InCloseNowrite = Event(unix.IN_CLOSE_NOWRITE) // Unwrittable file closed + InOpen = Event(unix.IN_OPEN) // File was opened + InMovedFrom = Event(unix.IN_MOVED_FROM) // File was moved from X + InMovedTo = Event(unix.IN_MOVED_TO) // File was moved to Y + InCreate = Event(unix.IN_CREATE) // Subfile was created + InDelete = Event(unix.IN_DELETE) // Subfile was deleted + InDeleteSelf = Event(unix.IN_DELETE_SELF) // Self was deleted + InMoveSelf = Event(unix.IN_MOVE_SELF) // Self was moved ) var osestr = map[Event]string{ @@ -56,15 +56,15 @@ var osestr = map[Event]string{ // Inotify behavior events are not **currently** supported by notify package. const ( - inDontFollow = Event(syscall.IN_DONT_FOLLOW) - inExclUnlink = Event(syscall.IN_EXCL_UNLINK) - inMaskAdd = Event(syscall.IN_MASK_ADD) - inOneshot = Event(syscall.IN_ONESHOT) - inOnlydir = Event(syscall.IN_ONLYDIR) + inDontFollow = Event(unix.IN_DONT_FOLLOW) + inExclUnlink = Event(unix.IN_EXCL_UNLINK) + inMaskAdd = Event(unix.IN_MASK_ADD) + inOneshot = Event(unix.IN_ONESHOT) + inOnlydir = Event(unix.IN_ONLYDIR) ) type event struct { - sys syscall.InotifyEvent + sys unix.InotifyEvent path string event Event } @@ -72,4 +72,4 @@ type event struct { func (e *event) Event() Event { return e.event } func (e *event) Path() string { return e.path } func (e *event) Sys() interface{} { return &e.sys } -func (e *event) isDir() (bool, error) { return e.sys.Mask&syscall.IN_ISDIR != 0, nil } +func (e *event) isDir() (bool, error) { return e.sys.Mask&unix.IN_ISDIR != 0, nil } diff --git a/vendor/github.com/rjeczalik/notify/notify.go b/vendor/github.com/rjeczalik/notify/notify.go index dbf1e7bc..7d2eec3a 100644 --- a/vendor/github.com/rjeczalik/notify/notify.go +++ b/vendor/github.com/rjeczalik/notify/notify.go @@ -4,7 +4,7 @@ // BUG(rjeczalik): Notify does not collect watchpoints, when underlying watches // were removed by their os-specific watcher implementations. Instead users are -// advised to listen on persistant paths to have guarantee they receive events +// advised to listen on persistent paths to have guarantee they receive events // for the whole lifetime of their applications (to discuss see #69). // BUG(ppknap): Linux (inotify) does not support watcher behavior masks like @@ -58,7 +58,7 @@ var defaultTree = newTree() // If a directory which path was used to create recursive watch under Windows // gets deleted, the OS will not report such event. It is advised to keep in // mind this limitation while setting recursive watchpoints for your application, -// e.g. use persistant paths like %userprofile% or watch additionally parent +// e.g. use persistent paths like %userprofile% or watch additionally parent // directory of a recursive watchpoint in order to receive delete events for it. func Watch(path string, c chan<- EventInfo, events ...Event) error { return defaultTree.Watch(path, c, events...) @@ -67,7 +67,7 @@ func Watch(path string, c chan<- EventInfo, events ...Event) error { // Stop removes all watchpoints registered for c. All underlying watches are // also removed, for which c was the last channel listening for events. // -// Stop does not close c. When Stop returns, it is guranteed that c will +// Stop does not close c. When Stop returns, it is guaranteed that c will // receive no more signals. func Stop(c chan<- EventInfo) { defaultTree.Stop(c) diff --git a/vendor/github.com/rjeczalik/notify/watcher_fsevents_cgo.go b/vendor/github.com/rjeczalik/notify/watcher_fsevents_cgo.go index ee9631a6..5be64632 100644 --- a/vendor/github.com/rjeczalik/notify/watcher_fsevents_cgo.go +++ b/vendor/github.com/rjeczalik/notify/watcher_fsevents_cgo.go @@ -144,7 +144,7 @@ type stream struct { } // NewStream creates a stream for given path, listening for file events and -// calling fn upon receving any. +// calling fn upon receiving any. func newStream(path string, fn streamFunc) *stream { return &stream{ path: path, diff --git a/vendor/github.com/rjeczalik/notify/watcher_inotify.go b/vendor/github.com/rjeczalik/notify/watcher_inotify.go index 3ceaa8f3..0606986b 100644 --- a/vendor/github.com/rjeczalik/notify/watcher_inotify.go +++ b/vendor/github.com/rjeczalik/notify/watcher_inotify.go @@ -13,14 +13,15 @@ import ( "runtime" "sync" "sync/atomic" - "syscall" "unsafe" + + "golang.org/x/sys/unix" ) // eventBufferSize defines the size of the buffer given to read(2) function. One // should not depend on this value, since it was arbitrary chosen and may be // changed in the future. -const eventBufferSize = 64 * (syscall.SizeofInotifyEvent + syscall.PathMax + 1) +const eventBufferSize = 64 * (unix.SizeofInotifyEvent + unix.PathMax + 1) // consumersCount defines the number of consumers in producer-consumer based // implementation. Each consumer is run in a separate goroutine and has read @@ -43,7 +44,7 @@ type inotify struct { fd int32 // inotify file descriptor pipefd []int // pipe's read and write descriptors epfd int // epoll descriptor - epes []syscall.EpollEvent // epoll events + epes []unix.EpollEvent // epoll events buffer [eventBufferSize]byte // inotify event buffer wg sync.WaitGroup // wait group used to close main loop c chan<- EventInfo // event dispatcher channel @@ -56,13 +57,13 @@ func newWatcher(c chan<- EventInfo) watcher { fd: invalidDescriptor, pipefd: []int{invalidDescriptor, invalidDescriptor}, epfd: invalidDescriptor, - epes: make([]syscall.EpollEvent, 0), + epes: make([]unix.EpollEvent, 0), c: c, } runtime.SetFinalizer(i, func(i *inotify) { i.epollclose() if i.fd != invalidDescriptor { - syscall.Close(int(i.fd)) + unix.Close(int(i.fd)) } }) return i @@ -82,13 +83,13 @@ func (i *inotify) Rewatch(path string, _, newevent Event) error { // one. If called for the first time, this function initializes inotify filesystem // monitor and starts producer-consumers goroutines. func (i *inotify) watch(path string, e Event) (err error) { - if e&^(All|Event(syscall.IN_ALL_EVENTS)) != 0 { + if e&^(All|Event(unix.IN_ALL_EVENTS)) != 0 { return errors.New("notify: unknown event") } if err = i.lazyinit(); err != nil { return } - iwd, err := syscall.InotifyAddWatch(int(i.fd), path, encode(e)) + iwd, err := unix.InotifyAddWatch(int(i.fd), path, encode(e)) if err != nil { return } @@ -119,13 +120,13 @@ func (i *inotify) lazyinit() error { i.Lock() defer i.Unlock() if atomic.LoadInt32(&i.fd) == invalidDescriptor { - fd, err := syscall.InotifyInit() + fd, err := unix.InotifyInit() if err != nil { return err } i.fd = int32(fd) if err = i.epollinit(); err != nil { - _, _ = i.epollclose(), syscall.Close(int(fd)) // Ignore errors. + _, _ = i.epollclose(), unix.Close(int(fd)) // Ignore errors. i.fd = invalidDescriptor return err } @@ -145,33 +146,33 @@ func (i *inotify) lazyinit() error { // with inotify event queue and the read end of the pipe are added to epoll set. // Note that `fd` member must be set before this function is called. func (i *inotify) epollinit() (err error) { - if i.epfd, err = syscall.EpollCreate1(0); err != nil { + if i.epfd, err = unix.EpollCreate1(0); err != nil { return } - if err = syscall.Pipe(i.pipefd); err != nil { + if err = unix.Pipe(i.pipefd); err != nil { return } - i.epes = []syscall.EpollEvent{ - {Events: syscall.EPOLLIN, Fd: i.fd}, - {Events: syscall.EPOLLIN, Fd: int32(i.pipefd[0])}, + i.epes = []unix.EpollEvent{ + {Events: unix.EPOLLIN, Fd: i.fd}, + {Events: unix.EPOLLIN, Fd: int32(i.pipefd[0])}, } - if err = syscall.EpollCtl(i.epfd, syscall.EPOLL_CTL_ADD, int(i.fd), &i.epes[0]); err != nil { + if err = unix.EpollCtl(i.epfd, unix.EPOLL_CTL_ADD, int(i.fd), &i.epes[0]); err != nil { return } - return syscall.EpollCtl(i.epfd, syscall.EPOLL_CTL_ADD, i.pipefd[0], &i.epes[1]) + return unix.EpollCtl(i.epfd, unix.EPOLL_CTL_ADD, i.pipefd[0], &i.epes[1]) } // epollclose closes the file descriptor created by the call to epoll_create(2) // and two file descriptors opened by pipe(2) function. func (i *inotify) epollclose() (err error) { if i.epfd != invalidDescriptor { - if err = syscall.Close(i.epfd); err == nil { + if err = unix.Close(i.epfd); err == nil { i.epfd = invalidDescriptor } } for n, fd := range i.pipefd { if fd != invalidDescriptor { - switch e := syscall.Close(fd); { + switch e := unix.Close(fd); { case e != nil && err == nil: err = e case e == nil: @@ -187,10 +188,10 @@ func (i *inotify) epollclose() (err error) { // one of the event's consumers. If pipe fd became ready, loop function closes // all file descriptors opened by lazyinit method and returns afterwards. func (i *inotify) loop(esch chan<- []*event) { - epes := make([]syscall.EpollEvent, 1) + epes := make([]unix.EpollEvent, 1) fd := atomic.LoadInt32(&i.fd) for { - switch _, err := syscall.EpollWait(i.epfd, epes, -1); err { + switch _, err := unix.EpollWait(i.epfd, epes, -1); err { case nil: switch epes[0].Fd { case fd: @@ -199,17 +200,17 @@ func (i *inotify) loop(esch chan<- []*event) { case int32(i.pipefd[0]): i.Lock() defer i.Unlock() - if err = syscall.Close(int(fd)); err != nil && err != syscall.EINTR { + if err = unix.Close(int(fd)); err != nil && err != unix.EINTR { panic("notify: close(2) error " + err.Error()) } atomic.StoreInt32(&i.fd, invalidDescriptor) - if err = i.epollclose(); err != nil && err != syscall.EINTR { + if err = i.epollclose(); err != nil && err != unix.EINTR { panic("notify: epollclose error " + err.Error()) } close(esch) return } - case syscall.EINTR: + case unix.EINTR: continue default: // We should never reach this line. panic("notify: epoll_wait(2) error " + err.Error()) @@ -220,22 +221,22 @@ func (i *inotify) loop(esch chan<- []*event) { // read reads events from an inotify file descriptor. It does not handle errors // returned from read(2) function since they are not critical to watcher logic. func (i *inotify) read() (es []*event) { - n, err := syscall.Read(int(i.fd), i.buffer[:]) - if err != nil || n < syscall.SizeofInotifyEvent { + n, err := unix.Read(int(i.fd), i.buffer[:]) + if err != nil || n < unix.SizeofInotifyEvent { return } - var sys *syscall.InotifyEvent - nmin := n - syscall.SizeofInotifyEvent + var sys *unix.InotifyEvent + nmin := n - unix.SizeofInotifyEvent for pos, path := 0, ""; pos <= nmin; { - sys = (*syscall.InotifyEvent)(unsafe.Pointer(&i.buffer[pos])) - pos += syscall.SizeofInotifyEvent + sys = (*unix.InotifyEvent)(unsafe.Pointer(&i.buffer[pos])) + pos += unix.SizeofInotifyEvent if path = ""; sys.Len > 0 { endpos := pos + int(sys.Len) path = string(bytes.TrimRight(i.buffer[pos:endpos], "\x00")) pos = endpos } es = append(es, &event{ - sys: syscall.InotifyEvent{ + sys: unix.InotifyEvent{ Wd: sys.Wd, Mask: sys.Mask, Cookie: sys.Cookie, @@ -268,7 +269,7 @@ func (i *inotify) transform(es []*event) []*event { var multi []*event i.RLock() for idx, e := range es { - if e.sys.Mask&(syscall.IN_IGNORED|syscall.IN_Q_OVERFLOW) != 0 { + if e.sys.Mask&(unix.IN_IGNORED|unix.IN_Q_OVERFLOW) != 0 { es[idx] = nil continue } @@ -317,7 +318,7 @@ func encode(e Event) uint32 { // can be nil when the event should not be passed on. func decode(mask Event, e *event) (syse *event) { if sysmask := uint32(mask) & e.sys.Mask; sysmask != 0 { - syse = &event{sys: syscall.InotifyEvent{ + syse = &event{sys: unix.InotifyEvent{ Wd: e.sys.Wd, Mask: e.sys.Mask, Cookie: e.sys.Cookie, @@ -357,7 +358,7 @@ func (i *inotify) Unwatch(path string) (err error) { return errors.New("notify: path " + path + " is already watched") } fd := atomic.LoadInt32(&i.fd) - if _, err = syscall.InotifyRmWatch(int(fd), uint32(iwd)); err != nil { + if _, err = unix.InotifyRmWatch(int(fd), uint32(iwd)); err != nil { return } i.Lock() @@ -377,12 +378,12 @@ func (i *inotify) Close() (err error) { return nil } for iwd := range i.m { - if _, e := syscall.InotifyRmWatch(int(i.fd), uint32(iwd)); e != nil && err == nil { + if _, e := unix.InotifyRmWatch(int(i.fd), uint32(iwd)); e != nil && err == nil { err = e } delete(i.m, iwd) } - switch _, errwrite := syscall.Write(i.pipefd[1], []byte{0x00}); { + switch _, errwrite := unix.Write(i.pipefd[1], []byte{0x00}); { case errwrite != nil && err == nil: err = errwrite fallthrough diff --git a/vendor/github.com/rjeczalik/notify/watchpoint_other.go b/vendor/github.com/rjeczalik/notify/watchpoint_other.go index 881631c9..9bb381db 100644 --- a/vendor/github.com/rjeczalik/notify/watchpoint_other.go +++ b/vendor/github.com/rjeczalik/notify/watchpoint_other.go @@ -15,7 +15,7 @@ func eventmask(ei EventInfo, extra Event) Event { // matches reports a match only when: // // - for user events, when event is present in the given set -// - for internal events, when additionaly both event and set have omit bit set +// - for internal events, when additionally both event and set have omit bit set // // Internal events must not be sent to user channels and vice versa. func matches(set, event Event) bool { diff --git a/vendor/vendor.json b/vendor/vendor.json index 4c431103..e03e6e52 100644 --- a/vendor/vendor.json +++ b/vendor/vendor.json @@ -39,10 +39,10 @@ "revisionTime": "2015-12-11T09:06:21+09:00" }, { - "checksumSHA1": "+jYYwEFAR+NW42UwA/AeppFYTbs=", + "checksumSHA1": "fUWokilZyc1QDKnIgCDJE8n1S9U=", "path": "github.com/minio/cli", - "revision": "bf72f027481f5fadaf8800f62c72904e6bd7a200", - "revisionTime": "2016-11-25T09:07:42Z" + "revision": "b8ae5507c0ceceecc22d5dbd386b58fbd4fdce72", + "revisionTime": "2017-02-27T07:32:28Z" }, { "path": "github.com/minio/go-homedir", @@ -50,10 +50,10 @@ "revisionTime": "2015-10-24T22:24:27-07:00" }, { - "checksumSHA1": "2FrFoR0UtufaCGRxM4UxP1fR3LM=", + "checksumSHA1": "q2mnNtdkxvuzEx8d5W0uCO0wmgI=", "path": "github.com/minio/minio-go", - "revision": "952412b95ae05cced91069ddc97b108a675ca1d1", - "revisionTime": "2017-01-05T09:15:05Z" + "revision": "ef0dc7e81b008739bd2ab9cb5b5cfbdc22bf32a5", + "revisionTime": "2017-04-01T21:28:19Z" }, { "checksumSHA1": "qTxOBp3GVxCC70ykb7Hxg6UgWwA=", @@ -80,10 +80,10 @@ "revisionTime": "2016-08-18T00:31:20Z" }, { - "checksumSHA1": "/sSaCssOzqtaSoIFhV0V8SPW5nk=", + "checksumSHA1": "M7IzPNZncWn7ve14/YPF2HKhCko=", "path": "github.com/minio/minio/pkg/madmin", - "revision": "f612a7dd8574ed98ac30ca0f3758f49fa5369635", - "revisionTime": "2017-02-01T19:46:49Z" + "revision": "97dc34fe06274894316a68e0e86e6c8cf498e21a", + "revisionTime": "2017-03-21T19:02:39Z" }, { "path": "github.com/minio/minio/pkg/probe", @@ -102,16 +102,28 @@ "revision": "0060549addd566b2ac568891efa1579be3024a97", "revisionTime": "2016-08-14T22:47:51Z" }, + { + "checksumSHA1": "6XkX4S1uBycCm+SYcY7CRtuFtvc=", + "path": "github.com/minio/minio/pkg/trie", + "revision": "8912b6bf3b22ff668b6448742cd50e7b837182ec", + "revisionTime": "2017-02-10T19:51:41Z" + }, + { + "checksumSHA1": "+lLm3Uz721j8WzlV813lWiATrXM=", + "path": "github.com/minio/minio/pkg/words", + "revision": "7ebf11b20233d0eba0f1a28dbd124e7fdd44aee2", + "revisionTime": "2017-03-19T21:23:05Z" + }, { "path": "github.com/pkg/profile", "revision": "19396ecfda37c1c9ddaa52019adca59d582e4832", "revisionTime": "2016-03-15T12:21:13+11:00" }, { - "checksumSHA1": "zkOV0IhJDfliQY72Z8OCBRGPZIw=", + "checksumSHA1": "ZYLNe3yInOcxTtzu7ERLL2hoQxE=", "path": "github.com/rjeczalik/notify", - "revision": "b8dab33f409f63a90858d0eff0da94ed1a692b66", - "revisionTime": "2017-01-17T22:12:36Z" + "revision": "41a86457b5eea072a7e6f40bbfaf94c8df41d3aa", + "revisionTime": "2017-03-01T20:33:46Z" }, { "checksumSHA1": "KqecwXo3OO+p4N+E9RhlHvl9I+w=",