Compare commits

..
Author SHA1 Message Date
Pavlo Ratushnyi 897dc478be LEAS-2795 mc: put-denied accepts the insufficient permissions wording of mc (run 3926)
release / release (push) Failing after 2m16s
2026-11-14 13:51:19 +01:00
Pavlo Ratushnyi bb972dde65 LEAS-2795 mc: print the denied PUT output (run 3924)
release / release (push) Failing after 3m7s
2026-11-14 13:39:14 +01:00
Pavlo Ratushnyi f14f61e47c LEAS-2795 mc: read-only smoke user has a three character name at least (run 3923)
release / release (push) Failing after 1m52s
2026-11-14 13:36:58 +01:00
Pavlo Ratushnyi 06ea8746d3 LEAS-2795 mc: root user of the smoke is 16 characters (run 3921)
release / release (push) Failing after 1m59s
2026-11-14 13:34:28 +01:00
Pavlo Ratushnyi 9318e1b7a7 LEAS-2795 mc: read both versions back by versionId without assuming the listing order (run 3920)
release / release (push) Failing after 1m46s
2026-11-14 13:32:19 +01:00
Pavlo Ratushnyi 4dab718e87 LEAS-2795 mc: bucket name of the smoke has three characters at least (run 3919)
release / release (push) Failing after 1m54s
2026-11-14 13:29:52 +01:00
Pavlo Ratushnyi 4c955aba31 LEAS-2795 mc: pass RECIPE_COMMIT to the image check (run 3918)
release / release (push) Failing after 1m49s
2026-11-14 13:27:38 +01:00
Pavlo Ratushnyi 5f0b4dcf4b LEAS-2795 mc: smoke and SOURCE template
release / release (push) Failing after 1m17s
2026-11-14 13:26:02 +01:00
Pavlo Ratushnyi b9e090f48a LEAS-2795 mc: gates, image check and release workflow 2026-11-14 13:26:01 +01:00
Pavlo Ratushnyi dbd79a6da1 LEAS-2795 mc: Dockerfile with pins, build and final stages 2026-11-14 13:26:00 +01:00
Pavlo Ratushnyi 4c2d094a4a LEAS-2795 mc: PINS, ignore files, README 2026-11-14 13:25:57 +01:00
Pavlo Ratushnyi 860e03059a LEAS-2795 mc: vezha recipe branch root 2026-11-14 13:13:15 +01:00
268 changed files with 1103 additions and 34382 deletions
+3
View File
@@ -0,0 +1,3 @@
.git
.gitea
out
+221
View File
@@ -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
View File
@@ -1,4 +1,3 @@
cover.out
mc
*~
*.test
/src/
/out/
/vezha/SOURCE
-15
View File
@@ -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>
-9
View File
@@ -1,9 +0,0 @@
language: go
script:
- make test GOFLAGS="-race"
go:
- 1.5.1
sudo: false
notifications:
slack:
secure: McinxQ4R/Yu2r/U8lVsdAIQ195Rf+3/Ku6DViWyqLHsTt5fTnVrSfbIKs8vy0t2A0bRLO6zv2xOSMWjfiimZLPMgMbMqLtTFEzUzB8RZyx2n2xgmL8q3gjXcLA3vkBreaRYCzJzX6DjvrxRfhyOg+BQHpLpACWik3FS/7VIdDCI=
-40
View File
@@ -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 depedencies 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
-9
View File
@@ -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>
-83
View File
@@ -1,83 +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
```
```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 enviornment
```sh
$ source ~/.bash_profile
```
##### Testing it all
```sh
$ go env
```
-202
View File
@@ -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.
-46
View File
@@ -1,46 +0,0 @@
# For maintainers only
## Responsibilities
Please go through this link [Maintainer Responsibility](https://gist.github.com/abperiasamy/f4d9b31d3186bbd26522)
## Current Maintainers
- Harshavardhana
- Krishna Srinivas
### 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`
-84
View File
@@ -1,84 +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 .
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
-9
View File
@@ -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.
-106
View File
@@ -1,106 +0,0 @@
# Minio Client (mc) [![Gitter](https://badges.gitter.im/Join%20Chat.svg)](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 [![Build Status](https://api.travis-ci.org/minio/mc.svg?branch=master)](https://travis-ci.org/minio/mc) [![Build status](https://ci.appveyor.com/api/projects/status/3ng8bef7b3e1v763?svg=true)](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’ continous 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 <YOUR-S3-ENDPOINT> <YOUR-ACCESS-KEY> <YOUR-SECRET-KEY> S3v4
```
Example
```
$ mc config host add 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 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.
-210
View File
@@ -1,210 +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.amazonaws.com/burningman2011
2. Set bucket to "public" on Amazon S3 cloud storage.
$ mc {{.Name}} set public s3.amazonaws.com/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.amazonaws.com/shared-authenticated
4. Get bucket permissions.
$ mc {{.Name}} get s3.amazonaws.com/shared
5. Get bucket permissions.
$ mc {{.Name}} get storage.googleapis.com/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, err := json.Marshal(s)
fatalIf(probe.NewError(err), "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 := url2Client(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 := url2Client(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, err := args2URLs(ctx.Args().Tail().Tail())
fatalIf(err.Trace(ctx.Args().Tail().Tail()...), "Unable to convert args 2 URLs.")
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, err := args2URLs(ctx.Args().Tail())
fatalIf(err.Trace(ctx.Args().Tail()...), "Unable to convert args 2 URLs.")
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,
})
}
}
}
-96
View File
@@ -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
}
-139
View File
@@ -1,139 +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"
"sync"
"sync/atomic"
"time"
)
// accountingReader - implements and inherits io.ReadCloser interface for accounter.
type accountingReader struct {
io.ReadSeeker
acct *accounter
}
// 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
}
}
// Add add to current values atomically.
func (a *accounter) Add(n int64) int64 {
return atomic.AddInt64(&a.current, n)
}
// Instantiate a new proxy reader for accounter.
func (a *accounter) NewProxyReader(r io.ReadSeeker) *accountingReader {
return &accountingReader{r, a}
}
// Read implement Reader which internally updates current value.
func (a *accountingReader) Read(p []byte) (n int, err error) {
n, err = a.ReadSeeker.Read(p)
if err != nil {
return
}
a.acct.Add(int64(n))
return
}
// Seek implement Seeker.
func (a *accountingReader) Seek(offset int64, whence int) (n int64, err error) {
n, err = a.ReadSeeker.Seek(offset, whence)
if err != nil {
return
}
a.acct.Add(n)
return
}
-74
View File
@@ -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 main
import (
"os"
"regexp"
"runtime"
"strings"
"github.com/minio/mc/pkg/client"
"github.com/minio/minio-xl/pkg/probe"
)
// isValidAliasName - Check if aliasName is a valid alias.
func isValidAliasName(aliasName string) bool {
return regexp.MustCompile("^[a-zA-Z][a-zA-Z0-9-]+$").MatchString(aliasName)
}
// normalizeAliasedURL - remove any preceding separators.
func normalizeAliasedURL(aliasedURL string) string {
if runtime.GOOS == "windows" {
aliasedURL = strings.Replace(aliasedURL, "/", "\\", -1)
}
aliasedURL = strings.TrimPrefix(aliasedURL, string(os.PathSeparator))
return aliasedURL
}
// getAliasURL expands aliased (name/path) to full URL, used by url-parser.
func getAliasURL(aliasedURL string) (string, *probe.Error) {
config, err := loadMcConfig()
if err != nil {
return aliasedURL, err.Trace(aliasedURL)
}
if strings.HasPrefix(aliasedURL, "https") || strings.HasPrefix(aliasedURL, "http") {
return aliasedURL, nil
}
for hostURL := range config.Hosts {
url := client.NewURL(hostURL)
if strings.Contains(aliasedURL, url.Host) {
return url.Scheme + url.SchemeSeparator + aliasedURL, nil
}
}
normalizedAliasURL := normalizeAliasedURL(aliasedURL)
for aliasName, aliasValue := range config.Aliases {
if strings.HasPrefix(normalizedAliasURL, aliasName) {
// Match found. Expand it.
if !strings.Contains(normalizedAliasURL, string(os.PathSeparator)) {
return aliasValue, nil
}
splits := strings.SplitN(normalizedAliasURL, string(os.PathSeparator), 2)
if len(splits) == 1 {
return aliasedURL, nil // Not an aliased URL. Return as is.
}
// Matched, but path needs to be joined.
return urlJoinPath(aliasValue, splits[1]), nil
}
}
return aliasedURL, nil // No matching alias found. Return as is.
}
-168
View File
@@ -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 (
"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, err := strconv.Atoi(r.Header.Get("Content-Length"))
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
var buffer bytes.Buffer
_, err = io.CopyN(&buffer, r.Body, int64(length))
if err != 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)
}
}
-44
View File
@@ -1,44 +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
# 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...
- gocyclo -over 40 .
- 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
-28
View File
@@ -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]
)
-239
View File
@@ -1,239 +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
GCC_VERSION="4.0"
CLANG_VERSION="7.0.0"
YASM_VERSION="1.2.0"
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
case ${UNAME%% *} in
"Linux")
check_version "$(env gcc --version 2>/dev/null | sed 's/^.* \([0-9.]*\).*$/\1/' | head -1)" "${GCC_VERSION}"
if [ $? -ge 2 ]; then
MISSING="${MISSING} build-essential(${GCC_VERSION})"
fi
;;
"Darwin")
check_version "$(env gcc --version 2>/dev/null | awk '{print $4}' | head -1)" "${CLANG_VERSION}"
if [ $? -ge 2 ]; then
MISSING="${MISSING} xcode-cli(${CLANG_VERSION})"
fi
;;
"*")
;;
esac
}
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 "$@"
-70
View File
@@ -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)))
}
-159
View File
@@ -1,159 +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.amazonaws.com/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.ReadSeeker
switch sourceURL {
case "-":
reader = os.Stdin
default:
sourceClnt, err := url2Client(sourceURL)
if err != nil {
return err.Trace(sourceURL)
}
// Ignore size, since os.Stat() would not return proper size all the
// time for local filesystem for example /proc files.
reader, err = sourceClnt.Get(0, 0)
if 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 _, err := io.Copy(os.Stdout, r); err != nil {
switch e := err.(type) {
case *os.PathError:
if e.Err == syscall.EPIPE {
// stdout closed by the user. Gracefully exit.
return nil
}
return probe.NewError(err)
default:
return probe.NewError(err)
}
}
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.
URLs, err := args2URLs(args)
fatalIf(err.Trace(args...), "Unable to parse arguments.")
for _, url := range URLs {
fatalIf(catURL(url).Trace(url), "Unable to read from ‘"+url+"’.")
}
}
-54
View File
@@ -1,54 +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/ioutil"
"os"
"path/filepath"
"github.com/minio/minio-xl/pkg/probe"
. "gopkg.in/check.v1"
)
func (s *TestSuite) TestCat(c *C) {
/// filesystem
root, e := ioutil.TempDir(os.TempDir(), "cmd-")
c.Assert(e, IsNil)
defer os.RemoveAll(root)
objectPath := filepath.Join(root, "object1")
objectPathServer := server.URL + "/bucket/object1"
data := "hello"
var err *probe.Error
err = putTarget(objectPath, bytes.NewReader([]byte(data)), int64(len(data)))
c.Assert(err, IsNil)
err = putTarget(objectPathServer, bytes.NewReader([]byte(data)), int64(len(data)))
c.Assert(err, IsNil)
var sourceURLs []string
sourceURLs = append(sourceURLs, objectPath)
sourceURLs = append(sourceURLs, objectPathServer)
for _, sourceURL := range sourceURLs {
c.Assert(catURL(sourceURL), IsNil)
}
objectPath = filepath.Join(root, "object2")
c.Assert(catURL(objectPath), Not(IsNil))
}
-111
View File
@@ -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 (
"io"
"os"
"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 {
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 getSource(sourceURL string) (reader io.ReadSeeker, err *probe.Error) {
sourceClnt, err := url2Client(sourceURL)
if err != nil {
return nil, err.Trace(sourceURL)
}
return sourceClnt.Get(0, 0)
}
// putTarget writes to URL from reader. If length=-1, read until EOF.
func putTarget(targetURL string, reader io.ReadSeeker, size int64) *probe.Error {
targetClnt, err := url2Client(targetURL)
if err != nil {
return err.Trace(targetURL)
}
contentType := guessURLContentType(targetURL)
err = targetClnt.Put(reader, size, contentType)
if err != nil {
return err.Trace(targetURL)
}
return nil
}
// getNewClient gives a new client interface
func getNewClient(urlStr string, auth hostConfig) (client.Client, *probe.Error) {
url := client.NewURL(urlStr)
switch url.Type {
case client.Object: // Minio and S3 compatible cloud storage
s3Config := new(client.Config)
s3Config.AccessKeyID = func() string {
if auth.AccessKeyID == globalAccessKeyID {
return ""
}
return auth.AccessKeyID
}()
s3Config.SecretAccessKey = func() string {
if auth.SecretAccessKey == globalSecretAccessKey {
return ""
}
return auth.SecretAccessKey
}()
s3Config.Signature = auth.API
s3Config.AppName = "Minio"
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(urlStr)
}
return s3Client, nil
case client.Filesystem:
fsClient, err := fs.New(urlStr)
if err != nil {
return nil, err.Trace(urlStr)
}
return fsClient, nil
}
return nil, errInitClient(urlStr).Trace(urlStr)
}
-69
View File
@@ -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 main
import (
"bytes"
"io"
"io/ioutil"
"os"
"path/filepath"
. "gopkg.in/check.v1"
)
func (s *TestSuite) TestCommonMethods(c *C) {
/// filesystem
root, e := ioutil.TempDir(os.TempDir(), "cmd-")
c.Assert(e, IsNil)
defer os.RemoveAll(root)
objectPath := filepath.Join(root, "object1")
c.Assert(isTargetURLDir(root), Equals, true)
c.Assert(isTargetURLDir(objectPath), Equals, false)
objectPathServer := server.URL + "/bucket/object1"
data := "hello"
err := putTarget(objectPath, bytes.NewReader([]byte(data)), int64(len(data)))
c.Assert(err, IsNil)
err = putTarget(objectPathServer, bytes.NewReader([]byte(data)), int64(len(data)))
c.Assert(err, IsNil)
c.Assert(isTargetURLDir(objectPathServer), Equals, false)
c.Assert(isTargetURLDir(server.URL+"/bucket"), Equals, true)
reader, err := getSource(objectPathServer)
c.Assert(err, IsNil)
var results bytes.Buffer
_, e = io.Copy(&results, reader)
c.Assert(e, IsNil)
c.Assert([]byte(data), DeepEquals, results.Bytes())
_, content, err := url2Stat(objectPathServer)
c.Assert(err, IsNil)
c.Assert(content.Type.IsRegular(), Equals, true)
_, _, err = url2Stat(objectPath + "invalid")
c.Assert(err, Not(IsNil))
_, err = url2Client(objectPathServer)
c.Assert(err, IsNil)
_, err = url2Client(objectPathServer)
c.Assert(err, IsNil)
}
-232
View File
@@ -1,232 +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 (
configAliasFlags = []cli.Flag{
cli.BoolFlag{
Name: "help, h",
Usage: "Help of config alias.",
},
}
)
var configAliasCmd = cli.Command{
Name: "alias",
Usage: "List, modify and remove aliases in configuration file.",
Action: mainConfigAlias,
Flags: append(configAliasFlags, globalFlags...),
CustomHelpTemplate: `NAME:
mc config {{.Name}} - {{.Usage}}
USAGE:
mc config {{.Name}} [FLAGS] OPERATION [ARGS...]
OPERATION:
remove Remove a alias.
list List all aliases.
add Add new alias.
FLAGS:
{{range .Flags}}{{.}}
{{end}}
EXAMPLES:
1. Add aliases for Amazon S3.
$ mc config {{.Name}} add mcloud https://miniocloud.s3.amazonaws.com
$ mc ls mcloud
2. Add aliases for Google Cloud Storage.
$ mc config {{.Name}} add gcscloud https://miniocloud.storage.googleapis.com
$ mc ls gcscloud
3. List all aliased URLs.
$ mc config {{.Name}} list
4. Remove an alias
$ mc config {{.Name}} remove mcloud
`,
}
// aliasMessage container for content message structure
type aliasMessage struct {
op string
Status string `json:"status"`
Alias string `json:"alias"`
URL string `json:"url,omitempty"`
}
// String colorized alias message
func (a aliasMessage) String() string {
if a.op == "list" {
message := console.Colorize("Alias", fmt.Sprintf("[%s] <- ", a.Alias))
message += console.Colorize("URL", fmt.Sprintf("%s", a.URL))
return message
}
if a.op == "remove" {
return console.Colorize("AliasMessage", "Removed alias ‘"+a.Alias+"’ successfully.")
}
if a.op == "add" {
return console.Colorize("AliasMessage", "Added alias ‘"+a.Alias+"’ successfully.")
}
// should never come here
return ""
}
// JSON jsonified alias message
func (a aliasMessage) JSON() string {
a.Status = "success"
jsonMessageBytes, e := json.Marshal(a)
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(jsonMessageBytes)
}
// checkConfigAliasAddSyntax validate 'config alias add' input arguments.
func checkConfigAliasAddSyntax(ctx *cli.Context) {
if len(ctx.Args().Tail()) != 2 {
fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...),
"Incorrect number of arguments for add alias command.")
}
aliasName := ctx.Args().Tail().Get(0)
aliasedURL := ctx.Args().Tail().Get(1)
if aliasName == "" || aliasedURL == "" {
fatalIf(errDummy().Trace(), "Alias or URL cannot be empty.")
}
aliasedURL = strings.TrimSuffix(aliasedURL, "/")
if !strings.HasPrefix(aliasedURL, "http") {
fatalIf(errDummy().Trace(aliasedURL),
fmt.Sprintf("Invalid alias URL ‘%s’. Valid examples are: http://s3.amazonaws.com, https://yourbucket.example.com.", aliasedURL))
}
if !isValidAliasName(aliasName) {
fatalIf(errDummy().Trace(aliasName),
fmt.Sprintf("Alias name ‘%s’ is invalid, valid examples are: mybucket, Area51, Grand-Nagus", aliasName))
}
}
// checkConfigAliasRemoveSyntax validate 'config alias remove' input argument.
func checkConfigAliasRemoveSyntax(ctx *cli.Context) {
if len(ctx.Args().Tail()) != 1 {
fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...),
"Incorrect number of arguments for remove alias command.")
}
aliasName := ctx.Args().Tail().Get(0)
if strings.TrimSpace(aliasName) == "" {
fatalIf(errDummy().Trace(), "Alias or URL cannot be empty.")
}
if !isValidAliasName(aliasName) {
fatalIf(errDummy().Trace(aliasName),
fmt.Sprintf("Alias name ‘%s’ is invalid, valid examples are: mybucket, Area51, Grand-Nagus", aliasName))
}
}
func checkConfigAliasSyntax(ctx *cli.Context) {
// show help if nothing is set
if !ctx.Args().Present() || ctx.Args().First() == "help" {
cli.ShowCommandHelpAndExit(ctx, "alias", 1) // last argument is exit code
}
if strings.TrimSpace(ctx.Args().First()) == "" {
cli.ShowCommandHelpAndExit(ctx, "alias", 1) // last argument is exit code
}
if len(ctx.Args().Tail()) > 2 {
fatalIf(errDummy().Trace(ctx.Args().Tail()...), "Incorrect number of arguments to alias command")
}
switch strings.TrimSpace(ctx.Args().Get(0)) {
case "add":
checkConfigAliasAddSyntax(ctx)
case "remove":
checkConfigAliasRemoveSyntax(ctx)
case "list":
default:
cli.ShowCommandHelpAndExit(ctx, "alias", 1) // last argument is exit code
}
}
// addAlias - adds an alias entry.
func addAlias(aliasName, aliasedURL string) {
conf, err := loadMcConfig()
fatalIf(err.Trace(globalMCConfigVersion), "Unable to load config version ‘"+globalMCConfigVersion+"’.")
conf.Aliases[aliasName] = aliasedURL
err = saveMcConfig(conf)
fatalIf(err.Trace(aliasName, aliasedURL), "Unable to update aliases in config version ‘"+globalMCConfigVersion+"’.")
printMsg(aliasMessage{op: "add", Alias: aliasName, URL: aliasedURL})
}
// removeAlias - remove a alias.
func removeAlias(aliasName string) {
conf, err := loadMcConfig()
fatalIf(err.Trace(globalMCConfigVersion), "Unable to load config version ‘"+globalMCConfigVersion+"’.")
delete(conf.Aliases, aliasName)
err = saveMcConfig(conf)
fatalIf(err.Trace(aliasName), "Unable to save deleted alias in config version ‘"+globalMCConfigVersion+"’.")
printMsg(aliasMessage{op: "remove", Alias: aliasName})
}
// listAliases - list aliases.
func listAliases() {
conf, err := loadMcConfig()
fatalIf(err.Trace(globalMCConfigVersion), "Unable to load config version ‘"+globalMCConfigVersion+"’")
for aliasName, aliasedURL := range conf.Aliases {
printMsg(aliasMessage{op: "list", Alias: aliasName, URL: aliasedURL})
}
}
func mainConfigAlias(ctx *cli.Context) {
// Set global flags from context.
setGlobalsFromContext(ctx)
// check 'config alias' cli arguments.
checkConfigAliasSyntax(ctx)
// Additional customization speific to each command.
console.SetColor("Alias", color.New(color.FgCyan, color.Bold))
console.SetColor("AliasMessage", color.New(color.FgGreen, color.Bold))
console.SetColor("URL", color.New(color.FgWhite, color.Bold))
arg := ctx.Args().First()
tailArgs := ctx.Args().Tail()
switch strings.TrimSpace(arg) {
case "add":
aliasName := tailArgs.Get(0)
aliasedURL := tailArgs.Get(1)
addAlias(aliasName, aliasedURL) // add alias name for aliased URL.
case "remove":
aliasName := tailArgs.Get(0)
removeAlias(aliasName) // remove alias name.
case "list":
listAliases() // list all aliases.
}
}
-324
View File
@@ -1,324 +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 [ARGS...]
OPERATION:
remove Remove a host.
list list all hosts.
add Add new host.
FLAGS:
{{range .Flags}}{{.}}
{{end}}
EXAMPLES:
1. Add host configuration for a URL, using default signature V4. For security reasons turn off bash history
$ set +o history
$ mc config {{.Name}} add https://s3.amazonaws.com BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12
$ set -o history
2. Add host configuration for a URL, using signature V2. For security reasons turn off bash history
$ set +o history
$ mc config {{.Name}} add https://storage.googleapis.com BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 S3v2
$ set -o history
3. Add host configuration for a URL by importing credentials csv file.
$ mc config {{.Name}} import https://s3.amazonaws.com credentials.csv
4. List all hosts.
$ mc config {{.Name}} list
5. Remove host config.
$ mc config {{.Name}} remove https://s3.amazonaws.com
`,
}
// hostMessage container for content message structure
type hostMessage struct {
op string
Status string `json:"status"`
Host string `json:"host"`
AccessKeyID string `json:"accessKeyId,omitempty"`
SecretAccessKey string `json:"secretAccessKey,omitempty"`
API string `json:"api,omitempty"`
}
// String colorized host message
func (a hostMessage) String() string {
if a.op == "list" {
message := console.Colorize("Host", fmt.Sprintf("[%s] ", a.Host))
if a.AccessKeyID != "" || a.SecretAccessKey != "" {
message += console.Colorize("AccessKeyID", fmt.Sprintf("<- %s,", a.AccessKeyID))
message += console.Colorize("SecretAccessKey", fmt.Sprintf(" %s,", a.SecretAccessKey))
message += console.Colorize("API", fmt.Sprintf(" %s", a.API))
}
return message
}
if a.op == "remove" {
return console.Colorize("HostMessage", "Removed host ‘"+a.Host+"’ successfully.")
}
if a.op == "add" {
return console.Colorize("HostMessage", "Added host ‘"+a.Host+"’ successfully.")
}
// should never reach here
return ""
}
// JSON jsonified host message
func (a hostMessage) JSON() string {
a.Status = "success"
jsonMessageBytes, e := json.Marshal(a)
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(jsonMessageBytes)
}
func checkConfigHostSyntax(ctx *cli.Context) {
// show help if nothing is set
if !ctx.Args().Present() || ctx.Args().First() == "help" {
cli.ShowCommandHelpAndExit(ctx, "host", 1) // last argument is exit code
}
if strings.TrimSpace(ctx.Args().First()) == "" {
cli.ShowCommandHelpAndExit(ctx, "host", 1) // last argument is exit code
}
if len(ctx.Args().Tail()) > 4 {
fatalIf(errDummy().Trace(ctx.Args().Tail()...), "Incorrect number of arguments to host command")
}
switch strings.TrimSpace(ctx.Args().First()) {
case "add":
checkConfigHostAddSyntax(ctx)
case "import":
checkConfigHostImportSyntax(ctx)
case "remove":
checkConfigHostRemoveSyntax(ctx)
case "list":
default:
cli.ShowCommandHelpAndExit(ctx, "host", 1) // last argument is exit code
}
}
// checkConfigHostImportSyntax - verifies input arguments to 'config host import'.
func checkConfigHostImportSyntax(ctx *cli.Context) {
tailArgs := ctx.Args().Tail()
if len(ctx.Args().Tail()) < 2 || len(ctx.Args().Tail()) > 3 {
fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...),
"Incorrect number of arguments for import host command.")
}
newHostURL := tailArgs.Get(0)
credentialsFile := tailArgs.Get(1)
api := tailArgs.Get(2)
if !isValidHostURL(newHostURL) {
fatalIf(errDummy().Trace(newHostURL),
"Invalid host ‘"+newHostURL+"’. Valid options are [http://example.test.io, https://bucket.s3.amazonaws.com].")
}
if strings.TrimSpace(credentialsFile) == "" {
fatalIf(errDummy().Trace(), "Credentials file cannot be empty.")
}
if strings.TrimSpace(api) == "" {
api = "S3v4"
}
if strings.TrimSpace(api) != "S3v2" && strings.TrimSpace(api) != "S3v4" {
fatalIf(errInvalidArgument().Trace(api),
"Unrecognized api version. Valid options are ‘[ S3v4, S3v2 ]’.")
}
}
// checkConfigHostAddSyntax - verifies input arguments to 'config host add'.
func checkConfigHostAddSyntax(ctx *cli.Context) {
tailArgs := ctx.Args().Tail()
if len(ctx.Args().Tail()) < 3 || len(ctx.Args().Tail()) > 4 {
fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...),
"Incorrect number of arguments for host add command.")
}
newHostURL := tailArgs.Get(0)
accessKeyID := tailArgs.Get(1)
secretAccessKey := tailArgs.Get(2)
api := tailArgs.Get(3)
if !isValidHostURL(newHostURL) {
fatalIf(errDummy().Trace(newHostURL),
"Invalid host URL: ‘"+newHostURL+"’. Valid options are [http://example.test.io, https://bucket.s3.amazonaws.com].")
}
if !isValidKeys(accessKeyID, secretAccessKey) {
fatalIf(errInvalidArgument().Trace(accessKeyID, secretAccessKey),
"Invalid access key id/secret access key for ‘"+newHostURL+"’")
}
if strings.TrimSpace(api) == "" {
api = "S3v4"
}
if strings.TrimSpace(api) != "S3v2" && strings.TrimSpace(api) != "S3v4" {
fatalIf(errInvalidArgument().Trace(api),
"Unrecognized api version. 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(ctx.Args().Tail()...),
"Incorrect number of arguments for remove host command.")
}
if !isValidHostURL(tailArgs.Get(0)) {
fatalIf(errDummy().Trace(tailArgs.Get(0)),
"Invalid host ‘"+tailArgs.Get(0)+"’. Valid options are [http://example.test.io, https://bucket.s3.amazonaws.com].")
}
if strings.TrimSpace(tailArgs.Get(0)) == "https://dl.minio.io:9000" {
fatalIf(errDummy().Trace(tailArgs.Get(0)),
"‘"+tailArgs.Get(0)+"’ is reserved hostname and cannot be removed.")
}
}
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("Host", color.New(color.FgCyan, color.Bold))
console.SetColor("API", color.New(color.FgYellow, color.Bold))
console.SetColor("HostMessage", color.New(color.FgGreen, color.Bold))
console.SetColor("AccessKeyID", color.New(color.FgBlue, color.Bold))
console.SetColor("SecretAccessKey", color.New(color.FgRed, color.Bold))
arg := ctx.Args().First()
tailArgs := ctx.Args().Tail()
// Switch case through commands.
switch strings.TrimSpace(arg) {
case "add":
hostURL := tailArgs.Get(0)
accessKeyID := tailArgs.Get(1)
secretAccessKey := tailArgs.Get(2)
api := tailArgs.Get(3)
if strings.TrimSpace(api) == "" {
api = "S3v4"
}
hostCfg := hostConfig{
AccessKeyID: accessKeyID,
SecretAccessKey: secretAccessKey,
API: api,
}
addHost(hostURL, hostCfg) // Add a host with specified credentials.
case "import":
hostURL := tailArgs.Get(0)
credentialsFile := tailArgs.Get(1)
api := tailArgs.Get(2)
if strings.TrimSpace(api) == "" {
api = "S3v4"
}
creds, err := getCredentials(credentialsFile)
fatalIf(err.Trace(credentialsFile), "Unable to unmarshal CSV credentials file ‘"+credentialsFile+"’")
var hostCfg hostConfig
hostCfg = hostConfig{
AccessKeyID: creds[0].AccessKeyID,
SecretAccessKey: creds[0].SecretAccessKey,
API: api,
}
addHost(hostURL, hostCfg) // Import credentials through a CSV file for a host.
case "remove":
hostURL := tailArgs.Get(0)
removeHost(hostURL) // Remove a host.
case "list":
listHosts() // List all configured hosts.
}
}
// addHost - add a host config.
func addHost(hostURL string, hostCfg hostConfig) {
conf, err := loadMcConfig()
fatalIf(err.Trace(globalMCConfigVersion), "Unable to load config version ‘"+globalMCConfigVersion+"’.")
// Add new host.
conf.Hosts[hostURL] = hostCfg
err = saveMcConfig(conf)
fatalIf(err.Trace(hostURL), "Unable to update hosts in config version ‘"+globalMCConfigVersion+"’.")
printMsg(hostMessage{
op: "add",
Host: hostURL,
AccessKeyID: hostCfg.AccessKeyID,
SecretAccessKey: hostCfg.SecretAccessKey,
API: hostCfg.API,
})
}
// removeHost - removes a host.
func removeHost(hostURL string) {
conf, err := loadMcConfig()
fatalIf(err.Trace(globalMCConfigVersion), "Unable to load config version ‘"+globalMCConfigVersion+"’.")
// Remove host.
delete(conf.Hosts, hostURL)
err = saveMcConfig(conf)
fatalIf(err.Trace(hostURL), "Unable to save deleted hosts in config version ‘"+globalMCConfigVersion+"’.")
printMsg(hostMessage{op: "remove", Host: hostURL})
}
// 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",
Host: k,
AccessKeyID: v.AccessKeyID,
SecretAccessKey: v.SecretAccessKey,
API: v.API,
})
}
}
-79
View File
@@ -1,79 +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{
configAliasCmd,
configHostCmd,
configVersionCmd,
},
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.
}
-580
View File
@@ -1,580 +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 (
"strings"
"github.com/minio/mc/pkg/client"
"github.com/minio/mc/pkg/console"
"github.com/minio/minio-xl/pkg/quick"
)
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()
}
func fixConfig() {
// Fix config V3
fixConfigV3()
// Fix config V6
fixConfigV6()
// Fix config V6 for hosts
fixConfigV6ForHosts()
}
func fixConfigV6ForHosts() {
if !isMcConfigExists() {
return
}
config, err := quick.New(newConfigV6())
fatalIf(err.Trace(), "Unable to initialize config.")
err = config.Load(mustGetMcConfigPath())
fatalIf(err.Trace(), "Unable to load config.")
if config.Data().(*configV6).Version == "6" {
newConfig := new(configV6)
newConfig.Aliases = make(map[string]string)
newConfig.Hosts = make(map[string]hostConfig)
newConfig.Version = "6"
newConfig.Aliases = config.Data().(*configV6).Aliases
url := new(client.URL)
for host, hostCfg := range config.Data().(*configV6).Hosts {
// Already fixed - move on.
if strings.HasPrefix(host, "https") || strings.HasPrefix(host, "http") {
newConfig.Hosts[host] = hostCfg
continue
}
if host == "s3.amazonaws.com" || host == "storage.googleapis.com" {
console.Infoln("Found hosts, replacing " + host + " with https://" + host)
url.Host = host
url.Scheme = "https"
url.SchemeSeparator = "://"
newConfig.Hosts[url.String()] = hostCfg
delete(newConfig.Hosts, host)
}
if host == "localhost:9000" || host == "127.0.0.1:9000" {
console.Infoln("Found hosts, replacing " + host + " with http://" + host)
url.Host = host
url.Scheme = "http"
url.SchemeSeparator = "://"
newConfig.Hosts[url.String()] = hostCfg
delete(newConfig.Hosts, host)
}
if host == "play.minio.io:9000" || host == "dl.minio.io:9000" {
console.Infoln("Found hosts, replacing " + host + " with https://" + host)
url.Host = host
url.Scheme = "https"
url.SchemeSeparator = "://"
newConfig.Hosts[url.String()] = hostCfg
delete(newConfig.Hosts, host)
}
}
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.")
}
}
// 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" {
newConfig := new(configV6)
newConfig.Aliases = make(map[string]string)
newConfig.Hosts = make(map[string]hostConfig)
newConfig.Version = "6"
newConfig.Aliases = config.Data().(*configV6).Aliases
for host, hostCfg := range config.Data().(*configV6).Hosts {
if strings.HasPrefix(host, "https") || strings.HasPrefix(host, "http") {
newConfig.Hosts[host] = hostCfg
continue
}
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
continue
}
if strings.Contains(host, "s3*") {
console.Infoln("Found glob url, replacing " + host + " with s3.amazonaws.com")
newConfig.Hosts["s3.amazonaws.com"] = hostCfg
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
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
continue
}
if strings.Contains(host, "localhost:*") {
console.Infoln("Found glob url, replacing " + host + " with localhost:9000")
newConfig.Hosts["localhost:9000"] = hostCfg
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
continue
}
newConfig.Hosts[host] = hostCfg
}
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.")
}
}
type configV5 struct {
Version string `json:"version"`
Aliases map[string]string `json:"alias"`
Hosts map[string]hostConfig `json:"hosts"`
}
type configV4 struct {
Version string `json:"version"`
Aliases map[string]string `json:"alias"`
Hosts map[string]struct {
AccessKeyID string `json:"accessKeyId"`
SecretAccessKey string `json:"secretAccessKey"`
Signature string `json:"signature"`
} `json:"hosts"`
}
type configV3 struct {
Version string `json:"version"`
Aliases map[string]string `json:"alias"`
// custom anonymous struct is necessary from version to 3 to version 4
// since hostConfig{} has changed to camelcase fields for unmarshal
Hosts map[string]struct {
AccessKeyID string `json:"access-key-id"`
SecretAccessKey string `json:"secret-access-key"`
} `json:"hosts"`
}
type configV2 struct {
Version string
Aliases map[string]string
// custom anonymous struct is necessary from version to 2 to version 3
// since hostConfig{} has changed to lower case fields for unmarshal
Hosts map[string]struct {
AccessKeyID string
SecretAccessKey string
}
}
// for backward compatibility
type configV101 configV2
type configV1 configV2
// Migrate from config version ‘1.0’ to ‘1.0.1’
func migrateConfigV1ToV101() {
if !isMcConfigExists() {
return
}
mcConfigV1, err := quick.Load(mustGetMcConfigPath(), newConfigV1())
fatalIf(err.Trace(), "Unable to load config version ‘1’.")
// update to newer version
if mcConfigV1.Version() == "1.0.0" {
confV101 := mcConfigV1.Data().(*configV1)
confV101.Version = "1.0.1"
localHostConfig := struct {
AccessKeyID string
SecretAccessKey string
}{}
localHostConfig.AccessKeyID = ""
localHostConfig.SecretAccessKey = ""
s3HostConf := struct {
AccessKeyID string
SecretAccessKey string
}{}
s3HostConf.AccessKeyID = globalAccessKeyID
s3HostConf.SecretAccessKey = globalSecretAccessKey
if _, ok := confV101.Hosts["localhost:*"]; !ok {
confV101.Hosts["localhost:*"] = localHostConfig
}
if _, ok := confV101.Hosts["127.0.0.1:*"]; !ok {
confV101.Hosts["127.0.0.1:*"] = localHostConfig
}
if _, ok := confV101.Hosts["*.s3*.amazonaws.com"]; !ok {
confV101.Hosts["*.s3*.amazonaws.com"] = s3HostConf
}
mcNewConfigV101, err := quick.New(confV101)
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘1.0.1’.")
err = mcNewConfigV101.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’
func migrateConfigV101ToV2() {
if !isMcConfigExists() {
return
}
mcConfigV101, err := quick.Load(mustGetMcConfigPath(), newConfigV101())
fatalIf(err.Trace(), "Unable to load config version ‘1.0.1’.")
// update to newer version
if mcConfigV101.Version() == "1.0.1" {
confV2 := mcConfigV101.Data().(*configV101)
confV2.Version = "2"
mcNewConfigV2, err := quick.New(confV2)
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘2’.")
err = mcNewConfigV2.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’
func migrateConfigV2ToV3() {
if !isMcConfigExists() {
return
}
mcConfigV2, err := quick.Load(mustGetMcConfigPath(), newConfigV2())
fatalIf(err.Trace(), "Unable to load mc config V2.")
// update to newer version
if mcConfigV2.Version() == "2" {
confV3 := new(configV3)
confV3.Aliases = mcConfigV2.Data().(*configV2).Aliases
confV3.Hosts = make(map[string]struct {
AccessKeyID string `json:"access-key-id"`
SecretAccessKey string `json:"secret-access-key"`
})
for host, hostConf := range mcConfigV2.Data().(*configV2).Hosts {
newHostConf := struct {
AccessKeyID string `json:"access-key-id"`
SecretAccessKey string `json:"secret-access-key"`
}{}
newHostConf.AccessKeyID = hostConf.AccessKeyID
newHostConf.SecretAccessKey = hostConf.SecretAccessKey
confV3.Hosts[host] = newHostConf
}
confV3.Version = "3"
mcNewConfigV3, err := quick.New(confV3)
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 migrated %s from version ‘2’ to version ‘3’.\n", mustGetMcConfigPath())
}
}
// Migrate from config version ‘3’ to ‘4’
func migrateConfigV3ToV4() {
if !isMcConfigExists() {
return
}
mcConfigV3, err := quick.Load(mustGetMcConfigPath(), newConfigV3())
fatalIf(err.Trace(), "Unable to load mc config V2.")
// update to newer version
if mcConfigV3.Version() == "3" {
confV4 := new(configV4)
confV4.Aliases = mcConfigV3.Data().(*configV3).Aliases
confV4.Hosts = make(map[string]struct {
AccessKeyID string `json:"accessKeyId"`
SecretAccessKey string `json:"secretAccessKey"`
Signature string `json:"signature"`
})
for host, hostConf := range mcConfigV3.Data().(*configV3).Hosts {
confV4.Hosts[host] = struct {
AccessKeyID string `json:"accessKeyId"`
SecretAccessKey string `json:"secretAccessKey"`
Signature string `json:"signature"`
}{
AccessKeyID: hostConf.AccessKeyID,
SecretAccessKey: hostConf.SecretAccessKey,
Signature: "v4",
}
}
confV4.Version = "4"
mcNewConfigV4, err := quick.New(confV4)
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘4’.")
err = mcNewConfigV4.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’
func migrateConfigV4ToV5() {
if !isMcConfigExists() {
return
}
mcConfigV4, err := quick.Load(mustGetMcConfigPath(), newConfigV4())
fatalIf(err.Trace(), "Unable to load mc config V4.")
// update to newer version
if mcConfigV4.Version() == "4" {
confV5 := new(configV5)
confV5.Aliases = mcConfigV4.Data().(*configV4).Aliases
confV5.Hosts = make(map[string]hostConfig)
for host, hostConf := range mcConfigV4.Data().(*configV4).Hosts {
confV5.Hosts[host] = hostConfig{
AccessKeyID: hostConf.AccessKeyID,
SecretAccessKey: hostConf.SecretAccessKey,
API: "S3v4",
}
}
confV5.Version = "5"
mcNewConfigV5, err := quick.New(confV5)
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘5’.")
err = mcNewConfigV5.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 ‘4’ to ‘5’
func migrateConfigV5ToV6() {
if !isMcConfigExists() {
return
}
mcConfigV5, err := quick.Load(mustGetMcConfigPath(), newConfigV5())
fatalIf(err.Trace(), "Unable to load mc config V5.")
// update to newer version
if mcConfigV5.Version() == "5" {
confV6 := new(configV6)
confV6.Aliases = mcConfigV5.Data().(*configV5).Aliases
confV6.Aliases["gcs"] = "https://storage.googleapis.com"
confV6.Hosts = make(map[string]hostConfig)
for host, hostConf := range mcConfigV5.Data().(*configV5).Hosts {
confV6.Hosts[host] = hostConfig{
AccessKeyID: hostConf.AccessKeyID,
SecretAccessKey: hostConf.SecretAccessKey,
API: hostConf.API,
}
}
var s3Conf hostConfig
for host, hostConf := range confV6.Hosts {
if strings.Contains(host, "s3") {
if (hostConf.AccessKeyID == globalAccessKeyID) ||
(hostConf.SecretAccessKey == globalSecretAccessKey) {
delete(confV6.Hosts, host)
}
if hostConf.AccessKeyID == "" || hostConf.SecretAccessKey == "" {
delete(confV6.Hosts, host)
}
s3Conf = hostConfig{
AccessKeyID: hostConf.AccessKeyID,
SecretAccessKey: hostConf.SecretAccessKey,
API: hostConf.API,
}
break
}
}
confV6.Hosts["*s3*amazonaws.com"] = s3Conf
confV6.Hosts["*storage.googleapis.com"] = hostConfig{
AccessKeyID: globalAccessKeyID,
SecretAccessKey: globalSecretAccessKey,
API: "S3v2",
}
confV6.Version = globalMCConfigVersion
mcNewConfigV6, err := quick.New(confV6)
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘6’.")
err = mcNewConfigV6.Save(mustGetMcConfigPath())
fatalIf(err.Trace(), "Unable to save config version ‘6’.")
console.Infof("Successfully migrated %s from version ‘5’ to version ‘6’.\n", mustGetMcConfigPath())
}
}
// Fix config version ‘3’, by removing broken struct tags.
func fixConfigV3() {
if !isMcConfigExists() {
return
}
// brokenConfigV3 broken config between version 3.
type brokenConfigV3 struct {
Version string
ACL string
Access string
Aliases map[string]string
Hosts map[string]struct {
AccessKeyID string
SecretAccessKey string
}
}
conf := new(brokenConfigV3)
conf.Aliases = make(map[string]string)
conf.Hosts = make(map[string]struct {
AccessKeyID string
SecretAccessKey string
})
mcConfigV3, err := quick.Load(mustGetMcConfigPath(), conf)
fatalIf(err.Trace(), "Unable to load config.")
// Update to newer version.
if len(mcConfigV3.Data().(*brokenConfigV3).Aliases) != 0 || mcConfigV3.Data().(*brokenConfigV3).ACL != "" || mcConfigV3.Data().(*brokenConfigV3).Access != "" && mcConfigV3.Version() == "3" {
confV3 := new(configV3)
confV3.Aliases = mcConfigV3.Data().(*brokenConfigV3).Aliases
confV3.Hosts = make(map[string]struct {
AccessKeyID string `json:"access-key-id"`
SecretAccessKey string `json:"secret-access-key"`
})
for host, hostConf := range mcConfigV3.Data().(*brokenConfigV3).Hosts {
newHostConf := struct {
AccessKeyID string `json:"access-key-id"`
SecretAccessKey string `json:"secret-access-key"`
}{}
newHostConf.AccessKeyID = hostConf.AccessKeyID
newHostConf.SecretAccessKey = hostConf.SecretAccessKey
confV3.Hosts[host] = newHostConf
}
confV3.Version = "3"
mcNewConfigV3, err := quick.New(confV3)
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())
}
}
// 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.Hosts = make(map[string]struct {
AccessKeyID string
SecretAccessKey string
})
conf.Aliases = make(map[string]string)
return conf
}
// newConfigV101() - get new config version 1.0.1
func newConfigV101() *configV101 {
conf := new(configV101)
conf.Version = "1.0.1"
// make sure to allocate map's otherwise Golang
// exits silently without providing any errors
conf.Hosts = make(map[string]struct {
AccessKeyID string
SecretAccessKey string
})
conf.Aliases = make(map[string]string)
return conf
}
// newConfigV2() - get new config version 2
func newConfigV2() *configV2 {
conf := new(configV2)
conf.Version = "2"
// make sure to allocate map's otherwise Golang
// exits silently without providing any errors
conf.Hosts = make(map[string]struct {
AccessKeyID string
SecretAccessKey string
})
conf.Aliases = make(map[string]string)
return conf
}
// newConfigV3 - get new config version 3
func newConfigV3() *configV3 {
conf := new(configV3)
conf.Version = "3"
// make sure to allocate map's otherwise Golang
// exits silently without providing any errors
conf.Hosts = make(map[string]struct {
AccessKeyID string `json:"access-key-id"`
SecretAccessKey string `json:"secret-access-key"`
})
conf.Aliases = make(map[string]string)
return conf
}
func newConfigV4() *configV4 {
conf := new(configV4)
conf.Version = "4"
// make sure to allocate map's otherwise Golang
// exits silently without providing any errors
conf.Hosts = make(map[string]struct {
AccessKeyID string `json:"accessKeyId"`
SecretAccessKey string `json:"secretAccessKey"`
Signature string `json:"signature"`
})
conf.Aliases = make(map[string]string)
return conf
}
func newConfigV5() *configV5 {
conf := new(configV5)
conf.Version = "5"
// make sure to allocate map's otherwise Golang
// exits silently without providing any errors
conf.Hosts = make(map[string]hostConfig)
conf.Aliases = make(map[string]string)
return conf
}
-49
View File
@@ -1,49 +0,0 @@
package main
import (
"regexp"
"strings"
"github.com/minio/mc/pkg/client"
)
// isValidSecretKey - validate secret key.
func isValidSecretKey(secretAccessKey string) bool {
if secretAccessKey == "" {
return true
}
regex := regexp.MustCompile("^.{40}$")
return regex.MatchString(secretAccessKey)
}
// isValidAccessKey - validate access key.
func isValidAccessKey(accessKeyID string) bool {
if accessKeyID == "" {
return true
}
regex := regexp.MustCompile("^[A-Z0-9\\-\\.\\_\\~]{20}$")
return regex.MatchString(accessKeyID)
}
// isValidKeys validates both access and secret key.
func isValidKeys(accessKeyID, secretAccessKey string) bool {
if isValidAccessKey(accessKeyID) && isValidSecretKey(secretAccessKey) {
return true
}
return false
}
// 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
}
-142
View File
@@ -1,142 +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"
)
// configV6 config version '6'.
type configV6 struct {
Version string `json:"version"`
Aliases map[string]string `json:"alias"`
Hosts map[string]hostConfig `json:"hosts"`
}
// cached variables should *NEVER* be accessed directly from outside this file.
var cache sync.Pool
// newConfigV6 - new config version '6'.
func newConfigV6() *configV6 {
conf := new(configV6)
conf.Version = globalMCConfigVersion
// make sure to allocate map's otherwise Golang
// exits silently without providing any errors.
conf.Hosts = make(map[string]hostConfig)
conf.Aliases = make(map[string]string)
localHostConfig := hostConfig{
AccessKeyID: "",
SecretAccessKey: "",
API: "S3v4",
}
s3HostConf := hostConfig{
AccessKeyID: globalAccessKeyID,
SecretAccessKey: globalSecretAccessKey,
API: "S3v4",
}
googlHostConf := hostConfig{
AccessKeyID: globalAccessKeyID,
SecretAccessKey: globalSecretAccessKey,
API: "S3v2",
}
// Your example host config.
exampleHostConf := hostConfig{
AccessKeyID: globalAccessKeyID,
SecretAccessKey: globalSecretAccessKey,
API: "S3v4",
}
playHostConfig := hostConfig{
AccessKeyID: "",
SecretAccessKey: "",
API: "S3v4",
}
dlHostConfig := hostConfig{
AccessKeyID: "",
SecretAccessKey: "",
API: "S3v4",
}
conf.Hosts[globalExampleHostURL] = exampleHostConf
conf.Hosts["http://localhost:9000"] = localHostConfig
conf.Hosts["https://dl.minio.io:9000"] = dlHostConfig
conf.Hosts["https://s3.amazonaws.com"] = s3HostConf
conf.Hosts["https://play.minio.io:9000"] = playHostConfig
conf.Hosts["https://storage.googleapis.com"] = googlHostConf
aliases := make(map[string]string)
aliases["s3"] = "https://s3.amazonaws.com"
aliases["dl"] = "https://dl.minio.io:9000"
aliases["gcs"] = "https://storage.googleapis.com"
aliases["play"] = "https://play.minio.io:9000"
aliases["local"] = "http://localhost:9000"
conf.Aliases = aliases
return conf
}
// saveConfigV6 - saves an updated config.
func saveConfigV6(config *configV6) *probe.Error {
qs, err := quick.New(config)
if err != nil {
return err.Trace()
}
return qs.Save(mustGetMcConfigPath()).Trace(mustGetMcConfigPath())
}
// loadConfigV6 - loads a new config.
func loadConfigV6() (*configV6, *probe.Error) {
if !isMcConfigExists() {
return nil, errInvalidArgument().Trace()
}
configFile, err := getMcConfigPath()
if err != nil {
return nil, err.Trace()
}
// Cached in private global variable.
if v := cache.Get(); v != nil { // Use previously cached config.
return v.(*configV6), nil
}
conf := new(configV6)
conf.Version = globalMCConfigVersion
qconf, err := quick.New(conf)
if err != nil {
return nil, err.Trace()
}
err = qconf.Load(configFile)
if err != nil {
return nil, err.Trace()
}
config := qconf.Data().(*configV6)
// Save in sync pool.
cache.Put(config)
return config, nil
}
-69
View File
@@ -1,69 +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/minio/cli"
"github.com/minio/mc/pkg/console"
"github.com/minio/minio-xl/pkg/probe"
)
var (
configVersionFlags = []cli.Flag{
cli.BoolFlag{
Name: "help, h",
Usage: "Help of config version",
},
}
)
// Print config version.
var configVersionCmd = cli.Command{
Name: "version",
Usage: "Print config version.",
Action: mainConfigVersion,
Flags: append(configVersionFlags, globalFlags...),
CustomHelpTemplate: `NAME:
mc config {{.Name}} - {{.Usage}}
USAGE:
mc config {{.Name}}
`,
}
func mainConfigVersion(ctx *cli.Context) {
// Set global flags from context.
setGlobalsFromContext(ctx)
config, err := loadMcConfig()
fatalIf(err.Trace(), "Unable to load config version ‘"+globalMCConfigVersion+"’.")
type Version string
if globalJSON {
tB, e := json.Marshal(
struct {
Version Version `json:"version"`
}{Version: Version(config.Version)},
)
fatalIf(probe.NewError(e), "Unable to construct version string.")
console.Println(string(tB))
return
}
console.Println(config.Version)
}
-133
View File
@@ -1,133 +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"
"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 err := os.MkdirAll(p, 0700); err != nil {
return probe.NewError(err)
}
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() *configV6 {
return newConfigV6()
}
// loadMcConfig - reads configuration file and returns config.
func loadMcConfig() (*configV6, *probe.Error) {
conf, err := loadConfigV6()
if err != nil {
return nil, err.Trace()
}
return conf, nil
}
// saveMcConfig - saves configuration file and returns error if any.
func saveMcConfig(config *configV6) *probe.Error {
if config == nil {
return errInvalidArgument().Trace()
}
err := createMcConfigDir()
if err != nil {
return err.Trace(mustGetMcConfigDir())
}
return saveConfigV6(config).Trace(mustGetMcConfigPath())
}
// isMcConfigExists returns err if config doesn't exist.
func isMcConfigExists() bool {
configFile, err := getMcConfigPath()
if err != nil {
return false
}
if _, err := os.Stat(configFile); err != nil {
return false
}
return true
}
-15
View File
@@ -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
-411
View File
@@ -1,411 +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"
"math"
"os"
"runtime"
"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.amazonaws.com/jukebox/
2. Copy a folder recursively from Minio cloud storage to Amazon S3 cloud storage.
$ mc {{.Name}} --recursive play.minio.io:9000/mybucket/burningman2011/ s3.amazonaws.com/mybucket/
3. Copy multiple local folders recursively to Minio cloud storage.
$ mc {{.Name}} --recursive backup/2014/ backup/2015/ play.minio.io:9000/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"`
Length int64 `json:"length"`
}
// 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, err := json.Marshal(c)
fatalIf(probe.NewError(err), "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 *barSend, accountingReader *accounter, cpQueue <-chan bool, wg *sync.WaitGroup, statusCh chan<- copyURLs) {
defer wg.Done() // Notify that this copy routine is done.
defer func() {
<-cpQueue
}()
if cpURLs.Error != nil {
cpURLs.Error.Trace()
statusCh <- cpURLs
return
}
if !globalQuiet && !globalJSON {
progressReader.SetCaption(cpURLs.SourceContent.URL.String() + ": ")
}
reader, err := getSource(cpURLs.SourceContent.URL.String())
if err != nil {
if !globalQuiet && !globalJSON {
progressReader.ErrorGet(cpURLs.SourceContent.Size)
}
cpURLs.Error = err.Trace(cpURLs.SourceContent.URL.String())
statusCh <- cpURLs
return
}
var newReader io.ReadSeeker
if globalQuiet || globalJSON {
printMsg(copyMessage{
Source: cpURLs.SourceContent.URL.String(),
Target: cpURLs.TargetContent.URL.String(),
Length: cpURLs.SourceContent.Size,
})
// No accounting necessary for JSON output.
if globalJSON {
newReader = reader
}
// Proxy reader to accounting reader only during quiet mode.
if globalQuiet {
newReader = accountingReader.NewProxyReader(reader)
}
} else {
// set up progress
newReader = progressReader.NewProxyReader(reader)
}
if err := putTarget(cpURLs.TargetContent.URL.String(), newReader, cpURLs.SourceContent.Size); err != nil {
if !globalQuiet && !globalJSON {
progressReader.ErrorPut(cpURLs.SourceContent.Size)
}
cpURLs.Error = err.Trace(cpURLs.TargetContent.URL.String())
statusCh <- cpURLs
return
}
cpURLs.Error = nil // just for safety
statusCh <- cpURLs
}
// doCopyFake - Perform a fake copy to update the progress bar appropriately.
func doCopyFake(cURLs copyURLs, progressReader *barSend) {
if !globalQuiet && !globalJSON {
progressReader.Progress(cURLs.SourceContent.Size)
}
}
// doPrepareCopyURLs scans the source URL and prepares a list of objects for copying.
func doPrepareCopyURLs(session *sessionV5, 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 prepration
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, err := json.Marshal(cpURLs)
if err != nil {
session.Delete()
fatalIf(probe.NewError(err), "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 *sessionV5) {
trapCh := signalTrap(os.Interrupt, syscall.SIGTERM)
if !session.HasData() {
doPrepareCopyURLs(session, trapCh)
}
// Enable accounting reader by default.
accntReader := newAccounter(session.Header.TotalBytes)
// Enable progress bar reader only during default mode.
var progressReader *barSend
if !globalQuiet && !globalJSON { // set up progress bar
progressReader = newProgressBar(session.Header.TotalBytes)
}
// Prepare URL scanner from session data file.
scanner := 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)
wg := new(sync.WaitGroup)
// Limit number of copy routines based on available CPU resources.
cpQueue := make(chan bool, int(math.Max(float64(runtime.NumCPU())-1, 1)))
defer close(cpQueue)
// Status channel for receiveing copy return status.
statusCh := make(chan copyURLs)
// Go routine to monitor doCopy status and signal traps.
wg.Add(1)
go func() {
defer wg.Done()
for {
select {
case cpURLs, ok := <-statusCh: // Receive status.
if !ok { // We are done here. Top level function has returned.
if !globalQuiet && !globalJSON {
progressReader.Finish()
}
if globalQuiet {
accntStat := accntReader.Stat()
cpStatMessage := copyStatMessage{
Total: accntStat.Total,
Transferred: accntStat.Transferred,
Speed: accntStat.Speed,
}
console.Println(console.Colorize("Copy", cpStatMessage.String()))
}
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
}
// for critical errors we should exit. Session can be resumed after the user figures out the problem
session.CloseAndDie()
}
case <-trapCh: // Receive interrupt notification.
if !globalQuiet && !globalJSON {
console.Eraseline()
}
session.CloseAndDie()
}
}
}()
// Go routine to perform concurrently copying.
wg.Add(1)
go func() {
defer wg.Done()
copyWg := new(sync.WaitGroup)
defer close(statusCh)
for scanner.Scan() {
var cpURLs copyURLs
json.Unmarshal([]byte(scanner.Text()), &cpURLs)
if isCopied(cpURLs.SourceContent.URL.String()) {
doCopyFake(cpURLs, progressReader)
} else {
// Wait for other copy routines to
// complete. We only have limited CPU
// and network resources.
cpQueue <- true
// Account for each copy routines we start.
copyWg.Add(1)
// Do copying in background concurrently.
go doCopy(cpURLs, progressReader, accntReader, cpQueue, copyWg, statusCh)
}
}
copyWg.Wait()
}()
wg.Wait()
}
// 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 := newSessionV5()
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.
var err *probe.Error
if session.Header.CommandArgs, err = args2URLs(ctx.Args()); err != nil {
session.Delete()
fatalIf(err.Trace(ctx.Args()...), "One or more unknown URL types passed.")
}
doCopySession(session)
session.Delete()
}
-144
View File
@@ -1,144 +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, err := args2URLs(ctx.Args())
fatalIf(err.Trace(ctx.Args()...), fmt.Sprintf("Argument parsing failed."))
if len(URLs) < 2 {
fatalIf(err.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 := guessCopyURLType(srcURLs, tgtURL, isRecursive)
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(), "Guessing CopyURLsType failed, Invalid arguments provided.")
}
}
// 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.")
}
}
}
-227
View File
@@ -1,227 +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 {
SourceContent *client.Content
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 {
if len(sourceURLs) == 1 { // 1 Source, 1 Target
sourceURL := sourceURLs[0]
_, sourceContent, err := url2Stat(sourceURL)
if err != nil {
return copyURLsTypeInvalid
}
// If recursion is ON, it is type C.
// If source is a folder, it is Type C.
if sourceContent.Type.IsDir() || isRecursive {
return copyURLsTypeC
}
// If target is a folder, it is Type B.
if isTargetURLDir(targetURL) {
return copyURLsTypeB
}
// else Type A.
return copyURLsTypeA
}
// Multiple source args and target is a folder. It is Type D.
if isTargetURLDir(targetURL) {
return copyURLsTypeD
}
return copyURLsTypeInvalid
}
// 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 {
if sourceURL == targetURL {
// source and target can not be same
return copyURLs{Error: errSourceTargetSame(sourceURL).Trace(sourceURL)}
}
_, 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)}
}
// All OK.. We can proceed. Type A
return makeCopyContentTypeA(sourceContent, targetURL)
}
// prepareCopyContentTypeA - makes CopyURLs content for copying.
func makeCopyContentTypeA(sourceContent *client.Content, targetURL string) copyURLs {
return copyURLs{SourceContent: sourceContent, 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 {
_, 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(sourceContent, targetURL)
}
// makeCopyContentTypeB - CopyURLs content for copying.
func makeCopyContentTypeB(sourceContent *client.Content, 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.Join(targetURLParse.Path, filepath.Base(sourceContent.URL.Path))
return makeCopyContentTypeA(sourceContent, 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 {
copyURLsCh := make(chan copyURLs)
go func(sourceURL, targetURL string, copyURLsCh chan copyURLs) {
defer close(copyURLsCh)
sourceClient, err := url2Client(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(sourceClient.GetURL(), sourceContent, targetURL)
}
}(sourceURL, targetURL, copyURLsCh)
return copyURLsCh
}
// makeCopyContentTypeC - CopyURLs content for copying.
func makeCopyContentTypeC(sourceURL client.URL, sourceContent *client.Content, targetURL string) copyURLs {
newSourceURL := sourceContent.URL
pathSeparatorIndex := strings.LastIndex(sourceURL.Path, string(sourceURL.Separator))
newSourceSuffix := newSourceURL.Path
if pathSeparatorIndex > 1 {
newSourceSuffix = strings.TrimPrefix(newSourceURL.Path, sourceURL.Path[:pathSeparatorIndex])
}
newTargetURL := urlJoinPath(targetURL, newSourceSuffix)
return makeCopyContentTypeA(sourceContent, 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)
switch guessCopyURLType(sourceURLs, targetURL, isRecursive) {
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
}
-68
View File
@@ -1,68 +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 . "gopkg.in/check.v1"
func (s *TestSuite) TestCopyURLType(c *C) {
// Valid Types.
sourceURLs := []string{server.URL + "/bucket/object1"}
targetURL := server.URL + "/bucket/test"
isRecursive := false
c.Assert(guessCopyURLType(sourceURLs, targetURL, isRecursive), Equals, copyURLsTypeA)
sourceURLs = []string{server.URL + "/bucket/object1"}
targetURL = server.URL + "/bucket"
isRecursive = false
c.Assert(guessCopyURLType(sourceURLs, targetURL, isRecursive), Equals, copyURLsTypeB)
sourceURLs = []string{server.URL + "/bucket/"}
targetURL = server.URL + "/bucket"
isRecursive = true
c.Assert(guessCopyURLType(sourceURLs, targetURL, isRecursive), Equals, copyURLsTypeC)
sourceURLs = []string{server.URL + "/bucket/test1.txt", server.URL + "/bucket/test2.txt"}
targetURL = server.URL + "/bucket"
isRecursive = false
c.Assert(guessCopyURLType(sourceURLs, targetURL, isRecursive), Equals, copyURLsTypeD)
// * INVALID RULES
// =========================
// copy(d, f)
// copy(d..., f)
// copy([]f, f)
sourceURLs = []string{"/test/"}
targetURL = server.URL + "/bucket/test.txt"
isRecursive = false
c.Assert(guessCopyURLType(sourceURLs, targetURL, isRecursive), Equals, copyURLsTypeInvalid)
sourceURLs = []string{"/test/"}
targetURL = server.URL + "/bucket/test.txt"
isRecursive = true
c.Assert(guessCopyURLType(sourceURLs, targetURL, isRecursive), Equals, copyURLsTypeInvalid)
sourceURLs = []string{"/test/test1.txt", "/test/test2.txt"}
targetURL = server.URL + "/bucket/test.txt"
isRecursive = false
c.Assert(guessCopyURLType(sourceURLs, targetURL, isRecursive), Equals, copyURLsTypeInvalid)
sourceURLs = []string{server.URL + "/bucket/", server.URL + "/bucket/"}
targetURL = ""
isRecursive = false
c.Assert(guessCopyURLType(sourceURLs, targetURL, isRecursive), Equals, copyURLsTypeInvalid)
}
-202
View File
@@ -1,202 +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.
*/
// Copyright 2010 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//
// Some of the code here is borrowed from 'encoding/json' package.
package main
import (
"encoding/csv"
"io"
"os"
"reflect"
"runtime"
"strconv"
"github.com/minio/minio-xl/pkg/probe"
)
// csvReader reads records from a CSV-encoded file.
type csvReader struct {
*csv.Reader
}
// newCSVReader returns a new csv Reader.
// additionally one can provide a line that needs to be skipped.
func newCSVReader(r io.Reader) *csvReader {
return &csvReader{
csv.NewReader(r),
}
}
// credential - struct to read from a CSV file.
type credential struct {
Name string
AccessKeyID string
SecretAccessKey string
}
// getCredentials - get credentials file.
func getCredentials(credentialsFile string) ([]credential, *probe.Error) {
reader, e := os.Open(credentialsFile)
if e != nil {
return nil, probe.NewError(e)
}
creds := []credential{}
// skip the first line of the csv file, usually csv header.
skipLine := 1
if err := newCSVReader(reader).Unmarshal(&creds, skipLine); err != nil {
return nil, err.Trace(credentialsFile)
}
if len(creds) == 0 {
return nil, errInvalidArgument().Trace(credentialsFile)
}
return creds, nil
}
//// CSV reader block.
/// CSV read errors.
// An invalidUnmarshalError describes an invalid argument passed to Unmarshal.
// (The argument to Unmarshal must be a non-nil pointer.)
type invalidUnmarshalError struct {
Type reflect.Type
}
func (e *invalidUnmarshalError) Error() string {
if e.Type == nil {
return "csv: Unmarshal(nil)"
}
if e.Type.Kind() != reflect.Ptr {
return "csv: Unmarshal(non-pointer " + e.Type.String() + ")"
}
return "csv: Unmarshal(nil " + e.Type.String() + ")"
}
// An unmarshalTypeError describes a CSV value that was
// not appropriate for a value of a specific Go type.
type unmarshalTypeError struct {
Type reflect.Type // type of Go value it could not be assigned to
}
func (e *unmarshalTypeError) Error() string {
return "csv: cannot unmarshal into Go value of type " + e.Type.String()
}
/// CSV Unmarshaler.
// Unmarshal - unmarshal everything into the input struct.
func (r *csvReader) Unmarshal(v interface{}, skipLine int) (err *probe.Error) {
// Handler for runtime errors.
defer func() {
if r := recover(); r != nil {
if _, ok := r.(runtime.Error); ok {
panic(r)
}
e := r.(error)
err = probe.NewError(e)
}
}()
{
// Check if incoming interface{} is nil.
rv := reflect.ValueOf(v)
if rv.Kind() != reflect.Ptr || rv.IsNil() {
return probe.NewError(&invalidUnmarshalError{reflect.TypeOf(v)})
}
}
rv := reflect.ValueOf(v).Elem()
rt := reflect.TypeOf(v).Elem().Elem()
records := reflect.MakeSlice(reflect.TypeOf(v).Elem(), 0, 0)
var e error
var lineCount int
for {
record := reflect.New(rt)
{
var csvRecord []string
csvRecord, e = r.Read()
if e != nil {
break
}
lineCount++
// Skip a particular line
if lineCount == skipLine {
continue
}
rvInternal := reflect.ValueOf(record.Interface()).Elem()
for s := 0; s < rvInternal.NumField(); s++ {
val := rvInternal.Field(s)
x := csvRecord[s]
setValue(&val, x)
}
}
records = reflect.Append(records, record.Elem())
}
if e == io.EOF {
rv.Set(records)
return nil
}
if e != nil {
return probe.NewError(e)
}
return nil
}
// setValue - following reflect.Value sets the actual value based on the Golang type.
// If no native type found throws an UnmarshalTypeError.
func setValue(v *reflect.Value, x string) *probe.Error {
switch v.Kind() {
case reflect.Bool:
val, e := strconv.ParseBool(x)
if e != nil {
return probe.NewError(e)
}
v.SetBool(val)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
val, e := strconv.ParseInt(x, 10, v.Type().Bits())
if e != nil {
return probe.NewError(e)
}
v.SetInt(val)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
val, e := strconv.ParseUint(x, 10, v.Type().Bits())
if e != nil {
return probe.NewError(e)
}
v.SetUint(val)
case reflect.Float32, reflect.Float64:
val, e := strconv.ParseFloat(x, v.Type().Bits())
if e != nil {
return probe.NewError(e)
}
v.SetFloat(val)
case reflect.String:
v.SetString(x)
case reflect.Struct:
case reflect.Map:
case reflect.Slice:
case reflect.Array:
case reflect.Interface, reflect.Ptr:
default:
return probe.NewError(&unmarshalTypeError{v.Type()})
}
return nil
}
-208
View File
@@ -1,208 +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.amazonaws.com/MyBucket/Photos
2. Compare two different folders on a local filesystem.
$ mc {{.Name}} ~/Photos /Media/Backup/Photos
`,
}
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.")
}
}
}
// 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, err := json.Marshal(d)
fatalIf(probe.NewError(err),
"Unable to marshal diff message ‘"+d.FirstURL+"’, ‘"+d.SecondURL+"’ and ‘"+d.Diff+"’.")
return string(diffJSONBytes)
}
// 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
}
firstClient, err := url2Client(firstURL)
if err != nil {
fatalIf(err.Trace(firstURL, secondURL), fmt.Sprintf("Failed to diff '%s' and '%s'", firstURL, secondURL))
}
difference, err := objectDifferenceFactory(secondURL)
if err != nil {
fatalIf(err.Trace(firstURL, 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, err := args2URLs(ctx.Args())
fatalIf(err.Trace(ctx.Args()...), "Unable to convert args 2 URLs")
firstURL := URLs[0]
secondURL := URLs[1]
_, firstContent, err := url2Stat(firstURL)
if err != nil {
fatalIf(err.Trace(firstURL), fmt.Sprintf("Unable to stat '%s'.", firstURL))
}
if !firstContent.Type.IsDir() {
fatalIf(errInvalidArgument().Trace(firstURL), fmt.Sprintf("‘%s’ is not a folder.", firstURL))
}
_, secondContent, err := url2Stat(secondURL)
if err != nil {
fatalIf(err.Trace(secondURL), fmt.Sprintf("Unable to stat '%s'.", secondURL))
}
if !secondContent.Type.IsDir() {
fatalIf(errInvalidArgument().Trace(secondURL), fmt.Sprintf("‘%s’ is not a folder.", secondURL))
}
doDiffMain(firstURL, secondURL)
}
-89
View File
@@ -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(targetURL string) (objectDifference, *probe.Error) {
clnt, err := url2Client(targetURL)
if err != nil {
return nil, err.Trace(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
}
-115
View File
@@ -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, err := json.Marshal(struct {
Status string `json:"status"`
Error errorMessage `json:"error"`
}{
Status: "error",
Error: errorMsg,
})
if err != nil {
console.Fatalln(probe.NewError(err))
}
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, err := json.Marshal(struct {
Status string `json:"status"`
Error errorMessage `json:"error"`
}{
Status: "error",
Error: errorMsg,
})
if err != nil {
console.Fatalln(probe.NewError(err))
}
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))
}
-56
View File
@@ -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)
}
-80
View File
@@ -1,80 +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 = "6"
globalMCConfigDir = ".mc/"
globalMCConfigWindowsDir = "mc\\"
globalMCConfigFile = "config.json"
// session config and shared urls related constants
globalSessionDir = "session"
globalSharedURLsDataDir = "share"
// default access and secret key
// do not pass accesskeyid and secretaccesskey through cli
// users should manually edit them, add a stub entry
globalAccessKeyID = "YOUR-ACCESS-KEY-ID-HERE"
globalSecretAccessKey = "YOUR-SECRET-ACCESS-KEY-HERE"
// default host
globalExampleHostURL = "http://YOUR-EXAMPLE.COM"
)
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)
}
-62
View File
@@ -1,62 +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 (
"strings"
"github.com/minio/mc/pkg/client"
"github.com/minio/minio-xl/pkg/probe"
)
// hostConfig configuration of a host.
type hostConfig struct {
AccessKeyID string `json:"accessKeyId"`
SecretAccessKey string `json:"secretAccessKey"`
API string `json:"api"`
}
// getHostConfig retrieves host specific configuration such as access keys, signature type.
func getHostConfig(URL string) (hostConfig, *probe.Error) {
config, err := loadMcConfig()
if err != nil {
return hostConfig{}, err.Trace(URL)
}
url := client.NewURL(URL)
// No host matching or keys needed for filesystem requests.
if url.Type == client.Filesystem {
hostCfg := hostConfig{
AccessKeyID: "",
SecretAccessKey: "",
API: "fs",
}
return hostCfg, nil
}
// if host is exact return quickly.
if _, ok := config.Hosts[url.String()]; ok {
return config.Hosts[url.String()], nil
}
// if host matches a suffix return.
for savedURLStr, hostCfg := range config.Hosts {
savedURL := client.NewURL(savedURLStr)
if strings.HasSuffix(url.Host, savedURL.Host) {
return hostCfg, nil
}
}
// return error if cannot be matched.
return hostConfig{}, errNoMatchingHost(URL).Trace(URL)
}
-145
View File
@@ -1,145 +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/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.amazonaws.com
2. List buckets and all its contents from Amazon S3 cloud storage recursively.
$ mc {{.Name}} --recursive s3.amazonaws.com
3. List files recursively on a local filesystem on Microsoft Windows.
$ mc {{.Name}} --recursive C:\Users\Worf\
4. List files with non-English characters on Amazon S3 cloud storage.
$ mc {{.Name}} s3/andoria/本
5. List folders with space separated names on Amazon S3 cloud storage.
$ mc {{.Name}} 's3/miniocloud/Community Files/'
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, err := args2URLs(ctx.Args())
fatalIf(err.Trace(ctx.Args()...), fmt.Sprintf("One or more unknown URL types passed."))
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{"."}
}
targetURLs, err := args2URLs(args)
fatalIf(err.Trace(args...), "One or more unknown URL types passed.")
for _, targetURL := range targetURLs {
var clnt client.Client
clnt, err = url2Client(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
}
}
}
-142
View File
@@ -1,142 +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"
"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) {
// fmt.Println(content)
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
}
contentURL := content.URL.Path
contentURL = strings.TrimPrefix(contentURL, prefixPath)
content.URL.Path = contentURL
parsedContent := parseContent(content)
// print colorized or jsonized content info.
printMsg(parsedContent)
}
return nil
}
-17
View File
@@ -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
-195
View File
@@ -1,195 +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 (
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]{{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)
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()
}
-129
View File
@@ -1,129 +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"
"strings"
"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.",
},
}
)
// 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.amazonaws.com/mynewbucket
2. Create a new bucket on Google Cloud Storage.
$ mc {{.Name}} storage.googleapis.com/miniocloud
3. Create a new bucket on Amazon S3 cloud storage, using virtual bucket request.
$ mc {{.Name}} ferenginar.s3.amazonaws.com
3. 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"`
}
// 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, err := json.Marshal(s)
fatalIf(probe.NewError(err), "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
}
for _, arg := range ctx.Args() {
if strings.TrimSpace(arg) == "" {
fatalIf(errInvalidArgument().Trace(), "Unable to validate empty argument.")
}
}
}
// 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))
URLs, err := args2URLs(ctx.Args())
fatalIf(err.Trace(ctx.Args()...), "Unable to convert args to URLs.")
for _, targetURL := range URLs {
// Instantiate client for URL.
clnt, err := url2Client(targetURL)
fatalIf(err.Trace(targetURL), "Invalid target ‘"+targetURL+"’.")
// Make bucket.
err = clnt.MakeBucket()
// Upon error print error and continue.
if err != nil {
errorIf(err.Trace(targetURL), "Unable to make bucket ‘"+targetURL+"’.")
continue
}
// Successfully created a bucket.
printMsg(makeBucketMessage{Status: "success", Bucket: targetURL})
}
}
-39
View File
@@ -1,39 +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 . "gopkg.in/check.v1"
func (s *TestSuite) TestMbAndAccess(c *C) {
// Instantiate client for URL.
clnt, err := url2Client(server.URL + "/bucket")
c.Assert(err, IsNil)
// Make bucket.
err = clnt.MakeBucket()
c.Assert(err, IsNil)
err = doSetAccess(server.URL+"/bucket", "public-read-write")
c.Assert(err, IsNil)
err = doSetAccess(server.URL+"/bucket", "invalid")
c.Assert(err, Not(IsNil))
perm, err := doGetAccess(server.URL + "/bucket")
c.Assert(err, IsNil)
c.Assert(perm.isPrivate(), Equals, true)
}
-284
View File
@@ -1,284 +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/ioutil"
"os"
"path/filepath"
"runtime"
"sync"
"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) {
objectAPI := objectAPIHandler(objectAPIHandler{lock: &sync.Mutex{}, bucket: "bucket", object: make(map[string][]byte)})
server = httptest.NewServer(objectAPI)
// do not set it elsewhere, leads to data races since this is a global flag
globalQuiet = true // quiet is set to turn of progress bar
tmpDir, e := ioutil.TempDir(os.TempDir(), "cmd-")
c.Assert(e, IsNil)
// For windows the path is slightly different.
if runtime.GOOS == "windows" {
customConfigDir = filepath.Join(tmpDir, globalMCConfigWindowsDir)
} else {
customConfigDir = filepath.Join(tmpDir, globalMCConfigDir)
}
setMcConfigDir(customConfigDir)
err := createMcConfigDir()
c.Assert(err, IsNil)
config := newMcConfig()
config.Hosts[server.URL] = hostConfig{
AccessKeyID: "WLGDGYAQYIGI833EV05A",
SecretAccessKey: "BYvgJM101sHngl2uzjXS/OBF/aMxAN06JrJ3qJlF",
API: "S3v4",
}
err = saveMcConfig(config)
c.Assert(err, IsNil)
err = createSessionDir()
c.Assert(err, IsNil)
app = registerApp()
}
func (s *TestSuite) TearDownSuite(c *C) {
os.RemoveAll(customConfigDir)
if server != nil {
server.Close()
}
}
func (s *TestSuite) TestGetNewClient(c *C) {
_, err := getNewClient("http://example.com/bucket1", hostConfig{})
c.Assert(err, IsNil)
_, err = getNewClient("https://example.com/bucket1", hostConfig{})
c.Assert(err, IsNil)
_, err = getNewClient("C:\\Users\\Administrator\\MyDocuments", hostConfig{})
c.Assert(err, IsNil)
_, err = getNewClient("/usr/bin/pandoc", hostConfig{})
c.Assert(err, IsNil)
_, err = getNewClient("pkg/client", hostConfig{})
c.Assert(err, IsNil)
}
// setMcConfigPath - set a custom minio client config path.
func setMcConfigPath(configPath string) {
mcCustomConfigPath = configPath
}
func (s *TestSuite) TestNewConfigV6(c *C) {
root, e := ioutil.TempDir(os.TempDir(), "mc-")
c.Assert(e, IsNil)
defer os.RemoveAll(root)
conf := newMcConfig()
configFile := filepath.Join(root, globalMCConfigFile)
setMcConfigPath(configFile)
err := saveMcConfig(conf)
c.Assert(err, IsNil)
data, err := loadMcConfig()
c.Assert(err, IsNil)
setMcConfigPath("")
type aliases struct {
name string
url string
}
wantAliases := []aliases{
{
"s3",
"https://s3.amazonaws.com",
},
{
"play",
"https://play.minio.io:9000",
},
{
"local",
"http://localhost:9000",
},
}
for _, alias := range wantAliases {
url, ok := data.Aliases[alias.name]
c.Assert(ok, Equals, true)
c.Assert(url, Equals, alias.url)
}
wantHosts := []string{
"http://localhost:9000",
"https://play.minio.io:9000",
"https://dl.minio.io:9000",
"https://s3.amazonaws.com",
"https://storage.googleapis.com",
}
for _, host := range wantHosts {
_, ok := data.Hosts[host]
c.Assert(ok, Equals, true)
}
}
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)
switch runtime.GOOS {
case "linux":
fallthrough
case "freebsd":
fallthrough
case "darwin":
c.Assert(dir, Equals, customConfigDir)
case "windows":
c.Assert(dir, Equals, customConfigDir)
default:
c.Fail()
}
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(isValidAliasName("helloWorld0"), Equals, true)
c.Check(isValidAliasName("h0SFD2k24Fdsa"), Equals, true)
c.Check(isValidAliasName("fdslka-4"), Equals, true)
c.Check(isValidAliasName("fdslka-"), Equals, true)
c.Check(isValidAliasName("helloWorld$"), Equals, false)
c.Check(isValidAliasName("h0SFD2k2#Fdsa"), Equals, false)
c.Check(isValidAliasName("0dslka-4"), Equals, false)
c.Check(isValidAliasName("-fdslka"), Equals, false)
}
func (s *TestSuite) TestEmptyExpansions(c *C) {
url, err := getAliasURL("hello")
c.Assert(err, IsNil)
c.Assert(url, Equals, "hello")
url, err = getAliasURL("minio://hello")
c.Assert(err, IsNil)
c.Assert(url, Equals, "minio://hello")
url, err = getAliasURL("$#\\")
c.Assert(err, IsNil)
c.Assert(url, Equals, "$#\\")
url, err = getAliasURL("myfoo/bar")
c.Assert(err, IsNil)
c.Assert(url, Equals, "myfoo/bar")
url, err = getAliasURL("")
c.Assert(err, IsNil)
c.Assert(url, Equals, "")
}
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)
}
func (s *TestSuite) TestApp(c *C) {
err := app.Run([]string{""})
c.Assert(err, IsNil)
}
-398
View File
@@ -1,398 +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"
"math"
"os"
"runtime"
"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.minio.io:9000/photos/2014 s3.amazonaws.com/backup-photos
2. Mirror a local folder recursively to Amazon S3 cloud storage.
$ mc {{.Name}} backup/ s3.amazonaws.com/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 *barSend, accountingReader *accounter, mirrorQueueCh <-chan bool, wg *sync.WaitGroup, statusCh chan<- mirrorURLs) {
defer wg.Done() // Notify that this copy routine is done.
defer func() {
<-mirrorQueueCh
}()
if sURLs.Error != nil { // Errorneous sURLs passed.
sURLs.Error = sURLs.Error.Trace()
statusCh <- sURLs
return
}
targetURL := sURLs.TargetContent.URL.String()
sourceURL := sURLs.SourceContent.URL.String()
length := sURLs.SourceContent.Size
if !globalQuiet && !globalJSON {
progressReader.SetCaption(sourceURL + ": ")
}
reader, err := getSource(sourceURL)
if err != nil {
if !globalQuiet && !globalJSON {
progressReader.ErrorGet(length)
}
sURLs.Error = err.Trace(sourceURL)
statusCh <- sURLs
return
}
var newReader io.ReadSeeker
if globalQuiet || globalJSON {
printMsg(mirrorMessage{
Source: sourceURL,
Target: targetURL,
})
if globalJSON {
newReader = reader
}
if globalQuiet {
newReader = accountingReader.NewProxyReader(reader)
}
} else {
// set up progress
newReader = progressReader.NewProxyReader(reader)
}
err = putTarget(targetURL, newReader, length)
if err != nil {
if !globalQuiet && !globalJSON {
progressReader.ErrorPut(length)
}
sURLs.Error = err.Trace(targetURL)
statusCh <- sURLs
return
}
sURLs.Error = nil // just for safety
statusCh <- sURLs
}
// doMirrorFake - Perform a fake mirror to update the progress bar appropriately.
func doMirrorFake(sURLs mirrorURLs, progressReader *barSend) {
if !globalDebug && !globalJSON {
progressReader.Progress(sURLs.SourceContent.Size)
}
}
// doPrepareMirrorURLs scans the source URL and prepares a list of objects for mirroring.
func doPrepareMirrorURLs(session *sessionV5, 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, err := json.Marshal(sURLs)
if err != nil {
session.Delete()
fatalIf(probe.NewError(err), "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 *sessionV5) {
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 *barSend
if !globalQuiet && !globalJSON {
progressReader = newProgressBar(session.Header.TotalBytes)
}
// Prepare URL scanner from session data file.
scanner := 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)
wg := new(sync.WaitGroup)
// Limit numner of mirror routines based on available CPU resources.
mirrorQueue := make(chan bool, int(math.Max(float64(runtime.NumCPU())-1, 1)))
defer close(mirrorQueue)
// Status channel for receiveing mirror return status.
statusCh := make(chan mirrorURLs)
// Go routine to monitor doMirror status and signal traps.
wg.Add(1)
go func() {
defer wg.Done()
for {
select {
case sURLs, ok := <-statusCh: // Receive status.
if !ok { // We are done here. Top level function has returned.
if !globalQuiet && !globalJSON {
progressReader.Finish()
} else {
accntStat := accntReader.Stat()
mrStatMessage := mirrorStatMessage{
Total: accntStat.Total,
Transferred: accntStat.Transferred,
Speed: accntStat.Speed,
}
console.Println(console.Colorize("Mirror", mrStatMessage.String()))
}
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(), fmt.Sprintf("Failed to mirror ‘%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
}
// for critical errors we should exit. Session can be resumed after the user figures out the problem
session.CloseAndDie()
}
case <-trapCh: // Receive interrupt notification.
// Print in new line and adjust to top so that we don't print over the ongoing progress bar
if !globalQuiet && !globalJSON {
console.Eraseline()
}
session.CloseAndDie()
}
}
}()
// Go routine to perform concurrently mirroring.
wg.Add(1)
go func() {
defer wg.Done()
mirrorWg := new(sync.WaitGroup)
defer close(statusCh)
for scanner.Scan() {
var sURLs mirrorURLs
json.Unmarshal([]byte(scanner.Text()), &sURLs)
if isCopied(sURLs.SourceContent.URL.String()) {
doMirrorFake(sURLs, progressReader)
} else {
// Wait for other mirror routines to
// complete. We only have limited CPU
// and network resources.
mirrorQueue <- true
// Account for each mirror routines we start.
mirrorWg.Add(1)
// Do mirroring in background concurrently.
go doMirror(sURLs, progressReader, accntReader, mirrorQueue, mirrorWg, statusCh)
}
}
mirrorWg.Wait()
}()
wg.Wait()
}
// 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 := newSessionV5()
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.
var err *probe.Error
session.Header.CommandArgs, err = args2URLs(ctx.Args())
if err != nil {
session.Delete()
fatalIf(err.Trace(ctx.Args()...), fmt.Sprintf("One or more unknown argument types found in ‘%s’.", ctx.Args()))
}
doMirrorSession(session)
session.Delete()
}
-160
View File
@@ -1,160 +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 {
SourceContent *client.Content
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, err := args2URLs(ctx.Args())
fatalIf(err.Trace(ctx.Args()...), "Unable to parse arguments.")
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) {
defer close(mirrorURLsCh)
// 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
}
objectDifferenceTarget, err := objectDifferenceFactory(targetURL)
if err != nil {
mirrorURLsCh <- mirrorURLs{Error: err.Trace(targetURL)}
return
}
sourceClient, err := url2Client(sourceURL)
if err != nil {
mirrorURLsCh <- mirrorURLs{Error: err.Trace(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{
SourceContent: sourceContent,
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
View File
@@ -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, err := ts.GetSize()
if err != nil {
return "", probe.NewError(err)
}
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
}
-112
View File
@@ -1,112 +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.amazonaws.com/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.amazonaws.com/ferenginar/gnuos.iso
4. Stream MySQL database dump to Amazon S3 directly.
$ mysqldump -u root -p ******* accountsdb | mc {{.Name}} s3.amazonaws.com/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 := putTarget(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, err := args2URLs(ctx.Args())
fatalIf(err.Trace(ctx.Args()...), "Unable to parse arguments.")
err = pipe(URLs[0])
fatalIf(err.Trace(URLs[0]), "Unable to write to one or more targets.")
}
}
-72
View File
@@ -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() *probe.Error
GetBucketAccess() (access string, error *probe.Error)
SetBucketAccess(access string) *probe.Error
// I/O operations
Get(offset, length int64) (body io.ReadSeeker, err *probe.Error)
Put(data io.ReadSeeker, size int64, contentType string) *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 {
AccessKeyID string
SecretAccessKey string
Signature string
HostURL string
AppName string
AppVersion string
AppComments []string
Debug bool
}
-69
View File
@@ -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, "")
}
-149
View File
@@ -1,149 +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 "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
}
// 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"
}
// PathIsDir (EISDIR) - file is a folder.
type PathIsDir GenericFileError
func (e PathIsDir) Error() string {
return "Requested file ‘" + e.Path + "’ is folder."
}
// 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"
}
-1
View File
@@ -1 +0,0 @@
*#
-86
View File
@@ -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(fpath)
}
return nil, probe.NewError(client.PathInsufficientPermission{Path: fpath})
}
err := f.toClientError(e, fpath)
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
}
-129
View File
@@ -1,129 +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"
)
// readDirNames reads the directory named by dirname and returns
// a sorted list of directory entries.
func readDirNames(dirname string) ([]string, error) {
names, err := readDirUnsortedNames(dirname)
if err != nil {
return nil, err
}
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(os.PathSeparator)
}
return info.Name()
}
func readDirUnsortedNames(dirname string) ([]string, error) {
f, err := os.Open(dirname)
if err != nil {
return nil, err
}
nameInfos, err := f.Readdir(-1)
f.Close()
if err != nil {
return nil, err
}
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, err := os.Lstat(root)
if err != nil {
return walkFn(root, nil, err)
}
return walk(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, err 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")
// walk recursively descends path, calling w.
func walk(path string, info os.FileInfo, walkFn WalkFunc) error {
err := walkFn(path, info, nil)
if err != nil {
if info.Mode().IsDir() && err == ErrSkipDir {
return nil
}
if info.Mode().IsRegular() && err == ErrSkipFile {
return nil
}
return err
}
if !info.IsDir() {
return nil
}
names, err := readDirNames(path)
if err != nil {
return walkFn(path, info, err)
}
for _, name := range names {
filename := filepath.Join(path, name)
fileInfo, err := os.Lstat(filename)
if err != nil {
if err := walkFn(filename, fileInfo, err); err != nil && err != ErrSkipDir && err != ErrSkipFile {
return err
}
} else {
err = walk(filename, fileInfo, walkFn)
if err != nil {
if err == ErrSkipDir || err == ErrSkipFile {
return nil
}
return err
}
}
}
return nil
}
-667
View File
@@ -1,667 +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/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(data io.ReadSeeker, size int64, contentType string) *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 a directory.
if st.IsDir() {
return probe.NewError(client.PathIsDir{
Path: objectPath,
})
}
}
// Proceed if file does not exist. return for all other errors.
if e != nil {
if !os.IsNotExist(e) {
return probe.NewError(e)
}
}
// Write to a temporary file "object.part.mc" before commiting.
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 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 err.Trace(f.PathURL.Path)
}
// Get stat to get the current size.
partSt, e := partFile.Stat()
if e != nil {
return probe.NewError(e)
}
// Seek to current position for incoming reader.
data.Seek(partSt.Size(), 0)
// Write to the part file.
if size < 0 { // Read till EOF.
_, e = io.Copy(partFile, data)
} else { // Read till N bytes.
_, e = io.CopyN(partFile, data, size-partSt.Size())
}
if e != nil {
err := f.toClientError(e, objectPartPath)
return err.Trace(objectPartPath)
}
// Close the file before rename.
partFile.Close()
// Safely completed put. Now commit by renaming to actual filename.
if e = os.Rename(objectPartPath, objectPath); e != nil {
err := f.toClientError(e, objectPath)
return err.Trace(objectPartPath, objectPath)
}
return 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",
})
}
// Get download an full or part object from bucket.
// returns a reader, length and nil for no errors.
func (f *fsClient) Get(offset, length int64) (io.ReadSeeker, *probe.Error) {
if offset < 0 || length < 0 {
return nil, probe.NewError(client.InvalidRange{Offset: offset})
}
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)
}
body, e := os.Open(f.PathURL.Path)
if e != nil {
err := f.toClientError(e, f.PathURL.Path)
return nil, err.Trace(f.PathURL.Path)
}
if offset == 0 && length == 0 {
return body, nil
}
return io.NewSectionReader(body, offset, length), 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 := ioutil.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 := ioutil.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 os.PathSeparator 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 os.PathSeparator - 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 os.PathSeparator,
// 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() *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
}
-249
View File
@@ -1,249 +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{})
func (s *MySuite) TestList(c *C) {
root, e := ioutil.TempDir(os.TempDir(), "fs-")
c.Assert(e, IsNil)
defer os.RemoveAll(root)
objectPath := filepath.Join(root, "object1")
fsc, err := fs.New(objectPath)
c.Assert(err, IsNil)
data := "hello"
err = fsc.Put(bytes.NewReader([]byte(data)), int64(len(data)), "application/octet-stream")
c.Assert(err, IsNil)
objectPath = filepath.Join(root, "object2")
fsc, err = fs.New(objectPath)
c.Assert(err, IsNil)
err = fsc.Put(bytes.NewReader([]byte(data)), int64(len(data)), "application/octet-stream")
c.Assert(err, IsNil)
fsc, err = fs.New(root)
c.Assert(err, IsNil)
var contents []*client.Content
for content := range fsc.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)
objectPath = filepath.Join(root, "test1/newObject1")
fsc, err = fs.New(objectPath)
c.Assert(err, IsNil)
err = fsc.Put(bytes.NewReader([]byte(data)), int64(len(data)), "application/octet-stream")
c.Assert(err, IsNil)
fsc, err = fs.New(root)
c.Assert(err, IsNil)
contents = nil
for content := range fsc.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)
fsc, err = fs.New(root)
c.Assert(err, IsNil)
contents = nil
for content := range fsc.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
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)
}
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")
fsc, err := fs.New(bucketPath)
c.Assert(err, IsNil)
err = fsc.MakeBucket()
c.Assert(err, IsNil)
}
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")
fsc, err := fs.New(bucketPath)
c.Assert(err, IsNil)
err = fsc.MakeBucket()
c.Assert(err, IsNil)
_, err = fsc.Stat()
c.Assert(err, IsNil)
}
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")
fsc, err := fs.New(bucketPath)
c.Assert(err, IsNil)
err = fsc.MakeBucket()
c.Assert(err, IsNil)
err = fsc.SetBucketAccess("private")
c.Assert(err, Not(IsNil))
_, err = fsc.GetBucketAccess()
c.Assert(err, Not(IsNil))
}
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")
fsc, err := fs.New(objectPath)
c.Assert(err, IsNil)
data := "hello"
err = fsc.Put(bytes.NewReader([]byte(data)), int64(len(data)), "application/octet-stream")
c.Assert(err, IsNil)
}
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")
fsc, err := fs.New(objectPath)
c.Assert(err, IsNil)
data := "hello"
err = fsc.Put(bytes.NewReader([]byte(data)), int64(len(data)), "application/octet-stream")
c.Assert(err, IsNil)
reader, err := fsc.Get(0, 0)
c.Assert(err, IsNil)
var results bytes.Buffer
_, e = io.Copy(&results, reader)
c.Assert(e, IsNil)
c.Assert([]byte(data), DeepEquals, results.Bytes())
}
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")
fsc, err := fs.New(objectPath)
c.Assert(err, IsNil)
data := "hello world"
err = fsc.Put(bytes.NewReader([]byte(data)), int64(len(data)), "application/octet-stream")
c.Assert(err, IsNil)
reader, err := fsc.Get(0, 5)
c.Assert(err, IsNil)
var results bytes.Buffer
_, e = io.Copy(&results, reader)
c.Assert(e, IsNil)
c.Assert([]byte("hello"), DeepEquals, results.Bytes())
}
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")
fsc, err := fs.New(objectPath)
c.Assert(err, IsNil)
data := "hello"
dataLen := len(data)
err = fsc.Put(bytes.NewReader([]byte(data)), int64(len(data)), "application/octet-stream")
c.Assert(err, IsNil)
content, err := fsc.Stat()
c.Assert(err, IsNil)
c.Assert(content.Size, Equals, int64(dataLen))
}
-23
View File
@@ -1,23 +0,0 @@
// +build darwin dragonfly freebsd linux nacl netbsd openbsd solaris
/*
* 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
}
-35
View File
@@ -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
}
-634
View File
@@ -1,634 +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"
"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 {
mu *sync.Mutex
api minio.CloudStorageAPI
hostURL *client.URL
virtualStyle bool
}
// New returns an initialized s3Client structure. if debug use a internal trace transport.
func New(config *client.Config) (client.Client, *probe.Error) {
u := client.NewURL(config.HostURL)
transport := http.DefaultTransport
if config.Debug == true {
if config.Signature == "S3v4" {
transport = httptracer.GetNewTraceTransport(NewTraceV4(), http.DefaultTransport)
}
if config.Signature == "S3v2" {
transport = httptracer.GetNewTraceTransport(NewTraceV2(), http.DefaultTransport)
}
}
s3Conf := minio.Config{
AccessKeyID: config.AccessKeyID,
SecretAccessKey: config.SecretAccessKey,
Transport: transport,
Endpoint: u.Scheme + u.SchemeSeparator + u.Host,
Signature: func() minio.SignatureType {
if config.Signature == "S3v2" {
return minio.SignatureV2
}
return minio.SignatureV4
}(),
}
s3Conf.SetUserAgent(config.AppName, config.AppVersion, config.AppComments...)
api, e := minio.New(s3Conf)
if e != nil {
return nil, probe.NewError(e)
}
s3Clnt := &s3Client{
mu: new(sync.Mutex),
api: api,
hostURL: u,
virtualStyle: isVirtualHostStyle(u.Host),
}
return s3Clnt, nil
}
// GetURL get url.
func (c *s3Client) GetURL() client.URL {
return *c.hostURL
}
// Get - get object.
func (c *s3Client) Get(offset, length int64) (io.ReadSeeker, *probe.Error) {
bucket, object := c.url2BucketAndObject()
reader, e := c.api.GetPartialObject(bucket, object, offset, length)
if e != nil {
errResponse := minio.ToErrorResponse(e)
if errResponse != nil {
if errResponse.Code == "AccessDenied" {
return nil, probe.NewError(client.PathInsufficientPermission{Path: c.hostURL.String()})
}
}
return nil, probe.NewError(e)
}
return reader, nil
}
// Remove - remove object or bucket.
func (c *s3Client) Remove(incomplete bool) *probe.Error {
bucket, object := c.url2BucketAndObject()
if incomplete {
errCh := c.api.RemoveIncompleteUpload(bucket, object)
return probe.NewError(<-errCh)
}
var e error
if object == "" {
e = c.api.RemoveBucket(bucket)
} else {
e = c.api.RemoveObject(bucket, object)
}
return probe.NewError(e)
}
// 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)
}
// Put - put object.
func (c *s3Client) Put(data io.ReadSeeker, size int64, contentType string) *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"
}
e := c.api.PutObject(bucket, object, data, size, contentType)
if e != nil {
errResponse := minio.ToErrorResponse(e)
if errResponse != nil {
if errResponse.Code == "AccessDenied" {
return probe.NewError(client.PathInsufficientPermission{
Path: c.hostURL.String(),
})
}
if errResponse.Code == "MethodNotAllowed" {
return probe.NewError(client.ObjectAlreadyExists{
Object: object,
})
}
if errResponse.Code == "InvalidArgument" {
return probe.NewError(client.ObjectMissing{})
}
}
return probe.NewError(e)
}
return nil
}
// MakeBucket - make a new bucket.
func (c *s3Client) MakeBucket() *probe.Error {
bucket, object := c.url2BucketAndObject()
if object != "" {
return probe.NewError(client.BucketNameTopLevel{})
}
if len(bucket) < 3 || len(bucket) > 63 {
return probe.NewError(errors.New("Bucket name should be more than 3 characters and less than 64 characters"))
}
match, _ := regexp.MatchString("^[a-zA-Z][a-zA-Z0-9\\-]+[a-zA-Z0-9]$", bucket)
if !match {
return probe.NewError(errors.New("Bucket name can contain alphabet, '-' and numbers, but first character should be an alphabet"))
}
e := c.api.MakeBucket(bucket, minio.BucketACL("private"))
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.mu.Lock()
objectMetadata := new(client.Content)
bucket, object := c.url2BucketAndObject()
switch {
// valid case for 'ls -r s3/'
case bucket == "" && object == "":
for bucket := range c.api.ListBuckets() {
if bucket.Err != nil {
c.mu.Unlock()
return nil, probe.NewError(bucket.Err)
}
}
c.mu.Unlock()
return &client.Content{URL: *c.hostURL, Type: os.ModeDir}, nil
}
if object != "" {
metadata, e := c.api.StatObject(bucket, object)
if e != nil {
c.mu.Unlock()
errResponse := minio.ToErrorResponse(e)
if errResponse != nil {
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.hostURL.Separator)) + string(c.hostURL.Separator)
for objectStat := range c.api.ListObjects(bucket, prefixName, false) {
if objectStat.Err != nil {
return nil, probe.NewError(objectStat.Err)
}
content := client.Content{}
content.URL = *c.hostURL
content.Type = os.ModeDir
return &content, nil
}
return nil, probe.NewError(client.PathNotFound{Path: c.hostURL.Path})
}
}
return nil, probe.NewError(e)
}
objectMetadata.URL = *c.hostURL
objectMetadata.Time = metadata.LastModified
objectMetadata.Size = metadata.Size
objectMetadata.Type = os.FileMode(0664)
c.mu.Unlock()
return objectMetadata, nil
}
e := c.api.BucketExists(bucket)
if e != nil {
c.mu.Unlock()
return nil, probe.NewError(e)
}
bucketMetadata := new(client.Content)
bucketMetadata.URL = *c.hostURL
bucketMetadata.Type = os.ModeDir
c.mu.Unlock()
return bucketMetadata, nil
}
// 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(hostURL string) bool {
matchS3, _ := filepath.Match("*.s3*.amazonaws.com", hostURL)
matchGoogle, _ := filepath.Match("*.storage.googleapis.com", hostURL)
return matchS3 || matchGoogle
}
// url2BucketAndObject gives bucketName and objectName from URL path.
func (c *s3Client) url2BucketAndObject() (bucketName, objectName string) {
path := c.hostURL.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.hostURL.Host, "s3")
if hostIndex == -1 {
hostIndex = strings.Index(c.hostURL.Host, "storage.googleapis")
}
if hostIndex > 0 {
bucket = c.hostURL.Host[:hostIndex-1]
path = string(c.hostURL.Separator) + bucket + c.hostURL.Path
}
}
splits := strings.SplitN(path, string(c.hostURL.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.mu.Lock()
defer c.mu.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 == "":
for bucket := range c.api.ListBuckets() {
if bucket.Err != nil {
contentCh <- &client.Content{
Err: probe.NewError(bucket.Err),
}
return
}
for object := range c.api.ListIncompleteUploads(bucket.Name, o, false) {
if object.Err != nil {
contentCh <- &client.Content{
Err: probe.NewError(object.Err),
}
return
}
content := new(client.Content)
url := *c.hostURL
// 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.hostURL.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:
for object := range c.api.ListIncompleteUploads(b, o, false) {
if object.Err != nil {
contentCh <- &client.Content{
Err: probe.NewError(object.Err),
}
return
}
content := new(client.Content)
url := *c.hostURL
// 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.hostURL.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 == "":
for bucket := range c.api.ListBuckets() {
if bucket.Err != nil {
contentCh <- &client.Content{
Err: probe.NewError(bucket.Err),
}
return
}
for object := range c.api.ListIncompleteUploads(bucket.Name, o, true) {
if object.Err != nil {
contentCh <- &client.Content{
Err: probe.NewError(object.Err),
}
return
}
content := new(client.Content)
url := *c.hostURL
url.Path = filepath.Join(url.Path, bucket.Name, object.Key)
content.URL = url
content.Size = object.Size
content.Time = object.Initiated
content.Type = os.ModeTemporary
contentCh <- content
}
}
default:
for object := range c.api.ListIncompleteUploads(b, o, true) {
if object.Err != nil {
contentCh <- &client.Content{
Err: probe.NewError(object.Err),
}
return
}
url := *c.hostURL
// 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 == "":
for bucket := range c.api.ListBuckets() {
if bucket.Err != nil {
contentCh <- &client.Content{
Err: probe.NewError(bucket.Err),
}
return
}
url := *c.hostURL
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.hostURL.Path, string(c.hostURL.Separator)) && o == "":
e := c.api.BucketExists(b)
if e != nil {
contentCh <- &client.Content{
Err: probe.NewError(e),
}
}
content := new(client.Content)
content.URL = *c.hostURL
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.hostURL
content.Time = metadata.LastModified
content.Size = metadata.Size
content.Type = os.FileMode(0664)
contentCh <- content
default:
for object := range c.api.ListObjects(b, o, false) {
if object.Err != nil {
contentCh <- &client.Content{
Err: probe.NewError(object.Err),
}
return
}
content := new(client.Content)
url := *c.hostURL
// 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.hostURL.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 == "":
for bucket := range c.api.ListBuckets() {
if bucket.Err != nil {
contentCh <- &client.Content{
Err: probe.NewError(bucket.Err),
}
return
}
bucketURL := *c.hostURL
bucketURL.Path = filepath.Join(bucketURL.Path, bucket.Name)
contentCh <- &client.Content{
URL: bucketURL,
Type: os.ModeDir,
Time: bucket.CreationDate,
}
for object := range c.api.ListObjects(bucket.Name, o, true) {
if object.Err != nil {
contentCh <- &client.Content{
Err: probe.NewError(object.Err),
}
continue
}
content := new(client.Content)
objectURL := *c.hostURL
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:
for object := range c.api.ListObjects(b, o, true) {
if object.Err != nil {
contentCh <- &client.Content{
Err: probe.NewError(object.Err),
}
continue
}
content := new(client.Content)
url := *c.hostURL
// 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
}
}
}
-202
View File
@@ -1,202 +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":
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)
case r.URL.Path == "/bucket":
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:
_, 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":
length, err := strconv.Atoi(r.Header.Get("Content-Length"))
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
var buffer bytes.Buffer
_, err = io.CopyN(&buffer, r.Body, int64(length))
if err != 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":
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 == "GET":
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{})
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
s3c, err := New(conf)
c.Assert(err, IsNil)
err = s3c.MakeBucket()
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)
}
}
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
s3c, err := New(conf)
c.Assert(err, IsNil)
err = s3c.Put(bytes.NewReader(object.data), int64(len(object.data)), "application/octet-stream")
c.Assert(err, IsNil)
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(0, 0)
var buffer bytes.Buffer
{
_, err := io.Copy(&buffer, reader)
c.Assert(err, IsNil)
c.Assert(buffer.Bytes(), DeepEquals, object.data)
}
}
-66
View File
@@ -1,66 +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) {
resTrace, err := httputil.DumpResponse(res, false) // Only display header
if err == nil {
console.Debug(string(resTrace))
}
return err
}
-75
View File
@@ -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"
"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) {
resTrace, err := httputil.DumpResponse(res, false) // Only display header
if err == nil {
console.Debug(string(resTrace))
}
return err
}
-178
View File
@@ -1,178 +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 = url1.Path
url2Path = url2.Path
if runtime.GOOS == "windows" {
url1Path = strings.Replace(url1.Path, "\\", "/", -1)
url2Path = strings.Replace(url2.Path, "\\", "/", -1)
}
if url1.Type == Object {
if strings.HasSuffix(url1Path, "/") {
url1.Path = url1Path + strings.TrimPrefix(url2Path, "/")
} else {
url1.Path = url1Path + "/" + strings.TrimPrefix(url2Path, "/")
}
}
if url1.Type == Filesystem {
if strings.HasSuffix(url1Path, "/") {
url1.Path = url1Path + strings.TrimPrefix(url2Path, "/")
} else {
url1.Path = url1Path + "/" + strings.TrimPrefix(url2Path, "/")
}
if runtime.GOOS == "windows" {
url1.Path = strings.Replace(url1.Path, "/", "\\", -1)
}
}
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()
}
-355
View File
@@ -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
}
-42
View File
@@ -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()
}
-53
View File
@@ -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
}
-74
View File
@@ -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}
}
-33
View File
@@ -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) {
//
}
-34
View File
@@ -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())
}
}
-239
View File
@@ -1,239 +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"
)
// pbBar type of operation.
type pbBar int
// collection of different progress bar operations.
const (
pbBarProgress pbBar = iota
pbBarFinish
pbBarPutError
pbBarGetError
pbBarSetCaption
)
// proxyReader progress bar proxy reader for barSend inherits io.ReadCloser.
type proxyReader struct {
io.ReadSeeker
bar *barSend
}
// Read proxy Read sends progress for each Read operation.
func (r *proxyReader) Read(p []byte) (n int, err error) {
n, err = r.ReadSeeker.Read(p)
if err != nil {
return
}
r.bar.Progress(int64(n))
return
}
func (r *proxyReader) Seek(offset int64, whence int) (n int64, err error) {
n, err = r.ReadSeeker.Seek(offset, whence)
if err != nil {
return
}
r.bar.Progress(n)
return
}
// barMsg progress bar message for a given operation.
type barMsg struct {
Op pbBar
Arg interface{}
}
// barSend implements various methods for progress bar operation.
type barSend struct {
opCh chan<- barMsg
finishCh <-chan bool
}
// Instantiate a new progress bar proxy reader.
func (b *barSend) NewProxyReader(r io.ReadSeeker) *proxyReader {
return &proxyReader{r, b}
}
// Progress send current progress message.
func (b barSend) Progress(progress int64) {
b.opCh <- barMsg{Op: pbBarProgress, Arg: progress}
}
// ErrorPut send message for error in put operation.
func (b barSend) ErrorPut(size int64) {
b.opCh <- barMsg{Op: pbBarPutError, Arg: size}
}
// ErrorGet send message for error in get operation.
func (b barSend) ErrorGet(size int64) {
b.opCh <- barMsg{Op: pbBarGetError, Arg: size}
}
// SetCaption set an additional prefix/caption for an active progress bar.
func (b *barSend) SetCaption(c string) {
b.opCh <- barMsg{Op: pbBarSetCaption, Arg: c}
}
// Finish finishes the progress bar and closes the message channel.
func (b barSend) Finish() {
defer close(b.opCh)
b.opCh <- barMsg{Op: pbBarFinish}
<-b.finishCh
}
// 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 = "◰◳◲◱"
case "darwin":
cursors = "◐◓◑◒"
//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
}
// newProgressBar - instantiate a progress bar.
func newProgressBar(total int64) *barSend {
// Progress bar speific theme customization.
console.SetColor("Bar", color.New(color.FgGreen, color.Bold))
cmdCh := make(chan barMsg)
finishCh := make(chan bool)
go func(total int64, cmdCh <-chan barMsg, finishCh chan<- bool) {
var started bool // has the progress bar started? default is false.
var totalBytesRead int64 // total amounts of bytes read
// get the new original progress bar.
bar := pb.New64(total)
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":
bar.Format("┃▓█░┃")
// bar.Format("█▓▒░█")
case "darwin":
bar.Format(" ▓ ░ ")
default:
bar.Format("[=> ]")
}
// Look for incoming progress bar messages.
for msg := range cmdCh {
switch msg.Op {
case pbBarSetCaption:
// Sets a new caption prefixed along with progress bar.
bar.Prefix(fixateBarCaption(msg.Arg.(string), getFixedWidth(bar.GetWidth(), 18)))
case pbBarProgress:
// Initializes the progerss bar, if already started bumps up the totalBytes.
if bar.Total > 0 && !started {
started = true
bar.Start()
}
if msg.Arg.(int64) > 0 {
totalBytesRead += msg.Arg.(int64)
bar.Add64(msg.Arg.(int64))
}
case pbBarPutError:
// Negates any put error of size from totalBytes.
if totalBytesRead > msg.Arg.(int64) {
bar.Set64(totalBytesRead - msg.Arg.(int64))
}
case pbBarGetError:
// Retains any size transferred but failed.
if msg.Arg.(int64) > 0 {
bar.Add64(msg.Arg.(int64))
}
case pbBarFinish:
// Progress finishes here.
if started {
bar.Finish()
}
// All done send true.
finishCh <- true
return
}
}
}(total, cmdCh, finishCh)
return &barSend{cmdCh, finishCh}
}
-5
View File
@@ -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
-6
View File
@@ -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"
-225
View File
@@ -1,225 +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"
"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.amazonaws.com/jazz-songs/louis/
3. Remove contents of a folder recursively.
$ mc {{.Name}} --force --recursive s3.amazonaws.com/jazz-songs/louis/
4. Remove all matching objects with this prefix.
$ mc {{.Name}} --force s3.amazonaws.com/ogg/gunmetal
5. Drop an incomplete upload of an object.
$ mc {{.Name}} --incomplete s3.amazonaws.com/jazz-songs/louis/file01.mp3
6. Drop all incomplete uploads recursively matching this prefix.
$ mc {{.Name}} --incomplete --force --recursive s3.amazonaws.com/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")
isIncomplete := ctx.Bool("incomplete")
if !ctx.Args().Present() {
exitCode := 1
cli.ShowCommandHelpAndExit(ctx, "rm", exitCode)
}
if !isRecursive && !isIncomplete {
URLs, err := args2URLs(ctx.Args())
fatalIf(err.Trace(ctx.Args()...), "Unable to parse arguments.")
for _, url := range URLs {
if _, _, err := url2Stat(url); err != nil {
fatalIf(err.Trace(url), "Unable to stat.")
}
}
}
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(url string, isIncomplete, isFake bool) *probe.Error {
clnt, err := url2Client(url)
if err != nil {
return err.Trace(url)
}
if isFake { // It is a fake remove. Return success.
return nil
}
if err = clnt.Remove(isIncomplete); err != nil {
return err.Trace(url)
}
return nil
}
// Remove all objects recursively.
func rmAll(url string, isRecursive, isIncomplete, isFake bool) {
// Initialize new client.
clnt, err := url2Client(url)
if err != nil {
errorIf(err.Trace(url), "Invalid URL ‘"+url+"’.")
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(url), "Unable to list ‘"+url+"’.")
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(url.String(), isRecursive, isIncomplete, isFake)
}
// Regular type.
if err = rm(entry.URL.String(), isIncomplete, isFake); err != nil {
errorIf(err.Trace(entry.URL.String()), "Unable to remove ‘"+entry.URL.String()+"’.")
continue
}
printMsg(rmMessage{Status: "success", URL: entry.URL.String()})
}
}
// 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))
// Parse args.
URLs, err := args2URLs(ctx.Args())
fatalIf(err.Trace(ctx.Args()...), "Unable to parse arguments.")
// Support multiple targets.
for _, url := range URLs {
if isRecursive && isForce {
rmAll(url, isRecursive, isIncomplete, isFake)
} else {
if err := rm(url, isIncomplete, isFake); err != nil {
errorIf(err.Trace(url), "Unable to remove ‘"+url+"’.")
continue
}
printMsg(rmMessage{Status: "success", URL: url})
}
}
}
-75
View File
@@ -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, err := ts.GetSize()
if err != nil {
fatalIf(probe.NewError(err), "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
View File
@@ -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 []*sessionV5
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 []*sessionV5
for _, sid := range getSessionIDs() {
s, err := loadSessionV5(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, err := json.Marshal(c)
fatalIf(probe.NewError(err), "Unable to marshal into JSON.")
return string(clearSessionJSONBytes)
}
// clearSession clear sessions.
func clearSession(sid string) {
if sid == "all" {
for _, sid := range getSessionIDs() {
session, err := loadSessionV5(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 := loadSessionV5(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 *sessionV5) {
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 := loadSessionV5(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()))
}
}
-349
View File
@@ -1,349 +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 migrateSessionV4ToV5() {
for _, sid := range getSessionIDs() {
sessionV5, err := loadSessionV5(sid)
fatalIf(err.Trace(sid), "Unable to load version ‘5’. Migration failed please report this issue at https://github.com/minio/mc/issues.")
if sessionV5.Header.Version == "5" { // It is new format.
return
}
/*** Remove all session files older than v5 ***/
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 ‘" + sessionV5.Header.Version + "’.")
if e := os.Remove(sessionFile); e != nil {
fatalIf(probe.NewError(e), "Unable to remove version ‘"+sessionV5.Header.Version+"’ session file ‘"+sessionFile+"’.")
}
if e := os.Remove(sessionDataFile); e != nil {
fatalIf(probe.NewError(e), "Unable to remove version ‘"+sessionV5.Header.Version+"’ session data file ‘"+sessionDataFile+"’.")
}
}
}
// sessionV5Header for resumable sessions.
type sessionV5Header 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"`
}
// sessionV5 resumable session container.
type sessionV5 struct {
Header *sessionV5Header
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 sessionV5) 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 sessionV5) 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)
}
// loadSessionV5 - reads session file if exists and re-initiates internal variables
func loadSessionV5(sid string) (*sessionV5, *probe.Error) {
if !isSessionDirExists() {
return nil, errInvalidArgument().Trace()
}
sessionFile, err := getSessionFile(sid)
if err != nil {
return nil, err.Trace(sid)
}
if _, err := os.Stat(sessionFile); err != nil {
return nil, probe.NewError(err)
}
s := &sessionV5{}
s.Header = &sessionV5Header{}
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().(*sessionV5Header)
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
}
// newSessionV5 provides a new session.
func newSessionV5() *sessionV5 {
s := &sessionV5{}
s.Header = &sessionV5Header{}
s.Header.Version = "5"
// 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 sessionV5) HasData() bool {
if s.Header.LastCopied == "" {
return false
}
return true
}
// NewDataReader provides reader interface to session data file.
func (s *sessionV5) 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 *sessionV5) 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 *sessionV5) 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 *sessionV5) 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 sessionV5) 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 *sessionV5) 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 *sessionV5) 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()
err := os.Remove(name)
if err != nil {
return probe.NewError(err)
}
}
sessionFile, err := getSessionFile(s.SessionID)
if err != nil {
return err.Trace(s.SessionID)
}
if err := os.Remove(sessionFile); err != nil {
return probe.NewError(err)
}
return nil
}
// Close a session and exit.
func (s sessionV5) CloseAndDie() {
s.Close()
console.Infoln("Session safely terminated. To resume session ‘mc session resume " + s.SessionID + "’")
os.Exit(0)
}
// 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
View File
@@ -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.
migrateSessionV4ToV5()
}
// createSessionDir - create session directory.
func createSessionDir() *probe.Error {
sessionDir, err := getSessionDir()
if err != nil {
return err.Trace()
}
if err := os.MkdirAll(sessionDir, 0700); err != nil {
return probe.NewError(err)
}
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
}
-53
View File
@@ -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 := newSessionV5()
c.Assert(session.Header.CommandArgs, IsNil)
c.Assert(len(session.SessionID), Equals, 8)
err = session.Close()
c.Assert(err, IsNil)
savedSession, err := loadSessionV5(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
View File
@@ -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 _, err := os.Stat(filename); err != nil {
return probe.NewError(err)
}
// 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)
}
-186
View File
@@ -1,186 +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.amazonaws.com/backup/2006-Mar-1/backup.tar.gz
2. Share this object with 10 minutes expiry.
$ mc share {{.Name}} --expire=10m s3.amazonaws.com/backup/2006-Mar-1/backup.tar.gz
3. Share all objects under this folder with 5 days expiry.
$ mc share {{.Name}} --expire=120h s3.amazonaws.com/backup/
4. Share all objects under this folder and all its sub-folders with 5 days expiry.
$ mc share {{.Name}} --recursive --expire=120h s3.amazonaws.com/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.")
}
URLs, err := args2URLs(ctx.Args()) // expand alias.
fatalIf(err.Trace(ctx.Args()...), "Unable to convert args to URLs.")
for _, url := range URLs {
_, _, 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 {
clnt, err := url2Client(targetURL)
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 := url2Client(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")+"’.")
}
URLs, err := args2URLs(ctx.Args()) // expand alias.
fatalIf(err.Trace(ctx.Args()...), "Unable to convert args to URLs.")
for _, targetURL := range URLs {
err := doShareDownloadURL(targetURL, isRecursive, expiry)
fatalIf(err.Trace(targetURL), "Unable to share target ‘"+targetURL+"’.")
}
}
-123
View File
@@ -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.")
}
-91
View File
@@ -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.
}
-215
View File
@@ -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 (
"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.amazonaws.com/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.amazonaws.com/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.amazonaws.com/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.amazonaws.com/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.")
}
URLs, err := args2URLs(ctx.Args()) // expand alias.
fatalIf(err.Trace(ctx.Args()...), "Unable to convert args to URLs.")
for _, targetURL := range URLs {
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 := url2Client(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)
}
// 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+"’.")
}
URLs, err := args2URLs(ctx.Args()) // expand alias.
fatalIf(err.Trace(ctx.Args()...), "Unable to convert args to URLs.")
for _, targetURL := range URLs {
err := doShareUploadURL(targetURL, isRecursive, expiry, contentType)
fatalIf(err.Trace(targetURL), "Unable to generate curl command for upload ‘"+targetURL+"’.")
}
}
-198
View File
@@ -1,198 +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 err := os.MkdirAll(mustGetShareDir(), 0700); err != nil {
return probe.NewError(err)
}
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
View File
@@ -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
View File
@@ -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
}
-24
View File
@@ -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
View File
@@ -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.
-2
View File
@@ -1,2 +0,0 @@
## mc-tests
Scripts written for daily automated testing.
-69
View File
@@ -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 "$@"
-5
View File
@@ -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.

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