Compare commits
589
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1dea194699 | ||
|
|
4569e519c5 | ||
|
|
0236dcf780 | ||
|
|
5e5ad3367d | ||
|
|
744b4728d1 | ||
|
|
f811b029b1 | ||
|
|
8b77f918b3 | ||
|
|
c5453d1528 | ||
|
|
fc668edadf | ||
|
|
01b0928989 | ||
|
|
0a4fce57cf | ||
|
|
257321c425 | ||
|
|
3b5dcd478a | ||
|
|
5c52a0adae | ||
|
|
d572648261 | ||
|
|
85e8b542de | ||
|
|
3a3dbb2722 | ||
|
|
47cd83c71c | ||
|
|
700f261b86 | ||
|
|
3f3adb1858 | ||
|
|
9a40a67410 | ||
|
|
cfac37f53b | ||
|
|
a769ce6439 | ||
|
|
951067295e | ||
|
|
bd97054b93 | ||
|
|
796d36083d | ||
|
|
acc4b97483 | ||
|
|
d92a93566b | ||
|
|
244d377f0a | ||
|
|
e958557d28 | ||
|
|
3b35f44eba | ||
|
|
c26c61d3c4 | ||
|
|
b347137d88 | ||
|
|
99e12696eb | ||
|
|
f01dc5b60c | ||
|
|
50240b0a1e | ||
|
|
11b286c149 | ||
|
|
fa87ad6b37 | ||
|
|
dd50ad532e | ||
|
|
31b07812cb | ||
|
|
e59ba922bd | ||
|
|
008a5f00de | ||
|
|
8a91ec65ce | ||
|
|
35cdba2204 | ||
|
|
664f982833 | ||
|
|
c08ebb25cd | ||
|
|
f7cdbc2583 | ||
|
|
d47faa3256 | ||
|
|
9cd535a6cd | ||
|
|
b6fe0d2529 | ||
|
|
0bd1edfd8f | ||
|
|
7ee79bc960 | ||
|
|
29f46b833c | ||
|
|
c888977e51 | ||
|
|
fbdae31d5b | ||
|
|
fe27a5c415 | ||
|
|
8686fe725f | ||
|
|
23992411cc | ||
|
|
727538fa8c | ||
|
|
dfc0dc3042 | ||
|
|
a4bc2c2be1 | ||
|
|
3f6053822f | ||
|
|
9fed1d73ee | ||
|
|
3782c4abe0 | ||
|
|
2663de4489 | ||
|
|
36e7e42637 | ||
|
|
3f91446e6e | ||
|
|
278701db48 | ||
|
|
5104938796 | ||
|
|
062e75617d | ||
|
|
4d339f7373 | ||
|
|
db9f5b3890 | ||
|
|
18d0df16bc | ||
|
|
e866b69baf | ||
|
|
8949e30524 | ||
|
|
791199e11c | ||
|
|
479b69487d | ||
|
|
0f1388aec2 | ||
|
|
fb133b6cce | ||
|
|
f463a45c7b | ||
|
|
759fb1f079 | ||
|
|
0fd1e3c387 | ||
|
|
3b95a39e3a | ||
|
|
7bd78afc3a | ||
|
|
93e26e9032 | ||
|
|
ca5d829158 | ||
|
|
a92a9e4c73 | ||
|
|
10d6e18600 | ||
|
|
dbdcdff874 | ||
|
|
c573ccf641 | ||
|
|
3b7d63bbf3 | ||
|
|
de463d2ada | ||
|
|
1664551119 | ||
|
|
cc78c1c5df | ||
|
|
99cc307a62 | ||
|
|
5acdfaf413 | ||
|
|
aea88d3756 | ||
|
|
4769531b3a | ||
|
|
a38318e6af | ||
|
|
4c3ea052c4 | ||
|
|
9219e1a320 | ||
|
|
59659f5bed | ||
|
|
4485529911 | ||
|
|
96afead3f1 | ||
|
|
1badfc8a04 | ||
|
|
1d07866fd3 | ||
|
|
e98c9b3625 | ||
|
|
6d542975be | ||
|
|
97090aee0c | ||
|
|
1429d26507 | ||
|
|
f94989dc0a | ||
|
|
9fe3b00394 | ||
|
|
f94399b01c | ||
|
|
71c03aa9d0 | ||
|
|
841c65c867 | ||
|
|
38631e0f34 | ||
|
|
8fc138f3a0 | ||
|
|
de760d4efb | ||
|
|
67809d105b | ||
|
|
5425d62130 | ||
|
|
681f389228 | ||
|
|
997527ee6c | ||
|
|
ae74a0d25b | ||
|
|
c4b8aaa2b2 | ||
|
|
5a30dadbe3 | ||
|
|
7c75879e4d | ||
|
|
aa3007bcd0 | ||
|
|
598be201f3 | ||
|
|
7df4766c93 | ||
|
|
e8b7a403a2 | ||
|
|
9771f2eb27 | ||
|
|
9479c999f2 | ||
|
|
d8e8fb0089 | ||
|
|
9ee1913e93 | ||
|
|
fd1cde749a | ||
|
|
9432addb14 | ||
|
|
7e5f4776ca | ||
|
|
f578358ab8 | ||
|
|
558c20e1e3 | ||
|
|
50c5d6429f | ||
|
|
3f52c951e7 | ||
|
|
11b82a6268 | ||
|
|
cc0cde16c6 | ||
|
|
4cd9421080 | ||
|
|
39ba33f4c6 | ||
|
|
2151c98abb | ||
|
|
269ac7b105 | ||
|
|
6a2b4e959d | ||
|
|
052f73f348 | ||
|
|
d81eaf56fa | ||
|
|
7355eecf56 | ||
|
|
c78b6e6645 | ||
|
|
0671f246ad | ||
|
|
cface860c5 | ||
|
|
11ea306ad2 | ||
|
|
88f188d202 | ||
|
|
d08392ba40 | ||
|
|
79474d117f | ||
|
|
6e56f06bd3 | ||
|
|
1167b2f231 | ||
|
|
de9380dd9d | ||
|
|
2f0acf91fa | ||
|
|
c757cf1829 | ||
|
|
02041802fe | ||
|
|
2a9293b79f | ||
|
|
16405682f8 | ||
|
|
bbf0f7687c | ||
|
|
c96117fa5d | ||
|
|
5f2417c8ad | ||
|
|
3e1819a33f | ||
|
|
1a85e97050 | ||
|
|
670fac2afb | ||
|
|
67fc0a61fe | ||
|
|
123fde256e | ||
|
|
1778d6a448 | ||
|
|
e6e5524d73 | ||
|
|
446cae9820 | ||
|
|
9ba8219481 | ||
|
|
569dd41ec5 | ||
|
|
9c226b0836 | ||
|
|
58056b0331 | ||
|
|
ba31d5812f | ||
|
|
628e8734ce | ||
|
|
26fa3ce647 | ||
|
|
da65cbae06 | ||
|
|
a106443505 | ||
|
|
36505dfd2c | ||
|
|
ad2cd0d529 | ||
|
|
cecc409a71 | ||
|
|
65723f1fce | ||
|
|
3c8afb2877 | ||
|
|
f248536162 | ||
|
|
b36ae24f86 | ||
|
|
22b409f535 | ||
|
|
2349ebda6b | ||
|
|
1dfc28dbc7 | ||
|
|
2eb9e58771 | ||
|
|
3d29ad2c17 | ||
|
|
b03deb9d3c | ||
|
|
54864b12b4 | ||
|
|
83d2accd5b | ||
|
|
28c9d83cc4 | ||
|
|
d4d14eb67b | ||
|
|
93de4ebfd1 | ||
|
|
34c9896d1d | ||
|
|
ca245999d5 | ||
|
|
097b337545 | ||
|
|
6db5b8fddc | ||
|
|
e7002e097b | ||
|
|
d8c60b998c | ||
|
|
d5dd4fb5bd | ||
|
|
b007b7cf91 | ||
|
|
054aaadde8 | ||
|
|
1ebcf98a6f | ||
|
|
0e2ab60c15 | ||
|
|
c5984150d3 | ||
|
|
5f01f6d98c | ||
|
|
454261962e | ||
|
|
61ec25d2bf | ||
|
|
2a3485b4be | ||
|
|
fa497d3811 | ||
|
|
1c1cd2aa7e | ||
|
|
75409ca9b5 | ||
|
|
8becf5fc64 | ||
|
|
f7bf20e4ce | ||
|
|
a089e541cc | ||
|
|
6e9ec398da | ||
|
|
7bb90683c2 | ||
|
|
2db255c276 | ||
|
|
330cfe65bb | ||
|
|
b2da734ec9 | ||
|
|
a7c02c675e | ||
|
|
43eda0e93f | ||
|
|
3eda3bfd44 | ||
|
|
0945e3b872 | ||
|
|
d66c79370c | ||
|
|
5f9055e7fd | ||
|
|
1673f9cd10 | ||
|
|
05675c3022 | ||
|
|
3f59c3d27a | ||
|
|
1a6c7ffd95 | ||
|
|
b481b4f1c3 | ||
|
|
6b4d976755 | ||
|
|
fd82bbf453 | ||
|
|
1d2aa6bcf3 | ||
|
|
b745676a24 | ||
|
|
cc434c43d1 | ||
|
|
389020b340 | ||
|
|
17bfd21ac8 | ||
|
|
1a8dad77ee | ||
|
|
4ee7cb92e0 | ||
|
|
24bf38a053 | ||
|
|
2419ca9c4d | ||
|
|
550f47371f | ||
|
|
9caa205f40 | ||
|
|
eada588802 | ||
|
|
1c2f292f77 | ||
|
|
8b897f169a | ||
|
|
d43416ca17 | ||
|
|
3c10e77ab6 | ||
|
|
4bd5f3063a | ||
|
|
a2b522da10 | ||
|
|
c76787c363 | ||
|
|
9a92298cca | ||
|
|
cbb937139e | ||
|
|
2132576d49 | ||
|
|
f686fc6ef4 | ||
|
|
b627ca12e5 | ||
|
|
2a4c7151f3 | ||
|
|
425b18a9c9 | ||
|
|
0e56a3b900 | ||
|
|
0a3cc546a5 | ||
|
|
aa3eacecf2 | ||
|
|
e63405bd96 | ||
|
|
814ba2cd97 | ||
|
|
fa9e1bc6df | ||
|
|
a218b3d2bc | ||
|
|
876873ec6f | ||
|
|
f529106f80 | ||
|
|
4df9c08972 | ||
|
|
e1763a057b | ||
|
|
baadb0d77e | ||
|
|
2320487dcb | ||
|
|
5391cf80a4 | ||
|
|
888e187a69 | ||
|
|
f78e197de3 | ||
|
|
3fb6d7f1bd | ||
|
|
295fed8b06 | ||
|
|
b10f709c09 | ||
|
|
c7ab507354 | ||
|
|
ff13eb5764 | ||
|
|
4248f5c996 | ||
|
|
7831917901 | ||
|
|
97abe0b87f | ||
|
|
19453ed798 | ||
|
|
b15e1e49fc | ||
|
|
afcb9223e4 | ||
|
|
b889dc7c99 | ||
|
|
eb35b5d9ee | ||
|
|
659a795ac4 | ||
|
|
a3522a2962 | ||
|
|
13a83d19db | ||
|
|
7999472cb7 | ||
|
|
2d221b656c | ||
|
|
e6a96a411a | ||
|
|
e65af14868 | ||
|
|
4af9e0e83c | ||
|
|
2bcef94ed5 | ||
|
|
36c66d7aa1 | ||
|
|
527cd0e661 | ||
|
|
44f03bede1 | ||
|
|
f2aa4a112d | ||
|
|
39f7441790 | ||
|
|
321e1aa039 | ||
|
|
7856e331a1 | ||
|
|
4ae29d6dd9 | ||
|
|
d75690c4fd | ||
|
|
127b72ab9f | ||
|
|
cf76387dea | ||
|
|
9335f9cf04 | ||
|
|
516a377bad | ||
|
|
c3331213bc | ||
|
|
540b72426a | ||
|
|
68d6066778 | ||
|
|
c68af8451b | ||
|
|
3c0f3134ca | ||
|
|
55a20d91aa | ||
|
|
47f1d2487b | ||
|
|
ee5e47c967 | ||
|
|
20a78ba84c | ||
|
|
995d2b1045 | ||
|
|
16faf7ed3e | ||
|
|
c4283ab48f | ||
|
|
dfbd6e6567 | ||
|
|
f94fca577b | ||
|
|
d9ecccaef2 | ||
|
|
e453443637 | ||
|
|
fb39bcba80 | ||
|
|
f37fdd8b81 | ||
|
|
365a7579bf | ||
|
|
ca0aaa2871 | ||
|
|
d4015c454b | ||
|
|
af91cd28cb | ||
|
|
17526e5cb6 | ||
|
|
6731541217 | ||
|
|
15a0466966 | ||
|
|
4c3f28f7dc | ||
|
|
f31e90f4a2 | ||
|
|
565bf235db | ||
|
|
5f56efb956 | ||
|
|
3f1ebdd846 | ||
|
|
5ba1266f5b | ||
|
|
5b5327d61a | ||
|
|
bfde2b119a | ||
|
|
e1c5cddc60 | ||
|
|
07abb224e6 | ||
|
|
2e072ec010 | ||
|
|
836c78bc72 | ||
|
|
40b5548838 | ||
|
|
2ea16262e0 | ||
|
|
e8e2d4a6c4 | ||
|
|
75f27fa74c | ||
|
|
91b02672d5 | ||
|
|
f419064871 | ||
|
|
cced0b79ec | ||
|
|
eb78783c3f | ||
|
|
2f30f6728d | ||
|
|
d03681df74 | ||
|
|
20bdadaf22 | ||
|
|
3790cf557a | ||
|
|
dd81951f51 | ||
|
|
940fd7c608 | ||
|
|
97381f67ca | ||
|
|
22051bb8af | ||
|
|
bdb04d5dc8 | ||
|
|
dc4b903be9 | ||
|
|
cf40673309 | ||
|
|
4f9589ef79 | ||
|
|
2a72d6b494 | ||
|
|
54e24eccaa | ||
|
|
a523baf1fc | ||
|
|
eb10e0e089 | ||
|
|
61062dd999 | ||
|
|
d917951b58 | ||
|
|
cdf1980666 | ||
|
|
e060875409 | ||
|
|
299fea13d5 | ||
|
|
3950402c89 | ||
|
|
bb06a6a733 | ||
|
|
5018b01a51 | ||
|
|
d8d7e89a42 | ||
|
|
881a8a1366 | ||
|
|
930ea1badd | ||
|
|
824a6b8cb8 | ||
|
|
6c605df8a3 | ||
|
|
21cf62912e | ||
|
|
6cd0ca9c51 | ||
|
|
49d5cd6b63 | ||
|
|
bd2573f210 | ||
|
|
9480f8c9ae | ||
|
|
27c3bb1e2c | ||
|
|
ed0dbb835b | ||
|
|
20b546b361 | ||
|
|
900770abfd | ||
|
|
1534003e95 | ||
|
|
5afc55acb7 | ||
|
|
1021d0b336 | ||
|
|
6f7e752aa0 | ||
|
|
fa85630cf7 | ||
|
|
7d3b1a6ddb | ||
|
|
d757a36e97 | ||
|
|
6176771556 | ||
|
|
f5ee78faa6 | ||
|
|
3422bab341 | ||
|
|
287ef7a9a8 | ||
|
|
32c7590621 | ||
|
|
9c98d7eaee | ||
|
|
d6c16ad597 | ||
|
|
286fe7fd7b | ||
|
|
970927cc6b | ||
|
|
fc6a2971cb | ||
|
|
08697dc332 | ||
|
|
d16e1f6d40 | ||
|
|
39edb01800 | ||
|
|
12b26375e2 | ||
|
|
8f11c67956 | ||
|
|
ebf96ea853 | ||
|
|
6333935562 | ||
|
|
09f696c640 | ||
|
|
08c90a2c03 | ||
|
|
b7dc5414d8 | ||
|
|
03e9fa70dd | ||
|
|
3fca2428ad | ||
|
|
dc985953e4 | ||
|
|
04b4ef4928 | ||
|
|
6d86cbc686 | ||
|
|
93ec567278 | ||
|
|
6a8224b4ab | ||
|
|
4441c9bb31 | ||
|
|
56ccca29f9 | ||
|
|
26ebf2d028 | ||
|
|
3d847915c7 | ||
|
|
2617b62ed3 | ||
|
|
fb48c24176 | ||
|
|
c37824d058 | ||
|
|
cb87550978 | ||
|
|
b71e2b4962 | ||
|
|
b9033d1cac | ||
|
|
d8efa979ff | ||
|
|
d634e3883a | ||
|
|
27a8e64350 | ||
|
|
334e864eea | ||
|
|
6534268dc2 | ||
|
|
8273192dcf | ||
|
|
5572d47cd2 | ||
|
|
234c3906d4 | ||
|
|
ffd1f54b55 | ||
|
|
8de841cd69 | ||
|
|
9f206f590f | ||
|
|
503e746778 | ||
|
|
c3e7786c92 | ||
|
|
540b76fb9c | ||
|
|
65d39bbfa9 | ||
|
|
d9d9f6f63c | ||
|
|
c67dfa8da3 | ||
|
|
2a8dd4b553 | ||
|
|
69ca816fd8 | ||
|
|
123e44d8c5 | ||
|
|
a719323cdd | ||
|
|
aedd2d2c39 | ||
|
|
9447548805 | ||
|
|
a17cb6037d | ||
|
|
619bc1bf23 | ||
|
|
e65b55e01a | ||
|
|
0ab5e27456 | ||
|
|
4ecade6ca6 | ||
|
|
d9fa12d862 | ||
|
|
c4dbd82f7d | ||
|
|
a584e6ce14 | ||
|
|
adc391d0b6 | ||
|
|
f4a00c9904 | ||
|
|
cab949b88f | ||
|
|
671ce5242d | ||
|
|
b89fe068e9 | ||
|
|
76a47677c3 | ||
|
|
4d2d32e661 | ||
|
|
d85973042c | ||
|
|
8570a25709 | ||
|
|
23e1d34d64 | ||
|
|
d23dcd8204 | ||
|
|
a0d7e5f9be | ||
|
|
a20c5518b1 | ||
|
|
ae447a96ad | ||
|
|
7452f7b1d2 | ||
|
|
00611fb35b | ||
|
|
fb6e9476fc | ||
|
|
079becd49e | ||
|
|
8ad658058b | ||
|
|
d4b6b180ad | ||
|
|
5ca65022c3 | ||
|
|
86edabd264 | ||
|
|
89b2ddd9f9 | ||
|
|
48adfcdcd8 | ||
|
|
009c1fd8ce | ||
|
|
f94de478c3 | ||
|
|
1ee1b984b8 | ||
|
|
795a8edf64 | ||
|
|
47991fba6c | ||
|
|
3d6b19f833 | ||
|
|
3473c88e95 | ||
|
|
322f1a0561 | ||
|
|
118d7e3bb4 | ||
|
|
513ab017b9 | ||
|
|
706124b248 | ||
|
|
b240c7c88a | ||
|
|
491a6ab31c | ||
|
|
e9bc4af214 | ||
|
|
ca6075e776 | ||
|
|
1cab0c2c24 | ||
|
|
53d32e31db | ||
|
|
d11767771c | ||
|
|
e74615943c | ||
|
|
2f46510d26 | ||
|
|
56ee709f16 | ||
|
|
a3b49bdd34 | ||
|
|
548f410ea7 | ||
|
|
9ccd387bc6 | ||
|
|
cbf1cc0206 | ||
|
|
1eb171544f | ||
|
|
21f8f55176 | ||
|
|
b4c78a33ff | ||
|
|
2a3b201457 | ||
|
|
7f7e4cc330 | ||
|
|
302d2c967f | ||
|
|
b73d4662e8 | ||
|
|
881c12ddf1 | ||
|
|
f85e8827e1 | ||
|
|
ed85b64fd5 | ||
|
|
ee212e5b52 | ||
|
|
8f08a067c4 | ||
|
|
0f8f5ae6b6 | ||
|
|
3d12efaaca | ||
|
|
30f08b054f | ||
|
|
096b229e03 | ||
|
|
7eb149d49c | ||
|
|
ccf7613e87 | ||
|
|
2218eaefd3 | ||
|
|
ca2525bb63 | ||
|
|
78a2c33b00 | ||
|
|
636f243dcc | ||
|
|
7ce37ea115 | ||
|
|
21a90da0bf | ||
|
|
a1365f63f0 | ||
|
|
c4b9891c6e | ||
|
|
f730083872 | ||
|
|
ef98d5963b | ||
|
|
1d51b376e7 | ||
|
|
918b5c06a0 | ||
|
|
31a72a02d2 | ||
|
|
26cb1e7ae3 | ||
|
|
f49cac08b9 | ||
|
|
4782259e57 | ||
|
|
ca7f612ac4 | ||
|
|
b1ae9bbfa3 | ||
|
|
18c0671c7e | ||
|
|
6ff16c0a0e | ||
|
|
98129e8400 | ||
|
|
e03315ba44 | ||
|
|
d3f7a28f14 | ||
|
|
0d63b236e8 | ||
|
|
5f6990014d | ||
|
|
16d489fa3b | ||
|
|
db4387c56a | ||
|
|
45b1351991 | ||
|
|
4354c139a0 | ||
|
|
0175f11388 | ||
|
|
1fb55f7685 | ||
|
|
aa53fb19f9 | ||
|
|
7ec74a33ce | ||
|
|
7c251c314b | ||
|
|
428cc1eed6 | ||
|
|
e3f3698526 | ||
|
|
6d95872ad8 | ||
|
|
f38e0569a6 | ||
|
|
dbe53325b0 | ||
|
|
4787a7b2a3 | ||
|
|
87aadd20ec | ||
|
|
9d96acfd01 | ||
|
|
9b45038a78 |
+18
-2
@@ -1,9 +1,25 @@
|
||||
sudo: false
|
||||
language: go
|
||||
|
||||
script:
|
||||
- make test GOFLAGS="-race"
|
||||
|
||||
os:
|
||||
- linux
|
||||
- osx
|
||||
|
||||
env:
|
||||
- ARCH=x86_64
|
||||
- ARCH=i686
|
||||
|
||||
go:
|
||||
- 1.5.1
|
||||
sudo: false
|
||||
- 1.5.2
|
||||
- 1.5.3
|
||||
|
||||
script:
|
||||
- diff -au <(gofmt -d *.go) <(printf "")
|
||||
- diff -au <(gofmt -d pkg) <(printf "")
|
||||
|
||||
notifications:
|
||||
slack:
|
||||
secure: McinxQ4R/Yu2r/U8lVsdAIQ195Rf+3/Ku6DViWyqLHsTt5fTnVrSfbIKs8vy0t2A0bRLO6zv2xOSMWjfiimZLPMgMbMqLtTFEzUzB8RZyx2n2xgmL8q3gjXcLA3vkBreaRYCzJzX6DjvrxRfhyOg+BQHpLpACWik3FS/7VIdDCI=
|
||||
|
||||
+1
-1
@@ -20,7 +20,7 @@ $ mc --help
|
||||
- Push to the branch (git push origin my-new-feature)
|
||||
- Create new Pull Request
|
||||
|
||||
* If you have additional dependencies for ``mc``, ``mc`` manages its depedencies using [govendor](https://github.com/kardianos/govendor)
|
||||
* If you have additional dependencies for ``mc``, ``mc`` manages its dependencies using [govendor](https://github.com/kardianos/govendor)
|
||||
- Run `go get foo/bar`
|
||||
- Edit your code to import foo/bar
|
||||
- Run `make pkg-add PKG=foo/bar` from top-level folder
|
||||
|
||||
+30
-8
@@ -23,9 +23,20 @@ Add the following exports to your ``~/.bashrc``. Environment variable GOROOT spe
|
||||
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
|
||||
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
|
||||
@@ -53,12 +64,23 @@ $ mkdir -p $HOME/go
|
||||
|
||||
##### Setup GOROOT and GOPATH
|
||||
|
||||
Add the following exports to your ``~/.bashrc``. Environment variable GOROOT specifies the location of your golang binaries
|
||||
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
|
||||
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,5 +1,9 @@
|
||||
# For maintainers only
|
||||
|
||||
## Responsibilities
|
||||
|
||||
Please go through this link [Maintainer Responsibility](https://gist.github.com/abperiasamy/f4d9b31d3186bbd26522)
|
||||
|
||||
### Setup your mc Github Repository
|
||||
|
||||
Fork [mc upstream](https://github.com/minio/mc/fork) source repository to your own personal repository.
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
## filter multiple GOPATH
|
||||
LDFLAGS := $(shell go run buildscripts/gen-ldflags.go)
|
||||
BUILD_LDFLAGS := '$(LDFLAGS)'
|
||||
|
||||
all: install
|
||||
|
||||
checkdeps:
|
||||
@@ -8,6 +10,7 @@ checkdeps:
|
||||
checkgopath:
|
||||
@echo "Checking if project is at ${GOPATH}"
|
||||
@for mcpath in $(echo ${GOPATH} | sed 's/:/\n/g'); do if [ ! -d ${mcpath}/src/github.com/minio/mc ]; then echo "Project not found in ${mcpath}, please follow instructions provided at https://github.com/minio/minio/blob/master/CONTRIBUTING.md#setup-your-minio-github-repository" && exit 1; fi done
|
||||
@echo "BUILD_LDFLAGS: ${BUILD_LDFLAGS}"
|
||||
|
||||
getdeps: checkdeps checkgopath
|
||||
@go get github.com/golang/lint/golint && echo "Installed golint:"
|
||||
@@ -36,45 +39,47 @@ lint:
|
||||
|
||||
cyclo:
|
||||
@echo "Running $@:"
|
||||
@GO15VENDOREXPERIMENT=1 gocyclo -over 30 .
|
||||
@GO15VENDOREXPERIMENT=1 gocyclo -over 40 *.go
|
||||
@GO15VENDOREXPERIMENT=1 gocyclo -over 40 pkg
|
||||
|
||||
deadcode:
|
||||
@echo "Running $@:"
|
||||
@GO15VENDOREXPERIMENT=1 deadcode
|
||||
|
||||
build: getdeps verifiers
|
||||
build: verifiers
|
||||
@echo "Installing mc:"
|
||||
|
||||
test: getdeps verifiers
|
||||
test: verifiers
|
||||
@echo "Running all testing:"
|
||||
@GO15VENDOREXPERIMENT=1 go test $(GOFLAGS) ./
|
||||
@GO15VENDOREXPERIMENT=1 go test $(GOFLAGS) github.com/minio/mc/pkg...
|
||||
|
||||
gomake-all: build
|
||||
@GO15VENDOREXPERIMENT=1 go install github.com/minio/mc
|
||||
@GO15VENDOREXPERIMENT=1 go build --ldflags $(BUILD_LDFLAGS) -o $(GOPATH)/bin/mc
|
||||
@mkdir -p $(HOME)/.mc
|
||||
|
||||
release: genversion
|
||||
@echo "Installing mc with new version.go:"
|
||||
@GO15VENDOREXPERIMENT=1 go install github.com/minio/mc
|
||||
@mkdir -p $(HOME)/.mc
|
||||
|
||||
genversion:
|
||||
@echo "Generating a new version.go:"
|
||||
@GO15VENDOREXPERIMENT=1 go run buildscripts/genversion.go
|
||||
|
||||
coverage:
|
||||
@GO15VENDOREXPERIMENT=1 go test -race -coverprofile=cover.out ./
|
||||
@go tool cover -html=cover.out && echo "Visit your browser"
|
||||
|
||||
pkg-remove:
|
||||
@GO15VENDOREXPERIMENT=1 govendor remove $(PKG)
|
||||
|
||||
pkg-add:
|
||||
@GO15VENDOREXPERIMENT=1 govendor add $(PKG)
|
||||
|
||||
pkg-update:
|
||||
@GO15VENDOREXPERIMENT=1 govendor update $(PKG)
|
||||
|
||||
pkg-remove:
|
||||
@GO15VENDOREXPERIMENT=1 govendor remove $(PKG)
|
||||
|
||||
install: gomake-all
|
||||
|
||||
all-tests: test
|
||||
# TODO disable them for now.
|
||||
#@./tests/test-minio.sh
|
||||
|
||||
release:
|
||||
@./release.sh
|
||||
|
||||
clean:
|
||||
@rm -fv cover.out
|
||||
@rm -fv mc
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Minio Client (mc) [](https://gitter.im/minio/minio?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
||||
|
||||
``mc`` provides minimal tools to work with Amazon S3 compatible cloud storage and filesystems. It has features to resume partial downloads, progress bar, parallel copy and network reconnect. ``mc`` is written in golang and released under [Apache license v2](./LICENSE).
|
||||
``mc`` provides minimal tools to work with Amazon S3 compatible cloud storage and filesystems. It has features like resumable uploads/downloads, progress bar, parallel copy. ``mc`` is written in golang and released under [Apache license v2](./LICENSE).
|
||||
|
||||
## Commands
|
||||
|
||||
@@ -9,14 +9,16 @@
|
||||
ls List files and folders.
|
||||
mb Make a bucket or folder.
|
||||
cat Display contents of a file.
|
||||
cp Copy files and folders from many sources to a single destination.
|
||||
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.
|
||||
session Manage sessions for cp and mirror.
|
||||
share Share documents via URL.
|
||||
diff Compute differences between two files or folders.
|
||||
access Set access permissions.
|
||||
config Modify, add, remove alias from default configuration file [~/.mc/config.json].
|
||||
update Check for new software updates.
|
||||
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.
|
||||
```
|
||||
|
||||
@@ -24,51 +26,78 @@
|
||||
|
||||
#### GNU/Linux
|
||||
|
||||
Download ``mc`` from https://dl.minio.io:9000/updates/2015/Sept/linux-amd64/mc
|
||||
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
|
||||
|
||||
~~~
|
||||
$ wget https://dl.minio.io:9000/updates/2015/Sept/linux-amd64/mc
|
||||
$ chmod +x mc
|
||||
$ ./mc
|
||||
$ ./mc --help
|
||||
~~~
|
||||
|
||||
#### OS X
|
||||
|
||||
Download ``mc`` from https://dl.minio.io:9000/updates/2015/Sept/darwin-amd64/mc
|
||||
Download ``mc`` from https://dl.minio.io/client/mc/release/darwin-amd64/mc
|
||||
|
||||
~~~
|
||||
$ curl https://dl.minio.io:9000/updates/2015/Sept/darwin-amd64/mc > mc
|
||||
$ chmod +x mc
|
||||
$ ./mc
|
||||
$ chmod 755 mc
|
||||
$ ./mc --help
|
||||
~~~
|
||||
|
||||
#### Windows
|
||||
#### Microsoft Windows
|
||||
|
||||
Download ``mc`` from https://dl.minio.io:9000/updates/2015/Sept/windows-amd64/mc.exe
|
||||
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
|
||||
C:\Users\Username\Downloads> mc.exe --help
|
||||
~~~
|
||||
|
||||
#### Source
|
||||
<blockquote>
|
||||
NOTE: Source installation is intended for only developers and advanced users. ‘mc update’ continuous delivery mechanism is not supported for ‘go get’ based binary builds. Please download official releases from https://minio.io/#mc.
|
||||
</blockquote>
|
||||
|
||||
If you do not have a working Golang environment, please follow [Install Golang](./INSTALLGO.md).
|
||||
|
||||
```sh
|
||||
$ go get github.com/minio/mc
|
||||
$ GO15VENDOREXPERIMENT=1 go get -u github.com/minio/mc
|
||||
```
|
||||
|
||||
## Public Minio Server
|
||||
|
||||
Minio 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 in memory mode with auto expiry of objects in about an hour. No account signup is required, which means S3 compatible tools and applications can access this service without access and secret keys.
|
||||
|
||||
## How to use mc?
|
||||
|
||||
[](https://asciinema.org/a/21576?async)
|
||||
Minio cloud storage server is hosted at ``https://play.minio.io:9000`` for public use. This service is primarily intended for developers and users to familiarize themselves with Amazon S3 compatible cloud storage. Minio runs with filesystem backend with auto-expiry for objects in about 24 hours. No account signup is required, which means S3 compatible tools and applications can access this service without access and secret keys.
|
||||
|
||||
## Configuring mc for Amazon S3
|
||||
|
||||
Update AccessKeyID and SecretAccessKey fields in your ``~/.mc/config.json`` configuration file by following [AWS Credentials Guide](http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSGettingStartedGuide/AWSCredentials.html).
|
||||
Get your AccessKeyID and SecretAccessKey by following [AWS Credentials Guide](http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSGettingStartedGuide/AWSCredentials.html).
|
||||
|
||||
Once you have them update your ``~/.mc/config.json`` configuration file.
|
||||
```
|
||||
$ mc config host add <ALIAS> <YOUR-S3-ENDPOINT> <YOUR-ACCESS-KEY> <YOUR-SECRET-KEY> S3v4
|
||||
```
|
||||
|
||||
Example
|
||||
```
|
||||
$ mc config host add mys3 https://s3.amazonaws.com BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12
|
||||
```
|
||||
|
||||
NOTE: ``S3v4`` is default if not specified.
|
||||
|
||||
## Configure mc for Google Cloud Storage
|
||||
|
||||
Get your AccessKeyID and SecretAccessKey by following [Google Credentials Guide](https://cloud.google.com/storage/docs/migrating?hl=en#keys).
|
||||
|
||||
Once you have them update your ``~/.mc/config.json`` configuration file.
|
||||
```
|
||||
$ mc config host add <ALIAS> https://storage.googleapis.com <YOUR-ACCESS-KEY> <YOUR-SECRET-KEY> S3v2
|
||||
```
|
||||
|
||||
NOTE: Google Cloud Storage only supports Legacy Signature Version ``2``, so you have to pick - ``S3v2``
|
||||
|
||||
## Contribute to Minio Client
|
||||
Please follow Minio [Contributor's Guide](./CONTRIBUTING.md)
|
||||
|
||||
+104
-79
@@ -23,86 +23,102 @@ import (
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
"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: "Set or get access permissions.",
|
||||
Usage: "Manage bucket access permissions.",
|
||||
Action: mainAccess,
|
||||
Flags: append(accessFlags, globalFlags...),
|
||||
CustomHelpTemplate: `Name:
|
||||
mc {{.Name}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
mc {{.Name}} set PERMISSION TARGET [TARGET ...]
|
||||
mc {{.Name}} get TARGET [TARGET ...]
|
||||
mc {{.Name}} [FLAGS] set PERMISSION TARGET [TARGET...]
|
||||
mc {{.Name}} [FLAGS] get TARGET [TARGET...]
|
||||
|
||||
PERMISSION = private | readonly | public | authorized {{if .Description}}
|
||||
|
||||
DESCRIPTION:
|
||||
{{.Description}}{{end}}
|
||||
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 https://s3.amazonaws.com/burningman2011
|
||||
$ mc {{.Name}} set private s3/burningman2011
|
||||
|
||||
2. Set bucket to "public" on Amazon S3 cloud storage.
|
||||
$ mc {{.Name}} set public https://s3.amazonaws.com/shared
|
||||
$ 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 https://s3.amazonaws.com/shared-authenticated
|
||||
$ mc {{.Name}} set authorized s3/shared-authenticated
|
||||
|
||||
4. Get bucket permissions.
|
||||
$ mc {{.Name}} get https://s3.amazonaws.com/shared
|
||||
$ 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 {
|
||||
// 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 bucketPerms `json:"permission"`
|
||||
Perms accessPerms `json:"permission"`
|
||||
}
|
||||
|
||||
// String colorized access message
|
||||
func (s AccessMessage) String() string {
|
||||
// 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+"’")
|
||||
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)+"’")
|
||||
return console.Colorize("Access",
|
||||
"Access permission for ‘"+s.Bucket+"’"+" is ‘"+string(s.Perms)+"’")
|
||||
}
|
||||
// nothing to print
|
||||
return ""
|
||||
}
|
||||
|
||||
// JSON jsonified access message
|
||||
func (s AccessMessage) JSON() string {
|
||||
accessJSONBytes, err := json.Marshal(s)
|
||||
fatalIf(probe.NewError(err), "Unable to marshal into JSON.")
|
||||
// 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() || ctx.Args().First() == "help" {
|
||||
cli.ShowCommandHelpAndExit(ctx, "access", 1) // last argument is exit code
|
||||
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
|
||||
cli.ShowCommandHelpAndExit(ctx, "access", 1) // last argument is exit code.
|
||||
}
|
||||
switch ctx.Args().Get(0) {
|
||||
switch ctx.Args().First() {
|
||||
case "set":
|
||||
if len(ctx.Args().Tail()) < 2 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "access", 1) // last argument is exit code
|
||||
cli.ShowCommandHelpAndExit(ctx, "access", 1) // last argument is exit code.
|
||||
}
|
||||
perms := bucketPerms(ctx.Args().Tail().Get(0))
|
||||
if !perms.isValidBucketPERM() {
|
||||
perms := accessPerms(ctx.Args().Tail().Get(0))
|
||||
if !perms.isValidAccessPERM() {
|
||||
fatalIf(errDummy().Trace(),
|
||||
"Unrecognized permission ‘"+perms.String()+"’. Allowed values are [private, public, readonly].")
|
||||
"Unrecognized permission ‘"+perms.String()+"’. Allowed values are [private, public, readonly, authorized].")
|
||||
}
|
||||
for _, arg := range ctx.Args().Tail().Tail() {
|
||||
if strings.TrimSpace(arg) == "" {
|
||||
@@ -111,70 +127,79 @@ func checkAccessSyntax(ctx *cli.Context) {
|
||||
}
|
||||
case "get":
|
||||
if len(ctx.Args().Tail()) < 1 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "access", 1) // last argument is exit code
|
||||
cli.ShowCommandHelpAndExit(ctx, "access", 1) // last argument is exit code.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func mainAccess(ctx *cli.Context) {
|
||||
checkAccessSyntax(ctx)
|
||||
|
||||
console.SetCustomTheme(map[string]*color.Color{
|
||||
"Access": color.New(color.FgGreen, color.Bold),
|
||||
})
|
||||
|
||||
config := mustGetMcConfig()
|
||||
|
||||
switch ctx.Args().Get(0) {
|
||||
case "set":
|
||||
perms := bucketPerms(ctx.Args().Tail().Get(0))
|
||||
for _, arg := range ctx.Args().Tail().Tail() {
|
||||
targetURL := getAliasURL(arg, config.Aliases)
|
||||
|
||||
fatalIf(doSetAccess(targetURL, perms).Trace(targetURL, string(perms)), "Unable to set access permission ‘"+string(perms)+"’ for ‘"+targetURL+"’.")
|
||||
|
||||
Prints("%s\n", AccessMessage{
|
||||
Operation: "set",
|
||||
Status: "success",
|
||||
Bucket: targetURL,
|
||||
Perms: perms,
|
||||
})
|
||||
}
|
||||
case "get":
|
||||
for _, arg := range ctx.Args().Tail() {
|
||||
targetURL := getAliasURL(arg, config.Aliases)
|
||||
perms, err := doGetAccess(targetURL)
|
||||
fatalIf(err.Trace(targetURL), "Unable to get access permission for ‘"+targetURL+"’.")
|
||||
|
||||
Prints("%s\n", AccessMessage{
|
||||
Operation: "get",
|
||||
Status: "success",
|
||||
Bucket: targetURL,
|
||||
Perms: perms,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func doSetAccess(targetURL string, targetPERMS bucketPerms) *probe.Error {
|
||||
clnt, err := target2Client(targetURL)
|
||||
// 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.SetBucketACL(targetPERMS.String()); err != nil {
|
||||
if err = clnt.SetBucketAccess(targetPERMS.String()); err != nil {
|
||||
return err.Trace(targetURL, targetPERMS.String())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func doGetAccess(targetURL string) (perms bucketPerms, err *probe.Error) {
|
||||
clnt, err := target2Client(targetURL)
|
||||
// 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.GetBucketACL()
|
||||
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,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+30
-29
@@ -16,8 +16,8 @@
|
||||
|
||||
package main
|
||||
|
||||
// isValidBucketPERM - is provided acl string supported
|
||||
func (b bucketPerms) isValidBucketPERM() bool {
|
||||
// isValidAccessPERM - is provided access perm string supported.
|
||||
func (b accessPerms) isValidAccessPERM() bool {
|
||||
switch true {
|
||||
case b.isPrivate():
|
||||
fallthrough
|
||||
@@ -32,19 +32,19 @@ func (b bucketPerms) isValidBucketPERM() bool {
|
||||
}
|
||||
}
|
||||
|
||||
// bucketPerms - bucket level access control
|
||||
type bucketPerms string
|
||||
// accessPerms - access level.
|
||||
type accessPerms string
|
||||
|
||||
// different types of ACL's currently supported for buckets
|
||||
// different types of Access perm's currently supported by accesss command.
|
||||
const (
|
||||
bucketPrivate = bucketPerms("private")
|
||||
bucketReadOnly = bucketPerms("readonly")
|
||||
bucketPublic = bucketPerms("public")
|
||||
bucketAuthorized = bucketPerms("authorized")
|
||||
accessPrivate = accessPerms("private")
|
||||
accessReadOnly = accessPerms("readonly")
|
||||
accessPublic = accessPerms("public")
|
||||
accessAuthorized = accessPerms("authorized")
|
||||
)
|
||||
|
||||
func (b bucketPerms) String() string {
|
||||
if !b.isValidBucketPERM() {
|
||||
func (b accessPerms) String() string {
|
||||
if !b.isValidAccessPERM() {
|
||||
return string(b)
|
||||
}
|
||||
if b.isReadOnly() {
|
||||
@@ -59,37 +59,38 @@ func (b bucketPerms) String() string {
|
||||
return "private"
|
||||
}
|
||||
|
||||
func aclToPerms(acl string) bucketPerms {
|
||||
// convert acl's to access perms
|
||||
func aclToPerms(acl string) accessPerms {
|
||||
switch acl {
|
||||
case "private":
|
||||
return bucketPerms("private")
|
||||
return accessPerms("private")
|
||||
case "public-read":
|
||||
return bucketPerms("readonly")
|
||||
return accessPerms("readonly")
|
||||
case "public-read-write":
|
||||
return bucketPerms("public")
|
||||
return accessPerms("public")
|
||||
case "authenticated-read":
|
||||
return bucketPerms("authorized")
|
||||
return accessPerms("authorized")
|
||||
default:
|
||||
return bucketPerms(acl)
|
||||
return accessPerms(acl)
|
||||
}
|
||||
}
|
||||
|
||||
// IsPrivate - is acl Private
|
||||
func (b bucketPerms) isPrivate() bool {
|
||||
return b == bucketPrivate
|
||||
// isPrivate - is acl Private.
|
||||
func (b accessPerms) isPrivate() bool {
|
||||
return b == accessPrivate
|
||||
}
|
||||
|
||||
// IsPublicRead - is acl PublicRead
|
||||
func (b bucketPerms) isReadOnly() bool {
|
||||
return b == bucketReadOnly
|
||||
// isPublicRead - is acl PublicRead.
|
||||
func (b accessPerms) isReadOnly() bool {
|
||||
return b == accessReadOnly
|
||||
}
|
||||
|
||||
// IsPublicReadWrite - is acl PublicReadWrite
|
||||
func (b bucketPerms) isPublic() bool {
|
||||
return b == bucketPublic
|
||||
// isPublicReadWrite - is acl PublicReadWrite.
|
||||
func (b accessPerms) isPublic() bool {
|
||||
return b == accessPublic
|
||||
}
|
||||
|
||||
// IsAuthorized - is acl AuthorizedRead
|
||||
func (b bucketPerms) isAuthorized() bool {
|
||||
return b == bucketAuthorized
|
||||
// isAuthorized - is acl AuthorizedRead.
|
||||
func (b accessPerms) isAuthorized() bool {
|
||||
return b == accessAuthorized
|
||||
}
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
/*
|
||||
* Minio Client (C) 2014, 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
|
||||
// accounter keeps tabs of ongoing data transfer information.
|
||||
type accounter struct {
|
||||
current int64
|
||||
|
||||
Total int64
|
||||
startTime time.Time
|
||||
startValue int64
|
||||
refreshRate time.Duration
|
||||
currentValue int64
|
||||
finishOnce sync.Once
|
||||
isFinished chan struct{}
|
||||
}
|
||||
|
||||
// Instantiate a new accounter.
|
||||
func newAccounter(total int64) *accounter {
|
||||
acct := &accounter{
|
||||
Total: total,
|
||||
startTime: time.Now(),
|
||||
startValue: 0,
|
||||
refreshRate: time.Millisecond * 200,
|
||||
isFinished: make(chan struct{}),
|
||||
currentValue: -1,
|
||||
}
|
||||
go acct.writer()
|
||||
return acct
|
||||
}
|
||||
|
||||
// write calculate the final speed.
|
||||
func (a *accounter) write(current int64) float64 {
|
||||
fromStart := time.Now().Sub(a.startTime)
|
||||
currentFromStart := current - a.startValue
|
||||
if currentFromStart > 0 {
|
||||
speed := float64(currentFromStart) / (float64(fromStart) / float64(time.Second))
|
||||
return speed
|
||||
}
|
||||
return 0.0
|
||||
}
|
||||
|
||||
// writer update new accounting data for a specified refreshRate.
|
||||
func (a *accounter) writer() {
|
||||
a.Update()
|
||||
for {
|
||||
select {
|
||||
case <-a.isFinished:
|
||||
return
|
||||
case <-time.After(a.refreshRate):
|
||||
a.Update()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// accountStat cantainer for current stats captured.
|
||||
type accountStat struct {
|
||||
Total int64
|
||||
Transferred int64
|
||||
Speed float64
|
||||
}
|
||||
|
||||
// Stat provides current stats captured.
|
||||
func (a *accounter) Stat() accountStat {
|
||||
var acntStat accountStat
|
||||
a.finishOnce.Do(func() {
|
||||
close(a.isFinished)
|
||||
acntStat.Total = a.Total
|
||||
acntStat.Transferred = a.current
|
||||
acntStat.Speed = a.write(atomic.LoadInt64(&a.current))
|
||||
})
|
||||
return acntStat
|
||||
}
|
||||
|
||||
// Update update with new values loaded atomically.
|
||||
func (a *accounter) Update() {
|
||||
c := atomic.LoadInt64(&a.current)
|
||||
if c != a.currentValue {
|
||||
a.write(c)
|
||||
a.currentValue = c
|
||||
}
|
||||
}
|
||||
|
||||
// Set sets the current value atomically.
|
||||
func (a *accounter) Set(n int64) *accounter {
|
||||
atomic.StoreInt64(&a.current, n)
|
||||
return a
|
||||
}
|
||||
|
||||
// Add add to current value atomically.
|
||||
func (a *accounter) Add(n int64) int64 {
|
||||
return atomic.AddInt64(&a.current, n)
|
||||
}
|
||||
|
||||
// Read implements Reader which internally updates current value.
|
||||
func (a *accounter) Read(p []byte) (n int, err error) {
|
||||
n = len(p)
|
||||
a.Add(int64(n))
|
||||
return
|
||||
}
|
||||
@@ -1,55 +0,0 @@
|
||||
/*
|
||||
* Minio Client (C) 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// validAliasName regex validation.
|
||||
var validAliasName = regexp.MustCompile("^[a-zA-Z][a-zA-Z0-9-]+$")
|
||||
|
||||
// Check if it is an aliased URL.
|
||||
func isValidAliasName(aliasName string) bool {
|
||||
return validAliasName.MatchString(aliasName)
|
||||
}
|
||||
|
||||
// getAliasURL expands aliased (name/path) to full URL, used by url-parser.
|
||||
func getAliasURL(aliasedURL string, aliases map[string]string) string {
|
||||
for aliasName, aliasValue := range aliases {
|
||||
if strings.HasPrefix(aliasedURL, aliasName) {
|
||||
// Match found. Expand it.
|
||||
splits := strings.SplitN(aliasedURL, aliasName, 2)
|
||||
if len(splits) == 1 {
|
||||
return aliasedURL // Not an aliased URL. Return as is.
|
||||
}
|
||||
if len(splits[0]) == 0 && len(splits[1]) == 0 {
|
||||
return aliasValue // exact match.
|
||||
}
|
||||
_, sepLen := utf8.DecodeRuneInString(splits[1])
|
||||
if sepLen == 1 && !os.IsPathSeparator(splits[1][0]) && splits[1] != recursiveSeparator {
|
||||
return aliasedURL // Do not expand for whole strings with alias prefix.
|
||||
}
|
||||
// Matched, but path needs to be joined.
|
||||
return urlJoinPath(aliasValue, splits[1])
|
||||
}
|
||||
}
|
||||
return aliasedURL // No matching alias found. Return as is.
|
||||
}
|
||||
@@ -138,14 +138,13 @@ func (h objectAPIHandler) putHandler(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
length, err := strconv.Atoi(r.Header.Get("Content-Length"))
|
||||
if err != nil {
|
||||
length, e := strconv.Atoi(r.Header.Get("Content-Length"))
|
||||
if e != nil {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
var buffer bytes.Buffer
|
||||
_, err = io.CopyN(&buffer, r.Body, int64(length))
|
||||
if err != nil {
|
||||
if _, e = io.CopyN(&buffer, r.Body, int64(length)); e != nil {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
+10
-8
@@ -14,29 +14,31 @@ environment:
|
||||
# scripts that run after cloning repository
|
||||
install:
|
||||
- set PATH=%GOPATH%\bin;c:\go\bin;%PATH%
|
||||
- set GOVENDOR15EXPERIMENT=1
|
||||
- rmdir c:\go /s /q
|
||||
- appveyor DownloadFile https://storage.googleapis.com/golang/go1.5.1.windows-amd64.msi
|
||||
- msiexec /i go1.5.1.windows-amd64.msi /q
|
||||
- go version
|
||||
- go env
|
||||
- go get -u github.com/golang/lint/golint
|
||||
- go get -u golang.org/x/tools/cmd/vet
|
||||
- go get -u github.com/fzipp/gocyclo
|
||||
- go get -u github.com/remyoudompheng/go-misc/deadcode
|
||||
- go get -u github.com/alecthomas/gometalinter
|
||||
- go get -u github.com/client9/misspell
|
||||
|
||||
# to run your custom scripts instead of automatic MSBuild
|
||||
build_script:
|
||||
- set GOVENDOR15EXPERIMENT=1
|
||||
- go tool vet -all ./pkg
|
||||
- go tool vet -shadow=true ./pkg
|
||||
- gofmt -s -l pkg
|
||||
- golint .
|
||||
- golint github.com/minio/mc/pkg...
|
||||
- gocyclo -over 30 .
|
||||
- gometalinter --disable-all --linter='misspell:misspell ./*.go:PATH:LINE:COL:MESSAGE' --enable=misspell ./...
|
||||
- gocyclo -over 40 pkg
|
||||
- deadcode
|
||||
- go test
|
||||
- go test -race
|
||||
- go test -race .
|
||||
- go test -race github.com/minio/mc/pkg...
|
||||
- go run buildscripts/gen-ldflags.go > temp.txt
|
||||
- set /p LDFLAGS=<temp.txt
|
||||
- go build -ldflags="%LDFLAGS%" -o %GOPATH%\bin\mc.exe
|
||||
- mc version
|
||||
|
||||
# to disable automatic tests
|
||||
test: off
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
/*
|
||||
* Minio Client (C) 2014, 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
var (
|
||||
// mcVersion - version time.RFC3339.
|
||||
mcVersion = "UNOFFICIAL.GOGET"
|
||||
// mcReleaseTag - release tag in TAG.%Y-%m-%dT%H-%M-%SZ.
|
||||
mcReleaseTag = "UNOFFICIAL.GOGET"
|
||||
// mcCommitID - latest commit id.
|
||||
mcCommitID = "UNOFFICIAL.GOGET"
|
||||
// mcShortCommitID - first 12 characters from mcCommitID.
|
||||
mcShortCommitID = mcCommitID[:12]
|
||||
)
|
||||
@@ -20,9 +20,6 @@ _init() {
|
||||
shopt -s extglob
|
||||
|
||||
## Minimum required versions for build dependencies
|
||||
GCC_VERSION="4.0"
|
||||
CLANG_VERSION="7.0.0"
|
||||
YASM_VERSION="1.2.0"
|
||||
GIT_VERSION="1.0"
|
||||
GO_VERSION="1.5.1"
|
||||
OSX_VERSION="10.8"
|
||||
@@ -160,6 +157,9 @@ is_supported_arch() {
|
||||
"x86_64")
|
||||
supported=1
|
||||
;;
|
||||
"arm"*)
|
||||
supported=1
|
||||
;;
|
||||
*)
|
||||
supported=0
|
||||
;;
|
||||
@@ -173,31 +173,13 @@ is_supported_arch() {
|
||||
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})"
|
||||
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})"
|
||||
MISSING="${MISSING} git(>=${GIT_VERSION})"
|
||||
fi
|
||||
|
||||
case ${UNAME%% *} in
|
||||
"Linux")
|
||||
check_version "$(env gcc --version 2>/dev/null | sed 's/^.* \([0-9.]*\).*$/\1/' | head -1)" "${GCC_VERSION}"
|
||||
if [ $? -ge 2 ]; then
|
||||
MISSING="${MISSING} build-essential(${GCC_VERSION})"
|
||||
fi
|
||||
;;
|
||||
"Darwin")
|
||||
check_version "$(env gcc --version 2>/dev/null | awk '{print $4}' | head -1)" "${CLANG_VERSION}"
|
||||
if [ $? -ge 2 ]; then
|
||||
MISSING="${MISSING} xcode-cli(${CLANG_VERSION})"
|
||||
fi
|
||||
;;
|
||||
"*")
|
||||
;;
|
||||
esac
|
||||
|
||||
}
|
||||
|
||||
main() {
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
// +build ignore
|
||||
|
||||
/*
|
||||
* Mc Client (C) 2014, 2015 Mc, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
func genLDFlags(version string) string {
|
||||
var ldflagsStr string
|
||||
ldflagsStr = "-X main.mcVersion=" + version + " "
|
||||
ldflagsStr = ldflagsStr + "-X main.mcReleaseTag=" + releaseTag(version) + " "
|
||||
ldflagsStr = ldflagsStr + "-X main.mcCommitID=" + commitID() + " "
|
||||
ldflagsStr = ldflagsStr + "-X main.mcShortCommitID=" + commitID()[:12]
|
||||
return ldflagsStr
|
||||
}
|
||||
|
||||
// genReleaseTag prints release tag to the console for easy git tagging.
|
||||
func releaseTag(version string) string {
|
||||
relPrefix := "UNOFFICIAL"
|
||||
if prefix := os.Getenv("MC_RELEASE"); prefix != "" {
|
||||
relPrefix = prefix
|
||||
}
|
||||
|
||||
relTag := strings.Replace(version, " ", "-", -1)
|
||||
relTag = strings.Replace(relTag, ":", "-", -1)
|
||||
relTag = strings.Replace(relTag, ",", "", -1)
|
||||
return relPrefix + "." + relTag
|
||||
}
|
||||
|
||||
// commitID returns the abbreviated commit-id hash of the last commit.
|
||||
func commitID() string {
|
||||
// git log --format="%h" -n1
|
||||
var (
|
||||
commit []byte
|
||||
e error
|
||||
)
|
||||
cmdName := "git"
|
||||
cmdArgs := []string{"log", "--format=%H", "-n1"}
|
||||
if commit, e = exec.Command(cmdName, cmdArgs...).Output(); e != nil {
|
||||
fmt.Fprintln(os.Stderr, "Error generating git commit-id: ", e)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
return strings.TrimSpace(string(commit))
|
||||
}
|
||||
|
||||
func main() {
|
||||
fmt.Println(genLDFlags(time.Now().UTC().Format(time.RFC3339)))
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
// +build ignore
|
||||
|
||||
/*
|
||||
* Minio Client (C) 2014, 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"text/template"
|
||||
"time"
|
||||
)
|
||||
|
||||
var versionTemplate = `// -------- DO NOT EDIT --------
|
||||
// This file is autogenerated by genversion.go during the release process.
|
||||
|
||||
package main
|
||||
|
||||
const mcVersion = {{if .Version}}"{{.Version}}"{{else}}""{{end}}
|
||||
const mcReleaseTag = {{if .ReleaseTag}}"{{.ReleaseTag}}"{{else}}""{{end}}
|
||||
`
|
||||
|
||||
// genVersion generates ‘version.go’.
|
||||
func genVersion(version string) {
|
||||
t := template.Must(template.New("version").Parse(versionTemplate))
|
||||
versionFile, err := os.OpenFile("version.go", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
|
||||
if err != nil {
|
||||
fmt.Printf("genversion: Unable to generate ‘version.go’. Error: %s.\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
defer versionFile.Close()
|
||||
|
||||
err = t.Execute(versionFile, struct {
|
||||
Version string
|
||||
ReleaseTag string
|
||||
}{version, genReleaseTag(version)})
|
||||
|
||||
if err != nil {
|
||||
fmt.Printf("genversion: Unable to generate ‘version.go’. Error: %s.\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
// genReleaseTag prints release tag to the console for easy git tagging.
|
||||
func genReleaseTag(version string) string {
|
||||
relTag := strings.Replace(version, " ", "-", -1)
|
||||
relTag = strings.Replace(relTag, ":", "-", -1)
|
||||
relTag = strings.Replace(relTag, ",", "", -1)
|
||||
return "RELEASE." + relTag
|
||||
}
|
||||
|
||||
func main() {
|
||||
// Version is in HTTP TimeFormat.
|
||||
version := time.Now().UTC().Format(http.TimeFormat)
|
||||
|
||||
// generate ‘version.go’ file.
|
||||
genVersion(version)
|
||||
|
||||
fmt.Println("Version: \"" + version + "\"")
|
||||
fmt.Println("Release-Tag: " + genReleaseTag(version))
|
||||
}
|
||||
+87
-62
@@ -17,13 +17,24 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
"syscall"
|
||||
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
"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.
|
||||
@@ -31,97 +42,111 @@ 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}} SOURCE [SOURCE...]
|
||||
mc {{.Name}} [FLAGS] SOURCE [SOURCE...]
|
||||
|
||||
FLAGS:
|
||||
{{range .Flags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Concantenate an object from Amazon S3 cloud storage to mplayer standard input.
|
||||
$ mc {{.Name}} https://s3.amazonaws.com/ferenginar/klingon_opera_aktuh_maylotah.ogg | mplayer -
|
||||
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 a file from local filesystem to standard output.
|
||||
$ mc {{.Name}} khitomer-accords.txt
|
||||
2. Concantenate contents of file1.txt and stdin to standard output.
|
||||
$ mc {{.Name}} file1.txt - > file.txt
|
||||
|
||||
3. Concantenate multiple files from local filesystem to standard output.
|
||||
$ mc {{.Name}} *.txt > newfile.txt
|
||||
3. Concantenate multiple files to one.
|
||||
$ mc {{.Name}} part.* > complete.img
|
||||
|
||||
4. Concatenate a non english file name from Amazon S3 cloud storage.
|
||||
$ mc {{.Name}} s3/andoria/本語 > /tmp/本語
|
||||
|
||||
5. Behave like operating system tool ‘cat’, used for shell aliases.
|
||||
$ echo "Hello, World!" | mc --mimic {{.Name}}
|
||||
Hello, World!
|
||||
|
||||
6. Concantenate an object with space characters from Amazon S3 cloud storage.
|
||||
$ mc {{.Name}} 's3/miniocloud/Readme First.txt' | head -1
|
||||
`,
|
||||
}
|
||||
|
||||
// checkCatSyntax performs command-line input validation for cat command.
|
||||
func checkCatSyntax(ctx *cli.Context) {
|
||||
if (!ctx.Args().Present() && !globalMimicFlag) || ctx.Args().First() == "help" {
|
||||
cli.ShowCommandHelpAndExit(ctx, "cat", 1) // last argument is exit code
|
||||
args := ctx.Args()
|
||||
if !args.Present() {
|
||||
args = []string{"-"}
|
||||
}
|
||||
for _, arg := range ctx.Args() {
|
||||
if strings.TrimSpace(arg) == "" {
|
||||
fatalIf(errInvalidArgument().Trace(), "Unable to validate empty argument.")
|
||||
for _, arg := range args {
|
||||
if strings.HasPrefix(arg, "-") && len(arg) > 1 {
|
||||
fatalIf(probe.NewError(errors.New("")), fmt.Sprintf("Unknown flag ‘%s’ passed.", arg))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func mainCat(ctx *cli.Context) {
|
||||
checkCatSyntax(ctx)
|
||||
|
||||
stdinMode := false
|
||||
if globalMimicFlag && !ctx.Args().Present() {
|
||||
stdinMode = true
|
||||
}
|
||||
|
||||
// handle std input data
|
||||
if stdinMode {
|
||||
fatalIf(catOut(os.Stdin).Trace(), "Unable to read from standard input.")
|
||||
return
|
||||
}
|
||||
|
||||
// Convert arguments to URLs: expand alias, fix format...
|
||||
for _, arg := range ctx.Args() {
|
||||
fatalIf(catURL(arg).Trace(arg), "Unable to read from ‘"+arg+"’.")
|
||||
}
|
||||
}
|
||||
|
||||
// catURL displays contents of a URL to stdout.
|
||||
func catURL(sourceURL string) *probe.Error {
|
||||
config := mustGetMcConfig()
|
||||
URL := getAliasURL(sourceURL, config.Aliases)
|
||||
|
||||
sourceClnt, err := source2Client(URL)
|
||||
if err != nil {
|
||||
return err.Trace(URL)
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
// Ignore size, since os.Stat() would not return proper size all the time for local filesystem for example /proc files.
|
||||
reader, _, err := sourceClnt.GetObject(0, 0)
|
||||
if err != nil {
|
||||
return err.Trace(URL)
|
||||
}
|
||||
defer reader.Close()
|
||||
|
||||
return catOut(reader).Trace(URL)
|
||||
return catOut(reader).Trace(sourceURL)
|
||||
}
|
||||
|
||||
// catOut reads from reader stream and writes to stdout.
|
||||
func catOut(r io.Reader) *probe.Error {
|
||||
// read till EOF
|
||||
if _, err := io.Copy(os.Stdout, r); err != nil {
|
||||
switch e := err.(type) {
|
||||
// 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(err)
|
||||
return probe.NewError(e)
|
||||
default:
|
||||
return probe.NewError(err)
|
||||
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+"’.")
|
||||
}
|
||||
}
|
||||
|
||||
-72
@@ -1,72 +0,0 @@
|
||||
/*
|
||||
* Minio Client (C) 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
. "gopkg.in/check.v1"
|
||||
)
|
||||
|
||||
func (s *TestSuite) TestCat(c *C) {
|
||||
/// filesystem
|
||||
root, err := ioutil.TempDir(os.TempDir(), "cmd-")
|
||||
c.Assert(err, IsNil)
|
||||
defer os.RemoveAll(root)
|
||||
|
||||
objectPath := filepath.Join(root, "object1")
|
||||
objectPathServer := server.URL + "/bucket/object1"
|
||||
data := "hello"
|
||||
dataLen := len(data)
|
||||
|
||||
var perr *probe.Error
|
||||
perr = putTarget(objectPath, int64(dataLen), bytes.NewReader([]byte(data)))
|
||||
c.Assert(perr, IsNil)
|
||||
perr = putTarget(objectPathServer, int64(dataLen), bytes.NewReader([]byte(data)))
|
||||
c.Assert(perr, IsNil)
|
||||
|
||||
var sourceURLs []string
|
||||
sourceURLs = append(sourceURLs, objectPath)
|
||||
sourceURLs = append(sourceURLs, objectPathServer)
|
||||
for _, sourceURL := range sourceURLs {
|
||||
c.Assert(catURL(sourceURL), IsNil)
|
||||
}
|
||||
|
||||
objectPath = filepath.Join(root, "object2")
|
||||
c.Assert(catURL(objectPath), Not(IsNil))
|
||||
}
|
||||
|
||||
func (s *TestSuite) TestCatContext(c *C) {
|
||||
err := app.Run([]string{os.Args[0], "cat", server.URL + "/bucket/object1"})
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(console.IsExited, Equals, false)
|
||||
|
||||
// reset back
|
||||
console.IsExited = false
|
||||
|
||||
err = app.Run([]string{os.Args[0], "cat", server.URL + "/invalid"})
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(console.IsExited, Equals, true)
|
||||
|
||||
// reset back
|
||||
console.IsExited = false
|
||||
}
|
||||
+78
-143
@@ -19,22 +19,25 @@ package main
|
||||
import (
|
||||
"io"
|
||||
"os"
|
||||
"regexp"
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/minio/mc/pkg/client"
|
||||
"github.com/minio/mc/pkg/client/fs"
|
||||
"github.com/minio/mc/pkg/client/s3v2"
|
||||
"github.com/minio/mc/pkg/client/s3v4"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
"github.com/minio/mc/pkg/client/s3"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
)
|
||||
|
||||
// Check if the target URL represents folder. It may or may not exist yet.
|
||||
func isTargetURLDir(targetURL string) bool {
|
||||
targetURLParse := client.NewURL(targetURL)
|
||||
_, targetContent, perr := url2Stat(targetURL)
|
||||
if perr != nil {
|
||||
_, targetContent, err := url2Stat(targetURL)
|
||||
if err != nil {
|
||||
_, aliasedTargetURL, _ := mustExpandAlias(targetURL)
|
||||
if aliasedTargetURL == targetURL {
|
||||
return false
|
||||
}
|
||||
if targetURLParse.Path == string(targetURLParse.Separator) && targetURLParse.Scheme != "" {
|
||||
return false
|
||||
}
|
||||
@@ -49,167 +52,99 @@ func isTargetURLDir(targetURL string) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// getSource gets a reader from URL<
|
||||
func getSource(sourceURL string) (reader io.ReadCloser, length int64, err *probe.Error) {
|
||||
sourceClnt, err := source2Client(sourceURL)
|
||||
// getSource gets a reader from URL.
|
||||
func getSourceStream(urlStr string) (reader io.Reader, err *probe.Error) {
|
||||
alias, urlStrFull, _, err := expandAlias(urlStr)
|
||||
if err != nil {
|
||||
return nil, 0, err.Trace()
|
||||
return nil, err.Trace(urlStr)
|
||||
}
|
||||
return sourceClnt.GetObject(0, 0)
|
||||
return getSourceStreamFromAlias(alias, urlStrFull)
|
||||
}
|
||||
|
||||
// putTarget writes to URL from reader.
|
||||
func putTarget(targetURL string, length int64, reader io.Reader) *probe.Error {
|
||||
targetClnt, err := target2Client(targetURL)
|
||||
// getSourceStreamFromAlias gets a reader from URL.
|
||||
func getSourceStreamFromAlias(alias string, urlStr string) (reader io.Reader, err *probe.Error) {
|
||||
sourceClnt, err := newClientFromAlias(alias, urlStr)
|
||||
if err != nil {
|
||||
return err.Trace(targetURL)
|
||||
return nil, err.Trace(alias, urlStr)
|
||||
}
|
||||
err = targetClnt.PutObject(length, reader)
|
||||
reader, err = sourceClnt.Get()
|
||||
if err != nil {
|
||||
return err.Trace(targetURL)
|
||||
return nil, err.Trace(alias, urlStr)
|
||||
}
|
||||
return nil
|
||||
return reader, nil
|
||||
}
|
||||
|
||||
// putTargets writes to URL from reader.
|
||||
func putTargets(targetURLs []string, length int64, reader io.Reader) *probe.Error {
|
||||
var tgtReaders []io.ReadCloser
|
||||
var tgtWriters []io.WriteCloser
|
||||
var tgtClients []client.Client
|
||||
|
||||
for _, targetURL := range targetURLs {
|
||||
tgtClient, err := target2Client(targetURL)
|
||||
if err != nil {
|
||||
return err.Trace(targetURL)
|
||||
}
|
||||
tgtClients = append(tgtClients, tgtClient)
|
||||
tgtReader, tgtWriter := io.Pipe()
|
||||
tgtReaders = append(tgtReaders, tgtReader)
|
||||
tgtWriters = append(tgtWriters, tgtWriter)
|
||||
// putTargetStreamFromAlias writes to URL from Reader.
|
||||
func putTargetStreamFromAlias(alias string, urlStr string, reader io.Reader, size int64, progress io.Reader) (int64, *probe.Error) {
|
||||
targetClnt, err := newClientFromAlias(alias, urlStr)
|
||||
if err != nil {
|
||||
return 0, err.Trace(alias, urlStr)
|
||||
}
|
||||
|
||||
go func() {
|
||||
var writers []io.Writer
|
||||
for _, tgtWriter := range tgtWriters {
|
||||
defer tgtWriter.Close()
|
||||
writers = append(writers, io.Writer(tgtWriter))
|
||||
}
|
||||
multiTgtWriter := io.MultiWriter(writers...)
|
||||
io.CopyN(multiTgtWriter, reader, length)
|
||||
}()
|
||||
|
||||
var wg sync.WaitGroup
|
||||
errorCh := make(chan *probe.Error, len(tgtClients))
|
||||
|
||||
func() { // Parallel putObject
|
||||
defer close(errorCh) // Each routine gets to return one err status.
|
||||
for i := range tgtClients {
|
||||
wg.Add(1)
|
||||
// make local copy for go routine
|
||||
tgtClient := tgtClients[i]
|
||||
tgtReader := tgtReaders[i]
|
||||
|
||||
go func(targetClient client.Client, reader io.ReadCloser, errorCh chan<- *probe.Error) {
|
||||
defer wg.Done()
|
||||
err := targetClient.PutObject(length, reader)
|
||||
if err != nil {
|
||||
defer reader.Close()
|
||||
errorCh <- err.Trace()
|
||||
return
|
||||
}
|
||||
errorCh <- nil
|
||||
}(tgtClient, tgtReader, errorCh)
|
||||
}
|
||||
wg.Wait()
|
||||
}()
|
||||
for err := range errorCh {
|
||||
if err != nil { // Return on first error encounter.
|
||||
return err.Trace()
|
||||
}
|
||||
contentType := guessURLContentType(urlStr)
|
||||
var n int64
|
||||
n, err = targetClnt.Put(reader, size, contentType, progress)
|
||||
if err != nil {
|
||||
return n, err.Trace(alias, urlStr)
|
||||
}
|
||||
return nil // success.
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// getNewClient gives a new client interface
|
||||
func getNewClient(urlStr string, auth hostConfig) (client.Client, *probe.Error) {
|
||||
url := client.NewURL(urlStr)
|
||||
switch url.Type {
|
||||
case client.Object: // Minio and S3 compatible cloud storage
|
||||
s3Config := new(client.Config)
|
||||
s3Config.AccessKeyID = func() string {
|
||||
if auth.AccessKeyID == globalAccessKeyID {
|
||||
return ""
|
||||
}
|
||||
return auth.AccessKeyID
|
||||
}()
|
||||
s3Config.SecretAccessKey = func() string {
|
||||
if auth.SecretAccessKey == globalSecretAccessKey {
|
||||
return ""
|
||||
}
|
||||
return auth.SecretAccessKey
|
||||
}()
|
||||
s3Config.AppName = "Minio"
|
||||
s3Config.AppVersion = globalMCVersion
|
||||
s3Config.AppComments = []string{os.Args[0], runtime.GOOS, runtime.GOARCH}
|
||||
s3Config.HostURL = urlStr
|
||||
s3Config.Debug = globalDebugFlag
|
||||
// putTargetStream writes to URL from reader. If length=-1, read until EOF.
|
||||
func putTargetStream(urlStr string, reader io.Reader, size int64) (int64, *probe.Error) {
|
||||
alias, urlStrFull, _, err := expandAlias(urlStr)
|
||||
if err != nil {
|
||||
return 0, err.Trace(alias, urlStr)
|
||||
}
|
||||
return putTargetStreamFromAlias(alias, urlStrFull, reader, size, nil)
|
||||
}
|
||||
|
||||
var s3Client client.Client
|
||||
var err *probe.Error
|
||||
if auth.API == "S3v2" {
|
||||
s3Client, err = s3v2.New(s3Config)
|
||||
} else {
|
||||
s3Client, err = s3v4.New(s3Config)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err.Trace()
|
||||
}
|
||||
return s3Client, nil
|
||||
case client.Filesystem:
|
||||
// newClientFromAlias gives a new client interface for matching
|
||||
// alias entry in the mc config file. If no matching host config entry
|
||||
// is found, fs client is returned.
|
||||
func newClientFromAlias(alias string, urlStr string) (client.Client, *probe.Error) {
|
||||
hostCfg := mustGetHostConfig(alias)
|
||||
if hostCfg == nil {
|
||||
// No matching host config. So we treat it like a
|
||||
// filesystem.
|
||||
fsClient, err := fs.New(urlStr)
|
||||
if err != nil {
|
||||
return nil, err.Trace()
|
||||
return nil, err.Trace(alias, urlStr)
|
||||
}
|
||||
return fsClient, nil
|
||||
}
|
||||
return nil, errInitClient(urlStr).Trace()
|
||||
|
||||
// We have a valid alias and hostConfig. We populate the
|
||||
// credentials from the match found in the config file.
|
||||
s3Config := new(client.Config)
|
||||
s3Config.AccessKey = hostCfg.AccessKey
|
||||
s3Config.SecretKey = hostCfg.SecretKey
|
||||
s3Config.Signature = hostCfg.API
|
||||
s3Config.AppName = "mc"
|
||||
s3Config.AppVersion = mcVersion
|
||||
s3Config.AppComments = []string{os.Args[0], runtime.GOOS, runtime.GOARCH}
|
||||
s3Config.HostURL = urlStr
|
||||
s3Config.Debug = globalDebug
|
||||
|
||||
s3Client, err := s3.New(s3Config)
|
||||
if err != nil {
|
||||
return nil, err.Trace(alias, urlStr)
|
||||
}
|
||||
return s3Client, nil
|
||||
}
|
||||
|
||||
func url2Client(url string) (client.Client, *probe.Error) {
|
||||
urlconfig, err := getHostConfig(url)
|
||||
if err != nil {
|
||||
return nil, err.Trace(url)
|
||||
}
|
||||
client, err := getNewClient(url, urlconfig)
|
||||
if err != nil {
|
||||
return nil, err.Trace(url)
|
||||
}
|
||||
return client, nil
|
||||
}
|
||||
// urlRgx - verify if aliased url is real URL.
|
||||
var urlRgx = regexp.MustCompile("^https?://")
|
||||
|
||||
// source2Client returns client and hostconfig objects from the source URL.
|
||||
func source2Client(sourceURL string) (client.Client, *probe.Error) {
|
||||
sourceClient, err := url2Client(sourceURL)
|
||||
// newClient gives a new client interface
|
||||
func newClient(aliasedURL string) (client.Client, *probe.Error) {
|
||||
alias, urlStrFull, hostCfg, err := expandAlias(aliasedURL)
|
||||
if err != nil {
|
||||
return nil, err.Trace(sourceURL)
|
||||
return nil, err.Trace(aliasedURL)
|
||||
}
|
||||
return sourceClient, nil
|
||||
}
|
||||
|
||||
// target2Client returns client and hostconfig objects from the target URL.
|
||||
func target2Client(targetURL string) (client.Client, *probe.Error) {
|
||||
targetClient, err := url2Client(targetURL)
|
||||
if err != nil {
|
||||
return nil, err.Trace(targetURL)
|
||||
// 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 targetClient, nil
|
||||
}
|
||||
|
||||
// bucketExists returns error
|
||||
func bucketExists(URL string) *probe.Error {
|
||||
_, _, err := url2Stat(URL)
|
||||
if err != nil {
|
||||
return err.Trace()
|
||||
}
|
||||
return nil
|
||||
return newClientFromAlias(alias, urlStrFull)
|
||||
}
|
||||
|
||||
@@ -1,81 +0,0 @@
|
||||
/*
|
||||
* Minio Client (C) 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
. "gopkg.in/check.v1"
|
||||
)
|
||||
|
||||
func (s *TestSuite) TestCommonMethods(c *C) {
|
||||
/// filesystem
|
||||
root, err := ioutil.TempDir(os.TempDir(), "cmd-")
|
||||
c.Assert(err, IsNil)
|
||||
defer os.RemoveAll(root)
|
||||
|
||||
objectPath := filepath.Join(root, "object1")
|
||||
|
||||
c.Assert(isTargetURLDir(root), Equals, true)
|
||||
c.Assert(isTargetURLDir(objectPath), Equals, false)
|
||||
|
||||
objectPathServer := server.URL + "/bucket/object1"
|
||||
data := "hello"
|
||||
dataLen := len(data)
|
||||
perr := putTarget(objectPath, int64(dataLen), bytes.NewReader([]byte(data)))
|
||||
c.Assert(perr, IsNil)
|
||||
perr = putTarget(objectPathServer, int64(dataLen), bytes.NewReader([]byte(data)))
|
||||
c.Assert(perr, IsNil)
|
||||
|
||||
c.Assert(isTargetURLDir(objectPathServer), Equals, false)
|
||||
c.Assert(isTargetURLDir(server.URL+"/bucket"), Equals, true)
|
||||
|
||||
reader, size, perr := getSource(objectPathServer)
|
||||
c.Assert(perr, IsNil)
|
||||
c.Assert(size, Not(Equals), 0)
|
||||
var results bytes.Buffer
|
||||
_, err = io.CopyN(&results, reader, int64(size))
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert([]byte(data), DeepEquals, results.Bytes())
|
||||
|
||||
_, content, perr := url2Stat(objectPathServer)
|
||||
c.Assert(perr, IsNil)
|
||||
c.Assert(content.Name, Equals, "object1")
|
||||
c.Assert(content.Type.IsRegular(), Equals, true)
|
||||
|
||||
_, _, perr = getSource(objectPathServer + "invalid")
|
||||
c.Assert(perr, Not(IsNil))
|
||||
|
||||
_, _, perr = url2Stat(objectPath + "invalid")
|
||||
c.Assert(perr, Not(IsNil))
|
||||
|
||||
_, perr = source2Client(objectPathServer)
|
||||
c.Assert(perr, IsNil)
|
||||
|
||||
_, perr = target2Client(objectPathServer)
|
||||
c.Assert(perr, IsNil)
|
||||
|
||||
_, perr = source2Client("http://test.minio.io" + "/bucket/fail")
|
||||
c.Assert(perr, Not(IsNil))
|
||||
|
||||
_, perr = target2Client("http://test.minio.io" + "/bucket/fail")
|
||||
c.Assert(perr, Not(IsNil))
|
||||
}
|
||||
@@ -1,228 +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
|
||||
|
||||
// listAliases - list alias
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
"github.com/minio/minio/pkg/quick"
|
||||
)
|
||||
|
||||
var configAliasCmd = cli.Command{
|
||||
Name: "alias",
|
||||
Usage: "List, modify and remove aliases in configuration file.",
|
||||
Action: mainConfigAlias,
|
||||
CustomHelpTemplate: `NAME:
|
||||
mc config {{.Name}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
mc config {{.Name}} OPERATION [ARGS...]
|
||||
|
||||
OPERATION = add | list | remove
|
||||
|
||||
EXAMPLES:
|
||||
1. Add aliases for a URL
|
||||
$ mc config {{.Name}} add mcloud https://s3.amazonaws.com/miniocloud
|
||||
$ mc ls mcloud
|
||||
$ mc cp /bin/true mcloud/true
|
||||
|
||||
2. List all aliased URLs.
|
||||
$ mc config {{.Name}} list
|
||||
|
||||
3. Remove an alias
|
||||
$ mc config {{.Name}} remove zek
|
||||
|
||||
`,
|
||||
}
|
||||
|
||||
// AliasMessage container for content message structure
|
||||
type AliasMessage struct {
|
||||
op string
|
||||
Alias string `json:"alias"`
|
||||
URL string `json:"url,omitempty"`
|
||||
}
|
||||
|
||||
// String colorized alias message
|
||||
func (a AliasMessage) String() string {
|
||||
if a.op == "list" {
|
||||
message := console.Colorize("Alias", fmt.Sprintf("[%s] <- ", a.Alias))
|
||||
message += console.Colorize("URL", fmt.Sprintf("%s", a.URL))
|
||||
return message
|
||||
}
|
||||
if a.op == "remove" {
|
||||
return console.Colorize("AliasMessage", "Removed alias ‘"+a.Alias+"’ successfully.")
|
||||
}
|
||||
if a.op == "add" {
|
||||
return console.Colorize("AliasMessage", "Added alias ‘"+a.Alias+"’ successfully.")
|
||||
}
|
||||
// should never come here
|
||||
return ""
|
||||
}
|
||||
|
||||
// JSON jsonified alias message
|
||||
func (a AliasMessage) JSON() string {
|
||||
jsonMessageBytes, e := json.Marshal(a)
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(jsonMessageBytes)
|
||||
}
|
||||
|
||||
func checkConfigAliasSyntax(ctx *cli.Context) {
|
||||
// show help if nothing is set
|
||||
if !ctx.Args().Present() || ctx.Args().First() == "help" {
|
||||
cli.ShowCommandHelpAndExit(ctx, "alias", 1) // last argument is exit code
|
||||
}
|
||||
if strings.TrimSpace(ctx.Args().First()) == "" {
|
||||
cli.ShowCommandHelpAndExit(ctx, "alias", 1) // last argument is exit code
|
||||
}
|
||||
if len(ctx.Args().Tail()) > 2 {
|
||||
fatalIf(errDummy().Trace(), "Incorrect number of arguments to alias command")
|
||||
}
|
||||
switch strings.TrimSpace(ctx.Args().Get(0)) {
|
||||
case "add":
|
||||
if len(ctx.Args().Tail()) != 2 {
|
||||
fatalIf(errInvalidArgument().Trace(), "Incorrect number of arguments for add alias command.")
|
||||
}
|
||||
case "remove":
|
||||
if len(ctx.Args().Tail()) != 1 {
|
||||
fatalIf(errInvalidArgument().Trace(), "Incorrect number of arguments for remove alias command.")
|
||||
}
|
||||
case "list":
|
||||
default:
|
||||
cli.ShowCommandHelpAndExit(ctx, "alias", 1) // last argument is exit code
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
func mainConfigAlias(ctx *cli.Context) {
|
||||
checkConfigAliasSyntax(ctx)
|
||||
|
||||
// set new custom coloring
|
||||
console.SetCustomTheme(map[string]*color.Color{
|
||||
"Alias": color.New(color.FgCyan, color.Bold),
|
||||
"AliasMessage": color.New(color.FgGreen, color.Bold),
|
||||
"URL": color.New(color.FgWhite, color.Bold),
|
||||
})
|
||||
|
||||
arg := ctx.Args().First()
|
||||
tailArgs := ctx.Args().Tail()
|
||||
|
||||
switch strings.TrimSpace(arg) {
|
||||
case "add":
|
||||
addAlias(tailArgs.Get(0), tailArgs.Get(1))
|
||||
case "remove":
|
||||
removeAlias(tailArgs.Get(0))
|
||||
case "list":
|
||||
listAliases()
|
||||
}
|
||||
}
|
||||
|
||||
func listAliases() {
|
||||
config, err := newConfig()
|
||||
fatalIf(err.Trace(globalMCConfigVersion), "Failed to initialize ‘quick’ configuration data structure.")
|
||||
|
||||
configPath := mustGetMcConfigPath()
|
||||
err = config.Load(configPath)
|
||||
fatalIf(err.Trace(configPath), "Unable to load config path")
|
||||
|
||||
// convert interface{} back to its original struct
|
||||
newConf := config.Data().(*configV5)
|
||||
for k, v := range newConf.Aliases {
|
||||
Prints("%s\n", AliasMessage{
|
||||
op: "list",
|
||||
Alias: k,
|
||||
URL: v,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// removeAlias - remove alias
|
||||
func removeAlias(alias string) {
|
||||
if strings.TrimSpace(alias) == "" {
|
||||
fatalIf(errDummy().Trace(), "Alias or URL cannot be empty.")
|
||||
}
|
||||
config, err := newConfig()
|
||||
fatalIf(err.Trace(), "Failed to initialize ‘quick’ configuration data structure.")
|
||||
|
||||
configPath := mustGetMcConfigPath()
|
||||
err = config.Load(configPath)
|
||||
fatalIf(err.Trace(configPath), "Unable to load config path")
|
||||
if !isValidAliasName(alias) {
|
||||
fatalIf(errDummy().Trace(), fmt.Sprintf("Alias name ‘%s’ is invalid, valid examples are: mybucket, Area51, Grand-Nagus", alias))
|
||||
}
|
||||
|
||||
// convert interface{} back to its original struct
|
||||
newConf := config.Data().(*configV5)
|
||||
if _, ok := newConf.Aliases[alias]; !ok {
|
||||
fatalIf(errDummy().Trace(), fmt.Sprintf("Alias ‘%s’ does not exist.", alias))
|
||||
}
|
||||
delete(newConf.Aliases, alias)
|
||||
|
||||
newConfig, err := quick.New(newConf)
|
||||
fatalIf(err.Trace(globalMCConfigVersion), "Failed to initialize ‘quick’ configuration data structure.")
|
||||
err = writeConfig(newConfig)
|
||||
fatalIf(err.Trace(alias), "Unable to save alias ‘"+alias+"’.")
|
||||
|
||||
Prints("%s\n", AliasMessage{
|
||||
op: "remove",
|
||||
Alias: alias,
|
||||
})
|
||||
}
|
||||
|
||||
// addAlias - add new aliases
|
||||
func addAlias(alias, url string) {
|
||||
if alias == "" || url == "" {
|
||||
fatalIf(errDummy().Trace(), "Alias or URL cannot be empty.")
|
||||
}
|
||||
config, err := newConfig()
|
||||
fatalIf(err.Trace(globalMCConfigVersion), "Failed to initialize ‘quick’ configuration data structure.")
|
||||
|
||||
err = config.Load(mustGetMcConfigPath())
|
||||
fatalIf(err.Trace(), "Unable to load config path")
|
||||
|
||||
url = strings.TrimSuffix(url, "/")
|
||||
if !strings.HasPrefix(url, "http") {
|
||||
fatalIf(errDummy().Trace(), fmt.Sprintf("Invalid alias URL ‘%s’. Valid examples are: http://s3.amazonaws.com, https://yourbucket.example.com.", url))
|
||||
}
|
||||
if !isValidAliasName(alias) {
|
||||
fatalIf(errDummy().Trace(), fmt.Sprintf("Alias name ‘%s’ is invalid, valid examples are: mybucket, Area51, Grand-Nagus", alias))
|
||||
}
|
||||
// convert interface{} back to its original struct
|
||||
newConf := config.Data().(*configV5)
|
||||
if oldURL, ok := newConf.Aliases[alias]; ok {
|
||||
fatalIf(errDummy().Trace(), fmt.Sprintf("Alias ‘%s’ already exists for ‘%s’.", alias, oldURL))
|
||||
}
|
||||
newConf.Aliases[alias] = url
|
||||
newConfig, err := quick.New(newConf)
|
||||
fatalIf(err.Trace(globalMCConfigVersion), "Failed to initialize ‘quick’ configuration data structure.")
|
||||
|
||||
err = writeConfig(newConfig)
|
||||
fatalIf(err.Trace(alias, url), "Unable to save alias ‘"+alias+"’.")
|
||||
|
||||
Prints("%s\n", AliasMessage{
|
||||
op: "add",
|
||||
Alias: alias,
|
||||
URL: url,
|
||||
})
|
||||
}
|
||||
+242
@@ -0,0 +1,242 @@
|
||||
/*
|
||||
* Minio Client (C) 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/minio/mc/pkg/client"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio-xl/pkg/quick"
|
||||
)
|
||||
|
||||
func fixConfig() {
|
||||
// Fix config V3
|
||||
fixConfigV3()
|
||||
// Fix config V6
|
||||
fixConfigV6()
|
||||
// Fix config V6 for hosts
|
||||
fixConfigV6ForHosts()
|
||||
|
||||
/* No more fixing job. Here after we bump the version for changes always.
|
||||
*/
|
||||
}
|
||||
|
||||
/////////////////// Broken Config V3 ///////////////////
|
||||
type brokenHostConfigV3 struct {
|
||||
AccessKeyID string
|
||||
SecretAccessKey string
|
||||
}
|
||||
|
||||
type brokenConfigV3 struct {
|
||||
Version string
|
||||
ACL string
|
||||
Access string
|
||||
Aliases map[string]string
|
||||
Hosts map[string]brokenHostConfigV3
|
||||
}
|
||||
|
||||
// newConfigV3 - get new config broken version 3.
|
||||
func newBrokenConfigV3() *brokenConfigV3 {
|
||||
conf := new(brokenConfigV3)
|
||||
conf.Version = "3"
|
||||
conf.Aliases = make(map[string]string)
|
||||
conf.Hosts = make(map[string]brokenHostConfigV3)
|
||||
return conf
|
||||
}
|
||||
|
||||
// Fix config version ‘3’. Some v3 config files are written without
|
||||
// proper hostConfig JSON tags. They may also contain unused ACL and
|
||||
// Access fields. Rewrite the hostConfig with proper fields using JSON
|
||||
// tags and drop the unused (ACL, Access) fields.
|
||||
func fixConfigV3() {
|
||||
if !isMcConfigExists() {
|
||||
return
|
||||
}
|
||||
brokenCfgV3 := newBrokenConfigV3()
|
||||
brokenMcCfgV3, err := quick.Load(mustGetMcConfigPath(), brokenCfgV3)
|
||||
fatalIf(err.Trace(), "Unable to load config.")
|
||||
|
||||
if brokenMcCfgV3.Version() != "3" {
|
||||
return
|
||||
}
|
||||
|
||||
cfgV3 := newConfigV3()
|
||||
isMutated := false
|
||||
for k, v := range brokenMcCfgV3.Data().(*brokenConfigV3).Aliases {
|
||||
cfgV3.Aliases[k] = v
|
||||
}
|
||||
|
||||
for host, brokenHostCfgV3 := range brokenMcCfgV3.Data().(*brokenConfigV3).Hosts {
|
||||
|
||||
// If any of these fields contains any real value anytime,
|
||||
// it means we have already fixed the broken configuration.
|
||||
// We don't have to regenerate again.
|
||||
if brokenHostCfgV3.AccessKeyID != "" && brokenHostCfgV3.SecretAccessKey != "" {
|
||||
isMutated = true
|
||||
}
|
||||
|
||||
// Use the correct hostConfig with JSON tags in it.
|
||||
cfgV3.Hosts[host] = hostConfigV3{
|
||||
AccessKeyID: brokenHostCfgV3.AccessKeyID,
|
||||
SecretAccessKey: brokenHostCfgV3.SecretAccessKey,
|
||||
}
|
||||
}
|
||||
|
||||
// We blindly drop ACL and Access fields from the broken config v3.
|
||||
|
||||
if isMutated {
|
||||
mcNewConfigV3, err := quick.New(cfgV3)
|
||||
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘3’.")
|
||||
|
||||
err = mcNewConfigV3.Save(mustGetMcConfigPath())
|
||||
fatalIf(err.Trace(), "Unable to save config version ‘3’.")
|
||||
|
||||
console.Infof("Successfully fixed %s broken config for version ‘3’.\n", mustGetMcConfigPath())
|
||||
}
|
||||
}
|
||||
|
||||
// If the host key does not have http(s), fix it.
|
||||
func fixConfigV6ForHosts() {
|
||||
if !isMcConfigExists() {
|
||||
return
|
||||
}
|
||||
|
||||
brokenMcCfgV6, err := quick.Load(mustGetMcConfigPath(), newConfigV6())
|
||||
fatalIf(err.Trace(), "Unable to load config.")
|
||||
|
||||
if brokenMcCfgV6.Version() != "6" {
|
||||
return
|
||||
}
|
||||
|
||||
newCfgV6 := newConfigV6()
|
||||
isMutated := false
|
||||
|
||||
// Copy aliases.
|
||||
for k, v := range brokenMcCfgV6.Data().(*configV6).Aliases {
|
||||
newCfgV6.Aliases[k] = v
|
||||
}
|
||||
|
||||
url := new(client.URL)
|
||||
// Copy hosts.
|
||||
for host, hostCfgV6 := range brokenMcCfgV6.Data().(*configV6).Hosts {
|
||||
// Already fixed - Copy and move on.
|
||||
if strings.HasPrefix(host, "https") || strings.HasPrefix(host, "http") {
|
||||
newCfgV6.Hosts[host] = hostCfgV6
|
||||
continue
|
||||
}
|
||||
|
||||
// If host entry does not contain "http(s)", introduce a new entry and delete the old one.
|
||||
if host == "s3.amazonaws.com" || host == "storage.googleapis.com" ||
|
||||
host == "localhost:9000" || host == "127.0.0.1:9000" ||
|
||||
host == "play.minio.io:9000" || host == "dl.minio.io:9000" {
|
||||
console.Infoln("Found broken host entries, replacing " + host + " with https://" + host + ".")
|
||||
url.Host = host
|
||||
url.Scheme = "https"
|
||||
url.SchemeSeparator = "://"
|
||||
newCfgV6.Hosts[url.String()] = hostCfgV6
|
||||
isMutated = true
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
if isMutated {
|
||||
// Save the new config back to the disk.
|
||||
mcCfgV6, err := quick.New(newCfgV6)
|
||||
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘v6’.")
|
||||
|
||||
err = mcCfgV6.Save(mustGetMcConfigPath())
|
||||
fatalIf(err.Trace(), "Unable to save config version ‘v6’.")
|
||||
}
|
||||
}
|
||||
|
||||
// fixConfigV6 - fix all the unnecessary glob URLs present in existing config version 6.
|
||||
func fixConfigV6() {
|
||||
if !isMcConfigExists() {
|
||||
return
|
||||
}
|
||||
config, err := quick.New(newConfigV6())
|
||||
fatalIf(err.Trace(), "Unable to initialize config.")
|
||||
|
||||
err = config.Load(mustGetMcConfigPath())
|
||||
fatalIf(err.Trace(mustGetMcConfigPath()), "Unable to load config.")
|
||||
|
||||
if config.Data().(*configV6).Version != "6" {
|
||||
return
|
||||
}
|
||||
|
||||
newConfig := new(configV6)
|
||||
isMutated := false
|
||||
newConfig.Aliases = make(map[string]string)
|
||||
newConfig.Hosts = make(map[string]hostConfigV6)
|
||||
newConfig.Version = "6"
|
||||
newConfig.Aliases = config.Data().(*configV6).Aliases
|
||||
for host, hostCfg := range config.Data().(*configV6).Hosts {
|
||||
if strings.Contains(host, "*") {
|
||||
fatalIf(err.Trace(),
|
||||
fmt.Sprintf("Glob style ‘*’ pattern matching is no longer supported. Please fix ‘%s’ entry manually.", host))
|
||||
}
|
||||
if strings.Contains(host, "*s3*") || strings.Contains(host, "*.s3*") {
|
||||
console.Infoln("Found glob url, replacing " + host + " with s3.amazonaws.com")
|
||||
newConfig.Hosts["s3.amazonaws.com"] = hostCfg
|
||||
isMutated = true
|
||||
continue
|
||||
}
|
||||
if strings.Contains(host, "s3*") {
|
||||
console.Infoln("Found glob url, replacing " + host + " with s3.amazonaws.com")
|
||||
newConfig.Hosts["s3.amazonaws.com"] = hostCfg
|
||||
isMutated = true
|
||||
continue
|
||||
}
|
||||
if strings.Contains(host, "*amazonaws.com") || strings.Contains(host, "*.amazonaws.com") {
|
||||
console.Infoln("Found glob url, replacing " + host + " with s3.amazonaws.com")
|
||||
newConfig.Hosts["s3.amazonaws.com"] = hostCfg
|
||||
isMutated = true
|
||||
continue
|
||||
}
|
||||
if strings.Contains(host, "*storage.googleapis.com") {
|
||||
console.Infoln("Found glob url, replacing " + host + " with storage.googleapis.com")
|
||||
newConfig.Hosts["storage.googleapis.com"] = hostCfg
|
||||
isMutated = true
|
||||
continue
|
||||
}
|
||||
if strings.Contains(host, "localhost:*") {
|
||||
console.Infoln("Found glob url, replacing " + host + " with localhost:9000")
|
||||
newConfig.Hosts["localhost:9000"] = hostCfg
|
||||
isMutated = true
|
||||
continue
|
||||
}
|
||||
if strings.Contains(host, "127.0.0.1:*") {
|
||||
console.Infoln("Found glob url, replacing " + host + " with 127.0.0.1:9000")
|
||||
newConfig.Hosts["127.0.0.1:9000"] = hostCfg
|
||||
isMutated = true
|
||||
continue
|
||||
}
|
||||
// Other entries are hopefully OK. Copy them blindly.
|
||||
newConfig.Hosts[host] = hostCfg
|
||||
}
|
||||
|
||||
if isMutated {
|
||||
newConf, err := quick.New(newConfig)
|
||||
fatalIf(err.Trace(), "Unable to initialize newly fixed config.")
|
||||
|
||||
err = newConf.Save(mustGetMcConfigPath())
|
||||
fatalIf(err.Trace(mustGetMcConfigPath()), "Unable to save newly fixed config path.")
|
||||
console.Infof("Successfully fixed %s broken config for version ‘6’.\n", mustGetMcConfigPath())
|
||||
}
|
||||
}
|
||||
+213
-185
@@ -1,257 +1,285 @@
|
||||
/*
|
||||
* Minio Client (C) 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
"github.com/minio/minio/pkg/quick"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
)
|
||||
|
||||
var (
|
||||
configHostFlags = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "help, h",
|
||||
Usage: "Help of config host",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
var configHostCmd = cli.Command{
|
||||
Name: "host",
|
||||
Usage: "List, modify and remove hosts in configuration file.",
|
||||
Flags: append(configHostFlags, globalFlags...),
|
||||
Action: mainConfigHost,
|
||||
CustomHelpTemplate: `NAME:
|
||||
mc config {{.Name}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
mc config {{.Name}} OPERATION [ARGS...]
|
||||
mc config {{.Name}} OPERATION
|
||||
|
||||
OPERATION = add | list | remove
|
||||
OPERATION:
|
||||
add ALIAS URL ACCESS-KEY SECRET-KEY [API]
|
||||
remove ALIAS
|
||||
list
|
||||
|
||||
FLAGS:
|
||||
{{range .Flags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Add host configuration for a URL, using default signature V4. For security reasons turn off bash history
|
||||
1. Add Amazon S3 storage service under "myphotos" alias. For security reasons turn off bash history momentarily.
|
||||
$ set +o history
|
||||
$ mc config {{.Name}} add s3.amazonaws.com BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12
|
||||
$ mc config {{.Name}} add myphotos https://s3.amazonaws.com BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12
|
||||
$ set -o history
|
||||
|
||||
2. Add host configuration for a URL, using s3 api v2. For security reasons turn off bash history
|
||||
$ set +o history
|
||||
$ mc config {{.Name}} add s3.amazonaws.com BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 S3v2
|
||||
$ set -o history
|
||||
2. Add Google Cloud Storage service under "goodisk" alias.
|
||||
$ mc config {{.Name}} add goodisk https://storage.googleapis.com BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 S3v2
|
||||
|
||||
3. List all hosts.
|
||||
$ mc config {{.Name}} list
|
||||
|
||||
4. Remove host config.
|
||||
$ mc config {{.Name}} remove s3.amazonaws.com
|
||||
|
||||
4. Remove "goodisk" config.
|
||||
$ mc config {{.Name}} remove goodisk
|
||||
`,
|
||||
}
|
||||
|
||||
// HostMessage container for content message structure
|
||||
type HostMessage struct {
|
||||
op string
|
||||
Host string `json:"host"`
|
||||
AccessKeyID string `json:"accessKeyId,omitempty"`
|
||||
SecretAccessKey string `json:"secretAccessKey,omitempty"`
|
||||
API string `json:"api,omitempty"`
|
||||
// hostMessage container for content message structure
|
||||
type hostMessage struct {
|
||||
op string
|
||||
Status string `json:"status"`
|
||||
Alias string `json:"alias"`
|
||||
URL string `json:"URL"`
|
||||
AccessKey string `json:"accessKey,omitempty"`
|
||||
SecretKey string `json:"secretKey,omitempty"`
|
||||
API string `json:"api,omitempty"`
|
||||
}
|
||||
|
||||
// String colorized host message
|
||||
func (a HostMessage) String() string {
|
||||
if a.op == "list" {
|
||||
message := console.Colorize("Host", fmt.Sprintf("[%s] ", a.Host))
|
||||
if a.AccessKeyID != "" || a.SecretAccessKey != "" {
|
||||
message += console.Colorize("AccessKeyID", fmt.Sprintf("<- %s,", a.AccessKeyID))
|
||||
message += console.Colorize("SecretAccessKey", fmt.Sprintf(" %s,", a.SecretAccessKey))
|
||||
message += console.Colorize("API", fmt.Sprintf(" %s", a.API))
|
||||
func (h hostMessage) String() string {
|
||||
switch h.op {
|
||||
case "list":
|
||||
message := console.Colorize("Alias", fmt.Sprintf("%s: ", h.Alias))
|
||||
message += console.Colorize("URL", fmt.Sprintf("%s", h.URL))
|
||||
if h.AccessKey != "" || h.SecretKey != "" {
|
||||
message += " | " + console.Colorize("AccessKey", fmt.Sprintf("<- %s,", h.AccessKey))
|
||||
message += " | " + console.Colorize("SecretKey", fmt.Sprintf(" %s,", h.SecretKey))
|
||||
message += " | " + console.Colorize("API", fmt.Sprintf(" %s", h.API))
|
||||
}
|
||||
return message
|
||||
case "remove":
|
||||
return console.Colorize("HostMessage", "Removed ‘"+h.Alias+"’ successfully.")
|
||||
case "add":
|
||||
return console.Colorize("HostMessage", "Added ‘"+h.Alias+"’ successfully.")
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
if a.op == "remove" {
|
||||
return console.Colorize("HostMessage", "Removed host ‘"+a.Host+"’ successfully.")
|
||||
}
|
||||
if a.op == "add" {
|
||||
return console.Colorize("HostMessage", "Added host ‘"+a.Host+"’ successfully.")
|
||||
}
|
||||
// should never reach here
|
||||
return ""
|
||||
}
|
||||
|
||||
// JSON jsonified host message
|
||||
func (a HostMessage) JSON() string {
|
||||
jsonMessageBytes, e := json.Marshal(a)
|
||||
func (h hostMessage) JSON() string {
|
||||
h.Status = "success"
|
||||
jsonMessageBytes, e := json.Marshal(h)
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(jsonMessageBytes)
|
||||
}
|
||||
|
||||
// Validate command-line input args.
|
||||
func checkConfigHostSyntax(ctx *cli.Context) {
|
||||
// show help if nothing is set
|
||||
if !ctx.Args().Present() || ctx.Args().First() == "help" {
|
||||
if !ctx.Args().Present() {
|
||||
cli.ShowCommandHelpAndExit(ctx, "host", 1) // last argument is exit code
|
||||
}
|
||||
if strings.TrimSpace(ctx.Args().First()) == "" {
|
||||
cli.ShowCommandHelpAndExit(ctx, "host", 1) // last argument is exit code
|
||||
}
|
||||
if len(ctx.Args().Tail()) > 4 {
|
||||
fatalIf(errDummy().Trace(), "Incorrect number of arguments to host command")
|
||||
}
|
||||
|
||||
switch strings.TrimSpace(ctx.Args().First()) {
|
||||
case "add":
|
||||
if len(ctx.Args().Tail()) < 3 || len(ctx.Args().Tail()) > 4 {
|
||||
fatalIf(errInvalidArgument().Trace(), "Incorrect number of arguments for add host command.")
|
||||
}
|
||||
checkConfigHostAddSyntax(ctx)
|
||||
case "remove":
|
||||
if len(ctx.Args().Tail()) != 1 {
|
||||
fatalIf(errInvalidArgument().Trace(), "Incorrect number of arguments for remove host command.")
|
||||
}
|
||||
checkConfigHostRemoveSyntax(ctx)
|
||||
case "list":
|
||||
default:
|
||||
cli.ShowCommandHelpAndExit(ctx, "host", 1) // last argument is exit code
|
||||
}
|
||||
}
|
||||
|
||||
func mainConfigHost(ctx *cli.Context) {
|
||||
checkConfigHostSyntax(ctx)
|
||||
// checkConfigHostAddSyntax - verifies input arguments to 'config host add'.
|
||||
func checkConfigHostAddSyntax(ctx *cli.Context) {
|
||||
tailArgs := ctx.Args().Tail()
|
||||
tailsArgsNr := len(tailArgs)
|
||||
if tailsArgsNr < 4 || tailsArgsNr > 5 {
|
||||
fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...),
|
||||
"Incorrect number of arguments for host add command.")
|
||||
}
|
||||
|
||||
// set new custom coloring
|
||||
console.SetCustomTheme(map[string]*color.Color{
|
||||
"Host": color.New(color.FgCyan, color.Bold),
|
||||
"API": color.New(color.FgYellow, color.Bold),
|
||||
"HostMessage": color.New(color.FgGreen, color.Bold),
|
||||
"AccessKeyID": color.New(color.FgBlue, color.Bold),
|
||||
"SecretAccessKey": color.New(color.FgRed, color.Bold),
|
||||
})
|
||||
alias := tailArgs.Get(0)
|
||||
url := tailArgs.Get(1)
|
||||
accessKey := tailArgs.Get(2)
|
||||
secretKey := tailArgs.Get(3)
|
||||
api := tailArgs.Get(4)
|
||||
|
||||
arg := ctx.Args().First()
|
||||
if !isValidAlias(alias) {
|
||||
fatalIf(errDummy().Trace(alias), "Invalid alias ‘"+alias+"’.")
|
||||
}
|
||||
|
||||
if !isValidHostURL(url) {
|
||||
fatalIf(errDummy().Trace(url),
|
||||
"Invalid URL ‘"+url+"’.")
|
||||
}
|
||||
|
||||
if !isValidAccessKey(accessKey) {
|
||||
fatalIf(errInvalidArgument().Trace(accessKey),
|
||||
"Invalid access key ‘"+accessKey+"’.")
|
||||
}
|
||||
|
||||
if !isValidSecretKey(secretKey) {
|
||||
fatalIf(errInvalidArgument().Trace(secretKey),
|
||||
"Invalid secret key ‘"+secretKey+"’.")
|
||||
}
|
||||
|
||||
switch api {
|
||||
case "S3v2", "S3v4", "":
|
||||
default:
|
||||
fatalIf(errInvalidArgument().Trace(api),
|
||||
"Unrecognized API signature. Valid options are ‘[ S3v4, S3v2 ]’.")
|
||||
}
|
||||
}
|
||||
|
||||
// checkConfigHostRemoveSyntax - verifies input arguments to 'config host remove'.
|
||||
func checkConfigHostRemoveSyntax(ctx *cli.Context) {
|
||||
tailArgs := ctx.Args().Tail()
|
||||
|
||||
switch strings.TrimSpace(arg) {
|
||||
case "add":
|
||||
addHost(tailArgs.Get(0), tailArgs.Get(1), tailArgs.Get(2), tailArgs.Get(3))
|
||||
case "remove":
|
||||
removeHost(tailArgs.Get(0))
|
||||
case "list":
|
||||
listHosts()
|
||||
if len(ctx.Args().Tail()) != 1 {
|
||||
fatalIf(errInvalidArgument().Trace(tailArgs...),
|
||||
"Incorrect number of arguments for remove host command.")
|
||||
}
|
||||
|
||||
if !isValidAlias(tailArgs.Get(0)) {
|
||||
fatalIf(errDummy().Trace(tailArgs.Get(0)),
|
||||
"Invalid alias ‘"+tailArgs.Get(0)+"’.")
|
||||
}
|
||||
}
|
||||
|
||||
func mainConfigHost(ctx *cli.Context) {
|
||||
// Set global flags from context.
|
||||
setGlobalsFromContext(ctx)
|
||||
|
||||
// check 'config host' cli arguments.
|
||||
checkConfigHostSyntax(ctx)
|
||||
|
||||
// Additional command speific theme customization.
|
||||
console.SetColor("HostMessage", color.New(color.FgGreen))
|
||||
console.SetColor("Alias", color.New(color.FgCyan, color.Bold))
|
||||
console.SetColor("URL", color.New(color.FgCyan))
|
||||
console.SetColor("AccessKey", color.New(color.FgBlue))
|
||||
console.SetColor("SecretKey", color.New(color.FgBlue))
|
||||
console.SetColor("API", color.New(color.FgYellow))
|
||||
|
||||
cmd := ctx.Args().First()
|
||||
args := ctx.Args().Tail()
|
||||
|
||||
// Switch case through commands.
|
||||
switch strings.TrimSpace(cmd) {
|
||||
case "add":
|
||||
alias := args.Get(0)
|
||||
url := args.Get(1)
|
||||
accessKey := args.Get(2)
|
||||
secretKey := args.Get(3)
|
||||
api := args.Get(4)
|
||||
if strings.TrimSpace(api) == "" {
|
||||
api = "S3v4"
|
||||
}
|
||||
hostCfg := hostConfigV7{
|
||||
URL: url,
|
||||
AccessKey: accessKey,
|
||||
SecretKey: secretKey,
|
||||
API: api,
|
||||
}
|
||||
addHost(alias, hostCfg) // Add a host with specified credentials.
|
||||
case "remove":
|
||||
alias := args.Get(0)
|
||||
removeHost(alias) // Remove a host.
|
||||
case "list":
|
||||
listHosts() // List all configured hosts.
|
||||
}
|
||||
}
|
||||
|
||||
// addHost - add a host config.
|
||||
func addHost(alias string, hostCfgV7 hostConfigV7) {
|
||||
mcCfgV7, err := loadMcConfig()
|
||||
fatalIf(err.Trace(globalMCConfigVersion), "Unable to load config ‘"+mustGetMcConfigPath()+"’.")
|
||||
|
||||
// Add new host.
|
||||
mcCfgV7.Hosts[alias] = hostCfgV7
|
||||
|
||||
err = saveMcConfig(mcCfgV7)
|
||||
fatalIf(err.Trace(alias), "Unable to update hosts in config version ‘"+mustGetMcConfigPath()+"’.")
|
||||
|
||||
printMsg(hostMessage{
|
||||
op: "add",
|
||||
Alias: alias,
|
||||
URL: hostCfgV7.URL,
|
||||
AccessKey: hostCfgV7.AccessKey,
|
||||
SecretKey: hostCfgV7.SecretKey,
|
||||
API: hostCfgV7.API,
|
||||
})
|
||||
}
|
||||
|
||||
// removeHost - removes a host.
|
||||
func removeHost(alias string) {
|
||||
conf, err := loadMcConfig()
|
||||
fatalIf(err.Trace(globalMCConfigVersion), "Unable to load config version ‘"+globalMCConfigVersion+"’.")
|
||||
|
||||
// Remove host.
|
||||
delete(conf.Hosts, alias)
|
||||
|
||||
err = saveMcConfig(conf)
|
||||
fatalIf(err.Trace(alias), "Unable to save deleted hosts in config version ‘"+globalMCConfigVersion+"’.")
|
||||
|
||||
printMsg(hostMessage{op: "remove", Alias: alias})
|
||||
}
|
||||
|
||||
// listHosts - list all host URLs.
|
||||
func listHosts() {
|
||||
config, err := newConfig()
|
||||
fatalIf(err.Trace(), "Failed to initialize ‘quick’ configuration data structure.")
|
||||
conf, err := loadMcConfig()
|
||||
fatalIf(err.Trace(globalMCConfigVersion), "Unable to load config version ‘"+globalMCConfigVersion+"’.")
|
||||
|
||||
configPath := mustGetMcConfigPath()
|
||||
err = config.Load(configPath)
|
||||
fatalIf(err.Trace(configPath), "Unable to load config path")
|
||||
|
||||
// convert interface{} back to its original struct
|
||||
newConf := config.Data().(*configV5)
|
||||
for k, v := range newConf.Hosts {
|
||||
Prints("%s\n", HostMessage{
|
||||
op: "list",
|
||||
Host: k,
|
||||
AccessKeyID: v.AccessKeyID,
|
||||
SecretAccessKey: v.SecretAccessKey,
|
||||
API: v.API,
|
||||
for k, v := range conf.Hosts {
|
||||
printMsg(hostMessage{
|
||||
op: "list",
|
||||
Alias: k,
|
||||
URL: v.URL,
|
||||
AccessKey: v.AccessKey,
|
||||
SecretKey: v.SecretKey,
|
||||
API: v.API,
|
||||
})
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func removeHost(hostGlob string) {
|
||||
if strings.TrimSpace(hostGlob) == "" {
|
||||
fatalIf(errDummy().Trace(), "Alias or URL cannot be empty.")
|
||||
}
|
||||
if strings.TrimSpace(hostGlob) == "dl.minio.io:9000" {
|
||||
fatalIf(errDummy().Trace(), "‘"+hostGlob+"’ is reserved hostname and cannot be removed.")
|
||||
}
|
||||
config, err := newConfig()
|
||||
fatalIf(err.Trace(globalMCConfigVersion), "Failed to initialize ‘quick’ configuration data structure.")
|
||||
|
||||
configPath := mustGetMcConfigPath()
|
||||
err = config.Load(configPath)
|
||||
fatalIf(err.Trace(configPath), "Unable to load config path")
|
||||
|
||||
// convert interface{} back to its original struct
|
||||
newConf := config.Data().(*configV5)
|
||||
if _, ok := newConf.Hosts[hostGlob]; !ok {
|
||||
fatalIf(errDummy().Trace(), fmt.Sprintf("Host glob ‘%s’ does not exist.", hostGlob))
|
||||
}
|
||||
delete(newConf.Hosts, hostGlob)
|
||||
|
||||
newConfig, err := quick.New(newConf)
|
||||
fatalIf(err.Trace(globalMCConfigVersion), "Failed to initialize ‘quick’ configuration data structure.")
|
||||
err = writeConfig(newConfig)
|
||||
fatalIf(err.Trace(hostGlob), "Unable to save host glob ‘"+hostGlob+"’.")
|
||||
|
||||
Prints("%s\n", HostMessage{
|
||||
op: "remove",
|
||||
Host: hostGlob,
|
||||
})
|
||||
}
|
||||
|
||||
// isValidSecretKey - validate secret key
|
||||
func isValidSecretKey(secretAccessKey string) bool {
|
||||
if secretAccessKey == "" {
|
||||
return true
|
||||
}
|
||||
regex := regexp.MustCompile("^.{40}$")
|
||||
return regex.MatchString(secretAccessKey)
|
||||
}
|
||||
|
||||
// isValidAccessKey - validate access key
|
||||
func isValidAccessKey(accessKeyID string) bool {
|
||||
if accessKeyID == "" {
|
||||
return true
|
||||
}
|
||||
regex := regexp.MustCompile("^[A-Z0-9\\-\\.\\_\\~]{20}$")
|
||||
return regex.MatchString(accessKeyID)
|
||||
}
|
||||
|
||||
// addHost - add new host
|
||||
func addHost(hostGlob, accessKeyID, secretAccessKey, api string) {
|
||||
if strings.TrimSpace(hostGlob) == "" {
|
||||
fatalIf(errDummy().Trace(), "Unable to proceed, empty arguments provided.")
|
||||
}
|
||||
if strings.TrimSpace(api) == "" {
|
||||
api = "S3v4"
|
||||
}
|
||||
if strings.TrimSpace(api) != "S3v2" && strings.TrimSpace(api) != "S3v4" {
|
||||
fatalIf(errInvalidArgument().Trace(), "Unrecognized version name provided, supported inputs are ‘S3v4’, ‘S3v2’")
|
||||
}
|
||||
config, err := newConfig()
|
||||
fatalIf(err.Trace(globalMCConfigVersion), "Failed to initialize ‘quick’ configuration data structure.")
|
||||
|
||||
configPath := mustGetMcConfigPath()
|
||||
err = config.Load(configPath)
|
||||
fatalIf(err.Trace(configPath), "Unable to load config path")
|
||||
|
||||
if len(accessKeyID) != 0 {
|
||||
if !isValidAccessKey(accessKeyID) {
|
||||
fatalIf(errInvalidArgument().Trace(), "Invalid access key id provided.")
|
||||
}
|
||||
}
|
||||
if len(secretAccessKey) != 0 {
|
||||
if !isValidSecretKey(secretAccessKey) {
|
||||
fatalIf(errInvalidArgument().Trace(), "Invalid secret access key provided.")
|
||||
}
|
||||
}
|
||||
// convert interface{} back to its original struct
|
||||
newConf := config.Data().(*configV5)
|
||||
newConf.Hosts[hostGlob] = hostConfig{
|
||||
AccessKeyID: accessKeyID,
|
||||
SecretAccessKey: secretAccessKey,
|
||||
API: api,
|
||||
}
|
||||
newConfig, err := quick.New(newConf)
|
||||
fatalIf(err.Trace(globalMCConfigVersion), "Failed to initialize ‘quick’ configuration data structure.")
|
||||
|
||||
err = writeConfig(newConfig)
|
||||
fatalIf(err.Trace(hostGlob), "Unable to save host glob ‘"+hostGlob+"’.")
|
||||
|
||||
Prints("%s\n", HostMessage{
|
||||
op: "add",
|
||||
Host: hostGlob,
|
||||
AccessKeyID: accessKeyID,
|
||||
SecretAccessKey: secretAccessKey,
|
||||
API: api,
|
||||
})
|
||||
}
|
||||
|
||||
+28
-8
@@ -28,30 +28,50 @@ import "github.com/minio/cli"
|
||||
// so to avoid taking credentials over cli arguments. It is a security precaution
|
||||
// ----
|
||||
//
|
||||
|
||||
var (
|
||||
configFlags = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "help, h",
|
||||
Usage: "Help of config.",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
var configCmd = cli.Command{
|
||||
Name: "config",
|
||||
Usage: "Collection of config management commands.",
|
||||
Usage: "Manage configuration file.",
|
||||
Action: mainConfig,
|
||||
Flags: append(configFlags, globalFlags...),
|
||||
Subcommands: []cli.Command{
|
||||
configAliasCmd,
|
||||
configHostCmd,
|
||||
configVersionCmd,
|
||||
},
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.Name}} - {{.Usage}}
|
||||
{{.Name}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.Name}} {{if .Flags}}[global flags] {{end}}command{{if .Flags}} [command flags]{{end}} [arguments...]
|
||||
{{.Name}} [FLAGS] COMMAND
|
||||
|
||||
COMMANDS:
|
||||
{{range .Commands}}{{ .Name }}{{ "\t" }}{{.Usage}}
|
||||
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) {
|
||||
if !ctx.Args().Present() || ctx.Args().First() == "help" {
|
||||
// Set global flags from context.
|
||||
setGlobalsFromContext(ctx)
|
||||
|
||||
if ctx.Args().First() != "" { // command help.
|
||||
cli.ShowCommandHelp(ctx, ctx.Args().First())
|
||||
} else {
|
||||
// command with Subcommands is an App.
|
||||
cli.ShowAppHelp(ctx)
|
||||
}
|
||||
|
||||
// Sub-commands like "host" and "alias" have their own main.
|
||||
}
|
||||
|
||||
@@ -0,0 +1,380 @@
|
||||
/*
|
||||
* Minio Client (C) 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio-xl/pkg/quick"
|
||||
)
|
||||
|
||||
// migrate config files from the any older version to the latest.
|
||||
func migrateConfig() {
|
||||
// Migrate config V1 to V101
|
||||
migrateConfigV1ToV101()
|
||||
// Migrate config V101 to V2
|
||||
migrateConfigV101ToV2()
|
||||
// Migrate config V2 to V3
|
||||
migrateConfigV2ToV3()
|
||||
// Migrate config V3 to V4
|
||||
migrateConfigV3ToV4()
|
||||
// Migrate config V4 to V5
|
||||
migrateConfigV4ToV5()
|
||||
// Migrate config V5 to V6
|
||||
migrateConfigV5ToV6()
|
||||
// Migrate config V6 to V7
|
||||
migrateConfigV6ToV7()
|
||||
}
|
||||
|
||||
// Migrate from config version 1.0 to 1.0.1. Populate example entries and save it back.
|
||||
func migrateConfigV1ToV101() {
|
||||
if !isMcConfigExists() {
|
||||
return
|
||||
}
|
||||
mcCfgV1, err := quick.Load(mustGetMcConfigPath(), newConfigV1())
|
||||
fatalIf(err.Trace(), "Unable to load config version ‘1’.")
|
||||
|
||||
// If loaded config version does not match 1.0.0, we do nothing.
|
||||
if mcCfgV1.Version() != "1.0.0" {
|
||||
return
|
||||
}
|
||||
|
||||
// 1.0.1 is compatible to 1.0.0. We are just adding new entries.
|
||||
cfgV101 := newConfigV101()
|
||||
|
||||
// Copy aliases.
|
||||
for k, v := range mcCfgV1.Data().(*configV1).Aliases {
|
||||
cfgV101.Aliases[k] = v
|
||||
}
|
||||
|
||||
// Copy hosts.
|
||||
for k, hostCfgV1 := range mcCfgV1.Data().(*configV1).Hosts {
|
||||
cfgV101.Hosts[k] = hostConfigV101{
|
||||
AccessKeyID: hostCfgV1.AccessKeyID,
|
||||
SecretAccessKey: hostCfgV1.SecretAccessKey,
|
||||
}
|
||||
}
|
||||
|
||||
// Example localhost entry.
|
||||
if _, ok := cfgV101.Hosts["localhost:*"]; !ok {
|
||||
cfgV101.Hosts["localhost:*"] = hostConfigV101{}
|
||||
}
|
||||
|
||||
// Example loopback IP entry.
|
||||
if _, ok := cfgV101.Hosts["127.0.0.1:*"]; !ok {
|
||||
cfgV101.Hosts["127.0.0.1:*"] = hostConfigV101{}
|
||||
}
|
||||
|
||||
// Example AWS entry.
|
||||
// Look for glob string (not glob match). We used to support glob based key matching earlier.
|
||||
if _, ok := cfgV101.Hosts["*.s3*.amazonaws.com"]; !ok {
|
||||
cfgV101.Hosts["*.s3*.amazonaws.com"] = hostConfigV101{
|
||||
AccessKeyID: "YOUR-ACCESS-KEY-ID-HERE",
|
||||
SecretAccessKey: "YOUR-SECRET-ACCESS-KEY-HERE",
|
||||
}
|
||||
}
|
||||
|
||||
// Save the new config back to the disk.
|
||||
mcCfgV101, err := quick.New(cfgV101)
|
||||
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘1.0.1’.")
|
||||
err = mcCfgV101.Save(mustGetMcConfigPath())
|
||||
fatalIf(err.Trace(), "Unable to save config version ‘1.0.1’.")
|
||||
|
||||
console.Infof("Successfully migrated %s from version ‘1.0.0’ to version ‘1.0.1’.\n", mustGetMcConfigPath())
|
||||
}
|
||||
|
||||
// Migrate from config ‘1.0.1’ to ‘2’. Drop semantic versioning and move to integer versioning. No other changes.
|
||||
func migrateConfigV101ToV2() {
|
||||
if !isMcConfigExists() {
|
||||
return
|
||||
}
|
||||
mcCfgV101, err := quick.Load(mustGetMcConfigPath(), newConfigV101())
|
||||
fatalIf(err.Trace(), "Unable to load config version ‘1.0.1’.")
|
||||
|
||||
// update to newer version
|
||||
if mcCfgV101.Version() != "1.0.1" {
|
||||
return
|
||||
}
|
||||
|
||||
cfgV2 := newConfigV2()
|
||||
|
||||
// Copy aliases.
|
||||
for k, v := range mcCfgV101.Data().(*configV101).Aliases {
|
||||
cfgV2.Aliases[k] = v
|
||||
}
|
||||
|
||||
// Copy hosts.
|
||||
for k, hostCfgV101 := range mcCfgV101.Data().(*configV101).Hosts {
|
||||
cfgV2.Hosts[k] = hostConfigV2{
|
||||
AccessKeyID: hostCfgV101.AccessKeyID,
|
||||
SecretAccessKey: hostCfgV101.SecretAccessKey,
|
||||
}
|
||||
}
|
||||
|
||||
mcCfgV2, err := quick.New(cfgV2)
|
||||
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘2’.")
|
||||
|
||||
err = mcCfgV2.Save(mustGetMcConfigPath())
|
||||
fatalIf(err.Trace(), "Unable to save config version ‘2’.")
|
||||
|
||||
console.Infof("Successfully migrated %s from version ‘1.0.1’ to version ‘2’.\n", mustGetMcConfigPath())
|
||||
}
|
||||
|
||||
// Migrate from config ‘2’ to ‘3’. Use ‘-’ separated names for
|
||||
// hostConfig using struct json tags.
|
||||
func migrateConfigV2ToV3() {
|
||||
if !isMcConfigExists() {
|
||||
return
|
||||
}
|
||||
|
||||
mcCfgV2, err := quick.Load(mustGetMcConfigPath(), newConfigV2())
|
||||
fatalIf(err.Trace(), "Unable to load mc config V2.")
|
||||
|
||||
// update to newer version
|
||||
if mcCfgV2.Version() != "2" {
|
||||
return
|
||||
}
|
||||
|
||||
cfgV3 := newConfigV3()
|
||||
|
||||
// Copy aliases.
|
||||
for k, v := range mcCfgV2.Data().(*configV2).Aliases {
|
||||
cfgV3.Aliases[k] = v
|
||||
}
|
||||
|
||||
// Copy hosts.
|
||||
for k, hostCfgV2 := range mcCfgV2.Data().(*configV2).Hosts {
|
||||
// New hostConfV3 uses struct json tags.
|
||||
cfgV3.Hosts[k] = hostConfigV3{
|
||||
AccessKeyID: hostCfgV2.AccessKeyID,
|
||||
SecretAccessKey: hostCfgV2.SecretAccessKey,
|
||||
}
|
||||
}
|
||||
|
||||
mcNewCfgV3, err := quick.New(cfgV3)
|
||||
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘3’.")
|
||||
|
||||
err = mcNewCfgV3.Save(mustGetMcConfigPath())
|
||||
fatalIf(err.Trace(), "Unable to save config version ‘3’.")
|
||||
|
||||
console.Infof("Successfully migrated %s from version ‘2’ to version ‘3’.\n", mustGetMcConfigPath())
|
||||
}
|
||||
|
||||
// Migrate from config version ‘3’ to ‘4’. Introduce API Signature
|
||||
// field in host config. Also Use JavaScript notation for field names.
|
||||
func migrateConfigV3ToV4() {
|
||||
if !isMcConfigExists() {
|
||||
return
|
||||
}
|
||||
mcCfgV3, err := quick.Load(mustGetMcConfigPath(), newConfigV3())
|
||||
fatalIf(err.Trace(), "Unable to load mc config V2.")
|
||||
|
||||
// update to newer version
|
||||
if mcCfgV3.Version() != "3" {
|
||||
return
|
||||
}
|
||||
|
||||
cfgV4 := newConfigV4()
|
||||
for k, v := range mcCfgV3.Data().(*configV3).Aliases {
|
||||
cfgV4.Aliases[k] = v
|
||||
}
|
||||
// New hostConfig has API signature. All older entries were V4
|
||||
// only. So it is safe to assume V4 as default for all older
|
||||
// entries.
|
||||
// HostConfigV4 als uses JavaScript naming notation for struct JSON tags.
|
||||
for host, hostCfgV3 := range mcCfgV3.Data().(*configV3).Hosts {
|
||||
cfgV4.Hosts[host] = hostConfigV4{
|
||||
AccessKeyID: hostCfgV3.AccessKeyID,
|
||||
SecretAccessKey: hostCfgV3.SecretAccessKey,
|
||||
Signature: "v4",
|
||||
}
|
||||
}
|
||||
|
||||
mcNewCfgV4, err := quick.New(cfgV4)
|
||||
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘4’.")
|
||||
|
||||
err = mcNewCfgV4.Save(mustGetMcConfigPath())
|
||||
fatalIf(err.Trace(), "Unable to save config version ‘4’.")
|
||||
|
||||
console.Infof("Successfully migrated %s from version ‘3’ to version ‘4’.\n", mustGetMcConfigPath())
|
||||
|
||||
}
|
||||
|
||||
// Migrate config version ‘4’ to ‘5’. Rename hostConfigV4.Signature -> hostConfigV5.API.
|
||||
func migrateConfigV4ToV5() {
|
||||
if !isMcConfigExists() {
|
||||
return
|
||||
}
|
||||
mcCfgV4, err := quick.Load(mustGetMcConfigPath(), newConfigV4())
|
||||
fatalIf(err.Trace(), "Unable to load mc config V4.")
|
||||
|
||||
// update to newer version
|
||||
if mcCfgV4.Version() != "4" {
|
||||
return
|
||||
}
|
||||
|
||||
cfgV5 := newConfigV5()
|
||||
for k, v := range mcCfgV4.Data().(*configV4).Aliases {
|
||||
cfgV5.Aliases[k] = v
|
||||
}
|
||||
for host, hostCfgV4 := range mcCfgV4.Data().(*configV4).Hosts {
|
||||
cfgV5.Hosts[host] = hostConfigV5{
|
||||
AccessKeyID: hostCfgV4.AccessKeyID,
|
||||
SecretAccessKey: hostCfgV4.SecretAccessKey,
|
||||
API: "v4", // Rename from .Signature to .API
|
||||
}
|
||||
}
|
||||
|
||||
mcNewCfgV5, err := quick.New(cfgV5)
|
||||
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘5’.")
|
||||
|
||||
err = mcNewCfgV5.Save(mustGetMcConfigPath())
|
||||
fatalIf(err.Trace(), "Unable to save config version ‘5’.")
|
||||
|
||||
console.Infof("Successfully migrated %s from version ‘4’ to version ‘5’.\n", mustGetMcConfigPath())
|
||||
}
|
||||
|
||||
// Migrate config version ‘5’ to ‘6’. Add google cloud storage servers
|
||||
// to host config. Also remove "." from s3 aws glob rule.
|
||||
func migrateConfigV5ToV6() {
|
||||
if !isMcConfigExists() {
|
||||
return
|
||||
}
|
||||
mcCfgV5, err := quick.Load(mustGetMcConfigPath(), newConfigV5())
|
||||
fatalIf(err.Trace(), "Unable to load mc config V5.")
|
||||
|
||||
// update to newer version
|
||||
if mcCfgV5.Version() != "5" {
|
||||
return
|
||||
}
|
||||
|
||||
cfgV6 := newConfigV6()
|
||||
|
||||
// Add new Google Cloud Storage alias.
|
||||
cfgV6.Aliases["gcs"] = "https://storage.googleapis.com"
|
||||
|
||||
for k, v := range mcCfgV5.Data().(*configV5).Aliases {
|
||||
cfgV6.Aliases[k] = v
|
||||
}
|
||||
|
||||
// Add defaults.
|
||||
cfgV6.Hosts["*s3*amazonaws.com"] = hostConfigV6{
|
||||
AccessKeyID: "YOUR-ACCESS-KEY-ID-HERE",
|
||||
SecretAccessKey: "YOUR-SECRET-ACCESS-KEY-HERE",
|
||||
API: "S3v4",
|
||||
}
|
||||
cfgV6.Hosts["*storage.googleapis.com"] = hostConfigV6{
|
||||
AccessKeyID: "YOUR-ACCESS-KEY-ID-HERE",
|
||||
SecretAccessKey: "YOUR-SECRET-ACCESS-KEY-HERE",
|
||||
API: "S3v2",
|
||||
}
|
||||
|
||||
for host, hostCfgV5 := range mcCfgV5.Data().(*configV5).Hosts {
|
||||
// Find any matching s3 entry and copy keys from it to newer generalized glob entry.
|
||||
if strings.Contains(host, "s3") {
|
||||
if (hostCfgV5.AccessKeyID == "YOUR-ACCESS-KEY-ID-HERE") ||
|
||||
(hostCfgV5.SecretAccessKey == "YOUR-SECRET-ACCESS-KEY-HERE") ||
|
||||
hostCfgV5.AccessKeyID == "" ||
|
||||
hostCfgV5.SecretAccessKey == "" {
|
||||
continue // Skip defaults.
|
||||
}
|
||||
// Now we have real keys set by the user. Copy
|
||||
// them over to newer glob rule.
|
||||
// Original host entry has "." in the glob rule.
|
||||
host = "*s3*amazonaws.com" // Use this glob entry.
|
||||
}
|
||||
|
||||
cfgV6.Hosts[host] = hostConfigV6{
|
||||
AccessKeyID: hostCfgV5.AccessKeyID,
|
||||
SecretAccessKey: hostCfgV5.SecretAccessKey,
|
||||
API: hostCfgV5.API,
|
||||
}
|
||||
}
|
||||
|
||||
mcNewCfgV6, err := quick.New(cfgV6)
|
||||
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘6’.")
|
||||
|
||||
err = mcNewCfgV6.Save(mustGetMcConfigPath())
|
||||
fatalIf(err.Trace(), "Unable to save config version ‘6’.")
|
||||
|
||||
console.Infof("Successfully migrated %s from version ‘5’ to version ‘6’.\n", mustGetMcConfigPath())
|
||||
}
|
||||
|
||||
// Migrate config version ‘6’ to ‘7'. Remove alias map and introduce
|
||||
// named Host config. Also no more glob match for host config entries.
|
||||
func migrateConfigV6ToV7() {
|
||||
if !isMcConfigExists() {
|
||||
return
|
||||
}
|
||||
|
||||
mcCfgV6, err := quick.Load(mustGetMcConfigPath(), newConfigV6())
|
||||
fatalIf(err.Trace(), "Unable to load mc config V6.")
|
||||
|
||||
if mcCfgV6.Version() != "6" {
|
||||
return
|
||||
}
|
||||
|
||||
cfgV7 := newConfigV7()
|
||||
aliasIndex := 0
|
||||
// We dropped alias support in v7. We only need to migrate host configs.
|
||||
for host, hostCfgV6 := range mcCfgV6.Data().(*configV6).Hosts {
|
||||
if hostCfgV6.AccessKeyID == "YOUR-ACCESS-KEY-ID-HERE" ||
|
||||
hostCfgV6.SecretAccessKey == "YOUR-SECRET-ACCESS-KEY-HERE" ||
|
||||
hostCfgV6.AccessKeyID == "" ||
|
||||
hostCfgV6.SecretAccessKey == "" {
|
||||
// Ignore default entries. configV7.loadDefaults() will re-insert them back.
|
||||
} else if host == "https://s3.amazonaws.com" {
|
||||
// Only one entry can exist for "s3" domain.
|
||||
cfgV7.Hosts["s3"] = hostConfigV7{
|
||||
URL: host,
|
||||
AccessKey: hostCfgV6.AccessKeyID,
|
||||
SecretKey: hostCfgV6.SecretAccessKey,
|
||||
API: hostCfgV6.API,
|
||||
}
|
||||
} else if host == "https://storage.googleapis.com" {
|
||||
// Only one entry can exist for "gcs" domain.
|
||||
cfgV7.Hosts["gcs"] = hostConfigV7{
|
||||
URL: host,
|
||||
AccessKey: hostCfgV6.AccessKeyID,
|
||||
SecretKey: hostCfgV6.SecretAccessKey,
|
||||
API: hostCfgV6.API,
|
||||
}
|
||||
} else {
|
||||
// Assign a generic "cloud1", cloud2..." key
|
||||
// for all other entries that has valid keys set.
|
||||
alias := fmt.Sprintf("cloud%d", aliasIndex)
|
||||
aliasIndex++
|
||||
cfgV7.Hosts[alias] = hostConfigV7{
|
||||
URL: host,
|
||||
AccessKey: hostCfgV6.AccessKeyID,
|
||||
SecretKey: hostCfgV6.SecretAccessKey,
|
||||
API: hostCfgV6.API,
|
||||
}
|
||||
}
|
||||
}
|
||||
// Load default settings.
|
||||
cfgV7.loadDefaults()
|
||||
mcNewCfgV7, err := quick.New(cfgV7)
|
||||
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘7’.")
|
||||
|
||||
err = mcNewCfgV7.Save(mustGetMcConfigPath())
|
||||
fatalIf(err.Trace(), "Unable to save config version ‘7’.")
|
||||
|
||||
console.Infof("Successfully migrated %s from version ‘6’ to version ‘7’.\n", mustGetMcConfigPath())
|
||||
}
|
||||
+164
@@ -0,0 +1,164 @@
|
||||
/*
|
||||
* Minio Client (C) 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
/////////////////// Config V1 ///////////////////
|
||||
type hostConfigV1 struct {
|
||||
AccessKeyID string
|
||||
SecretAccessKey string
|
||||
}
|
||||
|
||||
type configV1 struct {
|
||||
Version string
|
||||
Aliases map[string]string
|
||||
Hosts map[string]hostConfigV1
|
||||
}
|
||||
|
||||
// newConfigV1() - get new config version 1.0.0
|
||||
func newConfigV1() *configV1 {
|
||||
conf := new(configV1)
|
||||
conf.Version = "1.0.0"
|
||||
// make sure to allocate map's otherwise Golang
|
||||
// exits silently without providing any errors
|
||||
conf.Aliases = make(map[string]string)
|
||||
conf.Hosts = make(map[string]hostConfigV1)
|
||||
return conf
|
||||
}
|
||||
|
||||
/////////////////// Config V101 ///////////////////
|
||||
type hostConfigV101 hostConfigV1
|
||||
|
||||
type configV101 struct {
|
||||
Version string
|
||||
Aliases map[string]string
|
||||
Hosts map[string]hostConfigV101
|
||||
}
|
||||
|
||||
// newConfigV101() - get new config version 1.0.1
|
||||
func newConfigV101() *configV101 {
|
||||
conf := new(configV101)
|
||||
conf.Version = "1.0.1"
|
||||
conf.Aliases = make(map[string]string)
|
||||
conf.Hosts = make(map[string]hostConfigV101)
|
||||
return conf
|
||||
}
|
||||
|
||||
/////////////////// Config V2 ///////////////////
|
||||
type hostConfigV2 hostConfigV1
|
||||
|
||||
type configV2 struct {
|
||||
Version string
|
||||
Aliases map[string]string
|
||||
Hosts map[string]hostConfigV2
|
||||
}
|
||||
|
||||
// newConfigV2() - get new config version 2
|
||||
func newConfigV2() *configV2 {
|
||||
conf := new(configV2)
|
||||
conf.Version = "2"
|
||||
conf.Aliases = make(map[string]string)
|
||||
conf.Hosts = make(map[string]hostConfigV2)
|
||||
return conf
|
||||
}
|
||||
|
||||
/////////////////// Config V3 ///////////////////
|
||||
type hostConfigV3 struct {
|
||||
AccessKeyID string `json:"access-key-id"`
|
||||
SecretAccessKey string `json:"secret-access-key"`
|
||||
}
|
||||
|
||||
type configV3 struct {
|
||||
Version string `json:"version"`
|
||||
Aliases map[string]string `json:"alias"`
|
||||
Hosts map[string]hostConfigV3 `json:"hosts"`
|
||||
}
|
||||
|
||||
// newConfigV3 - get new config version 3.
|
||||
func newConfigV3() *configV3 {
|
||||
conf := new(configV3)
|
||||
conf.Version = "3"
|
||||
conf.Aliases = make(map[string]string)
|
||||
conf.Hosts = make(map[string]hostConfigV3)
|
||||
return conf
|
||||
}
|
||||
|
||||
/////////////////// Config V4 ///////////////////
|
||||
type hostConfigV4 struct {
|
||||
AccessKeyID string `json:"accessKeyId"`
|
||||
SecretAccessKey string `json:"secretAccessKey"`
|
||||
Signature string `json:"signature"`
|
||||
}
|
||||
|
||||
type configV4 struct {
|
||||
Version string `json:"version"`
|
||||
Aliases map[string]string `json:"alias"`
|
||||
Hosts map[string]hostConfigV4 `json:"hosts"`
|
||||
}
|
||||
|
||||
func newConfigV4() *configV4 {
|
||||
conf := new(configV4)
|
||||
conf.Version = "4"
|
||||
conf.Aliases = make(map[string]string)
|
||||
conf.Hosts = make(map[string]hostConfigV4)
|
||||
return conf
|
||||
}
|
||||
|
||||
/////////////////// Config V5 ///////////////////
|
||||
type hostConfigV5 struct {
|
||||
AccessKeyID string `json:"accessKeyId"`
|
||||
SecretAccessKey string `json:"secretAccessKey"`
|
||||
API string `json:"api"`
|
||||
}
|
||||
|
||||
type configV5 struct {
|
||||
Version string `json:"version"`
|
||||
Aliases map[string]string `json:"alias"`
|
||||
Hosts map[string]hostConfigV5 `json:"hosts"`
|
||||
}
|
||||
|
||||
func newConfigV5() *configV5 {
|
||||
conf := new(configV5)
|
||||
conf.Version = "5"
|
||||
conf.Aliases = make(map[string]string)
|
||||
conf.Hosts = make(map[string]hostConfigV5)
|
||||
return conf
|
||||
}
|
||||
|
||||
/////////////////// Config V6 ///////////////////
|
||||
type hostConfigV6 struct {
|
||||
AccessKeyID string `json:"accessKeyId"`
|
||||
SecretAccessKey string `json:"secretAccessKey"`
|
||||
API string `json:"api"`
|
||||
}
|
||||
|
||||
type configV6 struct {
|
||||
Version string `json:"version"`
|
||||
Aliases map[string]string `json:"alias"`
|
||||
Hosts map[string]hostConfigV6 `json:"hosts"`
|
||||
}
|
||||
|
||||
// newConfigV6 - new config version '6'.
|
||||
func newConfigV6() *configV6 {
|
||||
conf := new(configV6)
|
||||
conf.Version = "6"
|
||||
conf.Aliases = make(map[string]string)
|
||||
conf.Hosts = make(map[string]hostConfigV6)
|
||||
return conf
|
||||
}
|
||||
|
||||
/////////////////// Config V7 ///////////////////
|
||||
// RESERVED FOR FUTURE
|
||||
@@ -0,0 +1,41 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/minio/mc/pkg/client"
|
||||
)
|
||||
|
||||
// isValidSecretKey - validate secret key.
|
||||
func isValidSecretKey(secretKey string) bool {
|
||||
if secretKey == "" {
|
||||
return true
|
||||
}
|
||||
regex := regexp.MustCompile("^.{40}$")
|
||||
return regex.MatchString(secretKey)
|
||||
}
|
||||
|
||||
// isValidAccessKey - validate access key.
|
||||
func isValidAccessKey(accessKey string) bool {
|
||||
if accessKey == "" {
|
||||
return true
|
||||
}
|
||||
regex := regexp.MustCompile("^[A-Z0-9\\-\\.\\_\\~]{20}$")
|
||||
return regex.MatchString(accessKey)
|
||||
}
|
||||
|
||||
// isValidHostURL - validate input host url.
|
||||
func isValidHostURL(hostURL string) bool {
|
||||
if strings.TrimSpace(hostURL) == "" {
|
||||
return false
|
||||
}
|
||||
url := client.NewURL(hostURL)
|
||||
if url.Scheme != "https" && url.Scheme != "http" {
|
||||
return false
|
||||
}
|
||||
if url.Path != "" && url.Path != "/" {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
+157
@@ -0,0 +1,157 @@
|
||||
/*
|
||||
* Minio Client (C) 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"sync"
|
||||
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/minio-xl/pkg/quick"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultAccessKey = "YOUR-ACCESS-KEY-HERE"
|
||||
defaultSecretKey = "YOUR-SECRET-KEY-HERE"
|
||||
)
|
||||
|
||||
var (
|
||||
// set once during first load.
|
||||
cacheCfgV7 *configV7
|
||||
// All access to mc config file should be synchronized.
|
||||
cfgMutex = &sync.RWMutex{}
|
||||
)
|
||||
|
||||
// hostConfig configuration of a host.
|
||||
type hostConfigV7 struct {
|
||||
URL string `json:"url"`
|
||||
AccessKey string `json:"accessKey"`
|
||||
SecretKey string `json:"secretKey"`
|
||||
API string `json:"api"`
|
||||
}
|
||||
|
||||
// configV7 config version.
|
||||
type configV7 struct {
|
||||
Version string `json:"version"`
|
||||
Hosts map[string]hostConfigV7 `json:"hosts"`
|
||||
}
|
||||
|
||||
// newConfigV7 - new config version.
|
||||
func newConfigV7() *configV7 {
|
||||
cfg := new(configV7)
|
||||
cfg.Version = globalMCConfigVersion
|
||||
cfg.Hosts = make(map[string]hostConfigV7)
|
||||
return cfg
|
||||
}
|
||||
|
||||
// SetHost sets host config if not empty.
|
||||
func (c *configV7) setHost(alias string, cfg hostConfigV7) {
|
||||
if _, ok := c.Hosts[alias]; !ok {
|
||||
c.Hosts[alias] = cfg
|
||||
}
|
||||
}
|
||||
|
||||
// load default values for missing entries.
|
||||
func (c *configV7) loadDefaults() {
|
||||
// Minio server running locally.
|
||||
c.setHost("local", hostConfigV7{
|
||||
URL: "http://localhost:9000",
|
||||
AccessKey: "",
|
||||
SecretKey: "",
|
||||
API: "S3v4",
|
||||
})
|
||||
|
||||
// Amazon S3 cloud storage service.
|
||||
c.setHost("s3", hostConfigV7{
|
||||
URL: "https://s3.amazonaws.com",
|
||||
AccessKey: defaultAccessKey,
|
||||
SecretKey: defaultSecretKey,
|
||||
API: "S3v4",
|
||||
})
|
||||
|
||||
// Google cloud storage service.
|
||||
c.setHost("gcs", hostConfigV7{
|
||||
URL: "https://storage.googleapis.com",
|
||||
AccessKey: defaultAccessKey,
|
||||
SecretKey: defaultSecretKey,
|
||||
API: "S3v2",
|
||||
})
|
||||
|
||||
// Minio anonymous server for demo.
|
||||
c.setHost("play", hostConfigV7{
|
||||
URL: "https://play.minio.io:9000",
|
||||
AccessKey: "",
|
||||
SecretKey: "",
|
||||
API: "S3v4",
|
||||
})
|
||||
|
||||
// Minio demo server with public secret and access keys.
|
||||
c.setHost("player", hostConfigV7{
|
||||
URL: "https://play.minio.io:9002",
|
||||
AccessKey: "Q3AM3UQ867SPQQA43P2F",
|
||||
SecretKey: "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG",
|
||||
API: "S3v4",
|
||||
})
|
||||
|
||||
// Minio public download service.
|
||||
c.setHost("dl", hostConfigV7{
|
||||
URL: "https://dl.minio.io:9000",
|
||||
AccessKey: "",
|
||||
SecretKey: "",
|
||||
API: "S3v4",
|
||||
})
|
||||
}
|
||||
|
||||
// loadConfigV7 - loads a new config.
|
||||
func loadConfigV7() (*configV7, *probe.Error) {
|
||||
cfgMutex.RLock()
|
||||
defer cfgMutex.RUnlock()
|
||||
|
||||
// Cached in private global variable.
|
||||
if cacheCfgV7 != nil {
|
||||
return cacheCfgV7, nil
|
||||
}
|
||||
|
||||
if !isMcConfigExists() {
|
||||
return nil, errInvalidArgument().Trace()
|
||||
}
|
||||
|
||||
mcCfgV7, err := quick.Load(mustGetMcConfigPath(), newConfigV7())
|
||||
fatalIf(err.Trace(), "Unable to load mc config file ‘"+mustGetMcConfigPath()+"’.")
|
||||
|
||||
cfgV7 := mcCfgV7.Data().(*configV7)
|
||||
|
||||
// cache it.
|
||||
cacheCfgV7 = cfgV7
|
||||
|
||||
return cfgV7, nil
|
||||
}
|
||||
|
||||
// saveConfigV7 - saves an updated config.
|
||||
func saveConfigV7(cfgV7 *configV7) *probe.Error {
|
||||
cfgMutex.Lock()
|
||||
defer cfgMutex.Unlock()
|
||||
|
||||
qs, err := quick.New(cfgV7)
|
||||
if err != nil {
|
||||
return err.Trace()
|
||||
}
|
||||
|
||||
// update the cache.
|
||||
cacheCfgV7 = cfgV7
|
||||
|
||||
return qs.Save(mustGetMcConfigPath()).Trace(mustGetMcConfigPath())
|
||||
}
|
||||
@@ -1,69 +0,0 @@
|
||||
/*
|
||||
* Minio Client (C) 2014, 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
// Print config version.
|
||||
var configVersionCmd = cli.Command{
|
||||
Name: "version",
|
||||
Usage: "Print config version.",
|
||||
Action: mainConfigVersion,
|
||||
CustomHelpTemplate: `NAME:
|
||||
mc config {{.Name}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
mc config {{.Name}}
|
||||
|
||||
`,
|
||||
}
|
||||
|
||||
func mainConfigVersion(ctx *cli.Context) {
|
||||
if ctx.Args().First() == "help" {
|
||||
cli.ShowCommandHelpAndExit(ctx, "version", 1) // last argument is exit code
|
||||
}
|
||||
|
||||
config, err := newConfig()
|
||||
fatalIf(err.Trace(), "Failed to initialize ‘quick’ configuration data structure.")
|
||||
|
||||
configPath := mustGetMcConfigPath()
|
||||
err = config.Load(configPath)
|
||||
fatalIf(err.Trace(configPath), "Unable to load config path")
|
||||
|
||||
// convert interface{} back to its original struct
|
||||
newConf := config.Data().(*configV5)
|
||||
type Version struct {
|
||||
Value string `json:"value"`
|
||||
}
|
||||
if globalJSONFlag {
|
||||
tB, e := json.Marshal(
|
||||
struct {
|
||||
Version Version `json:"version"`
|
||||
}{Version: Version{newConf.Version}},
|
||||
)
|
||||
fatalIf(probe.NewError(e), "Unable to construct version string.")
|
||||
console.Println(string(tB))
|
||||
return
|
||||
}
|
||||
console.Println(newConf.Version)
|
||||
}
|
||||
@@ -18,65 +18,21 @@ package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"os/user"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"runtime"
|
||||
"sync"
|
||||
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
"github.com/minio/minio/pkg/quick"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/minio/pkg/user"
|
||||
)
|
||||
|
||||
type configV5 struct {
|
||||
Version string `json:"version"`
|
||||
Aliases map[string]string `json:"alias"`
|
||||
Hosts map[string]hostConfig `json:"hosts"`
|
||||
}
|
||||
|
||||
type configV4 struct {
|
||||
Version string `json:"version"`
|
||||
Aliases map[string]string `json:"alias"`
|
||||
Hosts map[string]struct {
|
||||
AccessKeyID string `json:"accessKeyId"`
|
||||
SecretAccessKey string `json:"secretAccessKey"`
|
||||
Signature string `json:"signature"`
|
||||
} `json:"hosts"`
|
||||
}
|
||||
|
||||
type configV3 struct {
|
||||
Version string `json:"version"`
|
||||
Aliases map[string]string `json:"alias"`
|
||||
// custom anonymous struct is necessary from version to 3 to version 4
|
||||
// since hostConfig{} has changed to camelcase fields for unmarshal
|
||||
Hosts map[string]struct {
|
||||
AccessKeyID string `json:"access-key-id"`
|
||||
SecretAccessKey string `json:"secret-access-key"`
|
||||
} `json:"hosts"`
|
||||
}
|
||||
|
||||
type configV2 struct {
|
||||
Version string
|
||||
Aliases map[string]string
|
||||
// custom anonymous struct is necessary from version to 2 to version 3
|
||||
// since hostConfig{} has changed to lower case fields for unmarshal
|
||||
Hosts map[string]struct {
|
||||
AccessKeyID string
|
||||
SecretAccessKey string
|
||||
}
|
||||
}
|
||||
|
||||
// for backward compatibility
|
||||
type configV101 configV2
|
||||
type configV1 configV2
|
||||
|
||||
// cached variables should *NEVER* be accessed directly from outside this file.
|
||||
var cache sync.Pool
|
||||
|
||||
// customConfigDir contains the whole path to config dir. Only access via get/set functions.
|
||||
// mcCustomConfigDir contains the whole path to config dir. Only access via get/set functions.
|
||||
var mcCustomConfigDir string
|
||||
|
||||
// setMcConfigDir - construct minio client config folder.
|
||||
// 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
|
||||
}
|
||||
@@ -86,16 +42,16 @@ func getMcConfigDir() (string, *probe.Error) {
|
||||
if mcCustomConfigDir != "" {
|
||||
return mcCustomConfigDir, nil
|
||||
}
|
||||
u, err := user.Current()
|
||||
if err != nil {
|
||||
return "", probe.NewError(err)
|
||||
homeDir, e := user.HomeDir()
|
||||
if e != nil {
|
||||
return "", probe.NewError(e)
|
||||
}
|
||||
// For windows the path is slightly different
|
||||
switch runtime.GOOS {
|
||||
case "windows":
|
||||
return filepath.Join(u.HomeDir, globalMCConfigWindowsDir), nil
|
||||
return filepath.Join(homeDir, globalMCConfigWindowsDir), nil
|
||||
default:
|
||||
return filepath.Join(u.HomeDir, globalMCConfigDir), nil
|
||||
return filepath.Join(homeDir, globalMCConfigDir), nil
|
||||
}
|
||||
}
|
||||
|
||||
@@ -113,14 +69,17 @@ func createMcConfigDir() *probe.Error {
|
||||
if err != nil {
|
||||
return err.Trace()
|
||||
}
|
||||
if err := os.MkdirAll(p, 0700); err != nil {
|
||||
return probe.NewError(err)
|
||||
if e := os.MkdirAll(p, 0700); e != nil {
|
||||
return probe.NewError(e)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// getMcConfigPath - construct minio client configuration path
|
||||
func getMcConfigPath() (string, *probe.Error) {
|
||||
if mcCustomConfigPath != "" {
|
||||
return mcCustomConfigPath, nil
|
||||
}
|
||||
dir, err := getMcConfigDir()
|
||||
if err != nil {
|
||||
return "", err.Trace()
|
||||
@@ -136,458 +95,101 @@ func mustGetMcConfigPath() string {
|
||||
return path
|
||||
}
|
||||
|
||||
// getMcConfig - reads configuration file and returns config
|
||||
func getMcConfig() (*configV5, *probe.Error) {
|
||||
if !isMcConfigExists() {
|
||||
return nil, errInvalidArgument().Trace()
|
||||
}
|
||||
|
||||
configFile, err := getMcConfigPath()
|
||||
if err != nil {
|
||||
return nil, err.Trace()
|
||||
}
|
||||
|
||||
// Cached in private global variable.
|
||||
if v := cache.Get(); v != nil { // Use previously cached config.
|
||||
return v.(quick.Config).Data().(*configV5), nil
|
||||
}
|
||||
|
||||
conf := new(configV5)
|
||||
conf.Version = globalMCConfigVersion
|
||||
qconf, err := quick.New(conf)
|
||||
if err != nil {
|
||||
return nil, err.Trace()
|
||||
}
|
||||
|
||||
err = qconf.Load(configFile)
|
||||
if err != nil {
|
||||
return nil, err.Trace()
|
||||
}
|
||||
cache.Put(qconf)
|
||||
return qconf.Data().(*configV5), nil
|
||||
// newMcConfig - initializes a new version '6' config.
|
||||
func newMcConfig() *configV7 {
|
||||
cfg := newConfigV7()
|
||||
cfg.loadDefaults()
|
||||
return cfg
|
||||
}
|
||||
|
||||
// mustGetMcConfig - reads configuration file and returns configs, exits on error
|
||||
func mustGetMcConfig() *configV5 {
|
||||
config, err := getMcConfig()
|
||||
fatalIf(err.Trace(), "Unable to read mc configuration.")
|
||||
return config
|
||||
// loadMcConfigCached - returns loadMcConfig with a closure for config cache.
|
||||
func loadMcConfigFactory() func() (*configV7, *probe.Error) {
|
||||
// Load once and cache in a closure.
|
||||
cfgCache, err := loadConfigV7()
|
||||
|
||||
// loadMcConfig - reads configuration file and returns config.
|
||||
return func() (*configV7, *probe.Error) {
|
||||
return cfgCache, err
|
||||
}
|
||||
}
|
||||
|
||||
// isMcConfigExists xreturns err if config doesn't exist
|
||||
var loadMcConfig = loadMcConfigFactory()
|
||||
|
||||
// saveMcConfig - saves configuration file and returns error if any.
|
||||
func saveMcConfig(config *configV7) *probe.Error {
|
||||
if config == nil {
|
||||
return errInvalidArgument().Trace()
|
||||
}
|
||||
|
||||
err := createMcConfigDir()
|
||||
if err != nil {
|
||||
return err.Trace(mustGetMcConfigDir())
|
||||
}
|
||||
|
||||
// Save the config.
|
||||
if err := saveConfigV7(config); err != nil {
|
||||
return err.Trace(mustGetMcConfigPath())
|
||||
}
|
||||
|
||||
// Refresh the config cache.
|
||||
loadMcConfig = loadMcConfigFactory()
|
||||
return nil
|
||||
}
|
||||
|
||||
// isMcConfigExists returns err if config doesn't exist.
|
||||
func isMcConfigExists() bool {
|
||||
configFile, err := getMcConfigPath()
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
if _, err := os.Stat(configFile); err != nil {
|
||||
if _, e := os.Stat(configFile); e != nil {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// writeConfig - write configuration file
|
||||
func writeConfig(config quick.Config) *probe.Error {
|
||||
if config == nil {
|
||||
return errInvalidArgument().Trace()
|
||||
}
|
||||
err := createMcConfigDir()
|
||||
// isValidAlias - Check if alias valid.
|
||||
func isValidAlias(alias string) bool {
|
||||
return regexp.MustCompile("^[a-zA-Z][a-zA-Z0-9-]+$").MatchString(alias)
|
||||
}
|
||||
|
||||
// getHostConfig retrieves host specific configuration such as access keys, signature type.
|
||||
func getHostConfig(alias string) (*hostConfigV7, *probe.Error) {
|
||||
mcCfg, err := loadMcConfig()
|
||||
if err != nil {
|
||||
return err.Trace()
|
||||
return nil, err.Trace(alias)
|
||||
}
|
||||
configPath, err := getMcConfigPath()
|
||||
if err != nil {
|
||||
return err.Trace()
|
||||
|
||||
// if host is exact return quickly.
|
||||
if _, ok := mcCfg.Hosts[alias]; ok {
|
||||
hostCfg := mcCfg.Hosts[alias]
|
||||
return &hostCfg, nil
|
||||
}
|
||||
if err := config.Save(configPath); err != nil {
|
||||
return err.Trace()
|
||||
}
|
||||
return nil
|
||||
|
||||
// return error if cannot be matched.
|
||||
return nil, errNoMatchingHost(alias).Trace(alias)
|
||||
}
|
||||
|
||||
func migrateConfig() {
|
||||
// Migrate config V1 to V101
|
||||
migrateConfigV1ToV101()
|
||||
// Migrate config V101 to V2
|
||||
migrateConfigV101ToV2()
|
||||
// Migrate config V2 to V3
|
||||
migrateConfigV2ToV3()
|
||||
// Migrate config V3 to V4
|
||||
migrateConfigV3ToV4()
|
||||
// Migrate config V4 to V5
|
||||
migrateConfigV4ToV5()
|
||||
// mustGetHostConfig retrieves host specific configuration such as access keys, signature type.
|
||||
func mustGetHostConfig(alias string) *hostConfigV7 {
|
||||
hostCfg, _ := getHostConfig(alias)
|
||||
return hostCfg
|
||||
}
|
||||
|
||||
func fixConfig() {
|
||||
// Fix config V3
|
||||
fixConfigV3()
|
||||
// expandAlias expands aliased URL if any match is found, returns as is otherwise.
|
||||
func expandAlias(aliasedURL string) (alias string, urlStr string, hostCfg *hostConfigV7, err *probe.Error) {
|
||||
// Extract alias from the URL.
|
||||
alias, path := url2Alias(aliasedURL)
|
||||
|
||||
// Find the matching alias entry and expand the URL.
|
||||
if hostCfg = mustGetHostConfig(alias); hostCfg != nil {
|
||||
return alias, urlJoinPath(hostCfg.URL, path), hostCfg, nil
|
||||
}
|
||||
return "", aliasedURL, nil, nil // No matching entry found. Return original URL as is.
|
||||
}
|
||||
|
||||
// Migrate from config version ‘1.0’ to ‘1.0.1’
|
||||
func migrateConfigV1ToV101() {
|
||||
if !isMcConfigExists() {
|
||||
return
|
||||
}
|
||||
mcConfigV1, err := quick.Load(mustGetMcConfigPath(), newConfigV1())
|
||||
fatalIf(err.Trace(), "Unable to load config version ‘1’.")
|
||||
|
||||
// update to newer version
|
||||
if mcConfigV1.Version() == "1.0.0" {
|
||||
confV101 := mcConfigV1.Data().(*configV1)
|
||||
confV101.Version = "1.0.1"
|
||||
|
||||
localHostConfig := struct {
|
||||
AccessKeyID string
|
||||
SecretAccessKey string
|
||||
}{}
|
||||
localHostConfig.AccessKeyID = ""
|
||||
localHostConfig.SecretAccessKey = ""
|
||||
|
||||
s3HostConf := struct {
|
||||
AccessKeyID string
|
||||
SecretAccessKey string
|
||||
}{}
|
||||
s3HostConf.AccessKeyID = globalAccessKeyID
|
||||
s3HostConf.SecretAccessKey = globalSecretAccessKey
|
||||
|
||||
if _, ok := confV101.Hosts["localhost:*"]; !ok {
|
||||
confV101.Hosts["localhost:*"] = localHostConfig
|
||||
}
|
||||
if _, ok := confV101.Hosts["127.0.0.1:*"]; !ok {
|
||||
confV101.Hosts["127.0.0.1:*"] = localHostConfig
|
||||
}
|
||||
if _, ok := confV101.Hosts["*.s3*.amazonaws.com"]; !ok {
|
||||
confV101.Hosts["*.s3*.amazonaws.com"] = s3HostConf
|
||||
}
|
||||
|
||||
mcNewConfigV101, err := quick.New(confV101)
|
||||
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘1.0.1’.")
|
||||
|
||||
err = mcNewConfigV101.Save(mustGetMcConfigPath())
|
||||
fatalIf(err.Trace(), "Unable to save config version ‘1.0.1’.")
|
||||
|
||||
console.Infof("Successfully migrated %s from version ‘1.0.0’ to version ‘1.0.1’.\n", mustGetMcConfigPath())
|
||||
}
|
||||
}
|
||||
|
||||
// Migrate from config ‘1.0.1’ to ‘2’
|
||||
func migrateConfigV101ToV2() {
|
||||
if !isMcConfigExists() {
|
||||
return
|
||||
}
|
||||
mcConfigV101, err := quick.Load(mustGetMcConfigPath(), newConfigV101())
|
||||
fatalIf(err.Trace(), "Unable to load config version ‘1.0.1’.")
|
||||
|
||||
// update to newer version
|
||||
if mcConfigV101.Version() == "1.0.1" {
|
||||
confV2 := mcConfigV101.Data().(*configV101)
|
||||
confV2.Version = "2"
|
||||
|
||||
mcNewConfigV2, err := quick.New(confV2)
|
||||
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘2’.")
|
||||
|
||||
err = mcNewConfigV2.Save(mustGetMcConfigPath())
|
||||
fatalIf(err.Trace(), "Unable to save config version ‘2’.")
|
||||
|
||||
console.Infof("Successfully migrated %s from version ‘1.0.1’ to version ‘2’.\n", mustGetMcConfigPath())
|
||||
}
|
||||
}
|
||||
|
||||
// Migrate from config ‘2’ to ‘3’
|
||||
func migrateConfigV2ToV3() {
|
||||
if !isMcConfigExists() {
|
||||
return
|
||||
}
|
||||
mcConfigV2, err := quick.Load(mustGetMcConfigPath(), newConfigV2())
|
||||
fatalIf(err.Trace(), "Unable to load mc config V2.")
|
||||
|
||||
// update to newer version
|
||||
if mcConfigV2.Version() == "2" {
|
||||
confV3 := new(configV3)
|
||||
confV3.Aliases = mcConfigV2.Data().(*configV2).Aliases
|
||||
confV3.Hosts = make(map[string]struct {
|
||||
AccessKeyID string `json:"access-key-id"`
|
||||
SecretAccessKey string `json:"secret-access-key"`
|
||||
})
|
||||
for host, hostConf := range mcConfigV2.Data().(*configV2).Hosts {
|
||||
newHostConf := struct {
|
||||
AccessKeyID string `json:"access-key-id"`
|
||||
SecretAccessKey string `json:"secret-access-key"`
|
||||
}{}
|
||||
newHostConf.AccessKeyID = hostConf.AccessKeyID
|
||||
newHostConf.SecretAccessKey = hostConf.SecretAccessKey
|
||||
confV3.Hosts[host] = newHostConf
|
||||
}
|
||||
confV3.Version = "3"
|
||||
|
||||
mcNewConfigV3, err := quick.New(confV3)
|
||||
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘3’.")
|
||||
|
||||
err = mcNewConfigV3.Save(mustGetMcConfigPath())
|
||||
fatalIf(err.Trace(), "Unable to save config version ‘3’.")
|
||||
|
||||
console.Infof("Successfully migrated %s from version ‘2’ to version ‘3’.\n", mustGetMcConfigPath())
|
||||
}
|
||||
}
|
||||
|
||||
// Migrate from config version ‘3’ to ‘4’
|
||||
func migrateConfigV3ToV4() {
|
||||
if !isMcConfigExists() {
|
||||
return
|
||||
}
|
||||
mcConfigV3, err := quick.Load(mustGetMcConfigPath(), newConfigV3())
|
||||
fatalIf(err.Trace(), "Unable to load mc config V2.")
|
||||
|
||||
// update to newer version
|
||||
if mcConfigV3.Version() == "3" {
|
||||
confV4 := new(configV4)
|
||||
confV4.Aliases = mcConfigV3.Data().(*configV3).Aliases
|
||||
confV4.Hosts = make(map[string]struct {
|
||||
AccessKeyID string `json:"accessKeyId"`
|
||||
SecretAccessKey string `json:"secretAccessKey"`
|
||||
Signature string `json:"signature"`
|
||||
})
|
||||
for host, hostConf := range mcConfigV3.Data().(*configV3).Hosts {
|
||||
confV4.Hosts[host] = struct {
|
||||
AccessKeyID string `json:"accessKeyId"`
|
||||
SecretAccessKey string `json:"secretAccessKey"`
|
||||
Signature string `json:"signature"`
|
||||
}{
|
||||
AccessKeyID: hostConf.AccessKeyID,
|
||||
SecretAccessKey: hostConf.SecretAccessKey,
|
||||
Signature: "v4",
|
||||
}
|
||||
}
|
||||
confV4.Version = "4"
|
||||
|
||||
mcNewConfigV4, err := quick.New(confV4)
|
||||
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘4’.")
|
||||
|
||||
err = mcNewConfigV4.Save(mustGetMcConfigPath())
|
||||
fatalIf(err.Trace(), "Unable to save config version ‘4’.")
|
||||
|
||||
console.Infof("Successfully migrated %s from version ‘3’ to version ‘4’.\n", mustGetMcConfigPath())
|
||||
}
|
||||
}
|
||||
|
||||
// Migrate config version ‘4’ to ‘5’
|
||||
func migrateConfigV4ToV5() {
|
||||
if !isMcConfigExists() {
|
||||
return
|
||||
}
|
||||
mcConfigV4, err := quick.Load(mustGetMcConfigPath(), newConfigV4())
|
||||
fatalIf(err.Trace(), "Unable to load mc config V2.")
|
||||
|
||||
// update to newer version
|
||||
if mcConfigV4.Version() == "4" {
|
||||
confV5 := new(configV5)
|
||||
confV5.Aliases = mcConfigV4.Data().(*configV4).Aliases
|
||||
confV5.Hosts = make(map[string]hostConfig)
|
||||
for host, hostConf := range mcConfigV4.Data().(*configV4).Hosts {
|
||||
confV5.Hosts[host] = hostConfig{
|
||||
AccessKeyID: hostConf.AccessKeyID,
|
||||
SecretAccessKey: hostConf.SecretAccessKey,
|
||||
API: "S3v4",
|
||||
}
|
||||
}
|
||||
confV5.Version = globalMCConfigVersion
|
||||
|
||||
mcNewConfigV5, err := quick.New(confV5)
|
||||
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘5’.")
|
||||
|
||||
err = mcNewConfigV5.Save(mustGetMcConfigPath())
|
||||
fatalIf(err.Trace(), "Unable to save config version ‘5’.")
|
||||
|
||||
console.Infof("Successfully migrated %s from version ‘4’ to version ‘5’.\n", mustGetMcConfigPath())
|
||||
}
|
||||
}
|
||||
|
||||
// Fix config version ‘3’, by removing broken struct tags
|
||||
func fixConfigV3() {
|
||||
if !isMcConfigExists() {
|
||||
return
|
||||
}
|
||||
// brokenConfigV3 broken config between version 3
|
||||
type brokenConfigV3 struct {
|
||||
Version string
|
||||
ACL string
|
||||
Access string
|
||||
Aliases map[string]string
|
||||
Hosts map[string]struct {
|
||||
AccessKeyID string
|
||||
SecretAccessKey string
|
||||
}
|
||||
}
|
||||
conf := new(brokenConfigV3)
|
||||
conf.Aliases = make(map[string]string)
|
||||
conf.Hosts = make(map[string]struct {
|
||||
AccessKeyID string
|
||||
SecretAccessKey string
|
||||
})
|
||||
|
||||
mcConfigV3, err := quick.Load(mustGetMcConfigPath(), conf)
|
||||
fatalIf(err.Trace(), "Unable to load config.")
|
||||
|
||||
// Update to newer version
|
||||
if len(mcConfigV3.Data().(*brokenConfigV3).Aliases) != 0 || mcConfigV3.Data().(*brokenConfigV3).ACL != "" || mcConfigV3.Data().(*brokenConfigV3).Access != "" && mcConfigV3.Version() == "3" {
|
||||
confV3 := new(configV3)
|
||||
confV3.Aliases = mcConfigV3.Data().(*brokenConfigV3).Aliases
|
||||
confV3.Hosts = make(map[string]struct {
|
||||
AccessKeyID string `json:"access-key-id"`
|
||||
SecretAccessKey string `json:"secret-access-key"`
|
||||
})
|
||||
for host, hostConf := range mcConfigV3.Data().(*brokenConfigV3).Hosts {
|
||||
newHostConf := struct {
|
||||
AccessKeyID string `json:"access-key-id"`
|
||||
SecretAccessKey string `json:"secret-access-key"`
|
||||
}{}
|
||||
newHostConf.AccessKeyID = hostConf.AccessKeyID
|
||||
newHostConf.SecretAccessKey = hostConf.SecretAccessKey
|
||||
confV3.Hosts[host] = newHostConf
|
||||
}
|
||||
confV3.Version = globalMCConfigVersion
|
||||
|
||||
mcNewConfigV3, err := quick.New(confV3)
|
||||
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘3’.")
|
||||
|
||||
err = mcNewConfigV3.Save(mustGetMcConfigPath())
|
||||
fatalIf(err.Trace(), "Unable to save config version ‘3’.")
|
||||
|
||||
console.Infof("Successfully fixed %s broken config for version ‘3’.\n", mustGetMcConfigPath())
|
||||
}
|
||||
}
|
||||
|
||||
// newConfigV1() - get new config version 1.0.0
|
||||
func newConfigV1() *configV1 {
|
||||
conf := new(configV1)
|
||||
conf.Version = "1.0.0"
|
||||
// make sure to allocate map's otherwise Golang
|
||||
// exits silently without providing any errors
|
||||
conf.Hosts = make(map[string]struct {
|
||||
AccessKeyID string
|
||||
SecretAccessKey string
|
||||
})
|
||||
conf.Aliases = make(map[string]string)
|
||||
return conf
|
||||
}
|
||||
|
||||
// newConfigV101() - get new config version 1.0.1
|
||||
func newConfigV101() *configV101 {
|
||||
conf := new(configV101)
|
||||
conf.Version = "1.0.1"
|
||||
// make sure to allocate map's otherwise Golang
|
||||
// exits silently without providing any errors
|
||||
conf.Hosts = make(map[string]struct {
|
||||
AccessKeyID string
|
||||
SecretAccessKey string
|
||||
})
|
||||
conf.Aliases = make(map[string]string)
|
||||
return conf
|
||||
}
|
||||
|
||||
// newConfigV2() - get new config version 2
|
||||
func newConfigV2() *configV2 {
|
||||
conf := new(configV2)
|
||||
conf.Version = "2"
|
||||
// make sure to allocate map's otherwise Golang
|
||||
// exits silently without providing any errors
|
||||
conf.Hosts = make(map[string]struct {
|
||||
AccessKeyID string
|
||||
SecretAccessKey string
|
||||
})
|
||||
conf.Aliases = make(map[string]string)
|
||||
return conf
|
||||
}
|
||||
|
||||
// newConfigV3 - get new config version 3
|
||||
func newConfigV3() *configV3 {
|
||||
conf := new(configV3)
|
||||
conf.Version = "3"
|
||||
// make sure to allocate map's otherwise Golang
|
||||
// exits silently without providing any errors
|
||||
conf.Hosts = make(map[string]struct {
|
||||
AccessKeyID string `json:"access-key-id"`
|
||||
SecretAccessKey string `json:"secret-access-key"`
|
||||
})
|
||||
conf.Aliases = make(map[string]string)
|
||||
return conf
|
||||
}
|
||||
|
||||
func newConfigV4() *configV4 {
|
||||
conf := new(configV4)
|
||||
conf.Version = "4"
|
||||
// make sure to allocate map's otherwise Golang
|
||||
// exits silently without providing any errors
|
||||
conf.Hosts = make(map[string]struct {
|
||||
AccessKeyID string `json:"accessKeyId"`
|
||||
SecretAccessKey string `json:"secretAccessKey"`
|
||||
Signature string `json:"signature"`
|
||||
})
|
||||
conf.Aliases = make(map[string]string)
|
||||
return conf
|
||||
}
|
||||
|
||||
func newConfigV5() *configV5 {
|
||||
conf := new(configV5)
|
||||
conf.Version = globalMCConfigVersion
|
||||
// make sure to allocate map's otherwise Golang
|
||||
// exits silently without providing any errors
|
||||
conf.Hosts = make(map[string]hostConfig)
|
||||
conf.Aliases = make(map[string]string)
|
||||
|
||||
localHostConfig := hostConfig{
|
||||
AccessKeyID: "",
|
||||
SecretAccessKey: "",
|
||||
API: "S3v4",
|
||||
}
|
||||
|
||||
s3HostConf := hostConfig{
|
||||
AccessKeyID: globalAccessKeyID,
|
||||
SecretAccessKey: globalSecretAccessKey,
|
||||
API: "S3v4",
|
||||
}
|
||||
|
||||
// Your example host config
|
||||
exampleHostConf := hostConfig{
|
||||
AccessKeyID: globalAccessKeyID,
|
||||
SecretAccessKey: globalSecretAccessKey,
|
||||
API: "S3v4",
|
||||
}
|
||||
|
||||
playHostConfig := hostConfig{
|
||||
AccessKeyID: "",
|
||||
SecretAccessKey: "",
|
||||
API: "S3v4",
|
||||
}
|
||||
|
||||
dlHostConfig := hostConfig{
|
||||
AccessKeyID: "",
|
||||
SecretAccessKey: "",
|
||||
API: "S3v4",
|
||||
}
|
||||
|
||||
conf.Hosts[globalExampleHostURL] = exampleHostConf
|
||||
conf.Hosts["localhost:*"] = localHostConfig
|
||||
conf.Hosts["127.0.0.1:*"] = localHostConfig
|
||||
conf.Hosts["s3*.amazonaws.com"] = s3HostConf
|
||||
conf.Hosts["*.s3*.amazonaws.com"] = s3HostConf
|
||||
conf.Hosts["play.minio.io:9000"] = playHostConfig
|
||||
conf.Hosts["dl.minio.io:9000"] = dlHostConfig
|
||||
|
||||
aliases := make(map[string]string)
|
||||
aliases["s3"] = "https://s3.amazonaws.com"
|
||||
aliases["play"] = "https://play.minio.io:9000"
|
||||
aliases["dl"] = "https://dl.minio.io:9000"
|
||||
aliases["localhost"] = "http://localhost:9000"
|
||||
conf.Aliases = aliases
|
||||
return conf
|
||||
}
|
||||
|
||||
// newConfig - get new config interface
|
||||
func newConfig() (config quick.Config, err *probe.Error) {
|
||||
config, err = quick.New(newConfigV5())
|
||||
if err != nil {
|
||||
return nil, err.Trace()
|
||||
}
|
||||
return config, nil
|
||||
// mustExpandAlias expands aliased URL if any match is found, returns as is otherwise.
|
||||
func mustExpandAlias(aliasedURL string) (alias string, urlStr string, hostCfg *hostConfigV7) {
|
||||
alias, urlStr, hostCfg, _ = expandAlias(aliasedURL)
|
||||
return alias, urlStr, hostCfg
|
||||
}
|
||||
|
||||
@@ -1,90 +0,0 @@
|
||||
/*
|
||||
* Minio Client (C) 2014, 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
|
||||
"github.com/minio/mc/pkg/console"
|
||||
. "gopkg.in/check.v1"
|
||||
)
|
||||
|
||||
func (s *TestSuite) TestConfigVersionContext(c *C) {
|
||||
console.IsExited = false
|
||||
err := app.Run([]string{os.Args[0], "config", "version"})
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(console.IsExited, Equals, false)
|
||||
console.IsExited = false
|
||||
}
|
||||
|
||||
func (s *TestSuite) TestConfigAliasContext(c *C) {
|
||||
console.IsExited = false
|
||||
|
||||
err := app.Run([]string{os.Args[0], "config", "alias", "add", "test", "htt://test.io"})
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(console.IsExited, Equals, true)
|
||||
|
||||
// reset back
|
||||
console.IsExited = false
|
||||
|
||||
err = app.Run([]string{os.Args[0], "config", "alias", "add", "new", "http://test.io"})
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(console.IsExited, Equals, false)
|
||||
|
||||
// reset back
|
||||
console.IsExited = false
|
||||
}
|
||||
|
||||
func (s *TestSuite) TestConfigHostContext(c *C) {
|
||||
console.IsExited = false
|
||||
|
||||
err := app.Run([]string{os.Args[0], "config", "host", "add", "*test.io", "invalid", "invalid"})
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(console.IsExited, Equals, true)
|
||||
|
||||
// reset back
|
||||
console.IsExited = false
|
||||
|
||||
err = app.Run([]string{os.Args[0],
|
||||
"config",
|
||||
"host",
|
||||
"add",
|
||||
"*my-example.com",
|
||||
"AKIKJAA5BMMU2RHO6IBB",
|
||||
"V7f1CCwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr9",
|
||||
"S3v2",
|
||||
})
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(console.IsExited, Equals, false)
|
||||
|
||||
// reset back
|
||||
console.IsExited = false
|
||||
|
||||
err = app.Run([]string{os.Args[0], "config", "host", "remove", "*my-example.com"})
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(console.IsExited, Equals, false)
|
||||
|
||||
// reset back
|
||||
console.IsExited = false
|
||||
|
||||
err = app.Run([]string{os.Args[0], "config", "host", "remove", "dl.minio.io:9000"})
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(console.IsExited, Equals, true)
|
||||
|
||||
// reset back
|
||||
console.IsExited = false
|
||||
}
|
||||
+222
-163
@@ -21,183 +21,226 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"net"
|
||||
"os"
|
||||
"runtime"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/client"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/pb"
|
||||
)
|
||||
|
||||
// Copy files and folders from many sources to a single destination.
|
||||
// cp command flags.
|
||||
var (
|
||||
cpFlags = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "help, h",
|
||||
Usage: "Help of cp.",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "recursive, r",
|
||||
Usage: "Copy recursively.",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
// Copy command.
|
||||
var cpCmd = cli.Command{
|
||||
Name: "cp",
|
||||
Usage: "Copy files and folders from many sources to a single destination.",
|
||||
Usage: "Copy one or more objects to a target.",
|
||||
Action: mainCopy,
|
||||
Flags: append(cpFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
mc {{.Name}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
mc {{.Name}} SOURCE [SOURCE...] TARGET
|
||||
mc {{.Name}} [FLAGS] SOURCE [SOURCE...] TARGET
|
||||
|
||||
FLAGS:
|
||||
{{range .Flags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Copy list of objects from local file system to Amazon S3 cloud storage.
|
||||
$ mc {{.Name}} Music/*.ogg https://s3.amazonaws.com/jukebox/
|
||||
1. Copy a list of objects from local file system to Amazon S3 cloud storage.
|
||||
$ mc {{.Name}} Music/*.ogg s3/jukebox/
|
||||
|
||||
2. Copy a bucket recursively from Minio cloud storage to Amazon S3 cloud storage.
|
||||
$ mc {{.Name}} https://play.minio.io:9000/photos/burningman2011... https://s3.amazonaws.com/private-photos/burningman/
|
||||
2. Copy a folder recursively from Minio cloud storage to Amazon S3 cloud storage.
|
||||
$ mc {{.Name}} --recursive play/mybucket/burningman2011/ s3/mybucket/
|
||||
|
||||
3. Copy multiple local folders recursively to Minio cloud storage.
|
||||
$ mc {{.Name}} backup/2014/... backup/2015/... https://play.minio.io:9000/archive/
|
||||
$ mc {{.Name}} --recursive backup/2014/ backup/2015/ play/archive/
|
||||
|
||||
4. Copy a bucket recursively from aliased Amazon S3 cloud storage to local filesystem on Windows.
|
||||
$ mc {{.Name}} s3/documents/2014/... C:\backup\2014
|
||||
$ mc {{.Name}} --recursive s3\documents\2014\ C:\Backups\2014
|
||||
|
||||
5. Copy an object of non english characters to Amazon S3 cloud storage.
|
||||
$ mc {{.Name}} 本語 s3/andoria/本語
|
||||
5. Copy an object with name containing unicode characters to Amazon S3 cloud storage.
|
||||
$ mc {{.Name}} 本語 s3/andoria/
|
||||
|
||||
6. Copy local folder with space characters to Amazon S3 cloud storage.
|
||||
$ mc {{.Name}} 'workdir/documents/May 2014...' s3/miniocloud
|
||||
6. Copy a local folder with space separated characters to Amazon S3 cloud storage.
|
||||
$ mc {{.Name}} --recursive 'workdir/documents/May 2014/' s3/miniocloud
|
||||
`,
|
||||
}
|
||||
|
||||
// CopyMessage container for file copy messages
|
||||
type CopyMessage struct {
|
||||
// copyMessage container for file copy messages
|
||||
type copyMessage struct {
|
||||
Status string `json:"status"`
|
||||
Source string `json:"source"`
|
||||
Target string `json:"target"`
|
||||
Length int64 `json:"length"`
|
||||
}
|
||||
|
||||
// String colorized copy message
|
||||
func (c CopyMessage) String() string {
|
||||
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 {
|
||||
copyMessageBytes, err := json.Marshal(c)
|
||||
fatalIf(probe.NewError(err), "Failed to marshal 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)
|
||||
}
|
||||
|
||||
// doCopy - Copy a singe file from source to destination
|
||||
func doCopy(cpURLs copyURLs, bar *barSend, cpQueue <-chan bool, wg *sync.WaitGroup, statusCh chan<- copyURLs) {
|
||||
defer wg.Done() // Notify that this copy routine is done.
|
||||
defer func() {
|
||||
<-cpQueue
|
||||
}()
|
||||
// copyStatMessage container for copy accounting message
|
||||
type copyStatMessage struct {
|
||||
Total int64
|
||||
Transferred int64
|
||||
Speed float64
|
||||
}
|
||||
|
||||
if cpURLs.Error != nil {
|
||||
cpURLs.Error.Trace()
|
||||
statusCh <- cpURLs
|
||||
return
|
||||
}
|
||||
|
||||
if !globalQuietFlag && !globalJSONFlag {
|
||||
bar.SetCaption(cpURLs.SourceContent.Name + ": ")
|
||||
}
|
||||
|
||||
reader, length, err := getSource(cpURLs.SourceContent.Name)
|
||||
if err != nil {
|
||||
if !globalQuietFlag && !globalJSONFlag {
|
||||
bar.ErrorGet(length)
|
||||
}
|
||||
cpURLs.Error = err.Trace()
|
||||
statusCh <- cpURLs
|
||||
return
|
||||
}
|
||||
|
||||
var newReader io.ReadCloser
|
||||
if globalQuietFlag || globalJSONFlag {
|
||||
Prints("%s\n", CopyMessage{
|
||||
Source: cpURLs.SourceContent.Name,
|
||||
Target: cpURLs.TargetContent.Name,
|
||||
Length: cpURLs.SourceContent.Size,
|
||||
})
|
||||
newReader = reader
|
||||
// copyStatMessage copy accounting message
|
||||
func (c copyStatMessage) String() string {
|
||||
speedBox := pb.FormatBytes(int64(c.Speed))
|
||||
if speedBox == "" {
|
||||
speedBox = "0 MB"
|
||||
} else {
|
||||
// set up progress
|
||||
newReader = bar.NewProxyReader(reader)
|
||||
speedBox = speedBox + "/s"
|
||||
}
|
||||
defer newReader.Close()
|
||||
message := fmt.Sprintf("Total: %s, Transferred: %s, Speed: %s", pb.FormatBytes(c.Total),
|
||||
pb.FormatBytes(c.Transferred), speedBox)
|
||||
return message
|
||||
}
|
||||
|
||||
if err := putTarget(cpURLs.TargetContent.Name, length, newReader); err != nil {
|
||||
if !globalQuietFlag && !globalJSONFlag {
|
||||
bar.ErrorPut(length)
|
||||
// doCopy - Copy a singe file from source to destination
|
||||
func doCopy(cpURLs copyURLs, progressReader *progressBar, accountingReader *accounter) copyURLs {
|
||||
if cpURLs.Error != nil {
|
||||
cpURLs.Error = cpURLs.Error.Trace()
|
||||
return cpURLs
|
||||
}
|
||||
|
||||
if !globalQuiet && !globalJSON {
|
||||
progressReader = progressReader.SetCaption(cpURLs.SourceContent.URL.String() + ": ")
|
||||
}
|
||||
|
||||
sourceAlias := cpURLs.SourceAlias
|
||||
sourceURL := cpURLs.SourceContent.URL
|
||||
targetAlias := cpURLs.TargetAlias
|
||||
targetURL := cpURLs.TargetContent.URL
|
||||
length := cpURLs.SourceContent.Size
|
||||
|
||||
reader, err := getSourceStreamFromAlias(sourceAlias, sourceURL.String())
|
||||
if err != nil {
|
||||
cpURLs.Error = err.Trace(sourceURL.String())
|
||||
return cpURLs
|
||||
}
|
||||
|
||||
var progress io.Reader
|
||||
if globalQuiet || globalJSON {
|
||||
sourcePath := filepath.ToSlash(filepath.Join(sourceAlias, sourceURL.Path))
|
||||
targetPath := filepath.ToSlash(filepath.Join(targetAlias, targetURL.Path))
|
||||
printMsg(copyMessage{
|
||||
Source: sourcePath,
|
||||
Target: targetPath,
|
||||
})
|
||||
// Proxy reader to accounting reader only during quiet mode.
|
||||
if globalQuiet || globalJSON {
|
||||
progress = accountingReader
|
||||
}
|
||||
cpURLs.Error = err.Trace()
|
||||
statusCh <- cpURLs
|
||||
return
|
||||
} else {
|
||||
// Set up progress reader.
|
||||
progress = progressReader.ProgressBar
|
||||
}
|
||||
_, err = putTargetStreamFromAlias(targetAlias, targetURL.String(), reader, length, progress)
|
||||
if err != nil {
|
||||
cpURLs.Error = err.Trace(targetURL.String())
|
||||
return cpURLs
|
||||
}
|
||||
|
||||
cpURLs.Error = nil // just for safety
|
||||
statusCh <- cpURLs
|
||||
return cpURLs
|
||||
}
|
||||
|
||||
// doCopyFake - Perform a fake copy to update the progress bar appropriately.
|
||||
func doCopyFake(cURLs copyURLs, bar *barSend) {
|
||||
if !globalQuietFlag && !globalJSONFlag {
|
||||
bar.Progress(cURLs.SourceContent.Size)
|
||||
func doCopyFake(cpURLs copyURLs, progressReader *progressBar) copyURLs {
|
||||
if !globalQuiet && !globalJSON {
|
||||
progressReader.ProgressBar.Add64(cpURLs.SourceContent.Size)
|
||||
}
|
||||
return cpURLs
|
||||
}
|
||||
|
||||
// doPrepareCopyURLs scans the source URL and prepares a list of objects for copying.
|
||||
func doPrepareCopyURLs(session *sessionV2, trapCh <-chan bool) {
|
||||
func doPrepareCopyURLs(session *sessionV6, trapCh <-chan bool) {
|
||||
// Separate source and target. 'cp' can take only one target,
|
||||
// but any number of sources, even the recursive URLs mixed in-between.
|
||||
// but any number of sources.
|
||||
sourceURLs := session.Header.CommandArgs[:len(session.Header.CommandArgs)-1]
|
||||
targetURL := session.Header.CommandArgs[len(session.Header.CommandArgs)-1] // Last one is target
|
||||
|
||||
var totalBytes int64
|
||||
var totalObjects int
|
||||
|
||||
// Access recursive flag inside the session header.
|
||||
isRecursive := session.Header.CommandBoolFlags["recursive"]
|
||||
|
||||
// Create a session data file to store the processed URLs.
|
||||
dataFP := session.NewDataWriter()
|
||||
|
||||
var scanBar scanBarFunc
|
||||
if !globalQuietFlag && !globalJSONFlag { // set up progress bar
|
||||
if !globalQuiet && !globalJSON { // set up progress bar
|
||||
scanBar = scanBarFactory()
|
||||
}
|
||||
|
||||
URLsCh := prepareCopyURLs(sourceURLs, targetURL)
|
||||
URLsCh := prepareCopyURLs(sourceURLs, targetURL, isRecursive)
|
||||
done := false
|
||||
|
||||
for done == false {
|
||||
select {
|
||||
case cpURLs, ok := <-URLsCh:
|
||||
if !ok { // Done with URL prepration
|
||||
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 !globalQuietFlag && !globalJSONFlag {
|
||||
if !globalQuiet && !globalJSON {
|
||||
console.Eraseline()
|
||||
}
|
||||
errorIf(cpURLs.Error.Trace(), "Unable to prepare URL for copying.")
|
||||
if strings.Contains(cpURLs.Error.ToGoError().Error(), " is a folder.") {
|
||||
errorIf(cpURLs.Error.Trace(), "Folder cannot be copied. Please use ‘...’ suffix.")
|
||||
} else {
|
||||
errorIf(cpURLs.Error.Trace(), "Unable to prepare URL for copying.")
|
||||
}
|
||||
break
|
||||
}
|
||||
|
||||
jsonData, err := json.Marshal(cpURLs)
|
||||
if err != nil {
|
||||
jsonData, e := json.Marshal(cpURLs)
|
||||
if e != nil {
|
||||
session.Delete()
|
||||
fatalIf(probe.NewError(err), "Unable to prepare URL for copying. Error in JSON marshaling.")
|
||||
fatalIf(probe.NewError(e), "Unable to prepare URL for copying. Error in JSON marshaling.")
|
||||
}
|
||||
fmt.Fprintln(dataFP, string(jsonData))
|
||||
if !globalQuietFlag && !globalJSONFlag {
|
||||
scanBar(cpURLs.SourceContent.Name)
|
||||
if !globalQuiet && !globalJSON {
|
||||
scanBar(cpURLs.SourceContent.URL.String())
|
||||
}
|
||||
|
||||
totalBytes += cpURLs.SourceContent.Size
|
||||
totalObjects++
|
||||
case <-trapCh:
|
||||
// Print in new line and adjust to top so that we don't print over the ongoing scan bar
|
||||
if !globalQuietFlag && !globalJSONFlag {
|
||||
if !globalQuiet && !globalJSON {
|
||||
console.Eraseline()
|
||||
}
|
||||
session.Delete() // If we are interrupted during the URL scanning, we drop the session.
|
||||
@@ -209,131 +252,147 @@ func doPrepareCopyURLs(session *sessionV2, trapCh <-chan bool) {
|
||||
session.Save()
|
||||
}
|
||||
|
||||
func doCopyCmdSession(session *sessionV2) {
|
||||
trapCh := signalTrap(os.Interrupt, os.Kill)
|
||||
func doCopySession(session *sessionV6) {
|
||||
trapCh := signalTrap(os.Interrupt, syscall.SIGTERM)
|
||||
|
||||
if !session.HasData() {
|
||||
doPrepareCopyURLs(session, trapCh)
|
||||
}
|
||||
|
||||
var bar barSend
|
||||
if !globalQuietFlag && !globalJSONFlag { // set up progress bar
|
||||
bar = newProgressBar()
|
||||
bar.Extend(session.Header.TotalBytes)
|
||||
}
|
||||
// Enable accounting reader by default.
|
||||
accntReader := newAccounter(session.Header.TotalBytes)
|
||||
|
||||
// Prepare URL scanner from session data file.
|
||||
scanner := bufio.NewScanner(session.NewDataReader())
|
||||
urlScanner := bufio.NewScanner(session.NewDataReader())
|
||||
// isCopied returns true if an object has been already copied
|
||||
// or not. This is useful when we resume from a session.
|
||||
isCopied := isCopiedFactory(session.Header.LastCopied)
|
||||
|
||||
wg := new(sync.WaitGroup)
|
||||
// Limit number of copy routines based on available CPU resources.
|
||||
cpQueue := make(chan bool, int(math.Max(float64(runtime.NumCPU())-1, 1)))
|
||||
defer close(cpQueue)
|
||||
// Enable progress bar reader only during default mode.
|
||||
var progressReader *progressBar
|
||||
if !globalQuiet && !globalJSON { // set up progress bar
|
||||
progressReader = newProgressBar(session.Header.TotalBytes)
|
||||
}
|
||||
|
||||
// Status channel for receiveing copy return status.
|
||||
statusCh := make(chan copyURLs)
|
||||
// Wait on status of doCopy() operation.
|
||||
var statusCh = make(chan copyURLs)
|
||||
|
||||
// Go routine to monitor doCopy status and signal traps.
|
||||
// Add a wait group.
|
||||
var wg = new(sync.WaitGroup)
|
||||
wg.Add(1)
|
||||
|
||||
// Go routine to monitor signal traps if any.
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for {
|
||||
select {
|
||||
case cpURLs, ok := <-statusCh: // Receive status.
|
||||
if !ok { // We are done here. Top level function has returned.
|
||||
if !globalQuietFlag && !globalJSONFlag {
|
||||
bar.Finish()
|
||||
}
|
||||
case <-trapCh:
|
||||
// Receive interrupt notification.
|
||||
if !globalQuiet && !globalJSON {
|
||||
console.Eraseline()
|
||||
}
|
||||
session.CloseAndDie()
|
||||
case cpURLs, ok := <-statusCh:
|
||||
// Status channel is closed, we should return.
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if cpURLs.Error == nil {
|
||||
session.Header.LastCopied = cpURLs.SourceContent.Name
|
||||
session.Header.LastCopied = cpURLs.SourceContent.URL.String()
|
||||
session.Save()
|
||||
} else {
|
||||
// Print in new line and adjust to top so that we don't print over the ongoing progress bar
|
||||
if !globalQuietFlag && !globalJSONFlag {
|
||||
// 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(), fmt.Sprintf("Failed to copy ‘%s’.", cpURLs.SourceContent.Name))
|
||||
// all the cases which are handled where session should be saved are contained in the following
|
||||
// switch case, we shouldn't be saving sessions for all errors since some errors might need to be
|
||||
// reported to user properly.
|
||||
//
|
||||
// All other critical cases should be handled properly gracefully
|
||||
// handle more errors and save the session.
|
||||
errorIf(cpURLs.Error.Trace(cpURLs.SourceContent.URL.String()),
|
||||
fmt.Sprintf("Failed to copy ‘%s’.", cpURLs.SourceContent.URL.String()))
|
||||
// For all non critical errors we can continue for the
|
||||
// remaining files.
|
||||
switch cpURLs.Error.ToGoError().(type) {
|
||||
case *net.OpError:
|
||||
gracefulSessionSave(session)
|
||||
case net.Error:
|
||||
gracefulSessionSave(session)
|
||||
// Handle this specifically for filesystem related
|
||||
// errors.
|
||||
case client.BrokenSymlink:
|
||||
continue
|
||||
case client.TooManyLevelsSymlink:
|
||||
continue
|
||||
case client.PathNotFound:
|
||||
continue
|
||||
case client.PathInsufficientPermission:
|
||||
continue
|
||||
case client.ObjectAlreadyExists:
|
||||
continue
|
||||
case client.BucketDoesNotExist:
|
||||
continue
|
||||
}
|
||||
// For critical errors we should exit. Session
|
||||
// can be resumed after the user figures out
|
||||
// the problem.
|
||||
session.CloseAndDie()
|
||||
}
|
||||
case <-trapCh: // Receive interrupt notification.
|
||||
if !globalQuietFlag && !globalJSONFlag {
|
||||
console.Eraseline()
|
||||
}
|
||||
gracefulSessionSave(session)
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
// Go routine to perform concurrently copying.
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
copyWg := new(sync.WaitGroup)
|
||||
defer close(statusCh)
|
||||
// Loop through all urls.
|
||||
for urlScanner.Scan() {
|
||||
var cpURLs copyURLs
|
||||
// Unmarshal copyURLs from each line.
|
||||
json.Unmarshal([]byte(urlScanner.Text()), &cpURLs)
|
||||
|
||||
for scanner.Scan() {
|
||||
var cpURLs copyURLs
|
||||
json.Unmarshal([]byte(scanner.Text()), &cpURLs)
|
||||
if isCopied(cpURLs.SourceContent.Name) {
|
||||
doCopyFake(cpURLs, &bar)
|
||||
} else {
|
||||
// Wait for other copy routines to
|
||||
// complete. We only have limited CPU
|
||||
// and network resources.
|
||||
cpQueue <- true
|
||||
// Account for each copy routines we start.
|
||||
copyWg.Add(1)
|
||||
// Do copying in background concurrently.
|
||||
go doCopy(cpURLs, &bar, cpQueue, copyWg, statusCh)
|
||||
}
|
||||
// Verify if previously copied, notify progress bar.
|
||||
if isCopied(cpURLs.SourceContent.URL.String()) {
|
||||
statusCh <- doCopyFake(cpURLs, progressReader)
|
||||
} else {
|
||||
statusCh <- doCopy(cpURLs, progressReader, accntReader)
|
||||
}
|
||||
copyWg.Wait()
|
||||
}()
|
||||
}
|
||||
|
||||
// Close the goroutine.
|
||||
close(statusCh)
|
||||
|
||||
// Wait for the goroutines to finish.
|
||||
wg.Wait()
|
||||
|
||||
if !globalQuiet && !globalJSON {
|
||||
if progressReader.ProgressBar.Total > 0 {
|
||||
progressReader.ProgressBar.Finish()
|
||||
}
|
||||
} else {
|
||||
accntStat := accntReader.Stat()
|
||||
cpStatMessage := copyStatMessage{
|
||||
Total: accntStat.Total,
|
||||
Transferred: accntStat.Transferred,
|
||||
Speed: accntStat.Speed,
|
||||
}
|
||||
console.Println(console.Colorize("Copy", cpStatMessage.String()))
|
||||
}
|
||||
}
|
||||
|
||||
// mainCopy is bound to sub-command
|
||||
// mainCopy is the entry point for cp command.
|
||||
func mainCopy(ctx *cli.Context) {
|
||||
// Set global flags from context.
|
||||
setGlobalsFromContext(ctx)
|
||||
|
||||
// check 'copy' cli arguments.
|
||||
checkCopySyntax(ctx)
|
||||
|
||||
console.SetCustomTheme(map[string]*color.Color{
|
||||
"Copy": color.New(color.FgGreen, color.Bold),
|
||||
})
|
||||
// Additional command speific theme customization.
|
||||
console.SetColor("Copy", color.New(color.FgGreen, color.Bold))
|
||||
|
||||
session := newSessionV2()
|
||||
session := newSessionV6()
|
||||
session.Header.CommandType = "cp"
|
||||
session.Header.CommandBoolFlags["recursive"] = ctx.Bool("recursive")
|
||||
|
||||
var e error
|
||||
session.Header.CommandType = "cp"
|
||||
session.Header.RootPath, e = os.Getwd()
|
||||
if e != nil {
|
||||
if session.Header.RootPath, e = os.Getwd(); e != nil {
|
||||
session.Delete()
|
||||
fatalIf(probe.NewError(e), "Unable to get current working folder.")
|
||||
}
|
||||
|
||||
// extract URLs.
|
||||
var err *probe.Error
|
||||
session.Header.CommandArgs, err = args2URLs(ctx.Args())
|
||||
if err != nil {
|
||||
session.Delete()
|
||||
fatalIf(err.Trace(), "One or more unknown URL types passed.")
|
||||
}
|
||||
|
||||
doCopyCmdSession(session)
|
||||
session.Header.CommandArgs = ctx.Args()
|
||||
doCopySession(session)
|
||||
session.Delete()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
/*
|
||||
* Minio Client (C) 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/client"
|
||||
)
|
||||
|
||||
func checkCopySyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) < 2 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "cp", 1) // last argument is exit code.
|
||||
}
|
||||
|
||||
// extract URLs.
|
||||
URLs := ctx.Args()
|
||||
if len(URLs) < 2 {
|
||||
fatalIf(errDummy().Trace(ctx.Args()...), fmt.Sprintf("Unable to parse source and target arguments."))
|
||||
}
|
||||
|
||||
srcURLs := URLs[:len(URLs)-1]
|
||||
tgtURL := URLs[len(URLs)-1]
|
||||
isRecursive := ctx.Bool("recursive")
|
||||
|
||||
/****** Generic Invalid Rules *******/
|
||||
// Check if bucket name is passed for URL type arguments.
|
||||
url := client.NewURL(tgtURL)
|
||||
if url.Host != "" {
|
||||
// This check is for type URL.
|
||||
if !isURLVirtualHostStyle(url.Host) {
|
||||
if url.Path == string(url.Separator) {
|
||||
fatalIf(errInvalidArgument().Trace(), fmt.Sprintf("Target ‘%s’ does not contain bucket name.", tgtURL))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Guess CopyURLsType based on source and target URLs.
|
||||
copyURLsType, err := guessCopyURLType(srcURLs, tgtURL, isRecursive)
|
||||
if err != nil {
|
||||
fatalIf(errInvalidArgument().Trace(), "Unable to guess the type of copy operation.")
|
||||
}
|
||||
switch copyURLsType {
|
||||
case copyURLsTypeA: // File -> File.
|
||||
checkCopySyntaxTypeA(srcURLs, tgtURL)
|
||||
case copyURLsTypeB: // File -> Folder.
|
||||
checkCopySyntaxTypeB(srcURLs, tgtURL)
|
||||
case copyURLsTypeC: // Folder... -> Folder.
|
||||
checkCopySyntaxTypeC(srcURLs, tgtURL, isRecursive)
|
||||
case copyURLsTypeD: // File1...FileN -> Folder.
|
||||
checkCopySyntaxTypeD(srcURLs, tgtURL)
|
||||
default:
|
||||
fatalIf(errInvalidArgument().Trace(), "Unable to guess the type of copy operation.")
|
||||
}
|
||||
}
|
||||
|
||||
// checkCopySyntaxTypeA verifies if the source and target are valid file arguments.
|
||||
func checkCopySyntaxTypeA(srcURLs []string, tgtURL string) {
|
||||
// Check source.
|
||||
if len(srcURLs) != 1 {
|
||||
fatalIf(errInvalidArgument().Trace(), "Invalid number of source arguments.")
|
||||
}
|
||||
srcURL := srcURLs[0]
|
||||
_, srcContent, err := url2Stat(srcURL)
|
||||
fatalIf(err.Trace(srcURL), "Unable to stat source ‘"+srcURL+"’.")
|
||||
|
||||
if !srcContent.Type.IsRegular() {
|
||||
fatalIf(errInvalidArgument().Trace(), "Source ‘"+srcURL+"’ is not a file.")
|
||||
}
|
||||
}
|
||||
|
||||
// checkCopySyntaxTypeB verifies if the source is a valid file and target is a valid folder.
|
||||
func checkCopySyntaxTypeB(srcURLs []string, tgtURL string) {
|
||||
// Check source.
|
||||
if len(srcURLs) != 1 {
|
||||
fatalIf(errInvalidArgument().Trace(), "Invalid number of source arguments.")
|
||||
}
|
||||
srcURL := srcURLs[0]
|
||||
_, srcContent, err := url2Stat(srcURL)
|
||||
fatalIf(err.Trace(srcURL), "Unable to stat source ‘"+srcURL+"’.")
|
||||
|
||||
if !srcContent.Type.IsRegular() {
|
||||
fatalIf(errInvalidArgument().Trace(srcURL), "Source ‘"+srcURL+"’ is not a file.")
|
||||
}
|
||||
|
||||
// Check target.
|
||||
if _, tgtContent, err := url2Stat(tgtURL); err == nil {
|
||||
if !tgtContent.Type.IsDir() {
|
||||
fatalIf(errInvalidArgument().Trace(tgtURL), "Target ‘"+tgtURL+"’ is not a folder.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// checkCopySyntaxTypeC verifies if the source is a valid recursive dir and target is a valid folder.
|
||||
func checkCopySyntaxTypeC(srcURLs []string, tgtURL string, isRecursive bool) {
|
||||
// Check source.
|
||||
if len(srcURLs) != 1 {
|
||||
fatalIf(errInvalidArgument().Trace(), "Invalid number of source arguments.")
|
||||
}
|
||||
|
||||
srcURL := srcURLs[0]
|
||||
_, srcContent, err := url2Stat(srcURL)
|
||||
// incomplete uploads are not necessary for copy operation, no need to verify for them.
|
||||
isIncomplete := false
|
||||
if err != nil && !isURLPrefixExists(srcURL, isIncomplete) {
|
||||
fatalIf(err.Trace(srcURL), "Unable to stat source ‘"+srcURL+"’.")
|
||||
}
|
||||
|
||||
if srcContent.Type.IsDir() && !isRecursive {
|
||||
fatalIf(errInvalidArgument().Trace(srcURL), "To copy a folder requires --recursive option.")
|
||||
}
|
||||
|
||||
// Check target.
|
||||
if _, tgtContent, err := url2Stat(tgtURL); err == nil {
|
||||
if !tgtContent.Type.IsDir() {
|
||||
fatalIf(errInvalidArgument().Trace(tgtURL), "Target ‘"+tgtURL+"’ is not a folder.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// checkCopySyntaxTypeD verifies if the source is a valid list of files and target is a valid folder.
|
||||
func checkCopySyntaxTypeD(srcURLs []string, tgtURL string) {
|
||||
// Source can be anything: file, dir, dir...
|
||||
// Check target if it is a dir
|
||||
if _, tgtContent, err := url2Stat(tgtURL); err == nil {
|
||||
if !tgtContent.Type.IsDir() {
|
||||
fatalIf(errInvalidArgument().Trace(tgtURL), "Target ‘"+tgtURL+"’ is not a folder.")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -17,23 +17,38 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/client"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
)
|
||||
|
||||
type copyURLs struct {
|
||||
SourceAlias string
|
||||
SourceContent *client.Content
|
||||
TargetAlias string
|
||||
TargetContent *client.Content
|
||||
Error *probe.Error `json:"-"`
|
||||
}
|
||||
|
||||
type copyURLsType uint8
|
||||
|
||||
// NOTE: All the parse rules should reduced to A: Copy(Source, Target).
|
||||
//
|
||||
// * VALID RULES
|
||||
// =======================
|
||||
// A: copy(f, f) -> copy(f, f)
|
||||
// B: copy(f, d) -> copy(f, d/f) -> []A
|
||||
// C: copy(d1..., d2) -> []copy(f, d2/d1/f) -> []A
|
||||
// D: copy([]f, d) -> []B
|
||||
|
||||
// * INVALID RULES
|
||||
// =========================
|
||||
// copy(d, f)
|
||||
// copy(d..., f)
|
||||
// copy([](f|d)..., f)
|
||||
|
||||
const (
|
||||
copyURLsTypeInvalid copyURLsType = iota
|
||||
copyURLsTypeA
|
||||
@@ -42,196 +57,46 @@ const (
|
||||
copyURLsTypeD
|
||||
)
|
||||
|
||||
// NOTE: All the parse rules should reduced to A: Copy(Source, Target).
|
||||
//
|
||||
// * VALID RULES
|
||||
// =======================
|
||||
// A: copy(f, f) -> copy(f, f)
|
||||
// B: copy(f, d) -> copy(f, d/f) -> A
|
||||
// C: copy(d1..., d2) -> []copy(d1/f, d2/d1/f) -> []A
|
||||
// D: copy([]{d1... | f}, d2) -> []{copy(d1/f, d2/d1/f) | copy(f, d2/f )} -> []A
|
||||
//
|
||||
// * INVALID RULES
|
||||
// =========================
|
||||
// A: copy(d, *)
|
||||
// B: copy(d..., f)
|
||||
// C: copy(*, d...)
|
||||
//
|
||||
func checkCopySyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) < 2 || ctx.Args().First() == "help" {
|
||||
cli.ShowCommandHelpAndExit(ctx, "cp", 1) // last argument is exit code.
|
||||
}
|
||||
// extract URLs.
|
||||
URLs, err := args2URLs(ctx.Args())
|
||||
fatalIf(err.Trace(ctx.Args()...), fmt.Sprintf("One or more unknown URL types passed."))
|
||||
|
||||
srcURLs := URLs[:len(URLs)-1]
|
||||
tgtURL := URLs[len(URLs)-1]
|
||||
|
||||
/****** Generic rules *******/
|
||||
// Recursive URLs are not allowed in target.
|
||||
if isURLRecursive(tgtURL) {
|
||||
fatalIf(errDummy().Trace(), fmt.Sprintf("Recursive option is not supported for target ‘%s’ argument.", tgtURL))
|
||||
}
|
||||
// scope locally
|
||||
{
|
||||
url := client.NewURL(tgtURL)
|
||||
if url.Host != "" {
|
||||
// This check is for type URL.
|
||||
if url.Path == string(url.Separator) {
|
||||
fatalIf(errInvalidArgument().Trace(), fmt.Sprintf("Target ‘%s’ does not contain bucket name.", tgtURL))
|
||||
}
|
||||
if strings.Count(url.Path, "/") < 2 {
|
||||
if err := bucketExists(tgtURL); err != nil {
|
||||
fatalIf(err.Trace(), fmt.Sprintf("Unable to stat target ‘%s’.", tgtURL))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
switch guessCopyURLType(srcURLs, tgtURL) {
|
||||
case copyURLsTypeA: // File -> File.
|
||||
checkCopySyntaxTypeA(srcURLs, tgtURL)
|
||||
case copyURLsTypeB: // File -> Folder.
|
||||
checkCopySyntaxTypeB(srcURLs, tgtURL)
|
||||
case copyURLsTypeC: // Folder... -> Folder.
|
||||
checkCopySyntaxTypeC(srcURLs, tgtURL)
|
||||
case copyURLsTypeD: // File | Folder... -> Folder.
|
||||
checkCopySyntaxTypeD(srcURLs, tgtURL)
|
||||
default:
|
||||
fatalIf(errInvalidArgument().Trace(), "Invalid arguments to copy command.")
|
||||
}
|
||||
}
|
||||
|
||||
// checkCopySyntaxTypeA verifies if the source and target are valid file arguments.
|
||||
func checkCopySyntaxTypeA(srcURLs []string, tgtURL string) {
|
||||
if len(srcURLs) != 1 {
|
||||
fatalIf(errInvalidArgument().Trace(), "Invalid number of source arguments to copy command.")
|
||||
}
|
||||
srcURL := srcURLs[0]
|
||||
_, srcContent, err := url2Stat(srcURL)
|
||||
|
||||
fatalIf(err.Trace(srcURL), "Unable to stat source ‘"+srcURL+"’.")
|
||||
|
||||
if srcContent.Type.IsDir() {
|
||||
fatalIf(errInvalidArgument().Trace(), fmt.Sprintf("Source ‘%s’ is a folder. Use ‘%s...’ argument to copy this folder and its contents recursively.", srcURL, srcURL))
|
||||
}
|
||||
if !srcContent.Type.IsRegular() {
|
||||
fatalIf(errInvalidArgument().Trace(), "Source ‘"+srcURL+"’ is not a file.")
|
||||
}
|
||||
}
|
||||
|
||||
// checkCopySyntaxTypeB verifies if the source is a valid file and target is a valid dir.
|
||||
func checkCopySyntaxTypeB(srcURLs []string, tgtURL string) {
|
||||
if len(srcURLs) != 1 {
|
||||
fatalIf(errInvalidArgument().Trace(), "Invalid number of source arguments to copy command.")
|
||||
}
|
||||
srcURL := srcURLs[0]
|
||||
_, srcContent, err := url2Stat(srcURL)
|
||||
fatalIf(err.Trace(srcURL), "Unable to stat source ‘"+srcURL+"’.")
|
||||
|
||||
if srcContent.Type.IsDir() {
|
||||
fatalIf(errInvalidArgument().Trace(), fmt.Sprintf("Source ‘%s’ is a folder. Use ‘%s...’ argument to copy this folder and its contents recursively.", srcURL, srcURL))
|
||||
}
|
||||
if !srcContent.Type.IsRegular() {
|
||||
fatalIf(errInvalidArgument().Trace(), "Source ‘"+srcURL+"’ is not a file.")
|
||||
}
|
||||
|
||||
_, tgtContent, err := url2Stat(tgtURL)
|
||||
// Target exist?.
|
||||
if err == nil {
|
||||
if !tgtContent.Type.IsDir() {
|
||||
fatalIf(errInvalidArgument().Trace(), "Target ‘"+tgtURL+"’ is not a folder.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// checkCopySyntaxTypeC verifies if the source is a valid recursive dir and target is a valid dir.
|
||||
func checkCopySyntaxTypeC(srcURLs []string, tgtURL string) {
|
||||
if len(srcURLs) != 1 {
|
||||
fatalIf(errInvalidArgument().Trace(), "Invalid number of source arguments to copy command.")
|
||||
}
|
||||
srcURL := srcURLs[0]
|
||||
srcURL = stripRecursiveURL(srcURL)
|
||||
_, srcContent, err := url2Stat(srcURL)
|
||||
fatalIf(err.Trace(srcURL), "Unable to stat source ‘"+srcURL+"’.")
|
||||
|
||||
if srcContent.Type.IsRegular() { // Ellipses is supported only for folders.
|
||||
fatalIf(errInvalidArgument().Trace(), "Source ‘"+srcURL+"’ is not a folder.")
|
||||
}
|
||||
_, tgtContent, err := url2Stat(tgtURL)
|
||||
// Target exist?.
|
||||
if err == nil {
|
||||
if !tgtContent.Type.IsDir() {
|
||||
fatalIf(errInvalidArgument().Trace(), "Target ‘"+tgtURL+"’ is not a folder.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// checkCopySyntaxTypeD verifies if the source is a valid list of file or valid recursive dir and target is a valid dir.
|
||||
func checkCopySyntaxTypeD(srcURLs []string, tgtURL string) {
|
||||
for _, srcURL := range srcURLs {
|
||||
if isURLRecursive(srcURL) {
|
||||
srcURL = stripRecursiveURL(srcURL)
|
||||
_, srcContent, err := url2Stat(srcURL)
|
||||
fatalIf(err.Trace(srcURL), "Unable to stat source ‘"+srcURL+"’.")
|
||||
|
||||
if !srcContent.Type.IsDir() { // Ellipses is supported only for folders.
|
||||
fatalIf(errInvalidArgument().Trace(), "Source ‘"+srcURL+"’ is not a folder.")
|
||||
}
|
||||
} else { // Regular URL.
|
||||
_, srcContent, err := url2Stat(srcURL)
|
||||
fatalIf(err.Trace(srcURL), "Unable to stat source ‘"+srcURL+"’.")
|
||||
|
||||
if srcContent.Type.IsDir() {
|
||||
fatalIf(errInvalidArgument().Trace(), fmt.Sprintf("Source ‘%s’ is a folder. Use ‘%s...’ argument to copy this folder and its contents recursively.", srcURL, srcURL))
|
||||
}
|
||||
if !srcContent.Type.IsRegular() {
|
||||
fatalIf(errInvalidArgument().Trace(), "Source ‘"+srcURL+"’ is not a file.")
|
||||
}
|
||||
}
|
||||
}
|
||||
_, tgtContent, err := url2Stat(tgtURL)
|
||||
// Target exist?.
|
||||
if err == nil {
|
||||
if !tgtContent.Type.IsDir() {
|
||||
fatalIf(errInvalidArgument().Trace(), "Target ‘"+tgtURL+"’ is not a folder.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// guessCopyURLType guesses the type of URL. This approach all allows prepareURL
|
||||
// functions to accurately report failure causes.
|
||||
func guessCopyURLType(sourceURLs []string, targetURL string) copyURLsType {
|
||||
if strings.TrimSpace(targetURL) == "" || targetURL == "" { // Target is empty
|
||||
return copyURLsTypeInvalid
|
||||
}
|
||||
if len(sourceURLs) == 0 || sourceURLs == nil { // Source list is empty
|
||||
return copyURLsTypeInvalid
|
||||
}
|
||||
for _, sourceURL := range sourceURLs {
|
||||
if sourceURL == "" { // One of the source is empty
|
||||
return copyURLsTypeInvalid
|
||||
}
|
||||
}
|
||||
func guessCopyURLType(sourceURLs []string, targetURL string, isRecursive bool) (copyURLsType, *probe.Error) {
|
||||
if len(sourceURLs) == 1 { // 1 Source, 1 Target
|
||||
switch {
|
||||
// Type C
|
||||
case isURLRecursive(sourceURLs[0]):
|
||||
return copyURLsTypeC
|
||||
// Type B
|
||||
case isTargetURLDir(targetURL):
|
||||
return copyURLsTypeB
|
||||
// Type A
|
||||
default:
|
||||
return copyURLsTypeA
|
||||
sourceURL := sourceURLs[0]
|
||||
_, sourceContent, err := url2Stat(sourceURL)
|
||||
if err != nil {
|
||||
return copyURLsTypeInvalid, err
|
||||
}
|
||||
} // else Type D
|
||||
return copyURLsTypeD
|
||||
|
||||
// If recursion is ON, it is type C.
|
||||
// If source is a folder, it is Type C.
|
||||
if sourceContent.Type.IsDir() || isRecursive {
|
||||
return copyURLsTypeC, nil
|
||||
}
|
||||
|
||||
// If target is a folder, it is Type B.
|
||||
if isTargetURLDir(targetURL) {
|
||||
return copyURLsTypeB, nil
|
||||
}
|
||||
// else Type A.
|
||||
return copyURLsTypeA, nil
|
||||
}
|
||||
|
||||
// Multiple source args and target is a folder. It is Type D.
|
||||
if isTargetURLDir(targetURL) {
|
||||
return copyURLsTypeD, nil
|
||||
}
|
||||
|
||||
return copyURLsTypeInvalid, errInvalidArgument().Trace()
|
||||
}
|
||||
|
||||
// SINGLE SOURCE - Type A: copy(f, f) -> copy(f, f)
|
||||
// prepareCopyURLsTypeA - prepares target and source URLs for copying.
|
||||
func prepareCopyURLsTypeA(sourceURL string, targetURL string) copyURLs {
|
||||
// Extract alias before fiddling with the URL.
|
||||
sourceAlias, _, _ := mustExpandAlias(sourceURL)
|
||||
// Find alias and expanded URL.
|
||||
targetAlias, targetURL, _ := mustExpandAlias(targetURL)
|
||||
|
||||
_, sourceContent, err := url2Stat(sourceURL)
|
||||
if err != nil {
|
||||
// Source does not exist or insufficient privileges.
|
||||
@@ -239,115 +104,120 @@ func prepareCopyURLsTypeA(sourceURL string, targetURL string) copyURLs {
|
||||
}
|
||||
if !sourceContent.Type.IsRegular() {
|
||||
// Source is not a regular file
|
||||
return copyURLs{Error: errInvalidSource(sourceURL).Trace()}
|
||||
return copyURLs{Error: errInvalidSource(sourceURL).Trace(sourceURL)}
|
||||
}
|
||||
if sourceContent.URL.String() == targetURL {
|
||||
// source and target can not be same
|
||||
return copyURLs{Error: errSourceTargetSame(sourceURL).Trace(sourceURL)}
|
||||
}
|
||||
|
||||
// All OK.. We can proceed. Type A
|
||||
sourceContent.Name = sourceURL
|
||||
return copyURLs{SourceContent: sourceContent, TargetContent: &client.Content{Name: targetURL}}
|
||||
return makeCopyContentTypeA(sourceAlias, sourceContent, targetAlias, targetURL)
|
||||
}
|
||||
|
||||
// prepareCopyContentTypeA - makes CopyURLs content for copying.
|
||||
func makeCopyContentTypeA(sourceAlias string, sourceContent *client.Content, targetAlias string, targetURL string) copyURLs {
|
||||
return copyURLs{
|
||||
SourceAlias: sourceAlias,
|
||||
SourceContent: sourceContent,
|
||||
TargetAlias: targetAlias,
|
||||
TargetContent: &client.Content{URL: *client.NewURL(targetURL)},
|
||||
}
|
||||
}
|
||||
|
||||
// SINGLE SOURCE - Type B: copy(f, d) -> copy(f, d/f) -> A
|
||||
// prepareCopyURLsTypeB - prepares target and source URLs for copying.
|
||||
func prepareCopyURLsTypeB(sourceURL string, targetURL string) copyURLs {
|
||||
// Extract alias before fiddling with the URL.
|
||||
sourceAlias, _, _ := mustExpandAlias(sourceURL)
|
||||
// Find alias and expanded URL.
|
||||
targetAlias, targetURL, _ := mustExpandAlias(targetURL)
|
||||
|
||||
_, sourceContent, err := url2Stat(sourceURL)
|
||||
if err != nil {
|
||||
// Source does not exist or insufficient privileges.
|
||||
return copyURLs{Error: err.Trace(sourceURL)}
|
||||
}
|
||||
|
||||
if !sourceContent.Type.IsRegular() {
|
||||
if sourceContent.Type.IsDir() {
|
||||
return copyURLs{Error: errSourceIsDir(sourceURL).Trace(sourceURL)}
|
||||
}
|
||||
// Source is not a regular file.
|
||||
return copyURLs{Error: errInvalidSource(sourceURL).Trace()}
|
||||
return copyURLs{Error: errInvalidSource(sourceURL).Trace(sourceURL)}
|
||||
}
|
||||
|
||||
// All OK.. We can proceed. Type B: source is a file, target is a folder and exists.
|
||||
{
|
||||
sourceURLParse := client.NewURL(sourceURL)
|
||||
targetURLParse := client.NewURL(targetURL)
|
||||
targetURLParse.Path = filepath.Join(targetURLParse.Path, filepath.Base(sourceURLParse.Path))
|
||||
return prepareCopyURLsTypeA(sourceURL, targetURLParse.String())
|
||||
}
|
||||
return makeCopyContentTypeB(sourceAlias, sourceContent, targetAlias, targetURL)
|
||||
}
|
||||
|
||||
// makeCopyContentTypeB - CopyURLs content for copying.
|
||||
func makeCopyContentTypeB(sourceAlias string, sourceContent *client.Content, targetAlias string, targetURL string) copyURLs {
|
||||
// All OK.. We can proceed. Type B: source is a file, target is a folder and exists.
|
||||
targetURLParse := client.NewURL(targetURL)
|
||||
targetURLParse.Path = filepath.ToSlash(filepath.Join(targetURLParse.Path, filepath.Base(sourceContent.URL.Path)))
|
||||
return makeCopyContentTypeA(sourceAlias, sourceContent, targetAlias, targetURLParse.String())
|
||||
}
|
||||
|
||||
// SINGLE SOURCE - Type C: copy(d1..., d2) -> []copy(d1/f, d1/d2/f) -> []A
|
||||
// prepareCopyRecursiveURLTypeC - prepares target and source URLs for copying.
|
||||
func prepareCopyURLsTypeC(sourceURL, targetURL string) <-chan copyURLs {
|
||||
func prepareCopyURLsTypeC(sourceURL, targetURL string, isRecursive bool) <-chan copyURLs {
|
||||
// Extract alias before fiddling with the URL.
|
||||
sourceAlias, _, _ := mustExpandAlias(sourceURL)
|
||||
// Find alias and expanded URL.
|
||||
targetAlias, targetURL, _ := mustExpandAlias(targetURL)
|
||||
|
||||
copyURLsCh := make(chan copyURLs)
|
||||
go func(sourceURL, targetURL string, copyURLsCh chan copyURLs) {
|
||||
defer close(copyURLsCh)
|
||||
if !isURLRecursive(sourceURL) {
|
||||
// Source is not of recursive type.
|
||||
copyURLsCh <- copyURLs{Error: errSourceNotRecursive(sourceURL).Trace()}
|
||||
return
|
||||
}
|
||||
|
||||
// add `/` after trimming off `...` to emulate folders
|
||||
sourceURL = stripRecursiveURL(sourceURL)
|
||||
sourceClient, sourceContent, err := url2Stat(sourceURL)
|
||||
sourceClient, err := newClient(sourceURL)
|
||||
if err != nil {
|
||||
// Source does not exist or insufficient privileges.
|
||||
// Source initialization failed.
|
||||
copyURLsCh <- copyURLs{Error: err.Trace(sourceURL)}
|
||||
return
|
||||
}
|
||||
|
||||
if !sourceContent.Type.IsDir() {
|
||||
// Source is not a dir.
|
||||
copyURLsCh <- copyURLs{Error: errSourceIsNotDir(sourceURL).Trace()}
|
||||
return
|
||||
}
|
||||
|
||||
for sourceContent := range sourceClient.List(true) {
|
||||
for sourceContent := range sourceClient.List(isRecursive, false) {
|
||||
if sourceContent.Err != nil {
|
||||
// Listing failed.
|
||||
copyURLsCh <- copyURLs{Error: sourceContent.Err.Trace()}
|
||||
copyURLsCh <- copyURLs{Error: sourceContent.Err.Trace(sourceClient.GetURL().String())}
|
||||
continue
|
||||
}
|
||||
|
||||
if !sourceContent.Content.Type.IsRegular() {
|
||||
if !sourceContent.Type.IsRegular() {
|
||||
// Source is not a regular file. Skip it for copy.
|
||||
continue
|
||||
}
|
||||
|
||||
// All OK.. We can proceed. Type B: source is a file, target is a folder and exists.
|
||||
sourceURLParse := client.NewURL(sourceURL)
|
||||
targetURLParse := client.NewURL(targetURL)
|
||||
|
||||
sourceURLDelimited := sourceURLParse.String()[:strings.LastIndex(sourceURLParse.String(),
|
||||
string(sourceURLParse.Separator))+1]
|
||||
sourceContentName := sourceContent.Content.Name
|
||||
sourceContentURL := sourceURLDelimited + sourceContentName
|
||||
sourceContentParse := client.NewURL(sourceContentURL)
|
||||
|
||||
// Construct target path from recursive path of source without its prefix dir.
|
||||
newTargetURLParse := *targetURLParse
|
||||
newTargetURLParse.Path = filepath.Join(newTargetURLParse.Path, sourceContentName)
|
||||
copyURLsCh <- prepareCopyURLsTypeA(sourceContentParse.String(), newTargetURLParse.String())
|
||||
copyURLsCh <- makeCopyContentTypeC(sourceAlias, sourceClient.GetURL(), sourceContent, targetAlias, targetURL)
|
||||
}
|
||||
}(sourceURL, targetURL, copyURLsCh)
|
||||
return copyURLsCh
|
||||
}
|
||||
|
||||
// MULTI-SOURCE - Type D: copy([]f, d) -> []B
|
||||
// prepareCopyURLsTypeD - prepares target and source URLs for copying.
|
||||
func prepareCopyURLsTypeD(sourceURLs []string, targetURL string) <-chan copyURLs {
|
||||
// makeCopyContentTypeC - CopyURLs content for copying.
|
||||
func makeCopyContentTypeC(sourceAlias string, sourceURL client.URL, sourceContent *client.Content, targetAlias string, targetURL string) copyURLs {
|
||||
newSourceURL := sourceContent.URL
|
||||
pathSeparatorIndex := strings.LastIndex(sourceURL.Path, string(sourceURL.Separator))
|
||||
newSourceSuffix := filepath.ToSlash(newSourceURL.Path)
|
||||
if pathSeparatorIndex > 1 {
|
||||
sourcePrefix := filepath.ToSlash(sourceURL.Path[:pathSeparatorIndex])
|
||||
newSourceSuffix = strings.TrimPrefix(newSourceSuffix, sourcePrefix)
|
||||
}
|
||||
newTargetURL := urlJoinPath(targetURL, newSourceSuffix)
|
||||
return makeCopyContentTypeA(sourceAlias, sourceContent, targetAlias, newTargetURL)
|
||||
}
|
||||
|
||||
// MULTI-SOURCE - Type D: copy([](f|d...), d) -> []B
|
||||
// prepareCopyURLsTypeE - prepares target and source URLs for copying.
|
||||
func prepareCopyURLsTypeD(sourceURLs []string, targetURL string, isRecursive bool) <-chan copyURLs {
|
||||
copyURLsCh := make(chan copyURLs)
|
||||
go func(sourceURLs []string, targetURL string, copyURLsCh chan copyURLs) {
|
||||
defer close(copyURLsCh)
|
||||
|
||||
if sourceURLs == nil {
|
||||
// Source list is empty.
|
||||
copyURLsCh <- copyURLs{Error: errSourceListEmpty().Trace()}
|
||||
return
|
||||
}
|
||||
|
||||
for _, sourceURL := range sourceURLs {
|
||||
// Target is folder. Possibilities are only Type B and C
|
||||
// Is it a recursive URL "..."?
|
||||
if isURLRecursive(sourceURL) {
|
||||
for cURLs := range prepareCopyURLsTypeC(sourceURL, targetURL) {
|
||||
copyURLsCh <- cURLs
|
||||
}
|
||||
} else {
|
||||
copyURLsCh <- prepareCopyURLsTypeB(sourceURL, targetURL)
|
||||
for cpURLs := range prepareCopyURLsTypeC(sourceURL, targetURL, isRecursive) {
|
||||
copyURLsCh <- cpURLs
|
||||
}
|
||||
}
|
||||
}(sourceURLs, targetURL, copyURLsCh)
|
||||
@@ -355,25 +225,27 @@ func prepareCopyURLsTypeD(sourceURLs []string, targetURL string) <-chan copyURLs
|
||||
}
|
||||
|
||||
// prepareCopyURLs - prepares target and source URLs for copying.
|
||||
func prepareCopyURLs(sourceURLs []string, targetURL string) <-chan copyURLs {
|
||||
func prepareCopyURLs(sourceURLs []string, targetURL string, isRecursive bool) <-chan copyURLs {
|
||||
copyURLsCh := make(chan copyURLs)
|
||||
go func(sourceURLs []string, targetURL string, copyURLsCh chan copyURLs) {
|
||||
defer close(copyURLsCh)
|
||||
switch guessCopyURLType(sourceURLs, targetURL) {
|
||||
cpType, err := guessCopyURLType(sourceURLs, targetURL, isRecursive)
|
||||
fatalIf(err.Trace(), "Unable to guess the type of copy operation.")
|
||||
switch cpType {
|
||||
case copyURLsTypeA:
|
||||
copyURLsCh <- prepareCopyURLsTypeA(sourceURLs[0], targetURL)
|
||||
case copyURLsTypeB:
|
||||
copyURLsCh <- prepareCopyURLsTypeB(sourceURLs[0], targetURL)
|
||||
case copyURLsTypeC:
|
||||
for cURLs := range prepareCopyURLsTypeC(sourceURLs[0], targetURL) {
|
||||
for cURLs := range prepareCopyURLsTypeC(sourceURLs[0], targetURL, isRecursive) {
|
||||
copyURLsCh <- cURLs
|
||||
}
|
||||
case copyURLsTypeD:
|
||||
for cURLs := range prepareCopyURLsTypeD(sourceURLs, targetURL) {
|
||||
for cURLs := range prepareCopyURLsTypeD(sourceURLs, targetURL, isRecursive) {
|
||||
copyURLsCh <- cURLs
|
||||
}
|
||||
default:
|
||||
copyURLsCh <- copyURLs{Error: errInvalidArgument().Trace()}
|
||||
copyURLsCh <- copyURLs{Error: errInvalidArgument().Trace(sourceURLs...)}
|
||||
}
|
||||
}(sourceURLs, targetURL, copyURLsCh)
|
||||
|
||||
|
||||
@@ -1,72 +0,0 @@
|
||||
/*
|
||||
* Minio Client (C) 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
|
||||
"github.com/minio/mc/pkg/console"
|
||||
. "gopkg.in/check.v1"
|
||||
)
|
||||
|
||||
func (s *TestSuite) TestCopyURLType(c *C) {
|
||||
sourceURLs := []string{server.URL + "/bucket/object1"}
|
||||
targetURL := server.URL + "/bucket/test"
|
||||
c.Assert(guessCopyURLType(sourceURLs, targetURL), Equals, copyURLsTypeA)
|
||||
|
||||
sourceURLs = []string{server.URL + "/bucket/object1"}
|
||||
targetURL = server.URL + "/bucket"
|
||||
c.Assert(guessCopyURLType(sourceURLs, targetURL), Equals, copyURLsTypeB)
|
||||
|
||||
sourceURLs = []string{server.URL + "/bucket/..."}
|
||||
targetURL = server.URL + "/bucket"
|
||||
c.Assert(guessCopyURLType(sourceURLs, targetURL), Equals, copyURLsTypeC)
|
||||
|
||||
sourceURLs = []string{server.URL + "/bucket/...", server.URL + "/bucket/..."}
|
||||
targetURL = server.URL + "/bucket/test"
|
||||
c.Assert(guessCopyURLType(sourceURLs, targetURL), Equals, copyURLsTypeD)
|
||||
|
||||
sourceURLs = []string{}
|
||||
targetURL = server.URL + "/bucket"
|
||||
c.Assert(guessCopyURLType(sourceURLs, targetURL), Equals, copyURLsTypeInvalid)
|
||||
|
||||
sourceURLs = nil
|
||||
targetURL = server.URL + "/bucket"
|
||||
c.Assert(guessCopyURLType(sourceURLs, targetURL), Equals, copyURLsTypeInvalid)
|
||||
|
||||
sourceURLs = []string{server.URL + "/bucket/...", server.URL + "/bucket/..."}
|
||||
targetURL = ""
|
||||
c.Assert(guessCopyURLType(sourceURLs, targetURL), Equals, copyURLsTypeInvalid)
|
||||
}
|
||||
|
||||
func (s *TestSuite) TestCopyContext(c *C) {
|
||||
err := app.Run([]string{os.Args[0], "cp", server.URL + "/invalid...", server.URL + "/bucket"})
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(console.IsError, Equals, true)
|
||||
|
||||
// reset back
|
||||
console.IsError = false
|
||||
}
|
||||
|
||||
func (s *TestSuite) TestMirrorContext(c *C) {
|
||||
err := app.Run([]string{os.Args[0], "mirror", server.URL + "/invalid...", server.URL + "/bucket"})
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(console.IsError, Equals, true)
|
||||
|
||||
// reset back
|
||||
console.IsError = false
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
/*
|
||||
* Minio Client (C) 2014-2016 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"math"
|
||||
)
|
||||
|
||||
// Returns the minimum value of a slice of integers
|
||||
func minimum(integers []int) (minVal int) {
|
||||
minVal = math.MaxInt32
|
||||
for _, v := range integers {
|
||||
if v < minVal {
|
||||
minVal = v
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// DamerauLevenshteinDistance calculates distance between two strings using an algorithm
|
||||
// described in https://en.wikipedia.org/wiki/Damerau-Levenshtein_distance
|
||||
func DamerauLevenshteinDistance(a string, b string) int {
|
||||
d := make([][]int, len(a)+1)
|
||||
for i := 1; i <= len(a)+1; i++ {
|
||||
d[i-1] = make([]int, len(b)+1)
|
||||
}
|
||||
for i := 0; i <= len(a); i++ {
|
||||
d[i][0] = i
|
||||
}
|
||||
for j := 0; j <= len(b); j++ {
|
||||
d[0][j] = j
|
||||
}
|
||||
for i := 1; i <= len(a); i++ {
|
||||
for j := 1; j <= len(b); j++ {
|
||||
cost := 0
|
||||
if a[i-1] == b[j-1] {
|
||||
cost = 0
|
||||
} else {
|
||||
cost = 1
|
||||
}
|
||||
d[i][j] = minimum([]int{
|
||||
d[i-1][j] + 1,
|
||||
d[i][j-1] + 1,
|
||||
d[i-1][j-1] + cost,
|
||||
})
|
||||
if i > 1 && j > 1 && a[i-1] == b[j-2] && a[i-2] == b[j-1] {
|
||||
d[i][j] = minimum([]int{d[i][j], d[i-2][j-2] + cost}) // transposition
|
||||
}
|
||||
}
|
||||
}
|
||||
return d[len(a)][len(b)]
|
||||
}
|
||||
+165
-35
@@ -17,77 +17,207 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/client"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
)
|
||||
|
||||
// diff specific flags.
|
||||
var (
|
||||
diffFlags = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "help, h",
|
||||
Usage: "Help of diff.",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
// Compute differences between two files or folders.
|
||||
var diffCmd = cli.Command{
|
||||
Name: "diff",
|
||||
Usage: "Compute differences between two files or folders.",
|
||||
Description: "NOTE: This command *DOES NOT* check for content similarity, which means objects with same size, but different content will not be spotted.",
|
||||
Usage: "Compute differences between two folders.",
|
||||
Description: "Diff only lists missing objects or objects with size differences. It *DOES NOT* compare contents. i.e. Objects of same name and size, but differ in contents are not noticed.",
|
||||
Action: mainDiff,
|
||||
Flags: append(diffFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
mc {{.Name}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
mc {{.Name}} FIRST SECOND
|
||||
mc {{.Name}} [FLAGS] FIRST SECOND
|
||||
|
||||
FLAGS:
|
||||
{{range .Flags}}{{.}}
|
||||
{{end}}
|
||||
DESCRIPTION:
|
||||
{{.Description}}
|
||||
|
||||
EXAMPLES:
|
||||
1. Compare foo.ogg on a local filesystem with bar.ogg on Amazon AWS cloud storage.
|
||||
$ mc {{.Name}} foo.ogg https://s3.amazonaws.com/jukebox/bar.ogg
|
||||
1. Compare a local folder with a folder on Amazon S3 cloud storage.
|
||||
$ mc {{.Name}} ~/Photos s3/MyBucket/Photos
|
||||
|
||||
2. Compare two different folders on a local filesystem.
|
||||
$ mc {{.Name}} ~/Photos /Media/Backup/Photos
|
||||
`,
|
||||
}
|
||||
|
||||
// diffMessage json container for diff messages
|
||||
type diffMessage struct {
|
||||
Status string `json:"status"`
|
||||
FirstURL string `json:"first"`
|
||||
SecondURL string `json:"second"`
|
||||
Diff string `json:"diff"`
|
||||
Error *probe.Error `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// String colorized diff message
|
||||
func (d diffMessage) String() string {
|
||||
msg := ""
|
||||
switch d.Diff {
|
||||
case "only-in-first":
|
||||
msg = console.Colorize("DiffMessage",
|
||||
"‘"+d.FirstURL+"’"+" and "+"‘"+d.SecondURL+"’") + console.Colorize("DiffOnlyInFirst", " - only in first.")
|
||||
case "type":
|
||||
msg = console.Colorize("DiffMessage",
|
||||
"‘"+d.FirstURL+"’"+" and "+"‘"+d.SecondURL+"’") + console.Colorize("DiffType", " - differ in type.")
|
||||
case "size":
|
||||
msg = console.Colorize("DiffMessage",
|
||||
"‘"+d.FirstURL+"’"+" and "+"‘"+d.SecondURL+"’") + console.Colorize("DiffSize", " - differ in size.")
|
||||
default:
|
||||
fatalIf(errDummy().Trace(d.FirstURL, d.SecondURL),
|
||||
"Unhandled difference between ‘"+d.FirstURL+"’ and ‘"+d.SecondURL+"’.")
|
||||
}
|
||||
return msg
|
||||
|
||||
}
|
||||
|
||||
// JSON jsonified diff message
|
||||
func (d diffMessage) JSON() string {
|
||||
d.Status = "success"
|
||||
diffJSONBytes, e := json.Marshal(d)
|
||||
fatalIf(probe.NewError(e),
|
||||
"Unable to marshal diff message ‘"+d.FirstURL+"’, ‘"+d.SecondURL+"’ and ‘"+d.Diff+"’.")
|
||||
return string(diffJSONBytes)
|
||||
}
|
||||
|
||||
func checkDiffSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) != 2 || ctx.Args().First() == "help" {
|
||||
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(), "Unable to validate empty argument.")
|
||||
fatalIf(errInvalidArgument().Trace(ctx.Args()...), "Unable to validate empty argument.")
|
||||
}
|
||||
}
|
||||
if isURLRecursive(ctx.Args().Last()) {
|
||||
fatalIf(errInvalidArgument().Trace(), "Second argument ‘"+ctx.Args().Last()+"’ cannot be recursive.")
|
||||
URLs := ctx.Args()
|
||||
firstURL := URLs[0]
|
||||
secondURL := URLs[1]
|
||||
|
||||
// Diff only works between two directories, verify them below.
|
||||
|
||||
// Verify if firstURL is accessible.
|
||||
_, firstContent, err := url2Stat(firstURL)
|
||||
if err != nil {
|
||||
fatalIf(err.Trace(firstURL), fmt.Sprintf("Unable to stat '%s'.", firstURL))
|
||||
}
|
||||
// Verify if its a directory.
|
||||
if !firstContent.Type.IsDir() {
|
||||
fatalIf(errInvalidArgument().Trace(firstURL), fmt.Sprintf("‘%s’ is not a folder.", firstURL))
|
||||
}
|
||||
|
||||
// Verify if secondURL is accessible.
|
||||
_, secondContent, err := url2Stat(secondURL)
|
||||
if err != nil {
|
||||
fatalIf(err.Trace(secondURL), fmt.Sprintf("Unable to stat '%s'.", secondURL))
|
||||
}
|
||||
// Verify if its a directory.
|
||||
if !secondContent.Type.IsDir() {
|
||||
fatalIf(errInvalidArgument().Trace(secondURL), fmt.Sprintf("‘%s’ is not a folder.", secondURL))
|
||||
}
|
||||
}
|
||||
|
||||
// mainDiff - is a handler for mc diff command
|
||||
// doDiffMain runs the diff.
|
||||
func doDiffMain(firstURL, secondURL string) {
|
||||
// Source and targets are always directories
|
||||
sourceSeparator := string(client.NewURL(firstURL).Separator)
|
||||
if !strings.HasSuffix(firstURL, sourceSeparator) {
|
||||
firstURL = firstURL + sourceSeparator
|
||||
}
|
||||
targetSeparator := string(client.NewURL(secondURL).Separator)
|
||||
if !strings.HasSuffix(secondURL, targetSeparator) {
|
||||
secondURL = secondURL + targetSeparator
|
||||
}
|
||||
|
||||
// Expand aliased urls.
|
||||
firstAlias, firstURL, _ := mustExpandAlias(firstURL)
|
||||
secondAlias, secondURL, _ := mustExpandAlias(secondURL)
|
||||
|
||||
firstClient, err := newClientFromAlias(firstAlias, firstURL)
|
||||
if err != nil {
|
||||
fatalIf(err.Trace(firstAlias, firstURL, secondAlias, secondURL),
|
||||
fmt.Sprintf("Failed to diff '%s' and '%s'", firstURL, secondURL))
|
||||
}
|
||||
difference, err := objectDifferenceFactory(secondAlias, secondURL)
|
||||
if err != nil {
|
||||
fatalIf(err.Trace(firstAlias, firstURL, secondAlias, secondURL),
|
||||
fmt.Sprintf("Failed to diff '%s' and '%s'", firstURL, secondURL))
|
||||
}
|
||||
isRecursive := true
|
||||
isIncomplete := false
|
||||
for sourceContent := range firstClient.List(isRecursive, isIncomplete) {
|
||||
if sourceContent.Err != nil {
|
||||
switch sourceContent.Err.ToGoError().(type) {
|
||||
// Handle this specifically for filesystem related errors.
|
||||
case client.BrokenSymlink, client.TooManyLevelsSymlink, client.PathNotFound, client.PathInsufficientPermission:
|
||||
errorIf(sourceContent.Err.Trace(firstURL, secondURL), fmt.Sprintf("Failed on '%s'", firstURL))
|
||||
default:
|
||||
fatalIf(sourceContent.Err.Trace(firstURL, secondURL), fmt.Sprintf("Failed on '%s'", firstURL))
|
||||
}
|
||||
continue
|
||||
}
|
||||
if sourceContent.Type.IsDir() {
|
||||
continue
|
||||
}
|
||||
suffix := strings.TrimPrefix(sourceContent.URL.String(), firstURL)
|
||||
differ, err := difference(suffix, sourceContent.Type, sourceContent.Size)
|
||||
if err != nil {
|
||||
errorIf(sourceContent.Err.Trace(secondURL, suffix),
|
||||
fmt.Sprintf("Failed on '%s'", urlJoinPath(secondURL, suffix)))
|
||||
continue
|
||||
}
|
||||
if differ == differNone {
|
||||
continue
|
||||
}
|
||||
printMsg(diffMessage{
|
||||
FirstURL: sourceContent.URL.String(),
|
||||
SecondURL: urlJoinPath(secondURL, suffix),
|
||||
Diff: differ,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// mainDiff main for 'diff'.
|
||||
func mainDiff(ctx *cli.Context) {
|
||||
// Set global flags from context.
|
||||
setGlobalsFromContext(ctx)
|
||||
|
||||
// check 'diff' cli arguments.
|
||||
checkDiffSyntax(ctx)
|
||||
|
||||
console.SetCustomTheme(map[string]*color.Color{
|
||||
"DiffMessage": color.New(color.FgGreen, color.Bold),
|
||||
"DiffOnlyInFirst": color.New(color.FgRed, color.Bold),
|
||||
"DiffType": color.New(color.FgYellow, color.Bold),
|
||||
"DiffSize": color.New(color.FgMagenta, color.Bold),
|
||||
})
|
||||
// Additional command specific theme customization.
|
||||
console.SetColor("DiffMessage", color.New(color.FgGreen, color.Bold))
|
||||
console.SetColor("DiffOnlyInFirst", color.New(color.FgRed, color.Bold))
|
||||
console.SetColor("DiffType", color.New(color.FgYellow, color.Bold))
|
||||
console.SetColor("DiffSize", color.New(color.FgMagenta, color.Bold))
|
||||
|
||||
config := mustGetMcConfig()
|
||||
firstArg := ctx.Args().First()
|
||||
secondArg := ctx.Args().Last()
|
||||
URLs := ctx.Args()
|
||||
firstURL := URLs[0]
|
||||
secondURL := URLs[1]
|
||||
|
||||
firstURL := getAliasURL(firstArg, config.Aliases)
|
||||
secondURL := getAliasURL(secondArg, config.Aliases)
|
||||
|
||||
newFirstURL := stripRecursiveURL(firstURL)
|
||||
for diff := range doDiff(newFirstURL, secondURL, isURLRecursive(firstURL)) {
|
||||
fatalIf(diff.Error.Trace(newFirstURL, secondURL), "Failed to diff ‘"+firstURL+"’ and ‘"+secondURL+"’.")
|
||||
|
||||
Prints("%s\n", diff)
|
||||
}
|
||||
}
|
||||
|
||||
// doDiff - Execute the diff command
|
||||
func doDiff(firstURL, secondURL string, recursive bool) <-chan DiffMessage {
|
||||
ch := make(chan DiffMessage, 10000)
|
||||
go doDiffInRoutine(firstURL, secondURL, recursive, ch)
|
||||
return ch
|
||||
doDiffMain(firstURL, secondURL)
|
||||
}
|
||||
|
||||
@@ -1,339 +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"
|
||||
"time"
|
||||
|
||||
"github.com/minio/mc/pkg/client"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
//
|
||||
// NOTE: All the parse rules should reduced to 1: Diff(First, Second).
|
||||
//
|
||||
// Valid cases
|
||||
// =======================
|
||||
// 1: diff(f, f) -> diff(f, f)
|
||||
// 2: diff(f, d) -> copy(f, d/f) -> 1
|
||||
// 3: diff(d1..., d2) -> []diff(d1/f, d2/f) -> []1
|
||||
//
|
||||
// InValid cases
|
||||
// =======================
|
||||
// 1. diff(d1..., d2) -> INVALID
|
||||
// 2. diff(d1..., d2...) -> INVALID
|
||||
//
|
||||
|
||||
// DiffMessage json container for diff messages
|
||||
type DiffMessage struct {
|
||||
FirstURL string `json:"first"`
|
||||
SecondURL string `json:"second"`
|
||||
Diff string `json:"diff"`
|
||||
Error *probe.Error `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// String colorized diff message
|
||||
func (d DiffMessage) String() string {
|
||||
msg := ""
|
||||
switch d.Diff {
|
||||
case "only-in-first":
|
||||
msg = console.Colorize("DiffMessage", "‘"+d.FirstURL+"’"+" and "+"‘"+d.SecondURL+"’") + console.Colorize("DiffOnlyInFirst", " - only in first.")
|
||||
case "type":
|
||||
msg = console.Colorize("DiffMessage", "‘"+d.FirstURL+"’"+" and "+"‘"+d.SecondURL+"’") + console.Colorize("DiffType", " - differ in type.")
|
||||
case "size":
|
||||
msg = console.Colorize("DiffMessage", "‘"+d.FirstURL+"’"+" and "+"‘"+d.SecondURL+"’") + console.Colorize("DiffSize", " - differ in size.")
|
||||
default:
|
||||
fatalIf(errDummy().Trace(), "Unhandled difference between ‘"+d.FirstURL+"’ and ‘"+d.SecondURL+"’.")
|
||||
}
|
||||
return msg
|
||||
|
||||
}
|
||||
|
||||
// JSON jsonified diff message
|
||||
func (d DiffMessage) JSON() string {
|
||||
diffJSONBytes, err := json.Marshal(d)
|
||||
fatalIf(probe.NewError(err), "Unable to marshal diff message ‘"+d.FirstURL+"’, ‘"+d.SecondURL+"’ and ‘"+d.Diff+"’.")
|
||||
|
||||
return string(diffJSONBytes)
|
||||
}
|
||||
|
||||
func doDiffInRoutine(firstURL, secondURL string, recursive bool, ch chan DiffMessage) {
|
||||
defer close(ch)
|
||||
firstClnt, firstContent, err := url2Stat(firstURL)
|
||||
if err != nil {
|
||||
ch <- DiffMessage{
|
||||
Error: err.Trace(firstURL),
|
||||
}
|
||||
return
|
||||
}
|
||||
secondClnt, secondContent, err := url2Stat(secondURL)
|
||||
if err != nil {
|
||||
ch <- DiffMessage{
|
||||
Error: err.Trace(secondURL),
|
||||
}
|
||||
return
|
||||
}
|
||||
if firstContent.Type.IsRegular() {
|
||||
switch {
|
||||
case secondContent.Type.IsDir():
|
||||
newSecondURL := urlJoinPath(secondURL, firstURL)
|
||||
doDiffObjects(firstURL, newSecondURL, ch)
|
||||
case !secondContent.Type.IsRegular():
|
||||
ch <- DiffMessage{
|
||||
FirstURL: firstURL,
|
||||
SecondURL: secondURL,
|
||||
Diff: "type",
|
||||
}
|
||||
return
|
||||
case secondContent.Type.IsRegular():
|
||||
doDiffObjects(firstURL, secondURL, ch)
|
||||
}
|
||||
}
|
||||
if firstContent.Type.IsDir() {
|
||||
switch {
|
||||
case !secondContent.Type.IsDir():
|
||||
ch <- DiffMessage{
|
||||
FirstURL: firstURL,
|
||||
SecondURL: secondURL,
|
||||
Diff: "type",
|
||||
}
|
||||
return
|
||||
default:
|
||||
doDiffDirs(firstClnt, secondClnt, recursive, ch)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// doDiffObjects - Diff two object URLs
|
||||
func doDiffObjects(firstURL, secondURL string, ch chan DiffMessage) {
|
||||
_, firstContent, errFirst := url2Stat(firstURL)
|
||||
_, secondContent, errSecond := url2Stat(secondURL)
|
||||
|
||||
switch {
|
||||
case errFirst != nil && errSecond == nil:
|
||||
ch <- DiffMessage{
|
||||
Error: errFirst.Trace(firstURL, secondURL),
|
||||
}
|
||||
return
|
||||
case errFirst == nil && errSecond != nil:
|
||||
ch <- DiffMessage{
|
||||
Error: errSecond.Trace(firstURL, secondURL),
|
||||
}
|
||||
return
|
||||
}
|
||||
if firstContent.Name == secondContent.Name {
|
||||
return
|
||||
}
|
||||
switch {
|
||||
case firstContent.Type.IsRegular():
|
||||
if !secondContent.Type.IsRegular() {
|
||||
ch <- DiffMessage{
|
||||
FirstURL: firstURL,
|
||||
SecondURL: secondURL,
|
||||
Diff: "type",
|
||||
}
|
||||
}
|
||||
default:
|
||||
ch <- DiffMessage{
|
||||
Error: errNotAnObject(firstURL).Trace(),
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if firstContent.Size != secondContent.Size {
|
||||
ch <- DiffMessage{
|
||||
FirstURL: firstURL,
|
||||
SecondURL: secondURL,
|
||||
Diff: "size",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func dodiff(firstClnt, secondClnt client.Client, ch chan DiffMessage) {
|
||||
for contentCh := range firstClnt.List(false) {
|
||||
if contentCh.Err != nil {
|
||||
ch <- DiffMessage{
|
||||
Error: contentCh.Err.Trace(firstClnt.URL().String()),
|
||||
}
|
||||
return
|
||||
}
|
||||
newFirstURL := urlJoinPath(firstClnt.URL().String(), contentCh.Content.Name)
|
||||
newSecondURL := urlJoinPath(secondClnt.URL().String(), contentCh.Content.Name)
|
||||
_, newFirstContent, errFirst := url2Stat(newFirstURL)
|
||||
_, newSecondContent, errSecond := url2Stat(newSecondURL)
|
||||
switch {
|
||||
case errFirst == nil && errSecond != nil:
|
||||
ch <- DiffMessage{
|
||||
FirstURL: newFirstURL,
|
||||
SecondURL: newSecondURL,
|
||||
Diff: "only-in-first",
|
||||
}
|
||||
continue
|
||||
case errFirst == nil && errSecond == nil:
|
||||
switch {
|
||||
case newFirstContent.Type.IsDir():
|
||||
if !newSecondContent.Type.IsDir() {
|
||||
ch <- DiffMessage{
|
||||
FirstURL: newFirstURL,
|
||||
SecondURL: newSecondURL,
|
||||
Diff: "type",
|
||||
}
|
||||
}
|
||||
continue
|
||||
case newFirstContent.Type.IsRegular():
|
||||
if !newSecondContent.Type.IsRegular() {
|
||||
ch <- DiffMessage{
|
||||
FirstURL: newFirstURL,
|
||||
SecondURL: newSecondURL,
|
||||
Diff: "type",
|
||||
}
|
||||
continue
|
||||
}
|
||||
doDiffObjects(newFirstURL, newSecondURL, ch)
|
||||
}
|
||||
}
|
||||
} // End of for-loop
|
||||
}
|
||||
|
||||
func dodiffRecursive(firstClnt, secondClnt client.Client, ch chan DiffMessage) {
|
||||
firstURLDelimited := firstClnt.URL().String()
|
||||
secondURLDelimited := secondClnt.URL().String()
|
||||
if strings.HasSuffix(firstURLDelimited, "/") == false {
|
||||
firstURLDelimited = firstURLDelimited + "/"
|
||||
}
|
||||
if strings.HasSuffix(secondURLDelimited, "/") == false {
|
||||
secondURLDelimited = secondURLDelimited + "/"
|
||||
}
|
||||
firstClnt, err := url2Client(firstURLDelimited)
|
||||
if err != nil {
|
||||
ch <- DiffMessage{Error: err.Trace()}
|
||||
return
|
||||
}
|
||||
secondClnt, err = url2Client(secondURLDelimited)
|
||||
if err != nil {
|
||||
ch <- DiffMessage{Error: err.Trace()}
|
||||
return
|
||||
}
|
||||
|
||||
doneCh := make(chan bool)
|
||||
defer close(doneCh)
|
||||
go func(doneCh <-chan bool) {
|
||||
cursorCh := cursorAnimate()
|
||||
for {
|
||||
select {
|
||||
case <-time.Tick(100 * time.Millisecond):
|
||||
if !globalQuietFlag && !globalJSONFlag {
|
||||
console.PrintC("\r" + "Scanning.. " + string(<-cursorCh))
|
||||
}
|
||||
case <-doneCh:
|
||||
return
|
||||
}
|
||||
}
|
||||
}(doneCh)
|
||||
doneCh <- true
|
||||
|
||||
if !globalQuietFlag && !globalJSONFlag {
|
||||
console.Eraseline()
|
||||
}
|
||||
|
||||
fch := firstClnt.List(true)
|
||||
sch := secondClnt.List(true)
|
||||
f, fok := <-fch
|
||||
s, sok := <-sch
|
||||
for {
|
||||
if fok == false {
|
||||
break
|
||||
}
|
||||
if f.Content.Type.IsDir() {
|
||||
// skip directories
|
||||
// there is no concept of directories on S3
|
||||
f, fok = <-fch
|
||||
continue
|
||||
}
|
||||
firstURL := firstURLDelimited + f.Content.Name
|
||||
secondURL := secondURLDelimited + f.Content.Name
|
||||
if sok == false {
|
||||
// Second list reached EOF
|
||||
ch <- DiffMessage{
|
||||
FirstURL: firstURL,
|
||||
SecondURL: secondURL,
|
||||
Diff: "only-in-first",
|
||||
}
|
||||
f, fok = <-fch
|
||||
continue
|
||||
}
|
||||
if s.Content.Type.IsDir() {
|
||||
// skip directories
|
||||
s, sok = <-sch
|
||||
continue
|
||||
}
|
||||
fC := f.Content
|
||||
sC := s.Content
|
||||
compare := strings.Compare(fC.Name, sC.Name)
|
||||
|
||||
if compare == 0 {
|
||||
if fC.Type.IsRegular() {
|
||||
if !sC.Type.IsRegular() {
|
||||
ch <- DiffMessage{
|
||||
FirstURL: firstURL,
|
||||
SecondURL: secondURL,
|
||||
Diff: "type",
|
||||
}
|
||||
}
|
||||
} else if fC.Type.IsDir() {
|
||||
if !sC.Type.IsDir() {
|
||||
ch <- DiffMessage{
|
||||
FirstURL: firstURL,
|
||||
SecondURL: secondURL,
|
||||
Diff: "type",
|
||||
}
|
||||
}
|
||||
} else if fC.Size != sC.Size {
|
||||
ch <- DiffMessage{
|
||||
FirstURL: firstURL,
|
||||
SecondURL: secondURL,
|
||||
Diff: "size",
|
||||
}
|
||||
}
|
||||
f, fok = <-fch
|
||||
s, sok = <-sch
|
||||
}
|
||||
if compare < 0 {
|
||||
ch <- DiffMessage{
|
||||
FirstURL: firstURL,
|
||||
SecondURL: secondURL,
|
||||
Diff: "only-in-first",
|
||||
}
|
||||
f, fok = <-fch
|
||||
}
|
||||
if compare > 0 {
|
||||
s, sok = <-sch
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// doDiffDirs - Diff two Dir URLs
|
||||
func doDiffDirs(firstClnt, secondClnt client.Client, recursive bool, ch chan DiffMessage) {
|
||||
if recursive {
|
||||
dodiffRecursive(firstClnt, secondClnt, ch)
|
||||
return
|
||||
}
|
||||
dodiff(firstClnt, secondClnt, ch)
|
||||
}
|
||||
-111
@@ -1,111 +0,0 @@
|
||||
/*
|
||||
* Minio Client (C) 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
. "gopkg.in/check.v1"
|
||||
)
|
||||
|
||||
func (s *TestSuite) TestDiffObjects(c *C) {
|
||||
/// filesystem
|
||||
root1, err := ioutil.TempDir(os.TempDir(), "cmd-")
|
||||
c.Assert(err, IsNil)
|
||||
defer os.RemoveAll(root1)
|
||||
|
||||
root2, err := ioutil.TempDir(os.TempDir(), "cmd-")
|
||||
c.Assert(err, IsNil)
|
||||
defer os.RemoveAll(root2)
|
||||
|
||||
objectPath1 := filepath.Join(root1, "object1")
|
||||
data := "hello"
|
||||
dataLen := len(data)
|
||||
perr := putTarget(objectPath1, int64(dataLen), bytes.NewReader([]byte(data)))
|
||||
c.Assert(perr, IsNil)
|
||||
|
||||
objectPath2 := filepath.Join(root2, "object1")
|
||||
data = "hello"
|
||||
dataLen = len(data)
|
||||
perr = putTarget(objectPath2, int64(dataLen), bytes.NewReader([]byte(data)))
|
||||
c.Assert(perr, IsNil)
|
||||
|
||||
for diff := range doDiff(objectPath1, objectPath2, false) {
|
||||
c.Assert(diff.Error, IsNil)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *TestSuite) TestDiffDirs(c *C) {
|
||||
/// filesystem
|
||||
root1, err := ioutil.TempDir(os.TempDir(), "cmd-")
|
||||
c.Assert(err, IsNil)
|
||||
defer os.RemoveAll(root1)
|
||||
|
||||
root2, err := ioutil.TempDir(os.TempDir(), "cmd-")
|
||||
c.Assert(err, IsNil)
|
||||
defer os.RemoveAll(root2)
|
||||
|
||||
var perr *probe.Error
|
||||
for i := 0; i < 10; i++ {
|
||||
objectPath := filepath.Join(root1, "object"+strconv.Itoa(i))
|
||||
data := "hello"
|
||||
dataLen := len(data)
|
||||
perr = putTarget(objectPath, int64(dataLen), bytes.NewReader([]byte(data)))
|
||||
c.Assert(perr, IsNil)
|
||||
}
|
||||
|
||||
for i := 0; i < 10; i++ {
|
||||
objectPath := filepath.Join(root2, "object"+strconv.Itoa(i))
|
||||
data := "hello"
|
||||
dataLen := len(data)
|
||||
perr = putTarget(objectPath, int64(dataLen), bytes.NewReader([]byte(data)))
|
||||
c.Assert(perr, IsNil)
|
||||
}
|
||||
|
||||
for diff := range doDiff(root1, root2, false) {
|
||||
c.Assert(diff.Error, IsNil)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *TestSuite) TestDiffContext(c *C) {
|
||||
err := app.Run([]string{os.Args[0], "diff", server.URL + "/bucket", server.URL + "/bucket"})
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(console.IsExited, Equals, false)
|
||||
|
||||
// reset back
|
||||
console.IsExited = false
|
||||
|
||||
err = app.Run([]string{os.Args[0], "diff", server.URL + "/bucket...", server.URL + "/bucket"})
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(console.IsExited, Equals, false)
|
||||
|
||||
// reset back
|
||||
console.IsExited = false
|
||||
|
||||
err = app.Run([]string{os.Args[0], "diff", server.URL + "/invalid", server.URL + "/invalid..."})
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(console.IsExited, Equals, true)
|
||||
|
||||
// reset back
|
||||
console.IsExited = false
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
/*
|
||||
* Minio Client (C) 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
|
||||
"github.com/minio/mc/pkg/client"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
)
|
||||
|
||||
// objectDifference function finds the difference between object on source and target
|
||||
// it takes suffix string, type and size on the source
|
||||
// objectDifferenceFactory returns objectDifference function
|
||||
type objectDifference func(string, os.FileMode, int64) (string, *probe.Error)
|
||||
|
||||
const (
|
||||
differSize string = "size" // differs in size
|
||||
differOnlyFirst string = "only-in-first" // only on source
|
||||
differType string = "type" // differs in type, ex file/directory
|
||||
differNone string = "" // does not differ
|
||||
)
|
||||
|
||||
// objectDifferenceFactory returns objectDifference function to check for difference
|
||||
// between sourceURL and targetURL
|
||||
// for usage reference check diff and mirror commands
|
||||
func objectDifferenceFactory(targetAlias, targetURL string) (objectDifference, *probe.Error) {
|
||||
clnt, err := newClientFromAlias(targetAlias, targetURL)
|
||||
if err != nil {
|
||||
return nil, err.Trace(targetAlias, targetURL)
|
||||
}
|
||||
isIncomplete := false
|
||||
isRecursive := true
|
||||
ch := clnt.List(isRecursive, isIncomplete)
|
||||
current := targetURL
|
||||
reachedEOF := false
|
||||
ok := false
|
||||
var content *client.Content
|
||||
|
||||
difference := func(suffix string, srcType os.FileMode, srcSize int64) (string, *probe.Error) {
|
||||
if reachedEOF {
|
||||
// would mean the suffix is not on target
|
||||
return differOnlyFirst, nil
|
||||
}
|
||||
expected := urlJoinPath(targetURL, suffix)
|
||||
for {
|
||||
if expected < current {
|
||||
return differOnlyFirst, nil // not available in the target
|
||||
}
|
||||
if expected == current {
|
||||
tgtType := content.Type
|
||||
tgtSize := content.Size
|
||||
if srcType.IsRegular() && !tgtType.IsRegular() {
|
||||
// Type differes. Source is never a directory
|
||||
return differType, nil
|
||||
}
|
||||
if (srcType.IsRegular() && tgtType.IsRegular()) && srcSize != tgtSize {
|
||||
// regular files differing in size
|
||||
return differSize, nil
|
||||
}
|
||||
return differNone, nil // available in the target
|
||||
}
|
||||
content, ok = <-ch
|
||||
if !ok {
|
||||
reachedEOF = true
|
||||
return differOnlyFirst, nil
|
||||
}
|
||||
if content.Err != nil {
|
||||
return "", content.Err.Trace()
|
||||
}
|
||||
current = content.URL.String()
|
||||
}
|
||||
}
|
||||
return difference, nil
|
||||
}
|
||||
@@ -19,16 +19,21 @@ package main
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
)
|
||||
|
||||
// ErrorMessage container for error messages
|
||||
type ErrorMessage struct {
|
||||
// causeMessage container for golang error messages
|
||||
type causeMessage struct {
|
||||
Message string `json:"message"`
|
||||
Error error `json:"error"`
|
||||
}
|
||||
|
||||
// errorMessage container for error messages
|
||||
type errorMessage struct {
|
||||
Message string `json:"message"`
|
||||
Cause error `json:"cause"`
|
||||
Cause causeMessage `json:"cause"`
|
||||
Type string `json:"type"`
|
||||
CallTrace []probe.TracePoint `json:"trace,omitempty"`
|
||||
SysInfo map[string]string `json:"sysinfo"`
|
||||
@@ -39,28 +44,33 @@ func fatalIf(err *probe.Error, msg string) {
|
||||
if err == nil {
|
||||
return
|
||||
}
|
||||
if globalJSONFlag {
|
||||
errorMessage := ErrorMessage{
|
||||
if globalJSON {
|
||||
errorMsg := errorMessage{
|
||||
Message: msg,
|
||||
Type: "fatal",
|
||||
Cause: err.ToGoError(),
|
||||
Cause: causeMessage{
|
||||
Message: err.ToGoError().Error(),
|
||||
Error: err.ToGoError(),
|
||||
},
|
||||
SysInfo: err.SysInfo,
|
||||
}
|
||||
if globalDebugFlag {
|
||||
errorMessage.CallTrace = err.CallTrace
|
||||
if globalDebug {
|
||||
errorMsg.CallTrace = err.CallTrace
|
||||
}
|
||||
json, err := json.Marshal(struct {
|
||||
Error ErrorMessage `json:"error"`
|
||||
json, e := json.Marshal(struct {
|
||||
Status string `json:"status"`
|
||||
Error errorMessage `json:"error"`
|
||||
}{
|
||||
Error: errorMessage,
|
||||
Status: "error",
|
||||
Error: errorMsg,
|
||||
})
|
||||
if err != nil {
|
||||
console.Fatalln(probe.NewError(err))
|
||||
if e != nil {
|
||||
console.Fatalln(probe.NewError(e))
|
||||
}
|
||||
console.Println(string(json))
|
||||
os.Exit(1)
|
||||
console.Fatalln()
|
||||
}
|
||||
if !globalDebugFlag {
|
||||
if !globalDebug {
|
||||
console.Fatalln(fmt.Sprintf("%s %s", msg, err.ToGoError()))
|
||||
}
|
||||
console.Fatalln(fmt.Sprintf("%s %s", msg, err))
|
||||
@@ -71,28 +81,33 @@ func errorIf(err *probe.Error, msg string) {
|
||||
if err == nil {
|
||||
return
|
||||
}
|
||||
if globalJSONFlag {
|
||||
errorMessage := ErrorMessage{
|
||||
if globalJSON {
|
||||
errorMsg := errorMessage{
|
||||
Message: msg,
|
||||
Type: "error",
|
||||
Cause: err.ToGoError(),
|
||||
Cause: causeMessage{
|
||||
Message: err.ToGoError().Error(),
|
||||
Error: err.ToGoError(),
|
||||
},
|
||||
SysInfo: err.SysInfo,
|
||||
}
|
||||
if globalDebugFlag {
|
||||
errorMessage.CallTrace = err.CallTrace
|
||||
if globalDebug {
|
||||
errorMsg.CallTrace = err.CallTrace
|
||||
}
|
||||
json, err := json.Marshal(struct {
|
||||
Error ErrorMessage `json:"error"`
|
||||
json, e := json.Marshal(struct {
|
||||
Status string `json:"status"`
|
||||
Error errorMessage `json:"error"`
|
||||
}{
|
||||
Error: errorMessage,
|
||||
Status: "error",
|
||||
Error: errorMsg,
|
||||
})
|
||||
if err != nil {
|
||||
console.Fatalln(probe.NewError(err))
|
||||
if e != nil {
|
||||
console.Fatalln(probe.NewError(e))
|
||||
}
|
||||
console.Println(string(json))
|
||||
return
|
||||
}
|
||||
if !globalDebugFlag {
|
||||
if !globalDebug {
|
||||
console.Errorln(fmt.Sprintf("%s %s", msg, err.ToGoError()))
|
||||
return
|
||||
}
|
||||
|
||||
@@ -21,54 +21,36 @@ import "github.com/minio/cli"
|
||||
// Collection of mc commands currently supported
|
||||
var commands = []cli.Command{}
|
||||
|
||||
// Collection of mc flags currently supported
|
||||
var flags = []cli.Flag{}
|
||||
|
||||
// Collection of mc commands currently supported in a trie tree
|
||||
var commandsTree = newTrie()
|
||||
|
||||
var (
|
||||
configFlag = cli.StringFlag{
|
||||
// Collection of mc flags currently supported
|
||||
var globalFlags = []cli.Flag{
|
||||
cli.StringFlag{
|
||||
Name: "config-folder, C",
|
||||
Value: mustGetMcConfigDir(),
|
||||
Usage: "Path to configuration folder.",
|
||||
}
|
||||
|
||||
quietFlag = cli.BoolFlag{
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "quiet, q",
|
||||
Usage: "Suppress chatty console output.",
|
||||
}
|
||||
|
||||
mimicFlag = cli.BoolFlag{
|
||||
Name: "mimic",
|
||||
Usage: "Behave like operating system tools. Use with shell aliases.",
|
||||
}
|
||||
|
||||
jsonFlag = cli.BoolFlag{
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "no-color",
|
||||
Usage: "Disable color theme.",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "json",
|
||||
Usage: "Enable json formatted output.",
|
||||
}
|
||||
|
||||
debugFlag = cli.BoolFlag{
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "debug",
|
||||
Usage: "Enable debugging output.",
|
||||
}
|
||||
|
||||
noColorFlag = cli.BoolFlag{
|
||||
Name: "nocolor",
|
||||
Usage: "Disable console coloring.",
|
||||
}
|
||||
|
||||
// Add your new flags starting here
|
||||
)
|
||||
},
|
||||
}
|
||||
|
||||
// registerCmd registers a cli command
|
||||
func registerCmd(cmd cli.Command) {
|
||||
commands = append(commands, cmd)
|
||||
commandsTree.Insert(cmd.Name)
|
||||
}
|
||||
|
||||
// registerFlag registers a cli flag
|
||||
func registerFlag(flag cli.Flag) {
|
||||
flags = append(flags, flag)
|
||||
}
|
||||
|
||||
+39
-18
@@ -17,17 +17,14 @@
|
||||
// This package contains all the global variables and constants. ONLY TO BE ACCESSED VIA GET/SET FUNCTIONS.
|
||||
package main
|
||||
|
||||
var (
|
||||
globalQuietFlag = false // Quiet flag set via command line
|
||||
globalMimicFlag = false // Unix flag set via command line
|
||||
globalJSONFlag = false // Json flag set via command line
|
||||
globalDebugFlag = false // Debug flag set via command line
|
||||
import (
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
)
|
||||
|
||||
// mc configuration related constants.
|
||||
const (
|
||||
globalMCConfigVersion = "5"
|
||||
globalMCVersion = mcVersion
|
||||
globalMCConfigVersion = "7"
|
||||
|
||||
globalMCConfigDir = ".mc/"
|
||||
globalMCConfigWindowsDir = "mc\\"
|
||||
@@ -36,15 +33,39 @@ const (
|
||||
// session config and shared urls related constants
|
||||
globalSessionDir = "session"
|
||||
globalSharedURLsDataDir = "share"
|
||||
|
||||
golbalSortedListDir = "sortedlist"
|
||||
|
||||
// default access and secret key
|
||||
// do not pass accesskeyid and secretaccesskey through cli
|
||||
// users should manually edit them, add a stub entry
|
||||
globalAccessKeyID = "YOUR-ACCESS-KEY-ID-HERE"
|
||||
globalSecretAccessKey = "YOUR-SECRET-ACCESS-KEY-HERE"
|
||||
|
||||
// default host
|
||||
globalExampleHostURL = "YOUR-EXAMPLE.COM"
|
||||
)
|
||||
|
||||
var (
|
||||
globalQuiet = false // Quiet flag set via command line
|
||||
globalJSON = false // Json flag set via command line
|
||||
globalDebug = false // Debug flag set via command line
|
||||
globalNoColor = false // Debug flag set via command line
|
||||
// WHEN YOU ADD NEXT GLOBAL FLAG, MAKE SURE TO ALSO UPDATE SESSION CODE AND CODE BELOW.
|
||||
)
|
||||
|
||||
// Set global states. NOTE: It is deliberately kept monolithic to ensure we dont miss out any flags.
|
||||
func setGlobals(quiet, debug, json, noColor bool) {
|
||||
globalQuiet = quiet
|
||||
globalDebug = debug
|
||||
globalJSON = json
|
||||
globalNoColor = noColor
|
||||
|
||||
// Enable debug messages if requested.
|
||||
if globalDebug == true {
|
||||
console.DebugPrint = true
|
||||
}
|
||||
|
||||
// Disable colorified messages if requested.
|
||||
if globalNoColor == true {
|
||||
console.SetColorOff()
|
||||
}
|
||||
}
|
||||
|
||||
// Set global states. NOTE: It is deliberately kept monolithic to ensure we dont miss out any flags.
|
||||
func setGlobalsFromContext(ctx *cli.Context) {
|
||||
quiet := ctx.Bool("quiet") || ctx.GlobalBool("quiet")
|
||||
debug := ctx.Bool("debug") || ctx.GlobalBool("debug")
|
||||
json := ctx.Bool("json") || ctx.GlobalBool("json")
|
||||
noColor := ctx.Bool("no-color") || ctx.GlobalBool("no-color")
|
||||
setGlobals(quiet, debug, json, noColor)
|
||||
}
|
||||
|
||||
@@ -1,61 +0,0 @@
|
||||
/*
|
||||
* Minio Client (C) 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
|
||||
"github.com/minio/mc/pkg/client"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
type hostConfig struct {
|
||||
AccessKeyID string `json:"accessKeyId"`
|
||||
SecretAccessKey string `json:"secretAccessKey"`
|
||||
API string `json:"api"`
|
||||
}
|
||||
|
||||
// getHostConfig retrieves host specific configuration such as access keys, certs.
|
||||
func getHostConfig(URL string) (hostConfig, *probe.Error) {
|
||||
config, err := getMcConfig()
|
||||
if err != nil {
|
||||
return hostConfig{}, err.Trace()
|
||||
}
|
||||
url := client.NewURL(URL)
|
||||
// No host matching or keys needed for filesystem requests
|
||||
if url.Type == client.Filesystem {
|
||||
hostCfg := hostConfig{
|
||||
AccessKeyID: "",
|
||||
SecretAccessKey: "",
|
||||
API: "fs",
|
||||
}
|
||||
return hostCfg, nil
|
||||
}
|
||||
if _, ok := config.Hosts[url.Host]; ok {
|
||||
return config.Hosts[url.Host], nil
|
||||
}
|
||||
for globURL, hostCfg := range config.Hosts {
|
||||
match, err := filepath.Match(globURL, url.Host)
|
||||
if err != nil {
|
||||
return hostConfig{}, errInvalidGlobURL(globURL, URL).Trace()
|
||||
}
|
||||
if match {
|
||||
return hostCfg, nil
|
||||
}
|
||||
}
|
||||
return hostConfig{}, errNoMatchingHost(URL).Trace()
|
||||
}
|
||||
+70
-50
@@ -25,96 +25,116 @@ import (
|
||||
"github.com/minio/mc/pkg/console"
|
||||
)
|
||||
|
||||
// ls specific flags.
|
||||
var (
|
||||
lsFlags = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "help, h",
|
||||
Usage: "Help of ls.",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "recursive, r",
|
||||
Usage: "List recursively.",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "incomplete, I",
|
||||
Usage: "Remove incomplete uploads.",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
// list files and folders.
|
||||
var lsCmd = cli.Command{
|
||||
Name: "ls",
|
||||
Usage: "List files and folders.",
|
||||
Action: mainList,
|
||||
Flags: append(lsFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
mc {{.Name}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
mc {{.Name}} TARGET [TARGET ...]
|
||||
mc {{.Name}} [FLAGS] TARGET [TARGET ...]
|
||||
|
||||
FLAGS:
|
||||
{{range .Flags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. List buckets on Amazon S3 cloud storage.
|
||||
$ mc {{.Name}} https://s3.amazonaws.com/
|
||||
[2015-01-20 15:42:00 PST] 0B rom/
|
||||
[2015-01-15 00:05:40 PST] 0B zek/
|
||||
$ mc {{.Name}} s3
|
||||
|
||||
2. List buckets from Amazon S3 cloud storage and recursively list objects from Minio cloud storage.
|
||||
$ mc {{.Name}} https://s3.amazonaws.com/ https://play.minio.io:9000/backup/...
|
||||
2015-01-15 00:05:40 PST 0B zek/
|
||||
2015-03-31 14:46:33 PDT 55MiB 2006-Mar-1/backup.tar.gz
|
||||
2. List buckets and all its contents from Amazon S3 cloud storage recursively.
|
||||
$ mc {{.Name}} --recursive s3
|
||||
|
||||
3. List files recursively on local filesystem on Windows.
|
||||
$ mc {{.Name}} C:\Users\Worf\...
|
||||
[2015-03-28 12:47:50 PDT] 11.00MiB Martok\Klingon Council Ministers.pdf
|
||||
[2015-03-31 14:46:33 PDT] 15.00MiB Gowron\Khitomer Conference Details.pdf
|
||||
3. List all contents of mybucket on Amazon S3 cloud storage.
|
||||
$ mc {{.Name}} s3/mybucket/
|
||||
|
||||
4. List files with non english characters on Amazon S3 cloud storage.
|
||||
$ mc ls s3/andoria/本...
|
||||
[2015-05-19 17:24:19 PDT] 41B 本語.txt
|
||||
[2015-05-19 17:28:22 PDT] 41B 本語.md
|
||||
4. List all contents of mybucket on Amazon S3 cloud storage on Microsoft Windows.
|
||||
$ mc {{.Name}} s3\mybucket\
|
||||
|
||||
5. List files with space characters on Amazon S3 cloud storage.
|
||||
$ mc ls 's3/miniocloud/Community Files/'
|
||||
[2015-05-19 17:24:19 PDT] 41B 本語.txt
|
||||
[2015-05-19 17:28:22 PDT] 41B 本語.md
|
||||
|
||||
6. Behave like operating system tool ‘ls’, used for shell aliases.
|
||||
$ mc --mimic ls
|
||||
[2015-05-19 17:28:22 PDT] 41B 本語.md
|
||||
5. List files recursively on a local filesystem on Microsoft Windows.
|
||||
$ mc {{.Name}} --recursive C:\Users\Worf\
|
||||
|
||||
6. List incomplete (previously failed) uploads of objects on Amazon S3.
|
||||
$ mc {{.Name}} --incomplete s3/mybucket
|
||||
`,
|
||||
}
|
||||
|
||||
// checkListSyntax - validate all the passed arguments
|
||||
func checkListSyntax(ctx *cli.Context) {
|
||||
args := ctx.Args()
|
||||
if !ctx.Args().Present() {
|
||||
if globalMimicFlag {
|
||||
args = []string{"."}
|
||||
} else {
|
||||
cli.ShowCommandHelpAndExit(ctx, "ls", 1) // last argument is exit code
|
||||
}
|
||||
}
|
||||
if ctx.Args().First() == "help" {
|
||||
cli.ShowCommandHelpAndExit(ctx, "ls", 1) // last argument is exit code
|
||||
args = []string{"."}
|
||||
}
|
||||
for _, arg := range args {
|
||||
if strings.TrimSpace(arg) == "" {
|
||||
fatalIf(errInvalidArgument().Trace(), "Unable to validate empty argument.")
|
||||
fatalIf(errInvalidArgument().Trace(args...), "Unable to validate empty argument.")
|
||||
}
|
||||
}
|
||||
// extract URLs.
|
||||
URLs := ctx.Args()
|
||||
isIncomplete := ctx.Bool("incomplete")
|
||||
|
||||
for _, url := range URLs {
|
||||
_, _, err := url2Stat(url)
|
||||
if err != nil && !isURLPrefixExists(url, isIncomplete) {
|
||||
fatalIf(err.Trace(url), "Unable to stat ‘"+url+"’.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// mainList - is a handler for mc ls command
|
||||
func mainList(ctx *cli.Context) {
|
||||
// Additional command speific theme customization.
|
||||
console.SetColor("File", color.New(color.FgWhite))
|
||||
console.SetColor("Dir", color.New(color.FgCyan, color.Bold))
|
||||
console.SetColor("Size", color.New(color.FgYellow))
|
||||
console.SetColor("Time", color.New(color.FgGreen))
|
||||
|
||||
// Set global flags from context.
|
||||
setGlobalsFromContext(ctx)
|
||||
|
||||
// check 'ls' cli arguments.
|
||||
checkListSyntax(ctx)
|
||||
|
||||
// Set command flags from context.
|
||||
isRecursive := ctx.Bool("recursive")
|
||||
isIncomplete := ctx.Bool("incomplete")
|
||||
|
||||
args := ctx.Args()
|
||||
// Operating system tool behavior
|
||||
if globalMimicFlag && !ctx.Args().Present() {
|
||||
// mimic operating system tool behavior.
|
||||
if !ctx.Args().Present() {
|
||||
args = []string{"."}
|
||||
}
|
||||
|
||||
console.SetCustomTheme(map[string]*color.Color{
|
||||
"File": color.New(color.FgWhite),
|
||||
"Dir": color.New(color.FgCyan, color.Bold),
|
||||
"Size": color.New(color.FgYellow),
|
||||
"Time": color.New(color.FgGreen),
|
||||
})
|
||||
|
||||
targetURLs, err := args2URLs(args)
|
||||
fatalIf(err.Trace(args...), "One or more unknown URL types passed.")
|
||||
|
||||
for _, targetURL := range targetURLs {
|
||||
// if recursive strip off the "..."
|
||||
for _, targetURL := range args {
|
||||
var clnt client.Client
|
||||
clnt, err = target2Client(stripRecursiveURL(targetURL))
|
||||
clnt, err := newClient(targetURL)
|
||||
fatalIf(err.Trace(targetURL), "Unable to initialize target ‘"+targetURL+"’.")
|
||||
|
||||
err = doList(clnt, isURLRecursive(targetURL), len(targetURLs) > 1)
|
||||
fatalIf(err.Trace(clnt.URL().String()), "Unable to list target ‘"+clnt.URL().String()+"’.")
|
||||
err = doList(clnt, isRecursive, isIncomplete)
|
||||
if err != nil {
|
||||
errorIf(err.Trace(clnt.GetURL().String()), "Unable to list target ‘"+clnt.GetURL().String()+"’.")
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,7 +19,6 @@ package main
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
@@ -28,38 +27,39 @@ import (
|
||||
"github.com/dustin/go-humanize"
|
||||
"github.com/minio/mc/pkg/client"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
)
|
||||
|
||||
/// ls - related internal functions
|
||||
|
||||
// printDate - human friendly formatted date.
|
||||
const (
|
||||
printDate = "2006-01-02 15:04:05 MST"
|
||||
)
|
||||
|
||||
// ContentMessage container for content message structure.
|
||||
type ContentMessage struct {
|
||||
// contentMessage container for content message structure.
|
||||
type contentMessage struct {
|
||||
Status string `json:"status"`
|
||||
Filetype string `json:"type"`
|
||||
Time time.Time `json:"lastModified"`
|
||||
Size int64 `json:"size"`
|
||||
Name string `json:"name"`
|
||||
Key string `json:"key"`
|
||||
}
|
||||
|
||||
// String colorized string message
|
||||
func (c ContentMessage) String() string {
|
||||
// String colorized string message.
|
||||
func (c contentMessage) String() string {
|
||||
message := console.Colorize("Time", fmt.Sprintf("[%s] ", c.Time.Format(printDate)))
|
||||
message = message + console.Colorize("Size", fmt.Sprintf("%6s ", humanize.IBytes(uint64(c.Size))))
|
||||
message = func() string {
|
||||
if c.Filetype == "folder" {
|
||||
return message + console.Colorize("Dir", fmt.Sprintf("%s", c.Name))
|
||||
return message + console.Colorize("Dir", fmt.Sprintf("%s", c.Key))
|
||||
}
|
||||
return message + console.Colorize("File", fmt.Sprintf("%s", c.Name))
|
||||
return message + console.Colorize("File", fmt.Sprintf("%s", c.Key))
|
||||
}()
|
||||
return message
|
||||
}
|
||||
|
||||
// JSON jsonified content message
|
||||
func (c ContentMessage) JSON() string {
|
||||
// JSON jsonified content message.
|
||||
func (c contentMessage) JSON() string {
|
||||
c.Status = "success"
|
||||
jsonMessageBytes, e := json.Marshal(c)
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
@@ -67,11 +67,11 @@ func (c ContentMessage) JSON() string {
|
||||
}
|
||||
|
||||
// parseContent parse client Content container into printer struct.
|
||||
func parseContent(c *client.Content) ContentMessage {
|
||||
content := ContentMessage{}
|
||||
func parseContent(c *client.Content) contentMessage {
|
||||
content := contentMessage{}
|
||||
content.Time = c.Time.Local()
|
||||
|
||||
// guess file type
|
||||
// guess file type.
|
||||
content.Filetype = func() string {
|
||||
if c.Type.IsDir() {
|
||||
return "folder"
|
||||
@@ -81,62 +81,66 @@ func parseContent(c *client.Content) ContentMessage {
|
||||
|
||||
content.Size = c.Size
|
||||
// Convert OS Type to match console file printing style.
|
||||
content.Name = func() string {
|
||||
content.Key = func() string {
|
||||
switch {
|
||||
// for windows make sure to print in 'windows' specific style.
|
||||
case runtime.GOOS == "windows":
|
||||
c.Name = strings.Replace(c.Name, "/", "\\", -1)
|
||||
c.Name = strings.TrimSuffix(c.Name, "\\")
|
||||
c.URL.Path = strings.Replace(c.URL.Path, "/", "\\", -1)
|
||||
c.URL.Path = strings.TrimSuffix(c.URL.Path, "\\")
|
||||
default:
|
||||
c.Name = strings.TrimSuffix(c.Name, "/")
|
||||
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.Name)
|
||||
return fmt.Sprintf("%s\\", c.URL.Path)
|
||||
default:
|
||||
return fmt.Sprintf("%s/", c.Name)
|
||||
return fmt.Sprintf("%s/", c.URL.Path)
|
||||
}
|
||||
}
|
||||
return c.Name
|
||||
return c.URL.Path
|
||||
}()
|
||||
return content
|
||||
}
|
||||
|
||||
// doList - list all entities inside a folder.
|
||||
func doList(clnt client.Client, recursive, multipleArgs bool) *probe.Error {
|
||||
var err *probe.Error
|
||||
var parentContent *client.Content
|
||||
parentContent, err = clnt.Stat()
|
||||
if err != nil {
|
||||
return err.Trace(clnt.URL().String())
|
||||
func doList(clnt client.Client, isRecursive, isIncomplete bool) *probe.Error {
|
||||
prefixPath := clnt.GetURL().Path
|
||||
separator := string(clnt.GetURL().Separator)
|
||||
if !strings.HasSuffix(prefixPath, separator) {
|
||||
prefixPath = prefixPath[:strings.LastIndex(prefixPath, separator)+1]
|
||||
}
|
||||
for contentCh := range clnt.List(recursive) {
|
||||
if contentCh.Err != nil {
|
||||
switch contentCh.Err.ToGoError().(type) {
|
||||
// handle this specifically for filesystem
|
||||
case client.ISBrokenSymlink:
|
||||
errorIf(contentCh.Err.Trace(), "Unable to list broken link.")
|
||||
for content := range clnt.List(isRecursive, isIncomplete) {
|
||||
if content.Err != nil {
|
||||
switch content.Err.ToGoError().(type) {
|
||||
// handle this specifically for filesystem related errors.
|
||||
case client.BrokenSymlink:
|
||||
errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list broken link.")
|
||||
continue
|
||||
case client.TooManyLevelsSymlink:
|
||||
errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list too many levels link.")
|
||||
continue
|
||||
case client.PathNotFound:
|
||||
errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list folder.")
|
||||
continue
|
||||
case client.PathInsufficientPermission:
|
||||
errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list folder.")
|
||||
continue
|
||||
}
|
||||
if os.IsNotExist(contentCh.Err.ToGoError()) || os.IsPermission(contentCh.Err.ToGoError()) {
|
||||
if contentCh.Content != nil {
|
||||
if contentCh.Content.Type.IsDir() && (contentCh.Content.Type&os.ModeSymlink == os.ModeSymlink) {
|
||||
continue
|
||||
}
|
||||
}
|
||||
errorIf(contentCh.Err.Trace(), "Unable to list.")
|
||||
continue
|
||||
}
|
||||
err = contentCh.Err.Trace()
|
||||
break
|
||||
errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list folder.")
|
||||
continue
|
||||
}
|
||||
if multipleArgs && parentContent.Type.IsDir() {
|
||||
contentCh.Content.Name = filepath.Join(parentContent.Name, strings.TrimPrefix(contentCh.Content.Name, parentContent.Name))
|
||||
}
|
||||
Prints("%s\n", parseContent(contentCh.Content))
|
||||
}
|
||||
if err != nil {
|
||||
return err.Trace()
|
||||
// Convert any os specific delimiters to "/".
|
||||
contentURL := filepath.ToSlash(content.URL.Path)
|
||||
prefixPath = filepath.ToSlash(prefixPath)
|
||||
|
||||
// Trim prefix path from the content path.
|
||||
contentURL = strings.TrimPrefix(contentURL, prefixPath)
|
||||
content.URL.Path = contentURL
|
||||
parsedContent := parseContent(content)
|
||||
// Print colorized or jsonized content info.
|
||||
printMsg(parsedContent)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
-71
@@ -15,74 +15,3 @@
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
. "gopkg.in/check.v1"
|
||||
)
|
||||
|
||||
func (s *TestSuite) TestLSContext(c *C) {
|
||||
/// filesystem
|
||||
root, err := ioutil.TempDir(os.TempDir(), "cmd-")
|
||||
c.Assert(err, IsNil)
|
||||
defer os.RemoveAll(root)
|
||||
|
||||
var perr *probe.Error
|
||||
for i := 0; i < 10; i++ {
|
||||
objectPath := filepath.Join(root, "object"+strconv.Itoa(i))
|
||||
data := "hello"
|
||||
dataLen := len(data)
|
||||
perr = putTarget(objectPath, int64(dataLen), bytes.NewReader([]byte(data)))
|
||||
c.Assert(perr, IsNil)
|
||||
}
|
||||
|
||||
for i := 0; i < 10; i++ {
|
||||
objectPath := server.URL + "/bucket/object" + strconv.Itoa(i)
|
||||
data := "hello"
|
||||
dataLen := len(data)
|
||||
perr := putTarget(objectPath, int64(dataLen), bytes.NewReader([]byte(data)))
|
||||
c.Assert(perr, IsNil)
|
||||
}
|
||||
|
||||
err = app.Run([]string{os.Args[0], "ls", root})
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(console.IsError, Equals, false)
|
||||
|
||||
// reset back
|
||||
console.IsExited = false
|
||||
|
||||
err = app.Run([]string{os.Args[0], "ls", root + "..."})
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(console.IsError, Equals, false)
|
||||
|
||||
// reset back
|
||||
console.IsExited = false
|
||||
|
||||
err = app.Run([]string{os.Args[0], "ls", server.URL + "/bucket"})
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(console.IsError, Equals, false)
|
||||
|
||||
// reset back
|
||||
console.IsExited = false
|
||||
|
||||
err = app.Run([]string{os.Args[0], "ls", server.URL + "/bucket..."})
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(console.IsError, Equals, false)
|
||||
|
||||
// reset back
|
||||
console.IsExited = false
|
||||
|
||||
err = app.Run([]string{os.Args[0], "ls", server.URL + "/invalid"})
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(console.IsExited, Equals, true)
|
||||
|
||||
// reset back
|
||||
console.IsExited = false
|
||||
}
|
||||
|
||||
@@ -19,49 +19,88 @@ package main
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/user"
|
||||
"runtime"
|
||||
"sort"
|
||||
"strconv"
|
||||
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/minio/pkg/contentdb"
|
||||
"github.com/minio/pb"
|
||||
"github.com/olekukonko/ts"
|
||||
)
|
||||
|
||||
// Check for the user id erarly on and gracefully report.
|
||||
func checkUser() {
|
||||
_, e := user.Current()
|
||||
fatalIf(probe.NewError(e), "Unable to determine current user.")
|
||||
var (
|
||||
// global flags for mc.
|
||||
mcFlags = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "help, h",
|
||||
Usage: "Show help.",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
if runtime.GOOS != "windows" {
|
||||
if os.Geteuid() == 0 {
|
||||
fatalIf(errDummy().Trace(), "Please run as a normal user, running as root is disallowed")
|
||||
// Help template for mc
|
||||
var mcHelpTemplate = `NAME:
|
||||
{{.Name}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.Name}} {{if .Flags}}[FLAGS] {{end}}COMMAND{{if .Flags}} [COMMAND FLAGS | -h]{{end}} [ARGUMENTS...]
|
||||
|
||||
COMMANDS:
|
||||
{{range .Commands}}{{join .Names ", "}}{{ "\t" }}{{.Usage}}
|
||||
{{end}}{{if .Flags}}
|
||||
GLOBAL FLAGS:
|
||||
{{range .Flags}}{{.}}
|
||||
{{end}}{{end}}
|
||||
VERSION:
|
||||
` + mcVersion +
|
||||
`{{ "\n"}}{{range $key, $value := ExtraInfo}}
|
||||
{{$key}}:
|
||||
{{$value}}
|
||||
{{end}}`
|
||||
|
||||
// Function invoked when invalid command is passed.
|
||||
func commandNotFound(ctx *cli.Context, command string) {
|
||||
msg := fmt.Sprintf("‘%s’ is not a mc command. See ‘mc --help’.", command)
|
||||
closestCommands := findClosestCommands(command)
|
||||
if len(closestCommands) > 0 {
|
||||
msg += fmt.Sprintf("\n\nDid you mean one of these?\n")
|
||||
if len(closestCommands) == 1 {
|
||||
cmd := closestCommands[0]
|
||||
msg += fmt.Sprintf(" ‘%s’", cmd)
|
||||
} else {
|
||||
for _, cmd := range closestCommands {
|
||||
msg += fmt.Sprintf(" ‘%s’\n", cmd)
|
||||
}
|
||||
}
|
||||
}
|
||||
fatalIf(errDummy().Trace(), msg)
|
||||
}
|
||||
|
||||
// Check for sane config environment early on and gracefully report.
|
||||
func checkConfig() {
|
||||
// Ensures config file is sane
|
||||
_, err := getMcConfig()
|
||||
fatalIf(err.Trace(), "Unable to access configuration file.")
|
||||
// Ensures config file is sane.
|
||||
_, err := loadMcConfig()
|
||||
fatalIf(err.Trace(mustGetMcConfigPath()), "Unable to access configuration file.")
|
||||
}
|
||||
|
||||
func migrate() {
|
||||
// Fix broken config files if any.
|
||||
fixConfig()
|
||||
|
||||
// Migrate config files if any.
|
||||
migrateConfig()
|
||||
|
||||
// Migrate session files if any.
|
||||
migrateSession()
|
||||
|
||||
// Migrate shared urls if any.
|
||||
migrateSharedURLs()
|
||||
migrateShare()
|
||||
}
|
||||
|
||||
// Get os/arch/platform specific information.
|
||||
// Returns a map of current os/arch/platform/memstats
|
||||
// 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.")
|
||||
@@ -84,109 +123,83 @@ func getSystemData() map[string]string {
|
||||
|
||||
func registerBefore(ctx *cli.Context) error {
|
||||
setMcConfigDir(ctx.GlobalString("config-folder"))
|
||||
globalQuietFlag = ctx.GlobalBool("quiet")
|
||||
globalMimicFlag = ctx.GlobalBool("mimic")
|
||||
globalDebugFlag = ctx.GlobalBool("debug")
|
||||
globalJSONFlag = ctx.GlobalBool("json")
|
||||
if globalDebugFlag {
|
||||
console.NoDebugPrint = false
|
||||
}
|
||||
if ctx.GlobalBool("nocolor") {
|
||||
console.SetNoColor()
|
||||
}
|
||||
|
||||
// check if mc is being run as root
|
||||
checkUser()
|
||||
// verify golang runtime
|
||||
// Verify golang runtime.
|
||||
verifyMCRuntime()
|
||||
|
||||
// Migrate any old version of config / state files to newer format.
|
||||
migrate()
|
||||
// checkConfig if it can be read
|
||||
|
||||
// Set global flags.
|
||||
setGlobalsFromContext(ctx)
|
||||
|
||||
// Checkconfig if it can be read.
|
||||
checkConfig()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// findClosestCommands to match a given string with commands trie tree.
|
||||
func findClosestCommands(command string) []string {
|
||||
var closestCommands []string
|
||||
for _, value := range commandsTree.PrefixMatch(command) {
|
||||
closestCommands = append(closestCommands, value.(string))
|
||||
}
|
||||
sort.Strings(closestCommands)
|
||||
// Suggest other close commands - allow missed, wrongly added and even transposed characters
|
||||
for _, value := range commandsTree.walk(commandsTree.root) {
|
||||
if sort.SearchStrings(closestCommands, value.(string)) < len(closestCommands) {
|
||||
continue
|
||||
}
|
||||
// 2 is arbitrary and represents the max allowed number of typed errors
|
||||
if DamerauLevenshteinDistance(command, value.(string)) < 2 {
|
||||
closestCommands = append(closestCommands, value.(string))
|
||||
}
|
||||
}
|
||||
return closestCommands
|
||||
}
|
||||
|
||||
func registerApp() *cli.App {
|
||||
// Register all the commands
|
||||
// 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(sessionCmd) // Manage sessions for copy and mirror.
|
||||
registerCmd(shareCmd) // Share documents via URL.
|
||||
registerCmd(diffCmd) // Computer differences between two files or folders.
|
||||
registerCmd(rmCmd) // Remove a file or bucket
|
||||
registerCmd(accessCmd) // Set access permissions.
|
||||
registerCmd(sessionCmd) // Manage sessions for copy and mirror.
|
||||
registerCmd(configCmd) // Configure minio client.
|
||||
registerCmd(updateCmd) // Check for new software updates.
|
||||
registerCmd(versionCmd) // Print version.
|
||||
|
||||
// register all the flags
|
||||
registerFlag(configFlag) // Path to configuration folder.
|
||||
registerFlag(quietFlag) // Suppress chatty console output.
|
||||
registerFlag(mimicFlag) // Behave like operating system tools. Use with shell aliases.
|
||||
registerFlag(jsonFlag) // Enable json formatted output.
|
||||
registerFlag(debugFlag) // Enable debugging output.
|
||||
registerFlag(noColorFlag) // Disable console coloring.
|
||||
|
||||
app := cli.NewApp()
|
||||
app.Usage = "Minio Client for cloud storage and filesystems."
|
||||
// hide --version flag, version is a command
|
||||
app.HideVersion = true
|
||||
app.Commands = commands
|
||||
app.Flags = flags
|
||||
app.Author = "Minio.io"
|
||||
app.CustomAppHelpTemplate = `NAME:
|
||||
{{.Name}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.Name}} {{if .Flags}}[global flags] {{end}}command{{if .Flags}} [command flags]{{end}} [arguments...]
|
||||
|
||||
COMMANDS:
|
||||
{{range .Commands}}{{join .Names ", "}}{{ "\t" }}{{.Usage}}
|
||||
{{end}}{{if .Flags}}
|
||||
GLOBAL FLAGS:
|
||||
{{range .Flags}}{{.}}
|
||||
{{end}}{{end}}
|
||||
VERSION:
|
||||
` + mcVersion +
|
||||
`{{ "\n"}} {{range $key, $value := ExtraInfo}}
|
||||
{{$key}}:
|
||||
{{$value}}
|
||||
{{end}}`
|
||||
app.CommandNotFound = func(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")
|
||||
for _, cmd := range closestCommands {
|
||||
msg += fmt.Sprintf(" ‘%s’\n", cmd)
|
||||
}
|
||||
}
|
||||
fatalIf(errDummy().Trace(), msg)
|
||||
|
||||
}
|
||||
app.Flags = append(mcFlags, globalFlags...)
|
||||
app.CustomAppHelpTemplate = mcHelpTemplate
|
||||
app.CommandNotFound = commandNotFound // handler function declared above.
|
||||
return app
|
||||
}
|
||||
|
||||
func main() {
|
||||
probe.Init() // Set project's root source path.
|
||||
probe.SetAppInfo("Release-Tag", mcReleaseTag)
|
||||
probe.SetAppInfo("Commit", mcShortCommitID)
|
||||
|
||||
contentdb.Init() // Load contentdb into memory.
|
||||
app := registerApp()
|
||||
app.Before = registerBefore
|
||||
|
||||
app.ExtraInfo = func() map[string]string {
|
||||
if _, e := ts.GetSize(); e != nil {
|
||||
globalQuietFlag = true
|
||||
globalQuiet = true
|
||||
}
|
||||
|
||||
if globalDebugFlag {
|
||||
if globalDebug {
|
||||
return getSystemData()
|
||||
}
|
||||
return make(map[string]string)
|
||||
|
||||
+61
-47
@@ -18,12 +18,25 @@ package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
)
|
||||
|
||||
var (
|
||||
mbFlags = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "help, h",
|
||||
Usage: "Help of mb.",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "region",
|
||||
Value: "us-east-1",
|
||||
Usage: "Specify bucket region. Defaults to ‘us-east-1’.",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
// make a bucket or folder.
|
||||
@@ -31,83 +44,84 @@ var mbCmd = cli.Command{
|
||||
Name: "mb",
|
||||
Usage: "Make a bucket or folder.",
|
||||
Action: mainMakeBucket,
|
||||
Flags: append(mbFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
mc {{.Name}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
mc {{.Name}} TARGET [TARGET ...]
|
||||
mc {{.Name}} [FLAGS] TARGET [TARGET...]
|
||||
|
||||
FLAGS:
|
||||
{{range .Flags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Create a bucket on Amazon S3 cloud storage.
|
||||
$ mc {{.Name}} https://s3.amazonaws.com/public-document-store
|
||||
$ mc {{.Name}} s3/mynewbucket
|
||||
|
||||
3. Make a folder on local filesystem with space characters
|
||||
$ mc {{.Name}} 'My Documents'
|
||||
2. Create a new bucket on Google Cloud Storage.
|
||||
$ mc {{.Name}} gcs/miniocloud
|
||||
|
||||
3. Create a bucket on Minio cloud storage.
|
||||
$ mc {{.Name}} https://play.minio.io:9000/mongodb-backup
|
||||
4. Create a new bucket on Amazon S3 cloud storage in region ‘us-west-2’.
|
||||
$ mc {{.Name}} --region=us-west-2 s3/myregionbucket
|
||||
|
||||
5. Create a new directory including its missing parents (equivalent to ‘mkdir -p’).
|
||||
$ mc {{.Name}} /tmp/this/new/dir1
|
||||
`,
|
||||
}
|
||||
|
||||
// MakeBucketMessage is container for make bucket success and failure messages
|
||||
type MakeBucketMessage struct {
|
||||
// makeBucketMessage is container for make bucket success and failure messages.
|
||||
type makeBucketMessage struct {
|
||||
Status string `json:"status"`
|
||||
Bucket string `json:"bucket"`
|
||||
Region string `json:"region"`
|
||||
}
|
||||
|
||||
// String colorized make bucket message
|
||||
func (s MakeBucketMessage) String() string {
|
||||
return console.Colorize("MakeBucket", "Bucket created successfully ‘"+s.Bucket+"’")
|
||||
// String colorized make bucket message.
|
||||
func (s makeBucketMessage) String() string {
|
||||
return console.Colorize("MakeBucket", "Bucket created successfully ‘"+s.Bucket+"’.")
|
||||
}
|
||||
|
||||
// JSON jsonified make bucket message
|
||||
func (s MakeBucketMessage) JSON() string {
|
||||
makeBucketJSONBytes, err := json.Marshal(s)
|
||||
fatalIf(probe.NewError(err), "Unable to marshal into JSON.")
|
||||
// JSON jsonified make bucket message.
|
||||
func (s makeBucketMessage) JSON() string {
|
||||
makeBucketJSONBytes, e := json.Marshal(s)
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(makeBucketJSONBytes)
|
||||
}
|
||||
|
||||
// Validate command line arguments.
|
||||
func checkMakeBucketSyntax(ctx *cli.Context) {
|
||||
if !ctx.Args().Present() || ctx.Args().First() == "help" {
|
||||
if !ctx.Args().Present() {
|
||||
cli.ShowCommandHelpAndExit(ctx, "mb", 1) // last argument is exit code
|
||||
}
|
||||
for _, arg := range ctx.Args() {
|
||||
if strings.TrimSpace(arg) == "" {
|
||||
fatalIf(errInvalidArgument().Trace(), "Unable to validate empty argument.")
|
||||
}
|
||||
if len(ctx.Args()) != 1 {
|
||||
fatalIf(errInvalidArgument().Trace(ctx.Args()...), "Incorrect number of arguments for mb command.")
|
||||
}
|
||||
}
|
||||
|
||||
// mainMakeBucket is the handler for mc mb command
|
||||
// mainMakeBucket is entry point for mb command.
|
||||
func mainMakeBucket(ctx *cli.Context) {
|
||||
// Set global flags from context.
|
||||
setGlobalsFromContext(ctx)
|
||||
|
||||
// check 'mb' cli arguments.
|
||||
checkMakeBucketSyntax(ctx)
|
||||
|
||||
console.SetCustomTheme(map[string]*color.Color{
|
||||
"MakeBucket": color.New(color.FgGreen, color.Bold),
|
||||
})
|
||||
// Additional command speific theme customization.
|
||||
console.SetColor("MakeBucket", color.New(color.FgGreen, color.Bold))
|
||||
|
||||
config := mustGetMcConfig()
|
||||
for _, arg := range ctx.Args() {
|
||||
targetURL := getAliasURL(arg, config.Aliases)
|
||||
// save region.
|
||||
region := ctx.String("region")
|
||||
|
||||
fatalIf(doMakeBucket(targetURL).Trace(targetURL), "Unable to make bucket ‘"+targetURL+"’.")
|
||||
Prints("%s\n", MakeBucketMessage{
|
||||
Status: "success",
|
||||
Bucket: targetURL,
|
||||
})
|
||||
}
|
||||
}
|
||||
targetURL := ctx.Args().First()
|
||||
// Instantiate client for URL.
|
||||
clnt, err := newClient(targetURL)
|
||||
fatalIf(err.Trace(targetURL), "Invalid target ‘"+targetURL+"’.")
|
||||
|
||||
// doMakeBucket -
|
||||
func doMakeBucket(targetURL string) *probe.Error {
|
||||
clnt, err := target2Client(targetURL)
|
||||
if err != nil {
|
||||
return err.Trace(targetURL)
|
||||
}
|
||||
err = clnt.MakeBucket()
|
||||
if err != nil {
|
||||
return err.Trace(targetURL)
|
||||
}
|
||||
return nil
|
||||
// Make bucket.
|
||||
err = clnt.MakeBucket(region)
|
||||
fatalIf(err.Trace(targetURL), "Unable to make bucket ‘"+targetURL+"’.")
|
||||
|
||||
// Successfully created a bucket.
|
||||
printMsg(makeBucketMessage{Status: "success", Bucket: targetURL})
|
||||
}
|
||||
|
||||
@@ -1,107 +0,0 @@
|
||||
/*
|
||||
* Minio Client (C) 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
|
||||
"github.com/minio/mc/pkg/console"
|
||||
. "gopkg.in/check.v1"
|
||||
)
|
||||
|
||||
func (s *TestSuite) TestMbAndAccess(c *C) {
|
||||
perr := doMakeBucket(server.URL + "/bucket")
|
||||
c.Assert(perr, IsNil)
|
||||
|
||||
perr = doSetAccess(server.URL+"/bucket", "public-read-write")
|
||||
c.Assert(perr, IsNil)
|
||||
|
||||
perr = doSetAccess(server.URL+"/bucket", "invalid")
|
||||
c.Assert(perr, Not(IsNil))
|
||||
|
||||
perm, perr := doGetAccess(server.URL + "/bucket")
|
||||
c.Assert(perr, IsNil)
|
||||
c.Assert(perm.isPrivate(), Equals, true)
|
||||
}
|
||||
|
||||
func (s *TestSuite) TestMBContext(c *C) {
|
||||
console.IsExited = false
|
||||
|
||||
err := app.Run([]string{os.Args[0], "mb", server.URL + "/bucket"})
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(console.IsExited, Equals, false)
|
||||
|
||||
// reset back
|
||||
console.IsExited = false
|
||||
|
||||
err = app.Run([]string{os.Args[0], "mb", server.URL + "/$.bucket"})
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(console.IsExited, Equals, true)
|
||||
|
||||
// reset back
|
||||
console.IsExited = false
|
||||
}
|
||||
|
||||
func (s *TestSuite) TestAccessContext(c *C) {
|
||||
console.IsExited = false
|
||||
|
||||
err := app.Run([]string{os.Args[0], "access", "set", "private", server.URL + "/bucket"})
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(console.IsExited, Equals, false)
|
||||
|
||||
// reset back
|
||||
console.IsExited = false
|
||||
|
||||
err = app.Run([]string{os.Args[0], "access", "set", "public", server.URL + "/bucket"})
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(console.IsExited, Equals, false)
|
||||
|
||||
// reset back
|
||||
console.IsExited = false
|
||||
|
||||
err = app.Run([]string{os.Args[0], "access", "set", "readonly", server.URL + "/bucket"})
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(console.IsExited, Equals, false)
|
||||
|
||||
// reset back
|
||||
console.IsExited = false
|
||||
|
||||
err = app.Run([]string{os.Args[0], "access", "set", "authorized", server.URL + "/bucket"})
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(console.IsExited, Equals, false)
|
||||
|
||||
// reset back
|
||||
console.IsExited = false
|
||||
|
||||
err = app.Run([]string{os.Args[0], "access", "set", "invalid", server.URL + "/bucket"})
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(console.IsExited, Equals, true)
|
||||
// reset back
|
||||
console.IsExited = false
|
||||
|
||||
err = app.Run([]string{os.Args[0], "access", "get", server.URL + "/bucket"})
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(console.IsExited, Equals, false)
|
||||
// reset back
|
||||
console.IsExited = false
|
||||
|
||||
err = app.Run([]string{os.Args[0], "access", "get", server.URL + "/invalid"})
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(console.IsExited, Equals, true)
|
||||
// reset back
|
||||
console.IsExited = false
|
||||
}
|
||||
+19
-210
@@ -17,19 +17,14 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"net/http/httptest"
|
||||
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio/pkg/quick"
|
||||
. "gopkg.in/check.v1"
|
||||
)
|
||||
|
||||
@@ -45,182 +40,35 @@ var server *httptest.Server
|
||||
var app *cli.App
|
||||
|
||||
func (s *TestSuite) SetUpSuite(c *C) {
|
||||
objectAPI := objectAPIHandler(objectAPIHandler{lock: &sync.Mutex{}, bucket: "bucket", object: make(map[string][]byte)})
|
||||
server = httptest.NewServer(objectAPI)
|
||||
console.IsTesting = true
|
||||
|
||||
// do not set it elsewhere, leads to data races since this is a global flag
|
||||
globalQuietFlag = true // quiet is set to turn of progress bar
|
||||
|
||||
tmpDir, err := ioutil.TempDir(os.TempDir(), "cmd-")
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
// For windows the path is slightly different.
|
||||
if runtime.GOOS == "windows" {
|
||||
customConfigDir = filepath.Join(tmpDir, globalMCConfigWindowsDir)
|
||||
} else {
|
||||
customConfigDir = filepath.Join(tmpDir, globalMCConfigDir)
|
||||
}
|
||||
setMcConfigDir(customConfigDir)
|
||||
|
||||
perr := createMcConfigDir()
|
||||
c.Assert(perr, IsNil)
|
||||
|
||||
config, perr := newConfig()
|
||||
c.Assert(perr, IsNil)
|
||||
|
||||
perr = writeConfig(config)
|
||||
c.Assert(perr, IsNil)
|
||||
|
||||
perr = createSessionDir()
|
||||
c.Assert(perr, IsNil)
|
||||
|
||||
app = registerApp()
|
||||
}
|
||||
|
||||
func (s *TestSuite) TearDownSuite(c *C) {
|
||||
os.RemoveAll(customConfigDir)
|
||||
if server != nil {
|
||||
server.Close()
|
||||
}
|
||||
}
|
||||
|
||||
func (s *TestSuite) TestGetNewClient(c *C) {
|
||||
_, err := getNewClient("http://example.com/bucket1", hostConfig{})
|
||||
c.Assert(err, IsNil)
|
||||
_, err = getNewClient("https://example.com/bucket1", hostConfig{})
|
||||
c.Assert(err, IsNil)
|
||||
_, err = getNewClient("C:\\Users\\Administrator\\MyDocuments", hostConfig{})
|
||||
c.Assert(err, IsNil)
|
||||
_, err = getNewClient("/usr/bin/pandoc", hostConfig{})
|
||||
c.Assert(err, IsNil)
|
||||
_, err = getNewClient("pkg/client", hostConfig{})
|
||||
c.Assert(err, IsNil)
|
||||
}
|
||||
|
||||
func (s *TestSuite) TestNewConfigV4(c *C) {
|
||||
root, err := ioutil.TempDir(os.TempDir(), "mc-")
|
||||
c.Assert(err, IsNil)
|
||||
defer os.RemoveAll(root)
|
||||
|
||||
conf, perr := newConfig()
|
||||
c.Assert(perr, IsNil)
|
||||
configFile := filepath.Join(root, "config.json")
|
||||
perr = conf.Save(configFile)
|
||||
c.Assert(perr, IsNil)
|
||||
|
||||
confNew := newConfigV5()
|
||||
config, perr := quick.New(confNew)
|
||||
c.Assert(perr, IsNil)
|
||||
perr = config.Load(configFile)
|
||||
c.Assert(perr, IsNil)
|
||||
data := config.Data().(*configV5)
|
||||
|
||||
type aliases struct {
|
||||
name string
|
||||
url string
|
||||
}
|
||||
|
||||
wantAliases := []aliases{
|
||||
{
|
||||
"s3",
|
||||
"https://s3.amazonaws.com",
|
||||
},
|
||||
{
|
||||
"play",
|
||||
"https://play.minio.io:9000",
|
||||
},
|
||||
{
|
||||
"localhost",
|
||||
"http://localhost:9000",
|
||||
},
|
||||
}
|
||||
for _, alias := range wantAliases {
|
||||
url, ok := data.Aliases[alias.name]
|
||||
c.Assert(ok, Equals, true)
|
||||
c.Assert(url, Equals, alias.url)
|
||||
}
|
||||
|
||||
wantHosts := []string{
|
||||
"localhost:*",
|
||||
"127.0.0.1:*",
|
||||
"play.minio.io:9000",
|
||||
"dl.minio.io:9000",
|
||||
"s3*.amazonaws.com",
|
||||
}
|
||||
for _, host := range wantHosts {
|
||||
_, ok := data.Hosts[host]
|
||||
c.Assert(ok, Equals, true)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *TestSuite) TestRecursiveURL(c *C) {
|
||||
c.Assert(isURLRecursive("url..."), Equals, true)
|
||||
c.Assert(isURLRecursive("url.."), Equals, false)
|
||||
c.Assert(stripRecursiveURL("url..."), Equals, "url")
|
||||
c.Assert(stripRecursiveURL("url.."), Equals, "url..")
|
||||
c.Assert(stripRecursiveURL("..."), Equals, ".")
|
||||
c.Assert(stripRecursiveURL("...url"), Equals, "...url")
|
||||
}
|
||||
|
||||
func (s *TestSuite) TestHostConfig(c *C) {
|
||||
hostcfg, err := getHostConfig("https://s3.amazonaws.com")
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(hostcfg.AccessKeyID, Equals, globalAccessKeyID)
|
||||
c.Assert(hostcfg.SecretAccessKey, Equals, globalSecretAccessKey)
|
||||
c.Assert(hostcfg.API, Equals, "S3v4")
|
||||
|
||||
_, err = getHostConfig("http://test.minio.io")
|
||||
c.Assert(err, Not(IsNil))
|
||||
}
|
||||
|
||||
func (s *TestSuite) TestArgs2URL(c *C) {
|
||||
URLs := []string{"localhost", "s3", "play", "playgo", "play.go", "https://s3-us-west-2.amazonaws.com"}
|
||||
expandedURLs, err := args2URLs(URLs)
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(expandedURLs[0], Equals, "http://localhost:9000")
|
||||
c.Assert(expandedURLs[1], Equals, "https://s3.amazonaws.com")
|
||||
c.Assert(expandedURLs[2], Equals, "https://play.minio.io:9000")
|
||||
c.Assert(expandedURLs[3], Equals, "playgo") // Has no corresponding alias. So expect same value.
|
||||
c.Assert(expandedURLs[4], Equals, "play.go") // Has no corresponding alias. So expect same value.
|
||||
c.Assert(expandedURLs[5], Equals, "https://s3-us-west-2.amazonaws.com")
|
||||
}
|
||||
|
||||
func (s *TestSuite) TestValidPERMS(c *C) {
|
||||
perms := bucketPerms("private")
|
||||
c.Assert(perms.isValidBucketPERM(), Equals, true)
|
||||
perms := accessPerms("private")
|
||||
c.Assert(perms.isValidAccessPERM(), Equals, true)
|
||||
c.Assert(perms.String(), Equals, "private")
|
||||
perms = bucketPerms("public")
|
||||
c.Assert(perms.isValidBucketPERM(), Equals, true)
|
||||
perms = accessPerms("public")
|
||||
c.Assert(perms.isValidAccessPERM(), Equals, true)
|
||||
c.Assert(perms.String(), Equals, "public-read-write")
|
||||
perms = bucketPerms("readonly")
|
||||
c.Assert(perms.isValidBucketPERM(), Equals, true)
|
||||
perms = accessPerms("readonly")
|
||||
c.Assert(perms.isValidAccessPERM(), Equals, true)
|
||||
c.Assert(perms.String(), Equals, "public-read")
|
||||
perms = bucketPerms("authorized")
|
||||
c.Assert(perms.isValidBucketPERM(), Equals, true)
|
||||
perms = accessPerms("authorized")
|
||||
c.Assert(perms.isValidAccessPERM(), Equals, true)
|
||||
c.Assert(perms.String(), Equals, "authenticated-read")
|
||||
}
|
||||
|
||||
func (s *TestSuite) TestInvalidPERMS(c *C) {
|
||||
perms := bucketPerms("invalid")
|
||||
c.Assert(perms.isValidBucketPERM(), Equals, false)
|
||||
perms := accessPerms("invalid")
|
||||
c.Assert(perms.isValidAccessPERM(), Equals, false)
|
||||
}
|
||||
|
||||
func (s *TestSuite) TestGetMcConfigDir(c *C) {
|
||||
dir, err := getMcConfigDir()
|
||||
c.Assert(err, IsNil)
|
||||
switch runtime.GOOS {
|
||||
case "linux":
|
||||
fallthrough
|
||||
case "freebsd":
|
||||
fallthrough
|
||||
case "darwin":
|
||||
c.Assert(dir, Equals, customConfigDir)
|
||||
case "windows":
|
||||
c.Assert(dir, Equals, customConfigDir)
|
||||
default:
|
||||
c.Fail()
|
||||
}
|
||||
c.Assert(dir, Not(Equals), "")
|
||||
c.Assert(mustGetMcConfigDir(), Equals, dir)
|
||||
}
|
||||
|
||||
@@ -243,37 +91,14 @@ func (s *TestSuite) TestGetMcConfigPath(c *C) {
|
||||
}
|
||||
|
||||
func (s *TestSuite) TestIsvalidAliasName(c *C) {
|
||||
c.Check(isValidAliasName("helloWorld0"), Equals, true)
|
||||
c.Check(isValidAliasName("h0SFD2k24Fdsa"), Equals, true)
|
||||
c.Check(isValidAliasName("fdslka-4"), Equals, true)
|
||||
c.Check(isValidAliasName("fdslka-"), Equals, true)
|
||||
c.Check(isValidAliasName("helloWorld$"), Equals, false)
|
||||
c.Check(isValidAliasName("h0SFD2k2#Fdsa"), Equals, false)
|
||||
c.Check(isValidAliasName("0dslka-4"), Equals, false)
|
||||
c.Check(isValidAliasName("-fdslka"), Equals, false)
|
||||
}
|
||||
|
||||
func (s *TestSuite) TestEmptyExpansions(c *C) {
|
||||
url := getAliasURL("hello", nil)
|
||||
c.Assert(url, Equals, "hello")
|
||||
|
||||
url = getAliasURL("minio://hello", nil)
|
||||
c.Assert(url, Equals, "minio://hello")
|
||||
|
||||
url = getAliasURL("$#\\", nil)
|
||||
c.Assert(url, Equals, "$#\\")
|
||||
|
||||
url = getAliasURL("foo/bar", map[string]string{"foo": "http://foo"})
|
||||
c.Assert(url, Equals, "http://foo/bar")
|
||||
|
||||
url = getAliasURL("myfoo/bar", nil)
|
||||
c.Assert(url, Equals, "myfoo/bar")
|
||||
|
||||
url = getAliasURL("", nil)
|
||||
c.Assert(url, Equals, "")
|
||||
|
||||
url = getAliasURL("hello", nil)
|
||||
c.Assert(url, Equals, "hello")
|
||||
c.Check(isValidAlias("helloWorld0"), Equals, true)
|
||||
c.Check(isValidAlias("h0SFD2k24Fdsa"), Equals, true)
|
||||
c.Check(isValidAlias("fdslka-4"), Equals, true)
|
||||
c.Check(isValidAlias("fdslka-"), Equals, true)
|
||||
c.Check(isValidAlias("helloWorld$"), Equals, false)
|
||||
c.Check(isValidAlias("h0SFD2k2#Fdsa"), Equals, false)
|
||||
c.Check(isValidAlias("0dslka-4"), Equals, false)
|
||||
c.Check(isValidAlias("-fdslka"), Equals, false)
|
||||
}
|
||||
|
||||
func (s *TestSuite) TestHumanizedTime(c *C) {
|
||||
@@ -293,17 +118,6 @@ func (s *TestSuite) TestHumanizedTime(c *C) {
|
||||
c.Assert(hTime.Days, Not(Equals), int64(0))
|
||||
}
|
||||
|
||||
func (s *TestSuite) TestVersionContext(c *C) {
|
||||
console.IsExited = false
|
||||
|
||||
err := app.Run([]string{os.Args[0], "version"})
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(console.IsExited, Equals, false)
|
||||
|
||||
// reset back
|
||||
console.IsExited = false
|
||||
}
|
||||
|
||||
func (s *TestSuite) TestCommonPrefix(c *C) {
|
||||
c.Assert(commonPrefix("/usr", "/usr/local"), Equals, "/usr")
|
||||
c.Assert(commonPrefix("/uabbf", "/ursfad/ccc"), Equals, "/u")
|
||||
@@ -316,8 +130,3 @@ func (s *TestSuite) TestVersions(c *C) {
|
||||
c.Assert(v2.LessThan(v1), Equals, true)
|
||||
c.Assert(v1.LessThan(v2), Equals, false)
|
||||
}
|
||||
|
||||
func (s *TestSuite) TestApp(c *C) {
|
||||
err := app.Run([]string{""})
|
||||
c.Assert(err, IsNil)
|
||||
}
|
||||
|
||||
+203
-157
@@ -21,136 +21,161 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"net"
|
||||
"os"
|
||||
"runtime"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"syscall"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/client"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/pb"
|
||||
)
|
||||
|
||||
// mirror specific flags.
|
||||
var (
|
||||
mirrorFlags = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "help, h",
|
||||
Usage: "Help of mirror.",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "force",
|
||||
Usage: "Force overwrite of an existing target(s).",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
// Mirror folders recursively from a single source to many destinations
|
||||
var mirrorCmd = cli.Command{
|
||||
Name: "mirror",
|
||||
Usage: "Mirror folders recursively from a single source to many destinations.",
|
||||
Usage: "Mirror folders recursively from a single source to single destination.",
|
||||
Action: mainMirror,
|
||||
Flags: append(mirrorFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
mc {{.Name}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
mc {{.Name}} SOURCE TARGET [TARGET...]
|
||||
mc {{.Name}} [FLAGS] SOURCE TARGET
|
||||
|
||||
FLAGS:
|
||||
{{range .Flags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Mirror a bucket recursively from Minio cloud storage to multiple buckets on Amazon S3 cloud storage.
|
||||
$ mc {{.Name}} https://play.minio.io:9000/photos/2014 https://s3.amazonaws.com/backup-photos https://s3-west-1.amazonaws.com/local-photos
|
||||
1. Mirror a bucket recursively from Minio cloud storage to a bucket on Amazon S3 cloud storage.
|
||||
$ mc {{.Name}} play/photos/2014 s3/backup-photos
|
||||
|
||||
2. Mirror a local folder recursively to Minio cloud storage and Amazon S3 cloud storage.
|
||||
$ mc {{.Name}} backup/ https://play.minio.io:9000/archive https://s3.amazonaws.com/archive
|
||||
2. Mirror a local folder recursively to Amazon S3 cloud storage.
|
||||
$ mc {{.Name}} backup/ s3/archive
|
||||
|
||||
3. Mirror a bucket from aliased Amazon S3 cloud storage to multiple folders on Windows.
|
||||
$ mc {{.Name}} s3/documents/2014/ C:\backup\2014 C:\shared\volume\backup\2014
|
||||
|
||||
4. Mirror a local folder of non english character recursively to Amazon s3 cloud storage and Minio cloud storage.
|
||||
$ mc {{.Name}} 本語/ s3/mylocaldocuments play/backup
|
||||
|
||||
5. Mirror a local folder with space characters to Amazon s3 cloud storage
|
||||
$ mc {{.Name}} 'workdir/documents/Aug 2015' s3/miniocloud
|
||||
3. Mirror a bucket from aliased Amazon S3 cloud storage to a folder on Windows.
|
||||
$ mc {{.Name}} s3\documents\2014\ C:\backup\2014
|
||||
`,
|
||||
}
|
||||
|
||||
// MirrorMessage container for file mirror messages
|
||||
type MirrorMessage struct {
|
||||
Source string `json:"source"`
|
||||
Targets []string `json:"targets"`
|
||||
// mirrorMessage container for file mirror messages
|
||||
type mirrorMessage struct {
|
||||
Status string `json:"status"`
|
||||
Source string `json:"source"`
|
||||
Target string `json:"target"`
|
||||
}
|
||||
|
||||
// String colorized mirror message
|
||||
func (m MirrorMessage) String() string {
|
||||
return console.Colorize("Mirror", fmt.Sprintf("‘%s’ -> ‘%s’", m.Source, m.Targets))
|
||||
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 {
|
||||
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)
|
||||
}
|
||||
|
||||
// doMirror - Mirror an object to multiple destination. mirrorURLs status contains a copy of sURLs and error if any.
|
||||
func doMirror(sURLs mirrorURLs, bar *barSend, mirrorQueueCh <-chan bool, wg *sync.WaitGroup, statusCh chan<- mirrorURLs) {
|
||||
defer wg.Done() // Notify that this copy routine is done.
|
||||
defer func() {
|
||||
<-mirrorQueueCh
|
||||
}()
|
||||
// mirrorStatMessage container for mirror accounting message
|
||||
type mirrorStatMessage struct {
|
||||
Total int64
|
||||
Transferred int64
|
||||
Speed float64
|
||||
}
|
||||
|
||||
// mirrorStatMessage mirror accounting message
|
||||
func (c mirrorStatMessage) String() string {
|
||||
speedBox := pb.FormatBytes(int64(c.Speed))
|
||||
if speedBox == "" {
|
||||
speedBox = "0 MB"
|
||||
} else {
|
||||
speedBox = speedBox + "/s"
|
||||
}
|
||||
message := fmt.Sprintf("Total: %s, Transferred: %s, Speed: %s", pb.FormatBytes(c.Total),
|
||||
pb.FormatBytes(c.Transferred), speedBox)
|
||||
return message
|
||||
}
|
||||
|
||||
// doMirror - Mirror an object to multiple destination. mirrorURLs status contains a copy of sURLs and error if any.
|
||||
func doMirror(sURLs mirrorURLs, progressReader *progressBar, accountingReader *accounter) mirrorURLs {
|
||||
if sURLs.Error != nil { // Errorneous sURLs passed.
|
||||
sURLs.Error = sURLs.Error.Trace()
|
||||
statusCh <- sURLs
|
||||
return
|
||||
return sURLs
|
||||
}
|
||||
|
||||
if !globalQuietFlag && !globalJSONFlag {
|
||||
bar.SetCaption(sURLs.SourceContent.Name + ": ")
|
||||
sourceAlias := sURLs.SourceAlias
|
||||
sourceURL := sURLs.SourceContent.URL
|
||||
targetAlias := sURLs.TargetAlias
|
||||
targetURL := sURLs.TargetContent.URL
|
||||
length := sURLs.SourceContent.Size
|
||||
|
||||
if !globalQuiet && !globalJSON {
|
||||
progressReader = progressReader.SetCaption(sourceURL.String() + ": ")
|
||||
}
|
||||
|
||||
reader, length, err := getSource(sURLs.SourceContent.Name)
|
||||
reader, err := getSourceStreamFromAlias(sourceAlias, sourceURL.String())
|
||||
if err != nil {
|
||||
if !globalQuietFlag && !globalJSONFlag {
|
||||
bar.ErrorGet(int64(length))
|
||||
}
|
||||
sURLs.Error = err.Trace(sURLs.SourceContent.Name)
|
||||
statusCh <- sURLs
|
||||
return
|
||||
sURLs.Error = err.Trace(sourceURL.String())
|
||||
return sURLs
|
||||
}
|
||||
|
||||
var targetURLs []string
|
||||
for _, targetContent := range sURLs.TargetContents {
|
||||
targetURLs = append(targetURLs, targetContent.Name)
|
||||
}
|
||||
|
||||
var newReader io.ReadCloser
|
||||
if globalQuietFlag || globalJSONFlag {
|
||||
Prints("%s\n", MirrorMessage{
|
||||
Source: sURLs.SourceContent.Name,
|
||||
Targets: targetURLs,
|
||||
var progress io.Reader
|
||||
if globalQuiet || globalJSON {
|
||||
sourcePath := filepath.ToSlash(filepath.Join(sourceAlias, sourceURL.Path))
|
||||
targetPath := filepath.ToSlash(filepath.Join(targetAlias, targetURL.Path))
|
||||
printMsg(mirrorMessage{
|
||||
Source: sourcePath,
|
||||
Target: targetPath,
|
||||
})
|
||||
newReader = reader
|
||||
} else {
|
||||
// set up progress
|
||||
newReader = bar.NewProxyReader(reader)
|
||||
}
|
||||
defer newReader.Close()
|
||||
|
||||
err = putTargets(targetURLs, length, newReader)
|
||||
if err != nil {
|
||||
if !globalQuietFlag && !globalJSONFlag {
|
||||
bar.ErrorPut(int64(length))
|
||||
if globalQuiet || globalJSON {
|
||||
progress = accountingReader
|
||||
}
|
||||
sURLs.Error = err.Trace(targetURLs...)
|
||||
statusCh <- sURLs
|
||||
return
|
||||
} else {
|
||||
// Set up progress bar.
|
||||
progress = progressReader.ProgressBar
|
||||
}
|
||||
_, err = putTargetStreamFromAlias(targetAlias, targetURL.String(), reader, length, progress)
|
||||
if err != nil {
|
||||
sURLs.Error = err.Trace(targetURL.String())
|
||||
return sURLs
|
||||
}
|
||||
|
||||
sURLs.Error = nil // just for safety
|
||||
statusCh <- sURLs
|
||||
return sURLs
|
||||
}
|
||||
|
||||
// doMirrorFake - Perform a fake mirror to update the progress bar appropriately.
|
||||
func doMirrorFake(sURLs mirrorURLs, bar *barSend) {
|
||||
if !globalDebugFlag && !globalJSONFlag {
|
||||
bar.Progress(sURLs.SourceContent.Size)
|
||||
func doMirrorFake(sURLs mirrorURLs, progressReader *progressBar) mirrorURLs {
|
||||
if !globalDebug && !globalJSON {
|
||||
progressReader.ProgressBar.Add64(sURLs.SourceContent.Size)
|
||||
}
|
||||
return sURLs
|
||||
}
|
||||
|
||||
// doPrepareMirrorURLs scans the source URL and prepares a list of objects for mirroring.
|
||||
func doPrepareMirrorURLs(session *sessionV2, trapCh <-chan bool) {
|
||||
func doPrepareMirrorURLs(session *sessionV6, isForce bool, trapCh <-chan bool) {
|
||||
sourceURL := session.Header.CommandArgs[0] // first one is source.
|
||||
targetURLs := session.Header.CommandArgs[1:]
|
||||
targetURL := session.Header.CommandArgs[1]
|
||||
var totalBytes int64
|
||||
var totalObjects int
|
||||
|
||||
@@ -158,11 +183,11 @@ func doPrepareMirrorURLs(session *sessionV2, trapCh <-chan bool) {
|
||||
dataFP := session.NewDataWriter()
|
||||
|
||||
var scanBar scanBarFunc
|
||||
if !globalQuietFlag && !globalJSONFlag { // set up progress bar
|
||||
if !globalQuiet && !globalJSON { // set up progress bar
|
||||
scanBar = scanBarFactory()
|
||||
}
|
||||
|
||||
URLsCh := prepareMirrorURLs(sourceURL, targetURLs)
|
||||
URLsCh := prepareMirrorURLs(sourceURL, targetURL, isForce)
|
||||
done := false
|
||||
for done == false {
|
||||
select {
|
||||
@@ -173,7 +198,7 @@ func doPrepareMirrorURLs(session *sessionV2, trapCh <-chan bool) {
|
||||
}
|
||||
if sURLs.Error != nil {
|
||||
// Print in new line and adjust to top so that we don't print over the ongoing scan bar
|
||||
if !globalQuietFlag && !globalJSONFlag {
|
||||
if !globalQuiet && !globalJSON {
|
||||
console.Eraseline()
|
||||
}
|
||||
errorIf(sURLs.Error.Trace(), "Unable to prepare URLs for mirroring.")
|
||||
@@ -182,21 +207,21 @@ func doPrepareMirrorURLs(session *sessionV2, trapCh <-chan bool) {
|
||||
if sURLs.isEmpty() {
|
||||
break
|
||||
}
|
||||
jsonData, err := json.Marshal(sURLs)
|
||||
if err != nil {
|
||||
jsonData, e := json.Marshal(sURLs)
|
||||
if e != nil {
|
||||
session.Delete()
|
||||
fatalIf(probe.NewError(err), "Unable to marshal URLs into JSON.")
|
||||
fatalIf(probe.NewError(e), "Unable to marshal URLs into JSON.")
|
||||
}
|
||||
fmt.Fprintln(dataFP, string(jsonData))
|
||||
if !globalQuietFlag && !globalJSONFlag {
|
||||
scanBar(sURLs.SourceContent.Name)
|
||||
if !globalQuiet && !globalJSON {
|
||||
scanBar(sURLs.SourceContent.URL.String())
|
||||
}
|
||||
|
||||
totalBytes += sURLs.SourceContent.Size
|
||||
totalObjects++
|
||||
case <-trapCh:
|
||||
// Print in new line and adjust to top so that we don't print over the ongoing scan bar
|
||||
if !globalQuietFlag && !globalJSONFlag {
|
||||
if !globalQuiet && !globalJSON {
|
||||
console.Eraseline()
|
||||
}
|
||||
session.Delete() // If we are interrupted during the URL scanning, we drop the session.
|
||||
@@ -208,116 +233,139 @@ func doPrepareMirrorURLs(session *sessionV2, trapCh <-chan bool) {
|
||||
session.Save()
|
||||
}
|
||||
|
||||
func doMirrorCmdSession(session *sessionV2) {
|
||||
trapCh := signalTrap(os.Interrupt, os.Kill)
|
||||
// Session'fied mirror command.
|
||||
func doMirrorSession(session *sessionV6) {
|
||||
isForce := session.Header.CommandBoolFlags["force"]
|
||||
trapCh := signalTrap(os.Interrupt, syscall.SIGTERM)
|
||||
|
||||
if !session.HasData() {
|
||||
doPrepareMirrorURLs(session, trapCh)
|
||||
doPrepareMirrorURLs(session, isForce, trapCh)
|
||||
}
|
||||
|
||||
// Enable accounting reader by default.
|
||||
accntReader := newAccounter(session.Header.TotalBytes)
|
||||
|
||||
// Set up progress bar.
|
||||
var bar barSend
|
||||
if !globalQuietFlag && !globalJSONFlag {
|
||||
bar = newProgressBar()
|
||||
bar.Extend(session.Header.TotalBytes)
|
||||
var progressReader *progressBar
|
||||
if !globalQuiet && !globalJSON {
|
||||
progressReader = newProgressBar(session.Header.TotalBytes)
|
||||
}
|
||||
|
||||
// Prepare URL scanner from session data file.
|
||||
scanner := bufio.NewScanner(session.NewDataReader())
|
||||
urlScanner := bufio.NewScanner(session.NewDataReader())
|
||||
|
||||
// isCopied returns true if an object has been already copied
|
||||
// or not. This is useful when we resume from a session.
|
||||
isCopied := isCopiedFactory(session.Header.LastCopied)
|
||||
|
||||
wg := new(sync.WaitGroup)
|
||||
// Limit numner of mirror routines based on available CPU resources.
|
||||
mirrorQueue := make(chan bool, int(math.Max(float64(runtime.NumCPU())-1, 1)))
|
||||
defer close(mirrorQueue)
|
||||
// Status channel for receiveing mirror return status.
|
||||
statusCh := make(chan mirrorURLs)
|
||||
// Wait on status of doMirror() operation.
|
||||
var statusCh = make(chan mirrorURLs)
|
||||
|
||||
// Go routine to monitor doMirror status and signal traps.
|
||||
// Add a wait group for the below go-routine.
|
||||
var wg = new(sync.WaitGroup)
|
||||
wg.Add(1)
|
||||
|
||||
// Go routine to monitor signal traps if any.
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for {
|
||||
select {
|
||||
case sURLs, ok := <-statusCh: // Receive status.
|
||||
if !ok { // We are done here. Top level function has returned.
|
||||
if !globalQuietFlag && !globalJSONFlag {
|
||||
bar.Finish()
|
||||
}
|
||||
case <-trapCh:
|
||||
// Receive interrupt notification.
|
||||
if !globalQuiet && !globalJSON {
|
||||
console.Eraseline()
|
||||
}
|
||||
session.CloseAndDie()
|
||||
case sURLs, ok := <-statusCh:
|
||||
// Status channel is closed, we should return.
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if sURLs.Error == nil {
|
||||
session.Header.LastCopied = sURLs.SourceContent.Name
|
||||
session.Header.LastCopied = sURLs.SourceContent.URL.String()
|
||||
session.Save()
|
||||
} else {
|
||||
// Print in new line and adjust to top so that we don't print over the ongoing progress bar
|
||||
if !globalQuietFlag && !globalJSONFlag {
|
||||
// Print in new line and adjust to top so that we
|
||||
// don't print over the ongoing progress bar.
|
||||
if !globalQuiet && !globalJSON {
|
||||
console.Eraseline()
|
||||
}
|
||||
// all the cases which are handled where session should be saved are contained in the following
|
||||
// switch case, we shouldn't be saving sessions for all errors since some errors might need to be
|
||||
// reported to user properly.
|
||||
//
|
||||
// All other critical cases should be handled properly gracefully
|
||||
// handle more errors and save the session.
|
||||
errorIf(sURLs.Error.Trace(), "Failed to mirror.")
|
||||
errorIf(sURLs.Error.Trace(sURLs.SourceContent.URL.String()),
|
||||
fmt.Sprintf("Failed to copy ‘%s’.", sURLs.SourceContent.URL.String()))
|
||||
// For all non critical errors we can continue for the
|
||||
// remaining files.
|
||||
switch sURLs.Error.ToGoError().(type) {
|
||||
case *net.OpError:
|
||||
gracefulSessionSave(session)
|
||||
case net.Error:
|
||||
gracefulSessionSave(session)
|
||||
// Handle this specifically for filesystem related
|
||||
// errors.
|
||||
case client.BrokenSymlink:
|
||||
continue
|
||||
case client.TooManyLevelsSymlink:
|
||||
continue
|
||||
case client.PathNotFound:
|
||||
continue
|
||||
case client.PathInsufficientPermission:
|
||||
continue
|
||||
case client.ObjectAlreadyExists:
|
||||
continue
|
||||
case client.BucketDoesNotExist:
|
||||
continue
|
||||
}
|
||||
// For critical errors we should exit. Session
|
||||
// can be resumed after the user figures out
|
||||
// the problem.
|
||||
session.CloseAndDie()
|
||||
}
|
||||
case <-trapCh: // Receive interrupt notification.
|
||||
// Print in new line and adjust to top so that we don't print over the ongoing progress bar
|
||||
if !globalQuietFlag && !globalJSONFlag {
|
||||
console.Eraseline()
|
||||
}
|
||||
gracefulSessionSave(session)
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
// Go routine to perform concurrently mirroring.
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
mirrorWg := new(sync.WaitGroup)
|
||||
defer close(statusCh)
|
||||
|
||||
for scanner.Scan() {
|
||||
var sURLs mirrorURLs
|
||||
json.Unmarshal([]byte(scanner.Text()), &sURLs)
|
||||
if isCopied(sURLs.SourceContent.Name) {
|
||||
doMirrorFake(sURLs, &bar)
|
||||
} else {
|
||||
// Wait for other mirror routines to
|
||||
// complete. We only have limited CPU
|
||||
// and network resources.
|
||||
mirrorQueue <- true
|
||||
// Account for each mirror routines we start.
|
||||
mirrorWg.Add(1)
|
||||
// Do mirroring in background concurrently.
|
||||
go doMirror(sURLs, &bar, mirrorQueue, mirrorWg, statusCh)
|
||||
}
|
||||
// Loop through all urls.
|
||||
for urlScanner.Scan() {
|
||||
var sURLs mirrorURLs
|
||||
// Unmarshal copyURLs from each line.
|
||||
json.Unmarshal([]byte(urlScanner.Text()), &sURLs)
|
||||
// Verify if previously copied, notify progress bar.
|
||||
if isCopied(sURLs.SourceContent.URL.String()) {
|
||||
statusCh <- doMirrorFake(sURLs, progressReader)
|
||||
} else {
|
||||
statusCh <- doMirror(sURLs, progressReader, accntReader)
|
||||
}
|
||||
mirrorWg.Wait()
|
||||
}()
|
||||
}
|
||||
|
||||
// Close the goroutine.
|
||||
close(statusCh)
|
||||
|
||||
// Wait for the goroutines to finish.
|
||||
wg.Wait()
|
||||
|
||||
if !globalQuiet && !globalJSON {
|
||||
if progressReader.ProgressBar.Total > 0 {
|
||||
progressReader.ProgressBar.Finish()
|
||||
}
|
||||
} else {
|
||||
accntStat := accntReader.Stat()
|
||||
mrStatMessage := mirrorStatMessage{
|
||||
Total: accntStat.Total,
|
||||
Transferred: accntStat.Transferred,
|
||||
Speed: accntStat.Speed,
|
||||
}
|
||||
console.Println(console.Colorize("Mirror", mrStatMessage.String()))
|
||||
}
|
||||
}
|
||||
|
||||
// Main entry point for mirror command.
|
||||
func mainMirror(ctx *cli.Context) {
|
||||
// Set global flags from context.
|
||||
setGlobalsFromContext(ctx)
|
||||
|
||||
// check 'mirror' cli arguments.
|
||||
checkMirrorSyntax(ctx)
|
||||
|
||||
console.SetCustomTheme(map[string]*color.Color{
|
||||
"Mirror": color.New(color.FgGreen, color.Bold),
|
||||
})
|
||||
// Additional command speific theme customization.
|
||||
console.SetColor("Mirror", color.New(color.FgGreen, color.Bold))
|
||||
|
||||
var e error
|
||||
session := newSessionV2()
|
||||
session := newSessionV6()
|
||||
session.Header.CommandType = "mirror"
|
||||
session.Header.RootPath, e = os.Getwd()
|
||||
if e != nil {
|
||||
@@ -325,14 +373,12 @@ func mainMirror(ctx *cli.Context) {
|
||||
fatalIf(probe.NewError(e), "Unable to get current working folder.")
|
||||
}
|
||||
|
||||
// extract URLs.
|
||||
var err *probe.Error
|
||||
session.Header.CommandArgs, err = args2URLs(ctx.Args())
|
||||
if err != nil {
|
||||
session.Delete()
|
||||
fatalIf(err.Trace(ctx.Args()...), fmt.Sprintf("One or more unknown argument types found in ‘%s’.", ctx.Args()))
|
||||
}
|
||||
// Set command flags from context.
|
||||
isForce := ctx.Bool("force")
|
||||
session.Header.CommandBoolFlags["force"] = isForce
|
||||
|
||||
doMirrorCmdSession(session)
|
||||
// extract URLs.
|
||||
session.Header.CommandArgs = ctx.Args()
|
||||
doMirrorSession(session)
|
||||
session.Delete()
|
||||
}
|
||||
|
||||
+102
-145
@@ -18,25 +18,26 @@ package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/client"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
)
|
||||
|
||||
type mirrorURLs struct {
|
||||
SourceContent *client.Content
|
||||
TargetContents []*client.Content
|
||||
Error *probe.Error `json:"-"`
|
||||
SourceAlias string
|
||||
SourceContent *client.Content
|
||||
TargetAlias string
|
||||
TargetContent *client.Content
|
||||
Error *probe.Error `json:"-"`
|
||||
}
|
||||
|
||||
func (m mirrorURLs) isEmpty() bool {
|
||||
if m.SourceContent == nil && len(m.TargetContents) == 0 && m.Error == nil {
|
||||
if m.SourceContent == nil && m.TargetContent == nil && m.Error == nil {
|
||||
return true
|
||||
}
|
||||
if m.SourceContent.Size == 0 && len(m.TargetContents) == 0 && m.Error == nil {
|
||||
if m.SourceContent.Size == 0 && m.TargetContent == nil && m.Error == nil {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
@@ -45,167 +46,123 @@ func (m mirrorURLs) isEmpty() bool {
|
||||
//
|
||||
// * MIRROR ARGS - VALID CASES
|
||||
// =========================
|
||||
// mirror(d1..., [](d2)) -> []mirror(d1/f, [](d2/d1/f))
|
||||
// mirror(d1..., d2) -> []mirror(d1/f, d2/d1/f)
|
||||
|
||||
// checkMirrorSyntax(URLs []string)
|
||||
func checkMirrorSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) < 2 || ctx.Args().First() == "help" {
|
||||
if len(ctx.Args()) != 2 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "mirror", 1) // last argument is exit code.
|
||||
}
|
||||
|
||||
// extract URLs.
|
||||
URLs, err := args2URLs(ctx.Args())
|
||||
fatalIf(err.Trace(ctx.Args()...), "Unable to parse arguments.")
|
||||
|
||||
URLs := ctx.Args()
|
||||
srcURL := URLs[0]
|
||||
tgtURLs := URLs[1:]
|
||||
tgtURL := URLs[1]
|
||||
|
||||
/****** Generic rules *******/
|
||||
// Recursive source URL.
|
||||
newSrcURL := stripRecursiveURL(srcURL)
|
||||
_, srcContent, err := url2Stat(newSrcURL)
|
||||
fatalIf(err.Trace(srcURL), "Unable to stat source ‘"+newSrcURL+"’.")
|
||||
|
||||
if !srcContent.Type.IsDir() {
|
||||
fatalIf(errInvalidArgument().Trace(srcContent.Name, srcContent.Type.String()), fmt.Sprintf("Source ‘%s’ is not a folder. Only folders are supported by mirror.", srcURL))
|
||||
_, srcContent, err := url2Stat(srcURL)
|
||||
// incomplete uploads are not necessary for copy operation, no need to verify for them.
|
||||
isIncomplete := false
|
||||
if err != nil && !isURLPrefixExists(srcURL, isIncomplete) {
|
||||
fatalIf(err.Trace(srcURL), "Unable to stat source ‘"+srcURL+"’.")
|
||||
}
|
||||
|
||||
if len(tgtURLs) == 0 && tgtURLs == nil {
|
||||
fatalIf(errInvalidArgument().Trace(), "Invalid number of target arguments to mirror command.")
|
||||
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))
|
||||
}
|
||||
|
||||
for _, tgtURL := range tgtURLs {
|
||||
// Recursive URLs are not allowed in target.
|
||||
if isURLRecursive(tgtURL) {
|
||||
fatalIf(errDummy().Trace(), fmt.Sprintf("Recursive option is not supported for target ‘%s’ argument.", tgtURL))
|
||||
}
|
||||
if len(tgtURL) == 0 && tgtURL == "" {
|
||||
fatalIf(errInvalidArgument().Trace(), "Invalid target arguments to mirror command.")
|
||||
}
|
||||
|
||||
url := client.NewURL(tgtURL)
|
||||
if url.Host != "" {
|
||||
url := client.NewURL(tgtURL)
|
||||
if url.Host != "" {
|
||||
if !isURLVirtualHostStyle(url.Host) {
|
||||
if url.Path == string(url.Separator) {
|
||||
fatalIf(errInvalidArgument().Trace(), fmt.Sprintf("Target ‘%s’ does not contain bucket name.", tgtURL))
|
||||
fatalIf(errInvalidArgument().Trace(tgtURL),
|
||||
fmt.Sprintf("Target ‘%s’ does not contain bucket name.", tgtURL))
|
||||
}
|
||||
}
|
||||
}
|
||||
_, _, err = url2Stat(tgtURL)
|
||||
// we die on any error other than client.PathNotFound - destination directory need not exist.
|
||||
if _, ok := err.ToGoError().(client.PathNotFound); !ok {
|
||||
fatalIf(err.Trace(tgtURL), fmt.Sprintf("Unable to stat %s", tgtURL))
|
||||
}
|
||||
}
|
||||
|
||||
_, content, err := url2Stat(tgtURL)
|
||||
fatalIf(err.Trace(tgtURL), "Unable to stat target ‘"+tgtURL+"’.")
|
||||
if !content.Type.IsDir() {
|
||||
fatalIf(errInvalidArgument().Trace(), "Target ‘"+tgtURL+"’ is not a folder.")
|
||||
func deltaSourceTargets(sourceURL string, targetURL string, isForce bool, mirrorURLsCh chan<- mirrorURLs) {
|
||||
// source and targets are always directories
|
||||
sourceSeparator := string(client.NewURL(sourceURL).Separator)
|
||||
if !strings.HasSuffix(sourceURL, sourceSeparator) {
|
||||
sourceURL = sourceURL + sourceSeparator
|
||||
}
|
||||
targetSeparator := string(client.NewURL(targetURL).Separator)
|
||||
if !strings.HasSuffix(targetURL, targetSeparator) {
|
||||
targetURL = targetURL + targetSeparator
|
||||
}
|
||||
|
||||
// Extract alias and expanded URL
|
||||
sourceAlias, sourceURL, _ := mustExpandAlias(sourceURL)
|
||||
targetAlias, targetURL, _ := mustExpandAlias(targetURL)
|
||||
|
||||
defer close(mirrorURLsCh)
|
||||
|
||||
objectDifferenceTarget, err := objectDifferenceFactory(targetAlias, targetURL)
|
||||
if err != nil {
|
||||
mirrorURLsCh <- mirrorURLs{Error: err.Trace(targetAlias, targetURL)}
|
||||
return
|
||||
}
|
||||
|
||||
sourceClient, err := newClientFromAlias(sourceAlias, sourceURL)
|
||||
if err != nil {
|
||||
mirrorURLsCh <- mirrorURLs{Error: err.Trace(sourceAlias, sourceURL)}
|
||||
return
|
||||
}
|
||||
|
||||
for sourceContent := range sourceClient.List(true, false) {
|
||||
if sourceContent.Err != nil {
|
||||
mirrorURLsCh <- mirrorURLs{
|
||||
Error: sourceContent.Err.Trace(sourceClient.GetURL().String()),
|
||||
}
|
||||
continue
|
||||
}
|
||||
if sourceContent.Type.IsDir() {
|
||||
continue
|
||||
}
|
||||
suffix := strings.TrimPrefix(sourceContent.URL.String(), sourceURL)
|
||||
differ, err := objectDifferenceTarget(suffix, sourceContent.Type, sourceContent.Size)
|
||||
if err != nil {
|
||||
mirrorURLsCh <- mirrorURLs{Error: err.Trace(sourceContent.URL.String())}
|
||||
continue
|
||||
}
|
||||
if differ == differNone {
|
||||
// no difference, continue
|
||||
continue
|
||||
}
|
||||
if differ == differType {
|
||||
mirrorURLsCh <- mirrorURLs{Error: errInvalidTarget(suffix)}
|
||||
continue
|
||||
}
|
||||
if differ == differSize && !isForce {
|
||||
// size differs and force not set
|
||||
mirrorURLsCh <- mirrorURLs{Error: errOverWriteNotAllowed(sourceContent.URL.String())}
|
||||
continue
|
||||
}
|
||||
// either available only in source or size differs and force is set
|
||||
targetPath := urlJoinPath(targetURL, suffix)
|
||||
targetContent := &client.Content{URL: *client.NewURL(targetPath)}
|
||||
mirrorURLsCh <- mirrorURLs{
|
||||
SourceAlias: sourceAlias,
|
||||
SourceContent: sourceContent,
|
||||
TargetAlias: targetAlias,
|
||||
TargetContent: targetContent,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func deltaSourceTargets(sourceClnt client.Client, targetClnts []client.Client) <-chan mirrorURLs {
|
||||
func prepareMirrorURLs(sourceURL string, targetURL string, isForce bool) <-chan mirrorURLs {
|
||||
mirrorURLsCh := make(chan mirrorURLs)
|
||||
|
||||
go func() {
|
||||
defer close(mirrorURLsCh)
|
||||
id := newRandomID(8)
|
||||
|
||||
sourceSortedList := sortedList{}
|
||||
targetSortedList := make([]*sortedList, len(targetClnts))
|
||||
|
||||
surldelimited := sourceClnt.URL().String()
|
||||
if strings.HasSuffix(surldelimited, "/") == false {
|
||||
surldelimited = surldelimited + "/"
|
||||
}
|
||||
err := sourceSortedList.Create(sourceClnt, id+".src")
|
||||
if err != nil {
|
||||
mirrorURLsCh <- mirrorURLs{
|
||||
Error: err.Trace(),
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
turldelimited := make([]string, len(targetClnts))
|
||||
for i := range targetClnts {
|
||||
turldelimited[i] = targetClnts[i].URL().String()
|
||||
if strings.HasSuffix(turldelimited[i], "/") == false {
|
||||
turldelimited[i] = turldelimited[i] + "/"
|
||||
}
|
||||
targetSortedList[i] = &sortedList{}
|
||||
err := targetSortedList[i].Create(targetClnts[i], id+"."+strconv.Itoa(i))
|
||||
if err != nil {
|
||||
// FIXME: do cleanup by calling Delete()
|
||||
mirrorURLsCh <- mirrorURLs{
|
||||
Error: err.Trace(),
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
for source := range sourceSortedList.List(true) {
|
||||
if source.Content.Type.IsDir() {
|
||||
continue
|
||||
}
|
||||
targetContents := make([]*client.Content, 0, len(targetClnts))
|
||||
for i, t := range targetSortedList {
|
||||
match, err := t.Match(source.Content)
|
||||
if err != nil || match {
|
||||
// continue on io.EOF or if the keys matches
|
||||
// FIXME: handle other errors and ignore this target for future calls
|
||||
continue
|
||||
}
|
||||
targetContents = append(targetContents, &client.Content{Name: turldelimited[i] + source.Content.Name})
|
||||
}
|
||||
source.Content.Name = surldelimited + source.Content.Name
|
||||
if len(targetContents) > 0 {
|
||||
mirrorURLsCh <- mirrorURLs{
|
||||
SourceContent: source.Content,
|
||||
TargetContents: targetContents,
|
||||
}
|
||||
}
|
||||
}
|
||||
if err := sourceSortedList.Delete(); err != nil {
|
||||
mirrorURLsCh <- mirrorURLs{
|
||||
Error: err.Trace(),
|
||||
}
|
||||
}
|
||||
for _, t := range targetSortedList {
|
||||
if err := t.Delete(); err != nil {
|
||||
mirrorURLsCh <- mirrorURLs{
|
||||
Error: err.Trace(),
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
return mirrorURLsCh
|
||||
}
|
||||
|
||||
// prepareMirrorURLs - prepares target and source URLs for mirroring.
|
||||
func prepareMirrorURLs(sourceURL string, targetURLs []string) <-chan mirrorURLs {
|
||||
mirrorURLsCh := make(chan mirrorURLs)
|
||||
|
||||
go func() {
|
||||
defer close(mirrorURLsCh)
|
||||
sourceClnt, err := url2Client(stripRecursiveURL(sourceURL))
|
||||
if err != nil {
|
||||
mirrorURLsCh <- mirrorURLs{Error: err.Trace(sourceURL)}
|
||||
return
|
||||
}
|
||||
targetClnts := make([]client.Client, len(targetURLs))
|
||||
for i, targetURL := range targetURLs {
|
||||
targetClnt, targetContent, err := url2Stat(targetURL)
|
||||
if err != nil {
|
||||
mirrorURLsCh <- mirrorURLs{Error: err.Trace(targetURL)}
|
||||
return
|
||||
}
|
||||
// if one of the targets is not dir exit
|
||||
if !targetContent.Type.IsDir() {
|
||||
mirrorURLsCh <- mirrorURLs{Error: errInvalidTarget(targetURL).Trace()}
|
||||
return
|
||||
}
|
||||
// special case, be extremely careful before changing this behavior - will lead to data loss
|
||||
newTargetURL := strings.TrimSuffix(targetURL, string(targetClnt.URL().Separator)) + string(targetClnt.URL().Separator)
|
||||
targetClnt, err = url2Client(newTargetURL)
|
||||
if err != nil {
|
||||
mirrorURLsCh <- mirrorURLs{Error: err.Trace(newTargetURL)}
|
||||
return
|
||||
}
|
||||
targetClnts[i] = targetClnt
|
||||
}
|
||||
for sURLs := range deltaSourceTargets(sourceClnt, targetClnts) {
|
||||
mirrorURLsCh <- sURLs
|
||||
}
|
||||
}()
|
||||
go deltaSourceTargets(sourceURL, targetURL, isForce, mirrorURLsCh)
|
||||
return mirrorURLsCh
|
||||
}
|
||||
|
||||
+17
-16
@@ -23,35 +23,36 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/olekukonko/ts"
|
||||
)
|
||||
|
||||
// colorizeUpdateMessage - inspired from Yeoman project npm package https://github.com/yeoman/update-notifier
|
||||
// colorizeUpdateMessage - inspired from Yeoman project npm package https://github.com/yeoman/update-notifier.
|
||||
func colorizeUpdateMessage(updateString string) (string, *probe.Error) {
|
||||
// initialize coloring
|
||||
cyan := color.New(color.FgCyan, color.Bold).SprintFunc()
|
||||
yellow := color.New(color.FgYellow, color.Bold).SprintfFunc()
|
||||
|
||||
// calculate length without color coding, due to ANSI color characters padded to actual
|
||||
// string the final length is wrong than the original string length
|
||||
line1Str := fmt.Sprintf(" Update available: ")
|
||||
line2Str := fmt.Sprintf(" Run \"%s\" to update. ", updateString)
|
||||
// string the final length is wrong than the original string length.
|
||||
line1Str := fmt.Sprintf(" New update available, please execute the following command to update: ")
|
||||
line2Str := fmt.Sprintf(" %s ", updateString)
|
||||
line1Length := len(line1Str)
|
||||
line2Length := len(line2Str)
|
||||
|
||||
// populate lines with color coding
|
||||
// populate lines with color coding.
|
||||
line1InColor := line1Str
|
||||
line2InColor := fmt.Sprintf(" Run \"%s\" to update. ", cyan(updateString))
|
||||
line2InColor := fmt.Sprintf(" %s ", cyan(updateString))
|
||||
|
||||
// calculate the rectangular box size
|
||||
// calculate the rectangular box size.
|
||||
maxContentWidth := int(math.Max(float64(line1Length), float64(line2Length)))
|
||||
line1Rest := maxContentWidth - line1Length
|
||||
line2Rest := maxContentWidth - line2Length
|
||||
|
||||
terminal, err := ts.GetSize()
|
||||
if err != nil {
|
||||
return "", probe.NewError(err)
|
||||
// Fetch terminal size to calculate optimal box size.
|
||||
terminal, e := ts.GetSize()
|
||||
if e != nil {
|
||||
return "", probe.NewError(e)
|
||||
}
|
||||
|
||||
var message string
|
||||
@@ -59,28 +60,28 @@ func colorizeUpdateMessage(updateString string) (string, *probe.Error) {
|
||||
case len(line2Str) > terminal.Col():
|
||||
message = "\n" + line1InColor + "\n" + line2InColor + "\n"
|
||||
default:
|
||||
// on windows terminal turn off unicode characters
|
||||
// on windows terminal turn off unicode characters.
|
||||
var top, bottom, sideBar string
|
||||
if runtime.GOOS == "windows" {
|
||||
top = yellow("*" + strings.Repeat("*", maxContentWidth) + "*")
|
||||
bottom = yellow("*" + strings.Repeat("*", maxContentWidth) + "*")
|
||||
sideBar = yellow("|")
|
||||
} else {
|
||||
// color the rectangular box, use unicode characters here
|
||||
// color the rectangular box, use unicode characters here.
|
||||
top = yellow("┏" + strings.Repeat("━", maxContentWidth) + "┓")
|
||||
bottom = yellow("┗" + strings.Repeat("━", maxContentWidth) + "┛")
|
||||
sideBar = yellow("┃")
|
||||
}
|
||||
// fill spaces to the rest of the area
|
||||
// fill spaces to the rest of the area.
|
||||
spacePaddingLine1 := strings.Repeat(" ", line1Rest)
|
||||
spacePaddingLine2 := strings.Repeat(" ", line2Rest)
|
||||
|
||||
// construct the final message
|
||||
// construct the final message.
|
||||
message = "\n" + top + "\n" +
|
||||
sideBar + line1InColor + spacePaddingLine1 + sideBar + "\n" +
|
||||
sideBar + line2InColor + spacePaddingLine2 + sideBar + "\n" +
|
||||
bottom + "\n"
|
||||
}
|
||||
// finally print the message
|
||||
// return the final message
|
||||
return message, nil
|
||||
}
|
||||
|
||||
@@ -1,257 +0,0 @@
|
||||
/*
|
||||
* Minio Client (C) 2014, 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/dustin/go-humanize"
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
"github.com/minio/pb"
|
||||
"github.com/olekukonko/ts"
|
||||
|
||||
"github.com/minio/mc/pkg/console"
|
||||
)
|
||||
|
||||
type pbBar int
|
||||
|
||||
const (
|
||||
pbBarExtend pbBar = iota
|
||||
pbBarProgress
|
||||
pbBarFinish
|
||||
pbBarPutError
|
||||
pbBarGetError
|
||||
pbBarSetCaption
|
||||
)
|
||||
|
||||
type proxyReader struct {
|
||||
io.ReadCloser
|
||||
bar *barSend
|
||||
}
|
||||
|
||||
func (r *proxyReader) Read(p []byte) (n int, err error) {
|
||||
n, err = r.ReadCloser.Read(p)
|
||||
r.bar.Progress(int64(n))
|
||||
return
|
||||
}
|
||||
|
||||
func (r *proxyReader) Close() (err error) {
|
||||
return r.ReadCloser.Close()
|
||||
}
|
||||
|
||||
type barMsg struct {
|
||||
Op pbBar
|
||||
Arg interface{}
|
||||
}
|
||||
|
||||
type barSend struct {
|
||||
opCh chan<- barMsg
|
||||
finishCh <-chan bool
|
||||
}
|
||||
|
||||
func (b *barSend) NewProxyReader(r io.ReadCloser) *proxyReader {
|
||||
return &proxyReader{r, b}
|
||||
}
|
||||
|
||||
func (b barSend) Extend(total int64) {
|
||||
b.opCh <- barMsg{Op: pbBarExtend, Arg: total}
|
||||
}
|
||||
|
||||
func (b barSend) Progress(progress int64) {
|
||||
b.opCh <- barMsg{Op: pbBarProgress, Arg: progress}
|
||||
}
|
||||
|
||||
func (b barSend) ErrorPut(size int64) {
|
||||
b.opCh <- barMsg{Op: pbBarPutError, Arg: size}
|
||||
}
|
||||
|
||||
func (b barSend) ErrorGet(size int64) {
|
||||
b.opCh <- barMsg{Op: pbBarGetError, Arg: size}
|
||||
}
|
||||
|
||||
func (b *barSend) SetCaption(c string) {
|
||||
b.opCh <- barMsg{Op: pbBarSetCaption, Arg: c}
|
||||
}
|
||||
|
||||
func (b barSend) Finish() {
|
||||
defer close(b.opCh)
|
||||
b.opCh <- barMsg{Op: pbBarFinish}
|
||||
<-b.finishCh
|
||||
console.Println()
|
||||
}
|
||||
|
||||
func cursorAnimate() <-chan rune {
|
||||
cursorCh := make(chan rune)
|
||||
var cursors string
|
||||
|
||||
switch runtime.GOOS {
|
||||
case "linux":
|
||||
// cursors = "➩➪➫➬➭➮➯➱"
|
||||
// cursors = "▁▃▄▅▆▇█▇▆▅▄▃"
|
||||
cursors = "◐◓◑◒"
|
||||
// cursors = "←↖↑↗→↘↓↙"
|
||||
// cursors = "◴◷◶◵"
|
||||
// cursors = "◰◳◲◱"
|
||||
case "darwin":
|
||||
cursors = "◐◓◑◒"
|
||||
//cursors = "⣾⣽⣻⢿⡿⣟⣯⣷"
|
||||
default:
|
||||
cursors = "|/-\\"
|
||||
}
|
||||
go func() {
|
||||
for {
|
||||
for _, cursor := range cursors {
|
||||
cursorCh <- cursor
|
||||
}
|
||||
}
|
||||
}()
|
||||
return cursorCh
|
||||
}
|
||||
|
||||
func fixateBarCaption(caption string, width int) string {
|
||||
switch {
|
||||
case len(caption) > width:
|
||||
// Trim caption to fit within the screen
|
||||
trimSize := len(caption) - width + 3
|
||||
if trimSize < len(caption) {
|
||||
caption = "..." + caption[trimSize:]
|
||||
}
|
||||
case len(caption) < width:
|
||||
caption += strings.Repeat(" ", width-len(caption))
|
||||
}
|
||||
return caption
|
||||
}
|
||||
|
||||
func getFixedWidth(width, percent int) int {
|
||||
return width * percent / 100
|
||||
}
|
||||
|
||||
// newProgressBar - instantiate a pbBar.
|
||||
func newProgressBar() barSend {
|
||||
console.SetCustomTheme(map[string]*color.Color{
|
||||
"Bar": color.New(color.FgGreen, color.Bold),
|
||||
})
|
||||
cmdCh := make(chan barMsg)
|
||||
finishCh := make(chan bool)
|
||||
go func(cmdCh <-chan barMsg, finishCh chan<- bool) {
|
||||
var started bool
|
||||
var totalBytesRead int64 // total amounts of bytes read
|
||||
bar := pb.New64(0)
|
||||
bar.SetUnits(pb.U_BYTES)
|
||||
bar.SetRefreshRate(time.Millisecond * 125)
|
||||
bar.NotPrint = true
|
||||
bar.ShowSpeed = true
|
||||
bar.Callback = func(s string) {
|
||||
console.Print(console.Colorize("Bar", "\r"+s))
|
||||
}
|
||||
switch runtime.GOOS {
|
||||
case "linux":
|
||||
bar.Format("┃▓█░┃")
|
||||
// bar.Format("█▓▒░█")
|
||||
case "darwin":
|
||||
bar.Format(" ▓ ░ ")
|
||||
default:
|
||||
bar.Format("[=> ]")
|
||||
}
|
||||
for msg := range cmdCh {
|
||||
switch msg.Op {
|
||||
case pbBarSetCaption:
|
||||
bar.Prefix(fixateBarCaption(msg.Arg.(string), getFixedWidth(bar.GetWidth(), 18)))
|
||||
case pbBarExtend:
|
||||
atomic.AddInt64(&bar.Total, msg.Arg.(int64))
|
||||
case pbBarProgress:
|
||||
if bar.Total > 0 && !started {
|
||||
started = true
|
||||
bar.Start()
|
||||
}
|
||||
if msg.Arg.(int64) > 0 {
|
||||
totalBytesRead += msg.Arg.(int64)
|
||||
bar.Add64(msg.Arg.(int64))
|
||||
}
|
||||
case pbBarPutError:
|
||||
if totalBytesRead > msg.Arg.(int64) {
|
||||
bar.Set64(totalBytesRead - msg.Arg.(int64))
|
||||
}
|
||||
case pbBarGetError:
|
||||
if msg.Arg.(int64) > 0 {
|
||||
bar.Add64(msg.Arg.(int64))
|
||||
}
|
||||
case pbBarFinish:
|
||||
if started {
|
||||
bar.Finish()
|
||||
}
|
||||
finishCh <- true
|
||||
return
|
||||
}
|
||||
}
|
||||
}(cmdCh, finishCh)
|
||||
return barSend{cmdCh, finishCh}
|
||||
}
|
||||
|
||||
/******************************** Scan Bar ************************************/
|
||||
// fixateScanBar truncates long text to fit within the terminal size.
|
||||
func fixateScanBar(text string, width int) string {
|
||||
if len([]rune(text)) > width {
|
||||
// Trim text to fit within the screen
|
||||
trimSize := len([]rune(text)) - width + 3 //"..."
|
||||
if trimSize < len([]rune(text)) {
|
||||
text = "..." + text[trimSize:]
|
||||
}
|
||||
}
|
||||
return text
|
||||
}
|
||||
|
||||
// Progress bar function report objects being scaned.
|
||||
type scanBarFunc func(string)
|
||||
|
||||
// scanBarFactory returns a progress bar function to report URL scanning.
|
||||
func scanBarFactory() scanBarFunc {
|
||||
prevLineSize := 0
|
||||
prevSource := ""
|
||||
fileCount := 0
|
||||
termSize, err := ts.GetSize()
|
||||
if err != nil {
|
||||
fatalIf(probe.NewError(err), "Unable to get terminal size. Please use --quiet option.")
|
||||
}
|
||||
termWidth := termSize.Col()
|
||||
cursorCh := cursorAnimate()
|
||||
|
||||
return func(source string) {
|
||||
scanPrefix := fmt.Sprintf("[%s] %s ", humanize.Comma(int64(fileCount)), string(<-cursorCh))
|
||||
cmnPrefix := commonPrefix(source, prevSource)
|
||||
eraseLen := prevLineSize - len([]rune(scanPrefix+cmnPrefix))
|
||||
if eraseLen < 1 {
|
||||
eraseLen = 0
|
||||
}
|
||||
if prevLineSize != 0 { // erase previous line
|
||||
console.PrintC("\r" + scanPrefix + cmnPrefix + strings.Repeat(" ", eraseLen))
|
||||
}
|
||||
|
||||
source = fixateScanBar(source, termWidth-len([]rune(scanPrefix))-1)
|
||||
barText := scanPrefix + source
|
||||
console.PrintC("\r" + barText)
|
||||
prevSource = source
|
||||
prevLineSize = len([]rune(barText))
|
||||
fileCount++
|
||||
}
|
||||
}
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
/*
|
||||
* Minio Client, (C) 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"syscall"
|
||||
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
)
|
||||
|
||||
var (
|
||||
pipeFlags = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "help, h",
|
||||
Usage: "Help of pipe.",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
// Display contents of a file.
|
||||
var pipeCmd = cli.Command{
|
||||
Name: "pipe",
|
||||
Usage: "Write contents of stdin to one target. When no target is specified, it writes to stdout.",
|
||||
Action: mainPipe,
|
||||
Flags: append(pipeFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
mc {{.Name}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
mc {{.Name}} [FLAGS] [TARGET]
|
||||
|
||||
FLAGS:
|
||||
{{range .Flags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Write contents of stdin to a file on local filesystem.
|
||||
$ mc {{.Name}} /tmp/hello-world.go
|
||||
|
||||
2. Write contents of stdin to an object on Amazon S3 cloud storage.
|
||||
$ mc {{.Name}} s3/personalbuck/meeting-notes.txt
|
||||
|
||||
3. Copy an ISO image to an object on Amazon S3 cloud storage and Google Cloud Storage simultaneously.
|
||||
$ cat debian-8.2.iso | mc {{.Name}} s3/ferenginar/gnuos.iso
|
||||
|
||||
4. Stream MySQL database dump to Amazon S3 directly.
|
||||
$ mysqldump -u root -p ******* accountsdb | mc {{.Name}} s3/ferenginar/backups/accountsdb-oct-9-2015.sql
|
||||
`,
|
||||
}
|
||||
|
||||
func pipe(targetURL string) *probe.Error {
|
||||
if targetURL == "" {
|
||||
// When no target is specified, pipe cat's stdin to stdout.
|
||||
return catOut(os.Stdin).Trace()
|
||||
}
|
||||
|
||||
// Stream from stdin to multiple objects until EOF.
|
||||
// Ignore size, since os.Stat() would not return proper size all the time
|
||||
// for local filesystem for example /proc files.
|
||||
_, err := putTargetStream(targetURL, os.Stdin, -1)
|
||||
// TODO: See if this check is necessary.
|
||||
switch e := err.ToGoError().(type) {
|
||||
case *os.PathError:
|
||||
if e.Err == syscall.EPIPE {
|
||||
// stdin closed by the user. Gracefully exit.
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return err.Trace(targetURL)
|
||||
}
|
||||
|
||||
// check pipe input arguments.
|
||||
func checkPipeSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) > 1 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "pipe", 1) // last argument is exit code.
|
||||
}
|
||||
}
|
||||
|
||||
// mainPipe is the main entry point for pipe command.
|
||||
func mainPipe(ctx *cli.Context) {
|
||||
// Set global flags from context.
|
||||
setGlobalsFromContext(ctx)
|
||||
|
||||
// validate pipe input arguments.
|
||||
checkPipeSyntax(ctx)
|
||||
|
||||
if len(ctx.Args()) == 0 {
|
||||
err := pipe("")
|
||||
fatalIf(err.Trace("stdout"), "Unable to write to one or more targets.")
|
||||
} else {
|
||||
// extract URLs.
|
||||
URLs := ctx.Args()
|
||||
err := pipe(URLs[0])
|
||||
fatalIf(err.Trace(URLs[0]), "Unable to write to one or more targets.")
|
||||
}
|
||||
}
|
||||
+26
-24
@@ -21,50 +21,52 @@ import (
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
)
|
||||
|
||||
// Client - client interface
|
||||
type Client interface {
|
||||
// Common operations
|
||||
Stat() (content *Content, err *probe.Error)
|
||||
List(recursive bool) <-chan ContentOnChannel
|
||||
List(recursive, incomplete bool) <-chan *Content
|
||||
|
||||
// Bucket operations
|
||||
MakeBucket() *probe.Error
|
||||
GetBucketACL() (acl string, error *probe.Error)
|
||||
SetBucketACL(acl string) *probe.Error
|
||||
MakeBucket(region string) *probe.Error
|
||||
GetBucketAccess() (access string, error *probe.Error)
|
||||
SetBucketAccess(access string) *probe.Error
|
||||
|
||||
// Object operations
|
||||
Share(expires time.Duration) (string, *probe.Error)
|
||||
GetObject(offset, length int64) (body io.ReadCloser, size int64, err *probe.Error)
|
||||
PutObject(size int64, data io.Reader) *probe.Error
|
||||
// I/O operations
|
||||
Get() (reader io.Reader, err *probe.Error)
|
||||
Put(reader io.Reader, size int64, contentType string, progress io.Reader) (n int64, err *probe.Error)
|
||||
|
||||
// URL returns back internal url
|
||||
URL() *URL
|
||||
}
|
||||
// I/O operations with expiration
|
||||
ShareDownload(expires time.Duration) (string, *probe.Error)
|
||||
ShareUpload(bool, time.Duration, string) (map[string]string, *probe.Error)
|
||||
|
||||
// ContentOnChannel - List contents on channel
|
||||
type ContentOnChannel struct {
|
||||
Content *Content
|
||||
Err *probe.Error
|
||||
// Delete operations
|
||||
Remove(incomplete bool) *probe.Error
|
||||
|
||||
// GetURL returns back internal url
|
||||
GetURL() URL
|
||||
}
|
||||
|
||||
// Content container for content metadata
|
||||
type Content struct {
|
||||
Name string
|
||||
URL URL
|
||||
Time time.Time
|
||||
Size int64
|
||||
Type os.FileMode
|
||||
Err *probe.Error
|
||||
}
|
||||
|
||||
// Config - see http://docs.amazonwebservices.com/AmazonS3/latest/dev/index.html?RESTAuthentication.html
|
||||
type Config struct {
|
||||
AccessKeyID string
|
||||
SecretAccessKey string
|
||||
HostURL string
|
||||
AppName string
|
||||
AppVersion string
|
||||
AppComments []string
|
||||
Debug bool
|
||||
AccessKey string
|
||||
SecretKey string
|
||||
Signature string
|
||||
HostURL string
|
||||
AppName string
|
||||
AppVersion string
|
||||
AppComments []string
|
||||
Debug bool
|
||||
}
|
||||
|
||||
+89
-79
@@ -16,7 +16,10 @@
|
||||
|
||||
package client
|
||||
|
||||
import "strconv"
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
/// Collection of standard errors
|
||||
|
||||
@@ -27,21 +30,7 @@ type APINotImplemented struct {
|
||||
}
|
||||
|
||||
func (e APINotImplemented) Error() string {
|
||||
return "‘" + e.API + "’ feature " + "is not implemented for ‘" + e.APIType + "’"
|
||||
}
|
||||
|
||||
// UnexpectedError - unexpected error
|
||||
type UnexpectedError GenericError
|
||||
|
||||
func (e UnexpectedError) Error() string {
|
||||
return "Unexpected error, please report this error at https://github.com/minio/mc/issues"
|
||||
}
|
||||
|
||||
// InvalidArgument - bad arguments provided
|
||||
type InvalidArgument GenericError
|
||||
|
||||
func (e InvalidArgument) Error() string {
|
||||
return "Invalid argument"
|
||||
return "‘" + e.API + "’ feature " + "is not implemented for ‘" + e.APIType + "’."
|
||||
}
|
||||
|
||||
// InvalidRange - invalid range requested
|
||||
@@ -50,25 +39,7 @@ type InvalidRange struct {
|
||||
}
|
||||
|
||||
func (e InvalidRange) Error() string {
|
||||
return "invalid range offset: " + strconv.FormatInt(e.Offset, 10)
|
||||
}
|
||||
|
||||
// InvalidACLType - invalid acl type
|
||||
type InvalidACLType struct {
|
||||
ACL string
|
||||
}
|
||||
|
||||
func (e InvalidACLType) Error() string {
|
||||
return "invalid acl type: " + e.ACL
|
||||
}
|
||||
|
||||
// InvalidMaxKeys - invalid maxkeys provided
|
||||
type InvalidMaxKeys struct {
|
||||
MaxKeys int
|
||||
}
|
||||
|
||||
func (e InvalidMaxKeys) Error() string {
|
||||
return "invalid maxkeys: " + strconv.Itoa(e.MaxKeys)
|
||||
return "Invalid range offset: ‘" + strconv.FormatInt(e.Offset, 10) + "’."
|
||||
}
|
||||
|
||||
// GenericBucketError - generic bucket operations error
|
||||
@@ -76,18 +47,32 @@ type GenericBucketError struct {
|
||||
Bucket string
|
||||
}
|
||||
|
||||
// BucketExists - bucket exists
|
||||
// BucketDoesNotExist - bucket does not exist.
|
||||
type BucketDoesNotExist GenericBucketError
|
||||
|
||||
func (e BucketDoesNotExist) Error() string {
|
||||
return "Bucket ‘" + e.Bucket + "’ does not exist."
|
||||
}
|
||||
|
||||
// BucketExists - bucket exists.
|
||||
type BucketExists GenericBucketError
|
||||
|
||||
func (e BucketExists) Error() string {
|
||||
return "bucket " + e.Bucket + " exists"
|
||||
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 "Invalid bucketname [‘" + e.Bucket + "’], please read http://goo.gl/wJlzDz."
|
||||
}
|
||||
|
||||
// BucketNameEmpty - bucket name empty (http://goo.gl/wJlzDz)
|
||||
type BucketNameEmpty struct{}
|
||||
|
||||
func (e BucketNameEmpty) Error() string {
|
||||
return "Bucket name cannot be empty."
|
||||
}
|
||||
|
||||
// GenericObjectError - generic object operations error
|
||||
@@ -102,78 +87,103 @@ type ObjectAlreadyExists struct {
|
||||
}
|
||||
|
||||
func (e ObjectAlreadyExists) Error() string {
|
||||
return "Object #" + e.Object + " already exists."
|
||||
}
|
||||
|
||||
// ObjectNotFound - object requested does not exist
|
||||
type ObjectNotFound GenericObjectError
|
||||
|
||||
func (e ObjectNotFound) Error() string {
|
||||
return "object " + e.Object + " not found in bucket " + e.Bucket
|
||||
return "Object ‘" + e.Object + "’ already exists."
|
||||
}
|
||||
|
||||
// InvalidObjectName - object requested is invalid
|
||||
type InvalidObjectName GenericObjectError
|
||||
|
||||
func (e InvalidObjectName) Error() string {
|
||||
return "object " + e.Object + "at" + e.Bucket + "is invalid"
|
||||
return "Object ‘" + e.Object + "’ at ‘" + e.Bucket + "’ is invalid."
|
||||
}
|
||||
|
||||
// ObjectExists - object exists
|
||||
type ObjectExists GenericObjectError
|
||||
// BucketNameTopLevel - generic error
|
||||
type BucketNameTopLevel struct{}
|
||||
|
||||
func (e ObjectExists) Error() string {
|
||||
return "object " + e.Object + " exists"
|
||||
func (e BucketNameTopLevel) Error() string {
|
||||
return "Buckets can only be created at the top level."
|
||||
}
|
||||
|
||||
// GenericError - generic error
|
||||
type GenericError struct{}
|
||||
|
||||
// InvalidQueryURL - generic error
|
||||
type InvalidQueryURL struct {
|
||||
URL string
|
||||
}
|
||||
|
||||
func (e InvalidQueryURL) Error() string {
|
||||
return "Invalid query URL: " + e.URL
|
||||
}
|
||||
|
||||
// GenericFileError - generic file error
|
||||
// GenericFileError - generic file error.
|
||||
type GenericFileError struct {
|
||||
Path string
|
||||
}
|
||||
|
||||
// NotFound (ENOENT) - file not found
|
||||
type NotFound GenericFileError
|
||||
// PathNotFound (ENOENT) - file not found.
|
||||
type PathNotFound GenericFileError
|
||||
|
||||
func (e NotFound) Error() string {
|
||||
func (e PathNotFound) Error() string {
|
||||
return "Requested file ‘" + e.Path + "’ not found"
|
||||
}
|
||||
|
||||
// ISFolder (EISDIR) - accessed file is a folder
|
||||
type ISFolder GenericFileError
|
||||
// PathIsNotRegular (ENOTREG) - file is not a regular file.
|
||||
type PathIsNotRegular GenericFileError
|
||||
|
||||
func (e ISFolder) Error() string {
|
||||
return "Requested file ‘" + e.Path + "’ is a folder"
|
||||
func (e PathIsNotRegular) Error() string {
|
||||
return "Requested file ‘" + e.Path + "’ is not a regular file."
|
||||
}
|
||||
|
||||
// NotFolder (ENOTDIR) - accessed file is not a folder
|
||||
type NotFolder GenericFileError
|
||||
// PathInsufficientPermission (EPERM) - permission denied.
|
||||
type PathInsufficientPermission GenericFileError
|
||||
|
||||
func (e NotFolder) Error() string {
|
||||
return "Requested file ‘" + e.Path + "’ is not a folder"
|
||||
func (e PathInsufficientPermission) Error() string {
|
||||
return "Insufficient permissions to access this file ‘" + e.Path + "’"
|
||||
}
|
||||
|
||||
// ISBrokenSymlink (ENOTENT) - file has broken symlink
|
||||
type ISBrokenSymlink GenericFileError
|
||||
// BrokenSymlink (ENOTENT) - file has broken symlink.
|
||||
type BrokenSymlink GenericFileError
|
||||
|
||||
func (e ISBrokenSymlink) Error() string {
|
||||
func (e BrokenSymlink) Error() string {
|
||||
return "Requested file ‘" + e.Path + "’ has broken symlink"
|
||||
}
|
||||
|
||||
// EmptyPath (EINVAL) - invalid argument
|
||||
// TooManyLevelsSymlink (ELOOP) - file has too many levels of symlinks.
|
||||
type TooManyLevelsSymlink GenericFileError
|
||||
|
||||
func (e TooManyLevelsSymlink) Error() string {
|
||||
return "Requested file ‘" + e.Path + "’ has too many levels of symlinks"
|
||||
}
|
||||
|
||||
// EmptyPath (EINVAL) - invalid argument.
|
||||
type EmptyPath struct{}
|
||||
|
||||
func (e EmptyPath) Error() string {
|
||||
return "Invalid path, path cannot be empty"
|
||||
}
|
||||
|
||||
// ObjectMissing (EINVAL) - object key missing.
|
||||
type ObjectMissing struct{}
|
||||
|
||||
func (e ObjectMissing) Error() string {
|
||||
return "Object key is missing, object key cannot be empty"
|
||||
}
|
||||
|
||||
// UnexpectedShortWrite - write wrote less bytes than expected.
|
||||
type UnexpectedShortWrite struct {
|
||||
InputSize int
|
||||
WriteSize int
|
||||
}
|
||||
|
||||
func (e UnexpectedShortWrite) Error() string {
|
||||
msg := fmt.Sprintf("Wrote less data than requested. Expected ‘%d’ bytes, but only wrote ‘%d’ bytes.", e.InputSize, e.WriteSize)
|
||||
return msg
|
||||
}
|
||||
|
||||
// UnexpectedEOF (EPIPE) - reader closed prematurely.
|
||||
type UnexpectedEOF struct {
|
||||
TotalSize int64
|
||||
TotalWritten int64
|
||||
}
|
||||
|
||||
func (e UnexpectedEOF) Error() string {
|
||||
msg := fmt.Sprintf("Input reader closed pre-maturely. Expected ‘%d’ bytes, but only received ‘%d’ bytes.", e.TotalSize, e.TotalWritten)
|
||||
return msg
|
||||
}
|
||||
|
||||
// UnexpectedExcessRead - reader wrote more data than requested.
|
||||
type UnexpectedExcessRead UnexpectedEOF
|
||||
|
||||
func (e UnexpectedExcessRead) Error() string {
|
||||
msg := fmt.Sprintf("Received excess data on input reader. Expected only ‘%d’ bytes, but received ‘%d’ bytes.", e.TotalSize, e.TotalWritten)
|
||||
return msg
|
||||
}
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
/*
|
||||
* Minio Client (C) 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this fs except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package fs
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
|
||||
"github.com/minio/mc/pkg/client"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
)
|
||||
|
||||
// toClientError error constructs a typed client error for known filesystem errors.
|
||||
func (f *fsClient) toClientError(e error, fpath string) *probe.Error {
|
||||
if os.IsPermission(e) {
|
||||
return probe.NewError(client.PathInsufficientPermission{Path: fpath})
|
||||
}
|
||||
if os.IsNotExist(e) {
|
||||
return probe.NewError(client.PathNotFound{Path: fpath})
|
||||
}
|
||||
return probe.NewError(e)
|
||||
}
|
||||
|
||||
// handle windows symlinks - eg: junction files.
|
||||
func (f *fsClient) handleWindowsSymlinks(fpath string) (os.FileInfo, *probe.Error) {
|
||||
// On windows there are directory symlinks which are called junction files.
|
||||
// These files carry special meaning on windows they cannot be,
|
||||
// accessed with regular operations.
|
||||
file, e := os.Lstat(fpath)
|
||||
if e != nil {
|
||||
err := f.toClientError(e, fpath)
|
||||
return nil, err.Trace(fpath)
|
||||
}
|
||||
return file, nil
|
||||
}
|
||||
|
||||
// fsStat - wrapper function to get file stat.
|
||||
func (f *fsClient) fsStat() (os.FileInfo, *probe.Error) {
|
||||
fpath := f.PathURL.Path
|
||||
// Golang strips trailing / if you clean(..) or
|
||||
// EvalSymlinks(..). Adding '.' prevents it from doing so.
|
||||
if strings.HasSuffix(fpath, string(f.PathURL.Separator)) {
|
||||
fpath = fpath + "."
|
||||
}
|
||||
fpath, e := filepath.EvalSymlinks(fpath)
|
||||
if e != nil {
|
||||
if os.IsPermission(e) {
|
||||
if runtime.GOOS == "windows" {
|
||||
return f.handleWindowsSymlinks(f.PathURL.Path)
|
||||
}
|
||||
return nil, probe.NewError(client.PathInsufficientPermission{Path: f.PathURL.Path})
|
||||
}
|
||||
err := f.toClientError(e, f.PathURL.Path)
|
||||
return nil, err.Trace(fpath)
|
||||
}
|
||||
st, e := os.Stat(fpath)
|
||||
if e != nil {
|
||||
if os.IsPermission(e) {
|
||||
if runtime.GOOS == "windows" {
|
||||
return f.handleWindowsSymlinks(fpath)
|
||||
}
|
||||
return nil, probe.NewError(client.PathInsufficientPermission{Path: f.PathURL.Path})
|
||||
}
|
||||
if os.IsNotExist(e) {
|
||||
return nil, probe.NewError(client.PathNotFound{Path: f.PathURL.Path})
|
||||
}
|
||||
return nil, probe.NewError(e)
|
||||
}
|
||||
return st, nil
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
/*
|
||||
* Minio Client (C) 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this fs except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package fs
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
)
|
||||
|
||||
// byDirName implements sort.Interface.
|
||||
type byDirName []os.FileInfo
|
||||
|
||||
func (f byDirName) Len() int { return len(f) }
|
||||
func (f byDirName) Less(i, j int) bool {
|
||||
// For directory add an ending separator fortrue lexical order.
|
||||
if f[i].Mode().IsDir() {
|
||||
return f[i].Name()+string(filepath.Separator) < f[j].Name()
|
||||
}
|
||||
// For directory add an ending separator for true lexical order.
|
||||
if f[j].Mode().IsDir() {
|
||||
return f[i].Name() < f[j].Name()+string(filepath.Separator)
|
||||
}
|
||||
return f[i].Name() < f[j].Name()
|
||||
}
|
||||
func (f byDirName) Swap(i, j int) { f[i], f[j] = f[j], f[i] }
|
||||
|
||||
// readDir reads the directory named by dirname and returns
|
||||
// a list of sorted directory entries.
|
||||
func readDir(dirname string) ([]os.FileInfo, error) {
|
||||
f, e := os.Open(dirname)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
list, e := f.Readdir(-1)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
if e = f.Close(); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
sort.Sort(byDirName(list))
|
||||
return list, nil
|
||||
}
|
||||
|
||||
// readDirNames reads the directory named by dirname and returns
|
||||
// a sorted list of directory entries.
|
||||
func readDirNames(dirname string) ([]string, error) {
|
||||
names, e := readDirUnsortedNames(dirname)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
sort.Strings(names)
|
||||
return names, nil
|
||||
}
|
||||
|
||||
// getRealName - gets the proper filename for sorting purposes
|
||||
// Readdir() filters out directory names without separators, add
|
||||
// them back for proper sorting results.
|
||||
func getRealName(info os.FileInfo) string {
|
||||
if info.IsDir() {
|
||||
// Make sure directory has its end separator.
|
||||
return info.Name() + string(filepath.Separator)
|
||||
}
|
||||
return info.Name()
|
||||
}
|
||||
|
||||
// readDirUnsortedNames reads the directory named by dirname and
|
||||
// return a unsorted list of directory entries.
|
||||
func readDirUnsortedNames(dirname string) ([]string, error) {
|
||||
f, e := os.Open(dirname)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
nameInfos, e := f.Readdir(-1)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
if e = f.Close(); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
var names []string
|
||||
for _, nameInfo := range nameInfos {
|
||||
names = append(names, getRealName(nameInfo))
|
||||
}
|
||||
return names, nil
|
||||
}
|
||||
|
||||
// walk walks the file tree rooted at root, calling walkFn for each file or
|
||||
// directory in the tree, including root.
|
||||
func walk(root string, walkFn walkFunc) error {
|
||||
info, e := os.Lstat(root)
|
||||
if e != nil {
|
||||
return walkFn(root, nil, e)
|
||||
}
|
||||
return walkInternal(root, info, walkFn)
|
||||
}
|
||||
|
||||
// WalkFunc is the type of the function called for each file or directory
|
||||
// visited by Walk. The path argument contains the argument to Walk as a
|
||||
// prefix; that is, if Walk is called with "dir", which is a directory
|
||||
// containing the file "a", the walk function will be called with argument
|
||||
// "dir/a". The info argument is the os.FileInfo for the named path.
|
||||
type walkFunc func(path string, info os.FileInfo, e error) error
|
||||
|
||||
// ErrSkipDir is used as a return value from WalkFuncs to indicate that
|
||||
// the directory named in the call is to be skipped. It is not returned
|
||||
// as an error by any function.
|
||||
var errSkipDir = errors.New("skip this directory")
|
||||
|
||||
// ErrSkipFile is used as a return value from WalkFuncs to indicate that
|
||||
// the file named in the call is to be skipped. It is not returned
|
||||
// as an error by any function.
|
||||
var errSkipFile = errors.New("skip this file")
|
||||
|
||||
// walkInternal recursively descends path, calling w.
|
||||
func walkInternal(path string, info os.FileInfo, walkFn walkFunc) error {
|
||||
e := walkFn(path, info, nil)
|
||||
if e != nil {
|
||||
if info.Mode().IsDir() && e == errSkipDir {
|
||||
return nil
|
||||
}
|
||||
if info.Mode().IsRegular() && e == errSkipFile {
|
||||
return nil
|
||||
}
|
||||
return e
|
||||
}
|
||||
if !info.IsDir() {
|
||||
return nil
|
||||
}
|
||||
names, e := readDirNames(path)
|
||||
if e != nil {
|
||||
return walkFn(path, info, e)
|
||||
}
|
||||
for _, name := range names {
|
||||
filename := filepath.Join(path, name)
|
||||
fileInfo, e := os.Lstat(filename)
|
||||
if e != nil {
|
||||
if e = walkFn(filename, fileInfo, e); e != nil && e != errSkipDir && e != errSkipFile {
|
||||
return e
|
||||
}
|
||||
} else {
|
||||
e = walkInternal(filename, fileInfo, walkFn)
|
||||
if e != nil {
|
||||
if e == errSkipDir || e == errSkipFile {
|
||||
return nil
|
||||
}
|
||||
return e
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
+558
-294
File diff suppressed because it is too large
Load Diff
+132
-114
@@ -35,230 +35,248 @@ type MySuite struct{}
|
||||
|
||||
var _ = Suite(&MySuite{})
|
||||
|
||||
// Test list files in a folder.
|
||||
func (s *MySuite) TestList(c *C) {
|
||||
root, err := ioutil.TempDir(os.TempDir(), "fs-")
|
||||
c.Assert(err, IsNil)
|
||||
root, e := ioutil.TempDir(os.TempDir(), "fs-")
|
||||
c.Assert(e, IsNil)
|
||||
defer os.RemoveAll(root)
|
||||
|
||||
// Create multiple files.
|
||||
objectPath := filepath.Join(root, "object1")
|
||||
fsc, perr := fs.New(objectPath)
|
||||
fsClient, err := fs.New(objectPath)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
data := "hello"
|
||||
dataLen := len(data)
|
||||
|
||||
perr = fsc.PutObject(int64(dataLen), bytes.NewReader([]byte(data)))
|
||||
reader := bytes.NewReader([]byte(data))
|
||||
var n int64
|
||||
n, err = fsClient.Put(reader, int64(len(data)), "application/octet-stream", nil)
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(n, Equals, int64(len(data)))
|
||||
|
||||
objectPath = filepath.Join(root, "object2")
|
||||
fsc, perr = fs.New(objectPath)
|
||||
fsClient, err = fs.New(objectPath)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
perr = fsc.PutObject(int64(dataLen), bytes.NewReader([]byte(data)))
|
||||
reader = bytes.NewReader([]byte(data))
|
||||
n, err = fsClient.Put(reader, int64(len(data)), "application/octet-stream", nil)
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(n, Equals, int64(len(data)))
|
||||
|
||||
fsc, perr = fs.New(root)
|
||||
fsClient, err = fs.New(root)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
// Verify previously create files and list them.
|
||||
var contents []*client.Content
|
||||
for contentCh := range fsc.List(false) {
|
||||
if contentCh.Err != nil {
|
||||
perr = contentCh.Err
|
||||
for content := range fsClient.List(false, false) {
|
||||
if content.Err != nil {
|
||||
err = content.Err
|
||||
break
|
||||
}
|
||||
contents = append(contents, contentCh.Content)
|
||||
}
|
||||
c.Assert(perr, IsNil)
|
||||
c.Assert(len(contents), Equals, 2)
|
||||
|
||||
for _, content := range contents {
|
||||
c.Assert(content.Type.IsRegular(), Equals, true)
|
||||
contents = append(contents, content)
|
||||
}
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(len(contents), Equals, 1)
|
||||
c.Assert(contents[0].Type.IsDir(), Equals, true)
|
||||
|
||||
// Create another file.
|
||||
objectPath = filepath.Join(root, "test1/newObject1")
|
||||
fsc, perr = fs.New(objectPath)
|
||||
fsClient, err = fs.New(objectPath)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
perr = fsc.PutObject(int64(dataLen), bytes.NewReader([]byte(data)))
|
||||
reader = bytes.NewReader([]byte(data))
|
||||
n, err = fsClient.Put(reader, int64(len(data)), "application/octet-stream", nil)
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(n, Equals, int64(len(data)))
|
||||
|
||||
fsc, perr = fs.New(root)
|
||||
fsClient, err = fs.New(root)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
contents = nil
|
||||
for contentCh := range fsc.List(false) {
|
||||
if contentCh.Err != nil {
|
||||
perr = contentCh.Err
|
||||
// List non recursive to list only top level files.
|
||||
for content := range fsClient.List(false, false) {
|
||||
if content.Err != nil {
|
||||
err = content.Err
|
||||
break
|
||||
}
|
||||
contents = append(contents, contentCh.Content)
|
||||
contents = append(contents, content)
|
||||
}
|
||||
c.Assert(perr, IsNil)
|
||||
c.Assert(len(contents), Equals, 3)
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(len(contents), Equals, 1)
|
||||
c.Assert(contents[0].Type.IsDir(), Equals, true)
|
||||
|
||||
for _, content := range contents {
|
||||
// skip previous regular files
|
||||
if content.Type.IsRegular() {
|
||||
continue
|
||||
}
|
||||
c.Assert(content.Type.IsDir(), Equals, true)
|
||||
}
|
||||
|
||||
fsc, perr = fs.New(root)
|
||||
fsClient, err = fs.New(root)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
contents = nil
|
||||
for contentCh := range fsc.List(true) {
|
||||
if contentCh.Err != nil {
|
||||
perr = contentCh.Err
|
||||
// List recursively all files and verify.
|
||||
for content := range fsClient.List(true, false) {
|
||||
if content.Err != nil {
|
||||
err = content.Err
|
||||
break
|
||||
}
|
||||
contents = append(contents, contentCh.Content)
|
||||
contents = append(contents, content)
|
||||
}
|
||||
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(len(contents), Equals, 4)
|
||||
c.Assert(len(contents), Equals, 5)
|
||||
|
||||
var regularFiles int
|
||||
var folders int
|
||||
var regularDirs int
|
||||
// Test number of expected files and directories.
|
||||
for _, content := range contents {
|
||||
if content.Type.IsRegular() {
|
||||
regularFiles++
|
||||
continue
|
||||
}
|
||||
if content.Type.IsDir() {
|
||||
folders++
|
||||
regularDirs++
|
||||
continue
|
||||
}
|
||||
}
|
||||
c.Assert(regularDirs, Equals, 2)
|
||||
c.Assert(regularFiles, Equals, 3)
|
||||
c.Assert(folders, Equals, 1)
|
||||
}
|
||||
|
||||
// Test put bucket aka 'mkdir()' operation.
|
||||
func (s *MySuite) TestPutBucket(c *C) {
|
||||
root, err := ioutil.TempDir(os.TempDir(), "fs-")
|
||||
c.Assert(err, IsNil)
|
||||
root, e := ioutil.TempDir(os.TempDir(), "fs-")
|
||||
c.Assert(e, IsNil)
|
||||
defer os.RemoveAll(root)
|
||||
|
||||
bucketPath := filepath.Join(root, "bucket")
|
||||
fsc, perr := fs.New(bucketPath)
|
||||
c.Assert(perr, IsNil)
|
||||
perr = fsc.MakeBucket()
|
||||
c.Assert(perr, IsNil)
|
||||
fsClient, err := fs.New(bucketPath)
|
||||
c.Assert(err, IsNil)
|
||||
err = fsClient.MakeBucket("us-east-1")
|
||||
c.Assert(err, IsNil)
|
||||
}
|
||||
|
||||
// Test stat bucket aka 'stat()' operation.
|
||||
func (s *MySuite) TestStatBucket(c *C) {
|
||||
root, err := ioutil.TempDir(os.TempDir(), "fs-")
|
||||
c.Assert(err, IsNil)
|
||||
root, e := ioutil.TempDir(os.TempDir(), "fs-")
|
||||
c.Assert(e, IsNil)
|
||||
defer os.RemoveAll(root)
|
||||
|
||||
bucketPath := filepath.Join(root, "bucket")
|
||||
|
||||
fsc, perr := fs.New(bucketPath)
|
||||
c.Assert(perr, IsNil)
|
||||
perr = fsc.MakeBucket()
|
||||
c.Assert(perr, IsNil)
|
||||
_, perr = fsc.Stat()
|
||||
c.Assert(perr, IsNil)
|
||||
fsClient, err := fs.New(bucketPath)
|
||||
c.Assert(err, IsNil)
|
||||
err = fsClient.MakeBucket("us-east-1")
|
||||
c.Assert(err, IsNil)
|
||||
_, err = fsClient.Stat()
|
||||
c.Assert(err, IsNil)
|
||||
}
|
||||
|
||||
// Test bucket acl fails for directories.
|
||||
func (s *MySuite) TestBucketACLFails(c *C) {
|
||||
root, err := ioutil.TempDir(os.TempDir(), "fs-")
|
||||
c.Assert(err, IsNil)
|
||||
root, e := ioutil.TempDir(os.TempDir(), "fs-")
|
||||
c.Assert(e, IsNil)
|
||||
defer os.RemoveAll(root)
|
||||
|
||||
bucketPath := filepath.Join(root, "bucket")
|
||||
fsc, perr := fs.New(bucketPath)
|
||||
c.Assert(perr, IsNil)
|
||||
perr = fsc.MakeBucket()
|
||||
c.Assert(perr, IsNil)
|
||||
fsClient, err := fs.New(bucketPath)
|
||||
c.Assert(err, IsNil)
|
||||
err = fsClient.MakeBucket("us-east-1")
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
perr = fsc.SetBucketACL("private")
|
||||
c.Assert(perr, Not(IsNil))
|
||||
err = fsClient.SetBucketAccess("private")
|
||||
c.Assert(err, Not(IsNil))
|
||||
|
||||
_, perr = fsc.GetBucketACL()
|
||||
c.Assert(perr, Not(IsNil))
|
||||
_, err = fsClient.GetBucketAccess()
|
||||
c.Assert(err, Not(IsNil))
|
||||
}
|
||||
|
||||
func (s *MySuite) TestPutObject(c *C) {
|
||||
root, err := ioutil.TempDir(os.TempDir(), "fs-")
|
||||
c.Assert(err, IsNil)
|
||||
// Test creating a file.
|
||||
func (s *MySuite) TestPut(c *C) {
|
||||
root, e := ioutil.TempDir(os.TempDir(), "fs-")
|
||||
c.Assert(e, IsNil)
|
||||
defer os.RemoveAll(root)
|
||||
|
||||
objectPath := filepath.Join(root, "object")
|
||||
fsc, perr := fs.New(objectPath)
|
||||
c.Assert(perr, IsNil)
|
||||
fsClient, err := fs.New(objectPath)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
data := "hello"
|
||||
dataLen := len(data)
|
||||
|
||||
perr = fsc.PutObject(int64(dataLen), bytes.NewReader([]byte(data)))
|
||||
c.Assert(perr, IsNil)
|
||||
reader := bytes.NewReader([]byte(data))
|
||||
var n int64
|
||||
n, err = fsClient.Put(reader, int64(len(data)), "application/octet-stream", nil)
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(n, Equals, int64(len(data)))
|
||||
}
|
||||
|
||||
func (s *MySuite) TestGetObject(c *C) {
|
||||
root, err := ioutil.TempDir(os.TempDir(), "fs-")
|
||||
c.Assert(err, IsNil)
|
||||
// Test read a file.
|
||||
func (s *MySuite) TestGet(c *C) {
|
||||
root, e := ioutil.TempDir(os.TempDir(), "fs-")
|
||||
c.Assert(e, IsNil)
|
||||
defer os.RemoveAll(root)
|
||||
|
||||
objectPath := filepath.Join(root, "object")
|
||||
fsc, perr := fs.New(objectPath)
|
||||
c.Assert(perr, IsNil)
|
||||
fsClient, err := fs.New(objectPath)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
data := "hello"
|
||||
dataLen := len(data)
|
||||
var reader io.Reader
|
||||
reader = bytes.NewReader([]byte(data))
|
||||
n, err := fsClient.Put(reader, int64(len(data)), "application/octet-stream", nil)
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(n, Equals, int64(len(data)))
|
||||
|
||||
perr = fsc.PutObject(int64(dataLen), bytes.NewReader([]byte(data)))
|
||||
c.Assert(perr, IsNil)
|
||||
|
||||
reader, size, perr := fsc.GetObject(0, 0)
|
||||
c.Assert(perr, IsNil)
|
||||
reader, err = fsClient.Get()
|
||||
c.Assert(err, IsNil)
|
||||
var results bytes.Buffer
|
||||
_, err = io.CopyN(&results, reader, int64(size))
|
||||
c.Assert(err, IsNil)
|
||||
_, e = io.Copy(&results, reader)
|
||||
c.Assert(e, IsNil)
|
||||
c.Assert([]byte(data), DeepEquals, results.Bytes())
|
||||
|
||||
}
|
||||
|
||||
func (s *MySuite) TestGetObjectRange(c *C) {
|
||||
root, err := ioutil.TempDir(os.TempDir(), "fs-")
|
||||
c.Assert(err, IsNil)
|
||||
// Test get range in a file.
|
||||
func (s *MySuite) TestGetRange(c *C) {
|
||||
root, e := ioutil.TempDir(os.TempDir(), "fs-")
|
||||
c.Assert(e, IsNil)
|
||||
defer os.RemoveAll(root)
|
||||
|
||||
objectPath := filepath.Join(root, "object")
|
||||
fsc, perr := fs.New(objectPath)
|
||||
c.Assert(perr, IsNil)
|
||||
fsClient, err := fs.New(objectPath)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
data := "hello world"
|
||||
dataLen := len(data)
|
||||
|
||||
perr = fsc.PutObject(int64(dataLen), bytes.NewReader([]byte(data)))
|
||||
c.Assert(perr, IsNil)
|
||||
|
||||
reader, size, perr := fsc.GetObject(0, 5)
|
||||
c.Assert(perr, IsNil)
|
||||
var results bytes.Buffer
|
||||
_, err = io.CopyN(&results, reader, int64(size))
|
||||
var reader io.Reader
|
||||
reader = bytes.NewReader([]byte(data))
|
||||
n, err := fsClient.Put(reader, int64(len(data)), "application/octet-stream", nil)
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(n, Equals, int64(len(data)))
|
||||
|
||||
reader, err = fsClient.Get()
|
||||
c.Assert(err, IsNil)
|
||||
var results bytes.Buffer
|
||||
buf := make([]byte, 5)
|
||||
m, e := reader.(io.ReaderAt).ReadAt(buf, 0)
|
||||
c.Assert(e, IsNil)
|
||||
c.Assert(m, Equals, 5)
|
||||
_, e = results.Write(buf)
|
||||
c.Assert(e, IsNil)
|
||||
c.Assert([]byte("hello"), DeepEquals, results.Bytes())
|
||||
}
|
||||
|
||||
// Test stat file.
|
||||
func (s *MySuite) TestStatObject(c *C) {
|
||||
root, err := ioutil.TempDir(os.TempDir(), "fs-")
|
||||
c.Assert(err, IsNil)
|
||||
root, e := ioutil.TempDir(os.TempDir(), "fs-")
|
||||
c.Assert(e, IsNil)
|
||||
defer os.RemoveAll(root)
|
||||
|
||||
objectPath := filepath.Join(root, "object")
|
||||
fsc, perr := fs.New(objectPath)
|
||||
c.Assert(perr, IsNil)
|
||||
fsClient, err := fs.New(objectPath)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
data := "hello"
|
||||
dataLen := len(data)
|
||||
reader := bytes.NewReader([]byte(data))
|
||||
n, err := fsClient.Put(reader, int64(dataLen), "application/octet-stream", nil)
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(n, Equals, int64(len(data)))
|
||||
|
||||
perr = fsc.PutObject(int64(dataLen), bytes.NewReader([]byte(data)))
|
||||
c.Assert(perr, IsNil)
|
||||
|
||||
content, perr := fsc.Stat()
|
||||
c.Assert(perr, IsNil)
|
||||
c.Assert(content.Name, Equals, objectPath)
|
||||
content, err := fsClient.Stat()
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(content.Size, Equals, int64(dataLen))
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// +build darwin dragonfly freebsd linux nacl netbsd openbsd solaris
|
||||
// +build !windows
|
||||
|
||||
/*
|
||||
* Minio Client (C) 2015 Minio, Inc.
|
||||
@@ -0,0 +1,725 @@
|
||||
/*
|
||||
* Minio Client (C) 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package s3
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"hash/fnv"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/minio/mc/pkg/client"
|
||||
"github.com/minio/mc/pkg/httptracer"
|
||||
"github.com/minio/minio-go"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
)
|
||||
|
||||
// S3 client
|
||||
type s3Client struct {
|
||||
mutex *sync.Mutex
|
||||
targetURL *client.URL
|
||||
api minio.CloudStorageClient
|
||||
virtualStyle bool
|
||||
}
|
||||
|
||||
// newFactory encloses New function with client cache.
|
||||
func newFactory() func(config *client.Config) (client.Client, *probe.Error) {
|
||||
clientCache := make(map[uint32]minio.CloudStorageClient)
|
||||
mutex := &sync.Mutex{}
|
||||
|
||||
// Return New function.
|
||||
return func(config *client.Config) (client.Client, *probe.Error) {
|
||||
// Creates a parsed URL.
|
||||
targetURL := client.NewURL(config.HostURL)
|
||||
// By default enable HTTPs.
|
||||
inSecure := false
|
||||
if targetURL.Scheme == "http" {
|
||||
inSecure = true
|
||||
}
|
||||
|
||||
// Instantiate s3 client.
|
||||
s3Clnt := &s3Client{}
|
||||
// Allocate a new mutex.
|
||||
s3Clnt.mutex = new(sync.Mutex)
|
||||
// Save the target URL.
|
||||
s3Clnt.targetURL = targetURL
|
||||
|
||||
// Save if target supports virtual host style.
|
||||
hostName := targetURL.Host
|
||||
s3Clnt.virtualStyle = isVirtualHostStyle(hostName)
|
||||
|
||||
if s3Clnt.virtualStyle {
|
||||
// If Amazon URL replace it with 's3.amazonaws.com'
|
||||
if isAmazon(hostName) {
|
||||
hostName = "s3.amazonaws.com"
|
||||
}
|
||||
// If Google URL replace it with 'storage.googleapis.com'
|
||||
if isGoogle(hostName) {
|
||||
hostName = "storage.googleapis.com"
|
||||
}
|
||||
}
|
||||
|
||||
// Generate a hash out of s3Conf.
|
||||
confHash := fnv.New32a()
|
||||
confHash.Write([]byte(hostName + config.AccessKey + config.SecretKey))
|
||||
confSum := confHash.Sum32()
|
||||
|
||||
// Lookup previous cache by hash.
|
||||
mutex.Lock()
|
||||
defer mutex.Unlock()
|
||||
var api minio.CloudStorageClient
|
||||
found := false
|
||||
if api, found = clientCache[confSum]; !found {
|
||||
// Not found. Instantiate a new minio client.
|
||||
var e error
|
||||
if config.Signature == "S3v2" {
|
||||
// if Signature version '2' use NewV2 directly.
|
||||
api, e = minio.NewV2(hostName, config.AccessKey, config.SecretKey, inSecure)
|
||||
} else {
|
||||
// if Signature version '4' use NewV4 directly.
|
||||
api, e = minio.NewV4(hostName, config.AccessKey, config.SecretKey, inSecure)
|
||||
}
|
||||
if e != nil {
|
||||
return nil, probe.NewError(e)
|
||||
}
|
||||
// Cache the new minio client with hash of config as key.
|
||||
clientCache[confSum] = api
|
||||
}
|
||||
// Set app info.
|
||||
api.SetAppInfo(config.AppName, config.AppVersion)
|
||||
|
||||
if config.Debug {
|
||||
transport := http.DefaultTransport
|
||||
if config.Signature == "S3v4" {
|
||||
transport = httptracer.GetNewTraceTransport(NewTraceV4(), http.DefaultTransport)
|
||||
}
|
||||
if config.Signature == "S3v2" {
|
||||
transport = httptracer.GetNewTraceTransport(NewTraceV2(), http.DefaultTransport)
|
||||
}
|
||||
// Set custom transport.
|
||||
api.SetCustomTransport(transport)
|
||||
}
|
||||
|
||||
// Store the new api object.
|
||||
s3Clnt.api = api
|
||||
|
||||
return s3Clnt, nil
|
||||
}
|
||||
}
|
||||
|
||||
// New returns an initialized s3Client structure. If debug is enabled,
|
||||
// it also enables an internal trace transport.
|
||||
var New = newFactory()
|
||||
|
||||
// GetURL get url.
|
||||
func (c *s3Client) GetURL() client.URL {
|
||||
return *c.targetURL
|
||||
}
|
||||
|
||||
// Get - get object.
|
||||
func (c *s3Client) Get() (io.Reader, *probe.Error) {
|
||||
bucket, object := c.url2BucketAndObject()
|
||||
reader, e := c.api.GetObject(bucket, object)
|
||||
if e != nil {
|
||||
errResponse := minio.ToErrorResponse(e)
|
||||
if errResponse.Code == "AccessDenied" {
|
||||
return nil, probe.NewError(client.PathInsufficientPermission{Path: c.targetURL.String()})
|
||||
}
|
||||
return nil, probe.NewError(e)
|
||||
}
|
||||
return reader, nil
|
||||
}
|
||||
|
||||
// Put - put object.
|
||||
func (c *s3Client) Put(reader io.Reader, size int64, contentType string, progress io.Reader) (int64, *probe.Error) {
|
||||
// md5 is purposefully ignored since AmazonS3 does not return proper md5sum
|
||||
// for a multipart upload and there is no need to cross verify,
|
||||
// invidual parts are properly verified fully in transit and also upon completion
|
||||
// of the multipart request.
|
||||
bucket, object := c.url2BucketAndObject()
|
||||
if contentType == "" {
|
||||
contentType = "application/octet-stream"
|
||||
}
|
||||
n, e := c.api.PutObjectWithProgress(bucket, object, reader, contentType, progress)
|
||||
if e != nil {
|
||||
errResponse := minio.ToErrorResponse(e)
|
||||
if errResponse.Code == "UnexpectedEOF" || e == io.EOF {
|
||||
return n, probe.NewError(client.UnexpectedEOF{
|
||||
TotalSize: size,
|
||||
TotalWritten: n,
|
||||
})
|
||||
}
|
||||
if errResponse.Code == "AccessDenied" {
|
||||
return n, probe.NewError(client.PathInsufficientPermission{
|
||||
Path: c.targetURL.String(),
|
||||
})
|
||||
}
|
||||
if errResponse.Code == "MethodNotAllowed" {
|
||||
return n, probe.NewError(client.ObjectAlreadyExists{
|
||||
Object: object,
|
||||
})
|
||||
}
|
||||
if errResponse.Code == "NoSuchBucket" {
|
||||
return n, probe.NewError(client.BucketDoesNotExist{
|
||||
Bucket: bucket,
|
||||
})
|
||||
}
|
||||
if errResponse.Code == "InvalidArgument" {
|
||||
return n, probe.NewError(client.ObjectMissing{})
|
||||
}
|
||||
return n, probe.NewError(e)
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// Remove - remove object or bucket.
|
||||
func (c *s3Client) Remove(incomplete bool) *probe.Error {
|
||||
bucket, object := c.url2BucketAndObject()
|
||||
// Remove only incomplete object.
|
||||
if incomplete && object != "" {
|
||||
e := c.api.RemoveIncompleteUpload(bucket, object)
|
||||
return probe.NewError(e)
|
||||
}
|
||||
var e error
|
||||
if object == "" {
|
||||
e = c.api.RemoveBucket(bucket)
|
||||
} else {
|
||||
e = c.api.RemoveObject(bucket, object)
|
||||
}
|
||||
return probe.NewError(e)
|
||||
}
|
||||
|
||||
// We support '.' with bucket names but we fallback to using path
|
||||
// style requests instead for such buckets
|
||||
var validBucketName = regexp.MustCompile(`^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$`)
|
||||
|
||||
// isValidBucketName - verify bucket name in accordance with
|
||||
// - http://docs.aws.amazon.com/AmazonS3/latest/dev/UsingBucket.html
|
||||
func isValidBucketName(bucketName string) *probe.Error {
|
||||
if strings.TrimSpace(bucketName) == "" {
|
||||
return probe.NewError(errors.New("Bucket name cannot be empty."))
|
||||
}
|
||||
if len(bucketName) < 3 || len(bucketName) > 63 {
|
||||
return probe.NewError(errors.New("Bucket name should be more than 3 characters and less than 64 characters"))
|
||||
}
|
||||
if !validBucketName.MatchString(bucketName) {
|
||||
return probe.NewError(errors.New("Bucket name can contain alphabet, '-' and numbers, but first character should be an alphabet or number"))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// MakeBucket - make a new bucket.
|
||||
func (c *s3Client) MakeBucket(region string) *probe.Error {
|
||||
bucket, object := c.url2BucketAndObject()
|
||||
if object != "" {
|
||||
return probe.NewError(client.BucketNameTopLevel{})
|
||||
}
|
||||
if err := isValidBucketName(bucket); err != nil {
|
||||
return err.Trace(bucket)
|
||||
}
|
||||
e := c.api.MakeBucket(bucket, minio.BucketACL("private"), region)
|
||||
if e != nil {
|
||||
return probe.NewError(e)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetBucketAccess get acl on a bucket.
|
||||
func (c *s3Client) GetBucketAccess() (acl string, err *probe.Error) {
|
||||
bucket, object := c.url2BucketAndObject()
|
||||
if object != "" {
|
||||
return "", probe.NewError(client.InvalidBucketName{Bucket: filepath.Join(bucket, object)})
|
||||
}
|
||||
if bucket == "" {
|
||||
return "", probe.NewError(client.BucketNameEmpty{})
|
||||
}
|
||||
bucketACL, e := c.api.GetBucketACL(bucket)
|
||||
if e != nil {
|
||||
return "", probe.NewError(e)
|
||||
}
|
||||
return bucketACL.String(), nil
|
||||
}
|
||||
|
||||
// SetBucketAccess set acl on a bucket
|
||||
func (c *s3Client) SetBucketAccess(acl string) *probe.Error {
|
||||
bucket, object := c.url2BucketAndObject()
|
||||
if object != "" {
|
||||
return probe.NewError(client.InvalidBucketName{Bucket: filepath.Join(bucket, object)})
|
||||
}
|
||||
if bucket == "" {
|
||||
return probe.NewError(client.BucketNameEmpty{})
|
||||
}
|
||||
e := c.api.SetBucketACL(bucket, minio.BucketACL(acl))
|
||||
if e != nil {
|
||||
return probe.NewError(e)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Stat - send a 'HEAD' on a bucket or object to fetch its metadata.
|
||||
func (c *s3Client) Stat() (*client.Content, *probe.Error) {
|
||||
c.mutex.Lock()
|
||||
objectMetadata := new(client.Content)
|
||||
bucket, object := c.url2BucketAndObject()
|
||||
switch {
|
||||
// valid case for 'ls -r s3/'
|
||||
case bucket == "" && object == "":
|
||||
_, e := c.api.ListBuckets()
|
||||
if e != nil {
|
||||
c.mutex.Unlock()
|
||||
return nil, probe.NewError(e)
|
||||
}
|
||||
c.mutex.Unlock()
|
||||
return &client.Content{URL: *c.targetURL, Type: os.ModeDir}, nil
|
||||
}
|
||||
if object != "" {
|
||||
metadata, e := c.api.StatObject(bucket, object)
|
||||
if e != nil {
|
||||
c.mutex.Unlock()
|
||||
errResponse := minio.ToErrorResponse(e)
|
||||
if errResponse.Code == "NoSuchKey" {
|
||||
// Append "/" to the object name proactively and see if the Listing
|
||||
// produces an output. If yes, then we treat it as a directory.
|
||||
prefixName := object
|
||||
// Trim any trailing separators and add it.
|
||||
prefixName = strings.TrimSuffix(prefixName, string(c.targetURL.Separator)) + string(c.targetURL.Separator)
|
||||
isRecursive := false
|
||||
for objectStat := range c.api.ListObjects(bucket, prefixName, isRecursive, nil) {
|
||||
if objectStat.Err != nil {
|
||||
return nil, probe.NewError(objectStat.Err)
|
||||
}
|
||||
content := client.Content{}
|
||||
content.URL = *c.targetURL
|
||||
content.Type = os.ModeDir
|
||||
return &content, nil
|
||||
}
|
||||
return nil, probe.NewError(client.PathNotFound{Path: c.targetURL.Path})
|
||||
}
|
||||
return nil, probe.NewError(e)
|
||||
}
|
||||
objectMetadata.URL = *c.targetURL
|
||||
objectMetadata.Time = metadata.LastModified
|
||||
objectMetadata.Size = metadata.Size
|
||||
objectMetadata.Type = os.FileMode(0664)
|
||||
c.mutex.Unlock()
|
||||
return objectMetadata, nil
|
||||
}
|
||||
e := c.api.BucketExists(bucket)
|
||||
if e != nil {
|
||||
c.mutex.Unlock()
|
||||
return nil, probe.NewError(e)
|
||||
}
|
||||
bucketMetadata := new(client.Content)
|
||||
bucketMetadata.URL = *c.targetURL
|
||||
bucketMetadata.Type = os.ModeDir
|
||||
c.mutex.Unlock()
|
||||
return bucketMetadata, nil
|
||||
}
|
||||
|
||||
func isAmazon(host string) bool {
|
||||
matchAmazon, _ := filepath.Match("*.s3*.amazonaws.com", host)
|
||||
return matchAmazon
|
||||
}
|
||||
|
||||
func isGoogle(host string) bool {
|
||||
matchGoogle, _ := filepath.Match("*.storage.googleapis.com", host)
|
||||
return matchGoogle
|
||||
}
|
||||
|
||||
// Figure out if the URL is of 'virtual host' style.
|
||||
// Currently only supported hosts with virtual style are Amazon S3 and Google Cloud Storage.
|
||||
func isVirtualHostStyle(host string) bool {
|
||||
return isAmazon(host) || isGoogle(host)
|
||||
}
|
||||
|
||||
// url2BucketAndObject gives bucketName and objectName from URL path.
|
||||
func (c *s3Client) url2BucketAndObject() (bucketName, objectName string) {
|
||||
path := c.targetURL.Path
|
||||
// Convert any virtual host styled requests.
|
||||
//
|
||||
// For the time being this check is introduced for S3,
|
||||
// If you have custom virtual styled hosts please.
|
||||
// List them below.
|
||||
if c.virtualStyle {
|
||||
var bucket string
|
||||
hostIndex := strings.Index(c.targetURL.Host, "s3")
|
||||
if hostIndex == -1 {
|
||||
hostIndex = strings.Index(c.targetURL.Host, "storage.googleapis")
|
||||
}
|
||||
if hostIndex > 0 {
|
||||
bucket = c.targetURL.Host[:hostIndex-1]
|
||||
path = string(c.targetURL.Separator) + bucket + c.targetURL.Path
|
||||
}
|
||||
}
|
||||
splits := strings.SplitN(path, string(c.targetURL.Separator), 3)
|
||||
switch len(splits) {
|
||||
case 0, 1:
|
||||
bucketName = ""
|
||||
objectName = ""
|
||||
case 2:
|
||||
bucketName = splits[1]
|
||||
objectName = ""
|
||||
case 3:
|
||||
bucketName = splits[1]
|
||||
objectName = splits[2]
|
||||
}
|
||||
return bucketName, objectName
|
||||
}
|
||||
|
||||
/// Bucket API operations.
|
||||
|
||||
// List - list at delimited path, if not recursive.
|
||||
func (c *s3Client) List(recursive, incomplete bool) <-chan *client.Content {
|
||||
c.mutex.Lock()
|
||||
defer c.mutex.Unlock()
|
||||
|
||||
contentCh := make(chan *client.Content)
|
||||
if incomplete {
|
||||
if recursive {
|
||||
go c.listIncompleteRecursiveInRoutine(contentCh)
|
||||
} else {
|
||||
go c.listIncompleteInRoutine(contentCh)
|
||||
}
|
||||
} else {
|
||||
if recursive {
|
||||
go c.listRecursiveInRoutine(contentCh)
|
||||
} else {
|
||||
go c.listInRoutine(contentCh)
|
||||
}
|
||||
}
|
||||
return contentCh
|
||||
}
|
||||
|
||||
func (c *s3Client) listIncompleteInRoutine(contentCh chan *client.Content) {
|
||||
defer close(contentCh)
|
||||
// get bucket and object from URL.
|
||||
b, o := c.url2BucketAndObject()
|
||||
switch {
|
||||
case b == "" && o == "":
|
||||
buckets, err := c.api.ListBuckets()
|
||||
if err != nil {
|
||||
contentCh <- &client.Content{
|
||||
Err: probe.NewError(err),
|
||||
}
|
||||
return
|
||||
}
|
||||
isRecursive := false
|
||||
for _, bucket := range buckets {
|
||||
for object := range c.api.ListIncompleteUploads(bucket.Name, o, isRecursive, nil) {
|
||||
if object.Err != nil {
|
||||
contentCh <- &client.Content{
|
||||
Err: probe.NewError(object.Err),
|
||||
}
|
||||
return
|
||||
}
|
||||
content := new(client.Content)
|
||||
url := *c.targetURL
|
||||
// Join bucket with - incoming object key.
|
||||
url.Path = filepath.Join(string(url.Separator), bucket.Name, object.Key)
|
||||
if c.virtualStyle {
|
||||
url.Path = filepath.Join(string(url.Separator), object.Key)
|
||||
}
|
||||
switch {
|
||||
case strings.HasSuffix(object.Key, string(c.targetURL.Separator)):
|
||||
// We need to keep the trailing Separator, do not use filepath.Join().
|
||||
content.URL = url
|
||||
content.Time = time.Now()
|
||||
content.Type = os.ModeDir
|
||||
default:
|
||||
content.URL = url
|
||||
content.Size = object.Size
|
||||
content.Time = object.Initiated
|
||||
content.Type = os.ModeTemporary
|
||||
}
|
||||
contentCh <- content
|
||||
}
|
||||
}
|
||||
default:
|
||||
isRecursive := false
|
||||
for object := range c.api.ListIncompleteUploads(b, o, isRecursive, nil) {
|
||||
if object.Err != nil {
|
||||
contentCh <- &client.Content{
|
||||
Err: probe.NewError(object.Err),
|
||||
}
|
||||
return
|
||||
}
|
||||
content := new(client.Content)
|
||||
url := *c.targetURL
|
||||
// Join bucket with - incoming object key.
|
||||
url.Path = filepath.Join(string(url.Separator), b, object.Key)
|
||||
if c.virtualStyle {
|
||||
url.Path = filepath.Join(string(url.Separator), object.Key)
|
||||
}
|
||||
switch {
|
||||
case strings.HasSuffix(object.Key, string(c.targetURL.Separator)):
|
||||
// We need to keep the trailing Separator, do not use filepath.Join().
|
||||
content.URL = url
|
||||
content.Time = time.Now()
|
||||
content.Type = os.ModeDir
|
||||
default:
|
||||
content.URL = url
|
||||
content.Size = object.Size
|
||||
content.Time = object.Initiated
|
||||
content.Type = os.ModeTemporary
|
||||
}
|
||||
contentCh <- content
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *s3Client) listIncompleteRecursiveInRoutine(contentCh chan *client.Content) {
|
||||
defer close(contentCh)
|
||||
// get bucket and object from URL.
|
||||
b, o := c.url2BucketAndObject()
|
||||
switch {
|
||||
case b == "" && o == "":
|
||||
buckets, err := c.api.ListBuckets()
|
||||
if err != nil {
|
||||
contentCh <- &client.Content{
|
||||
Err: probe.NewError(err),
|
||||
}
|
||||
return
|
||||
}
|
||||
isRecursive := true
|
||||
for _, bucket := range buckets {
|
||||
for object := range c.api.ListIncompleteUploads(bucket.Name, o, isRecursive, nil) {
|
||||
if object.Err != nil {
|
||||
contentCh <- &client.Content{
|
||||
Err: probe.NewError(object.Err),
|
||||
}
|
||||
return
|
||||
}
|
||||
url := *c.targetURL
|
||||
url.Path = filepath.Join(url.Path, bucket.Name, object.Key)
|
||||
content := new(client.Content)
|
||||
content.URL = url
|
||||
content.Size = object.Size
|
||||
content.Time = object.Initiated
|
||||
content.Type = os.ModeTemporary
|
||||
contentCh <- content
|
||||
}
|
||||
}
|
||||
default:
|
||||
isRecursive := true
|
||||
for object := range c.api.ListIncompleteUploads(b, o, isRecursive, nil) {
|
||||
if object.Err != nil {
|
||||
contentCh <- &client.Content{
|
||||
Err: probe.NewError(object.Err),
|
||||
}
|
||||
return
|
||||
}
|
||||
url := *c.targetURL
|
||||
// Join bucket and incoming object key.
|
||||
url.Path = filepath.Join(string(url.Separator), b, object.Key)
|
||||
if c.virtualStyle {
|
||||
url.Path = filepath.Join(string(url.Separator), object.Key)
|
||||
}
|
||||
content := new(client.Content)
|
||||
content.URL = url
|
||||
content.Size = object.Size
|
||||
content.Time = object.Initiated
|
||||
content.Type = os.ModeTemporary
|
||||
contentCh <- content
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *s3Client) listInRoutine(contentCh chan *client.Content) {
|
||||
defer close(contentCh)
|
||||
// get bucket and object from URL.
|
||||
b, o := c.url2BucketAndObject()
|
||||
switch {
|
||||
case b == "" && o == "":
|
||||
buckets, err := c.api.ListBuckets()
|
||||
if err != nil {
|
||||
contentCh <- &client.Content{
|
||||
Err: probe.NewError(err),
|
||||
}
|
||||
return
|
||||
}
|
||||
for _, bucket := range buckets {
|
||||
url := *c.targetURL
|
||||
url.Path = filepath.Join(url.Path, bucket.Name)
|
||||
content := new(client.Content)
|
||||
content.URL = url
|
||||
content.Size = 0
|
||||
content.Time = bucket.CreationDate
|
||||
content.Type = os.ModeDir
|
||||
contentCh <- content
|
||||
}
|
||||
case b != "" && !strings.HasSuffix(c.targetURL.Path, string(c.targetURL.Separator)) && o == "":
|
||||
e := c.api.BucketExists(b)
|
||||
if e != nil {
|
||||
contentCh <- &client.Content{
|
||||
Err: probe.NewError(e),
|
||||
}
|
||||
}
|
||||
content := new(client.Content)
|
||||
content.URL = *c.targetURL
|
||||
content.Type = os.ModeDir
|
||||
contentCh <- content
|
||||
default:
|
||||
metadata, e := c.api.StatObject(b, o)
|
||||
switch e.(type) {
|
||||
case nil:
|
||||
content := new(client.Content)
|
||||
content.URL = *c.targetURL
|
||||
content.Time = metadata.LastModified
|
||||
content.Size = metadata.Size
|
||||
content.Type = os.FileMode(0664)
|
||||
contentCh <- content
|
||||
default:
|
||||
isRecursive := false
|
||||
for object := range c.api.ListObjects(b, o, isRecursive, nil) {
|
||||
if object.Err != nil {
|
||||
contentCh <- &client.Content{
|
||||
Err: probe.NewError(object.Err),
|
||||
}
|
||||
return
|
||||
}
|
||||
content := new(client.Content)
|
||||
url := *c.targetURL
|
||||
// Join bucket and incoming object key.
|
||||
url.Path = filepath.Join(string(url.Separator), b, object.Key)
|
||||
if c.virtualStyle {
|
||||
url.Path = filepath.Join(string(url.Separator), object.Key)
|
||||
}
|
||||
switch {
|
||||
case strings.HasSuffix(object.Key, string(c.targetURL.Separator)):
|
||||
// We need to keep the trailing Separator, do not use filepath.Join().
|
||||
content.URL = url
|
||||
content.Time = time.Now()
|
||||
content.Type = os.ModeDir
|
||||
default:
|
||||
content.URL = url
|
||||
content.Size = object.Size
|
||||
content.Time = object.LastModified
|
||||
content.Type = os.FileMode(0664)
|
||||
}
|
||||
contentCh <- content
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *s3Client) listRecursiveInRoutine(contentCh chan *client.Content) {
|
||||
defer close(contentCh)
|
||||
// get bucket and object from URL.
|
||||
b, o := c.url2BucketAndObject()
|
||||
switch {
|
||||
case b == "" && o == "":
|
||||
buckets, err := c.api.ListBuckets()
|
||||
if err != nil {
|
||||
contentCh <- &client.Content{
|
||||
Err: probe.NewError(err),
|
||||
}
|
||||
return
|
||||
}
|
||||
for _, bucket := range buckets {
|
||||
bucketURL := *c.targetURL
|
||||
bucketURL.Path = filepath.Join(bucketURL.Path, bucket.Name)
|
||||
contentCh <- &client.Content{
|
||||
URL: bucketURL,
|
||||
Type: os.ModeDir,
|
||||
Time: bucket.CreationDate,
|
||||
}
|
||||
isRecursive := true
|
||||
for object := range c.api.ListObjects(bucket.Name, o, isRecursive, nil) {
|
||||
if object.Err != nil {
|
||||
contentCh <- &client.Content{
|
||||
Err: probe.NewError(object.Err),
|
||||
}
|
||||
continue
|
||||
}
|
||||
content := new(client.Content)
|
||||
objectURL := *c.targetURL
|
||||
objectURL.Path = filepath.Join(objectURL.Path, bucket.Name, object.Key)
|
||||
content.URL = objectURL
|
||||
content.Size = object.Size
|
||||
content.Time = object.LastModified
|
||||
content.Type = os.FileMode(0664)
|
||||
contentCh <- content
|
||||
}
|
||||
}
|
||||
default:
|
||||
isRecursive := true
|
||||
for object := range c.api.ListObjects(b, o, isRecursive, nil) {
|
||||
if object.Err != nil {
|
||||
contentCh <- &client.Content{
|
||||
Err: probe.NewError(object.Err),
|
||||
}
|
||||
continue
|
||||
}
|
||||
content := new(client.Content)
|
||||
url := *c.targetURL
|
||||
// Join bucket and incoming object key.
|
||||
url.Path = filepath.Join(string(url.Separator), b, object.Key)
|
||||
// If virtualStyle replace the url.Path back.
|
||||
if c.virtualStyle {
|
||||
url.Path = filepath.Join(string(url.Separator), object.Key)
|
||||
}
|
||||
content.URL = url
|
||||
content.Size = object.Size
|
||||
content.Time = object.LastModified
|
||||
content.Type = os.FileMode(0664)
|
||||
contentCh <- content
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ShareDownload - get a usable presigned object url to share.
|
||||
func (c *s3Client) ShareDownload(expires time.Duration) (string, *probe.Error) {
|
||||
bucket, object := c.url2BucketAndObject()
|
||||
presignedURL, e := c.api.PresignedGetObject(bucket, object, expires)
|
||||
if e != nil {
|
||||
return "", probe.NewError(e)
|
||||
}
|
||||
return presignedURL, nil
|
||||
}
|
||||
|
||||
// ShareUpload - get data for presigned post http form upload.
|
||||
func (c *s3Client) ShareUpload(isRecursive bool, expires time.Duration, contentType string) (map[string]string, *probe.Error) {
|
||||
bucket, object := c.url2BucketAndObject()
|
||||
p := minio.NewPostPolicy()
|
||||
if e := p.SetExpires(time.Now().UTC().Add(expires)); e != nil {
|
||||
return nil, probe.NewError(e)
|
||||
}
|
||||
if strings.TrimSpace(contentType) != "" || contentType != "" {
|
||||
// No need to verify for error here, since we have stripped out spaces.
|
||||
p.SetContentType(contentType)
|
||||
}
|
||||
if e := p.SetBucket(bucket); e != nil {
|
||||
return nil, probe.NewError(e)
|
||||
}
|
||||
if isRecursive {
|
||||
if e := p.SetKeyStartsWith(object); e != nil {
|
||||
return nil, probe.NewError(e)
|
||||
}
|
||||
} else {
|
||||
if e := p.SetKey(object); e != nil {
|
||||
return nil, probe.NewError(e)
|
||||
}
|
||||
}
|
||||
m, e := c.api.PresignedPostPolicy(p)
|
||||
return m, probe.NewError(e)
|
||||
}
|
||||
@@ -14,7 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package s3v2
|
||||
package s3
|
||||
|
||||
// bucketHandler is an http.Handler that verifies bucket responses and validates incoming requests
|
||||
import (
|
||||
@@ -38,12 +38,21 @@ type bucketHandler struct {
|
||||
func (h bucketHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case r.Method == "GET":
|
||||
// Handler for incoming getBucketLocation request.
|
||||
if _, ok := r.URL.Query()["location"]; ok {
|
||||
response := []byte("<LocationConstraint xmlns=\"http://doc.s3.amazonaws.com/2006-03-01\"></LocationConstraint>")
|
||||
w.Header().Set("Content-Length", strconv.Itoa(len(response)))
|
||||
w.Write(response)
|
||||
return
|
||||
}
|
||||
switch {
|
||||
case r.URL.Path == "/":
|
||||
// Handler for incoming ListBuckets request.
|
||||
response := []byte("<ListAllMyBucketsResult xmlns=\"http://doc.s3.amazonaws.com/2006-03-01\"><Buckets><Bucket><Name>bucket</Name><CreationDate>2015-05-20T23:05:09.230Z</CreationDate></Bucket></Buckets><Owner><ID>minio</ID><DisplayName>minio</DisplayName></Owner></ListAllMyBucketsResult>")
|
||||
w.Header().Set("Content-Length", strconv.Itoa(len(response)))
|
||||
w.Write(response)
|
||||
case r.URL.Path == "/bucket":
|
||||
case r.URL.Path == "/bucket/":
|
||||
// Handler for incoming ListObjects request.
|
||||
response := []byte("<ListBucketResult xmlns=\"http://doc.s3.amazonaws.com/2006-03-01\"><Contents><ETag>259d04a13802ae09c7e41be50ccc6baa</ETag><Key>object</Key><LastModified>2015-05-21T18:24:21.097Z</LastModified><Size>22061</Size><Owner><ID>minio</ID><DisplayName>minio</DisplayName></Owner><StorageClass>STANDARD</StorageClass></Contents><Delimiter></Delimiter><EncodingType></EncodingType><IsTruncated>false</IsTruncated><Marker></Marker><MaxKeys>1000</MaxKeys><Name>testbucket</Name><NextMarker></NextMarker><Prefix></Prefix></ListBucketResult>")
|
||||
w.Header().Set("Content-Length", strconv.Itoa(len(response)))
|
||||
w.Write(response)
|
||||
@@ -51,6 +60,7 @@ 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" {
|
||||
@@ -80,14 +90,14 @@ type objectHandler struct {
|
||||
func (h objectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case r.Method == "PUT":
|
||||
length, err := strconv.Atoi(r.Header.Get("Content-Length"))
|
||||
if err != nil {
|
||||
// Handler for PUT object request.
|
||||
length, e := strconv.Atoi(r.Header.Get("Content-Length"))
|
||||
if e != nil {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
var buffer bytes.Buffer
|
||||
_, err = io.CopyN(&buffer, r.Body, int64(length))
|
||||
if err != nil {
|
||||
if _, e = io.CopyN(&buffer, r.Body, int64(length)); e != nil {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
@@ -98,6 +108,7 @@ func (h objectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("ETag", "9af2f8218b150c351ad802c6f3d66abe")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
case r.Method == "HEAD":
|
||||
// Handler for Stat object request.
|
||||
if r.URL.Path != h.resource {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
return
|
||||
@@ -106,7 +117,45 @@ func (h objectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Last-Modified", time.Now().UTC().Format(http.TimeFormat))
|
||||
w.Header().Set("ETag", "9af2f8218b150c351ad802c6f3d66abe")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
case r.Method == "POST":
|
||||
// Handler for multipart upload request.
|
||||
if _, ok := r.URL.Query()["uploads"]; ok {
|
||||
if r.URL.Path == h.resource {
|
||||
response := []byte("<InitiateMultipartUploadResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\"><Bucket>bucket</Bucket><Key>object</Key><UploadId>EXAMPLEJZ6e0YupT2h66iePQCc9IEbYbDUy4RTpMeoSMLPRp8Z5o1u8feSRonpvnWsKKG35tI2LB9VDPiCgTy.Gq2VxQLYjrue4Nq.NBdqI-</UploadId></InitiateMultipartUploadResult>")
|
||||
w.Header().Set("Content-Length", strconv.Itoa(len(response)))
|
||||
w.Write(response)
|
||||
return
|
||||
}
|
||||
}
|
||||
if _, ok := r.URL.Query()["uploadId"]; ok {
|
||||
if r.URL.Path == h.resource {
|
||||
response := []byte("<CompleteMultipartUploadResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\"><Location>http://bucket.s3.amazonaws.com/object</Location><Bucket>bucket</Bucket><Key>object</Key><ETag>\"3858f62230ac3c915f300c664312c11f-9\"</ETag></CompleteMultipartUploadResult>")
|
||||
w.Header().Set("Content-Length", strconv.Itoa(len(response)))
|
||||
w.Write(response)
|
||||
return
|
||||
}
|
||||
}
|
||||
if r.URL.Path != h.resource {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
case r.Method == "GET":
|
||||
// Handler for get bucket location request.
|
||||
if _, ok := r.URL.Query()["location"]; ok {
|
||||
response := []byte("<LocationConstraint xmlns=\"http://doc.s3.amazonaws.com/2006-03-01\"></LocationConstraint>")
|
||||
w.Header().Set("Content-Length", strconv.Itoa(len(response)))
|
||||
w.Write(response)
|
||||
return
|
||||
}
|
||||
// Handler for list multipart upload request.
|
||||
if _, ok := r.URL.Query()["uploads"]; ok {
|
||||
if r.URL.Path == "/bucket/" {
|
||||
response := []byte("<ListMultipartUploadsResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\"><Bucket>bucket</Bucket><KeyMarker/><UploadIdMarker/><NextKeyMarker/><NextUploadIdMarker/><EncodingType/><MaxUploads>1000</MaxUploads><IsTruncated>false</IsTruncated><Prefix/><Delimiter/></ListMultipartUploadsResult>")
|
||||
w.Header().Set("Content-Length", strconv.Itoa(len(response)))
|
||||
w.Write(response)
|
||||
return
|
||||
}
|
||||
}
|
||||
if r.URL.Path != h.resource {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
return
|
||||
@@ -125,45 +174,57 @@ type MySuite struct{}
|
||||
|
||||
var _ = Suite(&MySuite{})
|
||||
|
||||
// Test bucket operations.
|
||||
func (s *MySuite) TestBucketOperations(c *C) {
|
||||
bucket := bucketHandler(bucketHandler{
|
||||
resource: "/bucket",
|
||||
resource: "/bucket/",
|
||||
})
|
||||
server := httptest.NewServer(bucket)
|
||||
defer server.Close()
|
||||
|
||||
conf := new(client.Config)
|
||||
conf.HostURL = server.URL + bucket.resource
|
||||
conf.AccessKey = "WLGDGYAQYIGI833EV05A"
|
||||
conf.SecretKey = "BYvgJM101sHngl2uzjXS/OBF/aMxAN06JrJ3qJlF"
|
||||
conf.Signature = "S3v4"
|
||||
s3c, err := New(conf)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
err = s3c.MakeBucket()
|
||||
err = s3c.MakeBucket("us-east-1")
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
err = s3c.SetBucketACL("public-read-write")
|
||||
err = s3c.SetBucketAccess("public-read-write")
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
conf.HostURL = server.URL + string(s3c.URL().Separator)
|
||||
conf.HostURL = server.URL + string(s3c.GetURL().Separator)
|
||||
s3c, err = New(conf)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
for content := range s3c.List(false) {
|
||||
for content := range s3c.List(false, false) {
|
||||
c.Assert(content.Err, IsNil)
|
||||
c.Assert(content.Content.Name, Equals, "bucket")
|
||||
c.Assert(content.Content.Type.IsDir(), Equals, true)
|
||||
c.Assert(content.Type.IsDir(), Equals, true)
|
||||
}
|
||||
|
||||
conf.HostURL = server.URL + "/bucket"
|
||||
s3c, err = New(conf)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
for content := range s3c.List(false) {
|
||||
for content := range s3c.List(false, false) {
|
||||
c.Assert(content.Err, IsNil)
|
||||
c.Assert(content.Content.Name, Equals, "object")
|
||||
c.Assert(content.Content.Type.IsRegular(), Equals, true)
|
||||
c.Assert(content.Type.IsDir(), Equals, true)
|
||||
}
|
||||
|
||||
conf.HostURL = server.URL + "/bucket/"
|
||||
s3c, err = New(conf)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
for content := range s3c.List(false, false) {
|
||||
c.Assert(content.Err, IsNil)
|
||||
c.Assert(content.Type.IsRegular(), Equals, true)
|
||||
}
|
||||
}
|
||||
|
||||
// Test all object operations.
|
||||
func (s *MySuite) TestObjectOperations(c *C) {
|
||||
object := objectHandler(objectHandler{
|
||||
resource: "/bucket/object",
|
||||
@@ -174,24 +235,27 @@ func (s *MySuite) TestObjectOperations(c *C) {
|
||||
|
||||
conf := new(client.Config)
|
||||
conf.HostURL = server.URL + object.resource
|
||||
conf.AccessKey = "WLGDGYAQYIGI833EV05A"
|
||||
conf.SecretKey = "BYvgJM101sHngl2uzjXS/OBF/aMxAN06JrJ3qJlF"
|
||||
conf.Signature = "S3v4"
|
||||
s3c, err := New(conf)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
err = s3c.PutObject(int64(len(object.data)), bytes.NewReader(object.data))
|
||||
var reader io.Reader
|
||||
reader = bytes.NewReader(object.data)
|
||||
n, err := s3c.Put(reader, int64(len(object.data)), "application/octet-stream", nil)
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(n, Equals, int64(len(object.data)))
|
||||
|
||||
content, err := s3c.Stat()
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(content.Name, Equals, "object")
|
||||
c.Assert(content.Size, Equals, int64(len(object.data)))
|
||||
c.Assert(content.Type.IsRegular(), Equals, true)
|
||||
|
||||
reader, size, err := s3c.GetObject(0, 0)
|
||||
c.Assert(size, Equals, int64(len(object.data)))
|
||||
|
||||
reader, err = s3c.Get()
|
||||
var buffer bytes.Buffer
|
||||
{
|
||||
_, err := io.CopyN(&buffer, reader, int64(size))
|
||||
_, err := io.Copy(&buffer, reader)
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(buffer.Bytes(), DeepEquals, object.data)
|
||||
}
|
||||
@@ -14,7 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package s3v2
|
||||
package s3
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
@@ -25,16 +25,16 @@ import (
|
||||
"github.com/minio/mc/pkg/httptracer"
|
||||
)
|
||||
|
||||
// Trace - tracing structure
|
||||
type Trace struct{}
|
||||
// TraceV2 - tracing structure
|
||||
type TraceV2 struct{}
|
||||
|
||||
// NewTrace - initialize Trace structure
|
||||
func NewTrace() httptracer.HTTPTracer {
|
||||
return Trace{}
|
||||
// NewTraceV2 - initialize Trace structure
|
||||
func NewTraceV2() httptracer.HTTPTracer {
|
||||
return TraceV2{}
|
||||
}
|
||||
|
||||
// Request - Trace HTTP Request
|
||||
func (t Trace) 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,8 +57,17 @@ func (t Trace) Request(req *http.Request) (err error) {
|
||||
}
|
||||
|
||||
// Response - Trace HTTP Response
|
||||
func (t Trace) Response(res *http.Response) (err error) {
|
||||
resTrace, err := httputil.DumpResponse(res, false) // Only display header
|
||||
func (t TraceV2) Response(res *http.Response) (err error) {
|
||||
var resTrace []byte
|
||||
// For errors we make sure to dump response body as well.
|
||||
if res.StatusCode != http.StatusOK &&
|
||||
res.StatusCode != http.StatusPartialContent &&
|
||||
res.StatusCode != http.StatusNoContent {
|
||||
resTrace, err = httputil.DumpResponse(res, true)
|
||||
} else {
|
||||
// Only display header
|
||||
resTrace, err = httputil.DumpResponse(res, false)
|
||||
}
|
||||
if err == nil {
|
||||
console.Debug(string(resTrace))
|
||||
}
|
||||
@@ -14,7 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package s3v4
|
||||
package s3
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
@@ -26,17 +26,16 @@ import (
|
||||
"github.com/minio/mc/pkg/httptracer"
|
||||
)
|
||||
|
||||
// Trace - tracing structure
|
||||
type Trace struct {
|
||||
}
|
||||
// TraceV4 - tracing structure
|
||||
type TraceV4 struct{}
|
||||
|
||||
// NewTrace - initialize Trace structure
|
||||
func NewTrace() httptracer.HTTPTracer {
|
||||
return Trace{}
|
||||
// NewTraceV4 - initialize Trace structure
|
||||
func NewTraceV4() httptracer.HTTPTracer {
|
||||
return TraceV4{}
|
||||
}
|
||||
|
||||
// Request - Trace HTTP Request
|
||||
func (t Trace) Request(req *http.Request) (err error) {
|
||||
func (t TraceV4) Request(req *http.Request) (err error) {
|
||||
origAuth := req.Header.Get("Authorization")
|
||||
|
||||
if strings.TrimSpace(origAuth) != "" {
|
||||
@@ -67,8 +66,17 @@ func (t Trace) Request(req *http.Request) (err error) {
|
||||
}
|
||||
|
||||
// Response - Trace HTTP Response
|
||||
func (t Trace) Response(res *http.Response) (err error) {
|
||||
resTrace, err := httputil.DumpResponse(res, false) // Only display header
|
||||
func (t TraceV4) Response(res *http.Response) (err error) {
|
||||
var resTrace []byte
|
||||
// For errors we make sure to dump response body as well.
|
||||
if res.StatusCode != http.StatusOK &&
|
||||
res.StatusCode != http.StatusPartialContent &&
|
||||
res.StatusCode != http.StatusNoContent {
|
||||
resTrace, err = httputil.DumpResponse(res, true)
|
||||
} else {
|
||||
// Only display header
|
||||
resTrace, err = httputil.DumpResponse(res, false)
|
||||
}
|
||||
if err == nil {
|
||||
console.Debug(string(resTrace))
|
||||
}
|
||||
@@ -1,379 +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 s3v2
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/minio/mc/pkg/client"
|
||||
"github.com/minio/mc/pkg/httptracer"
|
||||
"github.com/minio/minio-go-legacy"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
type s3Client struct {
|
||||
api minio.API
|
||||
hostURL *client.URL
|
||||
}
|
||||
|
||||
// New returns an initialized s3Client structure. if debug use a internal trace transport
|
||||
func New(config *client.Config) (client.Client, *probe.Error) {
|
||||
u := client.NewURL(config.HostURL)
|
||||
transport := http.DefaultTransport
|
||||
if config.Debug == true {
|
||||
transport = httptracer.GetNewTraceTransport(NewTrace(), http.DefaultTransport)
|
||||
}
|
||||
s3Conf := minio.Config{
|
||||
AccessKeyID: config.AccessKeyID,
|
||||
SecretAccessKey: config.SecretAccessKey,
|
||||
Transport: transport,
|
||||
Endpoint: u.Scheme + u.SchemeSeparator + u.Host,
|
||||
}
|
||||
s3Conf.AccessKeyID = config.AccessKeyID
|
||||
s3Conf.SecretAccessKey = config.SecretAccessKey
|
||||
s3Conf.Transport = transport
|
||||
s3Conf.SetUserAgent(config.AppName, config.AppVersion, config.AppComments...)
|
||||
s3Conf.Endpoint = u.Scheme + u.SchemeSeparator + u.Host
|
||||
api, err := minio.New(s3Conf)
|
||||
if err != nil {
|
||||
return nil, probe.NewError(err)
|
||||
}
|
||||
return &s3Client{api: api, hostURL: u}, nil
|
||||
}
|
||||
|
||||
// URL get url
|
||||
func (c *s3Client) URL() *client.URL {
|
||||
return c.hostURL
|
||||
}
|
||||
|
||||
// GetObject - get object
|
||||
func (c *s3Client) GetObject(offset, length int64) (io.ReadCloser, int64, *probe.Error) {
|
||||
bucket, object := c.url2BucketAndObject()
|
||||
reader, metadata, err := c.api.GetPartialObject(bucket, object, offset, length)
|
||||
if err != nil {
|
||||
return nil, length, probe.NewError(err)
|
||||
}
|
||||
return reader, metadata.Size, nil
|
||||
}
|
||||
|
||||
// Share - get a usable get object url to share
|
||||
func (c *s3Client) Share(expires time.Duration) (string, *probe.Error) {
|
||||
bucket, object := c.url2BucketAndObject()
|
||||
presignedURL, err := c.api.PresignedGetObject(bucket, object, expires)
|
||||
if err != nil {
|
||||
return "", probe.NewError(err)
|
||||
}
|
||||
return presignedURL, nil
|
||||
}
|
||||
|
||||
// PutObject - put object
|
||||
func (c *s3Client) PutObject(size int64, data io.Reader) *probe.Error {
|
||||
// md5 is purposefully ignored since AmazonS3 does not return proper md5sum
|
||||
// for a multipart upload and there is no need to cross verify,
|
||||
// invidual parts are properly verified
|
||||
bucket, object := c.url2BucketAndObject()
|
||||
err := c.api.PutObject(bucket, object, "application/octet-stream", size, data)
|
||||
if err != nil {
|
||||
errResponse := minio.ToErrorResponse(err)
|
||||
if errResponse != nil {
|
||||
if errResponse.Code == "MethodNotAllowed" {
|
||||
return probe.NewError(client.ObjectAlreadyExists{Object: object})
|
||||
}
|
||||
}
|
||||
return probe.NewError(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// MakeBucket - make a new bucket
|
||||
func (c *s3Client) MakeBucket() *probe.Error {
|
||||
bucket, object := c.url2BucketAndObject()
|
||||
if object != "" {
|
||||
return probe.NewError(client.InvalidQueryURL{URL: c.hostURL.String()})
|
||||
}
|
||||
if bucket == "" {
|
||||
return probe.NewError(errors.New("Bucket name is empty."))
|
||||
}
|
||||
|
||||
err := c.api.MakeBucket(bucket, minio.BucketACL("private"))
|
||||
if err != nil {
|
||||
return probe.NewError(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetBucketACL get canned acl's on a bucket
|
||||
func (c *s3Client) GetBucketACL() (acl string, error *probe.Error) {
|
||||
bucket, object := c.url2BucketAndObject()
|
||||
if object != "" {
|
||||
return "", probe.NewError(client.InvalidQueryURL{URL: c.hostURL.String()})
|
||||
}
|
||||
bucketACL, err := c.api.GetBucketACL(bucket)
|
||||
if err != nil {
|
||||
return "", probe.NewError(err)
|
||||
}
|
||||
return bucketACL.String(), nil
|
||||
}
|
||||
|
||||
// SetBucketACL add canned acl's on a bucket
|
||||
func (c *s3Client) SetBucketACL(acl string) *probe.Error {
|
||||
bucket, object := c.url2BucketAndObject()
|
||||
if object != "" {
|
||||
return probe.NewError(client.InvalidQueryURL{URL: c.hostURL.String()})
|
||||
}
|
||||
err := c.api.SetBucketACL(bucket, minio.BucketACL(acl))
|
||||
if err != nil {
|
||||
return probe.NewError(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Stat - send a 'HEAD' on a bucket or object to get its metadata
|
||||
func (c *s3Client) Stat() (*client.Content, *probe.Error) {
|
||||
objectMetadata := new(client.Content)
|
||||
bucket, object := c.url2BucketAndObject()
|
||||
switch {
|
||||
// valid case for s3/...
|
||||
case bucket == "" && object == "":
|
||||
for bucket := range c.api.ListBuckets() {
|
||||
if bucket.Err != nil {
|
||||
return nil, probe.NewError(bucket.Err)
|
||||
}
|
||||
}
|
||||
return &client.Content{Type: os.ModeDir}, nil
|
||||
}
|
||||
if object != "" {
|
||||
metadata, err := c.api.StatObject(bucket, object)
|
||||
if err != nil {
|
||||
errResponse := minio.ToErrorResponse(err)
|
||||
if errResponse != nil {
|
||||
if errResponse.Code == "NoSuchKey" {
|
||||
for content := range c.List(false) {
|
||||
if content.Err != nil {
|
||||
return nil, content.Err.Trace()
|
||||
}
|
||||
content.Content.Type = os.ModeDir
|
||||
content.Content.Name = object
|
||||
content.Content.Size = 0
|
||||
return content.Content, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil, probe.NewError(err)
|
||||
}
|
||||
objectMetadata.Name = metadata.Key
|
||||
objectMetadata.Time = metadata.LastModified
|
||||
objectMetadata.Size = metadata.Size
|
||||
objectMetadata.Type = os.FileMode(0664)
|
||||
return objectMetadata, nil
|
||||
}
|
||||
err := c.api.BucketExists(bucket)
|
||||
if err != nil {
|
||||
return nil, probe.NewError(err)
|
||||
}
|
||||
bucketMetadata := new(client.Content)
|
||||
bucketMetadata.Name = bucket
|
||||
bucketMetadata.Type = os.ModeDir
|
||||
return bucketMetadata, nil
|
||||
}
|
||||
|
||||
// url2BucketAndObject gives bucketName and objectName from URL path
|
||||
func (c *s3Client) url2BucketAndObject() (bucketName, objectName string) {
|
||||
path := c.hostURL.Path
|
||||
// Convert any virtual host styled requests
|
||||
//
|
||||
// For the time being this check is introduced for S3,
|
||||
// if you have custom virtual styled hosts please. list them below
|
||||
match, _ := filepath.Match("*.s3*.amazonaws.com", c.hostURL.Host)
|
||||
switch {
|
||||
case match == true:
|
||||
hostSplits := strings.SplitN(c.hostURL.Host, ".", 2)
|
||||
path = string(c.hostURL.Separator) + hostSplits[0] + c.hostURL.Path
|
||||
}
|
||||
|
||||
splits := strings.SplitN(path, string(c.hostURL.Separator), 3)
|
||||
switch len(splits) {
|
||||
case 0, 1:
|
||||
bucketName = ""
|
||||
objectName = ""
|
||||
case 2:
|
||||
bucketName = splits[1]
|
||||
objectName = ""
|
||||
case 3:
|
||||
bucketName = splits[1]
|
||||
objectName = splits[2]
|
||||
}
|
||||
return bucketName, objectName
|
||||
}
|
||||
|
||||
/// Bucket API operations
|
||||
|
||||
// List - list at delimited path, if not recursive
|
||||
func (c *s3Client) List(recursive bool) <-chan client.ContentOnChannel {
|
||||
contentCh := make(chan client.ContentOnChannel)
|
||||
switch recursive {
|
||||
case true:
|
||||
go c.listRecursiveInRoutine(contentCh)
|
||||
default:
|
||||
go c.listInRoutine(contentCh)
|
||||
}
|
||||
return contentCh
|
||||
}
|
||||
|
||||
func (c *s3Client) listInRoutine(contentCh chan client.ContentOnChannel) {
|
||||
defer close(contentCh)
|
||||
b, o := c.url2BucketAndObject()
|
||||
switch {
|
||||
case b == "" && o == "":
|
||||
for bucket := range c.api.ListBuckets() {
|
||||
if bucket.Err != nil {
|
||||
contentCh <- client.ContentOnChannel{
|
||||
Content: nil,
|
||||
Err: probe.NewError(bucket.Err),
|
||||
}
|
||||
return
|
||||
}
|
||||
content := new(client.Content)
|
||||
content.Name = bucket.Stat.Name
|
||||
content.Size = 0
|
||||
content.Time = bucket.Stat.CreationDate
|
||||
content.Type = os.ModeDir
|
||||
contentCh <- client.ContentOnChannel{
|
||||
Content: content,
|
||||
Err: nil,
|
||||
}
|
||||
}
|
||||
default:
|
||||
metadata, err := c.api.StatObject(b, o)
|
||||
switch err.(type) {
|
||||
case nil:
|
||||
content := new(client.Content)
|
||||
content.Name = metadata.Key
|
||||
content.Time = metadata.LastModified
|
||||
content.Size = metadata.Size
|
||||
content.Type = os.FileMode(0664)
|
||||
contentCh <- client.ContentOnChannel{
|
||||
Content: content,
|
||||
Err: nil,
|
||||
}
|
||||
default:
|
||||
for object := range c.api.ListObjects(b, o, false) {
|
||||
if object.Err != nil {
|
||||
contentCh <- client.ContentOnChannel{
|
||||
Content: nil,
|
||||
Err: probe.NewError(object.Err),
|
||||
}
|
||||
return
|
||||
}
|
||||
content := new(client.Content)
|
||||
normalizedPrefix := strings.TrimSuffix(o, string(c.hostURL.Separator)) + string(c.hostURL.Separator)
|
||||
normalizedKey := object.Stat.Key
|
||||
if normalizedPrefix != object.Stat.Key && strings.HasPrefix(object.Stat.Key, normalizedPrefix) {
|
||||
normalizedKey = strings.TrimPrefix(object.Stat.Key, normalizedPrefix)
|
||||
}
|
||||
content.Name = normalizedKey
|
||||
switch {
|
||||
case strings.HasSuffix(object.Stat.Key, string(c.hostURL.Separator)):
|
||||
content.Time = time.Now()
|
||||
content.Type = os.ModeDir
|
||||
default:
|
||||
content.Size = object.Stat.Size
|
||||
content.Time = object.Stat.LastModified
|
||||
content.Type = os.FileMode(0664)
|
||||
}
|
||||
contentCh <- client.ContentOnChannel{
|
||||
Content: content,
|
||||
Err: nil,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *s3Client) listRecursiveInRoutine(contentCh chan client.ContentOnChannel) {
|
||||
defer close(contentCh)
|
||||
b, o := c.url2BucketAndObject()
|
||||
switch {
|
||||
case b == "" && o == "":
|
||||
for bucket := range c.api.ListBuckets() {
|
||||
if bucket.Err != nil {
|
||||
contentCh <- client.ContentOnChannel{
|
||||
Content: nil,
|
||||
Err: probe.NewError(bucket.Err),
|
||||
}
|
||||
return
|
||||
}
|
||||
for object := range c.api.ListObjects(bucket.Stat.Name, o, true) {
|
||||
if object.Err != nil {
|
||||
contentCh <- client.ContentOnChannel{
|
||||
Content: nil,
|
||||
Err: probe.NewError(object.Err),
|
||||
}
|
||||
return
|
||||
}
|
||||
content := new(client.Content)
|
||||
content.Name = filepath.Join(bucket.Stat.Name, object.Stat.Key)
|
||||
content.Size = object.Stat.Size
|
||||
content.Time = object.Stat.LastModified
|
||||
content.Type = os.FileMode(0664)
|
||||
contentCh <- client.ContentOnChannel{
|
||||
Content: content,
|
||||
Err: nil,
|
||||
}
|
||||
}
|
||||
}
|
||||
default:
|
||||
for object := range c.api.ListObjects(b, o, true) {
|
||||
if object.Err != nil {
|
||||
contentCh <- client.ContentOnChannel{
|
||||
Content: nil,
|
||||
Err: probe.NewError(object.Err),
|
||||
}
|
||||
return
|
||||
}
|
||||
content := new(client.Content)
|
||||
normalizedKey := object.Stat.Key
|
||||
switch {
|
||||
case o == "":
|
||||
// if no prefix provided and also URL is not delimited then we add bucket back into object name
|
||||
if strings.LastIndex(c.hostURL.Path, string(c.hostURL.Separator)) == 0 {
|
||||
if c.hostURL.String()[:strings.LastIndex(c.hostURL.String(), string(c.hostURL.Separator))+1] != b {
|
||||
normalizedKey = filepath.Join(b, object.Stat.Key)
|
||||
}
|
||||
}
|
||||
default:
|
||||
if strings.HasSuffix(o, string(c.hostURL.Separator)) {
|
||||
normalizedKey = strings.TrimPrefix(object.Stat.Key, o)
|
||||
}
|
||||
}
|
||||
content.Name = normalizedKey
|
||||
content.Size = object.Stat.Size
|
||||
content.Time = object.Stat.LastModified
|
||||
content.Type = os.FileMode(0664)
|
||||
contentCh <- client.ContentOnChannel{
|
||||
Content: content,
|
||||
Err: nil,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,378 +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 s3v4
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/minio/mc/pkg/client"
|
||||
"github.com/minio/mc/pkg/httptracer"
|
||||
"github.com/minio/minio-go"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
type s3Client struct {
|
||||
api minio.API
|
||||
hostURL *client.URL
|
||||
}
|
||||
|
||||
// New returns an initialized s3Client structure. if debug use a internal trace transport
|
||||
func New(config *client.Config) (client.Client, *probe.Error) {
|
||||
u := client.NewURL(config.HostURL)
|
||||
transport := http.DefaultTransport
|
||||
if config.Debug == true {
|
||||
transport = httptracer.GetNewTraceTransport(NewTrace(), http.DefaultTransport)
|
||||
}
|
||||
s3Conf := minio.Config{
|
||||
AccessKeyID: config.AccessKeyID,
|
||||
SecretAccessKey: config.SecretAccessKey,
|
||||
Transport: transport,
|
||||
Endpoint: u.Scheme + u.SchemeSeparator + u.Host,
|
||||
}
|
||||
s3Conf.AccessKeyID = config.AccessKeyID
|
||||
s3Conf.SecretAccessKey = config.SecretAccessKey
|
||||
s3Conf.Transport = transport
|
||||
s3Conf.SetUserAgent(config.AppName, config.AppVersion, config.AppComments...)
|
||||
s3Conf.Endpoint = u.Scheme + u.SchemeSeparator + u.Host
|
||||
api, err := minio.New(s3Conf)
|
||||
if err != nil {
|
||||
return nil, probe.NewError(err)
|
||||
}
|
||||
return &s3Client{api: api, hostURL: u}, nil
|
||||
}
|
||||
|
||||
// URL get url
|
||||
func (c *s3Client) URL() *client.URL {
|
||||
return c.hostURL
|
||||
}
|
||||
|
||||
// GetObject - get object
|
||||
func (c *s3Client) GetObject(offset, length int64) (io.ReadCloser, int64, *probe.Error) {
|
||||
bucket, object := c.url2BucketAndObject()
|
||||
reader, metadata, err := c.api.GetPartialObject(bucket, object, offset, length)
|
||||
if err != nil {
|
||||
return nil, length, probe.NewError(err)
|
||||
}
|
||||
return reader, metadata.Size, nil
|
||||
}
|
||||
|
||||
// Share - get a usable get object url to share
|
||||
func (c *s3Client) Share(expires time.Duration) (string, *probe.Error) {
|
||||
bucket, object := c.url2BucketAndObject()
|
||||
presignedURL, err := c.api.PresignedGetObject(bucket, object, expires)
|
||||
if err != nil {
|
||||
return "", probe.NewError(err)
|
||||
}
|
||||
return presignedURL, nil
|
||||
}
|
||||
|
||||
// PutObject - put object
|
||||
func (c *s3Client) PutObject(size int64, data io.Reader) *probe.Error {
|
||||
// md5 is purposefully ignored since AmazonS3 does not return proper md5sum
|
||||
// for a multipart upload and there is no need to cross verify,
|
||||
// invidual parts are properly verified
|
||||
bucket, object := c.url2BucketAndObject()
|
||||
err := c.api.PutObject(bucket, object, "application/octet-stream", size, data)
|
||||
if err != nil {
|
||||
errResponse := minio.ToErrorResponse(err)
|
||||
if errResponse != nil {
|
||||
if errResponse.Code == "MethodNotAllowed" {
|
||||
return probe.NewError(client.ObjectAlreadyExists{Object: object})
|
||||
}
|
||||
}
|
||||
return probe.NewError(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// MakeBucket - make a new bucket
|
||||
func (c *s3Client) MakeBucket() *probe.Error {
|
||||
bucket, object := c.url2BucketAndObject()
|
||||
if object != "" {
|
||||
return probe.NewError(client.InvalidQueryURL{URL: c.hostURL.String()})
|
||||
}
|
||||
if bucket == "" {
|
||||
return probe.NewError(errors.New("Bucket name is empty."))
|
||||
}
|
||||
|
||||
err := c.api.MakeBucket(bucket, minio.BucketACL("private"))
|
||||
if err != nil {
|
||||
return probe.NewError(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetBucketACL get canned acl's on a bucket
|
||||
func (c *s3Client) GetBucketACL() (acl string, error *probe.Error) {
|
||||
bucket, object := c.url2BucketAndObject()
|
||||
if object != "" {
|
||||
return "", probe.NewError(client.InvalidQueryURL{URL: c.hostURL.String()})
|
||||
}
|
||||
bucketACL, err := c.api.GetBucketACL(bucket)
|
||||
if err != nil {
|
||||
return "", probe.NewError(err)
|
||||
}
|
||||
return bucketACL.String(), nil
|
||||
}
|
||||
|
||||
// SetBucketACL add canned acl's on a bucket
|
||||
func (c *s3Client) SetBucketACL(acl string) *probe.Error {
|
||||
bucket, object := c.url2BucketAndObject()
|
||||
if object != "" {
|
||||
return probe.NewError(client.InvalidQueryURL{URL: c.hostURL.String()})
|
||||
}
|
||||
err := c.api.SetBucketACL(bucket, minio.BucketACL(acl))
|
||||
if err != nil {
|
||||
return probe.NewError(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Stat - send a 'HEAD' on a bucket or object to get its metadata
|
||||
func (c *s3Client) Stat() (*client.Content, *probe.Error) {
|
||||
objectMetadata := new(client.Content)
|
||||
bucket, object := c.url2BucketAndObject()
|
||||
switch {
|
||||
// valid case for s3/...
|
||||
case bucket == "" && object == "":
|
||||
for bucket := range c.api.ListBuckets() {
|
||||
if bucket.Err != nil {
|
||||
return nil, probe.NewError(bucket.Err)
|
||||
}
|
||||
}
|
||||
return &client.Content{Type: os.ModeDir}, nil
|
||||
}
|
||||
if object != "" {
|
||||
metadata, err := c.api.StatObject(bucket, object)
|
||||
if err != nil {
|
||||
errResponse := minio.ToErrorResponse(err)
|
||||
if errResponse != nil {
|
||||
if errResponse.Code == "NoSuchKey" {
|
||||
for content := range c.List(false) {
|
||||
if content.Err != nil {
|
||||
return nil, content.Err.Trace()
|
||||
}
|
||||
content.Content.Type = os.ModeDir
|
||||
content.Content.Name = object
|
||||
content.Content.Size = 0
|
||||
return content.Content, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil, probe.NewError(err)
|
||||
}
|
||||
objectMetadata.Name = metadata.Key
|
||||
objectMetadata.Time = metadata.LastModified
|
||||
objectMetadata.Size = metadata.Size
|
||||
objectMetadata.Type = os.FileMode(0664)
|
||||
return objectMetadata, nil
|
||||
}
|
||||
err := c.api.BucketExists(bucket)
|
||||
if err != nil {
|
||||
return nil, probe.NewError(err)
|
||||
}
|
||||
bucketMetadata := new(client.Content)
|
||||
bucketMetadata.Name = bucket
|
||||
bucketMetadata.Type = os.ModeDir
|
||||
return bucketMetadata, nil
|
||||
}
|
||||
|
||||
// url2BucketAndObject gives bucketName and objectName from URL path
|
||||
func (c *s3Client) url2BucketAndObject() (bucketName, objectName string) {
|
||||
path := c.hostURL.Path
|
||||
// Convert any virtual host styled requests
|
||||
//
|
||||
// For the time being this check is introduced for S3,
|
||||
// if you have custom virtual styled hosts please. list them below
|
||||
match, _ := filepath.Match("*.s3*.amazonaws.com", c.hostURL.Host)
|
||||
switch {
|
||||
case match == true:
|
||||
hostSplits := strings.SplitN(c.hostURL.Host, ".", 2)
|
||||
path = string(c.hostURL.Separator) + hostSplits[0] + c.hostURL.Path
|
||||
}
|
||||
splits := strings.SplitN(path, string(c.hostURL.Separator), 3)
|
||||
switch len(splits) {
|
||||
case 0, 1:
|
||||
bucketName = ""
|
||||
objectName = ""
|
||||
case 2:
|
||||
bucketName = splits[1]
|
||||
objectName = ""
|
||||
case 3:
|
||||
bucketName = splits[1]
|
||||
objectName = splits[2]
|
||||
}
|
||||
return bucketName, objectName
|
||||
}
|
||||
|
||||
/// Bucket API operations
|
||||
|
||||
// List - list at delimited path, if not recursive
|
||||
func (c *s3Client) List(recursive bool) <-chan client.ContentOnChannel {
|
||||
contentCh := make(chan client.ContentOnChannel)
|
||||
switch recursive {
|
||||
case true:
|
||||
go c.listRecursiveInRoutine(contentCh)
|
||||
default:
|
||||
go c.listInRoutine(contentCh)
|
||||
}
|
||||
return contentCh
|
||||
}
|
||||
|
||||
func (c *s3Client) listInRoutine(contentCh chan client.ContentOnChannel) {
|
||||
defer close(contentCh)
|
||||
b, o := c.url2BucketAndObject()
|
||||
switch {
|
||||
case b == "" && o == "":
|
||||
for bucket := range c.api.ListBuckets() {
|
||||
if bucket.Err != nil {
|
||||
contentCh <- client.ContentOnChannel{
|
||||
Content: nil,
|
||||
Err: probe.NewError(bucket.Err),
|
||||
}
|
||||
return
|
||||
}
|
||||
content := new(client.Content)
|
||||
content.Name = bucket.Stat.Name
|
||||
content.Size = 0
|
||||
content.Time = bucket.Stat.CreationDate
|
||||
content.Type = os.ModeDir
|
||||
contentCh <- client.ContentOnChannel{
|
||||
Content: content,
|
||||
Err: nil,
|
||||
}
|
||||
}
|
||||
default:
|
||||
metadata, err := c.api.StatObject(b, o)
|
||||
switch err.(type) {
|
||||
case nil:
|
||||
content := new(client.Content)
|
||||
content.Name = metadata.Key
|
||||
content.Time = metadata.LastModified
|
||||
content.Size = metadata.Size
|
||||
content.Type = os.FileMode(0664)
|
||||
contentCh <- client.ContentOnChannel{
|
||||
Content: content,
|
||||
Err: nil,
|
||||
}
|
||||
default:
|
||||
for object := range c.api.ListObjects(b, o, false) {
|
||||
if object.Err != nil {
|
||||
contentCh <- client.ContentOnChannel{
|
||||
Content: nil,
|
||||
Err: probe.NewError(object.Err),
|
||||
}
|
||||
return
|
||||
}
|
||||
content := new(client.Content)
|
||||
normalizedPrefix := strings.TrimSuffix(o, string(c.hostURL.Separator)) + string(c.hostURL.Separator)
|
||||
normalizedKey := object.Stat.Key
|
||||
if normalizedPrefix != object.Stat.Key && strings.HasPrefix(object.Stat.Key, normalizedPrefix) {
|
||||
normalizedKey = strings.TrimPrefix(object.Stat.Key, normalizedPrefix)
|
||||
}
|
||||
content.Name = normalizedKey
|
||||
switch {
|
||||
case strings.HasSuffix(object.Stat.Key, string(c.hostURL.Separator)):
|
||||
content.Time = time.Now()
|
||||
content.Type = os.ModeDir
|
||||
default:
|
||||
content.Size = object.Stat.Size
|
||||
content.Time = object.Stat.LastModified
|
||||
content.Type = os.FileMode(0664)
|
||||
}
|
||||
contentCh <- client.ContentOnChannel{
|
||||
Content: content,
|
||||
Err: nil,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *s3Client) listRecursiveInRoutine(contentCh chan client.ContentOnChannel) {
|
||||
defer close(contentCh)
|
||||
b, o := c.url2BucketAndObject()
|
||||
switch {
|
||||
case b == "" && o == "":
|
||||
for bucket := range c.api.ListBuckets() {
|
||||
if bucket.Err != nil {
|
||||
contentCh <- client.ContentOnChannel{
|
||||
Content: nil,
|
||||
Err: probe.NewError(bucket.Err),
|
||||
}
|
||||
return
|
||||
}
|
||||
for object := range c.api.ListObjects(bucket.Stat.Name, o, true) {
|
||||
if object.Err != nil {
|
||||
contentCh <- client.ContentOnChannel{
|
||||
Content: nil,
|
||||
Err: probe.NewError(object.Err),
|
||||
}
|
||||
return
|
||||
}
|
||||
content := new(client.Content)
|
||||
content.Name = filepath.Join(bucket.Stat.Name, object.Stat.Key)
|
||||
content.Size = object.Stat.Size
|
||||
content.Time = object.Stat.LastModified
|
||||
content.Type = os.FileMode(0664)
|
||||
contentCh <- client.ContentOnChannel{
|
||||
Content: content,
|
||||
Err: nil,
|
||||
}
|
||||
}
|
||||
}
|
||||
default:
|
||||
for object := range c.api.ListObjects(b, o, true) {
|
||||
if object.Err != nil {
|
||||
contentCh <- client.ContentOnChannel{
|
||||
Content: nil,
|
||||
Err: probe.NewError(object.Err),
|
||||
}
|
||||
return
|
||||
}
|
||||
content := new(client.Content)
|
||||
normalizedKey := object.Stat.Key
|
||||
switch {
|
||||
case o == "":
|
||||
// if no prefix provided and also URL is not delimited then we add bucket back into object name
|
||||
if strings.LastIndex(c.hostURL.Path, string(c.hostURL.Separator)) == 0 {
|
||||
if c.hostURL.String()[:strings.LastIndex(c.hostURL.String(), string(c.hostURL.Separator))+1] != b {
|
||||
normalizedKey = filepath.Join(b, object.Stat.Key)
|
||||
}
|
||||
}
|
||||
default:
|
||||
if strings.HasSuffix(o, string(c.hostURL.Separator)) {
|
||||
normalizedKey = strings.TrimPrefix(object.Stat.Key, o)
|
||||
}
|
||||
}
|
||||
content.Name = normalizedKey
|
||||
content.Size = object.Stat.Size
|
||||
content.Time = object.Stat.LastModified
|
||||
content.Type = os.FileMode(0664)
|
||||
contentCh <- client.ContentOnChannel{
|
||||
Content: content,
|
||||
Err: nil,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,198 +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 s3v4
|
||||
|
||||
// bucketHandler is an http.Handler that verifies bucket responses and validates incoming requests
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/minio/mc/pkg/client"
|
||||
|
||||
. "gopkg.in/check.v1"
|
||||
)
|
||||
|
||||
type bucketHandler struct {
|
||||
resource string
|
||||
}
|
||||
|
||||
func (h bucketHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case r.Method == "GET":
|
||||
switch {
|
||||
case r.URL.Path == "/":
|
||||
response := []byte("<ListAllMyBucketsResult xmlns=\"http://doc.s3.amazonaws.com/2006-03-01\"><Buckets><Bucket><Name>bucket</Name><CreationDate>2015-05-20T23:05:09.230Z</CreationDate></Bucket></Buckets><Owner><ID>minio</ID><DisplayName>minio</DisplayName></Owner></ListAllMyBucketsResult>")
|
||||
w.Header().Set("Content-Length", strconv.Itoa(len(response)))
|
||||
w.Write(response)
|
||||
case r.URL.Path == "/bucket":
|
||||
response := []byte("<ListBucketResult xmlns=\"http://doc.s3.amazonaws.com/2006-03-01\"><Contents><ETag>259d04a13802ae09c7e41be50ccc6baa</ETag><Key>object</Key><LastModified>2015-05-21T18:24:21.097Z</LastModified><Size>22061</Size><Owner><ID>minio</ID><DisplayName>minio</DisplayName></Owner><StorageClass>STANDARD</StorageClass></Contents><Delimiter></Delimiter><EncodingType></EncodingType><IsTruncated>false</IsTruncated><Marker></Marker><MaxKeys>1000</MaxKeys><Name>testbucket</Name><NextMarker></NextMarker><Prefix></Prefix></ListBucketResult>")
|
||||
w.Header().Set("Content-Length", strconv.Itoa(len(response)))
|
||||
w.Write(response)
|
||||
}
|
||||
case r.Method == "PUT":
|
||||
switch {
|
||||
case r.URL.Path == h.resource:
|
||||
_, ok := r.URL.Query()["acl"]
|
||||
if ok {
|
||||
if r.Header.Get("x-amz-acl") != "public-read-write" {
|
||||
w.WriteHeader(http.StatusNotImplemented)
|
||||
}
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
default:
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
}
|
||||
case r.Method == "HEAD":
|
||||
switch {
|
||||
case r.URL.Path == h.resource:
|
||||
w.WriteHeader(http.StatusOK)
|
||||
default:
|
||||
w.WriteHeader(http.StatusForbidden)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// objectHandler is an http.Handler that verifies object responses and validates incoming requests
|
||||
type objectHandler struct {
|
||||
resource string
|
||||
data []byte
|
||||
}
|
||||
|
||||
func (h objectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case r.Method == "PUT":
|
||||
length, err := strconv.Atoi(r.Header.Get("Content-Length"))
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
var buffer bytes.Buffer
|
||||
_, err = io.CopyN(&buffer, r.Body, int64(length))
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
if !bytes.Equal(h.data, buffer.Bytes()) {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.Header().Set("ETag", "9af2f8218b150c351ad802c6f3d66abe")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
case r.Method == "HEAD":
|
||||
if r.URL.Path != h.resource {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Length", strconv.Itoa(len(h.data)))
|
||||
w.Header().Set("Last-Modified", time.Now().UTC().Format(http.TimeFormat))
|
||||
w.Header().Set("ETag", "9af2f8218b150c351ad802c6f3d66abe")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
case r.Method == "GET":
|
||||
if r.URL.Path != h.resource {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Length", strconv.Itoa(len(h.data)))
|
||||
w.Header().Set("Last-Modified", time.Now().UTC().Format(http.TimeFormat))
|
||||
w.Header().Set("ETag", "9af2f8218b150c351ad802c6f3d66abe")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
io.Copy(w, bytes.NewReader(h.data))
|
||||
}
|
||||
}
|
||||
|
||||
func Test(t *testing.T) { TestingT(t) }
|
||||
|
||||
type MySuite struct{}
|
||||
|
||||
var _ = Suite(&MySuite{})
|
||||
|
||||
func (s *MySuite) TestBucketOperations(c *C) {
|
||||
bucket := bucketHandler(bucketHandler{
|
||||
resource: "/bucket",
|
||||
})
|
||||
server := httptest.NewServer(bucket)
|
||||
defer server.Close()
|
||||
|
||||
conf := new(client.Config)
|
||||
conf.HostURL = server.URL + bucket.resource
|
||||
s3c, err := New(conf)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
err = s3c.MakeBucket()
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
err = s3c.SetBucketACL("public-read-write")
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
conf.HostURL = server.URL + string(s3c.URL().Separator)
|
||||
s3c, err = New(conf)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
for content := range s3c.List(false) {
|
||||
c.Assert(content.Err, IsNil)
|
||||
c.Assert(content.Content.Name, Equals, "bucket")
|
||||
c.Assert(content.Content.Type.IsDir(), Equals, true)
|
||||
}
|
||||
|
||||
conf.HostURL = server.URL + "/bucket"
|
||||
s3c, err = New(conf)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
for content := range s3c.List(false) {
|
||||
c.Assert(content.Err, IsNil)
|
||||
c.Assert(content.Content.Name, Equals, "object")
|
||||
c.Assert(content.Content.Type.IsRegular(), Equals, true)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *MySuite) TestObjectOperations(c *C) {
|
||||
object := objectHandler(objectHandler{
|
||||
resource: "/bucket/object",
|
||||
data: []byte("Hello, World"),
|
||||
})
|
||||
server := httptest.NewServer(object)
|
||||
defer server.Close()
|
||||
|
||||
conf := new(client.Config)
|
||||
conf.HostURL = server.URL + object.resource
|
||||
s3c, err := New(conf)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
err = s3c.PutObject(int64(len(object.data)), bytes.NewReader(object.data))
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
content, err := s3c.Stat()
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(content.Name, Equals, "object")
|
||||
c.Assert(content.Size, Equals, int64(len(object.data)))
|
||||
c.Assert(content.Type.IsRegular(), Equals, true)
|
||||
|
||||
reader, size, err := s3c.GetObject(0, 0)
|
||||
c.Assert(size, Equals, int64(len(object.data)))
|
||||
|
||||
var buffer bytes.Buffer
|
||||
{
|
||||
_, err := io.CopyN(&buffer, reader, int64(size))
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(buffer.Bytes(), DeepEquals, object.data)
|
||||
}
|
||||
}
|
||||
+14
-1
@@ -117,8 +117,21 @@ func NewURL(urlStr string) *URL {
|
||||
}
|
||||
}
|
||||
|
||||
// JoinURLs join two input urls and returns a url
|
||||
func JoinURLs(url1, url2 *URL) *URL {
|
||||
var url1Path, url2Path string
|
||||
url1Path = filepath.ToSlash(url1.Path)
|
||||
url2Path = filepath.ToSlash(url2.Path)
|
||||
if strings.HasSuffix(url1Path, "/") {
|
||||
url1.Path = url1Path + strings.TrimPrefix(url2Path, "/")
|
||||
} else {
|
||||
url1.Path = url1Path + "/" + strings.TrimPrefix(url2Path, "/")
|
||||
}
|
||||
return url1
|
||||
}
|
||||
|
||||
// String convert URL into its canonical form.
|
||||
func (u *URL) String() string {
|
||||
func (u URL) String() string {
|
||||
var buf bytes.Buffer
|
||||
// if fileystem no translation needed, return as is.
|
||||
if u.Type == Filesystem {
|
||||
|
||||
+74
-97
@@ -25,33 +25,13 @@ import (
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/mattn/go-isatty"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
"github.com/shiena/ansicolor"
|
||||
)
|
||||
|
||||
// NoDebugPrint defines if the input should be printed in debug or not. By default it's set to true.
|
||||
var NoDebugPrint = true
|
||||
|
||||
// IsTesting this flag indicates if IsExited should be set or not, false by default
|
||||
var IsTesting = false
|
||||
|
||||
// IsExited sets this boolean value if Fatal is called when IsTesting is enabled
|
||||
var IsExited = false
|
||||
|
||||
// IsError sets this boolean value if Error is called when IsTesting is enabled
|
||||
var IsError = false
|
||||
|
||||
// Theme default map
|
||||
var Theme = map[string]*color.Color{
|
||||
"Debug": color.New(color.FgWhite, color.Faint, color.Italic),
|
||||
"Fatal": color.New(color.FgRed, color.Italic, color.Bold),
|
||||
"Error": color.New(color.FgYellow, color.Italic),
|
||||
"Info": color.New(color.FgGreen, color.Bold),
|
||||
"Print": color.New(),
|
||||
"PrintC": color.New(color.FgGreen, color.Bold),
|
||||
}
|
||||
|
||||
var (
|
||||
// DebugPrint enables/disables console debug printing.
|
||||
DebugPrint = false
|
||||
|
||||
// Used by the caller to print multiple lines atomically. Exposed by Lock/Unlock methods.
|
||||
publicMutex = &sync.Mutex{}
|
||||
// Used internally by console.
|
||||
@@ -59,156 +39,139 @@ var (
|
||||
|
||||
stderrColoredOutput = ansicolor.NewAnsiColorWriter(os.Stderr)
|
||||
|
||||
// Print prints a message
|
||||
// Print prints a message.
|
||||
Print = func(data ...interface{}) {
|
||||
consolePrint("Print", Theme["Print"], data...)
|
||||
return
|
||||
}
|
||||
|
||||
// PrintC prints a message with color
|
||||
// PrintC prints a message with color.
|
||||
PrintC = func(data ...interface{}) {
|
||||
consolePrint("PrintC", Theme["PrintC"], data...)
|
||||
return
|
||||
}
|
||||
|
||||
// Printf prints a formatted message
|
||||
// Printf prints a formatted message.
|
||||
Printf = func(format string, data ...interface{}) {
|
||||
consolePrintf("Print", Theme["Print"], format, data...)
|
||||
return
|
||||
}
|
||||
|
||||
// Println prints a message with a newline
|
||||
// Println prints a message with a newline.
|
||||
Println = func(data ...interface{}) {
|
||||
consolePrintln("Print", Theme["Print"], data...)
|
||||
return
|
||||
}
|
||||
|
||||
// fatalQuitRoutine called after fatal message printing
|
||||
// by the user specific version
|
||||
fatalQuitRoutine = func() {
|
||||
if !IsTesting {
|
||||
os.Exit(1)
|
||||
}
|
||||
defer func() {
|
||||
IsExited = true
|
||||
}()
|
||||
}
|
||||
|
||||
// Fatal print a error message and exit
|
||||
// Fatal print a error message and exit.
|
||||
Fatal = func(data ...interface{}) {
|
||||
consolePrint("Fatal", Theme["Fatal"], data...)
|
||||
fatalQuitRoutine()
|
||||
os.Exit(1)
|
||||
return
|
||||
}
|
||||
|
||||
// Fatalf print a error message with a format specified and exit
|
||||
// Fatalf print a error message with a format specified and exit.
|
||||
Fatalf = func(format string, data ...interface{}) {
|
||||
consolePrintf("Fatal", Theme["Fatal"], format, data...)
|
||||
fatalQuitRoutine()
|
||||
os.Exit(1)
|
||||
return
|
||||
}
|
||||
|
||||
// Fatalln print a error message with a new line and exit
|
||||
// Fatalln print a error message with a new line and exit.
|
||||
Fatalln = func(data ...interface{}) {
|
||||
consolePrintln("Fatal", Theme["Fatal"], data...)
|
||||
fatalQuitRoutine()
|
||||
os.Exit(1)
|
||||
return
|
||||
}
|
||||
|
||||
// errorQuitRoutine called after error message printing
|
||||
// by the user specific version
|
||||
errorQuitRoutine = func() {
|
||||
if IsTesting {
|
||||
defer func() {
|
||||
IsError = true
|
||||
}()
|
||||
}
|
||||
}
|
||||
|
||||
// Error prints a error message
|
||||
// Error prints a error message.
|
||||
Error = func(data ...interface{}) {
|
||||
consolePrint("Error", Theme["Error"], data...)
|
||||
errorQuitRoutine()
|
||||
return
|
||||
}
|
||||
|
||||
// Errorf print a error message with a format specified
|
||||
// Errorf print a error message with a format specified.
|
||||
Errorf = func(format string, data ...interface{}) {
|
||||
consolePrintf("Error", Theme["Error"], format, data...)
|
||||
errorQuitRoutine()
|
||||
return
|
||||
}
|
||||
|
||||
// Errorln prints a error message with a new line
|
||||
// Errorln prints a error message with a new line.
|
||||
Errorln = func(data ...interface{}) {
|
||||
consolePrintln("Error", Theme["Error"], data...)
|
||||
errorQuitRoutine()
|
||||
return
|
||||
}
|
||||
|
||||
// Info prints a informational message
|
||||
// Info prints a informational message.
|
||||
Info = func(data ...interface{}) {
|
||||
consolePrint("Info", Theme["Info"], data...)
|
||||
return
|
||||
}
|
||||
|
||||
// Infof prints a informational message in custom format
|
||||
// Infof prints a informational message in custom format.
|
||||
Infof = func(format string, data ...interface{}) {
|
||||
consolePrintf("Info", Theme["Info"], format, data...)
|
||||
return
|
||||
}
|
||||
|
||||
// Infoln prints a informational message with a new line
|
||||
// Infoln prints a informational message with a new line.
|
||||
Infoln = func(data ...interface{}) {
|
||||
consolePrintln("Info", Theme["Info"], data...)
|
||||
return
|
||||
}
|
||||
|
||||
// Debug prints a debug message without a new line
|
||||
// Debug prints a debug message
|
||||
// Debug prints a debug message.
|
||||
Debug = func(data ...interface{}) {
|
||||
if !NoDebugPrint {
|
||||
if DebugPrint {
|
||||
consolePrint("Debug", Theme["Debug"], data...)
|
||||
}
|
||||
}
|
||||
|
||||
// Debugf prints a debug message with a new line
|
||||
// Debugf prints a debug message with a new line.
|
||||
Debugf = func(format string, data ...interface{}) {
|
||||
if !NoDebugPrint {
|
||||
if DebugPrint {
|
||||
consolePrintf("Debug", Theme["Debug"], format, data...)
|
||||
}
|
||||
}
|
||||
|
||||
// Debugln prints a debug message with a new line
|
||||
// Debugln prints a debug message with a new line.
|
||||
Debugln = func(data ...interface{}) {
|
||||
if !NoDebugPrint {
|
||||
if DebugPrint {
|
||||
consolePrintln("Debug", Theme["Debug"], data...)
|
||||
}
|
||||
}
|
||||
|
||||
// Colorize prints message in a colorized form, dictated by the corresponding tag argument
|
||||
// Colorize prints message in a colorized form, dictated by the corresponding tag argument.
|
||||
Colorize = func(tag string, data interface{}) string {
|
||||
if isatty.IsTerminal(os.Stdout.Fd()) {
|
||||
return Theme[tag].SprintFunc()(data)
|
||||
colorized, ok := Theme[tag]
|
||||
if ok {
|
||||
return colorized.SprintFunc()(data)
|
||||
} // else: No theme found. Return as string.
|
||||
}
|
||||
return fmt.Sprint(data)
|
||||
}
|
||||
|
||||
// Eraseline Print in new line and adjust to top so that we don't print over the ongoing progress bar
|
||||
// Eraseline Print in new line and adjust to top so that we don't print over the ongoing progress bar.
|
||||
Eraseline = func() {
|
||||
consolePrintf("Print", Theme["Print"], "%c[2K\n", 27)
|
||||
consolePrintf("Print", Theme["Print"], "%c[A", 27)
|
||||
}
|
||||
)
|
||||
|
||||
// wrap around standard fmt functions
|
||||
// consolePrint prints a message prefixed with message type and program name
|
||||
// wrap around standard fmt functions.
|
||||
// consolePrint prints a message prefixed with message type and program name.
|
||||
func consolePrint(tag string, c *color.Color, a ...interface{}) {
|
||||
privateMutex.Lock()
|
||||
defer privateMutex.Unlock()
|
||||
|
||||
switch tag {
|
||||
case "Debug":
|
||||
// if no arguments are given do not invoke debug printer.
|
||||
if len(a) == 0 {
|
||||
return
|
||||
}
|
||||
output := color.Output
|
||||
color.Output = stderrColoredOutput
|
||||
if isatty.IsTerminal(os.Stderr.Fd()) {
|
||||
@@ -222,6 +185,10 @@ func consolePrint(tag string, c *color.Color, a ...interface{}) {
|
||||
case "Fatal":
|
||||
fallthrough
|
||||
case "Error":
|
||||
// if no arguments are given do not invoke fatal and error printer.
|
||||
if len(a) == 0 {
|
||||
return
|
||||
}
|
||||
output := color.Output
|
||||
color.Output = stderrColoredOutput
|
||||
if isatty.IsTerminal(os.Stderr.Fd()) {
|
||||
@@ -233,6 +200,10 @@ func consolePrint(tag string, c *color.Color, a ...interface{}) {
|
||||
}
|
||||
color.Output = output
|
||||
case "Info":
|
||||
// if no arguments are given do not invoke info printer.
|
||||
if len(a) == 0 {
|
||||
return
|
||||
}
|
||||
if isatty.IsTerminal(os.Stdout.Fd()) {
|
||||
c.Print(ProgramName() + ": ")
|
||||
c.Print(a...)
|
||||
@@ -249,13 +220,17 @@ func consolePrint(tag string, c *color.Color, a ...interface{}) {
|
||||
}
|
||||
}
|
||||
|
||||
// consolePrintf - same as print with a new line
|
||||
// consolePrintf - same as print with a new line.
|
||||
func consolePrintf(tag string, c *color.Color, format string, a ...interface{}) {
|
||||
privateMutex.Lock()
|
||||
defer privateMutex.Unlock()
|
||||
|
||||
switch tag {
|
||||
case "Debug":
|
||||
// if no arguments are given do not invoke debug printer.
|
||||
if len(a) == 0 {
|
||||
return
|
||||
}
|
||||
output := color.Output
|
||||
color.Output = stderrColoredOutput
|
||||
if isatty.IsTerminal(os.Stderr.Fd()) {
|
||||
@@ -269,6 +244,10 @@ func consolePrintf(tag string, c *color.Color, format string, a ...interface{})
|
||||
case "Fatal":
|
||||
fallthrough
|
||||
case "Error":
|
||||
// if no arguments are given do not invoke fatal and error printer.
|
||||
if len(a) == 0 {
|
||||
return
|
||||
}
|
||||
output := color.Output
|
||||
color.Output = stderrColoredOutput
|
||||
if isatty.IsTerminal(os.Stderr.Fd()) {
|
||||
@@ -280,6 +259,10 @@ func consolePrintf(tag string, c *color.Color, format string, a ...interface{})
|
||||
}
|
||||
color.Output = output
|
||||
case "Info":
|
||||
// if no arguments are given do not invoke info printer.
|
||||
if len(a) == 0 {
|
||||
return
|
||||
}
|
||||
if isatty.IsTerminal(os.Stdout.Fd()) {
|
||||
c.Print(ProgramName() + ": ")
|
||||
c.Printf(format, a...)
|
||||
@@ -296,13 +279,17 @@ func consolePrintf(tag string, c *color.Color, format string, a ...interface{})
|
||||
}
|
||||
}
|
||||
|
||||
// consolePrintln - same as print with a new line
|
||||
// consolePrintln - same as print with a new line.
|
||||
func consolePrintln(tag string, c *color.Color, a ...interface{}) {
|
||||
privateMutex.Lock()
|
||||
defer privateMutex.Unlock()
|
||||
|
||||
switch tag {
|
||||
case "Debug":
|
||||
// if no arguments are given do not invoke debug printer.
|
||||
if len(a) == 0 {
|
||||
return
|
||||
}
|
||||
output := color.Output
|
||||
color.Output = stderrColoredOutput
|
||||
if isatty.IsTerminal(os.Stderr.Fd()) {
|
||||
@@ -316,6 +303,10 @@ func consolePrintln(tag string, c *color.Color, a ...interface{}) {
|
||||
case "Fatal":
|
||||
fallthrough
|
||||
case "Error":
|
||||
// if no arguments are given do not invoke fatal and error printer.
|
||||
if len(a) == 0 {
|
||||
return
|
||||
}
|
||||
output := color.Output
|
||||
color.Output = stderrColoredOutput
|
||||
if isatty.IsTerminal(os.Stderr.Fd()) {
|
||||
@@ -327,6 +318,10 @@ func consolePrintln(tag string, c *color.Color, a ...interface{}) {
|
||||
}
|
||||
color.Output = output
|
||||
case "Info":
|
||||
// if no arguments are given do not invoke info printer.
|
||||
if len(a) == 0 {
|
||||
return
|
||||
}
|
||||
if isatty.IsTerminal(os.Stdout.Fd()) {
|
||||
c.Print(ProgramName() + ": ")
|
||||
c.Println(a...)
|
||||
@@ -343,36 +338,18 @@ func consolePrintln(tag string, c *color.Color, a ...interface{}) {
|
||||
}
|
||||
}
|
||||
|
||||
// Lock console
|
||||
// Lock console.
|
||||
func Lock() {
|
||||
publicMutex.Lock()
|
||||
}
|
||||
|
||||
// Unlock locked console
|
||||
// Unlock locked console.
|
||||
func Unlock() {
|
||||
publicMutex.Unlock()
|
||||
}
|
||||
|
||||
// SetCustomTheme sets a color theme
|
||||
func SetCustomTheme(theme map[string]*color.Color) *probe.Error {
|
||||
privateMutex.Lock()
|
||||
defer privateMutex.Unlock()
|
||||
// add new theme
|
||||
for k, v := range theme {
|
||||
Theme[k] = v
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ProgramName - return the name of the executable program
|
||||
// ProgramName - return the name of the executable program.
|
||||
func ProgramName() string {
|
||||
_, progName := filepath.Split(os.Args[0])
|
||||
return progName
|
||||
}
|
||||
|
||||
// SetNoColor disable coloring
|
||||
func SetNoColor() {
|
||||
privateMutex.Lock()
|
||||
defer privateMutex.Unlock()
|
||||
color.NoColor = true
|
||||
}
|
||||
|
||||
@@ -29,9 +29,8 @@ type MySuite struct{}
|
||||
|
||||
var _ = Suite(&MySuite{})
|
||||
|
||||
func (s *MySuite) TestSetTheme(c *C) {
|
||||
err := SetCustomTheme(map[string]*color.Color{"unknown": new(color.Color)})
|
||||
c.Assert(err, IsNil)
|
||||
func (s *MySuite) TestSetColor(c *C) {
|
||||
SetColor("unknown", color.New(color.FgWhite))
|
||||
_, ok := Theme["unknown"]
|
||||
c.Assert(ok, Equals, true)
|
||||
}
|
||||
@@ -41,12 +40,3 @@ func (s *MySuite) TestLock(c *C) {
|
||||
Print("") // Test for deadlocks.
|
||||
Unlock()
|
||||
}
|
||||
|
||||
func (s *MySuite) TestTesting(c *C) {
|
||||
// Enable testing
|
||||
IsTesting = true
|
||||
Fatalln("THIS IS A TEST MESSAGE. PLEASE INGORE.")
|
||||
c.Assert(IsExited, Equals, true)
|
||||
// reset back
|
||||
IsExited = false
|
||||
}
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
/*
|
||||
* Minio Client (C) 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package console
|
||||
|
||||
import "github.com/fatih/color"
|
||||
|
||||
var (
|
||||
// Theme contains default color mapping.
|
||||
Theme = map[string]*color.Color{
|
||||
"Debug": color.New(color.FgWhite, color.Faint, color.Italic),
|
||||
"Fatal": color.New(color.FgRed, color.Italic, color.Bold),
|
||||
"Error": color.New(color.FgYellow, color.Italic),
|
||||
"Info": color.New(color.FgGreen, color.Bold),
|
||||
"Print": color.New(),
|
||||
"PrintC": color.New(color.FgGreen, color.Bold),
|
||||
}
|
||||
)
|
||||
|
||||
// SetColorOff disables coloring for the entire session.
|
||||
func SetColorOff() {
|
||||
privateMutex.Lock()
|
||||
defer privateMutex.Unlock()
|
||||
color.NoColor = true
|
||||
}
|
||||
|
||||
// SetColorOn enables coloring for the entire session.
|
||||
func SetColorOn() {
|
||||
privateMutex.Lock()
|
||||
defer privateMutex.Unlock()
|
||||
color.NoColor = false
|
||||
}
|
||||
|
||||
// SetColor sets a color for a particular tag.
|
||||
func SetColor(tag string, cl *color.Color) {
|
||||
privateMutex.Lock()
|
||||
defer privateMutex.Unlock()
|
||||
// add new theme
|
||||
Theme[tag] = cl
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
/*
|
||||
* Minio Client (C) 2016 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
// Package hookreader hooks additional reader in the source
|
||||
// stream. It is useful for making progress bars. Second reader is
|
||||
// appropriately notified about the exact number of bytes read from
|
||||
// the primary source on each Read operation.
|
||||
package hookreader
|
||||
|
||||
import "io"
|
||||
|
||||
type hookReader struct {
|
||||
source io.Reader
|
||||
hook io.Reader
|
||||
}
|
||||
|
||||
// Read implements io.Reader. Always reads from the source, the return
|
||||
// value 'n' number of bytes are reported through the hook. Returns
|
||||
// error for all non io.EOF conditions.
|
||||
func (hr *hookReader) Read(b []byte) (n int, err error) {
|
||||
n, err = hr.source.Read(b)
|
||||
if err != nil && err != io.EOF {
|
||||
return n, err
|
||||
}
|
||||
// Progress the hook with the total read bytes from the source.
|
||||
if _, herr := hr.hook.Read(b[:n]); herr != nil {
|
||||
if herr != io.EOF {
|
||||
return n, herr
|
||||
}
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
|
||||
// NewHook returns a io.Reader which implements hookReader that
|
||||
// reports the data read from the source to the hook.
|
||||
func NewHook(source, hook io.Reader) io.Reader {
|
||||
if hook == nil {
|
||||
return source
|
||||
}
|
||||
return &hookReader{source, hook}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
/*
|
||||
* Minio Client (C) 2016 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package hookreader
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"testing"
|
||||
|
||||
. "gopkg.in/check.v1"
|
||||
)
|
||||
|
||||
func Test(t *testing.T) { TestingT(t) }
|
||||
|
||||
type MySuite struct{}
|
||||
|
||||
var _ = Suite(&MySuite{})
|
||||
|
||||
// customReader - implements custom progress reader.
|
||||
type customReader struct {
|
||||
readBytes int
|
||||
}
|
||||
|
||||
func (c *customReader) Read(b []byte) (n int, err error) {
|
||||
c.readBytes += len(b)
|
||||
return len(b), nil
|
||||
}
|
||||
|
||||
// Tests hook reader implementation.
|
||||
func (s *MySuite) TestHookReader(c *C) {
|
||||
var buffer bytes.Buffer
|
||||
writer := &buffer
|
||||
_, err := writer.Write([]byte("Hello"))
|
||||
c.Assert(err, IsNil)
|
||||
progress := &customReader{}
|
||||
reader := NewHook(&buffer, progress)
|
||||
b := make([]byte, 3)
|
||||
n, err := reader.Read(b)
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(n, Equals, 3)
|
||||
c.Assert(progress.readBytes, Equals, 3)
|
||||
}
|
||||
@@ -18,17 +18,17 @@ package main
|
||||
|
||||
import "github.com/minio/mc/pkg/console"
|
||||
|
||||
// Message interface for all structured messages implementing JSON(), String() methods
|
||||
type Message interface {
|
||||
// message interface for all structured messages implementing JSON(), String() methods.
|
||||
type message interface {
|
||||
JSON() string
|
||||
String() string
|
||||
}
|
||||
|
||||
// Prints print wrapper for Message interface, implementing both JSON() and String() methods
|
||||
func Prints(format string, message Message) {
|
||||
if !globalJSONFlag {
|
||||
console.Printf(format, message.String())
|
||||
return
|
||||
// printMsg prints message string or JSON structure depending on the type of output console.
|
||||
func printMsg(msg message) {
|
||||
if !globalJSON {
|
||||
console.Println(msg.String())
|
||||
} else {
|
||||
console.Println(msg.JSON())
|
||||
}
|
||||
console.Printf(format, message.JSON())
|
||||
}
|
||||
|
||||
+151
@@ -0,0 +1,151 @@
|
||||
/*
|
||||
* Minio Client (C) 2014, 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"io"
|
||||
"runtime"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/pb"
|
||||
|
||||
"github.com/minio/mc/pkg/console"
|
||||
)
|
||||
|
||||
// progress extender.
|
||||
type progressBar struct {
|
||||
ProgressBar *pb.ProgressBar
|
||||
reader io.Reader
|
||||
readerLength int64
|
||||
bytesRead int64
|
||||
isResume bool
|
||||
}
|
||||
|
||||
// newProgressBar - instantiate a progress bar.
|
||||
func newProgressBar(total int64) *progressBar {
|
||||
// Progress bar speific theme customization.
|
||||
console.SetColor("Bar", color.New(color.FgGreen, color.Bold))
|
||||
|
||||
pgbar := progressBar{}
|
||||
|
||||
// get the new original progress bar.
|
||||
bar := pb.New64(total)
|
||||
|
||||
// Set new human friendly print units.
|
||||
bar.SetUnits(pb.U_BYTES)
|
||||
|
||||
// Refresh rate for progress bar is set to 125 milliseconds.
|
||||
bar.SetRefreshRate(time.Millisecond * 125)
|
||||
|
||||
// Do not print a newline by default handled, it is handled manually.
|
||||
bar.NotPrint = true
|
||||
|
||||
// Show current speed is true.
|
||||
bar.ShowSpeed = true
|
||||
|
||||
// Custom callback with colorized bar.
|
||||
bar.Callback = func(s string) {
|
||||
console.Print(console.Colorize("Bar", "\r"+s))
|
||||
}
|
||||
|
||||
// Use different unicodes for Linux, OS X and Windows.
|
||||
switch runtime.GOOS {
|
||||
case "linux":
|
||||
// Need to add '\x00' as delimiter for unicode characters.
|
||||
bar.Format("┃\x00▓\x00█\x00░\x00┃")
|
||||
case "darwin":
|
||||
// Need to add '\x00' as delimiter for unicode characters.
|
||||
bar.Format(" \x00▓\x00 \x00░\x00 ")
|
||||
default:
|
||||
// Default to non unicode characters.
|
||||
bar.Format("[=> ]")
|
||||
}
|
||||
|
||||
// Start the progress bar.
|
||||
if bar.Total > 0 {
|
||||
bar.Start()
|
||||
}
|
||||
|
||||
// Copy for future
|
||||
pgbar.ProgressBar = bar
|
||||
|
||||
// Return new progress bar here.
|
||||
return &pgbar
|
||||
}
|
||||
|
||||
// Set caption.
|
||||
func (p *progressBar) SetCaption(caption string) *progressBar {
|
||||
caption = fixateBarCaption(caption, getFixedWidth(p.ProgressBar.GetWidth(), 18))
|
||||
p.ProgressBar.Prefix(caption)
|
||||
return p
|
||||
}
|
||||
|
||||
func (p *progressBar) Set64(length int64) *progressBar {
|
||||
p.ProgressBar = p.ProgressBar.Set64(length)
|
||||
return p
|
||||
}
|
||||
|
||||
// cursorAnimate - returns a animated rune through read channel for every read.
|
||||
func cursorAnimate() <-chan rune {
|
||||
cursorCh := make(chan rune)
|
||||
var cursors string
|
||||
|
||||
switch runtime.GOOS {
|
||||
case "linux":
|
||||
// cursors = "➩➪➫➬➭➮➯➱"
|
||||
// cursors = "▁▃▄▅▆▇█▇▆▅▄▃"
|
||||
cursors = "◐◓◑◒"
|
||||
// cursors = "←↖↑↗→↘↓↙"
|
||||
// cursors = "◴◷◶◵"
|
||||
// cursors = "◰◳◲◱"
|
||||
//cursors = "⣾⣽⣻⢿⡿⣟⣯⣷"
|
||||
case "darwin":
|
||||
cursors = "◐◓◑◒"
|
||||
default:
|
||||
cursors = "|/-\\"
|
||||
}
|
||||
go func() {
|
||||
for {
|
||||
for _, cursor := range cursors {
|
||||
cursorCh <- cursor
|
||||
}
|
||||
}
|
||||
}()
|
||||
return cursorCh
|
||||
}
|
||||
|
||||
// fixateBarCaption - fancify bar caption based on the terminal width.
|
||||
func fixateBarCaption(caption string, width int) string {
|
||||
switch {
|
||||
case len(caption) > width:
|
||||
// Trim caption to fit within the screen
|
||||
trimSize := len(caption) - width + 3
|
||||
if trimSize < len(caption) {
|
||||
caption = "..." + caption[trimSize:]
|
||||
}
|
||||
case len(caption) < width:
|
||||
caption += strings.Repeat(" ", width-len(caption))
|
||||
}
|
||||
return caption
|
||||
}
|
||||
|
||||
// getFixedWidth - get a fixed width based for a given percentage.
|
||||
func getFixedWidth(width, percent int) int {
|
||||
return width * percent / 100
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
SET MC_RELEASE=OFFICIAL
|
||||
SET GO15VENDOREXPERIMENT=1
|
||||
go run buildscripts/gen-ldflags.go > temp.txt
|
||||
SET /p LDFLAGS=<temp.txt
|
||||
go build -ldflags="%LDFLAGS%" -o %GOPATH%\bin\mc.exe
|
||||
Executable
+6
@@ -0,0 +1,6 @@
|
||||
#!/bin/bash
|
||||
|
||||
echo -n "Making official release binaries.. "
|
||||
export MC_RELEASE=OFFICIAL
|
||||
make 1>/dev/null
|
||||
echo "Binaries built at ${GOPATH}/bin/mc"
|
||||
+215
@@ -0,0 +1,215 @@
|
||||
/*
|
||||
* Minio Client (C) 2014, 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
)
|
||||
|
||||
// rm specific flags.
|
||||
var (
|
||||
rmFlags = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "help, h",
|
||||
Usage: "Help of rm.",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "recursive, r",
|
||||
Usage: "Remove recursively.",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "force",
|
||||
Usage: "Force a dangerous remove operation.",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "incomplete, I",
|
||||
Usage: "Remove an incomplete upload(s).",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "fake",
|
||||
Usage: "Perform a fake remove operation.",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
// remove a file or folder.
|
||||
var rmCmd = cli.Command{
|
||||
Name: "rm",
|
||||
Usage: "Remove file or bucket [WARNING: Use with care].",
|
||||
Action: mainRm,
|
||||
Flags: append(rmFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
mc {{.Name}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
mc {{.Name}} [FLAGS] TARGET [TARGET ...]
|
||||
|
||||
FLAGS:
|
||||
{{range .Flags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Remove a file.
|
||||
$ mc {{.Name}} 1999/old-backup.tgz
|
||||
|
||||
2. Remove contents of a folder, excluding its sub-folders.
|
||||
$ mc {{.Name}} --force s3/jazz-songs/louis/
|
||||
|
||||
3. Remove contents of a folder recursively.
|
||||
$ mc {{.Name}} --force --recursive s3/jazz-songs/louis/
|
||||
|
||||
4. Remove all matching objects with this prefix.
|
||||
$ mc {{.Name}} --force s3/ogg/gunmetal
|
||||
|
||||
5. Drop an incomplete upload of an object.
|
||||
$ mc {{.Name}} --incomplete s3/jazz-songs/louis/file01.mp3
|
||||
|
||||
6. Drop all incomplete uploads recursively matching this prefix.
|
||||
$ mc {{.Name}} --incomplete --force --recursive s3/jazz-songs/louis/
|
||||
`,
|
||||
}
|
||||
|
||||
// Structured message depending on the type of console.
|
||||
type rmMessage struct {
|
||||
Status string `json:"status"`
|
||||
URL string `json:"url"`
|
||||
}
|
||||
|
||||
// Colorized message for console printing.
|
||||
func (r rmMessage) String() string {
|
||||
return console.Colorize("Remove", fmt.Sprintf("Removed ‘%s’.", r.URL))
|
||||
}
|
||||
|
||||
// JSON'ified message for scripting.
|
||||
func (r rmMessage) JSON() string {
|
||||
msgBytes, e := json.Marshal(r)
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
return string(msgBytes)
|
||||
}
|
||||
|
||||
// Validate command line arguments.
|
||||
func checkRmSyntax(ctx *cli.Context) {
|
||||
// Set command flags from context.
|
||||
isForce := ctx.Bool("force")
|
||||
isRecursive := ctx.Bool("recursive")
|
||||
|
||||
if !ctx.Args().Present() {
|
||||
exitCode := 1
|
||||
cli.ShowCommandHelpAndExit(ctx, "rm", exitCode)
|
||||
}
|
||||
|
||||
// For all recursive operations make sure to check for 'force' flag.
|
||||
if isRecursive && !isForce {
|
||||
fatalIf(errDummy().Trace(),
|
||||
"Recursive removal requires --force option. Please review carefully before performing this *DANGEROUS* operation.")
|
||||
}
|
||||
}
|
||||
|
||||
// Remove a single object.
|
||||
func rm(targetAlias, targetURL string, isIncomplete, isFake bool) *probe.Error {
|
||||
clnt, err := newClientFromAlias(targetAlias, targetURL)
|
||||
if err != nil {
|
||||
return err.Trace(targetURL)
|
||||
}
|
||||
|
||||
if isFake { // It is a fake remove. Return success.
|
||||
return nil
|
||||
}
|
||||
|
||||
if err = clnt.Remove(isIncomplete); err != nil {
|
||||
return err.Trace(targetURL)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Remove all objects recursively.
|
||||
func rmAll(targetAlias, targetURL string, isRecursive, isIncomplete, isFake bool) {
|
||||
// Initialize new client.
|
||||
clnt, err := newClientFromAlias(targetAlias, targetURL)
|
||||
if err != nil {
|
||||
errorIf(err.Trace(targetURL), "Invalid URL ‘"+targetURL+"’.")
|
||||
return // End of journey.
|
||||
}
|
||||
|
||||
/* Disable recursion and only list this folder's contents. We
|
||||
perform manual depth-first recursion ourself here. */
|
||||
nonRecursive := false
|
||||
for entry := range clnt.List(nonRecursive, isIncomplete) {
|
||||
if entry.Err != nil {
|
||||
errorIf(entry.Err.Trace(targetURL), "Unable to list ‘"+targetURL+"’.")
|
||||
return // End of journey.
|
||||
}
|
||||
|
||||
if entry.Type.IsDir() && isRecursive {
|
||||
// Add separator at the end to remove all its contents.
|
||||
url := entry.URL
|
||||
url.Path = strings.TrimSuffix(entry.URL.Path, string(entry.URL.Separator)) + string(entry.URL.Separator)
|
||||
|
||||
// Recursively remove contents of this directory.
|
||||
rmAll(targetAlias, url.String(), isRecursive, isIncomplete, isFake)
|
||||
}
|
||||
|
||||
// Regular type.
|
||||
if err = rm(targetAlias, entry.URL.String(), isIncomplete, isFake); err != nil {
|
||||
errorIf(err.Trace(entry.URL.String()), "Unable to remove ‘"+entry.URL.String()+"’.")
|
||||
continue
|
||||
}
|
||||
// Construct user facing message and path.
|
||||
entryPath := filepath.ToSlash(filepath.Join(targetAlias, entry.URL.Path))
|
||||
printMsg(rmMessage{Status: "success", URL: entryPath})
|
||||
}
|
||||
}
|
||||
|
||||
// main for rm command.
|
||||
func mainRm(ctx *cli.Context) {
|
||||
// Set global flags from context.
|
||||
setGlobalsFromContext(ctx)
|
||||
|
||||
// check 'rm' cli arguments.
|
||||
checkRmSyntax(ctx)
|
||||
|
||||
// rm specific flags.
|
||||
isForce := ctx.Bool("force")
|
||||
isIncomplete := ctx.Bool("incomplete")
|
||||
isRecursive := ctx.Bool("recursive")
|
||||
isFake := ctx.Bool("fake")
|
||||
|
||||
// Set color.
|
||||
console.SetColor("Remove", color.New(color.FgGreen, color.Bold))
|
||||
|
||||
// Support multiple targets.
|
||||
for _, url := range ctx.Args() {
|
||||
targetAlias, targetURL, _ := mustExpandAlias(url)
|
||||
if isRecursive && isForce {
|
||||
rmAll(targetAlias, targetURL, isRecursive, isIncomplete, isFake)
|
||||
} else {
|
||||
if err := rm(targetAlias, targetURL, isIncomplete, isFake); err != nil {
|
||||
errorIf(err.Trace(url), "Unable to remove ‘"+url+"’.")
|
||||
continue
|
||||
}
|
||||
printMsg(rmMessage{Status: "success", URL: url})
|
||||
}
|
||||
}
|
||||
}
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
/*
|
||||
* Minio Client (C) 2014, 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/dustin/go-humanize"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/olekukonko/ts"
|
||||
)
|
||||
|
||||
/******************************** Scan Bar ************************************/
|
||||
// fixateScanBar truncates long text to fit within the terminal size.
|
||||
func fixateScanBar(text string, width int) string {
|
||||
if len([]rune(text)) > width {
|
||||
// Trim text to fit within the screen
|
||||
trimSize := len([]rune(text)) - width + 3 //"..."
|
||||
if trimSize < len([]rune(text)) {
|
||||
text = "..." + text[trimSize:]
|
||||
}
|
||||
}
|
||||
return text
|
||||
}
|
||||
|
||||
// Progress bar function report objects being scaned.
|
||||
type scanBarFunc func(string)
|
||||
|
||||
// scanBarFactory returns a progress bar function to report URL scanning.
|
||||
func scanBarFactory() scanBarFunc {
|
||||
prevLineSize := 0
|
||||
prevSource := ""
|
||||
fileCount := 0
|
||||
termSize, e := ts.GetSize()
|
||||
if e != nil {
|
||||
fatalIf(probe.NewError(e), "Unable to get terminal size. Please use --quiet option.")
|
||||
}
|
||||
termWidth := termSize.Col()
|
||||
cursorCh := cursorAnimate()
|
||||
|
||||
return func(source string) {
|
||||
scanPrefix := fmt.Sprintf("[%s] %s ", humanize.Comma(int64(fileCount)), string(<-cursorCh))
|
||||
cmnPrefix := commonPrefix(source, prevSource)
|
||||
eraseLen := prevLineSize - len([]rune(scanPrefix+cmnPrefix))
|
||||
if eraseLen < 1 {
|
||||
eraseLen = 0
|
||||
}
|
||||
if prevLineSize != 0 { // erase previous line
|
||||
console.PrintC("\r" + scanPrefix + cmnPrefix + strings.Repeat(" ", eraseLen))
|
||||
}
|
||||
|
||||
source = fixateScanBar(source, termWidth-len([]rune(scanPrefix))-1)
|
||||
barText := scanPrefix + source
|
||||
console.PrintC("\r" + barText)
|
||||
prevSource = source
|
||||
prevLineSize = len([]rune(barText))
|
||||
fileCount++
|
||||
}
|
||||
}
|
||||
+109
-69
@@ -18,6 +18,7 @@ package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"sort"
|
||||
"strings"
|
||||
@@ -25,123 +26,139 @@ import (
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
)
|
||||
|
||||
var (
|
||||
sessionFlags = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "help, h",
|
||||
Usage: "Help of session.",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
// Manage sessions for cp and mirror.
|
||||
var sessionCmd = cli.Command{
|
||||
Name: "session",
|
||||
Usage: "Manage sessions for cp and mirror.",
|
||||
Usage: "Manage saved sessions of cp and mirror operations.",
|
||||
Action: mainSession,
|
||||
Flags: append(sessionFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
mc {{.Name}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
mc {{.Name}} list
|
||||
mc {{.Name}} resume SESSION-ID
|
||||
mc {{.Name}} clear SESSION-ID
|
||||
mc {{.Name}} [FLAGS] OPERATION [ARG]
|
||||
|
||||
SESSION-ID = $SESSION | all
|
||||
OPERATION:
|
||||
resume Resume a previously saved session.
|
||||
clear Clear a previously saved session.
|
||||
list List all previously saved sessions.
|
||||
|
||||
SESSION-ID:
|
||||
SESSION - Session can either be $SESSION-ID or "all".
|
||||
|
||||
FLAGS:
|
||||
{{range .Flags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. List sessions
|
||||
1. List sessions.
|
||||
$ mc {{.Name}} list
|
||||
ygVIpSJs -> [2015-08-29 15:25:12 PDT] cp /usr/bin... test
|
||||
|
||||
2. Resume session
|
||||
2. Resume session.
|
||||
$ mc {{.Name}} resume ygVIpSJs
|
||||
|
||||
3. Clear session
|
||||
3. Clear session.
|
||||
$ mc {{.Name}} clear ygVIpSJs
|
||||
|
||||
4. Clear session.
|
||||
$ mc {{.Name}} clear all
|
||||
`,
|
||||
}
|
||||
|
||||
// bySessionWhen is a type for sorting session metadata by time
|
||||
type bySessionWhen []*sessionV2
|
||||
// bySessionWhen is a type for sorting session metadata by time.
|
||||
type bySessionWhen []*sessionV6
|
||||
|
||||
func (b bySessionWhen) Len() int { return len(b) }
|
||||
func (b bySessionWhen) Swap(i, j int) { b[i], b[j] = b[j], b[i] }
|
||||
func (b bySessionWhen) Less(i, j int) bool { return b[i].Header.When.Before(b[j].Header.When) }
|
||||
|
||||
// listSessions list all current sessions.
|
||||
func listSessions() *probe.Error {
|
||||
var bySessions []*sessionV2
|
||||
var bySessions []*sessionV6
|
||||
for _, sid := range getSessionIDs() {
|
||||
s, err := loadSessionV2(sid)
|
||||
s, err := loadSessionV6(sid)
|
||||
if err != nil {
|
||||
return err.Trace()
|
||||
return err.Trace(sid)
|
||||
}
|
||||
bySessions = append(bySessions, s)
|
||||
}
|
||||
// sort sessions based on time
|
||||
// sort sessions based on time.
|
||||
sort.Sort(bySessionWhen(bySessions))
|
||||
for _, session := range bySessions {
|
||||
Prints("%s\n", session)
|
||||
printMsg(session)
|
||||
session.Close()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ClearSessionMessage container for clearing session messages
|
||||
type ClearSessionMessage struct {
|
||||
// clearSessionMessage container for clearing session messages.
|
||||
type clearSessionMessage struct {
|
||||
Status string `json:"success"`
|
||||
SessionID string `json:"sessionId"`
|
||||
}
|
||||
|
||||
// String colorized clear session message
|
||||
func (c ClearSessionMessage) String() string {
|
||||
return console.Colorize("ClearSession", "Session ‘"+c.SessionID+"’ cleared successfully")
|
||||
// String colorized clear session message.
|
||||
func (c clearSessionMessage) String() string {
|
||||
return console.Colorize("ClearSession", "Session ‘"+c.SessionID+"’ cleared successfully.")
|
||||
}
|
||||
|
||||
// JSON jsonified clear session message
|
||||
func (c ClearSessionMessage) JSON() string {
|
||||
clearSessionJSONBytes, err := json.Marshal(c)
|
||||
fatalIf(probe.NewError(err), "Unable to marshal into JSON.")
|
||||
// JSON jsonified clear session message.
|
||||
func (c clearSessionMessage) JSON() string {
|
||||
clearSessionJSONBytes, e := json.Marshal(c)
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(clearSessionJSONBytes)
|
||||
}
|
||||
|
||||
// clearSession clear sessions.
|
||||
func clearSession(sid string) {
|
||||
if sid == "all" {
|
||||
for _, sid := range getSessionIDs() {
|
||||
session, err := loadSessionV2(sid)
|
||||
session, err := loadSessionV6(sid)
|
||||
fatalIf(err.Trace(sid), "Unable to load session ‘"+sid+"’.")
|
||||
|
||||
fatalIf(session.Delete().Trace(sid), "Unable to load session ‘"+sid+"’.")
|
||||
|
||||
Prints("%s\n", ClearSessionMessage{
|
||||
Status: "success",
|
||||
SessionID: sid,
|
||||
})
|
||||
printMsg(clearSessionMessage{Status: "success", SessionID: sid})
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if !isSession(sid) {
|
||||
fatalIf(errDummy().Trace(), "Session ‘"+sid+"’ not found.")
|
||||
if !isSessionExists(sid) {
|
||||
fatalIf(errDummy().Trace(sid), "Session ‘"+sid+"’ not found.")
|
||||
}
|
||||
|
||||
session, err := loadSessionV2(sid)
|
||||
session, err := loadSessionV6(sid)
|
||||
fatalIf(err.Trace(sid), "Unable to load session ‘"+sid+"’.")
|
||||
|
||||
if session != nil {
|
||||
fatalIf(session.Delete().Trace(sid), "Unable to load session ‘"+sid+"’.")
|
||||
Prints("%s\n", ClearSessionMessage{
|
||||
Status: "success",
|
||||
SessionID: sid,
|
||||
})
|
||||
printMsg(clearSessionMessage{Status: "success", SessionID: sid})
|
||||
}
|
||||
}
|
||||
|
||||
func sessionExecute(s *sessionV2) {
|
||||
func sessionExecute(s *sessionV6) {
|
||||
switch s.Header.CommandType {
|
||||
case "cp":
|
||||
doCopyCmdSession(s)
|
||||
doCopySession(s)
|
||||
case "mirror":
|
||||
doMirrorCmdSession(s)
|
||||
doMirrorSession(s)
|
||||
}
|
||||
}
|
||||
|
||||
func checkSessionSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) < 1 || ctx.Args().First() == "help" {
|
||||
if len(ctx.Args()) < 1 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "session", 1) // last argument is exit code
|
||||
}
|
||||
if strings.TrimSpace(ctx.Args().First()) == "" {
|
||||
@@ -152,56 +169,80 @@ func checkSessionSyntax(ctx *cli.Context) {
|
||||
case "list":
|
||||
case "resume":
|
||||
if strings.TrimSpace(ctx.Args().Tail().First()) == "" {
|
||||
fatalIf(errInvalidArgument().Trace(), "Unable to validate empty argument.")
|
||||
fatalIf(errInvalidArgument().Trace(ctx.Args()...), "Unable to validate empty argument.")
|
||||
}
|
||||
case "clear":
|
||||
if strings.TrimSpace(ctx.Args().Tail().First()) == "" {
|
||||
fatalIf(errInvalidArgument().Trace(), "Unable to validate empty argument.")
|
||||
fatalIf(errInvalidArgument().Trace(ctx.Args()...), "Unable to validate empty argument.")
|
||||
}
|
||||
default:
|
||||
cli.ShowCommandHelpAndExit(ctx, "session", 1) // last argument is exit code
|
||||
}
|
||||
}
|
||||
|
||||
// findClosestSessions to match a given string with sessions trie tree.
|
||||
func findClosestSessions(session string) []string {
|
||||
sessionsTree := newTrie() // Allocate a new trie for sessions strings.
|
||||
for _, sid := range getSessionIDs() {
|
||||
sessionsTree.Insert(sid)
|
||||
}
|
||||
var closestSessions []string
|
||||
for _, value := range sessionsTree.PrefixMatch(session) {
|
||||
closestSessions = append(closestSessions, value.(string))
|
||||
}
|
||||
sort.Strings(closestSessions)
|
||||
return closestSessions
|
||||
}
|
||||
|
||||
func mainSession(ctx *cli.Context) {
|
||||
// Set global flags from context.
|
||||
setGlobalsFromContext(ctx)
|
||||
|
||||
// check 'session' cli arguments.
|
||||
checkSessionSyntax(ctx)
|
||||
|
||||
// Additional command speific theme customization.
|
||||
console.SetColor("Command", color.New(color.FgWhite, color.Bold))
|
||||
console.SetColor("SessionID", color.New(color.FgYellow, color.Bold))
|
||||
console.SetColor("SessionTime", color.New(color.FgGreen))
|
||||
console.SetColor("ClearSession", color.New(color.FgGreen, color.Bold))
|
||||
|
||||
if !isSessionDirExists() {
|
||||
fatalIf(createSessionDir().Trace(), "Unable to create session directory.")
|
||||
fatalIf(createSessionDir().Trace(), "Unable to create session folder.")
|
||||
}
|
||||
|
||||
console.SetCustomTheme(map[string]*color.Color{
|
||||
"Command": color.New(color.FgWhite, color.Bold),
|
||||
"SessionID": color.New(color.FgYellow, color.Bold),
|
||||
"SessionTime": color.New(color.FgGreen),
|
||||
"ClearSession": color.New(color.FgGreen, color.Bold),
|
||||
})
|
||||
|
||||
switch strings.TrimSpace(ctx.Args().First()) {
|
||||
// list resumable sessions
|
||||
// list all resumable sessions.
|
||||
case "list":
|
||||
fatalIf(listSessions().Trace(), "Unable to list sessions.")
|
||||
fatalIf(listSessions().Trace(ctx.Args()...), "Unable to list sessions.")
|
||||
case "resume":
|
||||
sid := strings.TrimSpace(ctx.Args().Tail().First())
|
||||
if !isSession(sid) {
|
||||
fatalIf(errDummy().Trace(), "Session ‘"+sid+"’ not found.")
|
||||
if !isSessionExists(sid) {
|
||||
closestSessions := findClosestSessions(sid)
|
||||
errorMsg := "Session ‘" + sid + "’ not found."
|
||||
if len(closestSessions) > 0 {
|
||||
errorMsg += fmt.Sprintf("\n\nDid you mean?\n")
|
||||
for _, session := range closestSessions {
|
||||
errorMsg += fmt.Sprintf(" ‘mc resume session %s’", session)
|
||||
// break on the first one, it is good enough.
|
||||
break
|
||||
}
|
||||
}
|
||||
fatalIf(errDummy().Trace(sid), errorMsg)
|
||||
}
|
||||
|
||||
s, err := loadSessionV2(sid)
|
||||
s, err := loadSessionV6(sid)
|
||||
fatalIf(err.Trace(sid), "Unable to load session.")
|
||||
|
||||
// extra check for testing purposes
|
||||
if s == nil {
|
||||
return
|
||||
}
|
||||
// Restore the state of global variables from this previous session.
|
||||
s.restoreGlobals()
|
||||
|
||||
savedCwd, e := os.Getwd()
|
||||
fatalIf(probe.NewError(e), "Unable to verify your current working folder.")
|
||||
fatalIf(probe.NewError(e), "Unable to determine current working folder.")
|
||||
|
||||
if s.Header.RootPath != "" {
|
||||
// chdir to RootPath
|
||||
// change folder to RootPath.
|
||||
e = os.Chdir(s.Header.RootPath)
|
||||
fatalIf(probe.NewError(e), "Unable to change directory to root path while resuming session.")
|
||||
fatalIf(probe.NewError(e), "Unable to change working folder to root path while resuming session.")
|
||||
}
|
||||
sessionExecute(s)
|
||||
err = s.Close()
|
||||
@@ -210,11 +251,10 @@ func mainSession(ctx *cli.Context) {
|
||||
err = s.Delete()
|
||||
fatalIf(err.Trace(), "Unable to clear session files properly.")
|
||||
|
||||
// chdir back to saved path
|
||||
// change folder back to saved path.
|
||||
e = os.Chdir(savedCwd)
|
||||
fatalIf(probe.NewError(e), "Unable to change directory to saved path ‘"+savedCwd+"’.")
|
||||
|
||||
// purge a requested pending session, if "all" purge everything
|
||||
fatalIf(probe.NewError(e), "Unable to change working folder to saved path ‘"+savedCwd+"’.")
|
||||
// purge a requested pending session, if "all" purge everything.
|
||||
case "clear":
|
||||
clearSession(strings.TrimSpace(ctx.Args().Tail().First()))
|
||||
}
|
||||
|
||||
-114
@@ -1,114 +0,0 @@
|
||||
/*
|
||||
* Minio Client, (C) 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
"github.com/minio/minio/pkg/quick"
|
||||
)
|
||||
|
||||
type sessionV1 struct {
|
||||
Version string `json:"version"`
|
||||
Started time.Time `json:"started"`
|
||||
CommandType string `json:"command-type"`
|
||||
SessionID string `json:"session-id"`
|
||||
URLs []string `json:"args"`
|
||||
Files map[string]bool `json:"files"`
|
||||
|
||||
Lock *sync.Mutex `json:"-"`
|
||||
}
|
||||
|
||||
func (s sessionV1) String() string {
|
||||
message := console.Colorize("Time", fmt.Sprintf("[%s] ", s.Started.Local().Format(printDate)))
|
||||
message = message + console.Colorize("SessionID", fmt.Sprintf("%s", s.SessionID))
|
||||
message = message + console.Colorize("Command", fmt.Sprintf(" [%s %s]", s.CommandType, strings.Join(s.URLs, " ")))
|
||||
return message
|
||||
}
|
||||
|
||||
// loadSession - reads session file if exists and re-initiates internal variables
|
||||
func loadSessionV1(sid string) (*sessionV1, *probe.Error) {
|
||||
if !isSessionDirExists() {
|
||||
return nil, probe.NewError(errors.New("Session folder does not exist."))
|
||||
}
|
||||
|
||||
sessionFile, err := getSessionFileV1(sid)
|
||||
if err != nil {
|
||||
return nil, err.Trace(sid)
|
||||
}
|
||||
|
||||
s := new(sessionV1)
|
||||
s.Version = "1.0.0"
|
||||
// map of command and files copied
|
||||
s.URLs = nil
|
||||
s.Lock = new(sync.Mutex)
|
||||
s.Files = make(map[string]bool)
|
||||
qs, err := quick.New(s)
|
||||
if err != nil {
|
||||
return nil, err.Trace(s.Version)
|
||||
}
|
||||
err = qs.Load(sessionFile)
|
||||
if err != nil {
|
||||
return nil, err.Trace(sessionFile, s.Version)
|
||||
}
|
||||
return qs.Data().(*sessionV1), nil
|
||||
}
|
||||
|
||||
func getSessionIDsV1() (sids []string) {
|
||||
sessionDir, err := getSessionDir()
|
||||
fatalIf(err.Trace(), "Unable to determine session folder.")
|
||||
|
||||
sessionList, e := filepath.Glob(sessionDir + "/*")
|
||||
fatalIf(probe.NewError(e), "Unable to access session folder ‘"+sessionDir+"’.")
|
||||
|
||||
for _, path := range sessionList {
|
||||
sidReg := regexp.MustCompile("^[a-zA-Z]{8}$")
|
||||
sid := filepath.Base(path)
|
||||
if sidReg.Match([]byte(sid)) {
|
||||
sessionV1, err := loadSessionV1(sid)
|
||||
fatalIf(err.Trace(sid), "Unable to load session ‘"+sid+"’.")
|
||||
if sessionV1.Version != "1.0.0" {
|
||||
continue
|
||||
}
|
||||
sids = append(sids, sid)
|
||||
}
|
||||
}
|
||||
return sids
|
||||
}
|
||||
|
||||
func getSessionFileV1(sid string) (string, *probe.Error) {
|
||||
sessionDir, err := getSessionDir()
|
||||
if err != nil {
|
||||
return "", err.Trace()
|
||||
}
|
||||
|
||||
sessionFile := filepath.Join(sessionDir, sid)
|
||||
if _, err := os.Stat(sessionFile); err != nil {
|
||||
return "", probe.NewError(err)
|
||||
}
|
||||
|
||||
return sessionFile, nil
|
||||
}
|
||||
-302
@@ -1,302 +0,0 @@
|
||||
/*
|
||||
* Minio Client, (C) 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
// Session V2 - Version 2 stores session header and session data in
|
||||
// two separate files. Session data contains fully prepared URL list.
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
"github.com/minio/minio/pkg/quick"
|
||||
)
|
||||
|
||||
// migrateSessionV1ToV2 migrates all session files from v1 to v2.
|
||||
// This function should be called from the main early on.
|
||||
func migrateSessionV1ToV2() {
|
||||
for _, sid := range getSessionIDsV1() {
|
||||
sessionFileV1, err := getSessionFileV1(sid)
|
||||
fatalIf(err.Trace(sid), "Unable to determine session file for ‘"+sid+"’.")
|
||||
|
||||
e := os.Remove(sessionFileV1)
|
||||
fatalIf(probe.NewError(e), "Migration failed. Unable to remove old session file ‘"+sessionFileV1+"’.")
|
||||
}
|
||||
}
|
||||
|
||||
// sessionV2Header
|
||||
type sessionV2Header struct {
|
||||
Version string `json:"version"`
|
||||
When time.Time `json:"time"`
|
||||
RootPath string `json:"working-folder"`
|
||||
CommandType string `json:"command-type"`
|
||||
CommandArgs []string `json:"cmd-args"`
|
||||
LastCopied string `json:"last-copied"`
|
||||
TotalBytes int64 `json:"total-bytes"`
|
||||
TotalObjects int `json:"total-objects"`
|
||||
}
|
||||
|
||||
// SessionMessage container for session messages
|
||||
type SessionMessage struct {
|
||||
SessionID string `json:"sessionid"`
|
||||
Time time.Time `json:"time"`
|
||||
CommandType string `json:"command-type"`
|
||||
CommandArgs []string `json:"command-args"`
|
||||
}
|
||||
|
||||
// sessionV2
|
||||
type sessionV2 struct {
|
||||
Header *sessionV2Header
|
||||
SessionID string
|
||||
mutex *sync.Mutex
|
||||
DataFP *sessionDataFP
|
||||
sigCh bool
|
||||
}
|
||||
|
||||
type sessionDataFP struct {
|
||||
dirty bool
|
||||
*os.File
|
||||
}
|
||||
|
||||
func (file *sessionDataFP) Write(p []byte) (int, error) {
|
||||
file.dirty = true
|
||||
return file.File.Write(p)
|
||||
}
|
||||
|
||||
// String colorized session message
|
||||
func (s sessionV2) String() string {
|
||||
message := console.Colorize("SessionID", fmt.Sprintf("%s -> ", s.SessionID))
|
||||
message = message + console.Colorize("SessionTime", fmt.Sprintf("[%s]", s.Header.When.Local().Format(printDate)))
|
||||
message = message + console.Colorize("Command", fmt.Sprintf(" %s %s", s.Header.CommandType, strings.Join(s.Header.CommandArgs, " ")))
|
||||
return message
|
||||
}
|
||||
|
||||
// JSON jsonified session message
|
||||
func (s sessionV2) JSON() string {
|
||||
sessionMesage := SessionMessage{
|
||||
SessionID: s.SessionID,
|
||||
Time: s.Header.When.Local(),
|
||||
CommandType: s.Header.CommandType,
|
||||
CommandArgs: s.Header.CommandArgs,
|
||||
}
|
||||
sessionBytes, e := json.Marshal(sessionMesage)
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(sessionBytes)
|
||||
}
|
||||
|
||||
// newSessionV2 provides a new session
|
||||
func newSessionV2() *sessionV2 {
|
||||
s := &sessionV2{}
|
||||
s.Header = &sessionV2Header{}
|
||||
s.Header.Version = "1.1.0"
|
||||
// map of command and files copied
|
||||
s.Header.CommandArgs = nil
|
||||
s.Header.When = time.Now().UTC()
|
||||
s.mutex = new(sync.Mutex)
|
||||
s.SessionID = newRandomID(8)
|
||||
|
||||
sessionDataFile, perr := getSessionDataFile(s.SessionID)
|
||||
fatalIf(perr.Trace(s.SessionID), "Unable to create session data file \""+sessionDataFile+"\".")
|
||||
|
||||
dataFile, err := os.Create(sessionDataFile)
|
||||
fatalIf(probe.NewError(err), "Unable to create session data file \""+sessionDataFile+"\".")
|
||||
|
||||
s.DataFP = &sessionDataFP{false, dataFile}
|
||||
return s
|
||||
}
|
||||
|
||||
// String printer for SessionV2
|
||||
func (s sessionV2) Info() {
|
||||
console.Infoln("Session safely terminated. To resume session ‘mc session resume " + s.SessionID + "’")
|
||||
}
|
||||
|
||||
func gracefulSessionSave(session *sessionV2) {
|
||||
session.Close()
|
||||
session.Info()
|
||||
os.Exit(0)
|
||||
}
|
||||
|
||||
// HasData provides true if this is a session resume, false otherwise.
|
||||
func (s sessionV2) HasData() bool {
|
||||
if s.Header.LastCopied == "" {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// NewDataReader provides reader interface to session data file.
|
||||
func (s *sessionV2) NewDataReader() io.Reader {
|
||||
// DataFP is always intitialized, either via new or load functions.
|
||||
s.DataFP.Seek(0, os.SEEK_SET)
|
||||
return io.Reader(s.DataFP)
|
||||
}
|
||||
|
||||
// NewDataReader provides writer interface to session data file.
|
||||
func (s *sessionV2) NewDataWriter() io.Writer {
|
||||
// DataFP is always intitialized, either via new or load functions.
|
||||
s.DataFP.Seek(0, os.SEEK_SET)
|
||||
return io.Writer(s.DataFP)
|
||||
}
|
||||
|
||||
// Save this session
|
||||
func (s *sessionV2) Save() *probe.Error {
|
||||
s.mutex.Lock()
|
||||
defer s.mutex.Unlock()
|
||||
|
||||
if s.DataFP.dirty {
|
||||
if err := s.DataFP.Sync(); err != nil {
|
||||
return probe.NewError(err)
|
||||
}
|
||||
s.DataFP.dirty = false
|
||||
}
|
||||
|
||||
qs, err := quick.New(s.Header)
|
||||
if err != nil {
|
||||
return err.Trace(s.SessionID)
|
||||
}
|
||||
|
||||
sessionFile, err := getSessionFile(s.SessionID)
|
||||
if err != nil {
|
||||
return err.Trace(s.SessionID)
|
||||
}
|
||||
return qs.Save(sessionFile).Trace()
|
||||
}
|
||||
|
||||
// Close ends this session and removes all associated session files.
|
||||
func (s *sessionV2) Close() *probe.Error {
|
||||
s.mutex.Lock()
|
||||
defer s.mutex.Unlock()
|
||||
|
||||
if err := s.DataFP.Close(); err != nil {
|
||||
return probe.NewError(err)
|
||||
}
|
||||
|
||||
qs, err := quick.New(s.Header)
|
||||
if err != nil {
|
||||
return err.Trace()
|
||||
}
|
||||
|
||||
sessionFile, err := getSessionFile(s.SessionID)
|
||||
if err != nil {
|
||||
return err.Trace(s.SessionID)
|
||||
}
|
||||
return qs.Save(sessionFile).Trace()
|
||||
}
|
||||
|
||||
// Delete removes all the session files.
|
||||
func (s *sessionV2) Delete() *probe.Error {
|
||||
s.mutex.Lock()
|
||||
defer s.mutex.Unlock()
|
||||
|
||||
if s.DataFP != nil {
|
||||
name := s.DataFP.Name()
|
||||
// close file pro-actively before deleting
|
||||
// ignore any error, it could be possibly that
|
||||
// the file is closed already
|
||||
s.DataFP.Close()
|
||||
|
||||
err := os.Remove(name)
|
||||
if err != nil {
|
||||
return probe.NewError(err)
|
||||
}
|
||||
}
|
||||
|
||||
sessionFile, err := getSessionFile(s.SessionID)
|
||||
if err != nil {
|
||||
return err.Trace(s.SessionID)
|
||||
}
|
||||
|
||||
if err := os.Remove(sessionFile); err != nil {
|
||||
return probe.NewError(err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// loadSession - reads session file if exists and re-initiates internal variables
|
||||
func loadSessionV2(sid string) (*sessionV2, *probe.Error) {
|
||||
if !isSessionDirExists() {
|
||||
return nil, errInvalidArgument().Trace()
|
||||
}
|
||||
sessionFile, err := getSessionFile(sid)
|
||||
if err != nil {
|
||||
return nil, err.Trace(sid)
|
||||
}
|
||||
|
||||
if _, err := os.Stat(sessionFile); err != nil {
|
||||
return nil, probe.NewError(err)
|
||||
}
|
||||
|
||||
s := &sessionV2{}
|
||||
s.Header = &sessionV2Header{}
|
||||
s.SessionID = sid
|
||||
s.Header.Version = "1.1.0"
|
||||
qs, err := quick.New(s.Header)
|
||||
if err != nil {
|
||||
return nil, err.Trace(sid, s.Header.Version)
|
||||
}
|
||||
err = qs.Load(sessionFile)
|
||||
if err != nil {
|
||||
return nil, err.Trace(sid, s.Header.Version)
|
||||
}
|
||||
|
||||
s.mutex = new(sync.Mutex)
|
||||
s.Header = qs.Data().(*sessionV2Header)
|
||||
|
||||
sessionDataFile, err := getSessionDataFile(s.SessionID)
|
||||
if err != nil {
|
||||
return nil, err.Trace(sid, s.Header.Version)
|
||||
}
|
||||
|
||||
var e error
|
||||
dataFile, e := os.Open(sessionDataFile)
|
||||
fatalIf(probe.NewError(e), "Unable to open session data file \""+sessionDataFile+"\".")
|
||||
|
||||
s.DataFP = &sessionDataFP{false, dataFile}
|
||||
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// Create a factory function to simplify checking if an
|
||||
// object has been copied or not.
|
||||
// isCopied(URL) -> true or false
|
||||
func isCopiedFactory(lastCopied string) func(string) bool {
|
||||
copied := true // closure
|
||||
return func(sourceURL string) bool {
|
||||
if sourceURL == "" {
|
||||
fatalIf(errInvalidArgument().Trace(), "Empty source argument passed.")
|
||||
}
|
||||
if lastCopied == "" {
|
||||
return false
|
||||
}
|
||||
|
||||
if copied {
|
||||
if lastCopied == sourceURL {
|
||||
copied = false // from next call onwards we say false.
|
||||
}
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
+347
@@ -0,0 +1,347 @@
|
||||
/*
|
||||
* Minio Client, (C) 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
// Session V2 - Version 2 stores session header and session data in
|
||||
// two separate files. Session data contains fully prepared URL list.
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/minio-xl/pkg/quick"
|
||||
)
|
||||
|
||||
func migrateSessionV5ToV6() {
|
||||
for _, sid := range getSessionIDs() {
|
||||
sessionV6, err := loadSessionV6(sid)
|
||||
fatalIf(err.Trace(sid), "Unable to load version ‘6’. Migration failed please report this issue at https://github.com/minio/mc/issues.")
|
||||
if sessionV6.Header.Version == "6" { // It is new format.
|
||||
return
|
||||
}
|
||||
/*** Remove all session files older than v6 ***/
|
||||
|
||||
sessionFile, err := getSessionFile(sid)
|
||||
fatalIf(err.Trace(sid), "Unable to get session file.")
|
||||
|
||||
sessionDataFile, err := getSessionDataFile(sid)
|
||||
fatalIf(err.Trace(sid), "Unable to get session data file.")
|
||||
|
||||
console.Println("Removing unsupported session file ‘" + sessionFile + "’ version ‘" + sessionV6.Header.Version + "’.")
|
||||
if e := os.Remove(sessionFile); e != nil {
|
||||
fatalIf(probe.NewError(e), "Unable to remove version ‘"+sessionV6.Header.Version+"’ session file ‘"+sessionFile+"’.")
|
||||
}
|
||||
if e := os.Remove(sessionDataFile); e != nil {
|
||||
fatalIf(probe.NewError(e), "Unable to remove version ‘"+sessionV6.Header.Version+"’ session data file ‘"+sessionDataFile+"’.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// sessionV6Header for resumable sessions.
|
||||
type sessionV6Header struct {
|
||||
Version string `json:"version"`
|
||||
When time.Time `json:"time"`
|
||||
RootPath string `json:"workingFolder"`
|
||||
GlobalBoolFlags map[string]bool `json:"globalBoolFlags"`
|
||||
GlobalIntFlags map[string]int `json:"globalIntFlags"`
|
||||
GlobalStringFlags map[string]string `json:"globalStringFlags"`
|
||||
CommandType string `json:"commandType"`
|
||||
CommandArgs []string `json:"cmdArgs"`
|
||||
CommandBoolFlags map[string]bool `json:"cmdBoolFlags"`
|
||||
CommandIntFlags map[string]int `json:"cmdIntFlags"`
|
||||
CommandStringFlags map[string]string `json:"cmdStringFlags"`
|
||||
LastCopied string `json:"lastCopied"`
|
||||
TotalBytes int64 `json:"totalBytes"`
|
||||
TotalObjects int `json:"totalObjects"`
|
||||
}
|
||||
|
||||
// sessionMessage container for session messages
|
||||
type sessionMessage struct {
|
||||
Status string `json:"status"`
|
||||
SessionID string `json:"sessionId"`
|
||||
Time time.Time `json:"time"`
|
||||
CommandType string `json:"commandType"`
|
||||
CommandArgs []string `json:"commandArgs"`
|
||||
}
|
||||
|
||||
// sessionV6 resumable session container.
|
||||
type sessionV6 struct {
|
||||
Header *sessionV6Header
|
||||
SessionID string
|
||||
mutex *sync.Mutex
|
||||
DataFP *sessionDataFP
|
||||
sigCh bool
|
||||
}
|
||||
|
||||
// sessionDataFP data file pointer.
|
||||
type sessionDataFP struct {
|
||||
dirty bool
|
||||
*os.File
|
||||
}
|
||||
|
||||
func (file *sessionDataFP) Write(p []byte) (int, error) {
|
||||
file.dirty = true
|
||||
return file.File.Write(p)
|
||||
}
|
||||
|
||||
// String colorized session message.
|
||||
func (s sessionV6) String() string {
|
||||
message := console.Colorize("SessionID", fmt.Sprintf("%s -> ", s.SessionID))
|
||||
message = message + console.Colorize("SessionTime", fmt.Sprintf("[%s]", s.Header.When.Local().Format(printDate)))
|
||||
message = message + console.Colorize("Command", fmt.Sprintf(" %s %s", s.Header.CommandType, strings.Join(s.Header.CommandArgs, " ")))
|
||||
return message
|
||||
}
|
||||
|
||||
// JSON jsonified session message.
|
||||
func (s sessionV6) JSON() string {
|
||||
sessionMsg := sessionMessage{
|
||||
SessionID: s.SessionID,
|
||||
Time: s.Header.When.Local(),
|
||||
CommandType: s.Header.CommandType,
|
||||
CommandArgs: s.Header.CommandArgs,
|
||||
}
|
||||
sessionMsg.Status = "success"
|
||||
sessionBytes, e := json.Marshal(sessionMsg)
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(sessionBytes)
|
||||
}
|
||||
|
||||
// loadSessionV6 - reads session file if exists and re-initiates internal variables
|
||||
func loadSessionV6(sid string) (*sessionV6, *probe.Error) {
|
||||
if !isSessionDirExists() {
|
||||
return nil, errInvalidArgument().Trace()
|
||||
}
|
||||
sessionFile, err := getSessionFile(sid)
|
||||
if err != nil {
|
||||
return nil, err.Trace(sid)
|
||||
}
|
||||
|
||||
if _, e := os.Stat(sessionFile); e != nil {
|
||||
return nil, probe.NewError(e)
|
||||
}
|
||||
|
||||
s := &sessionV6{}
|
||||
s.Header = &sessionV6Header{}
|
||||
s.SessionID = sid
|
||||
s.Header.Version = "5"
|
||||
qs, err := quick.New(s.Header)
|
||||
if err != nil {
|
||||
return nil, err.Trace(sid, s.Header.Version)
|
||||
}
|
||||
err = qs.Load(sessionFile)
|
||||
if err != nil {
|
||||
return nil, err.Trace(sid, s.Header.Version)
|
||||
}
|
||||
|
||||
s.mutex = new(sync.Mutex)
|
||||
s.Header = qs.Data().(*sessionV6Header)
|
||||
|
||||
sessionDataFile, err := getSessionDataFile(s.SessionID)
|
||||
if err != nil {
|
||||
return nil, err.Trace(sid, s.Header.Version)
|
||||
}
|
||||
|
||||
var e error
|
||||
dataFile, e := os.Open(sessionDataFile)
|
||||
fatalIf(probe.NewError(e), "Unable to open session data file \""+sessionDataFile+"\".")
|
||||
|
||||
s.DataFP = &sessionDataFP{false, dataFile}
|
||||
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// newSessionV6 provides a new session.
|
||||
func newSessionV6() *sessionV6 {
|
||||
s := &sessionV6{}
|
||||
s.Header = &sessionV6Header{}
|
||||
s.Header.Version = "6"
|
||||
// map of command and files copied.
|
||||
s.Header.GlobalBoolFlags = make(map[string]bool)
|
||||
s.Header.GlobalIntFlags = make(map[string]int)
|
||||
s.Header.GlobalStringFlags = make(map[string]string)
|
||||
s.Header.CommandArgs = nil
|
||||
s.Header.CommandBoolFlags = make(map[string]bool)
|
||||
s.Header.CommandIntFlags = make(map[string]int)
|
||||
s.Header.CommandStringFlags = make(map[string]string)
|
||||
s.Header.When = time.Now().UTC()
|
||||
s.mutex = new(sync.Mutex)
|
||||
s.SessionID = newRandomID(8)
|
||||
|
||||
sessionDataFile, err := getSessionDataFile(s.SessionID)
|
||||
fatalIf(err.Trace(s.SessionID), "Unable to create session data file \""+sessionDataFile+"\".")
|
||||
|
||||
dataFile, e := os.Create(sessionDataFile)
|
||||
fatalIf(probe.NewError(e), "Unable to create session data file \""+sessionDataFile+"\".")
|
||||
|
||||
s.DataFP = &sessionDataFP{false, dataFile}
|
||||
|
||||
// Capture state of global flags.
|
||||
s.setGlobals()
|
||||
|
||||
return s
|
||||
}
|
||||
|
||||
// HasData provides true if this is a session resume, false otherwise.
|
||||
func (s sessionV6) HasData() bool {
|
||||
if s.Header.LastCopied == "" {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// NewDataReader provides reader interface to session data file.
|
||||
func (s *sessionV6) NewDataReader() io.Reader {
|
||||
// DataFP is always intitialized, either via new or load functions.
|
||||
s.DataFP.Seek(0, os.SEEK_SET)
|
||||
return io.Reader(s.DataFP)
|
||||
}
|
||||
|
||||
// NewDataReader provides writer interface to session data file.
|
||||
func (s *sessionV6) NewDataWriter() io.Writer {
|
||||
// DataFP is always intitialized, either via new or load functions.
|
||||
s.DataFP.Seek(0, os.SEEK_SET)
|
||||
return io.Writer(s.DataFP)
|
||||
}
|
||||
|
||||
// Save this session.
|
||||
func (s *sessionV6) Save() *probe.Error {
|
||||
s.mutex.Lock()
|
||||
defer s.mutex.Unlock()
|
||||
|
||||
if s.DataFP.dirty {
|
||||
if err := s.DataFP.Sync(); err != nil {
|
||||
return probe.NewError(err)
|
||||
}
|
||||
s.DataFP.dirty = false
|
||||
}
|
||||
|
||||
qs, err := quick.New(s.Header)
|
||||
if err != nil {
|
||||
return err.Trace(s.SessionID)
|
||||
}
|
||||
|
||||
sessionFile, err := getSessionFile(s.SessionID)
|
||||
if err != nil {
|
||||
return err.Trace(s.SessionID)
|
||||
}
|
||||
return qs.Save(sessionFile).Trace(sessionFile)
|
||||
}
|
||||
|
||||
// setGlobals captures the state of global variables into session header.
|
||||
// Used by newSession.
|
||||
func (s *sessionV6) setGlobals() {
|
||||
s.Header.GlobalBoolFlags["quiet"] = globalQuiet
|
||||
s.Header.GlobalBoolFlags["debug"] = globalDebug
|
||||
s.Header.GlobalBoolFlags["json"] = globalJSON
|
||||
s.Header.GlobalBoolFlags["noColor"] = globalNoColor
|
||||
}
|
||||
|
||||
// RestoreGlobals restores the state of global variables.
|
||||
// Used by resumeSession.
|
||||
func (s sessionV6) restoreGlobals() {
|
||||
quiet := s.Header.GlobalBoolFlags["quiet"]
|
||||
debug := s.Header.GlobalBoolFlags["debug"]
|
||||
json := s.Header.GlobalBoolFlags["json"]
|
||||
noColor := s.Header.GlobalBoolFlags["noColor"]
|
||||
setGlobals(quiet, debug, json, noColor)
|
||||
}
|
||||
|
||||
// Close ends this session and removes all associated session files.
|
||||
func (s *sessionV6) Close() *probe.Error {
|
||||
s.mutex.Lock()
|
||||
defer s.mutex.Unlock()
|
||||
|
||||
if err := s.DataFP.Close(); err != nil {
|
||||
return probe.NewError(err)
|
||||
}
|
||||
|
||||
qs, err := quick.New(s.Header)
|
||||
if err != nil {
|
||||
return err.Trace()
|
||||
}
|
||||
|
||||
sessionFile, err := getSessionFile(s.SessionID)
|
||||
if err != nil {
|
||||
return err.Trace(s.SessionID)
|
||||
}
|
||||
return qs.Save(sessionFile).Trace(sessionFile)
|
||||
}
|
||||
|
||||
// Delete removes all the session files.
|
||||
func (s *sessionV6) Delete() *probe.Error {
|
||||
s.mutex.Lock()
|
||||
defer s.mutex.Unlock()
|
||||
|
||||
if s.DataFP != nil {
|
||||
name := s.DataFP.Name()
|
||||
// close file pro-actively before deleting
|
||||
// ignore any error, it could be possibly that
|
||||
// the file is closed already
|
||||
s.DataFP.Close()
|
||||
|
||||
if e := os.Remove(name); e != nil {
|
||||
return probe.NewError(e)
|
||||
}
|
||||
}
|
||||
|
||||
sessionFile, err := getSessionFile(s.SessionID)
|
||||
if err != nil {
|
||||
return err.Trace(s.SessionID)
|
||||
}
|
||||
|
||||
if e := os.Remove(sessionFile); e != nil {
|
||||
return probe.NewError(e)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Close a session and exit.
|
||||
func (s sessionV6) CloseAndDie() {
|
||||
s.Close()
|
||||
console.Fatalln("Session safely terminated. To resume session ‘mc session resume " + s.SessionID + "’")
|
||||
}
|
||||
|
||||
// Create a factory function to simplify checking if an
|
||||
// object has been copied or not.
|
||||
// isCopied(URL) -> true or false
|
||||
func isCopiedFactory(lastCopied string) func(string) bool {
|
||||
copied := true // closure
|
||||
return func(sourceURL string) bool {
|
||||
if sourceURL == "" {
|
||||
fatalIf(errInvalidArgument().Trace(), "Empty source argument passed.")
|
||||
}
|
||||
if lastCopied == "" {
|
||||
return false
|
||||
}
|
||||
|
||||
if copied {
|
||||
if lastCopied == sourceURL {
|
||||
copied = false // from next call onwards we say false.
|
||||
}
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
+14
-6
@@ -21,26 +21,29 @@ import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
)
|
||||
|
||||
// migrateSession migrates all previous migration to latest.
|
||||
func migrateSession() {
|
||||
// Migrate session V1 to V2
|
||||
migrateSessionV1ToV2()
|
||||
// We no longer support sessions older than v5. They will be removed.
|
||||
migrateSessionV5ToV6()
|
||||
}
|
||||
|
||||
// createSessionDir - create session directory.
|
||||
func createSessionDir() *probe.Error {
|
||||
sessionDir, err := getSessionDir()
|
||||
if err != nil {
|
||||
return err.Trace()
|
||||
}
|
||||
|
||||
if err := os.MkdirAll(sessionDir, 0700); err != nil {
|
||||
return probe.NewError(err)
|
||||
if e := os.MkdirAll(sessionDir, 0700); e != nil {
|
||||
return probe.NewError(e)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// getSessionDir - get session directory.
|
||||
func getSessionDir() (string, *probe.Error) {
|
||||
configDir, err := getMcConfigDir()
|
||||
if err != nil {
|
||||
@@ -51,6 +54,7 @@ func getSessionDir() (string, *probe.Error) {
|
||||
return sessionDir, nil
|
||||
}
|
||||
|
||||
// isSessionDirExists - verify if session directory exists.
|
||||
func isSessionDirExists() bool {
|
||||
sessionDir, err := getSessionDir()
|
||||
fatalIf(err.Trace(), "Unable to determine session folder.")
|
||||
@@ -61,6 +65,7 @@ func isSessionDirExists() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// getSessionFile - get current session file.
|
||||
func getSessionFile(sid string) (string, *probe.Error) {
|
||||
sessionDir, err := getSessionDir()
|
||||
if err != nil {
|
||||
@@ -71,7 +76,8 @@ func getSessionFile(sid string) (string, *probe.Error) {
|
||||
return sessionFile, nil
|
||||
}
|
||||
|
||||
func isSession(sid string) bool {
|
||||
// isSessionExists verifies if given session exists.
|
||||
func isSessionExists(sid string) bool {
|
||||
sessionFile, err := getSessionFile(sid)
|
||||
fatalIf(err.Trace(sid), "Unable to determine session filename for ‘"+sid+"’.")
|
||||
|
||||
@@ -82,6 +88,7 @@ func isSession(sid string) bool {
|
||||
return true // Session exists.
|
||||
}
|
||||
|
||||
// getSessionDataFile - get session data file for a given session.
|
||||
func getSessionDataFile(sid string) (string, *probe.Error) {
|
||||
sessionDir, err := getSessionDir()
|
||||
if err != nil {
|
||||
@@ -92,6 +99,7 @@ func getSessionDataFile(sid string) (string, *probe.Error) {
|
||||
return sessionDataFile, nil
|
||||
}
|
||||
|
||||
// getSessionIDs - get all active sessions.
|
||||
func getSessionIDs() (sids []string) {
|
||||
sessionDir, err := getSessionDir()
|
||||
fatalIf(err.Trace(), "Unable to access session folder.")
|
||||
|
||||
+10
-65
@@ -17,10 +17,8 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"regexp"
|
||||
|
||||
"github.com/minio/mc/pkg/console"
|
||||
. "gopkg.in/check.v1"
|
||||
)
|
||||
|
||||
@@ -32,77 +30,24 @@ func (s *TestSuite) TestValidSessionID(c *C) {
|
||||
}
|
||||
|
||||
func (s *TestSuite) TestSession(c *C) {
|
||||
perr := createSessionDir()
|
||||
c.Assert(perr, IsNil)
|
||||
err := createSessionDir()
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(isSessionDirExists(), Equals, true)
|
||||
|
||||
session := newSessionV2()
|
||||
session := newSessionV6()
|
||||
c.Assert(session.Header.CommandArgs, IsNil)
|
||||
c.Assert(len(session.SessionID), Equals, 8)
|
||||
|
||||
perr = session.Close()
|
||||
c.Assert(perr, IsNil)
|
||||
err = session.Close()
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
savedSession, perr := loadSessionV2(session.SessionID)
|
||||
c.Assert(perr, IsNil)
|
||||
savedSession, err := loadSessionV6(session.SessionID)
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(session.SessionID, Equals, savedSession.SessionID)
|
||||
|
||||
perr = savedSession.Close()
|
||||
c.Assert(perr, IsNil)
|
||||
err = savedSession.Close()
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
perr = savedSession.Delete()
|
||||
c.Assert(perr, IsNil)
|
||||
}
|
||||
|
||||
func (s *TestSuite) TestSessionContext(c *C) {
|
||||
err := app.Run([]string{os.Args[0], "session", "list"})
|
||||
err = savedSession.Delete()
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(console.IsExited, Equals, false)
|
||||
|
||||
// reset back
|
||||
console.IsExited = false
|
||||
|
||||
err = app.Run([]string{os.Args[0], "session", "clear", "all"})
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(console.IsExited, Equals, false)
|
||||
|
||||
// reset back
|
||||
console.IsExited = false
|
||||
|
||||
err = app.Run([]string{os.Args[0], "session", "resume", "invalid"})
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(console.IsExited, Equals, true)
|
||||
|
||||
// reset back
|
||||
console.IsExited = false
|
||||
|
||||
err = app.Run([]string{os.Args[0], "session", "clear", "invalid"})
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(console.IsExited, Equals, true)
|
||||
|
||||
// reset back
|
||||
console.IsExited = false
|
||||
|
||||
perr := createSessionDir()
|
||||
c.Assert(perr, IsNil)
|
||||
c.Assert(isSessionDirExists(), Equals, true)
|
||||
|
||||
// reset back
|
||||
console.IsExited = false
|
||||
|
||||
session := newSessionV2()
|
||||
c.Assert(session.Header.CommandArgs, IsNil)
|
||||
c.Assert(len(session.SessionID), Equals, 8)
|
||||
|
||||
perr = session.Save()
|
||||
c.Assert(perr, IsNil)
|
||||
|
||||
c.Assert(session.Close(), IsNil)
|
||||
|
||||
err = app.Run([]string{os.Args[0], "session", "clear", session.SessionID})
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(console.IsExited, Equals, false)
|
||||
|
||||
// reset back
|
||||
console.IsExited = false
|
||||
}
|
||||
|
||||
+134
@@ -0,0 +1,134 @@
|
||||
/*
|
||||
* Minio Client (C) 2014, 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/minio-xl/pkg/quick"
|
||||
)
|
||||
|
||||
// shareEntryV1 - container for each download/upload entries.
|
||||
type shareEntryV1 struct {
|
||||
URL string `json:"share"` // Object URL.
|
||||
Date time.Time `json:"date"`
|
||||
Expiry time.Duration `json:"expiry"`
|
||||
ContentType string `json:"contentType,omitempty"` // Only used by upload cmd.
|
||||
}
|
||||
|
||||
// JSON file to persist previously shared uploads.
|
||||
type shareDBV1 struct {
|
||||
Version string `json:"version"`
|
||||
mutex *sync.Mutex
|
||||
|
||||
// key is unique share URL.
|
||||
Shares map[string]shareEntryV1 `json:"shares"`
|
||||
}
|
||||
|
||||
// Instantiate a new uploads structure for persistence.
|
||||
func newShareDBV1() *shareDBV1 {
|
||||
s := &shareDBV1{
|
||||
Version: "1",
|
||||
}
|
||||
s.Shares = make(map[string]shareEntryV1)
|
||||
s.mutex = &sync.Mutex{}
|
||||
return s
|
||||
}
|
||||
|
||||
// Set upload info for each share.
|
||||
func (s *shareDBV1) Set(objectURL string, shareURL string, expiry time.Duration, contentType string) {
|
||||
s.mutex.Lock()
|
||||
defer s.mutex.Unlock()
|
||||
|
||||
s.Shares[shareURL] = shareEntryV1{
|
||||
URL: objectURL,
|
||||
Date: time.Now().UTC(),
|
||||
Expiry: expiry,
|
||||
ContentType: contentType,
|
||||
}
|
||||
}
|
||||
|
||||
// Delete upload info if it exists.
|
||||
func (s *shareDBV1) Delete(objectURL string) {
|
||||
s.mutex.Lock()
|
||||
defer s.mutex.Unlock()
|
||||
|
||||
delete(s.Shares, objectURL)
|
||||
}
|
||||
|
||||
// Delete all expired uploads.
|
||||
func (s *shareDBV1) deleteAllExpired() {
|
||||
for shareURL, share := range s.Shares {
|
||||
if (share.Expiry - time.Since(share.Date)) <= 0 {
|
||||
// Expired entry. Safe to drop.
|
||||
delete(s.Shares, shareURL)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Load shareDB entries from disk. Any entries held in memory are reset.
|
||||
func (s *shareDBV1) Load(filename string) *probe.Error {
|
||||
s.mutex.Lock()
|
||||
defer s.mutex.Unlock()
|
||||
|
||||
// Check if the db file exist.
|
||||
if _, e := os.Stat(filename); e != nil {
|
||||
return probe.NewError(e)
|
||||
}
|
||||
|
||||
// Initialize and load using quick package.
|
||||
qs, err := quick.New(newShareDBV1())
|
||||
if err != nil {
|
||||
return err.Trace(filename)
|
||||
}
|
||||
err = qs.Load(filename)
|
||||
if err != nil {
|
||||
return err.Trace(filename)
|
||||
}
|
||||
|
||||
// Copy map over.
|
||||
for k, v := range qs.Data().(*shareDBV1).Shares {
|
||||
s.Shares[k] = v
|
||||
}
|
||||
|
||||
// Filter out expired entries and save changes back to disk.
|
||||
s.deleteAllExpired()
|
||||
s.save(filename)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Persist share uploads to disk.
|
||||
func (s shareDBV1) save(filename string) *probe.Error {
|
||||
// Initialize a new quick file.
|
||||
qs, err := quick.New(s)
|
||||
if err != nil {
|
||||
return err.Trace(filename)
|
||||
}
|
||||
return qs.Save(filename).Trace(filename)
|
||||
}
|
||||
|
||||
// Persist share uploads to disk.
|
||||
func (s shareDBV1) Save(filename string) *probe.Error {
|
||||
s.mutex.Lock()
|
||||
defer s.mutex.Unlock()
|
||||
|
||||
return s.save(filename)
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
/*
|
||||
* Minio Client (C) 2014, 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
)
|
||||
|
||||
var (
|
||||
shareDownloadFlags = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "help, h",
|
||||
Usage: "Help of share download",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "recursive, r",
|
||||
Usage: "Share all objects recursively.",
|
||||
},
|
||||
shareFlagExpire,
|
||||
}
|
||||
)
|
||||
|
||||
// Share documents via URL.
|
||||
var shareDownload = cli.Command{
|
||||
Name: "download",
|
||||
Usage: "Generate URLs for download access.",
|
||||
Action: mainShareDownload,
|
||||
Flags: append(shareDownloadFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
mc share {{.Name}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
mc share {{.Name}} [OPTIONS] TARGET [TARGET...]
|
||||
|
||||
OPTIONS:
|
||||
{{range .Flags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Share this object with 7 days default expiry.
|
||||
$ mc share {{.Name}} s3/backup/2006-Mar-1/backup.tar.gz
|
||||
|
||||
2. Share this object with 10 minutes expiry.
|
||||
$ mc share {{.Name}} --expire=10m s3/backup/2006-Mar-1/backup.tar.gz
|
||||
|
||||
3. Share all objects under this folder with 5 days expiry.
|
||||
$ mc share {{.Name}} --expire=120h s3/backup/
|
||||
|
||||
4. Share all objects under this folder and all its sub-folders with 5 days expiry.
|
||||
$ mc share {{.Name}} --recursive --expire=120h s3/backup/
|
||||
`,
|
||||
}
|
||||
|
||||
// checkShareDownloadSyntax - validate command-line args.
|
||||
func checkShareDownloadSyntax(ctx *cli.Context) {
|
||||
args := ctx.Args()
|
||||
if !args.Present() {
|
||||
cli.ShowCommandHelpAndExit(ctx, "download", 1) // last argument is exit code.
|
||||
}
|
||||
|
||||
// Parse expiry.
|
||||
expiry := shareDefaultExpiry
|
||||
expireArg := ctx.String("expire")
|
||||
if expireArg != "" {
|
||||
var e error
|
||||
expiry, e = time.ParseDuration(expireArg)
|
||||
fatalIf(probe.NewError(e), "Unable to parse expire=‘"+expireArg+"’.")
|
||||
}
|
||||
|
||||
// Validate expiry.
|
||||
if expiry.Seconds() < 1 {
|
||||
fatalIf(errDummy().Trace(expiry.String()), "Expiry cannot be lesser than 1 second.")
|
||||
}
|
||||
if expiry.Seconds() > 604800 {
|
||||
fatalIf(errDummy().Trace(expiry.String()), "Expiry cannot be larger than 7 days.")
|
||||
}
|
||||
|
||||
for _, url := range ctx.Args() {
|
||||
_, _, err := url2Stat(url)
|
||||
fatalIf(err.Trace(url), "Unable to stat ‘"+url+"’.")
|
||||
}
|
||||
}
|
||||
|
||||
// doShareURL share files from target.
|
||||
func doShareDownloadURL(targetURL string, isRecursive bool, expiry time.Duration) *probe.Error {
|
||||
targetAlias, targetURLFull, _, err := expandAlias(targetURL)
|
||||
if err != nil {
|
||||
return err.Trace(targetURL)
|
||||
}
|
||||
clnt, err := newClientFromAlias(targetAlias, targetURLFull)
|
||||
if err != nil {
|
||||
return err.Trace(targetURL)
|
||||
}
|
||||
|
||||
// Load previously saved upload-shares. Add new entries and write it back.
|
||||
shareDB := newShareDBV1()
|
||||
shareDownloadsFile := getShareDownloadsFile()
|
||||
err = shareDB.Load(shareDownloadsFile)
|
||||
if err != nil {
|
||||
return err.Trace(shareDownloadsFile)
|
||||
}
|
||||
|
||||
// Generate share URL for each target.
|
||||
incomplete := false
|
||||
for content := range clnt.List(isRecursive, incomplete) {
|
||||
if content.Err != nil {
|
||||
return content.Err.Trace(clnt.GetURL().String())
|
||||
}
|
||||
// if any incoming directories, we don't need to calculate.
|
||||
if content.Type.IsDir() {
|
||||
continue
|
||||
}
|
||||
objectURL := content.URL.String()
|
||||
newClnt, err := newClientFromAlias(targetAlias, objectURL)
|
||||
if err != nil {
|
||||
return err.Trace(objectURL)
|
||||
}
|
||||
|
||||
// Generate share URL.
|
||||
shareURL, err := newClnt.ShareDownload(expiry)
|
||||
if err != nil {
|
||||
// add objectURL and expiry as part of the trace arguments.
|
||||
return err.Trace(objectURL, "expiry="+expiry.String())
|
||||
}
|
||||
|
||||
// Make new entries to shareDB.
|
||||
contentType := "" // Not useful for download shares.
|
||||
shareDB.Set(objectURL, shareURL, expiry, contentType)
|
||||
printMsg(shareMesssage{
|
||||
ObjectURL: objectURL,
|
||||
ShareURL: shareURL,
|
||||
TimeLeft: expiry,
|
||||
ContentType: contentType,
|
||||
})
|
||||
}
|
||||
|
||||
// Save downloads and return.
|
||||
return shareDB.Save(shareDownloadsFile)
|
||||
}
|
||||
|
||||
// main for share download.
|
||||
func mainShareDownload(ctx *cli.Context) {
|
||||
// Set global flags from context.
|
||||
setGlobalsFromContext(ctx)
|
||||
|
||||
// check input arguments.
|
||||
checkShareDownloadSyntax(ctx)
|
||||
|
||||
// Initialize share config folder.
|
||||
initShareConfig()
|
||||
|
||||
// Additional command speific theme customization.
|
||||
shareSetColor()
|
||||
|
||||
// Set command flags from context.
|
||||
isRecursive := ctx.Bool("recursive")
|
||||
expiry := shareDefaultExpiry
|
||||
if ctx.String("expire") != "" {
|
||||
var e error
|
||||
expiry, e = time.ParseDuration(ctx.String("expire"))
|
||||
fatalIf(probe.NewError(e), "Unable to parse expire=‘"+ctx.String("expire")+"’.")
|
||||
}
|
||||
|
||||
for _, targetURL := range ctx.Args() {
|
||||
err := doShareDownloadURL(targetURL, isRecursive, expiry)
|
||||
fatalIf(err.Trace(targetURL), "Unable to share target ‘"+targetURL+"’.")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
/*
|
||||
* Minio Client (C) 2014, 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
)
|
||||
|
||||
var (
|
||||
shareListFlags = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "help, h",
|
||||
Usage: "Help of share list.",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
// Share documents via URL.
|
||||
var shareList = cli.Command{
|
||||
Name: "list",
|
||||
Usage: "List previously shared objects and folders.",
|
||||
Action: mainShareList,
|
||||
Flags: append(shareListFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
mc share {{.Name}} COMMAND - {{.Usage}}
|
||||
|
||||
COMMAND:
|
||||
upload: list previously shared access to uploads.
|
||||
download: list previously shared access to downloads.
|
||||
|
||||
USAGE:
|
||||
mc share {{.Name}}
|
||||
|
||||
EXAMPLES:
|
||||
1. List previously shared downloads, that haven't expired yet.
|
||||
$ mc share {{.Name}} download
|
||||
2. List previously shared uploads, that haven't expired yet.
|
||||
$ mc share {{.Name}} upload
|
||||
`,
|
||||
}
|
||||
|
||||
// validate command-line args.
|
||||
func checkShareListSyntax(ctx *cli.Context) {
|
||||
args := ctx.Args()
|
||||
if !args.Present() || (args.First() != "upload" && args.First() != "download") {
|
||||
cli.ShowCommandHelpAndExit(ctx, "list", 1) // last argument is exit code.
|
||||
}
|
||||
}
|
||||
|
||||
// doShareList list shared url's.
|
||||
func doShareList(cmd string) *probe.Error {
|
||||
if cmd != "upload" && cmd != "download" {
|
||||
return probe.NewError(fmt.Errorf("Unknown argument ‘%s’ passed.", cmd))
|
||||
}
|
||||
|
||||
// Fetch defaults.
|
||||
uploadsFile := getShareUploadsFile()
|
||||
downloadsFile := getShareDownloadsFile()
|
||||
|
||||
// Load previously saved upload-shares.
|
||||
shareDB := newShareDBV1()
|
||||
|
||||
// if upload - read uploads file.
|
||||
if cmd == "upload" {
|
||||
if err := shareDB.Load(uploadsFile); err != nil {
|
||||
return err.Trace(uploadsFile)
|
||||
}
|
||||
}
|
||||
|
||||
// if download - read downloads file.
|
||||
if cmd == "download" {
|
||||
if err := shareDB.Load(downloadsFile); err != nil {
|
||||
return err.Trace(downloadsFile)
|
||||
}
|
||||
}
|
||||
|
||||
// Print previously shared entries.
|
||||
for shareURL, share := range shareDB.Shares {
|
||||
printMsg(shareMesssage{
|
||||
ObjectURL: share.URL,
|
||||
ShareURL: shareURL,
|
||||
TimeLeft: share.Expiry - time.Since(share.Date),
|
||||
ContentType: share.ContentType,
|
||||
})
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// main entry point for share list.
|
||||
func mainShareList(ctx *cli.Context) {
|
||||
// Set global flags from context.
|
||||
setGlobalsFromContext(ctx)
|
||||
|
||||
// validate command-line args.
|
||||
checkShareListSyntax(ctx)
|
||||
|
||||
// Additional command speific theme customization.
|
||||
shareSetColor()
|
||||
|
||||
// Initialize share config folder.
|
||||
initShareConfig()
|
||||
|
||||
// List shares.
|
||||
fatalIf(doShareList(ctx.Args().First()).Trace(), "Unable to list previously shared URLs.")
|
||||
}
|
||||
+45
-239
@@ -17,269 +17,75 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/client"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
)
|
||||
|
||||
var (
|
||||
shareFlags = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "help, h",
|
||||
Usage: "Help of share.",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
// Share documents via URL.
|
||||
var shareCmd = cli.Command{
|
||||
Name: "share",
|
||||
Usage: "Share documents via URL.",
|
||||
Usage: "Generate URL for sharing.",
|
||||
Action: mainShare,
|
||||
Flags: append(shareFlags, globalFlags...),
|
||||
Subcommands: []cli.Command{
|
||||
shareDownload,
|
||||
shareUpload,
|
||||
shareList,
|
||||
},
|
||||
CustomHelpTemplate: `NAME:
|
||||
mc {{.Name}} - {{.Usage}}
|
||||
{{.Name}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
mc {{.Name}} TARGET [DURATION]
|
||||
|
||||
DURATION = NN[h|m|s] [DEFAULT=168h]
|
||||
|
||||
EXAMPLES:
|
||||
1. Generate URL for sharing, with a default expiry of 7 days.
|
||||
$ mc {{.Name}} https://s3.amazonaws.com/backup/2006-Mar-1/backup.tar.gz
|
||||
|
||||
2. Generate URL for sharing, with an expiry of 10 minutes.
|
||||
$ mc {{.Name}} https://s3.amazonaws.com/backup/2006-Mar-1/backup.tar.gz 10m
|
||||
|
||||
3. Generate list of URLs for sharing a folder recursively, with expiration of 5 days each.
|
||||
$ mc {{.Name}} https://s3.amazonaws.com/backup... 120h
|
||||
|
||||
4. Generate URL with space characters for sharing, with an expiry of 5 seconds.
|
||||
$ mc {{.Name}} s3/miniocloud/nothing-like-anything 5s
|
||||
|
||||
5. List all the shared URLs which have not expired yet.
|
||||
$ mc {{.Name}} list
|
||||
{{.Name}} [FLAGS] COMMAND
|
||||
|
||||
FLAGS:
|
||||
{{range .Flags}}{{.}}
|
||||
{{end}}
|
||||
COMMANDS:
|
||||
{{range .Commands}}{{join .Names ", "}}{{ "\t" }}{{.Usage}}
|
||||
{{end}}
|
||||
`,
|
||||
}
|
||||
|
||||
// ShareMessage is container for share command on success and failure messages
|
||||
type ShareMessage struct {
|
||||
Expiry time.Duration `json:"expiry"`
|
||||
URL string `json:"url"`
|
||||
Key string `json:"keyName"`
|
||||
}
|
||||
|
||||
// String - regular colorized message
|
||||
func (s ShareMessage) String() string {
|
||||
return console.Colorize("Share", fmt.Sprintf("Expiry: %s\n URL: %s\n Key: %s", timeDurationToHumanizedTime(s.Expiry), s.URL, s.Key))
|
||||
}
|
||||
|
||||
// JSON json message for share command
|
||||
func (s ShareMessage) JSON() string {
|
||||
shareMessageBytes, err := json.Marshal(struct {
|
||||
Expiry humanizedTime `json:"expiry"`
|
||||
URL string `json:"url"`
|
||||
Key string `json:"keyName"`
|
||||
}{
|
||||
Expiry: timeDurationToHumanizedTime(s.Expiry),
|
||||
URL: s.URL,
|
||||
Key: s.Key,
|
||||
})
|
||||
fatalIf(probe.NewError(err), "Failed to marshal into JSON.")
|
||||
|
||||
// json encoding escapes ampersand into its unicode character which is not usable directly for share
|
||||
// and fails with cloud storage. convert them back so that they are usable
|
||||
shareMessageBytes = bytes.Replace(shareMessageBytes, []byte("\\u0026"), []byte("&"), -1)
|
||||
return string(shareMessageBytes)
|
||||
}
|
||||
|
||||
// migrateSharedURLs migrate to newest version sequentially
|
||||
func migrateSharedURLs() {
|
||||
migrateSharedURLsV1ToV2()
|
||||
}
|
||||
|
||||
func checkShareSyntax(ctx *cli.Context) {
|
||||
if !ctx.Args().Present() || ctx.Args().First() == "help" || len(ctx.Args()) > 2 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "share", 1) // last argument is exit code
|
||||
}
|
||||
if len(ctx.Args()) > 2 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "share", 1) // last argument is exit code
|
||||
}
|
||||
if ctx.Args().Get(0) == "list" {
|
||||
if len(ctx.Args()) >= 2 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "share", 1) // last argument is exit code
|
||||
}
|
||||
}
|
||||
if strings.TrimSpace(ctx.Args().Get(0)) == "" {
|
||||
fatalIf(errInvalidArgument().Trace(), "Unable to validate empty argument.")
|
||||
}
|
||||
}
|
||||
|
||||
// mainShare - is a handler for mc share command
|
||||
func mainShare(ctx *cli.Context) {
|
||||
checkShareSyntax(ctx)
|
||||
|
||||
if !isSharedURLsDataDirExists() {
|
||||
shareDir, err := getSharedURLsDataDir()
|
||||
fatalIf(err.Trace(), "Unable to get shared URL data directory")
|
||||
|
||||
fatalIf(createSharedURLsDataDir().Trace(), "Unable to create shared URL data directory ‘"+shareDir+"’.")
|
||||
}
|
||||
if !isSharedURLsDataFileExists() {
|
||||
shareFile, err := getSharedURLsDataFile()
|
||||
fatalIf(err.Trace(), "Unable to get shared URL data file")
|
||||
|
||||
fatalIf(createSharedURLsDataFile().Trace(), "Unable to create shared URL data file ‘"+shareFile+"’.")
|
||||
}
|
||||
|
||||
console.SetCustomTheme(map[string]*color.Color{
|
||||
"Share": color.New(color.FgGreen, color.Bold),
|
||||
"Expires": color.New(color.FgRed, color.Bold),
|
||||
"URL": color.New(color.FgCyan, color.Bold),
|
||||
})
|
||||
|
||||
args := ctx.Args()
|
||||
config := mustGetMcConfig()
|
||||
|
||||
// if its only list, return quickly
|
||||
if args.Get(0) == "list" {
|
||||
err := doShareList()
|
||||
fatalIf(err.Trace(), "Unable to list shared URLs.")
|
||||
// migrateShare migrate to newest version sequentially.
|
||||
func migrateShare() {
|
||||
if !isShareDirExists() {
|
||||
return
|
||||
}
|
||||
|
||||
/// get first and last arguments
|
||||
url := args.Get(0) // url to be shared
|
||||
// default expiration is 7days
|
||||
expires := time.Duration(604800) * time.Second
|
||||
if len(args) == 2 {
|
||||
var err error
|
||||
expires, err = time.ParseDuration(args.Get(1))
|
||||
fatalIf(probe.NewError(err), "Unable to parse time argument.")
|
||||
// Shared URLs are now managed by sub-commands. So delete any old URLs file if found.
|
||||
oldShareFile := filepath.Join(mustGetShareDir(), "urls.json")
|
||||
if _, e := os.Stat(oldShareFile); e == nil {
|
||||
// Old file exits.
|
||||
e := os.Remove(oldShareFile)
|
||||
fatalIf(probe.NewError(e), "Unable to delete old ‘"+oldShareFile+"’.")
|
||||
console.Infof("Removed older version of share ‘%s’ file.\n", oldShareFile)
|
||||
}
|
||||
|
||||
targetURL := getAliasURL(url, config.Aliases)
|
||||
|
||||
// if recursive strip off the "..."
|
||||
err := doShareURL(stripRecursiveURL(targetURL), isURLRecursive(targetURL), expires)
|
||||
fatalIf(err.Trace(targetURL), "Unable to generate URL for sharing.")
|
||||
}
|
||||
|
||||
// doShareList list shared url's
|
||||
func doShareList() *probe.Error {
|
||||
sURLs, err := loadSharedURLsV2()
|
||||
if err != nil {
|
||||
return err.Trace()
|
||||
}
|
||||
for i, data := range sURLs.URLs {
|
||||
if time.Since(data.Date) > data.Message.Expiry {
|
||||
sURLs.URLs = append(sURLs.URLs[:i], sURLs.URLs[i+1:]...)
|
||||
continue
|
||||
}
|
||||
expiry := data.Message.Expiry - time.Since(data.Date)
|
||||
if !globalJSONFlag {
|
||||
msg := console.Colorize("Share", "Name: ")
|
||||
msg += console.Colorize("URL", data.Message.Key+"\n")
|
||||
msg += console.Colorize("Share", "Expiry: ")
|
||||
msg += console.Colorize("Expires", timeDurationToHumanizedTime(expiry))
|
||||
msg += "\n"
|
||||
console.Println(msg)
|
||||
continue
|
||||
}
|
||||
shareListBytes, err := json.Marshal(struct {
|
||||
Expiry humanizedTime `json:"expiry"`
|
||||
URL string `json:"url"`
|
||||
Key string `json:"keyName"`
|
||||
}{
|
||||
Expiry: timeDurationToHumanizedTime(expiry),
|
||||
URL: data.Message.URL,
|
||||
Key: data.Message.Key,
|
||||
})
|
||||
if err != nil {
|
||||
return probe.NewError(err)
|
||||
}
|
||||
console.Println(string(shareListBytes))
|
||||
}
|
||||
if err := saveSharedURLsV2(sURLs); err != nil {
|
||||
return err.Trace()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
// mainShare - main handler for mc share command.
|
||||
func mainShare(ctx *cli.Context) {
|
||||
// Set global flags from context.
|
||||
setGlobalsFromContext(ctx)
|
||||
|
||||
// doShareURL share files from target
|
||||
func doShareURL(targetURL string, recursive bool, expires time.Duration) *probe.Error {
|
||||
shareDate := time.Now().UTC()
|
||||
sURLs, err := loadSharedURLsV2()
|
||||
if err != nil {
|
||||
return err.Trace()
|
||||
if ctx.Args().First() != "" { // command help.
|
||||
cli.ShowCommandHelp(ctx, ctx.Args().First())
|
||||
} else { // mc help.
|
||||
cli.ShowAppHelp(ctx)
|
||||
}
|
||||
|
||||
var clnt client.Client
|
||||
clnt, err = target2Client(targetURL)
|
||||
if err != nil {
|
||||
return err.Trace()
|
||||
}
|
||||
if expires.Seconds() < 1 {
|
||||
return probe.NewError(errors.New("Too low expires, expiration cannot be less than 1 second."))
|
||||
}
|
||||
if expires.Seconds() > 604800 {
|
||||
return probe.NewError(errors.New("Too high expires, expiration cannot be larger than 7 days."))
|
||||
}
|
||||
for contentCh := range clnt.List(recursive) {
|
||||
if contentCh.Err != nil {
|
||||
return contentCh.Err.Trace()
|
||||
}
|
||||
var newClnt client.Client
|
||||
newClnt, err = url2Client(getNewTargetURL(clnt.URL(), contentCh.Content.Name))
|
||||
if err != nil {
|
||||
return err.Trace()
|
||||
}
|
||||
var sharedURL string
|
||||
sharedURL, err = newClnt.Share(expires)
|
||||
if err != nil {
|
||||
return err.Trace()
|
||||
}
|
||||
shareMessage := ShareMessage{
|
||||
Expiry: expires,
|
||||
URL: sharedURL,
|
||||
Key: newClnt.URL().String(),
|
||||
}
|
||||
sURLs.URLs = append(sURLs.URLs, struct {
|
||||
Date time.Time
|
||||
Message ShareMessage
|
||||
}{
|
||||
Date: shareDate,
|
||||
Message: shareMessage,
|
||||
})
|
||||
Prints("%s\n", shareMessage)
|
||||
}
|
||||
saveSharedURLsV2(sURLs)
|
||||
return nil
|
||||
}
|
||||
|
||||
func getNewTargetURL(targetParser *client.URL, name string) string {
|
||||
match, _ := filepath.Match("*.s3*.amazonaws.com", targetParser.Host)
|
||||
if match {
|
||||
targetParser.Path = string(targetParser.Separator) + name
|
||||
} else {
|
||||
targetParser.Path = string(targetParser.Separator) + path2Bucket(targetParser) + string(targetParser.Separator) + name
|
||||
}
|
||||
return targetParser.String()
|
||||
}
|
||||
|
||||
// this code is necessary since, share only operates on cloud storage URLs not filesystem
|
||||
func path2Bucket(u *client.URL) (bucketName string) {
|
||||
pathSplits := strings.SplitN(u.Path, "?", 2)
|
||||
splits := strings.SplitN(pathSplits[0], string(u.Separator), 3)
|
||||
switch len(splits) {
|
||||
case 0, 1:
|
||||
bucketName = ""
|
||||
case 2:
|
||||
bucketName = splits[1]
|
||||
case 3:
|
||||
bucketName = splits[1]
|
||||
}
|
||||
return bucketName
|
||||
// Sub-commands like "upload" and "download" have their own main.
|
||||
}
|
||||
|
||||
@@ -0,0 +1,212 @@
|
||||
/*
|
||||
* Minio Client (C) 2014, 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/client"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
)
|
||||
|
||||
var (
|
||||
shareUploadFlags = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "help, h",
|
||||
Usage: "Help of share download.",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "recursive, r",
|
||||
Usage: "Recursively upload any object matching the prefix.",
|
||||
},
|
||||
shareFlagExpire,
|
||||
shareFlagContentType,
|
||||
}
|
||||
)
|
||||
|
||||
// Share documents via URL.
|
||||
var shareUpload = cli.Command{
|
||||
Name: "upload",
|
||||
Usage: "Generate ‘curl’ command to upload objects without requiring access/secret keys.",
|
||||
Action: mainShareUpload,
|
||||
Flags: append(shareUploadFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
mc share {{.Name}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
mc share {{.Name}} [OPTIONS] TARGET [TARGET...]
|
||||
|
||||
OPTIONS:
|
||||
{{range .Flags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Generate a curl command to allow upload access for a single object. Command expires in 7 days (default).
|
||||
$ mc share {{.Name}} s3/backup/2006-Mar-1/backup.tar.gz
|
||||
|
||||
2. Generate a curl command to allow upload access to a folder. Command expires in 120 hours.
|
||||
$ mc share {{.Name}} --expire=120h s3/backup/2007-Mar-2/
|
||||
|
||||
3. Generate a curl command to allow upload access of only '.png' images to a folder. Command expires in 2 hours.
|
||||
$ mc share {{.Name}} --expire=2h --content-type=image/png s3/backup/2007-Mar-2/
|
||||
|
||||
4. Generate a curl command to allow upload access to any objects matching the key prefix 'backup/'. Command expires in 2 hours.
|
||||
$ mc share {{.Name}} --recursive --expire=2h s3/backup/2007-Mar-2/backup/
|
||||
`,
|
||||
}
|
||||
|
||||
// checkShareUploadSyntax - validate command-line args.
|
||||
func checkShareUploadSyntax(ctx *cli.Context) {
|
||||
args := ctx.Args()
|
||||
if !args.Present() {
|
||||
cli.ShowCommandHelpAndExit(ctx, "upload", 1) // last argument is exit code.
|
||||
}
|
||||
|
||||
// Set command flags from context.
|
||||
isRecursive := ctx.Bool("recursive")
|
||||
expireArg := ctx.String("expire")
|
||||
|
||||
// Parse expiry.
|
||||
expiry := shareDefaultExpiry
|
||||
if expireArg != "" {
|
||||
var e error
|
||||
expiry, e = time.ParseDuration(expireArg)
|
||||
fatalIf(probe.NewError(e), "Unable to parse expire=‘"+expireArg+"’.")
|
||||
}
|
||||
|
||||
// Validate expiry.
|
||||
if expiry.Seconds() < 1 {
|
||||
fatalIf(errDummy().Trace(expiry.String()),
|
||||
"Expiry cannot be lesser than 1 second.")
|
||||
}
|
||||
if expiry.Seconds() > 604800 {
|
||||
fatalIf(errDummy().Trace(expiry.String()),
|
||||
"Expiry cannot be larger than 7 days.")
|
||||
}
|
||||
|
||||
for _, targetURL := range ctx.Args() {
|
||||
url := client.NewURL(targetURL)
|
||||
if strings.HasSuffix(targetURL, string(url.Separator)) && !isRecursive {
|
||||
fatalIf(errInvalidArgument().Trace(targetURL),
|
||||
"Use --recursive option to generate curl command for prefixes.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// makeCurlCmd constructs curl command-line.
|
||||
func makeCurlCmd(key string, isRecursive bool, uploadInfo map[string]string) string {
|
||||
URL := client.NewURL(key)
|
||||
postURL := URL.Scheme + URL.SchemeSeparator + URL.Host + string(URL.Separator)
|
||||
if !isBucketVirtualStyle(URL.Host) {
|
||||
postURL = postURL + uploadInfo["bucket"]
|
||||
}
|
||||
postURL += " "
|
||||
curlCommand := "curl " + postURL
|
||||
for k, v := range uploadInfo {
|
||||
if k == "key" {
|
||||
key = v
|
||||
continue
|
||||
}
|
||||
curlCommand += fmt.Sprintf("-F %s=%s ", k, v)
|
||||
}
|
||||
// If key starts with is enabled prefix it with the output.
|
||||
if isRecursive {
|
||||
curlCommand += fmt.Sprintf("-F key=%s<NAME> ", key) // Object name.
|
||||
} else {
|
||||
curlCommand += fmt.Sprintf("-F key=%s ", key) // Object name.
|
||||
}
|
||||
curlCommand += "-F file=@<FILE>" // File to upload.
|
||||
return curlCommand
|
||||
}
|
||||
|
||||
// save shared URL to disk.
|
||||
func saveSharedURL(objectURL string, shareURL string, expiry time.Duration, contentType string) *probe.Error {
|
||||
// Load previously saved upload-shares.
|
||||
shareDB := newShareDBV1()
|
||||
if err := shareDB.Load(getShareUploadsFile()); err != nil {
|
||||
return err.Trace(getShareUploadsFile())
|
||||
}
|
||||
|
||||
// Make new entries to uploadsDB.
|
||||
shareDB.Set(objectURL, shareURL, expiry, contentType)
|
||||
shareDB.Save(getShareUploadsFile())
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// doShareUploadURL uploads files to the target.
|
||||
func doShareUploadURL(objectURL string, isRecursive bool, expiry time.Duration, contentType string) *probe.Error {
|
||||
clnt, err := newClient(objectURL)
|
||||
if err != nil {
|
||||
return err.Trace(objectURL)
|
||||
}
|
||||
|
||||
// Generate pre-signed access info.
|
||||
uploadInfo, err := clnt.ShareUpload(isRecursive, expiry, contentType)
|
||||
if err != nil {
|
||||
return err.Trace(objectURL, "expiry="+expiry.String(), "contentType="+contentType)
|
||||
}
|
||||
|
||||
// Get the new expanded url.
|
||||
objectURL = clnt.GetURL().String()
|
||||
|
||||
// Generate curl command.
|
||||
curlCmd := makeCurlCmd(objectURL, isRecursive, uploadInfo)
|
||||
|
||||
printMsg(shareMesssage{
|
||||
ObjectURL: objectURL,
|
||||
ShareURL: curlCmd,
|
||||
TimeLeft: expiry,
|
||||
ContentType: contentType,
|
||||
})
|
||||
|
||||
// save shared URL to disk.
|
||||
return saveSharedURL(objectURL, curlCmd, expiry, contentType)
|
||||
}
|
||||
|
||||
// main for share upload command.
|
||||
func mainShareUpload(ctx *cli.Context) {
|
||||
// Set global flags from context.
|
||||
setGlobalsFromContext(ctx)
|
||||
|
||||
// check input arguments.
|
||||
checkShareUploadSyntax(ctx)
|
||||
|
||||
// Initialize share config folder.
|
||||
initShareConfig()
|
||||
|
||||
// Additional command speific theme customization.
|
||||
shareSetColor()
|
||||
|
||||
// Set command flags from context.
|
||||
isRecursive := ctx.Bool("recursive")
|
||||
expireArg := ctx.String("expire")
|
||||
expiry := shareDefaultExpiry
|
||||
contentType := ctx.String("content-type")
|
||||
if expireArg != "" {
|
||||
var e error
|
||||
expiry, e = time.ParseDuration(expireArg)
|
||||
fatalIf(probe.NewError(e), "Unable to parse expire=‘"+expireArg+"’.")
|
||||
}
|
||||
|
||||
for _, targetURL := range ctx.Args() {
|
||||
err := doShareUploadURL(targetURL, isRecursive, expiry, contentType)
|
||||
fatalIf(err.Trace(targetURL), "Unable to generate curl command for upload ‘"+targetURL+"’.")
|
||||
}
|
||||
}
|
||||
-65
@@ -1,65 +0,0 @@
|
||||
/*
|
||||
* Minio Client (C) 2014, 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
"github.com/minio/minio/pkg/quick"
|
||||
)
|
||||
|
||||
type sharedURLsV1 struct {
|
||||
Version string
|
||||
URLs map[string]struct {
|
||||
Date time.Time
|
||||
Message ShareMessage
|
||||
}
|
||||
}
|
||||
|
||||
func loadSharedURLsV1() (*sharedURLsV1, *probe.Error) {
|
||||
sharedURLsDataFile, err := getSharedURLsDataFile()
|
||||
if err != nil {
|
||||
return nil, err.Trace()
|
||||
}
|
||||
if _, err := os.Stat(sharedURLsDataFile); err != nil {
|
||||
return nil, probe.NewError(err)
|
||||
}
|
||||
|
||||
qs, err := quick.New(newSharedURLsV1())
|
||||
if err != nil {
|
||||
return nil, err.Trace()
|
||||
}
|
||||
err = qs.Load(sharedURLsDataFile)
|
||||
if err != nil {
|
||||
return nil, err.Trace(sharedURLsDataFile)
|
||||
}
|
||||
s := qs.Data().(*sharedURLsV1)
|
||||
return s, nil
|
||||
}
|
||||
|
||||
func newSharedURLsV1() *sharedURLsV1 {
|
||||
s := &sharedURLsV1{
|
||||
Version: "1.0.0",
|
||||
URLs: make(map[string]struct {
|
||||
Date time.Time
|
||||
Message ShareMessage
|
||||
}),
|
||||
}
|
||||
return s
|
||||
}
|
||||
-78
@@ -1,78 +0,0 @@
|
||||
/*
|
||||
* Minio Client (C) 2014, 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
"github.com/minio/minio/pkg/quick"
|
||||
)
|
||||
|
||||
type sharedURLsV2 struct {
|
||||
Version string
|
||||
URLs []struct {
|
||||
Date time.Time
|
||||
Message ShareMessage
|
||||
}
|
||||
}
|
||||
|
||||
func loadSharedURLsV2() (*sharedURLsV2, *probe.Error) {
|
||||
sharedURLsDataFile, err := getSharedURLsDataFile()
|
||||
if err != nil {
|
||||
return nil, err.Trace()
|
||||
}
|
||||
if _, err := os.Stat(sharedURLsDataFile); err != nil {
|
||||
return nil, probe.NewError(err)
|
||||
}
|
||||
|
||||
qs, err := quick.New(newSharedURLsV2())
|
||||
if err != nil {
|
||||
return nil, err.Trace()
|
||||
}
|
||||
err = qs.Load(sharedURLsDataFile)
|
||||
if err != nil {
|
||||
return nil, err.Trace(sharedURLsDataFile)
|
||||
}
|
||||
s := qs.Data().(*sharedURLsV2)
|
||||
return s, nil
|
||||
}
|
||||
|
||||
func saveSharedURLsV2(s *sharedURLsV2) *probe.Error {
|
||||
qs, err := quick.New(s)
|
||||
if err != nil {
|
||||
return err.Trace()
|
||||
}
|
||||
sharedURLsDataFile, err := getSharedURLsDataFile()
|
||||
if err != nil {
|
||||
return err.Trace()
|
||||
}
|
||||
return qs.Save(sharedURLsDataFile).Trace(sharedURLsDataFile)
|
||||
}
|
||||
|
||||
func newSharedURLsV2() *sharedURLsV2 {
|
||||
var urls []struct {
|
||||
Date time.Time
|
||||
Message ShareMessage
|
||||
}
|
||||
s := &sharedURLsV2{
|
||||
Version: "1.1.0",
|
||||
URLs: urls,
|
||||
}
|
||||
return s
|
||||
}
|
||||
@@ -17,48 +17,93 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
)
|
||||
|
||||
func newSharedURLs() *sharedURLsV2 {
|
||||
return newSharedURLsV2()
|
||||
const (
|
||||
// Default expiry is 7 days (168h).
|
||||
shareDefaultExpiry = time.Duration(604800) * time.Second
|
||||
)
|
||||
|
||||
// Upload specific flags.
|
||||
var (
|
||||
shareFlagContentType = cli.StringFlag{
|
||||
Name: "content-type, T",
|
||||
Usage: "Speific content-type to allow.",
|
||||
}
|
||||
shareFlagExpire = cli.StringFlag{
|
||||
Name: "expire, E",
|
||||
Value: "168h",
|
||||
Usage: "Set expiry in NN[h|m|s].",
|
||||
}
|
||||
)
|
||||
|
||||
// Structured share command message.
|
||||
type shareMesssage struct {
|
||||
Status string `json:"status"`
|
||||
ObjectURL string `json:"url"`
|
||||
ShareURL string `json:"share"`
|
||||
TimeLeft time.Duration `json:"timeLeft"`
|
||||
ContentType string `json:"contentType,omitempty"` // Only used by upload cmd.
|
||||
}
|
||||
|
||||
func migrateSharedURLsV1ToV2() {
|
||||
if !isSharedURLsDataFileExists() {
|
||||
return
|
||||
// String - Themefied string message for console printing.
|
||||
func (s shareMesssage) String() string {
|
||||
msg := console.Colorize("URL", fmt.Sprintf("URL: %s\n", s.ObjectURL))
|
||||
msg += console.Colorize("Expire", fmt.Sprintf("Expire: %s\n", timeDurationToHumanizedTime(s.TimeLeft)))
|
||||
if s.ContentType != "" {
|
||||
msg += console.Colorize("Content-type", fmt.Sprintf("Content-Type: %s\n", s.ContentType))
|
||||
}
|
||||
|
||||
// try to load latest version if possible
|
||||
sURLsV2, err := loadSharedURLsV2()
|
||||
if err != nil {
|
||||
switch err.ToGoError().(type) {
|
||||
case *json.UnmarshalTypeError:
|
||||
// try to load V1 if possible
|
||||
var sURLsV1 *sharedURLsV1
|
||||
sURLsV1, err = loadSharedURLsV1()
|
||||
fatalIf(err.Trace(), "Unable to load shared url version ‘1.0.0’.")
|
||||
if sURLsV1.Version != "1.0.0" {
|
||||
fatalIf(errDummy().Trace(), "Invalid version loaded ‘"+sURLsV1.Version+"’.")
|
||||
}
|
||||
sURLsV2 = newSharedURLsV2()
|
||||
for key, value := range sURLsV1.URLs {
|
||||
value.Message.Key = key
|
||||
sURLsV2.URLs = append(sURLsV2.URLs, value)
|
||||
}
|
||||
err = saveSharedURLsV2(sURLsV2)
|
||||
fatalIf(err.Trace(), "Unable to save new shared url version ‘1.1.0’.")
|
||||
default:
|
||||
fatalIf(err.Trace(), "Unable to load shared url version ‘1.1.0’.")
|
||||
}
|
||||
}
|
||||
// Highlight <FILE> specifically. "share upload" sub-commands use this identifier.
|
||||
shareURL := strings.Replace(s.ShareURL, "<FILE>", console.Colorize("File", "<FILE>"), 1)
|
||||
// Highlight <KEY> specifically for recursive operation.
|
||||
shareURL = strings.Replace(shareURL, "<NAME>", console.Colorize("File", "<NAME>"), 1)
|
||||
|
||||
msg += console.Colorize("Share", fmt.Sprintf("Share: %s\n", shareURL))
|
||||
|
||||
return msg
|
||||
}
|
||||
|
||||
func getSharedURLsDataDir() (string, *probe.Error) {
|
||||
// JSON - JSONified message for scripting.
|
||||
func (s shareMesssage) JSON() string {
|
||||
s.Status = "success"
|
||||
shareMessageBytes, e := json.Marshal(s)
|
||||
fatalIf(probe.NewError(e), "Failed to marshal into JSON.")
|
||||
|
||||
// JSON encoding escapes ampersand into its unicode character
|
||||
// which is not usable directly for share and fails with cloud
|
||||
// storage. convert them back so that they are usable.
|
||||
shareMessageBytes = bytes.Replace(shareMessageBytes, []byte("\\u0026"), []byte("&"), -1)
|
||||
shareMessageBytes = bytes.Replace(shareMessageBytes, []byte("\\u003c"), []byte("<"), -1)
|
||||
shareMessageBytes = bytes.Replace(shareMessageBytes, []byte("\\u003e"), []byte(">"), -1)
|
||||
|
||||
return string(shareMessageBytes)
|
||||
}
|
||||
|
||||
// shareSetColor sets colors share sub-commands.
|
||||
func shareSetColor() {
|
||||
// Additional command speific theme customization.
|
||||
console.SetColor("URL", color.New(color.FgWhite, color.Bold))
|
||||
console.SetColor("Expire", color.New(color.FgCyan))
|
||||
console.SetColor("Content-type", color.New(color.FgBlue))
|
||||
console.SetColor("Share", color.New(color.FgGreen))
|
||||
console.SetColor("File", color.New(color.FgRed, color.Bold))
|
||||
}
|
||||
|
||||
// Get share dir name.
|
||||
func getShareDir() (string, *probe.Error) {
|
||||
configDir, err := getMcConfigDir()
|
||||
if err != nil {
|
||||
return "", err.Trace()
|
||||
@@ -68,51 +113,85 @@ func getSharedURLsDataDir() (string, *probe.Error) {
|
||||
return sharedURLsDataDir, nil
|
||||
}
|
||||
|
||||
func isSharedURLsDataDirExists() bool {
|
||||
shareDir, err := getSharedURLsDataDir()
|
||||
// Get share dir name or die. (NOTE: This ‘Die’ approach is only OK for mc like tools.).
|
||||
func mustGetShareDir() string {
|
||||
shareDir, err := getShareDir()
|
||||
fatalIf(err.Trace(), "Unable to determine share folder.")
|
||||
return shareDir
|
||||
}
|
||||
|
||||
if _, e := os.Stat(shareDir); e != nil {
|
||||
// Check if the share dir exists.
|
||||
func isShareDirExists() bool {
|
||||
if _, e := os.Stat(mustGetShareDir()); e != nil {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func createSharedURLsDataDir() *probe.Error {
|
||||
shareDir, err := getSharedURLsDataDir()
|
||||
if err != nil {
|
||||
return err.Trace()
|
||||
}
|
||||
|
||||
if err := os.MkdirAll(shareDir, 0700); err != nil {
|
||||
return probe.NewError(err)
|
||||
// Create config share dir.
|
||||
func createShareDir() *probe.Error {
|
||||
if e := os.MkdirAll(mustGetShareDir(), 0700); e != nil {
|
||||
return probe.NewError(e)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func getSharedURLsDataFile() (string, *probe.Error) {
|
||||
shareDir, err := getSharedURLsDataDir()
|
||||
if err != nil {
|
||||
return "", err.Trace()
|
||||
}
|
||||
|
||||
shareFile := filepath.Join(shareDir, "urls.json")
|
||||
return shareFile, nil
|
||||
// Get share uploads file.
|
||||
func getShareUploadsFile() string {
|
||||
return filepath.Join(mustGetShareDir(), "uploads.json")
|
||||
}
|
||||
|
||||
func isSharedURLsDataFileExists() bool {
|
||||
shareFile, err := getSharedURLsDataFile()
|
||||
fatalIf(err.Trace(), "Unable to determine share filename.")
|
||||
// Get share downloads file.
|
||||
func getShareDownloadsFile() string {
|
||||
return filepath.Join(mustGetShareDir(), "downloads.json")
|
||||
}
|
||||
|
||||
if _, e := os.Stat(shareFile); e != nil {
|
||||
// Check if share uploads file exists?.
|
||||
func isShareUploadsExists() bool {
|
||||
if _, e := os.Stat(getShareUploadsFile()); e != nil {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func createSharedURLsDataFile() *probe.Error {
|
||||
if err := saveSharedURLsV2(newSharedURLs()); err != nil {
|
||||
return err.Trace()
|
||||
// Check if share downloads file exists?.
|
||||
func isShareDownloadsExists() bool {
|
||||
if _, e := os.Stat(getShareDownloadsFile()); e != nil {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// Initialize share uploads file.
|
||||
func initShareUploadsFile() *probe.Error {
|
||||
return newShareDBV1().Save(getShareUploadsFile())
|
||||
}
|
||||
|
||||
// Initialize share downloads file.
|
||||
func initShareDownloadsFile() *probe.Error {
|
||||
return newShareDBV1().Save(getShareDownloadsFile())
|
||||
}
|
||||
|
||||
// Initialize share directory, if not done already.
|
||||
func initShareConfig() {
|
||||
// Share directory.
|
||||
if !isShareDirExists() {
|
||||
fatalIf(createShareDir().Trace(mustGetShareDir()),
|
||||
"Failed to create share ‘"+mustGetShareDir()+"’ folder.")
|
||||
console.Infof("Successfully created ‘%s’.\n", mustGetShareDir())
|
||||
}
|
||||
|
||||
// Uploads share file.
|
||||
if !isShareUploadsExists() {
|
||||
fatalIf(initShareUploadsFile().Trace(getShareUploadsFile()),
|
||||
"Failed to initialize share uploads ‘"+getShareUploadsFile()+"’ file.")
|
||||
console.Infof("Initialized share uploads ‘%s’ file.\n", getShareUploadsFile())
|
||||
}
|
||||
|
||||
// Downloads share file.
|
||||
if !isShareDownloadsExists() {
|
||||
fatalIf(initShareDownloadsFile().Trace(getShareDownloadsFile()),
|
||||
"Failed to initialize share downloads ‘"+getShareDownloadsFile()+"’ file.")
|
||||
console.Infof("Initialized share downloads ‘%s’ file.\n", getShareDownloadsFile())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
+3
-3
@@ -16,12 +16,12 @@
|
||||
|
||||
package main
|
||||
|
||||
// signalTrap traps the registered signals and notifies the caller.
|
||||
import (
|
||||
"os"
|
||||
"os/signal"
|
||||
)
|
||||
|
||||
// signalTrap traps the registered signals and notifies the caller.
|
||||
func signalTrap(sig ...os.Signal) <-chan bool {
|
||||
// channel to notify the caller.
|
||||
trapCh := make(chan bool, 1)
|
||||
@@ -35,10 +35,10 @@ func signalTrap(sig ...os.Signal) <-chan bool {
|
||||
// receive notifications of the specified signals.
|
||||
signal.Notify(sigCh, sig...)
|
||||
|
||||
// Wait for the signal
|
||||
// Wait for the signal.
|
||||
<-sigCh
|
||||
|
||||
// Notify the caller
|
||||
// Notify the caller.
|
||||
trapCh <- true
|
||||
}(trapCh)
|
||||
|
||||
|
||||
-167
@@ -1,167 +0,0 @@
|
||||
/*
|
||||
* Minio Client (C) 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/gob"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/minio/mc/pkg/client"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
type sortedList struct {
|
||||
name string
|
||||
file *os.File
|
||||
dec *gob.Decoder
|
||||
enc *gob.Encoder
|
||||
current client.Content
|
||||
}
|
||||
|
||||
func getSortedListDir() (string, *probe.Error) {
|
||||
configDir, err := getMcConfigDir()
|
||||
if err != nil {
|
||||
return "", err.Trace()
|
||||
}
|
||||
sortedListDir := filepath.Join(configDir, golbalSortedListDir)
|
||||
return sortedListDir, nil
|
||||
}
|
||||
|
||||
func createSortedListDir() *probe.Error {
|
||||
sortedListDir, err := getSortedListDir()
|
||||
if err != nil {
|
||||
return err.Trace()
|
||||
}
|
||||
if _, err := os.Stat(sortedListDir); err == nil {
|
||||
return nil
|
||||
}
|
||||
if err := os.MkdirAll(sortedListDir, 0700); err != nil {
|
||||
return probe.NewError(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Create create an on disk sorted file from clnt
|
||||
func (sl *sortedList) Create(clnt client.Client, id string) *probe.Error {
|
||||
var e error
|
||||
if err := createSortedListDir(); err != nil {
|
||||
return err.Trace()
|
||||
}
|
||||
sortedListDir, err := getSortedListDir()
|
||||
if err != nil {
|
||||
return err.Trace()
|
||||
}
|
||||
sl.name = filepath.Join(sortedListDir, id)
|
||||
sl.file, e = os.OpenFile(sl.name, os.O_CREATE|os.O_EXCL|os.O_RDWR, 0666)
|
||||
if e != nil {
|
||||
return probe.NewError(e)
|
||||
}
|
||||
sl.enc = gob.NewEncoder(sl.file)
|
||||
sl.dec = gob.NewDecoder(sl.file)
|
||||
for content := range clnt.List(true) {
|
||||
if content.Err != nil {
|
||||
switch err := content.Err.ToGoError().(type) {
|
||||
case client.ISBrokenSymlink:
|
||||
// FIXME: send the error to caller using channel
|
||||
errorIf(content.Err.Trace(), fmt.Sprintf("Skipping broken Symlink ‘%s’.", err.Path))
|
||||
continue
|
||||
}
|
||||
if os.IsNotExist(content.Err.ToGoError()) || os.IsPermission(content.Err.ToGoError()) {
|
||||
// FIXME: abstract this at fs.go layer
|
||||
if content.Content != nil {
|
||||
if content.Content.Type.IsDir() && (content.Content.Type&os.ModeSymlink == os.ModeSymlink) {
|
||||
continue
|
||||
}
|
||||
}
|
||||
errorIf(content.Err.Trace(), fmt.Sprintf("Skipping ‘%s’.", content.Content.Name))
|
||||
continue
|
||||
}
|
||||
return content.Err.Trace()
|
||||
}
|
||||
sl.enc.Encode(*content.Content)
|
||||
}
|
||||
if _, err := sl.file.Seek(0, os.SEEK_SET); err != nil {
|
||||
return probe.NewError(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// List list the entries from the sorted file
|
||||
func (sl sortedList) List(recursive bool) <-chan client.ContentOnChannel {
|
||||
ch := make(chan client.ContentOnChannel)
|
||||
go func() {
|
||||
defer close(ch)
|
||||
for {
|
||||
var c client.Content
|
||||
err := sl.dec.Decode(&c)
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
ch <- client.ContentOnChannel{Content: nil, Err: probe.NewError(err)}
|
||||
break
|
||||
}
|
||||
ch <- client.ContentOnChannel{Content: &c, Err: nil}
|
||||
}
|
||||
}()
|
||||
return ch
|
||||
}
|
||||
|
||||
func (sl *sortedList) Match(source *client.Content) (bool, *probe.Error) {
|
||||
if len(sl.current.Name) == 0 {
|
||||
// for the first time read
|
||||
if err := sl.dec.Decode(&sl.current); err != nil {
|
||||
if err != io.EOF {
|
||||
return false, probe.NewError(err)
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
for {
|
||||
compare := strings.Compare(source.Name, sl.current.Name)
|
||||
if compare == 0 {
|
||||
if source.Type.IsRegular() && sl.current.Type.IsRegular() && source.Size == sl.current.Size {
|
||||
return true, nil
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
if compare < 0 {
|
||||
return false, nil
|
||||
}
|
||||
// assign zero values to fields because if s.current's previous decode had non zero value
|
||||
// fields it will not be over written if this loop's decode does not contain those fields
|
||||
sl.current = client.Content{}
|
||||
if err := sl.dec.Decode(&sl.current); err != nil {
|
||||
return false, probe.NewError(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Delete close and delete the ondisk file
|
||||
func (sl sortedList) Delete() *probe.Error {
|
||||
if err := sl.file.Close(); err != nil {
|
||||
return probe.NewError(err)
|
||||
}
|
||||
if err := os.Remove(sl.name); err != nil {
|
||||
return probe.NewError(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
# Compiled Object files, Static and Dynamic libs (Shared Objects)
|
||||
*.o
|
||||
*.a
|
||||
*.so
|
||||
|
||||
# Folders
|
||||
_obj
|
||||
_test
|
||||
|
||||
# Architecture specific extensions/prefixes
|
||||
*.[568vq]
|
||||
[568vq].out
|
||||
|
||||
*.cgo1.go
|
||||
*.cgo2.c
|
||||
_cgo_defun.c
|
||||
_cgo_gotypes.go
|
||||
_cgo_export.*
|
||||
|
||||
_testmain.go
|
||||
|
||||
*.exe
|
||||
*.test
|
||||
*.prof
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user