Compare commits
539
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
073ed250fe | ||
|
|
3b78c115f6 | ||
|
|
f8aafcc774 | ||
|
|
22b8ab43bd | ||
|
|
5eab7c2698 | ||
|
|
26f5102eae | ||
|
|
9998e077df | ||
|
|
480bc8aa2a | ||
|
|
a8c97b467d | ||
|
|
7f01db2cda | ||
|
|
d83e73b85b | ||
|
|
7e49e2d519 | ||
|
|
5a962a7cf5 | ||
|
|
70dcf20d74 | ||
|
|
c57a2dc4c2 | ||
|
|
4ab7f30f99 | ||
|
|
29f2dbca6b | ||
|
|
4070902cda | ||
|
|
556bbc2de5 | ||
|
|
7e879edabc | ||
|
|
f48ac0de19 | ||
|
|
1a5aab3ff4 | ||
|
|
8cf797da5f | ||
|
|
023b38fe3f | ||
|
|
afcfe758f3 | ||
|
|
c0b89a7aec | ||
|
|
4f1f864f64 | ||
|
|
2d4346bfe1 | ||
|
|
d566905d7a | ||
|
|
743d72ea1a | ||
|
|
10059459f3 | ||
|
|
376b4ce2f8 | ||
|
|
961c4b5dae | ||
|
|
1711f0bb46 | ||
|
|
b41b98b04d | ||
|
|
1b794a4ae1 | ||
|
|
182ad295d8 | ||
|
|
75e9691616 | ||
|
|
1ccf40d1e5 | ||
|
|
2dc48e9dd3 | ||
|
|
757fff7764 | ||
|
|
0fe4319e17 | ||
|
|
18ddd3925b | ||
|
|
8aaf909a08 | ||
|
|
da5c19848d | ||
|
|
45b32d3985 | ||
|
|
ae3c123a5c | ||
|
|
fe82b0381c | ||
|
|
0ede95b65e | ||
|
|
4758556eec | ||
|
|
ea580b0b65 | ||
|
|
b1dd99c94d | ||
|
|
57bf0c0e79 | ||
|
|
7ebe7908ea | ||
|
|
750644ec4d | ||
|
|
efeaf2ee72 | ||
|
|
97c7984bca | ||
|
|
335a53ad29 | ||
|
|
d4981656d3 | ||
|
|
766e04d79d | ||
|
|
4e30ca1617 | ||
|
|
65e22bee24 | ||
|
|
3987f1405a | ||
|
|
e1056aa50d | ||
|
|
017dddef97 | ||
|
|
55f06077e5 | ||
|
|
99ee2a5042 | ||
|
|
793cda2ca0 | ||
|
|
83bb797389 | ||
|
|
8fbbd0ee83 | ||
|
|
b94b8e67e9 | ||
|
|
f93fb55606 | ||
|
|
3b4626ea15 | ||
|
|
d9663e5d96 | ||
|
|
5d703df69d | ||
|
|
5f2f82b5f7 | ||
|
|
5dee56d5d0 | ||
|
|
722ee94165 | ||
|
|
b64c8a3aa9 | ||
|
|
13259eea21 | ||
|
|
9da492975c | ||
|
|
96dc4f920d | ||
|
|
2d221ba8da | ||
|
|
87309ebaac | ||
|
|
eeb18ff75c | ||
|
|
4cb6e35342 | ||
|
|
5ddf9728f8 | ||
|
|
275db95170 | ||
|
|
399187c4fb | ||
|
|
1fd03fb81f | ||
|
|
0aa704ad5e | ||
|
|
1e7b4c9e4a | ||
|
|
65c582cd5b | ||
|
|
336e7f58bf | ||
|
|
dfffc1e7cc | ||
|
|
a63a1f7eca | ||
|
|
b3fe40e113 | ||
|
|
093ab6b034 | ||
|
|
ceb38130fc | ||
|
|
7498e97182 | ||
|
|
32a8f34f7d | ||
|
|
014d09412a | ||
|
|
ab6b2a83ac | ||
|
|
79a51e9afc | ||
|
|
c9448749d0 | ||
|
|
aa8d5ed0cc | ||
|
|
a86080a0b7 | ||
|
|
59685e2d6b | ||
|
|
582f99b438 | ||
|
|
26c7c3e500 | ||
|
|
785e14a725 | ||
|
|
7ad9a36b9d | ||
|
|
9831612507 | ||
|
|
207d5cfb61 | ||
|
|
c10b429dcb | ||
|
|
8f38471e29 | ||
|
|
25254c7622 | ||
|
|
7d062fb08c | ||
|
|
37e5a78779 | ||
|
|
07e810fd51 | ||
|
|
224e602e59 | ||
|
|
be710ecb52 | ||
|
|
4810ab8727 | ||
|
|
5a2798dddb | ||
|
|
36d7d0b9a7 | ||
|
|
b1812ebe5a | ||
|
|
683fcf0dd2 | ||
|
|
39197ea3ae | ||
|
|
48bd32570f | ||
|
|
49ef42d36a | ||
|
|
fe583468ce | ||
|
|
3f4d3ee1c0 | ||
|
|
dd3b659f9e | ||
|
|
dc47c3819a | ||
|
|
e6ca983442 | ||
|
|
ca96cfc6e6 | ||
|
|
60681d7fb6 | ||
|
|
e53ad24e8c | ||
|
|
b62fa406d8 | ||
|
|
d066ff71f5 | ||
|
|
3e2c3fc94d | ||
|
|
c1b9079b73 | ||
|
|
b9401d574f | ||
|
|
eba548ca88 | ||
|
|
b4d7ec07f4 | ||
|
|
4753e1e61b | ||
|
|
8d7888eb4f | ||
|
|
54a7460fa0 | ||
|
|
5c135d25d6 | ||
|
|
8391a69dc5 | ||
|
|
1b9beadf2b | ||
|
|
05f588fd19 | ||
|
|
d01a50d301 | ||
|
|
3b53bbe478 | ||
|
|
685299ab75 | ||
|
|
1a8561115b | ||
|
|
c32b1ea48b | ||
|
|
ea05fcbcf5 | ||
|
|
2d44e8c85e | ||
|
|
21c677fc2d | ||
|
|
800f0af04e | ||
|
|
398bac82d9 | ||
|
|
cd16de763c | ||
|
|
694ab27649 | ||
|
|
61f2595852 | ||
|
|
be3370396a | ||
|
|
fed9ebe39d | ||
|
|
6c677e0d11 | ||
|
|
320e29e03f | ||
|
|
7f65ad4957 | ||
|
|
372e905dad | ||
|
|
7027211e58 | ||
|
|
f0ccc91890 | ||
|
|
136e286ef4 | ||
|
|
e54962e17f | ||
|
|
39aa635971 | ||
|
|
61e511cc3e | ||
|
|
dd9e715599 | ||
|
|
9bdb7affb1 | ||
|
|
9a881562b9 | ||
|
|
656f4f13d0 | ||
|
|
9eb967cabf | ||
|
|
1bf5ac350f | ||
|
|
313d0a358f | ||
|
|
81f3ffa3af | ||
|
|
9ea42680b0 | ||
|
|
018bcbf629 | ||
|
|
0733d37c67 | ||
|
|
b0968e29e8 | ||
|
|
fac4ef81b2 | ||
|
|
e494e138fe | ||
|
|
5805a37d27 | ||
|
|
ad04a6fcc4 | ||
|
|
7084a4361e | ||
|
|
a009299433 | ||
|
|
1c038760ce | ||
|
|
eafa942a30 | ||
|
|
05468dfc8d | ||
|
|
ff7ed00714 | ||
|
|
3c0094a5fe | ||
|
|
923c0e24b1 | ||
|
|
3b57e86cd3 | ||
|
|
1a6987558a | ||
|
|
a15d54c4a8 | ||
|
|
3c4c1222d8 | ||
|
|
250def49d5 | ||
|
|
b1e3d147f5 | ||
|
|
6c89b81d7b | ||
|
|
7c7969ed55 | ||
|
|
29920f8c9c | ||
|
|
9ebb916902 | ||
|
|
4369359286 | ||
|
|
1dab94c625 | ||
|
|
6c0f804f32 | ||
|
|
7991f67863 | ||
|
|
22ab1c4901 | ||
|
|
53cb92038a | ||
|
|
4425378b37 | ||
|
|
7fda78af40 | ||
|
|
6e8320a6dc | ||
|
|
99682ecbdb | ||
|
|
bf657a33e3 | ||
|
|
bab1b9302e | ||
|
|
8ce6f43e35 | ||
|
|
ecee324c00 | ||
|
|
0934a39d73 | ||
|
|
7673ef084d | ||
|
|
55e010ca52 | ||
|
|
1ef242a5c1 | ||
|
|
071c71efbc | ||
|
|
798775775b | ||
|
|
2ca601ef22 | ||
|
|
1cfb326e2f | ||
|
|
675fbee1f3 | ||
|
|
d055f0edac | ||
|
|
1f48b16acb | ||
|
|
41d4857d73 | ||
|
|
f7dbf9a20b | ||
|
|
d7a3a0bce3 | ||
|
|
7483cdebfb | ||
|
|
e7e44b96ee | ||
|
|
43388a06ca | ||
|
|
ace3f452c3 | ||
|
|
fb9d10772a | ||
|
|
a5014a8c71 | ||
|
|
8ce4b39fed | ||
|
|
f01f94a691 | ||
|
|
04cd5e80ee | ||
|
|
4fd1500312 | ||
|
|
5b74d8c444 | ||
|
|
1d683ea83e | ||
|
|
38652b168a | ||
|
|
cca8c10f33 | ||
|
|
2ffa265d8c | ||
|
|
ad850412d2 | ||
|
|
4f0c2bf376 | ||
|
|
fa75251c76 | ||
|
|
3fefebd05d | ||
|
|
9d7529118e | ||
|
|
507e7672c2 | ||
|
|
9c81d374b1 | ||
|
|
38c3703d08 | ||
|
|
973dc13cc0 | ||
|
|
bca93f6c83 | ||
|
|
caf6bfb76f | ||
|
|
76180184a5 | ||
|
|
0e1e954768 | ||
|
|
b031817fce | ||
|
|
6b2e63e66c | ||
|
|
085a1e512f | ||
|
|
31cb23f586 | ||
|
|
6a7ca4311e | ||
|
|
d87078bee6 | ||
|
|
50228116e1 | ||
|
|
95033f3f76 | ||
|
|
a8acbe5cfb | ||
|
|
f9d4c4dbac | ||
|
|
17abc6c736 | ||
|
|
94bd9564d0 | ||
|
|
c6cb6595be | ||
|
|
a2f25c2f3b | ||
|
|
5d3c4ed96c | ||
|
|
7cec8f2285 | ||
|
|
86777e7863 | ||
|
|
853fea16b4 | ||
|
|
9cf76b1233 | ||
|
|
66a65aab02 | ||
|
|
5581915bc0 | ||
|
|
ee7f4e1d52 | ||
|
|
8c65985cd0 | ||
|
|
23a58eb5da | ||
|
|
9193eef1c9 | ||
|
|
e90e9bc352 | ||
|
|
a1d860f818 | ||
|
|
d733d68b0c | ||
|
|
4a96d65408 | ||
|
|
1e16ed5e55 | ||
|
|
782352ae56 | ||
|
|
d97ba4eb0d | ||
|
|
282246fff2 | ||
|
|
b3059164aa | ||
|
|
64166319ee | ||
|
|
b8e732e526 | ||
|
|
f0d926ebba | ||
|
|
1e48d10617 | ||
|
|
ce9d706716 | ||
|
|
81abbca12f | ||
|
|
2cd67b296e | ||
|
|
7976d6d805 | ||
|
|
df395786bd | ||
|
|
2412aae68f | ||
|
|
0a42e2969a | ||
|
|
b51e6b0485 | ||
|
|
e1ed7c65e7 | ||
|
|
cf89d74561 | ||
|
|
38aec4d875 | ||
|
|
23f0a27acc | ||
|
|
447cb7a726 | ||
|
|
fa5a339434 | ||
|
|
7a295dd5fa | ||
|
|
2895b0acca | ||
|
|
ab9cdd7fce | ||
|
|
cc6fa9acbf | ||
|
|
e14dcccd37 | ||
|
|
27526399f5 | ||
|
|
8009e8108b | ||
|
|
b45d48f4f1 | ||
|
|
b9f1950320 | ||
|
|
6de2b4559e | ||
|
|
0661f537cf | ||
|
|
b737b2e7fc | ||
|
|
d9b3f276b8 | ||
|
|
53ab0168e4 | ||
|
|
01f0c35651 | ||
|
|
75d55783c0 | ||
|
|
f03aaef72f | ||
|
|
f54e426bb1 | ||
|
|
5b94ddc703 | ||
|
|
477461325d | ||
|
|
3094af8a5e | ||
|
|
add7dcc763 | ||
|
|
df7acbcad4 | ||
|
|
15b91126d5 | ||
|
|
2b24a7b520 | ||
|
|
b404c7583b | ||
|
|
6ce337ca38 | ||
|
|
d0caa630af | ||
|
|
8a48d604a8 | ||
|
|
80b0aa3842 | ||
|
|
c6a383590d | ||
|
|
fd34958ffa | ||
|
|
530a34a3f3 | ||
|
|
90093b5d8c | ||
|
|
939dad5900 | ||
|
|
85717527d9 | ||
|
|
768be74f74 | ||
|
|
a885ffd64b | ||
|
|
e25f1ee72f | ||
|
|
6e943832d5 | ||
|
|
3a3bc2ffb1 | ||
|
|
90a421e4af | ||
|
|
bc72ffb6b2 | ||
|
|
a30f0aca85 | ||
|
|
2ea2ec90d2 | ||
|
|
22670acfbe | ||
|
|
358a5af98e | ||
|
|
c70bd05494 | ||
|
|
0b4d52a141 | ||
|
|
a47c86c54c | ||
|
|
082ea3c295 | ||
|
|
a4177ad30b | ||
|
|
3603766f1c | ||
|
|
951429fe67 | ||
|
|
f5ff7e15cf | ||
|
|
c9c95f2e9e | ||
|
|
bc79fba49a | ||
|
|
b51fb32054 | ||
|
|
c9ecd023fa | ||
|
|
c28aa819b6 | ||
|
|
f6ca45c384 | ||
|
|
75de34de90 | ||
|
|
429a0d00af | ||
|
|
acf933646b | ||
|
|
b427202237 | ||
|
|
8eaa9463c1 | ||
|
|
e15f04c01b | ||
|
|
626baab73d | ||
|
|
5e8f861eac | ||
|
|
9217553a3c | ||
|
|
ab20dc98f7 | ||
|
|
9f1315fa64 | ||
|
|
46d158d023 | ||
|
|
acd80370e6 | ||
|
|
9ad19bfe52 | ||
|
|
eed14719db | ||
|
|
589c821f9b | ||
|
|
a09795c8a7 | ||
|
|
52df29917b | ||
|
|
16ae081c4c | ||
|
|
489d1629fb | ||
|
|
9be8aebfff | ||
|
|
e53fa1a5a2 | ||
|
|
92d1e226d3 | ||
|
|
64dbb7ed9c | ||
|
|
21b0f4b0d2 | ||
|
|
fc448e49d5 | ||
|
|
7a21e4bb0d | ||
|
|
47ca8a61ea | ||
|
|
1c3f889f6e | ||
|
|
6f4a0f9cbb | ||
|
|
67c1957eb0 | ||
|
|
3d7796f38c | ||
|
|
2d431dacbc | ||
|
|
17468c8863 | ||
|
|
475670de7d | ||
|
|
f9efb67bc2 | ||
|
|
9766ff1805 | ||
|
|
cc4227e3f2 | ||
|
|
ba2e8149c8 | ||
|
|
b48371e971 | ||
|
|
8b074767db | ||
|
|
e5bc26c75a | ||
|
|
959fa74ca5 | ||
|
|
ac57970229 | ||
|
|
9fb8cfc1b3 | ||
|
|
06ad6c53f7 | ||
|
|
a9b0b14149 | ||
|
|
9a454e714d | ||
|
|
319b3d8434 | ||
|
|
2fec2b4107 | ||
|
|
382aa26859 | ||
|
|
d7854b6dfa | ||
|
|
e3b6c12925 | ||
|
|
d9224348ce | ||
|
|
6b91c6f430 | ||
|
|
7e9b96e354 | ||
|
|
8a8d4619de | ||
|
|
3af0902f28 | ||
|
|
6b4c1a4239 | ||
|
|
783d29794a | ||
|
|
a094c50f5a | ||
|
|
621e8cf0ff | ||
|
|
4bd9336139 | ||
|
|
c517833663 | ||
|
|
8e4cc8df00 | ||
|
|
94f4c4cd2d | ||
|
|
c4c99999bc | ||
|
|
6abd3a4ed6 | ||
|
|
9e94120d68 | ||
|
|
ba088b8fc0 | ||
|
|
98ac1817cb | ||
|
|
65a31e34c9 | ||
|
|
264f1ef992 | ||
|
|
b30bbc0e74 | ||
|
|
7a77686878 | ||
|
|
0c4200306b | ||
|
|
619b1b4e2a | ||
|
|
57d22664f4 | ||
|
|
38339b7cd9 | ||
|
|
d5cb19aeab | ||
|
|
3d04e56228 | ||
|
|
3e8f7684f2 | ||
|
|
c11527780a | ||
|
|
5a204741b9 | ||
|
|
b23e8a77fc | ||
|
|
e926266c62 | ||
|
|
1eca4f8c0d | ||
|
|
edb1824006 | ||
|
|
6666262e51 | ||
|
|
221ee6c26b | ||
|
|
d3d4afd223 | ||
|
|
f55f64b5b9 | ||
|
|
69fbb9a87d | ||
|
|
8e50e8e8c3 | ||
|
|
8cdf71b539 | ||
|
|
e7f4b63212 | ||
|
|
12adf3be32 | ||
|
|
087516a783 | ||
|
|
1b2a2fc7f9 | ||
|
|
3e205dba15 | ||
|
|
ff874575e1 | ||
|
|
1e1516c968 | ||
|
|
aeb6de996c | ||
|
|
82d87111fc | ||
|
|
49953d53ed | ||
|
|
13a4133da5 | ||
|
|
a02ae19de2 | ||
|
|
9617f22fcd | ||
|
|
e156d62e44 | ||
|
|
f4e8352f5a | ||
|
|
deb7f72be2 | ||
|
|
a5a57fa2be | ||
|
|
c3fb1d52f4 | ||
|
|
9820dce775 | ||
|
|
426df2c9ab | ||
|
|
20c7a00af5 | ||
|
|
00d0f1e9d9 | ||
|
|
4cecac4ea4 | ||
|
|
b0e2bde84d | ||
|
|
49851c8795 | ||
|
|
7bdb39c743 | ||
|
|
09495582c4 | ||
|
|
f15be9582a | ||
|
|
c022107515 | ||
|
|
373b593c3e | ||
|
|
ca06c0e09f | ||
|
|
bd1086c244 | ||
|
|
69c8bf7959 | ||
|
|
db6b4f1344 | ||
|
|
05db6e3981 | ||
|
|
2623eeb82e | ||
|
|
cbebadc16a | ||
|
|
614d6d81e5 | ||
|
|
cac451c83e | ||
|
|
54a86c69e1 | ||
|
|
ea8f5c0f33 | ||
|
|
340d576931 | ||
|
|
7db8820042 | ||
|
|
54761b22fd | ||
|
|
253f13640c | ||
|
|
97110c9676 | ||
|
|
9805c4d907 | ||
|
|
56d548ad10 | ||
|
|
c196f6ee08 | ||
|
|
db55841e7d | ||
|
|
fb70ef7b1c | ||
|
|
fa82223c50 | ||
|
|
6f3cd87993 | ||
|
|
3ca7ac613d | ||
|
|
fe5b2f97e3 | ||
|
|
220bf92a3c | ||
|
|
5219fd59e8 | ||
|
|
4832da5cda | ||
|
|
4ef3dcffc4 | ||
|
|
fbe4768658 | ||
|
|
f63de3cc30 | ||
|
|
7c7d9e07a2 | ||
|
|
708f1e17f4 | ||
|
|
8fc48cf24a |
@@ -0,0 +1,12 @@
|
||||
## Expected behaviour
|
||||
|
||||
## Actual behaviour
|
||||
|
||||
## Steps to reproduce the behaviour
|
||||
|
||||
## mc version
|
||||
- (paste output of `mc version`)
|
||||
|
||||
## System information
|
||||
|
||||
|
||||
+8
-1
@@ -1,4 +1,11 @@
|
||||
cover.out
|
||||
mc
|
||||
*~
|
||||
*.test
|
||||
release
|
||||
experimental
|
||||
coverage.txt
|
||||
*.tar.bz2
|
||||
parts/
|
||||
prime/
|
||||
stage/
|
||||
mc
|
||||
|
||||
+14
-21
@@ -1,25 +1,18 @@
|
||||
sudo: false
|
||||
language: go
|
||||
|
||||
script:
|
||||
- make test GOFLAGS="-race"
|
||||
matrix:
|
||||
include:
|
||||
- os: linux
|
||||
env:
|
||||
- ARCH=x86_64
|
||||
go: 1.10.1
|
||||
script:
|
||||
- make test GOFLAGS="-race"
|
||||
- make coverage
|
||||
- diff -au <(gofmt -d *.go) <(printf "")
|
||||
- diff -au <(gofmt -d cmd) <(printf "")
|
||||
- diff -au <(gofmt -d pkg) <(printf "")
|
||||
|
||||
os:
|
||||
- linux
|
||||
- osx
|
||||
|
||||
env:
|
||||
- ARCH=x86_64
|
||||
- ARCH=i686
|
||||
|
||||
go:
|
||||
- 1.5.2
|
||||
- 1.5.3
|
||||
|
||||
script:
|
||||
- diff -au <(gofmt -d *.go) <(printf "")
|
||||
- diff -au <(gofmt -d pkg) <(printf "")
|
||||
|
||||
notifications:
|
||||
slack:
|
||||
secure: McinxQ4R/Yu2r/U8lVsdAIQ195Rf+3/Ku6DViWyqLHsTt5fTnVrSfbIKs8vy0t2A0bRLO6zv2xOSMWjfiimZLPMgMbMqLtTFEzUzB8RZyx2n2xgmL8q3gjXcLA3vkBreaRYCzJzX6DjvrxRfhyOg+BQHpLpACWik3FS/7VIdDCI=
|
||||
after_success:
|
||||
- bash <(curl -s https://codecov.io/bash)
|
||||
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
## mc (Minio Client) v/s Midnight Commander (mc)
|
||||
|
||||
There has been some amount of [requests](https://github.com/minio/mc/issues?q=is%3Aissue+midnight+commander+is%3Aclosed) on renaming this project to avoid the conflict with Midnight Commander for Unix distributions. We struggled with this, it is harder to find a name sweeter and shorter than `mc` for Minio Client.
|
||||
|
||||
Besides `mc` is a single static binary and can reside inside your application and is fully self contained. Midnight Commander (mc) is a free software clone of Norton Commander (nc). Minio and Midnight shares no code or ideas. Only their abbreviation matches.
|
||||
|
||||
Package managers are free to choose a different name if they like. One such solution [pointed out](https://github.com/minio/mc/issues/873#issuecomment-267583013) by one of our community members.
|
||||
|
||||
```sh
|
||||
mv ./mc ./mcli
|
||||
```
|
||||
@@ -1,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>
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
FROM golang:1.10.1-alpine3.7
|
||||
|
||||
MAINTAINER Minio Inc <dev@minio.io>
|
||||
|
||||
ENV PATH $PATH:$GOPATH/bin
|
||||
ENV CGO_ENABLED 0
|
||||
|
||||
WORKDIR /go/src/github.com/minio/
|
||||
|
||||
RUN \
|
||||
apk add --no-cache ca-certificates && \
|
||||
apk add --no-cache --virtual .build-deps git && \
|
||||
echo 'hosts: files mdns4_minimal [NOTFOUND=return] dns mdns4' >> /etc/nsswitch.conf && \
|
||||
go get -v -d github.com/minio/mc && \
|
||||
cd /go/src/github.com/minio/mc && \
|
||||
go install -v -ldflags "$(go run buildscripts/gen-ldflags.go)" && \
|
||||
rm -rf /go/pkg /go/src /usr/local/go && apk del .build-deps
|
||||
|
||||
ENTRYPOINT ["mc"]
|
||||
@@ -0,0 +1,11 @@
|
||||
FROM alpine:3.7
|
||||
|
||||
MAINTAINER Minio Inc <dev@minio.io>
|
||||
|
||||
RUN \
|
||||
apk add --no-cache ca-certificates && \
|
||||
apk add --no-cache --virtual .build-deps curl && \
|
||||
curl https://dl.minio.io/client/mc/release/linux-amd64/mc > /usr/bin/mc && \
|
||||
chmod +x /usr/bin/mc && apk del .build-deps
|
||||
|
||||
ENTRYPOINT ["mc"]
|
||||
@@ -1,86 +0,0 @@
|
||||
## Ubuntu (Kylin) 14.04
|
||||
### Build Dependencies
|
||||
This installation guide is based on Ubuntu 14.04+ on x86-64 platform.
|
||||
|
||||
##### Install Git, GCC
|
||||
```sh
|
||||
$ sudo apt-get install git build-essential
|
||||
```
|
||||
|
||||
##### Install Go 1.5+
|
||||
|
||||
Download Go 1.5+ from [https://golang.org/dl/](https://golang.org/dl/).
|
||||
|
||||
```sh
|
||||
$ wget https://storage.googleapis.com/golang/go1.5.1.linux-amd64.tar.gz
|
||||
$ mkdir -p ${HOME}/bin/
|
||||
$ mkdir -p ${HOME}/go/
|
||||
$ tar -C ${HOME}/bin/ -xzf go1.5.1.linux-amd64.tar.gz
|
||||
```
|
||||
##### Setup GOROOT and GOPATH
|
||||
|
||||
Add the following exports to your ``~/.bashrc``. Environment variable GOROOT specifies the location of your golang binaries
|
||||
and GOPATH specifies the location of your project workspace.
|
||||
|
||||
```sh
|
||||
export GOROOT=${HOME}/bin/go
|
||||
export GOPATH=${HOME}/go
|
||||
export PATH=$PATH:${HOME}/bin/go/bin:${GOPATH}/bin
|
||||
```
|
||||
|
||||
##### Source the new environment
|
||||
|
||||
```sh
|
||||
$ source ~/.bashrc
|
||||
```
|
||||
|
||||
##### Testing it all
|
||||
```sh
|
||||
$ go env
|
||||
```
|
||||
|
||||
## OS X (Yosemite) 10.10
|
||||
### Build Dependencies
|
||||
This installation document assumes OS X Yosemite 10.10+ on x86-64 platform.
|
||||
|
||||
##### Install brew
|
||||
```sh
|
||||
$ ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
|
||||
```
|
||||
|
||||
##### Install Git, Python
|
||||
```sh
|
||||
$ brew install git python
|
||||
```
|
||||
|
||||
##### Install Go 1.5+
|
||||
|
||||
Install golang binaries using `brew`
|
||||
|
||||
```sh
|
||||
$ brew install go
|
||||
$ mkdir -p $HOME/go
|
||||
```
|
||||
|
||||
##### Setup GOROOT and GOPATH
|
||||
|
||||
Add the following exports to your ``~/.bash_profile``. Environment variable GOROOT specifies the location of your golang binaries
|
||||
and GOPATH specifies the location of your project workspace.
|
||||
|
||||
```sh
|
||||
export GOPATH=${HOME}/go
|
||||
export GOVERSION=$(brew list go | head -n 1 | cut -d '/' -f 6)
|
||||
export GOROOT=$(brew --prefix)/Cellar/go/${GOVERSION}/libexec
|
||||
export PATH=$PATH:${GOPATH}/bin
|
||||
```
|
||||
|
||||
##### Source the new environment
|
||||
|
||||
```sh
|
||||
$ source ~/.bash_profile
|
||||
```
|
||||
|
||||
##### Testing it all
|
||||
```sh
|
||||
$ go env
|
||||
```
|
||||
@@ -1,85 +1,100 @@
|
||||
PWD := $(shell pwd)
|
||||
GOPATH := $(shell go env GOPATH)
|
||||
LDFLAGS := $(shell go run buildscripts/gen-ldflags.go)
|
||||
|
||||
BUILD_LDFLAGS := '$(LDFLAGS)'
|
||||
|
||||
all: install
|
||||
all: build
|
||||
|
||||
checkdeps:
|
||||
@echo "Checking deps:"
|
||||
checks:
|
||||
@echo "Checking dependencies"
|
||||
@(env bash $(PWD)/buildscripts/checkdeps.sh)
|
||||
@echo "Checking for project in GOPATH"
|
||||
@(env bash $(PWD)/buildscripts/checkgopath.sh)
|
||||
|
||||
checkgopath:
|
||||
@echo "Checking if project is at ${GOPATH}"
|
||||
@for mcpath in $(echo ${GOPATH} | sed 's/:/\n/g'); do if [ ! -d ${mcpath}/src/github.com/minio/mc ]; then echo "Project not found in ${mcpath}, please follow instructions provided at https://github.com/minio/minio/blob/master/CONTRIBUTING.md#setup-your-minio-github-repository" && exit 1; fi done
|
||||
@echo "BUILD_LDFLAGS: ${BUILD_LDFLAGS}"
|
||||
getdeps:
|
||||
@echo "Installing golint" && go get -u github.com/golang/lint/golint
|
||||
@echo "Installing gocyclo" && go get -u github.com/fzipp/gocyclo
|
||||
@echo "Installing deadcode" && go get -u github.com/remyoudompheng/go-misc/deadcode
|
||||
@echo "Installing misspell" && go get -u github.com/client9/misspell/cmd/misspell
|
||||
@echo "Installing ineffassign" && go get -u github.com/gordonklaus/ineffassign
|
||||
|
||||
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
|
||||
verifiers: getdeps vet fmt lint cyclo deadcode spelling
|
||||
|
||||
vet:
|
||||
@echo "Running $@:"
|
||||
@GO15VENDOREXPERIMENT=1 go tool vet -all *.go
|
||||
@GO15VENDOREXPERIMENT=1 go tool vet -all ./pkg
|
||||
@GO15VENDOREXPERIMENT=1 go tool vet -shadow=true *.go
|
||||
@GO15VENDOREXPERIMENT=1 go tool vet -shadow=true ./pkg
|
||||
@echo "Running $@"
|
||||
@go tool vet -atomic -bool -copylocks -nilfunc -printf -shadow -rangeloops -unreachable -unsafeptr -unusedresult cmd
|
||||
@go tool vet -atomic -bool -copylocks -nilfunc -printf -shadow -rangeloops -unreachable -unsafeptr -unusedresult pkg
|
||||
|
||||
fmt:
|
||||
@echo "Running $@:"
|
||||
@GO15VENDOREXPERIMENT=1 gofmt -s -l *.go
|
||||
@GO15VENDOREXPERIMENT=1 gofmt -s -l pkg
|
||||
@echo "Running $@"
|
||||
@gofmt -d cmd
|
||||
@gofmt -d pkg
|
||||
|
||||
lint:
|
||||
@echo "Running $@:"
|
||||
@GO15VENDOREXPERIMENT=1 golint .
|
||||
@GO15VENDOREXPERIMENT=1 golint github.com/minio/mc/pkg...
|
||||
@echo "Running $@"
|
||||
@${GOPATH}/bin/golint -set_exit_status github.com/minio/mc/cmd...
|
||||
@${GOPATH}/bin/golint -set_exit_status github.com/minio/mc/pkg...
|
||||
|
||||
ineffassign:
|
||||
@echo "Running $@"
|
||||
@${GOPATH}/bin/ineffassign .
|
||||
|
||||
cyclo:
|
||||
@echo "Running $@:"
|
||||
@GO15VENDOREXPERIMENT=1 gocyclo -over 40 *.go
|
||||
@GO15VENDOREXPERIMENT=1 gocyclo -over 40 pkg
|
||||
@echo "Running $@"
|
||||
@${GOPATH}/bin/gocyclo -over 100 cmd
|
||||
@${GOPATH}/bin/gocyclo -over 100 pkg
|
||||
|
||||
deadcode:
|
||||
@echo "Running $@:"
|
||||
@GO15VENDOREXPERIMENT=1 deadcode
|
||||
@echo "Running $@"
|
||||
@${GOPATH}/bin/deadcode -test $(shell go list ./...)
|
||||
|
||||
build: verifiers
|
||||
@echo "Installing mc:"
|
||||
spelling:
|
||||
@${GOPATH}/bin/misspell -error `find cmd/`
|
||||
@${GOPATH}/bin/misspell -error `find pkg/`
|
||||
@${GOPATH}/bin/misspell -error `find docs/`
|
||||
|
||||
test: verifiers
|
||||
@echo "Running all testing:"
|
||||
@GO15VENDOREXPERIMENT=1 go test $(GOFLAGS) ./
|
||||
@GO15VENDOREXPERIMENT=1 go test $(GOFLAGS) github.com/minio/mc/pkg...
|
||||
# Builds minio, runs the verifiers then runs the tests.
|
||||
check: test
|
||||
test: verifiers build
|
||||
@echo "Running unit tests"
|
||||
@go test $(GOFLAGS) -tags kqueue ./...
|
||||
@echo "Running functional tests"
|
||||
@(env bash $(PWD)/functional-tests.sh)
|
||||
|
||||
gomake-all: build
|
||||
@GO15VENDOREXPERIMENT=1 go build --ldflags $(BUILD_LDFLAGS) -o $(GOPATH)/bin/mc
|
||||
@mkdir -p $(HOME)/.mc
|
||||
coverage: build
|
||||
@echo "Running all coverage for minio"
|
||||
@(env bash $(PWD)/buildscripts/go-coverage.sh)
|
||||
|
||||
coverage:
|
||||
@GO15VENDOREXPERIMENT=1 go test -race -coverprofile=cover.out ./
|
||||
@go tool cover -html=cover.out && echo "Visit your browser"
|
||||
# Builds minio locally.
|
||||
build: checks
|
||||
@echo "Building minio binary to './mc'"
|
||||
@CGO_ENABLED=0 go build -tags kqueue --ldflags $(BUILD_LDFLAGS) -o $(PWD)/mc
|
||||
|
||||
pkg-add:
|
||||
@GO15VENDOREXPERIMENT=1 govendor add $(PKG)
|
||||
@echo "Adding new package $(PKG)"
|
||||
@${GOPATH}/bin/govendor add $(PKG)
|
||||
|
||||
pkg-update:
|
||||
@GO15VENDOREXPERIMENT=1 govendor update $(PKG)
|
||||
@echo "Updating new package $(PKG)"
|
||||
@${GOPATH}/bin/govendor update $(PKG)
|
||||
|
||||
pkg-remove:
|
||||
@GO15VENDOREXPERIMENT=1 govendor remove $(PKG)
|
||||
@echo "Remove new package $(PKG)"
|
||||
@${GOPATH}/bin/govendor remove $(PKG)
|
||||
|
||||
install: gomake-all
|
||||
pkg-list:
|
||||
@$(GOPATH)/bin/govendor list
|
||||
|
||||
all-tests: test
|
||||
# TODO disable them for now.
|
||||
#@./tests/test-minio.sh
|
||||
|
||||
release:
|
||||
@./release.sh
|
||||
# Builds minio and installs it to $GOPATH/bin.
|
||||
install: build
|
||||
@echo "Installing mc binary to '$(GOPATH)/bin/mc'"
|
||||
@mkdir -p $(GOPATH)/bin && cp $(PWD)/mc $(GOPATH)/bin/mc
|
||||
@echo "Installation successful. To learn more, try \"mc --help\"."
|
||||
|
||||
clean:
|
||||
@rm -fv cover.out
|
||||
@rm -fv mc
|
||||
@echo "Cleaning up all the generated files"
|
||||
@find . -name '*.test' | xargs rm -fv
|
||||
@rm -rvf mc
|
||||
@rm -rvf build
|
||||
@rm -rvf release
|
||||
|
||||
@@ -1,106 +1,201 @@
|
||||
# Minio Client (mc) [](https://gitter.im/minio/minio?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
||||
# Minio Client Quickstart Guide
|
||||
[](https://slack.minio.io) [](https://goreportcard.com/report/minio/mc) [](https://hub.docker.com/r/minio/mc/)
|
||||
|
||||
``mc`` provides minimal tools to work with Amazon S3 compatible cloud storage and filesystems. It has features like resumable uploads/downloads, progress bar, parallel copy. ``mc`` is written in golang and released under [Apache license v2](./LICENSE).
|
||||
Minio Client (mc) provides a modern alternative to UNIX commands like ls, cat, cp, mirror, diff, find etc. It supports filesystems and Amazon S3 compatible cloud storage service (AWS Signature v2 and v4).
|
||||
|
||||
## Commands
|
||||
|
||||
``mc`` implements the following commands
|
||||
```
|
||||
ls List files and folders.
|
||||
mb Make a bucket or folder.
|
||||
cat Display contents of a file.
|
||||
pipe Write contents of stdin to one or more targets. When no target is specified, it writes to stdout.
|
||||
share Generate URL for sharing.
|
||||
cp Copy one or more objects to a target.
|
||||
mirror Mirror folders recursively from a single source to many destinations.
|
||||
diff Compute differences between two folders.
|
||||
rm Remove file or bucket [WARNING: Use with care].
|
||||
access Manage bucket access permissions.
|
||||
session Manage saved sessions of cp and mirror operations.
|
||||
config Manage configuration file.
|
||||
update Check for a new software update.
|
||||
version Print version.
|
||||
ls List files and folders.
|
||||
mb Make a bucket or a folder.
|
||||
cat Display file and object contents.
|
||||
pipe Redirect STDIN to an object or file or STDOUT.
|
||||
share Generate URL for sharing.
|
||||
cp Copy files and objects.
|
||||
mirror Mirror buckets and folders.
|
||||
find Finds files which match the given set of parameters.
|
||||
stat Stat contents of objects and folders.
|
||||
diff List objects with size difference or missing between two folders or buckets.
|
||||
rm Remove files and objects.
|
||||
events Manage object notifications.
|
||||
watch Watch for file and object events.
|
||||
policy Manage anonymous access to objects.
|
||||
session Manage saved sessions for cp command.
|
||||
config Manage mc configuration file.
|
||||
update Check for a new software update.
|
||||
version Print version info.
|
||||
```
|
||||
|
||||
## Install [](https://travis-ci.org/minio/mc) [](https://ci.appveyor.com/project/harshavardhana/mc)
|
||||
## Docker Container
|
||||
### Stable
|
||||
```
|
||||
docker pull minio/mc
|
||||
docker run minio/mc ls play
|
||||
```
|
||||
|
||||
#### GNU/Linux
|
||||
### Edge
|
||||
```
|
||||
docker pull minio/mc:edge
|
||||
docker run minio/mc:edge ls play
|
||||
```
|
||||
|
||||
Download ``mc`` for:
|
||||
|
||||
- ``64-bit Intel`` from https://dl.minio.io/client/mc/release/linux-amd64/mc
|
||||
- ``32-bit Intel`` from https://dl.minio.io/client/mc/release/linux-386/mc
|
||||
- ``32-bit ARM`` from https://dl.minio.io/client/mc/release/linux-arm/mc
|
||||
|
||||
~~~
|
||||
$ chmod +x mc
|
||||
$ ./mc --help
|
||||
~~~
|
||||
|
||||
#### OS X
|
||||
|
||||
Download ``mc`` from https://dl.minio.io/client/mc/release/darwin-amd64/mc
|
||||
|
||||
~~~
|
||||
$ chmod 755 mc
|
||||
$ ./mc --help
|
||||
~~~
|
||||
|
||||
#### Microsoft Windows
|
||||
|
||||
Download ``mc`` for:
|
||||
|
||||
- ``64-bit`` from https://dl.minio.io/client/mc/release/windows-amd64/mc.exe
|
||||
- ``32-bit`` from https://dl.minio.io/client/mc/release/windows-386/mc.exe
|
||||
|
||||
~~~
|
||||
C:\Users\Username\Downloads> mc.exe --help
|
||||
~~~
|
||||
|
||||
#### Source
|
||||
<blockquote>
|
||||
NOTE: Source installation is intended for only developers and advanced users. ‘mc update’ continuous delivery mechanism is not supported for ‘go get’ based binary builds. Please download official releases from https://minio.io/#mc.
|
||||
</blockquote>
|
||||
|
||||
If you do not have a working Golang environment, please follow [Install Golang](./INSTALLGO.md).
|
||||
**Note:** Above examples run `mc` against Minio [_play_ environment](#test-your-setup) by default. To run `mc` against other S3 compatible servers, start the container this way:
|
||||
|
||||
```sh
|
||||
$ GO15VENDOREXPERIMENT=1 go get -u github.com/minio/mc
|
||||
docker run -it --entrypoint=/bin/sh minio/mc
|
||||
```
|
||||
|
||||
## Public Minio Server
|
||||
then use the [`mc config` command](#add-a-cloud-storage-service).
|
||||
|
||||
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.
|
||||
## macOS
|
||||
### Homebrew
|
||||
Install mc packages using [Homebrew](http://brew.sh/)
|
||||
|
||||
## Configuring mc for Amazon S3
|
||||
|
||||
Get your AccessKeyID and SecretAccessKey by following [AWS Credentials Guide](http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSGettingStartedGuide/AWSCredentials.html).
|
||||
|
||||
Once you have them update your ``~/.mc/config.json`` configuration file.
|
||||
```
|
||||
$ mc config host add <ALIAS> <YOUR-S3-ENDPOINT> <YOUR-ACCESS-KEY> <YOUR-SECRET-KEY> S3v4
|
||||
```sh
|
||||
brew install minio/stable/mc
|
||||
mc --help
|
||||
```
|
||||
|
||||
Example
|
||||
```
|
||||
$ mc config host add mys3 https://s3.amazonaws.com BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12
|
||||
## GNU/Linux
|
||||
### Binary Download
|
||||
| Platform | Architecture | URL |
|
||||
| ---------- | -------- |------|
|
||||
|GNU/Linux|64-bit Intel|https://dl.minio.io/client/mc/release/linux-amd64/mc |
|
||||
|
||||
```sh
|
||||
wget https://dl.minio.io/client/mc/release/linux-amd64/mc
|
||||
chmod +x mc
|
||||
./mc --help
|
||||
```
|
||||
|
||||
NOTE: ``S3v4`` is default if not specified.
|
||||
## Microsoft Windows
|
||||
### Binary Download
|
||||
| Platform | Architecture | URL |
|
||||
| ---------- | -------- |------|
|
||||
|Microsoft Windows|64-bit Intel|https://dl.minio.io/client/mc/release/windows-amd64/mc.exe |
|
||||
|
||||
## Configure mc for Google Cloud Storage
|
||||
|
||||
Get your AccessKeyID and SecretAccessKey by following [Google Credentials Guide](https://cloud.google.com/storage/docs/migrating?hl=en#keys).
|
||||
|
||||
Once you have them update your ``~/.mc/config.json`` configuration file.
|
||||
```
|
||||
$ mc config host add <ALIAS> https://storage.googleapis.com <YOUR-ACCESS-KEY> <YOUR-SECRET-KEY> S3v2
|
||||
```sh
|
||||
mc.exe --help
|
||||
```
|
||||
|
||||
NOTE: Google Cloud Storage only supports Legacy Signature Version ``2``, so you have to pick - ``S3v2``
|
||||
## Install from Source
|
||||
Source installation is intended only for developers and advanced users. `mc update` command does not support update notifications for source based installations. Please download official releases from https://minio.io/downloads/#minio-client.
|
||||
|
||||
## Contribute to Minio Client
|
||||
Please follow Minio [Contributor's Guide](./CONTRIBUTING.md)
|
||||
If you do not have a working Golang environment, please follow [How to install Golang](https://docs.minio.io/docs/how-to-install-golang).
|
||||
|
||||
### 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.
|
||||
```sh
|
||||
go get -d github.com/minio/mc
|
||||
cd ${GOPATH}/src/github.com/minio/mc
|
||||
make
|
||||
```
|
||||
|
||||
## Add a Cloud Storage Service
|
||||
If you are planning to use `mc` only on POSIX compatible filesystems, you may skip this step and proceed to [everyday use](#everyday-use).
|
||||
|
||||
To add one or more Amazon S3 compatible hosts, please follow the instructions below. `mc` stores all its configuration information in ``~/.mc/config.json`` file.
|
||||
|
||||
```sh
|
||||
mc config host add <ALIAS> <YOUR-S3-ENDPOINT> <YOUR-ACCESS-KEY> <YOUR-SECRET-KEY> --api <API-SIGNATURE> --lookup <BUCKET-LOOKUP-TYPE>
|
||||
```
|
||||
|
||||
Alias is simply a short name to your cloud storage service. S3 end-point, access and secret keys are supplied by your cloud storage provider. API signature is an optional argument. By default, it is set to "S3v4".
|
||||
|
||||
Lookup is an optional argument. It is used to indicate whether dns or path style url requests are supported by the server. It accepts "dns", "path" or "auto" as valid values. By default, it is set to "auto" and SDK automatically determines the type of url lookup to use.
|
||||
|
||||
### Example - Minio Cloud Storage
|
||||
Minio server displays URL, access and secret keys.
|
||||
|
||||
```sh
|
||||
mc config host add minio http://192.168.1.51 BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12
|
||||
```
|
||||
|
||||
### Example - Amazon S3 Cloud Storage
|
||||
Get your AccessKeyID and SecretAccessKey by following [AWS Credentials Guide](http://docs.aws.amazon.com/general/latest/gr/aws-security-credentials.html).
|
||||
|
||||
```sh
|
||||
mc config host add s3 https://s3.amazonaws.com BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12
|
||||
```
|
||||
|
||||
### Example - Google Cloud Storage
|
||||
Get your AccessKeyID and SecretAccessKey by following [Google Credentials Guide](https://cloud.google.com/storage/docs/migrating?hl=en#keys)
|
||||
|
||||
```sh
|
||||
mc config host add gcs https://storage.googleapis.com BKIKJAA5BMMU2RHO6IBB V8f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12
|
||||
```
|
||||
|
||||
NOTE: Google Cloud Storage only supports Legacy Signature Version 2, so you have to pick - S3v2
|
||||
|
||||
## Test Your Setup
|
||||
`mc` is pre-configured with https://play.minio.io:9000, aliased as "play". It is a hosted Minio server for testing and development purpose. To test Amazon S3, simply replace "play" with "s3" or the alias you used at the time of setup.
|
||||
|
||||
*Example:*
|
||||
|
||||
List all buckets from https://play.minio.io:9000
|
||||
|
||||
```sh
|
||||
mc ls play
|
||||
[2016-03-22 19:47:48 PDT] 0B my-bucketname/
|
||||
[2016-03-22 22:01:07 PDT] 0B mytestbucket/
|
||||
[2016-03-22 20:04:39 PDT] 0B mybucketname/
|
||||
[2016-01-28 17:23:11 PST] 0B newbucket/
|
||||
[2016-03-20 09:08:36 PDT] 0B s3git-test/
|
||||
```
|
||||
|
||||
Make a bucket
|
||||
`mb` command creates a new bucket.
|
||||
|
||||
*Example:*
|
||||
```sh
|
||||
mc mb play/mybucket
|
||||
Bucket created successfully `play/mybucket`.
|
||||
```
|
||||
|
||||
Copy Objects
|
||||
`cp` command copies data from one or more sources to a target.
|
||||
|
||||
*Example:*
|
||||
```sh
|
||||
mc cp myobject.txt play/mybucket
|
||||
myobject.txt: 14 B / 14 B ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ 100.00 % 41 B/s 0
|
||||
```
|
||||
|
||||
|
||||
|
||||
<a name="everyday-use"></a>
|
||||
## Everyday Use
|
||||
|
||||
### Shell aliases
|
||||
You may add shell aliases to override your common Unix tools.
|
||||
|
||||
```sh
|
||||
alias ls='mc ls'
|
||||
alias cp='mc cp'
|
||||
alias cat='mc cat'
|
||||
alias mkdir='mc mb'
|
||||
alias pipe='mc pipe'
|
||||
alias find='mc find'
|
||||
```
|
||||
|
||||
### Shell autocompletion
|
||||
You may also download [`autocomplete/bash_autocomplete`](https://raw.githubusercontent.com/minio/mc/master/autocomplete/bash_autocomplete) into `/etc/bash_completion.d/` and rename it to `mc`. Don't forget to source the file to make it active on your current shell.
|
||||
|
||||
```sh
|
||||
sudo wget https://raw.githubusercontent.com/minio/mc/master/autocomplete/bash_autocomplete -O /etc/bash_completion.d/mc
|
||||
source /etc/bash_completion.d/mc
|
||||
```
|
||||
|
||||
```sh
|
||||
mc <TAB>
|
||||
admin config diff ls mirror policy session update watch
|
||||
cat cp events mb pipe rm share version
|
||||
```
|
||||
|
||||
## Explore Further
|
||||
- [Minio Client Complete Guide](https://docs.minio.io/docs/minio-client-complete-guide)
|
||||
- [Minio Quickstart Guide](https://docs.minio.io/docs/minio-quickstart-guide)
|
||||
- [The Minio documentation website](https://docs.minio.io)
|
||||
|
||||
## Contribute to Minio Project
|
||||
Please follow Minio [Contributor's Guide](https://github.com/minio/mc/blob/master/CONTRIBUTING.md)
|
||||
|
||||
|
||||
## License
|
||||
[](https://app.fossa.io/projects/git%2Bgithub.com%2Fminio%2Fmc?ref=badge_large)
|
||||
|
||||
+173
@@ -0,0 +1,173 @@
|
||||
# Minio客户端快速入门指南
|
||||
[](https://slack.minio.io) [](https://goreportcard.com/report/minio/mc) [](https://hub.docker.com/r/minio/mc/)
|
||||
|
||||
Minio Client (mc)为ls,cat,cp,mirror,diff,find等UNIX命令提供了一种替代方案。它支持文件系统和兼容Amazon S3的云存储服务(AWS Signature v2和v4)。
|
||||
|
||||
|
||||
```
|
||||
ls 列出文件和文件夹。
|
||||
mb 创建一个存储桶或一个文件夹。
|
||||
cat 显示文件和对象内容。
|
||||
pipe 将一个STDIN重定向到一个对象或者文件或者STDOUT。
|
||||
share 生成用于共享的URL。
|
||||
cp 拷贝文件和对象。
|
||||
mirror 给存储桶和文件夹做镜像。
|
||||
find 基于参数查找文件。
|
||||
diff 对两个文件夹或者存储桶比较差异。
|
||||
rm 删除文件和对象。
|
||||
events 管理对象通知。
|
||||
watch 监听文件和对象的事件。
|
||||
policy 管理访问策略。
|
||||
session 为cp命令管理保存的会话。
|
||||
config 管理mc配置文件。
|
||||
update 检查软件更新。
|
||||
version 输出版本信息。
|
||||
```
|
||||
|
||||
## Docker容器
|
||||
### 稳定版
|
||||
```
|
||||
docker pull minio/mc
|
||||
docker run minio/mc ls play
|
||||
```
|
||||
|
||||
### 尝鲜版
|
||||
```
|
||||
docker pull minio/mc:edge
|
||||
docker run minio/mc:edge ls play
|
||||
```
|
||||
|
||||
**注意:** 上述示例默认使用Minio[演示环境](#test-your-setup)做演示,如果想用`mc`操作其它S3兼容的服务,采用下面的方式来启动容器:
|
||||
|
||||
```sh
|
||||
docker run -it --entrypoint=/bin/sh minio/mc
|
||||
```
|
||||
|
||||
然后使用[`mc config`命令](#add-a-cloud-storage-service)。
|
||||
|
||||
## macOS
|
||||
### Homebrew
|
||||
使用[Homebrew](http://brew.sh/)安装mc。
|
||||
|
||||
```sh
|
||||
brew install minio/stable/mc
|
||||
mc --help
|
||||
```
|
||||
|
||||
## GNU/Linux
|
||||
### 下载二进制文件
|
||||
| 平台 | CPU架构 | URL |
|
||||
| ---------- | -------- |------|
|
||||
|GNU/Linux|64-bit Intel|https://dl.minio.io/client/mc/release/linux-amd64/mc |
|
||||
|
||||
```sh
|
||||
chmod +x mc
|
||||
./mc --help
|
||||
```
|
||||
|
||||
## Microsoft Windows
|
||||
### 下载二进制文件
|
||||
| 平台 | CPU架构 | URL |
|
||||
| ---------- | -------- |------|
|
||||
|Microsoft Windows|64-bit Intel|https://dl.minio.io/client/mc/release/windows-amd64/mc.exe |
|
||||
|
||||
```sh
|
||||
mc.exe --help
|
||||
```
|
||||
|
||||
## 通过源码安装
|
||||
通过源码安装仅适用于开发人员和高级用户。`mc update`命令不支持基于源码安装的更新通知。请从https://minio.io/downloads/#minio-client下载官方版本。
|
||||
|
||||
如果您没有Golang环境,请参照[如何安装Golang](https://docs.minio.io/docs/how-to-install-golang)。
|
||||
|
||||
```sh
|
||||
go get -d github.com/minio/mc
|
||||
cd ${GOPATH}/src/github.com/minio/mc
|
||||
make
|
||||
```
|
||||
|
||||
## 添加一个云存储服务
|
||||
如果你打算仅在POSIX兼容文件系统中使用`mc`,那你可以直接略过本节,跳到[日常使用](#everyday-use)。
|
||||
|
||||
添加一个或多个S3兼容的服务,请参考下面说明。`mc`将所有的配置信息都存储在``~/.mc/config.json``文件中。
|
||||
|
||||
```sh
|
||||
mc config host add <ALIAS> <YOUR-S3-ENDPOINT> <YOUR-ACCESS-KEY> <YOUR-SECRET-KEY> <API-SIGNATURE>
|
||||
```
|
||||
|
||||
别名就是给你的云存储服务起了一个短点的外号。S3 endpoint,access key和secret key是你的云存储服务提供的。API签名是可选参数,默认情况下,它被设置为"S3v4"。
|
||||
|
||||
### 示例-Minio云存储
|
||||
从Minio服务获得URL、access key和secret key。
|
||||
|
||||
```sh
|
||||
mc config host add minio http://192.168.1.51 BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 S3v4
|
||||
```
|
||||
|
||||
### 示例-Amazon S3云存储
|
||||
参考[AWS Credentials指南](http://docs.aws.amazon.com/general/latest/gr/aws-security-credentials.html)获取你的AccessKeyID和SecretAccessKey。
|
||||
|
||||
```sh
|
||||
mc config host add s3 https://s3.amazonaws.com BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 S3v4
|
||||
```
|
||||
|
||||
### 示例-Google云存储
|
||||
参考[Google Credentials Guide](https://cloud.google.com/storage/docs/migrating?hl=en#keys)获取你的AccessKeyID和SecretAccessKey。
|
||||
|
||||
```sh
|
||||
mc config host add gcs https://storage.googleapis.com BKIKJAA5BMMU2RHO6IBB V8f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 S3v2
|
||||
```
|
||||
|
||||
注意:Google云存储只支持旧版签名版本V2,所以你需要选择S3v2。
|
||||
|
||||
## 验证
|
||||
`mc`预先配置了云存储服务URL:https://play.minio.io:9000,别名“play”。它是一个用于研发和测试的Minio服务。如果想测试Amazon S3,你可以将“play”替换为“s3”。
|
||||
|
||||
*示例:*
|
||||
|
||||
列出https://play.minio.io:9000上的所有存储桶。
|
||||
|
||||
```sh
|
||||
mc ls play
|
||||
[2016-03-22 19:47:48 PDT] 0B my-bucketname/
|
||||
[2016-03-22 22:01:07 PDT] 0B mytestbucket/
|
||||
[2016-03-22 20:04:39 PDT] 0B mybucketname/
|
||||
[2016-01-28 17:23:11 PST] 0B newbucket/
|
||||
[2016-03-20 09:08:36 PDT] 0B s3git-test/
|
||||
```
|
||||
<a name="everyday-use"></a>
|
||||
## 日常使用
|
||||
|
||||
### Shell别名
|
||||
你可以添加shell别名来覆盖默认的Unix工具命令。
|
||||
|
||||
```sh
|
||||
alias ls='mc ls'
|
||||
alias cp='mc cp'
|
||||
alias cat='mc cat'
|
||||
alias mkdir='mc mb'
|
||||
alias pipe='mc pipe'
|
||||
alias find='mc find'
|
||||
```
|
||||
|
||||
### Shell自动补全
|
||||
你也可以下载[`autocomplete/bash_autocomplete`](https://raw.githubusercontent.com/minio/mc/master/autocomplete/bash_autocomplete)到`/etc/bash_completion.d/`,然后将其重命名为`mc`。别忘了在这个文件运行source命令让其在你的当前shell上可用。
|
||||
|
||||
```sh
|
||||
sudo wget https://raw.githubusercontent.com/minio/mc/master/autocomplete/bash_autocomplete -O /etc/bash_completion.d/mc
|
||||
source /etc/bash_completion.d/mc
|
||||
```
|
||||
|
||||
```sh
|
||||
mc <TAB>
|
||||
admin config diff ls mirror policy session update watch
|
||||
cat cp events mb pipe rm share version
|
||||
```
|
||||
|
||||
## 了解更多
|
||||
- [Minio Client完全指南](https://docs.minio.io/docs/minio-client-complete-guide)
|
||||
- [Minio快速入门](https://docs.minio.io/docs/minio-quickstart-guide)
|
||||
- [Minio官方文档](https://docs.minio.io)
|
||||
|
||||
## 贡献
|
||||
请遵守Minio[贡献者指南](https://github.com/minio/mc/blob/master/docs/zh_CN/CONTRIBUTING.md)
|
||||
-205
@@ -1,205 +0,0 @@
|
||||
/*
|
||||
* Minio Client, (C) 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
)
|
||||
|
||||
var (
|
||||
accessFlags = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "help, h",
|
||||
Usage: "Help of access.",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
// Set access permissions.
|
||||
var accessCmd = cli.Command{
|
||||
Name: "access",
|
||||
Usage: "Manage bucket access permissions.",
|
||||
Action: mainAccess,
|
||||
Flags: append(accessFlags, globalFlags...),
|
||||
CustomHelpTemplate: `Name:
|
||||
mc {{.Name}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
mc {{.Name}} [FLAGS] set PERMISSION TARGET [TARGET...]
|
||||
mc {{.Name}} [FLAGS] get TARGET [TARGET...]
|
||||
|
||||
PERMISSION:
|
||||
Allowed permissions are: [private, readonly, public, authorized].
|
||||
|
||||
FLAGS:
|
||||
{{range .Flags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Set bucket to "private" on Amazon S3 cloud storage.
|
||||
$ mc {{.Name}} set private s3/burningman2011
|
||||
|
||||
2. Set bucket to "public" on Amazon S3 cloud storage.
|
||||
$ mc {{.Name}} set public s3/shared
|
||||
|
||||
3. Set bucket to "authenticated" on Amazon S3 cloud storage to provide read access to IAM Authenticated Users group.
|
||||
$ mc {{.Name}} set authorized s3/shared-authenticated
|
||||
|
||||
4. Get bucket permissions.
|
||||
$ mc {{.Name}} get s3/shared
|
||||
|
||||
5. Get bucket permissions.
|
||||
$ mc {{.Name}} get gcs/miniocloud
|
||||
`,
|
||||
}
|
||||
|
||||
// accessMessage is container for access command on bucket success and failure messages.
|
||||
type accessMessage struct {
|
||||
Operation string `json:"operation"`
|
||||
Status string `json:"status"`
|
||||
Bucket string `json:"bucket"`
|
||||
Perms accessPerms `json:"permission"`
|
||||
}
|
||||
|
||||
// String colorized access message.
|
||||
func (s accessMessage) String() string {
|
||||
if s.Operation == "set" {
|
||||
return console.Colorize("Access",
|
||||
"Set access permission ‘"+string(s.Perms)+"’ updated successfully for ‘"+s.Bucket+"’")
|
||||
}
|
||||
if s.Operation == "get" {
|
||||
return console.Colorize("Access",
|
||||
"Access permission for ‘"+s.Bucket+"’"+" is ‘"+string(s.Perms)+"’")
|
||||
}
|
||||
// nothing to print
|
||||
return ""
|
||||
}
|
||||
|
||||
// JSON jsonified access message.
|
||||
func (s accessMessage) JSON() string {
|
||||
accessJSONBytes, e := json.Marshal(s)
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(accessJSONBytes)
|
||||
}
|
||||
|
||||
// checkAccessSyntax check for incoming syntax.
|
||||
func checkAccessSyntax(ctx *cli.Context) {
|
||||
if !ctx.Args().Present() {
|
||||
cli.ShowCommandHelpAndExit(ctx, "access", 1) // last argument is exit code.
|
||||
}
|
||||
if len(ctx.Args()) < 2 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "access", 1) // last argument is exit code.
|
||||
}
|
||||
switch ctx.Args().First() {
|
||||
case "set":
|
||||
if len(ctx.Args().Tail()) < 2 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "access", 1) // last argument is exit code.
|
||||
}
|
||||
perms := accessPerms(ctx.Args().Tail().Get(0))
|
||||
if !perms.isValidAccessPERM() {
|
||||
fatalIf(errDummy().Trace(),
|
||||
"Unrecognized permission ‘"+perms.String()+"’. Allowed values are [private, public, readonly, authorized].")
|
||||
}
|
||||
for _, arg := range ctx.Args().Tail().Tail() {
|
||||
if strings.TrimSpace(arg) == "" {
|
||||
fatalIf(errInvalidArgument().Trace(), "Unable to validate empty argument.")
|
||||
}
|
||||
}
|
||||
case "get":
|
||||
if len(ctx.Args().Tail()) < 1 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "access", 1) // last argument is exit code.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// doSetAccess do set access.
|
||||
func doSetAccess(targetURL string, targetPERMS accessPerms) *probe.Error {
|
||||
clnt, err := newClient(targetURL)
|
||||
if err != nil {
|
||||
return err.Trace(targetURL)
|
||||
}
|
||||
if err = clnt.SetBucketAccess(targetPERMS.String()); err != nil {
|
||||
return err.Trace(targetURL, targetPERMS.String())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// doGetAccess do get access.
|
||||
func doGetAccess(targetURL string) (perms accessPerms, err *probe.Error) {
|
||||
clnt, err := newClient(targetURL)
|
||||
if err != nil {
|
||||
return "", err.Trace(targetURL)
|
||||
}
|
||||
acl, err := clnt.GetBucketAccess()
|
||||
if err != nil {
|
||||
return "", err.Trace(targetURL)
|
||||
}
|
||||
return aclToPerms(acl), nil
|
||||
}
|
||||
|
||||
func mainAccess(ctx *cli.Context) {
|
||||
// Set global flags from context.
|
||||
setGlobalsFromContext(ctx)
|
||||
|
||||
// check 'access' cli arguments.
|
||||
checkAccessSyntax(ctx)
|
||||
|
||||
// Additional command speific theme customization.
|
||||
console.SetColor("Access", color.New(color.FgGreen, color.Bold))
|
||||
|
||||
switch ctx.Args().First() {
|
||||
case "set":
|
||||
perms := accessPerms(ctx.Args().Tail().First())
|
||||
URLs := ctx.Args().Tail().Tail()
|
||||
for _, targetURL := range URLs {
|
||||
err := doSetAccess(targetURL, perms)
|
||||
// Upon error, print and continue.
|
||||
if err != nil {
|
||||
errorIf(err.Trace(targetURL, string(perms)),
|
||||
"Unable to set access permission ‘"+string(perms)+"’ for ‘"+targetURL+"’.")
|
||||
continue
|
||||
}
|
||||
printMsg(accessMessage{
|
||||
Status: "success",
|
||||
Operation: "set",
|
||||
Bucket: targetURL,
|
||||
Perms: perms,
|
||||
})
|
||||
}
|
||||
case "get":
|
||||
URLs := ctx.Args().Tail()
|
||||
for _, targetURL := range URLs {
|
||||
perms, err := doGetAccess(targetURL)
|
||||
if err != nil {
|
||||
errorIf(err.Trace(targetURL), "Unable to get access permission for ‘"+targetURL+"’.")
|
||||
continue
|
||||
}
|
||||
printMsg(accessMessage{
|
||||
Status: "success",
|
||||
Operation: "get",
|
||||
Bucket: targetURL,
|
||||
Perms: perms,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,96 +0,0 @@
|
||||
/*
|
||||
* Minio Client (C) 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
// isValidAccessPERM - is provided access perm string supported.
|
||||
func (b accessPerms) isValidAccessPERM() bool {
|
||||
switch true {
|
||||
case b.isPrivate():
|
||||
fallthrough
|
||||
case b.isReadOnly():
|
||||
fallthrough
|
||||
case b.isPublic():
|
||||
fallthrough
|
||||
case b.isAuthorized():
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// accessPerms - access level.
|
||||
type accessPerms string
|
||||
|
||||
// different types of Access perm's currently supported by accesss command.
|
||||
const (
|
||||
accessPrivate = accessPerms("private")
|
||||
accessReadOnly = accessPerms("readonly")
|
||||
accessPublic = accessPerms("public")
|
||||
accessAuthorized = accessPerms("authorized")
|
||||
)
|
||||
|
||||
func (b accessPerms) String() string {
|
||||
if !b.isValidAccessPERM() {
|
||||
return string(b)
|
||||
}
|
||||
if b.isReadOnly() {
|
||||
return "public-read"
|
||||
}
|
||||
if b.isPublic() {
|
||||
return "public-read-write"
|
||||
}
|
||||
if b.isAuthorized() {
|
||||
return "authenticated-read"
|
||||
}
|
||||
return "private"
|
||||
}
|
||||
|
||||
// convert acl's to access perms
|
||||
func aclToPerms(acl string) accessPerms {
|
||||
switch acl {
|
||||
case "private":
|
||||
return accessPerms("private")
|
||||
case "public-read":
|
||||
return accessPerms("readonly")
|
||||
case "public-read-write":
|
||||
return accessPerms("public")
|
||||
case "authenticated-read":
|
||||
return accessPerms("authorized")
|
||||
default:
|
||||
return accessPerms(acl)
|
||||
}
|
||||
}
|
||||
|
||||
// isPrivate - is acl Private.
|
||||
func (b accessPerms) isPrivate() bool {
|
||||
return b == accessPrivate
|
||||
}
|
||||
|
||||
// isPublicRead - is acl PublicRead.
|
||||
func (b accessPerms) isReadOnly() bool {
|
||||
return b == accessReadOnly
|
||||
}
|
||||
|
||||
// isPublicReadWrite - is acl PublicReadWrite.
|
||||
func (b accessPerms) isPublic() bool {
|
||||
return b == accessPublic
|
||||
}
|
||||
|
||||
// isAuthorized - is acl AuthorizedRead.
|
||||
func (b accessPerms) isAuthorized() bool {
|
||||
return b == accessAuthorized
|
||||
}
|
||||
+33
-25
@@ -4,44 +4,52 @@ version: "{build}"
|
||||
# Operating system (build VM template)
|
||||
os: Windows Server 2012 R2
|
||||
|
||||
# Platform.
|
||||
platform: x64
|
||||
|
||||
clone_folder: c:\gopath\src\github.com\minio\mc
|
||||
|
||||
# environment variables
|
||||
# Environment variables
|
||||
environment:
|
||||
GOPATH: c:\gopath
|
||||
GO15VENDOREXPERIMENT: 1
|
||||
GOROOT: c:\go
|
||||
|
||||
# scripts that run after cloning repository
|
||||
install:
|
||||
- set PATH=%GOPATH%\bin;c:\go\bin;%PATH%
|
||||
- set PATH=%GOPATH%\bin;%GOROOT%\bin;%PATH%
|
||||
- go version
|
||||
- go env
|
||||
- go get -u github.com/golang/lint/golint
|
||||
- go get -u golang.org/x/tools/cmd/vet
|
||||
- go get -u github.com/fzipp/gocyclo
|
||||
- go get -u github.com/remyoudompheng/go-misc/deadcode
|
||||
- go get -u github.com/alecthomas/gometalinter
|
||||
- go get -u github.com/client9/misspell
|
||||
- python --version
|
||||
|
||||
# to run your custom scripts instead of automatic MSBuild
|
||||
# To run your custom scripts instead of automatic MSBuild
|
||||
build_script:
|
||||
- go tool vet -all ./pkg
|
||||
- go tool vet -shadow=true ./pkg
|
||||
- gofmt -s -l pkg
|
||||
- golint .
|
||||
- golint github.com/minio/mc/pkg...
|
||||
- gometalinter --disable-all --linter='misspell:misspell ./*.go:PATH:LINE:COL:MESSAGE' --enable=misspell ./...
|
||||
- gocyclo -over 40 pkg
|
||||
- deadcode
|
||||
- go test -race .
|
||||
- go test -race github.com/minio/mc/pkg...
|
||||
# Compile
|
||||
# We need to disable firewall - https://github.com/appveyor/ci/issues/1579#issuecomment-309830648
|
||||
- ps: Disable-NetFirewallRule -DisplayName 'File and Printer Sharing (SMB-Out)'
|
||||
- appveyor AddCompilationMessage "Starting Compile"
|
||||
- cd c:\gopath\src\github.com\minio\mc
|
||||
- go run buildscripts/gen-ldflags.go > temp.txt
|
||||
- set /p LDFLAGS=<temp.txt
|
||||
- go build -ldflags="%LDFLAGS%" -o %GOPATH%\bin\mc.exe
|
||||
- mc version
|
||||
- set /p BUILD_LDFLAGS=<temp.txt
|
||||
- go build -ldflags="%BUILD_LDFLAGS%" -o %GOPATH%\bin\mc.exe
|
||||
- appveyor AddCompilationMessage "Compile Success"
|
||||
|
||||
# to disable automatic tests
|
||||
test: off
|
||||
# To run your custom scripts instead of automatic tests
|
||||
test_script:
|
||||
# Unit tests
|
||||
- ps: Add-AppveyorTest "Unit Tests" -Outcome Running
|
||||
- mkdir build\coverage
|
||||
- for /f "" %%G in ('go list github.com/minio/mc/...') do ( go test -v -race %%G )
|
||||
- go test -v -coverprofile=build\coverage\coverage.txt -covermode=atomic github.com/minio/mc/cmd
|
||||
- ps: Update-AppveyorTest "Unit Tests" -Outcome Passed
|
||||
|
||||
after_test:
|
||||
- go tool cover -html=build\coverage\coverage.txt -o build\coverage\coverage.html
|
||||
- ps: Push-AppveyorArtifact build\coverage\coverage.txt
|
||||
- ps: Push-AppveyorArtifact build\coverage\coverage.html
|
||||
# Upload coverage report.
|
||||
- "SET PATH=C:\\Python34;C:\\Python34\\Scripts;%PATH%"
|
||||
- pip install codecov
|
||||
- codecov -X gcov -f "build\coverage\coverage.txt"
|
||||
|
||||
# to disable deployment
|
||||
deploy: off
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
#!/bin/bash
|
||||
|
||||
: ${PROG:=$(basename ${BASH_SOURCE})}
|
||||
|
||||
_cli_bash_autocomplete() {
|
||||
local cur opts base
|
||||
COMPREPLY=()
|
||||
cur="${COMP_WORDS[COMP_CWORD]}"
|
||||
opts=$( ${COMP_WORDS[@]:0:$COMP_CWORD} --compgen )
|
||||
COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
|
||||
return 0
|
||||
}
|
||||
|
||||
complete -F _cli_bash_autocomplete $PROG -q
|
||||
@@ -0,0 +1,5 @@
|
||||
autoload -U compinit && compinit
|
||||
autoload -U bashcompinit && bashcompinit
|
||||
|
||||
script_dir=$(dirname $0)
|
||||
source ${script_dir}/bash_autocomplete
|
||||
Executable
+110
@@ -0,0 +1,110 @@
|
||||
#!/bin/bash
|
||||
|
||||
_init() {
|
||||
# Save release LDFLAGS
|
||||
LDFLAGS=$(go run buildscripts/gen-ldflags.go)
|
||||
|
||||
# Extract release tag
|
||||
release_tag=$(echo $LDFLAGS | awk {'print $6'} | cut -f2 -d=)
|
||||
|
||||
# Verify release tag.
|
||||
if [ -z "$release_tag" ]; then
|
||||
echo "Release tag cannot be empty. Please check return value of \`go run buildscripts/gen-ldflags.go\`"
|
||||
exit 1;
|
||||
fi
|
||||
|
||||
# Extract release string.
|
||||
release_str=$(echo $MC_RELEASE | tr '[:upper:]' '[:lower:]')
|
||||
|
||||
# Verify release string.
|
||||
if [ -z "$release_str" ]; then
|
||||
echo "Release string cannot be empty. Please set \`MC_RELEASE\` env variable."
|
||||
exit 1;
|
||||
fi
|
||||
|
||||
# List of supported architectures
|
||||
SUPPORTED_OSARCH='linux/amd64 linux/ppc64le windows/amd64 darwin/amd64'
|
||||
|
||||
## System binaries
|
||||
CP=`which cp`
|
||||
SHASUM=`which shasum`
|
||||
SHA256SUM="${SHASUM} -a 256"
|
||||
SED=`which sed`
|
||||
}
|
||||
|
||||
go_build() {
|
||||
local osarch=$1
|
||||
os=$(echo $osarch | cut -f1 -d'/')
|
||||
arch=$(echo $osarch | cut -f2 -d'/')
|
||||
package=$(go list -f '{{.ImportPath}}')
|
||||
echo -n "-->"
|
||||
printf "%15s:%s\n" "${osarch}" "${package}"
|
||||
|
||||
# Release binary name
|
||||
release_bin="$release_str/$os-$arch/$(basename $package).$release_tag"
|
||||
# Release binary downloadable name
|
||||
release_real_bin="$release_str/$os-$arch/$(basename $package)"
|
||||
|
||||
# Release sha1sum name
|
||||
release_shasum="$release_str/$os-$arch/$(basename $package).${release_tag}.shasum"
|
||||
# Release sha1sum default
|
||||
release_shasum_default="$release_str/$os-$arch/$(basename $package).shasum"
|
||||
|
||||
# Release sha256sum name
|
||||
release_sha256sum="$release_str/$os-$arch/$(basename $package).${release_tag}.sha256sum"
|
||||
# Release sha256sum default
|
||||
release_sha256sum_default="$release_str/$os-$arch/$(basename $package).sha256sum"
|
||||
|
||||
# Go build to build the binary.
|
||||
CGO_ENABLED=0 GOOS=$os GOARCH=$arch go build -tags kqueue --ldflags "${LDFLAGS}" -o $release_bin
|
||||
|
||||
# Create copy
|
||||
if [ $os == "windows" ]; then
|
||||
$CP -p $release_bin ${release_real_bin}.exe
|
||||
else
|
||||
$CP -p $release_bin $release_real_bin
|
||||
fi
|
||||
|
||||
# Calculate sha1sum
|
||||
shasum_str=$(${SHASUM} ${release_bin})
|
||||
echo ${shasum_str} | $SED "s/$release_str\/$os-$arch\///g" > $release_shasum
|
||||
$CP -p $release_shasum $release_shasum_default
|
||||
|
||||
# Calculate sha256sum
|
||||
sha256sum_str=$(${SHA256SUM} ${release_bin})
|
||||
echo ${sha256sum_str} | $SED "s/$release_str\/$os-$arch\///g" > $release_sha256sum
|
||||
$CP -p $release_sha256sum $release_sha256sum_default
|
||||
}
|
||||
|
||||
main() {
|
||||
# Build releases.
|
||||
echo "Executing $release_str builds for OS: ${SUPPORTED_OSARCH}"
|
||||
echo "Choose an OS Arch from the below"
|
||||
for osarch in ${SUPPORTED_OSARCH}; do
|
||||
echo ${osarch}
|
||||
done
|
||||
|
||||
read -p "If you want to build for all, Just press Enter: " chosen_osarch
|
||||
if [ "$chosen_osarch" = "" ] || [ "$chosen_osarch" = "all" ]; then
|
||||
for each_osarch in ${SUPPORTED_OSARCH}; do
|
||||
go_build ${each_osarch}
|
||||
done
|
||||
else
|
||||
local found=0
|
||||
for each_osarch in ${SUPPORTED_OSARCH}; do
|
||||
if [ "$chosen_osarch" = "$each_osarch" ]; then
|
||||
found=1
|
||||
fi
|
||||
done
|
||||
if [ ${found} -eq 1 ]; then
|
||||
go_build ${chosen_osarch}
|
||||
else
|
||||
echo "Unknown architecture \"${chosen_osarch}\""
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
}
|
||||
|
||||
# Run main.
|
||||
_init && main
|
||||
+87
-149
@@ -1,6 +1,6 @@
|
||||
#!/usr/bin/env bash
|
||||
#
|
||||
# Minio Client, (C) 2015 Minio, Inc.
|
||||
# Minio Client, (C) 2015, 2016, 2017 Minio, Inc.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
@@ -21,14 +21,26 @@ _init() {
|
||||
|
||||
## Minimum required versions for build dependencies
|
||||
GIT_VERSION="1.0"
|
||||
GO_VERSION="1.5.1"
|
||||
GO_VERSION="1.10.1"
|
||||
OSX_VERSION="10.8"
|
||||
UNAME=$(uname -sm)
|
||||
|
||||
## Check all dependencies are present
|
||||
MISSING=""
|
||||
KNAME=$(uname -s)
|
||||
ARCH=$(uname -m)
|
||||
case "${KNAME}" in
|
||||
SunOS )
|
||||
ARCH=$(isainfo -k)
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
## FIXME:
|
||||
## In OSX, 'readlink -f' option does not exist, hence
|
||||
## we have our own readlink -f behaviour here.
|
||||
## Once OSX has the option, below function is good enough.
|
||||
##
|
||||
## readlink() {
|
||||
## return /bin/readlink -f "$1"
|
||||
## }
|
||||
##
|
||||
readlink() {
|
||||
TARGET_FILE=$1
|
||||
|
||||
@@ -50,169 +62,95 @@ readlink() {
|
||||
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
|
||||
## FIXME:
|
||||
## In OSX, 'sort -V' option does not exist, hence
|
||||
## we have our own version compare function.
|
||||
## Once OSX has the option, below function is good enough.
|
||||
##
|
||||
## check_minimum_version() {
|
||||
## versions=($(echo -e "$1\n$2" | sort -V))
|
||||
## return [ "$1" == "${versions[0]}" ]
|
||||
## }
|
||||
##
|
||||
check_minimum_version() {
|
||||
IFS='.' read -r -a varray1 <<< "$1"
|
||||
IFS='.' read -r -a varray2 <<< "$2"
|
||||
|
||||
for i in "${!varray1[@]}"; do
|
||||
if [[ ${varray1[i]} -lt ${varray2[i]} ]]; then
|
||||
return 0
|
||||
elif [[ ${varray1[i]} -gt ${varray2[i]} ]]; then
|
||||
return 1
|
||||
fi
|
||||
if ((10#${ver1[i]} < 10#${ver2[i]})); then
|
||||
## Installed version is lesser than required - Bad condition
|
||||
return 2
|
||||
fi
|
||||
done
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
check_golang_env() {
|
||||
echo ${GOROOT:?} 2>&1 >/dev/null
|
||||
if [ $? -eq 1 ]; then
|
||||
echo "ERROR"
|
||||
echo "GOROOT environment variable missing, please refer to Go installation document"
|
||||
echo "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
|
||||
assert_is_supported_arch() {
|
||||
case "${ARCH}" in
|
||||
x86_64 | amd64 | ppc64le | aarch64 | arm* | s390x )
|
||||
return
|
||||
;;
|
||||
*)
|
||||
supported=0
|
||||
;;
|
||||
echo "Arch '${ARCH}' is not supported. Supported Arch: [x86_64, amd64, ppc64le, aarch64, arm*, s390x]"
|
||||
exit 1
|
||||
esac
|
||||
if [ $supported -eq 0 ]; then
|
||||
echo "Invalid arch: ${UNAME} not supported, please use x86_64/amd64"
|
||||
exit 1;
|
||||
}
|
||||
|
||||
assert_is_supported_os() {
|
||||
case "${KNAME}" in
|
||||
Linux | FreeBSD | OpenBSD | NetBSD | DragonFly | SunOS )
|
||||
return
|
||||
;;
|
||||
Darwin )
|
||||
osx_host_version=$(env sw_vers -productVersion)
|
||||
if ! check_minimum_version "${OSX_VERSION}" "${osx_host_version}"; then
|
||||
echo "OSX version '${osx_host_version}' is not supported. Minimum supported version: ${OSX_VERSION}"
|
||||
exit 1
|
||||
fi
|
||||
return
|
||||
;;
|
||||
*)
|
||||
echo "OS '${KNAME}' is not supported. Supported OS: [Linux, FreeBSD, OpenBSD, NetBSD, Darwin, DragonFly]"
|
||||
exit 1
|
||||
esac
|
||||
}
|
||||
|
||||
assert_check_golang_env() {
|
||||
if ! which go >/dev/null 2>&1; then
|
||||
echo "Cannot find go binary in your PATH configuration, please refer to Go installation document at https://docs.minio.io/docs/how-to-install-golang"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
installed_go_version=$(go version | sed 's/^.* go\([0-9.]*\).*$/\1/')
|
||||
if ! check_minimum_version "${GO_VERSION}" "${installed_go_version}"; then
|
||||
echo "Go runtime version '${installed_go_version}' is unsupported. Minimum supported version: ${GO_VERSION} to compile."
|
||||
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})"
|
||||
assert_check_deps() {
|
||||
# support unusual Git versions such as: 2.7.4 (Apple Git-66)
|
||||
installed_git_version=$(git version | perl -ne '$_ =~ m/git version (.*?)( |$)/; print "$1\n";')
|
||||
if ! check_minimum_version "${GIT_VERSION}" "${installed_git_version}"; then
|
||||
echo "Git version '${installed_git_version}' is not supported. Minimum supported version: ${GIT_VERSION}"
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
main() {
|
||||
echo -n "Check for supported arch.. "
|
||||
is_supported_arch
|
||||
## Check for supported arch
|
||||
assert_is_supported_arch
|
||||
|
||||
echo -n "Check for supported os.. "
|
||||
is_supported_os
|
||||
## Check for supported os
|
||||
assert_is_supported_os
|
||||
|
||||
echo -n "Checking if proper environment variables are set.. "
|
||||
check_golang_env
|
||||
## Check for Go environment
|
||||
assert_check_golang_env
|
||||
|
||||
echo "Done"
|
||||
echo "Using GOPATH=${GOPATH} and GOROOT=${GOROOT}"
|
||||
|
||||
echo -n "Checking dependencies for Minio Client.. "
|
||||
check_deps
|
||||
|
||||
## If dependencies are missing, warn the user and abort
|
||||
if [ "x${MISSING}" != "x" ]; then
|
||||
echo "ERROR"
|
||||
echo
|
||||
echo "The following build tools are missing:"
|
||||
echo
|
||||
echo "** ${MISSING} **"
|
||||
echo
|
||||
echo "Please install them "
|
||||
echo "${MISSING}"
|
||||
echo
|
||||
echo "Follow https://github.com/minio/mc/blob/master/INSTALLGO.md for further instructions"
|
||||
exit 1
|
||||
fi
|
||||
echo "Done"
|
||||
## Check for dependencies
|
||||
assert_check_deps
|
||||
}
|
||||
|
||||
_init && main "$@"
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
#!/usr/bin/env bash
|
||||
#
|
||||
# Minio Client, (C) 2015, 2016, 2017, 2018 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.
|
||||
#
|
||||
|
||||
main() {
|
||||
gopath=$(go env GOPATH)
|
||||
IFS=':' read -r -a paths <<< "$gopath"
|
||||
for path in "${paths[@]}"; do
|
||||
mcpath="$path/src/github.com/minio/mc"
|
||||
if [ -d "$mcpath" ]; then
|
||||
if [ "$mcpath" -ef "$PWD" ]; then
|
||||
exit 0
|
||||
fi
|
||||
fi
|
||||
done
|
||||
|
||||
echo "Project not found in ${gopath}. Follow instructions at https://github.com/minio/mc/blob/master/CONTRIBUTING.md#setup-your-mc-github-repository"
|
||||
exit 1
|
||||
}
|
||||
|
||||
main
|
||||
@@ -1,7 +1,7 @@
|
||||
// +build ignore
|
||||
|
||||
/*
|
||||
* Mc Client (C) 2014, 2015 Mc, Inc.
|
||||
* Minio Client (C) 2014, 2015, 2016, 2017, 2018 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -28,16 +28,16 @@ import (
|
||||
|
||||
func genLDFlags(version string) string {
|
||||
var ldflagsStr string
|
||||
ldflagsStr = "-X main.mcVersion=" + version + " "
|
||||
ldflagsStr = ldflagsStr + "-X main.mcReleaseTag=" + releaseTag(version) + " "
|
||||
ldflagsStr = ldflagsStr + "-X main.mcCommitID=" + commitID() + " "
|
||||
ldflagsStr = ldflagsStr + "-X main.mcShortCommitID=" + commitID()[:12]
|
||||
ldflagsStr = "-s -w -X github.com/minio/mc/cmd.Version=" + version + " "
|
||||
ldflagsStr = ldflagsStr + "-X github.com/minio/mc/cmd.ReleaseTag=" + releaseTag(version) + " "
|
||||
ldflagsStr = ldflagsStr + "-X github.com/minio/mc/cmd.CommitID=" + commitID() + " "
|
||||
ldflagsStr = ldflagsStr + "-X github.com/minio/mc/cmd.ShortCommitID=" + commitID()[:12]
|
||||
return ldflagsStr
|
||||
}
|
||||
|
||||
// genReleaseTag prints release tag to the console for easy git tagging.
|
||||
func releaseTag(version string) string {
|
||||
relPrefix := "UNOFFICIAL"
|
||||
relPrefix := "DEVELOPMENT"
|
||||
if prefix := os.Getenv("MC_RELEASE"); prefix != "" {
|
||||
relPrefix = prefix
|
||||
}
|
||||
|
||||
Executable
+12
@@ -0,0 +1,12 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
set -e
|
||||
echo "" > coverage.txt
|
||||
|
||||
for d in $(go list ./...); do
|
||||
go test -coverprofile=profile.out -covermode=atomic $d
|
||||
if [ -f profile.out ]; then
|
||||
cat profile.out >> coverage.txt
|
||||
rm profile.out
|
||||
fi
|
||||
done
|
||||
-152
@@ -1,152 +0,0 @@
|
||||
/*
|
||||
* Minio Client, (C) 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
"syscall"
|
||||
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
)
|
||||
|
||||
var (
|
||||
catFlags = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "help, h",
|
||||
Usage: "Help of cat",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
// Display contents of a file.
|
||||
var catCmd = cli.Command{
|
||||
Name: "cat",
|
||||
Usage: "Display contents of a file.",
|
||||
Action: mainCat,
|
||||
Flags: append(catFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
mc {{.Name}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
mc {{.Name}} [FLAGS] SOURCE [SOURCE...]
|
||||
|
||||
FLAGS:
|
||||
{{range .Flags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Stream an object from Amazon S3 cloud storage to mplayer standard input.
|
||||
$ mc {{.Name}} s3/ferenginar/klingon_opera_aktuh_maylotah.ogg | mplayer -
|
||||
|
||||
2. Concantenate contents of file1.txt and stdin to standard output.
|
||||
$ mc {{.Name}} file1.txt - > file.txt
|
||||
|
||||
3. Concantenate multiple files to one.
|
||||
$ mc {{.Name}} part.* > complete.img
|
||||
|
||||
`,
|
||||
}
|
||||
|
||||
// checkCatSyntax performs command-line input validation for cat command.
|
||||
func checkCatSyntax(ctx *cli.Context) {
|
||||
args := ctx.Args()
|
||||
if !args.Present() {
|
||||
args = []string{"-"}
|
||||
}
|
||||
for _, arg := range args {
|
||||
if strings.HasPrefix(arg, "-") && len(arg) > 1 {
|
||||
fatalIf(probe.NewError(errors.New("")), fmt.Sprintf("Unknown flag ‘%s’ passed.", arg))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// catURL displays contents of a URL to stdout.
|
||||
func catURL(sourceURL string) *probe.Error {
|
||||
var reader io.Reader
|
||||
switch sourceURL {
|
||||
case "-":
|
||||
reader = os.Stdin
|
||||
default:
|
||||
// Ignore size, since os.Stat() would not return proper size all the
|
||||
// time for local filesystem for example /proc files.
|
||||
var err *probe.Error
|
||||
if reader, err = getSourceStream(sourceURL); err != nil {
|
||||
return err.Trace(sourceURL)
|
||||
}
|
||||
}
|
||||
return catOut(reader).Trace(sourceURL)
|
||||
}
|
||||
|
||||
// catOut reads from reader stream and writes to stdout.
|
||||
func catOut(r io.Reader) *probe.Error {
|
||||
// Read till EOF.
|
||||
if _, e := io.Copy(os.Stdout, r); e != nil {
|
||||
switch e := e.(type) {
|
||||
case *os.PathError:
|
||||
if e.Err == syscall.EPIPE {
|
||||
// stdout closed by the user. Gracefully exit.
|
||||
return nil
|
||||
}
|
||||
return probe.NewError(e)
|
||||
default:
|
||||
return probe.NewError(e)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// mainCat is the main entry point for cat command.
|
||||
func mainCat(ctx *cli.Context) {
|
||||
// Set global flags from context.
|
||||
setGlobalsFromContext(ctx)
|
||||
|
||||
// check 'cat' cli arguments.
|
||||
checkCatSyntax(ctx)
|
||||
|
||||
// Set command flags from context.
|
||||
stdinMode := false
|
||||
if !ctx.Args().Present() {
|
||||
stdinMode = true
|
||||
}
|
||||
|
||||
// handle std input data.
|
||||
if stdinMode {
|
||||
fatalIf(catOut(os.Stdin).Trace(), "Unable to read from standard input.")
|
||||
return
|
||||
}
|
||||
|
||||
// if Args contain ‘-’, we need to preserve its order specially.
|
||||
args := []string(ctx.Args())
|
||||
if ctx.Args().First() == "-" {
|
||||
for i, arg := range os.Args {
|
||||
if arg == "cat" {
|
||||
// Overwrite ctx.Args with os.Args.
|
||||
args = os.Args[i+1:]
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Convert arguments to URLs: expand alias, fix format.
|
||||
for _, url := range args {
|
||||
fatalIf(catURL(url).Trace(url), "Unable to read from ‘"+url+"’.")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
/*
|
||||
* Minio Client (C) 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
// isValidAccessPERM - is provided access perm string supported.
|
||||
func (b accessPerms) isValidAccessPERM() bool {
|
||||
switch b {
|
||||
case accessNone, accessDownload, accessUpload, accessPublic:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// accessPerms - access level.
|
||||
type accessPerms string
|
||||
|
||||
// different types of Access perm's currently supported by policy command.
|
||||
const (
|
||||
accessNone = accessPerms("none")
|
||||
accessDownload = accessPerms("download")
|
||||
accessUpload = accessPerms("upload")
|
||||
accessPublic = accessPerms("public")
|
||||
)
|
||||
@@ -14,12 +14,15 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/cheggaaa/pb"
|
||||
)
|
||||
|
||||
// accounter keeps tabs of ongoing data transfer information.
|
||||
@@ -51,7 +54,7 @@ func newAccounter(total int64) *accounter {
|
||||
|
||||
// write calculate the final speed.
|
||||
func (a *accounter) write(current int64) float64 {
|
||||
fromStart := time.Now().Sub(a.startTime)
|
||||
fromStart := time.Since(a.startTime)
|
||||
currentFromStart := current - a.startValue
|
||||
if currentFromStart > 0 {
|
||||
speed := float64(currentFromStart) / (float64(fromStart) / float64(time.Second))
|
||||
@@ -80,6 +83,18 @@ type accountStat struct {
|
||||
Speed float64
|
||||
}
|
||||
|
||||
func (c accountStat) String() string {
|
||||
speedBox := pb.Format(int64(c.Speed)).To(pb.U_BYTES).String()
|
||||
if speedBox == "" {
|
||||
speedBox = "0 MB"
|
||||
} else {
|
||||
speedBox = speedBox + "/s"
|
||||
}
|
||||
message := fmt.Sprintf("Total: %s, Transferred: %s, Speed: %s", pb.Format(c.Total).To(pb.U_BYTES),
|
||||
pb.Format(c.Transferred).To(pb.U_BYTES), speedBox)
|
||||
return message
|
||||
}
|
||||
|
||||
// Stat provides current stats captured.
|
||||
func (a *accounter) Stat() accountStat {
|
||||
var acntStat accountStat
|
||||
@@ -107,6 +122,11 @@ func (a *accounter) Set(n int64) *accounter {
|
||||
return a
|
||||
}
|
||||
|
||||
// Get gets current value atomically
|
||||
func (a *accounter) Get() int64 {
|
||||
return atomic.LoadInt64(&a.current)
|
||||
}
|
||||
|
||||
// Add add to current value atomically.
|
||||
func (a *accounter) Add(n int64) int64 {
|
||||
return atomic.AddInt64(&a.current, n)
|
||||
@@ -0,0 +1,95 @@
|
||||
/*
|
||||
* Minio Client (C) 2017 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
)
|
||||
|
||||
var adminConfigGetCmd = cli.Command{
|
||||
Name: "get",
|
||||
Usage: "Get config of a Minio server/cluster.",
|
||||
Before: setGlobalsFromContext,
|
||||
Action: mainAdminConfigGet,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} TARGET
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Get server configuration of a Minio server/cluster.
|
||||
$ {{.HelpName}} play/
|
||||
|
||||
`,
|
||||
}
|
||||
|
||||
// configGetMessage container to hold locks information.
|
||||
type configGetMessage struct {
|
||||
Status string `json:"status"`
|
||||
Config []byte `json:"config"`
|
||||
}
|
||||
|
||||
// String colorized service status message.
|
||||
func (u configGetMessage) String() string {
|
||||
return string(u.Config)
|
||||
}
|
||||
|
||||
// JSON jsonified service status Message message.
|
||||
func (u configGetMessage) JSON() string {
|
||||
u.Status = "success"
|
||||
statusJSONBytes, e := json.Marshal(u)
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(statusJSONBytes)
|
||||
}
|
||||
|
||||
// checkAdminConfigGetSyntax - validate all the passed arguments
|
||||
func checkAdminConfigGetSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) == 0 || len(ctx.Args()) > 2 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "get", 1) // last argument is exit code
|
||||
}
|
||||
}
|
||||
|
||||
func mainAdminConfigGet(ctx *cli.Context) error {
|
||||
|
||||
checkAdminConfigGetSyntax(ctx)
|
||||
|
||||
// Get the alias parameter from cli
|
||||
args := ctx.Args()
|
||||
aliasedURL := args.Get(0)
|
||||
|
||||
// Create a new Minio Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
fatalIf(err, "Cannot get a configured admin connection.")
|
||||
|
||||
// Call get config API
|
||||
c, e := client.GetConfig()
|
||||
fatalIf(probe.NewError(e), "Cannot get server configuration file.")
|
||||
|
||||
// Print
|
||||
printMsg(configGetMessage{Config: c})
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
/*
|
||||
* Minio Client (C) 2017 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
)
|
||||
|
||||
var adminConfigSetCmd = cli.Command{
|
||||
Name: "set",
|
||||
Usage: "Set new config file to a Minio server/cluster.",
|
||||
Before: setGlobalsFromContext,
|
||||
Action: mainAdminConfigSet,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} TARGET
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Set server configuration of a Minio server/cluster.
|
||||
$ cat myconfig | {{.HelpName}} myminio/
|
||||
|
||||
`,
|
||||
}
|
||||
|
||||
// configSetMessage container to hold locks information.
|
||||
type configSetMessage struct {
|
||||
Status string `json:"status"`
|
||||
setConfigStatus bool
|
||||
}
|
||||
|
||||
// String colorized service status message.
|
||||
func (u configSetMessage) String() (msg string) {
|
||||
// Print the general set config status
|
||||
if u.setConfigStatus {
|
||||
msg += console.Colorize("SetConfigSuccess",
|
||||
"Setting new Minio configuration file has been successful.\n")
|
||||
} else {
|
||||
msg += console.Colorize("SetConfigFailure",
|
||||
"Setting new Minio configuration file has failed.\n")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// JSON jsonified service status Message message.
|
||||
func (u configSetMessage) JSON() string {
|
||||
if u.setConfigStatus {
|
||||
u.Status = "success"
|
||||
} else {
|
||||
u.Status = "error"
|
||||
}
|
||||
statusJSONBytes, e := json.Marshal(u)
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(statusJSONBytes)
|
||||
}
|
||||
|
||||
// checkAdminConfigSetSyntax - validate all the passed arguments
|
||||
func checkAdminConfigSetSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) == 0 || len(ctx.Args()) > 2 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "set", 1) // last argument is exit code
|
||||
}
|
||||
}
|
||||
|
||||
// main config set function
|
||||
func mainAdminConfigSet(ctx *cli.Context) error {
|
||||
|
||||
// Check command arguments
|
||||
checkAdminConfigSetSyntax(ctx)
|
||||
|
||||
// Set color preference of command outputs
|
||||
console.SetColor("SetConfigSuccess", color.New(color.FgGreen, color.Bold))
|
||||
console.SetColor("SetConfigFailure", color.New(color.FgRed, color.Bold))
|
||||
|
||||
// Get the alias parameter from cli
|
||||
args := ctx.Args()
|
||||
aliasedURL := args.Get(0)
|
||||
|
||||
// Create a new Minio Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
fatalIf(err, "Cannot get a configured admin connection.")
|
||||
|
||||
// Call get config API
|
||||
fatalIf(probe.NewError(client.SetConfig(os.Stdin)), "Cannot set server configuration file.")
|
||||
|
||||
// Print set config result
|
||||
printMsg(configSetMessage{
|
||||
setConfigStatus: true,
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/*
|
||||
* Minio Client (C) 2017 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import "github.com/minio/cli"
|
||||
|
||||
var adminConfigCmd = cli.Command{
|
||||
Name: "config",
|
||||
Usage: "Manage configuration file",
|
||||
Action: mainAdminConfig,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Subcommands: []cli.Command{
|
||||
adminConfigGetCmd,
|
||||
adminConfigSetCmd,
|
||||
},
|
||||
HideHelpCommand: true,
|
||||
}
|
||||
|
||||
// mainAdminConfig is the handle for "mc admin config" command.
|
||||
func mainAdminConfig(ctx *cli.Context) error {
|
||||
cli.ShowCommandHelp(ctx, ctx.Args().First())
|
||||
return nil
|
||||
// Sub-commands like "get", "set" have their own main.
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
/*
|
||||
* Minio Client (C) 2016, 2017 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
)
|
||||
|
||||
var (
|
||||
adminCredsFlags = []cli.Flag{}
|
||||
)
|
||||
|
||||
const credsCmdName = "credentials"
|
||||
|
||||
var adminCredsCmd = cli.Command{
|
||||
Name: credsCmdName,
|
||||
Usage: "Change server access and secret keys",
|
||||
Action: mainAdminCreds,
|
||||
Flags: append(adminCredsFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} TARGET ACCESS_KEY SECRET_KEY
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Set new credentials of a Minio server represented by its alias 'play'.
|
||||
$ {{.HelpName}} play/ minio minio123
|
||||
|
||||
`,
|
||||
}
|
||||
|
||||
// checkAdminCredsSyntax - validate all the passed arguments
|
||||
func checkAdminCredsSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) != 3 {
|
||||
cli.ShowCommandHelpAndExit(ctx, credsCmdName, 1) // last argument is exit code
|
||||
}
|
||||
}
|
||||
|
||||
func mainAdminCreds(ctx *cli.Context) error {
|
||||
|
||||
setGlobalsFromContext(ctx)
|
||||
|
||||
checkAdminCredsSyntax(ctx)
|
||||
|
||||
// Get the alias parameter from cli
|
||||
args := ctx.Args()
|
||||
// TODO: if accessKey and secretKey are not supplied we should
|
||||
// display the existing credentials. This needs GetCredentials
|
||||
// support from Minio server.
|
||||
aliasedURL := args.First()
|
||||
accessKey, secretKey := args.Get(1), args.Get(2)
|
||||
|
||||
// Create a new Minio Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
fatalIf(err, "Cannot get a configured admin connection.")
|
||||
|
||||
// Change the credentials of the specified Minio server
|
||||
e := client.SetCredentials(accessKey, secretKey)
|
||||
fatalIf(probe.NewError(e), "Unable to set new credentials to '"+aliasedURL+"'.")
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
/*
|
||||
* Minio Client (C) 2018 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/minio/minio/pkg/madmin"
|
||||
)
|
||||
|
||||
type hri struct {
|
||||
*madmin.HealResultItem
|
||||
}
|
||||
|
||||
func newHRI(i *madmin.HealResultItem) *hri {
|
||||
return &hri{i}
|
||||
}
|
||||
|
||||
// getObjectHCCChange - returns before and after color change for
|
||||
// objects
|
||||
func (h hri) getObjectHCCChange() (b, a col, err error) {
|
||||
parityShards := h.ParityBlocks
|
||||
dataShards := h.DataBlocks
|
||||
|
||||
onlineBefore, onlineAfter := h.GetOnlineCounts()
|
||||
surplusShardsBeforeHeal := onlineBefore - dataShards
|
||||
surplusShardsAfterHeal := onlineAfter - dataShards
|
||||
|
||||
b, err = getHColCode(surplusShardsBeforeHeal, parityShards)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
a, err = getHColCode(surplusShardsAfterHeal, parityShards)
|
||||
return
|
||||
|
||||
}
|
||||
|
||||
// getReplicatedFileHCCChange - fetches health color code for metadata
|
||||
// files that are replicated.
|
||||
func (h hri) getReplicatedFileHCCChange() (b, a col, err error) {
|
||||
getColCode := func(numAvail int) (c col, err error) {
|
||||
// calculate color code for replicated object similar
|
||||
// to erasure coded objects
|
||||
quorum := h.DiskCount/h.SetCount/2 + 1
|
||||
surplus := numAvail/h.SetCount - quorum
|
||||
parity := h.DiskCount/h.SetCount - quorum
|
||||
c, err = getHColCode(surplus, parity)
|
||||
return
|
||||
}
|
||||
|
||||
onlineBefore, onlineAfter := h.GetOnlineCounts()
|
||||
b, err = getColCode(onlineBefore)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
a, err = getColCode(onlineAfter)
|
||||
return
|
||||
}
|
||||
|
||||
func (h hri) makeHealEntityString() string {
|
||||
switch h.Type {
|
||||
case madmin.HealItemObject:
|
||||
return h.Bucket + "/" + h.Object
|
||||
case madmin.HealItemBucket:
|
||||
return h.Bucket
|
||||
case madmin.HealItemMetadata:
|
||||
return "[disk-format]"
|
||||
case madmin.HealItemBucketMetadata:
|
||||
return fmt.Sprintf("[bucket-metadata]%s/%s", h.Bucket, h.Object)
|
||||
}
|
||||
return "** unexpected **"
|
||||
}
|
||||
|
||||
func (h hri) getHRTypeAndName() (typ, name string) {
|
||||
name = fmt.Sprintf("%s/%s", h.Bucket, h.Object)
|
||||
switch h.Type {
|
||||
case madmin.HealItemMetadata:
|
||||
typ = "system"
|
||||
name = h.Detail
|
||||
case madmin.HealItemBucketMetadata:
|
||||
typ = "system"
|
||||
name = "bucket-metadata:" + name
|
||||
case madmin.HealItemBucket:
|
||||
typ = "bucket"
|
||||
case madmin.HealItemObject:
|
||||
typ = "object"
|
||||
default:
|
||||
typ = fmt.Sprintf("!! Unknown heal result record %#v !!", h)
|
||||
name = typ
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (h hri) getHealResultStr() string {
|
||||
typ, name := h.getHRTypeAndName()
|
||||
|
||||
switch h.Type {
|
||||
case madmin.HealItemMetadata, madmin.HealItemBucketMetadata:
|
||||
return typ + ":" + name
|
||||
default:
|
||||
return name
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,438 @@
|
||||
/*
|
||||
* Minio Client (C) 2018 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"math"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
humanize "github.com/dustin/go-humanize"
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/minio/pkg/madmin"
|
||||
)
|
||||
|
||||
const (
|
||||
lineWidth = 80
|
||||
)
|
||||
|
||||
var (
|
||||
hColOrder = []col{colRed, colYellow, colGreen}
|
||||
hColTable = map[int][]int{
|
||||
1: {0, -1, 1},
|
||||
2: {0, 1, 2},
|
||||
3: {1, 2, 3},
|
||||
4: {1, 2, 4},
|
||||
5: {1, 3, 5},
|
||||
6: {2, 4, 6},
|
||||
7: {2, 4, 7},
|
||||
8: {2, 5, 8},
|
||||
}
|
||||
)
|
||||
|
||||
func getHColCode(surplusShards, parityShards int) (c col, err error) {
|
||||
if parityShards < 1 || parityShards > 8 || surplusShards > parityShards {
|
||||
return c, fmt.Errorf("Invalid parity shard count/surplus shard count given")
|
||||
}
|
||||
if surplusShards < 0 {
|
||||
return colGrey, err
|
||||
}
|
||||
colRow := hColTable[parityShards]
|
||||
for index, val := range colRow {
|
||||
if val != -1 && surplusShards <= val {
|
||||
return hColOrder[index], err
|
||||
}
|
||||
}
|
||||
return c, fmt.Errorf("cannot get a heal color code")
|
||||
}
|
||||
|
||||
type uiData struct {
|
||||
Bucket, Prefix string
|
||||
Client *madmin.AdminClient
|
||||
ClientToken string
|
||||
ForceStart bool
|
||||
HealOpts *madmin.HealOpts
|
||||
LastItem *hri
|
||||
|
||||
// Total time since heal start
|
||||
HealDuration time.Duration
|
||||
|
||||
// Accumulated statistics of heal result records
|
||||
BytesScanned int64
|
||||
|
||||
// Counter for objects, and another counter for all kinds of
|
||||
// items
|
||||
ObjectsScanned, ItemsScanned int64
|
||||
|
||||
// Counters for healed objects and all kinds of healed items
|
||||
ObjectsHealed, ItemsHealed int64
|
||||
|
||||
// Map from online drives to number of objects with that many
|
||||
// online drives.
|
||||
ObjectsByOnlineDrives map[int]int64
|
||||
// Map of health color code to number of objects with that
|
||||
// health color code.
|
||||
HealthCols map[col]int64
|
||||
|
||||
// channel to receive a prompt string to indicate activity on
|
||||
// the terminal
|
||||
CurChan (<-chan string)
|
||||
}
|
||||
|
||||
func (ui *uiData) updateStats(i madmin.HealResultItem) error {
|
||||
if i.Type == madmin.HealItemObject {
|
||||
// Objects whose size could not be found have -1 size
|
||||
// returned.
|
||||
if i.ObjectSize >= 0 {
|
||||
ui.BytesScanned += i.ObjectSize
|
||||
}
|
||||
|
||||
ui.ObjectsScanned++
|
||||
}
|
||||
ui.ItemsScanned++
|
||||
|
||||
beforeUp, afterUp := i.GetOnlineCounts()
|
||||
if afterUp > beforeUp {
|
||||
if i.Type == madmin.HealItemObject {
|
||||
ui.ObjectsHealed++
|
||||
}
|
||||
ui.ItemsHealed++
|
||||
}
|
||||
ui.ObjectsByOnlineDrives[afterUp]++
|
||||
|
||||
// Update health color stats:
|
||||
|
||||
// Fetch health color after heal:
|
||||
var err error
|
||||
var afterCol col
|
||||
h := newHRI(&i)
|
||||
switch h.Type {
|
||||
case madmin.HealItemMetadata, madmin.HealItemBucket:
|
||||
_, afterCol, err = h.getReplicatedFileHCCChange()
|
||||
default:
|
||||
_, afterCol, err = h.getObjectHCCChange()
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
ui.HealthCols[afterCol]++
|
||||
return nil
|
||||
}
|
||||
|
||||
func (ui *uiData) updateDuration(s *madmin.HealTaskStatus) {
|
||||
ui.HealDuration = UTCNow().Sub(s.StartTime)
|
||||
}
|
||||
|
||||
func (ui *uiData) getProgress() (oCount, objSize, duration string) {
|
||||
oCount = humanize.Comma(ui.ObjectsScanned)
|
||||
|
||||
duration = ui.HealDuration.Round(time.Second).String()
|
||||
|
||||
bytesScanned := float64(ui.BytesScanned)
|
||||
|
||||
// Compute unit for object size
|
||||
magnitudes := []float64{1 << 10, 1 << 20, 1 << 30, 1 << 40, 1 << 50, 1 << 60}
|
||||
units := []string{"B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB"}
|
||||
var i int
|
||||
for i = 0; i < len(magnitudes); i++ {
|
||||
if bytesScanned <= magnitudes[i] {
|
||||
break
|
||||
}
|
||||
}
|
||||
numUnits := int(bytesScanned * (1 << 10) / magnitudes[i])
|
||||
objSize = fmt.Sprintf("%d %s", numUnits, units[i])
|
||||
return
|
||||
}
|
||||
|
||||
func (ui *uiData) getPercentsNBars() (p map[col]float64, b map[col]string) {
|
||||
// barChar, emptyBarChar := "█", "░"
|
||||
barChar, emptyBarChar := "█", " "
|
||||
barLen := 12
|
||||
sum := float64(ui.ItemsScanned)
|
||||
cols := []col{colGrey, colRed, colYellow, colGreen}
|
||||
|
||||
p = make(map[col]float64, len(cols))
|
||||
b = make(map[col]string, len(cols))
|
||||
var filledLen int
|
||||
for _, col := range cols {
|
||||
v := float64(ui.HealthCols[col])
|
||||
if sum == 0 {
|
||||
p[col] = 0
|
||||
filledLen = 0
|
||||
} else {
|
||||
p[col] = v * 100 / sum
|
||||
// round up the filled part
|
||||
filledLen = int(math.Ceil(float64(barLen) * v / sum))
|
||||
}
|
||||
b[col] = strings.Repeat(barChar, filledLen) +
|
||||
strings.Repeat(emptyBarChar, barLen-filledLen)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (ui *uiData) printItemsQuietly(s *madmin.HealTaskStatus) (err error) {
|
||||
lpad := func(s col) string {
|
||||
return fmt.Sprintf("%-6s", string(s))
|
||||
}
|
||||
rpad := func(s col) string {
|
||||
return fmt.Sprintf("%6s", string(s))
|
||||
}
|
||||
printColStr := func(before, after col) {
|
||||
console.PrintC("[" + lpad(before) + " -> " + rpad(after) + "] ")
|
||||
}
|
||||
|
||||
var b, a col
|
||||
for _, item := range s.Items {
|
||||
h := newHRI(&item)
|
||||
switch h.Type {
|
||||
case madmin.HealItemMetadata, madmin.HealItemBucket:
|
||||
b, a, err = h.getReplicatedFileHCCChange()
|
||||
default:
|
||||
b, a, err = h.getObjectHCCChange()
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
printColStr(b, a)
|
||||
hrStr := h.getHealResultStr()
|
||||
switch h.Type {
|
||||
case madmin.HealItemMetadata, madmin.HealItemBucketMetadata:
|
||||
console.PrintC(fmt.Sprintln("**", hrStr, "**"))
|
||||
default:
|
||||
console.PrintC(hrStr, "\n")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (ui *uiData) printStatsQuietly(s *madmin.HealTaskStatus) {
|
||||
totalObjects, totalSize, totalTime := ui.getProgress()
|
||||
|
||||
healedStr := fmt.Sprintf("Healed:\t%s/%s objects; %s in %s\n",
|
||||
humanize.Comma(ui.ObjectsHealed), totalObjects,
|
||||
totalSize, totalTime)
|
||||
|
||||
console.PrintC(healedStr)
|
||||
}
|
||||
|
||||
func (ui *uiData) printItemsJSON(s *madmin.HealTaskStatus) (err error) {
|
||||
type change struct {
|
||||
Before string `json:"before"`
|
||||
After string `json:"after"`
|
||||
}
|
||||
type healRec struct {
|
||||
Status string `json:"status"`
|
||||
Error string `json:"error,omitempty"`
|
||||
Type string `json:"type"`
|
||||
Name string `json:"name"`
|
||||
Before struct {
|
||||
Color string `json:"color"`
|
||||
Offline int `json:"offline"`
|
||||
Online int `json:"online"`
|
||||
Missing int `json:"missing"`
|
||||
Corrupted int `json:"corrupted"`
|
||||
Drives []madmin.HealDriveInfo `json:"drives"`
|
||||
} `json:"before"`
|
||||
After struct {
|
||||
Color string `json:"color"`
|
||||
Offline int `json:"offline"`
|
||||
Online int `json:"online"`
|
||||
Missing int `json:"missing"`
|
||||
Corrupted int `json:"corrupted"`
|
||||
Drives []madmin.HealDriveInfo `json:"drives"`
|
||||
} `json:"after"`
|
||||
Size int64 `json:"size"`
|
||||
}
|
||||
makeHR := func(h *hri) (r healRec, err error) {
|
||||
r.Status = "success"
|
||||
r.Type, r.Name = h.getHRTypeAndName()
|
||||
|
||||
var b, a col
|
||||
switch h.Type {
|
||||
case madmin.HealItemMetadata, madmin.HealItemBucket:
|
||||
b, a, err = h.getReplicatedFileHCCChange()
|
||||
default:
|
||||
if h.Type == madmin.HealItemObject {
|
||||
r.Size = h.ObjectSize
|
||||
}
|
||||
b, a, err = h.getObjectHCCChange()
|
||||
}
|
||||
if err != nil {
|
||||
return r, err
|
||||
}
|
||||
r.Before.Color = strings.ToLower(string(b))
|
||||
r.After.Color = strings.ToLower(string(a))
|
||||
r.Before.Online, r.After.Online = h.GetOnlineCounts()
|
||||
r.Before.Missing, r.After.Missing = h.GetMissingCounts()
|
||||
r.Before.Corrupted, r.After.Corrupted = h.GetCorruptedCounts()
|
||||
r.Before.Offline, r.After.Offline = h.GetOfflineCounts()
|
||||
r.Before.Drives = h.Before.Drives
|
||||
r.After.Drives = h.After.Drives
|
||||
return r, nil
|
||||
}
|
||||
|
||||
for _, item := range s.Items {
|
||||
h := newHRI(&item)
|
||||
r, err := makeHR(h)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
jsonBytes, err := json.Marshal(r)
|
||||
fatalIf(probe.NewError(err), "Unable to marshal to JSON.")
|
||||
console.Println(string(jsonBytes))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (ui *uiData) printStatsJSON(s *madmin.HealTaskStatus) {
|
||||
var summary struct {
|
||||
Status string `json:"status"`
|
||||
Error string `json:"error,omitempty"`
|
||||
Type string `json:"type"`
|
||||
ObjectsScanned int64 `json:"objects_scanned"`
|
||||
ObjectsHealed int64 `json:"objects_healed"`
|
||||
ItemsScanned int64 `json:"items_scanned"`
|
||||
ItemsHealed int64 `json:"items_healed"`
|
||||
Size int64 `json:"size"`
|
||||
ElapsedTime int64 `json:"duration"`
|
||||
}
|
||||
|
||||
summary.Status = "success"
|
||||
summary.Type = "summary"
|
||||
|
||||
summary.ObjectsScanned = ui.ObjectsScanned
|
||||
summary.ObjectsHealed = ui.ObjectsHealed
|
||||
summary.ItemsScanned = ui.ItemsScanned
|
||||
summary.ItemsHealed = ui.ItemsHealed
|
||||
summary.Size = ui.BytesScanned
|
||||
summary.ElapsedTime = int64(ui.HealDuration.Round(time.Second).Seconds())
|
||||
|
||||
jBytes, err := json.Marshal(summary)
|
||||
fatalIf(probe.NewError(err), "Unable to marshal to JSON.")
|
||||
console.Println(string(jBytes))
|
||||
}
|
||||
|
||||
func (ui *uiData) updateUI(s *madmin.HealTaskStatus) (err error) {
|
||||
itemCount := len(s.Items)
|
||||
h := ui.LastItem
|
||||
if itemCount > 0 {
|
||||
item := s.Items[itemCount-1]
|
||||
h = newHRI(&item)
|
||||
ui.LastItem = h
|
||||
}
|
||||
scannedStr := "** waiting for status from server **"
|
||||
if h != nil {
|
||||
scannedStr = lineTrunc(h.makeHealEntityString(), lineWidth-len("Scanned: "))
|
||||
}
|
||||
|
||||
totalObjects, totalSize, totalTime := ui.getProgress()
|
||||
healedStr := fmt.Sprintf("%s/%s objects; %s in %s",
|
||||
humanize.Comma(ui.ObjectsHealed), totalObjects,
|
||||
totalSize, totalTime)
|
||||
|
||||
console.Print(console.Colorize("HealUpdateUI", fmt.Sprintf(" %s", <-ui.CurChan)))
|
||||
console.PrintC(fmt.Sprintf(" %s\n", scannedStr))
|
||||
console.PrintC(fmt.Sprintf(" %s\n", healedStr))
|
||||
|
||||
dspOrder := []col{colGreen, colYellow, colRed, colGrey}
|
||||
printColors := []*color.Color{}
|
||||
for _, c := range dspOrder {
|
||||
printColors = append(printColors, getPrintCol(c))
|
||||
}
|
||||
t := console.NewTable(printColors, []bool{false, true, true}, 4)
|
||||
|
||||
percentMap, barMap := ui.getPercentsNBars()
|
||||
cellText := make([][]string, len(dspOrder))
|
||||
for i := range cellText {
|
||||
cellText[i] = []string{
|
||||
string(dspOrder[i]),
|
||||
fmt.Sprintf(humanize.Comma(ui.HealthCols[dspOrder[i]])),
|
||||
fmt.Sprintf("%5.1f%% %s", percentMap[dspOrder[i]], barMap[dspOrder[i]]),
|
||||
}
|
||||
}
|
||||
|
||||
t.DisplayTable(cellText)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (ui *uiData) UpdateDisplay(s *madmin.HealTaskStatus) (err error) {
|
||||
// Update state
|
||||
ui.updateDuration(s)
|
||||
for _, i := range s.Items {
|
||||
ui.updateStats(i)
|
||||
}
|
||||
|
||||
// Update display
|
||||
switch {
|
||||
case globalJSON:
|
||||
err = ui.printItemsJSON(s)
|
||||
case globalQuiet:
|
||||
err = ui.printItemsQuietly(s)
|
||||
default:
|
||||
err = ui.updateUI(s)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (ui *uiData) DisplayAndFollowHealStatus() (err error) {
|
||||
var res madmin.HealTaskStatus
|
||||
|
||||
firstIter := true
|
||||
for {
|
||||
_, res, err = ui.Client.Heal(ui.Bucket, ui.Prefix, *ui.HealOpts,
|
||||
ui.ClientToken, ui.ForceStart)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if firstIter {
|
||||
firstIter = false
|
||||
} else {
|
||||
if !globalQuiet && !globalJSON {
|
||||
console.RewindLines(8)
|
||||
}
|
||||
}
|
||||
err = ui.UpdateDisplay(&res)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if res.Summary == "finished" {
|
||||
break
|
||||
}
|
||||
|
||||
if res.Summary == "stopped" {
|
||||
fmt.Println("Heal had an error - ", res.FailureDetail)
|
||||
break
|
||||
}
|
||||
|
||||
time.Sleep(time.Second)
|
||||
}
|
||||
if globalJSON {
|
||||
ui.printStatsJSON(&res)
|
||||
return nil
|
||||
}
|
||||
if globalQuiet {
|
||||
ui.printStatsQuietly(&res)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
/*
|
||||
* Minio Client (C) 2017, 2018 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/minio/pkg/madmin"
|
||||
)
|
||||
|
||||
var adminHealFlags = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "recursive, r",
|
||||
Usage: "Heal recursively",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "dry-run, n",
|
||||
Usage: "Only inspect data, but do not mutate",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "force-start, f",
|
||||
Usage: "Force start a new heal sequence",
|
||||
},
|
||||
}
|
||||
|
||||
var adminHealCmd = cli.Command{
|
||||
Name: "heal",
|
||||
Usage: "Heal disks, buckets and objects on Minio server",
|
||||
Action: mainAdminHeal,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(adminHealFlags, globalFlags...),
|
||||
HideHelpCommand: true,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} [FLAGS] TARGET
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. To format newly replaced disks in a Minio server with alias 'play'
|
||||
$ {{.HelpName}} play
|
||||
|
||||
2. Heal 'testbucket' in a Minio server with alias 'play'
|
||||
$ {{.HelpName}} play/testbucket/
|
||||
|
||||
3. Heal all objects under 'dir' prefix
|
||||
$ {{.HelpName}} --recursive play/testbucket/dir/
|
||||
|
||||
4. Issue a dry-run heal operation to inspect objects health but not heal them
|
||||
$ {{.HelpName}} --dry-run play
|
||||
|
||||
5. Issue a dry-run heal operation to inspect objects health under 'dir' prefix
|
||||
$ {{.HelpName}} --recursive --dry-run play/testbucket/dir/
|
||||
|
||||
`,
|
||||
}
|
||||
|
||||
func checkAdminHealSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) != 1 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "heal", 1) // last argument is exit code
|
||||
}
|
||||
}
|
||||
|
||||
// mainAdminHeal - the entry function of heal command
|
||||
func mainAdminHeal(ctx *cli.Context) error {
|
||||
|
||||
// Check for command syntax
|
||||
checkAdminHealSyntax(ctx)
|
||||
|
||||
// Get the alias parameter from cli
|
||||
args := ctx.Args()
|
||||
aliasedURL := args.Get(0)
|
||||
|
||||
console.SetColor("Heal", color.New(color.FgGreen, color.Bold))
|
||||
console.SetColor("HealUpdateUI", color.New(color.FgYellow, color.Bold))
|
||||
|
||||
// Create a new Minio Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
if err != nil {
|
||||
fatalIf(err.Trace(aliasedURL), "Cannot initialize admin client.")
|
||||
return nil
|
||||
}
|
||||
|
||||
// Compute bucket and object from the aliased URL
|
||||
aliasedURL = filepath.ToSlash(aliasedURL)
|
||||
splits := splitStr(aliasedURL, "/", 3)
|
||||
bucket, prefix := splits[1], splits[2]
|
||||
|
||||
opts := madmin.HealOpts{
|
||||
Recursive: ctx.Bool("recursive"),
|
||||
DryRun: ctx.Bool("dry-run"),
|
||||
}
|
||||
forceStart := ctx.Bool("force-start")
|
||||
healStart, _, herr := client.Heal(bucket, prefix, opts, "", forceStart)
|
||||
errorIf(probe.NewError(herr), "Failed to start heal sequence.")
|
||||
|
||||
ui := uiData{
|
||||
Bucket: bucket,
|
||||
Prefix: prefix,
|
||||
Client: client,
|
||||
ClientToken: healStart.ClientToken,
|
||||
ForceStart: forceStart,
|
||||
HealOpts: &opts,
|
||||
ObjectsByOnlineDrives: make(map[int]int64),
|
||||
HealthCols: make(map[col]int64),
|
||||
CurChan: cursorAnimate(),
|
||||
}
|
||||
errorIf(
|
||||
probe.NewError(ui.DisplayAndFollowHealStatus()),
|
||||
"Unable to display follow heal status.",
|
||||
)
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,270 @@
|
||||
/*
|
||||
* Minio Client (C) 2016, 2017, 2018 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"time"
|
||||
|
||||
humanize "github.com/dustin/go-humanize"
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/minio/pkg/madmin"
|
||||
)
|
||||
|
||||
var (
|
||||
adminInfoFlags = []cli.Flag{}
|
||||
)
|
||||
|
||||
var adminInfoCmd = cli.Command{
|
||||
Name: "info",
|
||||
Usage: "Display Minio server information",
|
||||
Action: mainAdminInfo,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(adminInfoFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} TARGET
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Get server information of the 'play' Minio server.
|
||||
$ {{.HelpName}} play/
|
||||
|
||||
`,
|
||||
}
|
||||
|
||||
// backendType - indicates the type of backend storage
|
||||
type backendType string
|
||||
|
||||
const (
|
||||
fsType = backendType("FS")
|
||||
erasureType = backendType("Erasure")
|
||||
)
|
||||
|
||||
// fsBackend contains specific FS storage information
|
||||
type fsBackend struct {
|
||||
Type backendType `json:"backendType"`
|
||||
}
|
||||
|
||||
// xlBackend contains specific erasure storage information
|
||||
type xlBackend struct {
|
||||
Type backendType `json:"backendType"`
|
||||
OnlineDisks int `json:"onlineDisks"`
|
||||
OfflineDisks int `json:"offlineDisks"`
|
||||
// Data disks for currently configured Standard storage class.
|
||||
StandardSCData int `json:"standardSCData"`
|
||||
// Parity disks for currently configured Standard storage class.
|
||||
StandardSCParity int `json:"standardSCParity"`
|
||||
// Data disks for currently configured Reduced Redundancy storage class.
|
||||
RRSCData int `json:"rrSCData"`
|
||||
// Parity disks for currently configured Reduced Redundancy storage class.
|
||||
RRSCParity int `json:"rrSCParity"`
|
||||
|
||||
// List of all disk status.
|
||||
Sets [][]madmin.DriveInfo `json:"sets"`
|
||||
}
|
||||
|
||||
// backendStatus represents the overall information of all backend storage types
|
||||
type backendStatus struct {
|
||||
Used uint64 `json:"used"`
|
||||
Backend interface{} `json:"backend"`
|
||||
}
|
||||
|
||||
// ServerInfo holds the whole server information that will be
|
||||
// returned by ServerInfo API.
|
||||
type ServerInfo struct {
|
||||
StorageInfo backendStatus `json:"storage"`
|
||||
ConnStats madmin.ServerConnStats `json:"network"`
|
||||
Properties madmin.ServerProperties `json:"server"`
|
||||
}
|
||||
|
||||
// infoMessage container to hold service status information.
|
||||
type infoMessage struct {
|
||||
Status string `json:"status"`
|
||||
Service string `json:"service"`
|
||||
Addr string `json:"address"`
|
||||
Err string `json:"error"`
|
||||
*ServerInfo
|
||||
}
|
||||
|
||||
// String colorized service status message.
|
||||
func (u infoMessage) String() (msg string) {
|
||||
defer func() {
|
||||
msg += "\n"
|
||||
}()
|
||||
|
||||
dot := "●"
|
||||
|
||||
// When service is offline
|
||||
if u.Service == "off" {
|
||||
msg += fmt.Sprintf("%s %s\n", console.Colorize("InfoFail", dot), u.Addr)
|
||||
msg += fmt.Sprintf(" Uptime : Server is %s", console.Colorize("InfoFail", "offline"))
|
||||
return
|
||||
}
|
||||
|
||||
// Print error if any and exit
|
||||
if u.Err != "" {
|
||||
msg += fmt.Sprintf("%s %s\n", console.Colorize("InfoFail", dot), u.Addr)
|
||||
msg += fmt.Sprintf(" Uptime : Server is %s\n", console.Colorize("InfoFail", "offline"))
|
||||
msg += fmt.Sprintf(" Error : %s", u.Err)
|
||||
return
|
||||
}
|
||||
|
||||
// Print server title
|
||||
msg += fmt.Sprintf("%s %s\n", console.Colorize("Info", dot), u.Addr)
|
||||
|
||||
// Print server information
|
||||
|
||||
// Uptime
|
||||
msg += fmt.Sprintf(" Uptime : %s since %s\n", console.Colorize("Info", "online"),
|
||||
humanize.Time(time.Now().UTC().Add(-u.ServerInfo.Properties.Uptime)))
|
||||
// Version
|
||||
msg += fmt.Sprintf(" Version : %s\n", u.ServerInfo.Properties.Version)
|
||||
// Region
|
||||
msg += fmt.Sprintf(" Region : %s\n", u.ServerInfo.Properties.Region)
|
||||
// ARNs
|
||||
sqsARNs := ""
|
||||
for _, v := range u.ServerInfo.Properties.SQSARN {
|
||||
sqsARNs += fmt.Sprintf("%s ", v)
|
||||
}
|
||||
if sqsARNs == "" {
|
||||
sqsARNs = "<none>"
|
||||
}
|
||||
msg += fmt.Sprintf(" SQS ARNs : %s\n", sqsARNs)
|
||||
// Incoming/outgoing
|
||||
msg += fmt.Sprintf(" Stats : Incoming %s, Outgoing %s\n",
|
||||
humanize.IBytes(u.ServerInfo.ConnStats.TotalInputBytes),
|
||||
humanize.IBytes(u.ServerInfo.ConnStats.TotalOutputBytes))
|
||||
// Get storage information
|
||||
msg += fmt.Sprintf(" Storage : Used %s", humanize.IBytes(u.StorageInfo.Used))
|
||||
if v, ok := u.ServerInfo.StorageInfo.Backend.(xlBackend); ok {
|
||||
msg += fmt.Sprintf("\n Disks : %s, %s\n", console.Colorize("Info", v.OnlineDisks),
|
||||
console.Colorize("InfoFail", v.OfflineDisks))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// JSON jsonified service status Message message.
|
||||
func (u infoMessage) JSON() string {
|
||||
u.Status = "success"
|
||||
statusJSONBytes, e := json.Marshal(u)
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(statusJSONBytes)
|
||||
}
|
||||
|
||||
// checkAdminInfoSyntax - validate all the passed arguments
|
||||
func checkAdminInfoSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) == 0 || len(ctx.Args()) > 2 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "info", 1) // last argument is exit code
|
||||
}
|
||||
}
|
||||
|
||||
func mainAdminInfo(ctx *cli.Context) error {
|
||||
// Validate service status syntax.
|
||||
checkAdminInfoSyntax(ctx)
|
||||
|
||||
console.SetColor("Info", color.New(color.FgGreen, color.Bold))
|
||||
console.SetColor("InfoDegraded", color.New(color.FgYellow, color.Bold))
|
||||
console.SetColor("InfoFail", color.New(color.FgRed, color.Bold))
|
||||
|
||||
// Get the alias parameter from cli
|
||||
args := ctx.Args()
|
||||
aliasedURL := args.Get(0)
|
||||
|
||||
// Create a new Minio Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
fatalIf(err, "Cannot get a configured admin connection.")
|
||||
|
||||
// Fetch info of all servers (cluster or single server)
|
||||
serversInfo, e := client.ServerInfo()
|
||||
|
||||
// Check the availability of the server: online or offline. A server is considered
|
||||
// offline if we can't get any response or we get a bad format response
|
||||
var serviceOffline bool
|
||||
switch e.(type) {
|
||||
case *json.SyntaxError:
|
||||
serviceOffline = true
|
||||
case *url.Error:
|
||||
serviceOffline = true
|
||||
}
|
||||
|
||||
if serviceOffline {
|
||||
printMsg(infoMessage{Addr: aliasedURL, Service: "off"})
|
||||
return nil
|
||||
}
|
||||
|
||||
// If the error is not nil and not unrecognizable, just print it and exit
|
||||
fatalIf(probe.NewError(e), "Cannot get service status.")
|
||||
|
||||
for _, serverInfo := range serversInfo {
|
||||
// Print the error if exists and jump to the next server
|
||||
if serverInfo.Error != "" {
|
||||
printMsg(infoMessage{
|
||||
Service: "on",
|
||||
Addr: serverInfo.Addr,
|
||||
Err: serverInfo.Error,
|
||||
})
|
||||
continue
|
||||
}
|
||||
|
||||
// Construct the backend status
|
||||
storageInfo := backendStatus{
|
||||
Used: serverInfo.Data.StorageInfo.Used,
|
||||
}
|
||||
|
||||
if serverInfo.Data.StorageInfo.Backend.Type == madmin.Erasure {
|
||||
storageInfo.Backend = xlBackend{
|
||||
Type: erasureType,
|
||||
OnlineDisks: serverInfo.Data.StorageInfo.Backend.OnlineDisks,
|
||||
OfflineDisks: serverInfo.Data.StorageInfo.Backend.OfflineDisks,
|
||||
StandardSCData: serverInfo.Data.StorageInfo.Backend.StandardSCData,
|
||||
StandardSCParity: serverInfo.Data.StorageInfo.Backend.StandardSCParity,
|
||||
RRSCData: serverInfo.Data.StorageInfo.Backend.RRSCData,
|
||||
RRSCParity: serverInfo.Data.StorageInfo.Backend.RRSCParity,
|
||||
Sets: serverInfo.Data.StorageInfo.Backend.Sets,
|
||||
}
|
||||
} else {
|
||||
storageInfo.Backend = fsBackend{
|
||||
Type: fsType,
|
||||
}
|
||||
}
|
||||
|
||||
printMsg(infoMessage{
|
||||
Service: "on",
|
||||
Addr: serverInfo.Addr,
|
||||
Err: serverInfo.Error,
|
||||
ServerInfo: &ServerInfo{
|
||||
StorageInfo: storageInfo,
|
||||
ConnStats: serverInfo.Data.ConnStats,
|
||||
Properties: serverInfo.Data.Properties,
|
||||
},
|
||||
})
|
||||
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
/*
|
||||
* Minio Client (C) 2016, 2017 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import "github.com/minio/cli"
|
||||
|
||||
var (
|
||||
adminFlags = []cli.Flag{}
|
||||
)
|
||||
|
||||
var adminCmd = cli.Command{
|
||||
Name: "admin",
|
||||
Usage: "Manage Minio servers",
|
||||
Action: mainAdmin,
|
||||
HideHelpCommand: true,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(adminFlags, globalFlags...),
|
||||
Subcommands: []cli.Command{
|
||||
adminServiceCmd,
|
||||
adminInfoCmd,
|
||||
adminCredsCmd,
|
||||
adminConfigCmd,
|
||||
adminHealCmd,
|
||||
},
|
||||
}
|
||||
|
||||
// mainAdmin is the handle for "mc admin" command.
|
||||
func mainAdmin(ctx *cli.Context) error {
|
||||
cli.ShowCommandHelp(ctx, ctx.Args().First())
|
||||
return nil
|
||||
// Sub-commands like "service", "heal", "lock" have their own main.
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
/*
|
||||
* Minio Client (C) 2016 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/minio/pkg/madmin"
|
||||
)
|
||||
|
||||
var adminServiceRestartCmd = cli.Command{
|
||||
Name: "restart",
|
||||
Usage: "Restart Minio server",
|
||||
Action: mainAdminServiceRestart,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} TARGET
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Restart Minio server represented by its alias 'play'.
|
||||
$ {{.HelpName}} play/
|
||||
|
||||
`,
|
||||
}
|
||||
|
||||
// serviceRestartMessage is container for make bucket success and failure messages.
|
||||
type serviceRestartMessage struct {
|
||||
Status string `json:"status"`
|
||||
ServerURL string `json:"serverURL"`
|
||||
}
|
||||
|
||||
// String colorized make bucket message.
|
||||
func (s serviceRestartMessage) String() string {
|
||||
return console.Colorize("ServiceRestart", "Restarted `"+s.ServerURL+"` successfully.")
|
||||
}
|
||||
|
||||
// JSON jsonified make bucket message.
|
||||
func (s serviceRestartMessage) JSON() string {
|
||||
serviceRestartJSONBytes, e := json.Marshal(s)
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(serviceRestartJSONBytes)
|
||||
}
|
||||
|
||||
// checkAdminServiceRestartSyntax - validate all the passed arguments
|
||||
func checkAdminServiceRestartSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) == 0 || len(ctx.Args()) > 2 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "restart", 1) // last argument is exit code
|
||||
}
|
||||
}
|
||||
|
||||
func mainAdminServiceRestart(ctx *cli.Context) error {
|
||||
|
||||
// Validate serivce restart syntax.
|
||||
checkAdminServiceRestartSyntax(ctx)
|
||||
|
||||
// Set color.
|
||||
console.SetColor("ServiceRestart", color.New(color.FgGreen, color.Bold))
|
||||
|
||||
// Get the alias parameter from cli
|
||||
args := ctx.Args()
|
||||
aliasedURL := args.Get(0)
|
||||
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
fatalIf(err, "Cannot get a configured admin connection.")
|
||||
|
||||
// Restart the specified Minio server
|
||||
fatalIf(probe.NewError(client.ServiceSendAction(
|
||||
madmin.ServiceActionValueRestart)), "Cannot restart server.")
|
||||
|
||||
// Success..
|
||||
printMsg(serviceRestartMessage{Status: "success", ServerURL: aliasedURL})
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
/*
|
||||
* Minio Client (C) 2016, 2017 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"time"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
)
|
||||
|
||||
var (
|
||||
adminServiceStatusFlags = []cli.Flag{}
|
||||
)
|
||||
|
||||
var adminServiceStatusCmd = cli.Command{
|
||||
Name: "status",
|
||||
Usage: "Get the status of Minio server",
|
||||
Action: mainAdminServiceStatus,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(adminServiceStatusFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} TARGET
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Check if the 'play' Minio server is online and show its uptime.
|
||||
$ {{.HelpName}} play/
|
||||
`,
|
||||
}
|
||||
|
||||
// serviceStatusMessage container to hold service status information.
|
||||
type serviceStatusMessage struct {
|
||||
Status string `json:"status"`
|
||||
Service string `json:"service"`
|
||||
Uptime time.Duration `json:"uptime"`
|
||||
}
|
||||
|
||||
// String colorized service status message.
|
||||
func (u serviceStatusMessage) String() (msg string) {
|
||||
defer func() {
|
||||
msg = console.Colorize("ServiceStatus", msg)
|
||||
}()
|
||||
// When service is offline
|
||||
if u.Service == "off" {
|
||||
msg = "The server is offline."
|
||||
return
|
||||
}
|
||||
msg = fmt.Sprintf("Uptime: %s.", timeDurationToHumanizedDuration(u.Uptime))
|
||||
return
|
||||
}
|
||||
|
||||
// JSON jsonified service status Message message.
|
||||
func (u serviceStatusMessage) JSON() string {
|
||||
switch u.Service {
|
||||
case "on":
|
||||
u.Status = "success"
|
||||
case "off":
|
||||
u.Status = "failure"
|
||||
}
|
||||
|
||||
statusJSONBytes, e := json.Marshal(u)
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(statusJSONBytes)
|
||||
}
|
||||
|
||||
// checkAdminServiceStatusSyntax - validate all the passed arguments
|
||||
func checkAdminServiceStatusSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) == 0 || len(ctx.Args()) > 2 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "status", 1) // last argument is exit code
|
||||
}
|
||||
}
|
||||
|
||||
func mainAdminServiceStatus(ctx *cli.Context) error {
|
||||
|
||||
// Validate serivce status syntax.
|
||||
checkAdminServiceStatusSyntax(ctx)
|
||||
|
||||
console.SetColor("ServiceStatus", color.New(color.FgGreen, color.Bold))
|
||||
|
||||
// Get the alias parameter from cli
|
||||
args := ctx.Args()
|
||||
aliasedURL := args.Get(0)
|
||||
|
||||
// Create a new Minio Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
fatalIf(err, "Cannot get a configured admin connection.")
|
||||
|
||||
// Fetch the service status of the specified Minio server
|
||||
st, e := client.ServiceStatus()
|
||||
|
||||
// Check the availability of the server: online or offline. A server is considered
|
||||
// offline if we can't get any response or we get a bad format response
|
||||
var serviceOffline bool
|
||||
switch v := e.(type) {
|
||||
case *json.SyntaxError:
|
||||
serviceOffline = true
|
||||
case *url.Error:
|
||||
if v.Timeout() {
|
||||
serviceOffline = true
|
||||
}
|
||||
}
|
||||
if serviceOffline {
|
||||
printMsg(serviceStatusMessage{Service: "off"})
|
||||
return nil
|
||||
}
|
||||
|
||||
// If the error is not nil and not unrecognizable, just print it and exit
|
||||
fatalIf(probe.NewError(e), "Cannot get service status.")
|
||||
|
||||
// Print the whole response
|
||||
printMsg(serviceStatusMessage{
|
||||
Service: "on",
|
||||
Uptime: st.Uptime,
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
/*
|
||||
* Minio Client (C) 2018 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/minio/pkg/madmin"
|
||||
)
|
||||
|
||||
var adminServiceStopCmd = cli.Command{
|
||||
Name: "stop",
|
||||
Usage: "Stop Minio server",
|
||||
Action: mainAdminServiceStop,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} TARGET
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Stop Minio server represented by its alias 'play'.
|
||||
$ {{.HelpName}} play/
|
||||
|
||||
`,
|
||||
}
|
||||
|
||||
// serviceStopMessage is container for make bucket success and failure messages.
|
||||
type serviceStopMessage struct {
|
||||
Status string `json:"status"`
|
||||
ServerURL string `json:"serverURL"`
|
||||
}
|
||||
|
||||
// String colorized make bucket message.
|
||||
func (s serviceStopMessage) String() string {
|
||||
return console.Colorize("ServiceStop", "Stopped `"+s.ServerURL+"` successfully.")
|
||||
}
|
||||
|
||||
// JSON jsonified make bucket message.
|
||||
func (s serviceStopMessage) JSON() string {
|
||||
serviceStopJSONBytes, e := json.Marshal(s)
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(serviceStopJSONBytes)
|
||||
}
|
||||
|
||||
// checkAdminServiceStopSyntax - validate all the passed arguments
|
||||
func checkAdminServiceStopSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) == 0 || len(ctx.Args()) > 2 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "stop", 1) // last argument is exit code
|
||||
}
|
||||
}
|
||||
|
||||
func mainAdminServiceStop(ctx *cli.Context) error {
|
||||
|
||||
// Validate serivce stop syntax.
|
||||
checkAdminServiceStopSyntax(ctx)
|
||||
|
||||
// Set color.
|
||||
console.SetColor("ServiceStop", color.New(color.FgGreen, color.Bold))
|
||||
|
||||
// Get the alias parameter from cli
|
||||
args := ctx.Args()
|
||||
aliasedURL := args.Get(0)
|
||||
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
fatalIf(err, "Cannot get a configured admin connection.")
|
||||
|
||||
// Stop the specified Minio server
|
||||
pErr := client.ServiceSendAction(madmin.ServiceActionValueStop)
|
||||
fatalIf(probe.NewError(pErr), "Cannot stop server.")
|
||||
|
||||
// Success..
|
||||
printMsg(serviceStopMessage{Status: "success", ServerURL: aliasedURL})
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
/*
|
||||
* Minio Client (C) 2016, 2017, 2018 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import "github.com/minio/cli"
|
||||
|
||||
var adminServiceCmd = cli.Command{
|
||||
Name: "service",
|
||||
Usage: "Stop, restart or get status of Minio server",
|
||||
Action: mainAdminService,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
HideHelpCommand: true,
|
||||
Subcommands: []cli.Command{
|
||||
adminServiceStatusCmd,
|
||||
adminServiceRestartCmd,
|
||||
adminServiceStopCmd,
|
||||
},
|
||||
}
|
||||
|
||||
// mainAdmin is the handle for "mc admin service" command.
|
||||
func mainAdminService(ctx *cli.Context) error {
|
||||
cli.ShowCommandHelp(ctx, ctx.Args().First())
|
||||
return nil
|
||||
// Sub-commands like "status", "restart" have their own main.
|
||||
}
|
||||
@@ -14,7 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
@@ -25,7 +25,6 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
type objectAPIHandler struct {
|
||||
@@ -63,7 +62,7 @@ func (h objectAPIHandler) getHandler(w http.ResponseWriter, r *http.Request) {
|
||||
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("Last-Modified", UTCNow().Format(http.TimeFormat))
|
||||
w.Header().Set("ETag", "b1946ac92492d2347c6235b4d2611184")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
io.Copy(w, bytes.NewReader(h.object[filepath.Base(r.URL.Path)]))
|
||||
@@ -83,7 +82,7 @@ func (h objectAPIHandler) headHandler(w http.ResponseWriter, r *http.Request) {
|
||||
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("Last-Modified", UTCNow().Format(http.TimeFormat))
|
||||
w.Header().Set("ETag", "b1946ac92492d2347c6235b4d2611184")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
return
|
||||
@@ -97,7 +96,7 @@ func isValidBucket(bucket string) bool {
|
||||
if bucket[0] == '.' || bucket[len(bucket)-1] == '.' {
|
||||
return false
|
||||
}
|
||||
if match, _ := regexp.MatchString("\\.\\.", bucket); match == true {
|
||||
if match, _ := regexp.MatchString("\\.\\.", bucket); match {
|
||||
return false
|
||||
}
|
||||
// We don't support buckets with '.' in them
|
||||
@@ -14,15 +14,15 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
package cmd
|
||||
|
||||
var (
|
||||
// mcVersion - version time.RFC3339.
|
||||
mcVersion = "UNOFFICIAL.GOGET"
|
||||
// mcReleaseTag - release tag in TAG.%Y-%m-%dT%H-%M-%SZ.
|
||||
mcReleaseTag = "UNOFFICIAL.GOGET"
|
||||
// mcCommitID - latest commit id.
|
||||
mcCommitID = "UNOFFICIAL.GOGET"
|
||||
// mcShortCommitID - first 12 characters from mcCommitID.
|
||||
mcShortCommitID = mcCommitID[:12]
|
||||
// Version - version time.RFC3339.
|
||||
Version = "DEVELOPMENT.GOGET"
|
||||
// ReleaseTag - release tag in TAG.%Y-%m-%dT%H-%M-%SZ.
|
||||
ReleaseTag = "DEVELOPMENT.GOGET"
|
||||
// CommitID - latest commit id.
|
||||
CommitID = "DEVELOPMENT.GOGET"
|
||||
// ShortCommitID - first 12 characters from CommitID.
|
||||
ShortCommitID = CommitID[:12]
|
||||
)
|
||||
+250
@@ -0,0 +1,250 @@
|
||||
/*
|
||||
* Minio Client, (C) 2015, 2016, 2017 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
"syscall"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"golang.org/x/crypto/ssh/terminal"
|
||||
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
)
|
||||
|
||||
var (
|
||||
catFlags = []cli.Flag{
|
||||
cli.StringFlag{
|
||||
Name: "encrypt-key",
|
||||
Usage: "Decrypt object (using server-side encryption)",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
// Display contents of a file.
|
||||
var catCmd = cli.Command{
|
||||
Name: "cat",
|
||||
Usage: "Display file and object contents.",
|
||||
Action: mainCat,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(catFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} [FLAGS] SOURCE [SOURCE...]
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
|
||||
ENVIRONMENT VARIABLES:
|
||||
MC_ENCRYPT_KEY: List of comma delimited prefix=secret values
|
||||
EXAMPLES:
|
||||
1. Stream an object from Amazon S3 cloud storage to mplayer standard input.
|
||||
$ {{.HelpName}} s3/ferenginar/klingon_opera_aktuh_maylotah.ogg | mplayer -
|
||||
|
||||
2. Concatenate contents of file1.txt and stdin to standard output.
|
||||
$ {{.HelpName}} file1.txt - > file.txt
|
||||
|
||||
3. Concatenate multiple files to one.
|
||||
$ {{.HelpName}} part.* > complete.img
|
||||
|
||||
4. Stream a server encrypted object from Amazon S3 cloud storage to standard output.
|
||||
$ {{.HelpName}} --encrypt-key 's3/ferenginar=32byteslongsecretkeymustbegiven1' s3/ferenginar/klingon_opera_aktuh_maylotah.ogg
|
||||
`,
|
||||
}
|
||||
|
||||
// prettyStdout replaces some non printable characters
|
||||
// with <hex> format to be better viewable by the user
|
||||
type prettyStdout struct {
|
||||
// Internal data to pretty-print
|
||||
writer io.Writer
|
||||
// Internal buffer which contains pretty printed
|
||||
// form of binary (no printable) characters
|
||||
buffer *bytes.Buffer
|
||||
}
|
||||
|
||||
// newPrettyStdout returns an initialized prettyStdout struct
|
||||
func newPrettyStdout(w io.Writer) *prettyStdout {
|
||||
return &prettyStdout{
|
||||
writer: w,
|
||||
buffer: bytes.NewBuffer([]byte{}),
|
||||
}
|
||||
}
|
||||
|
||||
// Read() returns pretty printed binary characters
|
||||
func (s prettyStdout) Write(input []byte) (int, error) {
|
||||
inputLen := len(input)
|
||||
|
||||
// Convert no printable characters to '^?'
|
||||
// and fill into s.buffer
|
||||
for len(input) > 0 {
|
||||
r, size := utf8.DecodeRune(input)
|
||||
if unicode.IsPrint(r) || unicode.IsSpace(r) {
|
||||
s.buffer.WriteRune(r)
|
||||
} else {
|
||||
s.buffer.WriteString("^?")
|
||||
}
|
||||
input = input[size:]
|
||||
}
|
||||
|
||||
bufLen := s.buffer.Len()
|
||||
|
||||
// Copy all buffer content to the writer (stdout)
|
||||
n, err := s.buffer.WriteTo(s.writer)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
if int(n) != bufLen {
|
||||
return 0, errors.New("error when writing to stdout")
|
||||
}
|
||||
|
||||
return inputLen, nil
|
||||
}
|
||||
|
||||
// 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, encKeyDB map[string][]prefixSSEPair) *probe.Error {
|
||||
var reader io.Reader
|
||||
size := int64(-1)
|
||||
switch sourceURL {
|
||||
case "-":
|
||||
reader = os.Stdin
|
||||
default:
|
||||
var err *probe.Error
|
||||
// Try to stat the object, the purpose is to extract the
|
||||
// size of S3 object so we can check if the size of the
|
||||
// downloaded object is equal to the original one. FS files
|
||||
// are ignored since some of them have zero size though they
|
||||
// have contents like files under /proc.
|
||||
client, content, err := url2Stat(sourceURL, false, encKeyDB)
|
||||
if err == nil && client.GetURL().Type == objectStorage {
|
||||
size = content.Size
|
||||
}
|
||||
if reader, err = getSourceStreamFromURL(sourceURL, encKeyDB); err != nil {
|
||||
return err.Trace(sourceURL)
|
||||
}
|
||||
}
|
||||
return catOut(reader, size).Trace(sourceURL)
|
||||
}
|
||||
|
||||
// catOut reads from reader stream and writes to stdout. Also check the length of the
|
||||
// read bytes against size parameter (if not -1) and return the appropriate error
|
||||
func catOut(r io.Reader, size int64) *probe.Error {
|
||||
var n int64
|
||||
var e error
|
||||
|
||||
var stdout io.Writer
|
||||
|
||||
// In case of a user showing the object content in a terminal,
|
||||
// avoid printing control and other bad characters to avoid
|
||||
// terminal session corruption
|
||||
if terminal.IsTerminal(int(os.Stdout.Fd())) {
|
||||
stdout = newPrettyStdout(os.Stdout)
|
||||
} else {
|
||||
stdout = os.Stdout
|
||||
}
|
||||
|
||||
// Read till EOF.
|
||||
if n, e = io.Copy(stdout, r); e != nil {
|
||||
switch e := e.(type) {
|
||||
case *os.PathError:
|
||||
if e.Err == syscall.EPIPE {
|
||||
// stdout closed by the user. Gracefully exit.
|
||||
return nil
|
||||
}
|
||||
return probe.NewError(e)
|
||||
default:
|
||||
return probe.NewError(e)
|
||||
}
|
||||
}
|
||||
if size != -1 && n < size {
|
||||
return probe.NewError(UnexpectedEOF{
|
||||
TotalSize: size,
|
||||
TotalWritten: n,
|
||||
})
|
||||
}
|
||||
if size != -1 && n > size {
|
||||
return probe.NewError(UnexpectedEOF{
|
||||
TotalSize: size,
|
||||
TotalWritten: n,
|
||||
})
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// mainCat is the main entry point for cat command.
|
||||
func mainCat(ctx *cli.Context) error {
|
||||
// Parse encryption keys per command.
|
||||
encKeyDB, err := getEncKeys(ctx)
|
||||
fatalIf(err, "Unable to parse encryption keys.")
|
||||
|
||||
// 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, -1).Trace(), "Unable to read from standard input.")
|
||||
return nil
|
||||
}
|
||||
|
||||
// if Args contain `-`, we need to preserve its order specially.
|
||||
args := []string(ctx.Args())
|
||||
if ctx.Args().First() == "-" {
|
||||
for i, arg := range os.Args {
|
||||
if arg == "cat" {
|
||||
// Overwrite ctx.Args with os.Args.
|
||||
args = os.Args[i+1:]
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Convert arguments to URLs: expand alias, fix format.
|
||||
for _, url := range args {
|
||||
fatalIf(catURL(url, encKeyDB).Trace(url), "Unable to read from `"+url+"`.")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
/*
|
||||
* Minio Client (C) 2017 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestPrettyStdout(t *testing.T) {
|
||||
testCases := []struct {
|
||||
originText string
|
||||
prettyText string
|
||||
}{
|
||||
{"", ""},
|
||||
{"text", "text"},
|
||||
// Check with new lines
|
||||
{"text\r\n", "text\r\n"},
|
||||
{"\ttext\n", "\ttext\n"},
|
||||
// Print some unicode characters and check if it is not altered
|
||||
{"добро пожаловать.", "добро пожаловать."},
|
||||
// Print colored text
|
||||
{"\x1b\x5b\x33\x31\x6d\x66\x61\x69\x6c", "^?[31mfail"},
|
||||
// Print clear screen
|
||||
{"\x1b\x63", "^?c"},
|
||||
// Random data
|
||||
{"\x3d\xef\xd2\xb5", "=�ҵ"},
|
||||
}
|
||||
|
||||
for i, testCase := range testCases {
|
||||
reader := bytes.NewReader([]byte(testCase.originText))
|
||||
fakeStdout := bytes.NewBuffer([]byte(""))
|
||||
n, err := io.Copy(newPrettyStdout(fakeStdout), reader)
|
||||
if err != nil {
|
||||
t.Fatalf("Test %d: %v\n", i+1, err)
|
||||
}
|
||||
if int(n) != len(testCase.originText) {
|
||||
t.Fatalf("Test %d: copy error\n", i+1)
|
||||
}
|
||||
prettyText, err := ioutil.ReadAll(fakeStdout)
|
||||
if err != nil {
|
||||
t.Fatalf("Test %d: %v", i+1, err)
|
||||
}
|
||||
if string(prettyText) != testCase.prettyText {
|
||||
t.Fatalf("Test %d: expected output `%s`, found output `%s`", i+1, testCase.prettyText, string(prettyText))
|
||||
}
|
||||
}
|
||||
}
|
||||
+135
@@ -0,0 +1,135 @@
|
||||
/*
|
||||
* Minio Client (C) 2016 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"crypto/x509"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
)
|
||||
|
||||
// getCertsDir - return the full path of certs dir
|
||||
func getCertsDir() (string, *probe.Error) {
|
||||
p, err := getMcConfigDir()
|
||||
if err != nil {
|
||||
return "", err.Trace()
|
||||
}
|
||||
return filepath.Join(p, globalMCCertsDir), nil
|
||||
}
|
||||
|
||||
// isCertsDirExists - verify if certs directory exists.
|
||||
func isCertsDirExists() bool {
|
||||
certsDir, err := getCertsDir()
|
||||
fatalIf(err.Trace(), "Unable to determine certs folder.")
|
||||
if _, e := os.Stat(certsDir); e != nil {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// createCertsDir - create minio client certs folder
|
||||
func createCertsDir() *probe.Error {
|
||||
p, err := getCertsDir()
|
||||
if err != nil {
|
||||
return err.Trace()
|
||||
}
|
||||
if e := os.MkdirAll(p, 0700); e != nil {
|
||||
return probe.NewError(e)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// getCAsDir - return the full path of CAs dir
|
||||
func getCAsDir() (string, *probe.Error) {
|
||||
p, err := getCertsDir()
|
||||
if err != nil {
|
||||
return "", err.Trace()
|
||||
}
|
||||
return filepath.Join(p, globalMCCAsDir), nil
|
||||
}
|
||||
|
||||
// mustGetCAsDir - return the full path of CAs dir or empty string when an error occurs
|
||||
func mustGetCAsDir() string {
|
||||
p, err := getCAsDir()
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
// isCAsDirExists - verify if CAs directory exists.
|
||||
func isCAsDirExists() bool {
|
||||
CAsDir, err := getCAsDir()
|
||||
fatalIf(err.Trace(), "Unable to determine CAs folder.")
|
||||
if _, e := os.Stat(CAsDir); e != nil {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// createCAsDir - create minio client CAs folder
|
||||
func createCAsDir() *probe.Error {
|
||||
p, err := getCAsDir()
|
||||
if err != nil {
|
||||
return err.Trace()
|
||||
}
|
||||
if e := os.MkdirAll(p, 0700); e != nil {
|
||||
return probe.NewError(e)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// mustGetCAFiles - get the list of the CA certificates stored in minio config dir
|
||||
func mustGetCAFiles() (caCerts []string) {
|
||||
CAsDir := mustGetCAsDir()
|
||||
caFiles, _ := ioutil.ReadDir(CAsDir)
|
||||
for _, cert := range caFiles {
|
||||
caCerts = append(caCerts, filepath.Join(CAsDir, cert.Name()))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// mustGetSystemCertPool - return system CAs or empty pool in case of error (or windows)
|
||||
func mustGetSystemCertPool() *x509.CertPool {
|
||||
pool, err := x509.SystemCertPool()
|
||||
if err != nil {
|
||||
return x509.NewCertPool()
|
||||
}
|
||||
return pool
|
||||
}
|
||||
|
||||
// loadRootCAs fetches CA files provided in minio config and adds them to globalRootCAs
|
||||
// Currently under Windows, there is no way to load system + user CAs at the same time
|
||||
func loadRootCAs() {
|
||||
caFiles := mustGetCAFiles()
|
||||
if len(caFiles) == 0 {
|
||||
return
|
||||
}
|
||||
// Get system cert pool, and empty cert pool under Windows because it is not supported
|
||||
globalRootCAs = mustGetSystemCertPool()
|
||||
// Load custom root CAs for client requests
|
||||
for _, caFile := range caFiles {
|
||||
caCert, err := ioutil.ReadFile(caFile)
|
||||
if err != nil {
|
||||
fatalIf(probe.NewError(err), "Unable to load a CA file.")
|
||||
}
|
||||
globalRootCAs.AppendCertsFromPEM(caCert)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
/*
|
||||
* Minio Client (C) 2017 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
"hash/fnv"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/minio/mc/pkg/httptracer"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/minio/pkg/madmin"
|
||||
)
|
||||
|
||||
// newAdminFactory encloses New function with client cache.
|
||||
func newAdminFactory() func(config *Config) (*madmin.AdminClient, *probe.Error) {
|
||||
clientCache := make(map[uint32]*madmin.AdminClient)
|
||||
mutex := &sync.Mutex{}
|
||||
|
||||
// Return New function.
|
||||
return func(config *Config) (*madmin.AdminClient, *probe.Error) {
|
||||
// Creates a parsed URL.
|
||||
targetURL, e := url.Parse(config.HostURL)
|
||||
if e != nil {
|
||||
return nil, probe.NewError(e)
|
||||
}
|
||||
// By default enable HTTPs.
|
||||
useTLS := true
|
||||
if targetURL.Scheme == "http" {
|
||||
useTLS = false
|
||||
}
|
||||
|
||||
// Save if target supports virtual host style.
|
||||
hostName := targetURL.Host
|
||||
|
||||
// Generate a hash out of s3Conf.
|
||||
confHash := fnv.New32a()
|
||||
confHash.Write([]byte(hostName + config.AccessKey + config.SecretKey))
|
||||
confSum := confHash.Sum32()
|
||||
|
||||
// Lookup previous cache by hash.
|
||||
mutex.Lock()
|
||||
defer mutex.Unlock()
|
||||
var api *madmin.AdminClient
|
||||
var found bool
|
||||
if api, found = clientCache[confSum]; !found {
|
||||
// Not found. Instantiate a new minio
|
||||
var e error
|
||||
api, e = madmin.New(hostName, config.AccessKey, config.SecretKey, useTLS)
|
||||
if e != nil {
|
||||
return nil, probe.NewError(e)
|
||||
}
|
||||
|
||||
// Keep TLS config.
|
||||
tlsConfig := &tls.Config{RootCAs: globalRootCAs}
|
||||
if config.Insecure {
|
||||
tlsConfig.InsecureSkipVerify = true
|
||||
}
|
||||
|
||||
var transport http.RoundTripper = &http.Transport{
|
||||
Proxy: http.ProxyFromEnvironment,
|
||||
DialContext: (&net.Dialer{
|
||||
Timeout: 30 * time.Second,
|
||||
KeepAlive: 30 * time.Second,
|
||||
}).DialContext,
|
||||
MaxIdleConns: 100,
|
||||
IdleConnTimeout: 90 * time.Second,
|
||||
TLSHandshakeTimeout: 10 * time.Second,
|
||||
ExpectContinueTimeout: 1 * time.Second,
|
||||
TLSClientConfig: tlsConfig,
|
||||
}
|
||||
|
||||
if config.Debug {
|
||||
transport = httptracer.GetNewTraceTransport(newTraceV4(), transport)
|
||||
}
|
||||
|
||||
// Set custom transport.
|
||||
api.SetCustomTransport(transport)
|
||||
|
||||
// Set app info.
|
||||
api.SetAppInfo(config.AppName, config.AppVersion)
|
||||
|
||||
// Cache the new minio client with hash of config as key.
|
||||
clientCache[confSum] = api
|
||||
}
|
||||
|
||||
// Store the new api object.
|
||||
return api, nil
|
||||
}
|
||||
}
|
||||
|
||||
// newAdminClient gives a new client interface
|
||||
func newAdminClient(aliasedURL string) (*madmin.AdminClient, *probe.Error) {
|
||||
alias, urlStrFull, hostCfg, err := expandAlias(aliasedURL)
|
||||
if err != nil {
|
||||
return nil, err.Trace(aliasedURL)
|
||||
}
|
||||
// Verify if the aliasedURL is a real URL, fail in those cases
|
||||
// indicating the user to add alias.
|
||||
if hostCfg == nil && urlRgx.MatchString(aliasedURL) {
|
||||
return nil, errInvalidAliasedURL(aliasedURL).Trace(aliasedURL)
|
||||
}
|
||||
|
||||
if hostCfg == nil {
|
||||
return nil, probe.NewError(fmt.Errorf("The specified alias: %s not found", urlStrFull))
|
||||
}
|
||||
|
||||
s3Config := newS3Config(urlStrFull, hostCfg)
|
||||
|
||||
s3Client, err := s3AdminNew(s3Config)
|
||||
if err != nil {
|
||||
return nil, err.Trace(alias, urlStrFull)
|
||||
}
|
||||
return s3Client, nil
|
||||
}
|
||||
|
||||
// s3AdminNew returns an initialized minioAdmin structure. If debug is enabled,
|
||||
// it also enables an internal trace transport.
|
||||
var s3AdminNew = newAdminFactory()
|
||||
@@ -14,12 +14,9 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package client
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
)
|
||||
import "fmt"
|
||||
|
||||
/// Collection of standard errors
|
||||
|
||||
@@ -30,16 +27,7 @@ type APINotImplemented struct {
|
||||
}
|
||||
|
||||
func (e APINotImplemented) Error() string {
|
||||
return "‘" + e.API + "’ feature " + "is not implemented for ‘" + e.APIType + "’."
|
||||
}
|
||||
|
||||
// InvalidRange - invalid range requested
|
||||
type InvalidRange struct {
|
||||
Offset int64
|
||||
}
|
||||
|
||||
func (e InvalidRange) Error() string {
|
||||
return "Invalid range offset: ‘" + strconv.FormatInt(e.Offset, 10) + "’."
|
||||
return "`" + e.API + "` is not supported for `" + e.APIType + "`."
|
||||
}
|
||||
|
||||
// GenericBucketError - generic bucket operations error
|
||||
@@ -51,21 +39,14 @@ type GenericBucketError struct {
|
||||
type BucketDoesNotExist GenericBucketError
|
||||
|
||||
func (e BucketDoesNotExist) Error() string {
|
||||
return "Bucket ‘" + e.Bucket + "’ does not exist."
|
||||
return "Bucket `" + e.Bucket + "` does not exist."
|
||||
}
|
||||
|
||||
// BucketExists - bucket exists.
|
||||
type BucketExists GenericBucketError
|
||||
|
||||
func (e BucketExists) Error() string {
|
||||
return "Bucket ‘" + e.Bucket + "’ exists."
|
||||
}
|
||||
|
||||
// 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."
|
||||
return "Bucket `" + e.Bucket + "` exists."
|
||||
}
|
||||
|
||||
// BucketNameEmpty - bucket name empty (http://goo.gl/wJlzDz)
|
||||
@@ -75,10 +56,13 @@ func (e BucketNameEmpty) Error() string {
|
||||
return "Bucket name cannot be empty."
|
||||
}
|
||||
|
||||
// GenericObjectError - generic object operations error
|
||||
type GenericObjectError struct {
|
||||
// BucketInvalid - bucket name invalid.
|
||||
type BucketInvalid struct {
|
||||
Bucket string
|
||||
Object string
|
||||
}
|
||||
|
||||
func (e BucketInvalid) Error() string {
|
||||
return "Bucket name " + e.Bucket + " not valid."
|
||||
}
|
||||
|
||||
// ObjectAlreadyExists - typed return for MethodNotAllowed
|
||||
@@ -87,21 +71,32 @@ type ObjectAlreadyExists struct {
|
||||
}
|
||||
|
||||
func (e ObjectAlreadyExists) Error() string {
|
||||
return "Object ‘" + e.Object + "’ already exists."
|
||||
return "Object `" + e.Object + "` already exists."
|
||||
}
|
||||
|
||||
// InvalidObjectName - object requested is invalid
|
||||
type InvalidObjectName GenericObjectError
|
||||
// ObjectAlreadyExistsAsDirectory - typed return for XMinioObjectExistsAsDirectory
|
||||
type ObjectAlreadyExistsAsDirectory struct {
|
||||
Object string
|
||||
}
|
||||
|
||||
func (e InvalidObjectName) Error() string {
|
||||
return "Object ‘" + e.Object + "’ at ‘" + e.Bucket + "’ is invalid."
|
||||
func (e ObjectAlreadyExistsAsDirectory) Error() string {
|
||||
return "Object `" + e.Object + "` already exists as directory."
|
||||
}
|
||||
|
||||
// ObjectOnGlacier - object is of storage class glacier.
|
||||
type ObjectOnGlacier struct {
|
||||
Object string
|
||||
}
|
||||
|
||||
func (e ObjectOnGlacier) Error() string {
|
||||
return "Object `" + e.Object + "` is on Glacier storage."
|
||||
}
|
||||
|
||||
// BucketNameTopLevel - generic error
|
||||
type BucketNameTopLevel struct{}
|
||||
|
||||
func (e BucketNameTopLevel) Error() string {
|
||||
return "Buckets can only be created at the top level."
|
||||
return "Buckets or prefixes can only be created with `/` suffix."
|
||||
}
|
||||
|
||||
// GenericFileError - generic file error.
|
||||
@@ -113,35 +108,35 @@ type GenericFileError struct {
|
||||
type PathNotFound GenericFileError
|
||||
|
||||
func (e PathNotFound) Error() string {
|
||||
return "Requested file ‘" + e.Path + "’ not found"
|
||||
return "Requested file `" + e.Path + "` not found"
|
||||
}
|
||||
|
||||
// PathIsNotRegular (ENOTREG) - file is not a regular file.
|
||||
type PathIsNotRegular GenericFileError
|
||||
|
||||
func (e PathIsNotRegular) Error() string {
|
||||
return "Requested file ‘" + e.Path + "’ is not a regular file."
|
||||
return "Requested file `" + e.Path + "` is not a regular file."
|
||||
}
|
||||
|
||||
// PathInsufficientPermission (EPERM) - permission denied.
|
||||
type PathInsufficientPermission GenericFileError
|
||||
|
||||
func (e PathInsufficientPermission) Error() string {
|
||||
return "Insufficient permissions to access this file ‘" + e.Path + "’"
|
||||
return "Insufficient permissions to access this file `" + e.Path + "`"
|
||||
}
|
||||
|
||||
// BrokenSymlink (ENOTENT) - file has broken symlink.
|
||||
type BrokenSymlink GenericFileError
|
||||
|
||||
func (e BrokenSymlink) Error() string {
|
||||
return "Requested file ‘" + e.Path + "’ has broken symlink"
|
||||
return "Requested file `" + e.Path + "` has broken symlink"
|
||||
}
|
||||
|
||||
// TooManyLevelsSymlink (ELOOP) - file has too many levels of symlinks.
|
||||
type TooManyLevelsSymlink GenericFileError
|
||||
|
||||
func (e TooManyLevelsSymlink) Error() string {
|
||||
return "Requested file ‘" + e.Path + "’ has too many levels of symlinks"
|
||||
return "Requested file `" + e.Path + "` has too many levels of symlinks"
|
||||
}
|
||||
|
||||
// EmptyPath (EINVAL) - invalid argument.
|
||||
@@ -155,7 +150,7 @@ func (e EmptyPath) Error() string {
|
||||
type ObjectMissing struct{}
|
||||
|
||||
func (e ObjectMissing) Error() string {
|
||||
return "Object key is missing, object key cannot be empty"
|
||||
return "Object does not exist"
|
||||
}
|
||||
|
||||
// UnexpectedShortWrite - write wrote less bytes than expected.
|
||||
@@ -165,7 +160,7 @@ type UnexpectedShortWrite struct {
|
||||
}
|
||||
|
||||
func (e UnexpectedShortWrite) Error() string {
|
||||
msg := fmt.Sprintf("Wrote less data than requested. Expected ‘%d’ bytes, but only wrote ‘%d’ bytes.", e.InputSize, e.WriteSize)
|
||||
msg := fmt.Sprintf("Wrote less data than requested. Expected `%d` bytes, but only wrote `%d` bytes.", e.InputSize, e.WriteSize)
|
||||
return msg
|
||||
}
|
||||
|
||||
@@ -176,7 +171,7 @@ type UnexpectedEOF struct {
|
||||
}
|
||||
|
||||
func (e UnexpectedEOF) Error() string {
|
||||
msg := fmt.Sprintf("Input reader closed pre-maturely. Expected ‘%d’ bytes, but only received ‘%d’ bytes.", e.TotalSize, e.TotalWritten)
|
||||
msg := fmt.Sprintf("Input reader closed pre-maturely. Expected `%d` bytes, but only received `%d` bytes.", e.TotalSize, e.TotalWritten)
|
||||
return msg
|
||||
}
|
||||
|
||||
@@ -184,6 +179,15 @@ func (e UnexpectedEOF) Error() string {
|
||||
type UnexpectedExcessRead UnexpectedEOF
|
||||
|
||||
func (e UnexpectedExcessRead) Error() string {
|
||||
msg := fmt.Sprintf("Received excess data on input reader. Expected only ‘%d’ bytes, but received ‘%d’ bytes.", e.TotalSize, e.TotalWritten)
|
||||
msg := fmt.Sprintf("Received excess data on input reader. Expected only `%d` bytes, but received `%d` bytes.", e.TotalSize, e.TotalWritten)
|
||||
return msg
|
||||
}
|
||||
|
||||
// SameFile - source and destination are same files.
|
||||
type SameFile struct {
|
||||
Source, Destination string
|
||||
}
|
||||
|
||||
func (e SameFile) Error() string {
|
||||
return fmt.Sprintf("'%s' and '%s' are the same file", e.Source, e.Destination)
|
||||
}
|
||||
+1057
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,84 @@
|
||||
// +build darwin
|
||||
|
||||
/*
|
||||
* Minio Client (C) 2017 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this fs except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/pkg/xattr"
|
||||
"github.com/rjeczalik/notify"
|
||||
)
|
||||
|
||||
var (
|
||||
// EventTypePut contains the notify events that will cause a put (writer)
|
||||
EventTypePut = []notify.Event{notify.Create, notify.Write, notify.Rename}
|
||||
// EventTypeDelete contains the notify events that will cause a delete (remove)
|
||||
EventTypeDelete = []notify.Event{notify.Remove}
|
||||
// EventTypeGet contains the notify events that will cause a get (read)
|
||||
EventTypeGet = []notify.Event{} // On macOS, FreeBSD, Solaris this is not available.
|
||||
)
|
||||
|
||||
// IsGetEvent checks if the event return is a get event.
|
||||
func IsGetEvent(event notify.Event) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// IsPutEvent checks if the event returned is a put event
|
||||
func IsPutEvent(event notify.Event) bool {
|
||||
for _, ev := range EventTypePut {
|
||||
if event&ev != 0 {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// IsDeleteEvent checks if the event returned is a delete event
|
||||
func IsDeleteEvent(event notify.Event) bool {
|
||||
return event¬ify.Remove != 0
|
||||
}
|
||||
|
||||
// getXAttr fetches the extended attribute for a particular key on
|
||||
// file
|
||||
func getXAttr(path, key string) (string, error) {
|
||||
data, e := xattr.Get(path, key)
|
||||
if e != nil {
|
||||
return "", e
|
||||
}
|
||||
return string(data), nil
|
||||
}
|
||||
|
||||
// getAllXattrs returns the extended attributes for a file if supported
|
||||
// by the OS
|
||||
func getAllXattrs(path string) (map[string]string, error) {
|
||||
if !xattr.Supported(path) {
|
||||
return nil, nil
|
||||
}
|
||||
xMetadata := make(map[string]string)
|
||||
list, e := xattr.List(path)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
for _, key := range list {
|
||||
xMetadata[key], e = getXAttr(path, key)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
|
||||
}
|
||||
return xMetadata, nil
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
// +build freebsd
|
||||
|
||||
/*
|
||||
* Minio Client (C) 2017 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this fs except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/pkg/xattr"
|
||||
"github.com/rjeczalik/notify"
|
||||
)
|
||||
|
||||
var (
|
||||
// EventTypePut contains the notify events that will cause a put (writer)
|
||||
EventTypePut = []notify.Event{notify.Create, notify.Write, notify.Rename}
|
||||
// EventTypeDelete contains the notify events that will cause a delete (remove)
|
||||
EventTypeDelete = []notify.Event{notify.Remove}
|
||||
// EventTypeGet contains the notify events that will cause a get (read)
|
||||
EventTypeGet = []notify.Event{} // On macOS, FreeBSD, Solaris this is not available.
|
||||
)
|
||||
|
||||
// IsGetEvent checks if the event return is a get event.
|
||||
func IsGetEvent(event notify.Event) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// IsPutEvent checks if the event returned is a put event
|
||||
func IsPutEvent(event notify.Event) bool {
|
||||
for _, ev := range EventTypePut {
|
||||
if event&ev != 0 {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// IsDeleteEvent checks if the event returned is a delete event
|
||||
func IsDeleteEvent(event notify.Event) bool {
|
||||
return event¬ify.Remove != 0
|
||||
}
|
||||
|
||||
// getXAttr fetches the extended attribute for a particular key on
|
||||
// file
|
||||
func getXAttr(path, key string) (string, error) {
|
||||
data, e := xattr.Get(path, key)
|
||||
if e != nil {
|
||||
return "", e
|
||||
}
|
||||
return string(data), nil
|
||||
}
|
||||
|
||||
// getAllXattrs returns the extended attributes for a file if supported
|
||||
// by the OS
|
||||
func getAllXattrs(path string) (map[string]string, error) {
|
||||
if !xattr.Supported(path) {
|
||||
return nil, nil
|
||||
}
|
||||
xMetadata := make(map[string]string)
|
||||
list, e := xattr.List(path)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
for _, key := range list {
|
||||
xMetadata[key], e = getXAttr(path, key)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
|
||||
}
|
||||
return xMetadata, nil
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
// +build linux
|
||||
|
||||
/*
|
||||
* Minio Client (C) 2015, 2016, 2017 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this fs except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
"strings"
|
||||
|
||||
"github.com/pkg/xattr"
|
||||
"github.com/rjeczalik/notify"
|
||||
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
var (
|
||||
// EventTypePut contains the notify events that will cause a put (write)
|
||||
EventTypePut = []notify.Event{notify.InCloseWrite | notify.InMovedTo}
|
||||
// EventTypeDelete contains the notify events that will cause a delete (remove)
|
||||
EventTypeDelete = []notify.Event{notify.InDelete | notify.InDeleteSelf | notify.InMovedFrom}
|
||||
// EventTypeGet contains the notify events that will cause a get (read)
|
||||
EventTypeGet = []notify.Event{notify.InAccess | notify.InOpen}
|
||||
)
|
||||
|
||||
// IsGetEvent checks if the event return is a get event.
|
||||
func IsGetEvent(event notify.Event) bool {
|
||||
for _, ev := range EventTypeGet {
|
||||
if event&ev != 0 {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// IsPutEvent checks if the event returned is a put event
|
||||
func IsPutEvent(event notify.Event) bool {
|
||||
for _, ev := range EventTypePut {
|
||||
if event&ev != 0 {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// IsDeleteEvent checks if the event returned is a delete event
|
||||
func IsDeleteEvent(event notify.Event) bool {
|
||||
for _, ev := range EventTypeDelete {
|
||||
if event&ev != 0 {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// getXAttr fetches the extended attribute for a particular key on
|
||||
// file
|
||||
func getXAttr(path, key string) (string, error) {
|
||||
data, e := xattr.Get(path, key)
|
||||
if e != nil {
|
||||
return "", e
|
||||
}
|
||||
if utf8.ValidString(string(data)) {
|
||||
return string(data), nil
|
||||
}
|
||||
return hex.EncodeToString(data), nil
|
||||
}
|
||||
|
||||
// getAllXattrs returns the extended attributes for a file if supported
|
||||
// by the OS
|
||||
func getAllXattrs(path string) (map[string]string, error) {
|
||||
if !xattr.Supported(path) {
|
||||
return nil, nil
|
||||
}
|
||||
xMetadata := make(map[string]string)
|
||||
list, e := xattr.List(path)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
for _, key := range list {
|
||||
// filter out system specific xattr
|
||||
if strings.HasPrefix(key, "system.") {
|
||||
continue
|
||||
}
|
||||
xMetadata[key], e = getXAttr(path, key)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
}
|
||||
return xMetadata, nil
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
// +build solaris openbsd
|
||||
|
||||
/*
|
||||
* Minio Client (C) 2015, 2016, 2017 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this fs except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import "github.com/rjeczalik/notify"
|
||||
|
||||
var (
|
||||
// EventTypePut contains the notify events that will cause a put (writer)
|
||||
EventTypePut = []notify.Event{notify.Create, notify.Write, notify.Rename}
|
||||
// EventTypeDelete contains the notify events that will cause a delete (remove)
|
||||
EventTypeDelete = []notify.Event{notify.Remove}
|
||||
// EventTypeGet contains the notify events that will cause a get (read)
|
||||
EventTypeGet = []notify.Event{} // On macOS, FreeBSD, Solaris this is not available.
|
||||
)
|
||||
|
||||
// IsGetEvent checks if the event return is a get event.
|
||||
func IsGetEvent(event notify.Event) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// IsPutEvent checks if the event returned is a put event
|
||||
func IsPutEvent(event notify.Event) bool {
|
||||
for _, ev := range EventTypePut {
|
||||
if event&ev != 0 {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// IsDeleteEvent checks if the event returned is a delete event
|
||||
func IsDeleteEvent(event notify.Event) bool {
|
||||
return event¬ify.Remove != 0
|
||||
}
|
||||
|
||||
// getAtllXAttrs returns the extended attributes for a file if supported
|
||||
// by the OS
|
||||
func getAllXattrs(path string) (map[string]string, error) {
|
||||
return nil, nil
|
||||
}
|
||||
@@ -14,61 +14,58 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package fs_test
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"runtime"
|
||||
|
||||
"github.com/minio/mc/pkg/client"
|
||||
"github.com/minio/mc/pkg/client/fs"
|
||||
. "gopkg.in/check.v1"
|
||||
)
|
||||
|
||||
func Test(t *testing.T) { TestingT(t) }
|
||||
|
||||
type MySuite struct{}
|
||||
|
||||
var _ = Suite(&MySuite{})
|
||||
|
||||
// Test list files in a folder.
|
||||
func (s *MySuite) TestList(c *C) {
|
||||
func (s *TestSuite) TestList(c *C) {
|
||||
root, e := ioutil.TempDir(os.TempDir(), "fs-")
|
||||
c.Assert(e, IsNil)
|
||||
defer os.RemoveAll(root)
|
||||
|
||||
// Create multiple files.
|
||||
objectPath := filepath.Join(root, "object1")
|
||||
fsClient, err := fs.New(objectPath)
|
||||
fsClient, err := fsNew(objectPath)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
data := "hello"
|
||||
|
||||
reader := bytes.NewReader([]byte(data))
|
||||
var n int64
|
||||
n, err = fsClient.Put(reader, int64(len(data)), "application/octet-stream", nil)
|
||||
n, err = fsClient.Put(context.Background(), reader, int64(len(data)), map[string]string{
|
||||
"Content-Type": "application/octet-stream",
|
||||
}, nil, "")
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(n, Equals, int64(len(data)))
|
||||
|
||||
objectPath = filepath.Join(root, "object2")
|
||||
fsClient, err = fs.New(objectPath)
|
||||
fsClient, err = fsNew(objectPath)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
reader = bytes.NewReader([]byte(data))
|
||||
n, err = fsClient.Put(reader, int64(len(data)), "application/octet-stream", nil)
|
||||
n, err = fsClient.Put(context.Background(), reader, int64(len(data)), map[string]string{
|
||||
"Content-Type": "application/octet-stream",
|
||||
}, nil, "")
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(n, Equals, int64(len(data)))
|
||||
|
||||
fsClient, err = fs.New(root)
|
||||
fsClient, err = fsNew(root)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
// Verify previously create files and list them.
|
||||
var contents []*client.Content
|
||||
for content := range fsClient.List(false, false) {
|
||||
var contents []*clientContent
|
||||
for content := range fsClient.List(false, false, DirNone) {
|
||||
if content.Err != nil {
|
||||
err = content.Err
|
||||
break
|
||||
@@ -81,20 +78,22 @@ func (s *MySuite) TestList(c *C) {
|
||||
|
||||
// Create another file.
|
||||
objectPath = filepath.Join(root, "test1/newObject1")
|
||||
fsClient, err = fs.New(objectPath)
|
||||
fsClient, err = fsNew(objectPath)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
reader = bytes.NewReader([]byte(data))
|
||||
n, err = fsClient.Put(reader, int64(len(data)), "application/octet-stream", nil)
|
||||
n, err = fsClient.Put(context.Background(), reader, int64(len(data)), map[string]string{
|
||||
"Content-Type": "application/octet-stream",
|
||||
}, nil, "")
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(n, Equals, int64(len(data)))
|
||||
|
||||
fsClient, err = fs.New(root)
|
||||
fsClient, err = fsNew(root)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
contents = nil
|
||||
// List non recursive to list only top level files.
|
||||
for content := range fsClient.List(false, false) {
|
||||
for content := range fsClient.List(false, false, DirNone) {
|
||||
if content.Err != nil {
|
||||
err = content.Err
|
||||
break
|
||||
@@ -105,12 +104,12 @@ func (s *MySuite) TestList(c *C) {
|
||||
c.Assert(len(contents), Equals, 1)
|
||||
c.Assert(contents[0].Type.IsDir(), Equals, true)
|
||||
|
||||
fsClient, err = fs.New(root)
|
||||
fsClient, err = fsNew(root)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
contents = nil
|
||||
// List recursively all files and verify.
|
||||
for content := range fsClient.List(true, false) {
|
||||
for content := range fsClient.List(true, false, DirNone) {
|
||||
if content.Err != nil {
|
||||
err = content.Err
|
||||
break
|
||||
@@ -119,7 +118,7 @@ func (s *MySuite) TestList(c *C) {
|
||||
}
|
||||
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(len(contents), Equals, 5)
|
||||
c.Assert(len(contents), Equals, 3)
|
||||
|
||||
var regularFiles int
|
||||
var regularDirs int
|
||||
@@ -134,94 +133,149 @@ func (s *MySuite) TestList(c *C) {
|
||||
continue
|
||||
}
|
||||
}
|
||||
c.Assert(regularDirs, Equals, 2)
|
||||
c.Assert(regularDirs, Equals, 0)
|
||||
c.Assert(regularFiles, Equals, 3)
|
||||
|
||||
// Create an ignored file and list to verify if its ignored.
|
||||
objectPath = filepath.Join(root, "test1/.DS_Store")
|
||||
fsClient, err = fsNew(objectPath)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
reader = bytes.NewReader([]byte(data))
|
||||
n, err = fsClient.Put(context.Background(), reader, int64(len(data)), map[string]string{
|
||||
"Content-Type": "application/octet-stream",
|
||||
}, nil, "")
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(n, Equals, int64(len(data)))
|
||||
|
||||
fsClient, err = fsNew(root)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
contents = nil
|
||||
// List recursively all files and verify.
|
||||
for content := range fsClient.List(true, false, DirNone) {
|
||||
if content.Err != nil {
|
||||
err = content.Err
|
||||
break
|
||||
}
|
||||
contents = append(contents, content)
|
||||
}
|
||||
|
||||
c.Assert(err, IsNil)
|
||||
switch runtime.GOOS {
|
||||
case "darwin":
|
||||
c.Assert(len(contents), Equals, 3)
|
||||
default:
|
||||
c.Assert(len(contents), Equals, 4)
|
||||
}
|
||||
|
||||
regularFiles = 0
|
||||
// Test number of expected files.
|
||||
for _, content := range contents {
|
||||
if content.Type.IsRegular() {
|
||||
regularFiles++
|
||||
continue
|
||||
}
|
||||
}
|
||||
switch runtime.GOOS {
|
||||
case "darwin":
|
||||
c.Assert(regularFiles, Equals, 3)
|
||||
default:
|
||||
c.Assert(regularFiles, Equals, 4)
|
||||
}
|
||||
}
|
||||
|
||||
// Test put bucket aka 'mkdir()' operation.
|
||||
func (s *MySuite) TestPutBucket(c *C) {
|
||||
func (s *TestSuite) TestPutBucket(c *C) {
|
||||
root, e := ioutil.TempDir(os.TempDir(), "fs-")
|
||||
c.Assert(e, IsNil)
|
||||
defer os.RemoveAll(root)
|
||||
|
||||
bucketPath := filepath.Join(root, "bucket")
|
||||
fsClient, err := fs.New(bucketPath)
|
||||
fsClient, err := fsNew(bucketPath)
|
||||
c.Assert(err, IsNil)
|
||||
err = fsClient.MakeBucket("us-east-1")
|
||||
err = fsClient.MakeBucket("us-east-1", true)
|
||||
c.Assert(err, IsNil)
|
||||
}
|
||||
|
||||
// Test stat bucket aka 'stat()' operation.
|
||||
func (s *MySuite) TestStatBucket(c *C) {
|
||||
func (s *TestSuite) TestStatBucket(c *C) {
|
||||
root, e := ioutil.TempDir(os.TempDir(), "fs-")
|
||||
c.Assert(e, IsNil)
|
||||
defer os.RemoveAll(root)
|
||||
|
||||
bucketPath := filepath.Join(root, "bucket")
|
||||
|
||||
fsClient, err := fs.New(bucketPath)
|
||||
fsClient, err := fsNew(bucketPath)
|
||||
c.Assert(err, IsNil)
|
||||
err = fsClient.MakeBucket("us-east-1")
|
||||
err = fsClient.MakeBucket("us-east-1", true)
|
||||
c.Assert(err, IsNil)
|
||||
_, err = fsClient.Stat()
|
||||
_, err = fsClient.Stat(false, false, "")
|
||||
c.Assert(err, IsNil)
|
||||
}
|
||||
|
||||
// Test bucket acl fails for directories.
|
||||
func (s *MySuite) TestBucketACLFails(c *C) {
|
||||
func (s *TestSuite) TestBucketACLFails(c *C) {
|
||||
root, e := ioutil.TempDir(os.TempDir(), "fs-")
|
||||
c.Assert(e, IsNil)
|
||||
defer os.RemoveAll(root)
|
||||
|
||||
bucketPath := filepath.Join(root, "bucket")
|
||||
fsClient, err := fs.New(bucketPath)
|
||||
fsClient, err := fsNew(bucketPath)
|
||||
c.Assert(err, IsNil)
|
||||
err = fsClient.MakeBucket("us-east-1")
|
||||
err = fsClient.MakeBucket("us-east-1", true)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
err = fsClient.SetBucketAccess("private")
|
||||
c.Assert(err, Not(IsNil))
|
||||
// On windows setting permissions is not supported.
|
||||
if runtime.GOOS != "windows" {
|
||||
err = fsClient.SetAccess("readonly")
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
_, err = fsClient.GetBucketAccess()
|
||||
c.Assert(err, Not(IsNil))
|
||||
_, err = fsClient.GetAccess()
|
||||
c.Assert(err, IsNil)
|
||||
}
|
||||
}
|
||||
|
||||
// Test creating a file.
|
||||
func (s *MySuite) TestPut(c *C) {
|
||||
func (s *TestSuite) TestPut(c *C) {
|
||||
root, e := ioutil.TempDir(os.TempDir(), "fs-")
|
||||
c.Assert(e, IsNil)
|
||||
defer os.RemoveAll(root)
|
||||
|
||||
objectPath := filepath.Join(root, "object")
|
||||
fsClient, err := fs.New(objectPath)
|
||||
fsClient, err := fsNew(objectPath)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
data := "hello"
|
||||
reader := bytes.NewReader([]byte(data))
|
||||
var n int64
|
||||
n, err = fsClient.Put(reader, int64(len(data)), "application/octet-stream", nil)
|
||||
n, err = fsClient.Put(context.Background(), reader, int64(len(data)), map[string]string{
|
||||
"Content-Type": "application/octet-stream",
|
||||
}, nil, "")
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(n, Equals, int64(len(data)))
|
||||
}
|
||||
|
||||
// Test read a file.
|
||||
func (s *MySuite) TestGet(c *C) {
|
||||
func (s *TestSuite) TestGet(c *C) {
|
||||
root, e := ioutil.TempDir(os.TempDir(), "fs-")
|
||||
c.Assert(e, IsNil)
|
||||
defer os.RemoveAll(root)
|
||||
|
||||
objectPath := filepath.Join(root, "object")
|
||||
fsClient, err := fs.New(objectPath)
|
||||
fsClient, err := fsNew(objectPath)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
data := "hello"
|
||||
var reader io.Reader
|
||||
reader = bytes.NewReader([]byte(data))
|
||||
n, err := fsClient.Put(reader, int64(len(data)), "application/octet-stream", nil)
|
||||
n, err := fsClient.Put(context.Background(), reader, int64(len(data)), map[string]string{
|
||||
"Content-Type": "application/octet-stream",
|
||||
}, nil, "")
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(n, Equals, int64(len(data)))
|
||||
|
||||
reader, err = fsClient.Get()
|
||||
reader, err = fsClient.Get("")
|
||||
c.Assert(err, IsNil)
|
||||
var results bytes.Buffer
|
||||
_, e = io.Copy(&results, reader)
|
||||
@@ -231,23 +285,25 @@ func (s *MySuite) TestGet(c *C) {
|
||||
}
|
||||
|
||||
// Test get range in a file.
|
||||
func (s *MySuite) TestGetRange(c *C) {
|
||||
func (s *TestSuite) TestGetRange(c *C) {
|
||||
root, e := ioutil.TempDir(os.TempDir(), "fs-")
|
||||
c.Assert(e, IsNil)
|
||||
defer os.RemoveAll(root)
|
||||
|
||||
objectPath := filepath.Join(root, "object")
|
||||
fsClient, err := fs.New(objectPath)
|
||||
fsClient, err := fsNew(objectPath)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
data := "hello world"
|
||||
var reader io.Reader
|
||||
reader = bytes.NewReader([]byte(data))
|
||||
n, err := fsClient.Put(reader, int64(len(data)), "application/octet-stream", nil)
|
||||
n, err := fsClient.Put(context.Background(), reader, int64(len(data)), map[string]string{
|
||||
"Content-Type": "application/octet-stream",
|
||||
}, nil, "")
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(n, Equals, int64(len(data)))
|
||||
|
||||
reader, err = fsClient.Get()
|
||||
reader, err = fsClient.Get("")
|
||||
c.Assert(err, IsNil)
|
||||
var results bytes.Buffer
|
||||
buf := make([]byte, 5)
|
||||
@@ -260,23 +316,50 @@ func (s *MySuite) TestGetRange(c *C) {
|
||||
}
|
||||
|
||||
// Test stat file.
|
||||
func (s *MySuite) TestStatObject(c *C) {
|
||||
func (s *TestSuite) TestStatObject(c *C) {
|
||||
root, e := ioutil.TempDir(os.TempDir(), "fs-")
|
||||
c.Assert(e, IsNil)
|
||||
defer os.RemoveAll(root)
|
||||
|
||||
objectPath := filepath.Join(root, "object")
|
||||
fsClient, err := fs.New(objectPath)
|
||||
fsClient, err := fsNew(objectPath)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
data := "hello"
|
||||
dataLen := len(data)
|
||||
reader := bytes.NewReader([]byte(data))
|
||||
n, err := fsClient.Put(reader, int64(dataLen), "application/octet-stream", nil)
|
||||
n, err := fsClient.Put(context.Background(), reader, int64(dataLen), map[string]string{
|
||||
"Content-Type": "application/octet-stream",
|
||||
}, nil, "")
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(n, Equals, int64(len(data)))
|
||||
|
||||
content, err := fsClient.Stat()
|
||||
content, err := fsClient.Stat(false, false, "")
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(content.Size, Equals, int64(dataLen))
|
||||
}
|
||||
|
||||
// Test copy.
|
||||
func (s *TestSuite) TestCopy(c *C) {
|
||||
root, e := ioutil.TempDir(os.TempDir(), "fs-")
|
||||
c.Assert(e, IsNil)
|
||||
defer os.RemoveAll(root)
|
||||
sourcePath := filepath.Join(root, "source")
|
||||
targetPath := filepath.Join(root, "target")
|
||||
fsClientTarget, err := fsNew(targetPath)
|
||||
c.Assert(err, IsNil)
|
||||
fsClientSource, err := fsNew(sourcePath)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
data := "hello world"
|
||||
var reader io.Reader
|
||||
reader = bytes.NewReader([]byte(data))
|
||||
n, err := fsClientSource.Put(context.Background(), reader, int64(len(data)), map[string]string{
|
||||
"Content-Type": "application/octet-stream",
|
||||
}, nil, "")
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(n, Equals, int64(len(data)))
|
||||
|
||||
err = fsClientTarget.Copy(sourcePath, int64(len(data)), nil, "", "")
|
||||
c.Assert(err, IsNil)
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
// +build windows
|
||||
|
||||
/*
|
||||
* Minio Client (C) 2017 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this fs except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import "github.com/rjeczalik/notify"
|
||||
|
||||
var (
|
||||
// EventTypePut contains the notify events that will cause a put (writer)
|
||||
EventTypePut = []notify.Event{notify.Create, notify.Write, notify.Rename}
|
||||
// EventTypeDelete contains the notify events that will cause a delete (remove)
|
||||
EventTypeDelete = []notify.Event{notify.Remove}
|
||||
// EventTypeGet contains the notify events that will cause a get (read)
|
||||
EventTypeGet = []notify.Event{notify.FileNotifyChangeLastAccess}
|
||||
)
|
||||
|
||||
// IsGetEvent checks if the event return is a get event.
|
||||
func IsGetEvent(event notify.Event) bool {
|
||||
return event¬ify.FileNotifyChangeLastAccess != 0
|
||||
}
|
||||
|
||||
// IsPutEvent checks if the event returned is a put event
|
||||
func IsPutEvent(event notify.Event) bool {
|
||||
for _, ev := range EventTypePut {
|
||||
if event&ev != 0 {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// IsDeleteEvent checks if the event returned is a delete event
|
||||
func IsDeleteEvent(event notify.Event) bool {
|
||||
return event¬ify.Remove != 0
|
||||
}
|
||||
|
||||
// getAllXattrs returns the extended attributes for a file if supported
|
||||
// by the OS
|
||||
func getAllXattrs(path string) (map[string]string, error) {
|
||||
return nil, nil
|
||||
}
|
||||
@@ -14,7 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package s3
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
@@ -25,16 +25,16 @@ import (
|
||||
"github.com/minio/mc/pkg/httptracer"
|
||||
)
|
||||
|
||||
// TraceV2 - tracing structure
|
||||
type TraceV2 struct{}
|
||||
// traceV2 - tracing structure for signature version '2'.
|
||||
type traceV2 struct{}
|
||||
|
||||
// NewTraceV2 - initialize Trace structure
|
||||
func NewTraceV2() httptracer.HTTPTracer {
|
||||
return TraceV2{}
|
||||
// newTraceV2 - initialize Trace structure
|
||||
func newTraceV2() httptracer.HTTPTracer {
|
||||
return traceV2{}
|
||||
}
|
||||
|
||||
// Request - Trace HTTP Request
|
||||
func (t TraceV2) Request(req *http.Request) (err error) {
|
||||
func (t traceV2) Request(req *http.Request) (err error) {
|
||||
origAuth := req.Header.Get("Authorization")
|
||||
|
||||
if strings.TrimSpace(origAuth) != "" {
|
||||
@@ -57,19 +57,23 @@ func (t TraceV2) Request(req *http.Request) (err error) {
|
||||
}
|
||||
|
||||
// Response - Trace HTTP Response
|
||||
func (t TraceV2) Response(res *http.Response) (err error) {
|
||||
var resTrace []byte
|
||||
func (t traceV2) Response(resp *http.Response) (err error) {
|
||||
var respTrace []byte
|
||||
// For errors we make sure to dump response body as well.
|
||||
if res.StatusCode != http.StatusOK &&
|
||||
res.StatusCode != http.StatusPartialContent &&
|
||||
res.StatusCode != http.StatusNoContent {
|
||||
resTrace, err = httputil.DumpResponse(res, true)
|
||||
if resp.StatusCode != http.StatusOK &&
|
||||
resp.StatusCode != http.StatusPartialContent &&
|
||||
resp.StatusCode != http.StatusNoContent {
|
||||
respTrace, err = httputil.DumpResponse(resp, true)
|
||||
} else {
|
||||
// Only display header
|
||||
resTrace, err = httputil.DumpResponse(res, false)
|
||||
respTrace, err = httputil.DumpResponse(resp, false)
|
||||
}
|
||||
if err == nil {
|
||||
console.Debug(string(resTrace))
|
||||
console.Debug(string(respTrace))
|
||||
}
|
||||
|
||||
if globalInsecure && resp.TLS != nil {
|
||||
dumpTLSCertificates(resp.TLS)
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
@@ -14,7 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package s3
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
@@ -26,16 +26,16 @@ import (
|
||||
"github.com/minio/mc/pkg/httptracer"
|
||||
)
|
||||
|
||||
// TraceV4 - tracing structure
|
||||
type TraceV4 struct{}
|
||||
// traceV4 - tracing structure for signature version '4'.
|
||||
type traceV4 struct{}
|
||||
|
||||
// NewTraceV4 - initialize Trace structure
|
||||
func NewTraceV4() httptracer.HTTPTracer {
|
||||
return TraceV4{}
|
||||
// newTraceV4 - initialize Trace structure
|
||||
func newTraceV4() httptracer.HTTPTracer {
|
||||
return traceV4{}
|
||||
}
|
||||
|
||||
// Request - Trace HTTP Request
|
||||
func (t TraceV4) Request(req *http.Request) (err error) {
|
||||
func (t traceV4) Request(req *http.Request) (err error) {
|
||||
origAuth := req.Header.Get("Authorization")
|
||||
|
||||
if strings.TrimSpace(origAuth) != "" {
|
||||
@@ -66,19 +66,23 @@ func (t TraceV4) Request(req *http.Request) (err error) {
|
||||
}
|
||||
|
||||
// Response - Trace HTTP Response
|
||||
func (t TraceV4) Response(res *http.Response) (err error) {
|
||||
var resTrace []byte
|
||||
func (t traceV4) Response(resp *http.Response) (err error) {
|
||||
var respTrace []byte
|
||||
// For errors we make sure to dump response body as well.
|
||||
if res.StatusCode != http.StatusOK &&
|
||||
res.StatusCode != http.StatusPartialContent &&
|
||||
res.StatusCode != http.StatusNoContent {
|
||||
resTrace, err = httputil.DumpResponse(res, true)
|
||||
if resp.StatusCode != http.StatusOK &&
|
||||
resp.StatusCode != http.StatusPartialContent &&
|
||||
resp.StatusCode != http.StatusNoContent {
|
||||
respTrace, err = httputil.DumpResponse(resp, true)
|
||||
} else {
|
||||
// Only display header
|
||||
resTrace, err = httputil.DumpResponse(res, false)
|
||||
respTrace, err = httputil.DumpResponse(resp, false)
|
||||
}
|
||||
if err == nil {
|
||||
console.Debug(string(resTrace))
|
||||
console.Debug(string(respTrace))
|
||||
}
|
||||
|
||||
if globalInsecure && resp.TLS != nil {
|
||||
dumpTLSCertificates(resp.TLS)
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
+1788
File diff suppressed because it is too large
Load Diff
@@ -14,19 +14,16 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package s3
|
||||
package cmd
|
||||
|
||||
// bucketHandler is an http.Handler that verifies bucket responses and validates incoming requests
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/minio/mc/pkg/client"
|
||||
|
||||
. "gopkg.in/check.v1"
|
||||
)
|
||||
@@ -60,13 +57,6 @@ func (h bucketHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
case r.Method == "PUT":
|
||||
switch {
|
||||
case r.URL.Path == h.resource:
|
||||
// Handler for incoming SetBucketACL request.
|
||||
_, ok := r.URL.Query()["acl"]
|
||||
if ok {
|
||||
if r.Header.Get("x-amz-acl") != "public-read-write" {
|
||||
w.WriteHeader(http.StatusNotImplemented)
|
||||
}
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
default:
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
@@ -101,10 +91,6 @@ func (h objectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
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":
|
||||
@@ -114,7 +100,7 @@ func (h objectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
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("Last-Modified", UTCNow().Format(http.TimeFormat))
|
||||
w.Header().Set("ETag", "9af2f8218b150c351ad802c6f3d66abe")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
case r.Method == "POST":
|
||||
@@ -161,71 +147,62 @@ func (h objectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
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("Last-Modified", UTCNow().Format(http.TimeFormat))
|
||||
w.Header().Set("ETag", "9af2f8218b150c351ad802c6f3d66abe")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
io.Copy(w, bytes.NewReader(h.data))
|
||||
}
|
||||
}
|
||||
|
||||
func Test(t *testing.T) { TestingT(t) }
|
||||
|
||||
type MySuite struct{}
|
||||
|
||||
var _ = Suite(&MySuite{})
|
||||
|
||||
// Test bucket operations.
|
||||
func (s *MySuite) TestBucketOperations(c *C) {
|
||||
func (s *TestSuite) TestBucketOperations(c *C) {
|
||||
bucket := bucketHandler(bucketHandler{
|
||||
resource: "/bucket/",
|
||||
})
|
||||
server := httptest.NewServer(bucket)
|
||||
defer server.Close()
|
||||
|
||||
conf := new(client.Config)
|
||||
conf := new(Config)
|
||||
conf.HostURL = server.URL + bucket.resource
|
||||
conf.AccessKey = "WLGDGYAQYIGI833EV05A"
|
||||
conf.SecretKey = "BYvgJM101sHngl2uzjXS/OBF/aMxAN06JrJ3qJlF"
|
||||
conf.Signature = "S3v4"
|
||||
s3c, err := New(conf)
|
||||
s3c, err := s3New(conf)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
err = s3c.MakeBucket("us-east-1")
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
err = s3c.SetBucketAccess("public-read-write")
|
||||
err = s3c.MakeBucket("us-east-1", true)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
conf.HostURL = server.URL + string(s3c.GetURL().Separator)
|
||||
s3c, err = New(conf)
|
||||
s3c, err = s3New(conf)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
for content := range s3c.List(false, false) {
|
||||
for content := range s3c.List(false, false, DirNone) {
|
||||
c.Assert(content.Err, IsNil)
|
||||
c.Assert(content.Type.IsDir(), Equals, true)
|
||||
}
|
||||
|
||||
conf.HostURL = server.URL + "/bucket"
|
||||
s3c, err = New(conf)
|
||||
s3c, err = s3New(conf)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
for content := range s3c.List(false, false) {
|
||||
for content := range s3c.List(false, false, DirNone) {
|
||||
c.Assert(content.Err, IsNil)
|
||||
c.Assert(content.Type.IsDir(), Equals, true)
|
||||
}
|
||||
|
||||
conf.HostURL = server.URL + "/bucket/"
|
||||
s3c, err = New(conf)
|
||||
s3c, err = s3New(conf)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
for content := range s3c.List(false, false) {
|
||||
for content := range s3c.List(false, false, DirNone) {
|
||||
c.Assert(content.Err, IsNil)
|
||||
c.Assert(content.Type.IsRegular(), Equals, true)
|
||||
}
|
||||
}
|
||||
|
||||
// Test all object operations.
|
||||
func (s *MySuite) TestObjectOperations(c *C) {
|
||||
func (s *TestSuite) TestObjectOperations(c *C) {
|
||||
object := objectHandler(objectHandler{
|
||||
resource: "/bucket/object",
|
||||
data: []byte("Hello, World"),
|
||||
@@ -233,26 +210,24 @@ func (s *MySuite) TestObjectOperations(c *C) {
|
||||
server := httptest.NewServer(object)
|
||||
defer server.Close()
|
||||
|
||||
conf := new(client.Config)
|
||||
conf := new(Config)
|
||||
conf.HostURL = server.URL + object.resource
|
||||
conf.AccessKey = "WLGDGYAQYIGI833EV05A"
|
||||
conf.SecretKey = "BYvgJM101sHngl2uzjXS/OBF/aMxAN06JrJ3qJlF"
|
||||
conf.Signature = "S3v4"
|
||||
s3c, err := New(conf)
|
||||
s3c, err := s3New(conf)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
var reader io.Reader
|
||||
reader = bytes.NewReader(object.data)
|
||||
n, err := s3c.Put(reader, int64(len(object.data)), "application/octet-stream", nil)
|
||||
n, err := s3c.Put(context.Background(), reader, int64(len(object.data)), map[string]string{
|
||||
"Content-Type": "application/octet-stream",
|
||||
}, nil, "")
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(n, Equals, int64(len(object.data)))
|
||||
|
||||
content, err := s3c.Stat()
|
||||
reader, err = s3c.Get("")
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(content.Size, Equals, int64(len(object.data)))
|
||||
c.Assert(content.Type.IsRegular(), Equals, true)
|
||||
|
||||
reader, err = s3c.Get()
|
||||
var buffer bytes.Buffer
|
||||
{
|
||||
_, err := io.Copy(&buffer, reader)
|
||||
@@ -14,19 +14,22 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package client
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"mime"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"runtime"
|
||||
"strings"
|
||||
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
)
|
||||
|
||||
// URL client url structure
|
||||
type URL struct {
|
||||
Type URLType
|
||||
// url client url structure
|
||||
type clientURL struct {
|
||||
Type clientURLType
|
||||
Scheme string
|
||||
Host string
|
||||
Path string
|
||||
@@ -34,13 +37,13 @@ type URL struct {
|
||||
Separator rune
|
||||
}
|
||||
|
||||
// URLType - enum of different url types
|
||||
type URLType int
|
||||
// clientURLType - enum of different url types
|
||||
type clientURLType int
|
||||
|
||||
// enum types
|
||||
const (
|
||||
Object = iota // Minio and S3 compatible cloud storage
|
||||
Filesystem // POSIX compatible file systems
|
||||
objectStorage = iota // Minio and S3 compatible cloud storage
|
||||
fileSystem // POSIX compatible file systems
|
||||
)
|
||||
|
||||
// Maybe rawurl is of the form scheme:path. (Scheme must be [a-zA-Z][a-zA-Z0-9+-.]*)
|
||||
@@ -87,10 +90,9 @@ func getHost(authority string) (host string) {
|
||||
return authority
|
||||
}
|
||||
|
||||
// NewURL returns an abstracted URL for filesystems and object storage.
|
||||
func NewURL(urlStr string) *URL {
|
||||
// newClientURL returns an abstracted URL for filesystems and object storage.
|
||||
func newClientURL(urlStr string) *clientURL {
|
||||
scheme, rest := getScheme(urlStr)
|
||||
rest, _ = splitSpecial(rest, "?", true)
|
||||
if strings.HasPrefix(rest, "//") {
|
||||
// if rest has '//' prefix, skip them
|
||||
var authority string
|
||||
@@ -100,9 +102,9 @@ func NewURL(urlStr string) *URL {
|
||||
}
|
||||
host := getHost(authority)
|
||||
if host != "" && (scheme == "http" || scheme == "https") {
|
||||
return &URL{
|
||||
return &clientURL{
|
||||
Scheme: scheme,
|
||||
Type: Object,
|
||||
Type: objectStorage,
|
||||
Host: host,
|
||||
Path: rest,
|
||||
SchemeSeparator: "://",
|
||||
@@ -110,15 +112,15 @@ func NewURL(urlStr string) *URL {
|
||||
}
|
||||
}
|
||||
}
|
||||
return &URL{
|
||||
Type: Filesystem,
|
||||
return &clientURL{
|
||||
Type: fileSystem,
|
||||
Path: rest,
|
||||
Separator: filepath.Separator,
|
||||
}
|
||||
}
|
||||
|
||||
// JoinURLs join two input urls and returns a url
|
||||
func JoinURLs(url1, url2 *URL) *URL {
|
||||
// joinURLs join two input urls and returns a url
|
||||
func joinURLs(url1, url2 *clientURL) *clientURL {
|
||||
var url1Path, url2Path string
|
||||
url1Path = filepath.ToSlash(url1.Path)
|
||||
url2Path = filepath.ToSlash(url2.Path)
|
||||
@@ -131,14 +133,14 @@ func JoinURLs(url1, url2 *URL) *URL {
|
||||
}
|
||||
|
||||
// String convert URL into its canonical form.
|
||||
func (u URL) String() string {
|
||||
func (u clientURL) String() string {
|
||||
var buf bytes.Buffer
|
||||
// if fileystem no translation needed, return as is.
|
||||
if u.Type == Filesystem {
|
||||
// if fileSystem no translation needed, return as is.
|
||||
if u.Type == fileSystem {
|
||||
return u.Path
|
||||
}
|
||||
// if Object convert from any non standard paths to a supported URL path style.
|
||||
if u.Type == Object {
|
||||
// if objectStorage convert from any non standard paths to a supported URL path style.
|
||||
if u.Type == objectStorage {
|
||||
buf.WriteString(u.Scheme)
|
||||
buf.WriteByte(':')
|
||||
buf.WriteString("//")
|
||||
@@ -160,3 +162,75 @@ func (u URL) String() string {
|
||||
}
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
// urlJoinPath Join a path to existing URL.
|
||||
func urlJoinPath(url1, url2 string) string {
|
||||
u1 := newClientURL(url1)
|
||||
u2 := newClientURL(url2)
|
||||
return joinURLs(u1, u2).String()
|
||||
}
|
||||
|
||||
// url2Stat returns stat info for URL.
|
||||
func url2Stat(urlStr string, isFetchMeta bool, encKeyDB map[string][]prefixSSEPair) (client Client, content *clientContent, err *probe.Error) {
|
||||
client, err = newClient(urlStr)
|
||||
if err != nil {
|
||||
return nil, nil, err.Trace(urlStr)
|
||||
}
|
||||
alias, _ := url2Alias(urlStr)
|
||||
sseKey := getSSEKey(urlStr, encKeyDB[alias])
|
||||
|
||||
content, err = client.Stat(false, isFetchMeta, sseKey)
|
||||
if err != nil {
|
||||
return nil, nil, err.Trace(urlStr)
|
||||
}
|
||||
return client, content, nil
|
||||
}
|
||||
|
||||
// url2Alias separates alias and path from the URL. Aliased URL is of
|
||||
// the form alias/path/to/blah.
|
||||
func url2Alias(aliasedURL string) (alias, path string) {
|
||||
// Save aliased url.
|
||||
urlStr := aliasedURL
|
||||
|
||||
// Convert '/' on windows to filepath.Separator.
|
||||
urlStr = filepath.FromSlash(urlStr)
|
||||
|
||||
if runtime.GOOS == "windows" {
|
||||
// Remove '/' prefix before alias if any to support '\\home' alias
|
||||
// style under Windows
|
||||
urlStr = strings.TrimPrefix(urlStr, string(filepath.Separator))
|
||||
}
|
||||
|
||||
// Remove everything after alias (i.e. after '/').
|
||||
urlParts := strings.SplitN(urlStr, string(filepath.Separator), 2)
|
||||
if len(urlParts) == 2 {
|
||||
// Convert windows style path separator to Unix style.
|
||||
return urlParts[0], urlParts[1]
|
||||
}
|
||||
return urlParts[0], ""
|
||||
}
|
||||
|
||||
// isURLPrefixExists - check if object key prefix exists.
|
||||
func isURLPrefixExists(urlPrefix string, incomplete bool) bool {
|
||||
clnt, err := newClient(urlPrefix)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
isRecursive := false
|
||||
isIncomplete := incomplete
|
||||
for entry := range clnt.List(isRecursive, isIncomplete, DirNone) {
|
||||
return entry.Err == nil
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// guessURLContentType - guess content-type of the URL.
|
||||
// on failure just return 'application/octet-stream'.
|
||||
func guessURLContentType(urlStr string) string {
|
||||
url := newClientURL(urlStr)
|
||||
contentType := mime.TypeByExtension(filepath.Ext(url.Path))
|
||||
if contentType == "" {
|
||||
contentType = "application/octet-stream"
|
||||
}
|
||||
return contentType
|
||||
}
|
||||
@@ -14,10 +14,24 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
package cmd
|
||||
|
||||
import . "gopkg.in/check.v1"
|
||||
|
||||
// TestURL - tests url parsing and fields.
|
||||
func (s *TestSuite) TestURL(c *C) {
|
||||
urlStr := "foo?.go"
|
||||
url := newClientURL(urlStr)
|
||||
c.Assert(url.Path, Equals, "foo?.go")
|
||||
|
||||
urlStr = "https://s3.amazonaws.com/mybucket/foo?.go"
|
||||
url = newClientURL(urlStr)
|
||||
c.Assert(url.Scheme, Equals, "https")
|
||||
c.Assert(url.Host, Equals, "s3.amazonaws.com")
|
||||
c.Assert(url.Path, Equals, "/mybucket/foo?.go")
|
||||
}
|
||||
|
||||
// TestURLJoinPath - tests joining two different urls.
|
||||
func (s *TestSuite) TestURLJoinPath(c *C) {
|
||||
// Join two URLs
|
||||
url1 := "http://s3.mycompany.io/dev"
|
||||
@@ -31,7 +45,7 @@ func (s *TestSuite) TestURLJoinPath(c *C) {
|
||||
url = urlJoinPath(url1, url2)
|
||||
c.Assert(url, Equals, "http://s3.mycompany.io/dev/mybucket/bin/zgrep")
|
||||
|
||||
// Check if it strips URL2's tailing ‘/’
|
||||
// Check if it strips URL2's tailing `/`
|
||||
url1 = "http://s3.mycompany.io/dev"
|
||||
url2 = "mybucket/bin/"
|
||||
url = urlJoinPath(url1, url2)
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
/*
|
||||
* Minio Client (C) 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
minio "github.com/minio/minio-go"
|
||||
)
|
||||
|
||||
// DirOpt - list directory option.
|
||||
type DirOpt int8
|
||||
|
||||
const (
|
||||
// DirNone - do not include directories in the list.
|
||||
DirNone DirOpt = iota
|
||||
// DirFirst - include directories before objects in the list.
|
||||
DirFirst
|
||||
// DirLast - include directories after objects in the list.
|
||||
DirLast
|
||||
)
|
||||
|
||||
// Default number of multipart workers for a Put operation.
|
||||
const defaultMultipartThreadsNum = 4
|
||||
|
||||
// Client - client interface
|
||||
type Client interface {
|
||||
// Common operations
|
||||
Stat(isIncomplete, isFetchMeta bool, sseKey string) (content *clientContent, err *probe.Error)
|
||||
List(isRecursive, isIncomplete bool, showDir DirOpt) <-chan *clientContent
|
||||
|
||||
// Bucket operations
|
||||
MakeBucket(region string, ignoreExisting bool) *probe.Error
|
||||
|
||||
// Access policy operations.
|
||||
GetAccess() (access string, error *probe.Error)
|
||||
GetAccessRules() (policyRules map[string]string, error *probe.Error)
|
||||
SetAccess(access string) *probe.Error
|
||||
|
||||
// I/O operations
|
||||
Copy(source string, size int64, progress io.Reader, srcSSEKey, tgtSSEKey string) *probe.Error
|
||||
|
||||
// I/O operations with metadata.
|
||||
Get(sseKey string) (reader io.Reader, err *probe.Error)
|
||||
Put(ctx context.Context, reader io.Reader, size int64, metadata map[string]string, progress io.Reader, sseKey string) (n int64, err *probe.Error)
|
||||
|
||||
// I/O operations with expiration
|
||||
ShareDownload(expires time.Duration) (string, *probe.Error)
|
||||
ShareUpload(bool, time.Duration, string) (string, map[string]string, *probe.Error)
|
||||
|
||||
// Watch events
|
||||
Watch(params watchParams) (*watchObject, *probe.Error)
|
||||
|
||||
// Delete operations
|
||||
Remove(isIncomplete bool, contentCh <-chan *clientContent) (errorCh <-chan *probe.Error)
|
||||
|
||||
// GetURL returns back internal url
|
||||
GetURL() clientURL
|
||||
}
|
||||
|
||||
// Content container for content metadata
|
||||
type clientContent struct {
|
||||
URL clientURL
|
||||
Time time.Time
|
||||
Size int64
|
||||
Type os.FileMode
|
||||
Metadata map[string]string
|
||||
ETag string
|
||||
EncryptionHeaders map[string]string
|
||||
Err *probe.Error
|
||||
}
|
||||
|
||||
// Config - see http://docs.amazonwebservices.com/AmazonS3/latest/dev/index.html?RESTAuthentication.html
|
||||
type Config struct {
|
||||
AccessKey string
|
||||
SecretKey string
|
||||
Signature string
|
||||
HostURL string
|
||||
AppName string
|
||||
AppVersion string
|
||||
AppComments []string
|
||||
Debug bool
|
||||
Insecure bool
|
||||
Lookup minio.BucketLookupType
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
/*
|
||||
* Minio Client (C) 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"golang.org/x/net/http/httpguts"
|
||||
)
|
||||
|
||||
// parse and return encryption key pairs per alias.
|
||||
func getEncKeys(ctx *cli.Context) (map[string][]prefixSSEPair, *probe.Error) {
|
||||
sseKeys := os.Getenv("MC_ENCRYPT_KEY")
|
||||
if key := ctx.String("encrypt-key"); key != "" {
|
||||
sseKeys = key
|
||||
}
|
||||
|
||||
encKeyDB, err := parseAndValidateEncryptionKeys(sseKeys)
|
||||
if err != nil {
|
||||
return nil, err.Trace(sseKeys)
|
||||
}
|
||||
return encKeyDB, nil
|
||||
}
|
||||
|
||||
// Check if the passed URL represents a folder. It may or may not exist yet.
|
||||
// If it exists, we can easily check if it is a folder, if it doesn't exist,
|
||||
// we can guess if the url is a folder from how it looks.
|
||||
func isAliasURLDir(aliasURL string, keys map[string][]prefixSSEPair) bool {
|
||||
// If the target url exists, check if it is a directory
|
||||
// and return immediately.
|
||||
_, targetContent, err := url2Stat(aliasURL, false, keys)
|
||||
if err == nil {
|
||||
return targetContent.Type.IsDir()
|
||||
}
|
||||
|
||||
_, expandedURL, _ := mustExpandAlias(aliasURL)
|
||||
|
||||
// Check if targetURL is an FS or S3 aliased url
|
||||
if expandedURL == aliasURL {
|
||||
// This is an FS url, check if the url has a separator at the end
|
||||
return strings.HasSuffix(aliasURL, string(filepath.Separator))
|
||||
}
|
||||
|
||||
// This is an S3 url, then:
|
||||
// *) If alias format is specified, return false
|
||||
// *) If alias/bucket is specified, return true
|
||||
// *) If alias/bucket/prefix, check if prefix has
|
||||
// has a trailing slash.
|
||||
pathURL := filepath.ToSlash(aliasURL)
|
||||
fields := strings.Split(pathURL, "/")
|
||||
switch len(fields) {
|
||||
// Nothing or alias format
|
||||
case 0, 1:
|
||||
return false
|
||||
// alias/bucket format
|
||||
case 2:
|
||||
return true
|
||||
} // default case..
|
||||
|
||||
// alias/bucket/prefix format
|
||||
return strings.HasSuffix(pathURL, "/")
|
||||
}
|
||||
|
||||
// getSourceStreamFromURL gets a reader from URL.
|
||||
func getSourceStreamFromURL(urlStr string, encKeyDB map[string][]prefixSSEPair) (reader io.Reader, err *probe.Error) {
|
||||
alias, urlStrFull, _, err := expandAlias(urlStr)
|
||||
if err != nil {
|
||||
return nil, err.Trace(urlStr)
|
||||
}
|
||||
sseKey := getSSEKey(urlStr, encKeyDB[alias])
|
||||
reader, _, err = getSourceStream(alias, urlStrFull, false, sseKey)
|
||||
return reader, err
|
||||
}
|
||||
|
||||
// getSourceStream gets a reader from URL.
|
||||
func getSourceStream(alias string, urlStr string, fetchStat bool, sseKey string) (reader io.Reader, metadata map[string]string, err *probe.Error) {
|
||||
sourceClnt, err := newClientFromAlias(alias, urlStr)
|
||||
if err != nil {
|
||||
return nil, nil, err.Trace(alias, urlStr)
|
||||
}
|
||||
reader, err = sourceClnt.Get(sseKey)
|
||||
if err != nil {
|
||||
return nil, nil, err.Trace(alias, urlStr)
|
||||
}
|
||||
metadata = map[string]string{}
|
||||
if fetchStat {
|
||||
st, err := sourceClnt.Stat(false, true, sseKey)
|
||||
if err != nil {
|
||||
return nil, nil, err.Trace(alias, urlStr)
|
||||
}
|
||||
for k, v := range st.Metadata {
|
||||
if httpguts.ValidHeaderFieldName(k) &&
|
||||
httpguts.ValidHeaderFieldValue(v) {
|
||||
metadata[k] = v
|
||||
}
|
||||
}
|
||||
}
|
||||
return reader, metadata, nil
|
||||
}
|
||||
|
||||
// putTargetStream writes to URL from Reader.
|
||||
func putTargetStream(ctx context.Context, alias string, urlStr string, reader io.Reader, size int64, metadata map[string]string, progress io.Reader, sseKey string) (int64, *probe.Error) {
|
||||
targetClnt, err := newClientFromAlias(alias, urlStr)
|
||||
if err != nil {
|
||||
return 0, err.Trace(alias, urlStr)
|
||||
}
|
||||
n, err := targetClnt.Put(ctx, reader, size, metadata, progress, sseKey)
|
||||
if err != nil {
|
||||
return n, err.Trace(alias, urlStr)
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// putTargetStreamWithURL writes to URL from reader. If length=-1, read until EOF.
|
||||
func putTargetStreamWithURL(urlStr string, reader io.Reader, size int64, sseKey string) (int64, *probe.Error) {
|
||||
alias, urlStrFull, _, err := expandAlias(urlStr)
|
||||
if err != nil {
|
||||
return 0, err.Trace(alias, urlStr)
|
||||
}
|
||||
contentType := guessURLContentType(urlStr)
|
||||
metadata := map[string]string{
|
||||
"Content-Type": contentType,
|
||||
}
|
||||
return putTargetStream(context.Background(), alias, urlStrFull, reader, size, metadata, nil, sseKey)
|
||||
}
|
||||
|
||||
// copySourceToTargetURL copies to targetURL from source.
|
||||
func copySourceToTargetURL(alias string, urlStr string, source string, size int64, progress io.Reader, srcSSEKey, tgtSSEKey string) *probe.Error {
|
||||
targetClnt, err := newClientFromAlias(alias, urlStr)
|
||||
if err != nil {
|
||||
return err.Trace(alias, urlStr)
|
||||
}
|
||||
err = targetClnt.Copy(source, size, progress, srcSSEKey, tgtSSEKey)
|
||||
if err != nil {
|
||||
return err.Trace(alias, urlStr)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// uploadSourceToTargetURL - uploads to targetURL from source.
|
||||
// optionally optimizes copy for object sizes <= 5GiB by using
|
||||
// server side copy operation.
|
||||
func uploadSourceToTargetURL(ctx context.Context, urls URLs, progress io.Reader) URLs {
|
||||
sourceAlias := urls.SourceAlias
|
||||
sourceURL := urls.SourceContent.URL
|
||||
targetAlias := urls.TargetAlias
|
||||
targetURL := urls.TargetContent.URL
|
||||
length := urls.SourceContent.Size
|
||||
// Optimize for server side copy if the host is same.
|
||||
if sourceAlias == targetAlias {
|
||||
sourcePath := filepath.ToSlash(sourceURL.Path)
|
||||
err := copySourceToTargetURL(targetAlias, targetURL.String(), sourcePath, length, progress, urls.SrcSSEKey, urls.TgtSSEKey)
|
||||
if err != nil {
|
||||
return urls.WithError(err.Trace(sourceURL.String()))
|
||||
}
|
||||
} else {
|
||||
// Proceed with regular stream copy.
|
||||
reader, metadata, err := getSourceStream(sourceAlias, sourceURL.String(), true, urls.SrcSSEKey)
|
||||
if err != nil {
|
||||
return urls.WithError(err.Trace(sourceURL.String()))
|
||||
}
|
||||
// Get metadata from target content as well
|
||||
if urls.TargetContent.Metadata != nil {
|
||||
for k, v := range urls.TargetContent.Metadata {
|
||||
metadata[k] = v
|
||||
}
|
||||
}
|
||||
if urls.SrcSSEKey != "" {
|
||||
delete(metadata, "X-Amz-Server-Side-Encryption-Customer-Algorithm")
|
||||
delete(metadata, "X-Amz-Server-Side-Encryption-Customer-Key-Md5")
|
||||
}
|
||||
|
||||
_, err = putTargetStream(ctx, targetAlias, targetURL.String(), reader, length, metadata, progress, urls.TgtSSEKey)
|
||||
if err != nil {
|
||||
return urls.WithError(err.Trace(targetURL.String()))
|
||||
}
|
||||
}
|
||||
return urls.WithError(nil)
|
||||
}
|
||||
|
||||
// newClientFromAlias gives a new client interface for matching
|
||||
// alias entry in the mc config file. If no matching host config entry
|
||||
// is found, fs client is returned.
|
||||
func newClientFromAlias(alias, urlStr string) (Client, *probe.Error) {
|
||||
alias, _, hostCfg, err := expandAlias(alias)
|
||||
if err != nil {
|
||||
return nil, err.Trace(alias, urlStr)
|
||||
}
|
||||
|
||||
if hostCfg == nil {
|
||||
// No matching host config. So we treat it like a
|
||||
// filesystem.
|
||||
fsClient, fsErr := fsNew(urlStr)
|
||||
if fsErr != nil {
|
||||
return nil, fsErr.Trace(alias, urlStr)
|
||||
}
|
||||
return fsClient, nil
|
||||
}
|
||||
|
||||
s3Config := newS3Config(urlStr, hostCfg)
|
||||
|
||||
s3Client, err := s3New(s3Config)
|
||||
if err != nil {
|
||||
return nil, err.Trace(alias, urlStr)
|
||||
}
|
||||
return s3Client, nil
|
||||
}
|
||||
|
||||
// urlRgx - verify if aliased url is real URL.
|
||||
var urlRgx = regexp.MustCompile("^https?://")
|
||||
|
||||
// newClient gives a new client interface
|
||||
func newClient(aliasedURL string) (Client, *probe.Error) {
|
||||
alias, urlStrFull, hostCfg, err := expandAlias(aliasedURL)
|
||||
if err != nil {
|
||||
return nil, err.Trace(aliasedURL)
|
||||
}
|
||||
// Verify if the aliasedURL is a real URL, fail in those cases
|
||||
// indicating the user to add alias.
|
||||
if hostCfg == nil && urlRgx.MatchString(aliasedURL) {
|
||||
return nil, errInvalidAliasedURL(aliasedURL).Trace(aliasedURL)
|
||||
}
|
||||
return newClientFromAlias(alias, urlStrFull)
|
||||
}
|
||||
@@ -14,15 +14,15 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/minio/mc/pkg/client"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio-xl/pkg/quick"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/minio/pkg/quick"
|
||||
)
|
||||
|
||||
func fixConfig() {
|
||||
@@ -60,7 +60,7 @@ func newBrokenConfigV3() *brokenConfigV3 {
|
||||
return conf
|
||||
}
|
||||
|
||||
// Fix config version ‘3’. Some v3 config files are written without
|
||||
// Fix config version `3`. Some v3 config files are written without
|
||||
// proper hostConfig JSON tags. They may also contain unused ACL and
|
||||
// Access fields. Rewrite the hostConfig with proper fields using JSON
|
||||
// tags and drop the unused (ACL, Access) fields.
|
||||
@@ -69,8 +69,8 @@ func fixConfigV3() {
|
||||
return
|
||||
}
|
||||
brokenCfgV3 := newBrokenConfigV3()
|
||||
brokenMcCfgV3, err := quick.Load(mustGetMcConfigPath(), brokenCfgV3)
|
||||
fatalIf(err.Trace(), "Unable to load config.")
|
||||
brokenMcCfgV3, e := quick.LoadConfig(mustGetMcConfigPath(), nil, brokenCfgV3)
|
||||
fatalIf(probe.NewError(e), "Unable to load config.")
|
||||
|
||||
if brokenMcCfgV3.Version() != "3" {
|
||||
return
|
||||
@@ -101,13 +101,13 @@ func fixConfigV3() {
|
||||
// We blindly drop ACL and Access fields from the broken config v3.
|
||||
|
||||
if isMutated {
|
||||
mcNewConfigV3, err := quick.New(cfgV3)
|
||||
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘3’.")
|
||||
mcNewConfigV3, e := quick.NewConfig(cfgV3, nil)
|
||||
fatalIf(probe.NewError(e), "Unable to initialize quick config for config version `3`.")
|
||||
|
||||
err = mcNewConfigV3.Save(mustGetMcConfigPath())
|
||||
fatalIf(err.Trace(), "Unable to save config version ‘3’.")
|
||||
e = mcNewConfigV3.Save(mustGetMcConfigPath())
|
||||
fatalIf(probe.NewError(e), "Unable to save config version `3`.")
|
||||
|
||||
console.Infof("Successfully fixed %s broken config for version ‘3’.\n", mustGetMcConfigPath())
|
||||
console.Infof("Successfully fixed %s broken config for version `3`.\n", mustGetMcConfigPath())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -117,8 +117,8 @@ func fixConfigV6ForHosts() {
|
||||
return
|
||||
}
|
||||
|
||||
brokenMcCfgV6, err := quick.Load(mustGetMcConfigPath(), newConfigV6())
|
||||
fatalIf(err.Trace(), "Unable to load config.")
|
||||
brokenMcCfgV6, e := quick.LoadConfig(mustGetMcConfigPath(), nil, newConfigV6())
|
||||
fatalIf(probe.NewError(e), "Unable to load config.")
|
||||
|
||||
if brokenMcCfgV6.Version() != "6" {
|
||||
return
|
||||
@@ -132,7 +132,7 @@ func fixConfigV6ForHosts() {
|
||||
newCfgV6.Aliases[k] = v
|
||||
}
|
||||
|
||||
url := new(client.URL)
|
||||
url := &clientURL{}
|
||||
// Copy hosts.
|
||||
for host, hostCfgV6 := range brokenMcCfgV6.Data().(*configV6).Hosts {
|
||||
// Already fixed - Copy and move on.
|
||||
@@ -157,11 +157,11 @@ func fixConfigV6ForHosts() {
|
||||
|
||||
if isMutated {
|
||||
// Save the new config back to the disk.
|
||||
mcCfgV6, err := quick.New(newCfgV6)
|
||||
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘v6’.")
|
||||
mcCfgV6, e := quick.NewConfig(newCfgV6, nil)
|
||||
fatalIf(probe.NewError(e), "Unable to initialize quick config for config version `v6`.")
|
||||
|
||||
err = mcCfgV6.Save(mustGetMcConfigPath())
|
||||
fatalIf(err.Trace(), "Unable to save config version ‘v6’.")
|
||||
e = mcCfgV6.Save(mustGetMcConfigPath())
|
||||
fatalIf(probe.NewError(e), "Unable to save config version `v6`.")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -170,11 +170,11 @@ func fixConfigV6() {
|
||||
if !isMcConfigExists() {
|
||||
return
|
||||
}
|
||||
config, err := quick.New(newConfigV6())
|
||||
fatalIf(err.Trace(), "Unable to initialize config.")
|
||||
config, e := quick.NewConfig(newConfigV6(), nil)
|
||||
fatalIf(probe.NewError(e), "Unable to initialize config.")
|
||||
|
||||
err = config.Load(mustGetMcConfigPath())
|
||||
fatalIf(err.Trace(mustGetMcConfigPath()), "Unable to load config.")
|
||||
e = config.Load(mustGetMcConfigPath())
|
||||
fatalIf(probe.NewError(e).Trace(mustGetMcConfigPath()), "Unable to load config.")
|
||||
|
||||
if config.Data().(*configV6).Version != "6" {
|
||||
return
|
||||
@@ -188,8 +188,8 @@ func fixConfigV6() {
|
||||
newConfig.Aliases = config.Data().(*configV6).Aliases
|
||||
for host, hostCfg := range config.Data().(*configV6).Hosts {
|
||||
if strings.Contains(host, "*") {
|
||||
fatalIf(err.Trace(),
|
||||
fmt.Sprintf("Glob style ‘*’ pattern matching is no longer supported. Please fix ‘%s’ entry manually.", host))
|
||||
fatalIf(errInvalidArgument(),
|
||||
fmt.Sprintf("Glob style `*` pattern matching is no longer supported. Please fix `%s` entry manually.", host))
|
||||
}
|
||||
if strings.Contains(host, "*s3*") || strings.Contains(host, "*.s3*") {
|
||||
console.Infoln("Found glob url, replacing " + host + " with s3.amazonaws.com")
|
||||
@@ -232,11 +232,11 @@ func fixConfigV6() {
|
||||
}
|
||||
|
||||
if isMutated {
|
||||
newConf, err := quick.New(newConfig)
|
||||
fatalIf(err.Trace(), "Unable to initialize newly fixed config.")
|
||||
newConf, e := quick.NewConfig(newConfig, nil)
|
||||
fatalIf(probe.NewError(e), "Unable to initialize newly fixed config.")
|
||||
|
||||
err = newConf.Save(mustGetMcConfigPath())
|
||||
fatalIf(err.Trace(mustGetMcConfigPath()), "Unable to save newly fixed config path.")
|
||||
console.Infof("Successfully fixed %s broken config for version ‘6’.\n", mustGetMcConfigPath())
|
||||
e = newConf.Save(mustGetMcConfigPath())
|
||||
fatalIf(probe.NewError(e).Trace(mustGetMcConfigPath()), "Unable to save newly fixed config path.")
|
||||
console.Infof("Successfully fixed %s broken config for version `6`.\n", mustGetMcConfigPath())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
/*
|
||||
* Minio Client (C) 2017 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"math/rand"
|
||||
"time"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
)
|
||||
|
||||
var hostAddFlags = []cli.Flag{
|
||||
cli.StringFlag{
|
||||
Name: "lookup",
|
||||
Value: "auto",
|
||||
Usage: "bucket lookup supported by the server. Valid options are `[dns,path,auto]`",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "api",
|
||||
Usage: "API signature. Valid options are `[S3v4, S3v2]`",
|
||||
},
|
||||
}
|
||||
var configHostAddCmd = cli.Command{
|
||||
Name: "add",
|
||||
ShortName: "a",
|
||||
Usage: "Add a new host to configuration file.",
|
||||
Action: mainConfigHostAdd,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(hostAddFlags, globalFlags...),
|
||||
HideHelpCommand: true,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} ALIAS URL ACCESS-KEY SECRET-KEY
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Add Amazon S3 storage service under "mys3" alias. For security reasons turn off bash history momentarily.
|
||||
$ set +o history
|
||||
$ {{.HelpName}} mys3 https://s3.amazonaws.com \
|
||||
BKIKJAA5BMMU2RHO6IBB V8f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12
|
||||
$ set -o history
|
||||
|
||||
2. Add Amazon S3 accelerated storage service under "mys3-accel" alias. For security reasons turn off bash history momentarily.
|
||||
$ set +o history
|
||||
$ {{.HelpName}} mys3-accel https://s3-accelerate.amazonaws.com \
|
||||
BKIKJAA5BMMU2RHO6IBB V8f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12
|
||||
$ set -o history
|
||||
|
||||
3. Add Amazon S3 IAM temporary credentials with limited access, please make sure to override the signature probe by explicitly
|
||||
providing the signature type.
|
||||
$ set +o history
|
||||
$ {{.HelpName}} mys3-iam https://s3.amazonaws.com \
|
||||
BKIKJAA5BMMU2RHO6IBB V8f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 --api "s3v4"
|
||||
$ set -o history
|
||||
|
||||
4. Add S3 API compatible storage service under "myminio" alias, to use dns style bucket lookup. For security reasons turn off bash history momentarily.
|
||||
$ set +o history
|
||||
$ {{.HelpName}} myminio http://localhost:9000 \
|
||||
minio minio123 --api "s3v4" --lookup "dns"
|
||||
$ set -o history
|
||||
|
||||
`,
|
||||
}
|
||||
|
||||
// checkConfigHostAddSyntax - verifies input arguments to 'config host add'.
|
||||
func checkConfigHostAddSyntax(ctx *cli.Context) {
|
||||
args := ctx.Args()
|
||||
argsNr := len(args)
|
||||
if argsNr < 4 || argsNr > 5 {
|
||||
fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...),
|
||||
"Incorrect number of arguments for host add command.")
|
||||
}
|
||||
|
||||
alias := args.Get(0)
|
||||
url := args.Get(1)
|
||||
accessKey := args.Get(2)
|
||||
secretKey := args.Get(3)
|
||||
api := ctx.String("api")
|
||||
bucketLookup := ctx.String("lookup")
|
||||
if !isValidAlias(alias) {
|
||||
fatalIf(errInvalidAlias(alias), "Invalid alias.")
|
||||
}
|
||||
|
||||
if !isValidHostURL(url) {
|
||||
fatalIf(errInvalidURL(url), "Invalid URL.")
|
||||
}
|
||||
|
||||
if !isValidAccessKey(accessKey) {
|
||||
fatalIf(errInvalidArgument().Trace(accessKey),
|
||||
"Invalid access key `"+accessKey+"`.")
|
||||
}
|
||||
|
||||
if !isValidSecretKey(secretKey) {
|
||||
fatalIf(errInvalidArgument().Trace(secretKey),
|
||||
"Invalid secret key `"+secretKey+"`.")
|
||||
}
|
||||
|
||||
if api != "" && !isValidAPI(api) { // Empty value set to default "S3v4".
|
||||
fatalIf(errInvalidArgument().Trace(api),
|
||||
"Unrecognized API signature. Valid options are `[S3v4, S3v2]`.")
|
||||
}
|
||||
|
||||
if !isValidLookup(bucketLookup) {
|
||||
fatalIf(errInvalidArgument().Trace(bucketLookup),
|
||||
"Unrecognized bucket lookup. Valid options are `[dns,auto, path]`.")
|
||||
}
|
||||
}
|
||||
|
||||
// addHost - add a host config.
|
||||
func addHost(alias string, hostCfgV9 hostConfigV9) {
|
||||
mcCfgV9, err := loadMcConfig()
|
||||
fatalIf(err.Trace(globalMCConfigVersion), "Unable to load config `"+mustGetMcConfigPath()+"`.")
|
||||
|
||||
// Add new host.
|
||||
mcCfgV9.Hosts[alias] = hostCfgV9
|
||||
|
||||
err = saveMcConfig(mcCfgV9)
|
||||
fatalIf(err.Trace(alias), "Unable to update hosts in config version `"+mustGetMcConfigPath()+"`.")
|
||||
|
||||
printMsg(hostMessage{
|
||||
op: "add",
|
||||
Alias: alias,
|
||||
URL: hostCfgV9.URL,
|
||||
AccessKey: hostCfgV9.AccessKey,
|
||||
SecretKey: hostCfgV9.SecretKey,
|
||||
API: hostCfgV9.API,
|
||||
Lookup: hostCfgV9.Lookup,
|
||||
})
|
||||
}
|
||||
|
||||
// probeS3Signature - auto probe S3 server signature: issue a Stat call
|
||||
// using v4 signature then v2 in case of failure.
|
||||
func probeS3Signature(accessKey, secretKey, url string) (string, *probe.Error) {
|
||||
probeBucketName := randString(60, rand.NewSource(time.Now().UnixNano()), "probe-bucket-sign-")
|
||||
// Test s3 connection for API auto probe
|
||||
s3Config := &Config{
|
||||
// S3 connection parameters
|
||||
Insecure: globalInsecure,
|
||||
AccessKey: accessKey,
|
||||
SecretKey: secretKey,
|
||||
Signature: "s3v4",
|
||||
HostURL: urlJoinPath(url, probeBucketName),
|
||||
}
|
||||
|
||||
s3Client, err := s3New(s3Config)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
if _, err = s3Client.Stat(false, false, ""); err != nil {
|
||||
switch err.ToGoError().(type) {
|
||||
case BucketDoesNotExist:
|
||||
// Bucket doesn't exist, means signature probing worked V4.
|
||||
default:
|
||||
// Attempt with signature v2, since v4 seem to have failed.
|
||||
s3Config.Signature = "s3v2"
|
||||
s3Client, err = s3New(s3Config)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if _, err = s3Client.Stat(false, false, ""); err != nil {
|
||||
switch err.ToGoError().(type) {
|
||||
case BucketDoesNotExist:
|
||||
// Bucket doesn't exist, means signature probing worked with V2.
|
||||
default:
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return s3Config.Signature, nil
|
||||
}
|
||||
|
||||
// buildS3Config constructs an S3 Config and does
|
||||
// signature auto-probe when needed.
|
||||
func buildS3Config(url, accessKey, secretKey, api, lookup string) (*Config, *probe.Error) {
|
||||
|
||||
s3Config := newS3Config(url, &hostConfigV9{
|
||||
AccessKey: accessKey,
|
||||
SecretKey: secretKey,
|
||||
URL: url,
|
||||
Lookup: lookup,
|
||||
})
|
||||
|
||||
// If api is provided we do not auto probe signature, this is
|
||||
// required in situations when signature type is provided by the user.
|
||||
if api != "" {
|
||||
s3Config.Signature = api
|
||||
return s3Config, nil
|
||||
}
|
||||
// Probe S3 signature version
|
||||
api, err := probeS3Signature(accessKey, secretKey, url)
|
||||
if err != nil {
|
||||
return nil, err.Trace(url, accessKey, secretKey, api, lookup)
|
||||
}
|
||||
|
||||
s3Config.Signature = api
|
||||
// Success.
|
||||
return s3Config, nil
|
||||
}
|
||||
|
||||
func mainConfigHostAdd(ctx *cli.Context) error {
|
||||
checkConfigHostAddSyntax(ctx)
|
||||
|
||||
console.SetColor("HostMessage", color.New(color.FgGreen))
|
||||
var (
|
||||
args = ctx.Args()
|
||||
url = args.Get(1)
|
||||
accessKey = args.Get(2)
|
||||
secretKey = args.Get(3)
|
||||
api = ctx.String("api")
|
||||
lookup = ctx.String("lookup")
|
||||
)
|
||||
|
||||
s3Config, err := buildS3Config(url, accessKey, secretKey, api, lookup)
|
||||
fatalIf(err.Trace(ctx.Args()...), "Unable to initialize new config from the provided credentials.")
|
||||
|
||||
addHost(ctx.Args().Get(0), hostConfigV9{
|
||||
URL: s3Config.HostURL,
|
||||
AccessKey: s3Config.AccessKey,
|
||||
SecretKey: s3Config.SecretKey,
|
||||
API: s3Config.Signature,
|
||||
Lookup: lookup,
|
||||
}) // Add a host with specified credentials.
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
/*
|
||||
* Minio Client (C) 2017 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
)
|
||||
|
||||
var configHostListCmd = cli.Command{
|
||||
Name: "list",
|
||||
ShortName: "ls",
|
||||
Usage: "Lists hosts in configuration file.",
|
||||
Action: mainConfigHostList,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
HideHelpCommand: true,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} [ALIAS]
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. List all hosts.
|
||||
$ {{.HelpName}}
|
||||
|
||||
2. List a specific host.
|
||||
$ {{.HelpName}} s3
|
||||
`,
|
||||
}
|
||||
|
||||
// Input argument validator..
|
||||
func checkConfigHostListSyntax(ctx *cli.Context) {
|
||||
args := ctx.Args()
|
||||
|
||||
if len(ctx.Args()) > 1 {
|
||||
fatalIf(errInvalidArgument().Trace(args...),
|
||||
"Incorrect number of arguments to list hosts.")
|
||||
}
|
||||
|
||||
if args.Get(0) != "" {
|
||||
if !isValidAlias(args.Get(0)) {
|
||||
fatalIf(errDummy().Trace(args.Get(0)),
|
||||
"Invalid alias `"+args.Get(0)+"`.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func mainConfigHostList(ctx *cli.Context) error {
|
||||
checkConfigHostListSyntax(ctx)
|
||||
|
||||
// Additional command speific theme customization.
|
||||
console.SetColor("HostMessage", color.New(color.FgGreen))
|
||||
console.SetColor("Alias", color.New(color.FgCyan, color.Bold))
|
||||
console.SetColor("URL", color.New(color.FgCyan))
|
||||
console.SetColor("AccessKey", color.New(color.FgBlue))
|
||||
console.SetColor("SecretKey", color.New(color.FgBlue))
|
||||
console.SetColor("API", color.New(color.FgYellow))
|
||||
console.SetColor("Lookup", color.New(color.FgCyan))
|
||||
|
||||
args := ctx.Args()
|
||||
listHosts(args.Get(0)) // List all configured hosts.
|
||||
return nil
|
||||
}
|
||||
|
||||
// Prints all the hosts.
|
||||
func printHosts(hosts ...hostMessage) {
|
||||
var maxAlias = 0
|
||||
for _, host := range hosts {
|
||||
if len(host.Alias) > maxAlias {
|
||||
maxAlias = len(host.Alias)
|
||||
}
|
||||
}
|
||||
for _, host := range hosts {
|
||||
if !globalJSON {
|
||||
// Format properly for alignment based on alias length only in non json mode.
|
||||
host.Alias = fmt.Sprintf("%-*.*s:", maxAlias, maxAlias, host.Alias)
|
||||
}
|
||||
if host.AccessKey == "" || host.SecretKey == "" {
|
||||
host.AccessKey = ""
|
||||
host.SecretKey = ""
|
||||
host.API = ""
|
||||
}
|
||||
printMsg(host)
|
||||
}
|
||||
}
|
||||
|
||||
// byAlias is a collection satisfying sort.Interface
|
||||
type byAlias []hostMessage
|
||||
|
||||
func (d byAlias) Len() int { return len(d) }
|
||||
func (d byAlias) Swap(i, j int) { d[i], d[j] = d[j], d[i] }
|
||||
func (d byAlias) Less(i, j int) bool { return d[i].Alias < d[j].Alias }
|
||||
|
||||
// listHosts - list all host URLs or a requested host.
|
||||
func listHosts(alias string) {
|
||||
conf, err := loadMcConfig()
|
||||
fatalIf(err.Trace(globalMCConfigVersion), "Unable to load config version `"+globalMCConfigVersion+"`.")
|
||||
|
||||
// If specific alias is requested, look for it and print.
|
||||
if alias != "" {
|
||||
if v, ok := conf.Hosts[alias]; ok {
|
||||
printHosts(hostMessage{
|
||||
op: "list",
|
||||
prettyPrint: false,
|
||||
Alias: alias,
|
||||
URL: v.URL,
|
||||
AccessKey: v.AccessKey,
|
||||
SecretKey: v.SecretKey,
|
||||
API: v.API,
|
||||
Lookup: v.Lookup,
|
||||
})
|
||||
return
|
||||
}
|
||||
fatalIf(errInvalidAliasedURL(alias), "No such alias `"+alias+"` found.")
|
||||
}
|
||||
|
||||
var hosts []hostMessage
|
||||
for k, v := range conf.Hosts {
|
||||
hosts = append(hosts, hostMessage{
|
||||
op: "list",
|
||||
prettyPrint: true,
|
||||
Alias: k,
|
||||
URL: v.URL,
|
||||
AccessKey: v.AccessKey,
|
||||
SecretKey: v.SecretKey,
|
||||
API: v.API,
|
||||
Lookup: v.Lookup,
|
||||
})
|
||||
}
|
||||
|
||||
// Sort hosts by alias names lexically.
|
||||
sort.Sort(byAlias(hosts))
|
||||
|
||||
// Display all the hosts.
|
||||
printHosts(hosts...)
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
/*
|
||||
* Minio Client (C) 2017 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
)
|
||||
|
||||
var configHostRemoveCmd = cli.Command{
|
||||
Name: "remove",
|
||||
ShortName: "rm",
|
||||
Usage: "Remove a host from configuration file.",
|
||||
Action: mainConfigHostRemove,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
HideHelpCommand: true,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} ALIAS
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Remove "goodisk" from config.
|
||||
$ {{.HelpName}} goodisk
|
||||
|
||||
`,
|
||||
}
|
||||
|
||||
// checkConfigHostRemoveSyntax - verifies input arguments to 'config host remove'.
|
||||
func checkConfigHostRemoveSyntax(ctx *cli.Context) {
|
||||
args := ctx.Args()
|
||||
|
||||
if len(ctx.Args()) != 1 {
|
||||
fatalIf(errInvalidArgument().Trace(args...),
|
||||
"Incorrect number of arguments for remove host command.")
|
||||
}
|
||||
|
||||
if !isValidAlias(args.Get(0)) {
|
||||
fatalIf(errDummy().Trace(args.Get(0)),
|
||||
"Invalid alias `"+args.Get(0)+"`.")
|
||||
}
|
||||
}
|
||||
|
||||
// mainConfigHost is the handle for "mc config host rm" command.
|
||||
func mainConfigHostRemove(ctx *cli.Context) error {
|
||||
checkConfigHostRemoveSyntax(ctx)
|
||||
|
||||
console.SetColor("HostMessage", color.New(color.FgGreen))
|
||||
|
||||
args := ctx.Args()
|
||||
alias := args.Get(0)
|
||||
removeHost(alias) // Remove a host.
|
||||
return nil
|
||||
}
|
||||
|
||||
// removeHost - removes a host.
|
||||
func removeHost(alias string) {
|
||||
conf, err := loadMcConfig()
|
||||
fatalIf(err.Trace(globalMCConfigVersion), "Unable to load config version `"+globalMCConfigVersion+"`.")
|
||||
|
||||
// Remove host.
|
||||
delete(conf.Hosts, alias)
|
||||
|
||||
err = saveMcConfig(conf)
|
||||
fatalIf(err.Trace(alias), "Unable to save deleted hosts in config version `"+globalMCConfigVersion+"`.")
|
||||
|
||||
printMsg(hostMessage{op: "remove", Alias: alias})
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
/*
|
||||
* Minio Client (C) 2017 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
)
|
||||
|
||||
var configHostCmd = cli.Command{
|
||||
Name: "host",
|
||||
Usage: "List, modify and remove hosts in configuration file.",
|
||||
Action: mainConfigHost,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Subcommands: []cli.Command{
|
||||
configHostAddCmd,
|
||||
configHostRemoveCmd,
|
||||
configHostListCmd,
|
||||
},
|
||||
HideHelpCommand: true,
|
||||
}
|
||||
|
||||
// mainConfigHost is the handle for "mc config host" command.
|
||||
func mainConfigHost(ctx *cli.Context) error {
|
||||
cli.ShowCommandHelp(ctx, ctx.Args().First())
|
||||
return nil
|
||||
// Sub-commands like "remove", "list" have their own main.
|
||||
}
|
||||
|
||||
// hostMessage container for content message structure
|
||||
type hostMessage struct {
|
||||
op string
|
||||
prettyPrint bool
|
||||
Status string `json:"status"`
|
||||
Alias string `json:"alias"`
|
||||
URL string `json:"URL"`
|
||||
AccessKey string `json:"accessKey,omitempty"`
|
||||
SecretKey string `json:"secretKey,omitempty"`
|
||||
API string `json:"api,omitempty"`
|
||||
Lookup string `json:"lookup,omitempty"`
|
||||
}
|
||||
|
||||
// Print the config information of one alias, when prettyPrint flag
|
||||
// is activated, fields contents are cut and '...' will be added to
|
||||
// show a pretty table of all aliases configurations
|
||||
func (h hostMessage) String() string {
|
||||
switch h.op {
|
||||
case "list":
|
||||
urlFieldMaxLen, apiFieldMaxLen := -1, -1
|
||||
accessFieldMaxLen, secretFieldMaxLen := -1, -1
|
||||
lookupFieldMaxLen := -1
|
||||
// Set cols width if prettyPrint flag is enabled
|
||||
if h.prettyPrint {
|
||||
urlFieldMaxLen = 30
|
||||
accessFieldMaxLen = 20
|
||||
secretFieldMaxLen = 40
|
||||
apiFieldMaxLen = 5
|
||||
lookupFieldMaxLen = 5
|
||||
}
|
||||
|
||||
// Create a new pretty table with cols configuration
|
||||
t := newPrettyTable(" ",
|
||||
Field{"Alias", -1},
|
||||
Field{"URL", urlFieldMaxLen},
|
||||
Field{"AccessKey", accessFieldMaxLen},
|
||||
Field{"SecretKey", secretFieldMaxLen},
|
||||
Field{"API", apiFieldMaxLen},
|
||||
Field{"Lookup", lookupFieldMaxLen},
|
||||
)
|
||||
return t.buildRow(h.Alias, h.URL, h.AccessKey, h.SecretKey, h.API, h.Lookup)
|
||||
case "remove":
|
||||
return console.Colorize("HostMessage", "Removed `"+h.Alias+"` successfully.")
|
||||
case "add":
|
||||
return console.Colorize("HostMessage", "Added `"+h.Alias+"` successfully.")
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
// JSON jsonified host message
|
||||
func (h hostMessage) JSON() string {
|
||||
h.Status = "success"
|
||||
jsonMessageBytes, e := json.Marshal(h)
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(jsonMessageBytes)
|
||||
}
|
||||
@@ -14,7 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
package cmd
|
||||
|
||||
import "github.com/minio/cli"
|
||||
|
||||
@@ -30,48 +30,24 @@ import "github.com/minio/cli"
|
||||
//
|
||||
|
||||
var (
|
||||
configFlags = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "help, h",
|
||||
Usage: "Help of config.",
|
||||
},
|
||||
}
|
||||
configFlags = []cli.Flag{}
|
||||
)
|
||||
|
||||
var configCmd = cli.Command{
|
||||
Name: "config",
|
||||
Usage: "Manage configuration file.",
|
||||
Action: mainConfig,
|
||||
Flags: append(configFlags, globalFlags...),
|
||||
Name: "config",
|
||||
Usage: "Manage mc configuration file.",
|
||||
Action: mainConfig,
|
||||
Before: setGlobalsFromContext,
|
||||
HideHelpCommand: true,
|
||||
Flags: append(configFlags, globalFlags...),
|
||||
Subcommands: []cli.Command{
|
||||
configHostCmd,
|
||||
},
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.Name}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.Name}} [FLAGS] COMMAND
|
||||
|
||||
FLAGS:
|
||||
{{range .Flags}}{{.}}
|
||||
{{end}}
|
||||
COMMANDS:
|
||||
{{range .Commands}}{{join .Names ", "}}{{ "\t" }}{{.Usage}}
|
||||
{{end}}
|
||||
`,
|
||||
}
|
||||
|
||||
// mainConfig is the handle for "mc config" command. provides sub-commands which write configuration data in json format to config file.
|
||||
func mainConfig(ctx *cli.Context) {
|
||||
// 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)
|
||||
}
|
||||
|
||||
func mainConfig(ctx *cli.Context) error {
|
||||
cli.ShowCommandHelp(ctx, ctx.Args().First())
|
||||
return nil
|
||||
// Sub-commands like "host" and "alias" have their own main.
|
||||
}
|
||||
@@ -14,14 +14,15 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio-xl/pkg/quick"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/minio/pkg/quick"
|
||||
)
|
||||
|
||||
// migrate config files from the any older version to the latest.
|
||||
@@ -40,6 +41,10 @@ func migrateConfig() {
|
||||
migrateConfigV5ToV6()
|
||||
// Migrate config V6 to V7
|
||||
migrateConfigV6ToV7()
|
||||
// Migrate config V7 to V8
|
||||
migrateConfigV7ToV8()
|
||||
// Migrate config V8 to V9
|
||||
migrateConfigV8ToV9()
|
||||
}
|
||||
|
||||
// Migrate from config version 1.0 to 1.0.1. Populate example entries and save it back.
|
||||
@@ -47,8 +52,8 @@ func migrateConfigV1ToV101() {
|
||||
if !isMcConfigExists() {
|
||||
return
|
||||
}
|
||||
mcCfgV1, err := quick.Load(mustGetMcConfigPath(), newConfigV1())
|
||||
fatalIf(err.Trace(), "Unable to load config version ‘1’.")
|
||||
mcCfgV1, e := quick.LoadConfig(mustGetMcConfigPath(), nil, newConfigV1())
|
||||
fatalIf(probe.NewError(e), "Unable to load config version `1`.")
|
||||
|
||||
// If loaded config version does not match 1.0.0, we do nothing.
|
||||
if mcCfgV1.Version() != "1.0.0" {
|
||||
@@ -91,21 +96,21 @@ func migrateConfigV1ToV101() {
|
||||
}
|
||||
|
||||
// Save the new config back to the disk.
|
||||
mcCfgV101, err := quick.New(cfgV101)
|
||||
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘1.0.1’.")
|
||||
err = mcCfgV101.Save(mustGetMcConfigPath())
|
||||
fatalIf(err.Trace(), "Unable to save config version ‘1.0.1’.")
|
||||
mcCfgV101, e := quick.NewConfig(cfgV101, nil)
|
||||
fatalIf(probe.NewError(e), "Unable to initialize quick config for config version `1.0.1`.")
|
||||
e = mcCfgV101.Save(mustGetMcConfigPath())
|
||||
fatalIf(probe.NewError(e), "Unable to save config version `1.0.1`.")
|
||||
|
||||
console.Infof("Successfully migrated %s from version ‘1.0.0’ to version ‘1.0.1’.\n", mustGetMcConfigPath())
|
||||
console.Infof("Successfully migrated %s from version `1.0.0` to version `1.0.1`.\n", mustGetMcConfigPath())
|
||||
}
|
||||
|
||||
// Migrate from config ‘1.0.1’ to ‘2’. Drop semantic versioning and move to integer versioning. No other changes.
|
||||
// Migrate from config `1.0.1` to `2`. Drop semantic versioning and move to integer versioning. No other changes.
|
||||
func migrateConfigV101ToV2() {
|
||||
if !isMcConfigExists() {
|
||||
return
|
||||
}
|
||||
mcCfgV101, err := quick.Load(mustGetMcConfigPath(), newConfigV101())
|
||||
fatalIf(err.Trace(), "Unable to load config version ‘1.0.1’.")
|
||||
mcCfgV101, e := quick.LoadConfig(mustGetMcConfigPath(), nil, newConfigV101())
|
||||
fatalIf(probe.NewError(e), "Unable to load config version `1.0.1`.")
|
||||
|
||||
// update to newer version
|
||||
if mcCfgV101.Version() != "1.0.1" {
|
||||
@@ -127,24 +132,24 @@ func migrateConfigV101ToV2() {
|
||||
}
|
||||
}
|
||||
|
||||
mcCfgV2, err := quick.New(cfgV2)
|
||||
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘2’.")
|
||||
mcCfgV2, e := quick.NewConfig(cfgV2, nil)
|
||||
fatalIf(probe.NewError(e), "Unable to initialize quick config for config version `2`.")
|
||||
|
||||
err = mcCfgV2.Save(mustGetMcConfigPath())
|
||||
fatalIf(err.Trace(), "Unable to save config version ‘2’.")
|
||||
e = mcCfgV2.Save(mustGetMcConfigPath())
|
||||
fatalIf(probe.NewError(e), "Unable to save config version `2`.")
|
||||
|
||||
console.Infof("Successfully migrated %s from version ‘1.0.1’ to version ‘2’.\n", mustGetMcConfigPath())
|
||||
console.Infof("Successfully migrated %s from version `1.0.1` to version `2`.\n", mustGetMcConfigPath())
|
||||
}
|
||||
|
||||
// Migrate from config ‘2’ to ‘3’. Use ‘-’ separated names for
|
||||
// Migrate from config `2` to `3`. Use `-` separated names for
|
||||
// hostConfig using struct json tags.
|
||||
func migrateConfigV2ToV3() {
|
||||
if !isMcConfigExists() {
|
||||
return
|
||||
}
|
||||
|
||||
mcCfgV2, err := quick.Load(mustGetMcConfigPath(), newConfigV2())
|
||||
fatalIf(err.Trace(), "Unable to load mc config V2.")
|
||||
mcCfgV2, e := quick.LoadConfig(mustGetMcConfigPath(), nil, newConfigV2())
|
||||
fatalIf(probe.NewError(e), "Unable to load mc config V2.")
|
||||
|
||||
// update to newer version
|
||||
if mcCfgV2.Version() != "2" {
|
||||
@@ -167,23 +172,23 @@ func migrateConfigV2ToV3() {
|
||||
}
|
||||
}
|
||||
|
||||
mcNewCfgV3, err := quick.New(cfgV3)
|
||||
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘3’.")
|
||||
mcNewCfgV3, e := quick.NewConfig(cfgV3, nil)
|
||||
fatalIf(probe.NewError(e), "Unable to initialize quick config for config version `3`.")
|
||||
|
||||
err = mcNewCfgV3.Save(mustGetMcConfigPath())
|
||||
fatalIf(err.Trace(), "Unable to save config version ‘3’.")
|
||||
e = mcNewCfgV3.Save(mustGetMcConfigPath())
|
||||
fatalIf(probe.NewError(e), "Unable to save config version `3`.")
|
||||
|
||||
console.Infof("Successfully migrated %s from version ‘2’ to version ‘3’.\n", mustGetMcConfigPath())
|
||||
console.Infof("Successfully migrated %s from version `2` to version `3`.\n", mustGetMcConfigPath())
|
||||
}
|
||||
|
||||
// Migrate from config version ‘3’ to ‘4’. Introduce API Signature
|
||||
// Migrate from config version `3` to `4`. Introduce API Signature
|
||||
// field in host config. Also Use JavaScript notation for field names.
|
||||
func migrateConfigV3ToV4() {
|
||||
if !isMcConfigExists() {
|
||||
return
|
||||
}
|
||||
mcCfgV3, err := quick.Load(mustGetMcConfigPath(), newConfigV3())
|
||||
fatalIf(err.Trace(), "Unable to load mc config V2.")
|
||||
mcCfgV3, e := quick.LoadConfig(mustGetMcConfigPath(), nil, newConfigV3())
|
||||
fatalIf(probe.NewError(e), "Unable to load mc config V2.")
|
||||
|
||||
// update to newer version
|
||||
if mcCfgV3.Version() != "3" {
|
||||
@@ -206,23 +211,23 @@ func migrateConfigV3ToV4() {
|
||||
}
|
||||
}
|
||||
|
||||
mcNewCfgV4, err := quick.New(cfgV4)
|
||||
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘4’.")
|
||||
mcNewCfgV4, e := quick.NewConfig(cfgV4, nil)
|
||||
fatalIf(probe.NewError(e), "Unable to initialize quick config for config version `4`.")
|
||||
|
||||
err = mcNewCfgV4.Save(mustGetMcConfigPath())
|
||||
fatalIf(err.Trace(), "Unable to save config version ‘4’.")
|
||||
e = mcNewCfgV4.Save(mustGetMcConfigPath())
|
||||
fatalIf(probe.NewError(e), "Unable to save config version `4`.")
|
||||
|
||||
console.Infof("Successfully migrated %s from version ‘3’ to version ‘4’.\n", mustGetMcConfigPath())
|
||||
console.Infof("Successfully migrated %s from version `3` to version `4`.\n", mustGetMcConfigPath())
|
||||
|
||||
}
|
||||
|
||||
// Migrate config version ‘4’ to ‘5’. Rename hostConfigV4.Signature -> hostConfigV5.API.
|
||||
// Migrate config version `4` to `5`. Rename hostConfigV4.Signature -> hostConfigV5.API.
|
||||
func migrateConfigV4ToV5() {
|
||||
if !isMcConfigExists() {
|
||||
return
|
||||
}
|
||||
mcCfgV4, err := quick.Load(mustGetMcConfigPath(), newConfigV4())
|
||||
fatalIf(err.Trace(), "Unable to load mc config V4.")
|
||||
mcCfgV4, e := quick.LoadConfig(mustGetMcConfigPath(), nil, newConfigV4())
|
||||
fatalIf(probe.NewError(e), "Unable to load mc config V4.")
|
||||
|
||||
// update to newer version
|
||||
if mcCfgV4.Version() != "4" {
|
||||
@@ -241,23 +246,23 @@ func migrateConfigV4ToV5() {
|
||||
}
|
||||
}
|
||||
|
||||
mcNewCfgV5, err := quick.New(cfgV5)
|
||||
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘5’.")
|
||||
mcNewCfgV5, e := quick.NewConfig(cfgV5, nil)
|
||||
fatalIf(probe.NewError(e), "Unable to initialize quick config for config version `5`.")
|
||||
|
||||
err = mcNewCfgV5.Save(mustGetMcConfigPath())
|
||||
fatalIf(err.Trace(), "Unable to save config version ‘5’.")
|
||||
e = mcNewCfgV5.Save(mustGetMcConfigPath())
|
||||
fatalIf(probe.NewError(e), "Unable to save config version `5`.")
|
||||
|
||||
console.Infof("Successfully migrated %s from version ‘4’ to version ‘5’.\n", mustGetMcConfigPath())
|
||||
console.Infof("Successfully migrated %s from version `4` to version `5`.\n", mustGetMcConfigPath())
|
||||
}
|
||||
|
||||
// Migrate config version ‘5’ to ‘6’. Add google cloud storage servers
|
||||
// Migrate config version `5` to `6`. Add google cloud storage servers
|
||||
// to host config. Also remove "." from s3 aws glob rule.
|
||||
func migrateConfigV5ToV6() {
|
||||
if !isMcConfigExists() {
|
||||
return
|
||||
}
|
||||
mcCfgV5, err := quick.Load(mustGetMcConfigPath(), newConfigV5())
|
||||
fatalIf(err.Trace(), "Unable to load mc config V5.")
|
||||
mcCfgV5, e := quick.LoadConfig(mustGetMcConfigPath(), nil, newConfigV5())
|
||||
fatalIf(probe.NewError(e), "Unable to load mc config V5.")
|
||||
|
||||
// update to newer version
|
||||
if mcCfgV5.Version() != "5" {
|
||||
@@ -307,24 +312,24 @@ func migrateConfigV5ToV6() {
|
||||
}
|
||||
}
|
||||
|
||||
mcNewCfgV6, err := quick.New(cfgV6)
|
||||
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘6’.")
|
||||
mcNewCfgV6, e := quick.NewConfig(cfgV6, nil)
|
||||
fatalIf(probe.NewError(e), "Unable to initialize quick config for config version `6`.")
|
||||
|
||||
err = mcNewCfgV6.Save(mustGetMcConfigPath())
|
||||
fatalIf(err.Trace(), "Unable to save config version ‘6’.")
|
||||
e = mcNewCfgV6.Save(mustGetMcConfigPath())
|
||||
fatalIf(probe.NewError(e), "Unable to save config version `6`.")
|
||||
|
||||
console.Infof("Successfully migrated %s from version ‘5’ to version ‘6’.\n", mustGetMcConfigPath())
|
||||
console.Infof("Successfully migrated %s from version `5` to version `6`.\n", mustGetMcConfigPath())
|
||||
}
|
||||
|
||||
// Migrate config version ‘6’ to ‘7'. Remove alias map and introduce
|
||||
// Migrate config version `6` to `7'. Remove alias map and introduce
|
||||
// named Host config. Also no more glob match for host config entries.
|
||||
func migrateConfigV6ToV7() {
|
||||
if !isMcConfigExists() {
|
||||
return
|
||||
}
|
||||
|
||||
mcCfgV6, err := quick.Load(mustGetMcConfigPath(), newConfigV6())
|
||||
fatalIf(err.Trace(), "Unable to load mc config V6.")
|
||||
mcCfgV6, e := quick.LoadConfig(mustGetMcConfigPath(), nil, newConfigV6())
|
||||
fatalIf(probe.NewError(e), "Unable to load mc config V6.")
|
||||
|
||||
if mcCfgV6.Version() != "6" {
|
||||
return
|
||||
@@ -332,8 +337,24 @@ func migrateConfigV6ToV7() {
|
||||
|
||||
cfgV7 := newConfigV7()
|
||||
aliasIndex := 0
|
||||
|
||||
// old Aliases.
|
||||
oldAliases := mcCfgV6.Data().(*configV6).Aliases
|
||||
|
||||
// We dropped alias support in v7. We only need to migrate host configs.
|
||||
for host, hostCfgV6 := range mcCfgV6.Data().(*configV6).Hosts {
|
||||
// Look through old aliases, if found any matching save those entries.
|
||||
for aliasName, aliasedHost := range oldAliases {
|
||||
if aliasedHost == host {
|
||||
cfgV7.Hosts[aliasName] = hostConfigV7{
|
||||
URL: host,
|
||||
AccessKey: hostCfgV6.AccessKeyID,
|
||||
SecretKey: hostCfgV6.SecretAccessKey,
|
||||
API: hostCfgV6.API,
|
||||
}
|
||||
continue
|
||||
}
|
||||
}
|
||||
if hostCfgV6.AccessKeyID == "YOUR-ACCESS-KEY-ID-HERE" ||
|
||||
hostCfgV6.SecretAccessKey == "YOUR-SECRET-ACCESS-KEY-HERE" ||
|
||||
hostCfgV6.AccessKeyID == "" ||
|
||||
@@ -370,11 +391,94 @@ func migrateConfigV6ToV7() {
|
||||
}
|
||||
// Load default settings.
|
||||
cfgV7.loadDefaults()
|
||||
mcNewCfgV7, err := quick.New(cfgV7)
|
||||
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘7’.")
|
||||
mcNewCfgV7, e := quick.NewConfig(cfgV7, nil)
|
||||
fatalIf(probe.NewError(e), "Unable to initialize quick config for config version `7`.")
|
||||
|
||||
err = mcNewCfgV7.Save(mustGetMcConfigPath())
|
||||
fatalIf(err.Trace(), "Unable to save config version ‘7’.")
|
||||
e = mcNewCfgV7.Save(mustGetMcConfigPath())
|
||||
fatalIf(probe.NewError(e), "Unable to save config version `7`.")
|
||||
|
||||
console.Infof("Successfully migrated %s from version ‘6’ to version ‘7’.\n", mustGetMcConfigPath())
|
||||
console.Infof("Successfully migrated %s from version `6` to version `7`.\n", mustGetMcConfigPath())
|
||||
}
|
||||
|
||||
// Migrate config version `7` to `8'. Remove hosts
|
||||
// 'play.minio.io:9002' and 'dl.minio.io:9000'.
|
||||
func migrateConfigV7ToV8() {
|
||||
if !isMcConfigExists() {
|
||||
return
|
||||
}
|
||||
|
||||
mcCfgV7, e := quick.LoadConfig(mustGetMcConfigPath(), nil, newConfigV7())
|
||||
fatalIf(probe.NewError(e), "Unable to load mc config V7.")
|
||||
|
||||
if mcCfgV7.Version() != "7" {
|
||||
return
|
||||
}
|
||||
|
||||
cfgV8 := newConfigV8()
|
||||
// We dropped alias support in v7. We only need to migrate host configs.
|
||||
for host, hostCfgV7 := range mcCfgV7.Data().(*configV7).Hosts {
|
||||
// Ignore 'player', 'play' and 'dl' aliases.
|
||||
if host == "player" || host == "dl" || host == "play" {
|
||||
continue
|
||||
}
|
||||
hostCfgV8 := hostConfigV8{}
|
||||
hostCfgV8.URL = hostCfgV7.URL
|
||||
hostCfgV8.AccessKey = hostCfgV7.AccessKey
|
||||
hostCfgV8.SecretKey = hostCfgV7.SecretKey
|
||||
hostCfgV8.API = hostCfgV7.API
|
||||
cfgV8.Hosts[host] = hostCfgV8
|
||||
}
|
||||
// Load default settings.
|
||||
cfgV8.loadDefaults()
|
||||
mcNewCfgV8, e := quick.NewConfig(cfgV8, nil)
|
||||
fatalIf(probe.NewError(e), "Unable to initialize quick config for config version `8`.")
|
||||
|
||||
e = mcNewCfgV8.Save(mustGetMcConfigPath())
|
||||
fatalIf(probe.NewError(e), "Unable to save config version `8`.")
|
||||
|
||||
console.Infof("Successfully migrated %s from version `7` to version `8`.\n", mustGetMcConfigPath())
|
||||
}
|
||||
|
||||
// Migrate config version `8` to `9'. Add optional field virtual
|
||||
func migrateConfigV8ToV9() {
|
||||
if !isMcConfigExists() {
|
||||
return
|
||||
}
|
||||
|
||||
mcCfgV8, e := quick.LoadConfig(mustGetMcConfigPath(), nil, newConfigV8())
|
||||
fatalIf(probe.NewError(e), "Unable to load mc config V8.")
|
||||
|
||||
if mcCfgV8.Version() != "8" {
|
||||
return
|
||||
}
|
||||
|
||||
cfgV9 := newConfigV9()
|
||||
isEmpty := true
|
||||
// We dropped alias support in v8. We only need to migrate host configs.
|
||||
for host, hostCfgV8 := range mcCfgV8.Data().(*configV8).Hosts {
|
||||
// Ignore 'player', 'play' and 'dl' aliases.
|
||||
if host == "player" || host == "dl" || host == "play" {
|
||||
continue
|
||||
}
|
||||
isEmpty = false
|
||||
hostCfgV9 := hostConfigV9{}
|
||||
hostCfgV9.URL = hostCfgV8.URL
|
||||
hostCfgV9.AccessKey = hostCfgV8.AccessKey
|
||||
hostCfgV9.SecretKey = hostCfgV8.SecretKey
|
||||
hostCfgV9.API = hostCfgV8.API
|
||||
hostCfgV9.Lookup = "auto"
|
||||
cfgV9.Hosts[host] = hostCfgV9
|
||||
}
|
||||
if isEmpty {
|
||||
// Load default settings.
|
||||
cfgV9.loadDefaults()
|
||||
}
|
||||
|
||||
mcNewCfgV9, e := quick.NewConfig(cfgV9, nil)
|
||||
fatalIf(probe.NewError(e), "Unable to initialize quick config for config version `9`.")
|
||||
|
||||
e = mcNewCfgV9.Save(mustGetMcConfigPath())
|
||||
fatalIf(probe.NewError(e), "Unable to save config version `9`.")
|
||||
|
||||
console.Infof("Successfully migrated %s from version `8` to version `9`.\n", mustGetMcConfigPath())
|
||||
}
|
||||
@@ -14,7 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
package cmd
|
||||
|
||||
/////////////////// Config V1 ///////////////////
|
||||
type hostConfigV1 struct {
|
||||
@@ -160,5 +160,149 @@ func newConfigV6() *configV6 {
|
||||
return conf
|
||||
}
|
||||
|
||||
/////////////////// Config V7 ///////////////////
|
||||
/////////////////// Config V6 ///////////////////
|
||||
// hostConfig configuration of a host - version '7'.
|
||||
type hostConfigV7 struct {
|
||||
URL string `json:"url"`
|
||||
AccessKey string `json:"accessKey"`
|
||||
SecretKey string `json:"secretKey"`
|
||||
API string `json:"api"`
|
||||
}
|
||||
|
||||
// configV7 config version.
|
||||
type configV7 struct {
|
||||
Version string `json:"version"`
|
||||
Hosts map[string]hostConfigV7 `json:"hosts"`
|
||||
}
|
||||
|
||||
// newConfigV7 - new config version '7'.
|
||||
func newConfigV7() *configV7 {
|
||||
cfg := new(configV7)
|
||||
cfg.Version = "7"
|
||||
cfg.Hosts = make(map[string]hostConfigV7)
|
||||
return cfg
|
||||
}
|
||||
|
||||
func (c *configV7) loadDefaults() {
|
||||
// Minio server running locally.
|
||||
c.setHost("local", hostConfigV7{
|
||||
URL: "http://localhost:9000",
|
||||
AccessKey: "",
|
||||
SecretKey: "",
|
||||
API: "S3v4",
|
||||
})
|
||||
|
||||
// Amazon S3 cloud storage service.
|
||||
c.setHost("s3", hostConfigV7{
|
||||
URL: "https://s3.amazonaws.com",
|
||||
AccessKey: defaultAccessKey,
|
||||
SecretKey: defaultSecretKey,
|
||||
API: "S3v4",
|
||||
})
|
||||
|
||||
// Google cloud storage service.
|
||||
c.setHost("gcs", hostConfigV7{
|
||||
URL: "https://storage.googleapis.com",
|
||||
AccessKey: defaultAccessKey,
|
||||
SecretKey: defaultSecretKey,
|
||||
API: "S3v2",
|
||||
})
|
||||
|
||||
// Minio anonymous server for demo.
|
||||
c.setHost("play", hostConfigV7{
|
||||
URL: "https://play.minio.io:9000",
|
||||
AccessKey: "",
|
||||
SecretKey: "",
|
||||
API: "S3v4",
|
||||
})
|
||||
|
||||
// Minio demo server with public secret and access keys.
|
||||
c.setHost("player", hostConfigV7{
|
||||
URL: "https://play.minio.io:9002",
|
||||
AccessKey: "Q3AM3UQ867SPQQA43P2F",
|
||||
SecretKey: "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG",
|
||||
API: "S3v4",
|
||||
})
|
||||
|
||||
// Minio public download service.
|
||||
c.setHost("dl", hostConfigV7{
|
||||
URL: "https://dl.minio.io:9000",
|
||||
AccessKey: "",
|
||||
SecretKey: "",
|
||||
API: "S3v4",
|
||||
})
|
||||
}
|
||||
|
||||
// SetHost sets host config if not empty.
|
||||
func (c *configV7) setHost(alias string, cfg hostConfigV7) {
|
||||
if _, ok := c.Hosts[alias]; !ok {
|
||||
c.Hosts[alias] = cfg
|
||||
}
|
||||
}
|
||||
|
||||
/////////////////// Config V8 ///////////////////
|
||||
// configV8 config version.
|
||||
// hostConfig configuration of a host.
|
||||
type hostConfigV8 struct {
|
||||
URL string `json:"url"`
|
||||
AccessKey string `json:"accessKey"`
|
||||
SecretKey string `json:"secretKey"`
|
||||
API string `json:"api"`
|
||||
}
|
||||
type configV8 struct {
|
||||
Version string `json:"version"`
|
||||
Hosts map[string]hostConfigV8 `json:"hosts"`
|
||||
}
|
||||
|
||||
// newConfigV8 - new config version.
|
||||
func newConfigV8() *configV8 {
|
||||
cfg := new(configV8)
|
||||
cfg.Version = globalMCConfigVersion
|
||||
cfg.Hosts = make(map[string]hostConfigV8)
|
||||
return cfg
|
||||
}
|
||||
|
||||
// SetHost sets host config if not empty.
|
||||
func (c *configV8) setHost(alias string, cfg hostConfigV8) {
|
||||
if _, ok := c.Hosts[alias]; !ok {
|
||||
c.Hosts[alias] = cfg
|
||||
}
|
||||
}
|
||||
|
||||
// load default values for missing entries.
|
||||
func (c *configV8) loadDefaults() {
|
||||
// Minio server running locally.
|
||||
c.setHost("local", hostConfigV8{
|
||||
URL: "http://localhost:9000",
|
||||
AccessKey: "",
|
||||
SecretKey: "",
|
||||
API: "S3v4",
|
||||
})
|
||||
|
||||
// Amazon S3 cloud storage service.
|
||||
c.setHost("s3", hostConfigV8{
|
||||
URL: "https://s3.amazonaws.com",
|
||||
AccessKey: defaultAccessKey,
|
||||
SecretKey: defaultSecretKey,
|
||||
API: "S3v4",
|
||||
})
|
||||
|
||||
// Google cloud storage service.
|
||||
c.setHost("gcs", hostConfigV8{
|
||||
URL: "https://storage.googleapis.com",
|
||||
AccessKey: defaultAccessKey,
|
||||
SecretKey: defaultSecretKey,
|
||||
API: "S3v2",
|
||||
})
|
||||
|
||||
// Minio anonymous server for demo.
|
||||
c.setHost("play", hostConfigV8{
|
||||
URL: "https://play.minio.io:9000",
|
||||
AccessKey: "Q3AM3UQ867SPQQA43P2F",
|
||||
SecretKey: "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG",
|
||||
API: "S3v4",
|
||||
})
|
||||
}
|
||||
|
||||
/////////////////// Config V9 ///////////////////
|
||||
// RESERVED FOR FUTURE
|
||||
@@ -0,0 +1,76 @@
|
||||
/*
|
||||
* Minio Client (C) 2015, 2016 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import "strings"
|
||||
|
||||
var validAPIs = []string{"S3v4", "S3v2"}
|
||||
|
||||
const (
|
||||
accessKeyMinLen = 5
|
||||
secretKeyMinLen = 8
|
||||
)
|
||||
|
||||
// isValidAccessKey - validate access key for right length.
|
||||
func isValidAccessKey(accessKey string) bool {
|
||||
if accessKey == "" {
|
||||
return true
|
||||
}
|
||||
return len(accessKey) >= accessKeyMinLen
|
||||
}
|
||||
|
||||
// isValidSecretKey - validate secret key for right length.
|
||||
func isValidSecretKey(secretKey string) bool {
|
||||
if secretKey == "" {
|
||||
return true
|
||||
}
|
||||
return len(secretKey) >= secretKeyMinLen
|
||||
}
|
||||
|
||||
// isValidHostURL - validate input host url.
|
||||
func isValidHostURL(hostURL string) (ok bool) {
|
||||
if strings.TrimSpace(hostURL) != "" {
|
||||
url := newClientURL(hostURL)
|
||||
if url.Scheme == "https" || url.Scheme == "http" {
|
||||
if url.Path == "/" {
|
||||
ok = true
|
||||
}
|
||||
}
|
||||
}
|
||||
return ok
|
||||
}
|
||||
|
||||
// isValidAPI - Validates if API signature string of supported type.
|
||||
func isValidAPI(api string) (ok bool) {
|
||||
switch strings.ToLower(api) {
|
||||
case "s3v2", "s3v4":
|
||||
ok = true
|
||||
}
|
||||
return ok
|
||||
}
|
||||
|
||||
// isValidLookup - validates if bucket lookup is of valid type
|
||||
func isValidLookup(lookup string) (ok bool) {
|
||||
l := strings.TrimSpace(lookup)
|
||||
l = strings.ToLower(lookup)
|
||||
for _, v := range []string{"dns", "path", "auto"} {
|
||||
if l == v {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
/*
|
||||
* Minio Client (C) 2016 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import "testing"
|
||||
|
||||
// Tests valid host URL functionality.
|
||||
func TestValidHostURL(t *testing.T) {
|
||||
testCases := []struct {
|
||||
hostURL string
|
||||
isHost bool
|
||||
}{
|
||||
{
|
||||
hostURL: "https://localhost:9000",
|
||||
isHost: true,
|
||||
},
|
||||
{
|
||||
hostURL: "/",
|
||||
isHost: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
isHost := isValidHostURL(testCase.hostURL)
|
||||
if testCase.isHost != isHost {
|
||||
t.Fatalf("Expected %t, got %t", testCase.isHost, isHost)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsValidAPI(t *testing.T) {
|
||||
equalAssert(isValidAPI("s3V2"), true, t)
|
||||
equalAssert(isValidAPI("S3v2"), true, t)
|
||||
equalAssert(isValidAPI("s3"), false, t)
|
||||
}
|
||||
|
||||
func equalAssert(ok1, ok2 bool, t *testing.T) {
|
||||
if ok1 != ok2 {
|
||||
t.Errorf("Expected %t, got %t", ok2, ok1)
|
||||
}
|
||||
}
|
||||
|
||||
// Tests valid and invalid secret keys.
|
||||
func TestValidSecretKeys(t *testing.T) {
|
||||
equalAssert(isValidSecretKey("aaa"), false, t)
|
||||
|
||||
equalAssert(isValidSecretKey(""), true, t)
|
||||
equalAssert(isValidSecretKey("password"), true, t)
|
||||
equalAssert(isValidSecretKey("password%%"), true, t)
|
||||
equalAssert(isValidSecretKey("BYvgJM101sHngl2uzjXS/OBF/aMxAN06JrJ3qJlF"), true, t)
|
||||
}
|
||||
|
||||
// Tests valid and invalid access keys.
|
||||
func TestValidAccessKeys(t *testing.T) {
|
||||
equalAssert(isValidAccessKey("aaa"), false, t)
|
||||
|
||||
equalAssert(isValidAccessKey(""), true, t)
|
||||
equalAssert(isValidAccessKey("admin"), true, t)
|
||||
equalAssert(isValidAccessKey("$$%%%%%3333"), true, t)
|
||||
equalAssert(isValidAccessKey("c67W2-r4MAyAYScRl"), true, t)
|
||||
equalAssert(isValidAccessKey("EXOb76bfeb1234562iu679f11588"), true, t)
|
||||
equalAssert(isValidAccessKey("BYvgJM101sHngl2uzjXS/OBF/aMxAN06JrJ3qJlF"), true, t)
|
||||
}
|
||||
@@ -14,13 +14,13 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"sync"
|
||||
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/minio-xl/pkg/quick"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/minio/pkg/quick"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -30,128 +30,131 @@ const (
|
||||
|
||||
var (
|
||||
// set once during first load.
|
||||
cacheCfgV7 *configV7
|
||||
cacheCfgV9 *configV9
|
||||
// All access to mc config file should be synchronized.
|
||||
cfgMutex = &sync.RWMutex{}
|
||||
)
|
||||
|
||||
// hostConfig configuration of a host.
|
||||
type hostConfigV7 struct {
|
||||
type hostConfigV9 struct {
|
||||
URL string `json:"url"`
|
||||
AccessKey string `json:"accessKey"`
|
||||
SecretKey string `json:"secretKey"`
|
||||
API string `json:"api"`
|
||||
Lookup string `json:"lookup"`
|
||||
}
|
||||
|
||||
// configV7 config version.
|
||||
type configV7 struct {
|
||||
// configV8 config version.
|
||||
type configV9 struct {
|
||||
Version string `json:"version"`
|
||||
Hosts map[string]hostConfigV7 `json:"hosts"`
|
||||
Hosts map[string]hostConfigV9 `json:"hosts"`
|
||||
}
|
||||
|
||||
// newConfigV7 - new config version.
|
||||
func newConfigV7() *configV7 {
|
||||
cfg := new(configV7)
|
||||
// newConfigV9 - new config version.
|
||||
func newConfigV9() *configV9 {
|
||||
cfg := new(configV9)
|
||||
cfg.Version = globalMCConfigVersion
|
||||
cfg.Hosts = make(map[string]hostConfigV7)
|
||||
cfg.Hosts = make(map[string]hostConfigV9)
|
||||
return cfg
|
||||
}
|
||||
|
||||
// SetHost sets host config if not empty.
|
||||
func (c *configV7) setHost(alias string, cfg hostConfigV7) {
|
||||
func (c *configV9) setHost(alias string, cfg hostConfigV9) {
|
||||
if _, ok := c.Hosts[alias]; !ok {
|
||||
c.Hosts[alias] = cfg
|
||||
}
|
||||
}
|
||||
|
||||
// load default values for missing entries.
|
||||
func (c *configV7) loadDefaults() {
|
||||
func (c *configV9) loadDefaults() {
|
||||
// Minio server running locally.
|
||||
c.setHost("local", hostConfigV7{
|
||||
c.setHost("local", hostConfigV9{
|
||||
URL: "http://localhost:9000",
|
||||
AccessKey: "",
|
||||
SecretKey: "",
|
||||
API: "S3v4",
|
||||
Lookup: "auto",
|
||||
})
|
||||
|
||||
// Amazon S3 cloud storage service.
|
||||
c.setHost("s3", hostConfigV7{
|
||||
c.setHost("s3", hostConfigV9{
|
||||
URL: "https://s3.amazonaws.com",
|
||||
AccessKey: defaultAccessKey,
|
||||
SecretKey: defaultSecretKey,
|
||||
API: "S3v4",
|
||||
Lookup: "dns",
|
||||
})
|
||||
|
||||
// Google cloud storage service.
|
||||
c.setHost("gcs", hostConfigV7{
|
||||
c.setHost("gcs", hostConfigV9{
|
||||
URL: "https://storage.googleapis.com",
|
||||
AccessKey: defaultAccessKey,
|
||||
SecretKey: defaultSecretKey,
|
||||
API: "S3v2",
|
||||
Lookup: "dns",
|
||||
})
|
||||
|
||||
// Minio anonymous server for demo.
|
||||
c.setHost("play", hostConfigV7{
|
||||
c.setHost("play", hostConfigV9{
|
||||
URL: "https://play.minio.io:9000",
|
||||
AccessKey: "",
|
||||
SecretKey: "",
|
||||
API: "S3v4",
|
||||
})
|
||||
|
||||
// Minio demo server with public secret and access keys.
|
||||
c.setHost("player", hostConfigV7{
|
||||
URL: "https://play.minio.io:9002",
|
||||
AccessKey: "Q3AM3UQ867SPQQA43P2F",
|
||||
SecretKey: "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG",
|
||||
API: "S3v4",
|
||||
})
|
||||
|
||||
// Minio public download service.
|
||||
c.setHost("dl", hostConfigV7{
|
||||
URL: "https://dl.minio.io:9000",
|
||||
AccessKey: "",
|
||||
SecretKey: "",
|
||||
API: "S3v4",
|
||||
Lookup: "auto",
|
||||
})
|
||||
}
|
||||
|
||||
// loadConfigV7 - loads a new config.
|
||||
func loadConfigV7() (*configV7, *probe.Error) {
|
||||
// loadConfigV9 - loads a new config.
|
||||
func loadConfigV9() (*configV9, *probe.Error) {
|
||||
cfgMutex.RLock()
|
||||
defer cfgMutex.RUnlock()
|
||||
|
||||
// Cached in private global variable.
|
||||
if cacheCfgV7 != nil {
|
||||
return cacheCfgV7, nil
|
||||
// If already cached, return the cached value.
|
||||
if cacheCfgV9 != nil {
|
||||
return cacheCfgV9, nil
|
||||
}
|
||||
|
||||
if !isMcConfigExists() {
|
||||
return nil, errInvalidArgument().Trace()
|
||||
}
|
||||
|
||||
mcCfgV7, err := quick.Load(mustGetMcConfigPath(), newConfigV7())
|
||||
fatalIf(err.Trace(), "Unable to load mc config file ‘"+mustGetMcConfigPath()+"’.")
|
||||
// Initialize a new config loader.
|
||||
qc, e := quick.NewConfig(newConfigV9(), nil)
|
||||
if e != nil {
|
||||
return nil, probe.NewError(e)
|
||||
}
|
||||
|
||||
cfgV7 := mcCfgV7.Data().(*configV7)
|
||||
// Load config at configPath, fails if config is not
|
||||
// accessible, malformed or version missing.
|
||||
if e = qc.Load(mustGetMcConfigPath()); e != nil {
|
||||
return nil, probe.NewError(e)
|
||||
}
|
||||
|
||||
// cache it.
|
||||
cacheCfgV7 = cfgV7
|
||||
cfgV9 := qc.Data().(*configV9)
|
||||
|
||||
return cfgV7, nil
|
||||
// Cache config.
|
||||
cacheCfgV9 = cfgV9
|
||||
|
||||
// Success.
|
||||
return cfgV9, nil
|
||||
}
|
||||
|
||||
// saveConfigV7 - saves an updated config.
|
||||
func saveConfigV7(cfgV7 *configV7) *probe.Error {
|
||||
// saveConfigV8 - saves an updated config.
|
||||
func saveConfigV9(cfgV9 *configV9) *probe.Error {
|
||||
cfgMutex.Lock()
|
||||
defer cfgMutex.Unlock()
|
||||
|
||||
qs, err := quick.New(cfgV7)
|
||||
if err != nil {
|
||||
return err.Trace()
|
||||
qs, e := quick.NewConfig(cfgV9, nil)
|
||||
if e != nil {
|
||||
return probe.NewError(e)
|
||||
}
|
||||
|
||||
// update the cache.
|
||||
cacheCfgV7 = cfgV7
|
||||
cacheCfgV9 = cfgV9
|
||||
|
||||
return qs.Save(mustGetMcConfigPath()).Trace(mustGetMcConfigPath())
|
||||
e = qs.Save(mustGetMcConfigPath())
|
||||
if e != nil {
|
||||
return probe.NewError(e).Trace(mustGetMcConfigPath())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
/*
|
||||
* Minio Client (C) 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Check if version of the config is valid
|
||||
func validateConfigVersion(config *configV9) (bool, string) {
|
||||
if config.Version != globalMCConfigVersion {
|
||||
return false, fmt.Sprintf("Config version '%s' does not match mc config version '%s', please update your binary.\n",
|
||||
config.Version, globalMCConfigVersion)
|
||||
}
|
||||
return true, ""
|
||||
}
|
||||
|
||||
// Verifies the config file of the Minio Client
|
||||
func validateConfigFile(config *configV9) (bool, []string) {
|
||||
ok, err := validateConfigVersion(config)
|
||||
var validationSuccessful = true
|
||||
var errors []string
|
||||
if !ok {
|
||||
validationSuccessful = false
|
||||
errors = append(errors, err)
|
||||
}
|
||||
hosts := config.Hosts
|
||||
for _, hostConfig := range hosts {
|
||||
hostConfigHealthOk, hostErrors := validateConfigHost(hostConfig)
|
||||
if !hostConfigHealthOk {
|
||||
validationSuccessful = false
|
||||
errors = append(errors, hostErrors...)
|
||||
}
|
||||
}
|
||||
return validationSuccessful, errors
|
||||
}
|
||||
|
||||
func validateConfigHost(host hostConfigV9) (bool, []string) {
|
||||
var validationSuccessful = true
|
||||
var hostErrors []string
|
||||
if !isValidAPI(strings.ToLower(host.API)) {
|
||||
validationSuccessful = false
|
||||
hostErrors = append(hostErrors, errInvalidAPISignature(host.API, host.URL).ToGoError().Error())
|
||||
}
|
||||
if !isValidHostURL(host.URL) {
|
||||
validationSuccessful = false
|
||||
hostErrors = append(hostErrors, errInvalidURL(host.URL).ToGoError().Error())
|
||||
}
|
||||
return validationSuccessful, hostErrors
|
||||
}
|
||||
+81
-28
@@ -14,24 +14,22 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"runtime"
|
||||
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/minio/pkg/user"
|
||||
"github.com/minio/go-homedir"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
)
|
||||
|
||||
// mcCustomConfigDir contains the whole path to config dir. Only access via get/set functions.
|
||||
var mcCustomConfigDir string
|
||||
|
||||
// mcCustomConfigPath contains the whole path to config file. Only access via get/set functions.
|
||||
var mcCustomConfigPath string
|
||||
|
||||
// setMcConfigDir - set a custom minio client config folder.
|
||||
func setMcConfigDir(configDir string) {
|
||||
mcCustomConfigDir = configDir
|
||||
@@ -42,17 +40,18 @@ func getMcConfigDir() (string, *probe.Error) {
|
||||
if mcCustomConfigDir != "" {
|
||||
return mcCustomConfigDir, nil
|
||||
}
|
||||
homeDir, e := user.HomeDir()
|
||||
homeDir, e := homedir.Dir()
|
||||
if e != nil {
|
||||
return "", probe.NewError(e)
|
||||
}
|
||||
var configDir string
|
||||
// For windows the path is slightly different
|
||||
switch runtime.GOOS {
|
||||
case "windows":
|
||||
return filepath.Join(homeDir, globalMCConfigWindowsDir), nil
|
||||
default:
|
||||
return filepath.Join(homeDir, globalMCConfigDir), nil
|
||||
if runtime.GOOS == "windows" {
|
||||
configDir = filepath.Join(homeDir, globalMCConfigWindowsDir)
|
||||
} else {
|
||||
configDir = filepath.Join(homeDir, globalMCConfigDir)
|
||||
}
|
||||
return configDir, nil
|
||||
}
|
||||
|
||||
// mustGetMcConfigDir - construct minio client config folder or fail
|
||||
@@ -77,8 +76,8 @@ func createMcConfigDir() *probe.Error {
|
||||
|
||||
// getMcConfigPath - construct minio client configuration path
|
||||
func getMcConfigPath() (string, *probe.Error) {
|
||||
if mcCustomConfigPath != "" {
|
||||
return mcCustomConfigPath, nil
|
||||
if mcCustomConfigDir != "" {
|
||||
return filepath.Join(mcCustomConfigDir, globalMCConfigFile), nil
|
||||
}
|
||||
dir, err := getMcConfigDir()
|
||||
if err != nil {
|
||||
@@ -95,28 +94,29 @@ func mustGetMcConfigPath() string {
|
||||
return path
|
||||
}
|
||||
|
||||
// newMcConfig - initializes a new version '6' config.
|
||||
func newMcConfig() *configV7 {
|
||||
cfg := newConfigV7()
|
||||
// newMcConfig - initializes a new version '9' config.
|
||||
func newMcConfig() *configV9 {
|
||||
cfg := newConfigV9()
|
||||
cfg.loadDefaults()
|
||||
return cfg
|
||||
}
|
||||
|
||||
// loadMcConfigCached - returns loadMcConfig with a closure for config cache.
|
||||
func loadMcConfigFactory() func() (*configV7, *probe.Error) {
|
||||
func loadMcConfigFactory() func() (*configV9, *probe.Error) {
|
||||
// Load once and cache in a closure.
|
||||
cfgCache, err := loadConfigV7()
|
||||
cfgCache, err := loadConfigV9()
|
||||
|
||||
// loadMcConfig - reads configuration file and returns config.
|
||||
return func() (*configV7, *probe.Error) {
|
||||
return func() (*configV9, *probe.Error) {
|
||||
return cfgCache, err
|
||||
}
|
||||
}
|
||||
|
||||
var loadMcConfig = loadMcConfigFactory()
|
||||
// loadMcConfig - returns configuration, initialized later.
|
||||
var loadMcConfig func() (*configV9, *probe.Error)
|
||||
|
||||
// saveMcConfig - saves configuration file and returns error if any.
|
||||
func saveMcConfig(config *configV7) *probe.Error {
|
||||
func saveMcConfig(config *configV9) *probe.Error {
|
||||
if config == nil {
|
||||
return errInvalidArgument().Trace()
|
||||
}
|
||||
@@ -127,7 +127,7 @@ func saveMcConfig(config *configV7) *probe.Error {
|
||||
}
|
||||
|
||||
// Save the config.
|
||||
if err := saveConfigV7(config); err != nil {
|
||||
if err := saveConfigV9(config); err != nil {
|
||||
return err.Trace(mustGetMcConfigPath())
|
||||
}
|
||||
|
||||
@@ -150,11 +150,11 @@ func isMcConfigExists() bool {
|
||||
|
||||
// isValidAlias - Check if alias valid.
|
||||
func isValidAlias(alias string) bool {
|
||||
return regexp.MustCompile("^[a-zA-Z][a-zA-Z0-9-]+$").MatchString(alias)
|
||||
return regexp.MustCompile("^[a-zA-Z][a-zA-Z0-9-_]+$").MatchString(alias)
|
||||
}
|
||||
|
||||
// getHostConfig retrieves host specific configuration such as access keys, signature type.
|
||||
func getHostConfig(alias string) (*hostConfigV7, *probe.Error) {
|
||||
func getHostConfig(alias string) (*hostConfigV9, *probe.Error) {
|
||||
mcCfg, err := loadMcConfig()
|
||||
if err != nil {
|
||||
return nil, err.Trace(alias)
|
||||
@@ -171,16 +171,69 @@ func getHostConfig(alias string) (*hostConfigV7, *probe.Error) {
|
||||
}
|
||||
|
||||
// mustGetHostConfig retrieves host specific configuration such as access keys, signature type.
|
||||
func mustGetHostConfig(alias string) *hostConfigV7 {
|
||||
func mustGetHostConfig(alias string) *hostConfigV9 {
|
||||
hostCfg, _ := getHostConfig(alias)
|
||||
return hostCfg
|
||||
}
|
||||
|
||||
// parse url usually obtained from env.
|
||||
func parseEnvURL(envURL string) (*url.URL, string, string, *probe.Error) {
|
||||
u, e := url.Parse(envURL)
|
||||
if e != nil {
|
||||
return nil, "", "", probe.NewError(e).Trace(envURL)
|
||||
}
|
||||
|
||||
var accessKey, secretKey string
|
||||
// Check if username:password is provided in URL, with no
|
||||
// access keys or secret we proceed and perform anonymous
|
||||
// requests.
|
||||
if u.User != nil {
|
||||
accessKey = u.User.Username()
|
||||
secretKey, _ = u.User.Password()
|
||||
}
|
||||
|
||||
// Look for if URL has invalid values and return error.
|
||||
if !((u.Scheme == "http" || u.Scheme == "https") &&
|
||||
(u.Path == "/" || u.Path == "") && u.Opaque == "" &&
|
||||
u.ForceQuery == false && u.RawQuery == "" && u.Fragment == "") {
|
||||
return nil, "", "", errInvalidArgument().Trace(u.String())
|
||||
}
|
||||
|
||||
// Now that we have validated the URL to be in expected style.
|
||||
u.User = nil
|
||||
|
||||
return u, accessKey, secretKey, nil
|
||||
}
|
||||
|
||||
const mcEnvHostsPrefix = "MC_HOSTS_"
|
||||
|
||||
func expandAliasFromEnv(envURL string) (*hostConfigV9, *probe.Error) {
|
||||
u, accessKey, secretKey, err := parseEnvURL(envURL)
|
||||
if err != nil {
|
||||
return nil, err.Trace(envURL)
|
||||
}
|
||||
|
||||
return &hostConfigV9{
|
||||
URL: u.String(),
|
||||
API: "S3v4",
|
||||
AccessKey: accessKey,
|
||||
SecretKey: secretKey,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// expandAlias expands aliased URL if any match is found, returns as is otherwise.
|
||||
func expandAlias(aliasedURL string) (alias string, urlStr string, hostCfg *hostConfigV7, err *probe.Error) {
|
||||
func expandAlias(aliasedURL string) (alias string, urlStr string, hostCfg *hostConfigV9, err *probe.Error) {
|
||||
// Extract alias from the URL.
|
||||
alias, path := url2Alias(aliasedURL)
|
||||
|
||||
if envConfig, ok := os.LookupEnv(mcEnvHostsPrefix + alias); ok {
|
||||
hostCfg, err = expandAliasFromEnv(envConfig)
|
||||
if err != nil {
|
||||
return "", "", nil, err.Trace(aliasedURL)
|
||||
}
|
||||
return alias, urlJoinPath(hostCfg.URL, path), hostCfg, nil
|
||||
}
|
||||
|
||||
// Find the matching alias entry and expand the URL.
|
||||
if hostCfg = mustGetHostConfig(alias); hostCfg != nil {
|
||||
return alias, urlJoinPath(hostCfg.URL, path), hostCfg, nil
|
||||
@@ -189,7 +242,7 @@ func expandAlias(aliasedURL string) (alias string, urlStr string, hostCfg *hostC
|
||||
}
|
||||
|
||||
// mustExpandAlias expands aliased URL if any match is found, returns as is otherwise.
|
||||
func mustExpandAlias(aliasedURL string) (alias string, urlStr string, hostCfg *hostConfigV7) {
|
||||
func mustExpandAlias(aliasedURL string) (alias string, urlStr string, hostCfg *hostConfigV9) {
|
||||
alias, urlStr, hostCfg, _ = expandAlias(aliasedURL)
|
||||
return alias, urlStr, hostCfg
|
||||
}
|
||||
+471
@@ -0,0 +1,471 @@
|
||||
/*
|
||||
* Minio Client (C) 2014, 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"syscall"
|
||||
|
||||
"github.com/cheggaaa/pb"
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
)
|
||||
|
||||
// cp command flags.
|
||||
var (
|
||||
cpFlags = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "recursive, r",
|
||||
Usage: "Copy recursively.",
|
||||
},
|
||||
cli.IntFlag{
|
||||
Name: "older-than",
|
||||
Usage: "Copy objects older than N days",
|
||||
},
|
||||
cli.IntFlag{
|
||||
Name: "newer-than",
|
||||
Usage: "Copy objects newer than N days",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "storage-class, sc",
|
||||
Usage: "Set storage class for object",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "encrypt-key",
|
||||
Usage: "Encrypt/Decrypt objects (using server-side encryption)",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
// Copy command.
|
||||
var cpCmd = cli.Command{
|
||||
Name: "cp",
|
||||
Usage: "Copy files and objects.",
|
||||
Action: mainCopy,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(cpFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} [FLAGS] SOURCE [SOURCE...] TARGET
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
|
||||
ENVIRONMENT VARIABLES:
|
||||
MC_ENCRYPT_KEY: List of comma delimited prefix=secret values
|
||||
|
||||
EXAMPLES:
|
||||
1. Copy a list of objects from local file system to Amazon S3 cloud storage.
|
||||
$ {{.HelpName}} Music/*.ogg s3/jukebox/
|
||||
|
||||
2. Copy a folder recursively from Minio cloud storage to Amazon S3 cloud storage.
|
||||
$ {{.HelpName}} --recursive play/mybucket/burningman2011/ s3/mybucket/
|
||||
|
||||
3. Copy multiple local folders recursively to Minio cloud storage.
|
||||
$ {{.HelpName}} --recursive backup/2014/ backup/2015/ play/archive/
|
||||
|
||||
4. Copy a bucket recursively from aliased Amazon S3 cloud storage to local filesystem on Windows.
|
||||
$ {{.HelpName}} --recursive s3\documents\2014\ C:\Backups\2014
|
||||
|
||||
5. Copy files older than 7 days from Minio cloud storage to Amazon S3 cloud storage.
|
||||
$ {{.HelpName}} --older-than 7 play/mybucket/burningman2011/ s3/mybucket/
|
||||
|
||||
6. Copy files newer than 7 days from Minio cloud storage to a local path.
|
||||
$ {{.HelpName}} --newer-than 7 play/mybucket/burningman2011/ ~/latest/
|
||||
|
||||
7. Copy an object with name containing unicode characters to Amazon S3 cloud storage.
|
||||
$ {{.HelpName}} 本語 s3/andoria/
|
||||
|
||||
8. Copy a local folder with space separated characters to Amazon S3 cloud storage.
|
||||
$ {{.HelpName}} --recursive 'workdir/documents/May 2014/' s3/miniocloud
|
||||
|
||||
9. Copy a folder with encrypted objects recursively from Amazon S3 to Minio cloud storage.
|
||||
$ {{.HelpName}} --recursive --encrypt-key "s3/documents/=32byteslongsecretkeymustbegiven1,myminio/documents/=32byteslongsecretkeymustbegiven2" s3/documents/ myminio/documents/
|
||||
`,
|
||||
}
|
||||
|
||||
// copyMessage container for file copy messages
|
||||
type copyMessage struct {
|
||||
Status string `json:"status"`
|
||||
Source string `json:"source"`
|
||||
Target string `json:"target"`
|
||||
Size int64 `json:"size"`
|
||||
TotalCount int64 `json:"totalCount"`
|
||||
TotalSize int64 `json:"totalSize"`
|
||||
}
|
||||
|
||||
// String colorized copy message
|
||||
func (c copyMessage) String() string {
|
||||
return console.Colorize("Copy", fmt.Sprintf("`%s` -> `%s`", c.Source, c.Target))
|
||||
}
|
||||
|
||||
// JSON jsonified copy message
|
||||
func (c copyMessage) JSON() string {
|
||||
c.Status = "success"
|
||||
copyMessageBytes, e := json.Marshal(c)
|
||||
fatalIf(probe.NewError(e), "Failed to marshal copy message.")
|
||||
|
||||
return string(copyMessageBytes)
|
||||
}
|
||||
|
||||
// copyStatMessage container for copy accounting message
|
||||
type copyStatMessage struct {
|
||||
Total int64
|
||||
Transferred int64
|
||||
Speed float64
|
||||
}
|
||||
|
||||
// copyStatMessage copy accounting message
|
||||
func (c copyStatMessage) String() string {
|
||||
speedBox := pb.Format(int64(c.Speed)).To(pb.U_BYTES).String()
|
||||
if speedBox == "" {
|
||||
speedBox = "0 MB"
|
||||
} else {
|
||||
speedBox = speedBox + "/s"
|
||||
}
|
||||
message := fmt.Sprintf("Total: %s, Transferred: %s, Speed: %s", pb.Format(c.Total).To(pb.U_BYTES),
|
||||
pb.Format(c.Transferred).To(pb.U_BYTES), speedBox)
|
||||
return message
|
||||
}
|
||||
|
||||
// Progress - an interface which describes current amount
|
||||
// of data written.
|
||||
type Progress interface {
|
||||
Get() int64
|
||||
}
|
||||
|
||||
// ProgressReader can be used to update the progress of
|
||||
// an on-going transfer progress.
|
||||
type ProgressReader interface {
|
||||
io.Reader
|
||||
Progress
|
||||
}
|
||||
|
||||
// doCopy - Copy a singe file from source to destination
|
||||
func doCopy(ctx context.Context, cpURLs URLs, pg ProgressReader) URLs {
|
||||
if cpURLs.Error != nil {
|
||||
cpURLs.Error = cpURLs.Error.Trace()
|
||||
return cpURLs
|
||||
}
|
||||
|
||||
sourceAlias := cpURLs.SourceAlias
|
||||
sourceURL := cpURLs.SourceContent.URL
|
||||
targetAlias := cpURLs.TargetAlias
|
||||
targetURL := cpURLs.TargetContent.URL
|
||||
length := cpURLs.SourceContent.Size
|
||||
|
||||
if progressReader, ok := pg.(*progressBar); ok {
|
||||
progressReader.SetCaption(cpURLs.SourceContent.URL.String() + ": ")
|
||||
} else {
|
||||
sourcePath := filepath.ToSlash(filepath.Join(sourceAlias, sourceURL.Path))
|
||||
targetPath := filepath.ToSlash(filepath.Join(targetAlias, targetURL.Path))
|
||||
printMsg(copyMessage{
|
||||
Source: sourcePath,
|
||||
Target: targetPath,
|
||||
Size: length,
|
||||
TotalCount: cpURLs.TotalCount,
|
||||
TotalSize: cpURLs.TotalSize,
|
||||
})
|
||||
}
|
||||
return uploadSourceToTargetURL(ctx, cpURLs, pg)
|
||||
}
|
||||
|
||||
// doCopyFake - Perform a fake copy to update the progress bar appropriately.
|
||||
func doCopyFake(cpURLs URLs, pg Progress) URLs {
|
||||
if progressReader, ok := pg.(*progressBar); ok {
|
||||
progressReader.ProgressBar.Add64(cpURLs.SourceContent.Size)
|
||||
}
|
||||
return cpURLs
|
||||
}
|
||||
|
||||
// doPrepareCopyURLs scans the source URL and prepares a list of objects for copying.
|
||||
func doPrepareCopyURLs(session *sessionV8, trapCh <-chan bool, cancelCopy context.CancelFunc) {
|
||||
// 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 int64
|
||||
|
||||
// Access recursive flag inside the session header.
|
||||
isRecursive := session.Header.CommandBoolFlags["recursive"]
|
||||
|
||||
olderThan := session.Header.CommandIntFlags["older-than"]
|
||||
newerThan := session.Header.CommandIntFlags["newer-than"]
|
||||
encryptKeys := session.Header.CommandStringFlags["encrypt-key"]
|
||||
encKeyDB, err := parseAndValidateEncryptionKeys(encryptKeys)
|
||||
fatalIf(err, "Unable to parse encryption keys.")
|
||||
|
||||
// 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, encKeyDB)
|
||||
done := false
|
||||
for !done {
|
||||
select {
|
||||
case cpURLs, ok := <-URLsCh:
|
||||
if !ok { // Done with URL preparation
|
||||
done = true
|
||||
break
|
||||
}
|
||||
if cpURLs.Error != nil {
|
||||
// Print in new line and adjust to top so that we don't print over the ongoing scan bar
|
||||
if !globalQuiet && !globalJSON {
|
||||
console.Eraseline()
|
||||
}
|
||||
if strings.Contains(cpURLs.Error.ToGoError().Error(), " is a folder.") {
|
||||
errorIf(cpURLs.Error.Trace(), "Folder cannot be copied. Please use `...` suffix.")
|
||||
} else {
|
||||
errorIf(cpURLs.Error.Trace(), "Unable to prepare URL for copying.")
|
||||
}
|
||||
break
|
||||
}
|
||||
|
||||
jsonData, e := json.Marshal(cpURLs)
|
||||
if e != nil {
|
||||
session.Delete()
|
||||
fatalIf(probe.NewError(e), "Unable to prepare URL for copying. Error in JSON marshaling.")
|
||||
}
|
||||
|
||||
// Skip objects older than --older-than parameter if specified
|
||||
if olderThan > 0 && isOlder(cpURLs.SourceContent, olderThan) {
|
||||
continue
|
||||
}
|
||||
|
||||
// Skip objects newer than --newer-than parameter if specified
|
||||
if newerThan > 0 && isNewer(cpURLs.SourceContent, newerThan) {
|
||||
continue
|
||||
}
|
||||
|
||||
fmt.Fprintln(dataFP, string(jsonData))
|
||||
if !globalQuiet && !globalJSON {
|
||||
scanBar(cpURLs.SourceContent.URL.String())
|
||||
}
|
||||
|
||||
totalBytes += cpURLs.SourceContent.Size
|
||||
totalObjects++
|
||||
case <-trapCh:
|
||||
cancelCopy()
|
||||
// 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 *sessionV8) error {
|
||||
trapCh := signalTrap(os.Interrupt, syscall.SIGTERM, syscall.SIGKILL)
|
||||
|
||||
ctx, cancelCopy := context.WithCancel(context.Background())
|
||||
defer cancelCopy()
|
||||
if !session.HasData() {
|
||||
doPrepareCopyURLs(session, trapCh, cancelCopy)
|
||||
}
|
||||
|
||||
// Prepare URL scanner from session data file.
|
||||
urlScanner := bufio.NewScanner(session.NewDataReader())
|
||||
// isCopied returns true if an object has been already copied
|
||||
// or not. This is useful when we resume from a session.
|
||||
isCopied := isLastFactory(session.Header.LastCopied)
|
||||
|
||||
// Store a progress bar or an accounter
|
||||
var pg ProgressReader
|
||||
|
||||
// Enable progress bar reader only during default mode.
|
||||
if !globalQuiet && !globalJSON { // set up progress bar
|
||||
pg = newProgressBar(session.Header.TotalBytes)
|
||||
} else {
|
||||
pg = newAccounter(session.Header.TotalBytes)
|
||||
}
|
||||
|
||||
var quitCh = make(chan struct{})
|
||||
var statusCh = make(chan URLs)
|
||||
|
||||
parallel, queueCh := newParallelManager(statusCh, pg)
|
||||
|
||||
go func() {
|
||||
gracefulStop := func() {
|
||||
close(queueCh)
|
||||
parallel.wait()
|
||||
close(statusCh)
|
||||
}
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-quitCh:
|
||||
gracefulStop()
|
||||
return
|
||||
default:
|
||||
if !urlScanner.Scan() {
|
||||
// No more entries, quit immediately
|
||||
gracefulStop()
|
||||
return
|
||||
}
|
||||
var cpURLs URLs
|
||||
// Unmarshal copyURLs from each line.
|
||||
json.Unmarshal([]byte(urlScanner.Text()), &cpURLs)
|
||||
|
||||
// Save total count.
|
||||
cpURLs.TotalCount = session.Header.TotalObjects
|
||||
|
||||
// Save totalSize.
|
||||
cpURLs.TotalSize = session.Header.TotalBytes
|
||||
|
||||
// Check and handle storage class if passed in command line args
|
||||
if _, ok := session.Header.CommandStringFlags["storage-class"]; ok {
|
||||
if cpURLs.TargetContent.Metadata == nil {
|
||||
cpURLs.TargetContent.Metadata = make(map[string]string)
|
||||
}
|
||||
cpURLs.TargetContent.Metadata["X-Amz-Storage-Class"] = session.Header.CommandStringFlags["storage-class"]
|
||||
}
|
||||
|
||||
// Verify if previously copied, notify progress bar.
|
||||
if isCopied(cpURLs.SourceContent.URL.String()) {
|
||||
queueCh <- func() URLs {
|
||||
return doCopyFake(cpURLs, pg)
|
||||
}
|
||||
} else {
|
||||
queueCh <- func() URLs {
|
||||
return doCopy(ctx, cpURLs, pg)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
var retErr error
|
||||
|
||||
loop:
|
||||
for {
|
||||
select {
|
||||
case <-trapCh:
|
||||
quitCh <- struct{}{}
|
||||
cancelCopy()
|
||||
// Receive interrupt notification.
|
||||
if !globalQuiet && !globalJSON {
|
||||
console.Eraseline()
|
||||
}
|
||||
session.CloseAndDie()
|
||||
case cpURLs, ok := <-statusCh:
|
||||
// Status channel is closed, we should return.
|
||||
if !ok {
|
||||
break loop
|
||||
}
|
||||
if cpURLs.Error == nil {
|
||||
session.Header.LastCopied = cpURLs.SourceContent.URL.String()
|
||||
session.Save()
|
||||
} else {
|
||||
|
||||
// Set exit status for any copy error
|
||||
retErr = exitStatus(globalErrorExitStatus)
|
||||
|
||||
// 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()))
|
||||
if isErrIgnored(cpURLs.Error) {
|
||||
continue loop
|
||||
}
|
||||
// For critical errors we should exit. Session
|
||||
// can be resumed after the user figures out
|
||||
// the problem.
|
||||
session.CloseAndDie()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if progressReader, ok := pg.(*progressBar); ok {
|
||||
if progressReader.ProgressBar.Get() > 0 {
|
||||
progressReader.ProgressBar.Finish()
|
||||
}
|
||||
} else {
|
||||
if accntReader, ok := pg.(*accounter); ok {
|
||||
console.Println(console.Colorize("Copy", accntReader.Stat().String()))
|
||||
}
|
||||
}
|
||||
|
||||
return retErr
|
||||
}
|
||||
|
||||
// mainCopy is the entry point for cp command.
|
||||
func mainCopy(ctx *cli.Context) error {
|
||||
// Parse encryption keys per command.
|
||||
encKeyDB, err := getEncKeys(ctx)
|
||||
fatalIf(err, "Unable to parse encryption keys.")
|
||||
|
||||
// check 'copy' cli arguments.
|
||||
checkCopySyntax(ctx, encKeyDB)
|
||||
|
||||
// Additional command speific theme customization.
|
||||
console.SetColor("Copy", color.New(color.FgGreen, color.Bold))
|
||||
|
||||
recursive := ctx.Bool("recursive")
|
||||
olderThan := ctx.Int("older-than")
|
||||
newerThan := ctx.Int("newer-than")
|
||||
storageClass := ctx.String("storage-class")
|
||||
sseKeys := os.Getenv("MC_ENCRYPT_KEY")
|
||||
if key := ctx.String("encrypt-key"); key != "" {
|
||||
sseKeys = key
|
||||
}
|
||||
|
||||
session := newSessionV8()
|
||||
session.Header.CommandType = "cp"
|
||||
session.Header.CommandBoolFlags["recursive"] = recursive
|
||||
session.Header.CommandIntFlags["older-than"] = olderThan
|
||||
session.Header.CommandIntFlags["newer-than"] = newerThan
|
||||
session.Header.CommandStringFlags["storage-class"] = storageClass
|
||||
session.Header.CommandStringFlags["encrypt-key"] = sseKeys
|
||||
|
||||
var e error
|
||||
if session.Header.RootPath, e = os.Getwd(); e != nil {
|
||||
session.Delete()
|
||||
fatalIf(probe.NewError(e), "Unable to get current working folder.")
|
||||
}
|
||||
|
||||
// extract URLs.
|
||||
session.Header.CommandArgs = ctx.Args()
|
||||
e = doCopySession(session)
|
||||
session.Delete()
|
||||
|
||||
return e
|
||||
}
|
||||
@@ -14,16 +14,16 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/client"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
)
|
||||
|
||||
func checkCopySyntax(ctx *cli.Context) {
|
||||
func checkCopySyntax(ctx *cli.Context, encKeyDB map[string][]prefixSSEPair) {
|
||||
if len(ctx.Args()) < 2 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "cp", 1) // last argument is exit code.
|
||||
}
|
||||
@@ -38,108 +38,113 @@ func checkCopySyntax(ctx *cli.Context) {
|
||||
tgtURL := URLs[len(URLs)-1]
|
||||
isRecursive := ctx.Bool("recursive")
|
||||
|
||||
/****** Generic Invalid Rules *******/
|
||||
// Verify if source(s) exists.
|
||||
for _, srcURL := range srcURLs {
|
||||
_, _, err := url2Stat(srcURL, false, encKeyDB)
|
||||
if err != nil {
|
||||
console.Fatalf("Unable to validate source %s\n", srcURL)
|
||||
}
|
||||
}
|
||||
|
||||
// Check if bucket name is passed for URL type arguments.
|
||||
url := client.NewURL(tgtURL)
|
||||
url := newClientURL(tgtURL)
|
||||
if url.Host != "" {
|
||||
// This check is for type URL.
|
||||
if !isURLVirtualHostStyle(url.Host) {
|
||||
if url.Path == string(url.Separator) {
|
||||
fatalIf(errInvalidArgument().Trace(), fmt.Sprintf("Target ‘%s’ does not contain bucket name.", tgtURL))
|
||||
}
|
||||
if url.Path == string(url.Separator) {
|
||||
fatalIf(errInvalidArgument().Trace(), fmt.Sprintf("Target `%s` does not contain bucket name.", tgtURL))
|
||||
}
|
||||
}
|
||||
|
||||
// Guess CopyURLsType based on source and target URLs.
|
||||
copyURLsType, err := guessCopyURLType(srcURLs, tgtURL, isRecursive)
|
||||
copyURLsType, err := guessCopyURLType(srcURLs, tgtURL, isRecursive, encKeyDB)
|
||||
if err != nil {
|
||||
fatalIf(errInvalidArgument().Trace(), "Unable to guess the type of copy operation.")
|
||||
}
|
||||
|
||||
switch copyURLsType {
|
||||
case copyURLsTypeA: // File -> File.
|
||||
checkCopySyntaxTypeA(srcURLs, tgtURL)
|
||||
checkCopySyntaxTypeA(srcURLs, tgtURL, encKeyDB)
|
||||
case copyURLsTypeB: // File -> Folder.
|
||||
checkCopySyntaxTypeB(srcURLs, tgtURL)
|
||||
checkCopySyntaxTypeB(srcURLs, tgtURL, encKeyDB)
|
||||
case copyURLsTypeC: // Folder... -> Folder.
|
||||
checkCopySyntaxTypeC(srcURLs, tgtURL, isRecursive)
|
||||
checkCopySyntaxTypeC(srcURLs, tgtURL, isRecursive, encKeyDB)
|
||||
case copyURLsTypeD: // File1...FileN -> Folder.
|
||||
checkCopySyntaxTypeD(srcURLs, tgtURL)
|
||||
checkCopySyntaxTypeD(srcURLs, tgtURL, encKeyDB)
|
||||
default:
|
||||
fatalIf(errInvalidArgument().Trace(), "Unable to guess the type of copy operation.")
|
||||
}
|
||||
}
|
||||
|
||||
// checkCopySyntaxTypeA verifies if the source and target are valid file arguments.
|
||||
func checkCopySyntaxTypeA(srcURLs []string, tgtURL string) {
|
||||
func checkCopySyntaxTypeA(srcURLs []string, tgtURL string, keys map[string][]prefixSSEPair) {
|
||||
// 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+"’.")
|
||||
_, srcContent, err := url2Stat(srcURL, false, keys)
|
||||
fatalIf(err.Trace(srcURL), "Unable to stat source `"+srcURL+"`.")
|
||||
|
||||
if !srcContent.Type.IsRegular() {
|
||||
fatalIf(errInvalidArgument().Trace(), "Source ‘"+srcURL+"’ is not a file.")
|
||||
fatalIf(errInvalidArgument().Trace(), "Source `"+srcURL+"` is not a file.")
|
||||
}
|
||||
}
|
||||
|
||||
// checkCopySyntaxTypeB verifies if the source is a valid file and target is a valid folder.
|
||||
func checkCopySyntaxTypeB(srcURLs []string, tgtURL string) {
|
||||
func checkCopySyntaxTypeB(srcURLs []string, tgtURL string, keys map[string][]prefixSSEPair) {
|
||||
// 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+"’.")
|
||||
_, srcContent, err := url2Stat(srcURL, false, keys)
|
||||
fatalIf(err.Trace(srcURL), "Unable to stat source `"+srcURL+"`.")
|
||||
|
||||
if !srcContent.Type.IsRegular() {
|
||||
fatalIf(errInvalidArgument().Trace(srcURL), "Source ‘"+srcURL+"’ is not a file.")
|
||||
fatalIf(errInvalidArgument().Trace(srcURL), "Source `"+srcURL+"` is not a file.")
|
||||
}
|
||||
|
||||
// Check target.
|
||||
if _, tgtContent, err := url2Stat(tgtURL); err == nil {
|
||||
if _, tgtContent, err := url2Stat(tgtURL, false, keys); err == nil {
|
||||
if !tgtContent.Type.IsDir() {
|
||||
fatalIf(errInvalidArgument().Trace(tgtURL), "Target ‘"+tgtURL+"’ is not a folder.")
|
||||
fatalIf(errInvalidArgument().Trace(tgtURL), "Target `"+tgtURL+"` is not a folder.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// checkCopySyntaxTypeC verifies if the source is a valid recursive dir and target is a valid folder.
|
||||
func checkCopySyntaxTypeC(srcURLs []string, tgtURL string, isRecursive bool) {
|
||||
func checkCopySyntaxTypeC(srcURLs []string, tgtURL string, isRecursive bool, keys map[string][]prefixSSEPair) {
|
||||
// Check source.
|
||||
if len(srcURLs) != 1 {
|
||||
fatalIf(errInvalidArgument().Trace(), "Invalid number of source arguments.")
|
||||
}
|
||||
|
||||
srcURL := srcURLs[0]
|
||||
_, srcContent, err := url2Stat(srcURL)
|
||||
_, srcContent, err := url2Stat(srcURL, false, keys)
|
||||
// incomplete uploads are not necessary for copy operation, no need to verify for them.
|
||||
isIncomplete := false
|
||||
if err != nil && !isURLPrefixExists(srcURL, isIncomplete) {
|
||||
fatalIf(err.Trace(srcURL), "Unable to stat source ‘"+srcURL+"’.")
|
||||
fatalIf(err.Trace(srcURL), "Unable to stat source `"+srcURL+"`.")
|
||||
}
|
||||
|
||||
if srcContent.Type.IsDir() && !isRecursive {
|
||||
fatalIf(errInvalidArgument().Trace(srcURL), "To copy a folder requires --recursive option.")
|
||||
fatalIf(errInvalidArgument().Trace(srcURL), "To copy a folder requires --recursive flag.")
|
||||
}
|
||||
|
||||
// Check target.
|
||||
if _, tgtContent, err := url2Stat(tgtURL); err == nil {
|
||||
if _, tgtContent, err := url2Stat(tgtURL, false, keys); err == nil {
|
||||
if !tgtContent.Type.IsDir() {
|
||||
fatalIf(errInvalidArgument().Trace(tgtURL), "Target ‘"+tgtURL+"’ is not a folder.")
|
||||
fatalIf(errInvalidArgument().Trace(tgtURL), "Target `"+tgtURL+"` is not a folder.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// checkCopySyntaxTypeD verifies if the source is a valid list of files and target is a valid folder.
|
||||
func checkCopySyntaxTypeD(srcURLs []string, tgtURL string) {
|
||||
func checkCopySyntaxTypeD(srcURLs []string, tgtURL string, keys map[string][]prefixSSEPair) {
|
||||
// Source can be anything: file, dir, dir...
|
||||
// Check target if it is a dir
|
||||
if _, tgtContent, err := url2Stat(tgtURL); err == nil {
|
||||
if _, tgtContent, err := url2Stat(tgtURL, false, keys); err == nil {
|
||||
if !tgtContent.Type.IsDir() {
|
||||
fatalIf(errInvalidArgument().Trace(tgtURL), "Target ‘"+tgtURL+"’ is not a folder.")
|
||||
fatalIf(errInvalidArgument().Trace(tgtURL), "Target `"+tgtURL+"` is not a folder.")
|
||||
}
|
||||
}
|
||||
}
|
||||
+71
-69
@@ -14,24 +14,15 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/minio/mc/pkg/client"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
)
|
||||
|
||||
type copyURLs struct {
|
||||
SourceAlias string
|
||||
SourceContent *client.Content
|
||||
TargetAlias string
|
||||
TargetContent *client.Content
|
||||
Error *probe.Error `json:"-"`
|
||||
}
|
||||
|
||||
type copyURLsType uint8
|
||||
|
||||
// NOTE: All the parse rules should reduced to A: Copy(Source, Target).
|
||||
@@ -57,12 +48,12 @@ const (
|
||||
copyURLsTypeD
|
||||
)
|
||||
|
||||
// guessCopyURLType guesses the type of URL. This approach all allows prepareURL
|
||||
// guessCopyURLType guesses the type of clientURL. This approach all allows prepareURL
|
||||
// functions to accurately report failure causes.
|
||||
func guessCopyURLType(sourceURLs []string, targetURL string, isRecursive bool) (copyURLsType, *probe.Error) {
|
||||
func guessCopyURLType(sourceURLs []string, targetURL string, isRecursive bool, keys map[string][]prefixSSEPair) (copyURLsType, *probe.Error) {
|
||||
if len(sourceURLs) == 1 { // 1 Source, 1 Target
|
||||
sourceURL := sourceURLs[0]
|
||||
_, sourceContent, err := url2Stat(sourceURL)
|
||||
_, sourceContent, err := url2Stat(sourceURL, false, keys)
|
||||
if err != nil {
|
||||
return copyURLsTypeInvalid, err
|
||||
}
|
||||
@@ -74,7 +65,7 @@ func guessCopyURLType(sourceURLs []string, targetURL string, isRecursive bool) (
|
||||
}
|
||||
|
||||
// If target is a folder, it is Type B.
|
||||
if isTargetURLDir(targetURL) {
|
||||
if isAliasURLDir(targetURL, keys) {
|
||||
return copyURLsTypeB, nil
|
||||
}
|
||||
// else Type A.
|
||||
@@ -82,7 +73,7 @@ func guessCopyURLType(sourceURLs []string, targetURL string, isRecursive bool) (
|
||||
}
|
||||
|
||||
// Multiple source args and target is a folder. It is Type D.
|
||||
if isTargetURLDir(targetURL) {
|
||||
if isAliasURLDir(targetURL, keys) {
|
||||
return copyURLsTypeD, nil
|
||||
}
|
||||
|
||||
@@ -90,97 +81,107 @@ func guessCopyURLType(sourceURLs []string, targetURL string, isRecursive bool) (
|
||||
}
|
||||
|
||||
// SINGLE SOURCE - Type A: copy(f, f) -> copy(f, f)
|
||||
// prepareCopyURLsTypeA - prepares target and source URLs for copying.
|
||||
func prepareCopyURLsTypeA(sourceURL string, targetURL string) copyURLs {
|
||||
// Extract alias before fiddling with the URL.
|
||||
// prepareCopyURLsTypeA - prepares target and source clientURLs for copying.
|
||||
func prepareCopyURLsTypeA(sourceURL string, targetURL string, encKeyDB map[string][]prefixSSEPair) URLs {
|
||||
// Extract alias before fiddling with the clientURL.
|
||||
sourceAlias, _, _ := mustExpandAlias(sourceURL)
|
||||
// Find alias and expanded URL.
|
||||
// Find alias and expanded clientURL.
|
||||
targetAlias, targetURL, _ := mustExpandAlias(targetURL)
|
||||
|
||||
_, sourceContent, err := url2Stat(sourceURL)
|
||||
_, sourceContent, err := url2Stat(sourceURL, false, encKeyDB)
|
||||
if err != nil {
|
||||
// Source does not exist or insufficient privileges.
|
||||
return copyURLs{Error: err.Trace(sourceURL)}
|
||||
return URLs{Error: err.Trace(sourceURL)}
|
||||
}
|
||||
if !sourceContent.Type.IsRegular() {
|
||||
// Source is not a regular file
|
||||
return copyURLs{Error: errInvalidSource(sourceURL).Trace(sourceURL)}
|
||||
return URLs{Error: errInvalidSource(sourceURL).Trace(sourceURL)}
|
||||
}
|
||||
if sourceContent.URL.String() == targetURL {
|
||||
// source and target can not be same
|
||||
return copyURLs{Error: errSourceTargetSame(sourceURL).Trace(sourceURL)}
|
||||
return URLs{Error: errSourceTargetSame(sourceURL).Trace(sourceURL)}
|
||||
}
|
||||
|
||||
// All OK.. We can proceed. Type A
|
||||
return makeCopyContentTypeA(sourceAlias, sourceContent, targetAlias, targetURL)
|
||||
return makeCopyContentTypeA(sourceAlias, sourceContent, targetAlias, targetURL, encKeyDB)
|
||||
}
|
||||
|
||||
// prepareCopyContentTypeA - makes CopyURLs content for copying.
|
||||
func makeCopyContentTypeA(sourceAlias string, sourceContent *client.Content, targetAlias string, targetURL string) copyURLs {
|
||||
return copyURLs{
|
||||
func makeCopyContentTypeA(sourceAlias string, sourceContent *clientContent, targetAlias string, targetURL string, encKeyDB map[string][]prefixSSEPair) URLs {
|
||||
targetContent := clientContent{URL: *newClientURL(targetURL)}
|
||||
|
||||
sourcePath := filepath.ToSlash(filepath.Join(sourceAlias, sourceContent.URL.Path))
|
||||
targetPath := filepath.ToSlash(filepath.Join(targetAlias, targetContent.URL.Path))
|
||||
|
||||
srcSSEKey := getSSEKey(sourcePath, encKeyDB[sourceAlias])
|
||||
tgtSSEKey := getSSEKey(targetPath, encKeyDB[targetAlias])
|
||||
|
||||
return URLs{
|
||||
SourceAlias: sourceAlias,
|
||||
SourceContent: sourceContent,
|
||||
TargetAlias: targetAlias,
|
||||
TargetContent: &client.Content{URL: *client.NewURL(targetURL)},
|
||||
TargetContent: &targetContent,
|
||||
SrcSSEKey: srcSSEKey,
|
||||
TgtSSEKey: tgtSSEKey,
|
||||
}
|
||||
}
|
||||
|
||||
// SINGLE SOURCE - Type B: copy(f, d) -> copy(f, d/f) -> A
|
||||
// prepareCopyURLsTypeB - prepares target and source URLs for copying.
|
||||
func prepareCopyURLsTypeB(sourceURL string, targetURL string) copyURLs {
|
||||
// Extract alias before fiddling with the URL.
|
||||
// prepareCopyURLsTypeB - prepares target and source clientURLs for copying.
|
||||
func prepareCopyURLsTypeB(sourceURL string, targetURL string, encKeyDB map[string][]prefixSSEPair) URLs {
|
||||
// Extract alias before fiddling with the clientURL.
|
||||
sourceAlias, _, _ := mustExpandAlias(sourceURL)
|
||||
// Find alias and expanded URL.
|
||||
// Find alias and expanded clientURL.
|
||||
targetAlias, targetURL, _ := mustExpandAlias(targetURL)
|
||||
|
||||
_, sourceContent, err := url2Stat(sourceURL)
|
||||
_, sourceContent, err := url2Stat(sourceURL, false, encKeyDB)
|
||||
if err != nil {
|
||||
// Source does not exist or insufficient privileges.
|
||||
return copyURLs{Error: err.Trace(sourceURL)}
|
||||
return URLs{Error: err.Trace(sourceURL)}
|
||||
}
|
||||
|
||||
if !sourceContent.Type.IsRegular() {
|
||||
if sourceContent.Type.IsDir() {
|
||||
return copyURLs{Error: errSourceIsDir(sourceURL).Trace(sourceURL)}
|
||||
return URLs{Error: errSourceIsDir(sourceURL).Trace(sourceURL)}
|
||||
}
|
||||
// Source is not a regular file.
|
||||
return copyURLs{Error: errInvalidSource(sourceURL).Trace(sourceURL)}
|
||||
return URLs{Error: errInvalidSource(sourceURL).Trace(sourceURL)}
|
||||
}
|
||||
|
||||
// All OK.. We can proceed. Type B: source is a file, target is a folder and exists.
|
||||
return makeCopyContentTypeB(sourceAlias, sourceContent, targetAlias, targetURL)
|
||||
return makeCopyContentTypeB(sourceAlias, sourceContent, targetAlias, targetURL, encKeyDB)
|
||||
}
|
||||
|
||||
// makeCopyContentTypeB - CopyURLs content for copying.
|
||||
func makeCopyContentTypeB(sourceAlias string, sourceContent *client.Content, targetAlias string, targetURL string) copyURLs {
|
||||
func makeCopyContentTypeB(sourceAlias string, sourceContent *clientContent, targetAlias string, targetURL string, encKeyDB map[string][]prefixSSEPair) URLs {
|
||||
// All OK.. We can proceed. Type B: source is a file, target is a folder and exists.
|
||||
targetURLParse := client.NewURL(targetURL)
|
||||
targetURLParse := newClientURL(targetURL)
|
||||
targetURLParse.Path = filepath.ToSlash(filepath.Join(targetURLParse.Path, filepath.Base(sourceContent.URL.Path)))
|
||||
return makeCopyContentTypeA(sourceAlias, sourceContent, targetAlias, targetURLParse.String())
|
||||
return makeCopyContentTypeA(sourceAlias, sourceContent, targetAlias, targetURLParse.String(), encKeyDB)
|
||||
}
|
||||
|
||||
// SINGLE SOURCE - Type C: copy(d1..., d2) -> []copy(d1/f, d1/d2/f) -> []A
|
||||
// prepareCopyRecursiveURLTypeC - prepares target and source URLs for copying.
|
||||
func prepareCopyURLsTypeC(sourceURL, targetURL string, isRecursive bool) <-chan copyURLs {
|
||||
// Extract alias before fiddling with the URL.
|
||||
// prepareCopyRecursiveURLTypeC - prepares target and source clientURLs for copying.
|
||||
func prepareCopyURLsTypeC(sourceURL, targetURL string, isRecursive bool, encKeyDB map[string][]prefixSSEPair) <-chan URLs {
|
||||
// Extract alias before fiddling with the clientURL.
|
||||
sourceAlias, _, _ := mustExpandAlias(sourceURL)
|
||||
// Find alias and expanded URL.
|
||||
// Find alias and expanded clientURL.
|
||||
targetAlias, targetURL, _ := mustExpandAlias(targetURL)
|
||||
|
||||
copyURLsCh := make(chan copyURLs)
|
||||
go func(sourceURL, targetURL string, copyURLsCh chan copyURLs) {
|
||||
copyURLsCh := make(chan URLs)
|
||||
go func(sourceURL, targetURL string, copyURLsCh chan URLs) {
|
||||
defer close(copyURLsCh)
|
||||
sourceClient, err := newClient(sourceURL)
|
||||
if err != nil {
|
||||
// Source initialization failed.
|
||||
copyURLsCh <- copyURLs{Error: err.Trace(sourceURL)}
|
||||
copyURLsCh <- URLs{Error: err.Trace(sourceURL)}
|
||||
return
|
||||
}
|
||||
|
||||
for sourceContent := range sourceClient.List(isRecursive, false) {
|
||||
isIncomplete := false
|
||||
for sourceContent := range sourceClient.List(isRecursive, isIncomplete, DirNone) {
|
||||
if sourceContent.Err != nil {
|
||||
// Listing failed.
|
||||
copyURLsCh <- copyURLs{Error: sourceContent.Err.Trace(sourceClient.GetURL().String())}
|
||||
copyURLsCh <- URLs{Error: sourceContent.Err.Trace(sourceClient.GetURL().String())}
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -190,14 +191,14 @@ func prepareCopyURLsTypeC(sourceURL, targetURL string, isRecursive bool) <-chan
|
||||
}
|
||||
|
||||
// All OK.. We can proceed. Type B: source is a file, target is a folder and exists.
|
||||
copyURLsCh <- makeCopyContentTypeC(sourceAlias, sourceClient.GetURL(), sourceContent, targetAlias, targetURL)
|
||||
copyURLsCh <- makeCopyContentTypeC(sourceAlias, sourceClient.GetURL(), sourceContent, targetAlias, targetURL, encKeyDB)
|
||||
}
|
||||
}(sourceURL, targetURL, copyURLsCh)
|
||||
return copyURLsCh
|
||||
}
|
||||
|
||||
// makeCopyContentTypeC - CopyURLs content for copying.
|
||||
func makeCopyContentTypeC(sourceAlias string, sourceURL client.URL, sourceContent *client.Content, targetAlias string, targetURL string) copyURLs {
|
||||
func makeCopyContentTypeC(sourceAlias string, sourceURL clientURL, sourceContent *clientContent, targetAlias string, targetURL string, encKeyDB map[string][]prefixSSEPair) URLs {
|
||||
newSourceURL := sourceContent.URL
|
||||
pathSeparatorIndex := strings.LastIndex(sourceURL.Path, string(sourceURL.Separator))
|
||||
newSourceSuffix := filepath.ToSlash(newSourceURL.Path)
|
||||
@@ -206,17 +207,17 @@ func makeCopyContentTypeC(sourceAlias string, sourceURL client.URL, sourceConten
|
||||
newSourceSuffix = strings.TrimPrefix(newSourceSuffix, sourcePrefix)
|
||||
}
|
||||
newTargetURL := urlJoinPath(targetURL, newSourceSuffix)
|
||||
return makeCopyContentTypeA(sourceAlias, sourceContent, targetAlias, newTargetURL)
|
||||
return makeCopyContentTypeA(sourceAlias, sourceContent, targetAlias, newTargetURL, encKeyDB)
|
||||
}
|
||||
|
||||
// MULTI-SOURCE - Type D: copy([](f|d...), d) -> []B
|
||||
// prepareCopyURLsTypeE - prepares target and source URLs for copying.
|
||||
func prepareCopyURLsTypeD(sourceURLs []string, targetURL string, isRecursive bool) <-chan copyURLs {
|
||||
copyURLsCh := make(chan copyURLs)
|
||||
go func(sourceURLs []string, targetURL string, copyURLsCh chan copyURLs) {
|
||||
// prepareCopyURLsTypeE - prepares target and source clientURLs for copying.
|
||||
func prepareCopyURLsTypeD(sourceURLs []string, targetURL string, isRecursive bool, encKeyDB map[string][]prefixSSEPair) <-chan URLs {
|
||||
copyURLsCh := make(chan URLs)
|
||||
go func(sourceURLs []string, targetURL string, copyURLsCh chan URLs) {
|
||||
defer close(copyURLsCh)
|
||||
for _, sourceURL := range sourceURLs {
|
||||
for cpURLs := range prepareCopyURLsTypeC(sourceURL, targetURL, isRecursive) {
|
||||
for cpURLs := range prepareCopyURLsTypeC(sourceURL, targetURL, isRecursive, encKeyDB) {
|
||||
copyURLsCh <- cpURLs
|
||||
}
|
||||
}
|
||||
@@ -224,30 +225,31 @@ func prepareCopyURLsTypeD(sourceURLs []string, targetURL string, isRecursive boo
|
||||
return copyURLsCh
|
||||
}
|
||||
|
||||
// prepareCopyURLs - prepares target and source URLs for copying.
|
||||
func prepareCopyURLs(sourceURLs []string, targetURL string, isRecursive bool) <-chan copyURLs {
|
||||
copyURLsCh := make(chan copyURLs)
|
||||
go func(sourceURLs []string, targetURL string, copyURLsCh chan copyURLs) {
|
||||
// prepareCopyURLs - prepares target and source clientURLs for copying.
|
||||
func prepareCopyURLs(sourceURLs []string, targetURL string, isRecursive bool, encKeyDB map[string][]prefixSSEPair) <-chan URLs {
|
||||
copyURLsCh := make(chan URLs)
|
||||
go func(sourceURLs []string, targetURL string, copyURLsCh chan URLs, encKeyDB map[string][]prefixSSEPair) {
|
||||
defer close(copyURLsCh)
|
||||
cpType, err := guessCopyURLType(sourceURLs, targetURL, isRecursive)
|
||||
cpType, err := guessCopyURLType(sourceURLs, targetURL, isRecursive, encKeyDB)
|
||||
fatalIf(err.Trace(), "Unable to guess the type of copy operation.")
|
||||
|
||||
switch cpType {
|
||||
case copyURLsTypeA:
|
||||
copyURLsCh <- prepareCopyURLsTypeA(sourceURLs[0], targetURL)
|
||||
copyURLsCh <- prepareCopyURLsTypeA(sourceURLs[0], targetURL, encKeyDB)
|
||||
case copyURLsTypeB:
|
||||
copyURLsCh <- prepareCopyURLsTypeB(sourceURLs[0], targetURL)
|
||||
copyURLsCh <- prepareCopyURLsTypeB(sourceURLs[0], targetURL, encKeyDB)
|
||||
case copyURLsTypeC:
|
||||
for cURLs := range prepareCopyURLsTypeC(sourceURLs[0], targetURL, isRecursive) {
|
||||
for cURLs := range prepareCopyURLsTypeC(sourceURLs[0], targetURL, isRecursive, encKeyDB) {
|
||||
copyURLsCh <- cURLs
|
||||
}
|
||||
case copyURLsTypeD:
|
||||
for cURLs := range prepareCopyURLsTypeD(sourceURLs, targetURL, isRecursive) {
|
||||
for cURLs := range prepareCopyURLsTypeD(sourceURLs, targetURL, isRecursive, encKeyDB) {
|
||||
copyURLsCh <- cURLs
|
||||
}
|
||||
default:
|
||||
copyURLsCh <- copyURLs{Error: errInvalidArgument().Trace(sourceURLs...)}
|
||||
copyURLsCh <- URLs{Error: errInvalidArgument().Trace(sourceURLs...)}
|
||||
}
|
||||
}(sourceURLs, targetURL, copyURLsCh)
|
||||
}(sourceURLs, targetURL, copyURLsCh, encKeyDB)
|
||||
|
||||
return copyURLsCh
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
/*
|
||||
* Minio Client (C) 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
)
|
||||
|
||||
// diff specific flags.
|
||||
var (
|
||||
diffFlags = []cli.Flag{}
|
||||
)
|
||||
|
||||
// Compute differences between two files or folders.
|
||||
var diffCmd = cli.Command{
|
||||
Name: "diff",
|
||||
Usage: "List differences in object name, size, and date between folders.",
|
||||
Action: mainDiff,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(diffFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} [FLAGS] FIRST SECOND
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
DESCRIPTION:
|
||||
Diff only calculates differences in object name, size and time.
|
||||
It *DOES NOT* compare objects' contents.
|
||||
|
||||
LEGEND:
|
||||
> - object is only in source.
|
||||
< - object is only in destination.
|
||||
! - newer object is in source.
|
||||
|
||||
EXAMPLES:
|
||||
1. Compare a local folder with a folder on Amazon S3 cloud storage.
|
||||
$ {{.HelpName}} ~/Photos s3/mybucket/Photos
|
||||
|
||||
2. Compare two folders on a local filesystem.
|
||||
$ {{.HelpName}} ~/Photos /Media/Backup/Photos
|
||||
`,
|
||||
}
|
||||
|
||||
// diffMessage json container for diff messages
|
||||
type diffMessage struct {
|
||||
Status string `json:"status"`
|
||||
FirstURL string `json:"first"`
|
||||
SecondURL string `json:"second"`
|
||||
Diff differType `json:"diff"`
|
||||
Error *probe.Error `json:"error,omitempty"`
|
||||
firstContent *clientContent
|
||||
secondContent *clientContent
|
||||
}
|
||||
|
||||
// String colorized diff message
|
||||
func (d diffMessage) String() string {
|
||||
msg := ""
|
||||
switch d.Diff {
|
||||
case differInFirst:
|
||||
msg = console.Colorize("DiffOnlyInFirst", "< "+d.FirstURL)
|
||||
case differInSecond:
|
||||
msg = console.Colorize("DiffOnlyInSecond", "> "+d.SecondURL)
|
||||
case differInType:
|
||||
msg = console.Colorize("DiffType", "! "+d.SecondURL)
|
||||
case differInSize:
|
||||
msg = console.Colorize("DiffSize", "! "+d.SecondURL)
|
||||
case differInTime:
|
||||
msg = console.Colorize("DiffTime", "! "+d.SecondURL)
|
||||
default:
|
||||
fatalIf(errDummy().Trace(d.FirstURL, d.SecondURL),
|
||||
"Unhandled difference between `"+d.FirstURL+"` and `"+d.SecondURL+"`.")
|
||||
}
|
||||
return msg
|
||||
|
||||
}
|
||||
|
||||
// JSON jsonified diff message
|
||||
func (d diffMessage) JSON() string {
|
||||
d.Status = "success"
|
||||
diffJSONBytes, e := json.Marshal(d)
|
||||
fatalIf(probe.NewError(e),
|
||||
"Unable to marshal diff message `"+d.FirstURL+"`, `"+d.SecondURL+"` and `"+string(d.Diff)+"`.")
|
||||
return string(diffJSONBytes)
|
||||
}
|
||||
|
||||
func checkDiffSyntax(ctx *cli.Context, encKeyDB map[string][]prefixSSEPair) {
|
||||
if len(ctx.Args()) != 2 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "diff", 1) // last argument is exit code
|
||||
}
|
||||
for _, arg := range ctx.Args() {
|
||||
if strings.TrimSpace(arg) == "" {
|
||||
fatalIf(errInvalidArgument().Trace(ctx.Args()...), "Unable to validate empty argument.")
|
||||
}
|
||||
}
|
||||
URLs := ctx.Args()
|
||||
firstURL := URLs[0]
|
||||
secondURL := URLs[1]
|
||||
|
||||
// Diff only works between two directories, verify them below.
|
||||
|
||||
// Verify if firstURL is accessible.
|
||||
_, firstContent, err := url2Stat(firstURL, false, encKeyDB)
|
||||
if err != nil {
|
||||
fatalIf(err.Trace(firstURL), fmt.Sprintf("Unable to stat '%s'.", firstURL))
|
||||
}
|
||||
|
||||
// Verify if its a directory.
|
||||
if !firstContent.Type.IsDir() {
|
||||
fatalIf(errInvalidArgument().Trace(firstURL), fmt.Sprintf("`%s` is not a folder.", firstURL))
|
||||
}
|
||||
|
||||
// Verify if secondURL is accessible.
|
||||
_, secondContent, err := url2Stat(secondURL, false, encKeyDB)
|
||||
if err != nil {
|
||||
fatalIf(err.Trace(secondURL), fmt.Sprintf("Unable to stat '%s'.", secondURL))
|
||||
}
|
||||
|
||||
// Verify if its a directory.
|
||||
if !secondContent.Type.IsDir() {
|
||||
fatalIf(errInvalidArgument().Trace(secondURL), fmt.Sprintf("`%s` is not a folder.", secondURL))
|
||||
}
|
||||
}
|
||||
|
||||
// doDiffMain runs the diff.
|
||||
func doDiffMain(firstURL, secondURL string) error {
|
||||
// Source and targets are always directories
|
||||
sourceSeparator := string(newClientURL(firstURL).Separator)
|
||||
if !strings.HasSuffix(firstURL, sourceSeparator) {
|
||||
firstURL = firstURL + sourceSeparator
|
||||
}
|
||||
targetSeparator := string(newClientURL(secondURL).Separator)
|
||||
if !strings.HasSuffix(secondURL, targetSeparator) {
|
||||
secondURL = secondURL + targetSeparator
|
||||
}
|
||||
|
||||
// Expand aliased urls.
|
||||
firstAlias, firstURL, _ := mustExpandAlias(firstURL)
|
||||
secondAlias, secondURL, _ := mustExpandAlias(secondURL)
|
||||
|
||||
firstClient, err := newClientFromAlias(firstAlias, firstURL)
|
||||
if err != nil {
|
||||
fatalIf(err.Trace(firstAlias, firstURL, secondAlias, secondURL),
|
||||
fmt.Sprintf("Failed to diff '%s' and '%s'", firstURL, secondURL))
|
||||
}
|
||||
|
||||
secondClient, err := newClientFromAlias(secondAlias, secondURL)
|
||||
if err != nil {
|
||||
fatalIf(err.Trace(firstAlias, firstURL, secondAlias, secondURL),
|
||||
fmt.Sprintf("Failed to diff '%s' and '%s'", firstURL, secondURL))
|
||||
}
|
||||
|
||||
// Diff first and second urls.
|
||||
for diffMsg := range objectDifference(firstClient, secondClient, firstURL, secondURL) {
|
||||
if diffMsg.Error != nil {
|
||||
errorIf(diffMsg.Error, "Unable to calculate objects difference.")
|
||||
// Ignore error and proceed to next object.
|
||||
continue
|
||||
}
|
||||
printMsg(diffMsg)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// mainDiff main for 'diff'.
|
||||
func mainDiff(ctx *cli.Context) error {
|
||||
// Parse encryption keys per command.
|
||||
encKeyDB, err := getEncKeys(ctx)
|
||||
fatalIf(err, "Unable to parse encryption keys.")
|
||||
|
||||
// check 'diff' cli arguments.
|
||||
checkDiffSyntax(ctx, encKeyDB)
|
||||
|
||||
// Additional command specific theme customization.
|
||||
console.SetColor("DiffMessage", color.New(color.FgGreen, color.Bold))
|
||||
console.SetColor("DiffOnlyInFirst", color.New(color.FgRed))
|
||||
console.SetColor("DiffOnlyInSecond", color.New(color.FgGreen))
|
||||
console.SetColor("DiffType", color.New(color.FgMagenta))
|
||||
console.SetColor("DiffSize", color.New(color.FgYellow, color.Bold))
|
||||
console.SetColor("DiffTime", color.New(color.FgYellow, color.Bold))
|
||||
|
||||
URLs := ctx.Args()
|
||||
firstURL := URLs.Get(0)
|
||||
secondURL := URLs.Get(1)
|
||||
|
||||
return doDiffMain(firstURL, secondURL)
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
/*
|
||||
* Minio Client (C) 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
// golang does not support flat keys for path matching, find does
|
||||
|
||||
"golang.org/x/text/unicode/norm"
|
||||
)
|
||||
|
||||
// differType difference in type.
|
||||
type differType int
|
||||
|
||||
const (
|
||||
differInNone differType = iota // does not differ
|
||||
differInSize // differs in size
|
||||
differInTime // differs in time
|
||||
differInType // only in source
|
||||
differInFirst // only in target
|
||||
differInSecond // differs in type, exfile/directory
|
||||
)
|
||||
|
||||
func (d differType) String() string {
|
||||
switch d {
|
||||
case differInNone:
|
||||
return ""
|
||||
case differInSize:
|
||||
return "size"
|
||||
case differInTime:
|
||||
return "time"
|
||||
case differInType:
|
||||
return "type"
|
||||
case differInFirst:
|
||||
return "only-in-first"
|
||||
case differInSecond:
|
||||
return "only-in-second"
|
||||
}
|
||||
return "unknown"
|
||||
}
|
||||
|
||||
func objectDifference(sourceClnt, targetClnt Client, sourceURL, targetURL string) (diffCh chan diffMessage) {
|
||||
return difference(sourceClnt, targetClnt, sourceURL, targetURL, true, false, DirNone)
|
||||
}
|
||||
|
||||
func dirDifference(sourceClnt, targetClnt Client, sourceURL, targetURL string) (diffCh chan diffMessage) {
|
||||
return difference(sourceClnt, targetClnt, sourceURL, targetURL, false, true, DirFirst)
|
||||
}
|
||||
|
||||
// objectDifference function finds the difference between all objects
|
||||
// recursively in sorted order from source and target.
|
||||
func difference(sourceClnt, targetClnt Client, sourceURL, targetURL string, isRecursive, returnSimilar bool, dirOpt DirOpt) (diffCh chan diffMessage) {
|
||||
var (
|
||||
srcEOF, tgtEOF bool
|
||||
srcOk, tgtOk bool
|
||||
srcCtnt, tgtCtnt *clientContent
|
||||
srcSuffix, tgtSuffix string
|
||||
)
|
||||
|
||||
// Set default values for listing.
|
||||
isIncomplete := false // we will not compare any incomplete objects.
|
||||
srcCh := sourceClnt.List(isRecursive, isIncomplete, dirOpt)
|
||||
tgtCh := targetClnt.List(isRecursive, isIncomplete, dirOpt)
|
||||
|
||||
diffCh = make(chan diffMessage, 1000)
|
||||
|
||||
go func() {
|
||||
|
||||
srcCtnt, srcOk = <-srcCh
|
||||
tgtCtnt, tgtOk = <-tgtCh
|
||||
|
||||
defer close(diffCh)
|
||||
|
||||
for {
|
||||
srcEOF = !srcOk
|
||||
tgtEOF = !tgtOk
|
||||
|
||||
// No objects from source AND target: Finish
|
||||
if srcEOF && tgtEOF {
|
||||
break
|
||||
}
|
||||
|
||||
if !srcEOF && srcCtnt.Err != nil {
|
||||
diffCh <- diffMessage{Error: srcCtnt.Err.Trace(sourceURL, targetURL)}
|
||||
return
|
||||
}
|
||||
|
||||
if !tgtEOF && tgtCtnt.Err != nil {
|
||||
diffCh <- diffMessage{Error: tgtCtnt.Err.Trace(sourceURL, targetURL)}
|
||||
return
|
||||
}
|
||||
|
||||
// If source doesn't have objects anymore, comparison becomes obvious
|
||||
if srcEOF {
|
||||
diffCh <- diffMessage{
|
||||
SecondURL: tgtCtnt.URL.String(),
|
||||
Diff: differInSecond,
|
||||
secondContent: tgtCtnt,
|
||||
}
|
||||
tgtCtnt, tgtOk = <-tgtCh
|
||||
continue
|
||||
}
|
||||
|
||||
// The same for target
|
||||
if tgtEOF {
|
||||
diffCh <- diffMessage{
|
||||
FirstURL: srcCtnt.URL.String(),
|
||||
Diff: differInFirst,
|
||||
firstContent: srcCtnt,
|
||||
}
|
||||
srcCtnt, srcOk = <-srcCh
|
||||
continue
|
||||
}
|
||||
|
||||
srcSuffix = strings.TrimPrefix(srcCtnt.URL.String(), sourceURL)
|
||||
tgtSuffix = strings.TrimPrefix(tgtCtnt.URL.String(), targetURL)
|
||||
|
||||
current := urlJoinPath(targetURL, srcSuffix)
|
||||
expected := urlJoinPath(targetURL, tgtSuffix)
|
||||
|
||||
if !utf8.ValidString(srcSuffix) {
|
||||
// Error. Keys must be valid UTF-8.
|
||||
diffCh <- diffMessage{Error: errInvalidSource(current).Trace()}
|
||||
srcCtnt, srcOk = <-srcCh
|
||||
continue
|
||||
}
|
||||
if !utf8.ValidString(tgtSuffix) {
|
||||
// Error. Keys must be valid UTF-8.
|
||||
diffCh <- diffMessage{Error: errInvalidTarget(expected).Trace()}
|
||||
tgtCtnt, tgtOk = <-tgtCh
|
||||
continue
|
||||
}
|
||||
|
||||
// Normalize to avoid situations where multiple byte representations are possible.
|
||||
// e.g. 'ä' can be represented as precomposed U+00E4 (UTF-8 0xc3a4) or decomposed
|
||||
// U+0061 U+0308 (UTF-8 0x61cc88).
|
||||
normalizedCurrent := norm.NFC.String(current)
|
||||
normalizedExpected := norm.NFC.String(expected)
|
||||
|
||||
if normalizedExpected > normalizedCurrent {
|
||||
diffCh <- diffMessage{
|
||||
FirstURL: srcCtnt.URL.String(),
|
||||
Diff: differInFirst,
|
||||
firstContent: srcCtnt,
|
||||
}
|
||||
srcCtnt, srcOk = <-srcCh
|
||||
continue
|
||||
}
|
||||
if normalizedExpected == normalizedCurrent {
|
||||
srcType, tgtType := srcCtnt.Type, tgtCtnt.Type
|
||||
srcSize, tgtSize := srcCtnt.Size, tgtCtnt.Size
|
||||
srcTime, tgtTime := srcCtnt.Time, tgtCtnt.Time
|
||||
if srcType.IsRegular() && !tgtType.IsRegular() ||
|
||||
!srcType.IsRegular() && tgtType.IsRegular() {
|
||||
// Type differs. Source is never a directory.
|
||||
diffCh <- diffMessage{
|
||||
FirstURL: srcCtnt.URL.String(),
|
||||
SecondURL: tgtCtnt.URL.String(),
|
||||
Diff: differInType,
|
||||
firstContent: srcCtnt,
|
||||
secondContent: tgtCtnt,
|
||||
}
|
||||
continue
|
||||
}
|
||||
if (srcType.IsRegular() && tgtType.IsRegular()) && srcSize != tgtSize {
|
||||
// Regular files differing in size.
|
||||
diffCh <- diffMessage{
|
||||
FirstURL: srcCtnt.URL.String(),
|
||||
SecondURL: tgtCtnt.URL.String(),
|
||||
Diff: differInSize,
|
||||
firstContent: srcCtnt,
|
||||
secondContent: tgtCtnt,
|
||||
}
|
||||
} else if srcTime.After(tgtTime) {
|
||||
// Regular files differing in timestamp.
|
||||
diffCh <- diffMessage{
|
||||
FirstURL: srcCtnt.URL.String(),
|
||||
SecondURL: tgtCtnt.URL.String(),
|
||||
Diff: differInTime,
|
||||
firstContent: srcCtnt,
|
||||
secondContent: tgtCtnt,
|
||||
}
|
||||
}
|
||||
// No differ
|
||||
if returnSimilar {
|
||||
diffCh <- diffMessage{
|
||||
FirstURL: srcCtnt.URL.String(),
|
||||
SecondURL: tgtCtnt.URL.String(),
|
||||
Diff: differInNone,
|
||||
firstContent: srcCtnt,
|
||||
secondContent: tgtCtnt,
|
||||
}
|
||||
}
|
||||
srcCtnt, srcOk = <-srcCh
|
||||
tgtCtnt, tgtOk = <-tgtCh
|
||||
continue
|
||||
}
|
||||
// Differ in second
|
||||
diffCh <- diffMessage{
|
||||
SecondURL: tgtCtnt.URL.String(),
|
||||
Diff: differInSecond,
|
||||
secondContent: tgtCtnt,
|
||||
}
|
||||
tgtCtnt, tgtOk = <-tgtCh
|
||||
continue
|
||||
}
|
||||
}()
|
||||
|
||||
return diffCh
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
/*
|
||||
* Minio Client (C) 2017 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
var testCases = []struct {
|
||||
pattern []string
|
||||
|
||||
object string
|
||||
|
||||
match bool
|
||||
}{
|
||||
{nil, "testfile", false},
|
||||
{[]string{"test*"}, "testfile", true},
|
||||
{[]string{"file*"}, "file/abc/bcd/def", true},
|
||||
{[]string{"*"}, "file/abc/bcd/def", true},
|
||||
{[]string{""}, "file/abc/bcd/def", false},
|
||||
{[]string{"abc*"}, "file/abc/bcd/def", false},
|
||||
{[]string{"abc*", "*abc/*"}, "file/abc/bcd/def", true},
|
||||
{[]string{"*.txt"}, "file/abc/bcd/def.txt", true},
|
||||
{[]string{".*"}, ".sys", true},
|
||||
{[]string{"*."}, ".sys.", true},
|
||||
}
|
||||
|
||||
func TestExcludeOptions(t *testing.T) {
|
||||
for _, test := range testCases {
|
||||
if matchExcludeOptions(test.pattern, test.object) != test.match {
|
||||
t.Fatalf("Unexpected result %t, with pattern %s and object %s \n", !test.match, test.pattern, test.object)
|
||||
}
|
||||
}
|
||||
}
|
||||
+17
-5
@@ -14,14 +14,15 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
)
|
||||
|
||||
// causeMessage container for golang error messages
|
||||
@@ -40,7 +41,7 @@ type errorMessage struct {
|
||||
}
|
||||
|
||||
// fatalIf wrapper function which takes error and selectively prints stack frames if available on debug
|
||||
func fatalIf(err *probe.Error, msg string) {
|
||||
func fatalIf(err *probe.Error, msg string, data ...interface{}) {
|
||||
if err == nil {
|
||||
return
|
||||
}
|
||||
@@ -70,20 +71,30 @@ func fatalIf(err *probe.Error, msg string) {
|
||||
console.Println(string(json))
|
||||
console.Fatalln()
|
||||
}
|
||||
msg = fmt.Sprintf(msg, data...)
|
||||
if !globalDebug {
|
||||
console.Fatalln(fmt.Sprintf("%s %s", msg, err.ToGoError()))
|
||||
}
|
||||
console.Fatalln(fmt.Sprintf("%s %s", msg, err))
|
||||
}
|
||||
|
||||
// Exit coder wraps cli new exit error with a
|
||||
// custom exitStatus number. cli package requires
|
||||
// an error with `cli.ExitCoder` compatibility
|
||||
// after an action. Which woud allow cli package to
|
||||
// exit with the specified `exitStatus`.
|
||||
func exitStatus(status int) error {
|
||||
return cli.NewExitError("", status)
|
||||
}
|
||||
|
||||
// errorIf synonymous with fatalIf but doesn't exit on error != nil
|
||||
func errorIf(err *probe.Error, msg string) {
|
||||
func errorIf(err *probe.Error, msg string, data ...interface{}) {
|
||||
if err == nil {
|
||||
return
|
||||
}
|
||||
if globalJSON {
|
||||
errorMsg := errorMessage{
|
||||
Message: msg,
|
||||
Message: fmt.Sprintf(msg, data...),
|
||||
Type: "error",
|
||||
Cause: causeMessage{
|
||||
Message: err.ToGoError().Error(),
|
||||
@@ -107,6 +118,7 @@ func errorIf(err *probe.Error, msg string) {
|
||||
console.Println(string(json))
|
||||
return
|
||||
}
|
||||
msg = fmt.Sprintf(msg, data...)
|
||||
if !globalDebug {
|
||||
console.Errorln(fmt.Sprintf("%s %s", msg, err.ToGoError()))
|
||||
return
|
||||
@@ -0,0 +1,134 @@
|
||||
/*
|
||||
* Minio Client (C) 2016 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
)
|
||||
|
||||
var (
|
||||
eventsAddFlags = []cli.Flag{
|
||||
cli.StringFlag{
|
||||
Name: "events",
|
||||
Value: "put,delete,get",
|
||||
Usage: "Filter specific type of events. Defaults to all events.",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "prefix",
|
||||
Usage: "Filter events associated to the specified prefix",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "suffix",
|
||||
Usage: "Filter events associated to the specified suffix",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
var eventsAddCmd = cli.Command{
|
||||
Name: "add",
|
||||
Usage: "Add a new bucket notification.",
|
||||
Action: mainEventsAdd,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(eventsAddFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} TARGET ARN [FLAGS]
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Enable bucket notification with a specific arn
|
||||
$ {{.HelpName}} myminio/mybucket arn:aws:sqs:us-west-2:444455556666:your-queue
|
||||
|
||||
2. Enable bucket notification with filters parameters
|
||||
$ {{.HelpName}} s3/mybucket arn:aws:sqs:us-west-2:444455556666:your-queue --events put,delete,get --prefix photos/ --suffix .jpg
|
||||
|
||||
`,
|
||||
}
|
||||
|
||||
// checkEventsAddSyntax - validate all the passed arguments
|
||||
func checkEventsAddSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) != 2 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "add", 1) // last argument is exit code
|
||||
}
|
||||
}
|
||||
|
||||
// eventsAddMessage container
|
||||
type eventsAddMessage struct {
|
||||
ARN string `json:"arn"`
|
||||
Events []string `json:"events"`
|
||||
Prefix string `json:"prefix"`
|
||||
Suffix string `json:"suffix"`
|
||||
Status string `json:"status"`
|
||||
}
|
||||
|
||||
// JSON jsonified update message.
|
||||
func (u eventsAddMessage) JSON() string {
|
||||
u.Status = "success"
|
||||
eventsAddMessageJSONBytes, e := json.Marshal(u)
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
return string(eventsAddMessageJSONBytes)
|
||||
}
|
||||
|
||||
func (u eventsAddMessage) String() string {
|
||||
msg := console.Colorize("Events", "Successfully added "+u.ARN)
|
||||
return msg
|
||||
}
|
||||
|
||||
func mainEventsAdd(ctx *cli.Context) error {
|
||||
console.SetColor("Events", color.New(color.FgGreen, color.Bold))
|
||||
|
||||
checkEventsAddSyntax(ctx)
|
||||
|
||||
args := ctx.Args()
|
||||
path := args[0]
|
||||
arn := args[1]
|
||||
|
||||
events := strings.Split(ctx.String("events"), ",")
|
||||
prefix := ctx.String("prefix")
|
||||
suffix := ctx.String("suffix")
|
||||
|
||||
client, err := newClient(path)
|
||||
if err != nil {
|
||||
fatalIf(err.Trace(), "Cannot parse the provided url.")
|
||||
}
|
||||
|
||||
s3Client, ok := client.(*s3Client)
|
||||
if !ok {
|
||||
fatalIf(errDummy().Trace(), "The provided url doesn't point to a S3 server.")
|
||||
}
|
||||
|
||||
err = s3Client.AddNotificationConfig(arn, events, prefix, suffix)
|
||||
fatalIf(err, "Cannot enable notification on the specified bucket.")
|
||||
printMsg(eventsAddMessage{
|
||||
ARN: arn,
|
||||
Events: events,
|
||||
Prefix: prefix,
|
||||
Suffix: suffix,
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
/*
|
||||
* Minio Client (C) 2016 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
)
|
||||
|
||||
var (
|
||||
eventsListFlags = []cli.Flag{}
|
||||
)
|
||||
|
||||
var eventsListCmd = cli.Command{
|
||||
Name: "list",
|
||||
Usage: "List bucket notifications.",
|
||||
Action: mainEventsList,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(eventsListFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} TARGET ARN [FLAGS]
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. List notification configurations associated to a specific arn
|
||||
$ {{.HelpName}} myminio/mybucket arn:aws:sqs:us-west-2:444455556666:your-queue
|
||||
|
||||
2. List all notification configurations
|
||||
$ {{.HelpName}} s3/mybucket
|
||||
|
||||
`,
|
||||
}
|
||||
|
||||
// checkEventsListSyntax - validate all the passed arguments
|
||||
func checkEventsListSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) != 2 && len(ctx.Args()) != 1 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "list", 1) // last argument is exit code
|
||||
}
|
||||
}
|
||||
|
||||
// eventsListMessage container
|
||||
type eventsListMessage struct {
|
||||
Status string `json:"status"`
|
||||
ID string `json:"id"`
|
||||
Events []string `json:"events"`
|
||||
Prefix string `json:"prefix"`
|
||||
Suffix string `json:"suffix"`
|
||||
Arn string `json:"arn"`
|
||||
}
|
||||
|
||||
func (u eventsListMessage) JSON() string {
|
||||
u.Status = "success"
|
||||
eventsListMessageJSONBytes, e := json.Marshal(u)
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
return string(eventsListMessageJSONBytes)
|
||||
}
|
||||
|
||||
func (u eventsListMessage) String() string {
|
||||
msg := console.Colorize("ARN", fmt.Sprintf("%s ", u.Arn))
|
||||
for i, event := range u.Events {
|
||||
msg += console.Colorize("Events", event)
|
||||
if i != len(u.Events)-1 {
|
||||
msg += ","
|
||||
}
|
||||
}
|
||||
msg += console.Colorize("Filter", fmt.Sprintf(" Filter: "))
|
||||
if u.Prefix != "" {
|
||||
msg += console.Colorize("Filter", fmt.Sprintf("prefix=\"%s\"", u.Prefix))
|
||||
}
|
||||
if u.Suffix != "" {
|
||||
msg += console.Colorize("Filter", fmt.Sprintf("suffix=\"%s\"", u.Suffix))
|
||||
}
|
||||
return msg
|
||||
}
|
||||
|
||||
func mainEventsList(ctx *cli.Context) error {
|
||||
console.SetColor("ARN", color.New(color.FgGreen, color.Bold))
|
||||
console.SetColor("Events", color.New(color.FgCyan, color.Bold))
|
||||
console.SetColor("Filter", color.New(color.Bold))
|
||||
|
||||
checkEventsListSyntax(ctx)
|
||||
|
||||
args := ctx.Args()
|
||||
path := args[0]
|
||||
arn := ""
|
||||
if len(args) > 1 {
|
||||
arn = args[1]
|
||||
}
|
||||
|
||||
client, err := newClient(path)
|
||||
if err != nil {
|
||||
fatalIf(err.Trace(), "Cannot parse the provided url.")
|
||||
}
|
||||
|
||||
s3Client, ok := client.(*s3Client)
|
||||
if !ok {
|
||||
fatalIf(errDummy().Trace(), "The provided url doesn't point to a S3 server.")
|
||||
}
|
||||
|
||||
configs, err := s3Client.ListNotificationConfigs(arn)
|
||||
fatalIf(err, "Cannot list notifications on the specified bucket.")
|
||||
|
||||
for _, config := range configs {
|
||||
printMsg(eventsListMessage{Events: config.Events,
|
||||
Prefix: config.Prefix,
|
||||
Suffix: config.Suffix,
|
||||
Arn: config.Arn,
|
||||
ID: config.ID})
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
/*
|
||||
* Minio Client (C) 2016 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import "github.com/minio/cli"
|
||||
|
||||
var (
|
||||
eventsFlags = []cli.Flag{}
|
||||
)
|
||||
|
||||
var eventsCmd = cli.Command{
|
||||
Name: "events",
|
||||
Usage: "Manage object notifications.",
|
||||
HideHelpCommand: true,
|
||||
Action: mainEvents,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(eventsFlags, globalFlags...),
|
||||
Subcommands: []cli.Command{
|
||||
eventsAddCmd,
|
||||
eventsRemoveCmd,
|
||||
eventsListCmd,
|
||||
},
|
||||
}
|
||||
|
||||
// mainEvents is the handle for "mc events" command.
|
||||
func mainEvents(ctx *cli.Context) error {
|
||||
cli.ShowCommandHelp(ctx, ctx.Args().First())
|
||||
return nil
|
||||
// Sub-commands like "add", "remove", "list" have their own main.
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
/*
|
||||
* Minio Client (C) 2016 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
)
|
||||
|
||||
var (
|
||||
eventsRemoveFlags = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "force",
|
||||
Usage: "Force removing all bucket notifications",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
var eventsRemoveCmd = cli.Command{
|
||||
Name: "remove",
|
||||
Usage: "Remove a bucket notification. With '--force' can remove all bucket notifications.",
|
||||
Action: mainEventsRemove,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(eventsRemoveFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} TARGET [ARN] [FLAGS]
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Remove bucket notification associated to a specific arn
|
||||
$ {{.HelpName}} myminio/mybucket arn:aws:sqs:us-west-2:444455556666:your-queue
|
||||
|
||||
2. Remove all bucket notifications. --force flag is mandatory here
|
||||
$ {{.HelpName}} myminio/mybucket --force
|
||||
|
||||
`,
|
||||
}
|
||||
|
||||
// checkEventsRemoveSyntax - validate all the passed arguments
|
||||
func checkEventsRemoveSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) == 0 || len(ctx.Args()) > 2 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "remove", 1) // last argument is exit code
|
||||
}
|
||||
if len(ctx.Args()) == 1 && !ctx.Bool("force") {
|
||||
fatalIf(probe.NewError(errors.New("")), "--force flag needs to be passed to remove all bucket notifications.")
|
||||
}
|
||||
}
|
||||
|
||||
// eventsRemoveMessage container
|
||||
type eventsRemoveMessage struct {
|
||||
ARN string `json:"arn"`
|
||||
Status string `json:"status"`
|
||||
}
|
||||
|
||||
// JSON jsonified remove message.
|
||||
func (u eventsRemoveMessage) JSON() string {
|
||||
u.Status = "success"
|
||||
eventsRemoveMessageJSONBytes, e := json.Marshal(u)
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
return string(eventsRemoveMessageJSONBytes)
|
||||
}
|
||||
|
||||
func (u eventsRemoveMessage) String() string {
|
||||
msg := console.Colorize("Events", "Successfully removed "+u.ARN)
|
||||
return msg
|
||||
}
|
||||
|
||||
func mainEventsRemove(ctx *cli.Context) error {
|
||||
console.SetColor("Events", color.New(color.FgGreen, color.Bold))
|
||||
|
||||
checkEventsRemoveSyntax(ctx)
|
||||
|
||||
args := ctx.Args()
|
||||
path := args.Get(0)
|
||||
|
||||
arn := ""
|
||||
if len(args) == 2 {
|
||||
arn = args.Get(1)
|
||||
}
|
||||
|
||||
client, err := newClient(path)
|
||||
if err != nil {
|
||||
fatalIf(err.Trace(), "Cannot parse the provided url.")
|
||||
}
|
||||
|
||||
s3Client, ok := client.(*s3Client)
|
||||
if !ok {
|
||||
fatalIf(errDummy().Trace(), "The provided url doesn't point to a S3 server.")
|
||||
}
|
||||
|
||||
err = s3Client.RemoveNotificationConfig(arn)
|
||||
fatalIf(err, "Cannot disable notification on the specified bucket.")
|
||||
printMsg(eventsRemoveMessage{ARN: arn})
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,288 @@
|
||||
/*
|
||||
* Minio Client (C) 2017 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
humanize "github.com/dustin/go-humanize"
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
)
|
||||
|
||||
// List of all flags supported by find command.
|
||||
var (
|
||||
findFlags = []cli.Flag{
|
||||
cli.StringFlag{
|
||||
Name: "exec",
|
||||
Usage: "Spawn an external process for each matching object (see FORMAT)",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "ignore",
|
||||
Usage: "Exclude objects matching the wildcard pattern",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "name",
|
||||
Usage: "Find object names matching wildcard pattern",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "newer",
|
||||
Usage: "Match all objects newer than specified time in units (see UNITS)",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "older",
|
||||
Usage: "Match all objects older than specified time in units (see UNITS)",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "path",
|
||||
Usage: "Match directory names matching wildcard pattern",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "print",
|
||||
Usage: "Print in custom format to STDOUT (see FORMAT)",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "regex",
|
||||
Usage: "Match directory and object name with PCRE regex pattern",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "larger",
|
||||
Usage: "Match all objects larger than specified size in units (see UNITS)",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "smaller",
|
||||
Usage: "Match all objects smaller than specified size in units (see UNITS)",
|
||||
},
|
||||
cli.UintFlag{
|
||||
Name: "maxdepth",
|
||||
Usage: "Limit directory navigation to specified depth",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "watch",
|
||||
Usage: "Monitor a specified path for newly created files and objects",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
var findCmd = cli.Command{
|
||||
Name: "find",
|
||||
Usage: "Search for files and objects.",
|
||||
Action: mainFind,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(findFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} PATH [FLAGS]
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
UNITS
|
||||
--smaller, --larger flags accept human-readable case-insensitive number
|
||||
suffixes such as "k", "m", "g" and "t" referring to the metric units KB,
|
||||
MB, GB and TB respectively. Adding an "i" to these prefixes, uses the IEC
|
||||
units, so that "gi" refers to "gibibyte" or "GiB". A "b" at the end is
|
||||
also accepted. Without suffixes the unit is bytes.
|
||||
|
||||
--older, --newer flags accept the suffixes "d", "w", "m" and "y" to refer
|
||||
to units of days, weeks, months and years respectively. With the standard
|
||||
rate of conversion being 7 days in 1 week, 30 days in 1 month, and 365
|
||||
days in one year.
|
||||
|
||||
FORMAT
|
||||
Support string substitutions with special interpretations for following keywords.
|
||||
Keywords supported if target is filesystem or object storage:
|
||||
|
||||
{} --> Substitutes to full path.
|
||||
{base} --> Substitutes to basename of path.
|
||||
{dir} --> Substitutes to dirname of the path.
|
||||
{size} --> Substitutes to file size of the path.
|
||||
{time} --> Substitutes to file modified time of the path.
|
||||
|
||||
Keywords supported if target is object storage:
|
||||
|
||||
{url} --> Substitutes to a shareable URL of the path.
|
||||
|
||||
EXAMPLES:
|
||||
01. Find all "foo.jpg" in all buckets under "s3" account.
|
||||
$ {{.HelpName}} s3 --name "foo.jpg"
|
||||
|
||||
02. Find all objects with ".txt" extension under "s3/mybucket".
|
||||
$ {{.HelpName}} s3/mybucket --name "*.txt"
|
||||
|
||||
03. Find only the object names without the directory component under "s3/mybucket".
|
||||
$ {{.HelpName}} s3/mybucket --name "*" -print {base}
|
||||
|
||||
04. Find all images with ".jpg" extension under "s3/photos", prefixed with "album".
|
||||
$ {{.HelpName}} s3/photos --name "*.jpg" --path "*/album*/*"
|
||||
|
||||
05. Find all images with ".jpg", ".png", and ".gif" extensions, using regex under "s3/photos".
|
||||
$ {{.HelpName}} s3/photos --regex "(?i)\.(jpg|png|gif)$"
|
||||
|
||||
06. Find all images with ".jpg" extension under "s3/bucket" and copy to "play/bucket" *continuously*.
|
||||
$ {{.HelpName}} s3/bucket --name "*.jpg" --watch --exec "mc cp {} play/bucket"
|
||||
|
||||
07. Find and generate public URLs valid for 7 days, for all objects between 64 MB, and 1 GB in size under "s3" account.
|
||||
$ {{.HelpName}} s3 --larger 64MB --smaller 1GB --print {url}
|
||||
|
||||
08. Find all objects created in the last week under "s3/bucket".
|
||||
$ {{.HelpName}} s3/bucket --newer 1w
|
||||
|
||||
09. Find all objects which were created more than 6 months ago, and exclude the ones with ".jpg"
|
||||
extension under "s3".
|
||||
$ {{.HelpName}} s3 --older 6m --ignore "*.jpg"
|
||||
|
||||
10. List all objects up to 3 levels sub-directory deep under "s3/bucket".
|
||||
$ {{.HelpName}} s3/bucket --maxdepth 3
|
||||
|
||||
`,
|
||||
}
|
||||
|
||||
// checkFindSyntax - validate the passed arguments
|
||||
func checkFindSyntax(ctx *cli.Context, encKeyDB map[string][]prefixSSEPair) {
|
||||
args := ctx.Args()
|
||||
if !args.Present() {
|
||||
args = []string{"./"} // No args just default to present directory.
|
||||
} else if args.Get(0) == "." {
|
||||
args[0] = "./" // If the arg is '.' treat it as './'.
|
||||
}
|
||||
|
||||
for _, arg := range args {
|
||||
if strings.TrimSpace(arg) == "" {
|
||||
fatalIf(errInvalidArgument().Trace(args...), "Unable to validate empty argument.")
|
||||
}
|
||||
}
|
||||
|
||||
// Extract input URLs and validate.
|
||||
for _, url := range args {
|
||||
_, _, err := url2Stat(url, false, encKeyDB)
|
||||
if err != nil && !isURLPrefixExists(url, false) {
|
||||
// Bucket name empty is a valid error for 'find myminio' unless we are using watch, treat it as such.
|
||||
if _, ok := err.ToGoError().(BucketNameEmpty); ok && !ctx.Bool("watch") {
|
||||
continue
|
||||
}
|
||||
fatalIf(err.Trace(url), "Unable to stat `"+url+"`.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Find context is container to hold all parsed input arguments,
|
||||
// each parsed input is stored in its native typed form for
|
||||
// ease of repurposing.
|
||||
type findContext struct {
|
||||
*cli.Context
|
||||
execCmd string
|
||||
ignorePattern string
|
||||
namePattern string
|
||||
pathPattern string
|
||||
regexPattern string
|
||||
maxDepth uint
|
||||
printFmt string
|
||||
olderThan time.Time
|
||||
newerThan time.Time
|
||||
largerSize uint64
|
||||
smallerSize uint64
|
||||
watch bool
|
||||
|
||||
// Internal values
|
||||
targetAlias string
|
||||
targetURL string
|
||||
targetFullURL string
|
||||
clnt Client
|
||||
}
|
||||
|
||||
// mainFind - handler for mc find commands
|
||||
func mainFind(ctx *cli.Context) error {
|
||||
// Additional command specific theme customization.
|
||||
console.SetColor("Find", color.New(color.FgGreen, color.Bold))
|
||||
console.SetColor("FindExecErr", color.New(color.FgRed, color.Italic, color.Bold))
|
||||
|
||||
// Parse encryption keys per command.
|
||||
encKeyDB, err := getEncKeys(ctx)
|
||||
fatalIf(err, "Unable to parse encryption keys.")
|
||||
|
||||
checkFindSyntax(ctx, encKeyDB)
|
||||
|
||||
args := ctx.Args()
|
||||
if !args.Present() {
|
||||
args = []string{"./"} // Not args present default to present directory.
|
||||
} else if args.Get(0) == "." {
|
||||
args[0] = "./" // If the arg is '.' treat it as './'.
|
||||
}
|
||||
|
||||
clnt, err := newClient(args[0])
|
||||
fatalIf(err.Trace(args...), "Unable to initialize `"+args[0]+"`.")
|
||||
|
||||
var olderThan, newerThan time.Time
|
||||
|
||||
if ctx.String("older") != "" {
|
||||
olderThan, err = parseTime(ctx.String("older"))
|
||||
fatalIf(err.Trace(ctx.String("older")), "Unable to parse input time.")
|
||||
}
|
||||
if ctx.String("newer") != "" {
|
||||
newerThan, err = parseTime(ctx.String("newer"))
|
||||
fatalIf(err.Trace(ctx.String("newer")), "Unable to parse input time.")
|
||||
}
|
||||
|
||||
// Use 'e' to indicate Go error, this is a convention followed in `mc`. For probe.Error we call it
|
||||
// 'err' and regular Go error is called as 'e'.
|
||||
var e error
|
||||
var largerSize, smallerSize uint64
|
||||
|
||||
if ctx.String("larger") != "" {
|
||||
largerSize, e = humanize.ParseBytes(ctx.String("larger"))
|
||||
fatalIf(probe.NewError(e).Trace(ctx.String("larger")), "Unable to parse input bytes.")
|
||||
}
|
||||
|
||||
if ctx.String("smaller") != "" {
|
||||
smallerSize, e = humanize.ParseBytes(ctx.String("smaller"))
|
||||
fatalIf(probe.NewError(e).Trace(ctx.String("smaller")), "Unable to parse input bytes.")
|
||||
}
|
||||
|
||||
targetAlias, _, hostCfg, err := expandAlias(args[0])
|
||||
fatalIf(err.Trace(args[0]), "Unable to expand alias.")
|
||||
|
||||
var targetFullURL string
|
||||
if hostCfg != nil {
|
||||
targetFullURL = hostCfg.URL
|
||||
}
|
||||
|
||||
return doFind(&findContext{
|
||||
Context: ctx,
|
||||
maxDepth: ctx.Uint("maxdepth"),
|
||||
execCmd: ctx.String("exec"),
|
||||
printFmt: ctx.String("print"),
|
||||
namePattern: ctx.String("name"),
|
||||
pathPattern: ctx.String("path"),
|
||||
regexPattern: ctx.String("regex"),
|
||||
ignorePattern: ctx.String("ignore"),
|
||||
olderThan: olderThan,
|
||||
newerThan: newerThan,
|
||||
largerSize: largerSize,
|
||||
smallerSize: smallerSize,
|
||||
watch: ctx.Bool("watch"),
|
||||
targetAlias: targetAlias,
|
||||
targetURL: args[0],
|
||||
targetFullURL: targetFullURL,
|
||||
clnt: clnt,
|
||||
})
|
||||
}
|
||||
+480
@@ -0,0 +1,480 @@
|
||||
/*
|
||||
* Minio Client (C) 2017 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/dustin/go-humanize"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
|
||||
// golang does not support flat keys for path matching, find does
|
||||
"github.com/minio/minio/pkg/wildcard"
|
||||
)
|
||||
|
||||
// findMessage holds JSON and string values for printing find command output.
|
||||
type findMessage struct {
|
||||
contentMessage
|
||||
}
|
||||
|
||||
// String calls tells the console what to print and how to print it.
|
||||
func (f findMessage) String() string {
|
||||
return console.Colorize("Find", f.contentMessage.Key)
|
||||
}
|
||||
|
||||
// JSON formats output to be JSON output.
|
||||
func (f findMessage) JSON() string {
|
||||
return f.contentMessage.JSON()
|
||||
}
|
||||
|
||||
// nameMatch is similar to filepath.Match but only matches the
|
||||
// base path of the input, if we couldn't find a match we
|
||||
// also proceed to look for similar strings alone and print it.
|
||||
//
|
||||
// pattern:
|
||||
// { term }
|
||||
// term:
|
||||
// '*' matches any sequence of non-Separator characters
|
||||
// '?' matches any single non-Separator character
|
||||
// '[' [ '^' ] { character-range } ']'
|
||||
// character class (must be non-empty)
|
||||
// c matches character c (c != '*', '?', '\\', '[')
|
||||
// '\\' c matches character c
|
||||
// character-range:
|
||||
// c matches character c (c != '\\', '-', ']')
|
||||
// '\\' c matches character c
|
||||
// lo '-' hi matches character c for lo <= c <= hi
|
||||
//
|
||||
func nameMatch(pattern, path string) bool {
|
||||
matched, e := filepath.Match(pattern, filepath.Base(path))
|
||||
errorIf(probe.NewError(e).Trace(pattern, path), "Unable to match with input pattern.")
|
||||
if !matched {
|
||||
for _, pathComponent := range strings.Split(path, "/") {
|
||||
matched = pathComponent == pattern
|
||||
if matched {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return matched
|
||||
}
|
||||
|
||||
// pathMatch reports whether path matches the wildcard pattern.
|
||||
// supports '*' and '?' wildcards in the pattern string.
|
||||
// unlike path.Match(), considers a path as a flat name space
|
||||
// while matching the pattern. The difference is illustrated in
|
||||
// the example here https://play.golang.org/p/Ega9qgD4Qz .
|
||||
func pathMatch(pattern, path string) bool {
|
||||
return wildcard.Match(pattern, path)
|
||||
}
|
||||
|
||||
// regexMatch reports whether path matches the regex pattern.
|
||||
func regexMatch(pattern, path string) bool {
|
||||
matched, e := regexp.MatchString(pattern, path)
|
||||
errorIf(probe.NewError(e).Trace(pattern), "Unable to regex match with input pattern.")
|
||||
return matched
|
||||
}
|
||||
|
||||
func getExitStatus(err error) int {
|
||||
if err == nil {
|
||||
return 0
|
||||
}
|
||||
if pe, ok := err.(*exec.ExitError); ok {
|
||||
if es, ok := pe.ProcessState.Sys().(syscall.WaitStatus); ok {
|
||||
return es.ExitStatus()
|
||||
}
|
||||
}
|
||||
return 1
|
||||
}
|
||||
|
||||
// execFind executes the input command line, additionally formats input
|
||||
// for the command line in accordance with subsititution arguments.
|
||||
func execFind(command string) {
|
||||
commandArgs := strings.Split(command, " ")
|
||||
|
||||
cmd := exec.Command(commandArgs[0], commandArgs[1:]...)
|
||||
var out bytes.Buffer
|
||||
var stderr bytes.Buffer
|
||||
cmd.Stdout = &out
|
||||
cmd.Stderr = &stderr
|
||||
if err := cmd.Run(); err != nil {
|
||||
console.Print(console.Colorize("FindExecErr", stderr.String()))
|
||||
// Return exit status of the command run
|
||||
os.Exit(getExitStatus(err))
|
||||
}
|
||||
console.PrintC(out.String())
|
||||
}
|
||||
|
||||
// watchFind - enables listening on the input path, listens for all file/object
|
||||
// created actions. Asynchronously executes the input command line, also allows
|
||||
// formatting for the command line in accordance with subsititution arguments.
|
||||
func watchFind(ctx *findContext) {
|
||||
// Watch is not enabled, return quickly.
|
||||
if !ctx.watch {
|
||||
return
|
||||
}
|
||||
params := watchParams{
|
||||
recursive: true,
|
||||
events: []string{"put"},
|
||||
}
|
||||
watchObj, err := ctx.clnt.Watch(params)
|
||||
fatalIf(err.Trace(ctx.targetAlias), "Cannot watch with given params.")
|
||||
|
||||
// Enables users to kill using the control + c
|
||||
trapCh := signalTrap(os.Interrupt, syscall.SIGTERM)
|
||||
|
||||
// Loop until user CTRL-C the command line.
|
||||
for {
|
||||
select {
|
||||
case <-trapCh:
|
||||
console.Println()
|
||||
close(watchObj.doneChan)
|
||||
return
|
||||
case event, ok := <-watchObj.Events():
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
time, e := time.Parse(time.RFC3339, event.Time)
|
||||
if e != nil {
|
||||
errorIf(probe.NewError(e).Trace(event.Time), "Unable to parse event time.")
|
||||
continue
|
||||
}
|
||||
|
||||
find(ctx, contentMessage{
|
||||
Key: getAliasedPath(ctx, event.Path),
|
||||
Time: time,
|
||||
Size: event.Size,
|
||||
})
|
||||
|
||||
case err, ok := <-watchObj.Errors():
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
errorIf(err, "Unable to watch for events.")
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Descend at most (a non-negative integer) levels of files
|
||||
// below the starting-prefix and trims the suffix. This function
|
||||
// returns path as is without manipulation if the maxDepth is 0
|
||||
// i.e (not set).
|
||||
func trimSuffixAtMaxDepth(startPrefix, path, separator string, maxDepth uint) string {
|
||||
if maxDepth == 0 {
|
||||
return path
|
||||
}
|
||||
// Remove the requested prefix from consideration, maxDepth is
|
||||
// only considered for all other levels excluding the starting prefix.
|
||||
path = strings.TrimPrefix(path, startPrefix)
|
||||
pathComponents := strings.SplitAfter(path, separator)
|
||||
if len(pathComponents) >= int(maxDepth) {
|
||||
pathComponents = pathComponents[:maxDepth]
|
||||
}
|
||||
pathComponents = append([]string{startPrefix}, pathComponents...)
|
||||
return strings.Join(pathComponents, "")
|
||||
}
|
||||
|
||||
// Get aliased path used finally in printing, trim paths to ensure
|
||||
// that we have removed the fully qualified paths and original
|
||||
// start prefix (targetAlias) is retained. This function also honors
|
||||
// maxDepth if set then the resultant path will be trimmed at requested
|
||||
// maxDepth.
|
||||
func getAliasedPath(ctx *findContext, path string) string {
|
||||
separator := string(ctx.clnt.GetURL().Separator)
|
||||
prefixPath := ctx.clnt.GetURL().String()
|
||||
var aliasedPath string
|
||||
if ctx.targetAlias != "" {
|
||||
aliasedPath = ctx.targetAlias + strings.TrimPrefix(path, ctx.targetFullURL)
|
||||
} else {
|
||||
aliasedPath = path
|
||||
// look for prefix path, if found filter at that, Watch calls
|
||||
// for example always provide absolute path. So for relative
|
||||
// prefixes we need to employ this kind of code.
|
||||
if i := strings.Index(path, prefixPath); i > 0 {
|
||||
aliasedPath = path[i:]
|
||||
}
|
||||
}
|
||||
return trimSuffixAtMaxDepth(ctx.targetURL, aliasedPath, separator, ctx.maxDepth)
|
||||
}
|
||||
|
||||
func find(ctx *findContext, fileContent contentMessage) {
|
||||
// Match the incoming content, didn't match return.
|
||||
if !matchFind(ctx, fileContent) {
|
||||
return
|
||||
} // For all matching content
|
||||
|
||||
// proceed to either exec, format the output string.
|
||||
if ctx.execCmd != "" {
|
||||
execFind(stringsReplace(ctx.execCmd, fileContent))
|
||||
return
|
||||
}
|
||||
if ctx.printFmt != "" {
|
||||
fileContent.Key = stringsReplace(ctx.printFmt, fileContent)
|
||||
}
|
||||
printMsg(findMessage{fileContent})
|
||||
}
|
||||
|
||||
// doFind - find is main function body which interprets and executes
|
||||
// all the input parameters.
|
||||
func doFind(ctx *findContext) error {
|
||||
// If watch is enabled we will wait on the prefix perpetually
|
||||
// for all I/O events until cancelled by user, if watch is not enabled
|
||||
// following defer is a no-op.
|
||||
defer watchFind(ctx)
|
||||
|
||||
var prevKeyName string
|
||||
|
||||
// iterate over all content which is within the given directory
|
||||
for content := range ctx.clnt.List(true, false, DirNone) {
|
||||
if content.Err != nil {
|
||||
switch content.Err.ToGoError().(type) {
|
||||
// handle this specifically for filesystem related errors.
|
||||
case BrokenSymlink:
|
||||
errorIf(content.Err.Trace(ctx.clnt.GetURL().String()), "Unable to list broken link.")
|
||||
continue
|
||||
case TooManyLevelsSymlink:
|
||||
errorIf(content.Err.Trace(ctx.clnt.GetURL().String()), "Unable to list too many levels link.")
|
||||
continue
|
||||
case PathNotFound:
|
||||
errorIf(content.Err.Trace(ctx.clnt.GetURL().String()), "Unable to list folder.")
|
||||
continue
|
||||
case PathInsufficientPermission:
|
||||
errorIf(content.Err.Trace(ctx.clnt.GetURL().String()), "Unable to list folder.")
|
||||
continue
|
||||
case ObjectOnGlacier:
|
||||
errorIf(content.Err.Trace(ctx.clnt.GetURL().String()), "")
|
||||
continue
|
||||
}
|
||||
fatalIf(content.Err.Trace(ctx.clnt.GetURL().String()), "Unable to list folder.")
|
||||
continue
|
||||
}
|
||||
|
||||
fileKeyName := getAliasedPath(ctx, content.URL.String())
|
||||
fileContent := contentMessage{
|
||||
Key: fileKeyName,
|
||||
Time: content.Time.Local(),
|
||||
Size: content.Size,
|
||||
}
|
||||
|
||||
// Match the incoming content, didn't match return.
|
||||
if !matchFind(ctx, fileContent) || prevKeyName == fileKeyName {
|
||||
continue
|
||||
} // For all matching content
|
||||
|
||||
prevKeyName = fileKeyName
|
||||
|
||||
// proceed to either exec, format the output string.
|
||||
if ctx.execCmd != "" {
|
||||
execFind(stringsReplace(ctx.execCmd, fileContent))
|
||||
continue
|
||||
}
|
||||
if ctx.printFmt != "" {
|
||||
fileContent.Key = stringsReplace(ctx.printFmt, fileContent)
|
||||
}
|
||||
|
||||
printMsg(findMessage{fileContent})
|
||||
}
|
||||
|
||||
// Success, notice watch will execute in defer only if enabled and this call
|
||||
// will return after watch is cancelled.
|
||||
return nil
|
||||
}
|
||||
|
||||
// stringsReplace - formats the string to remove {} and replace each
|
||||
// with the appropriate argument
|
||||
func stringsReplace(args string, fileContent contentMessage) string {
|
||||
// replace all instances of {}
|
||||
str := args
|
||||
if strings.Contains(str, "{}") {
|
||||
str = strings.Replace(str, "{}", fileContent.Key, -1)
|
||||
}
|
||||
|
||||
// replace all instances of {""}
|
||||
if strings.Contains(str, `{""}`) {
|
||||
str = strings.Replace(str, `{""}`, strconv.Quote(fileContent.Key), -1)
|
||||
}
|
||||
|
||||
// replace all instances of {base}
|
||||
if strings.Contains(str, "{base}") {
|
||||
str = strings.Replace(str, "{base}", filepath.Base(fileContent.Key), -1)
|
||||
}
|
||||
|
||||
// replace all instances of {"base"}
|
||||
if strings.Contains(str, `{"base"}`) {
|
||||
str = strings.Replace(str, `{"base"}`, strconv.Quote(filepath.Base(fileContent.Key)), -1)
|
||||
}
|
||||
|
||||
// replace all instances of {dir}
|
||||
if strings.Contains(str, "{dir}") {
|
||||
str = strings.Replace(str, "{dir}", filepath.Dir(fileContent.Key), -1)
|
||||
}
|
||||
|
||||
// replace all instances of {"dir"}
|
||||
if strings.Contains(str, `{"dir"}`) {
|
||||
str = strings.Replace(str, `{"dir"}`, strconv.Quote(filepath.Dir(fileContent.Key)), -1)
|
||||
}
|
||||
|
||||
// replace all instances of {size}
|
||||
if strings.Contains(str, "{size}") {
|
||||
str = strings.Replace(str, "{size}", humanize.IBytes(uint64(fileContent.Size)), -1)
|
||||
}
|
||||
|
||||
// replace all instances of {"size"}
|
||||
if strings.Contains(str, `{"size"}`) {
|
||||
str = strings.Replace(str, `{"size"}`, strconv.Quote(humanize.IBytes(uint64(fileContent.Size))), -1)
|
||||
}
|
||||
|
||||
// replace all instances of {time}
|
||||
if strings.Contains(str, "{time}") {
|
||||
str = strings.Replace(str, "{time}", fileContent.Time.Format(printDate), -1)
|
||||
}
|
||||
|
||||
// replace all instances of {"time"}
|
||||
if strings.Contains(str, `{"time"}`) {
|
||||
str = strings.Replace(str, `{"time"}`, strconv.Quote(fileContent.Time.Format(printDate)), -1)
|
||||
}
|
||||
|
||||
// replace all instances of {url}
|
||||
if strings.Contains(str, "{url}") {
|
||||
str = strings.Replace(str, "{url}", getShareURL(fileContent.Key), -1)
|
||||
}
|
||||
|
||||
// replace all instances of {"url"}
|
||||
if strings.Contains(str, `{"url"}`) {
|
||||
str = strings.Replace(str, `{"url"}`, strconv.Quote(getShareURL(fileContent.Key)), -1)
|
||||
}
|
||||
|
||||
return str
|
||||
}
|
||||
|
||||
// matchFind matches whether fileContent matches appropriately with standard
|
||||
// "pattern matching" flags requested by the user, such as "name", "path", "regex" ..etc.
|
||||
func matchFind(ctx *findContext, fileContent contentMessage) (match bool) {
|
||||
match = true
|
||||
prefixPath := ctx.targetURL
|
||||
// Add separator only if targetURL doesn't already have separator.
|
||||
if !strings.HasPrefix(prefixPath, string(ctx.clnt.GetURL().Separator)) {
|
||||
prefixPath = ctx.targetURL + string(ctx.clnt.GetURL().Separator)
|
||||
}
|
||||
// Trim the prefix such that we will apply file path matching techniques
|
||||
// on path excluding the starting prefix.
|
||||
path := strings.TrimPrefix(fileContent.Key, prefixPath)
|
||||
if match && ctx.ignorePattern != "" {
|
||||
match = !pathMatch(ctx.ignorePattern, path)
|
||||
}
|
||||
if match && ctx.namePattern != "" {
|
||||
match = nameMatch(ctx.namePattern, path)
|
||||
}
|
||||
if match && ctx.pathPattern != "" {
|
||||
match = pathMatch(ctx.pathPattern, path)
|
||||
}
|
||||
if match && ctx.regexPattern != "" {
|
||||
match = regexMatch(ctx.regexPattern, path)
|
||||
}
|
||||
if match && !ctx.olderThan.IsZero() {
|
||||
match = fileContent.Time.Before(ctx.olderThan)
|
||||
}
|
||||
if match && !ctx.newerThan.IsZero() {
|
||||
match = fileContent.Time.After(ctx.newerThan) || fileContent.Time.Equal(ctx.newerThan)
|
||||
}
|
||||
if match && ctx.largerSize > 0 {
|
||||
match = int64(ctx.largerSize) < fileContent.Size
|
||||
}
|
||||
if match && ctx.smallerSize > 0 {
|
||||
match = int64(ctx.smallerSize) > fileContent.Size
|
||||
}
|
||||
return match
|
||||
}
|
||||
|
||||
// parseTime - parses input value into a corresponding time value in
|
||||
// time.Time by adding the input time duration to local UTC time.Now().
|
||||
func parseTime(duration string) (time.Time, *probe.Error) {
|
||||
if duration == "" {
|
||||
return time.Time{}, errInvalidArgument().Trace(duration)
|
||||
}
|
||||
|
||||
conversion := map[string]int{
|
||||
"d": 1,
|
||||
"w": 7,
|
||||
"m": 30,
|
||||
"y": 365,
|
||||
}
|
||||
|
||||
// Parse the incoming pattern if its exact number.
|
||||
i, e := strconv.Atoi(duration)
|
||||
if e != nil {
|
||||
// If cant parse as regular string look for
|
||||
// a conversion multiplier, either d,w,m,y.
|
||||
p := duration[len(duration)-1:]
|
||||
i, e = strconv.Atoi(duration[:len(duration)-1])
|
||||
if e != nil {
|
||||
// if we still cant parse, user input is invalid, return error.
|
||||
return time.Time{}, probe.NewError(e)
|
||||
}
|
||||
i = i * conversion[strings.ToLower(p)]
|
||||
}
|
||||
|
||||
now := UTCNow()
|
||||
|
||||
// Find all time in which the time in which the object was just created is after the current time
|
||||
t := time.Date(now.Year(), now.Month(), now.Day()-i, now.Hour(), now.Minute(), 0, 0, time.UTC)
|
||||
|
||||
// if we reach this line, user has passed a valid alphanumeric string
|
||||
return t, nil
|
||||
}
|
||||
|
||||
// 7 days in seconds.
|
||||
var defaultSevenDays = time.Duration(604800) * time.Second
|
||||
|
||||
// getShareURL is used in conjunction with the {url} substitution
|
||||
// argument to generate and return presigned URLs, returns error if any.
|
||||
func getShareURL(path string) string {
|
||||
targetAlias, targetURLFull, _, err := expandAlias(path)
|
||||
fatalIf(err.Trace(path), "Unable to expand alias.")
|
||||
|
||||
clnt, err := newClientFromAlias(targetAlias, targetURLFull)
|
||||
fatalIf(err.Trace(targetAlias, targetURLFull), "Unable to initialize client instance from alias.")
|
||||
|
||||
content, err := clnt.Stat(false, false, "")
|
||||
fatalIf(err.Trace(targetURLFull, targetAlias), "Unable to lookup file/object.")
|
||||
|
||||
// Skip if its a directory.
|
||||
if content.Type.IsDir() {
|
||||
return ""
|
||||
}
|
||||
|
||||
objectURL := content.URL.String()
|
||||
newClnt, err := newClientFromAlias(targetAlias, objectURL)
|
||||
fatalIf(err.Trace(targetAlias, objectURL), "Unable to initialize new client from alias.")
|
||||
|
||||
// Set default expiry for each url (point of no longer valid), to be 7 days
|
||||
shareURL, err := newClnt.ShareDownload(defaultSevenDays)
|
||||
fatalIf(err.Trace(targetAlias, objectURL), "Unable to generate share url.")
|
||||
|
||||
return shareURL
|
||||
}
|
||||
@@ -0,0 +1,505 @@
|
||||
/*
|
||||
* Minio Client (C) 2017 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"os/exec"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Tests match find function with all supported inputs on
|
||||
// file pattern, size and time.
|
||||
func TestMatchFind(t *testing.T) {
|
||||
// List of various contexts used in each tests,
|
||||
// tests are run in the same order as this list.
|
||||
var listFindContexts = []*findContext{
|
||||
&findContext{
|
||||
clnt: &s3Client{
|
||||
targetURL: &clientURL{},
|
||||
},
|
||||
ignorePattern: "*.go",
|
||||
},
|
||||
&findContext{
|
||||
clnt: &s3Client{
|
||||
targetURL: &clientURL{},
|
||||
},
|
||||
namePattern: "console",
|
||||
},
|
||||
&findContext{
|
||||
clnt: &s3Client{
|
||||
targetURL: &clientURL{},
|
||||
},
|
||||
pathPattern: "*console*",
|
||||
},
|
||||
&findContext{
|
||||
clnt: &s3Client{
|
||||
targetURL: &clientURL{},
|
||||
},
|
||||
regexPattern: `^(\d+\.){3}\d+$`,
|
||||
},
|
||||
&findContext{
|
||||
clnt: &s3Client{
|
||||
targetURL: &clientURL{},
|
||||
},
|
||||
olderThan: time.Unix(12000, 0).UTC(),
|
||||
},
|
||||
&findContext{
|
||||
clnt: &s3Client{
|
||||
targetURL: &clientURL{},
|
||||
},
|
||||
newerThan: time.Unix(12000, 0).UTC(),
|
||||
},
|
||||
&findContext{
|
||||
clnt: &s3Client{
|
||||
targetURL: &clientURL{},
|
||||
},
|
||||
largerSize: 1024 * 1024,
|
||||
},
|
||||
&findContext{
|
||||
clnt: &s3Client{
|
||||
targetURL: &clientURL{},
|
||||
},
|
||||
smallerSize: 1024,
|
||||
},
|
||||
&findContext{
|
||||
clnt: &s3Client{
|
||||
targetURL: &clientURL{},
|
||||
},
|
||||
ignorePattern: "*.txt",
|
||||
},
|
||||
&findContext{
|
||||
clnt: &s3Client{
|
||||
targetURL: &clientURL{},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
var testCases = []struct {
|
||||
content contentMessage
|
||||
expectedMatch bool
|
||||
}{
|
||||
// Matches ignore pattern, so match will be false - Test 1.
|
||||
{
|
||||
content: contentMessage{
|
||||
Key: "pkg/console/console.go",
|
||||
},
|
||||
expectedMatch: false,
|
||||
},
|
||||
// Matches name pattern - Test 2.
|
||||
{
|
||||
content: contentMessage{
|
||||
Key: "pkg/console/console.go",
|
||||
},
|
||||
expectedMatch: true,
|
||||
},
|
||||
// Matches path pattern - Test 3.
|
||||
{
|
||||
content: contentMessage{
|
||||
Key: "pkg/console/console.go",
|
||||
},
|
||||
expectedMatch: true,
|
||||
},
|
||||
// Matches regex pattern - Test 4.
|
||||
{
|
||||
content: contentMessage{
|
||||
Key: "192.168.1.1",
|
||||
},
|
||||
expectedMatch: true,
|
||||
},
|
||||
// Matches older than time - Test 5.
|
||||
{
|
||||
content: contentMessage{
|
||||
Time: time.Unix(11999, 0).UTC(),
|
||||
},
|
||||
expectedMatch: true,
|
||||
},
|
||||
// Matches newer than time - Test 6.
|
||||
{
|
||||
content: contentMessage{
|
||||
Time: time.Unix(12001, 0).UTC(),
|
||||
},
|
||||
expectedMatch: true,
|
||||
},
|
||||
// Matches size larger - Test 7.
|
||||
{
|
||||
content: contentMessage{
|
||||
Size: 1024 * 1024 * 2,
|
||||
},
|
||||
expectedMatch: true,
|
||||
},
|
||||
// Matches size smaller - Test 8.
|
||||
{
|
||||
content: contentMessage{
|
||||
Size: 1023,
|
||||
},
|
||||
expectedMatch: true,
|
||||
},
|
||||
// Does not match ignore pattern, so match will be true - Test 9.
|
||||
{
|
||||
content: contentMessage{
|
||||
Key: "pkg/console/console.go",
|
||||
},
|
||||
expectedMatch: true,
|
||||
},
|
||||
// No matching inputs were provided, so nothing to match return value is true - Test 10.
|
||||
{
|
||||
content: contentMessage{},
|
||||
expectedMatch: true,
|
||||
},
|
||||
}
|
||||
|
||||
// Runs all the test cases and validate the expected conditions.
|
||||
for i, testCase := range testCases {
|
||||
gotMatch := matchFind(listFindContexts[i], testCase.content)
|
||||
if testCase.expectedMatch != gotMatch {
|
||||
t.Errorf("Test: %d, expected match %t, got %t", i+1, testCase.expectedMatch, gotMatch)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Tests suffix strings trimmed off correctly at maxdepth.
|
||||
func TestSuffixTrimmingAtMaxDepth(t *testing.T) {
|
||||
var testCases = []struct {
|
||||
startPrefix string
|
||||
path string
|
||||
separator string
|
||||
maxDepth uint
|
||||
expectedNewPath string
|
||||
}{
|
||||
// Tests at max depth 0.
|
||||
{
|
||||
startPrefix: "./",
|
||||
path: ".git/refs/remotes",
|
||||
separator: "/",
|
||||
maxDepth: 0,
|
||||
expectedNewPath: ".git/refs/remotes",
|
||||
},
|
||||
// Tests at max depth 1.
|
||||
{
|
||||
startPrefix: "./",
|
||||
path: ".git/refs/remotes",
|
||||
separator: "/",
|
||||
maxDepth: 1,
|
||||
expectedNewPath: "./.git/",
|
||||
},
|
||||
// Tests at max depth 2.
|
||||
{
|
||||
startPrefix: "./",
|
||||
path: ".git/refs/remotes",
|
||||
separator: "/",
|
||||
maxDepth: 2,
|
||||
expectedNewPath: "./.git/refs/",
|
||||
},
|
||||
// Tests at max depth 3.
|
||||
{
|
||||
startPrefix: "./",
|
||||
path: ".git/refs/remotes",
|
||||
separator: "/",
|
||||
maxDepth: 3,
|
||||
expectedNewPath: "./.git/refs/remotes",
|
||||
},
|
||||
// Tests with startPrefix empty.
|
||||
{
|
||||
startPrefix: "",
|
||||
path: ".git/refs/remotes",
|
||||
separator: "/",
|
||||
maxDepth: 2,
|
||||
expectedNewPath: ".git/refs/",
|
||||
},
|
||||
// Tests with separator empty.
|
||||
{
|
||||
startPrefix: "",
|
||||
path: ".git/refs/remotes",
|
||||
separator: "",
|
||||
maxDepth: 2,
|
||||
expectedNewPath: ".g",
|
||||
},
|
||||
// Tests with nested startPrefix paths - 1.
|
||||
{
|
||||
startPrefix: ".git/refs/",
|
||||
path: ".git/refs/remotes",
|
||||
separator: "/",
|
||||
maxDepth: 1,
|
||||
expectedNewPath: ".git/refs/remotes",
|
||||
},
|
||||
// Tests with nested startPrefix paths - 2.
|
||||
{
|
||||
startPrefix: ".git/refs",
|
||||
path: ".git/refs/remotes",
|
||||
separator: "/",
|
||||
maxDepth: 1,
|
||||
expectedNewPath: ".git/refs/",
|
||||
},
|
||||
}
|
||||
|
||||
// Run all the test cases and validate for returned new path.
|
||||
for i, testCase := range testCases {
|
||||
gotNewPath := trimSuffixAtMaxDepth(testCase.startPrefix, testCase.path, testCase.separator, testCase.maxDepth)
|
||||
if testCase.expectedNewPath != gotNewPath {
|
||||
t.Errorf("Test: %d, expected path %s, got %s", i+1, testCase.expectedNewPath, gotNewPath)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Tests matching functions for name, path and regex.
|
||||
func TestFindMatch(t *testing.T) {
|
||||
// testFind is the structure used to contain params pertinent to find related tests
|
||||
type testFind struct {
|
||||
pattern, filePath, flagName string
|
||||
match bool
|
||||
}
|
||||
|
||||
var basicTests = []testFind{
|
||||
// Name match tests - success cases.
|
||||
{"*.jpg", "carter.jpg", "name", true},
|
||||
{"console", "pkg/console/console.go", "name", true},
|
||||
{"console.go", "pkg/console/console.go", "name", true},
|
||||
{"*XA==", "I/enjoy/morning/walks/XA==", "name ", true},
|
||||
{"*parser", "/This/might/mess up./the/parser", "name", true},
|
||||
{"*LTIxNDc0ODM2NDgvLTE=", "What/A/Naughty/String/LTIxNDc0ODM2NDgvLTE=", "name", true},
|
||||
{"*", "/bla/bla/bla/ ", "name", true},
|
||||
|
||||
// Name match tests - failure cases.
|
||||
{"*.jpg", "carter.jpeg", "name", false},
|
||||
{"*/test/*", "/test/bob/likes/cake", "name", false},
|
||||
{"*test/*", "bob/test/likes/cake", "name", false},
|
||||
{"*test/*", "bob/likes/test/cake", "name", false},
|
||||
{"*/test/*", "bob/likes/cake/test", "name", false},
|
||||
{"*.jpg", ".jpg/elves/are/evil", "name", false},
|
||||
{"wq3YgNiB2ILYg9iE2IXYnNud3I/hoI7igIvigIzigI3igI7igI/igKrigKvigKzigK3igK7igaDi",
|
||||
"An/Even/Bigger/String/wq3YgNiB2ILYg9iE2IXYnNud3I/hoI7igIvigIzigI3igI7igI/igKrigKvigKzigK3igK7igaDi", "name", false},
|
||||
{"𝕿𝖍𝖊", "well/this/isAN/odd/font/THE", "name", false},
|
||||
{"𝕿𝖍𝖊", "well/this/isAN/odd/font/The", "name", false},
|
||||
{"𝕿𝖍𝖊", "well/this/isAN/odd/font/𝓣𝓱𝓮", "name", false},
|
||||
{"𝕿𝖍𝖊", "what/a/strange/turn/of/events/𝓣he", "name", false},
|
||||
{"𝕿𝖍𝖊", "well/this/isAN/odd/font/𝕿𝖍𝖊", "name", true},
|
||||
|
||||
// Path match tests - success cases.
|
||||
{"*/test/*", "bob/test/likes/cake", "path", true},
|
||||
{"*/test/*", "/test/bob/likes/cake", "path", true},
|
||||
|
||||
// Path match tests - failure cases.
|
||||
{"*.jpg", ".jpg/elves/are/evil", "path", false},
|
||||
{"*/test/*", "test1/test2/test3/test", "path", false},
|
||||
{"*/ test /*", "test/test1/test2/test3/test", "path", false},
|
||||
{"*/test/*", " test /I/have/Really/Long/hair", "path", false},
|
||||
{"*XA==", "XA==/Height/is/a/social/construct", "path", false},
|
||||
{"*W", "/Word//this/is a/trickyTest", "path", false},
|
||||
{"LTIxNDc0ODM2NDgvLTE=", "LTIxNDc0ODM2NDgvLTE=/I/Am/One/Baaaaad/String", "path", false},
|
||||
{"/", "funky/path/name", "path", false},
|
||||
|
||||
// Regexp based - success cases.
|
||||
{"^[a-zA-Z][a-zA-Z0-9\\-]+[a-zA-Z0-9]$", "testbucket-1", "regex", true},
|
||||
{`^(\d+\.){3}\d+$`, "192.168.1.1", "regex", true},
|
||||
|
||||
// Regexp based - failure cases.
|
||||
{"^[a-zA-Z][a-zA-Z0-9\\-]+[a-zA-Z0-9]$", "testbucket.", "regex", false},
|
||||
{`^(\d+\.){3}\d+$`, "192.168.x.x", "regex", false},
|
||||
}
|
||||
|
||||
for _, test := range basicTests {
|
||||
switch test.flagName {
|
||||
case "name":
|
||||
testMatch := nameMatch(test.pattern, test.filePath)
|
||||
if testMatch != test.match {
|
||||
t.Fatalf("Unexpected result %t, with pattern %s, flag %s and filepath %s \n",
|
||||
!test.match, test.pattern, test.flagName, test.filePath)
|
||||
}
|
||||
case "path":
|
||||
testMatch := pathMatch(test.pattern, test.filePath)
|
||||
if testMatch != test.match {
|
||||
t.Fatalf("Unexpected result %t, with pattern %s, flag %s and filepath %s \n",
|
||||
!test.match, test.pattern, test.flagName, test.filePath)
|
||||
}
|
||||
case "regex":
|
||||
testMatch := regexMatch(test.pattern, test.filePath)
|
||||
if testMatch != test.match {
|
||||
t.Fatalf("Unexpected result %t, with pattern %s, flag %s and filepath %s \n",
|
||||
!test.match, test.pattern, test.flagName, test.filePath)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Tests for parsing time layout.
|
||||
func TestParseTime(t *testing.T) {
|
||||
testCases := []struct {
|
||||
value string
|
||||
success bool
|
||||
}{
|
||||
// Parses 1 day successfully.
|
||||
{
|
||||
value: "1d",
|
||||
success: true,
|
||||
},
|
||||
// Parses 1 week successfully.
|
||||
{
|
||||
value: "1w",
|
||||
success: true,
|
||||
},
|
||||
// Parses 1 year successfully.
|
||||
{
|
||||
value: "1y",
|
||||
success: true,
|
||||
},
|
||||
// Parses 2 months successfully.
|
||||
{
|
||||
value: "2m",
|
||||
success: true,
|
||||
},
|
||||
// Failure to parse "xd".
|
||||
{
|
||||
value: "xd",
|
||||
success: false,
|
||||
},
|
||||
// Failure to parse empty string.
|
||||
{
|
||||
value: "",
|
||||
success: false,
|
||||
},
|
||||
}
|
||||
for i, testCase := range testCases {
|
||||
pt, err := parseTime(testCase.value)
|
||||
if err != nil && testCase.success {
|
||||
t.Errorf("Test: %d, Expected to be successful, but found error %s, for time value %s", i+1, err, testCase.value)
|
||||
}
|
||||
if pt.IsZero() && testCase.success {
|
||||
t.Errorf("Test: %d, Expected time to be non zero, but found zero time for time value %s", i+1, testCase.value)
|
||||
}
|
||||
if err == nil && !testCase.success {
|
||||
t.Errorf("Test: %d, Expected error but found to be successful for time value %s", i+1, testCase.value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Tests string substitution function.
|
||||
func TestStringReplace(t *testing.T) {
|
||||
testCases := []struct {
|
||||
str string
|
||||
expectedStr string
|
||||
content contentMessage
|
||||
}{
|
||||
// Tests string replace {} without quotes.
|
||||
{
|
||||
str: "{}",
|
||||
expectedStr: "path/1",
|
||||
content: contentMessage{Key: "path/1"},
|
||||
},
|
||||
// Tests string replace {} with quotes.
|
||||
{
|
||||
str: `{""}`,
|
||||
expectedStr: `"path/1"`,
|
||||
content: contentMessage{Key: "path/1"},
|
||||
},
|
||||
// Tests string replace {base}
|
||||
{
|
||||
str: "{base}",
|
||||
expectedStr: "1",
|
||||
content: contentMessage{Key: "path/1"},
|
||||
},
|
||||
// Tests string replace {"base"} with quotes.
|
||||
{
|
||||
str: `{"base"}`,
|
||||
expectedStr: `"1"`,
|
||||
content: contentMessage{Key: "path/1"},
|
||||
},
|
||||
// Tests string replace {dir}
|
||||
{
|
||||
str: `{dir}`,
|
||||
expectedStr: `path`,
|
||||
content: contentMessage{Key: "path/1"},
|
||||
},
|
||||
// Tests string replace {"dir"} with quotes.
|
||||
{
|
||||
str: `{"dir"}`,
|
||||
expectedStr: `"path"`,
|
||||
content: contentMessage{Key: "path/1"},
|
||||
},
|
||||
// Tests string replace {"size"} with quotes.
|
||||
{
|
||||
str: `{"size"}`,
|
||||
expectedStr: `"0B"`,
|
||||
content: contentMessage{Size: 0},
|
||||
},
|
||||
// Tests string replace {"time"} with quotes.
|
||||
{
|
||||
str: `{"time"}`,
|
||||
expectedStr: `"2038-01-19 03:14:07 UTC"`,
|
||||
content: contentMessage{
|
||||
Time: time.Unix(2147483647, 0).UTC(),
|
||||
},
|
||||
},
|
||||
// Tests string replace {size}
|
||||
{
|
||||
str: `{size}`,
|
||||
expectedStr: `1.0MiB`,
|
||||
content: contentMessage{Size: 1024 * 1024},
|
||||
},
|
||||
// Tests string replace {time}
|
||||
{
|
||||
str: `{time}`,
|
||||
expectedStr: `2038-01-19 03:14:07 UTC`,
|
||||
content: contentMessage{
|
||||
Time: time.Unix(2147483647, 0).UTC(),
|
||||
},
|
||||
},
|
||||
}
|
||||
for i, testCase := range testCases {
|
||||
gotStr := stringsReplace(testCase.str, testCase.content)
|
||||
if gotStr != testCase.expectedStr {
|
||||
t.Errorf("Test %d: Expected %s, got %s", i+1, testCase.expectedStr, gotStr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Tests exit status, getExitStatus() function
|
||||
func TestGetExitStatus(t *testing.T) {
|
||||
testCases := []struct {
|
||||
command string
|
||||
expectedExitStatus int
|
||||
}{
|
||||
// Tests "No such file or directory", exit status code 2
|
||||
{
|
||||
command: "ls asdf",
|
||||
expectedExitStatus: 2,
|
||||
},
|
||||
{
|
||||
command: "cp x x",
|
||||
expectedExitStatus: 1,
|
||||
},
|
||||
// expectedExitStatus for "command not found" case is 127,
|
||||
// but exec command cannot capture anything since a process
|
||||
// for the command could not be started at all,
|
||||
// so the expectedExitStatus is 1
|
||||
{
|
||||
command: "asdf",
|
||||
expectedExitStatus: 1,
|
||||
},
|
||||
}
|
||||
for i, testCase := range testCases {
|
||||
commandArgs := strings.Split(testCase.command, " ")
|
||||
cmd := exec.Command(commandArgs[0], commandArgs[1:]...)
|
||||
// Return exit status of the command run
|
||||
exitStatus := getExitStatus(cmd.Run())
|
||||
if exitStatus != testCase.expectedExitStatus {
|
||||
t.Errorf("Test %d: Expected error status code for command \"%v\" is %v, got %v",
|
||||
i+1, testCase.command, testCase.expectedExitStatus, exitStatus)
|
||||
}
|
||||
}
|
||||
}
|
||||
+13
-6
@@ -14,15 +14,18 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
package cmd
|
||||
|
||||
import "github.com/minio/cli"
|
||||
import (
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/minio/pkg/trie"
|
||||
)
|
||||
|
||||
// Collection of mc commands currently supported
|
||||
var commands = []cli.Command{}
|
||||
|
||||
// Collection of mc commands currently supported in a trie tree
|
||||
var commandsTree = newTrie()
|
||||
var commandsTree = trie.NewTrie()
|
||||
|
||||
// Collection of mc flags currently supported
|
||||
var globalFlags = []cli.Flag{
|
||||
@@ -33,7 +36,7 @@ var globalFlags = []cli.Flag{
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "quiet, q",
|
||||
Usage: "Suppress chatty console output.",
|
||||
Usage: "Disable progress bar display.",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "no-color",
|
||||
@@ -41,11 +44,15 @@ var globalFlags = []cli.Flag{
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "json",
|
||||
Usage: "Enable json formatted output.",
|
||||
Usage: "Enable JSON formatted output.",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "debug",
|
||||
Usage: "Enable debugging output.",
|
||||
Usage: "Enable debug output.",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "insecure",
|
||||
Usage: "Disable SSL certificate verification.",
|
||||
},
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package fs
|
||||
package cmd
|
||||
|
||||
func normalizePath(path string) string {
|
||||
return path
|
||||
@@ -16,7 +16,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package fs
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
@@ -0,0 +1,99 @@
|
||||
/*
|
||||
* Minio Client (C) 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
// Package cmd contains all the global variables and constants. ONLY TO BE ACCESSED VIA GET/SET FUNCTIONS.
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"crypto/x509"
|
||||
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
)
|
||||
|
||||
// mc configuration related constants.
|
||||
const (
|
||||
minGoVersion = ">= 1.7.5" // mc requires at least Go v1.7.5
|
||||
)
|
||||
|
||||
const (
|
||||
globalMCConfigVersion = "9"
|
||||
|
||||
globalMCConfigDir = ".mc/"
|
||||
globalMCConfigWindowsDir = "mc\\"
|
||||
globalMCConfigFile = "config.json"
|
||||
globalMCCertsDir = "certs"
|
||||
globalMCCAsDir = "CAs"
|
||||
|
||||
// session config and shared urls related constants
|
||||
globalSessionDir = "session"
|
||||
globalSharedURLsDataDir = "share"
|
||||
globalSessionConfigVersion = "8"
|
||||
|
||||
// Profile directory for dumping profiler outputs.
|
||||
globalProfileDir = "profile"
|
||||
|
||||
// Global error exit status.
|
||||
globalErrorExitStatus = 1
|
||||
)
|
||||
|
||||
var (
|
||||
globalQuiet = false // Quiet flag set via command line
|
||||
globalJSON = false // Json flag set via command line
|
||||
globalDebug = false // Debug flag set via command line
|
||||
globalNoColor = false // No Color flag set via command line
|
||||
globalInsecure = false // Insecure flag set via command line
|
||||
|
||||
// WHEN YOU ADD NEXT GLOBAL FLAG, MAKE SURE TO ALSO UPDATE SESSION CODE AND CODE BELOW.
|
||||
)
|
||||
|
||||
var (
|
||||
// Terminal width
|
||||
globalTermWidth int
|
||||
|
||||
// CA root certificates, a nil value means system certs pool will be used
|
||||
globalRootCAs *x509.CertPool
|
||||
)
|
||||
|
||||
// Set global states. NOTE: It is deliberately kept monolithic to ensure we dont miss out any flags.
|
||||
func setGlobals(quiet, debug, json, noColor, insecure bool) {
|
||||
globalQuiet = globalQuiet || quiet
|
||||
globalDebug = globalDebug || debug
|
||||
globalJSON = globalJSON || json
|
||||
globalNoColor = globalNoColor || noColor
|
||||
globalInsecure = globalInsecure || insecure
|
||||
|
||||
// Enable debug messages if requested.
|
||||
if globalDebug {
|
||||
console.DebugPrint = true
|
||||
}
|
||||
|
||||
// Disable colorified messages if requested.
|
||||
if globalNoColor || globalQuiet {
|
||||
console.SetColorOff()
|
||||
}
|
||||
}
|
||||
|
||||
// Set global states. NOTE: It is deliberately kept monolithic to ensure we dont miss out any flags.
|
||||
func setGlobalsFromContext(ctx *cli.Context) error {
|
||||
quiet := ctx.IsSet("quiet")
|
||||
debug := ctx.IsSet("debug")
|
||||
json := ctx.IsSet("json")
|
||||
noColor := ctx.IsSet("no-color")
|
||||
insecure := ctx.IsSet("insecure")
|
||||
setGlobals(quiet, debug, json, noColor, insecure)
|
||||
return nil
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Minio Client (C) 2014, 2015 Minio, Inc.
|
||||
* Minio Client (C) 2017 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -14,7 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
@@ -22,16 +22,28 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// humanizedTime container to capture humanized time.
|
||||
type humanizedTime struct {
|
||||
// humanizedDuration container to capture humanized time.
|
||||
type humanizedDuration struct {
|
||||
Days int64 `json:"days,omitempty"`
|
||||
Hours int64 `json:"hours,omitempty"`
|
||||
Minutes int64 `json:"minutes,omitempty"`
|
||||
Seconds int64 `json:"seconds,omitempty"`
|
||||
}
|
||||
|
||||
// String() humanizes humanizedTime to human readable,
|
||||
func (r humanizedTime) String() string {
|
||||
// StringShort() humanizes humanizedDuration to human readable short format.
|
||||
// This does not print at seconds.
|
||||
func (r humanizedDuration) StringShort() string {
|
||||
if r.Days == 0 && r.Hours == 0 {
|
||||
return fmt.Sprintf("%d minutes", r.Minutes)
|
||||
}
|
||||
if r.Days == 0 {
|
||||
return fmt.Sprintf("%d hours %d minutes", r.Hours, r.Minutes)
|
||||
}
|
||||
return fmt.Sprintf("%d days %d hours %d minutes", r.Days, r.Hours, r.Minutes)
|
||||
}
|
||||
|
||||
// String() humanizes humanizedDuration to human readable,
|
||||
func (r humanizedDuration) String() string {
|
||||
if r.Days == 0 && r.Hours == 0 && r.Minutes == 0 {
|
||||
return fmt.Sprintf("%d seconds", r.Seconds)
|
||||
}
|
||||
@@ -44,9 +56,9 @@ func (r humanizedTime) String() string {
|
||||
return fmt.Sprintf("%d days %d hours %d minutes %d seconds", r.Days, r.Hours, r.Minutes, r.Seconds)
|
||||
}
|
||||
|
||||
// timeDurationToHumanizedTime convert golang time.Duration to a custom more readable humanizedTime.
|
||||
func timeDurationToHumanizedTime(duration time.Duration) humanizedTime {
|
||||
r := humanizedTime{}
|
||||
// timeDurationToHumanizedDuration convert golang time.Duration to a custom more readable humanizedDuration.
|
||||
func timeDurationToHumanizedDuration(duration time.Duration) humanizedDuration {
|
||||
r := humanizedDuration{}
|
||||
if duration.Seconds() < 60.0 {
|
||||
r.Seconds = int64(duration.Seconds())
|
||||
return r
|
||||
+53
-30
@@ -14,31 +14,30 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/client"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
)
|
||||
|
||||
// ls specific flags.
|
||||
var (
|
||||
lsFlags = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "help, h",
|
||||
Usage: "Help of ls.",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "recursive, r",
|
||||
Usage: "List recursively.",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "incomplete, I",
|
||||
Usage: "Remove incomplete uploads.",
|
||||
Usage: "List incomplete uploads.",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "encrypt-key",
|
||||
Usage: "Encrypt/Decrypt (using server-side encryption)",
|
||||
},
|
||||
}
|
||||
)
|
||||
@@ -48,34 +47,36 @@ var lsCmd = cli.Command{
|
||||
Name: "ls",
|
||||
Usage: "List files and folders.",
|
||||
Action: mainList,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(lsFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
mc {{.Name}} - {{.Usage}}
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
mc {{.Name}} [FLAGS] TARGET [TARGET ...]
|
||||
{{.HelpName}} [FLAGS] TARGET [TARGET ...]
|
||||
|
||||
FLAGS:
|
||||
{{range .Flags}}{{.}}
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. List buckets on Amazon S3 cloud storage.
|
||||
$ mc {{.Name}} s3
|
||||
$ {{.HelpName}} s3
|
||||
|
||||
2. List buckets and all its contents from Amazon S3 cloud storage recursively.
|
||||
$ mc {{.Name}} --recursive s3
|
||||
$ {{.HelpName}} --recursive s3
|
||||
|
||||
3. List all contents of mybucket on Amazon S3 cloud storage.
|
||||
$ mc {{.Name}} s3/mybucket/
|
||||
$ {{.HelpName}} s3/mybucket/
|
||||
|
||||
4. List all contents of mybucket on Amazon S3 cloud storage on Microsoft Windows.
|
||||
$ mc {{.Name}} s3\mybucket\
|
||||
$ {{.HelpName}} s3\mybucket\
|
||||
|
||||
5. List files recursively on a local filesystem on Microsoft Windows.
|
||||
$ mc {{.Name}} --recursive C:\Users\Worf\
|
||||
$ {{.HelpName}} --recursive C:\Users\Worf\
|
||||
|
||||
6. List incomplete (previously failed) uploads of objects on Amazon S3.
|
||||
$ mc {{.Name}} --incomplete s3/mybucket
|
||||
$ {{.HelpName}} --incomplete s3/mybucket
|
||||
|
||||
`,
|
||||
}
|
||||
|
||||
@@ -94,25 +95,31 @@ func checkListSyntax(ctx *cli.Context) {
|
||||
URLs := ctx.Args()
|
||||
isIncomplete := ctx.Bool("incomplete")
|
||||
|
||||
// Parse encryption keys per command.
|
||||
encKeyDB, err := getEncKeys(ctx)
|
||||
fatalIf(err, "Unable to parse encryption keys.")
|
||||
|
||||
for _, url := range URLs {
|
||||
_, _, err := url2Stat(url)
|
||||
_, _, err := url2Stat(url, false, encKeyDB)
|
||||
if err != nil && !isURLPrefixExists(url, isIncomplete) {
|
||||
fatalIf(err.Trace(url), "Unable to stat ‘"+url+"’.")
|
||||
// Bucket name empty is a valid error for 'ls myminio',
|
||||
// treat it as such.
|
||||
if _, ok := err.ToGoError().(BucketNameEmpty); ok {
|
||||
continue
|
||||
}
|
||||
fatalIf(err.Trace(url), "Unable to stat `"+url+"`.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// mainList - is a handler for mc ls command
|
||||
func mainList(ctx *cli.Context) {
|
||||
// Additional command speific theme customization.
|
||||
console.SetColor("File", color.New(color.FgWhite))
|
||||
func mainList(ctx *cli.Context) error {
|
||||
// Additional command specific theme customization.
|
||||
console.SetColor("File", color.New(color.Bold))
|
||||
console.SetColor("Dir", color.New(color.FgCyan, color.Bold))
|
||||
console.SetColor("Size", color.New(color.FgYellow))
|
||||
console.SetColor("Time", color.New(color.FgGreen))
|
||||
|
||||
// Set global flags from context.
|
||||
setGlobalsFromContext(ctx)
|
||||
|
||||
// check 'ls' cli arguments.
|
||||
checkListSyntax(ctx)
|
||||
|
||||
@@ -126,15 +133,31 @@ func mainList(ctx *cli.Context) {
|
||||
args = []string{"."}
|
||||
}
|
||||
|
||||
var cErr error
|
||||
for _, targetURL := range args {
|
||||
var clnt client.Client
|
||||
var clnt Client
|
||||
clnt, err := newClient(targetURL)
|
||||
fatalIf(err.Trace(targetURL), "Unable to initialize target ‘"+targetURL+"’.")
|
||||
fatalIf(err.Trace(targetURL), "Unable to initialize target `"+targetURL+"`.")
|
||||
|
||||
err = doList(clnt, isRecursive, isIncomplete)
|
||||
if err != nil {
|
||||
errorIf(err.Trace(clnt.GetURL().String()), "Unable to list target ‘"+clnt.GetURL().String()+"’.")
|
||||
continue
|
||||
var st *clientContent
|
||||
if st, err = clnt.Stat(isIncomplete, false, ""); err != nil {
|
||||
switch err.ToGoError().(type) {
|
||||
case BucketNameEmpty:
|
||||
// For aliases like ``mc ls s3`` it's acceptable to receive BucketNameEmpty error.
|
||||
// Nothing to do.
|
||||
default:
|
||||
fatalIf(err.Trace(targetURL), "Unable to initialize target `"+targetURL+"`.")
|
||||
}
|
||||
} else if st.Type.IsDir() {
|
||||
if !strings.HasSuffix(targetURL, string(clnt.GetURL().Separator)) {
|
||||
targetURL = targetURL + string(clnt.GetURL().Separator)
|
||||
}
|
||||
clnt, err = newClient(targetURL)
|
||||
fatalIf(err.Trace(targetURL), "Unable to initialize target `"+targetURL+"`.")
|
||||
}
|
||||
if e := doList(clnt, isRecursive, isIncomplete); e != nil {
|
||||
cErr = e
|
||||
}
|
||||
}
|
||||
return cErr
|
||||
}
|
||||
+36
-31
@@ -14,7 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
@@ -25,9 +25,8 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/dustin/go-humanize"
|
||||
"github.com/minio/mc/pkg/client"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
)
|
||||
|
||||
// printDate - human friendly formatted date.
|
||||
@@ -42,6 +41,7 @@ type contentMessage struct {
|
||||
Time time.Time `json:"lastModified"`
|
||||
Size int64 `json:"size"`
|
||||
Key string `json:"key"`
|
||||
ETag string `json:"etag"`
|
||||
}
|
||||
|
||||
// String colorized string message.
|
||||
@@ -67,7 +67,7 @@ func (c contentMessage) JSON() string {
|
||||
}
|
||||
|
||||
// parseContent parse client Content container into printer struct.
|
||||
func parseContent(c *client.Content) contentMessage {
|
||||
func parseContent(c *clientContent) contentMessage {
|
||||
content := contentMessage{}
|
||||
content.Time = c.Time.Local()
|
||||
|
||||
@@ -80,55 +80,60 @@ func parseContent(c *client.Content) contentMessage {
|
||||
}()
|
||||
|
||||
content.Size = c.Size
|
||||
md5sum := strings.TrimPrefix(c.ETag, "\"")
|
||||
md5sum = strings.TrimSuffix(md5sum, "\"")
|
||||
content.ETag = md5sum
|
||||
// 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
|
||||
}()
|
||||
content.Key = getKey(c)
|
||||
return content
|
||||
}
|
||||
|
||||
// get content key
|
||||
func getKey(c *clientContent) string {
|
||||
sep := "/"
|
||||
|
||||
// for windows make sure to print in 'windows' specific style.
|
||||
if runtime.GOOS == "windows" {
|
||||
c.URL.Path = strings.Replace(c.URL.Path, "/", "\\", -1)
|
||||
sep = "\\"
|
||||
}
|
||||
|
||||
if c.Type.IsDir() && !strings.HasSuffix(c.URL.Path, sep) {
|
||||
return fmt.Sprintf("%s%s", c.URL.Path, sep)
|
||||
}
|
||||
return c.URL.Path
|
||||
}
|
||||
|
||||
// doList - list all entities inside a folder.
|
||||
func doList(clnt client.Client, isRecursive, isIncomplete bool) *probe.Error {
|
||||
func doList(clnt Client, isRecursive, isIncomplete bool) error {
|
||||
prefixPath := clnt.GetURL().Path
|
||||
separator := string(clnt.GetURL().Separator)
|
||||
if !strings.HasSuffix(prefixPath, separator) {
|
||||
prefixPath = prefixPath[:strings.LastIndex(prefixPath, separator)+1]
|
||||
}
|
||||
for content := range clnt.List(isRecursive, isIncomplete) {
|
||||
var cErr error
|
||||
for content := range clnt.List(isRecursive, isIncomplete, DirNone) {
|
||||
if content.Err != nil {
|
||||
switch content.Err.ToGoError().(type) {
|
||||
// handle this specifically for filesystem related errors.
|
||||
case client.BrokenSymlink:
|
||||
case BrokenSymlink:
|
||||
errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list broken link.")
|
||||
continue
|
||||
case client.TooManyLevelsSymlink:
|
||||
case TooManyLevelsSymlink:
|
||||
errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list too many levels link.")
|
||||
continue
|
||||
case client.PathNotFound:
|
||||
case PathNotFound:
|
||||
errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list folder.")
|
||||
continue
|
||||
case client.PathInsufficientPermission:
|
||||
case PathInsufficientPermission:
|
||||
errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list folder.")
|
||||
continue
|
||||
case ObjectOnGlacier:
|
||||
errorIf(content.Err.Trace(clnt.GetURL().String()), "")
|
||||
continue
|
||||
}
|
||||
errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list folder.")
|
||||
cErr = exitStatus(globalErrorExitStatus) // Set the exit status.
|
||||
continue
|
||||
}
|
||||
// Convert any os specific delimiters to "/".
|
||||
@@ -142,5 +147,5 @@ func doList(clnt client.Client, isRecursive, isIncomplete bool) *probe.Error {
|
||||
// Print colorized or jsonized content info.
|
||||
printMsg(parsedContent)
|
||||
}
|
||||
return nil
|
||||
return cErr
|
||||
}
|
||||
@@ -14,4 +14,4 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
package cmd
|
||||
+329
@@ -0,0 +1,329 @@
|
||||
/*
|
||||
* Minio Client (C) 2014, 2015, 2016, 2017 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/cheggaaa/pb"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/minio/pkg/words"
|
||||
"github.com/pkg/profile"
|
||||
)
|
||||
|
||||
var (
|
||||
// global flags for mc.
|
||||
mcFlags = []cli.Flag{}
|
||||
)
|
||||
|
||||
// Help template for mc
|
||||
var mcHelpTemplate = `NAME:
|
||||
{{.Name}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.Name}} {{if .VisibleFlags}}[FLAGS] {{end}}COMMAND{{if .VisibleFlags}} [COMMAND FLAGS | -h]{{end}} [ARGUMENTS...]
|
||||
|
||||
COMMANDS:
|
||||
{{range .VisibleCommands}}{{join .Names ", "}}{{ "\t" }}{{.Usage}}
|
||||
{{end}}{{if .VisibleFlags}}
|
||||
GLOBAL FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}{{end}}
|
||||
VERSION:
|
||||
` + Version +
|
||||
`{{ "\n"}}{{range $key, $value := ExtraInfo}}
|
||||
{{$key}}:
|
||||
{{$value}}
|
||||
{{end}}`
|
||||
|
||||
// Main starts mc application
|
||||
func Main() {
|
||||
// Enable profiling supported modes are [cpu, mem, block].
|
||||
// ``MC_PROFILER`` supported options are [cpu, mem, block].
|
||||
switch os.Getenv("MC_PROFILER") {
|
||||
case "cpu":
|
||||
defer profile.Start(profile.CPUProfile, profile.ProfilePath(mustGetProfileDir())).Stop()
|
||||
case "mem":
|
||||
defer profile.Start(profile.MemProfile, profile.ProfilePath(mustGetProfileDir())).Stop()
|
||||
case "block":
|
||||
defer profile.Start(profile.BlockProfile, profile.ProfilePath(mustGetProfileDir())).Stop()
|
||||
}
|
||||
|
||||
probe.Init() // Set project's root source path.
|
||||
probe.SetAppInfo("Release-Tag", ReleaseTag)
|
||||
probe.SetAppInfo("Commit", ShortCommitID)
|
||||
|
||||
// Fetch terminal size, if not available, automatically
|
||||
// set globalQuiet to true.
|
||||
if w, e := pb.GetTerminalWidth(); e != nil {
|
||||
globalQuiet = true
|
||||
} else {
|
||||
globalTermWidth = w
|
||||
}
|
||||
|
||||
app := registerApp()
|
||||
app.Before = registerBefore
|
||||
app.ExtraInfo = func() map[string]string {
|
||||
if globalDebug {
|
||||
return getSystemData()
|
||||
}
|
||||
return make(map[string]string)
|
||||
}
|
||||
app.RunAndExitOnError()
|
||||
}
|
||||
|
||||
// Function invoked when invalid command is passed.
|
||||
func commandNotFound(ctx *cli.Context, command string) {
|
||||
msg := fmt.Sprintf("`%s` is not a mc command. See `mc --help`.", command)
|
||||
closestCommands := findClosestCommands(command)
|
||||
if len(closestCommands) > 0 {
|
||||
msg += fmt.Sprintf("\n\nDid you mean one of these?\n")
|
||||
if len(closestCommands) == 1 {
|
||||
cmd := closestCommands[0]
|
||||
msg += fmt.Sprintf(" `%s`", cmd)
|
||||
} else {
|
||||
for _, cmd := range closestCommands {
|
||||
msg += fmt.Sprintf(" `%s`\n", cmd)
|
||||
}
|
||||
}
|
||||
}
|
||||
fatalIf(errDummy().Trace(), msg)
|
||||
}
|
||||
|
||||
// Check for sane config environment early on and gracefully report.
|
||||
func checkConfig() {
|
||||
// Refresh the config once.
|
||||
loadMcConfig = loadMcConfigFactory()
|
||||
// Ensures config file is sane.
|
||||
config, err := loadMcConfig()
|
||||
// Verify if the path is accesible before validating the config
|
||||
fatalIf(err.Trace(mustGetMcConfigPath()), "Unable to access configuration file.")
|
||||
|
||||
// Validate and print error messges
|
||||
ok, errMsgs := validateConfigFile(config)
|
||||
if !ok {
|
||||
var errorMsg bytes.Buffer
|
||||
for index, errMsg := range errMsgs {
|
||||
// Print atmost 10 errors
|
||||
if index > 10 {
|
||||
break
|
||||
}
|
||||
errorMsg.WriteString(errMsg + "\n")
|
||||
}
|
||||
console.Fatal(errorMsg.String())
|
||||
}
|
||||
}
|
||||
|
||||
func migrate() {
|
||||
// Fix broken config files if any.
|
||||
fixConfig()
|
||||
|
||||
// Migrate config files if any.
|
||||
migrateConfig()
|
||||
|
||||
// Migrate session files if any.
|
||||
migrateSession()
|
||||
|
||||
// Migrate shared urls if any.
|
||||
migrateShare()
|
||||
}
|
||||
|
||||
// Get os/arch/platform specific information.
|
||||
// Returns a map of current os/arch/platform/memstats.
|
||||
func getSystemData() map[string]string {
|
||||
host, e := os.Hostname()
|
||||
fatalIf(probe.NewError(e), "Unable to determine the hostname.")
|
||||
|
||||
memstats := &runtime.MemStats{}
|
||||
runtime.ReadMemStats(memstats)
|
||||
mem := fmt.Sprintf("Used: %s | Allocated: %s | UsedHeap: %s | AllocatedHeap: %s",
|
||||
pb.Format(int64(memstats.Alloc)).To(pb.U_BYTES),
|
||||
pb.Format(int64(memstats.TotalAlloc)).To(pb.U_BYTES),
|
||||
pb.Format(int64(memstats.HeapAlloc)).To(pb.U_BYTES),
|
||||
pb.Format(int64(memstats.HeapSys)).To(pb.U_BYTES))
|
||||
platform := fmt.Sprintf("Host: %s | OS: %s | Arch: %s", host, runtime.GOOS, runtime.GOARCH)
|
||||
goruntime := fmt.Sprintf("Version: %s | CPUs: %s", runtime.Version(), strconv.Itoa(runtime.NumCPU()))
|
||||
return map[string]string{
|
||||
"PLATFORM": platform,
|
||||
"RUNTIME": goruntime,
|
||||
"MEM": mem,
|
||||
}
|
||||
}
|
||||
|
||||
// initMC - initialize 'mc'.
|
||||
func initMC() {
|
||||
// Check if mc config exists.
|
||||
if !isMcConfigExists() {
|
||||
err := saveMcConfig(newMcConfig())
|
||||
fatalIf(err.Trace(), "Unable to save new mc config.")
|
||||
|
||||
if !globalQuiet && !globalJSON {
|
||||
console.Infoln("Configuration written to `" + mustGetMcConfigPath() + "`. Please update your access credentials.")
|
||||
}
|
||||
}
|
||||
|
||||
// Check if mc session folder exists.
|
||||
if !isSessionDirExists() {
|
||||
fatalIf(createSessionDir().Trace(), "Unable to create session config folder.")
|
||||
}
|
||||
|
||||
// Check if mc share folder exists.
|
||||
if !isShareDirExists() {
|
||||
initShareConfig()
|
||||
}
|
||||
|
||||
// Check if certs dir exists
|
||||
if !isCertsDirExists() {
|
||||
fatalIf(createCertsDir().Trace(), "Unable to create `CAs` folder.")
|
||||
}
|
||||
|
||||
// Check if CAs dir exists
|
||||
if !isCAsDirExists() {
|
||||
fatalIf(createCAsDir().Trace(), "Unable to create `CAs` folder.")
|
||||
}
|
||||
|
||||
// Load all authority certificates present in CAs dir
|
||||
loadRootCAs()
|
||||
}
|
||||
|
||||
func registerBefore(ctx *cli.Context) error {
|
||||
// Check if mc was compiled using a supported version of Golang.
|
||||
checkGoVersion()
|
||||
|
||||
// Set the config folder.
|
||||
setMcConfigDir(ctx.GlobalString("config-folder"))
|
||||
|
||||
// Migrate any old version of config / state files to newer format.
|
||||
migrate()
|
||||
|
||||
// Set global flags.
|
||||
setGlobalsFromContext(ctx)
|
||||
|
||||
// Initialize default config files.
|
||||
initMC()
|
||||
|
||||
// Check if config can be read.
|
||||
checkConfig()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// findClosestCommands to match a given string with commands trie tree.
|
||||
func findClosestCommands(command string) []string {
|
||||
var closestCommands []string
|
||||
for _, value := range commandsTree.PrefixMatch(command) {
|
||||
closestCommands = append(closestCommands, value.(string))
|
||||
}
|
||||
sort.Strings(closestCommands)
|
||||
// Suggest other close commands - allow missed, wrongly added and even transposed characters
|
||||
for _, value := range commandsTree.Walk(commandsTree.Root()) {
|
||||
if sort.SearchStrings(closestCommands, value.(string)) < len(closestCommands) {
|
||||
continue
|
||||
}
|
||||
// 2 is arbitrary and represents the max allowed number of typed errors
|
||||
if words.DamerauLevenshteinDistance(command, value.(string)) < 2 {
|
||||
closestCommands = append(closestCommands, value.(string))
|
||||
}
|
||||
}
|
||||
return closestCommands
|
||||
}
|
||||
|
||||
// Check for updates and print a notification message
|
||||
func checkUpdate(ctx *cli.Context) {
|
||||
// Do not print update messages, if quiet flag is set.
|
||||
if ctx.Bool("quiet") || ctx.GlobalBool("quiet") {
|
||||
older, downloadURL, err := getUpdateInfo(1 * time.Second)
|
||||
if err != nil {
|
||||
// Its OK to ignore any errors during getUpdateInfo() here.
|
||||
return
|
||||
}
|
||||
if older > time.Duration(0) {
|
||||
console.Println(colorizeUpdateMessage(downloadURL, older))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func registerApp() *cli.App {
|
||||
// Register all the commands (refer flags.go)
|
||||
registerCmd(lsCmd) // List contents of a bucket.
|
||||
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(findCmd) // Find specific String patterns
|
||||
registerCmd(statCmd) // Stat contents of a bucket/object
|
||||
registerCmd(diffCmd) // Computer differences between two files or folders.
|
||||
registerCmd(rmCmd) // Remove a file or bucket
|
||||
registerCmd(eventsCmd) // Add events cmd
|
||||
registerCmd(watchCmd) // Add watch cmd
|
||||
registerCmd(policyCmd) // Set policy permissions.
|
||||
registerCmd(adminCmd) // Manage Minio servers
|
||||
registerCmd(sessionCmd) // Manage sessions for copy and mirror.
|
||||
registerCmd(configCmd) // Configure minio client.
|
||||
registerCmd(updateCmd) // Check for new software updates.
|
||||
registerCmd(versionCmd) // Print version.
|
||||
|
||||
cli.HelpFlag = cli.BoolFlag{
|
||||
Name: "help, h",
|
||||
Usage: "Show help.",
|
||||
}
|
||||
|
||||
cli.BashCompletionFlag = cli.BoolFlag{
|
||||
Name: "compgen",
|
||||
Usage: "Enables bash-completion for all commands and subcommands.",
|
||||
Hidden: true,
|
||||
}
|
||||
|
||||
app := cli.NewApp()
|
||||
app.Action = func(ctx *cli.Context) {
|
||||
if strings.HasPrefix(Version, "RELEASE.") {
|
||||
// Check for new updates from dl.minio.io.
|
||||
checkUpdate(ctx)
|
||||
}
|
||||
cli.ShowAppHelp(ctx)
|
||||
}
|
||||
|
||||
app.HideVersion = true
|
||||
app.HideHelpCommand = true
|
||||
app.Usage = "Minio Client for cloud storage and filesystems."
|
||||
app.Commands = commands
|
||||
app.Author = "Minio.io"
|
||||
app.Version = Version
|
||||
app.Flags = append(mcFlags, globalFlags...)
|
||||
app.CustomAppHelpTemplate = mcHelpTemplate
|
||||
app.CommandNotFound = commandNotFound // handler function declared above.
|
||||
app.EnableBashCompletion = true
|
||||
|
||||
return app
|
||||
}
|
||||
|
||||
// mustGetProfilePath must get location that the profile will be written to.
|
||||
func mustGetProfileDir() string {
|
||||
return filepath.Join(mustGetMcConfigDir(), globalProfileDir)
|
||||
}
|
||||
+55
-36
@@ -14,7 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
@@ -22,19 +22,19 @@ import (
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
)
|
||||
|
||||
var (
|
||||
mbFlags = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "help, h",
|
||||
Usage: "Help of mb.",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "region",
|
||||
Value: "us-east-1",
|
||||
Usage: "Specify bucket region. Defaults to ‘us-east-1’.",
|
||||
Usage: "Specify bucket region. Defaults to `us-east-1`.",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "ignore-existing, p",
|
||||
Usage: "Ignore if bucket/directory already exists",
|
||||
},
|
||||
}
|
||||
)
|
||||
@@ -42,30 +42,35 @@ var (
|
||||
// make a bucket or folder.
|
||||
var mbCmd = cli.Command{
|
||||
Name: "mb",
|
||||
Usage: "Make a bucket or folder.",
|
||||
Usage: "Make a bucket or a folder.",
|
||||
Action: mainMakeBucket,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(mbFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
mc {{.Name}} - {{.Usage}}
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
mc {{.Name}} [FLAGS] TARGET [TARGET...]
|
||||
|
||||
{{.HelpName}} [FLAGS] TARGET [TARGET...]
|
||||
{{if .VisibleFlags}}
|
||||
FLAGS:
|
||||
{{range .Flags}}{{.}}
|
||||
{{end}}
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}{{end}}
|
||||
EXAMPLES:
|
||||
1. Create a bucket on Amazon S3 cloud storage.
|
||||
$ mc {{.Name}} s3/mynewbucket
|
||||
$ {{.HelpName}} s3/mynewbucket
|
||||
|
||||
2. Create a new bucket on Google Cloud Storage.
|
||||
$ mc {{.Name}} gcs/miniocloud
|
||||
$ {{.HelpName}} gcs/miniocloud
|
||||
|
||||
4. Create a new bucket on Amazon S3 cloud storage in region ‘us-west-2’.
|
||||
$ mc {{.Name}} --region=us-west-2 s3/myregionbucket
|
||||
4. Create a new bucket on Amazon S3 cloud storage in region 'us-west-2'.
|
||||
$ {{.HelpName}} --region=us-west-2 s3/myregionbucket
|
||||
|
||||
5. Create a new directory including its missing parents (equivalent to 'mkdir -p').
|
||||
$ {{.HelpName}} /tmp/this/new/dir1
|
||||
|
||||
6. Create multiple directories including its missing parents (behavior similar to 'mkdir -p').
|
||||
$ {{.HelpName}} /mnt/sdb/mydisk /mnt/sdc/mydisk /mnt/sdd/mydisk
|
||||
|
||||
5. Create a new directory including its missing parents (equivalent to ‘mkdir -p’).
|
||||
$ mc {{.Name}} /tmp/this/new/dir1
|
||||
`,
|
||||
}
|
||||
|
||||
@@ -78,7 +83,7 @@ type makeBucketMessage struct {
|
||||
|
||||
// String colorized make bucket message.
|
||||
func (s makeBucketMessage) String() string {
|
||||
return console.Colorize("MakeBucket", "Bucket created successfully ‘"+s.Bucket+"’.")
|
||||
return console.Colorize("MakeBucket", "Bucket created successfully `"+s.Bucket+"`.")
|
||||
}
|
||||
|
||||
// JSON jsonified make bucket message.
|
||||
@@ -94,15 +99,10 @@ func checkMakeBucketSyntax(ctx *cli.Context) {
|
||||
if !ctx.Args().Present() {
|
||||
cli.ShowCommandHelpAndExit(ctx, "mb", 1) // last argument is exit code
|
||||
}
|
||||
if len(ctx.Args()) != 1 {
|
||||
fatalIf(errInvalidArgument().Trace(ctx.Args()...), "Incorrect number of arguments for mb command.")
|
||||
}
|
||||
}
|
||||
|
||||
// mainMakeBucket is entry point for mb command.
|
||||
func mainMakeBucket(ctx *cli.Context) {
|
||||
// Set global flags from context.
|
||||
setGlobalsFromContext(ctx)
|
||||
func mainMakeBucket(ctx *cli.Context) error {
|
||||
|
||||
// check 'mb' cli arguments.
|
||||
checkMakeBucketSyntax(ctx)
|
||||
@@ -110,18 +110,37 @@ func mainMakeBucket(ctx *cli.Context) {
|
||||
// Additional command speific theme customization.
|
||||
console.SetColor("MakeBucket", color.New(color.FgGreen, color.Bold))
|
||||
|
||||
// save region.
|
||||
// Save region.
|
||||
region := ctx.String("region")
|
||||
ignoreExisting := ctx.Bool("p")
|
||||
|
||||
targetURL := ctx.Args().First()
|
||||
// Instantiate client for URL.
|
||||
clnt, err := newClient(targetURL)
|
||||
fatalIf(err.Trace(targetURL), "Invalid target ‘"+targetURL+"’.")
|
||||
var cErr error
|
||||
for _, targetURL := range ctx.Args() {
|
||||
// Instantiate client for URL.
|
||||
clnt, err := newClient(targetURL)
|
||||
if err != nil {
|
||||
errorIf(err.Trace(targetURL), "Invalid target `"+targetURL+"`.")
|
||||
cErr = exitStatus(globalErrorExitStatus)
|
||||
continue
|
||||
}
|
||||
|
||||
// Make bucket.
|
||||
err = clnt.MakeBucket(region)
|
||||
fatalIf(err.Trace(targetURL), "Unable to make bucket ‘"+targetURL+"’.")
|
||||
// Make bucket.
|
||||
err = clnt.MakeBucket(region, ignoreExisting)
|
||||
if err != nil {
|
||||
switch err.ToGoError().(type) {
|
||||
case BucketNameEmpty:
|
||||
errorIf(err.Trace(targetURL), "Unable to make bucket, please use `mc mb %s/<your-bucket-name>`.", targetURL)
|
||||
case BucketNameTopLevel:
|
||||
errorIf(err.Trace(targetURL), "Unable to make prefix, please use `mc mb %s/`.", targetURL)
|
||||
default:
|
||||
errorIf(err.Trace(targetURL), "Unable to make bucket `"+targetURL+"`.")
|
||||
}
|
||||
cErr = exitStatus(globalErrorExitStatus)
|
||||
continue
|
||||
}
|
||||
|
||||
// Successfully created a bucket.
|
||||
printMsg(makeBucketMessage{Status: "success", Bucket: targetURL})
|
||||
// Successfully created a bucket.
|
||||
printMsg(makeBucketMessage{Status: "success", Bucket: targetURL})
|
||||
}
|
||||
return cErr
|
||||
}
|
||||
+22
-35
@@ -14,7 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
@@ -22,23 +22,16 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"net/http/httptest"
|
||||
|
||||
"github.com/minio/cli"
|
||||
"github.com/hashicorp/go-version"
|
||||
. "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) {
|
||||
}
|
||||
|
||||
@@ -46,18 +39,18 @@ func (s *TestSuite) TearDownSuite(c *C) {
|
||||
}
|
||||
|
||||
func (s *TestSuite) TestValidPERMS(c *C) {
|
||||
perms := accessPerms("private")
|
||||
perms := accessPerms("none")
|
||||
c.Assert(perms.isValidAccessPERM(), Equals, true)
|
||||
c.Assert(perms.String(), Equals, "private")
|
||||
c.Assert(string(perms), Equals, "none")
|
||||
perms = accessPerms("public")
|
||||
c.Assert(perms.isValidAccessPERM(), Equals, true)
|
||||
c.Assert(perms.String(), Equals, "public-read-write")
|
||||
perms = accessPerms("readonly")
|
||||
c.Assert(string(perms), Equals, "public")
|
||||
perms = accessPerms("download")
|
||||
c.Assert(perms.isValidAccessPERM(), Equals, true)
|
||||
c.Assert(perms.String(), Equals, "public-read")
|
||||
perms = accessPerms("authorized")
|
||||
c.Assert(string(perms), Equals, "download")
|
||||
perms = accessPerms("upload")
|
||||
c.Assert(perms.isValidAccessPERM(), Equals, true)
|
||||
c.Assert(perms.String(), Equals, "authenticated-read")
|
||||
c.Assert(string(perms), Equals, "upload")
|
||||
}
|
||||
|
||||
func (s *TestSuite) TestInvalidPERMS(c *C) {
|
||||
@@ -76,11 +69,7 @@ func (s *TestSuite) TestGetMcConfigPath(c *C) {
|
||||
dir, err := getMcConfigPath()
|
||||
c.Assert(err, IsNil)
|
||||
switch runtime.GOOS {
|
||||
case "linux":
|
||||
fallthrough
|
||||
case "freebsd":
|
||||
fallthrough
|
||||
case "darwin":
|
||||
case "linux", "freebsd", "darwin", "solaris":
|
||||
c.Assert(dir, Equals, filepath.Join(mustGetMcConfigDir(), "config.json"))
|
||||
case "windows":
|
||||
c.Assert(dir, Equals, filepath.Join(mustGetMcConfigDir(), "config.json"))
|
||||
@@ -92,6 +81,7 @@ func (s *TestSuite) TestGetMcConfigPath(c *C) {
|
||||
|
||||
func (s *TestSuite) TestIsvalidAliasName(c *C) {
|
||||
c.Check(isValidAlias("helloWorld0"), Equals, true)
|
||||
c.Check(isValidAlias("hello_World0"), Equals, true)
|
||||
c.Check(isValidAlias("h0SFD2k24Fdsa"), Equals, true)
|
||||
c.Check(isValidAlias("fdslka-4"), Equals, true)
|
||||
c.Check(isValidAlias("fdslka-"), Equals, true)
|
||||
@@ -102,31 +92,28 @@ func (s *TestSuite) TestIsvalidAliasName(c *C) {
|
||||
}
|
||||
|
||||
func (s *TestSuite) TestHumanizedTime(c *C) {
|
||||
hTime := timeDurationToHumanizedTime(time.Duration(10) * time.Second)
|
||||
hTime := timeDurationToHumanizedDuration(time.Duration(10) * time.Second)
|
||||
c.Assert(hTime.Minutes, Equals, int64(0))
|
||||
c.Assert(hTime.Hours, Equals, int64(0))
|
||||
c.Assert(hTime.Days, Equals, int64(0))
|
||||
|
||||
hTime = timeDurationToHumanizedTime(time.Duration(10) * time.Minute)
|
||||
hTime = timeDurationToHumanizedDuration(time.Duration(10) * time.Minute)
|
||||
c.Assert(hTime.Hours, Equals, int64(0))
|
||||
c.Assert(hTime.Days, Equals, int64(0))
|
||||
|
||||
hTime = timeDurationToHumanizedTime(time.Duration(10) * time.Hour)
|
||||
hTime = timeDurationToHumanizedDuration(time.Duration(10) * time.Hour)
|
||||
c.Assert(hTime.Days, Equals, int64(0))
|
||||
|
||||
hTime = timeDurationToHumanizedTime(time.Duration(24) * time.Hour)
|
||||
hTime = timeDurationToHumanizedDuration(time.Duration(24) * time.Hour)
|
||||
c.Assert(hTime.Days, Not(Equals), int64(0))
|
||||
}
|
||||
|
||||
func (s *TestSuite) TestCommonPrefix(c *C) {
|
||||
c.Assert(commonPrefix("/usr", "/usr/local"), Equals, "/usr")
|
||||
c.Assert(commonPrefix("/uabbf", "/ursfad/ccc"), Equals, "/u")
|
||||
c.Assert(commonPrefix("/usr/local/lib", "/usr/local/test"), Equals, "/usr/local/")
|
||||
}
|
||||
|
||||
func (s *TestSuite) TestVersions(c *C) {
|
||||
v1 := newVersion("1.5.1")
|
||||
v2 := newVersion("1.5.0")
|
||||
c.Assert(v2.LessThan(v1), Equals, true)
|
||||
c.Assert(v1.LessThan(v2), Equals, false)
|
||||
v1, e := version.NewVersion("1.8")
|
||||
v2, e := version.NewVersion("1.7")
|
||||
c.Assert(e, IsNil)
|
||||
constraint, e := version.NewConstraint(">= 1.8")
|
||||
c.Assert(e, IsNil)
|
||||
c.Assert(constraint.Check(v1), Equals, true)
|
||||
c.Assert(constraint.Check(v2), Equals, false)
|
||||
}
|
||||
@@ -0,0 +1,776 @@
|
||||
/*
|
||||
* Minio Client, (C) 2015, 2016 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
)
|
||||
|
||||
// mirror specific flags.
|
||||
var (
|
||||
mirrorFlags = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "force",
|
||||
Usage: "Force allows forced overwrite or removal of file(s) on target(s).",
|
||||
Hidden: true, // Hidden since this option is deprecated.
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "overwrite",
|
||||
Usage: "Overwrite file(s) on target(s).",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "fake",
|
||||
Usage: "Perform a fake mirror operation.",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "watch, w",
|
||||
Usage: "Watch and mirror for changes.",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "remove",
|
||||
Usage: "Remove extraneous file(s) on target(s).",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "region",
|
||||
Usage: "Specify which region to select when creating new buckets.",
|
||||
Value: "us-east-1",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "a",
|
||||
Usage: "Preserve bucket policies rules.",
|
||||
},
|
||||
cli.StringSliceFlag{
|
||||
Name: "exclude",
|
||||
Usage: "Exclude file/object that matches the passed file name pattern.",
|
||||
},
|
||||
cli.IntFlag{
|
||||
Name: "older-than",
|
||||
Usage: "Select objects older than N days",
|
||||
},
|
||||
cli.IntFlag{
|
||||
Name: "newer-than",
|
||||
Usage: "Select objects newer than N days",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "storage-class, sc",
|
||||
Usage: "Set storage class for object",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "encrypt-key",
|
||||
Usage: "Encrypt/Decrypt objects (using server-side encryption)",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
// Mirror folders recursively from a single source to many destinations
|
||||
var mirrorCmd = cli.Command{
|
||||
Name: "mirror",
|
||||
Usage: "Mirror buckets and folders.",
|
||||
Action: mainMirror,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(mirrorFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} [FLAGS] SOURCE TARGET
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
|
||||
ENVIRONMENT VARIABLES:
|
||||
MC_ENCRYPT_KEY: List of comma delimited prefix=secret values
|
||||
|
||||
EXAMPLES:
|
||||
1. Mirror a bucket recursively from Minio cloud storage to a bucket on Amazon S3 cloud storage.
|
||||
$ {{.HelpName}} play/photos/2014 s3/backup-photos
|
||||
|
||||
2. Mirror a local folder recursively to Amazon S3 cloud storage.
|
||||
$ {{.HelpName}} backup/ s3/archive
|
||||
|
||||
3. Only mirror files that are newer than 7 days to Amazon S3 cloud storage.
|
||||
$ {{.HelpName}} --newer-than 7 backup/ s3/archive
|
||||
|
||||
4. Mirror a bucket from aliased Amazon S3 cloud storage to a folder on Windows.
|
||||
$ {{.HelpName}} s3\documents\2014\ C:\backup\2014
|
||||
|
||||
5. Mirror a bucket from aliased Amazon S3 cloud storage to a local folder use '--overwrite' to overwrite destination.
|
||||
$ {{.HelpName}} --overwrite s3/miniocloud miniocloud-backup
|
||||
|
||||
6. Mirror a bucket from Minio cloud storage to a bucket on Amazon S3 cloud storage and remove any extraneous
|
||||
files on Amazon S3 cloud storage.
|
||||
$ {{.HelpName}} --remove play/photos/2014 s3/backup-photos/2014
|
||||
|
||||
7. Continuously mirror a local folder recursively to Minio cloud storage. '--watch' continuously watches for
|
||||
new objects, uploads and removes extraneous files on Amazon S3 cloud storage.
|
||||
$ {{.HelpName}} --remove --watch /var/lib/backups play/backups
|
||||
|
||||
8. Mirror a bucket from aliased Amazon S3 cloud storage to a local folder.
|
||||
Exclude all .* files and *.temp files when mirroring.
|
||||
$ {{.HelpName}} --exclude ".*" --exclude "*.temp" s3/test ~/test
|
||||
|
||||
9. Mirror objects newer than 10 days from bucket test to a local folder.
|
||||
$ {{.HelpName}} --newer-than=10 s3/test ~/localfolder
|
||||
|
||||
10. Mirror objects older than 30 days from Amazon S3 bucket test to a local folder.
|
||||
$ {{.HelpName}} --older-than=30 s3/test ~/test
|
||||
|
||||
11. Mirror server encrypted objects from Minio cloud storage to a bucket on Amazon S3 cloud storage
|
||||
$ {{.HelpName}} --encrypt-key "minio/photos=32byteslongsecretkeymustbegiven1,s3/archive=32byteslongsecretkeymustbegiven2" minio/photos/ s3/archive/
|
||||
|
||||
`,
|
||||
}
|
||||
|
||||
type mirrorJob struct {
|
||||
|
||||
// the channel to trap SIGKILL signals
|
||||
trapCh <-chan bool
|
||||
|
||||
// mutex for shutdown, this prevents the shutdown
|
||||
// to be initiated multiple times
|
||||
m *sync.Mutex
|
||||
|
||||
// channel for errors
|
||||
errorCh chan *probe.Error
|
||||
|
||||
// the global watcher object, which receives notifications of created
|
||||
// and deleted files
|
||||
watcher *Watcher
|
||||
|
||||
// Hold operation status information
|
||||
status Status
|
||||
|
||||
// waitgroup for status goroutine, waits till all status
|
||||
// messages have been written and received
|
||||
wgStatus *sync.WaitGroup
|
||||
|
||||
queueCh chan func() URLs
|
||||
// channel for status messages
|
||||
statusCh chan URLs
|
||||
|
||||
TotalObjects int64
|
||||
TotalBytes int64
|
||||
|
||||
sourceURL string
|
||||
targetURL string
|
||||
|
||||
isFake, isRemove, isOverwrite, isWatch bool
|
||||
olderThan, newerThan int
|
||||
storageClass string
|
||||
|
||||
excludeOptions []string
|
||||
encKeyDB map[string][]prefixSSEPair
|
||||
}
|
||||
|
||||
// mirrorMessage container for file mirror messages
|
||||
type mirrorMessage struct {
|
||||
Status string `json:"status"`
|
||||
Source string `json:"source"`
|
||||
Target string `json:"target"`
|
||||
Size int64 `json:"size"`
|
||||
TotalCount int64 `json:"totalCount"`
|
||||
TotalSize int64 `json:"totalSize"`
|
||||
}
|
||||
|
||||
// String colorized mirror message
|
||||
func (m mirrorMessage) String() string {
|
||||
return console.Colorize("Mirror", fmt.Sprintf("`%s` -> `%s`", m.Source, m.Target))
|
||||
}
|
||||
|
||||
// JSON jsonified mirror message
|
||||
func (m mirrorMessage) JSON() string {
|
||||
m.Status = "success"
|
||||
mirrorMessageBytes, e := json.Marshal(m)
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(mirrorMessageBytes)
|
||||
}
|
||||
|
||||
// doRemove - removes files on target.
|
||||
func (mj *mirrorJob) doRemove(sURLs URLs) URLs {
|
||||
if mj.isFake {
|
||||
return sURLs.WithError(nil)
|
||||
}
|
||||
|
||||
// We are not removing incomplete uploads.
|
||||
isIncomplete := false
|
||||
|
||||
// Construct proper path with alias.
|
||||
targetWithAlias := filepath.Join(sURLs.TargetAlias, sURLs.TargetContent.URL.Path)
|
||||
|
||||
// Remove extraneous file on target.
|
||||
err := probe.NewError(removeSingle(targetWithAlias, isIncomplete, mj.isFake, 0, 0, sURLs.encKeyDB))
|
||||
return sURLs.WithError(err)
|
||||
}
|
||||
|
||||
// doMirror - Mirror an object to multiple destination. URLs status contains a copy of sURLs and error if any.
|
||||
func (mj *mirrorJob) doMirror(ctx context.Context, cancelMirror context.CancelFunc, sURLs URLs) URLs {
|
||||
|
||||
if sURLs.Error != nil { // Erroneous sURLs passed.
|
||||
return sURLs.WithError(sURLs.Error.Trace())
|
||||
}
|
||||
|
||||
//s For a fake mirror make sure we update respective progress bars
|
||||
// and accounting readers under relevant conditions.
|
||||
if mj.isFake {
|
||||
mj.status.Add(sURLs.SourceContent.Size)
|
||||
return sURLs.WithError(nil)
|
||||
}
|
||||
|
||||
sourceAlias := sURLs.SourceAlias
|
||||
sourceURL := sURLs.SourceContent.URL
|
||||
targetAlias := sURLs.TargetAlias
|
||||
targetURL := sURLs.TargetContent.URL
|
||||
length := sURLs.SourceContent.Size
|
||||
|
||||
mj.status.SetCaption(sourceURL.String() + ": ")
|
||||
|
||||
if mj.storageClass != "" {
|
||||
if sURLs.TargetContent.Metadata == nil {
|
||||
sURLs.TargetContent.Metadata = make(map[string]string)
|
||||
}
|
||||
sURLs.TargetContent.Metadata["X-Amz-Storage-Class"] = mj.storageClass
|
||||
}
|
||||
|
||||
sourcePath := filepath.ToSlash(filepath.Join(sourceAlias, sourceURL.Path))
|
||||
targetPath := filepath.ToSlash(filepath.Join(targetAlias, targetURL.Path))
|
||||
mj.status.PrintMsg(mirrorMessage{
|
||||
Source: sourcePath,
|
||||
Target: targetPath,
|
||||
Size: length,
|
||||
TotalCount: sURLs.TotalCount,
|
||||
TotalSize: sURLs.TotalSize,
|
||||
})
|
||||
return uploadSourceToTargetURL(ctx, sURLs, mj.status)
|
||||
}
|
||||
|
||||
// Go routine to update progress status
|
||||
func (mj *mirrorJob) startStatus() {
|
||||
mj.wgStatus.Add(1)
|
||||
|
||||
// wait for status messages on statusChan, show error messages
|
||||
go func() {
|
||||
// now we want to start the progress bar
|
||||
mj.status.Start()
|
||||
defer mj.wgStatus.Done()
|
||||
|
||||
for sURLs := range mj.statusCh {
|
||||
if sURLs.Error != nil {
|
||||
// Print in new line and adjust to top so that we
|
||||
// don't print over the ongoing progress bar.
|
||||
if sURLs.SourceContent != nil {
|
||||
errorIf(sURLs.Error.Trace(sURLs.SourceContent.URL.String()),
|
||||
fmt.Sprintf("Failed to copy `%s`.", sURLs.SourceContent.URL.String()))
|
||||
} else {
|
||||
// When sURLs.SourceContent is nil, we know that we have an error related to removing
|
||||
errorIf(sURLs.Error.Trace(sURLs.TargetContent.URL.String()),
|
||||
fmt.Sprintf("Failed to remove `%s`.", sURLs.TargetContent.URL.String()))
|
||||
}
|
||||
}
|
||||
|
||||
if sURLs.SourceContent != nil {
|
||||
} else if sURLs.TargetContent != nil {
|
||||
// Construct user facing message and path.
|
||||
targetPath := filepath.ToSlash(filepath.Join(sURLs.TargetAlias, sURLs.TargetContent.URL.Path))
|
||||
mj.status.PrintMsg(rmMessage{Key: targetPath})
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// Stop status go routine, further updates could lead to a crash
|
||||
func (mj *mirrorJob) stopStatus() {
|
||||
close(mj.statusCh)
|
||||
mj.wgStatus.Wait()
|
||||
mj.status.Finish()
|
||||
}
|
||||
|
||||
// this goroutine will watch for notifications, and add modified objects to the queue
|
||||
func (mj *mirrorJob) watchMirror(ctx context.Context, cancelMirror context.CancelFunc, errCh chan<- *probe.Error) {
|
||||
for {
|
||||
select {
|
||||
case event, ok := <-mj.watcher.Events():
|
||||
if !ok {
|
||||
errCh <- nil
|
||||
// channel closed
|
||||
return
|
||||
}
|
||||
|
||||
// It will change the expanded alias back to the alias
|
||||
// again, by replacing the sourceUrlFull with the sourceAlias.
|
||||
// This url will be used to mirror.
|
||||
sourceAlias, sourceURLFull, _ := mustExpandAlias(mj.sourceURL)
|
||||
|
||||
// If the passed source URL points to fs, fetch the absolute src path
|
||||
// to correctly calculate targetPath
|
||||
if sourceAlias == "" {
|
||||
tmpSrcURL, err := filepath.Abs(sourceURLFull)
|
||||
if err == nil {
|
||||
sourceURLFull = tmpSrcURL
|
||||
}
|
||||
}
|
||||
eventPath := event.Path
|
||||
|
||||
if runtime.GOOS == "darwin" {
|
||||
// Strip the prefixes in the event path. Happens in darwin OS only
|
||||
eventPath = eventPath[strings.Index(eventPath, sourceURLFull):len(eventPath)]
|
||||
}
|
||||
|
||||
sourceURL := newClientURL(eventPath)
|
||||
aliasedPath := strings.Replace(eventPath, sourceURLFull, mj.sourceURL, -1)
|
||||
|
||||
// build target path, it is the relative of the eventPath with the sourceUrl
|
||||
// joined to the targetURL.
|
||||
sourceSuffix := strings.TrimPrefix(eventPath, sourceURLFull)
|
||||
//Skip the object, if it matches the Exclude options provided
|
||||
if matchExcludeOptions(mj.excludeOptions, sourceSuffix) {
|
||||
continue
|
||||
}
|
||||
|
||||
targetPath := urlJoinPath(mj.targetURL, sourceSuffix)
|
||||
|
||||
// newClient needs the unexpanded path, newCLientURL needs the expanded path
|
||||
targetAlias, expandedTargetPath, _ := mustExpandAlias(targetPath)
|
||||
targetURL := newClientURL(expandedTargetPath)
|
||||
sourcePath := filepath.ToSlash(filepath.Join(sourceAlias, sourceURL.Path))
|
||||
srcSSEKey := getSSEKey(sourcePath, mj.encKeyDB[sourceAlias])
|
||||
tgtSSEKey := getSSEKey(targetPath, mj.encKeyDB[targetAlias])
|
||||
|
||||
if event.Type == EventCreate {
|
||||
// we are checking if a destination file exists now, and if we only
|
||||
// overwrite it when force is enabled.
|
||||
mirrorURL := URLs{
|
||||
SourceAlias: sourceAlias,
|
||||
SourceContent: &clientContent{URL: *sourceURL},
|
||||
TargetAlias: targetAlias,
|
||||
TargetContent: &clientContent{URL: *targetURL},
|
||||
encKeyDB: mj.encKeyDB,
|
||||
SrcSSEKey: srcSSEKey,
|
||||
TgtSSEKey: tgtSSEKey,
|
||||
}
|
||||
if event.Size == 0 {
|
||||
sourceClient, err := newClient(aliasedPath)
|
||||
if err != nil {
|
||||
// cannot create sourceclient
|
||||
mj.statusCh <- mirrorURL.WithError(err)
|
||||
continue
|
||||
}
|
||||
sourceContent, err := sourceClient.Stat(false, false, srcSSEKey)
|
||||
if err != nil {
|
||||
// source doesn't exist anymore
|
||||
mj.statusCh <- mirrorURL.WithError(err)
|
||||
continue
|
||||
}
|
||||
targetClient, err := newClient(targetPath)
|
||||
if err != nil {
|
||||
// cannot create targetclient
|
||||
mj.statusCh <- mirrorURL.WithError(err)
|
||||
return
|
||||
}
|
||||
shouldQueue := false
|
||||
if !mj.isOverwrite {
|
||||
_, err = targetClient.Stat(false, false, tgtSSEKey)
|
||||
if err == nil {
|
||||
continue
|
||||
} // doesn't exist
|
||||
shouldQueue = true
|
||||
}
|
||||
if shouldQueue || mj.isOverwrite {
|
||||
mirrorURL.TotalCount = mj.TotalObjects
|
||||
mirrorURL.TotalSize = mj.TotalBytes
|
||||
// adjust total, because we want to show progress of the item still queued to be copied.
|
||||
mj.status.SetTotal(mj.status.Total() + sourceContent.Size).Update()
|
||||
mj.statusCh <- mj.doMirror(ctx, cancelMirror, mirrorURL)
|
||||
}
|
||||
continue
|
||||
}
|
||||
shouldQueue := false
|
||||
if !mj.isOverwrite {
|
||||
targetClient, err := newClient(targetPath)
|
||||
if err != nil {
|
||||
// cannot create targetclient
|
||||
mj.statusCh <- mirrorURL.WithError(err)
|
||||
return
|
||||
}
|
||||
_, err = targetClient.Stat(false, false, tgtSSEKey)
|
||||
if err == nil {
|
||||
continue
|
||||
} // doesn't exist
|
||||
shouldQueue = true
|
||||
}
|
||||
if shouldQueue || mj.isOverwrite {
|
||||
mirrorURL.SourceContent.Size = event.Size
|
||||
mirrorURL.TotalCount = mj.TotalObjects
|
||||
mirrorURL.TotalSize = mj.TotalBytes
|
||||
// adjust total, because we want to show progress of the itemj stiil queued to be copied.
|
||||
mj.status.SetTotal(mj.status.Total() + event.Size).Update()
|
||||
mj.statusCh <- mj.doMirror(ctx, cancelMirror, mirrorURL)
|
||||
}
|
||||
} else if event.Type == EventRemove {
|
||||
mirrorURL := URLs{
|
||||
SourceAlias: sourceAlias,
|
||||
SourceContent: nil,
|
||||
TargetAlias: targetAlias,
|
||||
TargetContent: &clientContent{URL: *targetURL},
|
||||
SrcSSEKey: srcSSEKey,
|
||||
TgtSSEKey: tgtSSEKey,
|
||||
encKeyDB: mj.encKeyDB,
|
||||
}
|
||||
mirrorURL.TotalCount = mj.TotalObjects
|
||||
mirrorURL.TotalSize = mj.TotalBytes
|
||||
if mirrorURL.TargetContent != nil && mj.isRemove {
|
||||
mj.statusCh <- mj.doRemove(mirrorURL)
|
||||
}
|
||||
}
|
||||
|
||||
case err := <-mj.watcher.Errors():
|
||||
switch err.ToGoError().(type) {
|
||||
case APINotImplemented:
|
||||
errorIf(err.Trace(), "Unable to Watch on source, ignoring.")
|
||||
// Watch is perhaps not implemented, log and ignore the error.
|
||||
err = nil
|
||||
}
|
||||
errCh <- err
|
||||
return
|
||||
case <-mj.trapCh:
|
||||
errCh <- nil
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (mj *mirrorJob) watchSourceURL(recursive bool) *probe.Error {
|
||||
sourceClient, err := newClient(mj.sourceURL)
|
||||
if err == nil {
|
||||
return mj.watcher.Join(sourceClient, recursive)
|
||||
} // Failed to initialize client.
|
||||
return err
|
||||
}
|
||||
|
||||
func (mj *mirrorJob) watchURL(sourceClient Client) *probe.Error {
|
||||
return mj.watcher.Join(sourceClient, true)
|
||||
}
|
||||
|
||||
// Fetch urls that need to be mirrored
|
||||
func (mj *mirrorJob) startMirror(ctx context.Context, cancelMirror context.CancelFunc, errCh chan<- *probe.Error) {
|
||||
var totalBytes int64
|
||||
var totalObjects int64
|
||||
|
||||
parallel, queueCh := newParallelManager(mj.statusCh, mj.status)
|
||||
stopParallel := func() {
|
||||
close(queueCh)
|
||||
parallel.wait()
|
||||
}
|
||||
|
||||
URLsCh := prepareMirrorURLs(mj.sourceURL, mj.targetURL, mj.isFake, mj.isOverwrite, mj.isRemove, mj.excludeOptions, mj.encKeyDB)
|
||||
|
||||
for {
|
||||
select {
|
||||
case sURLs, ok := <-URLsCh:
|
||||
if !ok {
|
||||
stopParallel()
|
||||
errCh <- nil
|
||||
return
|
||||
}
|
||||
if sURLs.Error != nil {
|
||||
errCh <- sURLs.Error
|
||||
continue
|
||||
}
|
||||
|
||||
if sURLs.SourceContent != nil {
|
||||
// Skip objects older than --older-than parameter if specified
|
||||
if mj.olderThan > 0 && isOlder(sURLs.SourceContent, mj.olderThan) {
|
||||
continue
|
||||
}
|
||||
|
||||
// Skip objects newer than --newer-than parameter if specified
|
||||
if mj.newerThan > 0 && isNewer(sURLs.SourceContent, mj.newerThan) {
|
||||
continue
|
||||
}
|
||||
|
||||
// copy
|
||||
totalBytes += sURLs.SourceContent.Size
|
||||
}
|
||||
|
||||
totalObjects++
|
||||
mj.TotalBytes = totalBytes
|
||||
mj.TotalObjects = totalObjects
|
||||
mj.status.SetTotal(totalBytes)
|
||||
|
||||
// Save total count.
|
||||
sURLs.TotalCount = mj.TotalObjects
|
||||
// Save totalSize.
|
||||
sURLs.TotalSize = mj.TotalBytes
|
||||
|
||||
if sURLs.SourceContent != nil {
|
||||
queueCh <- func() URLs {
|
||||
return mj.doMirror(ctx, cancelMirror, sURLs)
|
||||
}
|
||||
} else if sURLs.TargetContent != nil && mj.isRemove {
|
||||
queueCh <- func() URLs {
|
||||
return mj.doRemove(sURLs)
|
||||
}
|
||||
}
|
||||
case <-mj.trapCh:
|
||||
stopParallel()
|
||||
cancelMirror()
|
||||
errCh <- nil
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// when using a struct for copying, we could save a lot of passing of variables
|
||||
func (mj *mirrorJob) mirror(ctx context.Context, cancelMirror context.CancelFunc) *probe.Error {
|
||||
// start the status go routine
|
||||
mj.startStatus()
|
||||
|
||||
watchErrCh := make(chan *probe.Error)
|
||||
mirrorErrCh := make(chan *probe.Error)
|
||||
|
||||
// Starts watcher loop for watching for new events.
|
||||
if mj.isWatch {
|
||||
go mj.watchMirror(ctx, cancelMirror, watchErrCh)
|
||||
}
|
||||
|
||||
// Start mirroring.
|
||||
go mj.startMirror(ctx, cancelMirror, mirrorErrCh)
|
||||
|
||||
// Wait until all progress bar updates are actually shown and quit.
|
||||
defer mj.stopStatus()
|
||||
|
||||
var err *probe.Error
|
||||
var ok bool
|
||||
for {
|
||||
select {
|
||||
case err, ok = <-mirrorErrCh:
|
||||
if !ok || err == nil {
|
||||
if mj.isWatch {
|
||||
continue
|
||||
}
|
||||
return nil
|
||||
}
|
||||
case err, ok = <-watchErrCh:
|
||||
if !ok || err == nil {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
switch err.ToGoError().(type) {
|
||||
case BrokenSymlink, TooManyLevelsSymlink, PathNotFound,
|
||||
PathInsufficientPermission, ObjectOnGlacier:
|
||||
errorIf(err, "Unable to perform a mirror action.")
|
||||
continue
|
||||
case overwriteNotAllowedErr:
|
||||
errorIf(err, "Unable to perform a mirror action.")
|
||||
continue
|
||||
}
|
||||
return err.Trace()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func newMirrorJob(srcURL, dstURL string, isFake, isRemove, isOverwrite, isWatch bool, excludeOptions []string, olderThan, newerThan int, storageClass string, encKeyDB map[string][]prefixSSEPair) *mirrorJob {
|
||||
// we'll define the status to use here,
|
||||
// do we want the quiet status? or the progressbar
|
||||
var status = NewProgressStatus()
|
||||
if globalQuiet {
|
||||
status = NewQuietStatus()
|
||||
} else if globalJSON {
|
||||
status = NewDummyStatus()
|
||||
}
|
||||
|
||||
mj := mirrorJob{
|
||||
trapCh: signalTrap(os.Interrupt, syscall.SIGTERM, syscall.SIGKILL),
|
||||
m: new(sync.Mutex),
|
||||
|
||||
sourceURL: srcURL,
|
||||
targetURL: dstURL,
|
||||
|
||||
isFake: isFake,
|
||||
isRemove: isRemove,
|
||||
isOverwrite: isOverwrite,
|
||||
isWatch: isWatch,
|
||||
excludeOptions: excludeOptions,
|
||||
olderThan: olderThan,
|
||||
newerThan: newerThan,
|
||||
storageClass: storageClass,
|
||||
encKeyDB: encKeyDB,
|
||||
status: status,
|
||||
statusCh: make(chan URLs),
|
||||
queueCh: make(chan func() URLs),
|
||||
wgStatus: new(sync.WaitGroup),
|
||||
watcher: NewWatcher(UTCNow()),
|
||||
}
|
||||
|
||||
return &mj
|
||||
}
|
||||
|
||||
// copyBucketPolicies - copy policies from source to dest
|
||||
func copyBucketPolicies(srcClt, dstClt Client, isOverwrite bool) *probe.Error {
|
||||
rules, err := srcClt.GetAccessRules()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Set found rules to target bucket if permitted
|
||||
for _, r := range rules {
|
||||
originalRule, err := dstClt.GetAccess()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Set rule only if it doesn't exist in the target bucket
|
||||
// or force flag is activated
|
||||
if originalRule == "none" || isOverwrite {
|
||||
err = dstClt.SetAccess(r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// runMirror - mirrors all buckets to another S3 server
|
||||
func runMirror(srcURL, dstURL string, ctx *cli.Context, encKeyDB map[string][]prefixSSEPair) *probe.Error {
|
||||
// This is kept for backward compatibility, `--force` means
|
||||
// --overwrite.
|
||||
isOverwrite := ctx.Bool("force")
|
||||
if !isOverwrite {
|
||||
isOverwrite = ctx.Bool("overwrite")
|
||||
}
|
||||
|
||||
// Create a new mirror job and execute it
|
||||
mj := newMirrorJob(srcURL, dstURL,
|
||||
ctx.Bool("fake"),
|
||||
ctx.Bool("remove"),
|
||||
isOverwrite,
|
||||
ctx.Bool("watch"),
|
||||
ctx.StringSlice("exclude"),
|
||||
ctx.Int("older-than"),
|
||||
ctx.Int("newer-than"),
|
||||
ctx.String("storage-class"),
|
||||
encKeyDB)
|
||||
|
||||
srcClt, err := newClient(srcURL)
|
||||
fatalIf(err, "Unable to initialize `"+srcURL+"`.")
|
||||
|
||||
dstClt, err := newClient(dstURL)
|
||||
fatalIf(err, "Unable to initialize `"+srcURL+"`.")
|
||||
|
||||
if ctx.Bool("a") && (srcClt.GetURL().Type != objectStorage || dstClt.GetURL().Type != objectStorage) {
|
||||
fatalIf(errDummy(), "Synchronizing bucket policies is only possible when both source & target point to S3 servers.")
|
||||
}
|
||||
|
||||
mirrorAllBuckets := (srcClt.GetURL().Type == objectStorage && srcClt.GetURL().Path == "/") ||
|
||||
(dstClt.GetURL().Type == objectStorage && dstClt.GetURL().Path == "/")
|
||||
|
||||
if mirrorAllBuckets {
|
||||
// Synchronize buckets using dirDifference function
|
||||
for d := range dirDifference(srcClt, dstClt, srcURL, dstURL) {
|
||||
if d.Error != nil {
|
||||
mj.status.fatalIf(d.Error, fmt.Sprintf("Failed to start monitoring."))
|
||||
}
|
||||
if d.Diff == differInSecond {
|
||||
// Ignore buckets that only exist in target instance
|
||||
continue
|
||||
}
|
||||
|
||||
sourceSuffix := strings.TrimPrefix(d.FirstURL, srcClt.GetURL().String())
|
||||
newSrcURL := path.Join(srcURL, sourceSuffix)
|
||||
newTgtURL := path.Join(dstURL, sourceSuffix)
|
||||
|
||||
newSrcClt, _ := newClient(newSrcURL)
|
||||
newDstClt, _ := newClient(newTgtURL)
|
||||
|
||||
if d.Diff == differInFirst {
|
||||
// Bucket only exists in the source, create the same bucket in the destination
|
||||
if err := newDstClt.MakeBucket(ctx.String("region"), false); err != nil {
|
||||
errorIf(err, "Cannot created bucket in `"+newTgtURL+"`.")
|
||||
continue
|
||||
}
|
||||
// Copy policy rules from source to dest if flag is activated
|
||||
if ctx.Bool("a") {
|
||||
if err := copyBucketPolicies(srcClt, dstClt, isOverwrite); err != nil {
|
||||
errorIf(err, "Cannot copy bucket policies to `"+newDstClt.GetURL().String()+"`.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if mj.isWatch {
|
||||
// monitor mode will watch the source folders for changes,
|
||||
// and queue them for copying.
|
||||
if err := mj.watchURL(newSrcClt); err != nil {
|
||||
mj.status.fatalIf(err, fmt.Sprintf("Failed to start monitoring."))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !mirrorAllBuckets && mj.isWatch {
|
||||
// monitor mode will watch the source folders for changes,
|
||||
// and queue them for copying.
|
||||
if err := mj.watchURL(srcClt); err != nil {
|
||||
mj.status.fatalIf(err, fmt.Sprintf("Failed to start monitoring."))
|
||||
}
|
||||
}
|
||||
|
||||
ctxt, cancelMirror := context.WithCancel(context.Background())
|
||||
defer cancelMirror()
|
||||
|
||||
// Start mirroring job
|
||||
return mj.mirror(ctxt, cancelMirror)
|
||||
}
|
||||
|
||||
// Main entry point for mirror command.
|
||||
func mainMirror(ctx *cli.Context) error {
|
||||
// Parse encryption keys per command.
|
||||
encKeyDB, err := getEncKeys(ctx)
|
||||
fatalIf(err, "Unable to parse encryption keys.")
|
||||
|
||||
// check 'mirror' cli arguments.
|
||||
checkMirrorSyntax(ctx, encKeyDB)
|
||||
|
||||
// Additional command specific theme customization.
|
||||
console.SetColor("Mirror", color.New(color.FgGreen, color.Bold))
|
||||
|
||||
args := ctx.Args()
|
||||
|
||||
srcURL := args[0]
|
||||
tgtURL := args[1]
|
||||
|
||||
if err := runMirror(srcURL, tgtURL, ctx, encKeyDB); err != nil {
|
||||
errorIf(err.Trace(srcURL, tgtURL), "Unable to mirror.")
|
||||
return exitStatus(globalErrorExitStatus)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
/*
|
||||
* Minio Client (C) 2015, 2016 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/minio/pkg/wildcard"
|
||||
)
|
||||
|
||||
//
|
||||
// * MIRROR ARGS - VALID CASES
|
||||
// =========================
|
||||
// mirror(d1..., d2) -> []mirror(d1/f, d2/d1/f)
|
||||
|
||||
// checkMirrorSyntax(URLs []string)
|
||||
func checkMirrorSyntax(ctx *cli.Context, encKeyDB map[string][]prefixSSEPair) {
|
||||
if len(ctx.Args()) != 2 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "mirror", 1) // last argument is exit code.
|
||||
}
|
||||
|
||||
// extract URLs.
|
||||
URLs := ctx.Args()
|
||||
srcURL := URLs[0]
|
||||
tgtURL := URLs[1]
|
||||
|
||||
if ctx.Bool("force") && ctx.Bool("remove") {
|
||||
errorIf(errInvalidArgument().Trace(URLs...), "`--force` is deprecated please use `--overwrite` instead with `--remove` for the same functionality.")
|
||||
} else if ctx.Bool("force") {
|
||||
errorIf(errInvalidArgument().Trace(URLs...), "`--force` is deprecated please use `--overwrite` instead for the same functionality.")
|
||||
}
|
||||
|
||||
/****** Generic rules *******/
|
||||
if !ctx.Bool("watch") {
|
||||
_, srcContent, err := url2Stat(srcURL, false, encKeyDB)
|
||||
// incomplete uploads are not necessary for copy operation, no need to verify for them.
|
||||
isIncomplete := false
|
||||
if err != nil && !isURLPrefixExists(srcURL, isIncomplete) {
|
||||
errorIf(err.Trace(srcURL), "Unable to stat source `"+srcURL+"`.")
|
||||
}
|
||||
|
||||
if err == nil && !srcContent.Type.IsDir() {
|
||||
fatalIf(errInvalidArgument().Trace(srcContent.URL.String(), srcContent.Type.String()), fmt.Sprintf("Source `%s` is not a folder. Only folders are supported by mirror command.", srcURL))
|
||||
}
|
||||
}
|
||||
|
||||
if len(tgtURL) == 0 && tgtURL == "" {
|
||||
fatalIf(errInvalidArgument().Trace(), "Invalid target arguments to mirror command.")
|
||||
}
|
||||
|
||||
clientURL := newClientURL(tgtURL)
|
||||
if clientURL.Host != "" {
|
||||
if clientURL.Path == string(clientURL.Separator) {
|
||||
fatalIf(errInvalidArgument().Trace(tgtURL),
|
||||
fmt.Sprintf("Target `%s` does not contain bucket name.", tgtURL))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func matchExcludeOptions(excludeOptions []string, srcSuffix string) bool {
|
||||
for _, pattern := range excludeOptions {
|
||||
if wildcard.Match(pattern, srcSuffix) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func deltaSourceTarget(sourceURL, targetURL string, isFake, isOverwrite, isRemove bool, excludeOptions []string, URLsCh chan<- URLs, encKeyDB map[string][]prefixSSEPair) {
|
||||
// source and targets are always directories
|
||||
sourceSeparator := string(newClientURL(sourceURL).Separator)
|
||||
if !strings.HasSuffix(sourceURL, sourceSeparator) {
|
||||
sourceURL = sourceURL + sourceSeparator
|
||||
}
|
||||
targetSeparator := string(newClientURL(targetURL).Separator)
|
||||
if !strings.HasSuffix(targetURL, targetSeparator) {
|
||||
targetURL = targetURL + targetSeparator
|
||||
}
|
||||
|
||||
// Extract alias and expanded URL
|
||||
sourceAlias, sourceURL, _ := mustExpandAlias(sourceURL)
|
||||
targetAlias, targetURL, _ := mustExpandAlias(targetURL)
|
||||
|
||||
defer close(URLsCh)
|
||||
|
||||
sourceClnt, err := newClientFromAlias(sourceAlias, sourceURL)
|
||||
if err != nil {
|
||||
URLsCh <- URLs{Error: err.Trace(sourceAlias, sourceURL)}
|
||||
return
|
||||
}
|
||||
|
||||
targetClnt, err := newClientFromAlias(targetAlias, targetURL)
|
||||
if err != nil {
|
||||
URLsCh <- URLs{Error: err.Trace(targetAlias, targetURL)}
|
||||
return
|
||||
}
|
||||
|
||||
// List both source and target, compare and return values through channel.
|
||||
for diffMsg := range objectDifference(sourceClnt, targetClnt, sourceURL, targetURL) {
|
||||
if diffMsg.Error != nil {
|
||||
// Send all errors through the channel
|
||||
URLsCh <- URLs{Error: diffMsg.Error}
|
||||
return
|
||||
}
|
||||
|
||||
srcSuffix := strings.TrimPrefix(diffMsg.FirstURL, sourceURL)
|
||||
//Skip the source object if it matches the Exclude options provided
|
||||
if matchExcludeOptions(excludeOptions, srcSuffix) {
|
||||
continue
|
||||
}
|
||||
|
||||
tgtSuffix := strings.TrimPrefix(diffMsg.SecondURL, targetURL)
|
||||
//Skip the target object if it matches the Exclude options provided
|
||||
if matchExcludeOptions(excludeOptions, tgtSuffix) {
|
||||
continue
|
||||
}
|
||||
|
||||
sourcePath := filepath.ToSlash(filepath.Join(sourceAlias, sourceClnt.GetURL().Path))
|
||||
srcSSEKey := getSSEKey(sourcePath, encKeyDB[sourceAlias])
|
||||
targetPath := filepath.ToSlash(filepath.Join(targetAlias, targetClnt.GetURL().Path))
|
||||
tgtSSEKey := getSSEKey(targetPath, encKeyDB[targetAlias])
|
||||
|
||||
switch diffMsg.Diff {
|
||||
case differInNone:
|
||||
// No difference, continue.
|
||||
case differInType:
|
||||
URLsCh <- URLs{Error: errInvalidTarget(diffMsg.SecondURL)}
|
||||
case differInSize, differInTime:
|
||||
if !isOverwrite && !isFake {
|
||||
// Size or time differs but --overwrite not set.
|
||||
URLsCh <- URLs{Error: errOverWriteNotAllowed(diffMsg.SecondURL)}
|
||||
continue
|
||||
}
|
||||
|
||||
sourceSuffix := strings.TrimPrefix(diffMsg.FirstURL, sourceURL)
|
||||
// Either available only in source or size differs and force is set
|
||||
targetPath := urlJoinPath(targetURL, sourceSuffix)
|
||||
sourceContent := diffMsg.firstContent
|
||||
targetContent := &clientContent{URL: *newClientURL(targetPath)}
|
||||
URLsCh <- URLs{
|
||||
SourceAlias: sourceAlias,
|
||||
SourceContent: sourceContent,
|
||||
TargetAlias: targetAlias,
|
||||
TargetContent: targetContent,
|
||||
SrcSSEKey: srcSSEKey,
|
||||
TgtSSEKey: tgtSSEKey,
|
||||
}
|
||||
case differInFirst:
|
||||
// Only in first, always copy.
|
||||
sourceSuffix := strings.TrimPrefix(diffMsg.FirstURL, sourceURL)
|
||||
targetPath := urlJoinPath(targetURL, sourceSuffix)
|
||||
sourceContent := diffMsg.firstContent
|
||||
targetContent := &clientContent{URL: *newClientURL(targetPath)}
|
||||
URLsCh <- URLs{
|
||||
SourceAlias: sourceAlias,
|
||||
SourceContent: sourceContent,
|
||||
TargetAlias: targetAlias,
|
||||
TargetContent: targetContent,
|
||||
SrcSSEKey: srcSSEKey,
|
||||
TgtSSEKey: tgtSSEKey,
|
||||
}
|
||||
case differInSecond:
|
||||
if !isRemove && !isFake {
|
||||
continue
|
||||
}
|
||||
URLsCh <- URLs{
|
||||
TargetAlias: targetAlias,
|
||||
TargetContent: diffMsg.secondContent,
|
||||
TgtSSEKey: tgtSSEKey,
|
||||
}
|
||||
default:
|
||||
URLsCh <- URLs{
|
||||
Error: errUnrecognizedDiffType(diffMsg.Diff).Trace(diffMsg.FirstURL, diffMsg.SecondURL),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Prepares urls that need to be copied or removed based on requested options.
|
||||
func prepareMirrorURLs(sourceURL string, targetURL string, isFake, isOverwrite, isRemove bool, excludeOptions []string, encKeyDB map[string][]prefixSSEPair) <-chan URLs {
|
||||
URLsCh := make(chan URLs)
|
||||
go deltaSourceTarget(sourceURL, targetURL, isFake, isOverwrite, isRemove, excludeOptions, URLsCh, encKeyDB)
|
||||
return URLsCh
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Minio Client (C) 2015 Minio, Inc.
|
||||
* Minio Client (C) 2017 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -14,50 +14,54 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"runtime"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/cheggaaa/pb"
|
||||
"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
|
||||
// colorizeUpdateMessage - inspired from Yeoman project npm package https://github.com/yeoman/update-notifier
|
||||
func colorizeUpdateMessage(updateString string, newerThan time.Duration) string {
|
||||
// Initialize coloring.
|
||||
cyan := color.New(color.FgCyan, color.Bold).SprintFunc()
|
||||
yellow := color.New(color.FgYellow, color.Bold).SprintfFunc()
|
||||
|
||||
// calculate length without color coding, due to ANSI color characters padded to actual
|
||||
// string the final length is wrong than the original string length.
|
||||
line1Str := fmt.Sprintf(" New update available, please execute the following command to update: ")
|
||||
line2Str := fmt.Sprintf(" %s ", updateString)
|
||||
// Calculate length without color coding, due to ANSI color
|
||||
// characters padded to actual string the final length is wrong
|
||||
// than the original string length.
|
||||
hTime := timeDurationToHumanizedDuration(newerThan)
|
||||
line1Str := fmt.Sprintf(" mc is %s old ", hTime.StringShort())
|
||||
line2Str := fmt.Sprintf(" Update: %s ", updateString)
|
||||
line1Length := len(line1Str)
|
||||
line2Length := len(line2Str)
|
||||
|
||||
// populate lines with color coding.
|
||||
line1InColor := line1Str
|
||||
line2InColor := fmt.Sprintf(" %s ", cyan(updateString))
|
||||
// Populate lines with color coding.
|
||||
line1InColor := fmt.Sprintf(" mc is %s old ", yellow(hTime.StringShort()))
|
||||
line2InColor := fmt.Sprintf(" Update: %s ", cyan(updateString))
|
||||
|
||||
// calculate the rectangular box size.
|
||||
maxContentWidth := int(math.Max(float64(line1Length), float64(line2Length)))
|
||||
line1Rest := maxContentWidth - line1Length
|
||||
line2Rest := maxContentWidth - line2Length
|
||||
|
||||
// Fetch terminal size to calculate optimal box size.
|
||||
terminal, e := ts.GetSize()
|
||||
if e != nil {
|
||||
return "", probe.NewError(e)
|
||||
// termWidth is set to a default one to use when we are
|
||||
// not able to calculate terminal width via OS syscalls
|
||||
termWidth := 25
|
||||
|
||||
if width, err := pb.GetTerminalWidth(); err == nil {
|
||||
termWidth = width
|
||||
}
|
||||
|
||||
var message string
|
||||
switch {
|
||||
case len(line2Str) > terminal.Col():
|
||||
case len(line2Str) > termWidth:
|
||||
message = "\n" + line1InColor + "\n" + line2InColor + "\n"
|
||||
default:
|
||||
// on windows terminal turn off unicode characters.
|
||||
@@ -82,6 +86,6 @@ func colorizeUpdateMessage(updateString string) (string, *probe.Error) {
|
||||
sideBar + line2InColor + spacePaddingLine2 + sideBar + "\n" +
|
||||
bottom + "\n"
|
||||
}
|
||||
// return the final message
|
||||
return message, nil
|
||||
// Return the final message.
|
||||
return message
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user