Merge branch 'master' into release

This commit is contained in:
Minio Trusted
2017-04-03 11:32:59 -07:00
118 changed files with 4417 additions and 2204 deletions
+1 -1
View File
@@ -9,7 +9,7 @@ env:
- ARCH=i686
go:
- 1.7.3
- 1.8
script:
- make test GOFLAGS="-race"
+11
View File
@@ -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
```
+1 -1
View File
@@ -1,4 +1,4 @@
FROM golang:1.7-alpine
FROM golang:1.8-alpine
WORKDIR /go/src/app
+22 -30
View File
@@ -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> <YOUR-S3-ENDPOINT> <YOUR-ACCESS-KEY> <YOUR-SECRET-KEY> <API-SIGNATURE>
```
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/
```
<a name="everyday-use"></a>
## 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 <TAB>
admin config diff ls mirror policy session update watch
cat cp events mb pipe rm share version
```
## Explore Further
+4
View File
@@ -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
+14
View File
@@ -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
+5
View File
@@ -0,0 +1,5 @@
autoload -U compinit && compinit
autoload -U bashcompinit && bashcompinit
script_dir=$(dirname $0)
source ${script_dir}/bash_autocomplete
+88 -147
View File
@@ -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 "$@"
+1 -1
View File
@@ -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.
+16 -1
View File
@@ -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
+95
View File
@@ -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
}
+134
View File
@@ -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
}
+39
View File
@@ -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.
}
+66 -23
View File
@@ -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})
}
}
+131 -66
View File
@@ -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
+217
View File
@@ -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 = "<none>"
}
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
}
+25 -13
View File
@@ -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 {
+11 -12
View File
@@ -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/
`,
}
+3 -22
View File
@@ -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.
}
+11 -27
View File
@@ -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.
}
@@ -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
+6 -5
View File
@@ -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.
+14 -79
View File
@@ -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
+9 -29
View File
@@ -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.
}
+10 -10
View File
@@ -1,5 +1,5 @@
/*
* Minio Client, (C) 2015 Minio, Inc.
* Minio Client, (C) 2015, 2016, 2017 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -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
}
+14 -14
View File
@@ -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
}
+90 -262
View File
@@ -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) {
-7
View File
@@ -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.
+1 -1
View File
@@ -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)
+28 -13
View File
@@ -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.
+8 -8
View File
@@ -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())
}
}
+140
View File
@@ -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
}
+147
View File
@@ -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...)
}
-308
View File
@@ -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)
}
}
+88
View File
@@ -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})
}
+88
View File
@@ -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)
}
+7 -26
View File
@@ -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.
}
+33 -33
View File
@@ -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())
}
+1 -1
View File
@@ -24,7 +24,7 @@ const (
accessKeyMinLen = 5
accessKeyMaxLen = 20
secretKeyMinLen = 8
secretKeyMaxLen = 40
secretKeyMaxLen = 100
)
// isValidAccessKey - validate access key for right length.
+14 -19
View File
@@ -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()))
}
}
}
+9 -9
View File
@@ -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.")
}
}
}
+2 -2
View File
@@ -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
}
+31 -24
View File
@@ -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)
+26 -10
View File
@@ -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
+7 -5
View File
@@ -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
`,
}
+7 -5
View File
@@ -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
`,
}
+7 -26
View File
@@ -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.
}
+7 -5
View File
@@ -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
`,
}
+5 -2
View File
@@ -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{
+2 -1
View File
@@ -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 (
+20 -8
View File
@@ -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
+14 -13
View File
@@ -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
+46 -20
View File
@@ -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
}
+18 -17
View File
@@ -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
}
+7 -7
View File
@@ -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)
+188 -77
View File
@@ -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
}
+7 -11
View File
@@ -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.
+23 -17
View File
@@ -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
}
+8 -8
View File
@@ -1,5 +1,5 @@
/*
* Minio Client, (C) 2015 Minio, Inc.
* Minio Client, (C) 2015, 2016, 2017 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -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
`,
}
+30 -26
View File
@@ -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+"`.")
}
}
+40 -26
View File
@@ -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
}
+24 -22
View File
@@ -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()))
+11 -11
View File
@@ -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+"`.")
}
}
}
+1 -1
View File
@@ -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
+2 -2
View File
@@ -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"))
+39 -13
View File
@@ -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+"`.")
}
}
}
+6 -5
View File
@@ -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.
+9 -27
View File
@@ -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.
}
+13 -12
View File
@@ -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+"`.")
}
}
}
+8 -8
View File
@@ -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())
}
}
+1 -8
View File
@@ -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
+7 -7
View File
@@ -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 {
+206 -149
View File
@@ -1,5 +1,5 @@
/*
* Minio Client (C) 2015 Minio, Inc.
* Minio Client (C) 2015, 2016, 2017 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -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 (<OS>; <ARCH>[; docker][; source]) mc/<VERSION> mc/<RELEASE-TAG> mc/<COMMIT-ID>
//
// 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
}
+2 -2
View File
@@ -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
+22 -12
View File
@@ -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
}
+10 -10
View File
@@ -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
`,
}
+13 -7
View File
@@ -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)
}
}
+17 -7
View File
@@ -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)
}
+18 -4
View File
@@ -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
}
+40 -39
View File
@@ -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
}
+37 -23
View File
@@ -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
}
+16 -16
View File
@@ -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
+4 -4
View File
@@ -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
+3 -3
View File
@@ -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,
})
+15 -17
View File
@@ -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.
+21
View File
@@ -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.
+6 -6
View File
@@ -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,
})
+3 -5
View File
@@ -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)
+7 -7
View File
@@ -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.
+24 -12
View File
@@ -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
+10 -5
View File
@@ -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
+5 -2
View File
@@ -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"
+6 -4
View File
@@ -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.
+108
View File
@@ -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)
}
+294
View File
@@ -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
}
+164
View File
@@ -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
}
+44
View File
@@ -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
}
+1 -1
View File
@@ -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])
}
}
}
+6
View File
@@ -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
}
}
}
+202
View File
@@ -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.

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