Compare commits
12
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
897dc478be | ||
|
|
bb972dde65 | ||
|
|
f14f61e47c | ||
|
|
06ea8746d3 | ||
|
|
9318e1b7a7 | ||
|
|
4dab718e87 | ||
|
|
4c955aba31 | ||
|
|
5f0b4dcf4b | ||
|
|
b9e090f48a | ||
|
|
dbd79a6da1 | ||
|
|
4c2d094a4a | ||
|
|
860e03059a |
@@ -0,0 +1,3 @@
|
||||
.git
|
||||
.gitea
|
||||
out
|
||||
@@ -0,0 +1,221 @@
|
||||
name: release
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: ['**']
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
group: release-${{ github.ref }}
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
release:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 45
|
||||
permissions:
|
||||
contents: read
|
||||
env:
|
||||
KIND: mc
|
||||
BIN: mc
|
||||
PKG: minio-mc
|
||||
REGISTRY: git.vezha.io
|
||||
steps:
|
||||
- name: AC1 checkout the recipe
|
||||
uses: https://git.vezha.io/actions/checkout@v4
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: AC2 pins are complete and well formed
|
||||
id: pins
|
||||
run: sh vezha/gates.sh pins "$KIND" | tee -a "$GITHUB_ENV" | tee -a "$GITHUB_OUTPUT"
|
||||
|
||||
- name: AC3 no unpinned reference and workflow lint
|
||||
run: sh vezha/gates.sh refs "$KIND"
|
||||
|
||||
- name: tools docker cli and jq
|
||||
run: |
|
||||
command -v docker >/dev/null 2>&1 || { apt-get update -qq; DEBIAN_FRONTEND=noninteractive apt-get install -y -qq docker.io >/dev/null; }
|
||||
command -v jq >/dev/null 2>&1 || { apt-get update -qq; DEBIAN_FRONTEND=noninteractive apt-get install -y -qq jq >/dev/null; }
|
||||
docker version --format 'client {{.Client.Version}} server {{.Server.Version}}'
|
||||
jq --version
|
||||
|
||||
- name: AC1 provenance of the import, anonymous
|
||||
run: sh vezha/gates.sh provenance-remote
|
||||
|
||||
- name: AC1 checkout the pinned upstream source
|
||||
uses: https://git.vezha.io/actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ steps.pins.outputs.UPSTREAM_COMMIT }}
|
||||
path: src
|
||||
fetch-depth: 1
|
||||
persist-credentials: false
|
||||
|
||||
- name: AC1 source tree is at the pinned commit
|
||||
run: sh vezha/gates.sh provenance-src
|
||||
|
||||
- name: AC7 source offer URLs answer anonymously
|
||||
run: sh vezha/gates.sh source-urls
|
||||
|
||||
- name: negative controls, every gate must refuse its planted input
|
||||
run: sh vezha/gates.sh self-test
|
||||
|
||||
- name: names and build arguments
|
||||
run: |
|
||||
TAG=$(sh vezha/gates.sh make-tag)
|
||||
{ echo "TAG=$TAG"; echo "IMG=$REGISTRY/para/$PKG:$TAG"; echo "LOCAL=vezha-build-$KIND:$GITHUB_RUN_ID"; } >> "$GITHUB_ENV"
|
||||
mkdir -p out
|
||||
sh vezha/gates.sh pins "$KIND" | sed 's/^/--build-arg=/' > out/build-args
|
||||
echo "tag $TAG"
|
||||
|
||||
- name: AC2 pins stage proves the source tree and the module
|
||||
run: |
|
||||
mapfile -t ARGS < out/build-args
|
||||
docker build --target pins -f vezha/Dockerfile "${ARGS[@]}" -t "$LOCAL-pins" .
|
||||
|
||||
- name: AC4 build stage and binary hash A
|
||||
run: |
|
||||
mapfile -t ARGS < out/build-args
|
||||
docker build --target build -f vezha/Dockerfile "${ARGS[@]}" -t "$LOCAL-build" .
|
||||
cid=$(docker create "$LOCAL-build")
|
||||
docker cp "$cid:/out/$BIN" "out/$BIN.a"
|
||||
docker cp "$cid:/out/$BIN.sha256" out/sha.a
|
||||
docker rm "$cid" > /dev/null
|
||||
A=$(sha256sum "out/$BIN.a" | cut -d' ' -f1)
|
||||
if [ "$A" != "$(cat out/sha.a)" ]; then
|
||||
echo "REFUSED build: the extracted binary does not match the build stage's sha file"
|
||||
exit 1
|
||||
fi
|
||||
echo "BINARY_SHA256=$A" >> "$GITHUB_ENV"
|
||||
echo "binary sha256 A: $A"
|
||||
|
||||
- name: AC6 final image and content check
|
||||
run: |
|
||||
mapfile -t ARGS < out/build-args
|
||||
sh vezha/gates.sh render-source vezha/SOURCE.tmpl vezha/SOURCE
|
||||
docker build -f vezha/Dockerfile "${ARGS[@]}" "--build-arg=RECIPE_COMMIT=$GITHUB_SHA" "--build-arg=BINARY_SHA256=$BINARY_SHA256" -t "$IMG" .
|
||||
RECIPE_COMMIT="$GITHUB_SHA" sh vezha/check-image.sh "$KIND" "$IMG"
|
||||
|
||||
- name: AC4 version output carries the pinned release and commit
|
||||
run: |
|
||||
out=$(docker run --rm --label "io.vezha.smoke=$GITHUB_RUN_ID" "$IMG" --version)
|
||||
echo "$out"
|
||||
case "$out" in
|
||||
*"$UPSTREAM_RELEASE"*"commit-id=$UPSTREAM_COMMIT"*) echo "version output names $UPSTREAM_RELEASE and $UPSTREAM_COMMIT" ;;
|
||||
*) echo "REFUSED version: --version does not name $UPSTREAM_RELEASE and commit-id=$UPSTREAM_COMMIT"; exit 1 ;;
|
||||
esac
|
||||
|
||||
- name: AC5 reproducible, second no-cache build of the build stage
|
||||
run: |
|
||||
mapfile -t ARGS < out/build-args
|
||||
docker build --no-cache --target build -f vezha/Dockerfile "${ARGS[@]}" -t "$LOCAL-build2" .
|
||||
cid=$(docker create "$LOCAL-build2")
|
||||
docker cp "$cid:/out/$BIN" "out/$BIN.b"
|
||||
docker rm "$cid" > /dev/null
|
||||
B=$(sha256sum "out/$BIN.b" | cut -d' ' -f1)
|
||||
if [ "$B" != "$BINARY_SHA256" ]; then
|
||||
echo "REFUSED reproducible: second build has sha256 $B, first has $BINARY_SHA256"
|
||||
exit 1
|
||||
fi
|
||||
echo "both builds have sha256 $B"
|
||||
|
||||
- name: AC7 source offer in the image resolves anonymously
|
||||
run: sh vezha/gates.sh source-offer "$IMG" "$KIND" "$UPSTREAM_RELEASE"
|
||||
|
||||
- name: AC8 smoke against the stopgap server
|
||||
run: sh vezha/smoke.sh smoke git.vezha.io/para/minio@sha256:a1a8bd4ac40ad7881a245bab97323e18f971e4d4cba2c2007ec1bedd21cbaba2 "$IMG"
|
||||
|
||||
- name: AC10 preflight, write-once tag and the stopgap tags before
|
||||
run: |
|
||||
sh vezha/gates.sh preflight "$KIND" "$GITHUB_REF" "${MC_IMAGE:-}"
|
||||
sh vezha/gates.sh tag "$PKG" "$TAG"
|
||||
sh vezha/gates.sh stopgap | tee out/stopgap.before
|
||||
|
||||
- name: publish tools, pinned syft and oras installed before any login
|
||||
if: github.ref == 'refs/heads/vezha'
|
||||
run: |
|
||||
curl -fsSLO https://github.com/anchore/syft/releases/download/v1.50.0/syft_1.50.0_linux_amd64.tar.gz
|
||||
echo "bf7b29ff57f06da30918266a0e1c2885a8f99784798d1bdb1628886aa015d788 syft_1.50.0_linux_amd64.tar.gz" | sha256sum -c -
|
||||
tar -xzf syft_1.50.0_linux_amd64.tar.gz syft
|
||||
install -m 0755 syft /usr/local/bin/syft
|
||||
curl -fsSLO https://github.com/oras-project/oras/releases/download/v1.3.3/oras_1.3.3_linux_amd64.tar.gz
|
||||
echo "9ce999f8d2de03fc03968b29d743077a58783e545e5eaa53917ca177352d0e59 oras_1.3.3_linux_amd64.tar.gz" | sha256sum -c -
|
||||
tar -xzf oras_1.3.3_linux_amd64.tar.gz oras
|
||||
install -m 0755 oras /usr/local/bin/oras
|
||||
syft version
|
||||
oras version
|
||||
|
||||
- name: publish SBOM generated before the image
|
||||
if: github.ref == 'refs/heads/vezha'
|
||||
run: |
|
||||
syft "docker:$IMG" -o "spdx-json=out/sbom.spdx.json"
|
||||
test -s out/sbom.spdx.json
|
||||
|
||||
- name: publish login to the registry
|
||||
if: github.ref == 'refs/heads/vezha'
|
||||
env:
|
||||
REGISTRY_USER: ${{ secrets.REGISTRY_USER || github.actor }}
|
||||
REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }}
|
||||
run: |
|
||||
sh vezha/gates.sh login-guard
|
||||
echo "$REGISTRY_TOKEN" | docker login "$REGISTRY" -u "$REGISTRY_USER" --password-stdin
|
||||
|
||||
- name: publish SBOM artifact pushed before the image
|
||||
if: github.ref == 'refs/heads/vezha'
|
||||
run: cd out && oras push "$REGISTRY/para/$PKG-sbom:$TAG" --artifact-type application/spdx+json sbom.spdx.json:application/spdx+json
|
||||
|
||||
- name: publish the image and cross-check its digest
|
||||
if: github.ref == 'refs/heads/vezha'
|
||||
run: |
|
||||
docker push "$IMG" | tee out/push.log
|
||||
D=$(sed -n 's/.*digest: \(sha256:[0-9a-f]\{64\}\).*/\1/p' out/push.log | tail -1)
|
||||
if [ -z "$D" ]; then
|
||||
echo "REFUSED push: no digest in the push output"
|
||||
exit 1
|
||||
fi
|
||||
R=$(sh vezha/gates.sh digest "$PKG" "$TAG")
|
||||
if [ "$R" != "$D" ]; then
|
||||
echo "REFUSED push: docker push printed $D but the registry serves $R for $TAG"
|
||||
exit 1
|
||||
fi
|
||||
echo "DIGEST=$D" >> "$GITHUB_ENV"
|
||||
|
||||
- name: publish AC11 digest proof, pull by digest and compare the binary
|
||||
if: github.ref == 'refs/heads/vezha'
|
||||
run: |
|
||||
REF="$REGISTRY/para/$PKG@$DIGEST"
|
||||
docker rmi "$IMG" > /dev/null
|
||||
sh vezha/gates.sh prove "$REF" "$BIN" "$BINARY_SHA256"
|
||||
docker run --rm --label "io.vezha.smoke=$GITHUB_RUN_ID" "$REF" --version
|
||||
oras pull "$REGISTRY/para/$PKG-sbom:$TAG" -o out/sbom-back
|
||||
grep -q '"spdxVersion"' out/sbom-back/sbom.spdx.json
|
||||
echo "the SBOM was pulled back and is SPDX JSON"
|
||||
|
||||
- name: publish AC11 the PUBLISHED line
|
||||
if: github.ref == 'refs/heads/vezha'
|
||||
run: |
|
||||
LINE="PUBLISHED $REGISTRY/para/$PKG@$DIGEST tag=$TAG binary-sha256=$BINARY_SHA256"
|
||||
echo "$LINE" | grep -Eq '^PUBLISHED git\.vezha\.io/para/(minio|minio-mc)@sha256:[0-9a-f]{64} tag=[a-z0-9._-]+ binary-sha256=[0-9a-f]{64}$' || { echo "REFUSED published: malformed line"; exit 1; }
|
||||
echo "$LINE"
|
||||
echo "$LINE" > out/published.txt
|
||||
cd out && oras push "$REGISTRY/para/$PKG-published:$TAG" published.txt:text/plain
|
||||
|
||||
- name: publish AC10 stopgap tags unchanged after the run
|
||||
if: github.ref == 'refs/heads/vezha'
|
||||
run: |
|
||||
sh vezha/gates.sh stopgap > out/stopgap.after
|
||||
diff out/stopgap.before out/stopgap.after
|
||||
echo "the stopgap tags resolve to the same digests as before the run"
|
||||
|
||||
- name: publish AC7 source offer of the pulled digest resolves anonymously
|
||||
if: github.ref == 'refs/heads/vezha'
|
||||
run: sh vezha/gates.sh source-offer "$REGISTRY/para/$PKG@$DIGEST" "$KIND" "$UPSTREAM_RELEASE"
|
||||
|
||||
- name: cleanup of this run's containers, networks, volumes and images
|
||||
if: always()
|
||||
run: |
|
||||
for c in $(docker ps -aq --filter "label=io.vezha.smoke=$GITHUB_RUN_ID"); do docker rm -f "$c" > /dev/null 2>&1 || true; done
|
||||
for n in $(docker network ls -q --filter "label=io.vezha.smoke=$GITHUB_RUN_ID"); do docker network rm "$n" > /dev/null 2>&1 || true; done
|
||||
for v in $(docker volume ls -q --filter "label=io.vezha.smoke=$GITHUB_RUN_ID"); do docker volume rm "$v" > /dev/null 2>&1 || true; done
|
||||
for i in "${LOCAL:-none}-pins" "${LOCAL:-none}-build" "${LOCAL:-none}-build2" "${IMG:-none}" "${REGISTRY}/para/${PKG}@${DIGEST:-none}"; do docker rmi "$i" > /dev/null 2>&1 || true; done
|
||||
docker logout "$REGISTRY" > /dev/null 2>&1 || true
|
||||
+3
-4
@@ -1,4 +1,3 @@
|
||||
cover.out
|
||||
mc
|
||||
*~
|
||||
*.test
|
||||
/src/
|
||||
/out/
|
||||
/vezha/SOURCE
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
# Generate CONTRIBUTORS.md: contributors.sh
|
||||
|
||||
# Tip for finding duplicates (besides scanning the output of CONTRIBUTORS.md for name
|
||||
# duplicates that aren't also email duplicates): scan the output of:
|
||||
# git log --format='%aE - %aN' | sort -uf
|
||||
#
|
||||
# For explanation on this file format: man git-shortlog
|
||||
|
||||
Anand Babu (AB) Periasamy <ab@minio.io> Anand Babu (AB) Periasamy <abperiasamy@users.noreply.github.com>
|
||||
Anand Babu (AB) Periasamy <ab@minio.io> <ab@unlocksmith.org>
|
||||
Anis Elleuch <vadmeste@gmail.com>
|
||||
Frederick F. Kautz IV <fkautz@minio.io> <fkautz@alumni.cmu.edu>
|
||||
Harshavardhana <harsha@minio.io> <harsha@harshavardhana.net>
|
||||
Krishna Srinivas <krishna@minio.io> <krishna.srinivas@gmail.com>
|
||||
Bosky <bosky@helpshift.com>
|
||||
-25
@@ -1,25 +0,0 @@
|
||||
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
|
||||
|
||||
script:
|
||||
- diff -au <(gofmt -d *.go) <(printf "")
|
||||
- diff -au <(gofmt -d pkg) <(printf "")
|
||||
|
||||
notifications:
|
||||
slack:
|
||||
secure: McinxQ4R/Yu2r/U8lVsdAIQ195Rf+3/Ku6DViWyqLHsTt5fTnVrSfbIKs8vy0t2A0bRLO6zv2xOSMWjfiimZLPMgMbMqLtTFEzUzB8RZyx2n2xgmL8q3gjXcLA3vkBreaRYCzJzX6DjvrxRfhyOg+BQHpLpACWik3FS/7VIdDCI=
|
||||
@@ -1,40 +0,0 @@
|
||||
### Setup your mc Github Repository
|
||||
Fork [mc upstream](https://github.com/minio/mc/fork) source repository to your own personal repository.
|
||||
```sh
|
||||
$ mkdir -p $GOPATH/src/github.com/minio
|
||||
$ cd $GOPATH/src/github.com/minio
|
||||
$ git clone https://github.com/$USER_ID/mc
|
||||
$ cd mc
|
||||
$ make
|
||||
$ mc --help
|
||||
```
|
||||
|
||||
### Developer Guidelines
|
||||
|
||||
``mc`` welcomes your contribution. To make the process as seamless as possible, we ask for the following:
|
||||
|
||||
* Go ahead and fork the project and make your changes. We encourage pull requests to discuss code changes.
|
||||
- Fork it
|
||||
- Create your feature branch (git checkout -b my-new-feature)
|
||||
- Commit your changes (git commit -am 'Add some feature')
|
||||
- Push to the branch (git push origin my-new-feature)
|
||||
- Create new Pull Request
|
||||
|
||||
* If you have additional dependencies for ``mc``, ``mc`` manages its dependencies using [govendor](https://github.com/kardianos/govendor)
|
||||
- Run `go get foo/bar`
|
||||
- Edit your code to import foo/bar
|
||||
- Run `make pkg-add PKG=foo/bar` from top-level folder
|
||||
|
||||
* If you have dependencies which needs to be removed from ``mc``
|
||||
- Edit your code to not import foo/bar
|
||||
- Run `make pkg-remove PKG=foo/bar` from top-level folder
|
||||
|
||||
* When you're ready to create a pull request, be sure to:
|
||||
- Have test cases for the new code. If you have questions about how to do it, please ask in your pull request.
|
||||
- Run `go fmt`
|
||||
- Squash your commits into a single commit. `git rebase -i`. It's okay to force update your pull request.
|
||||
- Make sure `make build` completes.
|
||||
|
||||
* Read [Effective Go](https://github.com/golang/go/wiki/CodeReviewComments) article from Golang project
|
||||
- `mc` project is conformant with Golang style
|
||||
- if you happen to observe offending code, please feel free to send a pull request
|
||||
@@ -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>
|
||||
@@ -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,202 +0,0 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -1,41 +0,0 @@
|
||||
# For maintainers only
|
||||
|
||||
## Responsibilities
|
||||
|
||||
Please go through this link [Maintainer Responsibility](https://gist.github.com/abperiasamy/f4d9b31d3186bbd26522)
|
||||
|
||||
### Setup your mc Github Repository
|
||||
|
||||
Fork [mc upstream](https://github.com/minio/mc/fork) source repository to your own personal repository.
|
||||
```bash
|
||||
$ mkdir -p $GOPATH/src/github.com/minio
|
||||
$ cd $GOPATH/src/github.com/minio
|
||||
$ git clone https://github.com/$USER_ID/mc
|
||||
$
|
||||
```
|
||||
|
||||
``mc`` uses [govendor](https://github.com/kardianos/govendor) for its dependency management.
|
||||
|
||||
### To manage dependencies
|
||||
|
||||
#### Add new dependencies
|
||||
|
||||
- Run `go get foo/bar`
|
||||
- Edit your code to import foo/bar
|
||||
- Run `govendor add foo/bar` from top-level folder
|
||||
|
||||
#### Remove dependencies
|
||||
|
||||
- Run `govendor remove foo/bar`
|
||||
|
||||
#### Update dependencies
|
||||
|
||||
- Run `govendor remove +vendor`
|
||||
- Run to update the dependent package `go get -u foo/bar`
|
||||
- Run `govendor add +external`
|
||||
|
||||
### Making new releases
|
||||
|
||||
`mc` doesn't follow semantic versioning style, `mc` instead uses the release date and time as the release versions.
|
||||
|
||||
`make release` will install new released binary into your `GOPATH`
|
||||
@@ -1,85 +0,0 @@
|
||||
LDFLAGS := $(shell go run buildscripts/gen-ldflags.go)
|
||||
BUILD_LDFLAGS := '$(LDFLAGS)'
|
||||
|
||||
all: install
|
||||
|
||||
checkdeps:
|
||||
@echo "Checking deps:"
|
||||
@(env bash $(PWD)/buildscripts/checkdeps.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
|
||||
@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:"
|
||||
|
||||
# verifiers: getdeps vet fmt lint cyclo deadcode
|
||||
verifiers: getdeps vet fmt lint cyclo deadcode
|
||||
|
||||
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
|
||||
|
||||
fmt:
|
||||
@echo "Running $@:"
|
||||
@GO15VENDOREXPERIMENT=1 gofmt -s -l *.go
|
||||
@GO15VENDOREXPERIMENT=1 gofmt -s -l pkg
|
||||
lint:
|
||||
@echo "Running $@:"
|
||||
@GO15VENDOREXPERIMENT=1 golint .
|
||||
@GO15VENDOREXPERIMENT=1 golint github.com/minio/mc/pkg...
|
||||
|
||||
cyclo:
|
||||
@echo "Running $@:"
|
||||
@GO15VENDOREXPERIMENT=1 gocyclo -over 40 *.go
|
||||
@GO15VENDOREXPERIMENT=1 gocyclo -over 40 pkg
|
||||
|
||||
deadcode:
|
||||
@echo "Running $@:"
|
||||
@GO15VENDOREXPERIMENT=1 deadcode
|
||||
|
||||
build: verifiers
|
||||
@echo "Installing mc:"
|
||||
|
||||
test: verifiers
|
||||
@echo "Running all testing:"
|
||||
@GO15VENDOREXPERIMENT=1 go test $(GOFLAGS) ./
|
||||
@GO15VENDOREXPERIMENT=1 go test $(GOFLAGS) github.com/minio/mc/pkg...
|
||||
|
||||
gomake-all: build
|
||||
@GO15VENDOREXPERIMENT=1 go build --ldflags $(BUILD_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"
|
||||
|
||||
pkg-add:
|
||||
@GO15VENDOREXPERIMENT=1 govendor add $(PKG)
|
||||
|
||||
pkg-update:
|
||||
@GO15VENDOREXPERIMENT=1 govendor update $(PKG)
|
||||
|
||||
pkg-remove:
|
||||
@GO15VENDOREXPERIMENT=1 govendor remove $(PKG)
|
||||
|
||||
install: gomake-all
|
||||
|
||||
all-tests: test
|
||||
# TODO disable them for now.
|
||||
#@./tests/test-minio.sh
|
||||
|
||||
release:
|
||||
@./release.sh
|
||||
|
||||
clean:
|
||||
@rm -fv cover.out
|
||||
@rm -fv mc
|
||||
@@ -1,9 +0,0 @@
|
||||
Minio Client (C) 2014, 2015 Minio, Inc.
|
||||
|
||||
This product includes software developed at Minio, Inc.
|
||||
(https://minio.io/).
|
||||
|
||||
The Minio project contains unmodified/modified subcomponents too with
|
||||
separate copyright notices and license terms. Your use of the source
|
||||
code for the these subcomponents is subject to the terms and conditions
|
||||
of the following licenses.
|
||||
@@ -1,106 +0,0 @@
|
||||
# Minio Client (mc) [](https://gitter.im/minio/minio?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
||||
|
||||
``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).
|
||||
|
||||
## 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)
|
||||
|
||||
#### GNU/Linux
|
||||
|
||||
Download ``mc`` for:
|
||||
|
||||
- ``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
|
||||
|
||||
~~~
|
||||
$ 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).
|
||||
|
||||
```sh
|
||||
$ GO15VENDOREXPERIMENT=1 go get -u github.com/minio/mc
|
||||
```
|
||||
|
||||
## Public Minio Server
|
||||
|
||||
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.
|
||||
|
||||
## Configuring mc for Amazon S3
|
||||
|
||||
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
|
||||
```
|
||||
|
||||
Example
|
||||
```
|
||||
$ mc config host add mys3 https://s3.amazonaws.com BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12
|
||||
```
|
||||
|
||||
NOTE: ``S3v4`` is default if not specified.
|
||||
|
||||
## Configure mc for Google Cloud Storage
|
||||
|
||||
Get your AccessKeyID and SecretAccessKey by following [Google Credentials Guide](https://cloud.google.com/storage/docs/migrating?hl=en#keys).
|
||||
|
||||
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
|
||||
```
|
||||
|
||||
NOTE: Google Cloud Storage only supports Legacy Signature Version ``2``, so you have to pick - ``S3v2``
|
||||
|
||||
## Contribute to Minio Client
|
||||
Please follow Minio [Contributor's Guide](./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
|
||||
}
|
||||
@@ -1,120 +0,0 @@
|
||||
/*
|
||||
* Minio Client (C) 2014, 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
|
||||
// accounter keeps tabs of ongoing data transfer information.
|
||||
type accounter struct {
|
||||
current int64
|
||||
|
||||
Total int64
|
||||
startTime time.Time
|
||||
startValue int64
|
||||
refreshRate time.Duration
|
||||
currentValue int64
|
||||
finishOnce sync.Once
|
||||
isFinished chan struct{}
|
||||
}
|
||||
|
||||
// Instantiate a new accounter.
|
||||
func newAccounter(total int64) *accounter {
|
||||
acct := &accounter{
|
||||
Total: total,
|
||||
startTime: time.Now(),
|
||||
startValue: 0,
|
||||
refreshRate: time.Millisecond * 200,
|
||||
isFinished: make(chan struct{}),
|
||||
currentValue: -1,
|
||||
}
|
||||
go acct.writer()
|
||||
return acct
|
||||
}
|
||||
|
||||
// write calculate the final speed.
|
||||
func (a *accounter) write(current int64) float64 {
|
||||
fromStart := time.Now().Sub(a.startTime)
|
||||
currentFromStart := current - a.startValue
|
||||
if currentFromStart > 0 {
|
||||
speed := float64(currentFromStart) / (float64(fromStart) / float64(time.Second))
|
||||
return speed
|
||||
}
|
||||
return 0.0
|
||||
}
|
||||
|
||||
// writer update new accounting data for a specified refreshRate.
|
||||
func (a *accounter) writer() {
|
||||
a.Update()
|
||||
for {
|
||||
select {
|
||||
case <-a.isFinished:
|
||||
return
|
||||
case <-time.After(a.refreshRate):
|
||||
a.Update()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// accountStat cantainer for current stats captured.
|
||||
type accountStat struct {
|
||||
Total int64
|
||||
Transferred int64
|
||||
Speed float64
|
||||
}
|
||||
|
||||
// Stat provides current stats captured.
|
||||
func (a *accounter) Stat() accountStat {
|
||||
var acntStat accountStat
|
||||
a.finishOnce.Do(func() {
|
||||
close(a.isFinished)
|
||||
acntStat.Total = a.Total
|
||||
acntStat.Transferred = a.current
|
||||
acntStat.Speed = a.write(atomic.LoadInt64(&a.current))
|
||||
})
|
||||
return acntStat
|
||||
}
|
||||
|
||||
// Update update with new values loaded atomically.
|
||||
func (a *accounter) Update() {
|
||||
c := atomic.LoadInt64(&a.current)
|
||||
if c != a.currentValue {
|
||||
a.write(c)
|
||||
a.currentValue = c
|
||||
}
|
||||
}
|
||||
|
||||
// Set sets the current value atomically.
|
||||
func (a *accounter) Set(n int64) *accounter {
|
||||
atomic.StoreInt64(&a.current, n)
|
||||
return a
|
||||
}
|
||||
|
||||
// Add add to current value atomically.
|
||||
func (a *accounter) Add(n int64) int64 {
|
||||
return atomic.AddInt64(&a.current, n)
|
||||
}
|
||||
|
||||
// Read implements Reader which internally updates current value.
|
||||
func (a *accounter) Read(p []byte) (n int, err error) {
|
||||
n = len(p)
|
||||
a.Add(int64(n))
|
||||
return
|
||||
}
|
||||
@@ -1,167 +0,0 @@
|
||||
/*
|
||||
* Minio Client (C) 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
type objectAPIHandler struct {
|
||||
lock *sync.Mutex
|
||||
bucket string
|
||||
object map[string][]byte
|
||||
}
|
||||
|
||||
func (h objectAPIHandler) getHandler(w http.ResponseWriter, r *http.Request) {
|
||||
h.lock.Lock()
|
||||
defer h.lock.Unlock()
|
||||
switch {
|
||||
case r.URL.Path == "/":
|
||||
response := []byte("<ListAllMyBucketsResult xmlns=\"http://doc.s3.amazonaws.com/2006-03-01\"><Buckets><Bucket><Name>bucket</Name><CreationDate>2015-05-20T23:05:09.230Z</CreationDate></Bucket></Buckets><Owner><ID>minio</ID><DisplayName>minio</DisplayName></Owner></ListAllMyBucketsResult>")
|
||||
w.Header().Set("Content-Length", strconv.Itoa(len(response)))
|
||||
w.Write(response)
|
||||
return
|
||||
case r.URL.Path == "/bucket":
|
||||
_, ok := r.URL.Query()["acl"]
|
||||
if ok {
|
||||
response := []byte("<?xml version=\"1.0\" encoding=\"UTF-8\"?><AccessControlPolicy><Owner><ID>75aa57f09aa0c8caeab4f8c24e99d10f8e7faeebf76c078efc7c6caea54ba06a</ID><DisplayName>CustomersName@amazon.com</DisplayName></Owner><AccessControlList><Grant><Grantee xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"CanonicalUser\"><ID>75aa57f09aa0c8caeab4f8c24e99d10f8e7faeebf76c078efc7c6caea54ba06a</ID><DisplayName>CustomersName@amazon.com</DisplayName></Grantee><Permission>FULL_CONTROL</Permission></Grant></AccessControlList></AccessControlPolicy>")
|
||||
w.Header().Set("Content-Length", strconv.Itoa(len(response)))
|
||||
w.Write(response)
|
||||
return
|
||||
}
|
||||
fallthrough
|
||||
case r.URL.Path == "/bucket":
|
||||
response := []byte("<ListBucketResult xmlns=\"http://doc.s3.amazonaws.com/2006-03-01\"><Contents><ETag>b1946ac92492d2347c6235b4d2611184</ETag><Key>object0</Key><LastModified>2015-05-21T18:24:21.097Z</LastModified><Size>22061</Size><Owner><ID>minio</ID><DisplayName>minio</DisplayName></Owner><StorageClass>STANDARD</StorageClass></Contents><Contents><ETag>b1946ac92492d2347c6235b4d2611184</ETag><Key>object1</Key><LastModified>2015-05-21T18:24:21.097Z</LastModified><Size>22061</Size><Owner><ID>minio</ID><DisplayName>minio</DisplayName></Owner><StorageClass>STANDARD</StorageClass></Contents><Contents><ETag>b1946ac92492d2347c6235b4d2611184</ETag><Key>object2</Key><LastModified>2015-05-21T18:24:21.097Z</LastModified><Size>22061</Size><Owner><ID>minio</ID><DisplayName>minio</DisplayName></Owner><StorageClass>STANDARD</StorageClass></Contents><Contents><ETag>b1946ac92492d2347c6235b4d2611184</ETag><Key>object3</Key><LastModified>2015-05-21T18:24:21.097Z</LastModified><Size>22061</Size><Owner><ID>minio</ID><DisplayName>minio</DisplayName></Owner><StorageClass>STANDARD</StorageClass></Contents><Contents><ETag>b1946ac92492d2347c6235b4d2611184</ETag><Key>object4</Key><LastModified>2015-05-21T18:24:21.097Z</LastModified><Size>22061</Size><Owner><ID>minio</ID><DisplayName>minio</DisplayName></Owner><StorageClass>STANDARD</StorageClass></Contents><Contents><ETag>b1946ac92492d2347c6235b4d2611184</ETag><Key>object5</Key><LastModified>2015-05-21T18:24:21.097Z</LastModified><Size>22061</Size><Owner><ID>minio</ID><DisplayName>minio</DisplayName></Owner><StorageClass>STANDARD</StorageClass></Contents><Contents><ETag>b1946ac92492d2347c6235b4d2611184</ETag><Key>object6</Key><LastModified>2015-05-21T18:24:21.097Z</LastModified><Size>22061</Size><Owner><ID>minio</ID><DisplayName>minio</DisplayName></Owner><StorageClass>STANDARD</StorageClass></Contents><Contents><ETag>b1946ac92492d2347c6235b4d2611184</ETag><Key>object7</Key><LastModified>2015-05-21T18:24:21.097Z</LastModified><Size>22061</Size><Owner><ID>minio</ID><DisplayName>minio</DisplayName></Owner><StorageClass>STANDARD</StorageClass></Contents><Delimiter></Delimiter><EncodingType></EncodingType><IsTruncated>false</IsTruncated><Marker></Marker><MaxKeys>1000</MaxKeys><Name>testbucket</Name><NextMarker></NextMarker><Prefix></Prefix></ListBucketResult>")
|
||||
w.Header().Set("Content-Length", strconv.Itoa(len(response)))
|
||||
w.Write(response)
|
||||
return
|
||||
case r.URL.Path != "":
|
||||
if _, ok := h.object[filepath.Base(r.URL.Path)]; !ok {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Length", strconv.Itoa(len(h.object[filepath.Base(r.URL.Path)])))
|
||||
w.Header().Set("Last-Modified", time.Now().UTC().Format(http.TimeFormat))
|
||||
w.Header().Set("ETag", "b1946ac92492d2347c6235b4d2611184")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
io.Copy(w, bytes.NewReader(h.object[filepath.Base(r.URL.Path)]))
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func (h objectAPIHandler) headHandler(w http.ResponseWriter, r *http.Request) {
|
||||
h.lock.Lock()
|
||||
defer h.lock.Unlock()
|
||||
switch {
|
||||
case r.URL.Path == "/":
|
||||
w.WriteHeader(http.StatusOK)
|
||||
return
|
||||
case r.URL.Path == "/bucket":
|
||||
w.WriteHeader(http.StatusOK)
|
||||
return
|
||||
case r.URL.Path != "":
|
||||
w.Header().Set("Content-Length", strconv.Itoa(len(h.object[filepath.Base(r.URL.Path)])))
|
||||
w.Header().Set("Last-Modified", time.Now().UTC().Format(http.TimeFormat))
|
||||
w.Header().Set("ETag", "b1946ac92492d2347c6235b4d2611184")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func isValidBucket(bucket string) bool {
|
||||
if len(bucket) < 3 || len(bucket) > 63 {
|
||||
return false
|
||||
}
|
||||
if bucket[0] == '.' || bucket[len(bucket)-1] == '.' {
|
||||
return false
|
||||
}
|
||||
if match, _ := regexp.MatchString("\\.\\.", bucket); match == true {
|
||||
return false
|
||||
}
|
||||
// We don't support buckets with '.' in them
|
||||
match, _ := regexp.MatchString("^[a-zA-Z][a-zA-Z0-9\\-]+[a-zA-Z0-9]$", bucket)
|
||||
return match
|
||||
}
|
||||
|
||||
func (h objectAPIHandler) putHandler(w http.ResponseWriter, r *http.Request) {
|
||||
h.lock.Lock()
|
||||
defer h.lock.Unlock()
|
||||
switch {
|
||||
case r.URL.Path == "/":
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
case r.URL.Path == "/bucket":
|
||||
_, ok := r.URL.Query()["acl"]
|
||||
if ok {
|
||||
switch r.Header.Get("x-amz-acl") {
|
||||
case "public-read-write":
|
||||
fallthrough
|
||||
case "public-read":
|
||||
fallthrough
|
||||
case "private":
|
||||
fallthrough
|
||||
case "authenticated-read":
|
||||
w.WriteHeader(http.StatusOK)
|
||||
return
|
||||
default:
|
||||
w.WriteHeader(http.StatusNotImplemented)
|
||||
return
|
||||
}
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
return
|
||||
case r.URL.Path != "":
|
||||
if !isValidBucket(strings.Split(r.URL.Path, "/")[1]) {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
length, e := strconv.Atoi(r.Header.Get("Content-Length"))
|
||||
if e != nil {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
var buffer bytes.Buffer
|
||||
if _, e = io.CopyN(&buffer, r.Body, int64(length)); e != nil {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
h.object[filepath.Base(r.URL.Path)] = buffer.Bytes()
|
||||
w.Header().Set("ETag", "b1946ac92492d2347c6235b4d2611184")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func (h objectAPIHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case r.Method == "GET":
|
||||
h.getHandler(w, r)
|
||||
case r.Method == "HEAD":
|
||||
h.headHandler(w, r)
|
||||
case r.Method == "PUT":
|
||||
h.putHandler(w, r)
|
||||
}
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
# version format
|
||||
version: "{build}"
|
||||
|
||||
# Operating system (build VM template)
|
||||
os: Windows Server 2012 R2
|
||||
|
||||
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/pkg...
|
||||
- go run buildscripts/gen-ldflags.go > temp.txt
|
||||
- set /p LDFLAGS=<temp.txt
|
||||
- go build -ldflags="%LDFLAGS%" -o %GOPATH%\bin\mc.exe
|
||||
- mc version
|
||||
|
||||
# to disable automatic tests
|
||||
test: off
|
||||
|
||||
# to disable deployment
|
||||
deploy: off
|
||||
@@ -1,28 +0,0 @@
|
||||
/*
|
||||
* Minio Client (C) 2014, 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
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]
|
||||
)
|
||||
@@ -1,218 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
#
|
||||
# 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.
|
||||
#
|
||||
|
||||
_init() {
|
||||
|
||||
shopt -s extglob
|
||||
|
||||
## Minimum required versions for build dependencies
|
||||
GIT_VERSION="1.0"
|
||||
GO_VERSION="1.5.1"
|
||||
OSX_VERSION="10.8"
|
||||
UNAME=$(uname -sm)
|
||||
|
||||
## Check all dependencies are present
|
||||
MISSING=""
|
||||
}
|
||||
|
||||
readlink() {
|
||||
TARGET_FILE=$1
|
||||
|
||||
cd `dirname $TARGET_FILE`
|
||||
TARGET_FILE=`basename $TARGET_FILE`
|
||||
|
||||
# Iterate down a (possible) chain of symlinks
|
||||
while [ -L "$TARGET_FILE" ]
|
||||
do
|
||||
TARGET_FILE=$(env readlink $TARGET_FILE)
|
||||
cd `dirname $TARGET_FILE`
|
||||
TARGET_FILE=`basename $TARGET_FILE`
|
||||
done
|
||||
|
||||
# Compute the canonicalized name by finding the physical path
|
||||
# for the directory we're in and appending the target file.
|
||||
PHYS_DIR=`pwd -P`
|
||||
RESULT=$PHYS_DIR/$TARGET_FILE
|
||||
echo $RESULT
|
||||
}
|
||||
|
||||
###
|
||||
#
|
||||
# Takes two arguments
|
||||
# arg1: version number in `x.x.x` format
|
||||
# arg2: version number in `x.x.x` format
|
||||
#
|
||||
# example: check_version "$version1" "$version2"
|
||||
#
|
||||
# returns:
|
||||
# 0 - Installed version is equal to required
|
||||
# 1 - Installed version is greater than required
|
||||
# 2 - Installed version is lesser than required
|
||||
# 3 - If args have length zero
|
||||
#
|
||||
####
|
||||
check_version() {
|
||||
## validate args
|
||||
[[ -z "$1" ]] && return 3
|
||||
[[ -z "$2" ]] && return 3
|
||||
|
||||
if [[ $1 == $2 ]]; then
|
||||
return 0
|
||||
fi
|
||||
|
||||
local IFS=.
|
||||
local i ver1=($1) ver2=($2)
|
||||
# fill empty fields in ver1 with zeros
|
||||
for ((i=${#ver1[@]}; i<${#ver2[@]}; i++)); do
|
||||
ver1[i]=0
|
||||
done
|
||||
for ((i=0; i<${#ver1[@]}; i++)); do
|
||||
if [[ -z ${ver2[i]} ]]; then
|
||||
# fill empty fields in ver2 with zeros
|
||||
ver2[i]=0
|
||||
fi
|
||||
if ((10#${ver1[i]} > 10#${ver2[i]})); then
|
||||
|
||||
return 1
|
||||
fi
|
||||
if ((10#${ver1[i]} < 10#${ver2[i]})); then
|
||||
## Installed version is lesser than required - Bad condition
|
||||
return 2
|
||||
fi
|
||||
done
|
||||
return 0
|
||||
}
|
||||
|
||||
check_golang_env() {
|
||||
echo ${GOROOT:?} 2>&1 >/dev/null
|
||||
if [ $? -eq 1 ]; then
|
||||
echo "ERROR"
|
||||
echo "GOROOT environment variable missing, please refer to Go installation document"
|
||||
echo "https://github.com/minio/mc/blob/master/INSTALLGO.md#install-go-13"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo ${GOPATH:?} 2>&1 >/dev/null
|
||||
if [ $? -eq 1 ]; then
|
||||
echo "ERROR"
|
||||
echo "GOPATH environment variable missing, please refer to Go installation document"
|
||||
echo "https://github.com/minio/mc/blob/master/INSTALLGO.md#install-go-13"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
local go_binary_path=$(which go)
|
||||
|
||||
if [ -z "${go_binary_path}" ] ; then
|
||||
echo "Cannot find go binary in your PATH configuration, please refer to Go installation document"
|
||||
echo "https://github.com/minio/mc/blob/master/INSTALLGO.md#install-go-13"
|
||||
exit -1
|
||||
fi
|
||||
|
||||
local new_go_binary_path=${go_binary_path}
|
||||
if [ -h "${go_binary_path}" ]; then
|
||||
new_go_binary_path=$(readlink ${go_binary_path})
|
||||
fi
|
||||
|
||||
if [[ !"$(dirname ${new_go_binary_path})" =~ *"${GOROOT%%*(/)}"* ]] ; then
|
||||
echo "The go binary found in your PATH configuration does not belong to the Go installation pointed by your GOROOT environment," \
|
||||
"please refer to Go installation document"
|
||||
echo "https://github.com/minio/mc/blob/master/INSTALLGO.md#install-go-13"
|
||||
exit -1
|
||||
fi
|
||||
}
|
||||
|
||||
is_supported_os() {
|
||||
case ${UNAME%% *} in
|
||||
"Linux")
|
||||
os="linux"
|
||||
;;
|
||||
"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}"
|
||||
;;
|
||||
"*")
|
||||
echo "Exiting.. unsupported operating system found"
|
||||
exit 1;
|
||||
esac
|
||||
}
|
||||
|
||||
is_supported_arch() {
|
||||
local supported
|
||||
case ${UNAME##* } in
|
||||
"x86_64")
|
||||
supported=1
|
||||
;;
|
||||
"arm"*)
|
||||
supported=1
|
||||
;;
|
||||
*)
|
||||
supported=0
|
||||
;;
|
||||
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}"
|
||||
if [ $? -ge 2 ]; then
|
||||
MISSING="${MISSING} golang(>=${GO_VERSION})"
|
||||
fi
|
||||
|
||||
check_version "$(env git --version 2>/dev/null | sed -e 's/^.* \([0-9.\].*\).*$/\1/' -e 's/^\([0-9.\]*\).*/\1/g')" "${GIT_VERSION}"
|
||||
if [ $? -ge 2 ]; then
|
||||
MISSING="${MISSING} git(>=${GIT_VERSION})"
|
||||
fi
|
||||
}
|
||||
|
||||
main() {
|
||||
echo -n "Check for supported arch.. "
|
||||
is_supported_arch
|
||||
|
||||
echo -n "Check for supported os.. "
|
||||
is_supported_os
|
||||
|
||||
echo -n "Checking if proper environment variables are set.. "
|
||||
check_golang_env
|
||||
|
||||
echo "Done"
|
||||
echo "Using GOPATH=${GOPATH} and GOROOT=${GOROOT}"
|
||||
|
||||
echo -n "Checking dependencies for Minio Client.. "
|
||||
check_deps
|
||||
|
||||
## If dependencies are missing, warn the user and abort
|
||||
if [ "x${MISSING}" != "x" ]; then
|
||||
echo "ERROR"
|
||||
echo
|
||||
echo "The following build tools are missing:"
|
||||
echo
|
||||
echo "** ${MISSING} **"
|
||||
echo
|
||||
echo "Please install them "
|
||||
echo "${MISSING}"
|
||||
echo
|
||||
echo "Follow https://github.com/minio/mc/blob/master/INSTALLGO.md for further instructions"
|
||||
exit 1
|
||||
fi
|
||||
echo "Done"
|
||||
}
|
||||
|
||||
_init && main "$@"
|
||||
@@ -1,70 +0,0 @@
|
||||
// +build ignore
|
||||
|
||||
/*
|
||||
* Mc Client (C) 2014, 2015 Mc, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
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]
|
||||
return ldflagsStr
|
||||
}
|
||||
|
||||
// genReleaseTag prints release tag to the console for easy git tagging.
|
||||
func releaseTag(version string) string {
|
||||
relPrefix := "UNOFFICIAL"
|
||||
if prefix := os.Getenv("MC_RELEASE"); prefix != "" {
|
||||
relPrefix = prefix
|
||||
}
|
||||
|
||||
relTag := strings.Replace(version, " ", "-", -1)
|
||||
relTag = strings.Replace(relTag, ":", "-", -1)
|
||||
relTag = strings.Replace(relTag, ",", "", -1)
|
||||
return relPrefix + "." + relTag
|
||||
}
|
||||
|
||||
// commitID returns the abbreviated commit-id hash of the last commit.
|
||||
func commitID() string {
|
||||
// git log --format="%h" -n1
|
||||
var (
|
||||
commit []byte
|
||||
e error
|
||||
)
|
||||
cmdName := "git"
|
||||
cmdArgs := []string{"log", "--format=%H", "-n1"}
|
||||
if commit, e = exec.Command(cmdName, cmdArgs...).Output(); e != nil {
|
||||
fmt.Fprintln(os.Stderr, "Error generating git commit-id: ", e)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
return strings.TrimSpace(string(commit))
|
||||
}
|
||||
|
||||
func main() {
|
||||
fmt.Println(genLDFlags(time.Now().UTC().Format(time.RFC3339)))
|
||||
}
|
||||
-152
@@ -1,152 +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 (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
"syscall"
|
||||
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
)
|
||||
|
||||
var (
|
||||
catFlags = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "help, h",
|
||||
Usage: "Help of cat",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
// Display contents of a file.
|
||||
var catCmd = cli.Command{
|
||||
Name: "cat",
|
||||
Usage: "Display contents of a file.",
|
||||
Action: mainCat,
|
||||
Flags: append(catFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
mc {{.Name}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
mc {{.Name}} [FLAGS] SOURCE [SOURCE...]
|
||||
|
||||
FLAGS:
|
||||
{{range .Flags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Stream an object from Amazon S3 cloud storage to mplayer standard input.
|
||||
$ mc {{.Name}} s3/ferenginar/klingon_opera_aktuh_maylotah.ogg | mplayer -
|
||||
|
||||
2. Concantenate contents of file1.txt and stdin to standard output.
|
||||
$ mc {{.Name}} file1.txt - > file.txt
|
||||
|
||||
3. Concantenate multiple files to one.
|
||||
$ mc {{.Name}} part.* > complete.img
|
||||
|
||||
`,
|
||||
}
|
||||
|
||||
// checkCatSyntax performs command-line input validation for cat command.
|
||||
func checkCatSyntax(ctx *cli.Context) {
|
||||
args := ctx.Args()
|
||||
if !args.Present() {
|
||||
args = []string{"-"}
|
||||
}
|
||||
for _, arg := range args {
|
||||
if strings.HasPrefix(arg, "-") && len(arg) > 1 {
|
||||
fatalIf(probe.NewError(errors.New("")), fmt.Sprintf("Unknown flag ‘%s’ passed.", arg))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// catURL displays contents of a URL to stdout.
|
||||
func catURL(sourceURL string) *probe.Error {
|
||||
var reader io.Reader
|
||||
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
|
||||
if reader, err = getSourceStream(sourceURL); err != nil {
|
||||
return err.Trace(sourceURL)
|
||||
}
|
||||
}
|
||||
return catOut(reader).Trace(sourceURL)
|
||||
}
|
||||
|
||||
// catOut reads from reader stream and writes to stdout.
|
||||
func catOut(r io.Reader) *probe.Error {
|
||||
// Read till EOF.
|
||||
if _, e := io.Copy(os.Stdout, r); e != nil {
|
||||
switch e := e.(type) {
|
||||
case *os.PathError:
|
||||
if e.Err == syscall.EPIPE {
|
||||
// stdout closed by the user. Gracefully exit.
|
||||
return nil
|
||||
}
|
||||
return probe.NewError(e)
|
||||
default:
|
||||
return probe.NewError(e)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// mainCat is the main entry point for cat command.
|
||||
func mainCat(ctx *cli.Context) {
|
||||
// Set global flags from context.
|
||||
setGlobalsFromContext(ctx)
|
||||
|
||||
// check 'cat' cli arguments.
|
||||
checkCatSyntax(ctx)
|
||||
|
||||
// Set command flags from context.
|
||||
stdinMode := false
|
||||
if !ctx.Args().Present() {
|
||||
stdinMode = true
|
||||
}
|
||||
|
||||
// handle std input data.
|
||||
if stdinMode {
|
||||
fatalIf(catOut(os.Stdin).Trace(), "Unable to read from standard input.")
|
||||
return
|
||||
}
|
||||
|
||||
// if Args contain ‘-’, we need to preserve its order specially.
|
||||
args := []string(ctx.Args())
|
||||
if ctx.Args().First() == "-" {
|
||||
for i, arg := range os.Args {
|
||||
if arg == "cat" {
|
||||
// Overwrite ctx.Args with os.Args.
|
||||
args = os.Args[i+1:]
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Convert arguments to URLs: expand alias, fix format.
|
||||
for _, url := range args {
|
||||
fatalIf(catURL(url).Trace(url), "Unable to read from ‘"+url+"’.")
|
||||
}
|
||||
}
|
||||
@@ -1,150 +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 (
|
||||
"io"
|
||||
"os"
|
||||
"regexp"
|
||||
"runtime"
|
||||
"strings"
|
||||
|
||||
"github.com/minio/mc/pkg/client"
|
||||
"github.com/minio/mc/pkg/client/fs"
|
||||
"github.com/minio/mc/pkg/client/s3"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
)
|
||||
|
||||
// Check if the target URL represents folder. It may or may not exist yet.
|
||||
func isTargetURLDir(targetURL string) bool {
|
||||
targetURLParse := client.NewURL(targetURL)
|
||||
_, targetContent, err := url2Stat(targetURL)
|
||||
if err != nil {
|
||||
_, aliasedTargetURL, _ := mustExpandAlias(targetURL)
|
||||
if aliasedTargetURL == targetURL {
|
||||
return false
|
||||
}
|
||||
if targetURLParse.Path == string(targetURLParse.Separator) && targetURLParse.Scheme != "" {
|
||||
return false
|
||||
}
|
||||
if strings.HasSuffix(targetURLParse.Path, string(targetURLParse.Separator)) {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
if !targetContent.Type.IsDir() { // Target is a dir.
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
return getSourceStreamFromAlias(alias, urlStrFull)
|
||||
}
|
||||
|
||||
// getSourceStreamFromAlias gets a reader from URL.
|
||||
func getSourceStreamFromAlias(alias string, urlStr string) (reader io.Reader, err *probe.Error) {
|
||||
sourceClnt, err := newClientFromAlias(alias, urlStr)
|
||||
if err != nil {
|
||||
return nil, err.Trace(alias, urlStr)
|
||||
}
|
||||
reader, err = sourceClnt.Get()
|
||||
if err != nil {
|
||||
return nil, err.Trace(alias, urlStr)
|
||||
}
|
||||
return reader, nil
|
||||
}
|
||||
|
||||
// putTargetStreamFromAlias writes to URL from Reader.
|
||||
func putTargetStreamFromAlias(alias string, urlStr string, reader io.Reader, size int64, progress io.Reader) (int64, *probe.Error) {
|
||||
targetClnt, err := newClientFromAlias(alias, urlStr)
|
||||
if err != nil {
|
||||
return 0, err.Trace(alias, urlStr)
|
||||
}
|
||||
contentType := guessURLContentType(urlStr)
|
||||
var n int64
|
||||
n, err = targetClnt.Put(reader, size, contentType, progress)
|
||||
if err != nil {
|
||||
return n, err.Trace(alias, urlStr)
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// putTargetStream writes to URL from reader. If length=-1, read until EOF.
|
||||
func putTargetStream(urlStr string, reader io.Reader, size int64) (int64, *probe.Error) {
|
||||
alias, urlStrFull, _, err := expandAlias(urlStr)
|
||||
if err != nil {
|
||||
return 0, err.Trace(alias, urlStr)
|
||||
}
|
||||
return putTargetStreamFromAlias(alias, urlStrFull, reader, size, nil)
|
||||
}
|
||||
|
||||
// newClientFromAlias gives a new client interface for matching
|
||||
// alias entry in the mc config file. If no matching host config entry
|
||||
// is found, fs client is returned.
|
||||
func newClientFromAlias(alias string, urlStr string) (client.Client, *probe.Error) {
|
||||
hostCfg := mustGetHostConfig(alias)
|
||||
if hostCfg == nil {
|
||||
// No matching host config. So we treat it like a
|
||||
// filesystem.
|
||||
fsClient, err := fs.New(urlStr)
|
||||
if err != nil {
|
||||
return nil, err.Trace(alias, urlStr)
|
||||
}
|
||||
return fsClient, nil
|
||||
}
|
||||
|
||||
// We have a valid alias and hostConfig. We populate the
|
||||
// credentials from the match found in the config file.
|
||||
s3Config := new(client.Config)
|
||||
s3Config.AccessKey = hostCfg.AccessKey
|
||||
s3Config.SecretKey = hostCfg.SecretKey
|
||||
s3Config.Signature = hostCfg.API
|
||||
s3Config.AppName = "mc"
|
||||
s3Config.AppVersion = mcVersion
|
||||
s3Config.AppComments = []string{os.Args[0], runtime.GOOS, runtime.GOARCH}
|
||||
s3Config.HostURL = urlStr
|
||||
s3Config.Debug = globalDebug
|
||||
|
||||
s3Client, err := s3.New(s3Config)
|
||||
if err != nil {
|
||||
return nil, err.Trace(alias, urlStr)
|
||||
}
|
||||
return s3Client, nil
|
||||
}
|
||||
|
||||
// urlRgx - verify if aliased url is real URL.
|
||||
var urlRgx = regexp.MustCompile("^https?://")
|
||||
|
||||
// newClient gives a new client interface
|
||||
func newClient(aliasedURL string) (client.Client, *probe.Error) {
|
||||
alias, urlStrFull, hostCfg, err := expandAlias(aliasedURL)
|
||||
if err != nil {
|
||||
return nil, err.Trace(aliasedURL)
|
||||
}
|
||||
// Verify if the aliasedURL is a real URL, fail in those cases
|
||||
// indicating the user to add alias.
|
||||
if hostCfg == nil && urlRgx.MatchString(aliasedURL) {
|
||||
return nil, errInvalidAliasedURL(aliasedURL).Trace(aliasedURL)
|
||||
}
|
||||
return newClientFromAlias(alias, urlStrFull)
|
||||
}
|
||||
-242
@@ -1,242 +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 (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/minio/mc/pkg/client"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio-xl/pkg/quick"
|
||||
)
|
||||
|
||||
func fixConfig() {
|
||||
// Fix config V3
|
||||
fixConfigV3()
|
||||
// Fix config V6
|
||||
fixConfigV6()
|
||||
// Fix config V6 for hosts
|
||||
fixConfigV6ForHosts()
|
||||
|
||||
/* No more fixing job. Here after we bump the version for changes always.
|
||||
*/
|
||||
}
|
||||
|
||||
/////////////////// Broken Config V3 ///////////////////
|
||||
type brokenHostConfigV3 struct {
|
||||
AccessKeyID string
|
||||
SecretAccessKey string
|
||||
}
|
||||
|
||||
type brokenConfigV3 struct {
|
||||
Version string
|
||||
ACL string
|
||||
Access string
|
||||
Aliases map[string]string
|
||||
Hosts map[string]brokenHostConfigV3
|
||||
}
|
||||
|
||||
// newConfigV3 - get new config broken version 3.
|
||||
func newBrokenConfigV3() *brokenConfigV3 {
|
||||
conf := new(brokenConfigV3)
|
||||
conf.Version = "3"
|
||||
conf.Aliases = make(map[string]string)
|
||||
conf.Hosts = make(map[string]brokenHostConfigV3)
|
||||
return conf
|
||||
}
|
||||
|
||||
// Fix config version ‘3’. Some v3 config files are written without
|
||||
// proper hostConfig JSON tags. They may also contain unused ACL and
|
||||
// Access fields. Rewrite the hostConfig with proper fields using JSON
|
||||
// tags and drop the unused (ACL, Access) fields.
|
||||
func fixConfigV3() {
|
||||
if !isMcConfigExists() {
|
||||
return
|
||||
}
|
||||
brokenCfgV3 := newBrokenConfigV3()
|
||||
brokenMcCfgV3, err := quick.Load(mustGetMcConfigPath(), brokenCfgV3)
|
||||
fatalIf(err.Trace(), "Unable to load config.")
|
||||
|
||||
if brokenMcCfgV3.Version() != "3" {
|
||||
return
|
||||
}
|
||||
|
||||
cfgV3 := newConfigV3()
|
||||
isMutated := false
|
||||
for k, v := range brokenMcCfgV3.Data().(*brokenConfigV3).Aliases {
|
||||
cfgV3.Aliases[k] = v
|
||||
}
|
||||
|
||||
for host, brokenHostCfgV3 := range brokenMcCfgV3.Data().(*brokenConfigV3).Hosts {
|
||||
|
||||
// If any of these fields contains any real value anytime,
|
||||
// it means we have already fixed the broken configuration.
|
||||
// We don't have to regenerate again.
|
||||
if brokenHostCfgV3.AccessKeyID != "" && brokenHostCfgV3.SecretAccessKey != "" {
|
||||
isMutated = true
|
||||
}
|
||||
|
||||
// Use the correct hostConfig with JSON tags in it.
|
||||
cfgV3.Hosts[host] = hostConfigV3{
|
||||
AccessKeyID: brokenHostCfgV3.AccessKeyID,
|
||||
SecretAccessKey: brokenHostCfgV3.SecretAccessKey,
|
||||
}
|
||||
}
|
||||
|
||||
// We blindly drop ACL and Access fields from the broken config v3.
|
||||
|
||||
if isMutated {
|
||||
mcNewConfigV3, err := quick.New(cfgV3)
|
||||
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘3’.")
|
||||
|
||||
err = mcNewConfigV3.Save(mustGetMcConfigPath())
|
||||
fatalIf(err.Trace(), "Unable to save config version ‘3’.")
|
||||
|
||||
console.Infof("Successfully fixed %s broken config for version ‘3’.\n", mustGetMcConfigPath())
|
||||
}
|
||||
}
|
||||
|
||||
// If the host key does not have http(s), fix it.
|
||||
func fixConfigV6ForHosts() {
|
||||
if !isMcConfigExists() {
|
||||
return
|
||||
}
|
||||
|
||||
brokenMcCfgV6, err := quick.Load(mustGetMcConfigPath(), newConfigV6())
|
||||
fatalIf(err.Trace(), "Unable to load config.")
|
||||
|
||||
if brokenMcCfgV6.Version() != "6" {
|
||||
return
|
||||
}
|
||||
|
||||
newCfgV6 := newConfigV6()
|
||||
isMutated := false
|
||||
|
||||
// Copy aliases.
|
||||
for k, v := range brokenMcCfgV6.Data().(*configV6).Aliases {
|
||||
newCfgV6.Aliases[k] = v
|
||||
}
|
||||
|
||||
url := new(client.URL)
|
||||
// Copy hosts.
|
||||
for host, hostCfgV6 := range brokenMcCfgV6.Data().(*configV6).Hosts {
|
||||
// Already fixed - Copy and move on.
|
||||
if strings.HasPrefix(host, "https") || strings.HasPrefix(host, "http") {
|
||||
newCfgV6.Hosts[host] = hostCfgV6
|
||||
continue
|
||||
}
|
||||
|
||||
// If host entry does not contain "http(s)", introduce a new entry and delete the old one.
|
||||
if host == "s3.amazonaws.com" || host == "storage.googleapis.com" ||
|
||||
host == "localhost:9000" || host == "127.0.0.1:9000" ||
|
||||
host == "play.minio.io:9000" || host == "dl.minio.io:9000" {
|
||||
console.Infoln("Found broken host entries, replacing " + host + " with https://" + host + ".")
|
||||
url.Host = host
|
||||
url.Scheme = "https"
|
||||
url.SchemeSeparator = "://"
|
||||
newCfgV6.Hosts[url.String()] = hostCfgV6
|
||||
isMutated = true
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
if isMutated {
|
||||
// Save the new config back to the disk.
|
||||
mcCfgV6, err := quick.New(newCfgV6)
|
||||
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘v6’.")
|
||||
|
||||
err = mcCfgV6.Save(mustGetMcConfigPath())
|
||||
fatalIf(err.Trace(), "Unable to save config version ‘v6’.")
|
||||
}
|
||||
}
|
||||
|
||||
// fixConfigV6 - fix all the unnecessary glob URLs present in existing config version 6.
|
||||
func fixConfigV6() {
|
||||
if !isMcConfigExists() {
|
||||
return
|
||||
}
|
||||
config, err := quick.New(newConfigV6())
|
||||
fatalIf(err.Trace(), "Unable to initialize config.")
|
||||
|
||||
err = config.Load(mustGetMcConfigPath())
|
||||
fatalIf(err.Trace(mustGetMcConfigPath()), "Unable to load config.")
|
||||
|
||||
if config.Data().(*configV6).Version != "6" {
|
||||
return
|
||||
}
|
||||
|
||||
newConfig := new(configV6)
|
||||
isMutated := false
|
||||
newConfig.Aliases = make(map[string]string)
|
||||
newConfig.Hosts = make(map[string]hostConfigV6)
|
||||
newConfig.Version = "6"
|
||||
newConfig.Aliases = config.Data().(*configV6).Aliases
|
||||
for host, hostCfg := range config.Data().(*configV6).Hosts {
|
||||
if strings.Contains(host, "*") {
|
||||
fatalIf(err.Trace(),
|
||||
fmt.Sprintf("Glob style ‘*’ pattern matching is no longer supported. Please fix ‘%s’ entry manually.", host))
|
||||
}
|
||||
if strings.Contains(host, "*s3*") || strings.Contains(host, "*.s3*") {
|
||||
console.Infoln("Found glob url, replacing " + host + " with s3.amazonaws.com")
|
||||
newConfig.Hosts["s3.amazonaws.com"] = hostCfg
|
||||
isMutated = true
|
||||
continue
|
||||
}
|
||||
if strings.Contains(host, "s3*") {
|
||||
console.Infoln("Found glob url, replacing " + host + " with s3.amazonaws.com")
|
||||
newConfig.Hosts["s3.amazonaws.com"] = hostCfg
|
||||
isMutated = true
|
||||
continue
|
||||
}
|
||||
if strings.Contains(host, "*amazonaws.com") || strings.Contains(host, "*.amazonaws.com") {
|
||||
console.Infoln("Found glob url, replacing " + host + " with s3.amazonaws.com")
|
||||
newConfig.Hosts["s3.amazonaws.com"] = hostCfg
|
||||
isMutated = true
|
||||
continue
|
||||
}
|
||||
if strings.Contains(host, "*storage.googleapis.com") {
|
||||
console.Infoln("Found glob url, replacing " + host + " with storage.googleapis.com")
|
||||
newConfig.Hosts["storage.googleapis.com"] = hostCfg
|
||||
isMutated = true
|
||||
continue
|
||||
}
|
||||
if strings.Contains(host, "localhost:*") {
|
||||
console.Infoln("Found glob url, replacing " + host + " with localhost:9000")
|
||||
newConfig.Hosts["localhost:9000"] = hostCfg
|
||||
isMutated = true
|
||||
continue
|
||||
}
|
||||
if strings.Contains(host, "127.0.0.1:*") {
|
||||
console.Infoln("Found glob url, replacing " + host + " with 127.0.0.1:9000")
|
||||
newConfig.Hosts["127.0.0.1:9000"] = hostCfg
|
||||
isMutated = true
|
||||
continue
|
||||
}
|
||||
// Other entries are hopefully OK. Copy them blindly.
|
||||
newConfig.Hosts[host] = hostCfg
|
||||
}
|
||||
|
||||
if isMutated {
|
||||
newConf, err := quick.New(newConfig)
|
||||
fatalIf(err.Trace(), "Unable to initialize newly fixed config.")
|
||||
|
||||
err = newConf.Save(mustGetMcConfigPath())
|
||||
fatalIf(err.Trace(mustGetMcConfigPath()), "Unable to save newly fixed config path.")
|
||||
console.Infof("Successfully fixed %s broken config for version ‘6’.\n", mustGetMcConfigPath())
|
||||
}
|
||||
}
|
||||
@@ -1,285 +0,0 @@
|
||||
/*
|
||||
* Minio Client (C) 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
)
|
||||
|
||||
var (
|
||||
configHostFlags = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "help, h",
|
||||
Usage: "Help of config host",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
var configHostCmd = cli.Command{
|
||||
Name: "host",
|
||||
Usage: "List, modify and remove hosts in configuration file.",
|
||||
Flags: append(configHostFlags, globalFlags...),
|
||||
Action: mainConfigHost,
|
||||
CustomHelpTemplate: `NAME:
|
||||
mc config {{.Name}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
mc config {{.Name}} OPERATION
|
||||
|
||||
OPERATION:
|
||||
add ALIAS URL ACCESS-KEY SECRET-KEY [API]
|
||||
remove ALIAS
|
||||
list
|
||||
|
||||
FLAGS:
|
||||
{{range .Flags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Add Amazon S3 storage service under "myphotos" alias. For security reasons turn off bash history momentarily.
|
||||
$ set +o history
|
||||
$ mc config {{.Name}} add myphotos https://s3.amazonaws.com BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12
|
||||
$ set -o history
|
||||
|
||||
2. Add Google Cloud Storage service under "goodisk" alias.
|
||||
$ mc config {{.Name}} add goodisk https://storage.googleapis.com BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 S3v2
|
||||
|
||||
3. List all hosts.
|
||||
$ mc config {{.Name}} list
|
||||
|
||||
4. Remove "goodisk" config.
|
||||
$ mc config {{.Name}} remove goodisk
|
||||
`,
|
||||
}
|
||||
|
||||
// hostMessage container for content message structure
|
||||
type hostMessage struct {
|
||||
op string
|
||||
Status string `json:"status"`
|
||||
Alias string `json:"alias"`
|
||||
URL string `json:"URL"`
|
||||
AccessKey string `json:"accessKey,omitempty"`
|
||||
SecretKey string `json:"secretKey,omitempty"`
|
||||
API string `json:"api,omitempty"`
|
||||
}
|
||||
|
||||
// String colorized host message
|
||||
func (h hostMessage) String() string {
|
||||
switch h.op {
|
||||
case "list":
|
||||
message := console.Colorize("Alias", fmt.Sprintf("%s: ", h.Alias))
|
||||
message += console.Colorize("URL", fmt.Sprintf("%s", h.URL))
|
||||
if h.AccessKey != "" || h.SecretKey != "" {
|
||||
message += " | " + console.Colorize("AccessKey", fmt.Sprintf("<- %s,", h.AccessKey))
|
||||
message += " | " + console.Colorize("SecretKey", fmt.Sprintf(" %s,", h.SecretKey))
|
||||
message += " | " + console.Colorize("API", fmt.Sprintf(" %s", h.API))
|
||||
}
|
||||
return message
|
||||
case "remove":
|
||||
return console.Colorize("HostMessage", "Removed ‘"+h.Alias+"’ successfully.")
|
||||
case "add":
|
||||
return console.Colorize("HostMessage", "Added ‘"+h.Alias+"’ successfully.")
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
// JSON jsonified host message
|
||||
func (h hostMessage) JSON() string {
|
||||
h.Status = "success"
|
||||
jsonMessageBytes, e := json.Marshal(h)
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(jsonMessageBytes)
|
||||
}
|
||||
|
||||
// Validate command-line input args.
|
||||
func checkConfigHostSyntax(ctx *cli.Context) {
|
||||
// show help if nothing is set
|
||||
if !ctx.Args().Present() {
|
||||
cli.ShowCommandHelpAndExit(ctx, "host", 1) // last argument is exit code
|
||||
}
|
||||
|
||||
switch strings.TrimSpace(ctx.Args().First()) {
|
||||
case "add":
|
||||
checkConfigHostAddSyntax(ctx)
|
||||
case "remove":
|
||||
checkConfigHostRemoveSyntax(ctx)
|
||||
case "list":
|
||||
default:
|
||||
cli.ShowCommandHelpAndExit(ctx, "host", 1) // last argument is exit code
|
||||
}
|
||||
}
|
||||
|
||||
// checkConfigHostAddSyntax - verifies input arguments to 'config host add'.
|
||||
func checkConfigHostAddSyntax(ctx *cli.Context) {
|
||||
tailArgs := ctx.Args().Tail()
|
||||
tailsArgsNr := len(tailArgs)
|
||||
if tailsArgsNr < 4 || tailsArgsNr > 5 {
|
||||
fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...),
|
||||
"Incorrect number of arguments for host add command.")
|
||||
}
|
||||
|
||||
alias := tailArgs.Get(0)
|
||||
url := tailArgs.Get(1)
|
||||
accessKey := tailArgs.Get(2)
|
||||
secretKey := tailArgs.Get(3)
|
||||
api := tailArgs.Get(4)
|
||||
|
||||
if !isValidAlias(alias) {
|
||||
fatalIf(errDummy().Trace(alias), "Invalid alias ‘"+alias+"’.")
|
||||
}
|
||||
|
||||
if !isValidHostURL(url) {
|
||||
fatalIf(errDummy().Trace(url),
|
||||
"Invalid URL ‘"+url+"’.")
|
||||
}
|
||||
|
||||
if !isValidAccessKey(accessKey) {
|
||||
fatalIf(errInvalidArgument().Trace(accessKey),
|
||||
"Invalid access key ‘"+accessKey+"’.")
|
||||
}
|
||||
|
||||
if !isValidSecretKey(secretKey) {
|
||||
fatalIf(errInvalidArgument().Trace(secretKey),
|
||||
"Invalid secret key ‘"+secretKey+"’.")
|
||||
}
|
||||
|
||||
switch api {
|
||||
case "S3v2", "S3v4", "":
|
||||
default:
|
||||
fatalIf(errInvalidArgument().Trace(api),
|
||||
"Unrecognized API signature. Valid options are ‘[ S3v4, S3v2 ]’.")
|
||||
}
|
||||
}
|
||||
|
||||
// checkConfigHostRemoveSyntax - verifies input arguments to 'config host remove'.
|
||||
func checkConfigHostRemoveSyntax(ctx *cli.Context) {
|
||||
tailArgs := ctx.Args().Tail()
|
||||
|
||||
if len(ctx.Args().Tail()) != 1 {
|
||||
fatalIf(errInvalidArgument().Trace(tailArgs...),
|
||||
"Incorrect number of arguments for remove host command.")
|
||||
}
|
||||
|
||||
if !isValidAlias(tailArgs.Get(0)) {
|
||||
fatalIf(errDummy().Trace(tailArgs.Get(0)),
|
||||
"Invalid alias ‘"+tailArgs.Get(0)+"’.")
|
||||
}
|
||||
}
|
||||
|
||||
func mainConfigHost(ctx *cli.Context) {
|
||||
// Set global flags from context.
|
||||
setGlobalsFromContext(ctx)
|
||||
|
||||
// check 'config host' cli arguments.
|
||||
checkConfigHostSyntax(ctx)
|
||||
|
||||
// Additional command speific theme customization.
|
||||
console.SetColor("HostMessage", color.New(color.FgGreen))
|
||||
console.SetColor("Alias", color.New(color.FgCyan, color.Bold))
|
||||
console.SetColor("URL", color.New(color.FgCyan))
|
||||
console.SetColor("AccessKey", color.New(color.FgBlue))
|
||||
console.SetColor("SecretKey", color.New(color.FgBlue))
|
||||
console.SetColor("API", color.New(color.FgYellow))
|
||||
|
||||
cmd := ctx.Args().First()
|
||||
args := ctx.Args().Tail()
|
||||
|
||||
// Switch case through commands.
|
||||
switch strings.TrimSpace(cmd) {
|
||||
case "add":
|
||||
alias := args.Get(0)
|
||||
url := args.Get(1)
|
||||
accessKey := args.Get(2)
|
||||
secretKey := args.Get(3)
|
||||
api := args.Get(4)
|
||||
if strings.TrimSpace(api) == "" {
|
||||
api = "S3v4"
|
||||
}
|
||||
hostCfg := hostConfigV7{
|
||||
URL: url,
|
||||
AccessKey: accessKey,
|
||||
SecretKey: secretKey,
|
||||
API: api,
|
||||
}
|
||||
addHost(alias, hostCfg) // Add a host with specified credentials.
|
||||
case "remove":
|
||||
alias := args.Get(0)
|
||||
removeHost(alias) // Remove a host.
|
||||
case "list":
|
||||
listHosts() // List all configured hosts.
|
||||
}
|
||||
}
|
||||
|
||||
// addHost - add a host config.
|
||||
func addHost(alias string, hostCfgV7 hostConfigV7) {
|
||||
mcCfgV7, err := loadMcConfig()
|
||||
fatalIf(err.Trace(globalMCConfigVersion), "Unable to load config ‘"+mustGetMcConfigPath()+"’.")
|
||||
|
||||
// Add new host.
|
||||
mcCfgV7.Hosts[alias] = hostCfgV7
|
||||
|
||||
err = saveMcConfig(mcCfgV7)
|
||||
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,
|
||||
})
|
||||
}
|
||||
|
||||
// removeHost - removes a host.
|
||||
func removeHost(alias string) {
|
||||
conf, err := loadMcConfig()
|
||||
fatalIf(err.Trace(globalMCConfigVersion), "Unable to load config version ‘"+globalMCConfigVersion+"’.")
|
||||
|
||||
// Remove host.
|
||||
delete(conf.Hosts, alias)
|
||||
|
||||
err = saveMcConfig(conf)
|
||||
fatalIf(err.Trace(alias), "Unable to save deleted hosts in config version ‘"+globalMCConfigVersion+"’.")
|
||||
|
||||
printMsg(hostMessage{op: "remove", Alias: alias})
|
||||
}
|
||||
|
||||
// listHosts - list all host URLs.
|
||||
func listHosts() {
|
||||
conf, err := loadMcConfig()
|
||||
fatalIf(err.Trace(globalMCConfigVersion), "Unable to load config version ‘"+globalMCConfigVersion+"’.")
|
||||
|
||||
for k, v := range conf.Hosts {
|
||||
printMsg(hostMessage{
|
||||
op: "list",
|
||||
Alias: k,
|
||||
URL: v.URL,
|
||||
AccessKey: v.AccessKey,
|
||||
SecretKey: v.SecretKey,
|
||||
API: v.API,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
/*
|
||||
* Minio Client (C) 2014, 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import "github.com/minio/cli"
|
||||
|
||||
// Configure minio client
|
||||
//
|
||||
// ----
|
||||
// NOTE: that the configure command only writes values to the config file.
|
||||
// It does not use any configuration values from the environment variables.
|
||||
//
|
||||
// One needs to edit configuration file manually, this is purposefully done
|
||||
// so to avoid taking credentials over cli arguments. It is a security precaution
|
||||
// ----
|
||||
//
|
||||
|
||||
var (
|
||||
configFlags = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "help, h",
|
||||
Usage: "Help of config.",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
var configCmd = cli.Command{
|
||||
Name: "config",
|
||||
Usage: "Manage configuration file.",
|
||||
Action: mainConfig,
|
||||
Flags: append(configFlags, globalFlags...),
|
||||
Subcommands: []cli.Command{
|
||||
configHostCmd,
|
||||
},
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.Name}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.Name}} [FLAGS] COMMAND
|
||||
|
||||
FLAGS:
|
||||
{{range .Flags}}{{.}}
|
||||
{{end}}
|
||||
COMMANDS:
|
||||
{{range .Commands}}{{join .Names ", "}}{{ "\t" }}{{.Usage}}
|
||||
{{end}}
|
||||
`,
|
||||
}
|
||||
|
||||
// mainConfig is the handle for "mc config" command. provides sub-commands which write configuration data in json format to config file.
|
||||
func mainConfig(ctx *cli.Context) {
|
||||
// Set global flags from context.
|
||||
setGlobalsFromContext(ctx)
|
||||
|
||||
if ctx.Args().First() != "" { // command help.
|
||||
cli.ShowCommandHelp(ctx, ctx.Args().First())
|
||||
} else {
|
||||
// command with Subcommands is an App.
|
||||
cli.ShowAppHelp(ctx)
|
||||
}
|
||||
|
||||
// Sub-commands like "host" and "alias" have their own main.
|
||||
}
|
||||
@@ -1,380 +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 (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio-xl/pkg/quick"
|
||||
)
|
||||
|
||||
// migrate config files from the any older version to the latest.
|
||||
func migrateConfig() {
|
||||
// Migrate config V1 to V101
|
||||
migrateConfigV1ToV101()
|
||||
// Migrate config V101 to V2
|
||||
migrateConfigV101ToV2()
|
||||
// Migrate config V2 to V3
|
||||
migrateConfigV2ToV3()
|
||||
// Migrate config V3 to V4
|
||||
migrateConfigV3ToV4()
|
||||
// Migrate config V4 to V5
|
||||
migrateConfigV4ToV5()
|
||||
// Migrate config V5 to V6
|
||||
migrateConfigV5ToV6()
|
||||
// Migrate config V6 to V7
|
||||
migrateConfigV6ToV7()
|
||||
}
|
||||
|
||||
// Migrate from config version 1.0 to 1.0.1. Populate example entries and save it back.
|
||||
func migrateConfigV1ToV101() {
|
||||
if !isMcConfigExists() {
|
||||
return
|
||||
}
|
||||
mcCfgV1, err := quick.Load(mustGetMcConfigPath(), newConfigV1())
|
||||
fatalIf(err.Trace(), "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" {
|
||||
return
|
||||
}
|
||||
|
||||
// 1.0.1 is compatible to 1.0.0. We are just adding new entries.
|
||||
cfgV101 := newConfigV101()
|
||||
|
||||
// Copy aliases.
|
||||
for k, v := range mcCfgV1.Data().(*configV1).Aliases {
|
||||
cfgV101.Aliases[k] = v
|
||||
}
|
||||
|
||||
// Copy hosts.
|
||||
for k, hostCfgV1 := range mcCfgV1.Data().(*configV1).Hosts {
|
||||
cfgV101.Hosts[k] = hostConfigV101{
|
||||
AccessKeyID: hostCfgV1.AccessKeyID,
|
||||
SecretAccessKey: hostCfgV1.SecretAccessKey,
|
||||
}
|
||||
}
|
||||
|
||||
// Example localhost entry.
|
||||
if _, ok := cfgV101.Hosts["localhost:*"]; !ok {
|
||||
cfgV101.Hosts["localhost:*"] = hostConfigV101{}
|
||||
}
|
||||
|
||||
// Example loopback IP entry.
|
||||
if _, ok := cfgV101.Hosts["127.0.0.1:*"]; !ok {
|
||||
cfgV101.Hosts["127.0.0.1:*"] = hostConfigV101{}
|
||||
}
|
||||
|
||||
// Example AWS entry.
|
||||
// Look for glob string (not glob match). We used to support glob based key matching earlier.
|
||||
if _, ok := cfgV101.Hosts["*.s3*.amazonaws.com"]; !ok {
|
||||
cfgV101.Hosts["*.s3*.amazonaws.com"] = hostConfigV101{
|
||||
AccessKeyID: "YOUR-ACCESS-KEY-ID-HERE",
|
||||
SecretAccessKey: "YOUR-SECRET-ACCESS-KEY-HERE",
|
||||
}
|
||||
}
|
||||
|
||||
// Save the new config back to the disk.
|
||||
mcCfgV101, err := quick.New(cfgV101)
|
||||
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘1.0.1’.")
|
||||
err = mcCfgV101.Save(mustGetMcConfigPath())
|
||||
fatalIf(err.Trace(), "Unable to save config version ‘1.0.1’.")
|
||||
|
||||
console.Infof("Successfully migrated %s from version ‘1.0.0’ to version ‘1.0.1’.\n", mustGetMcConfigPath())
|
||||
}
|
||||
|
||||
// Migrate from config ‘1.0.1’ to ‘2’. Drop semantic versioning and move to integer versioning. No other changes.
|
||||
func migrateConfigV101ToV2() {
|
||||
if !isMcConfigExists() {
|
||||
return
|
||||
}
|
||||
mcCfgV101, err := quick.Load(mustGetMcConfigPath(), newConfigV101())
|
||||
fatalIf(err.Trace(), "Unable to load config version ‘1.0.1’.")
|
||||
|
||||
// update to newer version
|
||||
if mcCfgV101.Version() != "1.0.1" {
|
||||
return
|
||||
}
|
||||
|
||||
cfgV2 := newConfigV2()
|
||||
|
||||
// Copy aliases.
|
||||
for k, v := range mcCfgV101.Data().(*configV101).Aliases {
|
||||
cfgV2.Aliases[k] = v
|
||||
}
|
||||
|
||||
// Copy hosts.
|
||||
for k, hostCfgV101 := range mcCfgV101.Data().(*configV101).Hosts {
|
||||
cfgV2.Hosts[k] = hostConfigV2{
|
||||
AccessKeyID: hostCfgV101.AccessKeyID,
|
||||
SecretAccessKey: hostCfgV101.SecretAccessKey,
|
||||
}
|
||||
}
|
||||
|
||||
mcCfgV2, err := quick.New(cfgV2)
|
||||
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘2’.")
|
||||
|
||||
err = mcCfgV2.Save(mustGetMcConfigPath())
|
||||
fatalIf(err.Trace(), "Unable to save config version ‘2’.")
|
||||
|
||||
console.Infof("Successfully migrated %s from version ‘1.0.1’ to version ‘2’.\n", mustGetMcConfigPath())
|
||||
}
|
||||
|
||||
// Migrate from config ‘2’ to ‘3’. Use ‘-’ separated names for
|
||||
// hostConfig using struct json tags.
|
||||
func migrateConfigV2ToV3() {
|
||||
if !isMcConfigExists() {
|
||||
return
|
||||
}
|
||||
|
||||
mcCfgV2, err := quick.Load(mustGetMcConfigPath(), newConfigV2())
|
||||
fatalIf(err.Trace(), "Unable to load mc config V2.")
|
||||
|
||||
// update to newer version
|
||||
if mcCfgV2.Version() != "2" {
|
||||
return
|
||||
}
|
||||
|
||||
cfgV3 := newConfigV3()
|
||||
|
||||
// Copy aliases.
|
||||
for k, v := range mcCfgV2.Data().(*configV2).Aliases {
|
||||
cfgV3.Aliases[k] = v
|
||||
}
|
||||
|
||||
// Copy hosts.
|
||||
for k, hostCfgV2 := range mcCfgV2.Data().(*configV2).Hosts {
|
||||
// New hostConfV3 uses struct json tags.
|
||||
cfgV3.Hosts[k] = hostConfigV3{
|
||||
AccessKeyID: hostCfgV2.AccessKeyID,
|
||||
SecretAccessKey: hostCfgV2.SecretAccessKey,
|
||||
}
|
||||
}
|
||||
|
||||
mcNewCfgV3, err := quick.New(cfgV3)
|
||||
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘3’.")
|
||||
|
||||
err = mcNewCfgV3.Save(mustGetMcConfigPath())
|
||||
fatalIf(err.Trace(), "Unable to save config version ‘3’.")
|
||||
|
||||
console.Infof("Successfully migrated %s from version ‘2’ to version ‘3’.\n", mustGetMcConfigPath())
|
||||
}
|
||||
|
||||
// Migrate from config version ‘3’ to ‘4’. Introduce API Signature
|
||||
// field in host config. Also Use JavaScript notation for field names.
|
||||
func migrateConfigV3ToV4() {
|
||||
if !isMcConfigExists() {
|
||||
return
|
||||
}
|
||||
mcCfgV3, err := quick.Load(mustGetMcConfigPath(), newConfigV3())
|
||||
fatalIf(err.Trace(), "Unable to load mc config V2.")
|
||||
|
||||
// update to newer version
|
||||
if mcCfgV3.Version() != "3" {
|
||||
return
|
||||
}
|
||||
|
||||
cfgV4 := newConfigV4()
|
||||
for k, v := range mcCfgV3.Data().(*configV3).Aliases {
|
||||
cfgV4.Aliases[k] = v
|
||||
}
|
||||
// New hostConfig has API signature. All older entries were V4
|
||||
// only. So it is safe to assume V4 as default for all older
|
||||
// entries.
|
||||
// HostConfigV4 als uses JavaScript naming notation for struct JSON tags.
|
||||
for host, hostCfgV3 := range mcCfgV3.Data().(*configV3).Hosts {
|
||||
cfgV4.Hosts[host] = hostConfigV4{
|
||||
AccessKeyID: hostCfgV3.AccessKeyID,
|
||||
SecretAccessKey: hostCfgV3.SecretAccessKey,
|
||||
Signature: "v4",
|
||||
}
|
||||
}
|
||||
|
||||
mcNewCfgV4, err := quick.New(cfgV4)
|
||||
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘4’.")
|
||||
|
||||
err = mcNewCfgV4.Save(mustGetMcConfigPath())
|
||||
fatalIf(err.Trace(), "Unable to save config version ‘4’.")
|
||||
|
||||
console.Infof("Successfully migrated %s from version ‘3’ to version ‘4’.\n", mustGetMcConfigPath())
|
||||
|
||||
}
|
||||
|
||||
// Migrate config version ‘4’ to ‘5’. Rename hostConfigV4.Signature -> hostConfigV5.API.
|
||||
func migrateConfigV4ToV5() {
|
||||
if !isMcConfigExists() {
|
||||
return
|
||||
}
|
||||
mcCfgV4, err := quick.Load(mustGetMcConfigPath(), newConfigV4())
|
||||
fatalIf(err.Trace(), "Unable to load mc config V4.")
|
||||
|
||||
// update to newer version
|
||||
if mcCfgV4.Version() != "4" {
|
||||
return
|
||||
}
|
||||
|
||||
cfgV5 := newConfigV5()
|
||||
for k, v := range mcCfgV4.Data().(*configV4).Aliases {
|
||||
cfgV5.Aliases[k] = v
|
||||
}
|
||||
for host, hostCfgV4 := range mcCfgV4.Data().(*configV4).Hosts {
|
||||
cfgV5.Hosts[host] = hostConfigV5{
|
||||
AccessKeyID: hostCfgV4.AccessKeyID,
|
||||
SecretAccessKey: hostCfgV4.SecretAccessKey,
|
||||
API: "v4", // Rename from .Signature to .API
|
||||
}
|
||||
}
|
||||
|
||||
mcNewCfgV5, err := quick.New(cfgV5)
|
||||
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘5’.")
|
||||
|
||||
err = mcNewCfgV5.Save(mustGetMcConfigPath())
|
||||
fatalIf(err.Trace(), "Unable to save config version ‘5’.")
|
||||
|
||||
console.Infof("Successfully migrated %s from version ‘4’ to version ‘5’.\n", mustGetMcConfigPath())
|
||||
}
|
||||
|
||||
// Migrate config version ‘5’ to ‘6’. Add google cloud storage servers
|
||||
// to host config. Also remove "." from s3 aws glob rule.
|
||||
func migrateConfigV5ToV6() {
|
||||
if !isMcConfigExists() {
|
||||
return
|
||||
}
|
||||
mcCfgV5, err := quick.Load(mustGetMcConfigPath(), newConfigV5())
|
||||
fatalIf(err.Trace(), "Unable to load mc config V5.")
|
||||
|
||||
// update to newer version
|
||||
if mcCfgV5.Version() != "5" {
|
||||
return
|
||||
}
|
||||
|
||||
cfgV6 := newConfigV6()
|
||||
|
||||
// Add new Google Cloud Storage alias.
|
||||
cfgV6.Aliases["gcs"] = "https://storage.googleapis.com"
|
||||
|
||||
for k, v := range mcCfgV5.Data().(*configV5).Aliases {
|
||||
cfgV6.Aliases[k] = v
|
||||
}
|
||||
|
||||
// Add defaults.
|
||||
cfgV6.Hosts["*s3*amazonaws.com"] = hostConfigV6{
|
||||
AccessKeyID: "YOUR-ACCESS-KEY-ID-HERE",
|
||||
SecretAccessKey: "YOUR-SECRET-ACCESS-KEY-HERE",
|
||||
API: "S3v4",
|
||||
}
|
||||
cfgV6.Hosts["*storage.googleapis.com"] = hostConfigV6{
|
||||
AccessKeyID: "YOUR-ACCESS-KEY-ID-HERE",
|
||||
SecretAccessKey: "YOUR-SECRET-ACCESS-KEY-HERE",
|
||||
API: "S3v2",
|
||||
}
|
||||
|
||||
for host, hostCfgV5 := range mcCfgV5.Data().(*configV5).Hosts {
|
||||
// Find any matching s3 entry and copy keys from it to newer generalized glob entry.
|
||||
if strings.Contains(host, "s3") {
|
||||
if (hostCfgV5.AccessKeyID == "YOUR-ACCESS-KEY-ID-HERE") ||
|
||||
(hostCfgV5.SecretAccessKey == "YOUR-SECRET-ACCESS-KEY-HERE") ||
|
||||
hostCfgV5.AccessKeyID == "" ||
|
||||
hostCfgV5.SecretAccessKey == "" {
|
||||
continue // Skip defaults.
|
||||
}
|
||||
// Now we have real keys set by the user. Copy
|
||||
// them over to newer glob rule.
|
||||
// Original host entry has "." in the glob rule.
|
||||
host = "*s3*amazonaws.com" // Use this glob entry.
|
||||
}
|
||||
|
||||
cfgV6.Hosts[host] = hostConfigV6{
|
||||
AccessKeyID: hostCfgV5.AccessKeyID,
|
||||
SecretAccessKey: hostCfgV5.SecretAccessKey,
|
||||
API: hostCfgV5.API,
|
||||
}
|
||||
}
|
||||
|
||||
mcNewCfgV6, err := quick.New(cfgV6)
|
||||
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘6’.")
|
||||
|
||||
err = mcNewCfgV6.Save(mustGetMcConfigPath())
|
||||
fatalIf(err.Trace(), "Unable to save config version ‘6’.")
|
||||
|
||||
console.Infof("Successfully migrated %s from version ‘5’ to version ‘6’.\n", mustGetMcConfigPath())
|
||||
}
|
||||
|
||||
// Migrate config version ‘6’ to ‘7'. Remove alias map and introduce
|
||||
// named Host config. Also no more glob match for host config entries.
|
||||
func migrateConfigV6ToV7() {
|
||||
if !isMcConfigExists() {
|
||||
return
|
||||
}
|
||||
|
||||
mcCfgV6, err := quick.Load(mustGetMcConfigPath(), newConfigV6())
|
||||
fatalIf(err.Trace(), "Unable to load mc config V6.")
|
||||
|
||||
if mcCfgV6.Version() != "6" {
|
||||
return
|
||||
}
|
||||
|
||||
cfgV7 := newConfigV7()
|
||||
aliasIndex := 0
|
||||
// We dropped alias support in v7. We only need to migrate host configs.
|
||||
for host, hostCfgV6 := range mcCfgV6.Data().(*configV6).Hosts {
|
||||
if hostCfgV6.AccessKeyID == "YOUR-ACCESS-KEY-ID-HERE" ||
|
||||
hostCfgV6.SecretAccessKey == "YOUR-SECRET-ACCESS-KEY-HERE" ||
|
||||
hostCfgV6.AccessKeyID == "" ||
|
||||
hostCfgV6.SecretAccessKey == "" {
|
||||
// Ignore default entries. configV7.loadDefaults() will re-insert them back.
|
||||
} else if host == "https://s3.amazonaws.com" {
|
||||
// Only one entry can exist for "s3" domain.
|
||||
cfgV7.Hosts["s3"] = hostConfigV7{
|
||||
URL: host,
|
||||
AccessKey: hostCfgV6.AccessKeyID,
|
||||
SecretKey: hostCfgV6.SecretAccessKey,
|
||||
API: hostCfgV6.API,
|
||||
}
|
||||
} else if host == "https://storage.googleapis.com" {
|
||||
// Only one entry can exist for "gcs" domain.
|
||||
cfgV7.Hosts["gcs"] = hostConfigV7{
|
||||
URL: host,
|
||||
AccessKey: hostCfgV6.AccessKeyID,
|
||||
SecretKey: hostCfgV6.SecretAccessKey,
|
||||
API: hostCfgV6.API,
|
||||
}
|
||||
} else {
|
||||
// Assign a generic "cloud1", cloud2..." key
|
||||
// for all other entries that has valid keys set.
|
||||
alias := fmt.Sprintf("cloud%d", aliasIndex)
|
||||
aliasIndex++
|
||||
cfgV7.Hosts[alias] = hostConfigV7{
|
||||
URL: host,
|
||||
AccessKey: hostCfgV6.AccessKeyID,
|
||||
SecretKey: hostCfgV6.SecretAccessKey,
|
||||
API: hostCfgV6.API,
|
||||
}
|
||||
}
|
||||
}
|
||||
// Load default settings.
|
||||
cfgV7.loadDefaults()
|
||||
mcNewCfgV7, err := quick.New(cfgV7)
|
||||
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘7’.")
|
||||
|
||||
err = mcNewCfgV7.Save(mustGetMcConfigPath())
|
||||
fatalIf(err.Trace(), "Unable to save config version ‘7’.")
|
||||
|
||||
console.Infof("Successfully migrated %s from version ‘6’ to version ‘7’.\n", mustGetMcConfigPath())
|
||||
}
|
||||
-164
@@ -1,164 +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
|
||||
|
||||
/////////////////// Config V1 ///////////////////
|
||||
type hostConfigV1 struct {
|
||||
AccessKeyID string
|
||||
SecretAccessKey string
|
||||
}
|
||||
|
||||
type configV1 struct {
|
||||
Version string
|
||||
Aliases map[string]string
|
||||
Hosts map[string]hostConfigV1
|
||||
}
|
||||
|
||||
// newConfigV1() - get new config version 1.0.0
|
||||
func newConfigV1() *configV1 {
|
||||
conf := new(configV1)
|
||||
conf.Version = "1.0.0"
|
||||
// make sure to allocate map's otherwise Golang
|
||||
// exits silently without providing any errors
|
||||
conf.Aliases = make(map[string]string)
|
||||
conf.Hosts = make(map[string]hostConfigV1)
|
||||
return conf
|
||||
}
|
||||
|
||||
/////////////////// Config V101 ///////////////////
|
||||
type hostConfigV101 hostConfigV1
|
||||
|
||||
type configV101 struct {
|
||||
Version string
|
||||
Aliases map[string]string
|
||||
Hosts map[string]hostConfigV101
|
||||
}
|
||||
|
||||
// newConfigV101() - get new config version 1.0.1
|
||||
func newConfigV101() *configV101 {
|
||||
conf := new(configV101)
|
||||
conf.Version = "1.0.1"
|
||||
conf.Aliases = make(map[string]string)
|
||||
conf.Hosts = make(map[string]hostConfigV101)
|
||||
return conf
|
||||
}
|
||||
|
||||
/////////////////// Config V2 ///////////////////
|
||||
type hostConfigV2 hostConfigV1
|
||||
|
||||
type configV2 struct {
|
||||
Version string
|
||||
Aliases map[string]string
|
||||
Hosts map[string]hostConfigV2
|
||||
}
|
||||
|
||||
// newConfigV2() - get new config version 2
|
||||
func newConfigV2() *configV2 {
|
||||
conf := new(configV2)
|
||||
conf.Version = "2"
|
||||
conf.Aliases = make(map[string]string)
|
||||
conf.Hosts = make(map[string]hostConfigV2)
|
||||
return conf
|
||||
}
|
||||
|
||||
/////////////////// Config V3 ///////////////////
|
||||
type hostConfigV3 struct {
|
||||
AccessKeyID string `json:"access-key-id"`
|
||||
SecretAccessKey string `json:"secret-access-key"`
|
||||
}
|
||||
|
||||
type configV3 struct {
|
||||
Version string `json:"version"`
|
||||
Aliases map[string]string `json:"alias"`
|
||||
Hosts map[string]hostConfigV3 `json:"hosts"`
|
||||
}
|
||||
|
||||
// newConfigV3 - get new config version 3.
|
||||
func newConfigV3() *configV3 {
|
||||
conf := new(configV3)
|
||||
conf.Version = "3"
|
||||
conf.Aliases = make(map[string]string)
|
||||
conf.Hosts = make(map[string]hostConfigV3)
|
||||
return conf
|
||||
}
|
||||
|
||||
/////////////////// Config V4 ///////////////////
|
||||
type hostConfigV4 struct {
|
||||
AccessKeyID string `json:"accessKeyId"`
|
||||
SecretAccessKey string `json:"secretAccessKey"`
|
||||
Signature string `json:"signature"`
|
||||
}
|
||||
|
||||
type configV4 struct {
|
||||
Version string `json:"version"`
|
||||
Aliases map[string]string `json:"alias"`
|
||||
Hosts map[string]hostConfigV4 `json:"hosts"`
|
||||
}
|
||||
|
||||
func newConfigV4() *configV4 {
|
||||
conf := new(configV4)
|
||||
conf.Version = "4"
|
||||
conf.Aliases = make(map[string]string)
|
||||
conf.Hosts = make(map[string]hostConfigV4)
|
||||
return conf
|
||||
}
|
||||
|
||||
/////////////////// Config V5 ///////////////////
|
||||
type hostConfigV5 struct {
|
||||
AccessKeyID string `json:"accessKeyId"`
|
||||
SecretAccessKey string `json:"secretAccessKey"`
|
||||
API string `json:"api"`
|
||||
}
|
||||
|
||||
type configV5 struct {
|
||||
Version string `json:"version"`
|
||||
Aliases map[string]string `json:"alias"`
|
||||
Hosts map[string]hostConfigV5 `json:"hosts"`
|
||||
}
|
||||
|
||||
func newConfigV5() *configV5 {
|
||||
conf := new(configV5)
|
||||
conf.Version = "5"
|
||||
conf.Aliases = make(map[string]string)
|
||||
conf.Hosts = make(map[string]hostConfigV5)
|
||||
return conf
|
||||
}
|
||||
|
||||
/////////////////// Config V6 ///////////////////
|
||||
type hostConfigV6 struct {
|
||||
AccessKeyID string `json:"accessKeyId"`
|
||||
SecretAccessKey string `json:"secretAccessKey"`
|
||||
API string `json:"api"`
|
||||
}
|
||||
|
||||
type configV6 struct {
|
||||
Version string `json:"version"`
|
||||
Aliases map[string]string `json:"alias"`
|
||||
Hosts map[string]hostConfigV6 `json:"hosts"`
|
||||
}
|
||||
|
||||
// newConfigV6 - new config version '6'.
|
||||
func newConfigV6() *configV6 {
|
||||
conf := new(configV6)
|
||||
conf.Version = "6"
|
||||
conf.Aliases = make(map[string]string)
|
||||
conf.Hosts = make(map[string]hostConfigV6)
|
||||
return conf
|
||||
}
|
||||
|
||||
/////////////////// Config V7 ///////////////////
|
||||
// RESERVED FOR FUTURE
|
||||
@@ -1,41 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/minio/mc/pkg/client"
|
||||
)
|
||||
|
||||
// isValidSecretKey - validate secret key.
|
||||
func isValidSecretKey(secretKey string) bool {
|
||||
if secretKey == "" {
|
||||
return true
|
||||
}
|
||||
regex := regexp.MustCompile("^.{40}$")
|
||||
return regex.MatchString(secretKey)
|
||||
}
|
||||
|
||||
// isValidAccessKey - validate access key.
|
||||
func isValidAccessKey(accessKey string) bool {
|
||||
if accessKey == "" {
|
||||
return true
|
||||
}
|
||||
regex := regexp.MustCompile("^[A-Z0-9\\-\\.\\_\\~]{20}$")
|
||||
return regex.MatchString(accessKey)
|
||||
}
|
||||
|
||||
// isValidHostURL - validate input host url.
|
||||
func isValidHostURL(hostURL string) bool {
|
||||
if strings.TrimSpace(hostURL) == "" {
|
||||
return false
|
||||
}
|
||||
url := client.NewURL(hostURL)
|
||||
if url.Scheme != "https" && url.Scheme != "http" {
|
||||
return false
|
||||
}
|
||||
if url.Path != "" && url.Path != "/" {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
-157
@@ -1,157 +0,0 @@
|
||||
/*
|
||||
* Minio Client (C) 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"sync"
|
||||
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/minio-xl/pkg/quick"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultAccessKey = "YOUR-ACCESS-KEY-HERE"
|
||||
defaultSecretKey = "YOUR-SECRET-KEY-HERE"
|
||||
)
|
||||
|
||||
var (
|
||||
// set once during first load.
|
||||
cacheCfgV7 *configV7
|
||||
// All access to mc config file should be synchronized.
|
||||
cfgMutex = &sync.RWMutex{}
|
||||
)
|
||||
|
||||
// hostConfig configuration of a host.
|
||||
type hostConfigV7 struct {
|
||||
URL string `json:"url"`
|
||||
AccessKey string `json:"accessKey"`
|
||||
SecretKey string `json:"secretKey"`
|
||||
API string `json:"api"`
|
||||
}
|
||||
|
||||
// configV7 config version.
|
||||
type configV7 struct {
|
||||
Version string `json:"version"`
|
||||
Hosts map[string]hostConfigV7 `json:"hosts"`
|
||||
}
|
||||
|
||||
// newConfigV7 - new config version.
|
||||
func newConfigV7() *configV7 {
|
||||
cfg := new(configV7)
|
||||
cfg.Version = globalMCConfigVersion
|
||||
cfg.Hosts = make(map[string]hostConfigV7)
|
||||
return cfg
|
||||
}
|
||||
|
||||
// SetHost sets host config if not empty.
|
||||
func (c *configV7) setHost(alias string, cfg hostConfigV7) {
|
||||
if _, ok := c.Hosts[alias]; !ok {
|
||||
c.Hosts[alias] = cfg
|
||||
}
|
||||
}
|
||||
|
||||
// load default values for missing entries.
|
||||
func (c *configV7) loadDefaults() {
|
||||
// Minio server running locally.
|
||||
c.setHost("local", hostConfigV7{
|
||||
URL: "http://localhost:9000",
|
||||
AccessKey: "",
|
||||
SecretKey: "",
|
||||
API: "S3v4",
|
||||
})
|
||||
|
||||
// Amazon S3 cloud storage service.
|
||||
c.setHost("s3", hostConfigV7{
|
||||
URL: "https://s3.amazonaws.com",
|
||||
AccessKey: defaultAccessKey,
|
||||
SecretKey: defaultSecretKey,
|
||||
API: "S3v4",
|
||||
})
|
||||
|
||||
// Google cloud storage service.
|
||||
c.setHost("gcs", hostConfigV7{
|
||||
URL: "https://storage.googleapis.com",
|
||||
AccessKey: defaultAccessKey,
|
||||
SecretKey: defaultSecretKey,
|
||||
API: "S3v2",
|
||||
})
|
||||
|
||||
// Minio anonymous server for demo.
|
||||
c.setHost("play", hostConfigV7{
|
||||
URL: "https://play.minio.io:9000",
|
||||
AccessKey: "",
|
||||
SecretKey: "",
|
||||
API: "S3v4",
|
||||
})
|
||||
|
||||
// Minio demo server with public secret and access keys.
|
||||
c.setHost("player", hostConfigV7{
|
||||
URL: "https://play.minio.io:9002",
|
||||
AccessKey: "Q3AM3UQ867SPQQA43P2F",
|
||||
SecretKey: "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG",
|
||||
API: "S3v4",
|
||||
})
|
||||
|
||||
// Minio public download service.
|
||||
c.setHost("dl", hostConfigV7{
|
||||
URL: "https://dl.minio.io:9000",
|
||||
AccessKey: "",
|
||||
SecretKey: "",
|
||||
API: "S3v4",
|
||||
})
|
||||
}
|
||||
|
||||
// loadConfigV7 - loads a new config.
|
||||
func loadConfigV7() (*configV7, *probe.Error) {
|
||||
cfgMutex.RLock()
|
||||
defer cfgMutex.RUnlock()
|
||||
|
||||
// Cached in private global variable.
|
||||
if cacheCfgV7 != nil {
|
||||
return cacheCfgV7, nil
|
||||
}
|
||||
|
||||
if !isMcConfigExists() {
|
||||
return nil, errInvalidArgument().Trace()
|
||||
}
|
||||
|
||||
mcCfgV7, err := quick.Load(mustGetMcConfigPath(), newConfigV7())
|
||||
fatalIf(err.Trace(), "Unable to load mc config file ‘"+mustGetMcConfigPath()+"’.")
|
||||
|
||||
cfgV7 := mcCfgV7.Data().(*configV7)
|
||||
|
||||
// cache it.
|
||||
cacheCfgV7 = cfgV7
|
||||
|
||||
return cfgV7, nil
|
||||
}
|
||||
|
||||
// saveConfigV7 - saves an updated config.
|
||||
func saveConfigV7(cfgV7 *configV7) *probe.Error {
|
||||
cfgMutex.Lock()
|
||||
defer cfgMutex.Unlock()
|
||||
|
||||
qs, err := quick.New(cfgV7)
|
||||
if err != nil {
|
||||
return err.Trace()
|
||||
}
|
||||
|
||||
// update the cache.
|
||||
cacheCfgV7 = cfgV7
|
||||
|
||||
return qs.Save(mustGetMcConfigPath()).Trace(mustGetMcConfigPath())
|
||||
}
|
||||
@@ -1,195 +0,0 @@
|
||||
/*
|
||||
* Minio Client (C) 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"runtime"
|
||||
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/minio/pkg/user"
|
||||
)
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
// getMcConfigDir - construct minio client config folder.
|
||||
func getMcConfigDir() (string, *probe.Error) {
|
||||
if mcCustomConfigDir != "" {
|
||||
return mcCustomConfigDir, nil
|
||||
}
|
||||
homeDir, e := user.HomeDir()
|
||||
if e != nil {
|
||||
return "", probe.NewError(e)
|
||||
}
|
||||
// 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
|
||||
}
|
||||
}
|
||||
|
||||
// mustGetMcConfigDir - construct minio client config folder or fail
|
||||
func mustGetMcConfigDir() (configDir string) {
|
||||
configDir, err := getMcConfigDir()
|
||||
fatalIf(err.Trace(), "Unable to get mcConfigDir.")
|
||||
|
||||
return configDir
|
||||
}
|
||||
|
||||
// createMcConfigDir - create minio client config folder
|
||||
func createMcConfigDir() *probe.Error {
|
||||
p, err := getMcConfigDir()
|
||||
if err != nil {
|
||||
return err.Trace()
|
||||
}
|
||||
if e := os.MkdirAll(p, 0700); e != nil {
|
||||
return probe.NewError(e)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// getMcConfigPath - construct minio client configuration path
|
||||
func getMcConfigPath() (string, *probe.Error) {
|
||||
if mcCustomConfigPath != "" {
|
||||
return mcCustomConfigPath, nil
|
||||
}
|
||||
dir, err := getMcConfigDir()
|
||||
if err != nil {
|
||||
return "", err.Trace()
|
||||
}
|
||||
return filepath.Join(dir, globalMCConfigFile), nil
|
||||
}
|
||||
|
||||
// mustGetMcConfigPath - similar to getMcConfigPath, ignores errors
|
||||
func mustGetMcConfigPath() string {
|
||||
path, err := getMcConfigPath()
|
||||
fatalIf(err.Trace(), "Unable to get mcConfigPath.")
|
||||
|
||||
return path
|
||||
}
|
||||
|
||||
// newMcConfig - initializes a new version '6' config.
|
||||
func newMcConfig() *configV7 {
|
||||
cfg := newConfigV7()
|
||||
cfg.loadDefaults()
|
||||
return cfg
|
||||
}
|
||||
|
||||
// loadMcConfigCached - returns loadMcConfig with a closure for config cache.
|
||||
func loadMcConfigFactory() func() (*configV7, *probe.Error) {
|
||||
// Load once and cache in a closure.
|
||||
cfgCache, err := loadConfigV7()
|
||||
|
||||
// loadMcConfig - reads configuration file and returns config.
|
||||
return func() (*configV7, *probe.Error) {
|
||||
return cfgCache, err
|
||||
}
|
||||
}
|
||||
|
||||
var loadMcConfig = loadMcConfigFactory()
|
||||
|
||||
// saveMcConfig - saves configuration file and returns error if any.
|
||||
func saveMcConfig(config *configV7) *probe.Error {
|
||||
if config == nil {
|
||||
return errInvalidArgument().Trace()
|
||||
}
|
||||
|
||||
err := createMcConfigDir()
|
||||
if err != nil {
|
||||
return err.Trace(mustGetMcConfigDir())
|
||||
}
|
||||
|
||||
// Save the config.
|
||||
if err := saveConfigV7(config); err != nil {
|
||||
return err.Trace(mustGetMcConfigPath())
|
||||
}
|
||||
|
||||
// Refresh the config cache.
|
||||
loadMcConfig = loadMcConfigFactory()
|
||||
return nil
|
||||
}
|
||||
|
||||
// isMcConfigExists returns err if config doesn't exist.
|
||||
func isMcConfigExists() bool {
|
||||
configFile, err := getMcConfigPath()
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
if _, e := os.Stat(configFile); e != nil {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// isValidAlias - Check if alias valid.
|
||||
func isValidAlias(alias string) bool {
|
||||
return regexp.MustCompile("^[a-zA-Z][a-zA-Z0-9-]+$").MatchString(alias)
|
||||
}
|
||||
|
||||
// getHostConfig retrieves host specific configuration such as access keys, signature type.
|
||||
func getHostConfig(alias string) (*hostConfigV7, *probe.Error) {
|
||||
mcCfg, err := loadMcConfig()
|
||||
if err != nil {
|
||||
return nil, err.Trace(alias)
|
||||
}
|
||||
|
||||
// if host is exact return quickly.
|
||||
if _, ok := mcCfg.Hosts[alias]; ok {
|
||||
hostCfg := mcCfg.Hosts[alias]
|
||||
return &hostCfg, nil
|
||||
}
|
||||
|
||||
// return error if cannot be matched.
|
||||
return nil, errNoMatchingHost(alias).Trace(alias)
|
||||
}
|
||||
|
||||
// mustGetHostConfig retrieves host specific configuration such as access keys, signature type.
|
||||
func mustGetHostConfig(alias string) *hostConfigV7 {
|
||||
hostCfg, _ := getHostConfig(alias)
|
||||
return hostCfg
|
||||
}
|
||||
|
||||
// expandAlias expands aliased URL if any match is found, returns as is otherwise.
|
||||
func expandAlias(aliasedURL string) (alias string, urlStr string, hostCfg *hostConfigV7, err *probe.Error) {
|
||||
// Extract alias from the URL.
|
||||
alias, path := url2Alias(aliasedURL)
|
||||
|
||||
// Find the matching alias entry and expand the URL.
|
||||
if hostCfg = mustGetHostConfig(alias); hostCfg != nil {
|
||||
return alias, urlJoinPath(hostCfg.URL, path), hostCfg, nil
|
||||
}
|
||||
return "", aliasedURL, nil, nil // No matching entry found. Return original URL as is.
|
||||
}
|
||||
|
||||
// mustExpandAlias expands aliased URL if any match is found, returns as is otherwise.
|
||||
func mustExpandAlias(aliasedURL string) (alias string, urlStr string, hostCfg *hostConfigV7) {
|
||||
alias, urlStr, hostCfg, _ = expandAlias(aliasedURL)
|
||||
return alias, urlStr, hostCfg
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
#!/bin/bash
|
||||
set -e
|
||||
|
||||
cd "$(dirname "$(readlink -f "$BASH_SOURCE")")"
|
||||
|
||||
# see also ".mailmap" for how email addresses and names are deduplicated
|
||||
|
||||
{
|
||||
cat <<-'EOH'
|
||||
## Contributors
|
||||
<!-- DO NOT EDIT - CONTRIBUTORS.md is autogenerated from git commit log by contributors.sh script. -->
|
||||
EOH
|
||||
echo
|
||||
git log --format='%aN <%aE>' | LC_ALL=C.UTF-8 sort -uf | sed 's/^/- /g'
|
||||
} > CONTRIBUTORS.md
|
||||
-398
@@ -1,398 +0,0 @@
|
||||
/*
|
||||
* Minio Client (C) 2014, 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
|
||||
"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"
|
||||
)
|
||||
|
||||
// cp command flags.
|
||||
var (
|
||||
cpFlags = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "help, h",
|
||||
Usage: "Help of cp.",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "recursive, r",
|
||||
Usage: "Copy recursively.",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
// Copy command.
|
||||
var cpCmd = cli.Command{
|
||||
Name: "cp",
|
||||
Usage: "Copy one or more objects to a target.",
|
||||
Action: mainCopy,
|
||||
Flags: append(cpFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
mc {{.Name}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
mc {{.Name}} [FLAGS] SOURCE [SOURCE...] TARGET
|
||||
|
||||
FLAGS:
|
||||
{{range .Flags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Copy a list of objects from local file system to Amazon S3 cloud storage.
|
||||
$ mc {{.Name}} Music/*.ogg s3/jukebox/
|
||||
|
||||
2. Copy a folder recursively from Minio cloud storage to Amazon S3 cloud storage.
|
||||
$ mc {{.Name}} --recursive play/mybucket/burningman2011/ s3/mybucket/
|
||||
|
||||
3. Copy multiple local folders recursively to Minio cloud storage.
|
||||
$ mc {{.Name}} --recursive backup/2014/ backup/2015/ play/archive/
|
||||
|
||||
4. Copy a bucket recursively from aliased Amazon S3 cloud storage to local filesystem on Windows.
|
||||
$ mc {{.Name}} --recursive s3\documents\2014\ C:\Backups\2014
|
||||
|
||||
5. Copy an object with name containing unicode characters to Amazon S3 cloud storage.
|
||||
$ mc {{.Name}} 本語 s3/andoria/
|
||||
|
||||
6. Copy a local folder with space separated characters to Amazon S3 cloud storage.
|
||||
$ mc {{.Name}} --recursive 'workdir/documents/May 2014/' s3/miniocloud
|
||||
`,
|
||||
}
|
||||
|
||||
// copyMessage container for file copy messages
|
||||
type copyMessage struct {
|
||||
Status string `json:"status"`
|
||||
Source string `json:"source"`
|
||||
Target string `json:"target"`
|
||||
}
|
||||
|
||||
// String colorized copy message
|
||||
func (c copyMessage) String() string {
|
||||
return console.Colorize("Copy", fmt.Sprintf("‘%s’ -> ‘%s’", c.Source, c.Target))
|
||||
}
|
||||
|
||||
// JSON jsonified copy message
|
||||
func (c copyMessage) JSON() string {
|
||||
c.Status = "success"
|
||||
copyMessageBytes, e := json.Marshal(c)
|
||||
fatalIf(probe.NewError(e), "Failed to marshal copy message.")
|
||||
|
||||
return string(copyMessageBytes)
|
||||
}
|
||||
|
||||
// copyStatMessage container for copy accounting message
|
||||
type copyStatMessage struct {
|
||||
Total int64
|
||||
Transferred int64
|
||||
Speed float64
|
||||
}
|
||||
|
||||
// copyStatMessage copy accounting message
|
||||
func (c copyStatMessage) String() string {
|
||||
speedBox := pb.FormatBytes(int64(c.Speed))
|
||||
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)
|
||||
return message
|
||||
}
|
||||
|
||||
// doCopy - Copy a singe file from source to destination
|
||||
func doCopy(cpURLs copyURLs, progressReader *progressBar, accountingReader *accounter) copyURLs {
|
||||
if cpURLs.Error != nil {
|
||||
cpURLs.Error = cpURLs.Error.Trace()
|
||||
return cpURLs
|
||||
}
|
||||
|
||||
if !globalQuiet && !globalJSON {
|
||||
progressReader = progressReader.SetCaption(cpURLs.SourceContent.URL.String() + ": ")
|
||||
}
|
||||
|
||||
sourceAlias := cpURLs.SourceAlias
|
||||
sourceURL := cpURLs.SourceContent.URL
|
||||
targetAlias := cpURLs.TargetAlias
|
||||
targetURL := cpURLs.TargetContent.URL
|
||||
length := cpURLs.SourceContent.Size
|
||||
|
||||
reader, err := getSourceStreamFromAlias(sourceAlias, sourceURL.String())
|
||||
if err != nil {
|
||||
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,
|
||||
})
|
||||
// Proxy reader to accounting reader only during quiet mode.
|
||||
if globalQuiet || globalJSON {
|
||||
progress = accountingReader
|
||||
}
|
||||
} else {
|
||||
// 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
|
||||
}
|
||||
|
||||
// doCopyFake - Perform a fake copy to update the progress bar appropriately.
|
||||
func doCopyFake(cpURLs copyURLs, progressReader *progressBar) copyURLs {
|
||||
if !globalQuiet && !globalJSON {
|
||||
progressReader.ProgressBar.Add64(cpURLs.SourceContent.Size)
|
||||
}
|
||||
return cpURLs
|
||||
}
|
||||
|
||||
// doPrepareCopyURLs scans the source URL and prepares a list of objects for copying.
|
||||
func doPrepareCopyURLs(session *sessionV6, trapCh <-chan bool) {
|
||||
// Separate source and target. 'cp' can take only one target,
|
||||
// but any number of sources.
|
||||
sourceURLs := session.Header.CommandArgs[:len(session.Header.CommandArgs)-1]
|
||||
targetURL := session.Header.CommandArgs[len(session.Header.CommandArgs)-1] // Last one is target
|
||||
|
||||
var totalBytes int64
|
||||
var totalObjects int
|
||||
|
||||
// Access recursive flag inside the session header.
|
||||
isRecursive := session.Header.CommandBoolFlags["recursive"]
|
||||
|
||||
// Create a session data file to store the processed URLs.
|
||||
dataFP := session.NewDataWriter()
|
||||
|
||||
var scanBar scanBarFunc
|
||||
if !globalQuiet && !globalJSON { // set up progress bar
|
||||
scanBar = scanBarFactory()
|
||||
}
|
||||
|
||||
URLsCh := prepareCopyURLs(sourceURLs, targetURL, isRecursive)
|
||||
done := false
|
||||
|
||||
for done == false {
|
||||
select {
|
||||
case cpURLs, ok := <-URLsCh:
|
||||
if !ok { // Done with URL preparation
|
||||
done = true
|
||||
break
|
||||
}
|
||||
if cpURLs.Error != nil {
|
||||
// Print in new line and adjust to top so that we don't print over the ongoing scan bar
|
||||
if !globalQuiet && !globalJSON {
|
||||
console.Eraseline()
|
||||
}
|
||||
if strings.Contains(cpURLs.Error.ToGoError().Error(), " is a folder.") {
|
||||
errorIf(cpURLs.Error.Trace(), "Folder cannot be copied. Please use ‘...’ suffix.")
|
||||
} else {
|
||||
errorIf(cpURLs.Error.Trace(), "Unable to prepare URL for copying.")
|
||||
}
|
||||
break
|
||||
}
|
||||
|
||||
jsonData, e := json.Marshal(cpURLs)
|
||||
if e != nil {
|
||||
session.Delete()
|
||||
fatalIf(probe.NewError(e), "Unable to prepare URL for copying. Error in JSON marshaling.")
|
||||
}
|
||||
fmt.Fprintln(dataFP, string(jsonData))
|
||||
if !globalQuiet && !globalJSON {
|
||||
scanBar(cpURLs.SourceContent.URL.String())
|
||||
}
|
||||
|
||||
totalBytes += cpURLs.SourceContent.Size
|
||||
totalObjects++
|
||||
case <-trapCh:
|
||||
// Print in new line and adjust to top so that we don't print over the ongoing scan bar
|
||||
if !globalQuiet && !globalJSON {
|
||||
console.Eraseline()
|
||||
}
|
||||
session.Delete() // If we are interrupted during the URL scanning, we drop the session.
|
||||
os.Exit(0)
|
||||
}
|
||||
}
|
||||
session.Header.TotalBytes = totalBytes
|
||||
session.Header.TotalObjects = totalObjects
|
||||
session.Save()
|
||||
}
|
||||
|
||||
func doCopySession(session *sessionV6) {
|
||||
trapCh := signalTrap(os.Interrupt, syscall.SIGTERM)
|
||||
|
||||
if !session.HasData() {
|
||||
doPrepareCopyURLs(session, trapCh)
|
||||
}
|
||||
|
||||
// Enable accounting reader by default.
|
||||
accntReader := newAccounter(session.Header.TotalBytes)
|
||||
|
||||
// Prepare URL scanner from session data file.
|
||||
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)
|
||||
|
||||
// Enable progress bar reader only during default mode.
|
||||
var progressReader *progressBar
|
||||
if !globalQuiet && !globalJSON { // set up progress bar
|
||||
progressReader = newProgressBar(session.Header.TotalBytes)
|
||||
}
|
||||
|
||||
// Wait on status of doCopy() operation.
|
||||
var statusCh = make(chan copyURLs)
|
||||
|
||||
// Add a wait group.
|
||||
var wg = new(sync.WaitGroup)
|
||||
wg.Add(1)
|
||||
|
||||
// Go routine to monitor signal traps if any.
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for {
|
||||
select {
|
||||
case <-trapCh:
|
||||
// Receive interrupt notification.
|
||||
if !globalQuiet && !globalJSON {
|
||||
console.Eraseline()
|
||||
}
|
||||
session.CloseAndDie()
|
||||
case cpURLs, ok := <-statusCh:
|
||||
// Status channel is closed, we should return.
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if cpURLs.Error == nil {
|
||||
session.Header.LastCopied = cpURLs.SourceContent.URL.String()
|
||||
session.Save()
|
||||
} else {
|
||||
// Print in new line and adjust to top so that we
|
||||
// don't print over the ongoing progress bar.
|
||||
if !globalQuiet && !globalJSON {
|
||||
console.Eraseline()
|
||||
}
|
||||
errorIf(cpURLs.Error.Trace(cpURLs.SourceContent.URL.String()),
|
||||
fmt.Sprintf("Failed to copy ‘%s’.", cpURLs.SourceContent.URL.String()))
|
||||
// For all non critical errors we can continue for the
|
||||
// remaining files.
|
||||
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:
|
||||
continue
|
||||
}
|
||||
// For critical errors we should exit. Session
|
||||
// can be resumed after the user figures out
|
||||
// the problem.
|
||||
session.CloseAndDie()
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
// Loop through all urls.
|
||||
for urlScanner.Scan() {
|
||||
var cpURLs copyURLs
|
||||
// Unmarshal copyURLs from each line.
|
||||
json.Unmarshal([]byte(urlScanner.Text()), &cpURLs)
|
||||
|
||||
// Verify if previously copied, notify progress bar.
|
||||
if isCopied(cpURLs.SourceContent.URL.String()) {
|
||||
statusCh <- doCopyFake(cpURLs, progressReader)
|
||||
} else {
|
||||
statusCh <- doCopy(cpURLs, progressReader, accntReader)
|
||||
}
|
||||
}
|
||||
|
||||
// Close the goroutine.
|
||||
close(statusCh)
|
||||
|
||||
// Wait for the goroutines to finish.
|
||||
wg.Wait()
|
||||
|
||||
if !globalQuiet && !globalJSON {
|
||||
if progressReader.ProgressBar.Total > 0 {
|
||||
progressReader.ProgressBar.Finish()
|
||||
}
|
||||
} else {
|
||||
accntStat := accntReader.Stat()
|
||||
cpStatMessage := copyStatMessage{
|
||||
Total: accntStat.Total,
|
||||
Transferred: accntStat.Transferred,
|
||||
Speed: accntStat.Speed,
|
||||
}
|
||||
console.Println(console.Colorize("Copy", cpStatMessage.String()))
|
||||
}
|
||||
}
|
||||
|
||||
// mainCopy is the entry point for cp command.
|
||||
func mainCopy(ctx *cli.Context) {
|
||||
// Set global flags from context.
|
||||
setGlobalsFromContext(ctx)
|
||||
|
||||
// check 'copy' cli arguments.
|
||||
checkCopySyntax(ctx)
|
||||
|
||||
// Additional command speific theme customization.
|
||||
console.SetColor("Copy", color.New(color.FgGreen, color.Bold))
|
||||
|
||||
session := newSessionV6()
|
||||
session.Header.CommandType = "cp"
|
||||
session.Header.CommandBoolFlags["recursive"] = ctx.Bool("recursive")
|
||||
|
||||
var e error
|
||||
if session.Header.RootPath, e = os.Getwd(); e != nil {
|
||||
session.Delete()
|
||||
fatalIf(probe.NewError(e), "Unable to get current working folder.")
|
||||
}
|
||||
|
||||
// extract URLs.
|
||||
session.Header.CommandArgs = ctx.Args()
|
||||
doCopySession(session)
|
||||
session.Delete()
|
||||
}
|
||||
@@ -1,145 +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 (
|
||||
"fmt"
|
||||
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/client"
|
||||
)
|
||||
|
||||
func checkCopySyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) < 2 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "cp", 1) // last argument is exit code.
|
||||
}
|
||||
|
||||
// extract URLs.
|
||||
URLs := ctx.Args()
|
||||
if len(URLs) < 2 {
|
||||
fatalIf(errDummy().Trace(ctx.Args()...), fmt.Sprintf("Unable to parse source and target arguments."))
|
||||
}
|
||||
|
||||
srcURLs := URLs[:len(URLs)-1]
|
||||
tgtURL := URLs[len(URLs)-1]
|
||||
isRecursive := ctx.Bool("recursive")
|
||||
|
||||
/****** Generic Invalid Rules *******/
|
||||
// Check if bucket name is passed for URL type arguments.
|
||||
url := client.NewURL(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))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Guess CopyURLsType based on source and target URLs.
|
||||
copyURLsType, err := guessCopyURLType(srcURLs, tgtURL, isRecursive)
|
||||
if err != nil {
|
||||
fatalIf(errInvalidArgument().Trace(), "Unable to guess the type of copy operation.")
|
||||
}
|
||||
switch copyURLsType {
|
||||
case copyURLsTypeA: // File -> File.
|
||||
checkCopySyntaxTypeA(srcURLs, tgtURL)
|
||||
case copyURLsTypeB: // File -> Folder.
|
||||
checkCopySyntaxTypeB(srcURLs, tgtURL)
|
||||
case copyURLsTypeC: // Folder... -> Folder.
|
||||
checkCopySyntaxTypeC(srcURLs, tgtURL, isRecursive)
|
||||
case copyURLsTypeD: // File1...FileN -> Folder.
|
||||
checkCopySyntaxTypeD(srcURLs, tgtURL)
|
||||
default:
|
||||
fatalIf(errInvalidArgument().Trace(), "Unable to guess the type of copy operation.")
|
||||
}
|
||||
}
|
||||
|
||||
// checkCopySyntaxTypeA verifies if the source and target are valid file arguments.
|
||||
func checkCopySyntaxTypeA(srcURLs []string, tgtURL string) {
|
||||
// Check source.
|
||||
if len(srcURLs) != 1 {
|
||||
fatalIf(errInvalidArgument().Trace(), "Invalid number of source arguments.")
|
||||
}
|
||||
srcURL := srcURLs[0]
|
||||
_, srcContent, err := url2Stat(srcURL)
|
||||
fatalIf(err.Trace(srcURL), "Unable to stat source ‘"+srcURL+"’.")
|
||||
|
||||
if !srcContent.Type.IsRegular() {
|
||||
fatalIf(errInvalidArgument().Trace(), "Source ‘"+srcURL+"’ is not a file.")
|
||||
}
|
||||
}
|
||||
|
||||
// checkCopySyntaxTypeB verifies if the source is a valid file and target is a valid folder.
|
||||
func checkCopySyntaxTypeB(srcURLs []string, tgtURL string) {
|
||||
// Check source.
|
||||
if len(srcURLs) != 1 {
|
||||
fatalIf(errInvalidArgument().Trace(), "Invalid number of source arguments.")
|
||||
}
|
||||
srcURL := srcURLs[0]
|
||||
_, srcContent, err := url2Stat(srcURL)
|
||||
fatalIf(err.Trace(srcURL), "Unable to stat source ‘"+srcURL+"’.")
|
||||
|
||||
if !srcContent.Type.IsRegular() {
|
||||
fatalIf(errInvalidArgument().Trace(srcURL), "Source ‘"+srcURL+"’ is not a file.")
|
||||
}
|
||||
|
||||
// Check target.
|
||||
if _, tgtContent, err := url2Stat(tgtURL); err == nil {
|
||||
if !tgtContent.Type.IsDir() {
|
||||
fatalIf(errInvalidArgument().Trace(tgtURL), "Target ‘"+tgtURL+"’ is not a folder.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// checkCopySyntaxTypeC verifies if the source is a valid recursive dir and target is a valid folder.
|
||||
func checkCopySyntaxTypeC(srcURLs []string, tgtURL string, isRecursive bool) {
|
||||
// Check source.
|
||||
if len(srcURLs) != 1 {
|
||||
fatalIf(errInvalidArgument().Trace(), "Invalid number of source arguments.")
|
||||
}
|
||||
|
||||
srcURL := srcURLs[0]
|
||||
_, 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) {
|
||||
fatalIf(err.Trace(srcURL), "Unable to stat source ‘"+srcURL+"’.")
|
||||
}
|
||||
|
||||
if srcContent.Type.IsDir() && !isRecursive {
|
||||
fatalIf(errInvalidArgument().Trace(srcURL), "To copy a folder requires --recursive option.")
|
||||
}
|
||||
|
||||
// Check target.
|
||||
if _, tgtContent, err := url2Stat(tgtURL); err == nil {
|
||||
if !tgtContent.Type.IsDir() {
|
||||
fatalIf(errInvalidArgument().Trace(tgtURL), "Target ‘"+tgtURL+"’ is not a folder.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// checkCopySyntaxTypeD verifies if the source is a valid list of files and target is a valid folder.
|
||||
func checkCopySyntaxTypeD(srcURLs []string, tgtURL string) {
|
||||
// Source can be anything: file, dir, dir...
|
||||
// Check target if it is a dir
|
||||
if _, tgtContent, err := url2Stat(tgtURL); err == nil {
|
||||
if !tgtContent.Type.IsDir() {
|
||||
fatalIf(errInvalidArgument().Trace(tgtURL), "Target ‘"+tgtURL+"’ is not a folder.")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,253 +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 (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/minio/mc/pkg/client"
|
||||
"github.com/minio/minio-xl/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).
|
||||
//
|
||||
// * VALID RULES
|
||||
// =======================
|
||||
// A: copy(f, f) -> copy(f, f)
|
||||
// B: copy(f, d) -> copy(f, d/f) -> []A
|
||||
// C: copy(d1..., d2) -> []copy(f, d2/d1/f) -> []A
|
||||
// D: copy([]f, d) -> []B
|
||||
|
||||
// * INVALID RULES
|
||||
// =========================
|
||||
// copy(d, f)
|
||||
// copy(d..., f)
|
||||
// copy([](f|d)..., f)
|
||||
|
||||
const (
|
||||
copyURLsTypeInvalid copyURLsType = iota
|
||||
copyURLsTypeA
|
||||
copyURLsTypeB
|
||||
copyURLsTypeC
|
||||
copyURLsTypeD
|
||||
)
|
||||
|
||||
// guessCopyURLType guesses the type of URL. This approach all allows prepareURL
|
||||
// functions to accurately report failure causes.
|
||||
func guessCopyURLType(sourceURLs []string, targetURL string, isRecursive bool) (copyURLsType, *probe.Error) {
|
||||
if len(sourceURLs) == 1 { // 1 Source, 1 Target
|
||||
sourceURL := sourceURLs[0]
|
||||
_, sourceContent, err := url2Stat(sourceURL)
|
||||
if err != nil {
|
||||
return copyURLsTypeInvalid, err
|
||||
}
|
||||
|
||||
// If recursion is ON, it is type C.
|
||||
// If source is a folder, it is Type C.
|
||||
if sourceContent.Type.IsDir() || isRecursive {
|
||||
return copyURLsTypeC, nil
|
||||
}
|
||||
|
||||
// If target is a folder, it is Type B.
|
||||
if isTargetURLDir(targetURL) {
|
||||
return copyURLsTypeB, nil
|
||||
}
|
||||
// else Type A.
|
||||
return copyURLsTypeA, nil
|
||||
}
|
||||
|
||||
// Multiple source args and target is a folder. It is Type D.
|
||||
if isTargetURLDir(targetURL) {
|
||||
return copyURLsTypeD, nil
|
||||
}
|
||||
|
||||
return copyURLsTypeInvalid, errInvalidArgument().Trace()
|
||||
}
|
||||
|
||||
// SINGLE SOURCE - Type A: copy(f, f) -> copy(f, f)
|
||||
// prepareCopyURLsTypeA - prepares target and source URLs for copying.
|
||||
func prepareCopyURLsTypeA(sourceURL string, targetURL string) copyURLs {
|
||||
// Extract alias before fiddling with the URL.
|
||||
sourceAlias, _, _ := mustExpandAlias(sourceURL)
|
||||
// Find alias and expanded URL.
|
||||
targetAlias, targetURL, _ := mustExpandAlias(targetURL)
|
||||
|
||||
_, sourceContent, err := url2Stat(sourceURL)
|
||||
if err != nil {
|
||||
// Source does not exist or insufficient privileges.
|
||||
return copyURLs{Error: err.Trace(sourceURL)}
|
||||
}
|
||||
if !sourceContent.Type.IsRegular() {
|
||||
// Source is not a regular file
|
||||
return copyURLs{Error: errInvalidSource(sourceURL).Trace(sourceURL)}
|
||||
}
|
||||
if sourceContent.URL.String() == targetURL {
|
||||
// source and target can not be same
|
||||
return copyURLs{Error: errSourceTargetSame(sourceURL).Trace(sourceURL)}
|
||||
}
|
||||
|
||||
// All OK.. We can proceed. Type A
|
||||
return makeCopyContentTypeA(sourceAlias, sourceContent, targetAlias, targetURL)
|
||||
}
|
||||
|
||||
// prepareCopyContentTypeA - makes CopyURLs content for copying.
|
||||
func makeCopyContentTypeA(sourceAlias string, sourceContent *client.Content, targetAlias string, targetURL string) copyURLs {
|
||||
return copyURLs{
|
||||
SourceAlias: sourceAlias,
|
||||
SourceContent: sourceContent,
|
||||
TargetAlias: targetAlias,
|
||||
TargetContent: &client.Content{URL: *client.NewURL(targetURL)},
|
||||
}
|
||||
}
|
||||
|
||||
// SINGLE SOURCE - Type B: copy(f, d) -> copy(f, d/f) -> A
|
||||
// prepareCopyURLsTypeB - prepares target and source URLs for copying.
|
||||
func prepareCopyURLsTypeB(sourceURL string, targetURL string) copyURLs {
|
||||
// Extract alias before fiddling with the URL.
|
||||
sourceAlias, _, _ := mustExpandAlias(sourceURL)
|
||||
// Find alias and expanded URL.
|
||||
targetAlias, targetURL, _ := mustExpandAlias(targetURL)
|
||||
|
||||
_, sourceContent, err := url2Stat(sourceURL)
|
||||
if err != nil {
|
||||
// Source does not exist or insufficient privileges.
|
||||
return copyURLs{Error: err.Trace(sourceURL)}
|
||||
}
|
||||
|
||||
if !sourceContent.Type.IsRegular() {
|
||||
if sourceContent.Type.IsDir() {
|
||||
return copyURLs{Error: errSourceIsDir(sourceURL).Trace(sourceURL)}
|
||||
}
|
||||
// Source is not a regular file.
|
||||
return copyURLs{Error: errInvalidSource(sourceURL).Trace(sourceURL)}
|
||||
}
|
||||
|
||||
// All OK.. We can proceed. Type B: source is a file, target is a folder and exists.
|
||||
return makeCopyContentTypeB(sourceAlias, sourceContent, targetAlias, targetURL)
|
||||
}
|
||||
|
||||
// makeCopyContentTypeB - CopyURLs content for copying.
|
||||
func makeCopyContentTypeB(sourceAlias string, sourceContent *client.Content, targetAlias string, targetURL string) copyURLs {
|
||||
// All OK.. We can proceed. Type B: source is a file, target is a folder and exists.
|
||||
targetURLParse := client.NewURL(targetURL)
|
||||
targetURLParse.Path = filepath.ToSlash(filepath.Join(targetURLParse.Path, filepath.Base(sourceContent.URL.Path)))
|
||||
return makeCopyContentTypeA(sourceAlias, sourceContent, targetAlias, targetURLParse.String())
|
||||
}
|
||||
|
||||
// SINGLE SOURCE - Type C: copy(d1..., d2) -> []copy(d1/f, d1/d2/f) -> []A
|
||||
// prepareCopyRecursiveURLTypeC - prepares target and source URLs for copying.
|
||||
func prepareCopyURLsTypeC(sourceURL, targetURL string, isRecursive bool) <-chan copyURLs {
|
||||
// Extract alias before fiddling with the URL.
|
||||
sourceAlias, _, _ := mustExpandAlias(sourceURL)
|
||||
// Find alias and expanded URL.
|
||||
targetAlias, targetURL, _ := mustExpandAlias(targetURL)
|
||||
|
||||
copyURLsCh := make(chan copyURLs)
|
||||
go func(sourceURL, targetURL string, copyURLsCh chan copyURLs) {
|
||||
defer close(copyURLsCh)
|
||||
sourceClient, err := newClient(sourceURL)
|
||||
if err != nil {
|
||||
// Source initialization failed.
|
||||
copyURLsCh <- copyURLs{Error: err.Trace(sourceURL)}
|
||||
return
|
||||
}
|
||||
|
||||
for sourceContent := range sourceClient.List(isRecursive, false) {
|
||||
if sourceContent.Err != nil {
|
||||
// Listing failed.
|
||||
copyURLsCh <- copyURLs{Error: sourceContent.Err.Trace(sourceClient.GetURL().String())}
|
||||
continue
|
||||
}
|
||||
|
||||
if !sourceContent.Type.IsRegular() {
|
||||
// Source is not a regular file. Skip it for copy.
|
||||
continue
|
||||
}
|
||||
|
||||
// All OK.. We can proceed. Type B: source is a file, target is a folder and exists.
|
||||
copyURLsCh <- makeCopyContentTypeC(sourceAlias, sourceClient.GetURL(), sourceContent, targetAlias, targetURL)
|
||||
}
|
||||
}(sourceURL, targetURL, copyURLsCh)
|
||||
return copyURLsCh
|
||||
}
|
||||
|
||||
// makeCopyContentTypeC - CopyURLs content for copying.
|
||||
func makeCopyContentTypeC(sourceAlias string, sourceURL client.URL, sourceContent *client.Content, targetAlias string, targetURL string) copyURLs {
|
||||
newSourceURL := sourceContent.URL
|
||||
pathSeparatorIndex := strings.LastIndex(sourceURL.Path, string(sourceURL.Separator))
|
||||
newSourceSuffix := filepath.ToSlash(newSourceURL.Path)
|
||||
if pathSeparatorIndex > 1 {
|
||||
sourcePrefix := filepath.ToSlash(sourceURL.Path[:pathSeparatorIndex])
|
||||
newSourceSuffix = strings.TrimPrefix(newSourceSuffix, sourcePrefix)
|
||||
}
|
||||
newTargetURL := urlJoinPath(targetURL, newSourceSuffix)
|
||||
return makeCopyContentTypeA(sourceAlias, sourceContent, targetAlias, newTargetURL)
|
||||
}
|
||||
|
||||
// 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) {
|
||||
defer close(copyURLsCh)
|
||||
for _, sourceURL := range sourceURLs {
|
||||
for cpURLs := range prepareCopyURLsTypeC(sourceURL, targetURL, isRecursive) {
|
||||
copyURLsCh <- cpURLs
|
||||
}
|
||||
}
|
||||
}(sourceURLs, targetURL, copyURLsCh)
|
||||
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) {
|
||||
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)
|
||||
case copyURLsTypeB:
|
||||
copyURLsCh <- prepareCopyURLsTypeB(sourceURLs[0], targetURL)
|
||||
case copyURLsTypeC:
|
||||
for cURLs := range prepareCopyURLsTypeC(sourceURLs[0], targetURL, isRecursive) {
|
||||
copyURLsCh <- cURLs
|
||||
}
|
||||
case copyURLsTypeD:
|
||||
for cURLs := range prepareCopyURLsTypeD(sourceURLs, targetURL, isRecursive) {
|
||||
copyURLsCh <- cURLs
|
||||
}
|
||||
default:
|
||||
copyURLsCh <- copyURLs{Error: errInvalidArgument().Trace(sourceURLs...)}
|
||||
}
|
||||
}(sourceURLs, targetURL, copyURLsCh)
|
||||
|
||||
return copyURLsCh
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
/*
|
||||
* Minio Client (C) 2014-2016 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"math"
|
||||
)
|
||||
|
||||
// Returns the minimum value of a slice of integers
|
||||
func minimum(integers []int) (minVal int) {
|
||||
minVal = math.MaxInt32
|
||||
for _, v := range integers {
|
||||
if v < minVal {
|
||||
minVal = v
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// DamerauLevenshteinDistance calculates distance between two strings using an algorithm
|
||||
// described in https://en.wikipedia.org/wiki/Damerau-Levenshtein_distance
|
||||
func DamerauLevenshteinDistance(a string, b string) int {
|
||||
d := make([][]int, len(a)+1)
|
||||
for i := 1; i <= len(a)+1; i++ {
|
||||
d[i-1] = make([]int, len(b)+1)
|
||||
}
|
||||
for i := 0; i <= len(a); i++ {
|
||||
d[i][0] = i
|
||||
}
|
||||
for j := 0; j <= len(b); j++ {
|
||||
d[0][j] = j
|
||||
}
|
||||
for i := 1; i <= len(a); i++ {
|
||||
for j := 1; j <= len(b); j++ {
|
||||
cost := 0
|
||||
if a[i-1] == b[j-1] {
|
||||
cost = 0
|
||||
} else {
|
||||
cost = 1
|
||||
}
|
||||
d[i][j] = minimum([]int{
|
||||
d[i-1][j] + 1,
|
||||
d[i][j-1] + 1,
|
||||
d[i-1][j-1] + cost,
|
||||
})
|
||||
if i > 1 && j > 1 && a[i-1] == b[j-2] && a[i-2] == b[j-1] {
|
||||
d[i][j] = minimum([]int{d[i][j], d[i-2][j-2] + cost}) // transposition
|
||||
}
|
||||
}
|
||||
}
|
||||
return d[len(a)][len(b)]
|
||||
}
|
||||
-223
@@ -1,223 +0,0 @@
|
||||
/*
|
||||
* Minio Client (C) 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/client"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
)
|
||||
|
||||
// diff specific flags.
|
||||
var (
|
||||
diffFlags = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "help, h",
|
||||
Usage: "Help of diff.",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
// Compute differences between two files or folders.
|
||||
var diffCmd = cli.Command{
|
||||
Name: "diff",
|
||||
Usage: "Compute differences between two folders.",
|
||||
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,
|
||||
Flags: append(diffFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
mc {{.Name}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
mc {{.Name}} [FLAGS] FIRST SECOND
|
||||
|
||||
FLAGS:
|
||||
{{range .Flags}}{{.}}
|
||||
{{end}}
|
||||
DESCRIPTION:
|
||||
{{.Description}}
|
||||
|
||||
EXAMPLES:
|
||||
1. Compare a local folder with a folder on Amazon S3 cloud storage.
|
||||
$ mc {{.Name}} ~/Photos s3/MyBucket/Photos
|
||||
|
||||
2. Compare two different folders on a local filesystem.
|
||||
$ mc {{.Name}} ~/Photos /Media/Backup/Photos
|
||||
`,
|
||||
}
|
||||
|
||||
// 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"`
|
||||
}
|
||||
|
||||
// String colorized diff message
|
||||
func (d diffMessage) String() string {
|
||||
msg := ""
|
||||
switch d.Diff {
|
||||
case "only-in-first":
|
||||
msg = console.Colorize("DiffMessage",
|
||||
"‘"+d.FirstURL+"’"+" and "+"‘"+d.SecondURL+"’") + console.Colorize("DiffOnlyInFirst", " - only in first.")
|
||||
case "type":
|
||||
msg = console.Colorize("DiffMessage",
|
||||
"‘"+d.FirstURL+"’"+" and "+"‘"+d.SecondURL+"’") + console.Colorize("DiffType", " - differ in type.")
|
||||
case "size":
|
||||
msg = console.Colorize("DiffMessage",
|
||||
"‘"+d.FirstURL+"’"+" and "+"‘"+d.SecondURL+"’") + console.Colorize("DiffSize", " - differ in size.")
|
||||
default:
|
||||
fatalIf(errDummy().Trace(d.FirstURL, d.SecondURL),
|
||||
"Unhandled difference between ‘"+d.FirstURL+"’ and ‘"+d.SecondURL+"’.")
|
||||
}
|
||||
return msg
|
||||
|
||||
}
|
||||
|
||||
// JSON jsonified diff message
|
||||
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+"’.")
|
||||
return string(diffJSONBytes)
|
||||
}
|
||||
|
||||
func checkDiffSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) != 2 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "diff", 1) // last argument is exit code
|
||||
}
|
||||
for _, arg := range ctx.Args() {
|
||||
if strings.TrimSpace(arg) == "" {
|
||||
fatalIf(errInvalidArgument().Trace(ctx.Args()...), "Unable to validate empty argument.")
|
||||
}
|
||||
}
|
||||
URLs := ctx.Args()
|
||||
firstURL := URLs[0]
|
||||
secondURL := URLs[1]
|
||||
|
||||
// Diff only works between two directories, verify them below.
|
||||
|
||||
// Verify if firstURL is accessible.
|
||||
_, firstContent, err := url2Stat(firstURL)
|
||||
if err != nil {
|
||||
fatalIf(err.Trace(firstURL), fmt.Sprintf("Unable to stat '%s'.", firstURL))
|
||||
}
|
||||
// Verify if its a directory.
|
||||
if !firstContent.Type.IsDir() {
|
||||
fatalIf(errInvalidArgument().Trace(firstURL), fmt.Sprintf("‘%s’ is not a folder.", firstURL))
|
||||
}
|
||||
|
||||
// Verify if secondURL is accessible.
|
||||
_, secondContent, err := url2Stat(secondURL)
|
||||
if err != nil {
|
||||
fatalIf(err.Trace(secondURL), fmt.Sprintf("Unable to stat '%s'.", secondURL))
|
||||
}
|
||||
// Verify if its a directory.
|
||||
if !secondContent.Type.IsDir() {
|
||||
fatalIf(errInvalidArgument().Trace(secondURL), fmt.Sprintf("‘%s’ is not a folder.", secondURL))
|
||||
}
|
||||
}
|
||||
|
||||
// doDiffMain runs the diff.
|
||||
func doDiffMain(firstURL, secondURL string) {
|
||||
// Source and targets are always directories
|
||||
sourceSeparator := string(client.NewURL(firstURL).Separator)
|
||||
if !strings.HasSuffix(firstURL, sourceSeparator) {
|
||||
firstURL = firstURL + sourceSeparator
|
||||
}
|
||||
targetSeparator := string(client.NewURL(secondURL).Separator)
|
||||
if !strings.HasSuffix(secondURL, targetSeparator) {
|
||||
secondURL = secondURL + targetSeparator
|
||||
}
|
||||
|
||||
// Expand aliased urls.
|
||||
firstAlias, firstURL, _ := mustExpandAlias(firstURL)
|
||||
secondAlias, secondURL, _ := mustExpandAlias(secondURL)
|
||||
|
||||
firstClient, err := newClientFromAlias(firstAlias, firstURL)
|
||||
if err != nil {
|
||||
fatalIf(err.Trace(firstAlias, firstURL, secondAlias, secondURL),
|
||||
fmt.Sprintf("Failed to diff '%s' and '%s'", firstURL, secondURL))
|
||||
}
|
||||
difference, err := objectDifferenceFactory(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,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// mainDiff main for 'diff'.
|
||||
func mainDiff(ctx *cli.Context) {
|
||||
// Set global flags from context.
|
||||
setGlobalsFromContext(ctx)
|
||||
|
||||
// check 'diff' cli arguments.
|
||||
checkDiffSyntax(ctx)
|
||||
|
||||
// Additional command specific theme customization.
|
||||
console.SetColor("DiffMessage", color.New(color.FgGreen, color.Bold))
|
||||
console.SetColor("DiffOnlyInFirst", color.New(color.FgRed, color.Bold))
|
||||
console.SetColor("DiffType", color.New(color.FgYellow, color.Bold))
|
||||
console.SetColor("DiffSize", color.New(color.FgMagenta, color.Bold))
|
||||
|
||||
URLs := ctx.Args()
|
||||
firstURL := URLs[0]
|
||||
secondURL := URLs[1]
|
||||
|
||||
doDiffMain(firstURL, secondURL)
|
||||
}
|
||||
@@ -1,89 +0,0 @@
|
||||
/*
|
||||
* Minio Client (C) 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
|
||||
"github.com/minio/mc/pkg/client"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
)
|
||||
|
||||
// objectDifference function finds the difference between object on source and target
|
||||
// it takes suffix string, type and size on the source
|
||||
// objectDifferenceFactory returns objectDifference function
|
||||
type objectDifference func(string, os.FileMode, int64) (string, *probe.Error)
|
||||
|
||||
const (
|
||||
differSize string = "size" // differs in size
|
||||
differOnlyFirst string = "only-in-first" // only on source
|
||||
differType string = "type" // differs in type, ex file/directory
|
||||
differNone string = "" // does not differ
|
||||
)
|
||||
|
||||
// objectDifferenceFactory returns objectDifference function to check for difference
|
||||
// between sourceURL and targetURL
|
||||
// for usage reference check diff and mirror commands
|
||||
func objectDifferenceFactory(targetAlias, targetURL string) (objectDifference, *probe.Error) {
|
||||
clnt, err := newClientFromAlias(targetAlias, targetURL)
|
||||
if err != nil {
|
||||
return nil, err.Trace(targetAlias, targetURL)
|
||||
}
|
||||
isIncomplete := false
|
||||
isRecursive := true
|
||||
ch := clnt.List(isRecursive, isIncomplete)
|
||||
current := targetURL
|
||||
reachedEOF := false
|
||||
ok := false
|
||||
var content *client.Content
|
||||
|
||||
difference := func(suffix string, srcType os.FileMode, srcSize int64) (string, *probe.Error) {
|
||||
if reachedEOF {
|
||||
// would mean the suffix is not on target
|
||||
return differOnlyFirst, nil
|
||||
}
|
||||
expected := urlJoinPath(targetURL, suffix)
|
||||
for {
|
||||
if expected < current {
|
||||
return differOnlyFirst, nil // not available in the target
|
||||
}
|
||||
if expected == current {
|
||||
tgtType := content.Type
|
||||
tgtSize := content.Size
|
||||
if srcType.IsRegular() && !tgtType.IsRegular() {
|
||||
// Type differes. Source is never a directory
|
||||
return differType, nil
|
||||
}
|
||||
if (srcType.IsRegular() && tgtType.IsRegular()) && srcSize != tgtSize {
|
||||
// regular files differing in size
|
||||
return differSize, nil
|
||||
}
|
||||
return differNone, nil // available in the target
|
||||
}
|
||||
content, ok = <-ch
|
||||
if !ok {
|
||||
reachedEOF = true
|
||||
return differOnlyFirst, nil
|
||||
}
|
||||
if content.Err != nil {
|
||||
return "", content.Err.Trace()
|
||||
}
|
||||
current = content.URL.String()
|
||||
}
|
||||
}
|
||||
return difference, nil
|
||||
}
|
||||
@@ -1,115 +0,0 @@
|
||||
/*
|
||||
* Minio Client (C) 2014, 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
)
|
||||
|
||||
// causeMessage container for golang error messages
|
||||
type causeMessage struct {
|
||||
Message string `json:"message"`
|
||||
Error error `json:"error"`
|
||||
}
|
||||
|
||||
// errorMessage container for error messages
|
||||
type errorMessage struct {
|
||||
Message string `json:"message"`
|
||||
Cause causeMessage `json:"cause"`
|
||||
Type string `json:"type"`
|
||||
CallTrace []probe.TracePoint `json:"trace,omitempty"`
|
||||
SysInfo map[string]string `json:"sysinfo"`
|
||||
}
|
||||
|
||||
// fatalIf wrapper function which takes error and selectively prints stack frames if available on debug
|
||||
func fatalIf(err *probe.Error, msg string) {
|
||||
if err == nil {
|
||||
return
|
||||
}
|
||||
if globalJSON {
|
||||
errorMsg := errorMessage{
|
||||
Message: msg,
|
||||
Type: "fatal",
|
||||
Cause: causeMessage{
|
||||
Message: err.ToGoError().Error(),
|
||||
Error: err.ToGoError(),
|
||||
},
|
||||
SysInfo: err.SysInfo,
|
||||
}
|
||||
if globalDebug {
|
||||
errorMsg.CallTrace = err.CallTrace
|
||||
}
|
||||
json, e := json.Marshal(struct {
|
||||
Status string `json:"status"`
|
||||
Error errorMessage `json:"error"`
|
||||
}{
|
||||
Status: "error",
|
||||
Error: errorMsg,
|
||||
})
|
||||
if e != nil {
|
||||
console.Fatalln(probe.NewError(e))
|
||||
}
|
||||
console.Println(string(json))
|
||||
console.Fatalln()
|
||||
}
|
||||
if !globalDebug {
|
||||
console.Fatalln(fmt.Sprintf("%s %s", msg, err.ToGoError()))
|
||||
}
|
||||
console.Fatalln(fmt.Sprintf("%s %s", msg, err))
|
||||
}
|
||||
|
||||
// errorIf synonymous with fatalIf but doesn't exit on error != nil
|
||||
func errorIf(err *probe.Error, msg string) {
|
||||
if err == nil {
|
||||
return
|
||||
}
|
||||
if globalJSON {
|
||||
errorMsg := errorMessage{
|
||||
Message: msg,
|
||||
Type: "error",
|
||||
Cause: causeMessage{
|
||||
Message: err.ToGoError().Error(),
|
||||
Error: err.ToGoError(),
|
||||
},
|
||||
SysInfo: err.SysInfo,
|
||||
}
|
||||
if globalDebug {
|
||||
errorMsg.CallTrace = err.CallTrace
|
||||
}
|
||||
json, e := json.Marshal(struct {
|
||||
Status string `json:"status"`
|
||||
Error errorMessage `json:"error"`
|
||||
}{
|
||||
Status: "error",
|
||||
Error: errorMsg,
|
||||
})
|
||||
if e != nil {
|
||||
console.Fatalln(probe.NewError(e))
|
||||
}
|
||||
console.Println(string(json))
|
||||
return
|
||||
}
|
||||
if !globalDebug {
|
||||
console.Errorln(fmt.Sprintf("%s %s", msg, err.ToGoError()))
|
||||
return
|
||||
}
|
||||
console.Errorln(fmt.Sprintf("%s %s", msg, err))
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
/*
|
||||
* Minio Client (C) 2014, 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import "github.com/minio/cli"
|
||||
|
||||
// Collection of mc commands currently supported
|
||||
var commands = []cli.Command{}
|
||||
|
||||
// Collection of mc commands currently supported in a trie tree
|
||||
var commandsTree = newTrie()
|
||||
|
||||
// Collection of mc flags currently supported
|
||||
var globalFlags = []cli.Flag{
|
||||
cli.StringFlag{
|
||||
Name: "config-folder, C",
|
||||
Value: mustGetMcConfigDir(),
|
||||
Usage: "Path to configuration folder.",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "quiet, q",
|
||||
Usage: "Suppress chatty console output.",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "no-color",
|
||||
Usage: "Disable color theme.",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "json",
|
||||
Usage: "Enable json formatted output.",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "debug",
|
||||
Usage: "Enable debugging output.",
|
||||
},
|
||||
}
|
||||
|
||||
// registerCmd registers a cli command
|
||||
func registerCmd(cmd cli.Command) {
|
||||
commands = append(commands, cmd)
|
||||
commandsTree.Insert(cmd.Name)
|
||||
}
|
||||
-71
@@ -1,71 +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.
|
||||
*/
|
||||
|
||||
// This package contains all the global variables and constants. ONLY TO BE ACCESSED VIA GET/SET FUNCTIONS.
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
)
|
||||
|
||||
// mc configuration related constants.
|
||||
const (
|
||||
globalMCConfigVersion = "7"
|
||||
|
||||
globalMCConfigDir = ".mc/"
|
||||
globalMCConfigWindowsDir = "mc\\"
|
||||
globalMCConfigFile = "config.json"
|
||||
|
||||
// session config and shared urls related constants
|
||||
globalSessionDir = "session"
|
||||
globalSharedURLsDataDir = "share"
|
||||
)
|
||||
|
||||
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 // Debug flag set via command line
|
||||
// WHEN YOU ADD NEXT GLOBAL FLAG, MAKE SURE TO ALSO UPDATE SESSION CODE AND CODE BELOW.
|
||||
)
|
||||
|
||||
// Set global states. NOTE: It is deliberately kept monolithic to ensure we dont miss out any flags.
|
||||
func setGlobals(quiet, debug, json, noColor bool) {
|
||||
globalQuiet = quiet
|
||||
globalDebug = debug
|
||||
globalJSON = json
|
||||
globalNoColor = noColor
|
||||
|
||||
// Enable debug messages if requested.
|
||||
if globalDebug == true {
|
||||
console.DebugPrint = true
|
||||
}
|
||||
|
||||
// Disable colorified messages if requested.
|
||||
if globalNoColor == true {
|
||||
console.SetColorOff()
|
||||
}
|
||||
}
|
||||
|
||||
// Set global states. NOTE: It is deliberately kept monolithic to ensure we dont miss out any flags.
|
||||
func setGlobalsFromContext(ctx *cli.Context) {
|
||||
quiet := ctx.Bool("quiet") || ctx.GlobalBool("quiet")
|
||||
debug := ctx.Bool("debug") || ctx.GlobalBool("debug")
|
||||
json := ctx.Bool("json") || ctx.GlobalBool("json")
|
||||
noColor := ctx.Bool("no-color") || ctx.GlobalBool("no-color")
|
||||
setGlobals(quiet, debug, json, noColor)
|
||||
}
|
||||
-140
@@ -1,140 +0,0 @@
|
||||
/*
|
||||
* Minio Client (C) 2014, 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"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.",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
// list files and folders.
|
||||
var lsCmd = cli.Command{
|
||||
Name: "ls",
|
||||
Usage: "List files and folders.",
|
||||
Action: mainList,
|
||||
Flags: append(lsFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
mc {{.Name}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
mc {{.Name}} [FLAGS] TARGET [TARGET ...]
|
||||
|
||||
FLAGS:
|
||||
{{range .Flags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. List buckets on Amazon S3 cloud storage.
|
||||
$ mc {{.Name}} s3
|
||||
|
||||
2. List buckets and all its contents from Amazon S3 cloud storage recursively.
|
||||
$ mc {{.Name}} --recursive s3
|
||||
|
||||
3. List all contents of mybucket on Amazon S3 cloud storage.
|
||||
$ mc {{.Name}} s3/mybucket/
|
||||
|
||||
4. List all contents of mybucket on Amazon S3 cloud storage on Microsoft Windows.
|
||||
$ mc {{.Name}} s3\mybucket\
|
||||
|
||||
5. List files recursively on a local filesystem on Microsoft Windows.
|
||||
$ mc {{.Name}} --recursive C:\Users\Worf\
|
||||
|
||||
6. List incomplete (previously failed) uploads of objects on Amazon S3.
|
||||
$ mc {{.Name}} --incomplete s3/mybucket
|
||||
`,
|
||||
}
|
||||
|
||||
// checkListSyntax - validate all the passed arguments
|
||||
func checkListSyntax(ctx *cli.Context) {
|
||||
args := ctx.Args()
|
||||
if !ctx.Args().Present() {
|
||||
args = []string{"."}
|
||||
}
|
||||
for _, arg := range args {
|
||||
if strings.TrimSpace(arg) == "" {
|
||||
fatalIf(errInvalidArgument().Trace(args...), "Unable to validate empty argument.")
|
||||
}
|
||||
}
|
||||
// extract URLs.
|
||||
URLs := ctx.Args()
|
||||
isIncomplete := ctx.Bool("incomplete")
|
||||
|
||||
for _, url := range URLs {
|
||||
_, _, err := url2Stat(url)
|
||||
if err != nil && !isURLPrefixExists(url, isIncomplete) {
|
||||
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))
|
||||
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)
|
||||
|
||||
// Set command flags from context.
|
||||
isRecursive := ctx.Bool("recursive")
|
||||
isIncomplete := ctx.Bool("incomplete")
|
||||
|
||||
args := ctx.Args()
|
||||
// mimic operating system tool behavior.
|
||||
if !ctx.Args().Present() {
|
||||
args = []string{"."}
|
||||
}
|
||||
|
||||
for _, targetURL := range args {
|
||||
var clnt client.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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,146 +0,0 @@
|
||||
/*
|
||||
* Minio Client (C) 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"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"
|
||||
)
|
||||
|
||||
// printDate - human friendly formatted date.
|
||||
const (
|
||||
printDate = "2006-01-02 15:04:05 MST"
|
||||
)
|
||||
|
||||
// contentMessage container for content message structure.
|
||||
type contentMessage struct {
|
||||
Status string `json:"status"`
|
||||
Filetype string `json:"type"`
|
||||
Time time.Time `json:"lastModified"`
|
||||
Size int64 `json:"size"`
|
||||
Key string `json:"key"`
|
||||
}
|
||||
|
||||
// String colorized string message.
|
||||
func (c contentMessage) String() string {
|
||||
message := console.Colorize("Time", fmt.Sprintf("[%s] ", c.Time.Format(printDate)))
|
||||
message = message + console.Colorize("Size", fmt.Sprintf("%6s ", humanize.IBytes(uint64(c.Size))))
|
||||
message = func() string {
|
||||
if c.Filetype == "folder" {
|
||||
return message + console.Colorize("Dir", fmt.Sprintf("%s", c.Key))
|
||||
}
|
||||
return message + console.Colorize("File", fmt.Sprintf("%s", c.Key))
|
||||
}()
|
||||
return message
|
||||
}
|
||||
|
||||
// JSON jsonified content message.
|
||||
func (c contentMessage) JSON() string {
|
||||
c.Status = "success"
|
||||
jsonMessageBytes, e := json.Marshal(c)
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(jsonMessageBytes)
|
||||
}
|
||||
|
||||
// parseContent parse client Content container into printer struct.
|
||||
func parseContent(c *client.Content) contentMessage {
|
||||
content := contentMessage{}
|
||||
content.Time = c.Time.Local()
|
||||
|
||||
// guess file type.
|
||||
content.Filetype = func() string {
|
||||
if c.Type.IsDir() {
|
||||
return "folder"
|
||||
}
|
||||
return "file"
|
||||
}()
|
||||
|
||||
content.Size = c.Size
|
||||
// Convert OS Type to match console file printing style.
|
||||
content.Key = func() string {
|
||||
switch {
|
||||
// for windows make sure to print in 'windows' specific style.
|
||||
case runtime.GOOS == "windows":
|
||||
c.URL.Path = strings.Replace(c.URL.Path, "/", "\\", -1)
|
||||
c.URL.Path = strings.TrimSuffix(c.URL.Path, "\\")
|
||||
default:
|
||||
c.URL.Path = strings.TrimSuffix(c.URL.Path, "/")
|
||||
}
|
||||
if c.Type.IsDir() {
|
||||
switch {
|
||||
// for windows make sure to print in 'windows' specific style.
|
||||
case runtime.GOOS == "windows":
|
||||
return fmt.Sprintf("%s\\", c.URL.Path)
|
||||
default:
|
||||
return fmt.Sprintf("%s/", c.URL.Path)
|
||||
}
|
||||
}
|
||||
return c.URL.Path
|
||||
}()
|
||||
return content
|
||||
}
|
||||
|
||||
// doList - list all entities inside a folder.
|
||||
func doList(clnt client.Client, isRecursive, isIncomplete bool) *probe.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) {
|
||||
if content.Err != nil {
|
||||
switch content.Err.ToGoError().(type) {
|
||||
// handle this specifically for filesystem related errors.
|
||||
case client.BrokenSymlink:
|
||||
errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list broken link.")
|
||||
continue
|
||||
case client.TooManyLevelsSymlink:
|
||||
errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list too many levels link.")
|
||||
continue
|
||||
case client.PathNotFound:
|
||||
errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list folder.")
|
||||
continue
|
||||
case client.PathInsufficientPermission:
|
||||
errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list folder.")
|
||||
continue
|
||||
}
|
||||
errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list folder.")
|
||||
continue
|
||||
}
|
||||
// Convert any os specific delimiters to "/".
|
||||
contentURL := filepath.ToSlash(content.URL.Path)
|
||||
prefixPath = filepath.ToSlash(prefixPath)
|
||||
|
||||
// Trim prefix path from the content path.
|
||||
contentURL = strings.TrimPrefix(contentURL, prefixPath)
|
||||
content.URL.Path = contentURL
|
||||
parsedContent := parseContent(content)
|
||||
// Print colorized or jsonized content info.
|
||||
printMsg(parsedContent)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
-17
@@ -1,17 +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
|
||||
@@ -1,209 +0,0 @@
|
||||
/*
|
||||
* Minio Client (C) 2014, 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"runtime"
|
||||
"sort"
|
||||
"strconv"
|
||||
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/minio/pkg/contentdb"
|
||||
"github.com/minio/pb"
|
||||
"github.com/olekukonko/ts"
|
||||
)
|
||||
|
||||
var (
|
||||
// global flags for mc.
|
||||
mcFlags = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "help, h",
|
||||
Usage: "Show help.",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
// 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:
|
||||
` + mcVersion +
|
||||
`{{ "\n"}}{{range $key, $value := ExtraInfo}}
|
||||
{{$key}}:
|
||||
{{$value}}
|
||||
{{end}}`
|
||||
|
||||
// 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() {
|
||||
// Ensures config file is sane.
|
||||
_, err := loadMcConfig()
|
||||
fatalIf(err.Trace(mustGetMcConfigPath()), "Unable to access configuration file.")
|
||||
}
|
||||
|
||||
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.FormatBytes(int64(memstats.Alloc)),
|
||||
pb.FormatBytes(int64(memstats.TotalAlloc)),
|
||||
pb.FormatBytes(int64(memstats.HeapAlloc)),
|
||||
pb.FormatBytes(int64(memstats.HeapSys)))
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
func registerBefore(ctx *cli.Context) error {
|
||||
setMcConfigDir(ctx.GlobalString("config-folder"))
|
||||
|
||||
// Verify golang runtime.
|
||||
verifyMCRuntime()
|
||||
|
||||
// Migrate any old version of config / state files to newer format.
|
||||
migrate()
|
||||
|
||||
// Set global flags.
|
||||
setGlobalsFromContext(ctx)
|
||||
|
||||
// Checkconfig if it 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(accessCmd) // Set access permissions.
|
||||
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.Usage = "Minio Client for cloud storage and filesystems."
|
||||
app.Commands = commands
|
||||
app.Author = "Minio.io"
|
||||
app.Flags = append(mcFlags, globalFlags...)
|
||||
app.CustomAppHelpTemplate = mcHelpTemplate
|
||||
app.CommandNotFound = commandNotFound // handler function declared above.
|
||||
return app
|
||||
}
|
||||
|
||||
func main() {
|
||||
probe.Init() // Set project's root source path.
|
||||
probe.SetAppInfo("Release-Tag", mcReleaseTag)
|
||||
probe.SetAppInfo("Commit", mcShortCommitID)
|
||||
|
||||
contentdb.Init() // Load contentdb into memory.
|
||||
app := registerApp()
|
||||
app.Before = registerBefore
|
||||
|
||||
app.ExtraInfo = func() map[string]string {
|
||||
if _, e := ts.GetSize(); e != nil {
|
||||
globalQuiet = true
|
||||
}
|
||||
if globalDebug {
|
||||
return getSystemData()
|
||||
}
|
||||
return make(map[string]string)
|
||||
}
|
||||
|
||||
app.RunAndExitOnError()
|
||||
}
|
||||
-127
@@ -1,127 +0,0 @@
|
||||
/*
|
||||
* Minio Client (C) 2014, 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
)
|
||||
|
||||
var (
|
||||
mbFlags = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "help, h",
|
||||
Usage: "Help of mb.",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "region",
|
||||
Value: "us-east-1",
|
||||
Usage: "Specify bucket region. Defaults to ‘us-east-1’.",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
// make a bucket or folder.
|
||||
var mbCmd = cli.Command{
|
||||
Name: "mb",
|
||||
Usage: "Make a bucket or folder.",
|
||||
Action: mainMakeBucket,
|
||||
Flags: append(mbFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
mc {{.Name}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
mc {{.Name}} [FLAGS] TARGET [TARGET...]
|
||||
|
||||
FLAGS:
|
||||
{{range .Flags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Create a bucket on Amazon S3 cloud storage.
|
||||
$ mc {{.Name}} s3/mynewbucket
|
||||
|
||||
2. Create a new bucket on Google Cloud Storage.
|
||||
$ mc {{.Name}} gcs/miniocloud
|
||||
|
||||
4. Create a new bucket on Amazon S3 cloud storage in region ‘us-west-2’.
|
||||
$ mc {{.Name}} --region=us-west-2 s3/myregionbucket
|
||||
|
||||
5. Create a new directory including its missing parents (equivalent to ‘mkdir -p’).
|
||||
$ mc {{.Name}} /tmp/this/new/dir1
|
||||
`,
|
||||
}
|
||||
|
||||
// makeBucketMessage is container for make bucket success and failure messages.
|
||||
type makeBucketMessage struct {
|
||||
Status string `json:"status"`
|
||||
Bucket string `json:"bucket"`
|
||||
Region string `json:"region"`
|
||||
}
|
||||
|
||||
// String colorized make bucket message.
|
||||
func (s makeBucketMessage) String() string {
|
||||
return console.Colorize("MakeBucket", "Bucket created successfully ‘"+s.Bucket+"’.")
|
||||
}
|
||||
|
||||
// JSON jsonified make bucket message.
|
||||
func (s makeBucketMessage) JSON() string {
|
||||
makeBucketJSONBytes, e := json.Marshal(s)
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(makeBucketJSONBytes)
|
||||
}
|
||||
|
||||
// Validate command line arguments.
|
||||
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)
|
||||
|
||||
// check 'mb' cli arguments.
|
||||
checkMakeBucketSyntax(ctx)
|
||||
|
||||
// Additional command speific theme customization.
|
||||
console.SetColor("MakeBucket", color.New(color.FgGreen, color.Bold))
|
||||
|
||||
// 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+"’.")
|
||||
|
||||
// Make bucket.
|
||||
err = clnt.MakeBucket(region)
|
||||
fatalIf(err.Trace(targetURL), "Unable to make bucket ‘"+targetURL+"’.")
|
||||
|
||||
// Successfully created a bucket.
|
||||
printMsg(makeBucketMessage{Status: "success", Bucket: targetURL})
|
||||
}
|
||||
-132
@@ -1,132 +0,0 @@
|
||||
/*
|
||||
* Minio Client (C) 2014, 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"net/http/httptest"
|
||||
|
||||
"github.com/minio/cli"
|
||||
. "gopkg.in/check.v1"
|
||||
)
|
||||
|
||||
var customConfigDir string
|
||||
|
||||
func Test(t *testing.T) { TestingT(t) }
|
||||
|
||||
type TestSuite struct{}
|
||||
|
||||
var _ = Suite(&TestSuite{})
|
||||
|
||||
var server *httptest.Server
|
||||
var app *cli.App
|
||||
|
||||
func (s *TestSuite) SetUpSuite(c *C) {
|
||||
}
|
||||
|
||||
func (s *TestSuite) TearDownSuite(c *C) {
|
||||
}
|
||||
|
||||
func (s *TestSuite) TestValidPERMS(c *C) {
|
||||
perms := accessPerms("private")
|
||||
c.Assert(perms.isValidAccessPERM(), Equals, true)
|
||||
c.Assert(perms.String(), Equals, "private")
|
||||
perms = accessPerms("public")
|
||||
c.Assert(perms.isValidAccessPERM(), Equals, true)
|
||||
c.Assert(perms.String(), Equals, "public-read-write")
|
||||
perms = accessPerms("readonly")
|
||||
c.Assert(perms.isValidAccessPERM(), Equals, true)
|
||||
c.Assert(perms.String(), Equals, "public-read")
|
||||
perms = accessPerms("authorized")
|
||||
c.Assert(perms.isValidAccessPERM(), Equals, true)
|
||||
c.Assert(perms.String(), Equals, "authenticated-read")
|
||||
}
|
||||
|
||||
func (s *TestSuite) TestInvalidPERMS(c *C) {
|
||||
perms := accessPerms("invalid")
|
||||
c.Assert(perms.isValidAccessPERM(), Equals, false)
|
||||
}
|
||||
|
||||
func (s *TestSuite) TestGetMcConfigDir(c *C) {
|
||||
dir, err := getMcConfigDir()
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(dir, Not(Equals), "")
|
||||
c.Assert(mustGetMcConfigDir(), Equals, dir)
|
||||
}
|
||||
|
||||
func (s *TestSuite) TestGetMcConfigPath(c *C) {
|
||||
dir, err := getMcConfigPath()
|
||||
c.Assert(err, IsNil)
|
||||
switch runtime.GOOS {
|
||||
case "linux":
|
||||
fallthrough
|
||||
case "freebsd":
|
||||
fallthrough
|
||||
case "darwin":
|
||||
c.Assert(dir, Equals, filepath.Join(mustGetMcConfigDir(), "config.json"))
|
||||
case "windows":
|
||||
c.Assert(dir, Equals, filepath.Join(mustGetMcConfigDir(), "config.json"))
|
||||
default:
|
||||
c.Fail()
|
||||
}
|
||||
c.Assert(mustGetMcConfigPath(), Equals, dir)
|
||||
}
|
||||
|
||||
func (s *TestSuite) TestIsvalidAliasName(c *C) {
|
||||
c.Check(isValidAlias("helloWorld0"), Equals, true)
|
||||
c.Check(isValidAlias("h0SFD2k24Fdsa"), Equals, true)
|
||||
c.Check(isValidAlias("fdslka-4"), Equals, true)
|
||||
c.Check(isValidAlias("fdslka-"), Equals, true)
|
||||
c.Check(isValidAlias("helloWorld$"), Equals, false)
|
||||
c.Check(isValidAlias("h0SFD2k2#Fdsa"), Equals, false)
|
||||
c.Check(isValidAlias("0dslka-4"), Equals, false)
|
||||
c.Check(isValidAlias("-fdslka"), Equals, false)
|
||||
}
|
||||
|
||||
func (s *TestSuite) TestHumanizedTime(c *C) {
|
||||
hTime := timeDurationToHumanizedTime(time.Duration(10) * time.Second)
|
||||
c.Assert(hTime.Minutes, Equals, int64(0))
|
||||
c.Assert(hTime.Hours, Equals, int64(0))
|
||||
c.Assert(hTime.Days, Equals, int64(0))
|
||||
|
||||
hTime = timeDurationToHumanizedTime(time.Duration(10) * time.Minute)
|
||||
c.Assert(hTime.Hours, Equals, int64(0))
|
||||
c.Assert(hTime.Days, Equals, int64(0))
|
||||
|
||||
hTime = timeDurationToHumanizedTime(time.Duration(10) * time.Hour)
|
||||
c.Assert(hTime.Days, Equals, int64(0))
|
||||
|
||||
hTime = timeDurationToHumanizedTime(time.Duration(24) * time.Hour)
|
||||
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)
|
||||
}
|
||||
-384
@@ -1,384 +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 (
|
||||
"bufio"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"syscall"
|
||||
|
||||
"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"
|
||||
)
|
||||
|
||||
// mirror specific flags.
|
||||
var (
|
||||
mirrorFlags = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "help, h",
|
||||
Usage: "Help of mirror.",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "force",
|
||||
Usage: "Force overwrite of an existing target(s).",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
// Mirror folders recursively from a single source to many destinations
|
||||
var mirrorCmd = cli.Command{
|
||||
Name: "mirror",
|
||||
Usage: "Mirror folders recursively from a single source to single destination.",
|
||||
Action: mainMirror,
|
||||
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
|
||||
`,
|
||||
}
|
||||
|
||||
// mirrorMessage container for file mirror messages
|
||||
type mirrorMessage struct {
|
||||
Status string `json:"status"`
|
||||
Source string `json:"source"`
|
||||
Target string `json:"target"`
|
||||
}
|
||||
|
||||
// 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.FormatBytes(int64(c.Speed))
|
||||
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)
|
||||
return message
|
||||
}
|
||||
|
||||
// doMirror - Mirror an object to multiple destination. mirrorURLs status contains a copy of sURLs and error if any.
|
||||
func doMirror(sURLs mirrorURLs, progressReader *progressBar, accountingReader *accounter) mirrorURLs {
|
||||
if sURLs.Error != nil { // Errorneous sURLs passed.
|
||||
sURLs.Error = sURLs.Error.Trace()
|
||||
return sURLs
|
||||
}
|
||||
|
||||
sourceAlias := sURLs.SourceAlias
|
||||
sourceURL := sURLs.SourceContent.URL
|
||||
targetAlias := sURLs.TargetAlias
|
||||
targetURL := sURLs.TargetContent.URL
|
||||
length := sURLs.SourceContent.Size
|
||||
|
||||
if !globalQuiet && !globalJSON {
|
||||
progressReader = progressReader.SetCaption(sourceURL.String() + ": ")
|
||||
}
|
||||
|
||||
reader, err := getSourceStreamFromAlias(sourceAlias, sourceURL.String())
|
||||
if err != nil {
|
||||
sURLs.Error = err.Trace(sourceURL.String())
|
||||
return sURLs
|
||||
}
|
||||
|
||||
var progress io.Reader
|
||||
if globalQuiet || globalJSON {
|
||||
sourcePath := filepath.ToSlash(filepath.Join(sourceAlias, sourceURL.Path))
|
||||
targetPath := filepath.ToSlash(filepath.Join(targetAlias, targetURL.Path))
|
||||
printMsg(mirrorMessage{
|
||||
Source: sourcePath,
|
||||
Target: targetPath,
|
||||
})
|
||||
if globalQuiet || globalJSON {
|
||||
progress = accountingReader
|
||||
}
|
||||
} else {
|
||||
// Set up progress bar.
|
||||
progress = progressReader.ProgressBar
|
||||
}
|
||||
_, err = putTargetStreamFromAlias(targetAlias, targetURL.String(), reader, length, progress)
|
||||
if err != nil {
|
||||
sURLs.Error = err.Trace(targetURL.String())
|
||||
return sURLs
|
||||
}
|
||||
|
||||
sURLs.Error = nil // just for safety
|
||||
return sURLs
|
||||
}
|
||||
|
||||
// doMirrorFake - Perform a fake mirror to update the progress bar appropriately.
|
||||
func doMirrorFake(sURLs mirrorURLs, progressReader *progressBar) mirrorURLs {
|
||||
if !globalDebug && !globalJSON {
|
||||
progressReader.ProgressBar.Add64(sURLs.SourceContent.Size)
|
||||
}
|
||||
return sURLs
|
||||
}
|
||||
|
||||
// doPrepareMirrorURLs scans the source URL and prepares a list of objects for mirroring.
|
||||
func doPrepareMirrorURLs(session *sessionV6, isForce bool, trapCh <-chan bool) {
|
||||
sourceURL := session.Header.CommandArgs[0] // first one is source.
|
||||
targetURL := session.Header.CommandArgs[1]
|
||||
var totalBytes int64
|
||||
var totalObjects int
|
||||
|
||||
// Create a session data file to store the processed URLs.
|
||||
dataFP := session.NewDataWriter()
|
||||
|
||||
var scanBar scanBarFunc
|
||||
if !globalQuiet && !globalJSON { // set up progress bar
|
||||
scanBar = scanBarFactory()
|
||||
}
|
||||
|
||||
URLsCh := prepareMirrorURLs(sourceURL, targetURL, isForce)
|
||||
done := false
|
||||
for done == false {
|
||||
select {
|
||||
case sURLs, ok := <-URLsCh:
|
||||
if !ok { // Done with URL prepration
|
||||
done = true
|
||||
break
|
||||
}
|
||||
if sURLs.Error != nil {
|
||||
// Print in new line and adjust to top so that we don't print over the ongoing scan bar
|
||||
if !globalQuiet && !globalJSON {
|
||||
console.Eraseline()
|
||||
}
|
||||
errorIf(sURLs.Error.Trace(), "Unable to prepare URLs for mirroring.")
|
||||
break
|
||||
}
|
||||
if sURLs.isEmpty() {
|
||||
break
|
||||
}
|
||||
jsonData, e := json.Marshal(sURLs)
|
||||
if e != nil {
|
||||
session.Delete()
|
||||
fatalIf(probe.NewError(e), "Unable to marshal URLs into JSON.")
|
||||
}
|
||||
fmt.Fprintln(dataFP, string(jsonData))
|
||||
if !globalQuiet && !globalJSON {
|
||||
scanBar(sURLs.SourceContent.URL.String())
|
||||
}
|
||||
|
||||
totalBytes += sURLs.SourceContent.Size
|
||||
totalObjects++
|
||||
case <-trapCh:
|
||||
// Print in new line and adjust to top so that we don't print over the ongoing scan bar
|
||||
if !globalQuiet && !globalJSON {
|
||||
console.Eraseline()
|
||||
}
|
||||
session.Delete() // If we are interrupted during the URL scanning, we drop the session.
|
||||
os.Exit(0)
|
||||
}
|
||||
}
|
||||
session.Header.TotalBytes = totalBytes
|
||||
session.Header.TotalObjects = totalObjects
|
||||
session.Save()
|
||||
}
|
||||
|
||||
// Session'fied mirror command.
|
||||
func doMirrorSession(session *sessionV6) {
|
||||
isForce := session.Header.CommandBoolFlags["force"]
|
||||
trapCh := signalTrap(os.Interrupt, syscall.SIGTERM)
|
||||
|
||||
if !session.HasData() {
|
||||
doPrepareMirrorURLs(session, isForce, trapCh)
|
||||
}
|
||||
|
||||
// Enable accounting reader by default.
|
||||
accntReader := newAccounter(session.Header.TotalBytes)
|
||||
|
||||
// Set up progress bar.
|
||||
var progressReader *progressBar
|
||||
if !globalQuiet && !globalJSON {
|
||||
progressReader = newProgressBar(session.Header.TotalBytes)
|
||||
}
|
||||
|
||||
// Prepare URL scanner from session data file.
|
||||
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)
|
||||
|
||||
// Wait on status of doMirror() operation.
|
||||
var statusCh = make(chan mirrorURLs)
|
||||
|
||||
// Add a wait group for the below go-routine.
|
||||
var wg = new(sync.WaitGroup)
|
||||
wg.Add(1)
|
||||
|
||||
// Go routine to monitor signal traps if any.
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for {
|
||||
select {
|
||||
case <-trapCh:
|
||||
// Receive interrupt notification.
|
||||
if !globalQuiet && !globalJSON {
|
||||
console.Eraseline()
|
||||
}
|
||||
session.CloseAndDie()
|
||||
case sURLs, ok := <-statusCh:
|
||||
// Status channel is closed, we should return.
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if sURLs.Error == nil {
|
||||
session.Header.LastCopied = sURLs.SourceContent.URL.String()
|
||||
session.Save()
|
||||
} else {
|
||||
// Print in new line and adjust to top so that we
|
||||
// don't print over the ongoing progress bar.
|
||||
if !globalQuiet && !globalJSON {
|
||||
console.Eraseline()
|
||||
}
|
||||
errorIf(sURLs.Error.Trace(sURLs.SourceContent.URL.String()),
|
||||
fmt.Sprintf("Failed to copy ‘%s’.", sURLs.SourceContent.URL.String()))
|
||||
// For all non critical errors we can continue for the
|
||||
// remaining files.
|
||||
switch sURLs.Error.ToGoError().(type) {
|
||||
// Handle this specifically for filesystem related
|
||||
// errors.
|
||||
case client.BrokenSymlink:
|
||||
continue
|
||||
case client.TooManyLevelsSymlink:
|
||||
continue
|
||||
case client.PathNotFound:
|
||||
continue
|
||||
case client.PathInsufficientPermission:
|
||||
continue
|
||||
case client.ObjectAlreadyExists:
|
||||
continue
|
||||
case client.BucketDoesNotExist:
|
||||
continue
|
||||
}
|
||||
// For critical errors we should exit. Session
|
||||
// can be resumed after the user figures out
|
||||
// the problem.
|
||||
session.CloseAndDie()
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
// Loop through all urls.
|
||||
for urlScanner.Scan() {
|
||||
var sURLs mirrorURLs
|
||||
// Unmarshal copyURLs from each line.
|
||||
json.Unmarshal([]byte(urlScanner.Text()), &sURLs)
|
||||
// Verify if previously copied, notify progress bar.
|
||||
if isCopied(sURLs.SourceContent.URL.String()) {
|
||||
statusCh <- doMirrorFake(sURLs, progressReader)
|
||||
} else {
|
||||
statusCh <- doMirror(sURLs, progressReader, accntReader)
|
||||
}
|
||||
}
|
||||
|
||||
// Close the goroutine.
|
||||
close(statusCh)
|
||||
|
||||
// Wait for the goroutines to finish.
|
||||
wg.Wait()
|
||||
|
||||
if !globalQuiet && !globalJSON {
|
||||
if progressReader.ProgressBar.Total > 0 {
|
||||
progressReader.ProgressBar.Finish()
|
||||
}
|
||||
} else {
|
||||
accntStat := accntReader.Stat()
|
||||
mrStatMessage := mirrorStatMessage{
|
||||
Total: accntStat.Total,
|
||||
Transferred: accntStat.Transferred,
|
||||
Speed: accntStat.Speed,
|
||||
}
|
||||
console.Println(console.Colorize("Mirror", mrStatMessage.String()))
|
||||
}
|
||||
}
|
||||
|
||||
// Main entry point for mirror command.
|
||||
func mainMirror(ctx *cli.Context) {
|
||||
// Set global flags from context.
|
||||
setGlobalsFromContext(ctx)
|
||||
|
||||
// check 'mirror' cli arguments.
|
||||
checkMirrorSyntax(ctx)
|
||||
|
||||
// Additional command speific theme customization.
|
||||
console.SetColor("Mirror", color.New(color.FgGreen, color.Bold))
|
||||
|
||||
var e error
|
||||
session := newSessionV6()
|
||||
session.Header.CommandType = "mirror"
|
||||
session.Header.RootPath, e = os.Getwd()
|
||||
if e != nil {
|
||||
session.Delete()
|
||||
fatalIf(probe.NewError(e), "Unable to get current working folder.")
|
||||
}
|
||||
|
||||
// Set command flags from context.
|
||||
isForce := ctx.Bool("force")
|
||||
session.Header.CommandBoolFlags["force"] = isForce
|
||||
|
||||
// extract URLs.
|
||||
session.Header.CommandArgs = ctx.Args()
|
||||
doMirrorSession(session)
|
||||
session.Delete()
|
||||
}
|
||||
-168
@@ -1,168 +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 (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/client"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
)
|
||||
|
||||
type mirrorURLs struct {
|
||||
SourceAlias string
|
||||
SourceContent *client.Content
|
||||
TargetAlias string
|
||||
TargetContent *client.Content
|
||||
Error *probe.Error `json:"-"`
|
||||
}
|
||||
|
||||
func (m mirrorURLs) isEmpty() bool {
|
||||
if m.SourceContent == nil && m.TargetContent == nil && m.Error == nil {
|
||||
return true
|
||||
}
|
||||
if m.SourceContent.Size == 0 && m.TargetContent == nil && m.Error == nil {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
//
|
||||
// * 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 *******/
|
||||
_, 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) {
|
||||
fatalIf(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 := client.NewURL(tgtURL)
|
||||
if url.Host != "" {
|
||||
if !isURLVirtualHostStyle(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 client.PathNotFound - destination directory need not exist.
|
||||
if _, ok := err.ToGoError().(client.PathNotFound); !ok {
|
||||
fatalIf(err.Trace(tgtURL), fmt.Sprintf("Unable to stat %s", tgtURL))
|
||||
}
|
||||
}
|
||||
|
||||
func deltaSourceTargets(sourceURL string, targetURL string, isForce bool, mirrorURLsCh chan<- mirrorURLs) {
|
||||
// source and targets are always directories
|
||||
sourceSeparator := string(client.NewURL(sourceURL).Separator)
|
||||
if !strings.HasSuffix(sourceURL, sourceSeparator) {
|
||||
sourceURL = sourceURL + sourceSeparator
|
||||
}
|
||||
targetSeparator := string(client.NewURL(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(mirrorURLsCh)
|
||||
|
||||
objectDifferenceTarget, err := objectDifferenceFactory(targetAlias, targetURL)
|
||||
if err != nil {
|
||||
mirrorURLsCh <- mirrorURLs{Error: err.Trace(targetAlias, targetURL)}
|
||||
return
|
||||
}
|
||||
|
||||
sourceClient, err := newClientFromAlias(sourceAlias, sourceURL)
|
||||
if err != nil {
|
||||
mirrorURLsCh <- mirrorURLs{Error: err.Trace(sourceAlias, sourceURL)}
|
||||
return
|
||||
}
|
||||
|
||||
for sourceContent := range sourceClient.List(true, false) {
|
||||
if sourceContent.Err != nil {
|
||||
mirrorURLsCh <- mirrorURLs{
|
||||
Error: sourceContent.Err.Trace(sourceClient.GetURL().String()),
|
||||
}
|
||||
continue
|
||||
}
|
||||
if sourceContent.Type.IsDir() {
|
||||
continue
|
||||
}
|
||||
suffix := strings.TrimPrefix(sourceContent.URL.String(), sourceURL)
|
||||
differ, err := objectDifferenceTarget(suffix, sourceContent.Type, sourceContent.Size)
|
||||
if err != nil {
|
||||
mirrorURLsCh <- mirrorURLs{Error: err.Trace(sourceContent.URL.String())}
|
||||
continue
|
||||
}
|
||||
if differ == differNone {
|
||||
// no difference, continue
|
||||
continue
|
||||
}
|
||||
if differ == differType {
|
||||
mirrorURLsCh <- mirrorURLs{Error: errInvalidTarget(suffix)}
|
||||
continue
|
||||
}
|
||||
if differ == differSize && !isForce {
|
||||
// size differs and force not set
|
||||
mirrorURLsCh <- mirrorURLs{Error: errOverWriteNotAllowed(sourceContent.URL.String())}
|
||||
continue
|
||||
}
|
||||
// either available only in source or size differs and force is set
|
||||
targetPath := urlJoinPath(targetURL, suffix)
|
||||
targetContent := &client.Content{URL: *client.NewURL(targetPath)}
|
||||
mirrorURLsCh <- mirrorURLs{
|
||||
SourceAlias: sourceAlias,
|
||||
SourceContent: sourceContent,
|
||||
TargetAlias: targetAlias,
|
||||
TargetContent: targetContent,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func prepareMirrorURLs(sourceURL string, targetURL string, isForce bool) <-chan mirrorURLs {
|
||||
mirrorURLsCh := make(chan mirrorURLs)
|
||||
go deltaSourceTargets(sourceURL, targetURL, isForce, mirrorURLsCh)
|
||||
return mirrorURLsCh
|
||||
}
|
||||
-87
@@ -1,87 +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 (
|
||||
"fmt"
|
||||
"math"
|
||||
"runtime"
|
||||
"strings"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/olekukonko/ts"
|
||||
)
|
||||
|
||||
// colorizeUpdateMessage - inspired from Yeoman project npm package https://github.com/yeoman/update-notifier.
|
||||
func colorizeUpdateMessage(updateString string) (string, *probe.Error) {
|
||||
// initialize coloring
|
||||
cyan := color.New(color.FgCyan, color.Bold).SprintFunc()
|
||||
yellow := color.New(color.FgYellow, color.Bold).SprintfFunc()
|
||||
|
||||
// calculate length without color coding, due to ANSI color characters padded to actual
|
||||
// string the final length is wrong than the original string length.
|
||||
line1Str := fmt.Sprintf(" New update available, please execute the following command to update: ")
|
||||
line2Str := fmt.Sprintf(" %s ", updateString)
|
||||
line1Length := len(line1Str)
|
||||
line2Length := len(line2Str)
|
||||
|
||||
// populate lines with color coding.
|
||||
line1InColor := line1Str
|
||||
line2InColor := fmt.Sprintf(" %s ", cyan(updateString))
|
||||
|
||||
// calculate the rectangular box size.
|
||||
maxContentWidth := int(math.Max(float64(line1Length), float64(line2Length)))
|
||||
line1Rest := maxContentWidth - line1Length
|
||||
line2Rest := maxContentWidth - line2Length
|
||||
|
||||
// Fetch terminal size to calculate optimal box size.
|
||||
terminal, e := ts.GetSize()
|
||||
if e != nil {
|
||||
return "", probe.NewError(e)
|
||||
}
|
||||
|
||||
var message string
|
||||
switch {
|
||||
case len(line2Str) > terminal.Col():
|
||||
message = "\n" + line1InColor + "\n" + line2InColor + "\n"
|
||||
default:
|
||||
// on windows terminal turn off unicode characters.
|
||||
var top, bottom, sideBar string
|
||||
if runtime.GOOS == "windows" {
|
||||
top = yellow("*" + strings.Repeat("*", maxContentWidth) + "*")
|
||||
bottom = yellow("*" + strings.Repeat("*", maxContentWidth) + "*")
|
||||
sideBar = yellow("|")
|
||||
} else {
|
||||
// color the rectangular box, use unicode characters here.
|
||||
top = yellow("┏" + strings.Repeat("━", maxContentWidth) + "┓")
|
||||
bottom = yellow("┗" + strings.Repeat("━", maxContentWidth) + "┛")
|
||||
sideBar = yellow("┃")
|
||||
}
|
||||
// fill spaces to the rest of the area.
|
||||
spacePaddingLine1 := strings.Repeat(" ", line1Rest)
|
||||
spacePaddingLine2 := strings.Repeat(" ", line2Rest)
|
||||
|
||||
// construct the final message.
|
||||
message = "\n" + top + "\n" +
|
||||
sideBar + line1InColor + spacePaddingLine1 + sideBar + "\n" +
|
||||
sideBar + line2InColor + spacePaddingLine2 + sideBar + "\n" +
|
||||
bottom + "\n"
|
||||
}
|
||||
// return the final message
|
||||
return message, nil
|
||||
}
|
||||
-111
@@ -1,111 +0,0 @@
|
||||
/*
|
||||
* Minio Client, (C) 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"syscall"
|
||||
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
)
|
||||
|
||||
var (
|
||||
pipeFlags = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "help, h",
|
||||
Usage: "Help of pipe.",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
// 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.",
|
||||
Action: mainPipe,
|
||||
Flags: append(pipeFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
mc {{.Name}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
mc {{.Name}} [FLAGS] [TARGET]
|
||||
|
||||
FLAGS:
|
||||
{{range .Flags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Write contents of stdin to a file on local filesystem.
|
||||
$ mc {{.Name}} /tmp/hello-world.go
|
||||
|
||||
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.
|
||||
$ cat debian-8.2.iso | mc {{.Name}} s3/ferenginar/gnuos.iso
|
||||
|
||||
4. Stream MySQL database dump to Amazon S3 directly.
|
||||
$ mysqldump -u root -p ******* accountsdb | mc {{.Name}} s3/ferenginar/backups/accountsdb-oct-9-2015.sql
|
||||
`,
|
||||
}
|
||||
|
||||
func pipe(targetURL string) *probe.Error {
|
||||
if targetURL == "" {
|
||||
// When no target is specified, pipe cat's stdin to stdout.
|
||||
return catOut(os.Stdin).Trace()
|
||||
}
|
||||
|
||||
// Stream from stdin to multiple objects until EOF.
|
||||
// Ignore size, since os.Stat() would not return proper size all the time
|
||||
// for local filesystem for example /proc files.
|
||||
_, err := putTargetStream(targetURL, os.Stdin, -1)
|
||||
// TODO: See if this check is necessary.
|
||||
switch e := err.ToGoError().(type) {
|
||||
case *os.PathError:
|
||||
if e.Err == syscall.EPIPE {
|
||||
// stdin closed by the user. Gracefully exit.
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return err.Trace(targetURL)
|
||||
}
|
||||
|
||||
// check pipe input arguments.
|
||||
func checkPipeSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) > 1 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "pipe", 1) // last argument is exit code.
|
||||
}
|
||||
}
|
||||
|
||||
// mainPipe is the main entry point for pipe command.
|
||||
func mainPipe(ctx *cli.Context) {
|
||||
// Set global flags from context.
|
||||
setGlobalsFromContext(ctx)
|
||||
|
||||
// validate pipe input arguments.
|
||||
checkPipeSyntax(ctx)
|
||||
|
||||
if len(ctx.Args()) == 0 {
|
||||
err := pipe("")
|
||||
fatalIf(err.Trace("stdout"), "Unable to write to one or more targets.")
|
||||
} else {
|
||||
// extract URLs.
|
||||
URLs := ctx.Args()
|
||||
err := pipe(URLs[0])
|
||||
fatalIf(err.Trace(URLs[0]), "Unable to write to one or more targets.")
|
||||
}
|
||||
}
|
||||
@@ -1,72 +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 client
|
||||
|
||||
import (
|
||||
"io"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
)
|
||||
|
||||
// Client - client interface
|
||||
type Client interface {
|
||||
// Common operations
|
||||
Stat() (content *Content, err *probe.Error)
|
||||
List(recursive, incomplete bool) <-chan *Content
|
||||
|
||||
// Bucket operations
|
||||
MakeBucket(region string) *probe.Error
|
||||
GetBucketAccess() (access string, error *probe.Error)
|
||||
SetBucketAccess(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)
|
||||
|
||||
// I/O operations with expiration
|
||||
ShareDownload(expires time.Duration) (string, *probe.Error)
|
||||
ShareUpload(bool, time.Duration, string) (map[string]string, *probe.Error)
|
||||
|
||||
// Delete operations
|
||||
Remove(incomplete bool) *probe.Error
|
||||
|
||||
// GetURL returns back internal url
|
||||
GetURL() URL
|
||||
}
|
||||
|
||||
// Content container for content metadata
|
||||
type Content struct {
|
||||
URL URL
|
||||
Time time.Time
|
||||
Size int64
|
||||
Type os.FileMode
|
||||
Err *probe.Error
|
||||
}
|
||||
|
||||
// Config - see http://docs.amazonwebservices.com/AmazonS3/latest/dev/index.html?RESTAuthentication.html
|
||||
type Config struct {
|
||||
AccessKey string
|
||||
SecretKey string
|
||||
Signature string
|
||||
HostURL string
|
||||
AppName string
|
||||
AppVersion string
|
||||
AppComments []string
|
||||
Debug bool
|
||||
}
|
||||
@@ -1,69 +0,0 @@
|
||||
/*
|
||||
* Minio Client (C) 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package client
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
. "gopkg.in/check.v1"
|
||||
)
|
||||
|
||||
func Test(t *testing.T) { TestingT(t) }
|
||||
|
||||
type MySuite struct{}
|
||||
|
||||
var _ = Suite(&MySuite{})
|
||||
|
||||
func (s *MySuite) TestURLParse(c *C) {
|
||||
u := NewURL("http://s3.example.com")
|
||||
c.Assert(u.Scheme, Equals, "http")
|
||||
c.Assert(u.Host, Equals, "s3.example.com")
|
||||
c.Assert(u.Path, Equals, "/")
|
||||
c.Assert(u.SchemeSeparator, Equals, "://")
|
||||
|
||||
u = NewURL("http://s3.example.com/path/new")
|
||||
c.Assert(u.Scheme, Equals, "http")
|
||||
c.Assert(u.Host, Equals, "s3.example.com")
|
||||
c.Assert(u.Path, Equals, "/path/new")
|
||||
c.Assert(u.SchemeSeparator, Equals, "://")
|
||||
|
||||
u = NewURL(":::://s3.example.com/path/new")
|
||||
c.Assert(u.Scheme, Equals, "")
|
||||
c.Assert(u.Host, Equals, "")
|
||||
c.Assert(u.Path, Equals, ":::://s3.example.com/path/new")
|
||||
c.Assert(u.SchemeSeparator, Equals, "")
|
||||
|
||||
u = NewURL("localhost:9000")
|
||||
c.Assert(u.Scheme, Equals, "")
|
||||
c.Assert(u.Host, Equals, "")
|
||||
c.Assert(u.Path, Equals, "localhost:9000")
|
||||
c.Assert(u.SchemeSeparator, Equals, "")
|
||||
}
|
||||
|
||||
func (s *MySuite) TestPathParse(c *C) {
|
||||
u := NewURL("path/test")
|
||||
c.Assert(u.Scheme, Equals, "")
|
||||
c.Assert(u.Host, Equals, "")
|
||||
c.Assert(u.Path, Equals, "path/test")
|
||||
c.Assert(u.SchemeSeparator, Equals, "")
|
||||
|
||||
u = NewURL("/path/test")
|
||||
c.Assert(u.Scheme, Equals, "")
|
||||
c.Assert(u.Host, Equals, "")
|
||||
c.Assert(u.Path, Equals, "/path/test")
|
||||
c.Assert(u.SchemeSeparator, Equals, "")
|
||||
}
|
||||
@@ -1,189 +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 client
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
/// Collection of standard errors
|
||||
|
||||
// APINotImplemented - api not implemented
|
||||
type APINotImplemented struct {
|
||||
API string
|
||||
APIType string
|
||||
}
|
||||
|
||||
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) + "’."
|
||||
}
|
||||
|
||||
// GenericBucketError - generic bucket operations error
|
||||
type GenericBucketError struct {
|
||||
Bucket string
|
||||
}
|
||||
|
||||
// BucketDoesNotExist - bucket does not exist.
|
||||
type BucketDoesNotExist GenericBucketError
|
||||
|
||||
func (e BucketDoesNotExist) Error() string {
|
||||
return "Bucket ‘" + e.Bucket + "’ does not exist."
|
||||
}
|
||||
|
||||
// BucketExists - bucket exists.
|
||||
type BucketExists GenericBucketError
|
||||
|
||||
func (e BucketExists) Error() string {
|
||||
return "Bucket ‘" + e.Bucket + "’ exists."
|
||||
}
|
||||
|
||||
// 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{}
|
||||
|
||||
func (e BucketNameEmpty) Error() string {
|
||||
return "Bucket name cannot be empty."
|
||||
}
|
||||
|
||||
// GenericObjectError - generic object operations error
|
||||
type GenericObjectError struct {
|
||||
Bucket string
|
||||
Object string
|
||||
}
|
||||
|
||||
// ObjectAlreadyExists - typed return for MethodNotAllowed
|
||||
type ObjectAlreadyExists struct {
|
||||
Object string
|
||||
}
|
||||
|
||||
func (e ObjectAlreadyExists) Error() string {
|
||||
return "Object ‘" + e.Object + "’ already exists."
|
||||
}
|
||||
|
||||
// InvalidObjectName - object requested is invalid
|
||||
type InvalidObjectName GenericObjectError
|
||||
|
||||
func (e InvalidObjectName) Error() string {
|
||||
return "Object ‘" + e.Object + "’ at ‘" + e.Bucket + "’ is invalid."
|
||||
}
|
||||
|
||||
// BucketNameTopLevel - generic error
|
||||
type BucketNameTopLevel struct{}
|
||||
|
||||
func (e BucketNameTopLevel) Error() string {
|
||||
return "Buckets can only be created at the top level."
|
||||
}
|
||||
|
||||
// GenericFileError - generic file error.
|
||||
type GenericFileError struct {
|
||||
Path string
|
||||
}
|
||||
|
||||
// PathNotFound (ENOENT) - file not found.
|
||||
type PathNotFound GenericFileError
|
||||
|
||||
func (e PathNotFound) Error() string {
|
||||
return "Requested file ‘" + e.Path + "’ not found"
|
||||
}
|
||||
|
||||
// PathIsNotRegular (ENOTREG) - file is not a regular file.
|
||||
type PathIsNotRegular GenericFileError
|
||||
|
||||
func (e PathIsNotRegular) Error() string {
|
||||
return "Requested file ‘" + e.Path + "’ is not a regular file."
|
||||
}
|
||||
|
||||
// PathInsufficientPermission (EPERM) - permission denied.
|
||||
type PathInsufficientPermission GenericFileError
|
||||
|
||||
func (e PathInsufficientPermission) Error() string {
|
||||
return "Insufficient permissions to access this file ‘" + e.Path + "’"
|
||||
}
|
||||
|
||||
// BrokenSymlink (ENOTENT) - file has broken symlink.
|
||||
type BrokenSymlink GenericFileError
|
||||
|
||||
func (e BrokenSymlink) Error() string {
|
||||
return "Requested file ‘" + e.Path + "’ has broken symlink"
|
||||
}
|
||||
|
||||
// TooManyLevelsSymlink (ELOOP) - file has too many levels of symlinks.
|
||||
type TooManyLevelsSymlink GenericFileError
|
||||
|
||||
func (e TooManyLevelsSymlink) Error() string {
|
||||
return "Requested file ‘" + e.Path + "’ has too many levels of symlinks"
|
||||
}
|
||||
|
||||
// EmptyPath (EINVAL) - invalid argument.
|
||||
type EmptyPath struct{}
|
||||
|
||||
func (e EmptyPath) Error() string {
|
||||
return "Invalid path, path cannot be empty"
|
||||
}
|
||||
|
||||
// ObjectMissing (EINVAL) - object key missing.
|
||||
type ObjectMissing struct{}
|
||||
|
||||
func (e ObjectMissing) Error() string {
|
||||
return "Object key is missing, object key cannot be empty"
|
||||
}
|
||||
|
||||
// UnexpectedShortWrite - write wrote less bytes than expected.
|
||||
type UnexpectedShortWrite struct {
|
||||
InputSize int
|
||||
WriteSize int
|
||||
}
|
||||
|
||||
func (e UnexpectedShortWrite) Error() string {
|
||||
msg := fmt.Sprintf("Wrote less data than requested. Expected ‘%d’ bytes, but only wrote ‘%d’ bytes.", e.InputSize, e.WriteSize)
|
||||
return msg
|
||||
}
|
||||
|
||||
// UnexpectedEOF (EPIPE) - reader closed prematurely.
|
||||
type UnexpectedEOF struct {
|
||||
TotalSize int64
|
||||
TotalWritten int64
|
||||
}
|
||||
|
||||
func (e UnexpectedEOF) Error() string {
|
||||
msg := fmt.Sprintf("Input reader closed pre-maturely. Expected ‘%d’ bytes, but only received ‘%d’ bytes.", e.TotalSize, e.TotalWritten)
|
||||
return msg
|
||||
}
|
||||
|
||||
// UnexpectedExcessRead - reader wrote more data than requested.
|
||||
type UnexpectedExcessRead UnexpectedEOF
|
||||
|
||||
func (e UnexpectedExcessRead) Error() string {
|
||||
msg := fmt.Sprintf("Received excess data on input reader. Expected only ‘%d’ bytes, but received ‘%d’ bytes.", e.TotalSize, e.TotalWritten)
|
||||
return msg
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
*#
|
||||
@@ -1,86 +0,0 @@
|
||||
/*
|
||||
* 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 fs
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
|
||||
"github.com/minio/mc/pkg/client"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
)
|
||||
|
||||
// toClientError error constructs a typed client error for known filesystem errors.
|
||||
func (f *fsClient) toClientError(e error, fpath string) *probe.Error {
|
||||
if os.IsPermission(e) {
|
||||
return probe.NewError(client.PathInsufficientPermission{Path: fpath})
|
||||
}
|
||||
if os.IsNotExist(e) {
|
||||
return probe.NewError(client.PathNotFound{Path: fpath})
|
||||
}
|
||||
return probe.NewError(e)
|
||||
}
|
||||
|
||||
// handle windows symlinks - eg: junction files.
|
||||
func (f *fsClient) handleWindowsSymlinks(fpath string) (os.FileInfo, *probe.Error) {
|
||||
// On windows there are directory symlinks which are called junction files.
|
||||
// These files carry special meaning on windows they cannot be,
|
||||
// accessed with regular operations.
|
||||
file, e := os.Lstat(fpath)
|
||||
if e != nil {
|
||||
err := f.toClientError(e, fpath)
|
||||
return nil, err.Trace(fpath)
|
||||
}
|
||||
return file, nil
|
||||
}
|
||||
|
||||
// fsStat - wrapper function to get file stat.
|
||||
func (f *fsClient) fsStat() (os.FileInfo, *probe.Error) {
|
||||
fpath := f.PathURL.Path
|
||||
// Golang strips trailing / if you clean(..) or
|
||||
// EvalSymlinks(..). Adding '.' prevents it from doing so.
|
||||
if strings.HasSuffix(fpath, string(f.PathURL.Separator)) {
|
||||
fpath = fpath + "."
|
||||
}
|
||||
fpath, e := filepath.EvalSymlinks(fpath)
|
||||
if e != nil {
|
||||
if os.IsPermission(e) {
|
||||
if runtime.GOOS == "windows" {
|
||||
return f.handleWindowsSymlinks(f.PathURL.Path)
|
||||
}
|
||||
return nil, probe.NewError(client.PathInsufficientPermission{Path: f.PathURL.Path})
|
||||
}
|
||||
err := f.toClientError(e, f.PathURL.Path)
|
||||
return nil, err.Trace(fpath)
|
||||
}
|
||||
st, e := os.Stat(fpath)
|
||||
if e != nil {
|
||||
if os.IsPermission(e) {
|
||||
if runtime.GOOS == "windows" {
|
||||
return f.handleWindowsSymlinks(fpath)
|
||||
}
|
||||
return nil, probe.NewError(client.PathInsufficientPermission{Path: f.PathURL.Path})
|
||||
}
|
||||
if os.IsNotExist(e) {
|
||||
return nil, probe.NewError(client.PathNotFound{Path: f.PathURL.Path})
|
||||
}
|
||||
return nil, probe.NewError(e)
|
||||
}
|
||||
return st, nil
|
||||
}
|
||||
@@ -1,168 +0,0 @@
|
||||
/*
|
||||
* 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 fs
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
)
|
||||
|
||||
// byDirName implements sort.Interface.
|
||||
type byDirName []os.FileInfo
|
||||
|
||||
func (f byDirName) Len() int { return len(f) }
|
||||
func (f byDirName) Less(i, j int) bool {
|
||||
// For directory add an ending separator fortrue lexical order.
|
||||
if f[i].Mode().IsDir() {
|
||||
return f[i].Name()+string(filepath.Separator) < f[j].Name()
|
||||
}
|
||||
// For directory add an ending separator for true lexical order.
|
||||
if f[j].Mode().IsDir() {
|
||||
return f[i].Name() < f[j].Name()+string(filepath.Separator)
|
||||
}
|
||||
return f[i].Name() < f[j].Name()
|
||||
}
|
||||
func (f byDirName) Swap(i, j int) { f[i], f[j] = f[j], f[i] }
|
||||
|
||||
// readDir reads the directory named by dirname and returns
|
||||
// a list of sorted directory entries.
|
||||
func readDir(dirname string) ([]os.FileInfo, error) {
|
||||
f, e := os.Open(dirname)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
list, e := f.Readdir(-1)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
if e = f.Close(); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
sort.Sort(byDirName(list))
|
||||
return list, nil
|
||||
}
|
||||
|
||||
// readDirNames reads the directory named by dirname and returns
|
||||
// a sorted list of directory entries.
|
||||
func readDirNames(dirname string) ([]string, error) {
|
||||
names, e := readDirUnsortedNames(dirname)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
sort.Strings(names)
|
||||
return names, nil
|
||||
}
|
||||
|
||||
// getRealName - gets the proper filename for sorting purposes
|
||||
// Readdir() filters out directory names without separators, add
|
||||
// them back for proper sorting results.
|
||||
func getRealName(info os.FileInfo) string {
|
||||
if info.IsDir() {
|
||||
// Make sure directory has its end separator.
|
||||
return info.Name() + string(filepath.Separator)
|
||||
}
|
||||
return info.Name()
|
||||
}
|
||||
|
||||
// readDirUnsortedNames reads the directory named by dirname and
|
||||
// return a unsorted list of directory entries.
|
||||
func readDirUnsortedNames(dirname string) ([]string, error) {
|
||||
f, e := os.Open(dirname)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
nameInfos, e := f.Readdir(-1)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
if e = f.Close(); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
var names []string
|
||||
for _, nameInfo := range nameInfos {
|
||||
names = append(names, getRealName(nameInfo))
|
||||
}
|
||||
return names, nil
|
||||
}
|
||||
|
||||
// walk walks the file tree rooted at root, calling walkFn for each file or
|
||||
// directory in the tree, including root.
|
||||
func walk(root string, walkFn walkFunc) error {
|
||||
info, e := os.Lstat(root)
|
||||
if e != nil {
|
||||
return walkFn(root, nil, e)
|
||||
}
|
||||
return walkInternal(root, info, walkFn)
|
||||
}
|
||||
|
||||
// WalkFunc is the type of the function called for each file or directory
|
||||
// visited by Walk. The path argument contains the argument to Walk as a
|
||||
// prefix; that is, if Walk is called with "dir", which is a directory
|
||||
// containing the file "a", the walk function will be called with argument
|
||||
// "dir/a". The info argument is the os.FileInfo for the named path.
|
||||
type walkFunc func(path string, info os.FileInfo, e error) error
|
||||
|
||||
// ErrSkipDir is used as a return value from WalkFuncs to indicate that
|
||||
// the directory named in the call is to be skipped. It is not returned
|
||||
// as an error by any function.
|
||||
var errSkipDir = errors.New("skip this directory")
|
||||
|
||||
// ErrSkipFile is used as a return value from WalkFuncs to indicate that
|
||||
// the file named in the call is to be skipped. It is not returned
|
||||
// as an error by any function.
|
||||
var errSkipFile = errors.New("skip this file")
|
||||
|
||||
// walkInternal recursively descends path, calling w.
|
||||
func walkInternal(path string, info os.FileInfo, walkFn walkFunc) error {
|
||||
e := walkFn(path, info, nil)
|
||||
if e != nil {
|
||||
if info.Mode().IsDir() && e == errSkipDir {
|
||||
return nil
|
||||
}
|
||||
if info.Mode().IsRegular() && e == errSkipFile {
|
||||
return nil
|
||||
}
|
||||
return e
|
||||
}
|
||||
if !info.IsDir() {
|
||||
return nil
|
||||
}
|
||||
names, e := readDirNames(path)
|
||||
if e != nil {
|
||||
return walkFn(path, info, e)
|
||||
}
|
||||
for _, name := range names {
|
||||
filename := filepath.Join(path, name)
|
||||
fileInfo, e := os.Lstat(filename)
|
||||
if e != nil {
|
||||
if e = walkFn(filename, fileInfo, e); e != nil && e != errSkipDir && e != errSkipFile {
|
||||
return e
|
||||
}
|
||||
} else {
|
||||
e = walkInternal(filename, fileInfo, walkFn)
|
||||
if e != nil {
|
||||
if e == errSkipDir || e == errSkipFile {
|
||||
return nil
|
||||
}
|
||||
return e
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -1,745 +0,0 @@
|
||||
/*
|
||||
* 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 fs
|
||||
|
||||
import (
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"io/ioutil"
|
||||
|
||||
"github.com/minio/mc/pkg/client"
|
||||
"github.com/minio/mc/pkg/hookreader"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
)
|
||||
|
||||
// filesystem client
|
||||
type fsClient struct {
|
||||
PathURL *client.URL
|
||||
}
|
||||
|
||||
const (
|
||||
partSuffix = ".part.mc"
|
||||
)
|
||||
|
||||
// New - instantiate a new fs client.
|
||||
func New(path string) (client.Client, *probe.Error) {
|
||||
if strings.TrimSpace(path) == "" {
|
||||
return nil, probe.NewError(client.EmptyPath{})
|
||||
}
|
||||
return &fsClient{
|
||||
PathURL: client.NewURL(normalizePath(path)),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// URL get url.
|
||||
func (f *fsClient) GetURL() client.URL {
|
||||
return *f.PathURL
|
||||
}
|
||||
|
||||
/// Object operations.
|
||||
|
||||
// Put - create a new file.
|
||||
func (f *fsClient) Put(reader io.Reader, size int64, contentType string, progress io.Reader) (int64, *probe.Error) {
|
||||
// ContentType is not handled on purpose.
|
||||
// For filesystem this is a redundant information.
|
||||
|
||||
// Extract dir name.
|
||||
objectDir, _ := filepath.Split(f.PathURL.Path)
|
||||
objectPath := f.PathURL.Path
|
||||
|
||||
// Verify if destination already exists.
|
||||
st, e := os.Stat(objectPath)
|
||||
if e == nil {
|
||||
// If the destination exists and is not a regular file.
|
||||
if !st.Mode().IsRegular() {
|
||||
return 0, probe.NewError(client.PathIsNotRegular{
|
||||
Path: objectPath,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Proceed if file does not exist. return for all other errors.
|
||||
if e != nil {
|
||||
if !os.IsNotExist(e) {
|
||||
return 0, probe.NewError(e)
|
||||
}
|
||||
}
|
||||
|
||||
// Write to a temporary file "object.part.mc" before committ.
|
||||
objectPartPath := objectPath + partSuffix
|
||||
if objectDir != "" {
|
||||
// Create any missing top level directories.
|
||||
if e := os.MkdirAll(objectDir, 0700); e != nil {
|
||||
err := f.toClientError(e, f.PathURL.Path)
|
||||
return 0, err.Trace(f.PathURL.Path)
|
||||
}
|
||||
}
|
||||
|
||||
// If exists, open in append mode. If not create it the part file.
|
||||
partFile, e := os.OpenFile(objectPartPath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600)
|
||||
if e != nil {
|
||||
err := f.toClientError(e, f.PathURL.Path)
|
||||
return 0, err.Trace(f.PathURL.Path)
|
||||
}
|
||||
|
||||
// Get stat to get the current size.
|
||||
partSt, e := partFile.Stat()
|
||||
if e != nil {
|
||||
err := f.toClientError(e, objectPartPath)
|
||||
return 0, err.Trace(objectPartPath)
|
||||
}
|
||||
|
||||
var totalWritten int64
|
||||
// Current file offset.
|
||||
var currentOffset = partSt.Size()
|
||||
|
||||
// Reflect and verify if incoming reader implements ReaderAt.
|
||||
readerAt, ok := reader.(io.ReaderAt)
|
||||
if ok {
|
||||
// Notify the progress bar if any till current size.
|
||||
if progress != nil {
|
||||
if _, e = io.CopyN(ioutil.Discard, progress, currentOffset); e != nil {
|
||||
return 0, probe.NewError(e)
|
||||
}
|
||||
}
|
||||
// Allocate buffer of 10MiB once.
|
||||
readAtBuffer := make([]byte, 10*1024*1024)
|
||||
|
||||
// Loop through all offsets on incoming io.ReaderAt and write
|
||||
// to the destination.
|
||||
for {
|
||||
readAtSize, re := readerAt.ReadAt(readAtBuffer, currentOffset)
|
||||
if re != nil && re != io.EOF {
|
||||
// For any errors other than io.EOF, we return error
|
||||
// and breakout.
|
||||
err := f.toClientError(re, objectPartPath)
|
||||
return 0, err.Trace(objectPartPath)
|
||||
}
|
||||
writtenSize, we := partFile.Write(readAtBuffer[:readAtSize])
|
||||
if we != nil {
|
||||
err := f.toClientError(we, objectPartPath)
|
||||
return 0, err.Trace(objectPartPath)
|
||||
}
|
||||
// read size and subsequent write differ, a possible
|
||||
// corruption return here.
|
||||
if readAtSize != writtenSize {
|
||||
// Unexpected write (less data was written than expected).
|
||||
return 0, probe.NewError(client.UnexpectedShortWrite{
|
||||
InputSize: readAtSize,
|
||||
WriteSize: writtenSize,
|
||||
})
|
||||
}
|
||||
// Notify the progress bar if any for written size.
|
||||
if progress != nil {
|
||||
if _, e = io.CopyN(ioutil.Discard, progress, int64(writtenSize)); e != nil {
|
||||
return totalWritten, probe.NewError(e)
|
||||
}
|
||||
}
|
||||
currentOffset += int64(writtenSize)
|
||||
// Once we see io.EOF we break out of the loop.
|
||||
if re == io.EOF {
|
||||
break
|
||||
}
|
||||
}
|
||||
// Save currently copied total into totalWritten.
|
||||
totalWritten = currentOffset
|
||||
} else {
|
||||
reader = hookreader.NewHook(reader, progress)
|
||||
// Discard bytes until currentOffset.
|
||||
if _, e = io.CopyN(ioutil.Discard, reader, currentOffset); e != nil {
|
||||
return 0, probe.NewError(e)
|
||||
}
|
||||
var n int64
|
||||
n, e = io.Copy(partFile, reader)
|
||||
if e != nil {
|
||||
return 0, probe.NewError(e)
|
||||
}
|
||||
// Save currently copied total into totalWritten.
|
||||
totalWritten = n + currentOffset
|
||||
}
|
||||
|
||||
// Close the input reader as well, if possible.
|
||||
closer, ok := reader.(io.Closer)
|
||||
if ok {
|
||||
if e := closer.Close(); e != nil {
|
||||
return totalWritten, probe.NewError(e)
|
||||
}
|
||||
}
|
||||
|
||||
// Close the file before rename.
|
||||
if e := partFile.Close(); e != nil {
|
||||
return totalWritten, probe.NewError(e)
|
||||
}
|
||||
|
||||
// Following verification is needed only for input size greater than '0'.
|
||||
if size > 0 {
|
||||
// Unexpected EOF reached (less data was written than expected).
|
||||
if totalWritten < size {
|
||||
return totalWritten, probe.NewError(client.UnexpectedEOF{
|
||||
TotalSize: size,
|
||||
TotalWritten: totalWritten,
|
||||
})
|
||||
}
|
||||
// Unexpected ExcessRead (more data was written than expected).
|
||||
if totalWritten > size {
|
||||
return totalWritten, probe.NewError(client.UnexpectedExcessRead{
|
||||
TotalSize: size,
|
||||
TotalWritten: totalWritten,
|
||||
})
|
||||
}
|
||||
}
|
||||
// Safely completed put. Now commit by renaming to actual filename.
|
||||
if e = os.Rename(objectPartPath, objectPath); e != nil {
|
||||
err := f.toClientError(e, objectPath)
|
||||
return totalWritten, err.Trace(objectPartPath, objectPath)
|
||||
}
|
||||
return totalWritten, nil
|
||||
}
|
||||
|
||||
// ShareDownload - share download not implemented for filesystem.
|
||||
func (f *fsClient) ShareDownload(expires time.Duration) (string, *probe.Error) {
|
||||
return "", probe.NewError(client.APINotImplemented{
|
||||
API: "ShareDownload",
|
||||
APIType: "filesystem",
|
||||
})
|
||||
}
|
||||
|
||||
// ShareUpload - share upload not implemented for filesystem.
|
||||
func (f *fsClient) ShareUpload(startsWith bool, expires time.Duration, contentType string) (map[string]string, *probe.Error) {
|
||||
return nil, probe.NewError(client.APINotImplemented{
|
||||
API: "ShareUpload",
|
||||
APIType: "filesystem",
|
||||
})
|
||||
}
|
||||
|
||||
// GetPartial download a part object from bucket.
|
||||
// sets err for any errors, reader is nil for errors.
|
||||
func (f *fsClient) Get() (io.Reader, *probe.Error) {
|
||||
tmppath := f.PathURL.Path
|
||||
// Golang strips trailing / if you clean(..) or
|
||||
// EvalSymlinks(..). Adding '.' prevents it from doing so.
|
||||
if strings.HasSuffix(tmppath, string(f.PathURL.Separator)) {
|
||||
tmppath = tmppath + "."
|
||||
}
|
||||
|
||||
// Resolve symlinks.
|
||||
_, e := filepath.EvalSymlinks(tmppath)
|
||||
if e != nil {
|
||||
err := f.toClientError(e, f.PathURL.Path)
|
||||
return nil, err.Trace(f.PathURL.Path)
|
||||
}
|
||||
fileData, e := os.Open(f.PathURL.Path)
|
||||
if e != nil {
|
||||
err := f.toClientError(e, f.PathURL.Path)
|
||||
return nil, err.Trace(f.PathURL.Path)
|
||||
}
|
||||
return fileData, nil
|
||||
}
|
||||
|
||||
// Remove - remove the path.
|
||||
func (f *fsClient) Remove(incomplete bool) *probe.Error {
|
||||
if incomplete {
|
||||
return nil
|
||||
}
|
||||
e := os.Remove(f.PathURL.Path)
|
||||
err := f.toClientError(e, f.PathURL.Path)
|
||||
return err.Trace(f.PathURL.Path)
|
||||
}
|
||||
|
||||
// List - list files and folders.
|
||||
func (f *fsClient) List(recursive, incomplete bool) <-chan *client.Content {
|
||||
contentCh := make(chan *client.Content)
|
||||
switch recursive {
|
||||
case true:
|
||||
go f.listRecursiveInRoutine(contentCh, incomplete)
|
||||
default:
|
||||
go f.listInRoutine(contentCh, incomplete)
|
||||
}
|
||||
return contentCh
|
||||
}
|
||||
|
||||
// listPrefixes - list all files for any given prefix.
|
||||
func (f *fsClient) listPrefixes(prefix string, contentCh chan<- *client.Content, incomplete bool) {
|
||||
dirName := filepath.Dir(prefix)
|
||||
files, e := readDir(dirName)
|
||||
if e != nil {
|
||||
err := f.toClientError(e, dirName)
|
||||
contentCh <- &client.Content{
|
||||
Err: err.Trace(dirName),
|
||||
}
|
||||
return
|
||||
}
|
||||
pathURL := *f.PathURL
|
||||
for _, fi := range files {
|
||||
file := filepath.Join(dirName, fi.Name())
|
||||
if fi.Mode()&os.ModeSymlink == os.ModeSymlink {
|
||||
st, e := os.Stat(file)
|
||||
if e != nil {
|
||||
if os.IsPermission(e) {
|
||||
// On windows there are folder symlinks
|
||||
// which are called junction files which
|
||||
// carry special meaning on windows
|
||||
// - which cannot be accessed with regular operations
|
||||
if runtime.GOOS == "windows" {
|
||||
newPath := filepath.Join(prefix, fi.Name())
|
||||
lfi, le := f.handleWindowsSymlinks(newPath)
|
||||
if le != nil {
|
||||
contentCh <- &client.Content{
|
||||
Err: le.Trace(newPath),
|
||||
}
|
||||
continue
|
||||
}
|
||||
if incomplete {
|
||||
if !strings.HasSuffix(lfi.Name(), partSuffix) {
|
||||
continue
|
||||
}
|
||||
} else {
|
||||
if strings.HasSuffix(lfi.Name(), partSuffix) {
|
||||
continue
|
||||
}
|
||||
}
|
||||
pathURL.Path = filepath.Join(pathURL.Path, lfi.Name())
|
||||
contentCh <- &client.Content{
|
||||
URL: pathURL,
|
||||
Time: lfi.ModTime(),
|
||||
Size: lfi.Size(),
|
||||
Type: lfi.Mode(),
|
||||
Err: probe.NewError(client.PathInsufficientPermission{
|
||||
Path: pathURL.Path,
|
||||
}),
|
||||
}
|
||||
continue
|
||||
} else {
|
||||
contentCh <- &client.Content{
|
||||
Err: probe.NewError(client.PathInsufficientPermission{
|
||||
Path: pathURL.Path,
|
||||
}),
|
||||
}
|
||||
continue
|
||||
}
|
||||
}
|
||||
if os.IsNotExist(e) {
|
||||
contentCh <- &client.Content{
|
||||
Err: probe.NewError(client.BrokenSymlink{
|
||||
Path: pathURL.Path,
|
||||
}),
|
||||
}
|
||||
continue
|
||||
}
|
||||
if e != nil {
|
||||
contentCh <- &client.Content{
|
||||
Err: probe.NewError(e),
|
||||
}
|
||||
continue
|
||||
}
|
||||
}
|
||||
if strings.HasPrefix(file, prefix) {
|
||||
if incomplete {
|
||||
if !strings.HasSuffix(st.Name(), partSuffix) {
|
||||
continue
|
||||
}
|
||||
} else {
|
||||
if strings.HasSuffix(st.Name(), partSuffix) {
|
||||
continue
|
||||
}
|
||||
}
|
||||
contentCh <- &client.Content{
|
||||
URL: *client.NewURL(file),
|
||||
Time: st.ModTime(),
|
||||
Size: st.Size(),
|
||||
Type: st.Mode(),
|
||||
Err: nil,
|
||||
}
|
||||
continue
|
||||
}
|
||||
}
|
||||
if strings.HasPrefix(file, prefix) {
|
||||
if incomplete {
|
||||
if !strings.HasSuffix(fi.Name(), partSuffix) {
|
||||
continue
|
||||
}
|
||||
} else {
|
||||
if strings.HasSuffix(fi.Name(), partSuffix) {
|
||||
continue
|
||||
}
|
||||
}
|
||||
contentCh <- &client.Content{
|
||||
URL: *client.NewURL(file),
|
||||
Time: fi.ModTime(),
|
||||
Size: fi.Size(),
|
||||
Type: fi.Mode(),
|
||||
Err: nil,
|
||||
}
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (f *fsClient) listInRoutine(contentCh chan<- *client.Content, incomplete bool) {
|
||||
// close the channel when the function returns.
|
||||
defer close(contentCh)
|
||||
|
||||
// save pathURL and file path for further usage.
|
||||
pathURL := *f.PathURL
|
||||
fpath := pathURL.Path
|
||||
|
||||
fst, err := f.fsStat()
|
||||
if err != nil {
|
||||
if _, ok := err.ToGoError().(client.PathNotFound); ok {
|
||||
// If file does not exist treat it like a prefix and list all prefixes if any.
|
||||
prefix := fpath
|
||||
f.listPrefixes(prefix, contentCh, incomplete)
|
||||
return
|
||||
}
|
||||
// For all other errors we return genuine error back to the caller.
|
||||
contentCh <- &client.Content{Err: err.Trace(fpath)}
|
||||
return
|
||||
}
|
||||
|
||||
// Now if the file exists and doesn't end with a separator ('/') do not traverse it.
|
||||
// If the directory doesn't end with a separator, do not traverse it.
|
||||
if !strings.HasSuffix(fpath, string(pathURL.Separator)) && fst.Mode().IsDir() && fpath != "." {
|
||||
f.listPrefixes(fpath, contentCh, incomplete)
|
||||
return
|
||||
}
|
||||
|
||||
// If we really see the directory.
|
||||
switch fst.Mode().IsDir() {
|
||||
case true:
|
||||
files, e := readDir(fpath)
|
||||
if err != nil {
|
||||
contentCh <- &client.Content{Err: probe.NewError(e)}
|
||||
return
|
||||
}
|
||||
for _, file := range files {
|
||||
fi := file
|
||||
if fi.Mode()&os.ModeSymlink == os.ModeSymlink {
|
||||
fi, e = os.Stat(filepath.Join(fpath, fi.Name()))
|
||||
if os.IsPermission(e) {
|
||||
// On windows there are folder symlinks
|
||||
// which are called junction files which
|
||||
// carry special meaning on windows
|
||||
// - which cannot be accessed with regular operations
|
||||
if runtime.GOOS == "windows" {
|
||||
newPath := filepath.Join(fpath, fi.Name())
|
||||
lfi, le := f.handleWindowsSymlinks(newPath)
|
||||
if le != nil {
|
||||
contentCh <- &client.Content{
|
||||
Err: le.Trace(newPath),
|
||||
}
|
||||
continue
|
||||
}
|
||||
if incomplete {
|
||||
if !strings.HasSuffix(lfi.Name(), partSuffix) {
|
||||
continue
|
||||
}
|
||||
} else {
|
||||
if strings.HasSuffix(lfi.Name(), partSuffix) {
|
||||
continue
|
||||
}
|
||||
}
|
||||
pathURL = *f.PathURL
|
||||
pathURL.Path = filepath.Join(pathURL.Path, lfi.Name())
|
||||
contentCh <- &client.Content{
|
||||
URL: pathURL,
|
||||
Time: lfi.ModTime(),
|
||||
Size: lfi.Size(),
|
||||
Type: lfi.Mode(),
|
||||
Err: probe.NewError(client.PathInsufficientPermission{Path: pathURL.Path}),
|
||||
}
|
||||
continue
|
||||
} else {
|
||||
contentCh <- &client.Content{
|
||||
Err: probe.NewError(client.PathInsufficientPermission{Path: pathURL.Path}),
|
||||
}
|
||||
continue
|
||||
}
|
||||
}
|
||||
if os.IsNotExist(e) {
|
||||
contentCh <- &client.Content{
|
||||
Err: probe.NewError(client.BrokenSymlink{Path: file.Name()}),
|
||||
}
|
||||
continue
|
||||
}
|
||||
if e != nil {
|
||||
contentCh <- &client.Content{
|
||||
Err: probe.NewError(e),
|
||||
}
|
||||
continue
|
||||
}
|
||||
}
|
||||
if fi.Mode().IsRegular() || fi.Mode().IsDir() {
|
||||
if incomplete {
|
||||
if !strings.HasSuffix(fi.Name(), partSuffix) {
|
||||
continue
|
||||
}
|
||||
} else {
|
||||
if strings.HasSuffix(fi.Name(), partSuffix) {
|
||||
continue
|
||||
}
|
||||
}
|
||||
pathURL = *f.PathURL
|
||||
pathURL.Path = filepath.Join(pathURL.Path, fi.Name())
|
||||
contentCh <- &client.Content{
|
||||
URL: pathURL,
|
||||
Time: fi.ModTime(),
|
||||
Size: fi.Size(),
|
||||
Type: fi.Mode(),
|
||||
Err: nil,
|
||||
}
|
||||
}
|
||||
}
|
||||
default:
|
||||
if incomplete {
|
||||
if !strings.HasSuffix(fst.Name(), partSuffix) {
|
||||
return
|
||||
}
|
||||
} else {
|
||||
if strings.HasSuffix(fst.Name(), partSuffix) {
|
||||
return
|
||||
}
|
||||
}
|
||||
contentCh <- &client.Content{
|
||||
URL: pathURL,
|
||||
Time: fst.ModTime(),
|
||||
Size: fst.Size(),
|
||||
Type: fst.Mode(),
|
||||
Err: nil,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (f *fsClient) listRecursiveInRoutine(contentCh chan *client.Content, incomplete bool) {
|
||||
// close channels upon return.
|
||||
defer close(contentCh)
|
||||
var dirName string
|
||||
var filePrefix string
|
||||
pathURL := *f.PathURL
|
||||
visitFS := func(fp string, fi os.FileInfo, e error) error {
|
||||
// If file path ends with filepath.Separator and equals to root path, skip it.
|
||||
if strings.HasSuffix(fp, string(pathURL.Separator)) {
|
||||
if fp == dirName {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
// We would never need to print system root path '/'.
|
||||
if fp == "/" {
|
||||
return nil
|
||||
}
|
||||
|
||||
/// In following situations we need to handle listing properly.
|
||||
// - When filepath is '/usr' and prefix is '/usr/bi'
|
||||
// - When filepath is '/usr/bin/subdir' and prefix is '/usr/bi'
|
||||
// - Do not check filePrefix if its '.'
|
||||
if filePrefix != "." {
|
||||
if !strings.HasPrefix(fp, filePrefix) &&
|
||||
!strings.HasPrefix(filePrefix, fp) {
|
||||
if e == nil {
|
||||
if fi.IsDir() {
|
||||
return errSkipDir
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
// - Skip when fp is /usr and prefix is '/usr/bi'
|
||||
// - Do not check filePrefix if its '.'
|
||||
if filePrefix != "." {
|
||||
if !strings.HasPrefix(fp, filePrefix) {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
if e != nil {
|
||||
// If operation is not permitted, we throw quickly back.
|
||||
if strings.Contains(e.Error(), "operation not permitted") {
|
||||
contentCh <- &client.Content{
|
||||
Err: probe.NewError(e),
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if os.IsPermission(e) {
|
||||
if runtime.GOOS == "windows" {
|
||||
lfi, le := f.handleWindowsSymlinks(fp)
|
||||
if le != nil {
|
||||
contentCh <- &client.Content{
|
||||
Err: le.Trace(fp),
|
||||
}
|
||||
return nil
|
||||
}
|
||||
pathURL := *f.PathURL
|
||||
pathURL.Path = filepath.Join(pathURL.Path, dirName)
|
||||
if incomplete {
|
||||
if !strings.HasSuffix(lfi.Name(), partSuffix) {
|
||||
return nil
|
||||
}
|
||||
} else {
|
||||
if strings.HasSuffix(lfi.Name(), partSuffix) {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
contentCh <- &client.Content{
|
||||
URL: pathURL,
|
||||
Time: lfi.ModTime(),
|
||||
Size: lfi.Size(),
|
||||
Type: lfi.Mode(),
|
||||
Err: probe.NewError(e),
|
||||
}
|
||||
} else {
|
||||
contentCh <- &client.Content{
|
||||
Err: probe.NewError(client.PathInsufficientPermission{Path: fp}),
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return e
|
||||
}
|
||||
if fi.Mode()&os.ModeSymlink == os.ModeSymlink {
|
||||
fi, e = os.Stat(fp)
|
||||
if e != nil {
|
||||
if os.IsPermission(e) {
|
||||
if runtime.GOOS == "windows" {
|
||||
lfi, le := f.handleWindowsSymlinks(fp)
|
||||
if le != nil {
|
||||
contentCh <- &client.Content{
|
||||
Err: le.Trace(fp),
|
||||
}
|
||||
return nil
|
||||
}
|
||||
pathURL := *f.PathURL
|
||||
pathURL.Path = filepath.Join(pathURL.Path, dirName)
|
||||
if incomplete {
|
||||
if !strings.HasSuffix(lfi.Name(), partSuffix) {
|
||||
return nil
|
||||
}
|
||||
} else {
|
||||
if !strings.HasSuffix(lfi.Name(), partSuffix) {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
contentCh <- &client.Content{
|
||||
URL: pathURL,
|
||||
Time: lfi.ModTime(),
|
||||
Size: lfi.Size(),
|
||||
Type: lfi.Mode(),
|
||||
Err: probe.NewError(e),
|
||||
}
|
||||
return nil
|
||||
}
|
||||
contentCh <- &client.Content{
|
||||
Err: probe.NewError(e),
|
||||
}
|
||||
return nil
|
||||
}
|
||||
// Ignore in-accessible broken symlinks.
|
||||
if os.IsNotExist(e) {
|
||||
contentCh <- &client.Content{
|
||||
Err: probe.NewError(client.BrokenSymlink{Path: fp}),
|
||||
}
|
||||
return nil
|
||||
}
|
||||
// Ignore symlink loops.
|
||||
if strings.Contains(e.Error(), "too many levels of symbolic links") {
|
||||
contentCh <- &client.Content{
|
||||
Err: probe.NewError(client.TooManyLevelsSymlink{Path: fp}),
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return e
|
||||
}
|
||||
}
|
||||
if fi.Mode().IsRegular() || fi.Mode().IsDir() {
|
||||
if incomplete {
|
||||
if !strings.HasSuffix(fi.Name(), partSuffix) {
|
||||
return nil
|
||||
}
|
||||
} else {
|
||||
if strings.HasSuffix(fi.Name(), partSuffix) {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
contentCh <- &client.Content{
|
||||
URL: *client.NewURL(fp),
|
||||
Time: fi.ModTime(),
|
||||
Size: fi.Size(),
|
||||
Type: fi.Mode(),
|
||||
Err: nil,
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
// No prefix to be filtered by default.
|
||||
filePrefix = ""
|
||||
// if f.Path ends with filepath.Separator - assuming it to be a directory and moving on.
|
||||
if strings.HasSuffix(pathURL.Path, string(pathURL.Separator)) {
|
||||
dirName = pathURL.Path
|
||||
} else {
|
||||
// if not a directory, take base path to navigate through WalkFunc.
|
||||
dirName = filepath.Dir(pathURL.Path)
|
||||
if !strings.HasSuffix(dirName, string(pathURL.Separator)) {
|
||||
// basepath truncates the filepath.Separator,
|
||||
// add it deligently useful for trimming file path inside WalkFunc
|
||||
dirName = dirName + string(pathURL.Separator)
|
||||
}
|
||||
// filePrefix is kept for filtering incoming contents through WalkFunc.
|
||||
filePrefix = pathURL.Path
|
||||
}
|
||||
// walks invokes our custom function.
|
||||
e := walk(dirName, visitFS)
|
||||
if e != nil {
|
||||
contentCh <- &client.Content{
|
||||
Err: probe.NewError(e),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MakeBucket - create a new bucket.
|
||||
func (f *fsClient) MakeBucket(region string) *probe.Error {
|
||||
e := os.MkdirAll(f.PathURL.Path, 0775)
|
||||
if e != nil {
|
||||
return probe.NewError(e)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetBucketACL - get bucket access.
|
||||
func (f *fsClient) GetBucketAccess() (acl string, err *probe.Error) {
|
||||
return "", probe.NewError(client.APINotImplemented{API: "GetBucketAccess", APIType: "filesystem"})
|
||||
}
|
||||
|
||||
// SetBucketAccess - set bucket access.
|
||||
func (f *fsClient) SetBucketAccess(acl string) *probe.Error {
|
||||
return probe.NewError(client.APINotImplemented{API: "SetBucketAccess", APIType: "filesystem"})
|
||||
}
|
||||
|
||||
// Stat - get metadata from path.
|
||||
func (f *fsClient) Stat() (content *client.Content, err *probe.Error) {
|
||||
st, err := f.fsStat()
|
||||
if err != nil {
|
||||
return nil, err.Trace(f.PathURL.String())
|
||||
}
|
||||
content = new(client.Content)
|
||||
content.URL = *f.PathURL
|
||||
content.Size = st.Size()
|
||||
content.Time = st.ModTime()
|
||||
content.Type = st.Mode()
|
||||
return content, nil
|
||||
}
|
||||
@@ -1,282 +0,0 @@
|
||||
/*
|
||||
* 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 fs_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"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) {
|
||||
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)
|
||||
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)
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(n, Equals, int64(len(data)))
|
||||
|
||||
objectPath = filepath.Join(root, "object2")
|
||||
fsClient, err = fs.New(objectPath)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
reader = bytes.NewReader([]byte(data))
|
||||
n, err = fsClient.Put(reader, int64(len(data)), "application/octet-stream", nil)
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(n, Equals, int64(len(data)))
|
||||
|
||||
fsClient, err = fs.New(root)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
// Verify previously create files and list them.
|
||||
var contents []*client.Content
|
||||
for content := range fsClient.List(false, false) {
|
||||
if content.Err != nil {
|
||||
err = content.Err
|
||||
break
|
||||
}
|
||||
contents = append(contents, content)
|
||||
}
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(len(contents), Equals, 1)
|
||||
c.Assert(contents[0].Type.IsDir(), Equals, true)
|
||||
|
||||
// Create another file.
|
||||
objectPath = filepath.Join(root, "test1/newObject1")
|
||||
fsClient, err = fs.New(objectPath)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
reader = bytes.NewReader([]byte(data))
|
||||
n, err = fsClient.Put(reader, int64(len(data)), "application/octet-stream", nil)
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(n, Equals, int64(len(data)))
|
||||
|
||||
fsClient, err = fs.New(root)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
contents = nil
|
||||
// List non recursive to list only top level files.
|
||||
for content := range fsClient.List(false, false) {
|
||||
if content.Err != nil {
|
||||
err = content.Err
|
||||
break
|
||||
}
|
||||
contents = append(contents, content)
|
||||
}
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(len(contents), Equals, 1)
|
||||
c.Assert(contents[0].Type.IsDir(), Equals, true)
|
||||
|
||||
fsClient, err = fs.New(root)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
contents = nil
|
||||
// List recursively all files and verify.
|
||||
for content := range fsClient.List(true, false) {
|
||||
if content.Err != nil {
|
||||
err = content.Err
|
||||
break
|
||||
}
|
||||
contents = append(contents, content)
|
||||
}
|
||||
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(len(contents), Equals, 5)
|
||||
|
||||
var regularFiles int
|
||||
var regularDirs int
|
||||
// Test number of expected files and directories.
|
||||
for _, content := range contents {
|
||||
if content.Type.IsRegular() {
|
||||
regularFiles++
|
||||
continue
|
||||
}
|
||||
if content.Type.IsDir() {
|
||||
regularDirs++
|
||||
continue
|
||||
}
|
||||
}
|
||||
c.Assert(regularDirs, Equals, 2)
|
||||
c.Assert(regularFiles, Equals, 3)
|
||||
}
|
||||
|
||||
// Test put bucket aka 'mkdir()' operation.
|
||||
func (s *MySuite) TestPutBucket(c *C) {
|
||||
root, e := ioutil.TempDir(os.TempDir(), "fs-")
|
||||
c.Assert(e, IsNil)
|
||||
defer os.RemoveAll(root)
|
||||
|
||||
bucketPath := filepath.Join(root, "bucket")
|
||||
fsClient, err := fs.New(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) {
|
||||
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)
|
||||
c.Assert(err, IsNil)
|
||||
err = fsClient.MakeBucket("us-east-1")
|
||||
c.Assert(err, IsNil)
|
||||
_, err = fsClient.Stat()
|
||||
c.Assert(err, IsNil)
|
||||
}
|
||||
|
||||
// Test bucket acl fails for directories.
|
||||
func (s *MySuite) TestBucketACLFails(c *C) {
|
||||
root, e := ioutil.TempDir(os.TempDir(), "fs-")
|
||||
c.Assert(e, IsNil)
|
||||
defer os.RemoveAll(root)
|
||||
|
||||
bucketPath := filepath.Join(root, "bucket")
|
||||
fsClient, err := fs.New(bucketPath)
|
||||
c.Assert(err, IsNil)
|
||||
err = fsClient.MakeBucket("us-east-1")
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
err = fsClient.SetBucketAccess("private")
|
||||
c.Assert(err, Not(IsNil))
|
||||
|
||||
_, err = fsClient.GetBucketAccess()
|
||||
c.Assert(err, Not(IsNil))
|
||||
}
|
||||
|
||||
// Test creating a file.
|
||||
func (s *MySuite) TestPut(c *C) {
|
||||
root, e := ioutil.TempDir(os.TempDir(), "fs-")
|
||||
c.Assert(e, IsNil)
|
||||
defer os.RemoveAll(root)
|
||||
|
||||
objectPath := filepath.Join(root, "object")
|
||||
fsClient, err := fs.New(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)
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(n, Equals, int64(len(data)))
|
||||
}
|
||||
|
||||
// Test read a file.
|
||||
func (s *MySuite) TestGet(c *C) {
|
||||
root, e := ioutil.TempDir(os.TempDir(), "fs-")
|
||||
c.Assert(e, IsNil)
|
||||
defer os.RemoveAll(root)
|
||||
|
||||
objectPath := filepath.Join(root, "object")
|
||||
fsClient, err := fs.New(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)
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(n, Equals, int64(len(data)))
|
||||
|
||||
reader, err = fsClient.Get()
|
||||
c.Assert(err, IsNil)
|
||||
var results bytes.Buffer
|
||||
_, e = io.Copy(&results, reader)
|
||||
c.Assert(e, IsNil)
|
||||
c.Assert([]byte(data), DeepEquals, results.Bytes())
|
||||
|
||||
}
|
||||
|
||||
// Test get range in a file.
|
||||
func (s *MySuite) TestGetRange(c *C) {
|
||||
root, e := ioutil.TempDir(os.TempDir(), "fs-")
|
||||
c.Assert(e, IsNil)
|
||||
defer os.RemoveAll(root)
|
||||
|
||||
objectPath := filepath.Join(root, "object")
|
||||
fsClient, err := fs.New(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)
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(n, Equals, int64(len(data)))
|
||||
|
||||
reader, err = fsClient.Get()
|
||||
c.Assert(err, IsNil)
|
||||
var results bytes.Buffer
|
||||
buf := make([]byte, 5)
|
||||
m, e := reader.(io.ReaderAt).ReadAt(buf, 0)
|
||||
c.Assert(e, IsNil)
|
||||
c.Assert(m, Equals, 5)
|
||||
_, e = results.Write(buf)
|
||||
c.Assert(e, IsNil)
|
||||
c.Assert([]byte("hello"), DeepEquals, results.Bytes())
|
||||
}
|
||||
|
||||
// Test stat file.
|
||||
func (s *MySuite) TestStatObject(c *C) {
|
||||
root, e := ioutil.TempDir(os.TempDir(), "fs-")
|
||||
c.Assert(e, IsNil)
|
||||
defer os.RemoveAll(root)
|
||||
|
||||
objectPath := filepath.Join(root, "object")
|
||||
fsClient, err := fs.New(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)
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(n, Equals, int64(len(data)))
|
||||
|
||||
content, err := fsClient.Stat()
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(content.Size, Equals, int64(dataLen))
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
// +build !windows
|
||||
|
||||
/*
|
||||
* 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 fs
|
||||
|
||||
func normalizePath(path string) string {
|
||||
return path
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
// +build windows
|
||||
|
||||
/*
|
||||
* 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 fs
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
func normalizePath(path string) string {
|
||||
if filepath.VolumeName(path) == "" && filepath.HasPrefix(path, "\\") {
|
||||
var err error
|
||||
path, err = syscall.FullPath(path)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
return path
|
||||
}
|
||||
@@ -1,725 +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 s3
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"hash/fnv"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/minio/mc/pkg/client"
|
||||
"github.com/minio/mc/pkg/httptracer"
|
||||
"github.com/minio/minio-go"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
)
|
||||
|
||||
// S3 client
|
||||
type s3Client struct {
|
||||
mutex *sync.Mutex
|
||||
targetURL *client.URL
|
||||
api minio.CloudStorageClient
|
||||
virtualStyle bool
|
||||
}
|
||||
|
||||
// newFactory encloses New function with client cache.
|
||||
func newFactory() func(config *client.Config) (client.Client, *probe.Error) {
|
||||
clientCache := make(map[uint32]minio.CloudStorageClient)
|
||||
mutex := &sync.Mutex{}
|
||||
|
||||
// Return New function.
|
||||
return func(config *client.Config) (client.Client, *probe.Error) {
|
||||
// Creates a parsed URL.
|
||||
targetURL := client.NewURL(config.HostURL)
|
||||
// By default enable HTTPs.
|
||||
inSecure := false
|
||||
if targetURL.Scheme == "http" {
|
||||
inSecure = true
|
||||
}
|
||||
|
||||
// Instantiate s3 client.
|
||||
s3Clnt := &s3Client{}
|
||||
// Allocate a new mutex.
|
||||
s3Clnt.mutex = new(sync.Mutex)
|
||||
// Save the target URL.
|
||||
s3Clnt.targetURL = targetURL
|
||||
|
||||
// Save if target supports virtual host style.
|
||||
hostName := targetURL.Host
|
||||
s3Clnt.virtualStyle = isVirtualHostStyle(hostName)
|
||||
|
||||
if s3Clnt.virtualStyle {
|
||||
// If Amazon URL replace it with 's3.amazonaws.com'
|
||||
if isAmazon(hostName) {
|
||||
hostName = "s3.amazonaws.com"
|
||||
}
|
||||
// If Google URL replace it with 'storage.googleapis.com'
|
||||
if isGoogle(hostName) {
|
||||
hostName = "storage.googleapis.com"
|
||||
}
|
||||
}
|
||||
|
||||
// Generate a hash out of s3Conf.
|
||||
confHash := fnv.New32a()
|
||||
confHash.Write([]byte(hostName + config.AccessKey + config.SecretKey))
|
||||
confSum := confHash.Sum32()
|
||||
|
||||
// Lookup previous cache by hash.
|
||||
mutex.Lock()
|
||||
defer mutex.Unlock()
|
||||
var api minio.CloudStorageClient
|
||||
found := false
|
||||
if api, found = clientCache[confSum]; !found {
|
||||
// Not found. Instantiate a new minio client.
|
||||
var e error
|
||||
if config.Signature == "S3v2" {
|
||||
// if Signature version '2' use NewV2 directly.
|
||||
api, e = minio.NewV2(hostName, config.AccessKey, config.SecretKey, inSecure)
|
||||
} else {
|
||||
// if Signature version '4' use NewV4 directly.
|
||||
api, e = minio.NewV4(hostName, config.AccessKey, config.SecretKey, inSecure)
|
||||
}
|
||||
if e != nil {
|
||||
return nil, probe.NewError(e)
|
||||
}
|
||||
// Cache the new minio client with hash of config as key.
|
||||
clientCache[confSum] = api
|
||||
}
|
||||
// Set app info.
|
||||
api.SetAppInfo(config.AppName, config.AppVersion)
|
||||
|
||||
if config.Debug {
|
||||
transport := http.DefaultTransport
|
||||
if config.Signature == "S3v4" {
|
||||
transport = httptracer.GetNewTraceTransport(NewTraceV4(), http.DefaultTransport)
|
||||
}
|
||||
if config.Signature == "S3v2" {
|
||||
transport = httptracer.GetNewTraceTransport(NewTraceV2(), http.DefaultTransport)
|
||||
}
|
||||
// Set custom transport.
|
||||
api.SetCustomTransport(transport)
|
||||
}
|
||||
|
||||
// Store the new api object.
|
||||
s3Clnt.api = api
|
||||
|
||||
return s3Clnt, nil
|
||||
}
|
||||
}
|
||||
|
||||
// New returns an initialized s3Client structure. If debug is enabled,
|
||||
// it also enables an internal trace transport.
|
||||
var New = newFactory()
|
||||
|
||||
// GetURL get url.
|
||||
func (c *s3Client) GetURL() client.URL {
|
||||
return *c.targetURL
|
||||
}
|
||||
|
||||
// Get - get object.
|
||||
func (c *s3Client) Get() (io.Reader, *probe.Error) {
|
||||
bucket, object := c.url2BucketAndObject()
|
||||
reader, e := c.api.GetObject(bucket, object)
|
||||
if e != nil {
|
||||
errResponse := minio.ToErrorResponse(e)
|
||||
if errResponse.Code == "AccessDenied" {
|
||||
return nil, probe.NewError(client.PathInsufficientPermission{Path: c.targetURL.String()})
|
||||
}
|
||||
return nil, probe.NewError(e)
|
||||
}
|
||||
return reader, nil
|
||||
}
|
||||
|
||||
// Put - put object.
|
||||
func (c *s3Client) Put(reader io.Reader, size int64, contentType string, progress io.Reader) (int64, *probe.Error) {
|
||||
// md5 is purposefully ignored since AmazonS3 does not return proper md5sum
|
||||
// for a multipart upload and there is no need to cross verify,
|
||||
// invidual parts are properly verified fully in transit and also upon completion
|
||||
// of the multipart request.
|
||||
bucket, object := c.url2BucketAndObject()
|
||||
if contentType == "" {
|
||||
contentType = "application/octet-stream"
|
||||
}
|
||||
n, e := c.api.PutObjectWithProgress(bucket, object, reader, contentType, progress)
|
||||
if e != nil {
|
||||
errResponse := minio.ToErrorResponse(e)
|
||||
if errResponse.Code == "UnexpectedEOF" || e == io.EOF {
|
||||
return n, probe.NewError(client.UnexpectedEOF{
|
||||
TotalSize: size,
|
||||
TotalWritten: n,
|
||||
})
|
||||
}
|
||||
if errResponse.Code == "AccessDenied" {
|
||||
return n, probe.NewError(client.PathInsufficientPermission{
|
||||
Path: c.targetURL.String(),
|
||||
})
|
||||
}
|
||||
if errResponse.Code == "MethodNotAllowed" {
|
||||
return n, probe.NewError(client.ObjectAlreadyExists{
|
||||
Object: object,
|
||||
})
|
||||
}
|
||||
if errResponse.Code == "NoSuchBucket" {
|
||||
return n, probe.NewError(client.BucketDoesNotExist{
|
||||
Bucket: bucket,
|
||||
})
|
||||
}
|
||||
if errResponse.Code == "InvalidArgument" {
|
||||
return n, probe.NewError(client.ObjectMissing{})
|
||||
}
|
||||
return n, probe.NewError(e)
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// Remove - remove object or bucket.
|
||||
func (c *s3Client) Remove(incomplete bool) *probe.Error {
|
||||
bucket, object := c.url2BucketAndObject()
|
||||
// Remove only incomplete object.
|
||||
if incomplete && object != "" {
|
||||
e := c.api.RemoveIncompleteUpload(bucket, object)
|
||||
return probe.NewError(e)
|
||||
}
|
||||
var e error
|
||||
if object == "" {
|
||||
e = c.api.RemoveBucket(bucket)
|
||||
} else {
|
||||
e = c.api.RemoveObject(bucket, object)
|
||||
}
|
||||
return probe.NewError(e)
|
||||
}
|
||||
|
||||
// We support '.' with bucket names but we fallback to using path
|
||||
// style requests instead for such buckets
|
||||
var validBucketName = regexp.MustCompile(`^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$`)
|
||||
|
||||
// isValidBucketName - verify bucket name in accordance with
|
||||
// - http://docs.aws.amazon.com/AmazonS3/latest/dev/UsingBucket.html
|
||||
func isValidBucketName(bucketName string) *probe.Error {
|
||||
if strings.TrimSpace(bucketName) == "" {
|
||||
return probe.NewError(errors.New("Bucket name cannot be empty."))
|
||||
}
|
||||
if len(bucketName) < 3 || len(bucketName) > 63 {
|
||||
return probe.NewError(errors.New("Bucket name should be more than 3 characters and less than 64 characters"))
|
||||
}
|
||||
if !validBucketName.MatchString(bucketName) {
|
||||
return probe.NewError(errors.New("Bucket name can contain alphabet, '-' and numbers, but first character should be an alphabet or number"))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// MakeBucket - make a new bucket.
|
||||
func (c *s3Client) MakeBucket(region string) *probe.Error {
|
||||
bucket, object := c.url2BucketAndObject()
|
||||
if object != "" {
|
||||
return probe.NewError(client.BucketNameTopLevel{})
|
||||
}
|
||||
if err := isValidBucketName(bucket); err != nil {
|
||||
return err.Trace(bucket)
|
||||
}
|
||||
e := c.api.MakeBucket(bucket, minio.BucketACL("private"), region)
|
||||
if e != nil {
|
||||
return probe.NewError(e)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetBucketAccess get acl on a bucket.
|
||||
func (c *s3Client) GetBucketAccess() (acl string, err *probe.Error) {
|
||||
bucket, object := c.url2BucketAndObject()
|
||||
if object != "" {
|
||||
return "", probe.NewError(client.InvalidBucketName{Bucket: filepath.Join(bucket, object)})
|
||||
}
|
||||
if bucket == "" {
|
||||
return "", probe.NewError(client.BucketNameEmpty{})
|
||||
}
|
||||
bucketACL, e := c.api.GetBucketACL(bucket)
|
||||
if e != nil {
|
||||
return "", probe.NewError(e)
|
||||
}
|
||||
return bucketACL.String(), nil
|
||||
}
|
||||
|
||||
// SetBucketAccess set acl on a bucket
|
||||
func (c *s3Client) SetBucketAccess(acl string) *probe.Error {
|
||||
bucket, object := c.url2BucketAndObject()
|
||||
if object != "" {
|
||||
return probe.NewError(client.InvalidBucketName{Bucket: filepath.Join(bucket, object)})
|
||||
}
|
||||
if bucket == "" {
|
||||
return probe.NewError(client.BucketNameEmpty{})
|
||||
}
|
||||
e := c.api.SetBucketACL(bucket, minio.BucketACL(acl))
|
||||
if e != nil {
|
||||
return probe.NewError(e)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Stat - send a 'HEAD' on a bucket or object to fetch its metadata.
|
||||
func (c *s3Client) Stat() (*client.Content, *probe.Error) {
|
||||
c.mutex.Lock()
|
||||
objectMetadata := new(client.Content)
|
||||
bucket, object := c.url2BucketAndObject()
|
||||
switch {
|
||||
// valid case for 'ls -r s3/'
|
||||
case bucket == "" && object == "":
|
||||
_, e := c.api.ListBuckets()
|
||||
if e != nil {
|
||||
c.mutex.Unlock()
|
||||
return nil, probe.NewError(e)
|
||||
}
|
||||
c.mutex.Unlock()
|
||||
return &client.Content{URL: *c.targetURL, Type: os.ModeDir}, nil
|
||||
}
|
||||
if object != "" {
|
||||
metadata, e := c.api.StatObject(bucket, object)
|
||||
if e != nil {
|
||||
c.mutex.Unlock()
|
||||
errResponse := minio.ToErrorResponse(e)
|
||||
if errResponse.Code == "NoSuchKey" {
|
||||
// Append "/" to the object name proactively and see if the Listing
|
||||
// produces an output. If yes, then we treat it as a directory.
|
||||
prefixName := object
|
||||
// Trim any trailing separators and add it.
|
||||
prefixName = strings.TrimSuffix(prefixName, string(c.targetURL.Separator)) + string(c.targetURL.Separator)
|
||||
isRecursive := false
|
||||
for objectStat := range c.api.ListObjects(bucket, prefixName, isRecursive, nil) {
|
||||
if objectStat.Err != nil {
|
||||
return nil, probe.NewError(objectStat.Err)
|
||||
}
|
||||
content := client.Content{}
|
||||
content.URL = *c.targetURL
|
||||
content.Type = os.ModeDir
|
||||
return &content, nil
|
||||
}
|
||||
return nil, probe.NewError(client.PathNotFound{Path: c.targetURL.Path})
|
||||
}
|
||||
return nil, probe.NewError(e)
|
||||
}
|
||||
objectMetadata.URL = *c.targetURL
|
||||
objectMetadata.Time = metadata.LastModified
|
||||
objectMetadata.Size = metadata.Size
|
||||
objectMetadata.Type = os.FileMode(0664)
|
||||
c.mutex.Unlock()
|
||||
return objectMetadata, nil
|
||||
}
|
||||
e := c.api.BucketExists(bucket)
|
||||
if e != nil {
|
||||
c.mutex.Unlock()
|
||||
return nil, probe.NewError(e)
|
||||
}
|
||||
bucketMetadata := new(client.Content)
|
||||
bucketMetadata.URL = *c.targetURL
|
||||
bucketMetadata.Type = os.ModeDir
|
||||
c.mutex.Unlock()
|
||||
return bucketMetadata, nil
|
||||
}
|
||||
|
||||
func isAmazon(host string) bool {
|
||||
matchAmazon, _ := filepath.Match("*.s3*.amazonaws.com", host)
|
||||
return matchAmazon
|
||||
}
|
||||
|
||||
func isGoogle(host string) bool {
|
||||
matchGoogle, _ := filepath.Match("*.storage.googleapis.com", host)
|
||||
return matchGoogle
|
||||
}
|
||||
|
||||
// Figure out if the URL is of 'virtual host' style.
|
||||
// Currently only supported hosts with virtual style are Amazon S3 and Google Cloud Storage.
|
||||
func isVirtualHostStyle(host string) bool {
|
||||
return isAmazon(host) || isGoogle(host)
|
||||
}
|
||||
|
||||
// url2BucketAndObject gives bucketName and objectName from URL path.
|
||||
func (c *s3Client) url2BucketAndObject() (bucketName, objectName string) {
|
||||
path := c.targetURL.Path
|
||||
// Convert any virtual host styled requests.
|
||||
//
|
||||
// For the time being this check is introduced for S3,
|
||||
// If you have custom virtual styled hosts please.
|
||||
// List them below.
|
||||
if c.virtualStyle {
|
||||
var bucket string
|
||||
hostIndex := strings.Index(c.targetURL.Host, "s3")
|
||||
if hostIndex == -1 {
|
||||
hostIndex = strings.Index(c.targetURL.Host, "storage.googleapis")
|
||||
}
|
||||
if hostIndex > 0 {
|
||||
bucket = c.targetURL.Host[:hostIndex-1]
|
||||
path = string(c.targetURL.Separator) + bucket + c.targetURL.Path
|
||||
}
|
||||
}
|
||||
splits := strings.SplitN(path, string(c.targetURL.Separator), 3)
|
||||
switch len(splits) {
|
||||
case 0, 1:
|
||||
bucketName = ""
|
||||
objectName = ""
|
||||
case 2:
|
||||
bucketName = splits[1]
|
||||
objectName = ""
|
||||
case 3:
|
||||
bucketName = splits[1]
|
||||
objectName = splits[2]
|
||||
}
|
||||
return bucketName, objectName
|
||||
}
|
||||
|
||||
/// Bucket API operations.
|
||||
|
||||
// List - list at delimited path, if not recursive.
|
||||
func (c *s3Client) List(recursive, incomplete bool) <-chan *client.Content {
|
||||
c.mutex.Lock()
|
||||
defer c.mutex.Unlock()
|
||||
|
||||
contentCh := make(chan *client.Content)
|
||||
if incomplete {
|
||||
if recursive {
|
||||
go c.listIncompleteRecursiveInRoutine(contentCh)
|
||||
} else {
|
||||
go c.listIncompleteInRoutine(contentCh)
|
||||
}
|
||||
} else {
|
||||
if recursive {
|
||||
go c.listRecursiveInRoutine(contentCh)
|
||||
} else {
|
||||
go c.listInRoutine(contentCh)
|
||||
}
|
||||
}
|
||||
return contentCh
|
||||
}
|
||||
|
||||
func (c *s3Client) listIncompleteInRoutine(contentCh chan *client.Content) {
|
||||
defer close(contentCh)
|
||||
// get bucket and object from URL.
|
||||
b, o := c.url2BucketAndObject()
|
||||
switch {
|
||||
case b == "" && o == "":
|
||||
buckets, err := c.api.ListBuckets()
|
||||
if err != nil {
|
||||
contentCh <- &client.Content{
|
||||
Err: probe.NewError(err),
|
||||
}
|
||||
return
|
||||
}
|
||||
isRecursive := false
|
||||
for _, bucket := range buckets {
|
||||
for object := range c.api.ListIncompleteUploads(bucket.Name, o, isRecursive, nil) {
|
||||
if object.Err != nil {
|
||||
contentCh <- &client.Content{
|
||||
Err: probe.NewError(object.Err),
|
||||
}
|
||||
return
|
||||
}
|
||||
content := new(client.Content)
|
||||
url := *c.targetURL
|
||||
// Join bucket with - incoming object key.
|
||||
url.Path = filepath.Join(string(url.Separator), bucket.Name, object.Key)
|
||||
if c.virtualStyle {
|
||||
url.Path = filepath.Join(string(url.Separator), object.Key)
|
||||
}
|
||||
switch {
|
||||
case strings.HasSuffix(object.Key, string(c.targetURL.Separator)):
|
||||
// We need to keep the trailing Separator, do not use filepath.Join().
|
||||
content.URL = url
|
||||
content.Time = time.Now()
|
||||
content.Type = os.ModeDir
|
||||
default:
|
||||
content.URL = url
|
||||
content.Size = object.Size
|
||||
content.Time = object.Initiated
|
||||
content.Type = os.ModeTemporary
|
||||
}
|
||||
contentCh <- content
|
||||
}
|
||||
}
|
||||
default:
|
||||
isRecursive := false
|
||||
for object := range c.api.ListIncompleteUploads(b, o, isRecursive, nil) {
|
||||
if object.Err != nil {
|
||||
contentCh <- &client.Content{
|
||||
Err: probe.NewError(object.Err),
|
||||
}
|
||||
return
|
||||
}
|
||||
content := new(client.Content)
|
||||
url := *c.targetURL
|
||||
// Join bucket with - incoming object key.
|
||||
url.Path = filepath.Join(string(url.Separator), b, object.Key)
|
||||
if c.virtualStyle {
|
||||
url.Path = filepath.Join(string(url.Separator), object.Key)
|
||||
}
|
||||
switch {
|
||||
case strings.HasSuffix(object.Key, string(c.targetURL.Separator)):
|
||||
// We need to keep the trailing Separator, do not use filepath.Join().
|
||||
content.URL = url
|
||||
content.Time = time.Now()
|
||||
content.Type = os.ModeDir
|
||||
default:
|
||||
content.URL = url
|
||||
content.Size = object.Size
|
||||
content.Time = object.Initiated
|
||||
content.Type = os.ModeTemporary
|
||||
}
|
||||
contentCh <- content
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *s3Client) listIncompleteRecursiveInRoutine(contentCh chan *client.Content) {
|
||||
defer close(contentCh)
|
||||
// get bucket and object from URL.
|
||||
b, o := c.url2BucketAndObject()
|
||||
switch {
|
||||
case b == "" && o == "":
|
||||
buckets, err := c.api.ListBuckets()
|
||||
if err != nil {
|
||||
contentCh <- &client.Content{
|
||||
Err: probe.NewError(err),
|
||||
}
|
||||
return
|
||||
}
|
||||
isRecursive := true
|
||||
for _, bucket := range buckets {
|
||||
for object := range c.api.ListIncompleteUploads(bucket.Name, o, isRecursive, nil) {
|
||||
if object.Err != nil {
|
||||
contentCh <- &client.Content{
|
||||
Err: probe.NewError(object.Err),
|
||||
}
|
||||
return
|
||||
}
|
||||
url := *c.targetURL
|
||||
url.Path = filepath.Join(url.Path, bucket.Name, object.Key)
|
||||
content := new(client.Content)
|
||||
content.URL = url
|
||||
content.Size = object.Size
|
||||
content.Time = object.Initiated
|
||||
content.Type = os.ModeTemporary
|
||||
contentCh <- content
|
||||
}
|
||||
}
|
||||
default:
|
||||
isRecursive := true
|
||||
for object := range c.api.ListIncompleteUploads(b, o, isRecursive, nil) {
|
||||
if object.Err != nil {
|
||||
contentCh <- &client.Content{
|
||||
Err: probe.NewError(object.Err),
|
||||
}
|
||||
return
|
||||
}
|
||||
url := *c.targetURL
|
||||
// Join bucket and incoming object key.
|
||||
url.Path = filepath.Join(string(url.Separator), b, object.Key)
|
||||
if c.virtualStyle {
|
||||
url.Path = filepath.Join(string(url.Separator), object.Key)
|
||||
}
|
||||
content := new(client.Content)
|
||||
content.URL = url
|
||||
content.Size = object.Size
|
||||
content.Time = object.Initiated
|
||||
content.Type = os.ModeTemporary
|
||||
contentCh <- content
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *s3Client) listInRoutine(contentCh chan *client.Content) {
|
||||
defer close(contentCh)
|
||||
// get bucket and object from URL.
|
||||
b, o := c.url2BucketAndObject()
|
||||
switch {
|
||||
case b == "" && o == "":
|
||||
buckets, err := c.api.ListBuckets()
|
||||
if err != nil {
|
||||
contentCh <- &client.Content{
|
||||
Err: probe.NewError(err),
|
||||
}
|
||||
return
|
||||
}
|
||||
for _, bucket := range buckets {
|
||||
url := *c.targetURL
|
||||
url.Path = filepath.Join(url.Path, bucket.Name)
|
||||
content := new(client.Content)
|
||||
content.URL = url
|
||||
content.Size = 0
|
||||
content.Time = bucket.CreationDate
|
||||
content.Type = os.ModeDir
|
||||
contentCh <- content
|
||||
}
|
||||
case b != "" && !strings.HasSuffix(c.targetURL.Path, string(c.targetURL.Separator)) && o == "":
|
||||
e := c.api.BucketExists(b)
|
||||
if e != nil {
|
||||
contentCh <- &client.Content{
|
||||
Err: probe.NewError(e),
|
||||
}
|
||||
}
|
||||
content := new(client.Content)
|
||||
content.URL = *c.targetURL
|
||||
content.Type = os.ModeDir
|
||||
contentCh <- content
|
||||
default:
|
||||
metadata, e := c.api.StatObject(b, o)
|
||||
switch e.(type) {
|
||||
case nil:
|
||||
content := new(client.Content)
|
||||
content.URL = *c.targetURL
|
||||
content.Time = metadata.LastModified
|
||||
content.Size = metadata.Size
|
||||
content.Type = os.FileMode(0664)
|
||||
contentCh <- content
|
||||
default:
|
||||
isRecursive := false
|
||||
for object := range c.api.ListObjects(b, o, isRecursive, nil) {
|
||||
if object.Err != nil {
|
||||
contentCh <- &client.Content{
|
||||
Err: probe.NewError(object.Err),
|
||||
}
|
||||
return
|
||||
}
|
||||
content := new(client.Content)
|
||||
url := *c.targetURL
|
||||
// Join bucket and incoming object key.
|
||||
url.Path = filepath.Join(string(url.Separator), b, object.Key)
|
||||
if c.virtualStyle {
|
||||
url.Path = filepath.Join(string(url.Separator), object.Key)
|
||||
}
|
||||
switch {
|
||||
case strings.HasSuffix(object.Key, string(c.targetURL.Separator)):
|
||||
// We need to keep the trailing Separator, do not use filepath.Join().
|
||||
content.URL = url
|
||||
content.Time = time.Now()
|
||||
content.Type = os.ModeDir
|
||||
default:
|
||||
content.URL = url
|
||||
content.Size = object.Size
|
||||
content.Time = object.LastModified
|
||||
content.Type = os.FileMode(0664)
|
||||
}
|
||||
contentCh <- content
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *s3Client) listRecursiveInRoutine(contentCh chan *client.Content) {
|
||||
defer close(contentCh)
|
||||
// get bucket and object from URL.
|
||||
b, o := c.url2BucketAndObject()
|
||||
switch {
|
||||
case b == "" && o == "":
|
||||
buckets, err := c.api.ListBuckets()
|
||||
if err != nil {
|
||||
contentCh <- &client.Content{
|
||||
Err: probe.NewError(err),
|
||||
}
|
||||
return
|
||||
}
|
||||
for _, bucket := range buckets {
|
||||
bucketURL := *c.targetURL
|
||||
bucketURL.Path = filepath.Join(bucketURL.Path, bucket.Name)
|
||||
contentCh <- &client.Content{
|
||||
URL: bucketURL,
|
||||
Type: os.ModeDir,
|
||||
Time: bucket.CreationDate,
|
||||
}
|
||||
isRecursive := true
|
||||
for object := range c.api.ListObjects(bucket.Name, o, isRecursive, nil) {
|
||||
if object.Err != nil {
|
||||
contentCh <- &client.Content{
|
||||
Err: probe.NewError(object.Err),
|
||||
}
|
||||
continue
|
||||
}
|
||||
content := new(client.Content)
|
||||
objectURL := *c.targetURL
|
||||
objectURL.Path = filepath.Join(objectURL.Path, bucket.Name, object.Key)
|
||||
content.URL = objectURL
|
||||
content.Size = object.Size
|
||||
content.Time = object.LastModified
|
||||
content.Type = os.FileMode(0664)
|
||||
contentCh <- content
|
||||
}
|
||||
}
|
||||
default:
|
||||
isRecursive := true
|
||||
for object := range c.api.ListObjects(b, o, isRecursive, nil) {
|
||||
if object.Err != nil {
|
||||
contentCh <- &client.Content{
|
||||
Err: probe.NewError(object.Err),
|
||||
}
|
||||
continue
|
||||
}
|
||||
content := new(client.Content)
|
||||
url := *c.targetURL
|
||||
// Join bucket and incoming object key.
|
||||
url.Path = filepath.Join(string(url.Separator), b, object.Key)
|
||||
// If virtualStyle replace the url.Path back.
|
||||
if c.virtualStyle {
|
||||
url.Path = filepath.Join(string(url.Separator), object.Key)
|
||||
}
|
||||
content.URL = url
|
||||
content.Size = object.Size
|
||||
content.Time = object.LastModified
|
||||
content.Type = os.FileMode(0664)
|
||||
contentCh <- content
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ShareDownload - get a usable presigned object url to share.
|
||||
func (c *s3Client) ShareDownload(expires time.Duration) (string, *probe.Error) {
|
||||
bucket, object := c.url2BucketAndObject()
|
||||
presignedURL, e := c.api.PresignedGetObject(bucket, object, expires)
|
||||
if e != nil {
|
||||
return "", probe.NewError(e)
|
||||
}
|
||||
return presignedURL, nil
|
||||
}
|
||||
|
||||
// ShareUpload - get data for presigned post http form upload.
|
||||
func (c *s3Client) ShareUpload(isRecursive bool, expires time.Duration, contentType string) (map[string]string, *probe.Error) {
|
||||
bucket, object := c.url2BucketAndObject()
|
||||
p := minio.NewPostPolicy()
|
||||
if e := p.SetExpires(time.Now().UTC().Add(expires)); e != nil {
|
||||
return nil, probe.NewError(e)
|
||||
}
|
||||
if strings.TrimSpace(contentType) != "" || contentType != "" {
|
||||
// No need to verify for error here, since we have stripped out spaces.
|
||||
p.SetContentType(contentType)
|
||||
}
|
||||
if e := p.SetBucket(bucket); e != nil {
|
||||
return nil, probe.NewError(e)
|
||||
}
|
||||
if isRecursive {
|
||||
if e := p.SetKeyStartsWith(object); e != nil {
|
||||
return nil, probe.NewError(e)
|
||||
}
|
||||
} else {
|
||||
if e := p.SetKey(object); e != nil {
|
||||
return nil, probe.NewError(e)
|
||||
}
|
||||
}
|
||||
m, e := c.api.PresignedPostPolicy(p)
|
||||
return m, probe.NewError(e)
|
||||
}
|
||||
@@ -1,262 +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 s3
|
||||
|
||||
// bucketHandler is an http.Handler that verifies bucket responses and validates incoming requests
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/minio/mc/pkg/client"
|
||||
|
||||
. "gopkg.in/check.v1"
|
||||
)
|
||||
|
||||
type bucketHandler struct {
|
||||
resource string
|
||||
}
|
||||
|
||||
func (h bucketHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case r.Method == "GET":
|
||||
// Handler for incoming getBucketLocation request.
|
||||
if _, ok := r.URL.Query()["location"]; ok {
|
||||
response := []byte("<LocationConstraint xmlns=\"http://doc.s3.amazonaws.com/2006-03-01\"></LocationConstraint>")
|
||||
w.Header().Set("Content-Length", strconv.Itoa(len(response)))
|
||||
w.Write(response)
|
||||
return
|
||||
}
|
||||
switch {
|
||||
case r.URL.Path == "/":
|
||||
// Handler for incoming ListBuckets request.
|
||||
response := []byte("<ListAllMyBucketsResult xmlns=\"http://doc.s3.amazonaws.com/2006-03-01\"><Buckets><Bucket><Name>bucket</Name><CreationDate>2015-05-20T23:05:09.230Z</CreationDate></Bucket></Buckets><Owner><ID>minio</ID><DisplayName>minio</DisplayName></Owner></ListAllMyBucketsResult>")
|
||||
w.Header().Set("Content-Length", strconv.Itoa(len(response)))
|
||||
w.Write(response)
|
||||
case r.URL.Path == "/bucket/":
|
||||
// Handler for incoming ListObjects request.
|
||||
response := []byte("<ListBucketResult xmlns=\"http://doc.s3.amazonaws.com/2006-03-01\"><Contents><ETag>259d04a13802ae09c7e41be50ccc6baa</ETag><Key>object</Key><LastModified>2015-05-21T18:24:21.097Z</LastModified><Size>22061</Size><Owner><ID>minio</ID><DisplayName>minio</DisplayName></Owner><StorageClass>STANDARD</StorageClass></Contents><Delimiter></Delimiter><EncodingType></EncodingType><IsTruncated>false</IsTruncated><Marker></Marker><MaxKeys>1000</MaxKeys><Name>testbucket</Name><NextMarker></NextMarker><Prefix></Prefix></ListBucketResult>")
|
||||
w.Header().Set("Content-Length", strconv.Itoa(len(response)))
|
||||
w.Write(response)
|
||||
}
|
||||
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)
|
||||
}
|
||||
case r.Method == "HEAD":
|
||||
switch {
|
||||
case r.URL.Path == h.resource:
|
||||
w.WriteHeader(http.StatusOK)
|
||||
default:
|
||||
w.WriteHeader(http.StatusForbidden)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// objectHandler is an http.Handler that verifies object responses and validates incoming requests
|
||||
type objectHandler struct {
|
||||
resource string
|
||||
data []byte
|
||||
}
|
||||
|
||||
func (h objectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case r.Method == "PUT":
|
||||
// Handler for PUT object request.
|
||||
length, e := strconv.Atoi(r.Header.Get("Content-Length"))
|
||||
if e != nil {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
var buffer bytes.Buffer
|
||||
if _, e = io.CopyN(&buffer, r.Body, int64(length)); e != nil {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
if !bytes.Equal(h.data, buffer.Bytes()) {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.Header().Set("ETag", "9af2f8218b150c351ad802c6f3d66abe")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
case r.Method == "HEAD":
|
||||
// Handler for Stat object request.
|
||||
if r.URL.Path != h.resource {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Length", strconv.Itoa(len(h.data)))
|
||||
w.Header().Set("Last-Modified", time.Now().UTC().Format(http.TimeFormat))
|
||||
w.Header().Set("ETag", "9af2f8218b150c351ad802c6f3d66abe")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
case r.Method == "POST":
|
||||
// Handler for multipart upload request.
|
||||
if _, ok := r.URL.Query()["uploads"]; ok {
|
||||
if r.URL.Path == h.resource {
|
||||
response := []byte("<InitiateMultipartUploadResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\"><Bucket>bucket</Bucket><Key>object</Key><UploadId>EXAMPLEJZ6e0YupT2h66iePQCc9IEbYbDUy4RTpMeoSMLPRp8Z5o1u8feSRonpvnWsKKG35tI2LB9VDPiCgTy.Gq2VxQLYjrue4Nq.NBdqI-</UploadId></InitiateMultipartUploadResult>")
|
||||
w.Header().Set("Content-Length", strconv.Itoa(len(response)))
|
||||
w.Write(response)
|
||||
return
|
||||
}
|
||||
}
|
||||
if _, ok := r.URL.Query()["uploadId"]; ok {
|
||||
if r.URL.Path == h.resource {
|
||||
response := []byte("<CompleteMultipartUploadResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\"><Location>http://bucket.s3.amazonaws.com/object</Location><Bucket>bucket</Bucket><Key>object</Key><ETag>\"3858f62230ac3c915f300c664312c11f-9\"</ETag></CompleteMultipartUploadResult>")
|
||||
w.Header().Set("Content-Length", strconv.Itoa(len(response)))
|
||||
w.Write(response)
|
||||
return
|
||||
}
|
||||
}
|
||||
if r.URL.Path != h.resource {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
case r.Method == "GET":
|
||||
// Handler for get bucket location request.
|
||||
if _, ok := r.URL.Query()["location"]; ok {
|
||||
response := []byte("<LocationConstraint xmlns=\"http://doc.s3.amazonaws.com/2006-03-01\"></LocationConstraint>")
|
||||
w.Header().Set("Content-Length", strconv.Itoa(len(response)))
|
||||
w.Write(response)
|
||||
return
|
||||
}
|
||||
// Handler for list multipart upload request.
|
||||
if _, ok := r.URL.Query()["uploads"]; ok {
|
||||
if r.URL.Path == "/bucket/" {
|
||||
response := []byte("<ListMultipartUploadsResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\"><Bucket>bucket</Bucket><KeyMarker/><UploadIdMarker/><NextKeyMarker/><NextUploadIdMarker/><EncodingType/><MaxUploads>1000</MaxUploads><IsTruncated>false</IsTruncated><Prefix/><Delimiter/></ListMultipartUploadsResult>")
|
||||
w.Header().Set("Content-Length", strconv.Itoa(len(response)))
|
||||
w.Write(response)
|
||||
return
|
||||
}
|
||||
}
|
||||
if r.URL.Path != h.resource {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Length", strconv.Itoa(len(h.data)))
|
||||
w.Header().Set("Last-Modified", time.Now().UTC().Format(http.TimeFormat))
|
||||
w.Header().Set("ETag", "9af2f8218b150c351ad802c6f3d66abe")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
io.Copy(w, bytes.NewReader(h.data))
|
||||
}
|
||||
}
|
||||
|
||||
func Test(t *testing.T) { TestingT(t) }
|
||||
|
||||
type MySuite struct{}
|
||||
|
||||
var _ = Suite(&MySuite{})
|
||||
|
||||
// Test bucket operations.
|
||||
func (s *MySuite) TestBucketOperations(c *C) {
|
||||
bucket := bucketHandler(bucketHandler{
|
||||
resource: "/bucket/",
|
||||
})
|
||||
server := httptest.NewServer(bucket)
|
||||
defer server.Close()
|
||||
|
||||
conf := new(client.Config)
|
||||
conf.HostURL = server.URL + bucket.resource
|
||||
conf.AccessKey = "WLGDGYAQYIGI833EV05A"
|
||||
conf.SecretKey = "BYvgJM101sHngl2uzjXS/OBF/aMxAN06JrJ3qJlF"
|
||||
conf.Signature = "S3v4"
|
||||
s3c, err := New(conf)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
err = s3c.MakeBucket("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)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
for content := range s3c.List(false, false) {
|
||||
c.Assert(content.Err, IsNil)
|
||||
c.Assert(content.Type.IsDir(), Equals, true)
|
||||
}
|
||||
|
||||
conf.HostURL = server.URL + "/bucket"
|
||||
s3c, err = New(conf)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
for content := range s3c.List(false, false) {
|
||||
c.Assert(content.Err, IsNil)
|
||||
c.Assert(content.Type.IsDir(), Equals, true)
|
||||
}
|
||||
|
||||
conf.HostURL = server.URL + "/bucket/"
|
||||
s3c, err = New(conf)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
for content := range s3c.List(false, false) {
|
||||
c.Assert(content.Err, IsNil)
|
||||
c.Assert(content.Type.IsRegular(), Equals, true)
|
||||
}
|
||||
}
|
||||
|
||||
// Test all object operations.
|
||||
func (s *MySuite) TestObjectOperations(c *C) {
|
||||
object := objectHandler(objectHandler{
|
||||
resource: "/bucket/object",
|
||||
data: []byte("Hello, World"),
|
||||
})
|
||||
server := httptest.NewServer(object)
|
||||
defer server.Close()
|
||||
|
||||
conf := new(client.Config)
|
||||
conf.HostURL = server.URL + object.resource
|
||||
conf.AccessKey = "WLGDGYAQYIGI833EV05A"
|
||||
conf.SecretKey = "BYvgJM101sHngl2uzjXS/OBF/aMxAN06JrJ3qJlF"
|
||||
conf.Signature = "S3v4"
|
||||
s3c, err := New(conf)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
var reader io.Reader
|
||||
reader = bytes.NewReader(object.data)
|
||||
n, err := s3c.Put(reader, int64(len(object.data)), "application/octet-stream", nil)
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(n, Equals, int64(len(object.data)))
|
||||
|
||||
content, err := s3c.Stat()
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(content.Size, Equals, int64(len(object.data)))
|
||||
c.Assert(content.Type.IsRegular(), Equals, true)
|
||||
|
||||
reader, err = s3c.Get()
|
||||
var buffer bytes.Buffer
|
||||
{
|
||||
_, err := io.Copy(&buffer, reader)
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(buffer.Bytes(), DeepEquals, object.data)
|
||||
}
|
||||
}
|
||||
@@ -1,75 +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 s3
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"strings"
|
||||
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/mc/pkg/httptracer"
|
||||
)
|
||||
|
||||
// TraceV2 - tracing structure
|
||||
type TraceV2 struct{}
|
||||
|
||||
// NewTraceV2 - initialize Trace structure
|
||||
func NewTraceV2() httptracer.HTTPTracer {
|
||||
return TraceV2{}
|
||||
}
|
||||
|
||||
// Request - Trace HTTP Request
|
||||
func (t TraceV2) Request(req *http.Request) (err error) {
|
||||
origAuth := req.Header.Get("Authorization")
|
||||
|
||||
if strings.TrimSpace(origAuth) != "" {
|
||||
// Authorization (S3 v2 signature) Format:
|
||||
// Authorization: AWS AKIAJVA5BMMU2RHO6IO1:Y10YHUZ0DTUterAUI6w3XKX7Iqk=
|
||||
|
||||
// Set a temporary redacted auth
|
||||
req.Header.Set("Authorization", "AWS **REDACTED**:**REDACTED**")
|
||||
|
||||
var reqTrace []byte
|
||||
reqTrace, err = httputil.DumpRequestOut(req, false) // Only display header
|
||||
if err == nil {
|
||||
console.Debug(string(reqTrace))
|
||||
}
|
||||
|
||||
// Undo
|
||||
req.Header.Set("Authorization", origAuth)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// Response - Trace HTTP Response
|
||||
func (t TraceV2) Response(res *http.Response) (err error) {
|
||||
var resTrace []byte
|
||||
// For errors we make sure to dump response body as well.
|
||||
if res.StatusCode != http.StatusOK &&
|
||||
res.StatusCode != http.StatusPartialContent &&
|
||||
res.StatusCode != http.StatusNoContent {
|
||||
resTrace, err = httputil.DumpResponse(res, true)
|
||||
} else {
|
||||
// Only display header
|
||||
resTrace, err = httputil.DumpResponse(res, false)
|
||||
}
|
||||
if err == nil {
|
||||
console.Debug(string(resTrace))
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -1,84 +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 s3
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/mc/pkg/httptracer"
|
||||
)
|
||||
|
||||
// TraceV4 - tracing structure
|
||||
type TraceV4 struct{}
|
||||
|
||||
// NewTraceV4 - initialize Trace structure
|
||||
func NewTraceV4() httptracer.HTTPTracer {
|
||||
return TraceV4{}
|
||||
}
|
||||
|
||||
// Request - Trace HTTP Request
|
||||
func (t TraceV4) Request(req *http.Request) (err error) {
|
||||
origAuth := req.Header.Get("Authorization")
|
||||
|
||||
if strings.TrimSpace(origAuth) != "" {
|
||||
// Authorization (S3 v4 signature) Format:
|
||||
// Authorization: AWS4-HMAC-SHA256 Credential=AKIAJNACEGBGMXBHLEZA/20150524/us-east-1/s3/aws4_request, SignedHeaders=host;x-amz-content-sha256;x-amz-date, Signature=bbfaa693c626021bcb5f911cd898a1a30206c1fad6bad1e0eb89e282173bd24c
|
||||
|
||||
// Strip out accessKeyID from: Credential=<access-key-id>/<date>/<aws-region>/<aws-service>/aws4_request
|
||||
regCred := regexp.MustCompile("Credential=([A-Z0-9]+)/")
|
||||
newAuth := regCred.ReplaceAllString(origAuth, "Credential=**REDACTED**/")
|
||||
|
||||
// Strip out 256-bit signature from: Signature=<256-bit signature>
|
||||
regSign := regexp.MustCompile("Signature=([[0-9a-f]+)")
|
||||
newAuth = regSign.ReplaceAllString(newAuth, "Signature=**REDACTED**")
|
||||
|
||||
// Set a temporary redacted auth
|
||||
req.Header.Set("Authorization", newAuth)
|
||||
|
||||
var reqTrace []byte
|
||||
reqTrace, err = httputil.DumpRequestOut(req, false) // Only display header
|
||||
if err == nil {
|
||||
console.Debug(string(reqTrace))
|
||||
}
|
||||
|
||||
// Undo
|
||||
req.Header.Set("Authorization", origAuth)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// Response - Trace HTTP Response
|
||||
func (t TraceV4) Response(res *http.Response) (err error) {
|
||||
var resTrace []byte
|
||||
// For errors we make sure to dump response body as well.
|
||||
if res.StatusCode != http.StatusOK &&
|
||||
res.StatusCode != http.StatusPartialContent &&
|
||||
res.StatusCode != http.StatusNoContent {
|
||||
resTrace, err = httputil.DumpResponse(res, true)
|
||||
} else {
|
||||
// Only display header
|
||||
resTrace, err = httputil.DumpResponse(res, false)
|
||||
}
|
||||
if err == nil {
|
||||
console.Debug(string(resTrace))
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -1,162 +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 client
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"runtime"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// URL client url structure
|
||||
type URL struct {
|
||||
Type URLType
|
||||
Scheme string
|
||||
Host string
|
||||
Path string
|
||||
SchemeSeparator string
|
||||
Separator rune
|
||||
}
|
||||
|
||||
// URLType - enum of different url types
|
||||
type URLType int
|
||||
|
||||
// enum types
|
||||
const (
|
||||
Object = 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+-.]*)
|
||||
// If so, return scheme, path; else return "", rawurl.
|
||||
func getScheme(rawurl string) (scheme, path string) {
|
||||
urlSplits := strings.Split(rawurl, "://")
|
||||
if len(urlSplits) == 2 {
|
||||
scheme, uri := urlSplits[0], "//"+urlSplits[1]
|
||||
// ignore numbers in scheme
|
||||
validScheme := regexp.MustCompile("^[a-zA-Z]+$")
|
||||
if uri != "" {
|
||||
if validScheme.MatchString(scheme) {
|
||||
return scheme, uri
|
||||
}
|
||||
}
|
||||
}
|
||||
return "", rawurl
|
||||
}
|
||||
|
||||
// Assuming s is of the form [s delimiter s].
|
||||
// If so, return s, [delimiter]s or return s, s if cutdelimiter == true
|
||||
// If no delimiter found return s, "".
|
||||
func splitSpecial(s string, delimiter string, cutdelimiter bool) (string, string) {
|
||||
i := strings.Index(s, delimiter)
|
||||
if i < 0 {
|
||||
// if delimiter not found return as is.
|
||||
return s, ""
|
||||
}
|
||||
// if delimiter should be removed, remove it.
|
||||
if cutdelimiter {
|
||||
return s[0:i], s[i+len(delimiter):]
|
||||
}
|
||||
// return split strings with delimiter
|
||||
return s[0:i], s[i:]
|
||||
}
|
||||
|
||||
// getHost - extract host from authority string, we do not support ftp style username@ yet.
|
||||
func getHost(authority string) (host string) {
|
||||
i := strings.LastIndex(authority, "@")
|
||||
if i >= 0 {
|
||||
// TODO support, username@password style userinfo, useful for ftp support.
|
||||
return
|
||||
}
|
||||
return authority
|
||||
}
|
||||
|
||||
// NewURL returns an abstracted URL for filesystems and object storage.
|
||||
func NewURL(urlStr string) *URL {
|
||||
scheme, rest := getScheme(urlStr)
|
||||
rest, _ = splitSpecial(rest, "?", true)
|
||||
if strings.HasPrefix(rest, "//") {
|
||||
// if rest has '//' prefix, skip them
|
||||
var authority string
|
||||
authority, rest = splitSpecial(rest[2:], "/", false)
|
||||
if rest == "" {
|
||||
rest = "/"
|
||||
}
|
||||
host := getHost(authority)
|
||||
if host != "" && (scheme == "http" || scheme == "https") {
|
||||
return &URL{
|
||||
Scheme: scheme,
|
||||
Type: Object,
|
||||
Host: host,
|
||||
Path: rest,
|
||||
SchemeSeparator: "://",
|
||||
Separator: '/',
|
||||
}
|
||||
}
|
||||
}
|
||||
return &URL{
|
||||
Type: Filesystem,
|
||||
Path: rest,
|
||||
Separator: filepath.Separator,
|
||||
}
|
||||
}
|
||||
|
||||
// JoinURLs join two input urls and returns a url
|
||||
func JoinURLs(url1, url2 *URL) *URL {
|
||||
var url1Path, url2Path string
|
||||
url1Path = filepath.ToSlash(url1.Path)
|
||||
url2Path = filepath.ToSlash(url2.Path)
|
||||
if strings.HasSuffix(url1Path, "/") {
|
||||
url1.Path = url1Path + strings.TrimPrefix(url2Path, "/")
|
||||
} else {
|
||||
url1.Path = url1Path + "/" + strings.TrimPrefix(url2Path, "/")
|
||||
}
|
||||
return url1
|
||||
}
|
||||
|
||||
// String convert URL into its canonical form.
|
||||
func (u URL) String() string {
|
||||
var buf bytes.Buffer
|
||||
// if fileystem 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 {
|
||||
buf.WriteString(u.Scheme)
|
||||
buf.WriteByte(':')
|
||||
buf.WriteString("//")
|
||||
if h := u.Host; h != "" {
|
||||
buf.WriteString(h)
|
||||
}
|
||||
switch runtime.GOOS {
|
||||
case "windows":
|
||||
if u.Path != "" && u.Path[0] != '\\' && u.Host != "" && u.Path[0] != '/' {
|
||||
buf.WriteByte('/')
|
||||
}
|
||||
buf.WriteString(strings.Replace(u.Path, "\\", "/", -1))
|
||||
default:
|
||||
if u.Path != "" && u.Path[0] != '/' && u.Host != "" {
|
||||
buf.WriteByte('/')
|
||||
}
|
||||
buf.WriteString(u.Path)
|
||||
}
|
||||
}
|
||||
return buf.String()
|
||||
}
|
||||
@@ -1,355 +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 console
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"sync"
|
||||
|
||||
"path/filepath"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/mattn/go-isatty"
|
||||
"github.com/shiena/ansicolor"
|
||||
)
|
||||
|
||||
var (
|
||||
// DebugPrint enables/disables console debug printing.
|
||||
DebugPrint = false
|
||||
|
||||
// Used by the caller to print multiple lines atomically. Exposed by Lock/Unlock methods.
|
||||
publicMutex = &sync.Mutex{}
|
||||
// Used internally by console.
|
||||
privateMutex = &sync.Mutex{}
|
||||
|
||||
stderrColoredOutput = ansicolor.NewAnsiColorWriter(os.Stderr)
|
||||
|
||||
// Print prints a message.
|
||||
Print = func(data ...interface{}) {
|
||||
consolePrint("Print", Theme["Print"], data...)
|
||||
return
|
||||
}
|
||||
|
||||
// PrintC prints a message with color.
|
||||
PrintC = func(data ...interface{}) {
|
||||
consolePrint("PrintC", Theme["PrintC"], data...)
|
||||
return
|
||||
}
|
||||
|
||||
// Printf prints a formatted message.
|
||||
Printf = func(format string, data ...interface{}) {
|
||||
consolePrintf("Print", Theme["Print"], format, data...)
|
||||
return
|
||||
}
|
||||
|
||||
// Println prints a message with a newline.
|
||||
Println = func(data ...interface{}) {
|
||||
consolePrintln("Print", Theme["Print"], data...)
|
||||
return
|
||||
}
|
||||
|
||||
// Fatal print a error message and exit.
|
||||
Fatal = func(data ...interface{}) {
|
||||
consolePrint("Fatal", Theme["Fatal"], data...)
|
||||
os.Exit(1)
|
||||
return
|
||||
}
|
||||
|
||||
// Fatalf print a error message with a format specified and exit.
|
||||
Fatalf = func(format string, data ...interface{}) {
|
||||
consolePrintf("Fatal", Theme["Fatal"], format, data...)
|
||||
os.Exit(1)
|
||||
return
|
||||
}
|
||||
|
||||
// Fatalln print a error message with a new line and exit.
|
||||
Fatalln = func(data ...interface{}) {
|
||||
consolePrintln("Fatal", Theme["Fatal"], data...)
|
||||
os.Exit(1)
|
||||
return
|
||||
}
|
||||
|
||||
// Error prints a error message.
|
||||
Error = func(data ...interface{}) {
|
||||
consolePrint("Error", Theme["Error"], data...)
|
||||
return
|
||||
}
|
||||
|
||||
// Errorf print a error message with a format specified.
|
||||
Errorf = func(format string, data ...interface{}) {
|
||||
consolePrintf("Error", Theme["Error"], format, data...)
|
||||
return
|
||||
}
|
||||
|
||||
// Errorln prints a error message with a new line.
|
||||
Errorln = func(data ...interface{}) {
|
||||
consolePrintln("Error", Theme["Error"], data...)
|
||||
return
|
||||
}
|
||||
|
||||
// Info prints a informational message.
|
||||
Info = func(data ...interface{}) {
|
||||
consolePrint("Info", Theme["Info"], data...)
|
||||
return
|
||||
}
|
||||
|
||||
// Infof prints a informational message in custom format.
|
||||
Infof = func(format string, data ...interface{}) {
|
||||
consolePrintf("Info", Theme["Info"], format, data...)
|
||||
return
|
||||
}
|
||||
|
||||
// Infoln prints a informational message with a new line.
|
||||
Infoln = func(data ...interface{}) {
|
||||
consolePrintln("Info", Theme["Info"], data...)
|
||||
return
|
||||
}
|
||||
|
||||
// Debug prints a debug message without a new line
|
||||
// Debug prints a debug message.
|
||||
Debug = func(data ...interface{}) {
|
||||
if DebugPrint {
|
||||
consolePrint("Debug", Theme["Debug"], data...)
|
||||
}
|
||||
}
|
||||
|
||||
// Debugf prints a debug message with a new line.
|
||||
Debugf = func(format string, data ...interface{}) {
|
||||
if DebugPrint {
|
||||
consolePrintf("Debug", Theme["Debug"], format, data...)
|
||||
}
|
||||
}
|
||||
|
||||
// Debugln prints a debug message with a new line.
|
||||
Debugln = func(data ...interface{}) {
|
||||
if DebugPrint {
|
||||
consolePrintln("Debug", Theme["Debug"], data...)
|
||||
}
|
||||
}
|
||||
|
||||
// Colorize prints message in a colorized form, dictated by the corresponding tag argument.
|
||||
Colorize = func(tag string, data interface{}) string {
|
||||
if isatty.IsTerminal(os.Stdout.Fd()) {
|
||||
colorized, ok := Theme[tag]
|
||||
if ok {
|
||||
return colorized.SprintFunc()(data)
|
||||
} // else: No theme found. Return as string.
|
||||
}
|
||||
return fmt.Sprint(data)
|
||||
}
|
||||
|
||||
// Eraseline Print in new line and adjust to top so that we don't print over the ongoing progress bar.
|
||||
Eraseline = func() {
|
||||
consolePrintf("Print", Theme["Print"], "%c[2K\n", 27)
|
||||
consolePrintf("Print", Theme["Print"], "%c[A", 27)
|
||||
}
|
||||
)
|
||||
|
||||
// wrap around standard fmt functions.
|
||||
// consolePrint prints a message prefixed with message type and program name.
|
||||
func consolePrint(tag string, c *color.Color, a ...interface{}) {
|
||||
privateMutex.Lock()
|
||||
defer privateMutex.Unlock()
|
||||
|
||||
switch tag {
|
||||
case "Debug":
|
||||
// if no arguments are given do not invoke debug printer.
|
||||
if len(a) == 0 {
|
||||
return
|
||||
}
|
||||
output := color.Output
|
||||
color.Output = stderrColoredOutput
|
||||
if isatty.IsTerminal(os.Stderr.Fd()) {
|
||||
c.Print(ProgramName() + ": <DEBUG> ")
|
||||
c.Print(a...)
|
||||
} else {
|
||||
fmt.Fprint(color.Output, ProgramName()+": <DEBUG> ")
|
||||
fmt.Fprint(color.Output, a...)
|
||||
}
|
||||
color.Output = output
|
||||
case "Fatal":
|
||||
fallthrough
|
||||
case "Error":
|
||||
// if no arguments are given do not invoke fatal and error printer.
|
||||
if len(a) == 0 {
|
||||
return
|
||||
}
|
||||
output := color.Output
|
||||
color.Output = stderrColoredOutput
|
||||
if isatty.IsTerminal(os.Stderr.Fd()) {
|
||||
c.Print(ProgramName() + ": <ERROR> ")
|
||||
c.Print(a...)
|
||||
} else {
|
||||
fmt.Fprint(color.Output, ProgramName()+": <ERROR> ")
|
||||
fmt.Fprint(color.Output, a...)
|
||||
}
|
||||
color.Output = output
|
||||
case "Info":
|
||||
// if no arguments are given do not invoke info printer.
|
||||
if len(a) == 0 {
|
||||
return
|
||||
}
|
||||
if isatty.IsTerminal(os.Stdout.Fd()) {
|
||||
c.Print(ProgramName() + ": ")
|
||||
c.Print(a...)
|
||||
} else {
|
||||
fmt.Fprint(color.Output, ProgramName()+": ")
|
||||
fmt.Fprint(color.Output, a...)
|
||||
}
|
||||
default:
|
||||
if isatty.IsTerminal(os.Stdout.Fd()) {
|
||||
c.Print(a...)
|
||||
} else {
|
||||
fmt.Fprint(color.Output, a...)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// consolePrintf - same as print with a new line.
|
||||
func consolePrintf(tag string, c *color.Color, format string, a ...interface{}) {
|
||||
privateMutex.Lock()
|
||||
defer privateMutex.Unlock()
|
||||
|
||||
switch tag {
|
||||
case "Debug":
|
||||
// if no arguments are given do not invoke debug printer.
|
||||
if len(a) == 0 {
|
||||
return
|
||||
}
|
||||
output := color.Output
|
||||
color.Output = stderrColoredOutput
|
||||
if isatty.IsTerminal(os.Stderr.Fd()) {
|
||||
c.Print(ProgramName() + ": <DEBUG> ")
|
||||
c.Printf(format, a...)
|
||||
} else {
|
||||
fmt.Fprint(color.Output, ProgramName()+": <DEBUG> ")
|
||||
fmt.Fprintf(color.Output, format, a...)
|
||||
}
|
||||
color.Output = output
|
||||
case "Fatal":
|
||||
fallthrough
|
||||
case "Error":
|
||||
// if no arguments are given do not invoke fatal and error printer.
|
||||
if len(a) == 0 {
|
||||
return
|
||||
}
|
||||
output := color.Output
|
||||
color.Output = stderrColoredOutput
|
||||
if isatty.IsTerminal(os.Stderr.Fd()) {
|
||||
c.Print(ProgramName() + ": <ERROR> ")
|
||||
c.Printf(format, a...)
|
||||
} else {
|
||||
fmt.Fprint(color.Output, ProgramName()+": <ERROR> ")
|
||||
fmt.Fprintf(color.Output, format, a...)
|
||||
}
|
||||
color.Output = output
|
||||
case "Info":
|
||||
// if no arguments are given do not invoke info printer.
|
||||
if len(a) == 0 {
|
||||
return
|
||||
}
|
||||
if isatty.IsTerminal(os.Stdout.Fd()) {
|
||||
c.Print(ProgramName() + ": ")
|
||||
c.Printf(format, a...)
|
||||
} else {
|
||||
fmt.Fprint(color.Output, ProgramName()+": ")
|
||||
fmt.Fprintf(color.Output, format, a...)
|
||||
}
|
||||
default:
|
||||
if isatty.IsTerminal(os.Stdout.Fd()) {
|
||||
c.Printf(format, a...)
|
||||
} else {
|
||||
fmt.Fprintf(color.Output, format, a...)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// consolePrintln - same as print with a new line.
|
||||
func consolePrintln(tag string, c *color.Color, a ...interface{}) {
|
||||
privateMutex.Lock()
|
||||
defer privateMutex.Unlock()
|
||||
|
||||
switch tag {
|
||||
case "Debug":
|
||||
// if no arguments are given do not invoke debug printer.
|
||||
if len(a) == 0 {
|
||||
return
|
||||
}
|
||||
output := color.Output
|
||||
color.Output = stderrColoredOutput
|
||||
if isatty.IsTerminal(os.Stderr.Fd()) {
|
||||
c.Print(ProgramName() + ": <DEBUG> ")
|
||||
c.Println(a...)
|
||||
} else {
|
||||
fmt.Fprint(color.Output, ProgramName()+": <DEBUG> ")
|
||||
fmt.Fprintln(color.Output, a...)
|
||||
}
|
||||
color.Output = output
|
||||
case "Fatal":
|
||||
fallthrough
|
||||
case "Error":
|
||||
// if no arguments are given do not invoke fatal and error printer.
|
||||
if len(a) == 0 {
|
||||
return
|
||||
}
|
||||
output := color.Output
|
||||
color.Output = stderrColoredOutput
|
||||
if isatty.IsTerminal(os.Stderr.Fd()) {
|
||||
c.Print(ProgramName() + ": <ERROR> ")
|
||||
c.Println(a...)
|
||||
} else {
|
||||
fmt.Fprint(color.Output, ProgramName()+": <ERROR> ")
|
||||
fmt.Fprintln(color.Output, a...)
|
||||
}
|
||||
color.Output = output
|
||||
case "Info":
|
||||
// if no arguments are given do not invoke info printer.
|
||||
if len(a) == 0 {
|
||||
return
|
||||
}
|
||||
if isatty.IsTerminal(os.Stdout.Fd()) {
|
||||
c.Print(ProgramName() + ": ")
|
||||
c.Println(a...)
|
||||
} else {
|
||||
fmt.Fprint(color.Output, ProgramName()+": ")
|
||||
fmt.Fprintln(color.Output, a...)
|
||||
}
|
||||
default:
|
||||
if isatty.IsTerminal(os.Stdout.Fd()) {
|
||||
c.Println(a...)
|
||||
} else {
|
||||
fmt.Fprintln(color.Output, a...)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Lock console.
|
||||
func Lock() {
|
||||
publicMutex.Lock()
|
||||
}
|
||||
|
||||
// Unlock locked console.
|
||||
func Unlock() {
|
||||
publicMutex.Unlock()
|
||||
}
|
||||
|
||||
// ProgramName - return the name of the executable program.
|
||||
func ProgramName() string {
|
||||
_, progName := filepath.Split(os.Args[0])
|
||||
return progName
|
||||
}
|
||||
@@ -1,42 +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 console
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/fatih/color"
|
||||
. "gopkg.in/check.v1"
|
||||
)
|
||||
|
||||
func Test(t *testing.T) { TestingT(t) }
|
||||
|
||||
type MySuite struct{}
|
||||
|
||||
var _ = Suite(&MySuite{})
|
||||
|
||||
func (s *MySuite) TestSetColor(c *C) {
|
||||
SetColor("unknown", color.New(color.FgWhite))
|
||||
_, ok := Theme["unknown"]
|
||||
c.Assert(ok, Equals, true)
|
||||
}
|
||||
|
||||
func (s *MySuite) TestLock(c *C) {
|
||||
Lock()
|
||||
Print("") // Test for deadlocks.
|
||||
Unlock()
|
||||
}
|
||||
@@ -1,53 +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 console
|
||||
|
||||
import "github.com/fatih/color"
|
||||
|
||||
var (
|
||||
// Theme contains default color mapping.
|
||||
Theme = map[string]*color.Color{
|
||||
"Debug": color.New(color.FgWhite, color.Faint, color.Italic),
|
||||
"Fatal": color.New(color.FgRed, color.Italic, color.Bold),
|
||||
"Error": color.New(color.FgYellow, color.Italic),
|
||||
"Info": color.New(color.FgGreen, color.Bold),
|
||||
"Print": color.New(),
|
||||
"PrintC": color.New(color.FgGreen, color.Bold),
|
||||
}
|
||||
)
|
||||
|
||||
// SetColorOff disables coloring for the entire session.
|
||||
func SetColorOff() {
|
||||
privateMutex.Lock()
|
||||
defer privateMutex.Unlock()
|
||||
color.NoColor = true
|
||||
}
|
||||
|
||||
// SetColorOn enables coloring for the entire session.
|
||||
func SetColorOn() {
|
||||
privateMutex.Lock()
|
||||
defer privateMutex.Unlock()
|
||||
color.NoColor = false
|
||||
}
|
||||
|
||||
// SetColor sets a color for a particular tag.
|
||||
func SetColor(tag string, cl *color.Color) {
|
||||
privateMutex.Lock()
|
||||
defer privateMutex.Unlock()
|
||||
// add new theme
|
||||
Theme[tag] = cl
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
/*
|
||||
* Minio Client (C) 2016 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
// Package hookreader hooks additional reader in the source
|
||||
// stream. It is useful for making progress bars. Second reader is
|
||||
// appropriately notified about the exact number of bytes read from
|
||||
// the primary source on each Read operation.
|
||||
package hookreader
|
||||
|
||||
import "io"
|
||||
|
||||
type hookReader struct {
|
||||
source io.Reader
|
||||
hook io.Reader
|
||||
}
|
||||
|
||||
// Read implements io.Reader. Always reads from the source, the return
|
||||
// value 'n' number of bytes are reported through the hook. Returns
|
||||
// error for all non io.EOF conditions.
|
||||
func (hr *hookReader) Read(b []byte) (n int, err error) {
|
||||
n, err = hr.source.Read(b)
|
||||
if err != nil && err != io.EOF {
|
||||
return n, err
|
||||
}
|
||||
// Progress the hook with the total read bytes from the source.
|
||||
if _, herr := hr.hook.Read(b[:n]); herr != nil {
|
||||
if herr != io.EOF {
|
||||
return n, herr
|
||||
}
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
|
||||
// NewHook returns a io.Reader which implements hookReader that
|
||||
// reports the data read from the source to the hook.
|
||||
func NewHook(source, hook io.Reader) io.Reader {
|
||||
if hook == nil {
|
||||
return source
|
||||
}
|
||||
return &hookReader{source, hook}
|
||||
}
|
||||
@@ -1,55 +0,0 @@
|
||||
/*
|
||||
* Minio Client (C) 2016 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package hookreader
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"testing"
|
||||
|
||||
. "gopkg.in/check.v1"
|
||||
)
|
||||
|
||||
func Test(t *testing.T) { TestingT(t) }
|
||||
|
||||
type MySuite struct{}
|
||||
|
||||
var _ = Suite(&MySuite{})
|
||||
|
||||
// customReader - implements custom progress reader.
|
||||
type customReader struct {
|
||||
readBytes int
|
||||
}
|
||||
|
||||
func (c *customReader) Read(b []byte) (n int, err error) {
|
||||
c.readBytes += len(b)
|
||||
return len(b), nil
|
||||
}
|
||||
|
||||
// Tests hook reader implementation.
|
||||
func (s *MySuite) TestHookReader(c *C) {
|
||||
var buffer bytes.Buffer
|
||||
writer := &buffer
|
||||
_, err := writer.Write([]byte("Hello"))
|
||||
c.Assert(err, IsNil)
|
||||
progress := &customReader{}
|
||||
reader := NewHook(&buffer, progress)
|
||||
b := make([]byte, 3)
|
||||
n, err := reader.Read(b)
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(n, Equals, 3)
|
||||
c.Assert(progress.readBytes, Equals, 3)
|
||||
}
|
||||
@@ -1,74 +0,0 @@
|
||||
/*
|
||||
* Minio Client (C) 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package httptracer
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/minio/mc/pkg/console"
|
||||
)
|
||||
|
||||
// HTTPTracer provides callback hook mechanism for HTTP transport.
|
||||
type HTTPTracer interface {
|
||||
Request(req *http.Request) error
|
||||
Response(res *http.Response) error
|
||||
}
|
||||
|
||||
// RoundTripTrace interposes HTTP transport requests and respsonses using HTTPTracer hooks
|
||||
type RoundTripTrace struct {
|
||||
Trace HTTPTracer // User provides callback methods
|
||||
Transport http.RoundTripper // HTTP transport that needs to be intercepted
|
||||
}
|
||||
|
||||
// RoundTrip executes user provided request and response hooks for each HTTP call.
|
||||
func (t RoundTripTrace) RoundTrip(req *http.Request) (res *http.Response, err error) {
|
||||
timeStamp := time.Now()
|
||||
|
||||
if t.Transport == nil {
|
||||
return nil, errors.New("Invalid Argument")
|
||||
}
|
||||
|
||||
res, err = t.Transport.RoundTrip(req)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
if t.Trace != nil {
|
||||
err = t.Trace.Request(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
err = t.Trace.Response(res)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
console.Debugln("Response Time: ", time.Since(timeStamp).String()+"\n")
|
||||
}
|
||||
return res, err
|
||||
}
|
||||
|
||||
// GetNewTraceTransport returns a traceable transport
|
||||
//
|
||||
// Takes first argument a custom tracer which implements Response, Request() conforming to HTTPTracer interface.
|
||||
// Another argument can be a default transport or a custom http.RoundTripper implementation
|
||||
func GetNewTraceTransport(trace HTTPTracer, transport http.RoundTripper) RoundTripTrace {
|
||||
return RoundTripTrace{Trace: trace,
|
||||
Transport: transport}
|
||||
}
|
||||
@@ -1,33 +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 httptracer
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
. "gopkg.in/check.v1"
|
||||
)
|
||||
|
||||
func Test(t *testing.T) { TestingT(t) }
|
||||
|
||||
type MySuite struct{}
|
||||
|
||||
var _ = Suite(&MySuite{})
|
||||
|
||||
func (s *MySuite) TestHTTPTracer(c *C) {
|
||||
//
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
/*
|
||||
* Minio Client (C) 2014, 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import "github.com/minio/mc/pkg/console"
|
||||
|
||||
// message interface for all structured messages implementing JSON(), String() methods.
|
||||
type message interface {
|
||||
JSON() string
|
||||
String() string
|
||||
}
|
||||
|
||||
// printMsg prints message string or JSON structure depending on the type of output console.
|
||||
func printMsg(msg message) {
|
||||
if !globalJSON {
|
||||
console.Println(msg.String())
|
||||
} else {
|
||||
console.Println(msg.JSON())
|
||||
}
|
||||
}
|
||||
-151
@@ -1,151 +0,0 @@
|
||||
/*
|
||||
* Minio Client (C) 2014, 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"io"
|
||||
"runtime"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/pb"
|
||||
|
||||
"github.com/minio/mc/pkg/console"
|
||||
)
|
||||
|
||||
// progress extender.
|
||||
type progressBar struct {
|
||||
ProgressBar *pb.ProgressBar
|
||||
reader io.Reader
|
||||
readerLength int64
|
||||
bytesRead int64
|
||||
isResume bool
|
||||
}
|
||||
|
||||
// newProgressBar - instantiate a progress bar.
|
||||
func newProgressBar(total int64) *progressBar {
|
||||
// Progress bar speific theme customization.
|
||||
console.SetColor("Bar", color.New(color.FgGreen, color.Bold))
|
||||
|
||||
pgbar := progressBar{}
|
||||
|
||||
// get the new original progress bar.
|
||||
bar := pb.New64(total)
|
||||
|
||||
// Set new human friendly print units.
|
||||
bar.SetUnits(pb.U_BYTES)
|
||||
|
||||
// Refresh rate for progress bar is set to 125 milliseconds.
|
||||
bar.SetRefreshRate(time.Millisecond * 125)
|
||||
|
||||
// Do not print a newline by default handled, it is handled manually.
|
||||
bar.NotPrint = true
|
||||
|
||||
// Show current speed is true.
|
||||
bar.ShowSpeed = true
|
||||
|
||||
// Custom callback with colorized bar.
|
||||
bar.Callback = func(s string) {
|
||||
console.Print(console.Colorize("Bar", "\r"+s))
|
||||
}
|
||||
|
||||
// Use different unicodes for Linux, OS X and Windows.
|
||||
switch runtime.GOOS {
|
||||
case "linux":
|
||||
// Need to add '\x00' as delimiter for unicode characters.
|
||||
bar.Format("┃\x00▓\x00█\x00░\x00┃")
|
||||
case "darwin":
|
||||
// Need to add '\x00' as delimiter for unicode characters.
|
||||
bar.Format(" \x00▓\x00 \x00░\x00 ")
|
||||
default:
|
||||
// Default to non unicode characters.
|
||||
bar.Format("[=> ]")
|
||||
}
|
||||
|
||||
// Start the progress bar.
|
||||
if bar.Total > 0 {
|
||||
bar.Start()
|
||||
}
|
||||
|
||||
// Copy for future
|
||||
pgbar.ProgressBar = bar
|
||||
|
||||
// Return new progress bar here.
|
||||
return &pgbar
|
||||
}
|
||||
|
||||
// Set caption.
|
||||
func (p *progressBar) SetCaption(caption string) *progressBar {
|
||||
caption = fixateBarCaption(caption, getFixedWidth(p.ProgressBar.GetWidth(), 18))
|
||||
p.ProgressBar.Prefix(caption)
|
||||
return p
|
||||
}
|
||||
|
||||
func (p *progressBar) Set64(length int64) *progressBar {
|
||||
p.ProgressBar = p.ProgressBar.Set64(length)
|
||||
return p
|
||||
}
|
||||
|
||||
// cursorAnimate - returns a animated rune through read channel for every read.
|
||||
func cursorAnimate() <-chan rune {
|
||||
cursorCh := make(chan rune)
|
||||
var cursors string
|
||||
|
||||
switch runtime.GOOS {
|
||||
case "linux":
|
||||
// cursors = "➩➪➫➬➭➮➯➱"
|
||||
// cursors = "▁▃▄▅▆▇█▇▆▅▄▃"
|
||||
cursors = "◐◓◑◒"
|
||||
// cursors = "←↖↑↗→↘↓↙"
|
||||
// cursors = "◴◷◶◵"
|
||||
// cursors = "◰◳◲◱"
|
||||
//cursors = "⣾⣽⣻⢿⡿⣟⣯⣷"
|
||||
case "darwin":
|
||||
cursors = "◐◓◑◒"
|
||||
default:
|
||||
cursors = "|/-\\"
|
||||
}
|
||||
go func() {
|
||||
for {
|
||||
for _, cursor := range cursors {
|
||||
cursorCh <- cursor
|
||||
}
|
||||
}
|
||||
}()
|
||||
return cursorCh
|
||||
}
|
||||
|
||||
// fixateBarCaption - fancify bar caption based on the terminal width.
|
||||
func fixateBarCaption(caption string, width int) string {
|
||||
switch {
|
||||
case len(caption) > width:
|
||||
// Trim caption to fit within the screen
|
||||
trimSize := len(caption) - width + 3
|
||||
if trimSize < len(caption) {
|
||||
caption = "..." + caption[trimSize:]
|
||||
}
|
||||
case len(caption) < width:
|
||||
caption += strings.Repeat(" ", width-len(caption))
|
||||
}
|
||||
return caption
|
||||
}
|
||||
|
||||
// getFixedWidth - get a fixed width based for a given percentage.
|
||||
func getFixedWidth(width, percent int) int {
|
||||
return width * percent / 100
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
SET MC_RELEASE=OFFICIAL
|
||||
SET GO15VENDOREXPERIMENT=1
|
||||
go run buildscripts/gen-ldflags.go > temp.txt
|
||||
SET /p LDFLAGS=<temp.txt
|
||||
go build -ldflags="%LDFLAGS%" -o %GOPATH%\bin\mc.exe
|
||||
@@ -1,6 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
echo -n "Making official release binaries.. "
|
||||
export MC_RELEASE=OFFICIAL
|
||||
make 1>/dev/null
|
||||
echo "Binaries built at ${GOPATH}/bin/mc"
|
||||
-215
@@ -1,215 +0,0 @@
|
||||
/*
|
||||
* Minio Client (C) 2014, 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
)
|
||||
|
||||
// rm specific flags.
|
||||
var (
|
||||
rmFlags = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "help, h",
|
||||
Usage: "Help of rm.",
|
||||
},
|
||||
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 an incomplete upload(s).",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "fake",
|
||||
Usage: "Perform a fake remove operation.",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
// remove a file or folder.
|
||||
var rmCmd = cli.Command{
|
||||
Name: "rm",
|
||||
Usage: "Remove file or bucket [WARNING: Use with care].",
|
||||
Action: mainRm,
|
||||
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 contents of a folder, excluding its sub-folders.
|
||||
$ mc {{.Name}} --force s3/jazz-songs/louis/
|
||||
|
||||
3. Remove contents of a folder recursively.
|
||||
$ mc {{.Name}} --force --recursive s3/jazz-songs/louis/
|
||||
|
||||
4. Remove all matching objects with this prefix.
|
||||
$ mc {{.Name}} --force s3/ogg/gunmetal
|
||||
|
||||
5. Drop an incomplete upload of an object.
|
||||
$ mc {{.Name}} --incomplete s3/jazz-songs/louis/file01.mp3
|
||||
|
||||
6. Drop all incomplete uploads recursively matching this prefix.
|
||||
$ mc {{.Name}} --incomplete --force --recursive s3/jazz-songs/louis/
|
||||
`,
|
||||
}
|
||||
|
||||
// Structured message depending on the type of console.
|
||||
type rmMessage struct {
|
||||
Status string `json:"status"`
|
||||
URL string `json:"url"`
|
||||
}
|
||||
|
||||
// Colorized message for console printing.
|
||||
func (r rmMessage) String() string {
|
||||
return console.Colorize("Remove", fmt.Sprintf("Removed ‘%s’.", r.URL))
|
||||
}
|
||||
|
||||
// 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")
|
||||
|
||||
if !ctx.Args().Present() {
|
||||
exitCode := 1
|
||||
cli.ShowCommandHelpAndExit(ctx, "rm", exitCode)
|
||||
}
|
||||
|
||||
// For all recursive operations make sure to check for 'force' flag.
|
||||
if isRecursive && !isForce {
|
||||
fatalIf(errDummy().Trace(),
|
||||
"Recursive removal requires --force option. Please review carefully before performing this *DANGEROUS* operation.")
|
||||
}
|
||||
}
|
||||
|
||||
// Remove a single object.
|
||||
func rm(targetAlias, targetURL string, isIncomplete, isFake bool) *probe.Error {
|
||||
clnt, err := newClientFromAlias(targetAlias, targetURL)
|
||||
if err != nil {
|
||||
return err.Trace(targetURL)
|
||||
}
|
||||
|
||||
if isFake { // It is a fake remove. Return success.
|
||||
return nil
|
||||
}
|
||||
|
||||
if err = clnt.Remove(isIncomplete); err != nil {
|
||||
return err.Trace(targetURL)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Remove all objects recursively.
|
||||
func rmAll(targetAlias, targetURL string, isRecursive, isIncomplete, isFake bool) {
|
||||
// Initialize new client.
|
||||
clnt, err := newClientFromAlias(targetAlias, targetURL)
|
||||
if err != nil {
|
||||
errorIf(err.Trace(targetURL), "Invalid URL ‘"+targetURL+"’.")
|
||||
return // End of journey.
|
||||
}
|
||||
|
||||
/* Disable recursion and only list this folder's contents. We
|
||||
perform manual depth-first recursion ourself here. */
|
||||
nonRecursive := false
|
||||
for entry := range clnt.List(nonRecursive, isIncomplete) {
|
||||
if entry.Err != nil {
|
||||
errorIf(entry.Err.Trace(targetURL), "Unable to list ‘"+targetURL+"’.")
|
||||
return // End of journey.
|
||||
}
|
||||
|
||||
if entry.Type.IsDir() && isRecursive {
|
||||
// Add separator at the end to remove all its contents.
|
||||
url := entry.URL
|
||||
url.Path = strings.TrimSuffix(entry.URL.Path, string(entry.URL.Separator)) + string(entry.URL.Separator)
|
||||
|
||||
// Recursively remove contents of this directory.
|
||||
rmAll(targetAlias, url.String(), isRecursive, isIncomplete, isFake)
|
||||
}
|
||||
|
||||
// Regular type.
|
||||
if err = rm(targetAlias, entry.URL.String(), isIncomplete, isFake); err != nil {
|
||||
errorIf(err.Trace(entry.URL.String()), "Unable to remove ‘"+entry.URL.String()+"’.")
|
||||
continue
|
||||
}
|
||||
// Construct user facing message and path.
|
||||
entryPath := filepath.ToSlash(filepath.Join(targetAlias, entry.URL.Path))
|
||||
printMsg(rmMessage{Status: "success", URL: entryPath})
|
||||
}
|
||||
}
|
||||
|
||||
// main for rm command.
|
||||
func mainRm(ctx *cli.Context) {
|
||||
// Set global flags from context.
|
||||
setGlobalsFromContext(ctx)
|
||||
|
||||
// check 'rm' cli arguments.
|
||||
checkRmSyntax(ctx)
|
||||
|
||||
// rm specific flags.
|
||||
isForce := ctx.Bool("force")
|
||||
isIncomplete := ctx.Bool("incomplete")
|
||||
isRecursive := ctx.Bool("recursive")
|
||||
isFake := ctx.Bool("fake")
|
||||
|
||||
// Set color.
|
||||
console.SetColor("Remove", color.New(color.FgGreen, color.Bold))
|
||||
|
||||
// Support multiple targets.
|
||||
for _, url := range ctx.Args() {
|
||||
targetAlias, targetURL, _ := mustExpandAlias(url)
|
||||
if isRecursive && isForce {
|
||||
rmAll(targetAlias, targetURL, isRecursive, isIncomplete, isFake)
|
||||
} else {
|
||||
if err := rm(targetAlias, targetURL, isIncomplete, isFake); err != nil {
|
||||
errorIf(err.Trace(url), "Unable to remove ‘"+url+"’.")
|
||||
continue
|
||||
}
|
||||
printMsg(rmMessage{Status: "success", URL: url})
|
||||
}
|
||||
}
|
||||
}
|
||||
-75
@@ -1,75 +0,0 @@
|
||||
/*
|
||||
* Minio Client (C) 2014, 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/dustin/go-humanize"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/olekukonko/ts"
|
||||
)
|
||||
|
||||
/******************************** Scan Bar ************************************/
|
||||
// fixateScanBar truncates long 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
|
||||
trimSize := len([]rune(text)) - width + 3 //"..."
|
||||
if trimSize < len([]rune(text)) {
|
||||
text = "..." + text[trimSize:]
|
||||
}
|
||||
}
|
||||
return text
|
||||
}
|
||||
|
||||
// Progress bar function report objects being scaned.
|
||||
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()
|
||||
|
||||
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)
|
||||
barText := scanPrefix + source
|
||||
console.PrintC("\r" + barText)
|
||||
prevSource = source
|
||||
prevLineSize = len([]rune(barText))
|
||||
fileCount++
|
||||
}
|
||||
}
|
||||
-261
@@ -1,261 +0,0 @@
|
||||
/*
|
||||
* Minio Client, (C) 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
)
|
||||
|
||||
var (
|
||||
sessionFlags = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "help, h",
|
||||
Usage: "Help of session.",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
// Manage sessions for cp and mirror.
|
||||
var sessionCmd = cli.Command{
|
||||
Name: "session",
|
||||
Usage: "Manage saved sessions of cp and mirror operations.",
|
||||
Action: mainSession,
|
||||
Flags: append(sessionFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
mc {{.Name}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
mc {{.Name}} [FLAGS] OPERATION [ARG]
|
||||
|
||||
OPERATION:
|
||||
resume Resume a previously saved session.
|
||||
clear Clear a previously saved session.
|
||||
list List all previously saved sessions.
|
||||
|
||||
SESSION-ID:
|
||||
SESSION - Session can either be $SESSION-ID or "all".
|
||||
|
||||
FLAGS:
|
||||
{{range .Flags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. List sessions.
|
||||
$ mc {{.Name}} list
|
||||
|
||||
2. Resume session.
|
||||
$ mc {{.Name}} resume ygVIpSJs
|
||||
|
||||
3. Clear session.
|
||||
$ mc {{.Name}} clear ygVIpSJs
|
||||
|
||||
4. Clear session.
|
||||
$ mc {{.Name}} clear all
|
||||
`,
|
||||
}
|
||||
|
||||
// bySessionWhen is a type for sorting session metadata by time.
|
||||
type bySessionWhen []*sessionV6
|
||||
|
||||
func (b bySessionWhen) Len() int { return len(b) }
|
||||
func (b bySessionWhen) Swap(i, j int) { b[i], b[j] = b[j], b[i] }
|
||||
func (b bySessionWhen) Less(i, j int) bool { return b[i].Header.When.Before(b[j].Header.When) }
|
||||
|
||||
// listSessions list all current sessions.
|
||||
func listSessions() *probe.Error {
|
||||
var bySessions []*sessionV6
|
||||
for _, sid := range getSessionIDs() {
|
||||
s, err := loadSessionV6(sid)
|
||||
if err != nil {
|
||||
return err.Trace(sid)
|
||||
}
|
||||
bySessions = append(bySessions, s)
|
||||
}
|
||||
// sort sessions based on time.
|
||||
sort.Sort(bySessionWhen(bySessions))
|
||||
for _, session := range bySessions {
|
||||
printMsg(session)
|
||||
session.Close()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// clearSessionMessage container for clearing session messages.
|
||||
type clearSessionMessage struct {
|
||||
Status string `json:"success"`
|
||||
SessionID string `json:"sessionId"`
|
||||
}
|
||||
|
||||
// String colorized clear session message.
|
||||
func (c clearSessionMessage) String() string {
|
||||
return console.Colorize("ClearSession", "Session ‘"+c.SessionID+"’ cleared successfully.")
|
||||
}
|
||||
|
||||
// JSON jsonified clear session message.
|
||||
func (c clearSessionMessage) JSON() string {
|
||||
clearSessionJSONBytes, e := json.Marshal(c)
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(clearSessionJSONBytes)
|
||||
}
|
||||
|
||||
// clearSession clear sessions.
|
||||
func clearSession(sid string) {
|
||||
if sid == "all" {
|
||||
for _, sid := range getSessionIDs() {
|
||||
session, err := loadSessionV6(sid)
|
||||
fatalIf(err.Trace(sid), "Unable to load session ‘"+sid+"’.")
|
||||
|
||||
fatalIf(session.Delete().Trace(sid), "Unable to load session ‘"+sid+"’.")
|
||||
|
||||
printMsg(clearSessionMessage{Status: "success", SessionID: sid})
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if !isSessionExists(sid) {
|
||||
fatalIf(errDummy().Trace(sid), "Session ‘"+sid+"’ not found.")
|
||||
}
|
||||
|
||||
session, err := loadSessionV6(sid)
|
||||
fatalIf(err.Trace(sid), "Unable to load session ‘"+sid+"’.")
|
||||
|
||||
if session != nil {
|
||||
fatalIf(session.Delete().Trace(sid), "Unable to load session ‘"+sid+"’.")
|
||||
printMsg(clearSessionMessage{Status: "success", SessionID: sid})
|
||||
}
|
||||
}
|
||||
|
||||
func sessionExecute(s *sessionV6) {
|
||||
switch s.Header.CommandType {
|
||||
case "cp":
|
||||
doCopySession(s)
|
||||
case "mirror":
|
||||
doMirrorSession(s)
|
||||
}
|
||||
}
|
||||
|
||||
func checkSessionSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) < 1 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "session", 1) // last argument is exit code
|
||||
}
|
||||
if strings.TrimSpace(ctx.Args().First()) == "" {
|
||||
cli.ShowCommandHelpAndExit(ctx, "session", 1) // last argument is exit code
|
||||
}
|
||||
|
||||
switch strings.TrimSpace(ctx.Args().First()) {
|
||||
case "list":
|
||||
case "resume":
|
||||
if strings.TrimSpace(ctx.Args().Tail().First()) == "" {
|
||||
fatalIf(errInvalidArgument().Trace(ctx.Args()...), "Unable to validate empty argument.")
|
||||
}
|
||||
case "clear":
|
||||
if strings.TrimSpace(ctx.Args().Tail().First()) == "" {
|
||||
fatalIf(errInvalidArgument().Trace(ctx.Args()...), "Unable to validate empty argument.")
|
||||
}
|
||||
default:
|
||||
cli.ShowCommandHelpAndExit(ctx, "session", 1) // last argument is exit code
|
||||
}
|
||||
}
|
||||
|
||||
// findClosestSessions to match a given string with sessions trie tree.
|
||||
func findClosestSessions(session string) []string {
|
||||
sessionsTree := newTrie() // Allocate a new trie for sessions strings.
|
||||
for _, sid := range getSessionIDs() {
|
||||
sessionsTree.Insert(sid)
|
||||
}
|
||||
var closestSessions []string
|
||||
for _, value := range sessionsTree.PrefixMatch(session) {
|
||||
closestSessions = append(closestSessions, value.(string))
|
||||
}
|
||||
sort.Strings(closestSessions)
|
||||
return closestSessions
|
||||
}
|
||||
|
||||
func mainSession(ctx *cli.Context) {
|
||||
// Set global flags from context.
|
||||
setGlobalsFromContext(ctx)
|
||||
|
||||
// check 'session' cli arguments.
|
||||
checkSessionSyntax(ctx)
|
||||
|
||||
// Additional command speific theme customization.
|
||||
console.SetColor("Command", color.New(color.FgWhite, color.Bold))
|
||||
console.SetColor("SessionID", color.New(color.FgYellow, color.Bold))
|
||||
console.SetColor("SessionTime", color.New(color.FgGreen))
|
||||
console.SetColor("ClearSession", color.New(color.FgGreen, color.Bold))
|
||||
|
||||
if !isSessionDirExists() {
|
||||
fatalIf(createSessionDir().Trace(), "Unable to create session folder.")
|
||||
}
|
||||
|
||||
switch strings.TrimSpace(ctx.Args().First()) {
|
||||
// list all resumable sessions.
|
||||
case "list":
|
||||
fatalIf(listSessions().Trace(ctx.Args()...), "Unable to list sessions.")
|
||||
case "resume":
|
||||
sid := strings.TrimSpace(ctx.Args().Tail().First())
|
||||
if !isSessionExists(sid) {
|
||||
closestSessions := findClosestSessions(sid)
|
||||
errorMsg := "Session ‘" + sid + "’ not found."
|
||||
if len(closestSessions) > 0 {
|
||||
errorMsg += fmt.Sprintf("\n\nDid you mean?\n")
|
||||
for _, session := range closestSessions {
|
||||
errorMsg += fmt.Sprintf(" ‘mc resume session %s’", session)
|
||||
// break on the first one, it is good enough.
|
||||
break
|
||||
}
|
||||
}
|
||||
fatalIf(errDummy().Trace(sid), errorMsg)
|
||||
}
|
||||
s, err := loadSessionV6(sid)
|
||||
fatalIf(err.Trace(sid), "Unable to load session.")
|
||||
|
||||
// Restore the state of global variables from this previous session.
|
||||
s.restoreGlobals()
|
||||
|
||||
savedCwd, e := os.Getwd()
|
||||
fatalIf(probe.NewError(e), "Unable to determine current working folder.")
|
||||
|
||||
if s.Header.RootPath != "" {
|
||||
// change folder to RootPath.
|
||||
e = os.Chdir(s.Header.RootPath)
|
||||
fatalIf(probe.NewError(e), "Unable to change working folder to root path while resuming session.")
|
||||
}
|
||||
sessionExecute(s)
|
||||
err = s.Close()
|
||||
fatalIf(err.Trace(), "Unable to close session file properly.")
|
||||
|
||||
err = s.Delete()
|
||||
fatalIf(err.Trace(), "Unable to clear session files properly.")
|
||||
|
||||
// change folder back to saved path.
|
||||
e = os.Chdir(savedCwd)
|
||||
fatalIf(probe.NewError(e), "Unable to change working folder to saved path ‘"+savedCwd+"’.")
|
||||
// purge a requested pending session, if "all" purge everything.
|
||||
case "clear":
|
||||
clearSession(strings.TrimSpace(ctx.Args().Tail().First()))
|
||||
}
|
||||
}
|
||||
-347
@@ -1,347 +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.
|
||||
*/
|
||||
|
||||
// Session V2 - Version 2 stores session header and session data in
|
||||
// two separate files. Session data contains fully prepared URL list.
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/minio-xl/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 {
|
||||
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"`
|
||||
}
|
||||
|
||||
// sessionMessage container for session messages
|
||||
type sessionMessage struct {
|
||||
Status string `json:"status"`
|
||||
SessionID string `json:"sessionId"`
|
||||
Time time.Time `json:"time"`
|
||||
CommandType string `json:"commandType"`
|
||||
CommandArgs []string `json:"commandArgs"`
|
||||
}
|
||||
|
||||
// sessionV6 resumable session container.
|
||||
type sessionV6 struct {
|
||||
Header *sessionV6Header
|
||||
SessionID string
|
||||
mutex *sync.Mutex
|
||||
DataFP *sessionDataFP
|
||||
sigCh bool
|
||||
}
|
||||
|
||||
// sessionDataFP data file pointer.
|
||||
type sessionDataFP struct {
|
||||
dirty bool
|
||||
*os.File
|
||||
}
|
||||
|
||||
func (file *sessionDataFP) Write(p []byte) (int, error) {
|
||||
file.dirty = true
|
||||
return file.File.Write(p)
|
||||
}
|
||||
|
||||
// String colorized session message.
|
||||
func (s sessionV6) String() string {
|
||||
message := console.Colorize("SessionID", fmt.Sprintf("%s -> ", s.SessionID))
|
||||
message = message + console.Colorize("SessionTime", fmt.Sprintf("[%s]", s.Header.When.Local().Format(printDate)))
|
||||
message = message + console.Colorize("Command", fmt.Sprintf(" %s %s", s.Header.CommandType, strings.Join(s.Header.CommandArgs, " ")))
|
||||
return message
|
||||
}
|
||||
|
||||
// JSON jsonified session message.
|
||||
func (s sessionV6) JSON() string {
|
||||
sessionMsg := sessionMessage{
|
||||
SessionID: s.SessionID,
|
||||
Time: s.Header.When.Local(),
|
||||
CommandType: s.Header.CommandType,
|
||||
CommandArgs: s.Header.CommandArgs,
|
||||
}
|
||||
sessionMsg.Status = "success"
|
||||
sessionBytes, e := json.Marshal(sessionMsg)
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(sessionBytes)
|
||||
}
|
||||
|
||||
// loadSessionV6 - reads session file if exists and re-initiates internal variables
|
||||
func loadSessionV6(sid string) (*sessionV6, *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 := &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)
|
||||
}
|
||||
err = qs.Load(sessionFile)
|
||||
if err != nil {
|
||||
return nil, err.Trace(sid, s.Header.Version)
|
||||
}
|
||||
|
||||
s.mutex = new(sync.Mutex)
|
||||
s.Header = qs.Data().(*sessionV6Header)
|
||||
|
||||
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+"\".")
|
||||
|
||||
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"
|
||||
// map of command and files copied.
|
||||
s.Header.GlobalBoolFlags = make(map[string]bool)
|
||||
s.Header.GlobalIntFlags = make(map[string]int)
|
||||
s.Header.GlobalStringFlags = make(map[string]string)
|
||||
s.Header.CommandArgs = nil
|
||||
s.Header.CommandBoolFlags = make(map[string]bool)
|
||||
s.Header.CommandIntFlags = make(map[string]int)
|
||||
s.Header.CommandStringFlags = make(map[string]string)
|
||||
s.Header.When = time.Now().UTC()
|
||||
s.mutex = new(sync.Mutex)
|
||||
s.SessionID = newRandomID(8)
|
||||
|
||||
sessionDataFile, err := getSessionDataFile(s.SessionID)
|
||||
fatalIf(err.Trace(s.SessionID), "Unable to create session data file \""+sessionDataFile+"\".")
|
||||
|
||||
dataFile, e := os.Create(sessionDataFile)
|
||||
fatalIf(probe.NewError(e), "Unable to create session data file \""+sessionDataFile+"\".")
|
||||
|
||||
s.DataFP = &sessionDataFP{false, dataFile}
|
||||
|
||||
// Capture state of global flags.
|
||||
s.setGlobals()
|
||||
|
||||
return s
|
||||
}
|
||||
|
||||
// HasData provides true if this is a session resume, false otherwise.
|
||||
func (s sessionV6) HasData() bool {
|
||||
if s.Header.LastCopied == "" {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// NewDataReader provides reader interface to session data file.
|
||||
func (s *sessionV6) NewDataReader() io.Reader {
|
||||
// DataFP is always intitialized, either via new or load functions.
|
||||
s.DataFP.Seek(0, os.SEEK_SET)
|
||||
return io.Reader(s.DataFP)
|
||||
}
|
||||
|
||||
// NewDataReader provides writer interface to session data file.
|
||||
func (s *sessionV6) NewDataWriter() io.Writer {
|
||||
// DataFP is always intitialized, either via new or load functions.
|
||||
s.DataFP.Seek(0, os.SEEK_SET)
|
||||
return io.Writer(s.DataFP)
|
||||
}
|
||||
|
||||
// Save this session.
|
||||
func (s *sessionV6) Save() *probe.Error {
|
||||
s.mutex.Lock()
|
||||
defer s.mutex.Unlock()
|
||||
|
||||
if s.DataFP.dirty {
|
||||
if err := s.DataFP.Sync(); err != nil {
|
||||
return probe.NewError(err)
|
||||
}
|
||||
s.DataFP.dirty = false
|
||||
}
|
||||
|
||||
qs, err := quick.New(s.Header)
|
||||
if err != nil {
|
||||
return err.Trace(s.SessionID)
|
||||
}
|
||||
|
||||
sessionFile, err := getSessionFile(s.SessionID)
|
||||
if err != nil {
|
||||
return err.Trace(s.SessionID)
|
||||
}
|
||||
return qs.Save(sessionFile).Trace(sessionFile)
|
||||
}
|
||||
|
||||
// setGlobals captures the state of global variables into session header.
|
||||
// Used by newSession.
|
||||
func (s *sessionV6) setGlobals() {
|
||||
s.Header.GlobalBoolFlags["quiet"] = globalQuiet
|
||||
s.Header.GlobalBoolFlags["debug"] = globalDebug
|
||||
s.Header.GlobalBoolFlags["json"] = globalJSON
|
||||
s.Header.GlobalBoolFlags["noColor"] = globalNoColor
|
||||
}
|
||||
|
||||
// RestoreGlobals restores the state of global variables.
|
||||
// Used by resumeSession.
|
||||
func (s sessionV6) 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)
|
||||
}
|
||||
|
||||
// Close ends this session and removes all associated session files.
|
||||
func (s *sessionV6) Close() *probe.Error {
|
||||
s.mutex.Lock()
|
||||
defer s.mutex.Unlock()
|
||||
|
||||
if err := s.DataFP.Close(); err != nil {
|
||||
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)
|
||||
}
|
||||
|
||||
// Delete removes all the session files.
|
||||
func (s *sessionV6) Delete() *probe.Error {
|
||||
s.mutex.Lock()
|
||||
defer s.mutex.Unlock()
|
||||
|
||||
if s.DataFP != nil {
|
||||
name := s.DataFP.Name()
|
||||
// close file pro-actively before deleting
|
||||
// ignore any error, it could be possibly that
|
||||
// the file is closed already
|
||||
s.DataFP.Close()
|
||||
|
||||
if e := os.Remove(name); e != nil {
|
||||
return probe.NewError(e)
|
||||
}
|
||||
}
|
||||
|
||||
sessionFile, err := getSessionFile(s.SessionID)
|
||||
if err != nil {
|
||||
return err.Trace(s.SessionID)
|
||||
}
|
||||
|
||||
if e := os.Remove(sessionFile); e != nil {
|
||||
return probe.NewError(e)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Close a session and exit.
|
||||
func (s sessionV6) 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
|
||||
return func(sourceURL string) bool {
|
||||
if sourceURL == "" {
|
||||
fatalIf(errInvalidArgument().Trace(), "Empty source argument passed.")
|
||||
}
|
||||
if lastCopied == "" {
|
||||
return false
|
||||
}
|
||||
|
||||
if copied {
|
||||
if lastCopied == sourceURL {
|
||||
copied = false // from next call onwards we say false.
|
||||
}
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
-114
@@ -1,114 +0,0 @@
|
||||
/*
|
||||
* Minio Client, (C) 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
)
|
||||
|
||||
// migrateSession migrates all previous migration to latest.
|
||||
func migrateSession() {
|
||||
// We no longer support sessions older than v5. They will be removed.
|
||||
migrateSessionV5ToV6()
|
||||
}
|
||||
|
||||
// createSessionDir - create session directory.
|
||||
func createSessionDir() *probe.Error {
|
||||
sessionDir, err := getSessionDir()
|
||||
if err != nil {
|
||||
return err.Trace()
|
||||
}
|
||||
|
||||
if e := os.MkdirAll(sessionDir, 0700); e != nil {
|
||||
return probe.NewError(e)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// getSessionDir - get session directory.
|
||||
func getSessionDir() (string, *probe.Error) {
|
||||
configDir, err := getMcConfigDir()
|
||||
if err != nil {
|
||||
return "", err.Trace()
|
||||
}
|
||||
|
||||
sessionDir := filepath.Join(configDir, globalSessionDir)
|
||||
return sessionDir, nil
|
||||
}
|
||||
|
||||
// isSessionDirExists - verify if session directory exists.
|
||||
func isSessionDirExists() bool {
|
||||
sessionDir, err := getSessionDir()
|
||||
fatalIf(err.Trace(), "Unable to determine session folder.")
|
||||
|
||||
if _, e := os.Stat(sessionDir); e != nil {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// getSessionFile - get current session file.
|
||||
func getSessionFile(sid string) (string, *probe.Error) {
|
||||
sessionDir, err := getSessionDir()
|
||||
if err != nil {
|
||||
return "", err.Trace()
|
||||
}
|
||||
|
||||
sessionFile := filepath.Join(sessionDir, sid+".json")
|
||||
return sessionFile, nil
|
||||
}
|
||||
|
||||
// isSessionExists verifies if given session exists.
|
||||
func isSessionExists(sid string) bool {
|
||||
sessionFile, err := getSessionFile(sid)
|
||||
fatalIf(err.Trace(sid), "Unable to determine session filename for ‘"+sid+"’.")
|
||||
|
||||
if _, e := os.Stat(sessionFile); e != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
return true // Session exists.
|
||||
}
|
||||
|
||||
// getSessionDataFile - get session data file for a given session.
|
||||
func getSessionDataFile(sid string) (string, *probe.Error) {
|
||||
sessionDir, err := getSessionDir()
|
||||
if err != nil {
|
||||
return "", err.Trace()
|
||||
}
|
||||
|
||||
sessionDataFile := filepath.Join(sessionDir, sid+".data")
|
||||
return sessionDataFile, nil
|
||||
}
|
||||
|
||||
// getSessionIDs - get all active sessions.
|
||||
func getSessionIDs() (sids []string) {
|
||||
sessionDir, err := getSessionDir()
|
||||
fatalIf(err.Trace(), "Unable to access session folder.")
|
||||
|
||||
sessionList, e := filepath.Glob(sessionDir + "/*.json")
|
||||
fatalIf(probe.NewError(e), "Unable to access session folder ‘"+sessionDir+"’.")
|
||||
|
||||
for _, path := range sessionList {
|
||||
sids = append(sids, strings.TrimSuffix(filepath.Base(path), ".json"))
|
||||
}
|
||||
return sids
|
||||
}
|
||||
@@ -1,53 +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 (
|
||||
"regexp"
|
||||
|
||||
. "gopkg.in/check.v1"
|
||||
)
|
||||
|
||||
func (s *TestSuite) TestValidSessionID(c *C) {
|
||||
validSid := regexp.MustCompile("^[a-zA-Z]+$")
|
||||
sid := newRandomID(8)
|
||||
c.Assert(len(sid), Equals, 8)
|
||||
c.Assert(validSid.MatchString(sid), Equals, true)
|
||||
}
|
||||
|
||||
func (s *TestSuite) TestSession(c *C) {
|
||||
err := createSessionDir()
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(isSessionDirExists(), Equals, true)
|
||||
|
||||
session := newSessionV6()
|
||||
c.Assert(session.Header.CommandArgs, IsNil)
|
||||
c.Assert(len(session.SessionID), Equals, 8)
|
||||
|
||||
err = session.Close()
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
savedSession, err := loadSessionV6(session.SessionID)
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(session.SessionID, Equals, savedSession.SessionID)
|
||||
|
||||
err = savedSession.Close()
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
err = savedSession.Delete()
|
||||
c.Assert(err, IsNil)
|
||||
}
|
||||
-134
@@ -1,134 +0,0 @@
|
||||
/*
|
||||
* Minio Client (C) 2014, 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/minio-xl/pkg/quick"
|
||||
)
|
||||
|
||||
// shareEntryV1 - container for each download/upload entries.
|
||||
type shareEntryV1 struct {
|
||||
URL string `json:"share"` // Object URL.
|
||||
Date time.Time `json:"date"`
|
||||
Expiry time.Duration `json:"expiry"`
|
||||
ContentType string `json:"contentType,omitempty"` // Only used by upload cmd.
|
||||
}
|
||||
|
||||
// JSON file to persist previously shared uploads.
|
||||
type shareDBV1 struct {
|
||||
Version string `json:"version"`
|
||||
mutex *sync.Mutex
|
||||
|
||||
// key is unique share URL.
|
||||
Shares map[string]shareEntryV1 `json:"shares"`
|
||||
}
|
||||
|
||||
// Instantiate a new uploads structure for persistence.
|
||||
func newShareDBV1() *shareDBV1 {
|
||||
s := &shareDBV1{
|
||||
Version: "1",
|
||||
}
|
||||
s.Shares = make(map[string]shareEntryV1)
|
||||
s.mutex = &sync.Mutex{}
|
||||
return s
|
||||
}
|
||||
|
||||
// Set upload info for each share.
|
||||
func (s *shareDBV1) Set(objectURL string, shareURL string, expiry time.Duration, contentType string) {
|
||||
s.mutex.Lock()
|
||||
defer s.mutex.Unlock()
|
||||
|
||||
s.Shares[shareURL] = shareEntryV1{
|
||||
URL: objectURL,
|
||||
Date: time.Now().UTC(),
|
||||
Expiry: expiry,
|
||||
ContentType: contentType,
|
||||
}
|
||||
}
|
||||
|
||||
// Delete upload info if it exists.
|
||||
func (s *shareDBV1) Delete(objectURL string) {
|
||||
s.mutex.Lock()
|
||||
defer s.mutex.Unlock()
|
||||
|
||||
delete(s.Shares, objectURL)
|
||||
}
|
||||
|
||||
// Delete all expired uploads.
|
||||
func (s *shareDBV1) deleteAllExpired() {
|
||||
for shareURL, share := range s.Shares {
|
||||
if (share.Expiry - time.Since(share.Date)) <= 0 {
|
||||
// Expired entry. Safe to drop.
|
||||
delete(s.Shares, shareURL)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Load shareDB entries from disk. Any entries held in memory are reset.
|
||||
func (s *shareDBV1) Load(filename string) *probe.Error {
|
||||
s.mutex.Lock()
|
||||
defer s.mutex.Unlock()
|
||||
|
||||
// Check if the db file exist.
|
||||
if _, e := os.Stat(filename); e != nil {
|
||||
return probe.NewError(e)
|
||||
}
|
||||
|
||||
// Initialize and load using quick package.
|
||||
qs, err := quick.New(newShareDBV1())
|
||||
if err != nil {
|
||||
return err.Trace(filename)
|
||||
}
|
||||
err = qs.Load(filename)
|
||||
if err != nil {
|
||||
return err.Trace(filename)
|
||||
}
|
||||
|
||||
// Copy map over.
|
||||
for k, v := range qs.Data().(*shareDBV1).Shares {
|
||||
s.Shares[k] = v
|
||||
}
|
||||
|
||||
// Filter out expired entries and save changes back to disk.
|
||||
s.deleteAllExpired()
|
||||
s.save(filename)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
return qs.Save(filename).Trace(filename)
|
||||
}
|
||||
|
||||
// Persist share uploads to disk.
|
||||
func (s shareDBV1) Save(filename string) *probe.Error {
|
||||
s.mutex.Lock()
|
||||
defer s.mutex.Unlock()
|
||||
|
||||
return s.save(filename)
|
||||
}
|
||||
@@ -1,184 +0,0 @@
|
||||
/*
|
||||
* Minio Client (C) 2014, 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/minio-xl/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.",
|
||||
},
|
||||
shareFlagExpire,
|
||||
}
|
||||
)
|
||||
|
||||
// Share documents via URL.
|
||||
var shareDownload = cli.Command{
|
||||
Name: "download",
|
||||
Usage: "Generate URLs for download access.",
|
||||
Action: mainShareDownload,
|
||||
Flags: append(shareDownloadFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
mc share {{.Name}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
mc share {{.Name}} [OPTIONS] TARGET [TARGET...]
|
||||
|
||||
OPTIONS:
|
||||
{{range .Flags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Share this object with 7 days default expiry.
|
||||
$ mc share {{.Name}} s3/backup/2006-Mar-1/backup.tar.gz
|
||||
|
||||
2. Share this object with 10 minutes expiry.
|
||||
$ mc share {{.Name}} --expire=10m s3/backup/2006-Mar-1/backup.tar.gz
|
||||
|
||||
3. Share all objects under this folder with 5 days expiry.
|
||||
$ mc share {{.Name}} --expire=120h s3/backup/
|
||||
|
||||
4. Share all objects under this folder and all its sub-folders with 5 days expiry.
|
||||
$ mc share {{.Name}} --recursive --expire=120h s3/backup/
|
||||
`,
|
||||
}
|
||||
|
||||
// checkShareDownloadSyntax - validate command-line args.
|
||||
func checkShareDownloadSyntax(ctx *cli.Context) {
|
||||
args := ctx.Args()
|
||||
if !args.Present() {
|
||||
cli.ShowCommandHelpAndExit(ctx, "download", 1) // last argument is exit code.
|
||||
}
|
||||
|
||||
// Parse expiry.
|
||||
expiry := shareDefaultExpiry
|
||||
expireArg := ctx.String("expire")
|
||||
if expireArg != "" {
|
||||
var e error
|
||||
expiry, e = time.ParseDuration(expireArg)
|
||||
fatalIf(probe.NewError(e), "Unable to parse expire=‘"+expireArg+"’.")
|
||||
}
|
||||
|
||||
// Validate expiry.
|
||||
if expiry.Seconds() < 1 {
|
||||
fatalIf(errDummy().Trace(expiry.String()), "Expiry cannot be lesser than 1 second.")
|
||||
}
|
||||
if expiry.Seconds() > 604800 {
|
||||
fatalIf(errDummy().Trace(expiry.String()), "Expiry cannot be larger than 7 days.")
|
||||
}
|
||||
|
||||
for _, url := range ctx.Args() {
|
||||
_, _, err := url2Stat(url)
|
||||
fatalIf(err.Trace(url), "Unable to stat ‘"+url+"’.")
|
||||
}
|
||||
}
|
||||
|
||||
// doShareURL share files from target.
|
||||
func doShareDownloadURL(targetURL string, isRecursive bool, expiry time.Duration) *probe.Error {
|
||||
targetAlias, targetURLFull, _, err := expandAlias(targetURL)
|
||||
if err != nil {
|
||||
return err.Trace(targetURL)
|
||||
}
|
||||
clnt, err := newClientFromAlias(targetAlias, targetURLFull)
|
||||
if err != nil {
|
||||
return err.Trace(targetURL)
|
||||
}
|
||||
|
||||
// Load previously saved upload-shares. Add new entries and write it back.
|
||||
shareDB := newShareDBV1()
|
||||
shareDownloadsFile := getShareDownloadsFile()
|
||||
err = shareDB.Load(shareDownloadsFile)
|
||||
if err != nil {
|
||||
return err.Trace(shareDownloadsFile)
|
||||
}
|
||||
|
||||
// Generate share URL for each target.
|
||||
incomplete := false
|
||||
for content := range clnt.List(isRecursive, incomplete) {
|
||||
if content.Err != nil {
|
||||
return content.Err.Trace(clnt.GetURL().String())
|
||||
}
|
||||
// if any incoming directories, we don't need to calculate.
|
||||
if content.Type.IsDir() {
|
||||
continue
|
||||
}
|
||||
objectURL := content.URL.String()
|
||||
newClnt, err := newClientFromAlias(targetAlias, objectURL)
|
||||
if err != nil {
|
||||
return err.Trace(objectURL)
|
||||
}
|
||||
|
||||
// Generate share URL.
|
||||
shareURL, err := newClnt.ShareDownload(expiry)
|
||||
if err != nil {
|
||||
// add objectURL and expiry as part of the trace arguments.
|
||||
return err.Trace(objectURL, "expiry="+expiry.String())
|
||||
}
|
||||
|
||||
// Make new entries to shareDB.
|
||||
contentType := "" // Not useful for download shares.
|
||||
shareDB.Set(objectURL, shareURL, expiry, contentType)
|
||||
printMsg(shareMesssage{
|
||||
ObjectURL: objectURL,
|
||||
ShareURL: shareURL,
|
||||
TimeLeft: expiry,
|
||||
ContentType: contentType,
|
||||
})
|
||||
}
|
||||
|
||||
// Save downloads and return.
|
||||
return shareDB.Save(shareDownloadsFile)
|
||||
}
|
||||
|
||||
// main for share download.
|
||||
func mainShareDownload(ctx *cli.Context) {
|
||||
// Set global flags from context.
|
||||
setGlobalsFromContext(ctx)
|
||||
|
||||
// check input arguments.
|
||||
checkShareDownloadSyntax(ctx)
|
||||
|
||||
// Initialize share config folder.
|
||||
initShareConfig()
|
||||
|
||||
// Additional command speific theme customization.
|
||||
shareSetColor()
|
||||
|
||||
// Set command flags from context.
|
||||
isRecursive := ctx.Bool("recursive")
|
||||
expiry := shareDefaultExpiry
|
||||
if ctx.String("expire") != "" {
|
||||
var e error
|
||||
expiry, e = time.ParseDuration(ctx.String("expire"))
|
||||
fatalIf(probe.NewError(e), "Unable to parse expire=‘"+ctx.String("expire")+"’.")
|
||||
}
|
||||
|
||||
for _, targetURL := range ctx.Args() {
|
||||
err := doShareDownloadURL(targetURL, isRecursive, expiry)
|
||||
fatalIf(err.Trace(targetURL), "Unable to share target ‘"+targetURL+"’.")
|
||||
}
|
||||
}
|
||||
@@ -1,123 +0,0 @@
|
||||
/*
|
||||
* Minio Client (C) 2014, 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
)
|
||||
|
||||
var (
|
||||
shareListFlags = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "help, h",
|
||||
Usage: "Help of share list.",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
// Share documents via URL.
|
||||
var shareList = cli.Command{
|
||||
Name: "list",
|
||||
Usage: "List previously shared objects and folders.",
|
||||
Action: mainShareList,
|
||||
Flags: append(shareListFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
mc share {{.Name}} COMMAND - {{.Usage}}
|
||||
|
||||
COMMAND:
|
||||
upload: list previously shared access to uploads.
|
||||
download: list previously shared access to downloads.
|
||||
|
||||
USAGE:
|
||||
mc share {{.Name}}
|
||||
|
||||
EXAMPLES:
|
||||
1. List previously shared downloads, that haven't expired yet.
|
||||
$ mc share {{.Name}} download
|
||||
2. List previously shared uploads, that haven't expired yet.
|
||||
$ mc share {{.Name}} upload
|
||||
`,
|
||||
}
|
||||
|
||||
// validate command-line args.
|
||||
func checkShareListSyntax(ctx *cli.Context) {
|
||||
args := ctx.Args()
|
||||
if !args.Present() || (args.First() != "upload" && args.First() != "download") {
|
||||
cli.ShowCommandHelpAndExit(ctx, "list", 1) // last argument is exit code.
|
||||
}
|
||||
}
|
||||
|
||||
// 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))
|
||||
}
|
||||
|
||||
// Fetch defaults.
|
||||
uploadsFile := getShareUploadsFile()
|
||||
downloadsFile := getShareDownloadsFile()
|
||||
|
||||
// Load previously saved upload-shares.
|
||||
shareDB := newShareDBV1()
|
||||
|
||||
// if upload - read uploads file.
|
||||
if cmd == "upload" {
|
||||
if err := shareDB.Load(uploadsFile); err != nil {
|
||||
return err.Trace(uploadsFile)
|
||||
}
|
||||
}
|
||||
|
||||
// if download - read downloads file.
|
||||
if cmd == "download" {
|
||||
if err := shareDB.Load(downloadsFile); err != nil {
|
||||
return err.Trace(downloadsFile)
|
||||
}
|
||||
}
|
||||
|
||||
// Print previously shared entries.
|
||||
for shareURL, share := range shareDB.Shares {
|
||||
printMsg(shareMesssage{
|
||||
ObjectURL: share.URL,
|
||||
ShareURL: shareURL,
|
||||
TimeLeft: share.Expiry - time.Since(share.Date),
|
||||
ContentType: share.ContentType,
|
||||
})
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// main entry point for share list.
|
||||
func mainShareList(ctx *cli.Context) {
|
||||
// Set global flags from context.
|
||||
setGlobalsFromContext(ctx)
|
||||
|
||||
// validate command-line args.
|
||||
checkShareListSyntax(ctx)
|
||||
|
||||
// Additional command speific theme customization.
|
||||
shareSetColor()
|
||||
|
||||
// Initialize share config folder.
|
||||
initShareConfig()
|
||||
|
||||
// List shares.
|
||||
fatalIf(doShareList(ctx.Args().First()).Trace(), "Unable to list previously shared URLs.")
|
||||
}
|
||||
@@ -1,91 +0,0 @@
|
||||
/*
|
||||
* Minio Client (C) 2014, 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
)
|
||||
|
||||
var (
|
||||
shareFlags = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "help, h",
|
||||
Usage: "Help of share.",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
// Share documents via URL.
|
||||
var shareCmd = cli.Command{
|
||||
Name: "share",
|
||||
Usage: "Generate URL for sharing.",
|
||||
Action: mainShare,
|
||||
Flags: append(shareFlags, globalFlags...),
|
||||
Subcommands: []cli.Command{
|
||||
shareDownload,
|
||||
shareUpload,
|
||||
shareList,
|
||||
},
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.Name}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.Name}} [FLAGS] COMMAND
|
||||
|
||||
FLAGS:
|
||||
{{range .Flags}}{{.}}
|
||||
{{end}}
|
||||
COMMANDS:
|
||||
{{range .Commands}}{{join .Names ", "}}{{ "\t" }}{{.Usage}}
|
||||
{{end}}
|
||||
`,
|
||||
}
|
||||
|
||||
// migrateShare migrate to newest version sequentially.
|
||||
func migrateShare() {
|
||||
if !isShareDirExists() {
|
||||
return
|
||||
}
|
||||
|
||||
// Shared URLs are now managed by sub-commands. So delete any old URLs file if found.
|
||||
oldShareFile := filepath.Join(mustGetShareDir(), "urls.json")
|
||||
if _, e := os.Stat(oldShareFile); e == nil {
|
||||
// Old file exits.
|
||||
e := os.Remove(oldShareFile)
|
||||
fatalIf(probe.NewError(e), "Unable to delete old ‘"+oldShareFile+"’.")
|
||||
console.Infof("Removed older version of share ‘%s’ file.\n", oldShareFile)
|
||||
}
|
||||
}
|
||||
|
||||
// mainShare - main handler for mc share command.
|
||||
func mainShare(ctx *cli.Context) {
|
||||
// Set global flags from context.
|
||||
setGlobalsFromContext(ctx)
|
||||
|
||||
if ctx.Args().First() != "" { // command help.
|
||||
cli.ShowCommandHelp(ctx, ctx.Args().First())
|
||||
} else { // mc help.
|
||||
cli.ShowAppHelp(ctx)
|
||||
}
|
||||
|
||||
// Sub-commands like "upload" and "download" have their own main.
|
||||
}
|
||||
@@ -1,212 +0,0 @@
|
||||
/*
|
||||
* Minio Client (C) 2014, 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/client"
|
||||
"github.com/minio/minio-xl/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.",
|
||||
},
|
||||
shareFlagExpire,
|
||||
shareFlagContentType,
|
||||
}
|
||||
)
|
||||
|
||||
// Share documents via URL.
|
||||
var shareUpload = cli.Command{
|
||||
Name: "upload",
|
||||
Usage: "Generate ‘curl’ command to upload objects without requiring access/secret keys.",
|
||||
Action: mainShareUpload,
|
||||
Flags: append(shareUploadFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
mc share {{.Name}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
mc share {{.Name}} [OPTIONS] TARGET [TARGET...]
|
||||
|
||||
OPTIONS:
|
||||
{{range .Flags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Generate a curl command to allow upload access for a single object. Command expires in 7 days (default).
|
||||
$ mc share {{.Name}} s3/backup/2006-Mar-1/backup.tar.gz
|
||||
|
||||
2. Generate a curl command to allow upload access to a folder. Command expires in 120 hours.
|
||||
$ mc share {{.Name}} --expire=120h s3/backup/2007-Mar-2/
|
||||
|
||||
3. Generate a curl command to allow upload access of only '.png' images to a folder. Command expires in 2 hours.
|
||||
$ mc share {{.Name}} --expire=2h --content-type=image/png s3/backup/2007-Mar-2/
|
||||
|
||||
4. Generate a curl command to allow upload access to any objects matching the key prefix 'backup/'. Command expires in 2 hours.
|
||||
$ mc share {{.Name}} --recursive --expire=2h s3/backup/2007-Mar-2/backup/
|
||||
`,
|
||||
}
|
||||
|
||||
// checkShareUploadSyntax - validate command-line args.
|
||||
func checkShareUploadSyntax(ctx *cli.Context) {
|
||||
args := ctx.Args()
|
||||
if !args.Present() {
|
||||
cli.ShowCommandHelpAndExit(ctx, "upload", 1) // last argument is exit code.
|
||||
}
|
||||
|
||||
// Set command flags from context.
|
||||
isRecursive := ctx.Bool("recursive")
|
||||
expireArg := ctx.String("expire")
|
||||
|
||||
// Parse expiry.
|
||||
expiry := shareDefaultExpiry
|
||||
if expireArg != "" {
|
||||
var e error
|
||||
expiry, e = time.ParseDuration(expireArg)
|
||||
fatalIf(probe.NewError(e), "Unable to parse expire=‘"+expireArg+"’.")
|
||||
}
|
||||
|
||||
// Validate expiry.
|
||||
if expiry.Seconds() < 1 {
|
||||
fatalIf(errDummy().Trace(expiry.String()),
|
||||
"Expiry cannot be lesser than 1 second.")
|
||||
}
|
||||
if expiry.Seconds() > 604800 {
|
||||
fatalIf(errDummy().Trace(expiry.String()),
|
||||
"Expiry cannot be larger than 7 days.")
|
||||
}
|
||||
|
||||
for _, targetURL := range ctx.Args() {
|
||||
url := client.NewURL(targetURL)
|
||||
if strings.HasSuffix(targetURL, string(url.Separator)) && !isRecursive {
|
||||
fatalIf(errInvalidArgument().Trace(targetURL),
|
||||
"Use --recursive option to generate curl command for prefixes.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 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"]
|
||||
}
|
||||
postURL += " "
|
||||
curlCommand := "curl " + postURL
|
||||
for k, v := range uploadInfo {
|
||||
if k == "key" {
|
||||
key = v
|
||||
continue
|
||||
}
|
||||
curlCommand += fmt.Sprintf("-F %s=%s ", k, v)
|
||||
}
|
||||
// If key starts with is enabled prefix it with the output.
|
||||
if isRecursive {
|
||||
curlCommand += fmt.Sprintf("-F key=%s<NAME> ", key) // Object name.
|
||||
} else {
|
||||
curlCommand += fmt.Sprintf("-F key=%s ", key) // Object name.
|
||||
}
|
||||
curlCommand += "-F file=@<FILE>" // File to upload.
|
||||
return curlCommand
|
||||
}
|
||||
|
||||
// save shared URL to disk.
|
||||
func saveSharedURL(objectURL string, shareURL string, expiry time.Duration, contentType string) *probe.Error {
|
||||
// Load previously saved upload-shares.
|
||||
shareDB := newShareDBV1()
|
||||
if err := shareDB.Load(getShareUploadsFile()); err != nil {
|
||||
return err.Trace(getShareUploadsFile())
|
||||
}
|
||||
|
||||
// Make new entries to uploadsDB.
|
||||
shareDB.Set(objectURL, shareURL, expiry, contentType)
|
||||
shareDB.Save(getShareUploadsFile())
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// doShareUploadURL uploads files to the target.
|
||||
func doShareUploadURL(objectURL string, isRecursive bool, expiry time.Duration, contentType string) *probe.Error {
|
||||
clnt, err := newClient(objectURL)
|
||||
if err != nil {
|
||||
return err.Trace(objectURL)
|
||||
}
|
||||
|
||||
// Generate pre-signed access info.
|
||||
uploadInfo, err := clnt.ShareUpload(isRecursive, expiry, contentType)
|
||||
if err != nil {
|
||||
return err.Trace(objectURL, "expiry="+expiry.String(), "contentType="+contentType)
|
||||
}
|
||||
|
||||
// Get the new expanded url.
|
||||
objectURL = clnt.GetURL().String()
|
||||
|
||||
// Generate curl command.
|
||||
curlCmd := makeCurlCmd(objectURL, isRecursive, uploadInfo)
|
||||
|
||||
printMsg(shareMesssage{
|
||||
ObjectURL: objectURL,
|
||||
ShareURL: curlCmd,
|
||||
TimeLeft: expiry,
|
||||
ContentType: contentType,
|
||||
})
|
||||
|
||||
// save shared URL to disk.
|
||||
return saveSharedURL(objectURL, curlCmd, expiry, contentType)
|
||||
}
|
||||
|
||||
// main for share upload command.
|
||||
func mainShareUpload(ctx *cli.Context) {
|
||||
// Set global flags from context.
|
||||
setGlobalsFromContext(ctx)
|
||||
|
||||
// check input arguments.
|
||||
checkShareUploadSyntax(ctx)
|
||||
|
||||
// Initialize share config folder.
|
||||
initShareConfig()
|
||||
|
||||
// Additional command speific theme customization.
|
||||
shareSetColor()
|
||||
|
||||
// Set command flags from context.
|
||||
isRecursive := ctx.Bool("recursive")
|
||||
expireArg := ctx.String("expire")
|
||||
expiry := shareDefaultExpiry
|
||||
contentType := ctx.String("content-type")
|
||||
if expireArg != "" {
|
||||
var e error
|
||||
expiry, e = time.ParseDuration(expireArg)
|
||||
fatalIf(probe.NewError(e), "Unable to parse expire=‘"+expireArg+"’.")
|
||||
}
|
||||
|
||||
for _, targetURL := range ctx.Args() {
|
||||
err := doShareUploadURL(targetURL, isRecursive, expiry, contentType)
|
||||
fatalIf(err.Trace(targetURL), "Unable to generate curl command for upload ‘"+targetURL+"’.")
|
||||
}
|
||||
}
|
||||
@@ -1,197 +0,0 @@
|
||||
/*
|
||||
* Minio Client (C) 2014, 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
)
|
||||
|
||||
const (
|
||||
// Default expiry is 7 days (168h).
|
||||
shareDefaultExpiry = time.Duration(604800) * time.Second
|
||||
)
|
||||
|
||||
// Upload specific flags.
|
||||
var (
|
||||
shareFlagContentType = cli.StringFlag{
|
||||
Name: "content-type, T",
|
||||
Usage: "Speific content-type to allow.",
|
||||
}
|
||||
shareFlagExpire = cli.StringFlag{
|
||||
Name: "expire, E",
|
||||
Value: "168h",
|
||||
Usage: "Set expiry in NN[h|m|s].",
|
||||
}
|
||||
)
|
||||
|
||||
// Structured share command message.
|
||||
type shareMesssage struct {
|
||||
Status string `json:"status"`
|
||||
ObjectURL string `json:"url"`
|
||||
ShareURL string `json:"share"`
|
||||
TimeLeft time.Duration `json:"timeLeft"`
|
||||
ContentType string `json:"contentType,omitempty"` // Only used by upload cmd.
|
||||
}
|
||||
|
||||
// String - Themefied string message for console printing.
|
||||
func (s shareMesssage) String() string {
|
||||
msg := console.Colorize("URL", fmt.Sprintf("URL: %s\n", s.ObjectURL))
|
||||
msg += console.Colorize("Expire", fmt.Sprintf("Expire: %s\n", timeDurationToHumanizedTime(s.TimeLeft)))
|
||||
if s.ContentType != "" {
|
||||
msg += console.Colorize("Content-type", fmt.Sprintf("Content-Type: %s\n", s.ContentType))
|
||||
}
|
||||
|
||||
// Highlight <FILE> specifically. "share upload" sub-commands use this identifier.
|
||||
shareURL := strings.Replace(s.ShareURL, "<FILE>", console.Colorize("File", "<FILE>"), 1)
|
||||
// Highlight <KEY> specifically for recursive operation.
|
||||
shareURL = strings.Replace(shareURL, "<NAME>", console.Colorize("File", "<NAME>"), 1)
|
||||
|
||||
msg += console.Colorize("Share", fmt.Sprintf("Share: %s\n", shareURL))
|
||||
|
||||
return msg
|
||||
}
|
||||
|
||||
// JSON - JSONified message for scripting.
|
||||
func (s shareMesssage) JSON() string {
|
||||
s.Status = "success"
|
||||
shareMessageBytes, e := json.Marshal(s)
|
||||
fatalIf(probe.NewError(e), "Failed to marshal into JSON.")
|
||||
|
||||
// JSON encoding escapes ampersand into its unicode character
|
||||
// which is not usable directly for share and fails with cloud
|
||||
// storage. convert them back so that they are usable.
|
||||
shareMessageBytes = bytes.Replace(shareMessageBytes, []byte("\\u0026"), []byte("&"), -1)
|
||||
shareMessageBytes = bytes.Replace(shareMessageBytes, []byte("\\u003c"), []byte("<"), -1)
|
||||
shareMessageBytes = bytes.Replace(shareMessageBytes, []byte("\\u003e"), []byte(">"), -1)
|
||||
|
||||
return string(shareMessageBytes)
|
||||
}
|
||||
|
||||
// shareSetColor sets colors share sub-commands.
|
||||
func shareSetColor() {
|
||||
// Additional command speific theme customization.
|
||||
console.SetColor("URL", color.New(color.FgWhite, color.Bold))
|
||||
console.SetColor("Expire", color.New(color.FgCyan))
|
||||
console.SetColor("Content-type", color.New(color.FgBlue))
|
||||
console.SetColor("Share", color.New(color.FgGreen))
|
||||
console.SetColor("File", color.New(color.FgRed, color.Bold))
|
||||
}
|
||||
|
||||
// Get share dir name.
|
||||
func getShareDir() (string, *probe.Error) {
|
||||
configDir, err := getMcConfigDir()
|
||||
if err != nil {
|
||||
return "", err.Trace()
|
||||
}
|
||||
|
||||
sharedURLsDataDir := filepath.Join(configDir, globalSharedURLsDataDir)
|
||||
return sharedURLsDataDir, nil
|
||||
}
|
||||
|
||||
// Get share dir name or die. (NOTE: This ‘Die’ approach is only OK for mc like tools.).
|
||||
func mustGetShareDir() string {
|
||||
shareDir, err := getShareDir()
|
||||
fatalIf(err.Trace(), "Unable to determine share folder.")
|
||||
return shareDir
|
||||
}
|
||||
|
||||
// Check if the share dir exists.
|
||||
func isShareDirExists() bool {
|
||||
if _, e := os.Stat(mustGetShareDir()); e != nil {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// Create config share dir.
|
||||
func createShareDir() *probe.Error {
|
||||
if e := os.MkdirAll(mustGetShareDir(), 0700); e != nil {
|
||||
return probe.NewError(e)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Get share uploads file.
|
||||
func getShareUploadsFile() string {
|
||||
return filepath.Join(mustGetShareDir(), "uploads.json")
|
||||
}
|
||||
|
||||
// Get share downloads file.
|
||||
func getShareDownloadsFile() string {
|
||||
return filepath.Join(mustGetShareDir(), "downloads.json")
|
||||
}
|
||||
|
||||
// Check if share uploads file exists?.
|
||||
func isShareUploadsExists() bool {
|
||||
if _, e := os.Stat(getShareUploadsFile()); e != nil {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// Check if share downloads file exists?.
|
||||
func isShareDownloadsExists() bool {
|
||||
if _, e := os.Stat(getShareDownloadsFile()); e != nil {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// Initialize share uploads file.
|
||||
func initShareUploadsFile() *probe.Error {
|
||||
return newShareDBV1().Save(getShareUploadsFile())
|
||||
}
|
||||
|
||||
// Initialize share downloads file.
|
||||
func initShareDownloadsFile() *probe.Error {
|
||||
return newShareDBV1().Save(getShareDownloadsFile())
|
||||
}
|
||||
|
||||
// Initialize share directory, if not done already.
|
||||
func initShareConfig() {
|
||||
// Share directory.
|
||||
if !isShareDirExists() {
|
||||
fatalIf(createShareDir().Trace(mustGetShareDir()),
|
||||
"Failed to create share ‘"+mustGetShareDir()+"’ folder.")
|
||||
console.Infof("Successfully created ‘%s’.\n", mustGetShareDir())
|
||||
}
|
||||
|
||||
// Uploads share file.
|
||||
if !isShareUploadsExists() {
|
||||
fatalIf(initShareUploadsFile().Trace(getShareUploadsFile()),
|
||||
"Failed to initialize share uploads ‘"+getShareUploadsFile()+"’ file.")
|
||||
console.Infof("Initialized share uploads ‘%s’ file.\n", getShareUploadsFile())
|
||||
}
|
||||
|
||||
// Downloads share file.
|
||||
if !isShareDownloadsExists() {
|
||||
fatalIf(initShareDownloadsFile().Trace(getShareDownloadsFile()),
|
||||
"Failed to initialize share downloads ‘"+getShareDownloadsFile()+"’ file.")
|
||||
console.Infof("Initialized share downloads ‘%s’ file.\n", getShareDownloadsFile())
|
||||
}
|
||||
}
|
||||
-46
@@ -1,46 +0,0 @@
|
||||
/*
|
||||
* Minio Client, (C) 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"os/signal"
|
||||
)
|
||||
|
||||
// signalTrap traps the registered signals and notifies the caller.
|
||||
func signalTrap(sig ...os.Signal) <-chan bool {
|
||||
// channel to notify the caller.
|
||||
trapCh := make(chan bool, 1)
|
||||
|
||||
go func(chan<- bool) {
|
||||
// channel to receive signals.
|
||||
sigCh := make(chan os.Signal, 1)
|
||||
defer close(sigCh)
|
||||
|
||||
// `signal.Notify` registers the given channel to
|
||||
// receive notifications of the specified signals.
|
||||
signal.Notify(sigCh, sig...)
|
||||
|
||||
// Wait for the signal.
|
||||
<-sigCh
|
||||
|
||||
// Notify the caller.
|
||||
trapCh <- true
|
||||
}(trapCh)
|
||||
|
||||
return trapCh
|
||||
}
|
||||
-34
@@ -1,34 +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
|
||||
|
||||
// commonPrefix returns the longest common prefix between two strings.
|
||||
func commonPrefix(first, second string) string {
|
||||
if first == "" || second == "" {
|
||||
return ""
|
||||
}
|
||||
if first > second {
|
||||
// Pick the shorter one for looping.
|
||||
first, second = second, first
|
||||
}
|
||||
for i := range first {
|
||||
if first[i] != second[i] {
|
||||
return first[:i]
|
||||
}
|
||||
}
|
||||
return first
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
# Compiled Object files, Static and Dynamic libs (Shared Objects)
|
||||
*.o
|
||||
*.a
|
||||
*.so
|
||||
|
||||
# Folders
|
||||
_obj
|
||||
_test
|
||||
|
||||
# Architecture specific extensions/prefixes
|
||||
*.[568vq]
|
||||
[568vq].out
|
||||
|
||||
*.cgo1.go
|
||||
*.cgo2.c
|
||||
_cgo_defun.c
|
||||
_cgo_gotypes.go
|
||||
_cgo_export.*
|
||||
|
||||
_testmain.go
|
||||
|
||||
*.exe
|
||||
*.test
|
||||
*.prof
|
||||
-202
@@ -1,202 +0,0 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "{}"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright {yyyy} {name of copyright owner}
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
|
||||
@@ -1,2 +0,0 @@
|
||||
## mc-tests
|
||||
Scripts written for daily automated testing.
|
||||
@@ -1,69 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
ME=$(basename "$0")
|
||||
BASE_DIR=$(dirname "$0")
|
||||
MINIO_WORK_DIR="$PWD/automated-tests"
|
||||
TEST_CASE_DIR="$BASE_DIR/tests"
|
||||
|
||||
function fatal()
|
||||
{
|
||||
ec=$1
|
||||
shift
|
||||
if [ "$@" ]; then
|
||||
echo "Fatal: $@" >&2
|
||||
fi
|
||||
exit $ec
|
||||
}
|
||||
|
||||
function error()
|
||||
{
|
||||
echo "Error: $@" >&2
|
||||
}
|
||||
|
||||
function msg()
|
||||
{
|
||||
echo "Info: $@" >&1
|
||||
}
|
||||
|
||||
function go_get()
|
||||
{
|
||||
go get -d -u "$@" && make -C "$GOPATH/src/$@"
|
||||
rv=$?
|
||||
|
||||
if [ $rv -ne 0 ]; then
|
||||
error "failed to get $@."
|
||||
return $rv
|
||||
fi
|
||||
}
|
||||
|
||||
function run_minio()
|
||||
{
|
||||
go_get github.com/minio/minio || fatal 1
|
||||
[ ! -d "$MINIO_WORK_DIR" ] && mkdir -p "$MINIO_WORK_DIR"
|
||||
minio --anonymous server "$MINIO_WORK_DIR" || fatal 1 "failed to run minio server."
|
||||
}
|
||||
|
||||
function install_mc()
|
||||
{
|
||||
go_get github.com/minio/mc || fatal 2
|
||||
}
|
||||
|
||||
function main()
|
||||
{
|
||||
which go >/dev/null || fatal 1 "go executable not found."
|
||||
[ "$GOPATH" ] || fatal 1 "GOPATH env not found."
|
||||
|
||||
if [ "$1" == "minio" ]; then
|
||||
msg "Running minio server."
|
||||
run_minio
|
||||
fi
|
||||
|
||||
msg "Running all mc tests."
|
||||
for test_script in $TEST_CASE_DIR/*; do
|
||||
if [ -x "$test_script" ]; then
|
||||
"$test_script" "$@" || error "test $test_script failed."
|
||||
fi
|
||||
done
|
||||
}
|
||||
|
||||
main "$@"
|
||||
@@ -1,5 +0,0 @@
|
||||
# Test case HOWTO
|
||||
|
||||
* Test case is usually a bash shell script, but technically any executable
|
||||
* Test case is run with two arguments now ie server-name and source-dir-name.
|
||||
* Test case should check/validate mc command output and return exit code accordingly.
|
||||
@@ -1,6 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
server="$1"
|
||||
|
||||
mc --json access set readonly "$server/testbucket"
|
||||
# TODO: validate output
|
||||
@@ -1,7 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
server="$1"
|
||||
dir="$2"
|
||||
|
||||
mc --json cp "$dir..." "$server/testbucket"
|
||||
# TODO: validate output
|
||||
@@ -1,6 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
server="$1"
|
||||
|
||||
mc --json ls "$server"
|
||||
# TODO: validate output
|
||||
@@ -1,6 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
server="$1"
|
||||
|
||||
mc --json rm --force "$server/testbucket..."
|
||||
# TODO: validate output
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user