Compare commits
293
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3fe080982e | ||
|
|
2c8115de4e | ||
|
|
5b74d8c444 | ||
|
|
1d683ea83e | ||
|
|
38652b168a | ||
|
|
cca8c10f33 | ||
|
|
2ffa265d8c | ||
|
|
0098fbcc5b | ||
|
|
ad850412d2 | ||
|
|
4f0c2bf376 | ||
|
|
fa75251c76 | ||
|
|
3fefebd05d | ||
|
|
9d7529118e | ||
|
|
507e7672c2 | ||
|
|
9c81d374b1 | ||
|
|
38c3703d08 | ||
|
|
973dc13cc0 | ||
|
|
bca93f6c83 | ||
|
|
caf6bfb76f | ||
|
|
76180184a5 | ||
|
|
0e1e954768 | ||
|
|
b031817fce | ||
|
|
6b2e63e66c | ||
|
|
085a1e512f | ||
|
|
31cb23f586 | ||
|
|
6a7ca4311e | ||
|
|
d87078bee6 | ||
|
|
50228116e1 | ||
|
|
95033f3f76 | ||
|
|
a8acbe5cfb | ||
|
|
f9d4c4dbac | ||
|
|
17abc6c736 | ||
|
|
94bd9564d0 | ||
|
|
c6cb6595be | ||
|
|
a2f25c2f3b | ||
|
|
5d3c4ed96c | ||
|
|
7cec8f2285 | ||
|
|
86777e7863 | ||
|
|
853fea16b4 | ||
|
|
9cf76b1233 | ||
|
|
66a65aab02 | ||
|
|
5581915bc0 | ||
|
|
ee7f4e1d52 | ||
|
|
8c65985cd0 | ||
|
|
23a58eb5da | ||
|
|
9193eef1c9 | ||
|
|
e90e9bc352 | ||
|
|
a1d860f818 | ||
|
|
d733d68b0c | ||
|
|
4a96d65408 | ||
|
|
1e16ed5e55 | ||
|
|
782352ae56 | ||
|
|
d97ba4eb0d | ||
|
|
282246fff2 | ||
|
|
b3059164aa | ||
|
|
64166319ee | ||
|
|
b8e732e526 | ||
|
|
f0d926ebba | ||
|
|
1e48d10617 | ||
|
|
ce9d706716 | ||
|
|
81abbca12f | ||
|
|
2cd67b296e | ||
|
|
7976d6d805 | ||
|
|
df395786bd | ||
|
|
2412aae68f | ||
|
|
0a42e2969a | ||
|
|
b51e6b0485 | ||
|
|
e1ed7c65e7 | ||
|
|
cf89d74561 | ||
|
|
38aec4d875 | ||
|
|
23f0a27acc | ||
|
|
447cb7a726 | ||
|
|
fa5a339434 | ||
|
|
7a295dd5fa | ||
|
|
2895b0acca | ||
|
|
ab9cdd7fce | ||
|
|
cc6fa9acbf | ||
|
|
e14dcccd37 | ||
|
|
27526399f5 | ||
|
|
8009e8108b | ||
|
|
b45d48f4f1 | ||
|
|
b9f1950320 | ||
|
|
6de2b4559e | ||
|
|
0661f537cf | ||
|
|
b737b2e7fc | ||
|
|
d9b3f276b8 | ||
|
|
53ab0168e4 | ||
|
|
01f0c35651 | ||
|
|
75d55783c0 | ||
|
|
f03aaef72f | ||
|
|
f54e426bb1 | ||
|
|
5b94ddc703 | ||
|
|
477461325d | ||
|
|
3094af8a5e | ||
|
|
add7dcc763 | ||
|
|
df7acbcad4 | ||
|
|
15b91126d5 | ||
|
|
2b24a7b520 | ||
|
|
b404c7583b | ||
|
|
6ce337ca38 | ||
|
|
d0caa630af | ||
|
|
8a48d604a8 | ||
|
|
80b0aa3842 | ||
|
|
c6a383590d | ||
|
|
fd34958ffa | ||
|
|
530a34a3f3 | ||
|
|
90093b5d8c | ||
|
|
939dad5900 | ||
|
|
85717527d9 | ||
|
|
768be74f74 | ||
|
|
a885ffd64b | ||
|
|
e25f1ee72f | ||
|
|
6e943832d5 | ||
|
|
3a3bc2ffb1 | ||
|
|
90a421e4af | ||
|
|
bc72ffb6b2 | ||
|
|
a30f0aca85 | ||
|
|
2ea2ec90d2 | ||
|
|
22670acfbe | ||
|
|
358a5af98e | ||
|
|
c70bd05494 | ||
|
|
0b4d52a141 | ||
|
|
a47c86c54c | ||
|
|
082ea3c295 | ||
|
|
a4177ad30b | ||
|
|
3603766f1c | ||
|
|
951429fe67 | ||
|
|
f5ff7e15cf | ||
|
|
c9c95f2e9e | ||
|
|
bc79fba49a | ||
|
|
b51fb32054 | ||
|
|
c9ecd023fa | ||
|
|
c28aa819b6 | ||
|
|
f6ca45c384 | ||
|
|
75de34de90 | ||
|
|
429a0d00af | ||
|
|
acf933646b | ||
|
|
b427202237 | ||
|
|
8eaa9463c1 | ||
|
|
e15f04c01b | ||
|
|
626baab73d | ||
|
|
5e8f861eac | ||
|
|
9217553a3c | ||
|
|
ab20dc98f7 | ||
|
|
9f1315fa64 | ||
|
|
46d158d023 | ||
|
|
acd80370e6 | ||
|
|
9ad19bfe52 | ||
|
|
eed14719db | ||
|
|
589c821f9b | ||
|
|
a09795c8a7 | ||
|
|
52df29917b | ||
|
|
16ae081c4c | ||
|
|
489d1629fb | ||
|
|
9be8aebfff | ||
|
|
e53fa1a5a2 | ||
|
|
92d1e226d3 | ||
|
|
64dbb7ed9c | ||
|
|
21b0f4b0d2 | ||
|
|
fc448e49d5 | ||
|
|
7a21e4bb0d | ||
|
|
47ca8a61ea | ||
|
|
1c3f889f6e | ||
|
|
6f4a0f9cbb | ||
|
|
67c1957eb0 | ||
|
|
3d7796f38c | ||
|
|
2d431dacbc | ||
|
|
17468c8863 | ||
|
|
475670de7d | ||
|
|
f9efb67bc2 | ||
|
|
9766ff1805 | ||
|
|
cc4227e3f2 | ||
|
|
ba2e8149c8 | ||
|
|
b48371e971 | ||
|
|
8b074767db | ||
|
|
e5bc26c75a | ||
|
|
959fa74ca5 | ||
|
|
ac57970229 | ||
|
|
9fb8cfc1b3 | ||
|
|
06ad6c53f7 | ||
|
|
a9b0b14149 | ||
|
|
9a454e714d | ||
|
|
319b3d8434 | ||
|
|
2fec2b4107 | ||
|
|
382aa26859 | ||
|
|
d7854b6dfa | ||
|
|
e3b6c12925 | ||
|
|
d9224348ce | ||
|
|
6b91c6f430 | ||
|
|
7e9b96e354 | ||
|
|
8a8d4619de | ||
|
|
3af0902f28 | ||
|
|
6b4c1a4239 | ||
|
|
783d29794a | ||
|
|
a094c50f5a | ||
|
|
621e8cf0ff | ||
|
|
4bd9336139 | ||
|
|
c517833663 | ||
|
|
8e4cc8df00 | ||
|
|
94f4c4cd2d | ||
|
|
c4c99999bc | ||
|
|
6abd3a4ed6 | ||
|
|
9e94120d68 | ||
|
|
ba088b8fc0 | ||
|
|
98ac1817cb | ||
|
|
65a31e34c9 | ||
|
|
264f1ef992 | ||
|
|
b30bbc0e74 | ||
|
|
7a77686878 | ||
|
|
0c4200306b | ||
|
|
619b1b4e2a | ||
|
|
57d22664f4 | ||
|
|
38339b7cd9 | ||
|
|
d5cb19aeab | ||
|
|
3d04e56228 | ||
|
|
3e8f7684f2 | ||
|
|
c11527780a | ||
|
|
5a204741b9 | ||
|
|
b23e8a77fc | ||
|
|
e926266c62 | ||
|
|
1eca4f8c0d | ||
|
|
edb1824006 | ||
|
|
6666262e51 | ||
|
|
221ee6c26b | ||
|
|
d3d4afd223 | ||
|
|
f55f64b5b9 | ||
|
|
69fbb9a87d | ||
|
|
8e50e8e8c3 | ||
|
|
8cdf71b539 | ||
|
|
e7f4b63212 | ||
|
|
12adf3be32 | ||
|
|
087516a783 | ||
|
|
1b2a2fc7f9 | ||
|
|
3e205dba15 | ||
|
|
ff874575e1 | ||
|
|
1e1516c968 | ||
|
|
aeb6de996c | ||
|
|
82d87111fc | ||
|
|
49953d53ed | ||
|
|
13a4133da5 | ||
|
|
a02ae19de2 | ||
|
|
9617f22fcd | ||
|
|
e156d62e44 | ||
|
|
f4e8352f5a | ||
|
|
deb7f72be2 | ||
|
|
a5a57fa2be | ||
|
|
c3fb1d52f4 | ||
|
|
9820dce775 | ||
|
|
426df2c9ab | ||
|
|
20c7a00af5 | ||
|
|
00d0f1e9d9 | ||
|
|
4cecac4ea4 | ||
|
|
b0e2bde84d | ||
|
|
49851c8795 | ||
|
|
7bdb39c743 | ||
|
|
09495582c4 | ||
|
|
f15be9582a | ||
|
|
c022107515 | ||
|
|
373b593c3e | ||
|
|
ca06c0e09f | ||
|
|
bd1086c244 | ||
|
|
69c8bf7959 | ||
|
|
db6b4f1344 | ||
|
|
05db6e3981 | ||
|
|
2623eeb82e | ||
|
|
cbebadc16a | ||
|
|
614d6d81e5 | ||
|
|
cac451c83e | ||
|
|
54a86c69e1 | ||
|
|
ea8f5c0f33 | ||
|
|
340d576931 | ||
|
|
7db8820042 | ||
|
|
54761b22fd | ||
|
|
253f13640c | ||
|
|
97110c9676 | ||
|
|
9805c4d907 | ||
|
|
56d548ad10 | ||
|
|
c196f6ee08 | ||
|
|
db55841e7d | ||
|
|
fb70ef7b1c | ||
|
|
fa82223c50 | ||
|
|
6f3cd87993 | ||
|
|
3ca7ac613d | ||
|
|
fe5b2f97e3 | ||
|
|
220bf92a3c | ||
|
|
5219fd59e8 | ||
|
|
4832da5cda | ||
|
|
4ef3dcffc4 | ||
|
|
fbe4768658 | ||
|
|
f63de3cc30 | ||
|
|
7c7d9e07a2 | ||
|
|
708f1e17f4 | ||
|
|
8fc48cf24a |
@@ -0,0 +1,12 @@
|
||||
## Expected behaviour
|
||||
|
||||
## Actual behaviour
|
||||
|
||||
## Steps to reproduce the behaviour
|
||||
|
||||
## mc version
|
||||
- (paste output of `mc version`)
|
||||
|
||||
## System information
|
||||
|
||||
|
||||
+4
-1
@@ -1,4 +1,7 @@
|
||||
cover.out
|
||||
mc
|
||||
./mc
|
||||
*~
|
||||
*.test
|
||||
release
|
||||
experimental
|
||||
coverage.txt
|
||||
+5
-9
@@ -1,25 +1,21 @@
|
||||
sudo: false
|
||||
language: go
|
||||
|
||||
script:
|
||||
- make test GOFLAGS="-race"
|
||||
|
||||
os:
|
||||
- linux
|
||||
- osx
|
||||
|
||||
env:
|
||||
- ARCH=x86_64
|
||||
- ARCH=i686
|
||||
|
||||
go:
|
||||
- 1.5.2
|
||||
- 1.5.3
|
||||
- 1.7.3
|
||||
|
||||
script:
|
||||
- make test GOFLAGS="-race"
|
||||
- make coverage
|
||||
- diff -au <(gofmt -d *.go) <(printf "")
|
||||
- diff -au <(gofmt -d pkg) <(printf "")
|
||||
|
||||
notifications:
|
||||
slack:
|
||||
secure: McinxQ4R/Yu2r/U8lVsdAIQ195Rf+3/Ku6DViWyqLHsTt5fTnVrSfbIKs8vy0t2A0bRLO6zv2xOSMWjfiimZLPMgMbMqLtTFEzUzB8RZyx2n2xgmL8q3gjXcLA3vkBreaRYCzJzX6DjvrxRfhyOg+BQHpLpACWik3FS/7VIdDCI=
|
||||
after_success:
|
||||
- bash <(curl -s https://codecov.io/bash)
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
## Contributors
|
||||
<!-- DO NOT EDIT - CONTRIBUTORS.md is autogenerated from git commit log by contributors.sh script. -->
|
||||
|
||||
- Anand Babu (AB) Periasamy <ab@minio.io>
|
||||
- Anis Elleuch <vadmeste@gmail.com>
|
||||
- Bosky <bosky@helpshift.com>
|
||||
- Frederick F. Kautz IV <fkautz@minio.io>
|
||||
- Harshavardhana <harsha@minio.io>
|
||||
- Krishna Srinivas <krishna@minio.io>
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
FROM golang:1.7-alpine
|
||||
|
||||
WORKDIR /go/src/app
|
||||
|
||||
COPY . /go/src/app
|
||||
|
||||
RUN \
|
||||
apk add --no-cache git && \
|
||||
go-wrapper download && \
|
||||
go-wrapper install -ldflags "-X github.com/minio/mc/cmd.Version=2017-02-06T20:16:19Z -X github.com/minio/mc/cmd.ReleaseTag=RELEASE.2017-02-06T20-16-19Z -X github.com/minio/mc/cmd.CommitID=2c8115de4edc5612525488b1b3b804689d336d01" && \
|
||||
rm -rf /go/pkg /go/src && \
|
||||
apk del git
|
||||
|
||||
ENTRYPOINT ["mc"]
|
||||
@@ -1,86 +0,0 @@
|
||||
## Ubuntu (Kylin) 14.04
|
||||
### Build Dependencies
|
||||
This installation guide is based on Ubuntu 14.04+ on x86-64 platform.
|
||||
|
||||
##### Install Git, GCC
|
||||
```sh
|
||||
$ sudo apt-get install git build-essential
|
||||
```
|
||||
|
||||
##### Install Go 1.5+
|
||||
|
||||
Download Go 1.5+ from [https://golang.org/dl/](https://golang.org/dl/).
|
||||
|
||||
```sh
|
||||
$ wget https://storage.googleapis.com/golang/go1.5.1.linux-amd64.tar.gz
|
||||
$ mkdir -p ${HOME}/bin/
|
||||
$ mkdir -p ${HOME}/go/
|
||||
$ tar -C ${HOME}/bin/ -xzf go1.5.1.linux-amd64.tar.gz
|
||||
```
|
||||
##### Setup GOROOT and GOPATH
|
||||
|
||||
Add the following exports to your ``~/.bashrc``. Environment variable GOROOT specifies the location of your golang binaries
|
||||
and GOPATH specifies the location of your project workspace.
|
||||
|
||||
```sh
|
||||
export GOROOT=${HOME}/bin/go
|
||||
export GOPATH=${HOME}/go
|
||||
export PATH=$PATH:${HOME}/bin/go/bin:${GOPATH}/bin
|
||||
```
|
||||
|
||||
##### Source the new environment
|
||||
|
||||
```sh
|
||||
$ source ~/.bashrc
|
||||
```
|
||||
|
||||
##### Testing it all
|
||||
```sh
|
||||
$ go env
|
||||
```
|
||||
|
||||
## OS X (Yosemite) 10.10
|
||||
### Build Dependencies
|
||||
This installation document assumes OS X Yosemite 10.10+ on x86-64 platform.
|
||||
|
||||
##### Install brew
|
||||
```sh
|
||||
$ ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
|
||||
```
|
||||
|
||||
##### Install Git, Python
|
||||
```sh
|
||||
$ brew install git python
|
||||
```
|
||||
|
||||
##### Install Go 1.5+
|
||||
|
||||
Install golang binaries using `brew`
|
||||
|
||||
```sh
|
||||
$ brew install go
|
||||
$ mkdir -p $HOME/go
|
||||
```
|
||||
|
||||
##### Setup GOROOT and GOPATH
|
||||
|
||||
Add the following exports to your ``~/.bash_profile``. Environment variable GOROOT specifies the location of your golang binaries
|
||||
and GOPATH specifies the location of your project workspace.
|
||||
|
||||
```sh
|
||||
export GOPATH=${HOME}/go
|
||||
export GOVERSION=$(brew list go | head -n 1 | cut -d '/' -f 6)
|
||||
export GOROOT=$(brew --prefix)/Cellar/go/${GOVERSION}/libexec
|
||||
export PATH=$PATH:${GOPATH}/bin
|
||||
```
|
||||
|
||||
##### Source the new environment
|
||||
|
||||
```sh
|
||||
$ source ~/.bash_profile
|
||||
```
|
||||
|
||||
##### Testing it all
|
||||
```sh
|
||||
$ go env
|
||||
```
|
||||
@@ -1,75 +1,87 @@
|
||||
LDFLAGS := $(shell go run buildscripts/gen-ldflags.go)
|
||||
BUILD_LDFLAGS := '$(LDFLAGS)'
|
||||
|
||||
all: install
|
||||
|
||||
checkdeps:
|
||||
checks:
|
||||
@echo "Checking deps:"
|
||||
@(env bash $(PWD)/buildscripts/checkdeps.sh)
|
||||
@(env bash buildscripts/checkdeps.sh)
|
||||
@(env bash buildscripts/checkgopath.sh)
|
||||
|
||||
checkgopath:
|
||||
@echo "Checking if project is at ${GOPATH}"
|
||||
@for mcpath in $(echo ${GOPATH} | sed 's/:/\n/g'); do if [ ! -d ${mcpath}/src/github.com/minio/mc ]; then echo "Project not found in ${mcpath}, please follow instructions provided at https://github.com/minio/minio/blob/master/CONTRIBUTING.md#setup-your-minio-github-repository" && exit 1; fi done
|
||||
@echo "BUILD_LDFLAGS: ${BUILD_LDFLAGS}"
|
||||
|
||||
getdeps: checkdeps checkgopath
|
||||
getdeps: checks
|
||||
@go get github.com/golang/lint/golint && echo "Installed golint:"
|
||||
@go get golang.org/x/tools/cmd/vet && echo "Installed vet:"
|
||||
@go get github.com/fzipp/gocyclo && echo "Installed gocyclo:"
|
||||
@go get github.com/remyoudompheng/go-misc/deadcode && echo "Installed deadcode:"
|
||||
@go get github.com/client9/misspell/cmd/misspell && echo "Installed misspell:"
|
||||
|
||||
# verifiers: getdeps vet fmt lint cyclo deadcode
|
||||
verifiers: getdeps vet fmt lint cyclo deadcode
|
||||
verifiers: vet fmt lint cyclo deadcode spelling
|
||||
|
||||
vet:
|
||||
@echo "Running $@:"
|
||||
@GO15VENDOREXPERIMENT=1 go tool vet -all *.go
|
||||
@GO15VENDOREXPERIMENT=1 go tool vet -all ./pkg
|
||||
@GO15VENDOREXPERIMENT=1 go tool vet -shadow=true *.go
|
||||
@GO15VENDOREXPERIMENT=1 go tool vet -shadow=true ./pkg
|
||||
@go tool vet -all *.go
|
||||
@go tool vet -all ./cmd
|
||||
@go tool vet -all ./pkg
|
||||
@go tool vet -shadow=true *.go
|
||||
@go tool vet -shadow=true ./cmd
|
||||
@go tool vet -shadow=true ./pkg
|
||||
|
||||
spelling:
|
||||
@${GOPATH}/bin/misspell *.go
|
||||
@${GOPATH}/bin/misspell cmd/*
|
||||
@${GOPATH}/bin/misspell pkg/**/*
|
||||
|
||||
fmt:
|
||||
@echo "Running $@:"
|
||||
@GO15VENDOREXPERIMENT=1 gofmt -s -l *.go
|
||||
@GO15VENDOREXPERIMENT=1 gofmt -s -l pkg
|
||||
@gofmt -s -l *.go
|
||||
@gofmt -s -l cmd
|
||||
@gofmt -s -l pkg
|
||||
lint:
|
||||
@echo "Running $@:"
|
||||
@GO15VENDOREXPERIMENT=1 golint .
|
||||
@GO15VENDOREXPERIMENT=1 golint github.com/minio/mc/pkg...
|
||||
@$(GOPATH)/bin/golint .
|
||||
@$(GOPATH)/bin/golint github.com/minio/mc/cmd...
|
||||
@$(GOPATH)/bin/golint github.com/minio/mc/pkg...
|
||||
|
||||
cyclo:
|
||||
@echo "Running $@:"
|
||||
@GO15VENDOREXPERIMENT=1 gocyclo -over 40 *.go
|
||||
@GO15VENDOREXPERIMENT=1 gocyclo -over 40 pkg
|
||||
@$(GOPATH)/bin/gocyclo -over 40 cmd
|
||||
@$(GOPATH)/bin/gocyclo -over 40 pkg
|
||||
|
||||
deadcode:
|
||||
@echo "Running $@:"
|
||||
@GO15VENDOREXPERIMENT=1 deadcode
|
||||
@$(GOPATH)/bin/deadcode
|
||||
|
||||
build: verifiers
|
||||
@echo "Installing mc:"
|
||||
build: getdeps verifiers
|
||||
|
||||
test: verifiers
|
||||
test: getdeps verifiers
|
||||
@echo "Running all testing:"
|
||||
@GO15VENDOREXPERIMENT=1 go test $(GOFLAGS) ./
|
||||
@GO15VENDOREXPERIMENT=1 go test $(GOFLAGS) github.com/minio/mc/pkg...
|
||||
@go test $(GOFLAGS) github.com/minio/mc/cmd...
|
||||
@go test $(GOFLAGS) github.com/minio/mc/pkg...
|
||||
|
||||
gomake-all: build
|
||||
@GO15VENDOREXPERIMENT=1 go build --ldflags $(BUILD_LDFLAGS) -o $(GOPATH)/bin/mc
|
||||
@echo "Installing mc:"
|
||||
@go build --ldflags "$(LDFLAGS)" -o $(GOPATH)/bin/mc
|
||||
@mkdir -p $(HOME)/.mc
|
||||
|
||||
coverage:
|
||||
@GO15VENDOREXPERIMENT=1 go test -race -coverprofile=cover.out ./
|
||||
@go tool cover -html=cover.out && echo "Visit your browser"
|
||||
coverage: getdeps verifiers
|
||||
@echo "Running all coverage:"
|
||||
@./buildscripts/go-coverage.sh
|
||||
|
||||
pkg-add:
|
||||
@GO15VENDOREXPERIMENT=1 govendor add $(PKG)
|
||||
pkg-validate-arg-%: ;
|
||||
ifndef PKG
|
||||
$(error Usage: make $(@:pkg-validate-arg-%=pkg-%) PKG=pkg_name)
|
||||
endif
|
||||
|
||||
pkg-update:
|
||||
@GO15VENDOREXPERIMENT=1 govendor update $(PKG)
|
||||
pkg-add: pkg-validate-arg-add
|
||||
@$(GOPATH)/bin/govendor add $(PKG)
|
||||
|
||||
pkg-remove:
|
||||
@GO15VENDOREXPERIMENT=1 govendor remove $(PKG)
|
||||
pkg-update: pkg-validate-arg-update
|
||||
@$(GOPATH)/bin/govendor update $(PKG)
|
||||
|
||||
pkg-remove: pkg-validate-arg-remove
|
||||
@$(GOPATH)/bin/govendor remove $(PKG)
|
||||
|
||||
pkg-list:
|
||||
@$(GOPATH)/bin/govendor list
|
||||
|
||||
install: gomake-all
|
||||
|
||||
@@ -77,9 +89,14 @@ all-tests: test
|
||||
# TODO disable them for now.
|
||||
#@./tests/test-minio.sh
|
||||
|
||||
release:
|
||||
@./release.sh
|
||||
release: verifiers
|
||||
@MC_RELEASE=RELEASE ./buildscripts/build.sh
|
||||
|
||||
experimental: verifiers
|
||||
@MC_RELEASE=EXPERIMENTAL ./buildscripts/build.sh
|
||||
|
||||
clean:
|
||||
@rm -fv cover.out
|
||||
@rm -fv mc
|
||||
@rm -f cover.out
|
||||
@rm -f mc
|
||||
@find . -name '*.test' | xargs rm -fv
|
||||
@rm -fr release
|
||||
|
||||
@@ -1,106 +1,191 @@
|
||||
# Minio Client (mc) [](https://gitter.im/minio/minio?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
||||
# Minio Client Quickstart Guide [](https://slack.minio.io)
|
||||
|
||||
``mc`` provides minimal tools to work with Amazon S3 compatible cloud storage and filesystems. It has features like resumable uploads/downloads, progress bar, parallel copy. ``mc`` is written in golang and released under [Apache license v2](./LICENSE).
|
||||
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).
|
||||
|
||||
## Commands
|
||||
|
||||
``mc`` implements the following commands
|
||||
```
|
||||
ls List files and folders.
|
||||
mb Make a bucket or folder.
|
||||
cat Display contents of a file.
|
||||
pipe Write contents of stdin to one or more targets. When no target is specified, it writes to stdout.
|
||||
share Generate URL for sharing.
|
||||
cp Copy one or more objects to a target.
|
||||
mirror Mirror folders recursively from a single source to many destinations.
|
||||
diff Compute differences between two folders.
|
||||
rm Remove file or bucket [WARNING: Use with care].
|
||||
access Manage bucket access permissions.
|
||||
session Manage saved sessions of cp and mirror operations.
|
||||
config Manage configuration file.
|
||||
update Check for a new software update.
|
||||
version Print version.
|
||||
```
|
||||
|
||||
## Install [](https://travis-ci.org/minio/mc) [](https://ci.appveyor.com/project/harshavardhana/mc)
|
||||
ls List files and folders.
|
||||
mb Make a bucket or folder.
|
||||
cat Display contents of a file.
|
||||
pipe Write contents of stdin to target. When no target is specified, it writes to stdout.
|
||||
share Generate URL for sharing.
|
||||
cp Copy one or more objects to a target.
|
||||
mirror Mirror folders recursively from a single source to single destination.
|
||||
diff Compute differences between two folders.
|
||||
rm Remove file or bucket [WARNING: Use with care].
|
||||
events Manage bucket notification.
|
||||
watch Watch for events on object storage and filesystem.
|
||||
policy Set public policy on bucket or prefix.
|
||||
session Manage saved sessions of cp and mirror operations.
|
||||
config Manage configuration file.
|
||||
update Check for a new software update.
|
||||
version Print version.
|
||||
|
||||
#### GNU/Linux
|
||||
```
|
||||
|
||||
Download ``mc`` for:
|
||||
## Docker Container
|
||||
### Stable
|
||||
```
|
||||
docker pull minio/mc
|
||||
docker run minio/mc ls play
|
||||
```
|
||||
|
||||
- ``64-bit Intel`` from https://dl.minio.io/client/mc/release/linux-amd64/mc
|
||||
- ``32-bit Intel`` from https://dl.minio.io/client/mc/release/linux-386/mc
|
||||
- ``32-bit ARM`` from https://dl.minio.io/client/mc/release/linux-arm/mc
|
||||
### Edge
|
||||
```
|
||||
docker pull minio/mc:edge
|
||||
docker run minio/mc ls play
|
||||
```
|
||||
|
||||
~~~
|
||||
$ chmod +x mc
|
||||
$ ./mc --help
|
||||
~~~
|
||||
|
||||
#### OS X
|
||||
|
||||
Download ``mc`` from https://dl.minio.io/client/mc/release/darwin-amd64/mc
|
||||
|
||||
~~~
|
||||
$ chmod 755 mc
|
||||
$ ./mc --help
|
||||
~~~
|
||||
|
||||
#### Microsoft Windows
|
||||
|
||||
Download ``mc`` for:
|
||||
|
||||
- ``64-bit`` from https://dl.minio.io/client/mc/release/windows-amd64/mc.exe
|
||||
- ``32-bit`` from https://dl.minio.io/client/mc/release/windows-386/mc.exe
|
||||
|
||||
~~~
|
||||
C:\Users\Username\Downloads> mc.exe --help
|
||||
~~~
|
||||
|
||||
#### Source
|
||||
<blockquote>
|
||||
NOTE: Source installation is intended for only developers and advanced users. ‘mc update’ continuous delivery mechanism is not supported for ‘go get’ based binary builds. Please download official releases from https://minio.io/#mc.
|
||||
</blockquote>
|
||||
|
||||
If you do not have a working Golang environment, please follow [Install Golang](./INSTALLGO.md).
|
||||
## macOS
|
||||
### Homebrew
|
||||
Install mc packages using [Homebrew](http://brew.sh/)
|
||||
|
||||
```sh
|
||||
$ GO15VENDOREXPERIMENT=1 go get -u github.com/minio/mc
|
||||
brew install minio-mc
|
||||
mc --help
|
||||
|
||||
```
|
||||
|
||||
## Public Minio Server
|
||||
## GNU/Linux
|
||||
### 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|
|
||||
|
||||
Minio cloud storage server is hosted at ``https://play.minio.io:9000`` for public use. This service is primarily intended for developers and users to familiarize themselves with Amazon S3 compatible cloud storage. Minio runs with filesystem backend with auto-expiry for objects in about 24 hours. No account signup is required, which means S3 compatible tools and applications can access this service without access and secret keys.
|
||||
```sh
|
||||
|
||||
## Configuring mc for Amazon S3
|
||||
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 |
|
||||
|
||||
```sh
|
||||
|
||||
mc.exe --help
|
||||
|
||||
```
|
||||
|
||||
## FreeBSD
|
||||
### Binary Download
|
||||
| Platform | Architecture | URL |
|
||||
| ---------- | -------- |------|
|
||||
|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
|
||||
Source installation is intended only for developers and advanced users. `mc update` command does not support update notifications for source based installations. Please download official releases from https://minio.io/downloads/#minio-client.
|
||||
|
||||
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
|
||||
If you are planning to use `mc` only on POSIX compatible filesystems, you may skip this step and proceed to [everyday use](#everyday-use).
|
||||
|
||||
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".
|
||||
|
||||
### Example - Minio Cloud Storage
|
||||
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).
|
||||
|
||||
Once you have them update your ``~/.mc/config.json`` configuration file.
|
||||
```
|
||||
$ mc config host add <ALIAS> <YOUR-S3-ENDPOINT> <YOUR-ACCESS-KEY> <YOUR-SECRET-KEY> S3v4
|
||||
```sh
|
||||
|
||||
mc config host add s3 https://s3.amazonaws.com BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 S3v4
|
||||
|
||||
```
|
||||
|
||||
Example
|
||||
```
|
||||
$ mc config host add mys3 https://s3.amazonaws.com BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12
|
||||
### 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: ``S3v4`` is default if not specified.
|
||||
NOTE: Google Cloud Storage only supports Legacy Signature Version 2, so you have to pick - S3v2
|
||||
|
||||
## Configure mc for Google Cloud Storage
|
||||
## Test Your Setup
|
||||
`mc` is pre-configured with https://play.minio.io:9000, aliased as "play". It is a hosted Minio server for testing and development purpose. To test Amazon S3, simply replace "play" with "s3" or the alias you used at the time of setup.
|
||||
|
||||
Get your AccessKeyID and SecretAccessKey by following [Google Credentials Guide](https://cloud.google.com/storage/docs/migrating?hl=en#keys).
|
||||
*Example:*
|
||||
|
||||
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/
|
||||
|
||||
Once you have them update your ``~/.mc/config.json`` configuration file.
|
||||
```
|
||||
$ mc config host add <ALIAS> https://storage.googleapis.com <YOUR-ACCESS-KEY> <YOUR-SECRET-KEY> S3v2
|
||||
<a name="everyday-use"></a>
|
||||
## Everyday Use
|
||||
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'
|
||||
|
||||
```
|
||||
|
||||
NOTE: Google Cloud Storage only supports Legacy Signature Version ``2``, so you have to pick - ``S3v2``
|
||||
## Explore Further
|
||||
- [Minio Client Complete Guide](https://docs.minio.io/docs/minio-client-complete-guide)
|
||||
- [Minio Quickstart Guide](https://docs.minio.io/docs/minio-quickstart-guide)
|
||||
- [The Minio documentation website](https://docs.minio.io)
|
||||
|
||||
## Contribute to Minio Client
|
||||
Please follow Minio [Contributor's Guide](./CONTRIBUTING.md)
|
||||
## Contribute to Minio Project
|
||||
Please follow Minio [Contributor's Guide](https://github.com/minio/mc/blob/master/CONTRIBUTING.md)
|
||||
|
||||
### Jobs
|
||||
If you think in Lisp or Haskell and hack in go, you would blend right in. Send your github link to callhome@minio.io.
|
||||
|
||||
-205
@@ -1,205 +0,0 @@
|
||||
/*
|
||||
* Minio Client, (C) 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
)
|
||||
|
||||
var (
|
||||
accessFlags = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "help, h",
|
||||
Usage: "Help of access.",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
// Set access permissions.
|
||||
var accessCmd = cli.Command{
|
||||
Name: "access",
|
||||
Usage: "Manage bucket access permissions.",
|
||||
Action: mainAccess,
|
||||
Flags: append(accessFlags, globalFlags...),
|
||||
CustomHelpTemplate: `Name:
|
||||
mc {{.Name}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
mc {{.Name}} [FLAGS] set PERMISSION TARGET [TARGET...]
|
||||
mc {{.Name}} [FLAGS] get TARGET [TARGET...]
|
||||
|
||||
PERMISSION:
|
||||
Allowed permissions are: [private, readonly, public, authorized].
|
||||
|
||||
FLAGS:
|
||||
{{range .Flags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Set bucket to "private" on Amazon S3 cloud storage.
|
||||
$ mc {{.Name}} set private s3/burningman2011
|
||||
|
||||
2. Set bucket to "public" on Amazon S3 cloud storage.
|
||||
$ mc {{.Name}} set public s3/shared
|
||||
|
||||
3. Set bucket to "authenticated" on Amazon S3 cloud storage to provide read access to IAM Authenticated Users group.
|
||||
$ mc {{.Name}} set authorized s3/shared-authenticated
|
||||
|
||||
4. Get bucket permissions.
|
||||
$ mc {{.Name}} get s3/shared
|
||||
|
||||
5. Get bucket permissions.
|
||||
$ mc {{.Name}} get gcs/miniocloud
|
||||
`,
|
||||
}
|
||||
|
||||
// accessMessage is container for access command on bucket success and failure messages.
|
||||
type accessMessage struct {
|
||||
Operation string `json:"operation"`
|
||||
Status string `json:"status"`
|
||||
Bucket string `json:"bucket"`
|
||||
Perms accessPerms `json:"permission"`
|
||||
}
|
||||
|
||||
// String colorized access message.
|
||||
func (s accessMessage) String() string {
|
||||
if s.Operation == "set" {
|
||||
return console.Colorize("Access",
|
||||
"Set access permission ‘"+string(s.Perms)+"’ updated successfully for ‘"+s.Bucket+"’")
|
||||
}
|
||||
if s.Operation == "get" {
|
||||
return console.Colorize("Access",
|
||||
"Access permission for ‘"+s.Bucket+"’"+" is ‘"+string(s.Perms)+"’")
|
||||
}
|
||||
// nothing to print
|
||||
return ""
|
||||
}
|
||||
|
||||
// JSON jsonified access message.
|
||||
func (s accessMessage) JSON() string {
|
||||
accessJSONBytes, e := json.Marshal(s)
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(accessJSONBytes)
|
||||
}
|
||||
|
||||
// checkAccessSyntax check for incoming syntax.
|
||||
func checkAccessSyntax(ctx *cli.Context) {
|
||||
if !ctx.Args().Present() {
|
||||
cli.ShowCommandHelpAndExit(ctx, "access", 1) // last argument is exit code.
|
||||
}
|
||||
if len(ctx.Args()) < 2 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "access", 1) // last argument is exit code.
|
||||
}
|
||||
switch ctx.Args().First() {
|
||||
case "set":
|
||||
if len(ctx.Args().Tail()) < 2 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "access", 1) // last argument is exit code.
|
||||
}
|
||||
perms := accessPerms(ctx.Args().Tail().Get(0))
|
||||
if !perms.isValidAccessPERM() {
|
||||
fatalIf(errDummy().Trace(),
|
||||
"Unrecognized permission ‘"+perms.String()+"’. Allowed values are [private, public, readonly, authorized].")
|
||||
}
|
||||
for _, arg := range ctx.Args().Tail().Tail() {
|
||||
if strings.TrimSpace(arg) == "" {
|
||||
fatalIf(errInvalidArgument().Trace(), "Unable to validate empty argument.")
|
||||
}
|
||||
}
|
||||
case "get":
|
||||
if len(ctx.Args().Tail()) < 1 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "access", 1) // last argument is exit code.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// doSetAccess do set access.
|
||||
func doSetAccess(targetURL string, targetPERMS accessPerms) *probe.Error {
|
||||
clnt, err := newClient(targetURL)
|
||||
if err != nil {
|
||||
return err.Trace(targetURL)
|
||||
}
|
||||
if err = clnt.SetBucketAccess(targetPERMS.String()); err != nil {
|
||||
return err.Trace(targetURL, targetPERMS.String())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// doGetAccess do get access.
|
||||
func doGetAccess(targetURL string) (perms accessPerms, err *probe.Error) {
|
||||
clnt, err := newClient(targetURL)
|
||||
if err != nil {
|
||||
return "", err.Trace(targetURL)
|
||||
}
|
||||
acl, err := clnt.GetBucketAccess()
|
||||
if err != nil {
|
||||
return "", err.Trace(targetURL)
|
||||
}
|
||||
return aclToPerms(acl), nil
|
||||
}
|
||||
|
||||
func mainAccess(ctx *cli.Context) {
|
||||
// Set global flags from context.
|
||||
setGlobalsFromContext(ctx)
|
||||
|
||||
// check 'access' cli arguments.
|
||||
checkAccessSyntax(ctx)
|
||||
|
||||
// Additional command speific theme customization.
|
||||
console.SetColor("Access", color.New(color.FgGreen, color.Bold))
|
||||
|
||||
switch ctx.Args().First() {
|
||||
case "set":
|
||||
perms := accessPerms(ctx.Args().Tail().First())
|
||||
URLs := ctx.Args().Tail().Tail()
|
||||
for _, targetURL := range URLs {
|
||||
err := doSetAccess(targetURL, perms)
|
||||
// Upon error, print and continue.
|
||||
if err != nil {
|
||||
errorIf(err.Trace(targetURL, string(perms)),
|
||||
"Unable to set access permission ‘"+string(perms)+"’ for ‘"+targetURL+"’.")
|
||||
continue
|
||||
}
|
||||
printMsg(accessMessage{
|
||||
Status: "success",
|
||||
Operation: "set",
|
||||
Bucket: targetURL,
|
||||
Perms: perms,
|
||||
})
|
||||
}
|
||||
case "get":
|
||||
URLs := ctx.Args().Tail()
|
||||
for _, targetURL := range URLs {
|
||||
perms, err := doGetAccess(targetURL)
|
||||
if err != nil {
|
||||
errorIf(err.Trace(targetURL), "Unable to get access permission for ‘"+targetURL+"’.")
|
||||
continue
|
||||
}
|
||||
printMsg(accessMessage{
|
||||
Status: "success",
|
||||
Operation: "get",
|
||||
Bucket: targetURL,
|
||||
Perms: perms,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,96 +0,0 @@
|
||||
/*
|
||||
* Minio Client (C) 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
// isValidAccessPERM - is provided access perm string supported.
|
||||
func (b accessPerms) isValidAccessPERM() bool {
|
||||
switch true {
|
||||
case b.isPrivate():
|
||||
fallthrough
|
||||
case b.isReadOnly():
|
||||
fallthrough
|
||||
case b.isPublic():
|
||||
fallthrough
|
||||
case b.isAuthorized():
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// accessPerms - access level.
|
||||
type accessPerms string
|
||||
|
||||
// different types of Access perm's currently supported by accesss command.
|
||||
const (
|
||||
accessPrivate = accessPerms("private")
|
||||
accessReadOnly = accessPerms("readonly")
|
||||
accessPublic = accessPerms("public")
|
||||
accessAuthorized = accessPerms("authorized")
|
||||
)
|
||||
|
||||
func (b accessPerms) String() string {
|
||||
if !b.isValidAccessPERM() {
|
||||
return string(b)
|
||||
}
|
||||
if b.isReadOnly() {
|
||||
return "public-read"
|
||||
}
|
||||
if b.isPublic() {
|
||||
return "public-read-write"
|
||||
}
|
||||
if b.isAuthorized() {
|
||||
return "authenticated-read"
|
||||
}
|
||||
return "private"
|
||||
}
|
||||
|
||||
// convert acl's to access perms
|
||||
func aclToPerms(acl string) accessPerms {
|
||||
switch acl {
|
||||
case "private":
|
||||
return accessPerms("private")
|
||||
case "public-read":
|
||||
return accessPerms("readonly")
|
||||
case "public-read-write":
|
||||
return accessPerms("public")
|
||||
case "authenticated-read":
|
||||
return accessPerms("authorized")
|
||||
default:
|
||||
return accessPerms(acl)
|
||||
}
|
||||
}
|
||||
|
||||
// isPrivate - is acl Private.
|
||||
func (b accessPerms) isPrivate() bool {
|
||||
return b == accessPrivate
|
||||
}
|
||||
|
||||
// isPublicRead - is acl PublicRead.
|
||||
func (b accessPerms) isReadOnly() bool {
|
||||
return b == accessReadOnly
|
||||
}
|
||||
|
||||
// isPublicReadWrite - is acl PublicReadWrite.
|
||||
func (b accessPerms) isPublic() bool {
|
||||
return b == accessPublic
|
||||
}
|
||||
|
||||
// isAuthorized - is acl AuthorizedRead.
|
||||
func (b accessPerms) isAuthorized() bool {
|
||||
return b == accessAuthorized
|
||||
}
|
||||
+7
-18
@@ -9,37 +9,26 @@ clone_folder: c:\gopath\src\github.com\minio\mc
|
||||
# environment variables
|
||||
environment:
|
||||
GOPATH: c:\gopath
|
||||
GO15VENDOREXPERIMENT: 1
|
||||
|
||||
# scripts that run after cloning repository
|
||||
install:
|
||||
- set PATH=%GOPATH%\bin;c:\go\bin;%PATH%
|
||||
- go version
|
||||
- go env
|
||||
- go get -u github.com/golang/lint/golint
|
||||
- go get -u golang.org/x/tools/cmd/vet
|
||||
- go get -u github.com/fzipp/gocyclo
|
||||
- go get -u github.com/remyoudompheng/go-misc/deadcode
|
||||
- go get -u github.com/alecthomas/gometalinter
|
||||
- go get -u github.com/client9/misspell
|
||||
|
||||
# to run your custom scripts instead of automatic MSBuild
|
||||
build_script:
|
||||
- go tool vet -all ./pkg
|
||||
- go tool vet -shadow=true ./pkg
|
||||
- gofmt -s -l pkg
|
||||
- golint .
|
||||
- golint github.com/minio/mc/pkg...
|
||||
- gometalinter --disable-all --linter='misspell:misspell ./*.go:PATH:LINE:COL:MESSAGE' --enable=misspell ./...
|
||||
- gocyclo -over 40 pkg
|
||||
- deadcode
|
||||
- go test -race .
|
||||
- go test -race github.com/minio/mc/cmd...
|
||||
- go test -race github.com/minio/mc/pkg...
|
||||
- go test -coverprofile=coverage.txt -covermode=atomic
|
||||
- go run buildscripts/gen-ldflags.go > temp.txt
|
||||
- set /p LDFLAGS=<temp.txt
|
||||
- go build -ldflags="%LDFLAGS%" -o %GOPATH%\bin\mc.exe
|
||||
- set /p BUILD_LDFLAGS=<temp.txt
|
||||
- go build -ldflags="%BUILD_LDFLAGS%" -o %GOPATH%\bin\mc.exe
|
||||
- mc version
|
||||
|
||||
after_test:
|
||||
- bash <(curl -s https://codecov.io/bash)
|
||||
|
||||
# to disable automatic tests
|
||||
test: off
|
||||
|
||||
|
||||
Executable
+131
@@ -0,0 +1,131 @@
|
||||
#!/bin/bash
|
||||
|
||||
_init() {
|
||||
# Save release LDFLAGS
|
||||
LDFLAGS=$(go run buildscripts/gen-ldflags.go)
|
||||
|
||||
# Extract release tag
|
||||
release_tag=$(echo $LDFLAGS | awk {'print $4'} | cut -f2 -d=)
|
||||
|
||||
# Verify release tag.
|
||||
if [ -z "$release_tag" ]; then
|
||||
echo "Release tag cannot be empty. Please check return value of \`go run buildscripts/gen-ldflags.go\`"
|
||||
exit 1;
|
||||
fi
|
||||
|
||||
# Extract release string.
|
||||
release_str=$(echo $MC_RELEASE | tr '[:upper:]' '[:lower:]')
|
||||
|
||||
# Verify release string.
|
||||
if [ -z "$release_str" ]; then
|
||||
echo "Release string cannot be empty. Please set \`MC_RELEASE\` env variable."
|
||||
exit 1;
|
||||
fi
|
||||
|
||||
# List of supported architectures
|
||||
SUPPORTED_OSARCH='linux/386 linux/amd64 linux/arm linux/arm64 windows/386 windows/amd64 freebsd/amd64'
|
||||
|
||||
## System binaries
|
||||
CP=`which cp`
|
||||
SHASUM=`which shasum`
|
||||
SED=`which sed`
|
||||
}
|
||||
|
||||
go_build() {
|
||||
local osarch=$1
|
||||
os=$(echo $osarch | cut -f1 -d'/')
|
||||
arch=$(echo $osarch | cut -f2 -d'/')
|
||||
package=$(go list -f '{{.ImportPath}}')
|
||||
echo -n "-->"
|
||||
printf "%15s:%s\n" "${osarch}" "${package}"
|
||||
|
||||
# Release binary name
|
||||
release_bin="$release_str/$os-$arch/$(basename $package).$release_tag"
|
||||
# Release binary downloadable name
|
||||
release_real_bin="$release_str/$os-$arch/$(basename $package)"
|
||||
# Release shasum name
|
||||
release_shasum="$release_str/$os-$arch/$(basename $package).shasum"
|
||||
|
||||
# Go build to build the binary.
|
||||
if [ "${arch}" == "arm" ]; then
|
||||
# Release binary downloadable name
|
||||
release_real_bin_6="$release_str/$os-${arch}6vl/$(basename $package)"
|
||||
|
||||
release_bin_6="$release_str/$os-${arch}6vl/$(basename $package).$release_tag"
|
||||
## Support building for ARM6vl
|
||||
CGO_ENABLED=0 GOARM=6 GOOS=$os GOARCH=$arch go build --ldflags "${LDFLAGS}" -o $release_bin_6
|
||||
|
||||
## Copy
|
||||
$CP -p $release_bin_6 $release_real_bin_6
|
||||
|
||||
# Release shasum name
|
||||
release_shasum_6="$release_str/$os-${arch}6vl/$(basename $package).shasum"
|
||||
|
||||
# Calculate shasum
|
||||
shasum_str=$(${SHASUM} ${release_bin_6})
|
||||
echo ${shasum_str} | $SED "s/$release_str\/$os-${arch}6vl\///g" > $release_shasum_6
|
||||
|
||||
# Release binary downloadable name
|
||||
release_real_bin_7="$release_str/$os-$arch/$(basename $package)"
|
||||
|
||||
release_bin_7="$release_str/$os-$arch/$(basename $package).$release_tag"
|
||||
## Support building for ARM7vl
|
||||
CGO_ENABLED=0 GOARM=7 GOOS=$os GOARCH=$arch go build --ldflags "${LDFLAGS}" -o $release_bin_7
|
||||
|
||||
## Copy
|
||||
$CP -p $release_bin_7 $release_real_bin_7
|
||||
|
||||
# Release shasum name
|
||||
release_shasum_7="$release_str/$os-$arch/$(basename $package).shasum"
|
||||
|
||||
# Calculate shasum
|
||||
shasum_str=$(${SHASUM} ${release_bin_7})
|
||||
echo ${shasum_str} | $SED "s/$release_str\/$os-$arch\///g" > $release_shasum_7
|
||||
else
|
||||
CGO_ENABLED=0 GOOS=$os GOARCH=$arch go build --ldflags "${LDFLAGS}" -o $release_bin
|
||||
|
||||
# Create copy
|
||||
if [ $os == "windows" ]; then
|
||||
$CP -p $release_bin ${release_real_bin}.exe
|
||||
else
|
||||
$CP -p $release_bin $release_real_bin
|
||||
fi
|
||||
|
||||
# Calculate shasum
|
||||
shasum_str=$(${SHASUM} ${release_bin})
|
||||
echo ${shasum_str} | $SED "s/$release_str\/$os-$arch\///g" > $release_shasum
|
||||
fi
|
||||
}
|
||||
|
||||
main() {
|
||||
# Build releases.
|
||||
echo "Executing $release_str builds for OS: ${SUPPORTED_OSARCH}"
|
||||
echo "Choose an OS Arch from the below"
|
||||
for osarch in ${SUPPORTED_OSARCH}; do
|
||||
echo ${osarch}
|
||||
done
|
||||
|
||||
read -p "If you want to build for all, Just press Enter: " chosen_osarch
|
||||
if [ "$chosen_osarch" = "" ]; then
|
||||
for each_osarch in ${SUPPORTED_OSARCH}; do
|
||||
go_build ${each_osarch}
|
||||
done
|
||||
else
|
||||
local found=0
|
||||
for each_osarch in ${SUPPORTED_OSARCH}; do
|
||||
if [ "$chosen_osarch" = "$each_osarch" ]; then
|
||||
found=1
|
||||
fi
|
||||
done
|
||||
if [ ${found} -eq 1 ]; then
|
||||
go_build ${chosen_osarch}
|
||||
else
|
||||
echo "Unknown architecture \"${chosen_osarch}\""
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
}
|
||||
|
||||
# Run main.
|
||||
_init && main
|
||||
+50
-38
@@ -21,12 +21,16 @@ _init() {
|
||||
|
||||
## Minimum required versions for build dependencies
|
||||
GIT_VERSION="1.0"
|
||||
GO_VERSION="1.5.1"
|
||||
GO_VERSION="1.7.1"
|
||||
OSX_VERSION="10.8"
|
||||
UNAME=$(uname -sm)
|
||||
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"
|
||||
}
|
||||
|
||||
readlink() {
|
||||
@@ -53,8 +57,8 @@ readlink() {
|
||||
###
|
||||
#
|
||||
# Takes two arguments
|
||||
# arg1: version number in `x.x.x` format
|
||||
# arg2: version number in `x.x.x` format
|
||||
# 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"
|
||||
#
|
||||
@@ -76,6 +80,14 @@ check_version() {
|
||||
|
||||
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
|
||||
@@ -86,7 +98,6 @@ check_version() {
|
||||
ver2[i]=0
|
||||
fi
|
||||
if ((10#${ver1[i]} > 10#${ver2[i]})); then
|
||||
|
||||
return 1
|
||||
fi
|
||||
if ((10#${ver1[i]} < 10#${ver2[i]})); then
|
||||
@@ -102,7 +113,7 @@ check_golang_env() {
|
||||
if [ $? -eq 1 ]; then
|
||||
echo "ERROR"
|
||||
echo "GOROOT environment variable missing, please refer to Go installation document"
|
||||
echo "https://github.com/minio/mc/blob/master/INSTALLGO.md#install-go-13"
|
||||
echo "${DOC_GO_INSTALL_URL}"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
@@ -110,7 +121,7 @@ check_golang_env() {
|
||||
if [ $? -eq 1 ]; then
|
||||
echo "ERROR"
|
||||
echo "GOPATH environment variable missing, please refer to Go installation document"
|
||||
echo "https://github.com/minio/mc/blob/master/INSTALLGO.md#install-go-13"
|
||||
echo "${DOC_GO_INSTALL_URL}"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
@@ -118,7 +129,7 @@ check_golang_env() {
|
||||
|
||||
if [ -z "${go_binary_path}" ] ; then
|
||||
echo "Cannot find go binary in your PATH configuration, please refer to Go installation document"
|
||||
echo "https://github.com/minio/mc/blob/master/INSTALLGO.md#install-go-13"
|
||||
echo "${DOC_GO_INSTALL_URL}"
|
||||
exit -1
|
||||
fi
|
||||
|
||||
@@ -127,51 +138,52 @@ check_golang_env() {
|
||||
new_go_binary_path=$(readlink ${go_binary_path})
|
||||
fi
|
||||
|
||||
if [[ !"$(dirname ${new_go_binary_path})" =~ *"${GOROOT%%*(/)}"* ]] ; then
|
||||
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 "https://github.com/minio/mc/blob/master/INSTALLGO.md#install-go-13"
|
||||
echo "${DOC_GO_INSTALL_URL}"
|
||||
exit -1
|
||||
fi
|
||||
}
|
||||
|
||||
is_supported_os() {
|
||||
case ${UNAME%% *} in
|
||||
"Linux")
|
||||
os="linux"
|
||||
assert_is_supported_os() {
|
||||
case "${KNAME}" in
|
||||
Linux | FreeBSD )
|
||||
return
|
||||
;;
|
||||
"Darwin")
|
||||
Darwin )
|
||||
osx_host_version=$(env sw_vers -productVersion)
|
||||
check_version "${osx_host_version}" "${OSX_VERSION}"
|
||||
[[ $? -ge 2 ]] && die "Minimum OSX version supported is ${OSX_VERSION}"
|
||||
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 "Exiting.. unsupported operating system found"
|
||||
exit 1;
|
||||
*)
|
||||
echo "ERROR"
|
||||
echo "OS '${KNAME}' is not supported."
|
||||
echo "Supported OS: [Linux, FreeBSD, Darwin]"
|
||||
exit 1
|
||||
esac
|
||||
}
|
||||
|
||||
is_supported_arch() {
|
||||
local supported
|
||||
case ${UNAME##* } in
|
||||
"x86_64")
|
||||
supported=1
|
||||
;;
|
||||
"arm"*)
|
||||
supported=1
|
||||
assert_is_supported_arch() {
|
||||
case "${ARCH}" in
|
||||
x86_64 | amd64 | aarch64 | arm* )
|
||||
return
|
||||
;;
|
||||
*)
|
||||
supported=0
|
||||
;;
|
||||
echo "ERROR"
|
||||
echo "Arch '${ARCH}' not supported."
|
||||
echo "Supported Arch: [x86_64, amd64, aarch64, arm*]"
|
||||
exit 1
|
||||
esac
|
||||
if [ $supported -eq 0 ]; then
|
||||
echo "Invalid arch: ${UNAME} not supported, please use x86_64/amd64"
|
||||
exit 1;
|
||||
fi
|
||||
}
|
||||
|
||||
check_deps() {
|
||||
check_version "$(env go version 2>/dev/null | sed 's/^.* go\([0-9.]*\).*$/\1/')" "${GO_VERSION}"
|
||||
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})"
|
||||
fi
|
||||
@@ -184,10 +196,10 @@ check_deps() {
|
||||
|
||||
main() {
|
||||
echo -n "Check for supported arch.. "
|
||||
is_supported_arch
|
||||
assert_is_supported_arch
|
||||
|
||||
echo -n "Check for supported os.. "
|
||||
is_supported_os
|
||||
assert_is_supported_os
|
||||
|
||||
echo -n "Checking if proper environment variables are set.. "
|
||||
check_golang_env
|
||||
@@ -209,7 +221,7 @@ main() {
|
||||
echo "Please install them "
|
||||
echo "${MISSING}"
|
||||
echo
|
||||
echo "Follow https://github.com/minio/mc/blob/master/INSTALLGO.md for further instructions"
|
||||
echo "Follow ${DOC_GO_INSTALL_URL} for further instructions"
|
||||
exit 1
|
||||
fi
|
||||
echo "Done"
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
#!/usr/bin/env bash
|
||||
#
|
||||
# Minio Cloud Storage, (C) 2015, 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.
|
||||
#
|
||||
|
||||
_init() {
|
||||
|
||||
shopt -s extglob
|
||||
|
||||
# Fetch real paths instead of symlinks before comparing them
|
||||
PWD=$(env pwd -P)
|
||||
GOPATH=$(cd "$(go env GOPATH)" ; env pwd -P)
|
||||
}
|
||||
|
||||
main() {
|
||||
echo "Checking if project is at ${GOPATH}"
|
||||
for mc in $(echo ${GOPATH} | tr ':' ' '); do
|
||||
if [ ! -d ${mc}/src/github.com/minio/mc ]; then
|
||||
echo "Project not found in ${mc}, please follow instructions provided at https://github.com/minio/mc/blob/master/CONTRIBUTING.md#setup-your-mc-github-repository" \
|
||||
&& exit 1
|
||||
fi
|
||||
if [ "x${mc}/src/github.com/minio/mc" != "x${PWD}" ]; then
|
||||
echo "Build outside of ${mc}, two source checkouts found. Exiting." && exit 1
|
||||
fi
|
||||
done
|
||||
}
|
||||
|
||||
_init && main
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// +build ignore
|
||||
|
||||
/*
|
||||
* Mc Client (C) 2014, 2015 Mc, Inc.
|
||||
* Mc Client (C) 2014, 2015, 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.
|
||||
@@ -28,16 +28,16 @@ import (
|
||||
|
||||
func genLDFlags(version string) string {
|
||||
var ldflagsStr string
|
||||
ldflagsStr = "-X main.mcVersion=" + version + " "
|
||||
ldflagsStr = ldflagsStr + "-X main.mcReleaseTag=" + releaseTag(version) + " "
|
||||
ldflagsStr = ldflagsStr + "-X main.mcCommitID=" + commitID() + " "
|
||||
ldflagsStr = ldflagsStr + "-X main.mcShortCommitID=" + commitID()[:12]
|
||||
ldflagsStr = "-X github.com/minio/mc/cmd.Version=" + version + " "
|
||||
ldflagsStr = ldflagsStr + "-X github.com/minio/mc/cmd.ReleaseTag=" + releaseTag(version) + " "
|
||||
ldflagsStr = ldflagsStr + "-X github.com/minio/mc/cmd.CommitID=" + commitID() + " "
|
||||
ldflagsStr = ldflagsStr + "-X github.com/minio/mc/cmd.ShortCommitID=" + commitID()[:12]
|
||||
return ldflagsStr
|
||||
}
|
||||
|
||||
// genReleaseTag prints release tag to the console for easy git tagging.
|
||||
func releaseTag(version string) string {
|
||||
relPrefix := "UNOFFICIAL"
|
||||
relPrefix := "DEVELOPMENT"
|
||||
if prefix := os.Getenv("MC_RELEASE"); prefix != "" {
|
||||
relPrefix = prefix
|
||||
}
|
||||
|
||||
Executable
+12
@@ -0,0 +1,12 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
set -e
|
||||
echo "" > coverage.txt
|
||||
|
||||
for d in $(go list ./... | grep -v vendor); do
|
||||
go test -coverprofile=profile.out -covermode=atomic $d
|
||||
if [ -f profile.out ]; then
|
||||
cat profile.out >> coverage.txt
|
||||
rm profile.out
|
||||
fi
|
||||
done
|
||||
@@ -0,0 +1,37 @@
|
||||
/*
|
||||
* 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
|
||||
|
||||
// isValidAccessPERM - is provided access perm string supported.
|
||||
func (b accessPerms) isValidAccessPERM() bool {
|
||||
switch b {
|
||||
case accessNone, accessDownload, accessUpload, accessPublic:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// accessPerms - access level.
|
||||
type accessPerms string
|
||||
|
||||
// different types of Access perm's currently supported by policy command.
|
||||
const (
|
||||
accessNone = accessPerms("none")
|
||||
accessDownload = accessPerms("download")
|
||||
accessUpload = accessPerms("upload")
|
||||
accessPublic = accessPerms("public")
|
||||
)
|
||||
@@ -14,7 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"sync"
|
||||
@@ -0,0 +1,213 @@
|
||||
/*
|
||||
* Minio Client (C) 2017 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio/pkg/madmin"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
var (
|
||||
adminHealListFlags = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "recursive, r",
|
||||
Usage: "List recursively.",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
var adminHealListCmd = cli.Command{
|
||||
Name: "list",
|
||||
Usage: "Get the list of buckets or objects that need to be healed.",
|
||||
Before: setGlobalsFromContext,
|
||||
Action: mainAdminHealList,
|
||||
Flags: append(adminHealListFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
mc admin heal {{.Name}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
mc admin heal {{.Name}} ALIAS/BUCKET/PREFIX
|
||||
|
||||
FLAGS:
|
||||
{{range .Flags}}{{.}}
|
||||
{{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/
|
||||
2. Recursively list objects than need to be healed.
|
||||
$ mc admin heal {{.Name}} --recursive play/
|
||||
|
||||
`,
|
||||
}
|
||||
|
||||
// healListMessage container to hold heal information.
|
||||
type healListMessage struct {
|
||||
Status string `json:"status"`
|
||||
Bucket string `json:"bucket"`
|
||||
Object madmin.ObjectInfo `json:"object"`
|
||||
}
|
||||
|
||||
// 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 {
|
||||
case madmin.CanHeal:
|
||||
msg += "can be healed"
|
||||
case madmin.Corrupted:
|
||||
msg += "cannot be healed"
|
||||
case madmin.QuorumUnavailable:
|
||||
msg += "quorum not available for healing"
|
||||
}
|
||||
msg += ".\n"
|
||||
return console.Colorize("Heal", msg)
|
||||
}
|
||||
|
||||
// JSON jsonified service status Message message.
|
||||
func (u healListMessage) JSON() string {
|
||||
u.Status = "success"
|
||||
statusJSONBytes, e := json.Marshal(u)
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(statusJSONBytes)
|
||||
}
|
||||
|
||||
// healBucketListMessage container to hold heal information.
|
||||
type healBucketListMessage struct {
|
||||
Status string `json:"status"`
|
||||
Bucket madmin.BucketInfo `json:"bucket"`
|
||||
}
|
||||
|
||||
// String colorized service status message.
|
||||
func (u healBucketListMessage) String() string {
|
||||
msg := fmt.Sprintf("Bucket: `%s`, ", u.Bucket.Name)
|
||||
switch u.Bucket.HealBucketInfo.Status {
|
||||
case madmin.CanHeal:
|
||||
msg += "can be healed"
|
||||
case madmin.Corrupted:
|
||||
msg += "cannot be healed"
|
||||
case madmin.QuorumUnavailable:
|
||||
msg += "quorum not available for healing"
|
||||
}
|
||||
msg += ".\n"
|
||||
return console.Colorize("Heal", msg)
|
||||
}
|
||||
|
||||
// JSON jsonified service status Message message.
|
||||
func (u healBucketListMessage) JSON() string {
|
||||
u.Status = "success"
|
||||
statusJSONBytes, e := json.Marshal(u)
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(statusJSONBytes)
|
||||
}
|
||||
|
||||
// checkAdminHealListSyntax - validate all the passed arguments
|
||||
func checkAdminHealListSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) == 0 || len(ctx.Args()) > 2 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "list", 1) // last argument is exit code
|
||||
}
|
||||
}
|
||||
|
||||
func mainAdminHealList(ctx *cli.Context) error {
|
||||
|
||||
// Check for heal list syntax
|
||||
checkAdminHealListSyntax(ctx)
|
||||
// Set console theme for heal command
|
||||
console.SetColor("Heal", color.New(color.FgGreen, color.Bold))
|
||||
|
||||
// Get the alias parameter from cli
|
||||
args := ctx.Args()
|
||||
aliasedURL := args.Get(0)
|
||||
isRecursive := ctx.Bool("recursive")
|
||||
|
||||
// Create a new Minio Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
if err != nil {
|
||||
return err.ToGoError()
|
||||
}
|
||||
|
||||
// Transform windows backslash to the regular slash in the aliased url
|
||||
aliasedURL = filepath.ToSlash(aliasedURL)
|
||||
|
||||
// Compute bucket and object from aliased url
|
||||
splits := splitStr(aliasedURL, "/", 3)
|
||||
bucket, object := splits[1], splits[2]
|
||||
|
||||
// If bucket is not specified, list buckets that need to be healed
|
||||
if bucket == "" {
|
||||
bucketsToHeal, e := client.ListBucketsHeal()
|
||||
fatalIf(probe.NewError(e), "Cannot list buckets that need healing.")
|
||||
// Iterate over buckets that need healing and print them
|
||||
for _, bucketHeal := range bucketsToHeal {
|
||||
printMsg(healBucketListMessage{Bucket: bucketHeal})
|
||||
}
|
||||
}
|
||||
|
||||
// When bucket is not specified and recursive flag is not activated,
|
||||
// it means we will not scan inside buckets
|
||||
if bucket == "" && !isRecursive {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Now, it is time to examine for objects that need to be healed
|
||||
var buckets []string
|
||||
if bucket == "" {
|
||||
// Bucket is not specified, so we target all buckets so we need to list them.
|
||||
s3Client, err := newClient(aliasedURL)
|
||||
if err != nil {
|
||||
fatalIf(err, "Cannot resolve the provided path.")
|
||||
}
|
||||
recursive := false
|
||||
incomplete := false
|
||||
listCh := s3Client.List(recursive, incomplete, DirFirst)
|
||||
for content := range listCh {
|
||||
// Trim the leading slash and add to the list of buckets
|
||||
buckets = append(buckets,
|
||||
strings.TrimPrefix(content.URL.Path, string(content.URL.Separator)))
|
||||
}
|
||||
} else {
|
||||
// Bucket is passed in argument, so we will only search for objects in the specified bucket
|
||||
buckets = append(buckets, bucket)
|
||||
}
|
||||
|
||||
// Iterate over all computed buckets
|
||||
for _, currBucket := range buckets {
|
||||
// Search for objects that need to be healed in the current bucket
|
||||
doneCh := make(chan struct{})
|
||||
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
|
||||
}
|
||||
printMsg(healListMessage{Bucket: currBucket, Object: obj})
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
/*
|
||||
* 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"
|
||||
"path/filepath"
|
||||
|
||||
"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 (
|
||||
adminHealFlags = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "recursive, r",
|
||||
Usage: "List recursively.",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "fake, k",
|
||||
Usage: "Issue a fake heal operation.",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
var adminHealCmd = cli.Command{
|
||||
Name: "heal",
|
||||
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/
|
||||
|
||||
`,
|
||||
}
|
||||
|
||||
// healObjectMessage container to hold repair information.
|
||||
type healObjectMessage struct {
|
||||
Status string `json:"status"`
|
||||
Bucket string `json:"bucket"`
|
||||
Object madmin.ObjectInfo `json:"object"`
|
||||
}
|
||||
|
||||
// String colorized service status message.
|
||||
func (u healObjectMessage) String() string {
|
||||
msg := fmt.Sprintf("Object %s/%s is healed.", u.Bucket, u.Object.Key)
|
||||
return console.Colorize("Heal", msg)
|
||||
}
|
||||
|
||||
// JSON jsonified service status Message message.
|
||||
func (u healObjectMessage) JSON() string {
|
||||
u.Status = "success"
|
||||
statusJSONBytes, e := json.Marshal(u)
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(statusJSONBytes)
|
||||
}
|
||||
|
||||
// checkAdminHealSyntax - validate all the passed arguments
|
||||
func checkAdminHealSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) != 1 {
|
||||
cli.ShowSubcommandHelp(ctx)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
// mainAdminHeal - the entry function of heal command
|
||||
func mainAdminHeal(ctx *cli.Context) error {
|
||||
|
||||
// Check for command syntax
|
||||
checkAdminHealSyntax(ctx)
|
||||
|
||||
// Get the alias parameter from cli
|
||||
args := ctx.Args()
|
||||
aliasedURL := args.Get(0)
|
||||
|
||||
isRecursive := ctx.Bool("recursive")
|
||||
isFake := ctx.Bool("fake")
|
||||
|
||||
console.SetColor("Heal", color.New(color.FgGreen, color.Bold))
|
||||
|
||||
// Create a new Minio Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
if err != nil {
|
||||
return err.ToGoError()
|
||||
}
|
||||
|
||||
// Compute bucket and object from the aliased URL
|
||||
aliasedURL = filepath.ToSlash(aliasedURL)
|
||||
splits := splitStr(aliasedURL, "/", 3)
|
||||
bucket, object := splits[1], splits[2]
|
||||
|
||||
var e 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.")
|
||||
return nil
|
||||
}
|
||||
|
||||
// Heal the specified bucket
|
||||
e = client.HealBucket(bucket, isFake)
|
||||
fatalIf(probe.NewError(e), "Cannot repair 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.")
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
/*
|
||||
* 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"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/minio/pkg/madmin"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
var (
|
||||
adminLockClearFlags = []cli.Flag{
|
||||
cli.StringFlag{
|
||||
Name: "duration, d",
|
||||
Usage: "Only show locks that are hold for longer than NN[h|m|s].",
|
||||
Value: "0s",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
var adminLockClearCmd = cli.Command{
|
||||
Name: "clear",
|
||||
Usage: "Clear locks hold in a given Minio server",
|
||||
Before: setGlobalsFromContext,
|
||||
Action: mainAdminLockClear,
|
||||
Flags: append(adminLockClearFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
mc admin lock {{.Name}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
mc admin lock {{.Name}} ALIAS/BUCKET/PREFIX
|
||||
|
||||
FLAGS:
|
||||
{{range .Flags}}{{.}}
|
||||
{{end}}
|
||||
|
||||
EXAMPLES:
|
||||
1. Clear all locks hold by 'testbucket' in a Minio server represented by its alias 'play'.
|
||||
$ mc admin lock {{.Name}} play/testbucket
|
||||
|
||||
2. Clear all 'testbucket' locks that are older than 15 minutes.
|
||||
$ mc admin lock {{.Name}} --duration 15m play/testbucket/
|
||||
|
||||
3. Clear all locks hold by all objects under 'dir' prefix
|
||||
$ mc admin lock {{.Name}} play/testbucket/dir/
|
||||
|
||||
`,
|
||||
}
|
||||
|
||||
// lockClearMessage container to hold locks information.
|
||||
type lockClearMessage struct {
|
||||
Status string `json:"status"`
|
||||
madmin.VolumeLockInfo
|
||||
}
|
||||
|
||||
// String colorized service status message.
|
||||
func (u lockClearMessage) String() string {
|
||||
msg := fmt.Sprintf("%s/%s (LocksOnObject: %d, locksAcquiredOnObject: %d, totalBlockLocks:%d): ",
|
||||
u.Bucket,
|
||||
u.Object,
|
||||
u.LocksOnObject,
|
||||
u.LocksAcquiredOnObject,
|
||||
u.TotalBlockedLocks)
|
||||
for _, detail := range u.LockDetailsOnObject {
|
||||
msg += fmt.Sprintf(" %+v", detail)
|
||||
}
|
||||
msg += "\n"
|
||||
return msg
|
||||
}
|
||||
|
||||
// JSON jsonified service status Message message.
|
||||
func (u lockClearMessage) JSON() string {
|
||||
u.Status = "success"
|
||||
statusJSONBytes, e := json.Marshal(u)
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(statusJSONBytes)
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
}
|
||||
|
||||
func mainAdminLockClear(ctx *cli.Context) error {
|
||||
|
||||
checkAdminLockClearSyntax(ctx)
|
||||
|
||||
// Get the alias parameter from cli
|
||||
args := ctx.Args()
|
||||
aliasedURL := args.Get(0)
|
||||
|
||||
// Parse duration flag
|
||||
duration, e := time.ParseDuration(ctx.String("duration"))
|
||||
fatalIf(probe.NewError(e), "Unable to parse the passed duration flag.")
|
||||
|
||||
// Create a new Minio Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
fatalIf(err, "Cannot get a configured admin connection.")
|
||||
|
||||
aliasedURL = filepath.ToSlash(aliasedURL)
|
||||
|
||||
splits := splitStr(aliasedURL, "/", 3)
|
||||
|
||||
// Clear locks related to a specified pair of bucket and prefix
|
||||
locksInfo, e := client.ClearLocks(splits[1], splits[2], duration)
|
||||
fatalIf(probe.NewError(e), "Cannot clear the specified locks.")
|
||||
|
||||
for _, l := range locksInfo {
|
||||
printMsg(lockClearMessage{VolumeLockInfo: l})
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
/*
|
||||
* 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"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/minio/pkg/madmin"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
var (
|
||||
adminLockListFlags = []cli.Flag{
|
||||
cli.StringFlag{
|
||||
Name: "duration, d",
|
||||
Usage: "Only show locks that are hold for longer than NN[h|m|s].",
|
||||
Value: "24h",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
var adminLockListCmd = cli.Command{
|
||||
Name: "list",
|
||||
Usage: "Get the list of locks hold in a given Minio server",
|
||||
Action: mainAdminLockList,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(adminLockListFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
mc admin lock {{.Name}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
mc admin lock {{.Name}} ALIAS/BUCKET/PREFIX
|
||||
|
||||
FLAGS:
|
||||
{{range .Flags}}{{.}}
|
||||
{{end}}
|
||||
|
||||
EXAMPLES:
|
||||
1. List hold locks related to testbucket in a Minio server represented by its alias 'play'.
|
||||
$ mc admin lock {{.Name}} play/testbucket/
|
||||
|
||||
2. List locks that are hold for more than 15 minutes.
|
||||
$ mc admin lock {{.Name}} --duration 15m play/testbucket/
|
||||
|
||||
3. List locks hold by all objects under dir prefix
|
||||
$ mc admin lock {{.Name}} play/testbucket/dir/
|
||||
|
||||
`,
|
||||
}
|
||||
|
||||
// lockListMessage container to hold locks information.
|
||||
type lockListMessage struct {
|
||||
Status string `json:"status"`
|
||||
madmin.VolumeLockInfo
|
||||
}
|
||||
|
||||
// String colorized service status message.
|
||||
func (u lockListMessage) String() string {
|
||||
msg := fmt.Sprintf("%s/%s (LocksOnObject: %d, locksAcquiredOnObject: %d, totalBlockLocks:%d): ",
|
||||
u.Bucket,
|
||||
u.Object,
|
||||
u.LocksOnObject,
|
||||
u.LocksAcquiredOnObject,
|
||||
u.TotalBlockedLocks)
|
||||
for _, detail := range u.LockDetailsOnObject {
|
||||
msg += fmt.Sprintf(" %+v", detail)
|
||||
}
|
||||
msg += "\n"
|
||||
return msg
|
||||
}
|
||||
|
||||
// JSON jsonified service status Message message.
|
||||
func (u lockListMessage) JSON() string {
|
||||
u.Status = "success"
|
||||
statusJSONBytes, e := json.Marshal(u)
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(statusJSONBytes)
|
||||
}
|
||||
|
||||
// checkAdminLockListSyntax - validate all the passed arguments
|
||||
func checkAdminLockListSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) == 0 || len(ctx.Args()) > 2 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "list", 1) // last argument is exit code
|
||||
}
|
||||
}
|
||||
|
||||
func mainAdminLockList(ctx *cli.Context) error {
|
||||
|
||||
checkAdminLockListSyntax(ctx)
|
||||
|
||||
// Get the alias parameter from cli
|
||||
args := ctx.Args()
|
||||
aliasedURL := args.Get(0)
|
||||
|
||||
// Parse duration flag
|
||||
duration, e := time.ParseDuration(ctx.String("duration"))
|
||||
fatalIf(probe.NewError(e), "Unable to parse the passed duration flag.")
|
||||
|
||||
// Create a new Minio Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
fatalIf(err, "Cannot get a configured admin connection.")
|
||||
|
||||
aliasedURL = filepath.ToSlash(aliasedURL)
|
||||
|
||||
splits := splitStr(aliasedURL, "/", 3)
|
||||
|
||||
// Fetch the lock info related to a specified pair of bucket and prefix
|
||||
locksInfo, e := client.ListLocks(splits[1], splits[2], duration)
|
||||
fatalIf(probe.NewError(e), "Cannot get lock status.")
|
||||
|
||||
for _, l := range locksInfo {
|
||||
printMsg(lockListMessage{VolumeLockInfo: l})
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
/*
|
||||
* 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 "github.com/minio/cli"
|
||||
|
||||
var (
|
||||
adminLockFlags = []cli.Flag{}
|
||||
)
|
||||
|
||||
var adminLockCmd = cli.Command{
|
||||
Name: "lock",
|
||||
Usage: "Control locks in servers.",
|
||||
Action: mainAdminLock,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(adminLockFlags, globalFlags...),
|
||||
Subcommands: []cli.Command{
|
||||
adminLockListCmd,
|
||||
adminLockClearCmd,
|
||||
},
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.Name}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.Name}} [FLAGS] COMMAND
|
||||
|
||||
FLAGS:
|
||||
{{range .Flags}}{{.}}
|
||||
{{end}}
|
||||
COMMANDS:
|
||||
{{range .Commands}}{{join .Names ", "}}{{ "\t" }}{{.Usage}}
|
||||
{{end}}
|
||||
`,
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
|
||||
return nil
|
||||
// Sub-commands like "list", "unlock" have their own main.
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
/*
|
||||
* 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 "github.com/minio/cli"
|
||||
|
||||
var (
|
||||
adminFlags = []cli.Flag{}
|
||||
)
|
||||
|
||||
var adminCmd = cli.Command{
|
||||
Name: "admin",
|
||||
Usage: "Manage Minio servers.",
|
||||
Action: mainAdmin,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(adminFlags, globalFlags...),
|
||||
Subcommands: []cli.Command{
|
||||
adminServiceCmd,
|
||||
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)
|
||||
}
|
||||
|
||||
return nil
|
||||
// Sub-commands like "service", "heal", "lock" have their own main.
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
/*
|
||||
* 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 (
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
var (
|
||||
adminServiceCredsFlags = []cli.Flag{}
|
||||
)
|
||||
|
||||
var adminServiceCredsCmd = cli.Command{
|
||||
Name: "creds",
|
||||
Usage: "Change credentials of a minio server or cluster",
|
||||
Action: mainAdminServiceCreds,
|
||||
Flags: append(adminServiceCredsFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
mc admin service {{.Name}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
mc admin service {{.Name}} ALIAS ACCESS_KEY SECRET_KEY
|
||||
|
||||
FLAGS:
|
||||
{{range .Flags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Set new credentials of a Minio server represented by its alias 'play'.
|
||||
$ mc admin service {{.Name}} play/ minio minio123
|
||||
`,
|
||||
}
|
||||
|
||||
// checkAdminServiceCredsSyntax - validate all the passed arguments
|
||||
func checkAdminServiceCredsSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) != 3 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "creds", 1) // last argument is exit code
|
||||
}
|
||||
}
|
||||
|
||||
func mainAdminServiceCreds(ctx *cli.Context) error {
|
||||
|
||||
setGlobalsFromContext(ctx)
|
||||
|
||||
checkAdminServiceCredsSyntax(ctx)
|
||||
|
||||
// Get the alias parameter from cli
|
||||
args := ctx.Args()
|
||||
aliasedURL := args.Get(0)
|
||||
accessKey := args.Get(1)
|
||||
secretKey := 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)
|
||||
fatalIf(probe.NewError(e), "Unable to set new credentials to '"+aliasedURL+"'")
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
/*
|
||||
* 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"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
var adminServiceRestartCmd = cli.Command{
|
||||
Name: "restart",
|
||||
Usage: "Restart a minio server",
|
||||
Action: mainAdminServiceRestart,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
mc admin service {{.Name}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
mc admin service {{.Name}} ALIAS
|
||||
|
||||
FLAGS:
|
||||
{{range .Flags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Restart a Minio server represented by its alias 'play'.
|
||||
$ mc admin service {{.Name}} play/
|
||||
`,
|
||||
}
|
||||
|
||||
// serviceRestartMessage is container for make bucket success and failure messages.
|
||||
type serviceRestartMessage struct {
|
||||
Status string `json:"status"`
|
||||
ServerURL string `json:"serverURL"`
|
||||
}
|
||||
|
||||
// String colorized make bucket message.
|
||||
func (s serviceRestartMessage) String() string {
|
||||
return console.Colorize("ServiceRestart", "Server restarted ‘"+s.ServerURL+"’ successfully.")
|
||||
}
|
||||
|
||||
// JSON jsonified make bucket message.
|
||||
func (s serviceRestartMessage) JSON() string {
|
||||
serviceRestartJSONBytes, e := json.Marshal(s)
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(serviceRestartJSONBytes)
|
||||
}
|
||||
|
||||
// checkAdminServiceRestartSyntax - validate all the passed arguments
|
||||
func checkAdminServiceRestartSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) == 0 || len(ctx.Args()) > 2 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "restart", 1) // last argument is exit code
|
||||
}
|
||||
}
|
||||
|
||||
func mainAdminServiceRestart(ctx *cli.Context) error {
|
||||
|
||||
// Validate serivce restart syntax.
|
||||
checkAdminServiceRestartSyntax(ctx)
|
||||
|
||||
// Set color.
|
||||
console.SetColor("ServiceRestart", color.New(color.FgGreen, color.Bold))
|
||||
|
||||
// Get the alias parameter from cli
|
||||
args := ctx.Args()
|
||||
aliasedURL := args.Get(0)
|
||||
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
fatalIf(err, "Cannot get a configured admin connection.")
|
||||
|
||||
// Restart the specified Minio server
|
||||
fatalIf(probe.NewError(client.ServiceRestart()), "Cannot restart server.")
|
||||
|
||||
// Success..
|
||||
printMsg(serviceRestartMessage{Status: "success", ServerURL: aliasedURL})
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
/*
|
||||
* 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 (
|
||||
adminServiceStatusFlags = []cli.Flag{}
|
||||
)
|
||||
|
||||
var adminServiceStatusCmd = cli.Command{
|
||||
Name: "status",
|
||||
Usage: "Get the status of a Minio server",
|
||||
Action: mainAdminServiceStatus,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(adminServiceStatusFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
mc admin service {{.Name}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
mc admin service {{.Name}} ALIAS
|
||||
|
||||
FLAGS:
|
||||
{{range .Flags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Get storage information of a Minio server represented by its alias 'play'.
|
||||
$ mc admin service {{.Name}} 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"`
|
||||
}
|
||||
|
||||
// String colorized service status message.
|
||||
func (u serviceStatusMessage) String() (msg string) {
|
||||
defer func() {
|
||||
msg = console.Colorize("ServiceStatus", msg)
|
||||
}()
|
||||
// When service is offline
|
||||
if !u.Service {
|
||||
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)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// JSON jsonified service status Message message.
|
||||
func (u serviceStatusMessage) JSON() string {
|
||||
u.Status = "success"
|
||||
statusJSONBytes, e := json.Marshal(u)
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(statusJSONBytes)
|
||||
}
|
||||
|
||||
// checkAdminServiceStatusSyntax - validate all the passed arguments
|
||||
func checkAdminServiceStatusSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) == 0 || len(ctx.Args()) > 2 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "status", 1) // last argument is exit code
|
||||
}
|
||||
}
|
||||
|
||||
func mainAdminServiceStatus(ctx *cli.Context) error {
|
||||
|
||||
// Validate serivce status syntax.
|
||||
checkAdminServiceStatusSyntax(ctx)
|
||||
|
||||
console.SetColor("ServiceStatus", 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 storage info of the specified Minio server
|
||||
st, e := client.ServiceStatus()
|
||||
|
||||
// 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(serviceStatusMessage{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 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,
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
/*
|
||||
* 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 "github.com/minio/cli"
|
||||
|
||||
var adminServiceCmd = cli.Command{
|
||||
Name: "service",
|
||||
Usage: "Control servers.",
|
||||
Action: mainAdminService,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
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)
|
||||
}
|
||||
|
||||
return nil
|
||||
// Sub-commands like "status", "stop", "restart" have their own main.
|
||||
}
|
||||
@@ -14,7 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
@@ -97,7 +97,7 @@ func isValidBucket(bucket string) bool {
|
||||
if bucket[0] == '.' || bucket[len(bucket)-1] == '.' {
|
||||
return false
|
||||
}
|
||||
if match, _ := regexp.MatchString("\\.\\.", bucket); match == true {
|
||||
if match, _ := regexp.MatchString("\\.\\.", bucket); match {
|
||||
return false
|
||||
}
|
||||
// We don't support buckets with '.' in them
|
||||
@@ -14,15 +14,15 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
package cmd
|
||||
|
||||
var (
|
||||
// mcVersion - version time.RFC3339.
|
||||
mcVersion = "UNOFFICIAL.GOGET"
|
||||
// mcReleaseTag - release tag in TAG.%Y-%m-%dT%H-%M-%SZ.
|
||||
mcReleaseTag = "UNOFFICIAL.GOGET"
|
||||
// mcCommitID - latest commit id.
|
||||
mcCommitID = "UNOFFICIAL.GOGET"
|
||||
// mcShortCommitID - first 12 characters from mcCommitID.
|
||||
mcShortCommitID = mcCommitID[:12]
|
||||
// Version - version time.RFC3339.
|
||||
Version = "DEVELOPMENT.GOGET"
|
||||
// ReleaseTag - release tag in TAG.%Y-%m-%dT%H-%M-%SZ.
|
||||
ReleaseTag = "DEVELOPMENT.GOGET"
|
||||
// CommitID - latest commit id.
|
||||
CommitID = "DEVELOPMENT.GOGET"
|
||||
// ShortCommitID - first 12 characters from CommitID.
|
||||
ShortCommitID = CommitID[:12]
|
||||
)
|
||||
@@ -14,7 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"errors"
|
||||
@@ -25,23 +25,19 @@ import (
|
||||
"syscall"
|
||||
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
var (
|
||||
catFlags = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "help, h",
|
||||
Usage: "Help of cat",
|
||||
},
|
||||
}
|
||||
catFlags = []cli.Flag{}
|
||||
)
|
||||
|
||||
// Display contents of a file.
|
||||
var catCmd = cli.Command{
|
||||
Name: "cat",
|
||||
Usage: "Display contents of a file.",
|
||||
Usage: "Display file and object contents.",
|
||||
Action: mainCat,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(catFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
mc {{.Name}} - {{.Usage}}
|
||||
@@ -81,24 +77,36 @@ func checkCatSyntax(ctx *cli.Context) {
|
||||
// catURL displays contents of a URL to stdout.
|
||||
func catURL(sourceURL string) *probe.Error {
|
||||
var reader io.Reader
|
||||
size := int64(-1)
|
||||
switch sourceURL {
|
||||
case "-":
|
||||
reader = os.Stdin
|
||||
default:
|
||||
// Ignore size, since os.Stat() would not return proper size all the
|
||||
// time for local filesystem for example /proc files.
|
||||
var err *probe.Error
|
||||
client, content, err := url2Stat(sourceURL)
|
||||
if err != nil {
|
||||
return err.Trace(sourceURL)
|
||||
}
|
||||
// Ignore size for filesystem objects since os.Stat() would not
|
||||
// return proper size all the time, for example with /proc files.
|
||||
if client.GetURL().Type == objectStorage {
|
||||
size = content.Size
|
||||
}
|
||||
if reader, err = getSourceStream(sourceURL); err != nil {
|
||||
return err.Trace(sourceURL)
|
||||
}
|
||||
}
|
||||
return catOut(reader).Trace(sourceURL)
|
||||
return catOut(reader, size).Trace(sourceURL)
|
||||
}
|
||||
|
||||
// catOut reads from reader stream and writes to stdout.
|
||||
func catOut(r io.Reader) *probe.Error {
|
||||
// catOut reads from reader stream and writes to stdout. Also check the length of the
|
||||
// read bytes against size parameter (if not -1) and return the appropriate error
|
||||
func catOut(r io.Reader, size int64) *probe.Error {
|
||||
var n int64
|
||||
var e error
|
||||
|
||||
// Read till EOF.
|
||||
if _, e := io.Copy(os.Stdout, r); e != nil {
|
||||
if n, e = io.Copy(os.Stdout, r); e != nil {
|
||||
switch e := e.(type) {
|
||||
case *os.PathError:
|
||||
if e.Err == syscall.EPIPE {
|
||||
@@ -110,13 +118,23 @@ func catOut(r io.Reader) *probe.Error {
|
||||
return probe.NewError(e)
|
||||
}
|
||||
}
|
||||
if size != -1 && n < size {
|
||||
return probe.NewError(UnexpectedEOF{
|
||||
TotalSize: size,
|
||||
TotalWritten: n,
|
||||
})
|
||||
}
|
||||
if size != -1 && n > size {
|
||||
return probe.NewError(UnexpectedEOF{
|
||||
TotalSize: size,
|
||||
TotalWritten: n,
|
||||
})
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// mainCat is the main entry point for cat command.
|
||||
func mainCat(ctx *cli.Context) {
|
||||
// Set global flags from context.
|
||||
setGlobalsFromContext(ctx)
|
||||
func mainCat(ctx *cli.Context) error {
|
||||
|
||||
// check 'cat' cli arguments.
|
||||
checkCatSyntax(ctx)
|
||||
@@ -129,8 +147,8 @@ func mainCat(ctx *cli.Context) {
|
||||
|
||||
// handle std input data.
|
||||
if stdinMode {
|
||||
fatalIf(catOut(os.Stdin).Trace(), "Unable to read from standard input.")
|
||||
return
|
||||
fatalIf(catOut(os.Stdin, -1).Trace(), "Unable to read from standard input.")
|
||||
return nil
|
||||
}
|
||||
|
||||
// if Args contain ‘-’, we need to preserve its order specially.
|
||||
@@ -149,4 +167,5 @@ func mainCat(ctx *cli.Context) {
|
||||
for _, url := range args {
|
||||
fatalIf(catURL(url).Trace(url), "Unable to read from ‘"+url+"’.")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
+144
@@ -0,0 +1,144 @@
|
||||
/*
|
||||
* 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 (
|
||||
"crypto/x509"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
// getCertsDir - return the full path of certs dir
|
||||
func getCertsDir() (string, *probe.Error) {
|
||||
p, err := getMcConfigDir()
|
||||
if err != nil {
|
||||
return "", err.Trace()
|
||||
}
|
||||
return filepath.Join(p, globalMCCertsDir), nil
|
||||
}
|
||||
|
||||
// mustGetCertsDir - return the full path of certs dir or empty string when an error occurs
|
||||
func mustGetCertsDir() string {
|
||||
p, err := getCertsDir()
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
// isCertsDirExists - verify if certs directory exists.
|
||||
func isCertsDirExists() bool {
|
||||
certsDir, err := getCertsDir()
|
||||
fatalIf(err.Trace(), "Unable to determine certs folder.")
|
||||
if _, e := os.Stat(certsDir); e != nil {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// createCertsDir - create minio client certs folder
|
||||
func createCertsDir() *probe.Error {
|
||||
p, err := getCertsDir()
|
||||
if err != nil {
|
||||
return err.Trace()
|
||||
}
|
||||
if e := os.MkdirAll(p, 0700); e != nil {
|
||||
return probe.NewError(e)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// getCAsDir - return the full path of CAs dir
|
||||
func getCAsDir() (string, *probe.Error) {
|
||||
p, err := getCertsDir()
|
||||
if err != nil {
|
||||
return "", err.Trace()
|
||||
}
|
||||
return filepath.Join(p, globalMCCAsDir), nil
|
||||
}
|
||||
|
||||
// mustGetCAsDir - return the full path of CAs dir or empty string when an error occurs
|
||||
func mustGetCAsDir() string {
|
||||
p, err := getCAsDir()
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
// isCAsDirExists - verify if CAs directory exists.
|
||||
func isCAsDirExists() bool {
|
||||
CAsDir, err := getCAsDir()
|
||||
fatalIf(err.Trace(), "Unable to determine CAs folder.")
|
||||
if _, e := os.Stat(CAsDir); e != nil {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// createCAsDir - create minio client CAs folder
|
||||
func createCAsDir() *probe.Error {
|
||||
p, err := getCAsDir()
|
||||
if err != nil {
|
||||
return err.Trace()
|
||||
}
|
||||
if e := os.MkdirAll(p, 0700); e != nil {
|
||||
return probe.NewError(e)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// mustGetCAFiles - get the list of the CA certificates stored in minio config dir
|
||||
func mustGetCAFiles() (caCerts []string) {
|
||||
CAsDir := mustGetCAsDir()
|
||||
caFiles, _ := ioutil.ReadDir(CAsDir)
|
||||
for _, cert := range caFiles {
|
||||
caCerts = append(caCerts, filepath.Join(CAsDir, cert.Name()))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// mustGetSystemCertPool - return system CAs or empty pool in case of error (or windows)
|
||||
func mustGetSystemCertPool() *x509.CertPool {
|
||||
pool, err := x509.SystemCertPool()
|
||||
if err != nil {
|
||||
return x509.NewCertPool()
|
||||
}
|
||||
return pool
|
||||
}
|
||||
|
||||
// loadRootCAs fetches CA files provided in minio config and adds them to globalRootCAs
|
||||
// Currently under Windows, there is no way to load system + user CAs at the same time
|
||||
func loadRootCAs() {
|
||||
caFiles := mustGetCAFiles()
|
||||
if len(caFiles) == 0 {
|
||||
return
|
||||
}
|
||||
// Get system cert pool, and empty cert pool under Windows because it is not supported
|
||||
globalRootCAs = mustGetSystemCertPool()
|
||||
// Load custom root CAs for client requests
|
||||
for _, caFile := range caFiles {
|
||||
caCert, err := ioutil.ReadFile(caFile)
|
||||
if err != nil {
|
||||
fatalIf(probe.NewError(err), "Unable to load a CA file")
|
||||
}
|
||||
globalRootCAs.AppendCertsFromPEM(caCert)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
/*
|
||||
* 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 (
|
||||
"crypto/tls"
|
||||
"hash/fnv"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/minio/mc/pkg/httptracer"
|
||||
"github.com/minio/minio/pkg/madmin"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
// newAdminFactory encloses New function with client cache.
|
||||
func newAdminFactory() func(config *Config) (*madmin.AdminClient, *probe.Error) {
|
||||
clientCache := make(map[uint32]*madmin.AdminClient)
|
||||
mutex := &sync.Mutex{}
|
||||
|
||||
// Return New function.
|
||||
return func(config *Config) (*madmin.AdminClient, *probe.Error) {
|
||||
// Creates a parsed URL.
|
||||
targetURL, e := url.Parse(config.HostURL)
|
||||
if e != nil {
|
||||
return nil, probe.NewError(e)
|
||||
}
|
||||
// By default enable HTTPs.
|
||||
useTLS := true
|
||||
if targetURL.Scheme == "http" {
|
||||
useTLS = false
|
||||
}
|
||||
|
||||
// Save if target supports virtual host style.
|
||||
hostName := targetURL.Host
|
||||
|
||||
// Generate a hash out of s3Conf.
|
||||
confHash := fnv.New32a()
|
||||
confHash.Write([]byte(hostName + config.AccessKey + config.SecretKey))
|
||||
confSum := confHash.Sum32()
|
||||
|
||||
// Lookup previous cache by hash.
|
||||
mutex.Lock()
|
||||
defer mutex.Unlock()
|
||||
var api *madmin.AdminClient
|
||||
var found bool
|
||||
if api, found = clientCache[confSum]; !found {
|
||||
// Not found. Instantiate a new minio
|
||||
var e error
|
||||
api, e = madmin.New(hostName, config.AccessKey, config.SecretKey, useTLS)
|
||||
if e != nil {
|
||||
return nil, probe.NewError(e)
|
||||
}
|
||||
|
||||
// Keep TLS config.
|
||||
tlsConfig := &tls.Config{RootCAs: globalRootCAs}
|
||||
if config.Insecure {
|
||||
tlsConfig.InsecureSkipVerify = true
|
||||
}
|
||||
|
||||
var transport http.RoundTripper = &http.Transport{
|
||||
Proxy: http.ProxyFromEnvironment,
|
||||
DialContext: (&net.Dialer{
|
||||
Timeout: 30 * time.Second,
|
||||
KeepAlive: 30 * time.Second,
|
||||
}).DialContext,
|
||||
MaxIdleConns: 100,
|
||||
IdleConnTimeout: 90 * time.Second,
|
||||
ResponseHeaderTimeout: 5 * time.Minute,
|
||||
TLSHandshakeTimeout: 10 * time.Second,
|
||||
ExpectContinueTimeout: 1 * time.Second,
|
||||
TLSClientConfig: tlsConfig,
|
||||
}
|
||||
|
||||
if config.Debug {
|
||||
transport = httptracer.GetNewTraceTransport(newTraceV4(), transport)
|
||||
}
|
||||
|
||||
// Set custom transport.
|
||||
api.SetCustomTransport(transport)
|
||||
|
||||
// Set app info.
|
||||
api.SetAppInfo(config.AppName, config.AppVersion)
|
||||
|
||||
// Cache the new minio client with hash of config as key.
|
||||
clientCache[confSum] = api
|
||||
}
|
||||
|
||||
// Store the new api object.
|
||||
return api, nil
|
||||
}
|
||||
}
|
||||
|
||||
// newAdminClientFromAlias gives a new admin client interface for matching
|
||||
// alias entry in the mc config file. If no matching host config entry
|
||||
// is found, fs client is returned.
|
||||
func newAdminClientFromAlias(alias string, urlStr string) (*madmin.AdminClient, *probe.Error) {
|
||||
s3Config, err := buildS3Config(alias, urlStr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s3Client, err := s3AdminNew(s3Config)
|
||||
if err != nil {
|
||||
return nil, err.Trace(alias, urlStr)
|
||||
}
|
||||
return s3Client, nil
|
||||
}
|
||||
|
||||
// newAdminClient gives a new client interface
|
||||
func newAdminClient(aliasedURL string) (*madmin.AdminClient, *probe.Error) {
|
||||
alias, urlStrFull, hostCfg, err := expandAlias(aliasedURL)
|
||||
if err != nil {
|
||||
return nil, err.Trace(aliasedURL)
|
||||
}
|
||||
// Verify if the aliasedURL is a real URL, fail in those cases
|
||||
// indicating the user to add alias.
|
||||
if hostCfg == nil && urlRgx.MatchString(aliasedURL) {
|
||||
return nil, errInvalidAliasedURL(aliasedURL).Trace(aliasedURL)
|
||||
}
|
||||
return newAdminClientFromAlias(alias, urlStrFull)
|
||||
}
|
||||
|
||||
// s3AdminNew returns an initialized minioAdmin structure. If debug is enabled,
|
||||
// it also enables an internal trace transport.
|
||||
var s3AdminNew = newAdminFactory()
|
||||
@@ -14,12 +14,9 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package client
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
)
|
||||
import "fmt"
|
||||
|
||||
/// Collection of standard errors
|
||||
|
||||
@@ -30,16 +27,7 @@ type APINotImplemented struct {
|
||||
}
|
||||
|
||||
func (e APINotImplemented) Error() string {
|
||||
return "‘" + e.API + "’ feature " + "is not implemented for ‘" + e.APIType + "’."
|
||||
}
|
||||
|
||||
// InvalidRange - invalid range requested
|
||||
type InvalidRange struct {
|
||||
Offset int64
|
||||
}
|
||||
|
||||
func (e InvalidRange) Error() string {
|
||||
return "Invalid range offset: ‘" + strconv.FormatInt(e.Offset, 10) + "’."
|
||||
return "‘" + e.API + "’ is not supported for ‘" + e.APIType + "’."
|
||||
}
|
||||
|
||||
// GenericBucketError - generic bucket operations error
|
||||
@@ -61,13 +49,6 @@ func (e BucketExists) Error() string {
|
||||
return "Bucket ‘" + e.Bucket + "’ exists."
|
||||
}
|
||||
|
||||
// InvalidBucketName - bucket name invalid (http://goo.gl/wJlzDz)
|
||||
type InvalidBucketName GenericBucketError
|
||||
|
||||
func (e InvalidBucketName) Error() string {
|
||||
return "Invalid bucketname [‘" + e.Bucket + "’], please read http://goo.gl/wJlzDz."
|
||||
}
|
||||
|
||||
// BucketNameEmpty - bucket name empty (http://goo.gl/wJlzDz)
|
||||
type BucketNameEmpty struct{}
|
||||
|
||||
@@ -75,10 +56,13 @@ func (e BucketNameEmpty) Error() string {
|
||||
return "Bucket name cannot be empty."
|
||||
}
|
||||
|
||||
// GenericObjectError - generic object operations error
|
||||
type GenericObjectError struct {
|
||||
// BucketInvalid - bucket name invalid.
|
||||
type BucketInvalid struct {
|
||||
Bucket string
|
||||
Object string
|
||||
}
|
||||
|
||||
func (e BucketInvalid) Error() string {
|
||||
return "Bucket name " + e.Bucket + " not valid."
|
||||
}
|
||||
|
||||
// ObjectAlreadyExists - typed return for MethodNotAllowed
|
||||
@@ -90,11 +74,22 @@ func (e ObjectAlreadyExists) Error() string {
|
||||
return "Object ‘" + e.Object + "’ already exists."
|
||||
}
|
||||
|
||||
// InvalidObjectName - object requested is invalid
|
||||
type InvalidObjectName GenericObjectError
|
||||
// ObjectAlreadyExistsAsDirectory - typed return for XMinioObjectExistsAsDirectory
|
||||
type ObjectAlreadyExistsAsDirectory struct {
|
||||
Object string
|
||||
}
|
||||
|
||||
func (e InvalidObjectName) Error() string {
|
||||
return "Object ‘" + e.Object + "’ at ‘" + e.Bucket + "’ is invalid."
|
||||
func (e ObjectAlreadyExistsAsDirectory) Error() string {
|
||||
return "Object ‘" + e.Object + "’ already exists as directory."
|
||||
}
|
||||
|
||||
// ObjectOnGlacier - object is of storage class glacier.
|
||||
type ObjectOnGlacier struct {
|
||||
Object string
|
||||
}
|
||||
|
||||
func (e ObjectOnGlacier) Error() string {
|
||||
return "Object ‘" + e.Object + "’ is on Glacier storage."
|
||||
}
|
||||
|
||||
// BucketNameTopLevel - generic error
|
||||
+1245
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,56 @@
|
||||
// +build linux
|
||||
|
||||
/*
|
||||
* Minio Client (C) 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this fs except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/rjeczalik/notify"
|
||||
)
|
||||
|
||||
var (
|
||||
// EventTypePut contains the notify events that will cause a put
|
||||
EventTypePut = []notify.Event{notify.InCloseWrite | notify.InMovedTo}
|
||||
// EventTypeDelete contains the notify events that will cause a delete
|
||||
EventTypeDelete = []notify.Event{notify.InDelete | notify.InDeleteSelf | notify.InMovedFrom}
|
||||
)
|
||||
|
||||
// IsPutEvent checks if the event returned is a put event
|
||||
func IsPutEvent(event notify.Event) bool {
|
||||
switch event {
|
||||
case notify.InCloseWrite:
|
||||
return true
|
||||
case notify.InMovedTo:
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
// IsDeleteEvent checks if the event returned is a delete event
|
||||
func IsDeleteEvent(event notify.Event) bool {
|
||||
switch event {
|
||||
case notify.InDelete:
|
||||
return true
|
||||
case notify.InDeleteSelf:
|
||||
return true
|
||||
case notify.InMovedFrom:
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
// +build !linux
|
||||
|
||||
/*
|
||||
* Minio Client (C) 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this fs except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import "github.com/rjeczalik/notify"
|
||||
|
||||
var (
|
||||
// EventTypePut contains the notify events that will cause a put
|
||||
EventTypePut = []notify.Event{notify.Create, notify.Write, notify.Rename}
|
||||
// EventTypeDelete contains the notify events that will cause a delete
|
||||
EventTypeDelete = []notify.Event{notify.Remove}
|
||||
)
|
||||
|
||||
// IsPutEvent checks if the event returned is a put event
|
||||
func IsPutEvent(event notify.Event) bool {
|
||||
switch event {
|
||||
case notify.Create:
|
||||
return true
|
||||
case notify.Rename:
|
||||
return true
|
||||
case notify.Write:
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
// IsDeleteEvent checks if the event returned is a delete event
|
||||
func IsDeleteEvent(event notify.Event) bool {
|
||||
switch event {
|
||||
case notify.Remove:
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
@@ -14,7 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package fs_test
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
@@ -22,53 +22,49 @@ import (
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"runtime"
|
||||
|
||||
"github.com/minio/mc/pkg/client"
|
||||
"github.com/minio/mc/pkg/client/fs"
|
||||
. "gopkg.in/check.v1"
|
||||
)
|
||||
|
||||
func Test(t *testing.T) { TestingT(t) }
|
||||
|
||||
type MySuite struct{}
|
||||
|
||||
var _ = Suite(&MySuite{})
|
||||
|
||||
// Test list files in a folder.
|
||||
func (s *MySuite) TestList(c *C) {
|
||||
func (s *TestSuite) TestList(c *C) {
|
||||
root, e := ioutil.TempDir(os.TempDir(), "fs-")
|
||||
c.Assert(e, IsNil)
|
||||
defer os.RemoveAll(root)
|
||||
|
||||
// Create multiple files.
|
||||
objectPath := filepath.Join(root, "object1")
|
||||
fsClient, err := fs.New(objectPath)
|
||||
fsClient, err := fsNew(objectPath)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
data := "hello"
|
||||
|
||||
reader := bytes.NewReader([]byte(data))
|
||||
var n int64
|
||||
n, err = fsClient.Put(reader, int64(len(data)), "application/octet-stream", nil)
|
||||
n, err = fsClient.Put(reader, int64(len(data)), map[string][]string{
|
||||
"Content-Type": {"application/octet-stream"},
|
||||
}, nil)
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(n, Equals, int64(len(data)))
|
||||
|
||||
objectPath = filepath.Join(root, "object2")
|
||||
fsClient, err = fs.New(objectPath)
|
||||
fsClient, err = fsNew(objectPath)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
reader = bytes.NewReader([]byte(data))
|
||||
n, err = fsClient.Put(reader, int64(len(data)), "application/octet-stream", nil)
|
||||
n, err = fsClient.Put(reader, int64(len(data)), map[string][]string{
|
||||
"Content-Type": {"application/octet-stream"},
|
||||
}, nil)
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(n, Equals, int64(len(data)))
|
||||
|
||||
fsClient, err = fs.New(root)
|
||||
fsClient, err = fsNew(root)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
// Verify previously create files and list them.
|
||||
var contents []*client.Content
|
||||
for content := range fsClient.List(false, false) {
|
||||
var contents []*clientContent
|
||||
for content := range fsClient.List(false, false, DirNone) {
|
||||
if content.Err != nil {
|
||||
err = content.Err
|
||||
break
|
||||
@@ -81,20 +77,22 @@ func (s *MySuite) TestList(c *C) {
|
||||
|
||||
// Create another file.
|
||||
objectPath = filepath.Join(root, "test1/newObject1")
|
||||
fsClient, err = fs.New(objectPath)
|
||||
fsClient, err = fsNew(objectPath)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
reader = bytes.NewReader([]byte(data))
|
||||
n, err = fsClient.Put(reader, int64(len(data)), "application/octet-stream", nil)
|
||||
n, err = fsClient.Put(reader, int64(len(data)), map[string][]string{
|
||||
"Content-Type": {"application/octet-stream"},
|
||||
}, nil)
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(n, Equals, int64(len(data)))
|
||||
|
||||
fsClient, err = fs.New(root)
|
||||
fsClient, err = fsNew(root)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
contents = nil
|
||||
// List non recursive to list only top level files.
|
||||
for content := range fsClient.List(false, false) {
|
||||
for content := range fsClient.List(false, false, DirNone) {
|
||||
if content.Err != nil {
|
||||
err = content.Err
|
||||
break
|
||||
@@ -105,12 +103,12 @@ func (s *MySuite) TestList(c *C) {
|
||||
c.Assert(len(contents), Equals, 1)
|
||||
c.Assert(contents[0].Type.IsDir(), Equals, true)
|
||||
|
||||
fsClient, err = fs.New(root)
|
||||
fsClient, err = fsNew(root)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
contents = nil
|
||||
// List recursively all files and verify.
|
||||
for content := range fsClient.List(true, false) {
|
||||
for content := range fsClient.List(true, false, DirNone) {
|
||||
if content.Err != nil {
|
||||
err = content.Err
|
||||
break
|
||||
@@ -119,7 +117,7 @@ func (s *MySuite) TestList(c *C) {
|
||||
}
|
||||
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(len(contents), Equals, 5)
|
||||
c.Assert(len(contents), Equals, 3)
|
||||
|
||||
var regularFiles int
|
||||
var regularDirs int
|
||||
@@ -134,94 +132,149 @@ func (s *MySuite) TestList(c *C) {
|
||||
continue
|
||||
}
|
||||
}
|
||||
c.Assert(regularDirs, Equals, 2)
|
||||
c.Assert(regularDirs, Equals, 0)
|
||||
c.Assert(regularFiles, Equals, 3)
|
||||
|
||||
// Create an ignored file and list to verify if its ignored.
|
||||
objectPath = filepath.Join(root, "test1/.DS_Store")
|
||||
fsClient, err = fsNew(objectPath)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
reader = bytes.NewReader([]byte(data))
|
||||
n, err = fsClient.Put(reader, int64(len(data)), map[string][]string{
|
||||
"Content-Type": {"application/octet-stream"},
|
||||
}, nil)
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(n, Equals, int64(len(data)))
|
||||
|
||||
fsClient, err = fsNew(root)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
contents = nil
|
||||
// List recursively all files and verify.
|
||||
for content := range fsClient.List(true, false, DirNone) {
|
||||
if content.Err != nil {
|
||||
err = content.Err
|
||||
break
|
||||
}
|
||||
contents = append(contents, content)
|
||||
}
|
||||
|
||||
c.Assert(err, IsNil)
|
||||
switch runtime.GOOS {
|
||||
case "darwin":
|
||||
c.Assert(len(contents), Equals, 3)
|
||||
default:
|
||||
c.Assert(len(contents), Equals, 4)
|
||||
}
|
||||
|
||||
regularFiles = 0
|
||||
// Test number of expected files.
|
||||
for _, content := range contents {
|
||||
if content.Type.IsRegular() {
|
||||
regularFiles++
|
||||
continue
|
||||
}
|
||||
}
|
||||
switch runtime.GOOS {
|
||||
case "darwin":
|
||||
c.Assert(regularFiles, Equals, 3)
|
||||
default:
|
||||
c.Assert(regularFiles, Equals, 4)
|
||||
}
|
||||
}
|
||||
|
||||
// Test put bucket aka 'mkdir()' operation.
|
||||
func (s *MySuite) TestPutBucket(c *C) {
|
||||
func (s *TestSuite) TestPutBucket(c *C) {
|
||||
root, e := ioutil.TempDir(os.TempDir(), "fs-")
|
||||
c.Assert(e, IsNil)
|
||||
defer os.RemoveAll(root)
|
||||
|
||||
bucketPath := filepath.Join(root, "bucket")
|
||||
fsClient, err := fs.New(bucketPath)
|
||||
fsClient, err := fsNew(bucketPath)
|
||||
c.Assert(err, IsNil)
|
||||
err = fsClient.MakeBucket("us-east-1")
|
||||
c.Assert(err, IsNil)
|
||||
}
|
||||
|
||||
// Test stat bucket aka 'stat()' operation.
|
||||
func (s *MySuite) TestStatBucket(c *C) {
|
||||
func (s *TestSuite) TestStatBucket(c *C) {
|
||||
root, e := ioutil.TempDir(os.TempDir(), "fs-")
|
||||
c.Assert(e, IsNil)
|
||||
defer os.RemoveAll(root)
|
||||
|
||||
bucketPath := filepath.Join(root, "bucket")
|
||||
|
||||
fsClient, err := fs.New(bucketPath)
|
||||
fsClient, err := fsNew(bucketPath)
|
||||
c.Assert(err, IsNil)
|
||||
err = fsClient.MakeBucket("us-east-1")
|
||||
c.Assert(err, IsNil)
|
||||
_, err = fsClient.Stat()
|
||||
_, err = fsClient.Stat(false)
|
||||
c.Assert(err, IsNil)
|
||||
}
|
||||
|
||||
// Test bucket acl fails for directories.
|
||||
func (s *MySuite) TestBucketACLFails(c *C) {
|
||||
func (s *TestSuite) TestBucketACLFails(c *C) {
|
||||
root, e := ioutil.TempDir(os.TempDir(), "fs-")
|
||||
c.Assert(e, IsNil)
|
||||
defer os.RemoveAll(root)
|
||||
|
||||
bucketPath := filepath.Join(root, "bucket")
|
||||
fsClient, err := fs.New(bucketPath)
|
||||
fsClient, err := fsNew(bucketPath)
|
||||
c.Assert(err, IsNil)
|
||||
err = fsClient.MakeBucket("us-east-1")
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
err = fsClient.SetBucketAccess("private")
|
||||
c.Assert(err, Not(IsNil))
|
||||
// On windows setting permissions is not supported.
|
||||
if runtime.GOOS != "windows" {
|
||||
err = fsClient.SetAccess("readonly")
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
_, err = fsClient.GetBucketAccess()
|
||||
c.Assert(err, Not(IsNil))
|
||||
_, err = fsClient.GetAccess()
|
||||
c.Assert(err, IsNil)
|
||||
}
|
||||
}
|
||||
|
||||
// Test creating a file.
|
||||
func (s *MySuite) TestPut(c *C) {
|
||||
func (s *TestSuite) TestPut(c *C) {
|
||||
root, e := ioutil.TempDir(os.TempDir(), "fs-")
|
||||
c.Assert(e, IsNil)
|
||||
defer os.RemoveAll(root)
|
||||
|
||||
objectPath := filepath.Join(root, "object")
|
||||
fsClient, err := fs.New(objectPath)
|
||||
fsClient, err := fsNew(objectPath)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
data := "hello"
|
||||
reader := bytes.NewReader([]byte(data))
|
||||
var n int64
|
||||
n, err = fsClient.Put(reader, int64(len(data)), "application/octet-stream", nil)
|
||||
n, err = fsClient.Put(reader, int64(len(data)), map[string][]string{
|
||||
"Content-Type": {"application/octet-stream"},
|
||||
}, nil)
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(n, Equals, int64(len(data)))
|
||||
}
|
||||
|
||||
// Test read a file.
|
||||
func (s *MySuite) TestGet(c *C) {
|
||||
func (s *TestSuite) TestGet(c *C) {
|
||||
root, e := ioutil.TempDir(os.TempDir(), "fs-")
|
||||
c.Assert(e, IsNil)
|
||||
defer os.RemoveAll(root)
|
||||
|
||||
objectPath := filepath.Join(root, "object")
|
||||
fsClient, err := fs.New(objectPath)
|
||||
fsClient, err := fsNew(objectPath)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
data := "hello"
|
||||
var reader io.Reader
|
||||
reader = bytes.NewReader([]byte(data))
|
||||
n, err := fsClient.Put(reader, int64(len(data)), "application/octet-stream", nil)
|
||||
n, err := fsClient.Put(reader, int64(len(data)), map[string][]string{
|
||||
"Content-Type": {"application/octet-stream"},
|
||||
}, nil)
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(n, Equals, int64(len(data)))
|
||||
|
||||
reader, err = fsClient.Get()
|
||||
reader, _, err = fsClient.Get()
|
||||
c.Assert(err, IsNil)
|
||||
var results bytes.Buffer
|
||||
_, e = io.Copy(&results, reader)
|
||||
@@ -231,23 +284,25 @@ func (s *MySuite) TestGet(c *C) {
|
||||
}
|
||||
|
||||
// Test get range in a file.
|
||||
func (s *MySuite) TestGetRange(c *C) {
|
||||
func (s *TestSuite) TestGetRange(c *C) {
|
||||
root, e := ioutil.TempDir(os.TempDir(), "fs-")
|
||||
c.Assert(e, IsNil)
|
||||
defer os.RemoveAll(root)
|
||||
|
||||
objectPath := filepath.Join(root, "object")
|
||||
fsClient, err := fs.New(objectPath)
|
||||
fsClient, err := fsNew(objectPath)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
data := "hello world"
|
||||
var reader io.Reader
|
||||
reader = bytes.NewReader([]byte(data))
|
||||
n, err := fsClient.Put(reader, int64(len(data)), "application/octet-stream", nil)
|
||||
n, err := fsClient.Put(reader, int64(len(data)), map[string][]string{
|
||||
"Content-Type": {"application/octet-stream"},
|
||||
}, nil)
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(n, Equals, int64(len(data)))
|
||||
|
||||
reader, err = fsClient.Get()
|
||||
reader, _, err = fsClient.Get()
|
||||
c.Assert(err, IsNil)
|
||||
var results bytes.Buffer
|
||||
buf := make([]byte, 5)
|
||||
@@ -260,23 +315,50 @@ func (s *MySuite) TestGetRange(c *C) {
|
||||
}
|
||||
|
||||
// Test stat file.
|
||||
func (s *MySuite) TestStatObject(c *C) {
|
||||
func (s *TestSuite) TestStatObject(c *C) {
|
||||
root, e := ioutil.TempDir(os.TempDir(), "fs-")
|
||||
c.Assert(e, IsNil)
|
||||
defer os.RemoveAll(root)
|
||||
|
||||
objectPath := filepath.Join(root, "object")
|
||||
fsClient, err := fs.New(objectPath)
|
||||
fsClient, err := fsNew(objectPath)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
data := "hello"
|
||||
dataLen := len(data)
|
||||
reader := bytes.NewReader([]byte(data))
|
||||
n, err := fsClient.Put(reader, int64(dataLen), "application/octet-stream", nil)
|
||||
n, err := fsClient.Put(reader, int64(dataLen), map[string][]string{
|
||||
"Content-Type": {"application/octet-stream"},
|
||||
}, nil)
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(n, Equals, int64(len(data)))
|
||||
|
||||
content, err := fsClient.Stat()
|
||||
content, err := fsClient.Stat(false)
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(content.Size, Equals, int64(dataLen))
|
||||
}
|
||||
|
||||
// Test copy.
|
||||
func (s *TestSuite) TestCopy(c *C) {
|
||||
root, e := ioutil.TempDir(os.TempDir(), "fs-")
|
||||
c.Assert(e, IsNil)
|
||||
defer os.RemoveAll(root)
|
||||
sourcePath := filepath.Join(root, "source")
|
||||
targetPath := filepath.Join(root, "target")
|
||||
fsClientTarget, err := fsNew(targetPath)
|
||||
c.Assert(err, IsNil)
|
||||
fsClientSource, err := fsNew(sourcePath)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
data := "hello world"
|
||||
var reader io.Reader
|
||||
reader = bytes.NewReader([]byte(data))
|
||||
n, err := fsClientSource.Put(reader, int64(len(data)), map[string][]string{
|
||||
"Content-Type": {"application/octet-stream"},
|
||||
}, nil)
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(n, Equals, int64(len(data)))
|
||||
|
||||
err = fsClientTarget.Copy(sourcePath, int64(len(data)), nil)
|
||||
c.Assert(err, IsNil)
|
||||
}
|
||||
@@ -14,9 +14,10 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package s3
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"strings"
|
||||
@@ -25,16 +26,16 @@ import (
|
||||
"github.com/minio/mc/pkg/httptracer"
|
||||
)
|
||||
|
||||
// TraceV2 - tracing structure
|
||||
type TraceV2 struct{}
|
||||
// traceV2 - tracing structure for signature version '2'.
|
||||
type traceV2 struct{}
|
||||
|
||||
// NewTraceV2 - initialize Trace structure
|
||||
func NewTraceV2() httptracer.HTTPTracer {
|
||||
return TraceV2{}
|
||||
// newTraceV2 - initialize Trace structure
|
||||
func newTraceV2() httptracer.HTTPTracer {
|
||||
return traceV2{}
|
||||
}
|
||||
|
||||
// Request - Trace HTTP Request
|
||||
func (t TraceV2) Request(req *http.Request) (err error) {
|
||||
func (t traceV2) Request(req *http.Request) (err error) {
|
||||
origAuth := req.Header.Get("Authorization")
|
||||
|
||||
if strings.TrimSpace(origAuth) != "" {
|
||||
@@ -57,19 +58,39 @@ func (t TraceV2) Request(req *http.Request) (err error) {
|
||||
}
|
||||
|
||||
// Response - Trace HTTP Response
|
||||
func (t TraceV2) Response(res *http.Response) (err error) {
|
||||
var resTrace []byte
|
||||
func (t traceV2) Response(resp *http.Response) (err error) {
|
||||
var respTrace []byte
|
||||
// For errors we make sure to dump response body as well.
|
||||
if res.StatusCode != http.StatusOK &&
|
||||
res.StatusCode != http.StatusPartialContent &&
|
||||
res.StatusCode != http.StatusNoContent {
|
||||
resTrace, err = httputil.DumpResponse(res, true)
|
||||
if resp.StatusCode != http.StatusOK &&
|
||||
resp.StatusCode != http.StatusPartialContent &&
|
||||
resp.StatusCode != http.StatusNoContent {
|
||||
respTrace, err = httputil.DumpResponse(resp, true)
|
||||
} else {
|
||||
// Only display header
|
||||
resTrace, err = httputil.DumpResponse(res, false)
|
||||
// WORKAROUND for https://github.com/golang/go/issues/13942.
|
||||
// httputil.DumpResponse does not print response headers for
|
||||
// all successful calls which have response ContentLength set
|
||||
// to zero. Keep this workaround until the above bug is fixed.
|
||||
if resp.ContentLength == 0 {
|
||||
var buffer bytes.Buffer
|
||||
if err = resp.Header.Write(&buffer); err != nil {
|
||||
return err
|
||||
}
|
||||
respTrace = buffer.Bytes()
|
||||
respTrace = append(respTrace, []byte("\r\n")...)
|
||||
} else {
|
||||
respTrace, err = httputil.DumpResponse(resp, false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
if err == nil {
|
||||
console.Debug(string(resTrace))
|
||||
console.Debug(string(respTrace))
|
||||
}
|
||||
|
||||
if globalInsecure && resp.TLS != nil {
|
||||
dumpTLSCertificates(resp.TLS)
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
@@ -14,9 +14,10 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package s3
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"regexp"
|
||||
@@ -26,16 +27,16 @@ import (
|
||||
"github.com/minio/mc/pkg/httptracer"
|
||||
)
|
||||
|
||||
// TraceV4 - tracing structure
|
||||
type TraceV4 struct{}
|
||||
// traceV4 - tracing structure for signature version '4'.
|
||||
type traceV4 struct{}
|
||||
|
||||
// NewTraceV4 - initialize Trace structure
|
||||
func NewTraceV4() httptracer.HTTPTracer {
|
||||
return TraceV4{}
|
||||
// newTraceV4 - initialize Trace structure
|
||||
func newTraceV4() httptracer.HTTPTracer {
|
||||
return traceV4{}
|
||||
}
|
||||
|
||||
// Request - Trace HTTP Request
|
||||
func (t TraceV4) Request(req *http.Request) (err error) {
|
||||
func (t traceV4) Request(req *http.Request) (err error) {
|
||||
origAuth := req.Header.Get("Authorization")
|
||||
|
||||
if strings.TrimSpace(origAuth) != "" {
|
||||
@@ -66,19 +67,39 @@ func (t TraceV4) Request(req *http.Request) (err error) {
|
||||
}
|
||||
|
||||
// Response - Trace HTTP Response
|
||||
func (t TraceV4) Response(res *http.Response) (err error) {
|
||||
var resTrace []byte
|
||||
func (t traceV4) Response(resp *http.Response) (err error) {
|
||||
var respTrace []byte
|
||||
// For errors we make sure to dump response body as well.
|
||||
if res.StatusCode != http.StatusOK &&
|
||||
res.StatusCode != http.StatusPartialContent &&
|
||||
res.StatusCode != http.StatusNoContent {
|
||||
resTrace, err = httputil.DumpResponse(res, true)
|
||||
if resp.StatusCode != http.StatusOK &&
|
||||
resp.StatusCode != http.StatusPartialContent &&
|
||||
resp.StatusCode != http.StatusNoContent {
|
||||
respTrace, err = httputil.DumpResponse(resp, true)
|
||||
} else {
|
||||
// Only display header
|
||||
resTrace, err = httputil.DumpResponse(res, false)
|
||||
// WORKAROUND for https://github.com/golang/go/issues/13942.
|
||||
// httputil.DumpResponse does not print response headers for
|
||||
// all successful calls which have response ContentLength set
|
||||
// to zero. Keep this workaround until the above bug is fixed.
|
||||
if resp.ContentLength == 0 {
|
||||
var buffer bytes.Buffer
|
||||
if err = resp.Header.Write(&buffer); err != nil {
|
||||
return err
|
||||
}
|
||||
respTrace = buffer.Bytes()
|
||||
respTrace = append(respTrace, []byte("\r\n")...)
|
||||
} else {
|
||||
respTrace, err = httputil.DumpResponse(resp, false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
if err == nil {
|
||||
console.Debug(string(resTrace))
|
||||
console.Debug(string(respTrace))
|
||||
}
|
||||
|
||||
if globalInsecure && resp.TLS != nil {
|
||||
dumpTLSCertificates(resp.TLS)
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
+1528
File diff suppressed because it is too large
Load Diff
@@ -14,7 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package s3
|
||||
package cmd
|
||||
|
||||
// bucketHandler is an http.Handler that verifies bucket responses and validates incoming requests
|
||||
import (
|
||||
@@ -23,11 +23,8 @@ import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/minio/mc/pkg/client"
|
||||
|
||||
. "gopkg.in/check.v1"
|
||||
)
|
||||
|
||||
@@ -60,13 +57,6 @@ func (h bucketHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
case r.Method == "PUT":
|
||||
switch {
|
||||
case r.URL.Path == h.resource:
|
||||
// Handler for incoming SetBucketACL request.
|
||||
_, ok := r.URL.Query()["acl"]
|
||||
if ok {
|
||||
if r.Header.Get("x-amz-acl") != "public-read-write" {
|
||||
w.WriteHeader(http.StatusNotImplemented)
|
||||
}
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
default:
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
@@ -168,64 +158,55 @@ func (h objectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
}
|
||||
|
||||
func Test(t *testing.T) { TestingT(t) }
|
||||
|
||||
type MySuite struct{}
|
||||
|
||||
var _ = Suite(&MySuite{})
|
||||
|
||||
// Test bucket operations.
|
||||
func (s *MySuite) TestBucketOperations(c *C) {
|
||||
func (s *TestSuite) TestBucketOperations(c *C) {
|
||||
bucket := bucketHandler(bucketHandler{
|
||||
resource: "/bucket/",
|
||||
})
|
||||
server := httptest.NewServer(bucket)
|
||||
defer server.Close()
|
||||
|
||||
conf := new(client.Config)
|
||||
conf := new(Config)
|
||||
conf.HostURL = server.URL + bucket.resource
|
||||
conf.AccessKey = "WLGDGYAQYIGI833EV05A"
|
||||
conf.SecretKey = "BYvgJM101sHngl2uzjXS/OBF/aMxAN06JrJ3qJlF"
|
||||
conf.Signature = "S3v4"
|
||||
s3c, err := New(conf)
|
||||
s3c, err := s3New(conf)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
err = s3c.MakeBucket("us-east-1")
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
err = s3c.SetBucketAccess("public-read-write")
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
conf.HostURL = server.URL + string(s3c.GetURL().Separator)
|
||||
s3c, err = New(conf)
|
||||
s3c, err = s3New(conf)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
for content := range s3c.List(false, false) {
|
||||
for content := range s3c.List(false, false, DirNone) {
|
||||
c.Assert(content.Err, IsNil)
|
||||
c.Assert(content.Type.IsDir(), Equals, true)
|
||||
}
|
||||
|
||||
conf.HostURL = server.URL + "/bucket"
|
||||
s3c, err = New(conf)
|
||||
s3c, err = s3New(conf)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
for content := range s3c.List(false, false) {
|
||||
for content := range s3c.List(false, false, DirNone) {
|
||||
c.Assert(content.Err, IsNil)
|
||||
c.Assert(content.Type.IsDir(), Equals, true)
|
||||
}
|
||||
|
||||
conf.HostURL = server.URL + "/bucket/"
|
||||
s3c, err = New(conf)
|
||||
s3c, err = s3New(conf)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
for content := range s3c.List(false, false) {
|
||||
for content := range s3c.List(false, false, DirNone) {
|
||||
c.Assert(content.Err, IsNil)
|
||||
c.Assert(content.Type.IsRegular(), Equals, true)
|
||||
}
|
||||
}
|
||||
|
||||
// Test all object operations.
|
||||
func (s *MySuite) TestObjectOperations(c *C) {
|
||||
func (s *TestSuite) TestObjectOperations(c *C) {
|
||||
object := objectHandler(objectHandler{
|
||||
resource: "/bucket/object",
|
||||
data: []byte("Hello, World"),
|
||||
@@ -233,26 +214,24 @@ func (s *MySuite) TestObjectOperations(c *C) {
|
||||
server := httptest.NewServer(object)
|
||||
defer server.Close()
|
||||
|
||||
conf := new(client.Config)
|
||||
conf := new(Config)
|
||||
conf.HostURL = server.URL + object.resource
|
||||
conf.AccessKey = "WLGDGYAQYIGI833EV05A"
|
||||
conf.SecretKey = "BYvgJM101sHngl2uzjXS/OBF/aMxAN06JrJ3qJlF"
|
||||
conf.Signature = "S3v4"
|
||||
s3c, err := New(conf)
|
||||
s3c, err := s3New(conf)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
var reader io.Reader
|
||||
reader = bytes.NewReader(object.data)
|
||||
n, err := s3c.Put(reader, int64(len(object.data)), "application/octet-stream", nil)
|
||||
n, err := s3c.Put(reader, int64(len(object.data)), map[string][]string{
|
||||
"Content-Type": {"application/octet-stream"},
|
||||
}, nil)
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(n, Equals, int64(len(object.data)))
|
||||
|
||||
content, err := s3c.Stat()
|
||||
reader, _, err = s3c.Get()
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(content.Size, Equals, int64(len(object.data)))
|
||||
c.Assert(content.Type.IsRegular(), Equals, true)
|
||||
|
||||
reader, err = s3c.Get()
|
||||
var buffer bytes.Buffer
|
||||
{
|
||||
_, err := io.Copy(&buffer, reader)
|
||||
@@ -14,19 +14,22 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package client
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"mime"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"runtime"
|
||||
"strings"
|
||||
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
// URL client url structure
|
||||
type URL struct {
|
||||
Type URLType
|
||||
// url client url structure
|
||||
type clientURL struct {
|
||||
Type clientURLType
|
||||
Scheme string
|
||||
Host string
|
||||
Path string
|
||||
@@ -34,13 +37,13 @@ type URL struct {
|
||||
Separator rune
|
||||
}
|
||||
|
||||
// URLType - enum of different url types
|
||||
type URLType int
|
||||
// clientURLType - enum of different url types
|
||||
type clientURLType int
|
||||
|
||||
// enum types
|
||||
const (
|
||||
Object = iota // Minio and S3 compatible cloud storage
|
||||
Filesystem // POSIX compatible file systems
|
||||
objectStorage = iota // Minio and S3 compatible cloud storage
|
||||
fileSystem // POSIX compatible file systems
|
||||
)
|
||||
|
||||
// Maybe rawurl is of the form scheme:path. (Scheme must be [a-zA-Z][a-zA-Z0-9+-.]*)
|
||||
@@ -87,10 +90,9 @@ func getHost(authority string) (host string) {
|
||||
return authority
|
||||
}
|
||||
|
||||
// NewURL returns an abstracted URL for filesystems and object storage.
|
||||
func NewURL(urlStr string) *URL {
|
||||
// newClientURL returns an abstracted URL for filesystems and object storage.
|
||||
func newClientURL(urlStr string) *clientURL {
|
||||
scheme, rest := getScheme(urlStr)
|
||||
rest, _ = splitSpecial(rest, "?", true)
|
||||
if strings.HasPrefix(rest, "//") {
|
||||
// if rest has '//' prefix, skip them
|
||||
var authority string
|
||||
@@ -100,9 +102,9 @@ func NewURL(urlStr string) *URL {
|
||||
}
|
||||
host := getHost(authority)
|
||||
if host != "" && (scheme == "http" || scheme == "https") {
|
||||
return &URL{
|
||||
return &clientURL{
|
||||
Scheme: scheme,
|
||||
Type: Object,
|
||||
Type: objectStorage,
|
||||
Host: host,
|
||||
Path: rest,
|
||||
SchemeSeparator: "://",
|
||||
@@ -110,15 +112,15 @@ func NewURL(urlStr string) *URL {
|
||||
}
|
||||
}
|
||||
}
|
||||
return &URL{
|
||||
Type: Filesystem,
|
||||
return &clientURL{
|
||||
Type: fileSystem,
|
||||
Path: rest,
|
||||
Separator: filepath.Separator,
|
||||
}
|
||||
}
|
||||
|
||||
// JoinURLs join two input urls and returns a url
|
||||
func JoinURLs(url1, url2 *URL) *URL {
|
||||
// joinURLs join two input urls and returns a url
|
||||
func joinURLs(url1, url2 *clientURL) *clientURL {
|
||||
var url1Path, url2Path string
|
||||
url1Path = filepath.ToSlash(url1.Path)
|
||||
url2Path = filepath.ToSlash(url2.Path)
|
||||
@@ -131,14 +133,14 @@ func JoinURLs(url1, url2 *URL) *URL {
|
||||
}
|
||||
|
||||
// String convert URL into its canonical form.
|
||||
func (u URL) String() string {
|
||||
func (u clientURL) String() string {
|
||||
var buf bytes.Buffer
|
||||
// if fileystem no translation needed, return as is.
|
||||
if u.Type == Filesystem {
|
||||
// if fileSystem no translation needed, return as is.
|
||||
if u.Type == fileSystem {
|
||||
return u.Path
|
||||
}
|
||||
// if Object convert from any non standard paths to a supported URL path style.
|
||||
if u.Type == Object {
|
||||
// if objectStorage convert from any non standard paths to a supported URL path style.
|
||||
if u.Type == objectStorage {
|
||||
buf.WriteString(u.Scheme)
|
||||
buf.WriteByte(':')
|
||||
buf.WriteString("//")
|
||||
@@ -160,3 +162,72 @@ func (u URL) String() string {
|
||||
}
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
// urlJoinPath Join a path to existing URL.
|
||||
func urlJoinPath(url1, url2 string) string {
|
||||
u1 := newClientURL(url1)
|
||||
u2 := newClientURL(url2)
|
||||
return joinURLs(u1, u2).String()
|
||||
}
|
||||
|
||||
// url2Stat returns stat info for URL.
|
||||
func url2Stat(urlStr string) (client Client, content *clientContent, err *probe.Error) {
|
||||
client, err = newClient(urlStr)
|
||||
if err != nil {
|
||||
return nil, nil, err.Trace(urlStr)
|
||||
}
|
||||
content, err = client.Stat(false)
|
||||
if err != nil {
|
||||
return nil, nil, err.Trace(urlStr)
|
||||
}
|
||||
return client, content, nil
|
||||
}
|
||||
|
||||
// url2Alias separates alias and path from the URL. Aliased URL is of
|
||||
// the form alias/path/to/blah.
|
||||
func url2Alias(aliasedURL string) (alias, path string) {
|
||||
// Save aliased url.
|
||||
urlStr := aliasedURL
|
||||
|
||||
// Convert '/' on windows to filepath.Separator.
|
||||
urlStr = filepath.FromSlash(urlStr)
|
||||
|
||||
if runtime.GOOS == "windows" {
|
||||
// Remove '/' prefix before alias if any to support '\\home' alias
|
||||
// style under Windows
|
||||
urlStr = strings.TrimPrefix(urlStr, string(filepath.Separator))
|
||||
}
|
||||
|
||||
// Remove everything after alias (i.e. after '/').
|
||||
urlParts := strings.SplitN(urlStr, string(filepath.Separator), 2)
|
||||
if len(urlParts) == 2 {
|
||||
// Convert windows style path separator to Unix style.
|
||||
return urlParts[0], urlParts[1]
|
||||
}
|
||||
return urlParts[0], ""
|
||||
}
|
||||
|
||||
// isURLPrefixExists - check if object key prefix exists.
|
||||
func isURLPrefixExists(urlPrefix string, incomplete bool) bool {
|
||||
clnt, err := newClient(urlPrefix)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
isRecursive := false
|
||||
isIncomplete := incomplete
|
||||
for entry := range clnt.List(isRecursive, isIncomplete, DirNone) {
|
||||
return entry.Err == nil
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// guessURLContentType - guess content-type of the URL.
|
||||
// on failure just return 'application/octet-stream'.
|
||||
func guessURLContentType(urlStr string) string {
|
||||
url := newClientURL(urlStr)
|
||||
contentType := mime.TypeByExtension(filepath.Ext(url.Path))
|
||||
if contentType == "" {
|
||||
contentType = "application/octet-stream"
|
||||
}
|
||||
return contentType
|
||||
}
|
||||
@@ -14,10 +14,24 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
package cmd
|
||||
|
||||
import . "gopkg.in/check.v1"
|
||||
|
||||
// TestURL - tests url parsing and fields.
|
||||
func (s *TestSuite) TestURL(c *C) {
|
||||
urlStr := "foo?.go"
|
||||
url := newClientURL(urlStr)
|
||||
c.Assert(url.Path, Equals, "foo?.go")
|
||||
|
||||
urlStr = "https://s3.amazonaws.com/mybucket/foo?.go"
|
||||
url = newClientURL(urlStr)
|
||||
c.Assert(url.Scheme, Equals, "https")
|
||||
c.Assert(url.Host, Equals, "s3.amazonaws.com")
|
||||
c.Assert(url.Path, Equals, "/mybucket/foo?.go")
|
||||
}
|
||||
|
||||
// TestURLJoinPath - tests joining two different urls.
|
||||
func (s *TestSuite) TestURLJoinPath(c *C) {
|
||||
// Join two URLs
|
||||
url1 := "http://s3.mycompany.io/dev"
|
||||
@@ -14,45 +14,66 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package client
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"io"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
// DirOpt - list directory option.
|
||||
type DirOpt int8
|
||||
|
||||
const (
|
||||
// DirNone - do not include directories in the list.
|
||||
DirNone DirOpt = iota
|
||||
// DirFirst - include directories before objects in the list.
|
||||
DirFirst
|
||||
// DirLast - include directories after objects in the list.
|
||||
DirLast
|
||||
)
|
||||
|
||||
// Client - client interface
|
||||
type Client interface {
|
||||
// Common operations
|
||||
Stat() (content *Content, err *probe.Error)
|
||||
List(recursive, incomplete bool) <-chan *Content
|
||||
Stat(isIncomplete bool) (content *clientContent, err *probe.Error)
|
||||
List(isRecursive, isIncomplete bool, showDir DirOpt) <-chan *clientContent
|
||||
|
||||
// Bucket operations
|
||||
MakeBucket(region string) *probe.Error
|
||||
GetBucketAccess() (access string, error *probe.Error)
|
||||
SetBucketAccess(access string) *probe.Error
|
||||
|
||||
// Access policy operations.
|
||||
GetAccess() (access string, error *probe.Error)
|
||||
GetAccessRules() (policyRules map[string]string, error *probe.Error)
|
||||
SetAccess(access string) *probe.Error
|
||||
|
||||
// I/O operations
|
||||
Get() (reader io.Reader, err *probe.Error)
|
||||
Put(reader io.Reader, size int64, contentType string, progress io.Reader) (n int64, err *probe.Error)
|
||||
Copy(source string, size int64, progress io.Reader) *probe.Error
|
||||
|
||||
// I/O operations with metadata.
|
||||
Get() (reader io.Reader, metadata map[string][]string, err *probe.Error)
|
||||
Put(reader io.Reader, size int64, metadata map[string][]string, progress io.Reader) (n int64, err *probe.Error)
|
||||
|
||||
// I/O operations with expiration
|
||||
ShareDownload(expires time.Duration) (string, *probe.Error)
|
||||
ShareUpload(bool, time.Duration, string) (map[string]string, *probe.Error)
|
||||
ShareUpload(bool, time.Duration, string) (string, map[string]string, *probe.Error)
|
||||
|
||||
// Watch events
|
||||
Watch(params watchParams) (*watchObject, *probe.Error)
|
||||
|
||||
// Delete operations
|
||||
Remove(incomplete bool) *probe.Error
|
||||
Remove(isIncomplete bool, contentCh <-chan *clientContent) (errorCh <-chan *probe.Error)
|
||||
|
||||
// GetURL returns back internal url
|
||||
GetURL() URL
|
||||
GetURL() clientURL
|
||||
}
|
||||
|
||||
// Content container for content metadata
|
||||
type Content struct {
|
||||
URL URL
|
||||
type clientContent struct {
|
||||
URL clientURL
|
||||
Time time.Time
|
||||
Size int64
|
||||
Type os.FileMode
|
||||
@@ -69,4 +90,5 @@ type Config struct {
|
||||
AppVersion string
|
||||
AppComments []string
|
||||
Debug bool
|
||||
Insecure bool
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
/*
|
||||
* 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 (
|
||||
"io"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"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)
|
||||
if err == nil {
|
||||
return targetContent.Type.IsDir()
|
||||
}
|
||||
_, aliasedTargetURL, _ := mustExpandAlias(targetURL)
|
||||
if aliasedTargetURL == targetURL {
|
||||
return false
|
||||
}
|
||||
// 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))
|
||||
switch len(fields) {
|
||||
case 0, 1:
|
||||
return false
|
||||
case 2:
|
||||
return true
|
||||
default:
|
||||
return strings.HasSuffix(pathURL, string(filepath.Separator))
|
||||
}
|
||||
}
|
||||
|
||||
// getSource gets a reader from URL.
|
||||
func getSourceStream(urlStr string) (reader io.Reader, err *probe.Error) {
|
||||
alias, urlStrFull, _, err := expandAlias(urlStr)
|
||||
if err != nil {
|
||||
return nil, err.Trace(urlStr)
|
||||
}
|
||||
reader, _, err = getSourceStreamFromAlias(alias, urlStrFull)
|
||||
return reader, err
|
||||
}
|
||||
|
||||
// getSourceStreamFromAlias gets a reader from URL.
|
||||
func getSourceStreamFromAlias(alias string, urlStr string) (reader io.Reader, metadata map[string][]string, err *probe.Error) {
|
||||
sourceClnt, err := newClientFromAlias(alias, urlStr)
|
||||
if err != nil {
|
||||
return nil, nil, err.Trace(alias, urlStr)
|
||||
}
|
||||
reader, metadata, err = sourceClnt.Get()
|
||||
if err != nil {
|
||||
return nil, nil, err.Trace(alias, urlStr)
|
||||
}
|
||||
return reader, metadata, nil
|
||||
}
|
||||
|
||||
// putTargetStreamFromAlias writes to URL from Reader.
|
||||
func putTargetStreamFromAlias(alias string, urlStr string, reader io.Reader, size int64, metadata map[string][]string, progress io.Reader) (int64, *probe.Error) {
|
||||
targetClnt, err := newClientFromAlias(alias, urlStr)
|
||||
if err != nil {
|
||||
return 0, err.Trace(alias, urlStr)
|
||||
}
|
||||
n, err := targetClnt.Put(reader, size, metadata, progress)
|
||||
if err != nil {
|
||||
return n, err.Trace(alias, urlStr)
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// putTargetStream writes to URL from reader. If length=-1, read until EOF.
|
||||
func putTargetStream(urlStr string, reader io.Reader, size int64) (int64, *probe.Error) {
|
||||
alias, urlStrFull, _, err := expandAlias(urlStr)
|
||||
if err != nil {
|
||||
return 0, err.Trace(alias, urlStr)
|
||||
}
|
||||
contentType := guessURLContentType(urlStr)
|
||||
metadata := map[string][]string{
|
||||
"Content-Type": {contentType},
|
||||
}
|
||||
return putTargetStreamFromAlias(alias, urlStrFull, reader, size, metadata, nil)
|
||||
}
|
||||
|
||||
// copySourceToTargetURL copies to targetURL from source.
|
||||
func copySourceToTargetURL(alias string, urlStr string, source string, size int64, progress io.Reader) *probe.Error {
|
||||
targetClnt, err := newClientFromAlias(alias, urlStr)
|
||||
if err != nil {
|
||||
return err.Trace(alias, urlStr)
|
||||
}
|
||||
err = targetClnt.Copy(source, size, progress)
|
||||
if err != nil {
|
||||
return err.Trace(alias, urlStr)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// uploadSourceToTargetURL - uploads to targetURL from source.
|
||||
// optionally optimizes copy for object sizes <= 5GiB by using
|
||||
// server side copy operation.
|
||||
func uploadSourceToTargetURL(urls URLs, progress io.Reader) URLs {
|
||||
sourceAlias := urls.SourceAlias
|
||||
sourceURL := urls.SourceContent.URL
|
||||
targetAlias := urls.TargetAlias
|
||||
targetURL := urls.TargetContent.URL
|
||||
length := urls.SourceContent.Size
|
||||
|
||||
// Optimize for server side copy if object is <= 5GiB and the host is same.
|
||||
if length <= globalMaximumPutSize && sourceAlias == targetAlias {
|
||||
sourcePath := filepath.ToSlash(sourceURL.Path)
|
||||
err := copySourceToTargetURL(targetAlias, targetURL.String(), sourcePath, length, progress)
|
||||
if err != nil {
|
||||
return urls.WithError(err.Trace(sourceURL.String()))
|
||||
}
|
||||
} else {
|
||||
// Proceed with regular stream copy.
|
||||
reader, metadata, err := getSourceStreamFromAlias(sourceAlias, sourceURL.String())
|
||||
if err != nil {
|
||||
return urls.WithError(err.Trace(sourceURL.String()))
|
||||
}
|
||||
_, err = putTargetStreamFromAlias(targetAlias, targetURL.String(), reader, length, metadata, progress)
|
||||
if err != nil {
|
||||
return urls.WithError(err.Trace(targetURL.String()))
|
||||
}
|
||||
}
|
||||
return urls.WithError(nil)
|
||||
}
|
||||
|
||||
// newClientFromAlias gives a new client interface for matching
|
||||
// alias entry in the mc config file. If no matching host config entry
|
||||
// is found, fs client is returned.
|
||||
func newClientFromAlias(alias string, urlStr string) (Client, *probe.Error) {
|
||||
s3Config, err := buildS3Config(alias, urlStr)
|
||||
if err != nil {
|
||||
// No matching host config. So we treat it like a
|
||||
// filesystem.
|
||||
fsClient, fsErr := fsNew(urlStr)
|
||||
if fsErr != nil {
|
||||
return nil, fsErr.Trace(alias, urlStr)
|
||||
}
|
||||
return fsClient, nil
|
||||
}
|
||||
|
||||
s3Client, err := s3New(s3Config)
|
||||
if err != nil {
|
||||
return nil, err.Trace(alias, urlStr)
|
||||
}
|
||||
return s3Client, nil
|
||||
}
|
||||
|
||||
// urlRgx - verify if aliased url is real URL.
|
||||
var urlRgx = regexp.MustCompile("^https?://")
|
||||
|
||||
// newClient gives a new client interface
|
||||
func newClient(aliasedURL string) (Client, *probe.Error) {
|
||||
alias, urlStrFull, hostCfg, err := expandAlias(aliasedURL)
|
||||
if err != nil {
|
||||
return nil, err.Trace(aliasedURL)
|
||||
}
|
||||
// Verify if the aliasedURL is a real URL, fail in those cases
|
||||
// indicating the user to add alias.
|
||||
if hostCfg == nil && urlRgx.MatchString(aliasedURL) {
|
||||
return nil, errInvalidAliasedURL(aliasedURL).Trace(aliasedURL)
|
||||
}
|
||||
return newClientFromAlias(alias, urlStrFull)
|
||||
}
|
||||
@@ -14,15 +14,15 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/minio/mc/pkg/client"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio-xl/pkg/quick"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
"github.com/minio/minio/pkg/quick"
|
||||
)
|
||||
|
||||
func fixConfig() {
|
||||
@@ -69,8 +69,8 @@ func fixConfigV3() {
|
||||
return
|
||||
}
|
||||
brokenCfgV3 := newBrokenConfigV3()
|
||||
brokenMcCfgV3, err := quick.Load(mustGetMcConfigPath(), brokenCfgV3)
|
||||
fatalIf(err.Trace(), "Unable to load config.")
|
||||
brokenMcCfgV3, e := quick.Load(mustGetMcConfigPath(), brokenCfgV3)
|
||||
fatalIf(probe.NewError(e), "Unable to load config.")
|
||||
|
||||
if brokenMcCfgV3.Version() != "3" {
|
||||
return
|
||||
@@ -101,11 +101,11 @@ func fixConfigV3() {
|
||||
// We blindly drop ACL and Access fields from the broken config v3.
|
||||
|
||||
if isMutated {
|
||||
mcNewConfigV3, err := quick.New(cfgV3)
|
||||
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘3’.")
|
||||
mcNewConfigV3, e := quick.New(cfgV3)
|
||||
fatalIf(probe.NewError(e), "Unable to initialize quick config for config version ‘3’.")
|
||||
|
||||
err = mcNewConfigV3.Save(mustGetMcConfigPath())
|
||||
fatalIf(err.Trace(), "Unable to save config version ‘3’.")
|
||||
e = mcNewConfigV3.Save(mustGetMcConfigPath())
|
||||
fatalIf(probe.NewError(e), "Unable to save config version ‘3’.")
|
||||
|
||||
console.Infof("Successfully fixed %s broken config for version ‘3’.\n", mustGetMcConfigPath())
|
||||
}
|
||||
@@ -117,8 +117,8 @@ func fixConfigV6ForHosts() {
|
||||
return
|
||||
}
|
||||
|
||||
brokenMcCfgV6, err := quick.Load(mustGetMcConfigPath(), newConfigV6())
|
||||
fatalIf(err.Trace(), "Unable to load config.")
|
||||
brokenMcCfgV6, e := quick.Load(mustGetMcConfigPath(), newConfigV6())
|
||||
fatalIf(probe.NewError(e), "Unable to load config.")
|
||||
|
||||
if brokenMcCfgV6.Version() != "6" {
|
||||
return
|
||||
@@ -132,7 +132,7 @@ func fixConfigV6ForHosts() {
|
||||
newCfgV6.Aliases[k] = v
|
||||
}
|
||||
|
||||
url := new(client.URL)
|
||||
url := &clientURL{}
|
||||
// Copy hosts.
|
||||
for host, hostCfgV6 := range brokenMcCfgV6.Data().(*configV6).Hosts {
|
||||
// Already fixed - Copy and move on.
|
||||
@@ -157,11 +157,11 @@ func fixConfigV6ForHosts() {
|
||||
|
||||
if isMutated {
|
||||
// Save the new config back to the disk.
|
||||
mcCfgV6, err := quick.New(newCfgV6)
|
||||
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘v6’.")
|
||||
mcCfgV6, e := quick.New(newCfgV6)
|
||||
fatalIf(probe.NewError(e), "Unable to initialize quick config for config version ‘v6’.")
|
||||
|
||||
err = mcCfgV6.Save(mustGetMcConfigPath())
|
||||
fatalIf(err.Trace(), "Unable to save config version ‘v6’.")
|
||||
e = mcCfgV6.Save(mustGetMcConfigPath())
|
||||
fatalIf(probe.NewError(e), "Unable to save config version ‘v6’.")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -170,11 +170,11 @@ func fixConfigV6() {
|
||||
if !isMcConfigExists() {
|
||||
return
|
||||
}
|
||||
config, err := quick.New(newConfigV6())
|
||||
fatalIf(err.Trace(), "Unable to initialize config.")
|
||||
config, e := quick.New(newConfigV6())
|
||||
fatalIf(probe.NewError(e), "Unable to initialize config.")
|
||||
|
||||
err = config.Load(mustGetMcConfigPath())
|
||||
fatalIf(err.Trace(mustGetMcConfigPath()), "Unable to load config.")
|
||||
e = config.Load(mustGetMcConfigPath())
|
||||
fatalIf(probe.NewError(e).Trace(mustGetMcConfigPath()), "Unable to load config.")
|
||||
|
||||
if config.Data().(*configV6).Version != "6" {
|
||||
return
|
||||
@@ -188,7 +188,7 @@ func fixConfigV6() {
|
||||
newConfig.Aliases = config.Data().(*configV6).Aliases
|
||||
for host, hostCfg := range config.Data().(*configV6).Hosts {
|
||||
if strings.Contains(host, "*") {
|
||||
fatalIf(err.Trace(),
|
||||
fatalIf(errInvalidArgument(),
|
||||
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*") {
|
||||
@@ -232,11 +232,11 @@ func fixConfigV6() {
|
||||
}
|
||||
|
||||
if isMutated {
|
||||
newConf, err := quick.New(newConfig)
|
||||
fatalIf(err.Trace(), "Unable to initialize newly fixed config.")
|
||||
newConf, e := quick.New(newConfig)
|
||||
fatalIf(probe.NewError(e), "Unable to initialize newly fixed config.")
|
||||
|
||||
err = newConf.Save(mustGetMcConfigPath())
|
||||
fatalIf(err.Trace(mustGetMcConfigPath()), "Unable to save newly fixed config path.")
|
||||
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())
|
||||
}
|
||||
}
|
||||
@@ -14,26 +14,22 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
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-xl/pkg/probe"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
var (
|
||||
configHostFlags = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "help, h",
|
||||
Usage: "Help of config host",
|
||||
},
|
||||
}
|
||||
configHostFlags = []cli.Flag{}
|
||||
)
|
||||
|
||||
var configHostCmd = cli.Command{
|
||||
@@ -41,6 +37,7 @@ var configHostCmd = cli.Command{
|
||||
Usage: "List, modify and remove hosts in configuration file.",
|
||||
Flags: append(configHostFlags, globalFlags...),
|
||||
Action: mainConfigHost,
|
||||
Before: setGlobalsFromContext,
|
||||
CustomHelpTemplate: `NAME:
|
||||
mc config {{.Name}} - {{.Usage}}
|
||||
|
||||
@@ -58,11 +55,15 @@ FLAGS:
|
||||
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 V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12
|
||||
$ mc config {{.Name}} add myphotos https://s3.amazonaws.com \
|
||||
BKIKJAA5BMMU2RHO6IBB V8f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12
|
||||
$ set -o history
|
||||
|
||||
2. Add Google Cloud Storage service under "goodisk" alias.
|
||||
$ mc config {{.Name}} add goodisk https://storage.googleapis.com BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 S3v2
|
||||
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
|
||||
@@ -88,11 +89,11 @@ func (h hostMessage) String() string {
|
||||
switch h.op {
|
||||
case "list":
|
||||
message := console.Colorize("Alias", fmt.Sprintf("%s: ", h.Alias))
|
||||
message += console.Colorize("URL", fmt.Sprintf("%s", h.URL))
|
||||
message += console.Colorize("URL", fmt.Sprintf("%-30.30s", h.URL))
|
||||
if h.AccessKey != "" || h.SecretKey != "" {
|
||||
message += " | " + console.Colorize("AccessKey", fmt.Sprintf("<- %s,", h.AccessKey))
|
||||
message += " | " + console.Colorize("SecretKey", fmt.Sprintf(" %s,", h.SecretKey))
|
||||
message += " | " + console.Colorize("API", fmt.Sprintf(" %s", h.API))
|
||||
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":
|
||||
@@ -165,11 +166,9 @@ func checkConfigHostAddSyntax(ctx *cli.Context) {
|
||||
"Invalid secret key ‘"+secretKey+"’.")
|
||||
}
|
||||
|
||||
switch api {
|
||||
case "S3v2", "S3v4", "":
|
||||
default:
|
||||
if api != "" && !isValidAPI(api) { // Empty value set to default "S3v4".
|
||||
fatalIf(errInvalidArgument().Trace(api),
|
||||
"Unrecognized API signature. Valid options are ‘[ S3v4, S3v2 ]’.")
|
||||
"Unrecognized API signature. Valid options are ‘[S3v4, S3v2]’.")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -188,9 +187,7 @@ func checkConfigHostRemoveSyntax(ctx *cli.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
func mainConfigHost(ctx *cli.Context) {
|
||||
// Set global flags from context.
|
||||
setGlobalsFromContext(ctx)
|
||||
func mainConfigHost(ctx *cli.Context) error {
|
||||
|
||||
// check 'config host' cli arguments.
|
||||
checkConfigHostSyntax(ctx)
|
||||
@@ -214,10 +211,10 @@ func mainConfigHost(ctx *cli.Context) {
|
||||
accessKey := args.Get(2)
|
||||
secretKey := args.Get(3)
|
||||
api := args.Get(4)
|
||||
if strings.TrimSpace(api) == "" {
|
||||
if api == "" {
|
||||
api = "S3v4"
|
||||
}
|
||||
hostCfg := hostConfigV7{
|
||||
hostCfg := hostConfigV8{
|
||||
URL: url,
|
||||
AccessKey: accessKey,
|
||||
SecretKey: secretKey,
|
||||
@@ -230,26 +227,27 @@ func mainConfigHost(ctx *cli.Context) {
|
||||
case "list":
|
||||
listHosts() // List all configured hosts.
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// addHost - add a host config.
|
||||
func addHost(alias string, hostCfgV7 hostConfigV7) {
|
||||
mcCfgV7, err := loadMcConfig()
|
||||
func addHost(alias string, hostCfgV8 hostConfigV8) {
|
||||
mcCfgV8, err := loadMcConfig()
|
||||
fatalIf(err.Trace(globalMCConfigVersion), "Unable to load config ‘"+mustGetMcConfigPath()+"’.")
|
||||
|
||||
// Add new host.
|
||||
mcCfgV7.Hosts[alias] = hostCfgV7
|
||||
mcCfgV8.Hosts[alias] = hostCfgV8
|
||||
|
||||
err = saveMcConfig(mcCfgV7)
|
||||
err = saveMcConfig(mcCfgV8)
|
||||
fatalIf(err.Trace(alias), "Unable to update hosts in config version ‘"+mustGetMcConfigPath()+"’.")
|
||||
|
||||
printMsg(hostMessage{
|
||||
op: "add",
|
||||
Alias: alias,
|
||||
URL: hostCfgV7.URL,
|
||||
AccessKey: hostCfgV7.AccessKey,
|
||||
SecretKey: hostCfgV7.SecretKey,
|
||||
API: hostCfgV7.API,
|
||||
URL: hostCfgV8.URL,
|
||||
AccessKey: hostCfgV8.AccessKey,
|
||||
SecretKey: hostCfgV8.SecretKey,
|
||||
API: hostCfgV8.API,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -267,13 +265,28 @@ func removeHost(alias string) {
|
||||
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 {
|
||||
printMsg(hostMessage{
|
||||
hosts = append(hosts, hostMessage{
|
||||
op: "list",
|
||||
Alias: k,
|
||||
URL: v.URL,
|
||||
@@ -282,4 +295,14 @@ func listHosts() {
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -14,7 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
package cmd
|
||||
|
||||
import "github.com/minio/cli"
|
||||
|
||||
@@ -30,18 +30,14 @@ import "github.com/minio/cli"
|
||||
//
|
||||
|
||||
var (
|
||||
configFlags = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "help, h",
|
||||
Usage: "Help of config.",
|
||||
},
|
||||
}
|
||||
configFlags = []cli.Flag{}
|
||||
)
|
||||
|
||||
var configCmd = cli.Command{
|
||||
Name: "config",
|
||||
Usage: "Manage configuration file.",
|
||||
Usage: "Manage mc configuration file.",
|
||||
Action: mainConfig,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(configFlags, globalFlags...),
|
||||
Subcommands: []cli.Command{
|
||||
configHostCmd,
|
||||
@@ -62,9 +58,7 @@ COMMANDS:
|
||||
}
|
||||
|
||||
// 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) {
|
||||
// Set global flags from context.
|
||||
setGlobalsFromContext(ctx)
|
||||
func mainConfig(ctx *cli.Context) error {
|
||||
|
||||
if ctx.Args().First() != "" { // command help.
|
||||
cli.ShowCommandHelp(ctx, ctx.Args().First())
|
||||
@@ -73,5 +67,6 @@ func mainConfig(ctx *cli.Context) {
|
||||
cli.ShowAppHelp(ctx)
|
||||
}
|
||||
|
||||
return nil
|
||||
// Sub-commands like "host" and "alias" have their own main.
|
||||
}
|
||||
@@ -14,14 +14,15 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio-xl/pkg/quick"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
"github.com/minio/minio/pkg/quick"
|
||||
)
|
||||
|
||||
// migrate config files from the any older version to the latest.
|
||||
@@ -40,6 +41,8 @@ func migrateConfig() {
|
||||
migrateConfigV5ToV6()
|
||||
// Migrate config V6 to V7
|
||||
migrateConfigV6ToV7()
|
||||
// Migrate config V7 to V8
|
||||
migrateConfigV7ToV8()
|
||||
}
|
||||
|
||||
// Migrate from config version 1.0 to 1.0.1. Populate example entries and save it back.
|
||||
@@ -47,8 +50,8 @@ func migrateConfigV1ToV101() {
|
||||
if !isMcConfigExists() {
|
||||
return
|
||||
}
|
||||
mcCfgV1, err := quick.Load(mustGetMcConfigPath(), newConfigV1())
|
||||
fatalIf(err.Trace(), "Unable to load config version ‘1’.")
|
||||
mcCfgV1, e := quick.Load(mustGetMcConfigPath(), newConfigV1())
|
||||
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" {
|
||||
@@ -91,10 +94,10 @@ func migrateConfigV1ToV101() {
|
||||
}
|
||||
|
||||
// Save the new config back to the disk.
|
||||
mcCfgV101, err := quick.New(cfgV101)
|
||||
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘1.0.1’.")
|
||||
err = mcCfgV101.Save(mustGetMcConfigPath())
|
||||
fatalIf(err.Trace(), "Unable to save config version ‘1.0.1’.")
|
||||
mcCfgV101, e := quick.New(cfgV101)
|
||||
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’.")
|
||||
|
||||
console.Infof("Successfully migrated %s from version ‘1.0.0’ to version ‘1.0.1’.\n", mustGetMcConfigPath())
|
||||
}
|
||||
@@ -104,8 +107,8 @@ func migrateConfigV101ToV2() {
|
||||
if !isMcConfigExists() {
|
||||
return
|
||||
}
|
||||
mcCfgV101, err := quick.Load(mustGetMcConfigPath(), newConfigV101())
|
||||
fatalIf(err.Trace(), "Unable to load config version ‘1.0.1’.")
|
||||
mcCfgV101, e := quick.Load(mustGetMcConfigPath(), newConfigV101())
|
||||
fatalIf(probe.NewError(e), "Unable to load config version ‘1.0.1’.")
|
||||
|
||||
// update to newer version
|
||||
if mcCfgV101.Version() != "1.0.1" {
|
||||
@@ -127,11 +130,11 @@ func migrateConfigV101ToV2() {
|
||||
}
|
||||
}
|
||||
|
||||
mcCfgV2, err := quick.New(cfgV2)
|
||||
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘2’.")
|
||||
mcCfgV2, e := quick.New(cfgV2)
|
||||
fatalIf(probe.NewError(e), "Unable to initialize quick config for config version ‘2’.")
|
||||
|
||||
err = mcCfgV2.Save(mustGetMcConfigPath())
|
||||
fatalIf(err.Trace(), "Unable to save config version ‘2’.")
|
||||
e = mcCfgV2.Save(mustGetMcConfigPath())
|
||||
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())
|
||||
}
|
||||
@@ -143,8 +146,8 @@ func migrateConfigV2ToV3() {
|
||||
return
|
||||
}
|
||||
|
||||
mcCfgV2, err := quick.Load(mustGetMcConfigPath(), newConfigV2())
|
||||
fatalIf(err.Trace(), "Unable to load mc config V2.")
|
||||
mcCfgV2, e := quick.Load(mustGetMcConfigPath(), newConfigV2())
|
||||
fatalIf(probe.NewError(e), "Unable to load mc config V2.")
|
||||
|
||||
// update to newer version
|
||||
if mcCfgV2.Version() != "2" {
|
||||
@@ -167,11 +170,11 @@ func migrateConfigV2ToV3() {
|
||||
}
|
||||
}
|
||||
|
||||
mcNewCfgV3, err := quick.New(cfgV3)
|
||||
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘3’.")
|
||||
mcNewCfgV3, e := quick.New(cfgV3)
|
||||
fatalIf(probe.NewError(e), "Unable to initialize quick config for config version ‘3’.")
|
||||
|
||||
err = mcNewCfgV3.Save(mustGetMcConfigPath())
|
||||
fatalIf(err.Trace(), "Unable to save config version ‘3’.")
|
||||
e = mcNewCfgV3.Save(mustGetMcConfigPath())
|
||||
fatalIf(probe.NewError(e), "Unable to save config version ‘3’.")
|
||||
|
||||
console.Infof("Successfully migrated %s from version ‘2’ to version ‘3’.\n", mustGetMcConfigPath())
|
||||
}
|
||||
@@ -182,8 +185,8 @@ func migrateConfigV3ToV4() {
|
||||
if !isMcConfigExists() {
|
||||
return
|
||||
}
|
||||
mcCfgV3, err := quick.Load(mustGetMcConfigPath(), newConfigV3())
|
||||
fatalIf(err.Trace(), "Unable to load mc config V2.")
|
||||
mcCfgV3, e := quick.Load(mustGetMcConfigPath(), newConfigV3())
|
||||
fatalIf(probe.NewError(e), "Unable to load mc config V2.")
|
||||
|
||||
// update to newer version
|
||||
if mcCfgV3.Version() != "3" {
|
||||
@@ -206,11 +209,11 @@ func migrateConfigV3ToV4() {
|
||||
}
|
||||
}
|
||||
|
||||
mcNewCfgV4, err := quick.New(cfgV4)
|
||||
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘4’.")
|
||||
mcNewCfgV4, e := quick.New(cfgV4)
|
||||
fatalIf(probe.NewError(e), "Unable to initialize quick config for config version ‘4’.")
|
||||
|
||||
err = mcNewCfgV4.Save(mustGetMcConfigPath())
|
||||
fatalIf(err.Trace(), "Unable to save config version ‘4’.")
|
||||
e = mcNewCfgV4.Save(mustGetMcConfigPath())
|
||||
fatalIf(probe.NewError(e), "Unable to save config version ‘4’.")
|
||||
|
||||
console.Infof("Successfully migrated %s from version ‘3’ to version ‘4’.\n", mustGetMcConfigPath())
|
||||
|
||||
@@ -221,8 +224,8 @@ func migrateConfigV4ToV5() {
|
||||
if !isMcConfigExists() {
|
||||
return
|
||||
}
|
||||
mcCfgV4, err := quick.Load(mustGetMcConfigPath(), newConfigV4())
|
||||
fatalIf(err.Trace(), "Unable to load mc config V4.")
|
||||
mcCfgV4, e := quick.Load(mustGetMcConfigPath(), newConfigV4())
|
||||
fatalIf(probe.NewError(e), "Unable to load mc config V4.")
|
||||
|
||||
// update to newer version
|
||||
if mcCfgV4.Version() != "4" {
|
||||
@@ -241,11 +244,11 @@ func migrateConfigV4ToV5() {
|
||||
}
|
||||
}
|
||||
|
||||
mcNewCfgV5, err := quick.New(cfgV5)
|
||||
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘5’.")
|
||||
mcNewCfgV5, e := quick.New(cfgV5)
|
||||
fatalIf(probe.NewError(e), "Unable to initialize quick config for config version ‘5’.")
|
||||
|
||||
err = mcNewCfgV5.Save(mustGetMcConfigPath())
|
||||
fatalIf(err.Trace(), "Unable to save config version ‘5’.")
|
||||
e = mcNewCfgV5.Save(mustGetMcConfigPath())
|
||||
fatalIf(probe.NewError(e), "Unable to save config version ‘5’.")
|
||||
|
||||
console.Infof("Successfully migrated %s from version ‘4’ to version ‘5’.\n", mustGetMcConfigPath())
|
||||
}
|
||||
@@ -256,8 +259,8 @@ func migrateConfigV5ToV6() {
|
||||
if !isMcConfigExists() {
|
||||
return
|
||||
}
|
||||
mcCfgV5, err := quick.Load(mustGetMcConfigPath(), newConfigV5())
|
||||
fatalIf(err.Trace(), "Unable to load mc config V5.")
|
||||
mcCfgV5, e := quick.Load(mustGetMcConfigPath(), newConfigV5())
|
||||
fatalIf(probe.NewError(e), "Unable to load mc config V5.")
|
||||
|
||||
// update to newer version
|
||||
if mcCfgV5.Version() != "5" {
|
||||
@@ -307,11 +310,11 @@ func migrateConfigV5ToV6() {
|
||||
}
|
||||
}
|
||||
|
||||
mcNewCfgV6, err := quick.New(cfgV6)
|
||||
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘6’.")
|
||||
mcNewCfgV6, e := quick.New(cfgV6)
|
||||
fatalIf(probe.NewError(e), "Unable to initialize quick config for config version ‘6’.")
|
||||
|
||||
err = mcNewCfgV6.Save(mustGetMcConfigPath())
|
||||
fatalIf(err.Trace(), "Unable to save config version ‘6’.")
|
||||
e = mcNewCfgV6.Save(mustGetMcConfigPath())
|
||||
fatalIf(probe.NewError(e), "Unable to save config version ‘6’.")
|
||||
|
||||
console.Infof("Successfully migrated %s from version ‘5’ to version ‘6’.\n", mustGetMcConfigPath())
|
||||
}
|
||||
@@ -323,8 +326,8 @@ func migrateConfigV6ToV7() {
|
||||
return
|
||||
}
|
||||
|
||||
mcCfgV6, err := quick.Load(mustGetMcConfigPath(), newConfigV6())
|
||||
fatalIf(err.Trace(), "Unable to load mc config V6.")
|
||||
mcCfgV6, e := quick.Load(mustGetMcConfigPath(), newConfigV6())
|
||||
fatalIf(probe.NewError(e), "Unable to load mc config V6.")
|
||||
|
||||
if mcCfgV6.Version() != "6" {
|
||||
return
|
||||
@@ -332,8 +335,24 @@ func migrateConfigV6ToV7() {
|
||||
|
||||
cfgV7 := newConfigV7()
|
||||
aliasIndex := 0
|
||||
|
||||
// old Aliases.
|
||||
oldAliases := mcCfgV6.Data().(*configV6).Aliases
|
||||
|
||||
// We dropped alias support in v7. We only need to migrate host configs.
|
||||
for host, hostCfgV6 := range mcCfgV6.Data().(*configV6).Hosts {
|
||||
// Look through old aliases, if found any matching save those entries.
|
||||
for aliasName, aliasedHost := range oldAliases {
|
||||
if aliasedHost == host {
|
||||
cfgV7.Hosts[aliasName] = hostConfigV7{
|
||||
URL: host,
|
||||
AccessKey: hostCfgV6.AccessKeyID,
|
||||
SecretKey: hostCfgV6.SecretAccessKey,
|
||||
API: hostCfgV6.API,
|
||||
}
|
||||
continue
|
||||
}
|
||||
}
|
||||
if hostCfgV6.AccessKeyID == "YOUR-ACCESS-KEY-ID-HERE" ||
|
||||
hostCfgV6.SecretAccessKey == "YOUR-SECRET-ACCESS-KEY-HERE" ||
|
||||
hostCfgV6.AccessKeyID == "" ||
|
||||
@@ -370,11 +389,50 @@ func migrateConfigV6ToV7() {
|
||||
}
|
||||
// Load default settings.
|
||||
cfgV7.loadDefaults()
|
||||
mcNewCfgV7, err := quick.New(cfgV7)
|
||||
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘7’.")
|
||||
mcNewCfgV7, e := quick.New(cfgV7)
|
||||
fatalIf(probe.NewError(e), "Unable to initialize quick config for config version ‘7’.")
|
||||
|
||||
err = mcNewCfgV7.Save(mustGetMcConfigPath())
|
||||
fatalIf(err.Trace(), "Unable to save config version ‘7’.")
|
||||
e = mcNewCfgV7.Save(mustGetMcConfigPath())
|
||||
fatalIf(probe.NewError(e), "Unable to save config version ‘7’.")
|
||||
|
||||
console.Infof("Successfully migrated %s from version ‘6’ to version ‘7’.\n", mustGetMcConfigPath())
|
||||
}
|
||||
|
||||
// Migrate config version ‘7’ to ‘8'. Remove hosts
|
||||
// 'play.minio.io:9002' and 'dl.minio.io:9000'.
|
||||
func migrateConfigV7ToV8() {
|
||||
if !isMcConfigExists() {
|
||||
return
|
||||
}
|
||||
|
||||
mcCfgV7, e := quick.Load(mustGetMcConfigPath(), newConfigV7())
|
||||
fatalIf(probe.NewError(e), "Unable to load mc config V7.")
|
||||
|
||||
if mcCfgV7.Version() != "7" {
|
||||
return
|
||||
}
|
||||
|
||||
cfgV8 := newConfigV8()
|
||||
// We dropped alias support in v7. We only need to migrate host configs.
|
||||
for host, hostCfgV7 := range mcCfgV7.Data().(*configV7).Hosts {
|
||||
// Ignore 'player', 'play' and 'dl' aliases.
|
||||
if host == "player" || host == "dl" || host == "play" {
|
||||
continue
|
||||
}
|
||||
hostCfgV8 := hostConfigV8{}
|
||||
hostCfgV8.URL = hostCfgV7.URL
|
||||
hostCfgV8.AccessKey = hostCfgV7.AccessKey
|
||||
hostCfgV8.SecretKey = hostCfgV7.SecretKey
|
||||
hostCfgV8.API = hostCfgV7.API
|
||||
cfgV8.Hosts[host] = hostCfgV8
|
||||
}
|
||||
// Load default settings.
|
||||
cfgV8.loadDefaults()
|
||||
mcNewCfgV8, e := quick.New(cfgV8)
|
||||
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’.")
|
||||
|
||||
console.Infof("Successfully migrated %s from version ‘7’ to version ‘8’.\n", mustGetMcConfigPath())
|
||||
}
|
||||
@@ -14,7 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
package cmd
|
||||
|
||||
/////////////////// Config V1 ///////////////////
|
||||
type hostConfigV1 struct {
|
||||
@@ -160,5 +160,85 @@ func newConfigV6() *configV6 {
|
||||
return conf
|
||||
}
|
||||
|
||||
/////////////////// Config V7 ///////////////////
|
||||
/////////////////// Config V6 ///////////////////
|
||||
// hostConfig configuration of a host - version '7'.
|
||||
type hostConfigV7 struct {
|
||||
URL string `json:"url"`
|
||||
AccessKey string `json:"accessKey"`
|
||||
SecretKey string `json:"secretKey"`
|
||||
API string `json:"api"`
|
||||
}
|
||||
|
||||
// configV7 config version.
|
||||
type configV7 struct {
|
||||
Version string `json:"version"`
|
||||
Hosts map[string]hostConfigV7 `json:"hosts"`
|
||||
}
|
||||
|
||||
// newConfigV7 - new config version '7'.
|
||||
func newConfigV7() *configV7 {
|
||||
cfg := new(configV7)
|
||||
cfg.Version = "7"
|
||||
cfg.Hosts = make(map[string]hostConfigV7)
|
||||
return cfg
|
||||
}
|
||||
|
||||
func (c *configV7) loadDefaults() {
|
||||
// Minio server running locally.
|
||||
c.setHost("local", hostConfigV7{
|
||||
URL: "http://localhost:9000",
|
||||
AccessKey: "",
|
||||
SecretKey: "",
|
||||
API: "S3v4",
|
||||
})
|
||||
|
||||
// Amazon S3 cloud storage service.
|
||||
c.setHost("s3", hostConfigV7{
|
||||
URL: "https://s3.amazonaws.com",
|
||||
AccessKey: defaultAccessKey,
|
||||
SecretKey: defaultSecretKey,
|
||||
API: "S3v4",
|
||||
})
|
||||
|
||||
// Google cloud storage service.
|
||||
c.setHost("gcs", hostConfigV7{
|
||||
URL: "https://storage.googleapis.com",
|
||||
AccessKey: defaultAccessKey,
|
||||
SecretKey: defaultSecretKey,
|
||||
API: "S3v2",
|
||||
})
|
||||
|
||||
// Minio anonymous server for demo.
|
||||
c.setHost("play", hostConfigV7{
|
||||
URL: "https://play.minio.io:9000",
|
||||
AccessKey: "",
|
||||
SecretKey: "",
|
||||
API: "S3v4",
|
||||
})
|
||||
|
||||
// Minio demo server with public secret and access keys.
|
||||
c.setHost("player", hostConfigV7{
|
||||
URL: "https://play.minio.io:9002",
|
||||
AccessKey: "Q3AM3UQ867SPQQA43P2F",
|
||||
SecretKey: "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG",
|
||||
API: "S3v4",
|
||||
})
|
||||
|
||||
// Minio public download service.
|
||||
c.setHost("dl", hostConfigV7{
|
||||
URL: "https://dl.minio.io:9000",
|
||||
AccessKey: "",
|
||||
SecretKey: "",
|
||||
API: "S3v4",
|
||||
})
|
||||
}
|
||||
|
||||
// SetHost sets host config if not empty.
|
||||
func (c *configV7) setHost(alias string, cfg hostConfigV7) {
|
||||
if _, ok := c.Hosts[alias]; !ok {
|
||||
c.Hosts[alias] = cfg
|
||||
}
|
||||
}
|
||||
|
||||
/////////////////// Config V8 ///////////////////
|
||||
// RESERVED FOR FUTURE
|
||||
@@ -0,0 +1,66 @@
|
||||
/*
|
||||
* Minio Client (C) 2015, 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 "strings"
|
||||
|
||||
var validAPIs = []string{"S3v4", "S3v2"}
|
||||
|
||||
const (
|
||||
accessKeyMinLen = 5
|
||||
accessKeyMaxLen = 20
|
||||
secretKeyMinLen = 8
|
||||
secretKeyMaxLen = 40
|
||||
)
|
||||
|
||||
// isValidAccessKey - validate access key for right length.
|
||||
func isValidAccessKey(accessKey string) bool {
|
||||
if accessKey == "" {
|
||||
return true
|
||||
}
|
||||
return len(accessKey) >= accessKeyMinLen && len(accessKey) <= accessKeyMaxLen
|
||||
}
|
||||
|
||||
// isValidSecretKey - validate secret key for right length.
|
||||
func isValidSecretKey(secretKey string) bool {
|
||||
if secretKey == "" {
|
||||
return true
|
||||
}
|
||||
return len(secretKey) >= secretKeyMinLen && len(secretKey) <= secretKeyMaxLen
|
||||
}
|
||||
|
||||
// isValidHostURL - validate input host url.
|
||||
func isValidHostURL(hostURL string) (ok bool) {
|
||||
if strings.TrimSpace(hostURL) != "" {
|
||||
url := newClientURL(hostURL)
|
||||
if url.Scheme == "https" || url.Scheme == "http" {
|
||||
if url.Path == "/" {
|
||||
ok = true
|
||||
}
|
||||
}
|
||||
}
|
||||
return ok
|
||||
}
|
||||
|
||||
// isValidAPI - Validates if API signature string of supported type.
|
||||
func isValidAPI(api string) (ok bool) {
|
||||
switch strings.ToLower(api) {
|
||||
case "s3v2", "s3v4":
|
||||
ok = true
|
||||
}
|
||||
return ok
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
/*
|
||||
* 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 "testing"
|
||||
|
||||
// Tests valid host URL functionality.
|
||||
func TestValidHostURL(t *testing.T) {
|
||||
testCases := []struct {
|
||||
hostURL string
|
||||
isHost bool
|
||||
}{
|
||||
{
|
||||
hostURL: "https://localhost:9000",
|
||||
isHost: true,
|
||||
},
|
||||
{
|
||||
hostURL: "/",
|
||||
isHost: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
isHost := isValidHostURL(testCase.hostURL)
|
||||
if testCase.isHost != isHost {
|
||||
t.Fatalf("Expected %t, got %t", testCase.isHost, isHost)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsValidAPI(t *testing.T) {
|
||||
equalAssert(isValidAPI("s3V2"), true, t)
|
||||
equalAssert(isValidAPI("S3v2"), true, t)
|
||||
equalAssert(isValidAPI("s3"), false, t)
|
||||
}
|
||||
|
||||
func equalAssert(ok1, ok2 bool, t *testing.T) {
|
||||
if ok1 != ok2 {
|
||||
t.Errorf("Expected %t, got %t", ok2, ok1)
|
||||
}
|
||||
}
|
||||
|
||||
// Tests valid and invalid secret keys.
|
||||
func TestValidSecretKeys(t *testing.T) {
|
||||
equalAssert(isValidSecretKey("password"), true, t)
|
||||
equalAssert(isValidSecretKey("BYvgJM101sHngl2uzjXS/OBF/aMxAN06JrJ3qJlF"), true, t)
|
||||
|
||||
equalAssert(isValidSecretKey("aaa"), false, t)
|
||||
equalAssert(isValidSecretKey("password%%"), true, t)
|
||||
}
|
||||
|
||||
// Tests valid and invalid access keys.
|
||||
func TestValidAccessKeys(t *testing.T) {
|
||||
equalAssert(isValidAccessKey("c67W2-r4MAyAYScRl"), true, t)
|
||||
equalAssert(isValidAccessKey("EXOb76bfeb1234562iu679f11588"), false, t)
|
||||
equalAssert(isValidAccessKey("BYvgJM101sHngl2uzjXS/OBF/aMxAN06JrJ3qJlF"), false, t)
|
||||
equalAssert(isValidAccessKey("admin"), true, t)
|
||||
|
||||
equalAssert(isValidAccessKey("aaa"), false, t)
|
||||
equalAssert(isValidAccessKey("$$%%%%%3333"), true, t)
|
||||
}
|
||||
@@ -14,13 +14,13 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"sync"
|
||||
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/minio-xl/pkg/quick"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
"github.com/minio/minio/pkg/quick"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -30,44 +30,44 @@ const (
|
||||
|
||||
var (
|
||||
// set once during first load.
|
||||
cacheCfgV7 *configV7
|
||||
cacheCfgV8 *configV8
|
||||
// All access to mc config file should be synchronized.
|
||||
cfgMutex = &sync.RWMutex{}
|
||||
)
|
||||
|
||||
// hostConfig configuration of a host.
|
||||
type hostConfigV7 struct {
|
||||
type hostConfigV8 struct {
|
||||
URL string `json:"url"`
|
||||
AccessKey string `json:"accessKey"`
|
||||
SecretKey string `json:"secretKey"`
|
||||
API string `json:"api"`
|
||||
}
|
||||
|
||||
// configV7 config version.
|
||||
type configV7 struct {
|
||||
// configV8 config version.
|
||||
type configV8 struct {
|
||||
Version string `json:"version"`
|
||||
Hosts map[string]hostConfigV7 `json:"hosts"`
|
||||
Hosts map[string]hostConfigV8 `json:"hosts"`
|
||||
}
|
||||
|
||||
// newConfigV7 - new config version.
|
||||
func newConfigV7() *configV7 {
|
||||
cfg := new(configV7)
|
||||
// newConfigV8 - new config version.
|
||||
func newConfigV8() *configV8 {
|
||||
cfg := new(configV8)
|
||||
cfg.Version = globalMCConfigVersion
|
||||
cfg.Hosts = make(map[string]hostConfigV7)
|
||||
cfg.Hosts = make(map[string]hostConfigV8)
|
||||
return cfg
|
||||
}
|
||||
|
||||
// SetHost sets host config if not empty.
|
||||
func (c *configV7) setHost(alias string, cfg hostConfigV7) {
|
||||
func (c *configV8) setHost(alias string, cfg hostConfigV8) {
|
||||
if _, ok := c.Hosts[alias]; !ok {
|
||||
c.Hosts[alias] = cfg
|
||||
}
|
||||
}
|
||||
|
||||
// load default values for missing entries.
|
||||
func (c *configV7) loadDefaults() {
|
||||
func (c *configV8) loadDefaults() {
|
||||
// Minio server running locally.
|
||||
c.setHost("local", hostConfigV7{
|
||||
c.setHost("local", hostConfigV8{
|
||||
URL: "http://localhost:9000",
|
||||
AccessKey: "",
|
||||
SecretKey: "",
|
||||
@@ -75,7 +75,7 @@ func (c *configV7) loadDefaults() {
|
||||
})
|
||||
|
||||
// Amazon S3 cloud storage service.
|
||||
c.setHost("s3", hostConfigV7{
|
||||
c.setHost("s3", hostConfigV8{
|
||||
URL: "https://s3.amazonaws.com",
|
||||
AccessKey: defaultAccessKey,
|
||||
SecretKey: defaultSecretKey,
|
||||
@@ -83,7 +83,7 @@ func (c *configV7) loadDefaults() {
|
||||
})
|
||||
|
||||
// Google cloud storage service.
|
||||
c.setHost("gcs", hostConfigV7{
|
||||
c.setHost("gcs", hostConfigV8{
|
||||
URL: "https://storage.googleapis.com",
|
||||
AccessKey: defaultAccessKey,
|
||||
SecretKey: defaultSecretKey,
|
||||
@@ -91,67 +91,65 @@ func (c *configV7) loadDefaults() {
|
||||
})
|
||||
|
||||
// Minio anonymous server for demo.
|
||||
c.setHost("play", hostConfigV7{
|
||||
c.setHost("play", hostConfigV8{
|
||||
URL: "https://play.minio.io:9000",
|
||||
AccessKey: "",
|
||||
SecretKey: "",
|
||||
API: "S3v4",
|
||||
})
|
||||
|
||||
// Minio demo server with public secret and access keys.
|
||||
c.setHost("player", hostConfigV7{
|
||||
URL: "https://play.minio.io:9002",
|
||||
AccessKey: "Q3AM3UQ867SPQQA43P2F",
|
||||
SecretKey: "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG",
|
||||
API: "S3v4",
|
||||
})
|
||||
|
||||
// Minio public download service.
|
||||
c.setHost("dl", hostConfigV7{
|
||||
URL: "https://dl.minio.io:9000",
|
||||
AccessKey: "",
|
||||
SecretKey: "",
|
||||
API: "S3v4",
|
||||
})
|
||||
}
|
||||
|
||||
// loadConfigV7 - loads a new config.
|
||||
func loadConfigV7() (*configV7, *probe.Error) {
|
||||
// loadConfigV8 - loads a new config.
|
||||
func loadConfigV8() (*configV8, *probe.Error) {
|
||||
cfgMutex.RLock()
|
||||
defer cfgMutex.RUnlock()
|
||||
|
||||
// Cached in private global variable.
|
||||
if cacheCfgV7 != nil {
|
||||
return cacheCfgV7, nil
|
||||
// If already cached, return the cached value.
|
||||
if cacheCfgV8 != nil {
|
||||
return cacheCfgV8, nil
|
||||
}
|
||||
|
||||
if !isMcConfigExists() {
|
||||
return nil, errInvalidArgument().Trace()
|
||||
}
|
||||
|
||||
mcCfgV7, err := quick.Load(mustGetMcConfigPath(), newConfigV7())
|
||||
fatalIf(err.Trace(), "Unable to load mc config file ‘"+mustGetMcConfigPath()+"’.")
|
||||
// Initialize a new config loader.
|
||||
qc, e := quick.New(newConfigV8())
|
||||
if e != nil {
|
||||
return nil, probe.NewError(e)
|
||||
}
|
||||
|
||||
cfgV7 := mcCfgV7.Data().(*configV7)
|
||||
// Load config at configPath, fails if config is not
|
||||
// accessible, malformed or version missing.
|
||||
if e = qc.Load(mustGetMcConfigPath()); e != nil {
|
||||
return nil, probe.NewError(e)
|
||||
}
|
||||
|
||||
// cache it.
|
||||
cacheCfgV7 = cfgV7
|
||||
cfgV8 := qc.Data().(*configV8)
|
||||
|
||||
return cfgV7, nil
|
||||
// Cache config.
|
||||
cacheCfgV8 = cfgV8
|
||||
|
||||
// Success.
|
||||
return cfgV8, nil
|
||||
}
|
||||
|
||||
// saveConfigV7 - saves an updated config.
|
||||
func saveConfigV7(cfgV7 *configV7) *probe.Error {
|
||||
// saveConfigV8 - saves an updated config.
|
||||
func saveConfigV8(cfgV8 *configV8) *probe.Error {
|
||||
cfgMutex.Lock()
|
||||
defer cfgMutex.Unlock()
|
||||
|
||||
qs, err := quick.New(cfgV7)
|
||||
if err != nil {
|
||||
return err.Trace()
|
||||
qs, e := quick.New(cfgV8)
|
||||
if e != nil {
|
||||
return probe.NewError(e)
|
||||
}
|
||||
|
||||
// update the cache.
|
||||
cacheCfgV7 = cfgV7
|
||||
cacheCfgV8 = cfgV8
|
||||
|
||||
return qs.Save(mustGetMcConfigPath()).Trace(mustGetMcConfigPath())
|
||||
e = qs.Save(mustGetMcConfigPath())
|
||||
if e != nil {
|
||||
return probe.NewError(e).Trace(mustGetMcConfigPath())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
/*
|
||||
* 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 (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Check if version of the config is valid
|
||||
func validateConfigVersion(config *configV8) (bool, string) {
|
||||
if config.Version != globalMCConfigVersion {
|
||||
return false, fmt.Sprintf("Config version '%s' does not match mc config version '%s', please update your binary.\n",
|
||||
config.Version, globalMCConfigVersion)
|
||||
}
|
||||
return true, ""
|
||||
}
|
||||
|
||||
// Verifies the config file of the Minio Client
|
||||
func validateConfigFile(config *configV8) (bool, []string) {
|
||||
ok, err := validateConfigVersion(config)
|
||||
var validationSuccessful = true
|
||||
var errors []string
|
||||
if !ok {
|
||||
validationSuccessful = false
|
||||
errors = append(errors, err)
|
||||
}
|
||||
hosts := config.Hosts
|
||||
for _, hostConfig := range hosts {
|
||||
hostConfigHealthOk, hostErrors := validateConfigHost(hostConfig)
|
||||
if !hostConfigHealthOk {
|
||||
validationSuccessful = false
|
||||
errors = append(errors, hostErrors...)
|
||||
}
|
||||
}
|
||||
return validationSuccessful, errors
|
||||
}
|
||||
|
||||
func validateConfigHost(host hostConfigV8) (bool, []string) {
|
||||
var validationSuccessful = true
|
||||
var hostErrors []string
|
||||
api := host.API
|
||||
validAPI := isValidAPI(strings.ToLower(api))
|
||||
if !validAPI {
|
||||
var errorMsg bytes.Buffer
|
||||
errorMsg.WriteString(fmt.Sprintf(
|
||||
"%s API for host %s is not Valid. It is not part of any of the following APIs:\n",
|
||||
api, host.URL))
|
||||
for index, validAPI := range validAPIs {
|
||||
errorMsg.WriteString(fmt.Sprintf("%d. %s\n", index+1, validAPI))
|
||||
}
|
||||
validationSuccessful = false
|
||||
hostErrors = append(hostErrors, errorMsg.String())
|
||||
}
|
||||
url := host.URL
|
||||
validURL := isValidHostURL(url)
|
||||
if !validURL {
|
||||
validationSuccessful = false
|
||||
msg := fmt.Sprintf("URL %s for host %s is not valid. Could not parse it.\n", url, host.URL)
|
||||
hostErrors = append(hostErrors, msg)
|
||||
}
|
||||
return validationSuccessful, hostErrors
|
||||
}
|
||||
+25
-26
@@ -14,7 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"os"
|
||||
@@ -22,16 +22,13 @@ import (
|
||||
"regexp"
|
||||
"runtime"
|
||||
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/minio/pkg/user"
|
||||
"github.com/minio/go-homedir"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
// mcCustomConfigDir contains the whole path to config dir. Only access via get/set functions.
|
||||
var mcCustomConfigDir string
|
||||
|
||||
// mcCustomConfigPath contains the whole path to config file. Only access via get/set functions.
|
||||
var mcCustomConfigPath string
|
||||
|
||||
// setMcConfigDir - set a custom minio client config folder.
|
||||
func setMcConfigDir(configDir string) {
|
||||
mcCustomConfigDir = configDir
|
||||
@@ -42,17 +39,18 @@ func getMcConfigDir() (string, *probe.Error) {
|
||||
if mcCustomConfigDir != "" {
|
||||
return mcCustomConfigDir, nil
|
||||
}
|
||||
homeDir, e := user.HomeDir()
|
||||
homeDir, e := homedir.Dir()
|
||||
if e != nil {
|
||||
return "", probe.NewError(e)
|
||||
}
|
||||
var configDir string
|
||||
// For windows the path is slightly different
|
||||
switch runtime.GOOS {
|
||||
case "windows":
|
||||
return filepath.Join(homeDir, globalMCConfigWindowsDir), nil
|
||||
default:
|
||||
return filepath.Join(homeDir, globalMCConfigDir), nil
|
||||
if runtime.GOOS == "windows" {
|
||||
configDir = filepath.Join(homeDir, globalMCConfigWindowsDir)
|
||||
} else {
|
||||
configDir = filepath.Join(homeDir, globalMCConfigDir)
|
||||
}
|
||||
return configDir, nil
|
||||
}
|
||||
|
||||
// mustGetMcConfigDir - construct minio client config folder or fail
|
||||
@@ -77,8 +75,8 @@ func createMcConfigDir() *probe.Error {
|
||||
|
||||
// getMcConfigPath - construct minio client configuration path
|
||||
func getMcConfigPath() (string, *probe.Error) {
|
||||
if mcCustomConfigPath != "" {
|
||||
return mcCustomConfigPath, nil
|
||||
if mcCustomConfigDir != "" {
|
||||
return filepath.Join(mcCustomConfigDir, globalMCConfigFile), nil
|
||||
}
|
||||
dir, err := getMcConfigDir()
|
||||
if err != nil {
|
||||
@@ -96,27 +94,28 @@ func mustGetMcConfigPath() string {
|
||||
}
|
||||
|
||||
// newMcConfig - initializes a new version '6' config.
|
||||
func newMcConfig() *configV7 {
|
||||
cfg := newConfigV7()
|
||||
func newMcConfig() *configV8 {
|
||||
cfg := newConfigV8()
|
||||
cfg.loadDefaults()
|
||||
return cfg
|
||||
}
|
||||
|
||||
// loadMcConfigCached - returns loadMcConfig with a closure for config cache.
|
||||
func loadMcConfigFactory() func() (*configV7, *probe.Error) {
|
||||
func loadMcConfigFactory() func() (*configV8, *probe.Error) {
|
||||
// Load once and cache in a closure.
|
||||
cfgCache, err := loadConfigV7()
|
||||
cfgCache, err := loadConfigV8()
|
||||
|
||||
// loadMcConfig - reads configuration file and returns config.
|
||||
return func() (*configV7, *probe.Error) {
|
||||
return func() (*configV8, *probe.Error) {
|
||||
return cfgCache, err
|
||||
}
|
||||
}
|
||||
|
||||
var loadMcConfig = loadMcConfigFactory()
|
||||
// loadMcConfig - returns configuration, initialized later.
|
||||
var loadMcConfig func() (*configV8, *probe.Error)
|
||||
|
||||
// saveMcConfig - saves configuration file and returns error if any.
|
||||
func saveMcConfig(config *configV7) *probe.Error {
|
||||
func saveMcConfig(config *configV8) *probe.Error {
|
||||
if config == nil {
|
||||
return errInvalidArgument().Trace()
|
||||
}
|
||||
@@ -127,7 +126,7 @@ func saveMcConfig(config *configV7) *probe.Error {
|
||||
}
|
||||
|
||||
// Save the config.
|
||||
if err := saveConfigV7(config); err != nil {
|
||||
if err := saveConfigV8(config); err != nil {
|
||||
return err.Trace(mustGetMcConfigPath())
|
||||
}
|
||||
|
||||
@@ -154,7 +153,7 @@ func isValidAlias(alias string) bool {
|
||||
}
|
||||
|
||||
// getHostConfig retrieves host specific configuration such as access keys, signature type.
|
||||
func getHostConfig(alias string) (*hostConfigV7, *probe.Error) {
|
||||
func getHostConfig(alias string) (*hostConfigV8, *probe.Error) {
|
||||
mcCfg, err := loadMcConfig()
|
||||
if err != nil {
|
||||
return nil, err.Trace(alias)
|
||||
@@ -171,13 +170,13 @@ func getHostConfig(alias string) (*hostConfigV7, *probe.Error) {
|
||||
}
|
||||
|
||||
// mustGetHostConfig retrieves host specific configuration such as access keys, signature type.
|
||||
func mustGetHostConfig(alias string) *hostConfigV7 {
|
||||
func mustGetHostConfig(alias string) *hostConfigV8 {
|
||||
hostCfg, _ := getHostConfig(alias)
|
||||
return hostCfg
|
||||
}
|
||||
|
||||
// expandAlias expands aliased URL if any match is found, returns as is otherwise.
|
||||
func expandAlias(aliasedURL string) (alias string, urlStr string, hostCfg *hostConfigV7, err *probe.Error) {
|
||||
func expandAlias(aliasedURL string) (alias string, urlStr string, hostCfg *hostConfigV8, err *probe.Error) {
|
||||
// Extract alias from the URL.
|
||||
alias, path := url2Alias(aliasedURL)
|
||||
|
||||
@@ -189,7 +188,7 @@ func expandAlias(aliasedURL string) (alias string, urlStr string, hostCfg *hostC
|
||||
}
|
||||
|
||||
// mustExpandAlias expands aliased URL if any match is found, returns as is otherwise.
|
||||
func mustExpandAlias(aliasedURL string) (alias string, urlStr string, hostCfg *hostConfigV7) {
|
||||
func mustExpandAlias(aliasedURL string) (alias string, urlStr string, hostCfg *hostConfigV8) {
|
||||
alias, urlStr, hostCfg, _ = expandAlias(aliasedURL)
|
||||
return alias, urlStr, hostCfg
|
||||
}
|
||||
+50
-68
@@ -14,7 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
@@ -27,21 +27,16 @@ import (
|
||||
"sync"
|
||||
"syscall"
|
||||
|
||||
"github.com/cheggaaa/pb"
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/client"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/pb"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
// cp command flags.
|
||||
var (
|
||||
cpFlags = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "help, h",
|
||||
Usage: "Help of cp.",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "recursive, r",
|
||||
Usage: "Copy recursively.",
|
||||
@@ -52,8 +47,9 @@ var (
|
||||
// Copy command.
|
||||
var cpCmd = cli.Command{
|
||||
Name: "cp",
|
||||
Usage: "Copy one or more objects to a target.",
|
||||
Usage: "Copy files and objects.",
|
||||
Action: mainCopy,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(cpFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
mc {{.Name}} - {{.Usage}}
|
||||
@@ -87,9 +83,12 @@ EXAMPLES:
|
||||
|
||||
// copyMessage container for file copy messages
|
||||
type copyMessage struct {
|
||||
Status string `json:"status"`
|
||||
Source string `json:"source"`
|
||||
Target string `json:"target"`
|
||||
Status string `json:"status"`
|
||||
Source string `json:"source"`
|
||||
Target string `json:"target"`
|
||||
Size int64 `json:"size"`
|
||||
TotalCount int64 `json:"totalCount"`
|
||||
TotalSize int64 `json:"totalSize"`
|
||||
}
|
||||
|
||||
// String colorized copy message
|
||||
@@ -115,19 +114,19 @@ type copyStatMessage struct {
|
||||
|
||||
// copyStatMessage copy accounting message
|
||||
func (c copyStatMessage) String() string {
|
||||
speedBox := pb.FormatBytes(int64(c.Speed))
|
||||
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.FormatBytes(c.Total),
|
||||
pb.FormatBytes(c.Transferred), speedBox)
|
||||
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
|
||||
}
|
||||
|
||||
// doCopy - Copy a singe file from source to destination
|
||||
func doCopy(cpURLs copyURLs, progressReader *progressBar, accountingReader *accounter) copyURLs {
|
||||
func doCopy(cpURLs URLs, progressReader *progressBar, accountingReader *accounter) URLs {
|
||||
if cpURLs.Error != nil {
|
||||
cpURLs.Error = cpURLs.Error.Trace()
|
||||
return cpURLs
|
||||
@@ -143,19 +142,16 @@ func doCopy(cpURLs copyURLs, progressReader *progressBar, accountingReader *acco
|
||||
targetURL := cpURLs.TargetContent.URL
|
||||
length := cpURLs.SourceContent.Size
|
||||
|
||||
reader, err := getSourceStreamFromAlias(sourceAlias, sourceURL.String())
|
||||
if err != nil {
|
||||
cpURLs.Error = err.Trace(sourceURL.String())
|
||||
return cpURLs
|
||||
}
|
||||
|
||||
var progress io.Reader
|
||||
if globalQuiet || globalJSON {
|
||||
sourcePath := filepath.ToSlash(filepath.Join(sourceAlias, sourceURL.Path))
|
||||
targetPath := filepath.ToSlash(filepath.Join(targetAlias, targetURL.Path))
|
||||
printMsg(copyMessage{
|
||||
Source: sourcePath,
|
||||
Target: targetPath,
|
||||
Source: sourcePath,
|
||||
Target: targetPath,
|
||||
Size: length,
|
||||
TotalCount: cpURLs.TotalCount,
|
||||
TotalSize: cpURLs.TotalSize,
|
||||
})
|
||||
// Proxy reader to accounting reader only during quiet mode.
|
||||
if globalQuiet || globalJSON {
|
||||
@@ -165,17 +161,11 @@ func doCopy(cpURLs copyURLs, progressReader *progressBar, accountingReader *acco
|
||||
// Set up progress reader.
|
||||
progress = progressReader.ProgressBar
|
||||
}
|
||||
_, err = putTargetStreamFromAlias(targetAlias, targetURL.String(), reader, length, progress)
|
||||
if err != nil {
|
||||
cpURLs.Error = err.Trace(targetURL.String())
|
||||
return cpURLs
|
||||
}
|
||||
cpURLs.Error = nil // just for safety
|
||||
return cpURLs
|
||||
return uploadSourceToTargetURL(cpURLs, progress)
|
||||
}
|
||||
|
||||
// doCopyFake - Perform a fake copy to update the progress bar appropriately.
|
||||
func doCopyFake(cpURLs copyURLs, progressReader *progressBar) copyURLs {
|
||||
func doCopyFake(cpURLs URLs, progressReader *progressBar) URLs {
|
||||
if !globalQuiet && !globalJSON {
|
||||
progressReader.ProgressBar.Add64(cpURLs.SourceContent.Size)
|
||||
}
|
||||
@@ -183,14 +173,14 @@ func doCopyFake(cpURLs copyURLs, progressReader *progressBar) copyURLs {
|
||||
}
|
||||
|
||||
// doPrepareCopyURLs scans the source URL and prepares a list of objects for copying.
|
||||
func doPrepareCopyURLs(session *sessionV6, trapCh <-chan bool) {
|
||||
func doPrepareCopyURLs(session *sessionV8, trapCh <-chan bool) {
|
||||
// Separate source and target. 'cp' can take only one target,
|
||||
// but any number of sources.
|
||||
sourceURLs := session.Header.CommandArgs[:len(session.Header.CommandArgs)-1]
|
||||
targetURL := session.Header.CommandArgs[len(session.Header.CommandArgs)-1] // Last one is target
|
||||
|
||||
var totalBytes int64
|
||||
var totalObjects int
|
||||
var totalObjects int64
|
||||
|
||||
// Access recursive flag inside the session header.
|
||||
isRecursive := session.Header.CommandBoolFlags["recursive"]
|
||||
@@ -205,8 +195,7 @@ func doPrepareCopyURLs(session *sessionV6, trapCh <-chan bool) {
|
||||
|
||||
URLsCh := prepareCopyURLs(sourceURLs, targetURL, isRecursive)
|
||||
done := false
|
||||
|
||||
for done == false {
|
||||
for !done {
|
||||
select {
|
||||
case cpURLs, ok := <-URLsCh:
|
||||
if !ok { // Done with URL preparation
|
||||
@@ -252,8 +241,8 @@ func doPrepareCopyURLs(session *sessionV6, trapCh <-chan bool) {
|
||||
session.Save()
|
||||
}
|
||||
|
||||
func doCopySession(session *sessionV6) {
|
||||
trapCh := signalTrap(os.Interrupt, syscall.SIGTERM)
|
||||
func doCopySession(session *sessionV8) {
|
||||
trapCh := signalTrap(os.Interrupt, syscall.SIGTERM, syscall.SIGKILL)
|
||||
|
||||
if !session.HasData() {
|
||||
doPrepareCopyURLs(session, trapCh)
|
||||
@@ -266,7 +255,7 @@ func doCopySession(session *sessionV6) {
|
||||
urlScanner := bufio.NewScanner(session.NewDataReader())
|
||||
// isCopied returns true if an object has been already copied
|
||||
// or not. This is useful when we resume from a session.
|
||||
isCopied := isCopiedFactory(session.Header.LastCopied)
|
||||
isCopied := isLastFactory(session.Header.LastCopied)
|
||||
|
||||
// Enable progress bar reader only during default mode.
|
||||
var progressReader *progressBar
|
||||
@@ -275,7 +264,7 @@ func doCopySession(session *sessionV6) {
|
||||
}
|
||||
|
||||
// Wait on status of doCopy() operation.
|
||||
var statusCh = make(chan copyURLs)
|
||||
var statusCh = make(chan URLs)
|
||||
|
||||
// Add a wait group.
|
||||
var wg = new(sync.WaitGroup)
|
||||
@@ -308,22 +297,7 @@ func doCopySession(session *sessionV6) {
|
||||
}
|
||||
errorIf(cpURLs.Error.Trace(cpURLs.SourceContent.URL.String()),
|
||||
fmt.Sprintf("Failed to copy ‘%s’.", cpURLs.SourceContent.URL.String()))
|
||||
// For all non critical errors we can continue for the
|
||||
// remaining files.
|
||||
switch cpURLs.Error.ToGoError().(type) {
|
||||
// Handle this specifically for filesystem related
|
||||
// errors.
|
||||
case client.BrokenSymlink:
|
||||
continue
|
||||
case client.TooManyLevelsSymlink:
|
||||
continue
|
||||
case client.PathNotFound:
|
||||
continue
|
||||
case client.PathInsufficientPermission:
|
||||
continue
|
||||
case client.ObjectAlreadyExists:
|
||||
continue
|
||||
case client.BucketDoesNotExist:
|
||||
if isErrIgnored(cpURLs.Error) {
|
||||
continue
|
||||
}
|
||||
// For critical errors we should exit. Session
|
||||
@@ -337,10 +311,16 @@ func doCopySession(session *sessionV6) {
|
||||
|
||||
// Loop through all urls.
|
||||
for urlScanner.Scan() {
|
||||
var cpURLs copyURLs
|
||||
var cpURLs URLs
|
||||
// Unmarshal copyURLs from each line.
|
||||
json.Unmarshal([]byte(urlScanner.Text()), &cpURLs)
|
||||
|
||||
// Save total count.
|
||||
cpURLs.TotalCount = session.Header.TotalObjects
|
||||
|
||||
// Save totalSize.
|
||||
cpURLs.TotalSize = session.Header.TotalBytes
|
||||
|
||||
// Verify if previously copied, notify progress bar.
|
||||
if isCopied(cpURLs.SourceContent.URL.String()) {
|
||||
statusCh <- doCopyFake(cpURLs, progressReader)
|
||||
@@ -356,24 +336,24 @@ func doCopySession(session *sessionV6) {
|
||||
wg.Wait()
|
||||
|
||||
if !globalQuiet && !globalJSON {
|
||||
if progressReader.ProgressBar.Total > 0 {
|
||||
if progressReader.ProgressBar.Get() > 0 {
|
||||
progressReader.ProgressBar.Finish()
|
||||
}
|
||||
} else {
|
||||
accntStat := accntReader.Stat()
|
||||
cpStatMessage := copyStatMessage{
|
||||
Total: accntStat.Total,
|
||||
Transferred: accntStat.Transferred,
|
||||
Speed: accntStat.Speed,
|
||||
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", cpStatMessage.String()))
|
||||
}
|
||||
}
|
||||
|
||||
// mainCopy is the entry point for cp command.
|
||||
func mainCopy(ctx *cli.Context) {
|
||||
// Set global flags from context.
|
||||
setGlobalsFromContext(ctx)
|
||||
func mainCopy(ctx *cli.Context) error {
|
||||
|
||||
// check 'copy' cli arguments.
|
||||
checkCopySyntax(ctx)
|
||||
@@ -381,7 +361,7 @@ func mainCopy(ctx *cli.Context) {
|
||||
// Additional command speific theme customization.
|
||||
console.SetColor("Copy", color.New(color.FgGreen, color.Bold))
|
||||
|
||||
session := newSessionV6()
|
||||
session := newSessionV8()
|
||||
session.Header.CommandType = "cp"
|
||||
session.Header.CommandBoolFlags["recursive"] = ctx.Bool("recursive")
|
||||
|
||||
@@ -395,4 +375,6 @@ func mainCopy(ctx *cli.Context) {
|
||||
session.Header.CommandArgs = ctx.Args()
|
||||
doCopySession(session)
|
||||
session.Delete()
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -14,13 +14,12 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/client"
|
||||
)
|
||||
|
||||
func checkCopySyntax(ctx *cli.Context) {
|
||||
@@ -39,14 +38,19 @@ func checkCopySyntax(ctx *cli.Context) {
|
||||
isRecursive := ctx.Bool("recursive")
|
||||
|
||||
/****** Generic Invalid Rules *******/
|
||||
// Verify if source(s) exists.
|
||||
for _, srcURL := range srcURLs {
|
||||
_, _, err := url2Stat(srcURL)
|
||||
if err != nil {
|
||||
fatalIf(err.Trace(srcURL), fmt.Sprintf("Unable to stat '%s'.", srcURL))
|
||||
}
|
||||
}
|
||||
|
||||
// Check if bucket name is passed for URL type arguments.
|
||||
url := client.NewURL(tgtURL)
|
||||
url := newClientURL(tgtURL)
|
||||
if url.Host != "" {
|
||||
// This check is for type URL.
|
||||
if !isURLVirtualHostStyle(url.Host) {
|
||||
if url.Path == string(url.Separator) {
|
||||
fatalIf(errInvalidArgument().Trace(), fmt.Sprintf("Target ‘%s’ does not contain bucket name.", tgtURL))
|
||||
}
|
||||
if url.Path == string(url.Separator) {
|
||||
fatalIf(errInvalidArgument().Trace(), fmt.Sprintf("Target ‘%s’ does not contain bucket name.", tgtURL))
|
||||
}
|
||||
}
|
||||
|
||||
+43
-50
@@ -14,24 +14,15 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/minio/mc/pkg/client"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
type copyURLs struct {
|
||||
SourceAlias string
|
||||
SourceContent *client.Content
|
||||
TargetAlias string
|
||||
TargetContent *client.Content
|
||||
Error *probe.Error `json:"-"`
|
||||
}
|
||||
|
||||
type copyURLsType uint8
|
||||
|
||||
// NOTE: All the parse rules should reduced to A: Copy(Source, Target).
|
||||
@@ -57,7 +48,7 @@ const (
|
||||
copyURLsTypeD
|
||||
)
|
||||
|
||||
// guessCopyURLType guesses the type of URL. This approach all allows prepareURL
|
||||
// guessCopyURLType guesses the type of clientURL. This approach all allows prepareURL
|
||||
// functions to accurately report failure causes.
|
||||
func guessCopyURLType(sourceURLs []string, targetURL string, isRecursive bool) (copyURLsType, *probe.Error) {
|
||||
if len(sourceURLs) == 1 { // 1 Source, 1 Target
|
||||
@@ -90,25 +81,25 @@ func guessCopyURLType(sourceURLs []string, targetURL string, isRecursive bool) (
|
||||
}
|
||||
|
||||
// SINGLE SOURCE - Type A: copy(f, f) -> copy(f, f)
|
||||
// prepareCopyURLsTypeA - prepares target and source URLs for copying.
|
||||
func prepareCopyURLsTypeA(sourceURL string, targetURL string) copyURLs {
|
||||
// Extract alias before fiddling with the URL.
|
||||
// prepareCopyURLsTypeA - prepares target and source clientURLs for copying.
|
||||
func prepareCopyURLsTypeA(sourceURL string, targetURL string) URLs {
|
||||
// Extract alias before fiddling with the clientURL.
|
||||
sourceAlias, _, _ := mustExpandAlias(sourceURL)
|
||||
// Find alias and expanded URL.
|
||||
// Find alias and expanded clientURL.
|
||||
targetAlias, targetURL, _ := mustExpandAlias(targetURL)
|
||||
|
||||
_, sourceContent, err := url2Stat(sourceURL)
|
||||
if err != nil {
|
||||
// Source does not exist or insufficient privileges.
|
||||
return copyURLs{Error: err.Trace(sourceURL)}
|
||||
return URLs{Error: err.Trace(sourceURL)}
|
||||
}
|
||||
if !sourceContent.Type.IsRegular() {
|
||||
// Source is not a regular file
|
||||
return copyURLs{Error: errInvalidSource(sourceURL).Trace(sourceURL)}
|
||||
return URLs{Error: errInvalidSource(sourceURL).Trace(sourceURL)}
|
||||
}
|
||||
if sourceContent.URL.String() == targetURL {
|
||||
// source and target can not be same
|
||||
return copyURLs{Error: errSourceTargetSame(sourceURL).Trace(sourceURL)}
|
||||
return URLs{Error: errSourceTargetSame(sourceURL).Trace(sourceURL)}
|
||||
}
|
||||
|
||||
// All OK.. We can proceed. Type A
|
||||
@@ -116,35 +107,35 @@ func prepareCopyURLsTypeA(sourceURL string, targetURL string) copyURLs {
|
||||
}
|
||||
|
||||
// prepareCopyContentTypeA - makes CopyURLs content for copying.
|
||||
func makeCopyContentTypeA(sourceAlias string, sourceContent *client.Content, targetAlias string, targetURL string) copyURLs {
|
||||
return copyURLs{
|
||||
func makeCopyContentTypeA(sourceAlias string, sourceContent *clientContent, targetAlias string, targetURL string) URLs {
|
||||
return URLs{
|
||||
SourceAlias: sourceAlias,
|
||||
SourceContent: sourceContent,
|
||||
TargetAlias: targetAlias,
|
||||
TargetContent: &client.Content{URL: *client.NewURL(targetURL)},
|
||||
TargetContent: &clientContent{URL: *newClientURL(targetURL)},
|
||||
}
|
||||
}
|
||||
|
||||
// SINGLE SOURCE - Type B: copy(f, d) -> copy(f, d/f) -> A
|
||||
// prepareCopyURLsTypeB - prepares target and source URLs for copying.
|
||||
func prepareCopyURLsTypeB(sourceURL string, targetURL string) copyURLs {
|
||||
// Extract alias before fiddling with the URL.
|
||||
// prepareCopyURLsTypeB - prepares target and source clientURLs for copying.
|
||||
func prepareCopyURLsTypeB(sourceURL string, targetURL string) URLs {
|
||||
// Extract alias before fiddling with the clientURL.
|
||||
sourceAlias, _, _ := mustExpandAlias(sourceURL)
|
||||
// Find alias and expanded URL.
|
||||
// Find alias and expanded clientURL.
|
||||
targetAlias, targetURL, _ := mustExpandAlias(targetURL)
|
||||
|
||||
_, sourceContent, err := url2Stat(sourceURL)
|
||||
if err != nil {
|
||||
// Source does not exist or insufficient privileges.
|
||||
return copyURLs{Error: err.Trace(sourceURL)}
|
||||
return URLs{Error: err.Trace(sourceURL)}
|
||||
}
|
||||
|
||||
if !sourceContent.Type.IsRegular() {
|
||||
if sourceContent.Type.IsDir() {
|
||||
return copyURLs{Error: errSourceIsDir(sourceURL).Trace(sourceURL)}
|
||||
return URLs{Error: errSourceIsDir(sourceURL).Trace(sourceURL)}
|
||||
}
|
||||
// Source is not a regular file.
|
||||
return copyURLs{Error: errInvalidSource(sourceURL).Trace(sourceURL)}
|
||||
return URLs{Error: errInvalidSource(sourceURL).Trace(sourceURL)}
|
||||
}
|
||||
|
||||
// All OK.. We can proceed. Type B: source is a file, target is a folder and exists.
|
||||
@@ -152,35 +143,36 @@ func prepareCopyURLsTypeB(sourceURL string, targetURL string) copyURLs {
|
||||
}
|
||||
|
||||
// makeCopyContentTypeB - CopyURLs content for copying.
|
||||
func makeCopyContentTypeB(sourceAlias string, sourceContent *client.Content, targetAlias string, targetURL string) copyURLs {
|
||||
func makeCopyContentTypeB(sourceAlias string, sourceContent *clientContent, targetAlias string, targetURL string) URLs {
|
||||
// All OK.. We can proceed. Type B: source is a file, target is a folder and exists.
|
||||
targetURLParse := client.NewURL(targetURL)
|
||||
targetURLParse := newClientURL(targetURL)
|
||||
targetURLParse.Path = filepath.ToSlash(filepath.Join(targetURLParse.Path, filepath.Base(sourceContent.URL.Path)))
|
||||
return makeCopyContentTypeA(sourceAlias, sourceContent, targetAlias, targetURLParse.String())
|
||||
}
|
||||
|
||||
// SINGLE SOURCE - Type C: copy(d1..., d2) -> []copy(d1/f, d1/d2/f) -> []A
|
||||
// prepareCopyRecursiveURLTypeC - prepares target and source URLs for copying.
|
||||
func prepareCopyURLsTypeC(sourceURL, targetURL string, isRecursive bool) <-chan copyURLs {
|
||||
// Extract alias before fiddling with the URL.
|
||||
// prepareCopyRecursiveURLTypeC - prepares target and source clientURLs for copying.
|
||||
func prepareCopyURLsTypeC(sourceURL, targetURL string, isRecursive bool) <-chan URLs {
|
||||
// Extract alias before fiddling with the clientURL.
|
||||
sourceAlias, _, _ := mustExpandAlias(sourceURL)
|
||||
// Find alias and expanded URL.
|
||||
// Find alias and expanded clientURL.
|
||||
targetAlias, targetURL, _ := mustExpandAlias(targetURL)
|
||||
|
||||
copyURLsCh := make(chan copyURLs)
|
||||
go func(sourceURL, targetURL string, copyURLsCh chan copyURLs) {
|
||||
copyURLsCh := make(chan URLs)
|
||||
go func(sourceURL, targetURL string, copyURLsCh chan URLs) {
|
||||
defer close(copyURLsCh)
|
||||
sourceClient, err := newClient(sourceURL)
|
||||
if err != nil {
|
||||
// Source initialization failed.
|
||||
copyURLsCh <- copyURLs{Error: err.Trace(sourceURL)}
|
||||
copyURLsCh <- URLs{Error: err.Trace(sourceURL)}
|
||||
return
|
||||
}
|
||||
|
||||
for sourceContent := range sourceClient.List(isRecursive, false) {
|
||||
isIncomplete := false
|
||||
for sourceContent := range sourceClient.List(isRecursive, isIncomplete, DirNone) {
|
||||
if sourceContent.Err != nil {
|
||||
// Listing failed.
|
||||
copyURLsCh <- copyURLs{Error: sourceContent.Err.Trace(sourceClient.GetURL().String())}
|
||||
copyURLsCh <- URLs{Error: sourceContent.Err.Trace(sourceClient.GetURL().String())}
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -197,7 +189,7 @@ func prepareCopyURLsTypeC(sourceURL, targetURL string, isRecursive bool) <-chan
|
||||
}
|
||||
|
||||
// makeCopyContentTypeC - CopyURLs content for copying.
|
||||
func makeCopyContentTypeC(sourceAlias string, sourceURL client.URL, sourceContent *client.Content, targetAlias string, targetURL string) copyURLs {
|
||||
func makeCopyContentTypeC(sourceAlias string, sourceURL clientURL, sourceContent *clientContent, targetAlias string, targetURL string) URLs {
|
||||
newSourceURL := sourceContent.URL
|
||||
pathSeparatorIndex := strings.LastIndex(sourceURL.Path, string(sourceURL.Separator))
|
||||
newSourceSuffix := filepath.ToSlash(newSourceURL.Path)
|
||||
@@ -210,10 +202,10 @@ func makeCopyContentTypeC(sourceAlias string, sourceURL client.URL, sourceConten
|
||||
}
|
||||
|
||||
// MULTI-SOURCE - Type D: copy([](f|d...), d) -> []B
|
||||
// prepareCopyURLsTypeE - prepares target and source URLs for copying.
|
||||
func prepareCopyURLsTypeD(sourceURLs []string, targetURL string, isRecursive bool) <-chan copyURLs {
|
||||
copyURLsCh := make(chan copyURLs)
|
||||
go func(sourceURLs []string, targetURL string, copyURLsCh chan copyURLs) {
|
||||
// prepareCopyURLsTypeE - prepares target and source clientURLs for copying.
|
||||
func prepareCopyURLsTypeD(sourceURLs []string, targetURL string, isRecursive bool) <-chan URLs {
|
||||
copyURLsCh := make(chan URLs)
|
||||
go func(sourceURLs []string, targetURL string, copyURLsCh chan URLs) {
|
||||
defer close(copyURLsCh)
|
||||
for _, sourceURL := range sourceURLs {
|
||||
for cpURLs := range prepareCopyURLsTypeC(sourceURL, targetURL, isRecursive) {
|
||||
@@ -224,13 +216,14 @@ func prepareCopyURLsTypeD(sourceURLs []string, targetURL string, isRecursive boo
|
||||
return copyURLsCh
|
||||
}
|
||||
|
||||
// prepareCopyURLs - prepares target and source URLs for copying.
|
||||
func prepareCopyURLs(sourceURLs []string, targetURL string, isRecursive bool) <-chan copyURLs {
|
||||
copyURLsCh := make(chan copyURLs)
|
||||
go func(sourceURLs []string, targetURL string, copyURLsCh chan copyURLs) {
|
||||
// prepareCopyURLs - prepares target and source clientURLs for copying.
|
||||
func prepareCopyURLs(sourceURLs []string, targetURL string, isRecursive bool) <-chan URLs {
|
||||
copyURLsCh := make(chan URLs)
|
||||
go func(sourceURLs []string, targetURL string, copyURLsCh chan URLs) {
|
||||
defer close(copyURLsCh)
|
||||
cpType, err := guessCopyURLType(sourceURLs, targetURL, isRecursive)
|
||||
fatalIf(err.Trace(), "Unable to guess the type of copy operation.")
|
||||
|
||||
switch cpType {
|
||||
case copyURLsTypeA:
|
||||
copyURLsCh <- prepareCopyURLsTypeA(sourceURLs[0], targetURL)
|
||||
@@ -245,7 +238,7 @@ func prepareCopyURLs(sourceURLs []string, targetURL string, isRecursive bool) <-
|
||||
copyURLsCh <- cURLs
|
||||
}
|
||||
default:
|
||||
copyURLsCh <- copyURLs{Error: errInvalidArgument().Trace(sourceURLs...)}
|
||||
copyURLsCh <- URLs{Error: errInvalidArgument().Trace(sourceURLs...)}
|
||||
}
|
||||
}(sourceURLs, targetURL, copyURLsCh)
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"math"
|
||||
@@ -34,6 +34,7 @@ func minimum(integers []int) (minVal int) {
|
||||
// DamerauLevenshteinDistance calculates distance between two strings using an algorithm
|
||||
// described in https://en.wikipedia.org/wiki/Damerau-Levenshtein_distance
|
||||
func DamerauLevenshteinDistance(a string, b string) int {
|
||||
var cost int
|
||||
d := make([][]int, len(a)+1)
|
||||
for i := 1; i <= len(a)+1; i++ {
|
||||
d[i-1] = make([]int, len(b)+1)
|
||||
@@ -46,7 +47,6 @@ func DamerauLevenshteinDistance(a string, b string) int {
|
||||
}
|
||||
for i := 1; i <= len(a); i++ {
|
||||
for j := 1; j <= len(b); j++ {
|
||||
cost := 0
|
||||
if a[i-1] == b[j-1] {
|
||||
cost = 0
|
||||
} else {
|
||||
@@ -14,7 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
@@ -23,27 +23,22 @@ import (
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/client"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
// diff specific flags.
|
||||
var (
|
||||
diffFlags = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "help, h",
|
||||
Usage: "Help of diff.",
|
||||
},
|
||||
}
|
||||
diffFlags = []cli.Flag{}
|
||||
)
|
||||
|
||||
// Compute differences between two files or folders.
|
||||
var diffCmd = cli.Command{
|
||||
Name: "diff",
|
||||
Usage: "Compute differences between two folders.",
|
||||
Usage: "Show differences between two folders or buckets.",
|
||||
Description: "Diff only lists missing objects or objects with size differences. It *DOES NOT* compare contents. i.e. Objects of same name and size, but differ in contents are not noticed.",
|
||||
Action: mainDiff,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(diffFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
mc {{.Name}} - {{.Usage}}
|
||||
@@ -68,24 +63,29 @@ EXAMPLES:
|
||||
|
||||
// diffMessage json container for diff messages
|
||||
type diffMessage struct {
|
||||
Status string `json:"status"`
|
||||
FirstURL string `json:"first"`
|
||||
SecondURL string `json:"second"`
|
||||
Diff string `json:"diff"`
|
||||
Error *probe.Error `json:"error,omitempty"`
|
||||
Status string `json:"status"`
|
||||
FirstURL string `json:"first"`
|
||||
SecondURL string `json:"second"`
|
||||
Diff differType `json:"diff"`
|
||||
Error *probe.Error `json:"error,omitempty"`
|
||||
firstContent *clientContent
|
||||
secondContent *clientContent
|
||||
}
|
||||
|
||||
// String colorized diff message
|
||||
func (d diffMessage) String() string {
|
||||
msg := ""
|
||||
switch d.Diff {
|
||||
case "only-in-first":
|
||||
case differInFirst:
|
||||
msg = console.Colorize("DiffMessage",
|
||||
"‘"+d.FirstURL+"’"+" and "+"‘"+d.SecondURL+"’") + console.Colorize("DiffOnlyInFirst", " - only in first.")
|
||||
case "type":
|
||||
"‘"+d.FirstURL+"’") + console.Colorize("DiffOnlyInFirst", " - only in first.")
|
||||
case differInSecond:
|
||||
msg = console.Colorize("DiffMessage",
|
||||
"‘"+d.SecondURL+"’") + console.Colorize("DiffOnlyInSecond", " - only in second.")
|
||||
case differInType:
|
||||
msg = console.Colorize("DiffMessage",
|
||||
"‘"+d.FirstURL+"’"+" and "+"‘"+d.SecondURL+"’") + console.Colorize("DiffType", " - differ in type.")
|
||||
case "size":
|
||||
case differInSize:
|
||||
msg = console.Colorize("DiffMessage",
|
||||
"‘"+d.FirstURL+"’"+" and "+"‘"+d.SecondURL+"’") + console.Colorize("DiffSize", " - differ in size.")
|
||||
default:
|
||||
@@ -101,7 +101,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 ‘"+d.Diff+"’.")
|
||||
"Unable to marshal diff message ‘"+d.FirstURL+"’, ‘"+d.SecondURL+"’ and ‘"+string(d.Diff)+"’.")
|
||||
return string(diffJSONBytes)
|
||||
}
|
||||
|
||||
@@ -125,6 +125,7 @@ func checkDiffSyntax(ctx *cli.Context) {
|
||||
if err != nil {
|
||||
fatalIf(err.Trace(firstURL), fmt.Sprintf("Unable to stat '%s'.", firstURL))
|
||||
}
|
||||
|
||||
// Verify if its a directory.
|
||||
if !firstContent.Type.IsDir() {
|
||||
fatalIf(errInvalidArgument().Trace(firstURL), fmt.Sprintf("‘%s’ is not a folder.", firstURL))
|
||||
@@ -135,6 +136,7 @@ func checkDiffSyntax(ctx *cli.Context) {
|
||||
if err != nil {
|
||||
fatalIf(err.Trace(secondURL), fmt.Sprintf("Unable to stat '%s'.", secondURL))
|
||||
}
|
||||
|
||||
// Verify if its a directory.
|
||||
if !secondContent.Type.IsDir() {
|
||||
fatalIf(errInvalidArgument().Trace(secondURL), fmt.Sprintf("‘%s’ is not a folder.", secondURL))
|
||||
@@ -142,13 +144,13 @@ func checkDiffSyntax(ctx *cli.Context) {
|
||||
}
|
||||
|
||||
// doDiffMain runs the diff.
|
||||
func doDiffMain(firstURL, secondURL string) {
|
||||
func doDiffMain(firstURL, secondURL string) error {
|
||||
// Source and targets are always directories
|
||||
sourceSeparator := string(client.NewURL(firstURL).Separator)
|
||||
sourceSeparator := string(newClientURL(firstURL).Separator)
|
||||
if !strings.HasSuffix(firstURL, sourceSeparator) {
|
||||
firstURL = firstURL + sourceSeparator
|
||||
}
|
||||
targetSeparator := string(client.NewURL(secondURL).Separator)
|
||||
targetSeparator := string(newClientURL(secondURL).Separator)
|
||||
if !strings.HasSuffix(secondURL, targetSeparator) {
|
||||
secondURL = secondURL + targetSeparator
|
||||
}
|
||||
@@ -162,49 +164,23 @@ func doDiffMain(firstURL, secondURL string) {
|
||||
fatalIf(err.Trace(firstAlias, firstURL, secondAlias, secondURL),
|
||||
fmt.Sprintf("Failed to diff '%s' and '%s'", firstURL, secondURL))
|
||||
}
|
||||
difference, err := objectDifferenceFactory(secondAlias, secondURL)
|
||||
|
||||
secondClient, err := newClientFromAlias(secondAlias, secondURL)
|
||||
if err != nil {
|
||||
fatalIf(err.Trace(firstAlias, firstURL, secondAlias, secondURL),
|
||||
fmt.Sprintf("Failed to diff '%s' and '%s'", firstURL, secondURL))
|
||||
}
|
||||
isRecursive := true
|
||||
isIncomplete := false
|
||||
for sourceContent := range firstClient.List(isRecursive, isIncomplete) {
|
||||
if sourceContent.Err != nil {
|
||||
switch sourceContent.Err.ToGoError().(type) {
|
||||
// Handle this specifically for filesystem related errors.
|
||||
case client.BrokenSymlink, client.TooManyLevelsSymlink, client.PathNotFound, client.PathInsufficientPermission:
|
||||
errorIf(sourceContent.Err.Trace(firstURL, secondURL), fmt.Sprintf("Failed on '%s'", firstURL))
|
||||
default:
|
||||
fatalIf(sourceContent.Err.Trace(firstURL, secondURL), fmt.Sprintf("Failed on '%s'", firstURL))
|
||||
}
|
||||
continue
|
||||
}
|
||||
if sourceContent.Type.IsDir() {
|
||||
continue
|
||||
}
|
||||
suffix := strings.TrimPrefix(sourceContent.URL.String(), firstURL)
|
||||
differ, err := difference(suffix, sourceContent.Type, sourceContent.Size)
|
||||
if err != nil {
|
||||
errorIf(sourceContent.Err.Trace(secondURL, suffix),
|
||||
fmt.Sprintf("Failed on '%s'", urlJoinPath(secondURL, suffix)))
|
||||
continue
|
||||
}
|
||||
if differ == differNone {
|
||||
continue
|
||||
}
|
||||
printMsg(diffMessage{
|
||||
FirstURL: sourceContent.URL.String(),
|
||||
SecondURL: urlJoinPath(secondURL, suffix),
|
||||
Diff: differ,
|
||||
})
|
||||
|
||||
// Diff first and second urls.
|
||||
for diffMsg := range objectDifference(firstClient, secondClient, firstURL, secondURL) {
|
||||
printMsg(diffMsg)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// mainDiff main for 'diff'.
|
||||
func mainDiff(ctx *cli.Context) {
|
||||
// Set global flags from context.
|
||||
setGlobalsFromContext(ctx)
|
||||
func mainDiff(ctx *cli.Context) error {
|
||||
|
||||
// check 'diff' cli arguments.
|
||||
checkDiffSyntax(ctx)
|
||||
@@ -214,10 +190,11 @@ func mainDiff(ctx *cli.Context) {
|
||||
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))
|
||||
|
||||
URLs := ctx.Args()
|
||||
firstURL := URLs[0]
|
||||
secondURL := URLs[1]
|
||||
firstURL := URLs.Get(0)
|
||||
secondURL := URLs.Get(1)
|
||||
|
||||
doDiffMain(firstURL, secondURL)
|
||||
return doDiffMain(firstURL, secondURL)
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
/*
|
||||
* 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 (
|
||||
"fmt"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"golang.org/x/text/unicode/norm"
|
||||
)
|
||||
|
||||
// differType difference in type.
|
||||
type differType int
|
||||
|
||||
const (
|
||||
differInNone differType = iota // does not differ
|
||||
differInSize // differs in size
|
||||
differInType // only in source
|
||||
differInFirst // only in target
|
||||
differInSecond // differs in type, exfile/directory
|
||||
)
|
||||
|
||||
func (d differType) String() string {
|
||||
switch d {
|
||||
case differInNone:
|
||||
return ""
|
||||
case differInSize:
|
||||
return "size"
|
||||
case differInType:
|
||||
return "type"
|
||||
case differInFirst:
|
||||
return "only-in-first"
|
||||
case differInSecond:
|
||||
return "only-in-second"
|
||||
}
|
||||
return "unknown"
|
||||
}
|
||||
|
||||
// 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) {
|
||||
var (
|
||||
srcEOF, tgtEOF bool
|
||||
srcOk, tgtOk bool
|
||||
srcCtnt, tgtCtnt *clientContent
|
||||
srcSuffix, tgtSuffix 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)
|
||||
|
||||
diffCh = make(chan diffMessage, 1000)
|
||||
|
||||
go func() {
|
||||
|
||||
srcCtnt, srcOk = <-srcCh
|
||||
tgtCtnt, tgtOk = <-tgtCh
|
||||
|
||||
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))
|
||||
srcCtnt, srcOk = <-srcCh
|
||||
continue
|
||||
}
|
||||
|
||||
if !tgtEOF && tgtCtnt.Err != nil {
|
||||
errorIf(tgtCtnt.Err.Trace(sourceURL, targetURL), fmt.Sprintf("Failed on '%s'", targetURL))
|
||||
tgtCtnt, tgtOk = <-tgtCh
|
||||
continue
|
||||
}
|
||||
|
||||
// If source doesn't have objects anymore, comparison becomes obvious
|
||||
if srcEOF {
|
||||
diffCh <- diffMessage{
|
||||
SecondURL: tgtCtnt.URL.String(),
|
||||
Diff: differInSecond,
|
||||
secondContent: tgtCtnt,
|
||||
}
|
||||
tgtCtnt, tgtOk = <-tgtCh
|
||||
continue
|
||||
}
|
||||
|
||||
// The same for target
|
||||
if tgtEOF {
|
||||
diffCh <- diffMessage{
|
||||
FirstURL: srcCtnt.URL.String(),
|
||||
Diff: differInFirst,
|
||||
firstContent: srcCtnt,
|
||||
}
|
||||
srcCtnt, srcOk = <-srcCh
|
||||
continue
|
||||
}
|
||||
|
||||
srcSuffix = strings.TrimPrefix(srcCtnt.URL.String(), sourceURL)
|
||||
tgtSuffix = strings.TrimPrefix(tgtCtnt.URL.String(), targetURL)
|
||||
|
||||
current := urlJoinPath(targetURL, srcSuffix)
|
||||
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))
|
||||
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))
|
||||
tgtCtnt, tgtOk = <-tgtCh
|
||||
continue
|
||||
}
|
||||
|
||||
// Normalize to avoid situations where multiple byte representations are possible.
|
||||
// e.g. 'ä' can be represented as precomposed U+00E4 (UTF-8 0xc3a4) or decomposed
|
||||
// U+0061 U+0308 (UTF-8 0x61cc88).
|
||||
normalizedCurrent := norm.NFC.String(current)
|
||||
normalizedExpected := norm.NFC.String(expected)
|
||||
|
||||
if normalizedExpected > normalizedCurrent {
|
||||
diffCh <- diffMessage{
|
||||
FirstURL: srcCtnt.URL.String(),
|
||||
Diff: differInFirst,
|
||||
firstContent: srcCtnt,
|
||||
}
|
||||
srcCtnt, srcOk = <-srcCh
|
||||
continue
|
||||
}
|
||||
if normalizedExpected == normalizedCurrent {
|
||||
srcType, tgtType := srcCtnt.Type, tgtCtnt.Type
|
||||
srcSize, tgtSize := srcCtnt.Size, tgtCtnt.Size
|
||||
if srcType.IsRegular() && !tgtType.IsRegular() ||
|
||||
!srcType.IsRegular() && tgtType.IsRegular() {
|
||||
// Type differes. Source is never a directory.
|
||||
diffCh <- diffMessage{
|
||||
FirstURL: srcCtnt.URL.String(),
|
||||
SecondURL: tgtCtnt.URL.String(),
|
||||
Diff: differInType,
|
||||
firstContent: srcCtnt,
|
||||
secondContent: tgtCtnt,
|
||||
}
|
||||
} else if (srcType.IsRegular() && tgtType.IsRegular()) && srcSize != tgtSize {
|
||||
// Regular files differing in size.
|
||||
diffCh <- diffMessage{
|
||||
FirstURL: srcCtnt.URL.String(),
|
||||
SecondURL: tgtCtnt.URL.String(),
|
||||
Diff: differInSize,
|
||||
firstContent: srcCtnt,
|
||||
secondContent: tgtCtnt,
|
||||
}
|
||||
}
|
||||
// No differ
|
||||
srcCtnt, srcOk = <-srcCh
|
||||
tgtCtnt, tgtOk = <-tgtCh
|
||||
continue
|
||||
}
|
||||
// Differ in second
|
||||
diffCh <- diffMessage{
|
||||
SecondURL: tgtCtnt.URL.String(),
|
||||
Diff: differInSecond,
|
||||
secondContent: tgtCtnt,
|
||||
}
|
||||
tgtCtnt, tgtOk = <-tgtCh
|
||||
continue
|
||||
}
|
||||
}()
|
||||
|
||||
return diffCh
|
||||
}
|
||||
+12
-2
@@ -14,14 +14,15 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
// causeMessage container for golang error messages
|
||||
@@ -76,6 +77,15 @@ func fatalIf(err *probe.Error, msg string) {
|
||||
console.Fatalln(fmt.Sprintf("%s %s", msg, err))
|
||||
}
|
||||
|
||||
// Exit coder wraps cli new exit error with a
|
||||
// custom exitStatus number. cli package requires
|
||||
// an error with `cli.ExitCoder` compatibility
|
||||
// after an action. Which woud allow cli package to
|
||||
// exit with the specified `exitStatus`.
|
||||
func exitStatus(status int) error {
|
||||
return cli.NewExitError("", status)
|
||||
}
|
||||
|
||||
// errorIf synonymous with fatalIf but doesn't exit on error != nil
|
||||
func errorIf(err *probe.Error, msg string) {
|
||||
if err == nil {
|
||||
@@ -0,0 +1,132 @@
|
||||
/*
|
||||
* 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"
|
||||
"strings"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
var (
|
||||
eventsAddFlags = []cli.Flag{
|
||||
cli.StringFlag{
|
||||
Name: "events",
|
||||
Value: "put,delete",
|
||||
Usage: "Filter specific type of events. Defaults to all events.",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "prefix",
|
||||
Usage: "Filter events associated to the specified prefix",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "suffix",
|
||||
Usage: "Filter events associated to the specified suffix",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
var eventsAddCmd = cli.Command{
|
||||
Name: "add",
|
||||
Usage: "Add a new bucket notification.",
|
||||
Action: mainEventsAdd,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(eventsAddFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
mc events {{.Name}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
mc events {{.Name}} ALIAS/BUCKET ARN [FLAGS]
|
||||
|
||||
FLAGS:
|
||||
{{range .Flags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Enable bucket notification with a specific arn
|
||||
$ mc events {{.Name}} 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
|
||||
`,
|
||||
}
|
||||
|
||||
// checkEventsAddSyntax - validate all the passed arguments
|
||||
func checkEventsAddSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) != 2 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "add", 1) // last argument is exit code
|
||||
}
|
||||
}
|
||||
|
||||
// eventsAddMessage container
|
||||
type eventsAddMessage struct {
|
||||
ARN string `json:"arn"`
|
||||
Events []string `json:"events"`
|
||||
Prefix string `json:"prefix"`
|
||||
Suffix string `json:"suffix"`
|
||||
Status string `json:"status"`
|
||||
}
|
||||
|
||||
// JSON jsonified update message.
|
||||
func (u eventsAddMessage) JSON() string {
|
||||
u.Status = "success"
|
||||
eventsAddMessageJSONBytes, e := json.Marshal(u)
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
return string(eventsAddMessageJSONBytes)
|
||||
}
|
||||
|
||||
func (u eventsAddMessage) String() string {
|
||||
msg := console.Colorize("Events", "Successfully added "+u.ARN)
|
||||
return msg
|
||||
}
|
||||
|
||||
func mainEventsAdd(ctx *cli.Context) error {
|
||||
console.SetColor("Events", color.New(color.FgGreen, color.Bold))
|
||||
|
||||
checkEventsAddSyntax(ctx)
|
||||
|
||||
args := ctx.Args()
|
||||
path := args[0]
|
||||
arn := args[1]
|
||||
|
||||
events := strings.Split(ctx.String("events"), ",")
|
||||
prefix := ctx.String("prefix")
|
||||
suffix := ctx.String("suffix")
|
||||
|
||||
client, err := newClient(path)
|
||||
if err != nil {
|
||||
fatalIf(err.Trace(), "Cannot parse the provided url.")
|
||||
}
|
||||
|
||||
s3Client, ok := client.(*s3Client)
|
||||
if !ok {
|
||||
fatalIf(errDummy().Trace(), "The provided url doesn't point to a S3 server.")
|
||||
}
|
||||
|
||||
err = s3Client.AddNotificationConfig(arn, events, prefix, suffix)
|
||||
fatalIf(err, "Cannot enable notification on the specified bucket.")
|
||||
printMsg(eventsAddMessage{
|
||||
ARN: arn,
|
||||
Events: events,
|
||||
Prefix: prefix,
|
||||
Suffix: suffix,
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
/*
|
||||
* 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"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
var (
|
||||
eventsListFlags = []cli.Flag{}
|
||||
)
|
||||
|
||||
var eventsListCmd = cli.Command{
|
||||
Name: "list",
|
||||
Usage: "List bucket notifications.",
|
||||
Action: mainEventsList,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(eventsListFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
mc events {{.Name}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
mc events {{.Name}} ALIAS/BUCKET ARN [FLAGS]
|
||||
|
||||
FLAGS:
|
||||
{{range .Flags}}{{.}}
|
||||
{{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
|
||||
2. List all notification configurations
|
||||
$ mc events {{.Name}} s3/mybucket
|
||||
`,
|
||||
}
|
||||
|
||||
// checkEventsListSyntax - validate all the passed arguments
|
||||
func checkEventsListSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) != 2 && len(ctx.Args()) != 1 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "list", 1) // last argument is exit code
|
||||
}
|
||||
}
|
||||
|
||||
// eventsListMessage container
|
||||
type eventsListMessage struct {
|
||||
Status string `json:"status"`
|
||||
ID string `json:"id"`
|
||||
Events []string `json:"events"`
|
||||
Prefix string `json:"prefix"`
|
||||
Suffix string `json:"suffix"`
|
||||
Arn string `json:"arn"`
|
||||
}
|
||||
|
||||
func (u eventsListMessage) JSON() string {
|
||||
u.Status = "success"
|
||||
eventsListMessageJSONBytes, e := json.Marshal(u)
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
return string(eventsListMessageJSONBytes)
|
||||
}
|
||||
|
||||
func (u eventsListMessage) String() string {
|
||||
msg := console.Colorize("ARN", fmt.Sprintf("%s ", u.Arn))
|
||||
for i, event := range u.Events {
|
||||
msg += console.Colorize("Events", event)
|
||||
if i != len(u.Events)-1 {
|
||||
msg += ","
|
||||
}
|
||||
}
|
||||
msg += console.Colorize("Filter", fmt.Sprintf(" Filter: "))
|
||||
if u.Prefix != "" {
|
||||
msg += console.Colorize("Filter", fmt.Sprintf("prefix=\"%s\"", u.Prefix))
|
||||
}
|
||||
if u.Suffix != "" {
|
||||
msg += console.Colorize("Filter", fmt.Sprintf("suffix=\"%s\"", u.Suffix))
|
||||
}
|
||||
return msg
|
||||
}
|
||||
|
||||
func mainEventsList(ctx *cli.Context) error {
|
||||
console.SetColor("ARN", color.New(color.FgGreen, color.Bold))
|
||||
console.SetColor("Events", color.New(color.FgCyan, color.Bold))
|
||||
console.SetColor("Filter", color.New(color.Bold))
|
||||
|
||||
checkEventsListSyntax(ctx)
|
||||
|
||||
args := ctx.Args()
|
||||
path := args[0]
|
||||
arn := ""
|
||||
if len(args) > 1 {
|
||||
arn = args[1]
|
||||
}
|
||||
|
||||
client, err := newClient(path)
|
||||
if err != nil {
|
||||
fatalIf(err.Trace(), "Cannot parse the provided url.")
|
||||
}
|
||||
|
||||
s3Client, ok := client.(*s3Client)
|
||||
if !ok {
|
||||
fatalIf(errDummy().Trace(), "The provided url doesn't point to a S3 server.")
|
||||
}
|
||||
|
||||
configs, err := s3Client.ListNotificationConfigs(arn)
|
||||
fatalIf(err, "Cannot enable notification on the specified bucket.")
|
||||
|
||||
for _, config := range configs {
|
||||
printMsg(eventsListMessage{Events: config.Events,
|
||||
Prefix: config.Prefix,
|
||||
Suffix: config.Suffix,
|
||||
Arn: config.Arn,
|
||||
ID: config.ID})
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
/*
|
||||
* 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 "github.com/minio/cli"
|
||||
|
||||
var (
|
||||
eventsFlags = []cli.Flag{}
|
||||
)
|
||||
|
||||
var eventsCmd = cli.Command{
|
||||
Name: "events",
|
||||
Usage: "Manage object notifications.",
|
||||
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)
|
||||
}
|
||||
|
||||
return nil
|
||||
// Sub-commands like "add", "remove", "list" have their own main.
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
/*
|
||||
* 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"
|
||||
"errors"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
var (
|
||||
eventsRemoveFlags = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "force",
|
||||
Usage: "Force removing all bucket notifications",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
var eventsRemoveCmd = cli.Command{
|
||||
Name: "remove",
|
||||
Usage: "Remove a bucket notification. With '--force' can remove all bucket notifications.",
|
||||
Action: mainEventsRemove,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(eventsRemoveFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
mc events {{.Name}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
mc events {{.Name}} ALIAS/BUCKET [ARN] [FLAGS]
|
||||
|
||||
FLAGS:
|
||||
{{range .Flags}}{{.}}
|
||||
{{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
|
||||
2. Remove all bucket notifications. --force flag is mandatory here
|
||||
$ mc events {{.Name}} myminio/mybucket --force
|
||||
`,
|
||||
}
|
||||
|
||||
// checkEventsRemoveSyntax - validate all the passed arguments
|
||||
func checkEventsRemoveSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) == 0 || len(ctx.Args()) > 2 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "remove", 1) // last argument is exit code
|
||||
}
|
||||
if len(ctx.Args()) == 1 && !ctx.Bool("force") {
|
||||
fatalIf(probe.NewError(errors.New("")), "--force flag needs to be passed to remove all bucket notifications")
|
||||
}
|
||||
}
|
||||
|
||||
// eventsRemoveMessage container
|
||||
type eventsRemoveMessage struct {
|
||||
ARN string `json:"arn"`
|
||||
Status string `json:"status"`
|
||||
}
|
||||
|
||||
// JSON jsonified remove message.
|
||||
func (u eventsRemoveMessage) JSON() string {
|
||||
u.Status = "success"
|
||||
eventsRemoveMessageJSONBytes, e := json.Marshal(u)
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
return string(eventsRemoveMessageJSONBytes)
|
||||
}
|
||||
|
||||
func (u eventsRemoveMessage) String() string {
|
||||
msg := console.Colorize("Events", "Successfully removed "+u.ARN)
|
||||
return msg
|
||||
}
|
||||
|
||||
func mainEventsRemove(ctx *cli.Context) error {
|
||||
console.SetColor("Events", color.New(color.FgGreen, color.Bold))
|
||||
|
||||
checkEventsRemoveSyntax(ctx)
|
||||
|
||||
args := ctx.Args()
|
||||
path := args.Get(0)
|
||||
|
||||
arn := ""
|
||||
if len(args) == 2 {
|
||||
arn = args.Get(1)
|
||||
}
|
||||
|
||||
client, err := newClient(path)
|
||||
if err != nil {
|
||||
fatalIf(err.Trace(), "Cannot parse the provided url.")
|
||||
}
|
||||
|
||||
s3Client, ok := client.(*s3Client)
|
||||
if !ok {
|
||||
fatalIf(errDummy().Trace(), "The provided url doesn't point to a S3 server.")
|
||||
}
|
||||
|
||||
err = s3Client.RemoveNotificationConfig(arn)
|
||||
fatalIf(err, "Cannot enable notification on the specified bucket.")
|
||||
printMsg(eventsRemoveMessage{ARN: arn})
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -14,7 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
package cmd
|
||||
|
||||
import "github.com/minio/cli"
|
||||
|
||||
@@ -41,11 +41,15 @@ var globalFlags = []cli.Flag{
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "json",
|
||||
Usage: "Enable json formatted output.",
|
||||
Usage: "Enable JSON formatted output.",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "debug",
|
||||
Usage: "Enable debugging output.",
|
||||
Usage: "Enable debug output.",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "insecure",
|
||||
Usage: "Disable SSL certificate verification.",
|
||||
},
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package fs
|
||||
package cmd
|
||||
|
||||
func normalizePath(path string) string {
|
||||
return path
|
||||
@@ -16,7 +16,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package fs
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
@@ -0,0 +1,98 @@
|
||||
/*
|
||||
* 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 contains all the global variables and constants. ONLY TO BE ACCESSED VIA GET/SET FUNCTIONS.
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"crypto/x509"
|
||||
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
)
|
||||
|
||||
// mc configuration related constants.
|
||||
const (
|
||||
minGoVersion = ">= 1.7.1" // mc requires at least Go v1.7.1
|
||||
)
|
||||
|
||||
const (
|
||||
globalMCConfigVersion = "8"
|
||||
|
||||
globalMCConfigDir = ".mc/"
|
||||
globalMCConfigWindowsDir = "mc\\"
|
||||
globalMCConfigFile = "config.json"
|
||||
globalMCCertsDir = "certs"
|
||||
globalMCCAsDir = "CAs"
|
||||
|
||||
// session config and shared urls related constants
|
||||
globalSessionDir = "session"
|
||||
globalSharedURLsDataDir = "share"
|
||||
globalSessionConfigVersion = "8"
|
||||
|
||||
// Profile directory for dumping profiler outputs.
|
||||
globalProfileDir = "profile"
|
||||
|
||||
// Global error exit status.
|
||||
globalErrorExitStatus = 1
|
||||
|
||||
// Maximum size for a single PUT operation.
|
||||
globalMaximumPutSize = 5 * 1024 * 1024 * 1024 // 5GiB.
|
||||
)
|
||||
|
||||
var (
|
||||
globalQuiet = false // Quiet flag set via command line
|
||||
globalJSON = false // Json flag set via command line
|
||||
globalDebug = false // Debug flag set via command line
|
||||
globalNoColor = false // No Color flag set via command line
|
||||
globalInsecure = false // Insecure flag set via command line
|
||||
// WHEN YOU ADD NEXT GLOBAL FLAG, MAKE SURE TO ALSO UPDATE SESSION CODE AND CODE BELOW.
|
||||
)
|
||||
|
||||
var (
|
||||
// CA root certificates, a nil value means system certs pool will be used
|
||||
globalRootCAs *x509.CertPool
|
||||
)
|
||||
|
||||
// Set global states. NOTE: It is deliberately kept monolithic to ensure we dont miss out any flags.
|
||||
func setGlobals(quiet, debug, json, noColor, insecure bool) {
|
||||
globalQuiet = globalQuiet || quiet
|
||||
globalDebug = globalDebug || debug
|
||||
globalJSON = globalJSON || json
|
||||
globalNoColor = globalNoColor || noColor
|
||||
globalInsecure = globalInsecure || insecure
|
||||
|
||||
// Enable debug messages if requested.
|
||||
if globalDebug {
|
||||
console.DebugPrint = true
|
||||
}
|
||||
|
||||
// Disable colorified messages if requested.
|
||||
if globalNoColor {
|
||||
console.SetColorOff()
|
||||
}
|
||||
}
|
||||
|
||||
// Set global states. NOTE: It is deliberately kept monolithic to ensure we dont miss out any flags.
|
||||
func setGlobalsFromContext(ctx *cli.Context) error {
|
||||
quiet := ctx.IsSet("quiet")
|
||||
debug := ctx.IsSet("debug")
|
||||
json := ctx.IsSet("json")
|
||||
noColor := ctx.IsSet("no-color")
|
||||
insecure := ctx.IsSet("insecure")
|
||||
setGlobals(quiet, debug, json, noColor, insecure)
|
||||
return nil
|
||||
}
|
||||
+32
-18
@@ -14,31 +14,26 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/client"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
)
|
||||
|
||||
// ls specific flags.
|
||||
var (
|
||||
lsFlags = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "help, h",
|
||||
Usage: "Help of ls.",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "recursive, r",
|
||||
Usage: "List recursively.",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "incomplete, I",
|
||||
Usage: "Remove incomplete uploads.",
|
||||
Usage: "List incomplete uploads.",
|
||||
},
|
||||
}
|
||||
)
|
||||
@@ -48,6 +43,7 @@ var lsCmd = cli.Command{
|
||||
Name: "ls",
|
||||
Usage: "List files and folders.",
|
||||
Action: mainList,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(lsFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
mc {{.Name}} - {{.Usage}}
|
||||
@@ -97,22 +93,24 @@ func checkListSyntax(ctx *cli.Context) {
|
||||
for _, url := range URLs {
|
||||
_, _, err := url2Stat(url)
|
||||
if err != nil && !isURLPrefixExists(url, isIncomplete) {
|
||||
// Bucket name empty is a valid error for 'ls myminio',
|
||||
// treat it as such.
|
||||
if _, ok := err.ToGoError().(BucketNameEmpty); ok {
|
||||
continue
|
||||
}
|
||||
fatalIf(err.Trace(url), "Unable to stat ‘"+url+"’.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// mainList - is a handler for mc ls command
|
||||
func mainList(ctx *cli.Context) {
|
||||
// Additional command speific theme customization.
|
||||
console.SetColor("File", color.New(color.FgWhite))
|
||||
func mainList(ctx *cli.Context) error {
|
||||
// Additional command specific theme customization.
|
||||
console.SetColor("File", color.New(color.Bold))
|
||||
console.SetColor("Dir", color.New(color.FgCyan, color.Bold))
|
||||
console.SetColor("Size", color.New(color.FgYellow))
|
||||
console.SetColor("Time", color.New(color.FgGreen))
|
||||
|
||||
// Set global flags from context.
|
||||
setGlobalsFromContext(ctx)
|
||||
|
||||
// check 'ls' cli arguments.
|
||||
checkListSyntax(ctx)
|
||||
|
||||
@@ -126,15 +124,31 @@ func mainList(ctx *cli.Context) {
|
||||
args = []string{"."}
|
||||
}
|
||||
|
||||
var cErr error
|
||||
for _, targetURL := range args {
|
||||
var clnt client.Client
|
||||
var clnt Client
|
||||
clnt, err := newClient(targetURL)
|
||||
fatalIf(err.Trace(targetURL), "Unable to initialize target ‘"+targetURL+"’.")
|
||||
|
||||
err = doList(clnt, isRecursive, isIncomplete)
|
||||
if err != nil {
|
||||
errorIf(err.Trace(clnt.GetURL().String()), "Unable to list target ‘"+clnt.GetURL().String()+"’.")
|
||||
continue
|
||||
var st *clientContent
|
||||
if st, err = clnt.Stat(isIncomplete); err != nil {
|
||||
switch err.ToGoError().(type) {
|
||||
case BucketNameEmpty:
|
||||
// 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+"’.")
|
||||
}
|
||||
} 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+"’.")
|
||||
}
|
||||
if e := doList(clnt, isRecursive, isIncomplete); e != nil {
|
||||
cErr = e
|
||||
}
|
||||
}
|
||||
return cErr
|
||||
}
|
||||
+15
-11
@@ -14,7 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
@@ -25,9 +25,8 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/dustin/go-humanize"
|
||||
"github.com/minio/mc/pkg/client"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
// printDate - human friendly formatted date.
|
||||
@@ -67,7 +66,7 @@ func (c contentMessage) JSON() string {
|
||||
}
|
||||
|
||||
// parseContent parse client Content container into printer struct.
|
||||
func parseContent(c *client.Content) contentMessage {
|
||||
func parseContent(c *clientContent) contentMessage {
|
||||
content := contentMessage{}
|
||||
content.Time = c.Time.Local()
|
||||
|
||||
@@ -105,30 +104,35 @@ func parseContent(c *client.Content) contentMessage {
|
||||
}
|
||||
|
||||
// doList - list all entities inside a folder.
|
||||
func doList(clnt client.Client, isRecursive, isIncomplete bool) *probe.Error {
|
||||
func doList(clnt Client, isRecursive, isIncomplete bool) error {
|
||||
prefixPath := clnt.GetURL().Path
|
||||
separator := string(clnt.GetURL().Separator)
|
||||
if !strings.HasSuffix(prefixPath, separator) {
|
||||
prefixPath = prefixPath[:strings.LastIndex(prefixPath, separator)+1]
|
||||
}
|
||||
for content := range clnt.List(isRecursive, isIncomplete) {
|
||||
var cErr error
|
||||
for content := range clnt.List(isRecursive, isIncomplete, DirNone) {
|
||||
if content.Err != nil {
|
||||
switch content.Err.ToGoError().(type) {
|
||||
// handle this specifically for filesystem related errors.
|
||||
case client.BrokenSymlink:
|
||||
case BrokenSymlink:
|
||||
errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list broken link.")
|
||||
continue
|
||||
case client.TooManyLevelsSymlink:
|
||||
case TooManyLevelsSymlink:
|
||||
errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list too many levels link.")
|
||||
continue
|
||||
case client.PathNotFound:
|
||||
case PathNotFound:
|
||||
errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list folder.")
|
||||
continue
|
||||
case client.PathInsufficientPermission:
|
||||
case PathInsufficientPermission:
|
||||
errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list folder.")
|
||||
continue
|
||||
case ObjectOnGlacier:
|
||||
errorIf(content.Err.Trace(clnt.GetURL().String()), "")
|
||||
continue
|
||||
}
|
||||
errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list folder.")
|
||||
cErr = exitStatus(globalErrorExitStatus) // Set the exit status.
|
||||
continue
|
||||
}
|
||||
// Convert any os specific delimiters to "/".
|
||||
@@ -142,5 +146,5 @@ func doList(clnt client.Client, isRecursive, isIncomplete bool) *probe.Error {
|
||||
// Print colorized or jsonized content info.
|
||||
printMsg(parsedContent)
|
||||
}
|
||||
return nil
|
||||
return cErr
|
||||
}
|
||||
@@ -14,4 +14,4 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
package cmd
|
||||
+294
@@ -0,0 +1,294 @@
|
||||
/*
|
||||
* Minio Client (C) 2014, 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/cheggaaa/pb"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
"github.com/pkg/profile"
|
||||
)
|
||||
|
||||
var (
|
||||
// global flags for mc.
|
||||
mcFlags = []cli.Flag{}
|
||||
)
|
||||
|
||||
// Help template for mc
|
||||
var mcHelpTemplate = `NAME:
|
||||
{{.Name}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.Name}} {{if .Flags}}[FLAGS] {{end}}COMMAND{{if .Flags}} [COMMAND FLAGS | -h]{{end}} [ARGUMENTS...]
|
||||
|
||||
COMMANDS:
|
||||
{{range .Commands}}{{join .Names ", "}}{{ "\t" }}{{.Usage}}
|
||||
{{end}}{{if .Flags}}
|
||||
GLOBAL FLAGS:
|
||||
{{range .Flags}}{{.}}
|
||||
{{end}}{{end}}
|
||||
VERSION:
|
||||
` + Version +
|
||||
`{{ "\n"}}{{range $key, $value := ExtraInfo}}
|
||||
{{$key}}:
|
||||
{{$value}}
|
||||
{{end}}`
|
||||
|
||||
// Main starts mc application
|
||||
func Main() {
|
||||
// Enable profiling supported modes are [cpu, mem, block].
|
||||
// ``MC_PROFILER`` supported options are [cpu, mem, block].
|
||||
switch os.Getenv("MC_PROFILER") {
|
||||
case "cpu":
|
||||
defer profile.Start(profile.CPUProfile, profile.ProfilePath(mustGetProfileDir())).Stop()
|
||||
case "mem":
|
||||
defer profile.Start(profile.MemProfile, profile.ProfilePath(mustGetProfileDir())).Stop()
|
||||
case "block":
|
||||
defer profile.Start(profile.BlockProfile, profile.ProfilePath(mustGetProfileDir())).Stop()
|
||||
}
|
||||
|
||||
probe.Init() // Set project's root source path.
|
||||
probe.SetAppInfo("Release-Tag", ReleaseTag)
|
||||
probe.SetAppInfo("Commit", ShortCommitID)
|
||||
|
||||
app := registerApp()
|
||||
app.Before = registerBefore
|
||||
app.ExtraInfo = func() map[string]string {
|
||||
if _, e := pb.GetTerminalWidth(); e != nil {
|
||||
globalQuiet = true
|
||||
}
|
||||
if globalDebug {
|
||||
return getSystemData()
|
||||
}
|
||||
return make(map[string]string)
|
||||
}
|
||||
app.RunAndExitOnError()
|
||||
}
|
||||
|
||||
// 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)
|
||||
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)
|
||||
} else {
|
||||
for _, cmd := range closestCommands {
|
||||
msg += fmt.Sprintf(" ‘%s’\n", cmd)
|
||||
}
|
||||
}
|
||||
}
|
||||
fatalIf(errDummy().Trace(), msg)
|
||||
}
|
||||
|
||||
// Check for sane config environment early on and gracefully report.
|
||||
func checkConfig() {
|
||||
// Refresh the config once.
|
||||
loadMcConfig = loadMcConfigFactory()
|
||||
// Ensures config file is sane.
|
||||
config, err := loadMcConfig()
|
||||
// Verify if the path is accesible before validating the config
|
||||
fatalIf(err.Trace(mustGetMcConfigPath()), "Unable to access configuration file.")
|
||||
|
||||
// Validate and print error messges
|
||||
ok, errMsgs := validateConfigFile(config)
|
||||
if !ok {
|
||||
var errorMsg bytes.Buffer
|
||||
for index, errMsg := range errMsgs {
|
||||
// Print atmost 10 errors
|
||||
if index > 10 {
|
||||
break
|
||||
}
|
||||
errorMsg.WriteString(errMsg + "\n")
|
||||
}
|
||||
console.Fatalln(errorMsg.String())
|
||||
}
|
||||
}
|
||||
|
||||
func migrate() {
|
||||
// Fix broken config files if any.
|
||||
fixConfig()
|
||||
|
||||
// Migrate config files if any.
|
||||
migrateConfig()
|
||||
|
||||
// Migrate session files if any.
|
||||
migrateSession()
|
||||
|
||||
// Migrate shared urls if any.
|
||||
migrateShare()
|
||||
}
|
||||
|
||||
// Get os/arch/platform specific information.
|
||||
// Returns a map of current os/arch/platform/memstats.
|
||||
func getSystemData() map[string]string {
|
||||
host, e := os.Hostname()
|
||||
fatalIf(probe.NewError(e), "Unable to determine the hostname.")
|
||||
|
||||
memstats := &runtime.MemStats{}
|
||||
runtime.ReadMemStats(memstats)
|
||||
mem := fmt.Sprintf("Used: %s | Allocated: %s | UsedHeap: %s | AllocatedHeap: %s",
|
||||
pb.Format(int64(memstats.Alloc)).To(pb.U_BYTES),
|
||||
pb.Format(int64(memstats.TotalAlloc)).To(pb.U_BYTES),
|
||||
pb.Format(int64(memstats.HeapAlloc)).To(pb.U_BYTES),
|
||||
pb.Format(int64(memstats.HeapSys)).To(pb.U_BYTES))
|
||||
platform := fmt.Sprintf("Host: %s | OS: %s | Arch: %s", host, runtime.GOOS, runtime.GOARCH)
|
||||
goruntime := fmt.Sprintf("Version: %s | CPUs: %s", runtime.Version(), strconv.Itoa(runtime.NumCPU()))
|
||||
return map[string]string{
|
||||
"PLATFORM": platform,
|
||||
"RUNTIME": goruntime,
|
||||
"MEM": mem,
|
||||
}
|
||||
}
|
||||
|
||||
// initMC - initialize 'mc'.
|
||||
func initMC() {
|
||||
// Check if mc config exists.
|
||||
if !isMcConfigExists() {
|
||||
err := saveMcConfig(newMcConfig())
|
||||
fatalIf(err.Trace(), "Unable to save new mc config.")
|
||||
|
||||
console.Infoln("Configuration written to ‘" + mustGetMcConfigPath() + "’. Please update your access credentials.")
|
||||
}
|
||||
|
||||
// Check if mc session folder exists.
|
||||
if !isSessionDirExists() {
|
||||
fatalIf(createSessionDir().Trace(), "Unable to create session config folder.")
|
||||
}
|
||||
|
||||
// Check if mc share folder exists.
|
||||
if !isShareDirExists() {
|
||||
initShareConfig()
|
||||
}
|
||||
|
||||
// Check if certs dir exists
|
||||
if !isCertsDirExists() {
|
||||
fatalIf(createCertsDir().Trace(), "Unable to create `CAs` folder.")
|
||||
}
|
||||
|
||||
// Check if CAs dir exists
|
||||
if !isCAsDirExists() {
|
||||
fatalIf(createCAsDir().Trace(), "Unable to create `CAs` folder.")
|
||||
}
|
||||
|
||||
// Load all authority certificates present in CAs dir
|
||||
loadRootCAs()
|
||||
}
|
||||
|
||||
func registerBefore(ctx *cli.Context) error {
|
||||
// Check if mc was compiled using a supported version of Golang.
|
||||
checkGoVersion()
|
||||
|
||||
// Set the config folder.
|
||||
setMcConfigDir(ctx.GlobalString("config-folder"))
|
||||
|
||||
// Migrate any old version of config / state files to newer format.
|
||||
migrate()
|
||||
|
||||
// Initialize default config files.
|
||||
initMC()
|
||||
|
||||
// Set global flags.
|
||||
setGlobalsFromContext(ctx)
|
||||
|
||||
// Check if config can be read.
|
||||
checkConfig()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// findClosestCommands to match a given string with commands trie tree.
|
||||
func findClosestCommands(command string) []string {
|
||||
var closestCommands []string
|
||||
for _, value := range commandsTree.PrefixMatch(command) {
|
||||
closestCommands = append(closestCommands, value.(string))
|
||||
}
|
||||
sort.Strings(closestCommands)
|
||||
// Suggest other close commands - allow missed, wrongly added and even transposed characters
|
||||
for _, value := range commandsTree.walk(commandsTree.root) {
|
||||
if sort.SearchStrings(closestCommands, value.(string)) < len(closestCommands) {
|
||||
continue
|
||||
}
|
||||
// 2 is arbitrary and represents the max allowed number of typed errors
|
||||
if DamerauLevenshteinDistance(command, value.(string)) < 2 {
|
||||
closestCommands = append(closestCommands, value.(string))
|
||||
}
|
||||
}
|
||||
return closestCommands
|
||||
}
|
||||
|
||||
func registerApp() *cli.App {
|
||||
// Register all the commands (refer flags.go)
|
||||
registerCmd(lsCmd) // List contents of a bucket.
|
||||
registerCmd(mbCmd) // Make a bucket.
|
||||
registerCmd(catCmd) // Display contents of a file.
|
||||
registerCmd(pipeCmd) // Write contents of stdin to a file.
|
||||
registerCmd(shareCmd) // Share documents via URL.
|
||||
registerCmd(cpCmd) // Copy objects and files from multiple sources to single destination.
|
||||
registerCmd(mirrorCmd) // Mirror objects and files from single source to multiple destinations.
|
||||
registerCmd(diffCmd) // Computer differences between two files or folders.
|
||||
registerCmd(rmCmd) // Remove a file or bucket
|
||||
registerCmd(eventsCmd) // Add events cmd
|
||||
registerCmd(watchCmd) // Add watch cmd
|
||||
registerCmd(policyCmd) // Set policy permissions.
|
||||
// registerCmd(adminCmd) // Manage Minio servers
|
||||
registerCmd(sessionCmd) // Manage sessions for copy and mirror.
|
||||
registerCmd(configCmd) // Configure minio client.
|
||||
registerCmd(updateCmd) // Check for new software updates.
|
||||
registerCmd(versionCmd) // Print version.
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
cli.ShowAppHelp(ctx)
|
||||
}
|
||||
app.Usage = "Minio Client for cloud storage and filesystems."
|
||||
app.Commands = commands
|
||||
app.Author = "Minio.io"
|
||||
app.Version = Version
|
||||
app.Flags = append(mcFlags, globalFlags...)
|
||||
app.CustomAppHelpTemplate = mcHelpTemplate
|
||||
app.CommandNotFound = commandNotFound // handler function declared above.
|
||||
return app
|
||||
}
|
||||
|
||||
// mustGetProfilePath must get location that the profile will be written to.
|
||||
func mustGetProfileDir() string {
|
||||
return filepath.Join(mustGetMcConfigDir(), globalProfileDir)
|
||||
}
|
||||
+30
-23
@@ -14,7 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
@@ -22,15 +22,11 @@ import (
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
var (
|
||||
mbFlags = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "help, h",
|
||||
Usage: "Help of mb.",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "region",
|
||||
Value: "us-east-1",
|
||||
@@ -42,8 +38,9 @@ var (
|
||||
// make a bucket or folder.
|
||||
var mbCmd = cli.Command{
|
||||
Name: "mb",
|
||||
Usage: "Make a bucket or folder.",
|
||||
Usage: "Make a bucket or a folder.",
|
||||
Action: mainMakeBucket,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(mbFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
mc {{.Name}} - {{.Usage}}
|
||||
@@ -66,6 +63,9 @@ EXAMPLES:
|
||||
|
||||
5. Create a new directory including its missing parents (equivalent to ‘mkdir -p’).
|
||||
$ mc {{.Name}} /tmp/this/new/dir1
|
||||
|
||||
6. Create multiple directories including its missing parents (behavior similar to ‘mkdir -p’).
|
||||
$ mc {{.Name}} /mnt/sdb/mydisk /mnt/sdc/mydisk /mnt/sdd/mydisk
|
||||
`,
|
||||
}
|
||||
|
||||
@@ -94,15 +94,10 @@ func checkMakeBucketSyntax(ctx *cli.Context) {
|
||||
if !ctx.Args().Present() {
|
||||
cli.ShowCommandHelpAndExit(ctx, "mb", 1) // last argument is exit code
|
||||
}
|
||||
if len(ctx.Args()) != 1 {
|
||||
fatalIf(errInvalidArgument().Trace(ctx.Args()...), "Incorrect number of arguments for mb command.")
|
||||
}
|
||||
}
|
||||
|
||||
// mainMakeBucket is entry point for mb command.
|
||||
func mainMakeBucket(ctx *cli.Context) {
|
||||
// Set global flags from context.
|
||||
setGlobalsFromContext(ctx)
|
||||
func mainMakeBucket(ctx *cli.Context) error {
|
||||
|
||||
// check 'mb' cli arguments.
|
||||
checkMakeBucketSyntax(ctx)
|
||||
@@ -110,18 +105,30 @@ func mainMakeBucket(ctx *cli.Context) {
|
||||
// Additional command speific theme customization.
|
||||
console.SetColor("MakeBucket", color.New(color.FgGreen, color.Bold))
|
||||
|
||||
// save region.
|
||||
// Save region.
|
||||
region := ctx.String("region")
|
||||
|
||||
targetURL := ctx.Args().First()
|
||||
// Instantiate client for URL.
|
||||
clnt, err := newClient(targetURL)
|
||||
fatalIf(err.Trace(targetURL), "Invalid target ‘"+targetURL+"’.")
|
||||
var cErr error
|
||||
for i := range ctx.Args() {
|
||||
targetURL := ctx.Args().Get(i)
|
||||
// Instantiate client for URL.
|
||||
clnt, err := newClient(targetURL)
|
||||
if err != nil {
|
||||
errorIf(err.Trace(targetURL), "Invalid target ‘"+targetURL+"’.")
|
||||
cErr = exitStatus(globalErrorExitStatus)
|
||||
continue
|
||||
}
|
||||
|
||||
// Make bucket.
|
||||
err = clnt.MakeBucket(region)
|
||||
fatalIf(err.Trace(targetURL), "Unable to make bucket ‘"+targetURL+"’.")
|
||||
// Make bucket.
|
||||
err = clnt.MakeBucket(region)
|
||||
if err != nil {
|
||||
errorIf(err.Trace(targetURL), "Unable to make bucket ‘"+targetURL+"’.")
|
||||
cErr = exitStatus(globalErrorExitStatus)
|
||||
continue
|
||||
}
|
||||
|
||||
// Successfully created a bucket.
|
||||
printMsg(makeBucketMessage{Status: "success", Bucket: targetURL})
|
||||
// Successfully created a bucket.
|
||||
printMsg(makeBucketMessage{Status: "success", Bucket: targetURL})
|
||||
}
|
||||
return cErr
|
||||
}
|
||||
+17
-23
@@ -14,7 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
@@ -24,6 +24,7 @@ import (
|
||||
|
||||
"net/http/httptest"
|
||||
|
||||
"github.com/hashicorp/go-version"
|
||||
"github.com/minio/cli"
|
||||
. "gopkg.in/check.v1"
|
||||
)
|
||||
@@ -46,18 +47,18 @@ func (s *TestSuite) TearDownSuite(c *C) {
|
||||
}
|
||||
|
||||
func (s *TestSuite) TestValidPERMS(c *C) {
|
||||
perms := accessPerms("private")
|
||||
perms := accessPerms("none")
|
||||
c.Assert(perms.isValidAccessPERM(), Equals, true)
|
||||
c.Assert(perms.String(), Equals, "private")
|
||||
c.Assert(string(perms), Equals, "none")
|
||||
perms = accessPerms("public")
|
||||
c.Assert(perms.isValidAccessPERM(), Equals, true)
|
||||
c.Assert(perms.String(), Equals, "public-read-write")
|
||||
perms = accessPerms("readonly")
|
||||
c.Assert(string(perms), Equals, "public")
|
||||
perms = accessPerms("download")
|
||||
c.Assert(perms.isValidAccessPERM(), Equals, true)
|
||||
c.Assert(perms.String(), Equals, "public-read")
|
||||
perms = accessPerms("authorized")
|
||||
c.Assert(string(perms), Equals, "download")
|
||||
perms = accessPerms("upload")
|
||||
c.Assert(perms.isValidAccessPERM(), Equals, true)
|
||||
c.Assert(perms.String(), Equals, "authenticated-read")
|
||||
c.Assert(string(perms), Equals, "upload")
|
||||
}
|
||||
|
||||
func (s *TestSuite) TestInvalidPERMS(c *C) {
|
||||
@@ -76,11 +77,7 @@ func (s *TestSuite) TestGetMcConfigPath(c *C) {
|
||||
dir, err := getMcConfigPath()
|
||||
c.Assert(err, IsNil)
|
||||
switch runtime.GOOS {
|
||||
case "linux":
|
||||
fallthrough
|
||||
case "freebsd":
|
||||
fallthrough
|
||||
case "darwin":
|
||||
case "linux", "freebsd", "darwin", "solaris":
|
||||
c.Assert(dir, Equals, filepath.Join(mustGetMcConfigDir(), "config.json"))
|
||||
case "windows":
|
||||
c.Assert(dir, Equals, filepath.Join(mustGetMcConfigDir(), "config.json"))
|
||||
@@ -118,15 +115,12 @@ func (s *TestSuite) TestHumanizedTime(c *C) {
|
||||
c.Assert(hTime.Days, Not(Equals), int64(0))
|
||||
}
|
||||
|
||||
func (s *TestSuite) TestCommonPrefix(c *C) {
|
||||
c.Assert(commonPrefix("/usr", "/usr/local"), Equals, "/usr")
|
||||
c.Assert(commonPrefix("/uabbf", "/ursfad/ccc"), Equals, "/u")
|
||||
c.Assert(commonPrefix("/usr/local/lib", "/usr/local/test"), Equals, "/usr/local/")
|
||||
}
|
||||
|
||||
func (s *TestSuite) TestVersions(c *C) {
|
||||
v1 := newVersion("1.5.1")
|
||||
v2 := newVersion("1.5.0")
|
||||
c.Assert(v2.LessThan(v1), Equals, true)
|
||||
c.Assert(v1.LessThan(v2), Equals, false)
|
||||
v1, e := version.NewVersion("1.7.1")
|
||||
v2, e := version.NewVersion("1.6.3")
|
||||
c.Assert(e, IsNil)
|
||||
constraint, e := version.NewConstraint(">= 1.7.1")
|
||||
c.Assert(e, IsNil)
|
||||
c.Assert(constraint.Check(v1), Equals, true)
|
||||
c.Assert(constraint.Check(v2), Equals, false)
|
||||
}
|
||||
@@ -0,0 +1,537 @@
|
||||
/*
|
||||
* Minio Client, (C) 2015, 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"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/cheggaaa/pb"
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
// mirror specific flags.
|
||||
var (
|
||||
mirrorFlags = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "force",
|
||||
Usage: "Force overwrite of an existing target(s).",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "fake",
|
||||
Usage: "Perform a fake mirror operation.",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "watch, w",
|
||||
Usage: "Watch and mirror for changes.",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "remove",
|
||||
Usage: "Remove extraneous file(s) on target.",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
// Mirror folders recursively from a single source to many destinations
|
||||
var mirrorCmd = cli.Command{
|
||||
Name: "mirror",
|
||||
Usage: "Mirror buckets and folders.",
|
||||
Action: mainMirror,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(mirrorFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
mc {{.Name}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
mc {{.Name}} [FLAGS] SOURCE TARGET
|
||||
|
||||
FLAGS:
|
||||
{{range .Flags}}{{.}}
|
||||
{{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
|
||||
|
||||
2. Mirror a local folder recursively to Amazon S3 cloud storage.
|
||||
$ mc {{.Name}} backup/ s3/archive
|
||||
|
||||
3. Mirror a bucket from aliased Amazon S3 cloud storage to a folder on Windows.
|
||||
$ mc {{.Name}} s3\documents\2014\ C:\backup\2014
|
||||
|
||||
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
|
||||
|
||||
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
|
||||
|
||||
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
|
||||
`,
|
||||
}
|
||||
|
||||
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
|
||||
|
||||
// channel for errors
|
||||
errorCh chan *probe.Error
|
||||
|
||||
// Contains if watcher is currently running.
|
||||
watcherRunning bool
|
||||
|
||||
// the global watcher object, which receives notifications of created
|
||||
// and deleted files
|
||||
watcher *Watcher
|
||||
|
||||
// Hold operation status information
|
||||
status Status
|
||||
scanBar scanBarFunc
|
||||
|
||||
// waitgroup for status goroutine, waits till all status
|
||||
// messages have been written and received
|
||||
wgStatus *sync.WaitGroup
|
||||
// channel for status messages
|
||||
statusCh chan URLs
|
||||
|
||||
TotalObjects int64
|
||||
TotalBytes int64
|
||||
|
||||
sourceURL string
|
||||
targetURL string
|
||||
}
|
||||
|
||||
// mirrorMessage container for file mirror messages
|
||||
type mirrorMessage struct {
|
||||
Status string `json:"status"`
|
||||
Source string `json:"source"`
|
||||
Target string `json:"target"`
|
||||
Size int64 `json:"size"`
|
||||
TotalCount int64 `json:"totalCount"`
|
||||
TotalSize int64 `json:"totalSize"`
|
||||
}
|
||||
|
||||
// String colorized mirror message
|
||||
func (m mirrorMessage) String() string {
|
||||
return console.Colorize("Mirror", fmt.Sprintf("‘%s’ -> ‘%s’", m.Source, m.Target))
|
||||
}
|
||||
|
||||
// JSON jsonified mirror message
|
||||
func (m mirrorMessage) JSON() string {
|
||||
m.Status = "success"
|
||||
mirrorMessageBytes, e := json.Marshal(m)
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
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 {
|
||||
return sURLs.WithError(nil)
|
||||
}
|
||||
|
||||
// We are not removing incomplete uploads.
|
||||
isIncomplete := false
|
||||
|
||||
// Construct proper path with alias.
|
||||
targetWithAlias := filepath.Join(sURLs.TargetAlias, sURLs.TargetContent.URL.Path)
|
||||
|
||||
// Remove extraneous file on target.
|
||||
err := probe.NewError(removeSingle(targetWithAlias, isIncomplete, 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())
|
||||
}
|
||||
|
||||
//s For a fake mirror make sure we update respective progress bars
|
||||
// and accounting readers under relevant conditions.
|
||||
if isFake {
|
||||
mj.status.Add(sURLs.SourceContent.Size)
|
||||
return sURLs.WithError(nil)
|
||||
}
|
||||
|
||||
sourceAlias := sURLs.SourceAlias
|
||||
sourceURL := sURLs.SourceContent.URL
|
||||
targetAlias := sURLs.TargetAlias
|
||||
targetURL := sURLs.TargetContent.URL
|
||||
length := sURLs.SourceContent.Size
|
||||
|
||||
mj.status.SetCaption(sourceURL.String() + ": ")
|
||||
|
||||
sourcePath := filepath.ToSlash(filepath.Join(sourceAlias, sourceURL.Path))
|
||||
targetPath := filepath.ToSlash(filepath.Join(targetAlias, targetURL.Path))
|
||||
mj.status.PrintMsg(mirrorMessage{
|
||||
Source: sourcePath,
|
||||
Target: targetPath,
|
||||
Size: length,
|
||||
TotalCount: sURLs.TotalCount,
|
||||
TotalSize: sURLs.TotalSize,
|
||||
})
|
||||
return uploadSourceToTargetURL(sURLs, mj.status)
|
||||
}
|
||||
|
||||
// Go routine to update progress status
|
||||
func (mj *mirrorJob) startStatus() {
|
||||
mj.wgStatus.Add(1)
|
||||
|
||||
// wait for status messages on statusChan, show error messages
|
||||
go func() {
|
||||
// now we want to start the progress bar
|
||||
mj.status.Start()
|
||||
defer mj.status.Finish()
|
||||
defer mj.wgStatus.Done()
|
||||
|
||||
for sURLs := range mj.statusCh {
|
||||
if sURLs.Error != nil {
|
||||
// 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()))
|
||||
} 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()))
|
||||
}
|
||||
}
|
||||
|
||||
if sURLs.SourceContent != nil {
|
||||
} else if sURLs.TargetContent != nil {
|
||||
// Construct user facing message and path.
|
||||
targetPath := filepath.ToSlash(filepath.Join(sURLs.TargetAlias, sURLs.TargetContent.URL.Path))
|
||||
mj.status.PrintMsg(rmMessage{Key: targetPath})
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// 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 {
|
||||
case event, ok := <-mj.watcher.Events():
|
||||
if !ok {
|
||||
// channel closed
|
||||
return
|
||||
}
|
||||
|
||||
// It will change the expanded alias back to the alias
|
||||
// again, by replacing the sourceUrlFull with the sourceAlias.
|
||||
// This url will be used to mirror.
|
||||
sourceAlias, sourceURLFull, _ := mustExpandAlias(mj.sourceURL)
|
||||
|
||||
// If the passed source URL points to fs, fetch the absolute src path
|
||||
// to correctly calculate targetPath
|
||||
if sourceAlias == "" {
|
||||
tmpSrcURL, err := filepath.Abs(sourceURLFull)
|
||||
if err == nil {
|
||||
sourceURLFull = tmpSrcURL
|
||||
}
|
||||
}
|
||||
|
||||
sourceURL := newClientURL(event.Path)
|
||||
aliasedPath := strings.Replace(event.Path, sourceURLFull, mj.sourceURL, -1)
|
||||
|
||||
// build target path, it is the relative of the event.Path with the sourceUrl
|
||||
// joined to the targetURL.
|
||||
sourceSuffix := strings.TrimPrefix(event.Path, sourceURLFull)
|
||||
targetPath := urlJoinPath(mj.targetURL, sourceSuffix)
|
||||
|
||||
// newClient needs the unexpanded path, newCLientURL needs the expanded path
|
||||
targetAlias, expandedTargetPath, _ := mustExpandAlias(targetPath)
|
||||
targetURL := newClientURL(expandedTargetPath)
|
||||
|
||||
if event.Type == EventCreate {
|
||||
// we are checking if a destination file exists now, and if we only
|
||||
// overwrite it when force is enabled.
|
||||
mirrorURL := URLs{
|
||||
SourceAlias: sourceAlias,
|
||||
SourceContent: &clientContent{URL: *sourceURL},
|
||||
TargetAlias: targetAlias,
|
||||
TargetContent: &clientContent{URL: *targetURL},
|
||||
}
|
||||
if event.Size == 0 {
|
||||
sourceClient, err := newClient(aliasedPath)
|
||||
if err != nil {
|
||||
// cannot create sourceclient
|
||||
mj.statusCh <- mirrorURL.WithError(err)
|
||||
continue
|
||||
}
|
||||
sourceContent, err := sourceClient.Stat(false)
|
||||
if err != nil {
|
||||
// source doesn't exist anymore
|
||||
mj.statusCh <- mirrorURL.WithError(err)
|
||||
continue
|
||||
}
|
||||
targetClient, err := newClient(targetPath)
|
||||
if err != nil {
|
||||
// cannot create targetclient
|
||||
mj.statusCh <- mirrorURL.WithError(err)
|
||||
return
|
||||
}
|
||||
shouldQueue := false
|
||||
if !isForce {
|
||||
_, err = targetClient.Stat(false)
|
||||
if err == nil {
|
||||
continue
|
||||
} // doesn't exist
|
||||
shouldQueue = true
|
||||
}
|
||||
if shouldQueue || 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.
|
||||
mj.status.SetTotal(mj.status.Total() + sourceContent.Size).Update()
|
||||
mj.statusCh <- mj.doMirror(mirrorURL)
|
||||
}
|
||||
continue
|
||||
}
|
||||
shouldQueue := false
|
||||
if !isForce {
|
||||
targetClient, err := newClient(targetPath)
|
||||
if err != nil {
|
||||
// cannot create targetclient
|
||||
mj.statusCh <- mirrorURL.WithError(err)
|
||||
return
|
||||
}
|
||||
_, err = targetClient.Stat(false)
|
||||
if err == nil {
|
||||
continue
|
||||
} // doesn't exist
|
||||
shouldQueue = true
|
||||
}
|
||||
if shouldQueue || isForce {
|
||||
mirrorURL.SourceContent.Size = event.Size
|
||||
mirrorURL.TotalCount = mj.TotalObjects
|
||||
mirrorURL.TotalSize = mj.TotalBytes
|
||||
// adjust total, because we want to show progress of the itemj stiil queued to be copied.
|
||||
mj.status.SetTotal(mj.status.Total() + event.Size).Update()
|
||||
mj.statusCh <- mj.doMirror(mirrorURL)
|
||||
}
|
||||
} else if event.Type == EventRemove {
|
||||
mirrorURL := URLs{
|
||||
SourceAlias: sourceAlias,
|
||||
SourceContent: nil,
|
||||
TargetAlias: targetAlias,
|
||||
TargetContent: &clientContent{URL: *targetURL},
|
||||
}
|
||||
mirrorURL.TotalCount = mj.TotalObjects
|
||||
mirrorURL.TotalSize = mj.TotalBytes
|
||||
if mirrorURL.TargetContent != nil && isRemove && isForce {
|
||||
mj.statusCh <- mj.doRemove(mirrorURL)
|
||||
}
|
||||
}
|
||||
|
||||
case err := <-mj.watcher.Errors():
|
||||
switch err.ToGoError().(type) {
|
||||
case APINotImplemented:
|
||||
// Ignore error if API is not implemented.
|
||||
mj.watcherRunning = false
|
||||
return
|
||||
default:
|
||||
errorIf(err, "Unexpected error during monitoring.")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (mj *mirrorJob) watchSourceURL(recursive bool) *probe.Error {
|
||||
sourceClient, err := newClient(mj.sourceURL)
|
||||
if err == nil {
|
||||
return mj.watcher.Join(sourceClient, recursive)
|
||||
} // Failed to initialize client.
|
||||
return err
|
||||
}
|
||||
|
||||
// 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)
|
||||
for {
|
||||
select {
|
||||
case sURLs, ok := <-URLsCh:
|
||||
if !ok {
|
||||
// finished harvesting urls
|
||||
return
|
||||
}
|
||||
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.")
|
||||
} else {
|
||||
mj.status.errorIf(sURLs.Error.Trace(), "Unable to prepare URL for copying.")
|
||||
}
|
||||
continue
|
||||
}
|
||||
if sURLs.SourceContent != nil {
|
||||
// copy
|
||||
totalBytes += sURLs.SourceContent.Size
|
||||
}
|
||||
|
||||
totalObjects++
|
||||
mj.TotalBytes = totalBytes
|
||||
mj.TotalObjects = totalObjects
|
||||
mj.status.SetTotal(totalBytes)
|
||||
|
||||
// Save total count.
|
||||
sURLs.TotalCount = mj.TotalObjects
|
||||
// Save totalSize.
|
||||
sURLs.TotalSize = mj.TotalBytes
|
||||
|
||||
if sURLs.SourceContent != nil {
|
||||
mj.statusCh <- mj.doMirror(sURLs)
|
||||
} else if sURLs.TargetContent != nil && isRemove && isForce {
|
||||
mj.statusCh <- mj.doRemove(sURLs)
|
||||
}
|
||||
case <-mj.trapCh:
|
||||
os.Exit(0)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// when using a struct for copying, we could save a lot of passing of variables
|
||||
func (mj *mirrorJob) mirror() {
|
||||
if globalQuiet || globalJSON {
|
||||
} else {
|
||||
// Enable progress bar reader only during default mode
|
||||
mj.scanBar = scanBarFactory()
|
||||
}
|
||||
|
||||
// start the status go routine
|
||||
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.
|
||||
go mj.watchMirror()
|
||||
}
|
||||
|
||||
// Start mirroring.
|
||||
mj.startMirror()
|
||||
|
||||
// Wait if watcher is running.
|
||||
if mj.watcherRunning && isWatch {
|
||||
<-mj.trapCh
|
||||
}
|
||||
}
|
||||
|
||||
func newMirrorJob(ctx *cli.Context) *mirrorJob {
|
||||
args := ctx.Args()
|
||||
|
||||
// we'll define the status to use here,
|
||||
// do we want the quiet status? or the progressbar
|
||||
var status = NewProgressStatus()
|
||||
if globalQuiet {
|
||||
status = NewQuietStatus()
|
||||
} else if globalJSON {
|
||||
status = NewDummyStatus()
|
||||
}
|
||||
|
||||
mj := mirrorJob{
|
||||
context: ctx,
|
||||
trapCh: signalTrap(os.Interrupt, syscall.SIGTERM, syscall.SIGKILL),
|
||||
m: new(sync.Mutex),
|
||||
|
||||
sourceURL: args[0],
|
||||
targetURL: args[len(args)-1], // Last one is target
|
||||
|
||||
status: status,
|
||||
scanBar: func(s string) {},
|
||||
statusCh: make(chan URLs),
|
||||
wgStatus: new(sync.WaitGroup),
|
||||
watcherRunning: true,
|
||||
watcher: NewWatcher(time.Now().UTC()),
|
||||
}
|
||||
|
||||
return &mj
|
||||
}
|
||||
|
||||
// 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()
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
/*
|
||||
* Minio Client (C) 2015, 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 (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/minio/cli"
|
||||
)
|
||||
|
||||
//
|
||||
// * MIRROR ARGS - VALID CASES
|
||||
// =========================
|
||||
// mirror(d1..., d2) -> []mirror(d1/f, d2/d1/f)
|
||||
|
||||
// checkMirrorSyntax(URLs []string)
|
||||
func checkMirrorSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) != 2 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "mirror", 1) // last argument is exit code.
|
||||
}
|
||||
|
||||
// extract URLs.
|
||||
URLs := ctx.Args()
|
||||
srcURL := URLs[0]
|
||||
tgtURL := URLs[1]
|
||||
|
||||
/****** Generic rules *******/
|
||||
if !ctx.Bool("watch") {
|
||||
_, srcContent, err := url2Stat(srcURL)
|
||||
// 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+"’.")
|
||||
}
|
||||
|
||||
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))
|
||||
}
|
||||
}
|
||||
|
||||
if len(tgtURL) == 0 && tgtURL == "" {
|
||||
fatalIf(errInvalidArgument().Trace(), "Invalid target arguments to mirror command.")
|
||||
}
|
||||
|
||||
url := newClientURL(tgtURL)
|
||||
if url.Host != "" {
|
||||
if url.Path == string(url.Separator) {
|
||||
fatalIf(errInvalidArgument().Trace(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) {
|
||||
// source and targets are always directories
|
||||
sourceSeparator := string(newClientURL(sourceURL).Separator)
|
||||
if !strings.HasSuffix(sourceURL, sourceSeparator) {
|
||||
sourceURL = sourceURL + sourceSeparator
|
||||
}
|
||||
targetSeparator := string(newClientURL(targetURL).Separator)
|
||||
if !strings.HasSuffix(targetURL, targetSeparator) {
|
||||
targetURL = targetURL + targetSeparator
|
||||
}
|
||||
|
||||
// Extract alias and expanded URL
|
||||
sourceAlias, sourceURL, _ := mustExpandAlias(sourceURL)
|
||||
targetAlias, targetURL, _ := mustExpandAlias(targetURL)
|
||||
|
||||
defer close(URLsCh)
|
||||
|
||||
sourceClnt, err := newClientFromAlias(sourceAlias, sourceURL)
|
||||
if err != nil {
|
||||
URLsCh <- URLs{Error: err.Trace(sourceAlias, sourceURL)}
|
||||
return
|
||||
}
|
||||
|
||||
targetClnt, err := newClientFromAlias(targetAlias, targetURL)
|
||||
if err != nil {
|
||||
URLsCh <- URLs{Error: err.Trace(targetAlias, targetURL)}
|
||||
return
|
||||
}
|
||||
|
||||
// List both source and target, compare and return values through channel.
|
||||
for diffMsg := range objectDifference(sourceClnt, targetClnt, sourceURL, targetURL) {
|
||||
switch diffMsg.Diff {
|
||||
case differInNone:
|
||||
// No difference, continue.
|
||||
continue
|
||||
case differInType:
|
||||
URLsCh <- URLs{Error: errInvalidTarget(diffMsg.SecondURL)}
|
||||
continue
|
||||
case differInSize:
|
||||
if !isForce && !isFake {
|
||||
// Size differs and force not set
|
||||
URLsCh <- URLs{Error: errOverWriteNotAllowed(diffMsg.SecondURL)}
|
||||
continue
|
||||
}
|
||||
sourceSuffix := strings.TrimPrefix(diffMsg.FirstURL, sourceURL)
|
||||
// Either available only in source or size differs and force is set
|
||||
targetPath := urlJoinPath(targetURL, sourceSuffix)
|
||||
sourceContent := diffMsg.firstContent
|
||||
targetContent := &clientContent{URL: *newClientURL(targetPath)}
|
||||
URLsCh <- URLs{
|
||||
SourceAlias: sourceAlias,
|
||||
SourceContent: sourceContent,
|
||||
TargetAlias: targetAlias,
|
||||
TargetContent: targetContent,
|
||||
}
|
||||
continue
|
||||
case differInFirst:
|
||||
sourceSuffix := strings.TrimPrefix(diffMsg.FirstURL, sourceURL)
|
||||
// Either available only in source or size differs and force is set
|
||||
targetPath := urlJoinPath(targetURL, sourceSuffix)
|
||||
sourceContent := diffMsg.firstContent
|
||||
targetContent := &clientContent{URL: *newClientURL(targetPath)}
|
||||
URLsCh <- URLs{
|
||||
SourceAlias: sourceAlias,
|
||||
SourceContent: sourceContent,
|
||||
TargetAlias: targetAlias,
|
||||
TargetContent: targetContent,
|
||||
}
|
||||
case differInSecond:
|
||||
if isRemove {
|
||||
// todo(nl5887): I'd all force and fake checks to the the actual mirror / harvest
|
||||
if !isForce && !isFake {
|
||||
// Object removal not allowed if force is not set.
|
||||
URLsCh <- URLs{
|
||||
Error: errDeleteNotAllowed(diffMsg.SecondURL),
|
||||
}
|
||||
continue
|
||||
}
|
||||
URLsCh <- URLs{
|
||||
TargetAlias: targetAlias,
|
||||
TargetContent: diffMsg.secondContent,
|
||||
}
|
||||
}
|
||||
continue
|
||||
default:
|
||||
URLsCh <- URLs{
|
||||
Error: errUnrecognizedDiffType(diffMsg.Diff).Trace(diffMsg.FirstURL, diffMsg.SecondURL),
|
||||
}
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Prepares urls that need to be copied or removed based on requested options.
|
||||
func prepareMirrorURLs(sourceURL string, targetURL string, isForce bool, isFake bool, isRemove bool) <-chan URLs {
|
||||
URLsCh := make(chan URLs)
|
||||
go deltaSourceTarget(sourceURL, targetURL, isForce, isFake, isRemove, URLsCh)
|
||||
return URLsCh
|
||||
}
|
||||
@@ -14,7 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
@@ -22,9 +22,9 @@ import (
|
||||
"runtime"
|
||||
"strings"
|
||||
|
||||
"github.com/cheggaaa/pb"
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/olekukonko/ts"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
// colorizeUpdateMessage - inspired from Yeoman project npm package https://github.com/yeoman/update-notifier.
|
||||
@@ -49,15 +49,13 @@ func colorizeUpdateMessage(updateString string) (string, *probe.Error) {
|
||||
line1Rest := maxContentWidth - line1Length
|
||||
line2Rest := maxContentWidth - line2Length
|
||||
|
||||
// Fetch terminal size to calculate optimal box size.
|
||||
terminal, e := ts.GetSize()
|
||||
termWidth, e := pb.GetTerminalWidth()
|
||||
if e != nil {
|
||||
return "", probe.NewError(e)
|
||||
}
|
||||
|
||||
var message string
|
||||
switch {
|
||||
case len(line2Str) > terminal.Col():
|
||||
case len(line2Str) > termWidth:
|
||||
message = "\n" + line1InColor + "\n" + line2InColor + "\n"
|
||||
default:
|
||||
// on windows terminal turn off unicode characters.
|
||||
@@ -14,30 +14,26 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"os"
|
||||
"syscall"
|
||||
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
var (
|
||||
pipeFlags = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "help, h",
|
||||
Usage: "Help of pipe.",
|
||||
},
|
||||
}
|
||||
pipeFlags = []cli.Flag{}
|
||||
)
|
||||
|
||||
// Display contents of a file.
|
||||
var pipeCmd = cli.Command{
|
||||
Name: "pipe",
|
||||
Usage: "Write contents of stdin to one target. When no target is specified, it writes to stdout.",
|
||||
Usage: "Redirect STDIN to an object or file or STDOUT.",
|
||||
Action: mainPipe,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(pipeFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
mc {{.Name}} - {{.Usage}}
|
||||
@@ -55,7 +51,7 @@ EXAMPLES:
|
||||
2. Write contents of stdin to an object on Amazon S3 cloud storage.
|
||||
$ mc {{.Name}} s3/personalbuck/meeting-notes.txt
|
||||
|
||||
3. Copy an ISO image to an object on Amazon S3 cloud storage and Google Cloud Storage simultaneously.
|
||||
3. Copy an ISO image to an object on Amazon S3 cloud storage.
|
||||
$ cat debian-8.2.iso | mc {{.Name}} s3/ferenginar/gnuos.iso
|
||||
|
||||
4. Stream MySQL database dump to Amazon S3 directly.
|
||||
@@ -66,7 +62,7 @@ EXAMPLES:
|
||||
func pipe(targetURL string) *probe.Error {
|
||||
if targetURL == "" {
|
||||
// When no target is specified, pipe cat's stdin to stdout.
|
||||
return catOut(os.Stdin).Trace()
|
||||
return catOut(os.Stdin, -1).Trace()
|
||||
}
|
||||
|
||||
// Stream from stdin to multiple objects until EOF.
|
||||
@@ -92,9 +88,7 @@ func checkPipeSyntax(ctx *cli.Context) {
|
||||
}
|
||||
|
||||
// mainPipe is the main entry point for pipe command.
|
||||
func mainPipe(ctx *cli.Context) {
|
||||
// Set global flags from context.
|
||||
setGlobalsFromContext(ctx)
|
||||
func mainPipe(ctx *cli.Context) error {
|
||||
|
||||
// validate pipe input arguments.
|
||||
checkPipeSyntax(ctx)
|
||||
@@ -108,4 +102,7 @@ func mainPipe(ctx *cli.Context) {
|
||||
err := pipe(URLs[0])
|
||||
fatalIf(err.Trace(URLs[0]), "Unable to write to one or more targets.")
|
||||
}
|
||||
|
||||
// Done.
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,404 @@
|
||||
/*
|
||||
* Minio Client, (C) 2015, 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"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
var (
|
||||
policyFlags = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "recursive, r",
|
||||
Usage: "List recursively.",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
// Set public policy
|
||||
var policyCmd = cli.Command{
|
||||
Name: "policy",
|
||||
Usage: "Manage anonymous access to objects.",
|
||||
Action: mainPolicy,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(policyFlags, globalFlags...),
|
||||
CustomHelpTemplate: `Name:
|
||||
mc {{.Name}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
mc {{.Name}} [FLAGS] PERMISSION TARGET
|
||||
mc {{.Name}} [FLAGS] TARGET
|
||||
|
||||
PERMISSION:
|
||||
Allowed policies are: [none, download, upload, public].
|
||||
|
||||
FLAGS:
|
||||
{{range .Flags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Set bucket to "download" on Amazon S3 cloud storage.
|
||||
$ mc {{.Name}} download s3/burningman2011
|
||||
|
||||
2. Set bucket to "public" on Amazon S3 cloud storage.
|
||||
$ mc {{.Name}} public s3/shared
|
||||
|
||||
3. Set bucket to "upload" on Amazon S3 cloud storage.
|
||||
$ mc {{.Name}} upload s3/incoming
|
||||
|
||||
4. Set a prefix to "public" on Amazon S3 cloud storage.
|
||||
$ mc {{.Name}} public s3/public-commons/images
|
||||
|
||||
5. Get bucket permissions.
|
||||
$ mc {{.Name}} s3/shared
|
||||
|
||||
6. List policies set to a specified bucket.
|
||||
$ mc {{.Name}} list s3/shared
|
||||
|
||||
7. List public object URLs recursively.
|
||||
$ mc {{.Name}} --recursive links s3/shared/
|
||||
|
||||
`,
|
||||
}
|
||||
|
||||
// policyRules contains policy rule
|
||||
type policyRules struct {
|
||||
Resource string `json:"resource"`
|
||||
Allow string `json:"allow"`
|
||||
}
|
||||
|
||||
// String colorized access message.
|
||||
func (s policyRules) String() string {
|
||||
return console.Colorize("Policy", s.Resource+" => "+s.Allow+"")
|
||||
}
|
||||
|
||||
// JSON jsonified policy message.
|
||||
func (s policyRules) JSON() string {
|
||||
policyJSONBytes, e := json.Marshal(s)
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
return string(policyJSONBytes)
|
||||
}
|
||||
|
||||
// policyMessage is container for policy command on bucket success and failure messages.
|
||||
type policyMessage struct {
|
||||
Operation string `json:"operation"`
|
||||
Status string `json:"status"`
|
||||
Bucket string `json:"bucket"`
|
||||
Perms accessPerms `json:"permission"`
|
||||
}
|
||||
|
||||
// String colorized access message.
|
||||
func (s policyMessage) String() string {
|
||||
if s.Operation == "set" {
|
||||
return console.Colorize("Policy",
|
||||
"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)+"’")
|
||||
}
|
||||
// nothing to print
|
||||
return ""
|
||||
}
|
||||
|
||||
// JSON jsonified policy message.
|
||||
func (s policyMessage) JSON() string {
|
||||
policyJSONBytes, e := json.Marshal(s)
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(policyJSONBytes)
|
||||
}
|
||||
|
||||
// policyLinksMessage is container for policy links command
|
||||
type policyLinksMessage struct {
|
||||
Status string `json:"status"`
|
||||
URL string `json:"url"`
|
||||
}
|
||||
|
||||
// String colorized access message.
|
||||
func (s policyLinksMessage) String() string {
|
||||
return console.Colorize("Policy", string(s.URL))
|
||||
}
|
||||
|
||||
// JSON jsonified policy message.
|
||||
func (s policyLinksMessage) JSON() string {
|
||||
policyJSONBytes, e := json.Marshal(s)
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(policyJSONBytes)
|
||||
}
|
||||
|
||||
// checkPolicySyntax check for incoming syntax.
|
||||
func checkPolicySyntax(ctx *cli.Context) {
|
||||
argsLength := len(ctx.Args())
|
||||
// Always print a help message when we have extra arguments
|
||||
if argsLength > 2 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "policy", 1) // last argument is exit code.
|
||||
}
|
||||
// Always print a help message when no arguments specified
|
||||
if argsLength < 1 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "policy", 1)
|
||||
}
|
||||
|
||||
firstArg := ctx.Args().Get(0)
|
||||
|
||||
// More syntax checking
|
||||
switch accessPerms(firstArg) {
|
||||
case accessNone, accessDownload, accessUpload, accessPublic:
|
||||
// Always expect two arguments when a policy permission is provided
|
||||
if argsLength != 2 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "policy", 1)
|
||||
}
|
||||
case "list":
|
||||
// Always expect an argument after list cmd
|
||||
if argsLength != 2 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "policy", 1)
|
||||
}
|
||||
case "links":
|
||||
// Always expect an argument after links cmd
|
||||
if argsLength != 2 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "policy", 1)
|
||||
}
|
||||
|
||||
default:
|
||||
if argsLength == 2 {
|
||||
fatalIf(errDummy().Trace(),
|
||||
"Unrecognized permission ‘"+string(firstArg)+"’. Allowed values are [none, download, upload, public].")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Convert an accessPerms to a string recognizable by minio-go
|
||||
func accessPermToString(perm accessPerms) string {
|
||||
policy := ""
|
||||
switch perm {
|
||||
case accessNone:
|
||||
policy = "none"
|
||||
case accessDownload:
|
||||
policy = "readonly"
|
||||
case accessUpload:
|
||||
policy = "writeonly"
|
||||
case accessPublic:
|
||||
policy = "readwrite"
|
||||
}
|
||||
return policy
|
||||
}
|
||||
|
||||
// doSetAccess do set access.
|
||||
func doSetAccess(targetURL string, targetPERMS accessPerms) *probe.Error {
|
||||
clnt, err := newClient(targetURL)
|
||||
if err != nil {
|
||||
return err.Trace(targetURL)
|
||||
}
|
||||
policy := accessPermToString(targetPERMS)
|
||||
if err = clnt.SetAccess(policy); err != nil {
|
||||
return err.Trace(targetURL, string(targetPERMS))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Convert a minio-go permission to accessPerms type
|
||||
func stringToAccessPerm(perm string) accessPerms {
|
||||
var policy accessPerms
|
||||
switch perm {
|
||||
case "none":
|
||||
policy = accessNone
|
||||
case "readonly":
|
||||
policy = accessDownload
|
||||
case "writeonly":
|
||||
policy = accessUpload
|
||||
case "readwrite":
|
||||
policy = accessPublic
|
||||
}
|
||||
return policy
|
||||
}
|
||||
|
||||
// doGetAccess do get access.
|
||||
func doGetAccess(targetURL string) (perms accessPerms, err *probe.Error) {
|
||||
clnt, err := newClient(targetURL)
|
||||
if err != nil {
|
||||
return "", err.Trace(targetURL)
|
||||
}
|
||||
perm, err := clnt.GetAccess()
|
||||
if err != nil {
|
||||
return "", err.Trace(targetURL)
|
||||
}
|
||||
return stringToAccessPerm(perm), nil
|
||||
}
|
||||
|
||||
// doGetAccessRules do get access rules.
|
||||
func doGetAccessRules(targetURL string) (r map[string]string, err *probe.Error) {
|
||||
clnt, err := newClient(targetURL)
|
||||
if err != nil {
|
||||
return map[string]string{}, err.Trace(targetURL)
|
||||
}
|
||||
return clnt.GetAccessRules()
|
||||
}
|
||||
|
||||
// Run policy list command
|
||||
func runPolicyListCmd(ctx *cli.Context) {
|
||||
targetURL := ctx.Args().Last()
|
||||
policies, err := doGetAccessRules(targetURL)
|
||||
if err != nil {
|
||||
switch err.ToGoError().(type) {
|
||||
case APINotImplemented:
|
||||
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+"’.")
|
||||
}
|
||||
}
|
||||
for k, v := range policies {
|
||||
printMsg(policyRules{Resource: k, Allow: v})
|
||||
}
|
||||
}
|
||||
|
||||
// Run policy links command
|
||||
func runPolicyLinksCmd(ctx *cli.Context) {
|
||||
// Get alias/bucket/prefix argument
|
||||
targetURL := ctx.Args().Last()
|
||||
|
||||
// Fetch all policies associated to the passed url
|
||||
policies, err := doGetAccessRules(targetURL)
|
||||
if err != nil {
|
||||
switch err.ToGoError().(type) {
|
||||
case APINotImplemented:
|
||||
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+"’.")
|
||||
}
|
||||
}
|
||||
|
||||
// Extract alias from the passed argument, we'll need it to
|
||||
// construct new pathes to list public objects
|
||||
alias, path := url2Alias(targetURL)
|
||||
|
||||
isRecursive := ctx.Bool("recursive")
|
||||
isIncomplete := false
|
||||
|
||||
// Iterate over policy rules to fetch public urls, then search
|
||||
// for objects under those urls
|
||||
for k, v := range policies {
|
||||
// Trim the asterisk in policy rules
|
||||
policyPath := strings.TrimSuffix(k, "*")
|
||||
// Check if current policy prefix is related to the url passed by the user
|
||||
if !strings.HasPrefix(policyPath, path) {
|
||||
continue
|
||||
}
|
||||
// Check if the found policy has read permission
|
||||
perm := stringToAccessPerm(v)
|
||||
if perm != accessDownload && perm != accessPublic {
|
||||
continue
|
||||
}
|
||||
// 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+"’.")
|
||||
// Search for public objects
|
||||
for content := range clnt.List(isRecursive, isIncomplete, DirFirst) {
|
||||
if content.Err != nil {
|
||||
errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list folder.")
|
||||
continue
|
||||
}
|
||||
|
||||
// Encode public URL
|
||||
u, e := url.Parse(content.URL.String())
|
||||
errorIf(probe.NewError(e), "Unable to parse url `"+content.URL.String()+"`")
|
||||
publicURL := u.String()
|
||||
|
||||
// Construct the message to be displayed to the user
|
||||
msg := policyLinksMessage{
|
||||
Status: "success",
|
||||
URL: publicURL,
|
||||
}
|
||||
// Print the found object
|
||||
printMsg(msg)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Run policy cmd to fetch set permission
|
||||
func runPolicyCmd(ctx *cli.Context) {
|
||||
perms := accessPerms(ctx.Args().First())
|
||||
if perms.isValidAccessPERM() {
|
||||
targetURL := ctx.Args().Last()
|
||||
err := doSetAccess(targetURL, perms)
|
||||
// Upon error exit.
|
||||
if err != nil {
|
||||
switch err.ToGoError().(type) {
|
||||
case APINotImplemented:
|
||||
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+"’.")
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
printMsg(policyMessage{
|
||||
Status: "success",
|
||||
Operation: "set",
|
||||
Bucket: targetURL,
|
||||
Perms: perms,
|
||||
})
|
||||
} else {
|
||||
targetURL := ctx.Args().First()
|
||||
perms, err := doGetAccess(targetURL)
|
||||
if err != nil {
|
||||
switch err.ToGoError().(type) {
|
||||
case APINotImplemented:
|
||||
fatalIf(err.Trace(), "Unable to get policy of a non S3 url ‘"+targetURL+"’.")
|
||||
default:
|
||||
fatalIf(err.Trace(targetURL), "Unable to get policy for ‘"+targetURL+"’.")
|
||||
}
|
||||
}
|
||||
|
||||
printMsg(policyMessage{
|
||||
Status: "success",
|
||||
Operation: "get",
|
||||
Bucket: targetURL,
|
||||
Perms: perms,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func mainPolicy(ctx *cli.Context) error {
|
||||
|
||||
// check 'policy' cli arguments.
|
||||
checkPolicySyntax(ctx)
|
||||
|
||||
// Additional command speific theme customization.
|
||||
console.SetColor("Policy", color.New(color.FgGreen, color.Bold))
|
||||
|
||||
switch ctx.Args().First() {
|
||||
case "list":
|
||||
// policy list alias/bucket/prefix
|
||||
runPolicyListCmd(ctx)
|
||||
case "links":
|
||||
// policy links alias/bucket/prefix
|
||||
runPolicyLinksCmd(ctx)
|
||||
default:
|
||||
// policy [download|upload|public|] alias/bucket/prefix
|
||||
runPolicyCmd(ctx)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -14,7 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
package cmd
|
||||
|
||||
import "github.com/minio/mc/pkg/console"
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"io"
|
||||
@@ -22,15 +22,15 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/cheggaaa/pb"
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/pb"
|
||||
|
||||
"github.com/minio/mc/pkg/console"
|
||||
)
|
||||
|
||||
// progress extender.
|
||||
type progressBar struct {
|
||||
ProgressBar *pb.ProgressBar
|
||||
*pb.ProgressBar
|
||||
reader io.Reader
|
||||
readerLength int64
|
||||
bytesRead int64
|
||||
@@ -101,6 +101,11 @@ func (p *progressBar) Set64(length int64) *progressBar {
|
||||
return p
|
||||
}
|
||||
|
||||
func (p *progressBar) SetTotal(total int64) *progressBar {
|
||||
p.ProgressBar.Total = total
|
||||
return p
|
||||
}
|
||||
|
||||
// cursorAnimate - returns a animated rune through read channel for every read.
|
||||
func cursorAnimate() <-chan rune {
|
||||
cursorCh := make(chan rune)
|
||||
+303
@@ -0,0 +1,303 @@
|
||||
/*
|
||||
* Minio Client (C) 2014, 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
// Day time.Duration for day.
|
||||
const Day = 24 * time.Hour
|
||||
|
||||
// rm specific flags.
|
||||
var (
|
||||
rmFlags = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "recursive, r",
|
||||
Usage: "Remove recursively.",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "force",
|
||||
Usage: "Force a dangerous remove operation.",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "incomplete, I",
|
||||
Usage: "Remove incomplete uploads.",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "fake",
|
||||
Usage: "Perform a fake remove operation.",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "stdin",
|
||||
Usage: "Read object names from STDIN.",
|
||||
},
|
||||
cli.IntFlag{
|
||||
Name: "older-than",
|
||||
Usage: "Remove objects older than N days.",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
// remove a file or folder.
|
||||
var rmCmd = cli.Command{
|
||||
Name: "rm",
|
||||
Usage: "Remove files and objects.",
|
||||
Action: mainRm,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(rmFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
mc {{.Name}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
mc {{.Name}} [FLAGS] TARGET [TARGET ...]
|
||||
|
||||
FLAGS:
|
||||
{{range .Flags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Remove a file.
|
||||
$ mc {{.Name}} 1999/old-backup.tgz
|
||||
|
||||
2. Remove all objects recursively.
|
||||
$ mc {{.Name}} --recursive s3/jazz-songs/louis/
|
||||
|
||||
3. Remove all objects older than '90' days.
|
||||
$ mc {{.Name}} --recursive --older-than=90 s3/jazz-songs/louis/
|
||||
|
||||
4. Remove all objects read from STDIN.
|
||||
$ mc {{.Name}} --force --stdin
|
||||
|
||||
5. Drop all incomplete uploads on 'jazz-songs' bucket.
|
||||
$ mc {{.Name}} --incomplete --recursive s3/jazz-songs/
|
||||
`,
|
||||
}
|
||||
|
||||
// Structured message depending on the type of console.
|
||||
type rmMessage struct {
|
||||
Key string `json:"key"`
|
||||
Size int64 `json:"size"`
|
||||
}
|
||||
|
||||
// Colorized message for console printing.
|
||||
func (r rmMessage) String() string {
|
||||
return console.Colorize("Remove", fmt.Sprintf("Removing ‘%s’.", r.Key))
|
||||
}
|
||||
|
||||
// JSON'ified message for scripting.
|
||||
func (r rmMessage) JSON() string {
|
||||
msgBytes, e := json.Marshal(r)
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
return string(msgBytes)
|
||||
}
|
||||
|
||||
// Validate command line arguments.
|
||||
func checkRmSyntax(ctx *cli.Context) {
|
||||
// Set command flags from context.
|
||||
isForce := ctx.Bool("force")
|
||||
isRecursive := ctx.Bool("recursive")
|
||||
isStdin := ctx.Bool("stdin")
|
||||
|
||||
if !ctx.Args().Present() && !isStdin {
|
||||
exitCode := 1
|
||||
cli.ShowCommandHelpAndExit(ctx, "rm", exitCode)
|
||||
}
|
||||
|
||||
// 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.")
|
||||
}
|
||||
}
|
||||
|
||||
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+"’.")
|
||||
return exitStatus(globalErrorExitStatus) // End of journey.
|
||||
}
|
||||
|
||||
content, pErr := clnt.Stat(isIncomplete)
|
||||
if pErr != nil {
|
||||
errorIf(pErr.Trace(url), "Failed to remove ‘"+url+"’.")
|
||||
return exitStatus(globalErrorExitStatus)
|
||||
}
|
||||
if older > 0 {
|
||||
// Check whether object is created older than given time.
|
||||
now := time.Now().UTC()
|
||||
timeDiff := now.Sub(content.Time)
|
||||
if timeDiff < (time.Duration(older) * Day) {
|
||||
// time difference of info.Time with current time is less than older time.
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
printMsg(rmMessage{
|
||||
Key: url,
|
||||
Size: content.Size,
|
||||
})
|
||||
|
||||
if !isFake {
|
||||
contentCh := make(chan *clientContent, 1)
|
||||
contentCh <- &clientContent{URL: *newClientURL(targetURL)}
|
||||
close(contentCh)
|
||||
|
||||
errorCh := clnt.Remove(isIncomplete, contentCh)
|
||||
for pErr := range errorCh {
|
||||
if pErr != nil {
|
||||
errorIf(pErr.Trace(url), "Failed to remove ‘"+url+"’.")
|
||||
switch pErr.ToGoError().(type) {
|
||||
case PathInsufficientPermission:
|
||||
// Ignore Permission error.
|
||||
continue
|
||||
}
|
||||
return exitStatus(globalErrorExitStatus)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func removeRecursive(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), "Failed to remove ‘"+url+"’ recursively.")
|
||||
return exitStatus(globalErrorExitStatus) // End of journey.
|
||||
}
|
||||
|
||||
contentCh := make(chan *clientContent)
|
||||
errorCh := clnt.Remove(isIncomplete, contentCh)
|
||||
|
||||
isEmpty := true
|
||||
isRecursive := true
|
||||
for content := range clnt.List(isRecursive, isIncomplete, DirLast) {
|
||||
isEmpty = false
|
||||
if content.Err != nil {
|
||||
errorIf(content.Err.Trace(url), "Failed to remove ‘"+url+"’ recursively.")
|
||||
switch content.Err.ToGoError().(type) {
|
||||
case PathInsufficientPermission:
|
||||
// Ignore Permission error.
|
||||
continue
|
||||
}
|
||||
close(contentCh)
|
||||
return exitStatus(globalErrorExitStatus)
|
||||
}
|
||||
|
||||
if older > 0 {
|
||||
// Check whether object is created older than given time.
|
||||
now := time.Now().UTC()
|
||||
timeDiff := now.Sub(content.Time)
|
||||
if timeDiff < (time.Duration(older) * Day) {
|
||||
// time difference of info.Time with current time is less than older time.
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
urlString := content.URL.Path
|
||||
printMsg(rmMessage{
|
||||
Key: targetAlias + urlString,
|
||||
Size: content.Size,
|
||||
})
|
||||
|
||||
if !isFake {
|
||||
sent := false
|
||||
for sent == false {
|
||||
select {
|
||||
case contentCh <- content:
|
||||
sent = true
|
||||
case pErr := <-errorCh:
|
||||
errorIf(pErr.Trace(urlString), "Failed to remove ‘"+urlString+"’.")
|
||||
switch pErr.ToGoError().(type) {
|
||||
case PathInsufficientPermission:
|
||||
// Ignore Permission error.
|
||||
continue
|
||||
}
|
||||
|
||||
close(contentCh)
|
||||
return exitStatus(globalErrorExitStatus)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
close(contentCh)
|
||||
for pErr := range errorCh {
|
||||
errorIf(pErr.Trace(url), "Failed to remove ‘"+url+"’ recursively.")
|
||||
switch pErr.ToGoError().(type) {
|
||||
case PathInsufficientPermission:
|
||||
// Ignore Permission error.
|
||||
continue
|
||||
}
|
||||
return exitStatus(globalErrorExitStatus)
|
||||
}
|
||||
|
||||
// As clnt.List() returns empty, we just send dummy value to behave like non-recursive.
|
||||
if isEmpty {
|
||||
printMsg(rmMessage{Key: url})
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// main for rm command.
|
||||
func mainRm(ctx *cli.Context) error {
|
||||
|
||||
// check 'rm' cli arguments.
|
||||
checkRmSyntax(ctx)
|
||||
|
||||
// rm specific flags.
|
||||
isIncomplete := ctx.Bool("incomplete")
|
||||
isRecursive := ctx.Bool("recursive")
|
||||
isFake := ctx.Bool("fake")
|
||||
isStdin := ctx.Bool("stdin")
|
||||
older := ctx.Int("older-than")
|
||||
|
||||
// Set color.
|
||||
console.SetColor("Remove", color.New(color.FgGreen, color.Bold))
|
||||
|
||||
// Support multiple targets.
|
||||
for _, url := range ctx.Args() {
|
||||
if isRecursive {
|
||||
return removeRecursive(url, isIncomplete, isFake, older)
|
||||
} // else {
|
||||
return removeSingle(url, isIncomplete, isFake, older)
|
||||
}
|
||||
|
||||
if !isStdin {
|
||||
return nil
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
/*
|
||||
* Minio Client (C) 2014, 2015, 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 (
|
||||
"fmt"
|
||||
"runtime"
|
||||
"strings"
|
||||
|
||||
"github.com/hashicorp/go-version"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
)
|
||||
|
||||
// check if minimum Go version is met.
|
||||
func checkGoVersion() {
|
||||
runtimeVersion := runtime.Version()
|
||||
|
||||
// Checking version is always successful with go tip
|
||||
if strings.HasPrefix(runtimeVersion, "devel") {
|
||||
return
|
||||
}
|
||||
|
||||
// Parsing golang version
|
||||
curVersion, e := version.NewVersion(runtimeVersion[2:])
|
||||
if e != nil {
|
||||
console.Fatalln("Unable to determine current go version.", e)
|
||||
}
|
||||
|
||||
// Prepare version constraint.
|
||||
constraints, e := version.NewConstraint(minGoVersion)
|
||||
if e != nil {
|
||||
console.Fatalln("Unable to check go version.")
|
||||
}
|
||||
|
||||
// Check for minimum version.
|
||||
if !constraints.Check(curVersion) {
|
||||
console.Fatalln(fmt.Sprintf("Please recompile Minio with Golang version %s.", minGoVersion))
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Minio Client (C) 2014, 2015 Minio, Inc.
|
||||
* Minio Client (C) 2014-2016 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -14,20 +14,19 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/cheggaaa/pb"
|
||||
"github.com/dustin/go-humanize"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/olekukonko/ts"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
/******************************** Scan Bar ************************************/
|
||||
// fixateScanBar truncates long text to fit within the terminal size.
|
||||
// fixateScanBar truncates or stretches text to fit within the terminal size.
|
||||
func fixateScanBar(text string, width int) string {
|
||||
if len([]rune(text)) > width {
|
||||
// Trim text to fit within the screen
|
||||
@@ -35,6 +34,8 @@ func fixateScanBar(text string, width int) string {
|
||||
if trimSize < len([]rune(text)) {
|
||||
text = "..." + text[trimSize:]
|
||||
}
|
||||
} else {
|
||||
text += strings.Repeat(" ", width-len([]rune(text)))
|
||||
}
|
||||
return text
|
||||
}
|
||||
@@ -44,32 +45,17 @@ type scanBarFunc func(string)
|
||||
|
||||
// scanBarFactory returns a progress bar function to report URL scanning.
|
||||
func scanBarFactory() scanBarFunc {
|
||||
prevLineSize := 0
|
||||
prevSource := ""
|
||||
fileCount := 0
|
||||
termSize, e := ts.GetSize()
|
||||
if e != nil {
|
||||
fatalIf(probe.NewError(e), "Unable to get terminal size. Please use --quiet option.")
|
||||
}
|
||||
termWidth := termSize.Col()
|
||||
cursorCh := cursorAnimate()
|
||||
termWidth, e := pb.GetTerminalWidth()
|
||||
fatalIf(probe.NewError(e), "Unable to get terminal size. Please use --quiet option.")
|
||||
|
||||
// Cursor animate channel.
|
||||
cursorCh := cursorAnimate()
|
||||
return func(source string) {
|
||||
scanPrefix := fmt.Sprintf("[%s] %s ", humanize.Comma(int64(fileCount)), string(<-cursorCh))
|
||||
cmnPrefix := commonPrefix(source, prevSource)
|
||||
eraseLen := prevLineSize - len([]rune(scanPrefix+cmnPrefix))
|
||||
if eraseLen < 1 {
|
||||
eraseLen = 0
|
||||
}
|
||||
if prevLineSize != 0 { // erase previous line
|
||||
console.PrintC("\r" + scanPrefix + cmnPrefix + strings.Repeat(" ", eraseLen))
|
||||
}
|
||||
|
||||
source = fixateScanBar(source, termWidth-len([]rune(scanPrefix))-1)
|
||||
source = fixateScanBar(source, termWidth-len([]rune(scanPrefix)))
|
||||
barText := scanPrefix + source
|
||||
console.PrintC("\r" + barText)
|
||||
prevSource = source
|
||||
prevLineSize = len([]rune(barText))
|
||||
console.PrintC("\r" + barText + "\r")
|
||||
fileCount++
|
||||
}
|
||||
}
|
||||
@@ -14,7 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
@@ -26,24 +26,20 @@ import (
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
var (
|
||||
sessionFlags = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "help, h",
|
||||
Usage: "Help of session.",
|
||||
},
|
||||
}
|
||||
sessionFlags = []cli.Flag{}
|
||||
)
|
||||
|
||||
// Manage sessions for cp and mirror.
|
||||
var sessionCmd = cli.Command{
|
||||
Name: "session",
|
||||
Usage: "Manage saved sessions of cp and mirror operations.",
|
||||
Usage: "Manage saved sessions for cp and mirror commands.",
|
||||
Action: mainSession,
|
||||
Flags: append(sessionFlags, globalFlags...),
|
||||
Before: setGlobalsFromContext,
|
||||
CustomHelpTemplate: `NAME:
|
||||
mc {{.Name}} - {{.Usage}}
|
||||
|
||||
@@ -71,13 +67,13 @@ EXAMPLES:
|
||||
3. Clear session.
|
||||
$ mc {{.Name}} clear ygVIpSJs
|
||||
|
||||
4. Clear session.
|
||||
4. Clear all sessions.
|
||||
$ mc {{.Name}} clear all
|
||||
`,
|
||||
}
|
||||
|
||||
// bySessionWhen is a type for sorting session metadata by time.
|
||||
type bySessionWhen []*sessionV6
|
||||
type bySessionWhen []*sessionV8
|
||||
|
||||
func (b bySessionWhen) Len() int { return len(b) }
|
||||
func (b bySessionWhen) Swap(i, j int) { b[i], b[j] = b[j], b[i] }
|
||||
@@ -85,19 +81,19 @@ func (b bySessionWhen) Less(i, j int) bool { return b[i].Header.When.Before(b[j]
|
||||
|
||||
// listSessions list all current sessions.
|
||||
func listSessions() *probe.Error {
|
||||
var bySessions []*sessionV6
|
||||
var bySessions []*sessionV8
|
||||
for _, sid := range getSessionIDs() {
|
||||
s, err := loadSessionV6(sid)
|
||||
session, err := loadSessionV8(sid)
|
||||
if err != nil {
|
||||
return err.Trace(sid)
|
||||
continue // Skip 'broken' session during listing
|
||||
}
|
||||
bySessions = append(bySessions, s)
|
||||
session.Close() // Session close right here.
|
||||
bySessions = append(bySessions, session)
|
||||
}
|
||||
// sort sessions based on time.
|
||||
sort.Sort(bySessionWhen(bySessions))
|
||||
for _, session := range bySessions {
|
||||
printMsg(session)
|
||||
session.Close()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -110,7 +106,15 @@ type clearSessionMessage struct {
|
||||
|
||||
// String colorized clear session message.
|
||||
func (c clearSessionMessage) String() string {
|
||||
return console.Colorize("ClearSession", "Session ‘"+c.SessionID+"’ cleared successfully.")
|
||||
msg := "Session ‘" + c.SessionID + "’"
|
||||
var colorizedMsg string
|
||||
switch c.Status {
|
||||
case "success":
|
||||
colorizedMsg = console.Colorize("ClearSession", msg+" cleared successfully.")
|
||||
case "forced":
|
||||
colorizedMsg = console.Colorize("ClearSession", msg+" cleared forcefully.")
|
||||
}
|
||||
return colorizedMsg
|
||||
}
|
||||
|
||||
// JSON jsonified clear session message.
|
||||
@@ -125,7 +129,7 @@ func (c clearSessionMessage) JSON() string {
|
||||
func clearSession(sid string) {
|
||||
if sid == "all" {
|
||||
for _, sid := range getSessionIDs() {
|
||||
session, err := loadSessionV6(sid)
|
||||
session, err := loadSessionV8(sid)
|
||||
fatalIf(err.Trace(sid), "Unable to load session ‘"+sid+"’.")
|
||||
|
||||
fatalIf(session.Delete().Trace(sid), "Unable to load session ‘"+sid+"’.")
|
||||
@@ -139,8 +143,15 @@ func clearSession(sid string) {
|
||||
fatalIf(errDummy().Trace(sid), "Session ‘"+sid+"’ not found.")
|
||||
}
|
||||
|
||||
session, err := loadSessionV6(sid)
|
||||
fatalIf(err.Trace(sid), "Unable to load session ‘"+sid+"’.")
|
||||
session, err := loadSessionV8(sid)
|
||||
if err != nil {
|
||||
// `mc session clear <broken-session-id>` assumes that user is aware that the session is unuseful
|
||||
// and wants the associated session files to be removed
|
||||
removeSessionFile(sid)
|
||||
removeSessionDataFile(sid)
|
||||
printMsg(clearSessionMessage{Status: "forced", SessionID: sid})
|
||||
return
|
||||
}
|
||||
|
||||
if session != nil {
|
||||
fatalIf(session.Delete().Trace(sid), "Unable to load session ‘"+sid+"’.")
|
||||
@@ -148,12 +159,10 @@ func clearSession(sid string) {
|
||||
}
|
||||
}
|
||||
|
||||
func sessionExecute(s *sessionV6) {
|
||||
func sessionExecute(s *sessionV8) {
|
||||
switch s.Header.CommandType {
|
||||
case "cp":
|
||||
doCopySession(s)
|
||||
case "mirror":
|
||||
doMirrorSession(s)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -194,9 +203,7 @@ func findClosestSessions(session string) []string {
|
||||
return closestSessions
|
||||
}
|
||||
|
||||
func mainSession(ctx *cli.Context) {
|
||||
// Set global flags from context.
|
||||
setGlobalsFromContext(ctx)
|
||||
func mainSession(ctx *cli.Context) error {
|
||||
|
||||
// check 'session' cli arguments.
|
||||
checkSessionSyntax(ctx)
|
||||
@@ -230,7 +237,7 @@ func mainSession(ctx *cli.Context) {
|
||||
}
|
||||
fatalIf(errDummy().Trace(sid), errorMsg)
|
||||
}
|
||||
s, err := loadSessionV6(sid)
|
||||
s, err := loadSessionV8(sid)
|
||||
fatalIf(err.Trace(sid), "Unable to load session.")
|
||||
|
||||
// Restore the state of global variables from this previous session.
|
||||
@@ -258,4 +265,6 @@ func mainSession(ctx *cli.Context) {
|
||||
case "clear":
|
||||
clearSession(strings.TrimSpace(ctx.Args().Tail().First()))
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
/*
|
||||
* 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 (
|
||||
"os"
|
||||
"strconv"
|
||||
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
"github.com/minio/minio/pkg/quick"
|
||||
)
|
||||
|
||||
// Migrates session header version '7' to '8'. The only
|
||||
// change was the adding of insecure global flag
|
||||
func migrateSessionV7ToV8() {
|
||||
for _, sid := range getSessionIDs() {
|
||||
sV7, err := loadSessionV7(sid)
|
||||
if err != nil {
|
||||
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.")
|
||||
}
|
||||
|
||||
sessionVersion, e := strconv.Atoi(sV7.Header.Version)
|
||||
fatalIf(probe.NewError(e), "Unable to load version ‘7’. Migration failed please report this issue at https://github.com/minio/mc/issues.")
|
||||
if sessionVersion > 7 { // It is new format.
|
||||
continue
|
||||
}
|
||||
|
||||
sessionFile, err := getSessionFile(sid)
|
||||
fatalIf(err.Trace(sid), "Unable to get session file.")
|
||||
|
||||
// Initialize v7 header and migrate to new config.
|
||||
sV8Header := &sessionV8Header{}
|
||||
sV8Header.Version = globalSessionConfigVersion
|
||||
sV8Header.When = sV7.Header.When
|
||||
sV8Header.RootPath = sV7.Header.RootPath
|
||||
sV8Header.GlobalBoolFlags = sV7.Header.GlobalBoolFlags
|
||||
sV8Header.GlobalIntFlags = sV7.Header.GlobalIntFlags
|
||||
sV8Header.GlobalStringFlags = sV7.Header.GlobalStringFlags
|
||||
sV8Header.CommandType = sV7.Header.CommandType
|
||||
sV8Header.CommandArgs = sV7.Header.CommandArgs
|
||||
sV8Header.CommandBoolFlags = sV7.Header.CommandBoolFlags
|
||||
sV8Header.CommandIntFlags = sV7.Header.CommandIntFlags
|
||||
sV8Header.CommandStringFlags = sV7.Header.CommandStringFlags
|
||||
sV8Header.LastCopied = sV7.Header.LastCopied
|
||||
sV8Header.LastRemoved = sV7.Header.LastRemoved
|
||||
sV8Header.TotalBytes = sV7.Header.TotalBytes
|
||||
sV8Header.TotalObjects = int64(sV7.Header.TotalObjects)
|
||||
|
||||
// Add insecure flag to the new V8 header
|
||||
sV8Header.GlobalBoolFlags["insecure"] = false
|
||||
|
||||
qs, e := quick.New(sV8Header)
|
||||
fatalIf(probe.NewError(e).Trace(sid), "Unable to initialize quick config for session '8' header.")
|
||||
|
||||
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 + "’.")
|
||||
}
|
||||
}
|
||||
|
||||
// Migrates session header version '6' to '7'. Only change is
|
||||
// LastRemoved field which was added in version '7'.
|
||||
func migrateSessionV6ToV7() {
|
||||
for _, sid := range getSessionIDs() {
|
||||
sV6Header, err := loadSessionV6Header(sid)
|
||||
if err != nil {
|
||||
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.")
|
||||
}
|
||||
|
||||
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.")
|
||||
if sessionVersion > 6 { // It is new format.
|
||||
continue
|
||||
}
|
||||
|
||||
sessionFile, err := getSessionFile(sid)
|
||||
fatalIf(err.Trace(sid), "Unable to get session file.")
|
||||
|
||||
// Initialize v7 header and migrate to new config.
|
||||
sV7Header := &sessionV7Header{}
|
||||
sV7Header.Version = "7"
|
||||
sV7Header.When = sV6Header.When
|
||||
sV7Header.RootPath = sV6Header.RootPath
|
||||
sV7Header.GlobalBoolFlags = sV6Header.GlobalBoolFlags
|
||||
sV7Header.GlobalIntFlags = sV6Header.GlobalIntFlags
|
||||
sV7Header.GlobalStringFlags = sV6Header.GlobalStringFlags
|
||||
sV7Header.CommandType = sV6Header.CommandType
|
||||
sV7Header.CommandArgs = sV6Header.CommandArgs
|
||||
sV7Header.CommandBoolFlags = sV6Header.CommandBoolFlags
|
||||
sV7Header.CommandIntFlags = sV6Header.CommandIntFlags
|
||||
sV7Header.CommandStringFlags = sV6Header.CommandStringFlags
|
||||
sV7Header.LastCopied = sV6Header.LastCopied
|
||||
sV7Header.LastRemoved = ""
|
||||
sV7Header.TotalBytes = sV6Header.TotalBytes
|
||||
sV7Header.TotalObjects = sV6Header.TotalObjects
|
||||
|
||||
qs, e := quick.New(sV7Header)
|
||||
fatalIf(probe.NewError(e).Trace(sid), "Unable to initialize quick config for session '7' header.")
|
||||
|
||||
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 + "’.")
|
||||
}
|
||||
}
|
||||
|
||||
// Migrate session version '5' to version '6', all older sessions are
|
||||
// in-fact removed and not migrated. All session files from '6' and
|
||||
// above should be migrated - See: migrateSessionV6ToV7().
|
||||
func migrateSessionV5ToV6() {
|
||||
for _, sid := range getSessionIDs() {
|
||||
sV6Header, err := loadSessionV6Header(sid)
|
||||
if err != nil {
|
||||
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.")
|
||||
}
|
||||
|
||||
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.")
|
||||
if sessionVersion > 5 { // It is new format.
|
||||
continue
|
||||
}
|
||||
|
||||
/*** Remove all session files older than v6 ***/
|
||||
|
||||
sessionFile, err := getSessionFile(sid)
|
||||
fatalIf(err.Trace(sid), "Unable to get session file.")
|
||||
|
||||
sessionDataFile, err := getSessionDataFile(sid)
|
||||
fatalIf(err.Trace(sid), "Unable to get session data file.")
|
||||
|
||||
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+"’.")
|
||||
}
|
||||
if e := os.Remove(sessionDataFile); e != nil {
|
||||
fatalIf(probe.NewError(e), "Unable to remove version ‘"+sV6Header.Version+"’ session data file ‘"+sessionDataFile+"’.")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
/*
|
||||
* 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 (
|
||||
"os"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
"github.com/minio/minio/pkg/quick"
|
||||
)
|
||||
|
||||
/////////////////// Session V6 ///////////////////
|
||||
// sessionV6Header for resumable sessions.
|
||||
type sessionV6Header struct {
|
||||
Version string `json:"version"`
|
||||
When time.Time `json:"time"`
|
||||
RootPath string `json:"workingFolder"`
|
||||
GlobalBoolFlags map[string]bool `json:"globalBoolFlags"`
|
||||
GlobalIntFlags map[string]int `json:"globalIntFlags"`
|
||||
GlobalStringFlags map[string]string `json:"globalStringFlags"`
|
||||
CommandType string `json:"commandType"`
|
||||
CommandArgs []string `json:"cmdArgs"`
|
||||
CommandBoolFlags map[string]bool `json:"cmdBoolFlags"`
|
||||
CommandIntFlags map[string]int `json:"cmdIntFlags"`
|
||||
CommandStringFlags map[string]string `json:"cmdStringFlags"`
|
||||
LastCopied string `json:"lastCopied"`
|
||||
TotalBytes int64 `json:"totalBytes"`
|
||||
TotalObjects int `json:"totalObjects"`
|
||||
}
|
||||
|
||||
func loadSessionV6Header(sid string) (*sessionV6Header, *probe.Error) {
|
||||
if !isSessionDirExists() {
|
||||
return nil, errInvalidArgument().Trace()
|
||||
}
|
||||
|
||||
sessionFile, err := getSessionFile(sid)
|
||||
if err != nil {
|
||||
return nil, err.Trace(sid)
|
||||
}
|
||||
|
||||
if _, e := os.Stat(sessionFile); e != nil {
|
||||
return nil, probe.NewError(e)
|
||||
}
|
||||
|
||||
sV6Header := &sessionV6Header{}
|
||||
sV6Header.Version = "6"
|
||||
qs, e := quick.New(sV6Header)
|
||||
if e != nil {
|
||||
return nil, probe.NewError(e).Trace(sid, sV6Header.Version)
|
||||
}
|
||||
e = qs.Load(sessionFile)
|
||||
if e != nil {
|
||||
return nil, probe.NewError(e).Trace(sid, sV6Header.Version)
|
||||
}
|
||||
|
||||
sV6Header = qs.Data().(*sessionV6Header)
|
||||
return sV6Header, nil
|
||||
}
|
||||
|
||||
/////////////////// Session V7 ///////////////////
|
||||
// RESERVED FOR FUTURE
|
||||
|
||||
// sessionV7Header for resumable sessions.
|
||||
type sessionV7Header struct {
|
||||
Version string `json:"version"`
|
||||
When time.Time `json:"time"`
|
||||
RootPath string `json:"workingFolder"`
|
||||
GlobalBoolFlags map[string]bool `json:"globalBoolFlags"`
|
||||
GlobalIntFlags map[string]int `json:"globalIntFlags"`
|
||||
GlobalStringFlags map[string]string `json:"globalStringFlags"`
|
||||
CommandType string `json:"commandType"`
|
||||
CommandArgs []string `json:"cmdArgs"`
|
||||
CommandBoolFlags map[string]bool `json:"cmdBoolFlags"`
|
||||
CommandIntFlags map[string]int `json:"cmdIntFlags"`
|
||||
CommandStringFlags map[string]string `json:"cmdStringFlags"`
|
||||
LastCopied string `json:"lastCopied"`
|
||||
LastRemoved string `json:"lastRemoved"`
|
||||
TotalBytes int64 `json:"totalBytes"`
|
||||
TotalObjects int `json:"totalObjects"`
|
||||
}
|
||||
|
||||
// sessionV7 resumable session container.
|
||||
type sessionV7 struct {
|
||||
Header *sessionV7Header
|
||||
SessionID string
|
||||
mutex *sync.Mutex
|
||||
DataFP *sessionDataFP
|
||||
sigCh bool
|
||||
}
|
||||
|
||||
// loadSessionV7 - reads session file if exists and re-initiates internal variables
|
||||
func loadSessionV7(sid string) (*sessionV7, *probe.Error) {
|
||||
if !isSessionDirExists() {
|
||||
return nil, errInvalidArgument().Trace()
|
||||
}
|
||||
sessionFile, err := getSessionFile(sid)
|
||||
if err != nil {
|
||||
return nil, err.Trace(sid)
|
||||
}
|
||||
|
||||
if _, e := os.Stat(sessionFile); e != nil {
|
||||
return nil, probe.NewError(e)
|
||||
}
|
||||
|
||||
s := &sessionV7{}
|
||||
s.Header = &sessionV7Header{}
|
||||
s.SessionID = sid
|
||||
s.Header.Version = "7"
|
||||
qs, e := quick.New(s.Header)
|
||||
if e != nil {
|
||||
return nil, probe.NewError(e).Trace(sid, s.Header.Version)
|
||||
}
|
||||
e = qs.Load(sessionFile)
|
||||
if e != nil {
|
||||
return nil, probe.NewError(e).Trace(sid, s.Header.Version)
|
||||
}
|
||||
|
||||
s.mutex = new(sync.Mutex)
|
||||
s.Header = qs.Data().(*sessionV7Header)
|
||||
|
||||
sessionDataFile, err := getSessionDataFile(s.SessionID)
|
||||
if err != nil {
|
||||
return nil, err.Trace(sid, s.Header.Version)
|
||||
}
|
||||
|
||||
dataFile, e := os.Open(sessionDataFile)
|
||||
if e != nil {
|
||||
return nil, probe.NewError(e)
|
||||
}
|
||||
s.DataFP = &sessionDataFP{false, dataFile}
|
||||
|
||||
return s, nil
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Minio Client, (C) 2015 Minio, Inc.
|
||||
* Minio Client, (C) 2015, 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.
|
||||
@@ -14,12 +14,13 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
// Session V2 - Version 2 stores session header and session data in
|
||||
// Package cmd - session V8 - Version 8 stores session header and session data in
|
||||
// two separate files. Session data contains fully prepared URL list.
|
||||
package main
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
@@ -28,37 +29,12 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/minio-xl/pkg/quick"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
"github.com/minio/minio/pkg/quick"
|
||||
)
|
||||
|
||||
func migrateSessionV5ToV6() {
|
||||
for _, sid := range getSessionIDs() {
|
||||
sessionV6, err := loadSessionV6(sid)
|
||||
fatalIf(err.Trace(sid), "Unable to load version ‘6’. Migration failed please report this issue at https://github.com/minio/mc/issues.")
|
||||
if sessionV6.Header.Version == "6" { // It is new format.
|
||||
return
|
||||
}
|
||||
/*** Remove all session files older than v6 ***/
|
||||
|
||||
sessionFile, err := getSessionFile(sid)
|
||||
fatalIf(err.Trace(sid), "Unable to get session file.")
|
||||
|
||||
sessionDataFile, err := getSessionDataFile(sid)
|
||||
fatalIf(err.Trace(sid), "Unable to get session data file.")
|
||||
|
||||
console.Println("Removing unsupported session file ‘" + sessionFile + "’ version ‘" + sessionV6.Header.Version + "’.")
|
||||
if e := os.Remove(sessionFile); e != nil {
|
||||
fatalIf(probe.NewError(e), "Unable to remove version ‘"+sessionV6.Header.Version+"’ session file ‘"+sessionFile+"’.")
|
||||
}
|
||||
if e := os.Remove(sessionDataFile); e != nil {
|
||||
fatalIf(probe.NewError(e), "Unable to remove version ‘"+sessionV6.Header.Version+"’ session data file ‘"+sessionDataFile+"’.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// sessionV6Header for resumable sessions.
|
||||
type sessionV6Header struct {
|
||||
// sessionV8Header for resumable sessions.
|
||||
type sessionV8Header struct {
|
||||
Version string `json:"version"`
|
||||
When time.Time `json:"time"`
|
||||
RootPath string `json:"workingFolder"`
|
||||
@@ -71,8 +47,9 @@ type sessionV6Header struct {
|
||||
CommandIntFlags map[string]int `json:"cmdIntFlags"`
|
||||
CommandStringFlags map[string]string `json:"cmdStringFlags"`
|
||||
LastCopied string `json:"lastCopied"`
|
||||
LastRemoved string `json:"lastRemoved"`
|
||||
TotalBytes int64 `json:"totalBytes"`
|
||||
TotalObjects int `json:"totalObjects"`
|
||||
TotalObjects int64 `json:"totalObjects"`
|
||||
}
|
||||
|
||||
// sessionMessage container for session messages
|
||||
@@ -84,9 +61,9 @@ type sessionMessage struct {
|
||||
CommandArgs []string `json:"commandArgs"`
|
||||
}
|
||||
|
||||
// sessionV6 resumable session container.
|
||||
type sessionV6 struct {
|
||||
Header *sessionV6Header
|
||||
// sessionV8 resumable session container.
|
||||
type sessionV8 struct {
|
||||
Header *sessionV8Header
|
||||
SessionID string
|
||||
mutex *sync.Mutex
|
||||
DataFP *sessionDataFP
|
||||
@@ -105,7 +82,7 @@ func (file *sessionDataFP) Write(p []byte) (int, error) {
|
||||
}
|
||||
|
||||
// String colorized session message.
|
||||
func (s sessionV6) String() string {
|
||||
func (s sessionV8) String() string {
|
||||
message := console.Colorize("SessionID", fmt.Sprintf("%s -> ", s.SessionID))
|
||||
message = message + console.Colorize("SessionTime", fmt.Sprintf("[%s]", s.Header.When.Local().Format(printDate)))
|
||||
message = message + console.Colorize("Command", fmt.Sprintf(" %s %s", s.Header.CommandType, strings.Join(s.Header.CommandArgs, " ")))
|
||||
@@ -113,7 +90,7 @@ func (s sessionV6) String() string {
|
||||
}
|
||||
|
||||
// JSON jsonified session message.
|
||||
func (s sessionV6) JSON() string {
|
||||
func (s sessionV8) JSON() string {
|
||||
sessionMsg := sessionMessage{
|
||||
SessionID: s.SessionID,
|
||||
Time: s.Header.When.Local(),
|
||||
@@ -127,8 +104,8 @@ func (s sessionV6) JSON() string {
|
||||
return string(sessionBytes)
|
||||
}
|
||||
|
||||
// loadSessionV6 - reads session file if exists and re-initiates internal variables
|
||||
func loadSessionV6(sid string) (*sessionV6, *probe.Error) {
|
||||
// loadSessionV8 - reads session file if exists and re-initiates internal variables
|
||||
func loadSessionV8(sid string) (*sessionV8, *probe.Error) {
|
||||
if !isSessionDirExists() {
|
||||
return nil, errInvalidArgument().Trace()
|
||||
}
|
||||
@@ -141,41 +118,54 @@ func loadSessionV6(sid string) (*sessionV6, *probe.Error) {
|
||||
return nil, probe.NewError(e)
|
||||
}
|
||||
|
||||
s := &sessionV6{}
|
||||
s.Header = &sessionV6Header{}
|
||||
s.SessionID = sid
|
||||
s.Header.Version = "5"
|
||||
qs, err := quick.New(s.Header)
|
||||
if err != nil {
|
||||
return nil, err.Trace(sid, s.Header.Version)
|
||||
// Initialize new session.
|
||||
s := &sessionV8{
|
||||
Header: &sessionV8Header{
|
||||
Version: globalSessionConfigVersion,
|
||||
},
|
||||
SessionID: sid,
|
||||
}
|
||||
err = qs.Load(sessionFile)
|
||||
if err != nil {
|
||||
return nil, err.Trace(sid, s.Header.Version)
|
||||
|
||||
// Initialize session config loader.
|
||||
qs, e := quick.New(s.Header)
|
||||
if e != nil {
|
||||
return nil, probe.NewError(e).Trace(sid, s.Header.Version)
|
||||
}
|
||||
|
||||
if e = qs.Load(sessionFile); e != nil {
|
||||
return nil, probe.NewError(e).Trace(sid, s.Header.Version)
|
||||
}
|
||||
|
||||
// Validate if the version matches with expected current version.
|
||||
sV8Header := qs.Data().(*sessionV8Header)
|
||||
if sV8Header.Version != globalSessionConfigVersion {
|
||||
msg := fmt.Sprintf("Session header version %s does not match mc session version %s.\n",
|
||||
sV8Header.Version, globalSessionConfigVersion)
|
||||
return nil, probe.NewError(errors.New(msg)).Trace(sid, sV8Header.Version)
|
||||
}
|
||||
|
||||
s.mutex = new(sync.Mutex)
|
||||
s.Header = qs.Data().(*sessionV6Header)
|
||||
s.Header = sV8Header
|
||||
|
||||
sessionDataFile, err := getSessionDataFile(s.SessionID)
|
||||
if err != nil {
|
||||
return nil, err.Trace(sid, s.Header.Version)
|
||||
}
|
||||
|
||||
var e error
|
||||
dataFile, e := os.Open(sessionDataFile)
|
||||
fatalIf(probe.NewError(e), "Unable to open session data file \""+sessionDataFile+"\".")
|
||||
|
||||
if e != nil {
|
||||
return nil, probe.NewError(e)
|
||||
}
|
||||
s.DataFP = &sessionDataFP{false, dataFile}
|
||||
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// newSessionV6 provides a new session.
|
||||
func newSessionV6() *sessionV6 {
|
||||
s := &sessionV6{}
|
||||
s.Header = &sessionV6Header{}
|
||||
s.Header.Version = "6"
|
||||
// newSessionV8 provides a new session.
|
||||
func newSessionV8() *sessionV8 {
|
||||
s := &sessionV8{}
|
||||
s.Header = &sessionV8Header{}
|
||||
s.Header.Version = globalSessionConfigVersion
|
||||
// map of command and files copied.
|
||||
s.Header.GlobalBoolFlags = make(map[string]bool)
|
||||
s.Header.GlobalIntFlags = make(map[string]int)
|
||||
@@ -203,29 +193,29 @@ func newSessionV6() *sessionV6 {
|
||||
}
|
||||
|
||||
// HasData provides true if this is a session resume, false otherwise.
|
||||
func (s sessionV6) HasData() bool {
|
||||
if s.Header.LastCopied == "" {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
func (s sessionV8) HasData() bool {
|
||||
return s.Header.LastCopied != "" || s.Header.LastRemoved != ""
|
||||
}
|
||||
|
||||
// NewDataReader provides reader interface to session data file.
|
||||
func (s *sessionV6) NewDataReader() io.Reader {
|
||||
func (s *sessionV8) NewDataReader() io.Reader {
|
||||
// DataFP is always intitialized, either via new or load functions.
|
||||
s.DataFP.Seek(0, os.SEEK_SET)
|
||||
return io.Reader(s.DataFP)
|
||||
}
|
||||
|
||||
// NewDataReader provides writer interface to session data file.
|
||||
func (s *sessionV6) NewDataWriter() io.Writer {
|
||||
func (s *sessionV8) NewDataWriter() io.Writer {
|
||||
// DataFP is always intitialized, either via new or load functions.
|
||||
s.DataFP.Seek(0, os.SEEK_SET)
|
||||
// when moving to file position 0 we want to truncate the file as well,
|
||||
// otherwise we'll partly overwrite existing data
|
||||
s.DataFP.Truncate(0)
|
||||
return io.Writer(s.DataFP)
|
||||
}
|
||||
|
||||
// Save this session.
|
||||
func (s *sessionV6) Save() *probe.Error {
|
||||
func (s *sessionV8) Save() *probe.Error {
|
||||
s.mutex.Lock()
|
||||
defer s.mutex.Unlock()
|
||||
|
||||
@@ -236,39 +226,102 @@ func (s *sessionV6) Save() *probe.Error {
|
||||
s.DataFP.dirty = false
|
||||
}
|
||||
|
||||
qs, err := quick.New(s.Header)
|
||||
if err != nil {
|
||||
return err.Trace(s.SessionID)
|
||||
qs, e := quick.New(s.Header)
|
||||
if e != nil {
|
||||
return probe.NewError(e).Trace(s.SessionID)
|
||||
}
|
||||
|
||||
sessionFile, err := getSessionFile(s.SessionID)
|
||||
if err != nil {
|
||||
return err.Trace(s.SessionID)
|
||||
}
|
||||
return qs.Save(sessionFile).Trace(sessionFile)
|
||||
e = qs.Save(sessionFile)
|
||||
if e != nil {
|
||||
return probe.NewError(e).Trace(sessionFile)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// setGlobals captures the state of global variables into session header.
|
||||
// Used by newSession.
|
||||
func (s *sessionV6) setGlobals() {
|
||||
func (s *sessionV8) setGlobals() {
|
||||
s.Header.GlobalBoolFlags["quiet"] = globalQuiet
|
||||
s.Header.GlobalBoolFlags["debug"] = globalDebug
|
||||
s.Header.GlobalBoolFlags["json"] = globalJSON
|
||||
s.Header.GlobalBoolFlags["noColor"] = globalNoColor
|
||||
s.Header.GlobalBoolFlags["insecure"] = globalInsecure
|
||||
}
|
||||
|
||||
// RestoreGlobals restores the state of global variables.
|
||||
// Used by resumeSession.
|
||||
func (s sessionV6) restoreGlobals() {
|
||||
func (s sessionV8) restoreGlobals() {
|
||||
quiet := s.Header.GlobalBoolFlags["quiet"]
|
||||
debug := s.Header.GlobalBoolFlags["debug"]
|
||||
json := s.Header.GlobalBoolFlags["json"]
|
||||
noColor := s.Header.GlobalBoolFlags["noColor"]
|
||||
setGlobals(quiet, debug, json, noColor)
|
||||
insecure := s.Header.GlobalBoolFlags["insecure"]
|
||||
setGlobals(quiet, debug, json, noColor, insecure)
|
||||
}
|
||||
|
||||
// IsModified - returns if in memory session header has changed from
|
||||
// its on disk value.
|
||||
func (s *sessionV8) isModified(sessionFile string) (bool, *probe.Error) {
|
||||
qs, e := quick.New(s.Header)
|
||||
if e != nil {
|
||||
return false, probe.NewError(e).Trace(s.SessionID)
|
||||
}
|
||||
|
||||
var currentHeader = &sessionV8Header{}
|
||||
currentQS, e := quick.Load(sessionFile, currentHeader)
|
||||
if e != nil {
|
||||
// If session does not exist for the first, return modified to
|
||||
// be true.
|
||||
if os.IsNotExist(e) {
|
||||
return true, nil
|
||||
}
|
||||
// For all other errors return.
|
||||
return false, probe.NewError(e).Trace(s.SessionID)
|
||||
}
|
||||
|
||||
changedFields, e := qs.DeepDiff(currentQS)
|
||||
if e != nil {
|
||||
return false, probe.NewError(e).Trace(s.SessionID)
|
||||
}
|
||||
|
||||
// Returns true if there are changed entries.
|
||||
return len(changedFields) > 0, nil
|
||||
}
|
||||
|
||||
// save - wrapper for quick.Save and saves only if sessionHeader is
|
||||
// modified.
|
||||
func (s *sessionV8) save() *probe.Error {
|
||||
sessionFile, err := getSessionFile(s.SessionID)
|
||||
if err != nil {
|
||||
return err.Trace(s.SessionID)
|
||||
}
|
||||
|
||||
// Verify if sessionFile is modified.
|
||||
modified, err := s.isModified(sessionFile)
|
||||
if err != nil {
|
||||
return err.Trace(s.SessionID)
|
||||
}
|
||||
// Header is modified, we save it.
|
||||
if modified {
|
||||
qs, e := quick.New(s.Header)
|
||||
if e != nil {
|
||||
return probe.NewError(e).Trace(s.SessionID)
|
||||
}
|
||||
// Save an return.
|
||||
e = qs.Save(sessionFile)
|
||||
if e != nil {
|
||||
return probe.NewError(e).Trace(sessionFile)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Close ends this session and removes all associated session files.
|
||||
func (s *sessionV6) Close() *probe.Error {
|
||||
func (s *sessionV8) Close() *probe.Error {
|
||||
s.mutex.Lock()
|
||||
defer s.mutex.Unlock()
|
||||
|
||||
@@ -276,20 +329,12 @@ func (s *sessionV6) Close() *probe.Error {
|
||||
return probe.NewError(err)
|
||||
}
|
||||
|
||||
qs, err := quick.New(s.Header)
|
||||
if err != nil {
|
||||
return err.Trace()
|
||||
}
|
||||
|
||||
sessionFile, err := getSessionFile(s.SessionID)
|
||||
if err != nil {
|
||||
return err.Trace(s.SessionID)
|
||||
}
|
||||
return qs.Save(sessionFile).Trace(sessionFile)
|
||||
// Attempt to save the header if modified.
|
||||
return s.save()
|
||||
}
|
||||
|
||||
// Delete removes all the session files.
|
||||
func (s *sessionV6) Delete() *probe.Error {
|
||||
func (s *sessionV8) Delete() *probe.Error {
|
||||
s.mutex.Lock()
|
||||
defer s.mutex.Unlock()
|
||||
|
||||
@@ -300,45 +345,50 @@ func (s *sessionV6) Delete() *probe.Error {
|
||||
// the file is closed already
|
||||
s.DataFP.Close()
|
||||
|
||||
// Remove the data file.
|
||||
if e := os.Remove(name); e != nil {
|
||||
return probe.NewError(e)
|
||||
}
|
||||
}
|
||||
|
||||
// Fetch the session file.
|
||||
sessionFile, err := getSessionFile(s.SessionID)
|
||||
if err != nil {
|
||||
return err.Trace(s.SessionID)
|
||||
}
|
||||
|
||||
// Remove session file
|
||||
if e := os.Remove(sessionFile); e != nil {
|
||||
return probe.NewError(e)
|
||||
}
|
||||
|
||||
// Remove session backup file if any, ignore any error.
|
||||
os.Remove(sessionFile + ".old")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Close a session and exit.
|
||||
func (s sessionV6) CloseAndDie() {
|
||||
func (s sessionV8) CloseAndDie() {
|
||||
s.Close()
|
||||
console.Fatalln("Session safely terminated. To resume session ‘mc session resume " + s.SessionID + "’")
|
||||
}
|
||||
|
||||
// Create a factory function to simplify checking if an
|
||||
// object has been copied or not.
|
||||
// isCopied(URL) -> true or false
|
||||
func isCopiedFactory(lastCopied string) func(string) bool {
|
||||
copied := true // closure
|
||||
// Create a factory function to simplify checking if
|
||||
// object was last operated on.
|
||||
func isLastFactory(lastURL string) func(string) bool {
|
||||
last := true // closure
|
||||
return func(sourceURL string) bool {
|
||||
if sourceURL == "" {
|
||||
fatalIf(errInvalidArgument().Trace(), "Empty source argument passed.")
|
||||
}
|
||||
if lastCopied == "" {
|
||||
if lastURL == "" {
|
||||
return false
|
||||
}
|
||||
|
||||
if copied {
|
||||
if lastCopied == sourceURL {
|
||||
copied = false // from next call onwards we say false.
|
||||
if last {
|
||||
if lastURL == sourceURL {
|
||||
last = false // from next call onwards we say false.
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -14,20 +14,26 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
// migrateSession migrates all previous migration to latest.
|
||||
func migrateSession() {
|
||||
// We no longer support sessions older than v5. They will be removed.
|
||||
migrateSessionV5ToV6()
|
||||
|
||||
// Migrate V6 to V7.
|
||||
migrateSessionV6ToV7()
|
||||
|
||||
// Migrate V7 to V8
|
||||
migrateSessionV7ToV8()
|
||||
}
|
||||
|
||||
// createSessionDir - create session directory.
|
||||
@@ -112,3 +118,21 @@ func getSessionIDs() (sids []string) {
|
||||
}
|
||||
return sids
|
||||
}
|
||||
|
||||
// removeSessionFile - remove the session file, ending with .json
|
||||
func removeSessionFile(sid string) {
|
||||
sessionFile, err := getSessionFile(sid)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
os.Remove(sessionFile)
|
||||
}
|
||||
|
||||
// removeSessionDataFile - remove the session data file, ending with .data
|
||||
func removeSessionDataFile(sid string) {
|
||||
dataFile, err := getSessionDataFile(sid)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
os.Remove(dataFile)
|
||||
}
|
||||
@@ -14,9 +14,10 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"os"
|
||||
"regexp"
|
||||
|
||||
. "gopkg.in/check.v1"
|
||||
@@ -34,14 +35,17 @@ func (s *TestSuite) TestSession(c *C) {
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(isSessionDirExists(), Equals, true)
|
||||
|
||||
session := newSessionV6()
|
||||
session := newSessionV8()
|
||||
c.Assert(session.Header.CommandArgs, IsNil)
|
||||
c.Assert(len(session.SessionID), Equals, 8)
|
||||
_, e := os.Stat(session.DataFP.Name())
|
||||
c.Assert(e, IsNil)
|
||||
|
||||
err = session.Close()
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(isSessionExists(session.SessionID), Equals, true)
|
||||
|
||||
savedSession, err := loadSessionV6(session.SessionID)
|
||||
savedSession, err := loadSessionV8(session.SessionID)
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(session.SessionID, Equals, savedSession.SessionID)
|
||||
|
||||
@@ -50,4 +54,7 @@ func (s *TestSuite) TestSession(c *C) {
|
||||
|
||||
err = savedSession.Delete()
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(isSessionExists(session.SessionID), Equals, false)
|
||||
_, e = os.Stat(session.DataFP.Name())
|
||||
c.Assert(e, NotNil)
|
||||
}
|
||||
@@ -14,15 +14,15 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"os"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/minio-xl/pkg/quick"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
"github.com/minio/minio/pkg/quick"
|
||||
)
|
||||
|
||||
// shareEntryV1 - container for each download/upload entries.
|
||||
@@ -94,13 +94,13 @@ func (s *shareDBV1) Load(filename string) *probe.Error {
|
||||
}
|
||||
|
||||
// Initialize and load using quick package.
|
||||
qs, err := quick.New(newShareDBV1())
|
||||
if err != nil {
|
||||
return err.Trace(filename)
|
||||
qs, e := quick.New(newShareDBV1())
|
||||
if e != nil {
|
||||
return probe.NewError(e).Trace(filename)
|
||||
}
|
||||
err = qs.Load(filename)
|
||||
if err != nil {
|
||||
return err.Trace(filename)
|
||||
e = qs.Load(filename)
|
||||
if e != nil {
|
||||
return probe.NewError(e).Trace(filename)
|
||||
}
|
||||
|
||||
// Copy map over.
|
||||
@@ -118,11 +118,14 @@ func (s *shareDBV1) Load(filename string) *probe.Error {
|
||||
// Persist share uploads to disk.
|
||||
func (s shareDBV1) save(filename string) *probe.Error {
|
||||
// Initialize a new quick file.
|
||||
qs, err := quick.New(s)
|
||||
if err != nil {
|
||||
return err.Trace(filename)
|
||||
qs, e := quick.New(s)
|
||||
if e != nil {
|
||||
return probe.NewError(e).Trace(filename)
|
||||
}
|
||||
return qs.Save(filename).Trace(filename)
|
||||
if e := qs.Save(filename); e != nil {
|
||||
return probe.NewError(e).Trace(filename)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Persist share uploads to disk.
|
||||
@@ -14,21 +14,17 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
var (
|
||||
shareDownloadFlags = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "help, h",
|
||||
Usage: "Help of share download",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "recursive, r",
|
||||
Usage: "Share all objects recursively.",
|
||||
@@ -42,6 +38,7 @@ var shareDownload = cli.Command{
|
||||
Name: "download",
|
||||
Usage: "Generate URLs for download access.",
|
||||
Action: mainShareDownload,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(shareDownloadFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
mc share {{.Name}} - {{.Usage}}
|
||||
@@ -117,8 +114,8 @@ func doShareDownloadURL(targetURL string, isRecursive bool, expiry time.Duration
|
||||
}
|
||||
|
||||
// Generate share URL for each target.
|
||||
incomplete := false
|
||||
for content := range clnt.List(isRecursive, incomplete) {
|
||||
isIncomplete := false
|
||||
for content := range clnt.List(isRecursive, isIncomplete, DirNone) {
|
||||
if content.Err != nil {
|
||||
return content.Err.Trace(clnt.GetURL().String())
|
||||
}
|
||||
@@ -155,9 +152,7 @@ func doShareDownloadURL(targetURL string, isRecursive bool, expiry time.Duration
|
||||
}
|
||||
|
||||
// main for share download.
|
||||
func mainShareDownload(ctx *cli.Context) {
|
||||
// Set global flags from context.
|
||||
setGlobalsFromContext(ctx)
|
||||
func mainShareDownload(ctx *cli.Context) error {
|
||||
|
||||
// check input arguments.
|
||||
checkShareDownloadSyntax(ctx)
|
||||
@@ -179,6 +174,14 @@ func mainShareDownload(ctx *cli.Context) {
|
||||
|
||||
for _, targetURL := range ctx.Args() {
|
||||
err := doShareDownloadURL(targetURL, isRecursive, expiry)
|
||||
fatalIf(err.Trace(targetURL), "Unable to share target ‘"+targetURL+"’.")
|
||||
if err != nil {
|
||||
switch err.ToGoError().(type) {
|
||||
case APINotImplemented:
|
||||
fatalIf(err.Trace(), "Unable to share a non S3 url ‘"+targetURL+"’.")
|
||||
default:
|
||||
fatalIf(err.Trace(targetURL), "Unable to share target ‘"+targetURL+"’.")
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -14,23 +14,18 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
var (
|
||||
shareListFlags = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "help, h",
|
||||
Usage: "Help of share list.",
|
||||
},
|
||||
}
|
||||
shareListFlags = []cli.Flag{}
|
||||
)
|
||||
|
||||
// Share documents via URL.
|
||||
@@ -38,6 +33,7 @@ var shareList = cli.Command{
|
||||
Name: "list",
|
||||
Usage: "List previously shared objects and folders.",
|
||||
Action: mainShareList,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(shareListFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
mc share {{.Name}} COMMAND - {{.Usage}}
|
||||
@@ -68,7 +64,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.
|
||||
@@ -105,9 +101,7 @@ func doShareList(cmd string) *probe.Error {
|
||||
}
|
||||
|
||||
// main entry point for share list.
|
||||
func mainShareList(ctx *cli.Context) {
|
||||
// Set global flags from context.
|
||||
setGlobalsFromContext(ctx)
|
||||
func mainShareList(ctx *cli.Context) error {
|
||||
|
||||
// validate command-line args.
|
||||
checkShareListSyntax(ctx)
|
||||
@@ -120,4 +114,5 @@ func mainShareList(ctx *cli.Context) {
|
||||
|
||||
// List shares.
|
||||
fatalIf(doShareList(ctx.Args().First()).Trace(), "Unable to list previously shared URLs.")
|
||||
return nil
|
||||
}
|
||||
@@ -14,7 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"os"
|
||||
@@ -22,16 +22,11 @@ import (
|
||||
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
var (
|
||||
shareFlags = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "help, h",
|
||||
Usage: "Help of share.",
|
||||
},
|
||||
}
|
||||
shareFlags = []cli.Flag{}
|
||||
)
|
||||
|
||||
// Share documents via URL.
|
||||
@@ -39,6 +34,7 @@ var shareCmd = cli.Command{
|
||||
Name: "share",
|
||||
Usage: "Generate URL for sharing.",
|
||||
Action: mainShare,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(shareFlags, globalFlags...),
|
||||
Subcommands: []cli.Command{
|
||||
shareDownload,
|
||||
@@ -77,9 +73,7 @@ func migrateShare() {
|
||||
}
|
||||
|
||||
// mainShare - main handler for mc share command.
|
||||
func mainShare(ctx *cli.Context) {
|
||||
// Set global flags from context.
|
||||
setGlobalsFromContext(ctx)
|
||||
func mainShare(ctx *cli.Context) error {
|
||||
|
||||
if ctx.Args().First() != "" { // command help.
|
||||
cli.ShowCommandHelp(ctx, ctx.Args().First())
|
||||
@@ -87,5 +81,6 @@ func mainShare(ctx *cli.Context) {
|
||||
cli.ShowAppHelp(ctx)
|
||||
}
|
||||
|
||||
return nil
|
||||
// Sub-commands like "upload" and "download" have their own main.
|
||||
}
|
||||
@@ -14,7 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
@@ -22,16 +22,11 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/client"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
var (
|
||||
shareUploadFlags = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "help, h",
|
||||
Usage: "Help of share download.",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "recursive, r",
|
||||
Usage: "Recursively upload any object matching the prefix.",
|
||||
@@ -46,6 +41,7 @@ var shareUpload = cli.Command{
|
||||
Name: "upload",
|
||||
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}}
|
||||
@@ -101,7 +97,7 @@ func checkShareUploadSyntax(ctx *cli.Context) {
|
||||
}
|
||||
|
||||
for _, targetURL := range ctx.Args() {
|
||||
url := client.NewURL(targetURL)
|
||||
url := newClientURL(targetURL)
|
||||
if strings.HasSuffix(targetURL, string(url.Separator)) && !isRecursive {
|
||||
fatalIf(errInvalidArgument().Trace(targetURL),
|
||||
"Use --recursive option to generate curl command for prefixes.")
|
||||
@@ -110,12 +106,7 @@ func checkShareUploadSyntax(ctx *cli.Context) {
|
||||
}
|
||||
|
||||
// makeCurlCmd constructs curl command-line.
|
||||
func makeCurlCmd(key string, isRecursive bool, uploadInfo map[string]string) string {
|
||||
URL := client.NewURL(key)
|
||||
postURL := URL.Scheme + URL.SchemeSeparator + URL.Host + string(URL.Separator)
|
||||
if !isBucketVirtualStyle(URL.Host) {
|
||||
postURL = postURL + uploadInfo["bucket"]
|
||||
}
|
||||
func makeCurlCmd(key, postURL string, isRecursive bool, uploadInfo map[string]string) (string, *probe.Error) {
|
||||
postURL += " "
|
||||
curlCommand := "curl " + postURL
|
||||
for k, v := range uploadInfo {
|
||||
@@ -132,7 +123,7 @@ func makeCurlCmd(key string, isRecursive bool, uploadInfo map[string]string) str
|
||||
curlCommand += fmt.Sprintf("-F key=%s ", key) // Object name.
|
||||
}
|
||||
curlCommand += "-F file=@<FILE>" // File to upload.
|
||||
return curlCommand
|
||||
return curlCommand, nil
|
||||
}
|
||||
|
||||
// save shared URL to disk.
|
||||
@@ -158,7 +149,7 @@ func doShareUploadURL(objectURL string, isRecursive bool, expiry time.Duration,
|
||||
}
|
||||
|
||||
// Generate pre-signed access info.
|
||||
uploadInfo, err := clnt.ShareUpload(isRecursive, expiry, contentType)
|
||||
shareURL, uploadInfo, err := clnt.ShareUpload(isRecursive, expiry, contentType)
|
||||
if err != nil {
|
||||
return err.Trace(objectURL, "expiry="+expiry.String(), "contentType="+contentType)
|
||||
}
|
||||
@@ -167,7 +158,10 @@ func doShareUploadURL(objectURL string, isRecursive bool, expiry time.Duration,
|
||||
objectURL = clnt.GetURL().String()
|
||||
|
||||
// Generate curl command.
|
||||
curlCmd := makeCurlCmd(objectURL, isRecursive, uploadInfo)
|
||||
curlCmd, err := makeCurlCmd(objectURL, shareURL, isRecursive, uploadInfo)
|
||||
if err != nil {
|
||||
return err.Trace(objectURL)
|
||||
}
|
||||
|
||||
printMsg(shareMesssage{
|
||||
ObjectURL: objectURL,
|
||||
@@ -181,9 +175,7 @@ func doShareUploadURL(objectURL string, isRecursive bool, expiry time.Duration,
|
||||
}
|
||||
|
||||
// main for share upload command.
|
||||
func mainShareUpload(ctx *cli.Context) {
|
||||
// Set global flags from context.
|
||||
setGlobalsFromContext(ctx)
|
||||
func mainShareUpload(ctx *cli.Context) error {
|
||||
|
||||
// check input arguments.
|
||||
checkShareUploadSyntax(ctx)
|
||||
@@ -207,6 +199,14 @@ func mainShareUpload(ctx *cli.Context) {
|
||||
|
||||
for _, targetURL := range ctx.Args() {
|
||||
err := doShareUploadURL(targetURL, isRecursive, expiry, contentType)
|
||||
fatalIf(err.Trace(targetURL), "Unable to generate curl command for upload ‘"+targetURL+"’.")
|
||||
if err != nil {
|
||||
switch err.ToGoError().(type) {
|
||||
case APINotImplemented:
|
||||
fatalIf(err.Trace(), "Unable to share a non S3 url ‘"+targetURL+"’.")
|
||||
default:
|
||||
fatalIf(err.Trace(targetURL), "Unable to generate curl command for upload ‘"+targetURL+"’.")
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -14,7 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
@@ -28,7 +28,7 @@ import (
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -95,7 +95,7 @@ func (s shareMesssage) JSON() string {
|
||||
// shareSetColor sets colors share sub-commands.
|
||||
func shareSetColor() {
|
||||
// Additional command speific theme customization.
|
||||
console.SetColor("URL", color.New(color.FgWhite, color.Bold))
|
||||
console.SetColor("URL", color.New(color.Bold))
|
||||
console.SetColor("Expire", color.New(color.FgCyan))
|
||||
console.SetColor("Content-type", color.New(color.FgBlue))
|
||||
console.SetColor("Share", color.New(color.FgGreen))
|
||||
@@ -14,7 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"os"
|
||||
@@ -38,6 +38,9 @@ func signalTrap(sig ...os.Signal) <-chan bool {
|
||||
// Wait for the signal.
|
||||
<-sigCh
|
||||
|
||||
// Once signal has been received stop signal Notify handler.
|
||||
signal.Stop(sigCh)
|
||||
|
||||
// Notify the caller.
|
||||
trapCh <- true
|
||||
}(trapCh)
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user