Compare commits

..
Author SHA1 Message Date
Anand Babu (AB) Periasamy 475670de7d Update play description. (#1735) 2016-05-30 22:51:44 -07:00
Aakash Muttineni f9efb67bc2 Minio-go vendor update (#1734) 2016-05-29 23:44:16 -07:00
Krishnan Parthasarathi 9766ff1805 Append trailing slash to targetURL only if absent (#1731) 2016-05-28 13:16:57 -07:00
Krishnan Parthasarathi cc4227e3f2 Made session list ignore broken sessions (#1728)
* Made session list ignore broken sessions

- `mc session list` - skips partial sessions[1]

- `mc session clear all` - doesn't clear partial sessions.
The idea is to prevent the user from clearing all sessions without
realising that there were partial sessions.

When there is one or more partial sessions, clear each one of them individually
as follows,
 `mc session clear <broken-session-id>` - clears the partial sessions.

[1] - partial session - a session with missing `.data` file in the sessions directory.

N B The presence of partial sessions indicate some underlying bug in session mangement
code. This PR provides relief for users in the event of such a bug.

* Added comments to session helper functions and to be provide context
2016-05-23 23:05:39 -07:00
Krishnan Parthasarathi ba2e8149c8 Ignore BucketEmpty error for top-level listing (#1727)
* Ignore BucketEmpty error for top-level listing

This is relevant in the case of non-fs backend like s3, play etc.

* Used ToGoError() to get Error interface from *probe.Error
2016-05-22 23:04:26 -07:00
Krishnan Parthasarathi b48371e971 Create only one custom transport for all S3 clients (#1722)
* Create only one custom transport for all S3 clients

Closes #1721

* Moved back to http.DefaultTransport

... because ResponseHeaderTimeout may fail `mc mirror` in slow networks
2016-05-21 02:07:18 -07:00
Anis Elleuch 8b074767db ls: list objects inside a directory when this latter is passed without a trailing separator (#1724) 2016-05-20 16:43:06 -07:00
Krishnan Parthasarathi e5bc26c75a Removed setting of http.Client Timeout for mc (#1720)
* Removed setting of http.Client Timeout for mc

Fixes #1719

* Moved mcDefaultTransport closer to use

* Set ResponseHeaderTimeout to 3 secs

* Vendored in changes from github.com/minio/minio-go

* Fixed CI build errors due to API changes, post vendoring

* Fixed unit tests w.r.t the change from insecure to secure in minio.NewV{2,4} API
2016-05-20 00:35:49 -07:00
Harshavardhana 959fa74ca5 profile: Add MC_PROFILER env supporting cpu, mem, block profiling. (#1714)
All profiled outputs are written inside `~/.mc/profile`
2016-05-10 19:10:59 -07:00
Krishna Srinivas ac57970229 Merge pull request #1711 from harshavardhana/signals
session: Signal trap shouldn't panic, close the Notify handler.
2016-05-10 12:39:42 +05:30
Harshavardhana 9fb8cfc1b3 session: Signal trap shouldn't panic, close the Notify handler.
Avoid executing Notify handler again when two SIGINTS are
received which can occur when 'mc' is busy copying a
largefile.

Fixes #1710
2016-05-10 00:05:18 -07:00
Harshavardhana 06ad6c53f7 debug: Tracing should print success response for PUT/POST ops. (#1708)
Due to a golang bug need to add specific code to handle this
properly when the response body has ContentLength of '0'

Ref for more info : https://github.com/golang/go/issues/13942.
2016-05-07 01:11:09 -07:00
Anis Elleuch a9b0b14149 Increase update url fetching timeout to 3 seconds (#1704) 2016-04-28 16:03:09 -07:00
Krishna Srinivas 9a454e714d Merge pull request #1702 from harshavardhana/mirror
mirror/cp: Skip NoSuckKey, NoSuchBucket errors properly in cp/mirror.
2016-04-28 14:40:01 +05:30
Harshavardhana 319b3d8434 mirror/cp: Skip NoSuckKey, NoSuchBucket errors properly in cp/mirror.
Fixes #1693
2016-04-27 20:37:42 -07:00
Harshavardhana 2fec2b4107 session: Close session only if fields have changed. (#1701)
Fixes #1700
2016-04-27 20:10:40 -07:00
Harshavardhana 382aa26859 vendorize: New changes in minio-go. (#1699)
- Fixes listing bug with done channel.
- Fixes retry go-routine leak.
- Adds more to the list of network errors to retry safely.
2016-04-25 01:20:15 -07:00
Anand Babu (AB) Periasamy d7854b6dfa Merge pull request #1698 from harshavardhana/access-msg
access: Change set access perm message.
2016-04-24 00:40:19 -07:00
Harshavardhana e3b6c12925 access: Change set access perm message. 2016-04-24 00:33:39 -07:00
Anand Babu (AB) Periasamy d9224348ce Merge pull request #1697 from harshavardhana/access-docs
access: update docs.
2016-04-23 16:23:44 -07:00
Harshavardhana 6b91c6f430 access: update docs. 2016-04-23 15:15:20 -07:00
Aaron Walker 7e9b96e354 cp/mirror use CopyObject API to enable server side copy (#1686)
Add Copy to s3 and fs methods/enable server side copy
2016-04-23 15:14:31 -07:00
Anand Babu (AB) Periasamy 8a8d4619de Merge pull request #1695 from harshavardhana/ignore
fs: Ignore file in recursive as well.
2016-04-22 01:31:01 -07:00
Harshavardhana 3af0902f28 fs: Ignore file in recursive as well. 2016-04-22 01:23:23 -07:00
Anand Babu (AB) Periasamy 6b4c1a4239 Merge pull request #1694 from harshavardhana/ls
ls: ls should ignore error BucketNameEmpty.
2016-04-21 18:15:12 -07:00
Harshavardhana 783d29794a ls: ls should ignore error BucketNameEmpty.
This is a valid case of 'ls', without this change.

```
$ mc ls localhost
mc: <ERROR> Unable to stat ‘localhost’. Bucket name cannot be empty.
```

What we need to ideally see is if server is not available is
```
$ mc ls localhost
mc: <ERROR> Unable to list folder. Get http://localhost:9000/: dial tcp [::1]:9000: getsockopt: connection refused
```
2016-04-21 17:10:16 -07:00
Anand Babu (AB) Periasamy a094c50f5a Merge pull request #1692 from harshavardhana/is-valid
config: Relax valid access and secret keys.
2016-04-19 18:27:44 -07:00
Harshavardhana 621e8cf0ff config: Relax valid access and secret keys.
Deviating from AWS Standards to support non
AWS Standard keys for Ceph and Exoscale probably
others.

Fixes #1690
2016-04-19 14:52:33 -07:00
Anand Babu (AB) Periasamy 4bd9336139 Merge pull request #1691 from harshavardhana/vendor
vendor: Vendorize minio-go
2016-04-19 02:47:13 -07:00
Harshavardhana c517833663 vendor: Vendorize minio-go
- Bucket policy fixes by Karthik Rao.
- China region fixes.
- Fixes a concurrent crash in Signature V2 code by Anis Elleuch.
2016-04-18 23:15:56 -07:00
Anand Babu (AB) Periasamy 8e4cc8df00 Merge pull request #1687 from harshavardhana/mirror-remove
mirror: Implement '--remove' feature.
2016-04-18 18:29:18 -07:00
Anis Elleuch 94f4c4cd2d Avoid removing session v7 json files by migrateSessionV5ToV6 (#2) 2016-04-18 17:47:39 -07:00
Harshavardhana c4c99999bc session: Add isRemoved() for session to avoid removing last removed files again. 2016-04-18 13:56:14 -07:00
Anis Elleuch 6abd3a4ed6 Avoid a possible crash when an error occurs while removing a file (#1) 2016-04-18 11:41:56 -07:00
Harshavardhana 9e94120d68 mirror: Implement '--remove' feature.
Fixes #1628
2016-04-17 12:21:43 -07:00
Anis Elleuch ba088b8fc0 Move ioutils pkg from minio to mc and fix a sorting list bug (#1688)
* Move ioutils pkg from minio to mc

* Fix an important bug in sorting fs list in recursive mode
2016-04-17 12:20:48 -07:00
Anis Elleuch 98ac1817cb Rewrite diff code (#1681) 2016-04-17 01:18:30 -07:00
Anand Babu (AB) Periasamy 65a31e34c9 check if sources exist (#1685) 2016-04-15 16:59:38 -07:00
Krishna Srinivas 264f1ef992 Merge pull request #1684 from harshavardhana/zip
release: Remove zip, tar.gz release builds.
2016-04-14 13:42:32 +05:30
Harshavardhana b30bbc0e74 release: Remove zip, tar.gz release builds. 2016-04-13 23:48:58 -07:00
Krishna Srinivas 7a77686878 Merge pull request #1680 from harshavardhana/gofmt
url: isURLPrefixExists() should use non-recursive mechanism.
2016-04-12 12:24:04 +05:30
Harshavardhana 0c4200306b url: isURLPrefixExists() should use non-recursive mechanism.
The reason is to avoid generating recursive requests while
we are only concerned about the top level prefix that if
it exists.
2016-04-11 20:44:36 -07:00
Harshavardhana 619b1b4e2a url: There is no reason to split '?' delimiter. (#1679)
The reasoning is that we are not providing query
params through 'mc' and we don't need to handle it
specially. Since all paths are absolute with only
delimiter of '/' all other characters should be allowed
including '?'.

For this same reason now newURL is called newClientURL.

Fixes #1677
2016-04-11 18:20:56 -07:00
Sreeram Boyapati 57d22664f4 config: validate config.json file (#1676)
- Minio Client validates only config host add parameters
    Not the config file. Use the same utils to validate config file

    if HostURL is wrong.
        /storage?googleapis?com for host /storage?googleapis?com is not valid. Could not parse it

    if API is wrong.
        S3v2iasdasd API for host https://www.google.com is not Valid. It is not part of any of the following APIs:
        1. S3v4
        2. S3v2

    If the version is wrong.
        Config version 9 does not match GlobalMCConfiguration 8.

    Example:

    mc: <ERROR> Config version 9 does not match GlobalMCConfiguration 8.

    S3v2asda API for host httpsasdkasd is not Valid. It is not part of any of the following APIs:
    1. S3v4
    2. S3v2

    URL httpsasdkasd for host httpsasdkasd is not valid. Could not parse it.
2016-04-10 21:28:17 -07:00
Anis Elleuch 38339b7cd9 Allow question mark in fs file names (#1678) 2016-04-10 15:28:03 -07:00
Anand Babu (AB) Periasamy d5cb19aeab allow caseless API signature in config (#1675) 2016-04-09 13:24:03 -07:00
karthic rao 3d04e56228 vendor: vendor updates for minio-go 2016-04-07 10:08:09 -07:00
Harshavardhana 3e8f7684f2 build: cmd/vet is deprecated fix the url. 2016-04-06 20:07:57 -07:00
Anand Babu (AB) Periasamy c11527780a implement OS specific file ignore list 2016-04-06 15:44:23 -07:00
Sreeram Boyapati 5a204741b9 config: intialize loadMcConfig later in the app
Go caches the McConfig earlier leading to having no effect on changing config-dir during initialization.
2016-04-05 14:33:34 -07:00
Krishna Srinivas b23e8a77fc Merge pull request #1665 from harshavardhana/mirror-fake
mirror: More fixes for quiet mode, make sure fake is honored.
2016-04-05 13:10:59 +05:30
Harshavardhana e926266c62 mirror: More fixes for quiet mode, make sure fake is honored. 2016-04-04 17:25:15 -07:00
Harshavardhana 1eca4f8c0d mirror: Make sure isFake is set to false properly. 2016-04-04 15:35:25 -07:00
Harshavardhana edb1824006 mc: Simplify, conditional checks across codebase. 2016-04-04 14:58:36 -07:00
Anis Elleuch 6666262e51 Make --json and --quiet work as expected with mc mirror cmd 2016-04-04 11:42:46 -07:00
Harshavardhana 221ee6c26b Merge pull request #1660 from vadmeste/fix_mirror_crash
Fix a crash when --fake is coupled with --quiet in mirror cmd
2016-04-02 10:55:47 -07:00
Anis ELLEUCH d3d4afd223 Fix a crash when --fake is coupled with --quiet in mirror cmd 2016-04-02 15:10:53 +01:00
Krishna Srinivas f55f64b5b9 Merge pull request #1659 from harshavardhana/version
mc: Fix Golang version handling.
2016-04-02 15:28:21 +05:30
Harshavardhana 69fbb9a87d mc: Fix Golang version handling.
Migrate to a better go-version package to handle
version numbers.  Default to 'go1.6' as minimum.
2016-04-02 02:51:27 -07:00
Harshavardhana 8e50e8e8c3 Merge pull request #1657 from vadmeste/fix_realpath_behavior
realpath() alternative implementation doesn't really work under linux and freebsd, use a simpler and more portable method
2016-04-01 13:27:14 -07:00
Anis Elleuch 8cdf71b539 realpath() doesn't really work under linux and freebsd, use a simpler and more portable method 2016-04-01 19:21:01 +01:00
Harshavardhana e7f4b63212 docs: Update readme.md with new links. 2016-03-31 17:53:35 -07:00
Anand Babu (AB) Periasamy 12adf3be32 Merge pull request #1656 from harshavardhana/rel-bz
release: Release binaries will have now .tar.gz and .zip extension.
2016-03-31 17:12:16 -07:00
Harshavardhana 087516a783 release: Release binaries will have now .tar.gz and .zip extension.
The reasoning behind is to preserve permissions of binaries.
2016-03-31 17:04:45 -07:00
Anand Babu (AB) Periasamy 1b2a2fc7f9 Merge pull request #1655 from harshavardhana/global
config: Handle aliases migration from v6 --> v7.
2016-03-31 15:42:20 -07:00
Harshavardhana 3e205dba15 config: Handle aliases migration from v6 --> v7.
Fixes #1652
2016-03-31 15:23:55 -07:00
Anand Babu (AB) Periasamy ff874575e1 Merge pull request #1654 from harshavardhana/object-name
stat: Print proper error messages when bucket name is empty.
2016-03-31 15:22:48 -07:00
Harshavardhana 1e1516c968 stat: Print proper error messages when bucket name is empty.
Handle cases for situations for all commands where target bucket
name is not specified, indicate proper errors in this situation.

Fixes #1629
2016-03-30 18:46:20 -07:00
Harshavardhana aeb6de996c Merge pull request #1653 from krishnasrinivas/timeout-8-minute
ListObjects on a prefix with 10 million entries takes around 8 minutes.
2016-03-30 01:44:58 -07:00
Krishna Srinivas 82d87111fc vendor: vendor update minio-go. Increase http client timeout to 8 minutes. 2016-03-30 14:07:24 +05:30
Anand Babu (AB) Periasamy 49953d53ed Merge pull request #1622 from vadmeste/retrieve_secret_from_env
Retrieve secretKey from the environment first
2016-03-28 12:59:45 -07:00
Anis Elleuch 13a4133da5 Retrieve acessKey/secretKey from the environment first 2016-03-28 19:36:13 +01:00
Anand Babu (AB) Periasamy a02ae19de2 Merge pull request #1651 from harshavardhana/buffer
pipe: Avoid double copy of buffers in minio-go
2016-03-27 20:25:33 -07:00
Harshavardhana 9617f22fcd pipe: Avoid double copy of buffers in minio-go
Disallows multiple copies being referenced internally leads
to OOM conditions on certain low memory devices and systems.

Fixes #1641
2016-03-27 20:08:57 -07:00
Anand Babu (AB) Periasamy e156d62e44 Merge pull request #1640 from harshavardhana/mc-access
access: Access policy command implemented.
2016-03-27 19:55:40 -07:00
Harshavardhana f4e8352f5a access: Access policy command implemented.
This patch implements as decided..

To set a bucket policy.
```
mc access readonly s3/<bucket>
mc access readwrite s3/<bucket>
mc access writeonly s3/<bucket>
mc access none s3/<bucket>
```

To get a bucket policy.
```
mc access s3/<bucket>
```
2016-03-27 19:49:54 -07:00
Harshavardhana deb7f72be2 Merge pull request #1650 from sreeram-boyapati/config_tests
tests: add tests for 'mc cat' and 'mc config host'
2016-03-27 10:12:58 -07:00
Sreeram Boyapati a5a57fa2be tests: add tests for 'mc cat' and 'mc config host' 2016-03-27 21:06:40 +05:30
Harshavardhana c3fb1d52f4 Update README.md 2016-03-23 13:09:45 -07:00
Harshavardhana 9820dce775 config: mcConfigVersion should be '8' 2016-03-22 02:42:31 -07:00
Anand Babu (AB) Periasamy 426df2c9ab Merge pull request #1645 from harshavardhana/config-v8
config: Migrate to new version of config '8'
2016-03-22 02:37:36 -07:00
Harshavardhana 20c7a00af5 config: Migrate to new version of config '8'
This config migration was done to the fact that
play.minio.io:9000 anonymous access has been
removed but instead access keys, while server is
public will not honor anonymous requests anymore.
2016-03-21 15:27:31 -07:00
Anand Babu (AB) Periasamy 00d0f1e9d9 Merge pull request #1644 from harshavardhana/fake-rm
rm: treat --fake option properly and list what its going to do.
2016-03-20 15:42:16 -07:00
Harshavardhana 4cecac4ea4 rm: treat --fake option properly and list what its going to do.
Fixes #1643
2016-03-20 14:43:25 -07:00
Harshavardhana b0e2bde84d Merge pull request #1636 from harshavardhana/vendorize
vendor: Vendorize with new changes to minio-go
2016-03-14 19:03:42 -07:00
Harshavardhana 49851c8795 vendor: Vendorize with new changes to minio-go 2016-03-13 03:22:39 -07:00
Harshavardhana 7bdb39c743 Merge pull request #1635 from hackintoshrao/progress-bar-fix
progress bar: Fixing progress on occurance of non-critical error
2016-03-10 19:35:16 -08:00
Karthic Rao 09495582c4 Adding Get() method to check on currentValue instead of totalFileSize
Adding vendor changes from minio-go and pb, aslo adding minio-go/retry.go changes to solve the race condition
2016-03-11 07:06:24 +05:30
Anand Babu (AB) Periasamy f15be9582a Merge pull request #1634 from harshavardhana/delete-option
diff: Implement url difference with time.
2016-03-10 16:10:34 -08:00
Harshavardhana c022107515 diff: Implement url difference with time.
Also make a 'differType' - fixes #1632
2016-03-09 22:11:07 -08:00
Harshavardhana 373b593c3e Merge pull request #1630 from harshavardhana/fake-option
mirror: Implement --fake option.
2016-03-05 13:20:36 -08:00
Harshavardhana ca06c0e09f Merge pull request #1631 from harshavardhana/difference-factory
diff/mirror: Factory function now refactored to reply function only idiomatic style.
2016-03-05 13:19:36 -08:00
Harshavardhana bd1086c244 diff/mirror: Factory function now refactored to reply function only idiomatic style.
Refactor the current code into more idiomatic style and use
consistent variable names.

ref #1628
2016-03-04 19:52:32 -08:00
Harshavardhana 69c8bf7959 mirror: Implement --fake option.
This option helps users verify what operation 'mirror'
is going to perform without it. It also allows for scripts
to validate what files will be copied etc.

- #1628
2016-03-04 19:14:56 -08:00
Harshavardhana db6b4f1344 Merge pull request #1625 from harshavardhana/bucket-list
ls: Fix bucket date.
2016-02-29 08:42:30 -08:00
Krishna Srinivas 05db6e3981 Merge pull request #1624 from harshavardhana/session-old
session: Remove session backup file if any.
2016-02-29 16:18:03 +05:30
Harshavardhana 2623eeb82e session: Remove session backup file if any.
Fixes #1623
2016-02-29 02:06:25 -08:00
Harshavardhana cbebadc16a ls: Fix bucket date.
While listing buckets 'mc ls s3/bucket' would list the
date incorrectly. Populate it properly from 'ListBuckets()'
2016-02-29 02:00:23 -08:00
Harshavardhana 614d6d81e5 Merge pull request #1620 from vadmeste/make_builder_freebsd_support
Add needed changes to make mc buildable using make under FreeBSD
2016-02-24 12:55:46 -08:00
Anis Elleuch cac451c83e Add needed changes to make mc buildable using make under FreeBSD 2016-02-24 20:54:34 +01:00
Harshavardhana 54a86c69e1 Merge pull request #1618 from harshavardhana/windows
windows: Add progress bar windows fixes.
2016-02-19 15:53:00 -08:00
Harshavardhana ea8f5c0f33 windows: Add progress bar windows fixes. 2016-02-19 15:40:38 -08:00
Harshavardhana 340d576931 Merge pull request #1617 from minio/harshavardhana-patch-1
Update README.md
2016-02-18 20:48:27 -08:00
Harshavardhana 7db8820042 Update README.md 2016-02-18 20:43:41 -08:00
Harshavardhana 54761b22fd Merge pull request #1616 from harshavardhana/tag1
update: Change update tag to verify RELEASE instead of OFFICIAL
2016-02-18 20:05:18 -08:00
Harshavardhana 253f13640c update: Change update tag to verify RELEASE instead of OFFICIAL 2016-02-18 20:01:38 -08:00
Harshavardhana 97110c9676 Merge pull request #1615 from harshavardhana/build
build: Check for gopath and multiple source build locations.
2016-02-18 19:14:40 -08:00
Harshavardhana 9805c4d907 build: Check for gopath and multiple source build locations. 2016-02-18 18:26:47 -08:00
Anand Babu (AB) Periasamy 56d548ad10 Merge pull request #1614 from harshavardhana/fix-shadowing
build/vet: Fix all the shadowed variables.
2016-02-19 07:32:10 +05:30
Harshavardhana c196f6ee08 build/vet: Fix all the shadowed variables. 2016-02-18 17:04:45 -08:00
Harshavardhana db55841e7d Merge pull request #1613 from harshavardhana/go-1.6
build: Default to Golang 1.6
2016-02-18 16:23:24 -08:00
Harshavardhana fb70ef7b1c build: Default to Golang 1.6 2016-02-18 16:08:07 -08:00
Harshavardhana fa82223c50 Merge pull request #1612 from harshavardhana/config-folder
config: Config folder option should be honored.
2016-02-17 16:04:21 -08:00
Harshavardhana 6f3cd87993 config: Config folder option should be honored.
The fix is to load config factory once again, to avoid looking for stale
scoped global variables. For example ``mcCustomConfigDir``

Fixes #1611
2016-02-17 15:59:55 -08:00
Anand Babu (AB) Periasamy 3ca7ac613d Merge pull request #1609 from harshavardhana/fs-s3
fs/s3: move the code for fs and s3 out to the top-level.
2016-02-17 05:53:27 +05:30
Harshavardhana fe5b2f97e3 fs/s3: move the code for fs and s3 out to the top-level.
Now the interface moves to the top level - fixes #1604
2016-02-16 11:27:42 -08:00
Harshavardhana 220bf92a3c Merge pull request #1606 from harshavardhana/solaris
porting: mc now properly works on solaris.
2016-02-15 20:11:35 -08:00
Super-User 5219fd59e8 porting: mc now properly works on solaris.
Fixes #1603
2016-02-15 15:03:40 -08:00
Anand Babu (AB) Periasamy 4832da5cda Merge pull request #1602 from harshavardhana/make-release
build: Now builds for all platforms and builds into 'release/experimental' directory.
2016-02-09 14:22:24 -08:00
Harshavardhana 4ef3dcffc4 build: Now builds for all platforms and builds into 'release/experimental' directory.
Two Makefile options are

- make release
- make experimental

Currently supported OS and arch -

- linux/386
- linux/amd64
- linux/arm
- windows/386
- windows/amd64
- darwin/amd64
2016-02-09 14:18:35 -08:00
Harshavardhana fbe4768658 Merge pull request #1601 from harshavardhana/request-params
mc: update to new changes in minio-go.
2016-02-07 18:09:13 -08:00
Harshavardhana f63de3cc30 mc: update to new changes in minio-go. 2016-02-07 18:03:32 -08:00
Anand Babu (AB) Periasamy 7c7d9e07a2 Merge pull request #1600 from harshavardhana/use-mime
mc: Remove contentdb and use golang pkg/mime instead.
2016-02-06 16:15:51 -08:00
Harshavardhana 708f1e17f4 mc: Remove contentdb and use golang pkg/mime instead.
This is also because golang package sets proper 'charset's
for contentTypes. Also there is no reason for 'mc' to have
its own mimedb.
2016-02-06 10:43:57 -08:00
Krishna Srinivas 8fc48cf24a Merge pull request #1599 from harshavardhana/vendorize
minio-go: Vendorize with new changes.
2016-02-06 13:21:52 +05:30
358 changed files with 105423 additions and 6627 deletions
+2
View File
@@ -2,3 +2,5 @@ cover.out
mc
*~
*.test
release
experimental
+3 -2
View File
@@ -13,10 +13,11 @@ env:
- ARCH=i686
go:
- 1.5.2
- 1.5.3
- 1.6
script:
- make test
- make test GOFLAGS="-race"
- diff -au <(gofmt -d *.go) <(printf "")
- diff -au <(gofmt -d pkg) <(printf "")
+5 -5
View File
@@ -7,15 +7,15 @@ This installation guide is based on Ubuntu 14.04+ on x86-64 platform.
$ sudo apt-get install git build-essential
```
##### Install Go 1.5+
##### Install Go 1.6+
Download Go 1.5+ from [https://golang.org/dl/](https://golang.org/dl/).
Download Go 1.6+ from [https://golang.org/dl/](https://golang.org/dl/).
```sh
$ wget https://storage.googleapis.com/golang/go1.5.1.linux-amd64.tar.gz
$ wget https://storage.googleapis.com/golang/go1.6.linux-amd64.tar.gz
$ mkdir -p ${HOME}/bin/
$ mkdir -p ${HOME}/go/
$ tar -C ${HOME}/bin/ -xzf go1.5.1.linux-amd64.tar.gz
$ tar -C ${HOME}/bin/ -xzf go1.6.linux-amd64.tar.gz
```
##### Setup GOROOT and GOPATH
@@ -53,7 +53,7 @@ $ ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/maste
$ brew install git python
```
##### Install Go 1.5+
##### Install Go 1.6+
Install golang binaries using `brew`
+1 -1
View File
@@ -38,4 +38,4 @@ $
`mc` doesn't follow semantic versioning style, `mc` instead uses the release date and time as the release versions.
`make release` will install new released binary into your `GOPATH`
`make release` will generate new binary into `release` directory.
+33 -26
View File
@@ -1,25 +1,20 @@
LDFLAGS := $(shell go run buildscripts/gen-ldflags.go)
BUILD_LDFLAGS := '$(LDFLAGS)'
all: install
checkdeps:
checks:
@echo "Checking deps:"
@(env bash $(PWD)/buildscripts/checkdeps.sh)
@(env bash buildscripts/checkdeps.sh)
@(env bash buildscripts/checkgopath.sh)
checkgopath:
@echo "Checking if project is at ${GOPATH}"
@for mcpath in $(echo ${GOPATH} | sed 's/:/\n/g'); do if [ ! -d ${mcpath}/src/github.com/minio/mc ]; then echo "Project not found in ${mcpath}, please follow instructions provided at https://github.com/minio/minio/blob/master/CONTRIBUTING.md#setup-your-minio-github-repository" && exit 1; fi done
@echo "BUILD_LDFLAGS: ${BUILD_LDFLAGS}"
getdeps: checkdeps checkgopath
getdeps: checks
@go get github.com/golang/lint/golint && echo "Installed golint:"
@go get golang.org/x/tools/cmd/vet && echo "Installed vet:"
@go get github.com/fzipp/gocyclo && echo "Installed gocyclo:"
@go get github.com/remyoudompheng/go-misc/deadcode && echo "Installed deadcode:"
@go get github.com/client9/misspell/cmd/misspell && echo "Installed misspell:"
# verifiers: getdeps vet fmt lint cyclo deadcode
verifiers: getdeps vet fmt lint cyclo deadcode
verifiers: vet fmt lint cyclo deadcode spelling
vet:
@echo "Running $@:"
@@ -28,34 +23,38 @@ vet:
@GO15VENDOREXPERIMENT=1 go tool vet -shadow=true *.go
@GO15VENDOREXPERIMENT=1 go tool vet -shadow=true ./pkg
spelling:
@GO15VENDOREXPERIMENT=1 ${GOPATH}/bin/misspell *.go
@GO15VENDOREXPERIMENT=1 ${GOPATH}/bin/misspell pkg/**/*
fmt:
@echo "Running $@:"
@GO15VENDOREXPERIMENT=1 gofmt -s -l *.go
@GO15VENDOREXPERIMENT=1 gofmt -s -l pkg
lint:
@echo "Running $@:"
@GO15VENDOREXPERIMENT=1 golint .
@GO15VENDOREXPERIMENT=1 golint github.com/minio/mc/pkg...
@GO15VENDOREXPERIMENT=1 $(GOPATH)/bin/golint .
@GO15VENDOREXPERIMENT=1 $(GOPATH)/bin/golint github.com/minio/mc/pkg...
cyclo:
@echo "Running $@:"
@GO15VENDOREXPERIMENT=1 gocyclo -over 40 *.go
@GO15VENDOREXPERIMENT=1 gocyclo -over 40 pkg
@GO15VENDOREXPERIMENT=1 $(GOPATH)/bin/gocyclo -over 40 *.go
@GO15VENDOREXPERIMENT=1 $(GOPATH)/bin/gocyclo -over 40 pkg
deadcode:
@echo "Running $@:"
@GO15VENDOREXPERIMENT=1 deadcode
@GO15VENDOREXPERIMENT=1 $(GOPATH)/bin/deadcode
build: verifiers
build: getdeps verifiers
@echo "Installing mc:"
test: verifiers
test: getdeps verifiers
@echo "Running all testing:"
@GO15VENDOREXPERIMENT=1 go test $(GOFLAGS) ./
@GO15VENDOREXPERIMENT=1 go test $(GOFLAGS) github.com/minio/mc/pkg...
gomake-all: build
@GO15VENDOREXPERIMENT=1 go build --ldflags $(BUILD_LDFLAGS) -o $(GOPATH)/bin/mc
@GO15VENDOREXPERIMENT=1 go build --ldflags "$(LDFLAGS)" -o $(GOPATH)/bin/mc
@mkdir -p $(HOME)/.mc
coverage:
@@ -63,13 +62,16 @@ coverage:
@go tool cover -html=cover.out && echo "Visit your browser"
pkg-add:
@GO15VENDOREXPERIMENT=1 govendor add $(PKG)
@GO15VENDOREXPERIMENT=1 $(GOPATH)/bin/govendor add $(PKG)
pkg-update:
@GO15VENDOREXPERIMENT=1 govendor update $(PKG)
@GO15VENDOREXPERIMENT=1 $(GOPATH)/bin/govendor update $(PKG)
pkg-remove:
@GO15VENDOREXPERIMENT=1 govendor remove $(PKG)
@GO15VENDOREXPERIMENT=1 $(GOPATH)/bin/govendor remove $(PKG)
pkg-list:
@GO15VENDOREXPERIMENT=1 $(GOPATH)/bin/govendor list
install: gomake-all
@@ -77,9 +79,14 @@ all-tests: test
# TODO disable them for now.
#@./tests/test-minio.sh
release:
@./release.sh
release: verifiers
@MC_RELEASE=RELEASE GO15VENDOREXPERIMENT=1 ./buildscripts/build.sh
experimental: verifiers
@MC_RELEASE=EXPERIMENTAL GO15VENDOREXPERIMENT=1 ./buildscripts/build.sh
clean:
@rm -fv cover.out
@rm -fv mc
@rm -f cover.out
@rm -f mc
@find . -name '*.test' | xargs rm -fv
@rm -fr release
+31 -11
View File
@@ -1,6 +1,6 @@
# Minio Client (mc) [![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/minio/minio?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
``mc`` provides minimal tools to work with Amazon S3 compatible cloud storage and filesystems. It has features like resumable uploads/downloads, progress bar, parallel copy. ``mc`` is written in golang and released under [Apache license v2](./LICENSE).
``mc`` provides minimal tools to work with Amazon S3 compatible cloud storage and filesystems. It has features like resumable uploads/downloads, progress bar, mirroring etc. ``mc`` is written in golang and released under [Apache license v2](./LICENSE).
## Commands
@@ -33,7 +33,7 @@ Download ``mc`` for:
- ``32-bit ARM`` from https://dl.minio.io/client/mc/release/linux-arm/mc
~~~
$ chmod +x mc
$ chmod 755 mc
$ ./mc --help
~~~
@@ -53,10 +53,30 @@ 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
Extract the downloaded zip file.
~~~
C:\Users\Username\Downloads> mc.exe --help
~~~
#### Solaris/Illumos
Download ``mc`` from https://dl.minio.io/client/mc/release/solaris-amd64/mc
~~~
$ chmod 755 mc
$ ./mc --help
~~~
#### FreeBSD
Download ``mc`` from https://dl.minio.io/client/mc/release/freebsd-amd64/mc
~~~
$ chmod 755 mc
$ ./mc --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.
@@ -68,9 +88,12 @@ If you do not have a working Golang environment, please follow [Install Golang](
$ GO15VENDOREXPERIMENT=1 go get -u github.com/minio/mc
```
## Public Minio Server
Minio cloud storage server is hosted at ``https://play.minio.io:9000`` for public use. This service is primarily intended for developers and users to familiarize themselves with Amazon S3 compatible cloud storage. Minio runs with filesystem backend with auto-expiry for objects in about 24 hours. No account signup is required, which means S3 compatible tools and applications can access this service without access and secret keys.
## Minio Test Server
Minio test server is hosted at ``https://play.minio.io:9000`` for public use. `mc` is pre-configured to use this service as 'play' alias. Access and secret keys for this server is saved in your `~/.mc/config.json`.
```
$ ./mc mb play/myownbucket
$ ./mc ls play
```
## Configuring mc for Amazon S3
@@ -78,12 +101,12 @@ Get your AccessKeyID and SecretAccessKey by following [AWS Credentials Guide](ht
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
$ ./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
$ ./mc config host add mys3 https://s3.amazonaws.com BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12
```
NOTE: ``S3v4`` is default if not specified.
@@ -94,13 +117,10 @@ Get your AccessKeyID and SecretAccessKey by following [Google Credentials Guide]
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
$ ./mc config host add <ALIAS> https://storage.googleapis.com <YOUR-ACCESS-KEY> <YOUR-SECRET-KEY> S3v2
```
NOTE: Google Cloud Storage only supports Legacy Signature Version ``2``, so you have to pick - ``S3v2``
## Contribute to Minio Client
Please follow Minio [Contributor's Guide](./CONTRIBUTING.md)
### Jobs
If you think in Lisp or Haskell and hack in go, you would blend right in. Send your github link to callhome@minio.io.
+52 -73
View File
@@ -1,5 +1,5 @@
/*
* Minio Client, (C) 2015 Minio, Inc.
* Minio Client, (C) 2015, 2016 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,12 +18,11 @@ package main
import (
"encoding/json"
"strings"
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/console"
"github.com/minio/minio-xl/pkg/probe"
"github.com/minio/minio/pkg/probe"
)
var (
@@ -35,40 +34,41 @@ var (
}
)
// Set access permissions.
// Set public access permissions.
var accessCmd = cli.Command{
Name: "access",
Usage: "Manage bucket access permissions.",
Usage: "Set public access permissions on bucket or prefix.",
Action: mainAccess,
Flags: append(accessFlags, globalFlags...),
CustomHelpTemplate: `Name:
mc {{.Name}} - {{.Usage}}
USAGE:
mc {{.Name}} [FLAGS] set PERMISSION TARGET [TARGET...]
mc {{.Name}} [FLAGS] get TARGET [TARGET...]
mc {{.Name}} [FLAGS] PERMISSION TARGET
mc {{.Name}} [FLAGS] TARGET
PERMISSION:
Allowed permissions are: [private, readonly, public, authorized].
Allowed permissions are: [none, readonly, readwrite, writeonly].
FLAGS:
{{range .Flags}}{{.}}
{{end}}
EXAMPLES:
1. Set bucket to "private" on Amazon S3 cloud storage.
$ mc {{.Name}} set private s3/burningman2011
1. Set bucket to "readonly" on Amazon S3 cloud storage.
$ mc {{.Name}} readonly s3/burningman2011
2. Set bucket to "public" on Amazon S3 cloud storage.
$ mc {{.Name}} set public s3/shared
2. Set bucket to "readwrite" on Amazon S3 cloud storage.
$ mc {{.Name}} readwrite s3/shared
3. Set bucket to "authenticated" on Amazon S3 cloud storage to provide read access to IAM Authenticated Users group.
$ mc {{.Name}} set authorized s3/shared-authenticated
3. Set bucket to "writeonly" on Amazon S3 cloud storage.
$ mc {{.Name}} writeonly s3/incoming
4. Get bucket permissions.
$ mc {{.Name}} get s3/shared
4. Set a prefix to "readwrite" on Amazon S3 cloud storage.
$ mc {{.Name}} readwrite s3/public-commons/images
5. Get bucket permissions.
$ mc {{.Name}} get gcs/miniocloud
$ mc {{.Name}} s3/shared
`,
}
@@ -84,7 +84,7 @@ type accessMessage struct {
func (s accessMessage) String() string {
if s.Operation == "set" {
return console.Colorize("Access",
"Set access permission ‘"+string(s.Perms)+"’ updated successfully for ‘"+s.Bucket+"’")
"Access permission for ‘"+s.Bucket+"’ is set to ‘"+string(s.Perms)+"’")
}
if s.Operation == "get" {
return console.Colorize("Access",
@@ -107,29 +107,19 @@ func checkAccessSyntax(ctx *cli.Context) {
if !ctx.Args().Present() {
cli.ShowCommandHelpAndExit(ctx, "access", 1) // last argument is exit code.
}
if len(ctx.Args()) < 2 {
if len(ctx.Args()) > 2 {
cli.ShowCommandHelpAndExit(ctx, "access", 1) // last argument is exit code.
}
switch ctx.Args().First() {
case "set":
if len(ctx.Args().Tail()) < 2 {
cli.ShowCommandHelpAndExit(ctx, "access", 1) // last argument is exit code.
}
perms := accessPerms(ctx.Args().Tail().Get(0))
if len(ctx.Args()) == 2 {
perms := accessPerms(ctx.Args().Get(0))
if !perms.isValidAccessPERM() {
fatalIf(errDummy().Trace(),
"Unrecognized permission ‘"+perms.String()+"’. Allowed values are [private, public, readonly, authorized].")
}
for _, arg := range ctx.Args().Tail().Tail() {
if strings.TrimSpace(arg) == "" {
fatalIf(errInvalidArgument().Trace(), "Unable to validate empty argument.")
}
}
case "get":
if len(ctx.Args().Tail()) < 1 {
cli.ShowCommandHelpAndExit(ctx, "access", 1) // last argument is exit code.
"Unrecognized permission ‘"+string(perms)+"’. Allowed values are [none, readonly, readwrite, writeonly].")
}
}
if len(ctx.Args()) < 1 {
cli.ShowCommandHelpAndExit(ctx, "access", 1) // last argument is exit code.
}
}
// doSetAccess do set access.
@@ -138,8 +128,8 @@ func doSetAccess(targetURL string, targetPERMS accessPerms) *probe.Error {
if err != nil {
return err.Trace(targetURL)
}
if err = clnt.SetBucketAccess(targetPERMS.String()); err != nil {
return err.Trace(targetURL, targetPERMS.String())
if err = clnt.SetAccess(string(targetPERMS)); err != nil {
return err.Trace(targetURL, string(targetPERMS))
}
return nil
}
@@ -150,11 +140,11 @@ func doGetAccess(targetURL string) (perms accessPerms, err *probe.Error) {
if err != nil {
return "", err.Trace(targetURL)
}
acl, err := clnt.GetBucketAccess()
perm, err := clnt.GetAccess()
if err != nil {
return "", err.Trace(targetURL)
}
return aclToPerms(acl), nil
return accessPerms(perm), nil
}
func mainAccess(ctx *cli.Context) {
@@ -167,39 +157,28 @@ func mainAccess(ctx *cli.Context) {
// 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,
})
}
perms := accessPerms(ctx.Args().First())
if perms.isValidAccessPERM() {
targetURL := ctx.Args().Last()
err := doSetAccess(targetURL, perms)
// Upon error exit.
fatalIf(err.Trace(targetURL, string(perms)),
"Unable to set access permission ‘"+string(perms)+"’ for ‘"+targetURL+"’.")
printMsg(accessMessage{
Status: "success",
Operation: "set",
Bucket: targetURL,
Perms: perms,
})
} else {
targetURL := ctx.Args().First()
perms, err := doGetAccess(targetURL)
fatalIf(err.Trace(targetURL), "Unable to get access permission for ‘"+targetURL+"’.")
printMsg(accessMessage{
Status: "success",
Operation: "get",
Bucket: targetURL,
Perms: perms,
})
}
}
+8 -67
View File
@@ -18,79 +18,20 @@ package main
// isValidAccessPERM - is provided access perm string supported.
func (b accessPerms) isValidAccessPERM() bool {
switch true {
case b.isPrivate():
fallthrough
case b.isReadOnly():
fallthrough
case b.isPublic():
fallthrough
case b.isAuthorized():
switch b {
case accessNone, accessReadOnly, accessReadWrite, accessWriteOnly:
return true
default:
return false
}
return false
}
// accessPerms - access level.
type accessPerms string
// different types of Access perm's currently supported by accesss command.
// different types of Access perm's currently supported by access command.
const (
accessPrivate = accessPerms("private")
accessReadOnly = accessPerms("readonly")
accessPublic = accessPerms("public")
accessAuthorized = accessPerms("authorized")
accessNone = accessPerms("none")
accessReadOnly = accessPerms("readonly")
accessReadWrite = accessPerms("readwrite")
accessWriteOnly = accessPerms("writeonly")
)
func (b accessPerms) String() string {
if !b.isValidAccessPERM() {
return string(b)
}
if b.isReadOnly() {
return "public-read"
}
if b.isPublic() {
return "public-read-write"
}
if b.isAuthorized() {
return "authenticated-read"
}
return "private"
}
// convert acl's to access perms
func aclToPerms(acl string) accessPerms {
switch acl {
case "private":
return accessPerms("private")
case "public-read":
return accessPerms("readonly")
case "public-read-write":
return accessPerms("public")
case "authenticated-read":
return accessPerms("authorized")
default:
return accessPerms(acl)
}
}
// isPrivate - is acl Private.
func (b accessPerms) isPrivate() bool {
return b == accessPrivate
}
// isPublicRead - is acl PublicRead.
func (b accessPerms) isReadOnly() bool {
return b == accessReadOnly
}
// isPublicReadWrite - is acl PublicReadWrite.
func (b accessPerms) isPublic() bool {
return b == accessPublic
}
// isAuthorized - is acl AuthorizedRead.
func (b accessPerms) isAuthorized() bool {
return b == accessAuthorized
}
+1 -1
View File
@@ -97,7 +97,7 @@ func isValidBucket(bucket string) bool {
if bucket[0] == '.' || bucket[len(bucket)-1] == '.' {
return false
}
if match, _ := regexp.MatchString("\\.\\.", bucket); match == true {
if match, _ := regexp.MatchString("\\.\\.", bucket); match {
return false
}
// We don't support buckets with '.' in them
+5 -4
View File
@@ -14,14 +14,15 @@ environment:
# scripts that run after cloning repository
install:
- set PATH=%GOPATH%\bin;c:\go\bin;%PATH%
- rd C:\Go /s /q
- appveyor DownloadFile https://storage.googleapis.com/golang/go1.6.windows-amd64.zip
- 7z x go1.6.windows-amd64.zip -oC:\ >nul
- 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
- go get -u github.com/client9/misspell/cmd/misspell
# to run your custom scripts instead of automatic MSBuild
build_script:
@@ -30,7 +31,7 @@ build_script:
- gofmt -s -l pkg
- golint .
- golint github.com/minio/mc/pkg...
- gometalinter --disable-all --linter='misspell:misspell ./*.go:PATH:LINE:COL:MESSAGE' --enable=misspell ./...
- misspell .
- gocyclo -over 40 pkg
- deadcode
- go test -race .
+3 -3
View File
@@ -18,11 +18,11 @@ package main
var (
// mcVersion - version time.RFC3339.
mcVersion = "UNOFFICIAL.GOGET"
mcVersion = "DEVELOPMENT.GOGET"
// mcReleaseTag - release tag in TAG.%Y-%m-%dT%H-%M-%SZ.
mcReleaseTag = "UNOFFICIAL.GOGET"
mcReleaseTag = "DEVELOPMENT.GOGET"
// mcCommitID - latest commit id.
mcCommitID = "UNOFFICIAL.GOGET"
mcCommitID = "DEVELOPMENT.GOGET"
// mcShortCommitID - first 12 characters from mcCommitID.
mcShortCommitID = mcCommitID[:12]
)
+95
View File
@@ -0,0 +1,95 @@
#!/bin/bash
_init() {
# Save release LDFLAGS
LDFLAGS=$(go run buildscripts/gen-ldflags.go)
# Extract release tag
release_tag=$(echo $LDFLAGS | awk {'print $4'} | cut -f2 -d=)
# Verify release tag.
if [ -z "$release_tag" ]; then
echo "Release tag cannot be empty. Please check return value of \`go run buildscripts/gen-ldflags.go\`"
exit 1;
fi
# Extract release string.
release_str=$(echo $MC_RELEASE | tr '[:upper:]' '[:lower:]')
# Verify release string.
if [ -z "$release_str" ]; then
echo "Release string cannot be empty. Please set \`MC_RELEASE\` env variable."
exit 1;
fi
# List of supported architectures
SUPPORTED_OSARCH='linux/386 linux/amd64 linux/arm windows/386 windows/amd64 darwin/amd64 solaris/amd64 freebsd/amd64'
## System binaries
CP=`which cp`
SHASUM=`which shasum`
SED=`which sed`
}
go_build() {
local osarch=$1
os=$(echo $osarch | cut -f1 -d'/')
arch=$(echo $osarch | cut -f2 -d'/')
package=$(go list -f '{{.ImportPath}}')
echo -n "-->"
printf "%15s:%s\n" "${osarch}" "${package}"
# Release binary name
release_bin="$release_str/$os-$arch/$(basename $package).$release_tag"
# Release binary downloadable name
release_real_bin="$release_str/$os-$arch/$(basename $package)"
# Release shasum name
release_shasum="$release_str/$os-$arch/$(basename $package).shasum"
# Go build to build the binary.
GOOS=$os GOARCH=$arch go build --ldflags "${LDFLAGS}" -o $release_bin
# Create copy
if [ $os == "windows" ]; then
$CP -p $release_bin ${release_real_bin}.exe
else
$CP -p $release_bin $release_real_bin
fi
# Calculate shasum
shasum_str=$(${SHASUM} ${release_bin})
echo ${shasum_str} | $SED "s/$release_str\/$os-$arch\///g" > $release_shasum
}
main() {
# Build releases.
echo "Executing $release_str builds for OS: ${SUPPORTED_OSARCH}"
echo "Choose an OS Arch from the below"
for osarch in ${SUPPORTED_OSARCH}; do
echo ${osarch}
done
read -p "If you want to build for all, Just press Enter: " chosen_osarch
if [ "$chosen_osarch" = "" ]; then
for each_osarch in ${SUPPORTED_OSARCH}; do
go_build ${each_osarch}
done
else
local found=0
for each_osarch in ${SUPPORTED_OSARCH}; do
if [ "$chosen_osarch" = "$each_osarch" ]; then
found=1
fi
done
if [ ${found} -eq 1 ]; then
go_build ${chosen_osarch}
else
echo "Unknown architecture \"${chosen_osarch}\""
exit 1
fi
fi
}
# Run main.
_init && main
+22 -7
View File
@@ -21,7 +21,7 @@ _init() {
## Minimum required versions for build dependencies
GIT_VERSION="1.0"
GO_VERSION="1.5.1"
GO_VERSION="1.6"
OSX_VERSION="10.8"
UNAME=$(uname -sm)
@@ -136,36 +136,51 @@ check_golang_env() {
}
is_supported_os() {
local supported
case ${UNAME%% *} in
"Linux")
os="linux"
supported=1
;;
"Darwin")
osx_host_version=$(env sw_vers -productVersion)
check_version "${osx_host_version}" "${OSX_VERSION}"
[[ $? -ge 2 ]] && die "Minimum OSX version supported is ${OSX_VERSION}"
supported=1
;;
"SunOS")
supported=1
;;
"FreeBSD")
supported=1
;;
"*")
echo "Exiting.. unsupported operating system found"
exit 1;
supported=0
;;
esac
if [ "x$supported" != "x1" ]; then
echo "Invalid os: ${UNAME} not supported"
exit 1;
fi
}
is_supported_arch() {
local supported
case ${UNAME##* } in
"x86_64")
"x86_64" | "amd64")
supported=1
;;
"arm"*)
supported=1
;;
"i86pc"*)
supported=1
;;
*)
supported=0
;;
esac
if [ $supported -eq 0 ]; then
echo "Invalid arch: ${UNAME} not supported, please use x86_64/amd64"
if [ "x$supported" != "x1" ]; then
echo "Invalid arch: ${UNAME} not supported"
exit 1;
fi
}
+41
View File
@@ -0,0 +1,41 @@
#!/usr/bin/env bash
#
# Minio Cloud Storage, (C) 2015, 2016 Minio, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
_init() {
shopt -s extglob
# Fetch real paths instead of symlinks before comparing them
PWD=$(env pwd -P)
GOPATH=$(cd "$(go env GOPATH)" ; env pwd -P)
}
main() {
echo "Checking if project is at ${GOPATH}"
for mc in $(echo ${GOPATH} | tr ':' ' '); do
if [ ! -d ${mc}/src/github.com/minio/mc ]; then
echo "Project not found in ${mc}, please follow instructions provided at https://github.com/minio/mc/blob/master/CONTRIBUTING.md#setup-your-mc-github-repository" \
&& exit 1
fi
if [ "x${mc}/src/github.com/minio/mc" != "x${PWD}" ]; then
echo "Build outside of ${mc}, two source checkouts found. Exiting." && exit 1
fi
done
}
_init && main
+1 -1
View File
@@ -37,7 +37,7 @@ func genLDFlags(version string) string {
// genReleaseTag prints release tag to the console for easy git tagging.
func releaseTag(version string) string {
relPrefix := "UNOFFICIAL"
relPrefix := "DEVELOPMENT"
if prefix := os.Getenv("MC_RELEASE"); prefix != "" {
relPrefix = prefix
}
+1 -1
View File
@@ -25,7 +25,7 @@ import (
"syscall"
"github.com/minio/cli"
"github.com/minio/minio-xl/pkg/probe"
"github.com/minio/minio/pkg/probe"
)
var (
+8 -31
View File
@@ -14,12 +14,9 @@
* limitations under the License.
*/
package client
package main
import (
"fmt"
"strconv"
)
import "fmt"
/// Collection of standard errors
@@ -33,15 +30,6 @@ func (e APINotImplemented) Error() string {
return "‘" + e.API + "’ feature " + "is not implemented for ‘" + e.APIType + "’."
}
// InvalidRange - invalid range requested
type InvalidRange struct {
Offset int64
}
func (e InvalidRange) Error() string {
return "Invalid range offset: ‘" + strconv.FormatInt(e.Offset, 10) + "’."
}
// GenericBucketError - generic bucket operations error
type GenericBucketError struct {
Bucket string
@@ -61,13 +49,6 @@ func (e BucketExists) Error() string {
return "Bucket ‘" + e.Bucket + "’ exists."
}
// InvalidBucketName - bucket name invalid (http://goo.gl/wJlzDz)
type InvalidBucketName GenericBucketError
func (e InvalidBucketName) Error() string {
return "Invalid bucketname [‘" + e.Bucket + "’], please read http://goo.gl/wJlzDz."
}
// BucketNameEmpty - bucket name empty (http://goo.gl/wJlzDz)
type BucketNameEmpty struct{}
@@ -75,10 +56,13 @@ func (e BucketNameEmpty) Error() string {
return "Bucket name cannot be empty."
}
// GenericObjectError - generic object operations error
type GenericObjectError struct {
// BucketInvalid - bucket name invalid.
type BucketInvalid struct {
Bucket string
Object string
}
func (e BucketInvalid) Error() string {
return "Bucket name " + e.Bucket + " not valid."
}
// ObjectAlreadyExists - typed return for MethodNotAllowed
@@ -90,13 +74,6 @@ func (e ObjectAlreadyExists) Error() string {
return "Object ‘" + e.Object + "’ already exists."
}
// InvalidObjectName - object requested is invalid
type InvalidObjectName GenericObjectError
func (e InvalidObjectName) Error() string {
return "Object ‘" + e.Object + "’ at ‘" + e.Bucket + "’ is invalid."
}
// BucketNameTopLevel - generic error
type BucketNameTopLevel struct{}
+349 -82
View File
@@ -14,44 +14,74 @@
* limitations under the License.
*/
package fs
package main
import (
"io"
"os"
"path"
"path/filepath"
"runtime"
"sort"
"strings"
"time"
"io/ioutil"
"github.com/minio/mc/pkg/client"
"github.com/minio/mc/pkg/hookreader"
"github.com/minio/minio-xl/pkg/probe"
"github.com/minio/mc/pkg/ioutils"
"github.com/minio/minio/pkg/probe"
)
// filesystem client
type fsClient struct {
PathURL *client.URL
PathURL *clientURL
}
const (
partSuffix = ".part.mc"
partSuffix = ".part.minio"
)
// New - instantiate a new fs client.
func New(path string) (client.Client, *probe.Error) {
var ( // GOOS specific ignore list.
ignoreFiles = map[string][]string{
"darwin": {".DS_Store"},
// "default": []string{""},
}
)
// fsNew - instantiate a new fs
func fsNew(path string) (Client, *probe.Error) {
if strings.TrimSpace(path) == "" {
return nil, probe.NewError(client.EmptyPath{})
return nil, probe.NewError(EmptyPath{})
}
return &fsClient{
PathURL: client.NewURL(normalizePath(path)),
PathURL: newClientURL(normalizePath(path)),
}, nil
}
// isIgnoredFile returns true if 'filename' is on the exclude list.
func isIgnoredFile(filename string) bool {
matchFile := path.Base(filename)
// OS specific ignore list.
for _, ignoredFile := range ignoreFiles[runtime.GOOS] {
if ignoredFile == matchFile {
return true
}
}
// Default ignore list for all OSes.
for _, ignoredFile := range ignoreFiles["default"] {
if ignoredFile == matchFile {
return true
}
}
return false
}
// URL get url.
func (f *fsClient) GetURL() client.URL {
func (f *fsClient) GetURL() clientURL {
return *f.PathURL
}
@@ -71,7 +101,7 @@ func (f *fsClient) Put(reader io.Reader, size int64, contentType string, progres
if e == nil {
// If the destination exists and is not a regular file.
if !st.Mode().IsRegular() {
return 0, probe.NewError(client.PathIsNotRegular{
return 0, probe.NewError(PathIsNotRegular{
Path: objectPath,
})
}
@@ -84,11 +114,11 @@ func (f *fsClient) Put(reader io.Reader, size int64, contentType string, progres
}
}
// Write to a temporary file "object.part.mc" before committ.
// Write to a temporary file "object.part.mc" before commit.
objectPartPath := objectPath + partSuffix
if objectDir != "" {
// Create any missing top level directories.
if e := os.MkdirAll(objectDir, 0700); e != nil {
if e = os.MkdirAll(objectDir, 0700); e != nil {
err := f.toClientError(e, f.PathURL.Path)
return 0, err.Trace(f.PathURL.Path)
}
@@ -143,7 +173,7 @@ func (f *fsClient) Put(reader io.Reader, size int64, contentType string, progres
// corruption return here.
if readAtSize != writtenSize {
// Unexpected write (less data was written than expected).
return 0, probe.NewError(client.UnexpectedShortWrite{
return 0, probe.NewError(UnexpectedShortWrite{
InputSize: readAtSize,
WriteSize: writtenSize,
})
@@ -180,13 +210,13 @@ func (f *fsClient) Put(reader io.Reader, size int64, contentType string, progres
// Close the input reader as well, if possible.
closer, ok := reader.(io.Closer)
if ok {
if e := closer.Close(); e != nil {
if e = closer.Close(); e != nil {
return totalWritten, probe.NewError(e)
}
}
// Close the file before rename.
if e := partFile.Close(); e != nil {
if e = partFile.Close(); e != nil {
return totalWritten, probe.NewError(e)
}
@@ -194,14 +224,14 @@ func (f *fsClient) Put(reader io.Reader, size int64, contentType string, progres
if size > 0 {
// Unexpected EOF reached (less data was written than expected).
if totalWritten < size {
return totalWritten, probe.NewError(client.UnexpectedEOF{
return totalWritten, probe.NewError(UnexpectedEOF{
TotalSize: size,
TotalWritten: totalWritten,
})
}
// Unexpected ExcessRead (more data was written than expected).
if totalWritten > size {
return totalWritten, probe.NewError(client.UnexpectedExcessRead{
return totalWritten, probe.NewError(UnexpectedExcessRead{
TotalSize: size,
TotalWritten: totalWritten,
})
@@ -217,7 +247,7 @@ func (f *fsClient) Put(reader io.Reader, size int64, contentType string, progres
// ShareDownload - share download not implemented for filesystem.
func (f *fsClient) ShareDownload(expires time.Duration) (string, *probe.Error) {
return "", probe.NewError(client.APINotImplemented{
return "", probe.NewError(APINotImplemented{
API: "ShareDownload",
APIType: "filesystem",
})
@@ -225,12 +255,93 @@ func (f *fsClient) ShareDownload(expires time.Duration) (string, *probe.Error) {
// ShareUpload - share upload not implemented for filesystem.
func (f *fsClient) ShareUpload(startsWith bool, expires time.Duration, contentType string) (map[string]string, *probe.Error) {
return nil, probe.NewError(client.APINotImplemented{
return nil, probe.NewError(APINotImplemented{
API: "ShareUpload",
APIType: "filesystem",
})
}
// readFile reads and returns the data inside the file located
// at the provided filepath.
func readFile(fpath string) (io.ReadCloser, error) {
// Golang strips trailing / if you clean(..) or
// EvalSymlinks(..). Adding '.' prevents it from doing so.
if strings.HasSuffix(fpath, "/") {
fpath = fpath + "."
}
fpath, e := filepath.EvalSymlinks(fpath)
if e != nil {
return nil, e
}
fileData, e := os.Open(fpath)
if e != nil {
return nil, e
}
return fileData, nil
}
// createFile creates an empty file at the provided filepath
// if one does not exist already.
func createFile(fpath string) (io.WriteCloser, error) {
st, e := os.Stat(fpath)
// If destination exists but is not regular.
if e == nil && !st.Mode().IsRegular() {
return nil, PathIsNotRegular{Path: fpath}
}
// If file exists already.
if e != nil && !os.IsNotExist(e) {
return nil, e
}
if e = os.MkdirAll(filepath.Dir(fpath), 0775); e != nil {
return nil, e
}
file, e := os.Create(fpath)
if e != nil {
return nil, e
}
return file, nil
}
// Copy - copy data from source to destination
func (f *fsClient) Copy(source string, size int64, progress io.Reader) *probe.Error {
// Don't use f.Get() f.Put() directly. Instead use readFile and createFile
destination := f.PathURL.Path
if destination == source { // Cannot copy file into itself
return errOverWriteNotAllowed(destination).Trace(destination)
}
rc, e := readFile(source)
if e != nil {
err := f.toClientError(e, destination)
return err.Trace(destination)
}
defer rc.Close()
wc, e := createFile(destination)
if e != nil {
err := f.toClientError(e, destination)
return err.Trace(destination)
}
defer wc.Close()
reader := hookreader.NewHook(rc, progress)
// Perform copy
n, e := io.CopyN(wc, reader, size) // e == nil only if n != size
// Only check size related errors if size is positive
if size > 0 {
if n < size { // Unexpected early EOF
return probe.NewError(UnexpectedEOF{
TotalSize: size,
TotalWritten: n,
})
}
if n > size { // Unexpected ExcessRead
return probe.NewError(UnexpectedExcessRead{
TotalSize: size,
TotalWritten: n,
})
}
}
return nil
}
// GetPartial download a part object from bucket.
// sets err for any errors, reader is nil for errors.
func (f *fsClient) Get() (io.Reader, *probe.Error) {
@@ -266,30 +377,71 @@ func (f *fsClient) Remove(incomplete bool) *probe.Error {
}
// List - list files and folders.
func (f *fsClient) List(recursive, incomplete bool) <-chan *client.Content {
contentCh := make(chan *client.Content)
switch recursive {
case true:
func (f *fsClient) List(recursive, incomplete bool) <-chan *clientContent {
contentCh := make(chan *clientContent)
if recursive {
go f.listRecursiveInRoutine(contentCh, incomplete)
default:
} else {
go f.listInRoutine(contentCh, incomplete)
}
return contentCh
}
// 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
}
// listPrefixes - list all files for any given prefix.
func (f *fsClient) listPrefixes(prefix string, contentCh chan<- *client.Content, incomplete bool) {
func (f *fsClient) listPrefixes(prefix string, contentCh chan<- *clientContent, incomplete bool) {
dirName := filepath.Dir(prefix)
files, e := readDir(dirName)
if e != nil {
err := f.toClientError(e, dirName)
contentCh <- &client.Content{
contentCh <- &clientContent{
Err: err.Trace(dirName),
}
return
}
pathURL := *f.PathURL
for _, fi := range files {
// Skip ignored files.
if isIgnoredFile(fi.Name()) {
continue
}
file := filepath.Join(dirName, fi.Name())
if fi.Mode()&os.ModeSymlink == os.ModeSymlink {
st, e := os.Stat(file)
@@ -303,7 +455,7 @@ func (f *fsClient) listPrefixes(prefix string, contentCh chan<- *client.Content,
newPath := filepath.Join(prefix, fi.Name())
lfi, le := f.handleWindowsSymlinks(newPath)
if le != nil {
contentCh <- &client.Content{
contentCh <- &clientContent{
Err: le.Trace(newPath),
}
continue
@@ -318,19 +470,19 @@ func (f *fsClient) listPrefixes(prefix string, contentCh chan<- *client.Content,
}
}
pathURL.Path = filepath.Join(pathURL.Path, lfi.Name())
contentCh <- &client.Content{
contentCh <- &clientContent{
URL: pathURL,
Time: lfi.ModTime(),
Size: lfi.Size(),
Type: lfi.Mode(),
Err: probe.NewError(client.PathInsufficientPermission{
Err: probe.NewError(PathInsufficientPermission{
Path: pathURL.Path,
}),
}
continue
} else {
contentCh <- &client.Content{
Err: probe.NewError(client.PathInsufficientPermission{
contentCh <- &clientContent{
Err: probe.NewError(PathInsufficientPermission{
Path: pathURL.Path,
}),
}
@@ -338,15 +490,15 @@ func (f *fsClient) listPrefixes(prefix string, contentCh chan<- *client.Content,
}
}
if os.IsNotExist(e) {
contentCh <- &client.Content{
Err: probe.NewError(client.BrokenSymlink{
contentCh <- &clientContent{
Err: probe.NewError(BrokenSymlink{
Path: pathURL.Path,
}),
}
continue
}
if e != nil {
contentCh <- &client.Content{
contentCh <- &clientContent{
Err: probe.NewError(e),
}
continue
@@ -362,8 +514,8 @@ func (f *fsClient) listPrefixes(prefix string, contentCh chan<- *client.Content,
continue
}
}
contentCh <- &client.Content{
URL: *client.NewURL(file),
contentCh <- &clientContent{
URL: *newClientURL(file),
Time: st.ModTime(),
Size: st.Size(),
Type: st.Mode(),
@@ -382,8 +534,8 @@ func (f *fsClient) listPrefixes(prefix string, contentCh chan<- *client.Content,
continue
}
}
contentCh <- &client.Content{
URL: *client.NewURL(file),
contentCh <- &clientContent{
URL: *newClientURL(file),
Time: fi.ModTime(),
Size: fi.Size(),
Type: fi.Mode(),
@@ -394,7 +546,7 @@ func (f *fsClient) listPrefixes(prefix string, contentCh chan<- *client.Content,
return
}
func (f *fsClient) listInRoutine(contentCh chan<- *client.Content, incomplete bool) {
func (f *fsClient) listInRoutine(contentCh chan<- *clientContent, incomplete bool) {
// close the channel when the function returns.
defer close(contentCh)
@@ -404,14 +556,14 @@ func (f *fsClient) listInRoutine(contentCh chan<- *client.Content, incomplete bo
fst, err := f.fsStat()
if err != nil {
if _, ok := err.ToGoError().(client.PathNotFound); ok {
if _, ok := err.ToGoError().(PathNotFound); ok {
// If file does not exist treat it like a prefix and list all prefixes if any.
prefix := fpath
f.listPrefixes(prefix, contentCh, incomplete)
return
}
// For all other errors we return genuine error back to the caller.
contentCh <- &client.Content{Err: err.Trace(fpath)}
contentCh <- &clientContent{Err: err.Trace(fpath)}
return
}
@@ -427,7 +579,7 @@ func (f *fsClient) listInRoutine(contentCh chan<- *client.Content, incomplete bo
case true:
files, e := readDir(fpath)
if err != nil {
contentCh <- &client.Content{Err: probe.NewError(e)}
contentCh <- &clientContent{Err: probe.NewError(e)}
return
}
for _, file := range files {
@@ -443,7 +595,7 @@ func (f *fsClient) listInRoutine(contentCh chan<- *client.Content, incomplete bo
newPath := filepath.Join(fpath, fi.Name())
lfi, le := f.handleWindowsSymlinks(newPath)
if le != nil {
contentCh <- &client.Content{
contentCh <- &clientContent{
Err: le.Trace(newPath),
}
continue
@@ -459,29 +611,29 @@ func (f *fsClient) listInRoutine(contentCh chan<- *client.Content, incomplete bo
}
pathURL = *f.PathURL
pathURL.Path = filepath.Join(pathURL.Path, lfi.Name())
contentCh <- &client.Content{
contentCh <- &clientContent{
URL: pathURL,
Time: lfi.ModTime(),
Size: lfi.Size(),
Type: lfi.Mode(),
Err: probe.NewError(client.PathInsufficientPermission{Path: pathURL.Path}),
Err: probe.NewError(PathInsufficientPermission{Path: pathURL.Path}),
}
continue
} else {
contentCh <- &client.Content{
Err: probe.NewError(client.PathInsufficientPermission{Path: pathURL.Path}),
contentCh <- &clientContent{
Err: probe.NewError(PathInsufficientPermission{Path: pathURL.Path}),
}
continue
}
}
if os.IsNotExist(e) {
contentCh <- &client.Content{
Err: probe.NewError(client.BrokenSymlink{Path: file.Name()}),
contentCh <- &clientContent{
Err: probe.NewError(BrokenSymlink{Path: file.Name()}),
}
continue
}
if e != nil {
contentCh <- &client.Content{
contentCh <- &clientContent{
Err: probe.NewError(e),
}
continue
@@ -499,7 +651,13 @@ func (f *fsClient) listInRoutine(contentCh chan<- *client.Content, incomplete bo
}
pathURL = *f.PathURL
pathURL.Path = filepath.Join(pathURL.Path, fi.Name())
contentCh <- &client.Content{
// Skip ignored files.
if isIgnoredFile(fi.Name()) {
continue
}
contentCh <- &clientContent{
URL: pathURL,
Time: fi.ModTime(),
Size: fi.Size(),
@@ -518,7 +676,7 @@ func (f *fsClient) listInRoutine(contentCh chan<- *client.Content, incomplete bo
return
}
}
contentCh <- &client.Content{
contentCh <- &clientContent{
URL: pathURL,
Time: fst.ModTime(),
Size: fst.Size(),
@@ -528,7 +686,7 @@ func (f *fsClient) listInRoutine(contentCh chan<- *client.Content, incomplete bo
}
}
func (f *fsClient) listRecursiveInRoutine(contentCh chan *client.Content, incomplete bool) {
func (f *fsClient) listRecursiveInRoutine(contentCh chan *clientContent, incomplete bool) {
// close channels upon return.
defer close(contentCh)
var dirName string
@@ -546,6 +704,11 @@ func (f *fsClient) listRecursiveInRoutine(contentCh chan *client.Content, incomp
return nil
}
// Ignore files from ignore list.
if isIgnoredFile(fi.Name()) {
return nil
}
/// In following situations we need to handle listing properly.
// - When filepath is '/usr' and prefix is '/usr/bi'
// - When filepath is '/usr/bin/subdir' and prefix is '/usr/bi'
@@ -555,7 +718,7 @@ func (f *fsClient) listRecursiveInRoutine(contentCh chan *client.Content, incomp
!strings.HasPrefix(filePrefix, fp) {
if e == nil {
if fi.IsDir() {
return errSkipDir
return ioutils.ErrSkipDir
}
return nil
}
@@ -571,7 +734,7 @@ func (f *fsClient) listRecursiveInRoutine(contentCh chan *client.Content, incomp
if e != nil {
// If operation is not permitted, we throw quickly back.
if strings.Contains(e.Error(), "operation not permitted") {
contentCh <- &client.Content{
contentCh <- &clientContent{
Err: probe.NewError(e),
}
return nil
@@ -580,12 +743,12 @@ func (f *fsClient) listRecursiveInRoutine(contentCh chan *client.Content, incomp
if runtime.GOOS == "windows" {
lfi, le := f.handleWindowsSymlinks(fp)
if le != nil {
contentCh <- &client.Content{
contentCh <- &clientContent{
Err: le.Trace(fp),
}
return nil
}
pathURL := *f.PathURL
pathURL = *f.PathURL
pathURL.Path = filepath.Join(pathURL.Path, dirName)
if incomplete {
if !strings.HasSuffix(lfi.Name(), partSuffix) {
@@ -596,7 +759,7 @@ func (f *fsClient) listRecursiveInRoutine(contentCh chan *client.Content, incomp
return nil
}
}
contentCh <- &client.Content{
contentCh <- &clientContent{
URL: pathURL,
Time: lfi.ModTime(),
Size: lfi.Size(),
@@ -604,8 +767,8 @@ func (f *fsClient) listRecursiveInRoutine(contentCh chan *client.Content, incomp
Err: probe.NewError(e),
}
} else {
contentCh <- &client.Content{
Err: probe.NewError(client.PathInsufficientPermission{Path: fp}),
contentCh <- &clientContent{
Err: probe.NewError(PathInsufficientPermission{Path: fp}),
}
}
return nil
@@ -619,12 +782,12 @@ func (f *fsClient) listRecursiveInRoutine(contentCh chan *client.Content, incomp
if runtime.GOOS == "windows" {
lfi, le := f.handleWindowsSymlinks(fp)
if le != nil {
contentCh <- &client.Content{
contentCh <- &clientContent{
Err: le.Trace(fp),
}
return nil
}
pathURL := *f.PathURL
pathURL = *f.PathURL
pathURL.Path = filepath.Join(pathURL.Path, dirName)
if incomplete {
if !strings.HasSuffix(lfi.Name(), partSuffix) {
@@ -635,7 +798,7 @@ func (f *fsClient) listRecursiveInRoutine(contentCh chan *client.Content, incomp
return nil
}
}
contentCh <- &client.Content{
contentCh <- &clientContent{
URL: pathURL,
Time: lfi.ModTime(),
Size: lfi.Size(),
@@ -644,29 +807,29 @@ func (f *fsClient) listRecursiveInRoutine(contentCh chan *client.Content, incomp
}
return nil
}
contentCh <- &client.Content{
contentCh <- &clientContent{
Err: probe.NewError(e),
}
return nil
}
// Ignore in-accessible broken symlinks.
if os.IsNotExist(e) {
contentCh <- &client.Content{
Err: probe.NewError(client.BrokenSymlink{Path: fp}),
contentCh <- &clientContent{
Err: probe.NewError(BrokenSymlink{Path: fp}),
}
return nil
}
// Ignore symlink loops.
if strings.Contains(e.Error(), "too many levels of symbolic links") {
contentCh <- &client.Content{
Err: probe.NewError(client.TooManyLevelsSymlink{Path: fp}),
contentCh <- &clientContent{
Err: probe.NewError(TooManyLevelsSymlink{Path: fp}),
}
return nil
}
return e
}
}
if fi.Mode().IsRegular() || fi.Mode().IsDir() {
if fi.Mode().IsRegular() {
if incomplete {
if !strings.HasSuffix(fi.Name(), partSuffix) {
return nil
@@ -676,8 +839,8 @@ func (f *fsClient) listRecursiveInRoutine(contentCh chan *client.Content, incomp
return nil
}
}
contentCh <- &client.Content{
URL: *client.NewURL(fp),
contentCh <- &clientContent{
URL: *newClientURL(fp),
Time: fi.ModTime(),
Size: fi.Size(),
Type: fi.Mode(),
@@ -703,9 +866,9 @@ func (f *fsClient) listRecursiveInRoutine(contentCh chan *client.Content, incomp
filePrefix = pathURL.Path
}
// walks invokes our custom function.
e := walk(dirName, visitFS)
e := ioutils.FTW(dirName, visitFS)
if e != nil {
contentCh <- &client.Content{
contentCh <- &clientContent{
Err: probe.NewError(e),
}
}
@@ -720,26 +883,130 @@ func (f *fsClient) MakeBucket(region string) *probe.Error {
return nil
}
// GetBucketACL - get bucket access.
func (f *fsClient) GetBucketAccess() (acl string, err *probe.Error) {
return "", probe.NewError(client.APINotImplemented{API: "GetBucketAccess", APIType: "filesystem"})
// GetAccess - get access policy permissions.
func (f *fsClient) GetAccess() (access string, err *probe.Error) {
// For windows this feature is not implemented.
if runtime.GOOS == "windows" {
return "", probe.NewError(APINotImplemented{API: "GetAccess", APIType: "filesystem"})
}
st, err := f.fsStat()
if err != nil {
return "", err.Trace(f.PathURL.String())
}
if !st.Mode().IsDir() {
return "", probe.NewError(APINotImplemented{API: "GetAccess", APIType: "filesystem"})
}
switch {
case st.Mode() == os.FileMode(0777):
return "readwrite", nil
case st.Mode() == os.FileMode(0555):
return "readonly", nil
case st.Mode() == os.FileMode(0333):
return "writeonly", nil
}
return "none", nil
}
// SetBucketAccess - set bucket access.
func (f *fsClient) SetBucketAccess(acl string) *probe.Error {
return probe.NewError(client.APINotImplemented{API: "SetBucketAccess", APIType: "filesystem"})
// SetAccess - set access policy permissions.
func (f *fsClient) SetAccess(access string) *probe.Error {
// For windows this feature is not implemented.
if runtime.GOOS == "windows" {
return probe.NewError(APINotImplemented{API: "SetAccess", APIType: "filesystem"})
}
st, err := f.fsStat()
if err != nil {
return err.Trace(f.PathURL.String())
}
if !st.Mode().IsDir() {
return probe.NewError(APINotImplemented{API: "SetAccess", APIType: "filesystem"})
}
var mode os.FileMode
switch access {
case "readonly":
mode = os.FileMode(0555)
case "writeonly":
mode = os.FileMode(0333)
case "readwrite":
mode = os.FileMode(0777)
case "none":
mode = os.FileMode(0755)
}
e := os.Chmod(f.PathURL.Path, mode)
if e != nil {
return probe.NewError(e)
}
return nil
}
// Stat - get metadata from path.
func (f *fsClient) Stat() (content *client.Content, err *probe.Error) {
func (f *fsClient) Stat() (content *clientContent, err *probe.Error) {
st, err := f.fsStat()
if err != nil {
return nil, err.Trace(f.PathURL.String())
}
content = new(client.Content)
content = &clientContent{}
content.URL = *f.PathURL
content.Size = st.Size()
content.Time = st.ModTime()
content.Type = st.Mode()
return content, nil
}
// 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(PathInsufficientPermission{Path: fpath})
}
if os.IsNotExist(e) {
return probe.NewError(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(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(PathInsufficientPermission{Path: f.PathURL.Path})
}
if os.IsNotExist(e) {
return nil, probe.NewError(PathNotFound{Path: f.PathURL.Path})
}
return nil, probe.NewError(e)
}
return st, nil
}
+100 -38
View File
@@ -14,7 +14,7 @@
* limitations under the License.
*/
package fs_test
package main
import (
"bytes"
@@ -22,28 +22,20 @@ import (
"io/ioutil"
"os"
"path/filepath"
"testing"
"runtime"
"github.com/minio/mc/pkg/client"
"github.com/minio/mc/pkg/client/fs"
. "gopkg.in/check.v1"
)
func Test(t *testing.T) { TestingT(t) }
type MySuite struct{}
var _ = Suite(&MySuite{})
// Test list files in a folder.
func (s *MySuite) TestList(c *C) {
func (s *TestSuite) TestList(c *C) {
root, e := ioutil.TempDir(os.TempDir(), "fs-")
c.Assert(e, IsNil)
defer os.RemoveAll(root)
// Create multiple files.
objectPath := filepath.Join(root, "object1")
fsClient, err := fs.New(objectPath)
fsClient, err := fsNew(objectPath)
c.Assert(err, IsNil)
data := "hello"
@@ -55,7 +47,7 @@ func (s *MySuite) TestList(c *C) {
c.Assert(n, Equals, int64(len(data)))
objectPath = filepath.Join(root, "object2")
fsClient, err = fs.New(objectPath)
fsClient, err = fsNew(objectPath)
c.Assert(err, IsNil)
reader = bytes.NewReader([]byte(data))
@@ -63,11 +55,11 @@ func (s *MySuite) TestList(c *C) {
c.Assert(err, IsNil)
c.Assert(n, Equals, int64(len(data)))
fsClient, err = fs.New(root)
fsClient, err = fsNew(root)
c.Assert(err, IsNil)
// Verify previously create files and list them.
var contents []*client.Content
var contents []*clientContent
for content := range fsClient.List(false, false) {
if content.Err != nil {
err = content.Err
@@ -81,7 +73,7 @@ func (s *MySuite) TestList(c *C) {
// Create another file.
objectPath = filepath.Join(root, "test1/newObject1")
fsClient, err = fs.New(objectPath)
fsClient, err = fsNew(objectPath)
c.Assert(err, IsNil)
reader = bytes.NewReader([]byte(data))
@@ -89,7 +81,7 @@ func (s *MySuite) TestList(c *C) {
c.Assert(err, IsNil)
c.Assert(n, Equals, int64(len(data)))
fsClient, err = fs.New(root)
fsClient, err = fsNew(root)
c.Assert(err, IsNil)
contents = nil
@@ -105,7 +97,7 @@ func (s *MySuite) TestList(c *C) {
c.Assert(len(contents), Equals, 1)
c.Assert(contents[0].Type.IsDir(), Equals, true)
fsClient, err = fs.New(root)
fsClient, err = fsNew(root)
c.Assert(err, IsNil)
contents = nil
@@ -119,7 +111,7 @@ func (s *MySuite) TestList(c *C) {
}
c.Assert(err, IsNil)
c.Assert(len(contents), Equals, 5)
c.Assert(len(contents), Equals, 3)
var regularFiles int
var regularDirs int
@@ -134,32 +126,77 @@ func (s *MySuite) TestList(c *C) {
continue
}
}
c.Assert(regularDirs, Equals, 2)
c.Assert(regularDirs, Equals, 0)
c.Assert(regularFiles, Equals, 3)
// Create an ignored file and list to verify if its ignored.
objectPath = filepath.Join(root, "test1/.DS_Store")
fsClient, err = fsNew(objectPath)
reader = bytes.NewReader([]byte(data))
n, err = fsClient.Put(reader, int64(len(data)), "application/octet-stream", nil)
c.Assert(err, IsNil)
c.Assert(n, Equals, int64(len(data)))
fsClient, err = fsNew(root)
c.Assert(err, IsNil)
contents = nil
// List recursively all files and verify.
for content := range fsClient.List(true, false) {
if content.Err != nil {
err = content.Err
break
}
contents = append(contents, content)
}
c.Assert(err, IsNil)
switch runtime.GOOS {
case "darwin":
c.Assert(len(contents), Equals, 3)
default:
c.Assert(len(contents), Equals, 4)
}
regularFiles = 0
// Test number of expected files.
for _, content := range contents {
if content.Type.IsRegular() {
regularFiles++
continue
}
}
switch runtime.GOOS {
case "darwin":
c.Assert(regularFiles, Equals, 3)
default:
c.Assert(regularFiles, Equals, 4)
}
}
// Test put bucket aka 'mkdir()' operation.
func (s *MySuite) TestPutBucket(c *C) {
func (s *TestSuite) TestPutBucket(c *C) {
root, e := ioutil.TempDir(os.TempDir(), "fs-")
c.Assert(e, IsNil)
defer os.RemoveAll(root)
bucketPath := filepath.Join(root, "bucket")
fsClient, err := fs.New(bucketPath)
fsClient, err := fsNew(bucketPath)
c.Assert(err, IsNil)
err = fsClient.MakeBucket("us-east-1")
c.Assert(err, IsNil)
}
// Test stat bucket aka 'stat()' operation.
func (s *MySuite) TestStatBucket(c *C) {
func (s *TestSuite) TestStatBucket(c *C) {
root, e := ioutil.TempDir(os.TempDir(), "fs-")
c.Assert(e, IsNil)
defer os.RemoveAll(root)
bucketPath := filepath.Join(root, "bucket")
fsClient, err := fs.New(bucketPath)
fsClient, err := fsNew(bucketPath)
c.Assert(err, IsNil)
err = fsClient.MakeBucket("us-east-1")
c.Assert(err, IsNil)
@@ -168,32 +205,35 @@ func (s *MySuite) TestStatBucket(c *C) {
}
// Test bucket acl fails for directories.
func (s *MySuite) TestBucketACLFails(c *C) {
func (s *TestSuite) TestBucketACLFails(c *C) {
root, e := ioutil.TempDir(os.TempDir(), "fs-")
c.Assert(e, IsNil)
defer os.RemoveAll(root)
bucketPath := filepath.Join(root, "bucket")
fsClient, err := fs.New(bucketPath)
fsClient, err := fsNew(bucketPath)
c.Assert(err, IsNil)
err = fsClient.MakeBucket("us-east-1")
c.Assert(err, IsNil)
err = fsClient.SetBucketAccess("private")
c.Assert(err, Not(IsNil))
// On windows setting permissions is not supported.
if runtime.GOOS != "windows" {
err = fsClient.SetAccess("readonly")
c.Assert(err, IsNil)
_, err = fsClient.GetBucketAccess()
c.Assert(err, Not(IsNil))
_, err = fsClient.GetAccess()
c.Assert(err, IsNil)
}
}
// Test creating a file.
func (s *MySuite) TestPut(c *C) {
func (s *TestSuite) TestPut(c *C) {
root, e := ioutil.TempDir(os.TempDir(), "fs-")
c.Assert(e, IsNil)
defer os.RemoveAll(root)
objectPath := filepath.Join(root, "object")
fsClient, err := fs.New(objectPath)
fsClient, err := fsNew(objectPath)
c.Assert(err, IsNil)
data := "hello"
@@ -205,13 +245,13 @@ func (s *MySuite) TestPut(c *C) {
}
// Test read a file.
func (s *MySuite) TestGet(c *C) {
func (s *TestSuite) TestGet(c *C) {
root, e := ioutil.TempDir(os.TempDir(), "fs-")
c.Assert(e, IsNil)
defer os.RemoveAll(root)
objectPath := filepath.Join(root, "object")
fsClient, err := fs.New(objectPath)
fsClient, err := fsNew(objectPath)
c.Assert(err, IsNil)
data := "hello"
@@ -231,13 +271,13 @@ func (s *MySuite) TestGet(c *C) {
}
// Test get range in a file.
func (s *MySuite) TestGetRange(c *C) {
func (s *TestSuite) TestGetRange(c *C) {
root, e := ioutil.TempDir(os.TempDir(), "fs-")
c.Assert(e, IsNil)
defer os.RemoveAll(root)
objectPath := filepath.Join(root, "object")
fsClient, err := fs.New(objectPath)
fsClient, err := fsNew(objectPath)
c.Assert(err, IsNil)
data := "hello world"
@@ -260,13 +300,13 @@ func (s *MySuite) TestGetRange(c *C) {
}
// Test stat file.
func (s *MySuite) TestStatObject(c *C) {
func (s *TestSuite) TestStatObject(c *C) {
root, e := ioutil.TempDir(os.TempDir(), "fs-")
c.Assert(e, IsNil)
defer os.RemoveAll(root)
objectPath := filepath.Join(root, "object")
fsClient, err := fs.New(objectPath)
fsClient, err := fsNew(objectPath)
c.Assert(err, IsNil)
data := "hello"
@@ -280,3 +320,25 @@ func (s *MySuite) TestStatObject(c *C) {
c.Assert(err, IsNil)
c.Assert(content.Size, Equals, int64(dataLen))
}
// Test copy.
func (s *TestSuite) TestCopy(c *C) {
root, e := ioutil.TempDir(os.TempDir(), "fs-")
c.Assert(e, IsNil)
defer os.RemoveAll(root)
sourcePath := filepath.Join(root, "source")
targetPath := filepath.Join(root, "target")
fsClientTarget, err := fsNew(targetPath)
fsClientSource, err := fsNew(sourcePath)
c.Assert(err, IsNil)
data := "hello world"
var reader io.Reader
reader = bytes.NewReader([]byte(data))
n, err := fsClientSource.Put(reader, int64(len(data)), "application/octet-stream", nil)
c.Assert(err, IsNil)
c.Assert(n, Equals, int64(len(data)))
err = fsClientTarget.Copy(sourcePath, int64(len(data)), nil)
c.Assert(err, IsNil)
}
@@ -14,9 +14,10 @@
* limitations under the License.
*/
package s3
package main
import (
"bytes"
"net/http"
"net/http/httputil"
"strings"
@@ -25,16 +26,16 @@ import (
"github.com/minio/mc/pkg/httptracer"
)
// TraceV2 - tracing structure
type TraceV2 struct{}
// traceV2 - tracing structure for signature version '2'.
type traceV2 struct{}
// NewTraceV2 - initialize Trace structure
func NewTraceV2() httptracer.HTTPTracer {
return TraceV2{}
// newTraceV2 - initialize Trace structure
func newTraceV2() httptracer.HTTPTracer {
return traceV2{}
}
// Request - Trace HTTP Request
func (t TraceV2) Request(req *http.Request) (err error) {
func (t traceV2) Request(req *http.Request) (err error) {
origAuth := req.Header.Get("Authorization")
if strings.TrimSpace(origAuth) != "" {
@@ -57,19 +58,34 @@ func (t TraceV2) Request(req *http.Request) (err error) {
}
// Response - Trace HTTP Response
func (t TraceV2) Response(res *http.Response) (err error) {
var resTrace []byte
func (t traceV2) Response(resp *http.Response) (err error) {
var respTrace []byte
// For errors we make sure to dump response body as well.
if res.StatusCode != http.StatusOK &&
res.StatusCode != http.StatusPartialContent &&
res.StatusCode != http.StatusNoContent {
resTrace, err = httputil.DumpResponse(res, true)
if resp.StatusCode != http.StatusOK &&
resp.StatusCode != http.StatusPartialContent &&
resp.StatusCode != http.StatusNoContent {
respTrace, err = httputil.DumpResponse(resp, true)
} else {
// Only display header
resTrace, err = httputil.DumpResponse(res, false)
// WORKAROUND for https://github.com/golang/go/issues/13942.
// httputil.DumpResponse does not print response headers for
// all successful calls which have response ContentLength set
// to zero. Keep this workaround until the above bug is fixed.
if resp.ContentLength == 0 {
var buffer bytes.Buffer
if err = resp.Header.Write(&buffer); err != nil {
return err
}
respTrace = buffer.Bytes()
respTrace = append(respTrace, []byte("\r\n")...)
} else {
respTrace, err = httputil.DumpResponse(resp, false)
if err != nil {
return err
}
}
}
if err == nil {
console.Debug(string(resTrace))
console.Debug(string(respTrace))
}
return err
}
@@ -14,9 +14,10 @@
* limitations under the License.
*/
package s3
package main
import (
"bytes"
"net/http"
"net/http/httputil"
"regexp"
@@ -26,16 +27,16 @@ import (
"github.com/minio/mc/pkg/httptracer"
)
// TraceV4 - tracing structure
type TraceV4 struct{}
// traceV4 - tracing structure for signature version '4'.
type traceV4 struct{}
// NewTraceV4 - initialize Trace structure
func NewTraceV4() httptracer.HTTPTracer {
return TraceV4{}
// newTraceV4 - initialize Trace structure
func newTraceV4() httptracer.HTTPTracer {
return traceV4{}
}
// Request - Trace HTTP Request
func (t TraceV4) Request(req *http.Request) (err error) {
func (t traceV4) Request(req *http.Request) (err error) {
origAuth := req.Header.Get("Authorization")
if strings.TrimSpace(origAuth) != "" {
@@ -66,19 +67,34 @@ func (t TraceV4) Request(req *http.Request) (err error) {
}
// Response - Trace HTTP Response
func (t TraceV4) Response(res *http.Response) (err error) {
var resTrace []byte
func (t traceV4) Response(resp *http.Response) (err error) {
var respTrace []byte
// For errors we make sure to dump response body as well.
if res.StatusCode != http.StatusOK &&
res.StatusCode != http.StatusPartialContent &&
res.StatusCode != http.StatusNoContent {
resTrace, err = httputil.DumpResponse(res, true)
if resp.StatusCode != http.StatusOK &&
resp.StatusCode != http.StatusPartialContent &&
resp.StatusCode != http.StatusNoContent {
respTrace, err = httputil.DumpResponse(resp, true)
} else {
// Only display header
resTrace, err = httputil.DumpResponse(res, false)
// WORKAROUND for https://github.com/golang/go/issues/13942.
// httputil.DumpResponse does not print response headers for
// all successful calls which have response ContentLength set
// to zero. Keep this workaround until the above bug is fixed.
if resp.ContentLength == 0 {
var buffer bytes.Buffer
if err = resp.Header.Write(&buffer); err != nil {
return err
}
respTrace = buffer.Bytes()
respTrace = append(respTrace, []byte("\r\n")...)
} else {
respTrace, err = httputil.DumpResponse(resp, false)
if err != nil {
return err
}
}
}
if err == nil {
console.Debug(string(resTrace))
console.Debug(string(respTrace))
}
return err
}
+197 -139
View File
@@ -14,13 +14,14 @@
* limitations under the License.
*/
package s3
package main
import (
"errors"
"hash/fnv"
"io"
"net/http"
"net/url"
"os"
"path/filepath"
"regexp"
@@ -28,36 +29,37 @@ import (
"sync"
"time"
"github.com/minio/mc/pkg/client"
"io/ioutil"
"github.com/minio/mc/pkg/httptracer"
"github.com/minio/minio-go"
"github.com/minio/minio-xl/pkg/probe"
"github.com/minio/minio/pkg/probe"
)
// S3 client
type s3Client struct {
mutex *sync.Mutex
targetURL *client.URL
api minio.CloudStorageClient
targetURL *clientURL
api *minio.Client
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)
func newFactory() func(config *Config) (Client, *probe.Error) {
clientCache := make(map[uint32]*minio.Client)
mutex := &sync.Mutex{}
// Return New function.
return func(config *client.Config) (client.Client, *probe.Error) {
return func(config *Config) (Client, *probe.Error) {
// Creates a parsed URL.
targetURL := client.NewURL(config.HostURL)
targetURL := newClientURL(config.HostURL)
// By default enable HTTPs.
inSecure := false
secure := true
if targetURL.Scheme == "http" {
inSecure = true
secure = false
}
// Instantiate s3 client.
// Instantiate s3
s3Clnt := &s3Client{}
// Allocate a new mutex.
s3Clnt.mutex = new(sync.Mutex)
@@ -87,39 +89,38 @@ func newFactory() func(config *client.Config) (client.Client, *probe.Error) {
// Lookup previous cache by hash.
mutex.Lock()
defer mutex.Unlock()
var api minio.CloudStorageClient
var api *minio.Client
found := false
if api, found = clientCache[confSum]; !found {
// Not found. Instantiate a new minio client.
// Not found. Instantiate a new minio
var e error
if config.Signature == "S3v2" {
if strings.ToUpper(config.Signature) == "S3V2" {
// if Signature version '2' use NewV2 directly.
api, e = minio.NewV2(hostName, config.AccessKey, config.SecretKey, inSecure)
api, e = minio.NewV2(hostName, config.AccessKey, config.SecretKey, secure)
} else {
// if Signature version '4' use NewV4 directly.
api, e = minio.NewV4(hostName, config.AccessKey, config.SecretKey, inSecure)
api, e = minio.NewV4(hostName, config.AccessKey, config.SecretKey, secure)
}
if e != nil {
return nil, probe.NewError(e)
}
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)
}
// 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
@@ -127,12 +128,12 @@ func newFactory() func(config *client.Config) (client.Client, *probe.Error) {
}
}
// New returns an initialized s3Client structure. If debug is enabled,
// s3New returns an initialized s3Client structure. If debug is enabled,
// it also enables an internal trace transport.
var New = newFactory()
var s3New = newFactory()
// GetURL get url.
func (c *s3Client) GetURL() client.URL {
func (c *s3Client) GetURL() clientURL {
return *c.targetURL
}
@@ -143,13 +144,66 @@ func (c *s3Client) Get() (io.Reader, *probe.Error) {
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(PathInsufficientPermission{Path: c.targetURL.String()})
}
if errResponse.Code == "NoSuchBucket" {
return nil, probe.NewError(BucketDoesNotExist{
Bucket: bucket,
})
}
if errResponse.Code == "InvalidBucketName" {
return nil, probe.NewError(BucketInvalid{
Bucket: bucket,
})
}
if errResponse.Code == "NoSuchKey" || errResponse.Code == "InvalidArgument" {
return nil, probe.NewError(ObjectMissing{})
}
return nil, probe.NewError(e)
}
return reader, nil
}
// Copy - copy object
func (c *s3Client) Copy(source string, size int64, progress io.Reader) *probe.Error {
bucket, object := c.url2BucketAndObject()
if bucket == "" {
return probe.NewError(BucketNameEmpty{})
}
// Empty copy conditions
copyConds := minio.NewCopyConditions()
e := c.api.CopyObject(bucket, object, source, copyConds)
if e != nil {
errResponse := minio.ToErrorResponse(e)
if errResponse.Code == "AccessDenied" {
return probe.NewError(PathInsufficientPermission{
Path: c.targetURL.String(),
})
}
if errResponse.Code == "NoSuchBucket" {
return probe.NewError(BucketDoesNotExist{
Bucket: bucket,
})
}
if errResponse.Code == "InvalidBucketName" {
return probe.NewError(BucketInvalid{
Bucket: bucket,
})
}
if errResponse.Code == "NoSuchKey" || errResponse.Code == "InvalidArgument" {
return probe.NewError(ObjectMissing{})
}
return probe.NewError(e)
}
// Successful copy update progress bar if there is one.
if progress != nil {
if _, e := io.CopyN(ioutil.Discard, progress, size); e != nil {
return probe.NewError(e)
}
}
return 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
@@ -160,32 +214,40 @@ func (c *s3Client) Put(reader io.Reader, size int64, contentType string, progres
if contentType == "" {
contentType = "application/octet-stream"
}
if bucket == "" {
return 0, probe.NewError(BucketNameEmpty{})
}
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{
return n, probe.NewError(UnexpectedEOF{
TotalSize: size,
TotalWritten: n,
})
}
if errResponse.Code == "AccessDenied" {
return n, probe.NewError(client.PathInsufficientPermission{
return n, probe.NewError(PathInsufficientPermission{
Path: c.targetURL.String(),
})
}
if errResponse.Code == "MethodNotAllowed" {
return n, probe.NewError(client.ObjectAlreadyExists{
return n, probe.NewError(ObjectAlreadyExists{
Object: object,
})
}
if errResponse.Code == "NoSuchBucket" {
return n, probe.NewError(client.BucketDoesNotExist{
return n, probe.NewError(BucketDoesNotExist{
Bucket: bucket,
})
}
if errResponse.Code == "InvalidArgument" {
return n, probe.NewError(client.ObjectMissing{})
if errResponse.Code == "InvalidBucketName" {
return n, probe.NewError(BucketInvalid{
Bucket: bucket,
})
}
if errResponse.Code == "NoSuchKey" || errResponse.Code == "InvalidArgument" {
return n, probe.NewError(ObjectMissing{})
}
return n, probe.NewError(e)
}
@@ -232,44 +294,38 @@ func isValidBucketName(bucketName string) *probe.Error {
func (c *s3Client) MakeBucket(region string) *probe.Error {
bucket, object := c.url2BucketAndObject()
if object != "" {
return probe.NewError(client.BucketNameTopLevel{})
return probe.NewError(BucketNameTopLevel{})
}
if err := isValidBucketName(bucket); err != nil {
return err.Trace(bucket)
}
e := c.api.MakeBucket(bucket, minio.BucketACL("private"), region)
e := c.api.MakeBucket(bucket, 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) {
// GetAccess get access policy permissions.
func (c *s3Client) GetAccess() (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{})
return "", probe.NewError(BucketNameEmpty{})
}
bucketACL, e := c.api.GetBucketACL(bucket)
bucketPolicy, e := c.api.GetBucketPolicy(bucket, object)
if e != nil {
return "", probe.NewError(e)
}
return bucketACL.String(), nil
return string(bucketPolicy), nil
}
// SetBucketAccess set acl on a bucket
func (c *s3Client) SetBucketAccess(acl string) *probe.Error {
// SetAccess set access policy permissions.
func (c *s3Client) SetAccess(bucketPolicy 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{})
return probe.NewError(BucketNameEmpty{})
}
e := c.api.SetBucketACL(bucket, minio.BucketACL(acl))
e := c.api.SetBucketPolicy(bucket, object, minio.BucketPolicy(bucketPolicy))
if e != nil {
return probe.NewError(e)
}
@@ -277,63 +333,56 @@ func (c *s3Client) SetBucketAccess(acl string) *probe.Error {
}
// Stat - send a 'HEAD' on a bucket or object to fetch its metadata.
func (c *s3Client) Stat() (*client.Content, *probe.Error) {
func (c *s3Client) Stat() (*clientContent, *probe.Error) {
c.mutex.Lock()
objectMetadata := new(client.Content)
objectMetadata := &clientContent{}
bucket, object := c.url2BucketAndObject()
switch {
// valid case for 'ls -r s3/'
case bucket == "" && object == "":
_, e := c.api.ListBuckets()
// Bucket name cannot be empty, stat on URL has no meaning.
if bucket == "" {
c.mutex.Unlock()
return nil, probe.NewError(BucketNameEmpty{})
} else if object == "" {
e := c.api.BucketExists(bucket)
if e != nil {
c.mutex.Unlock()
return nil, probe.NewError(e)
}
bucketMetadata := &clientContent{}
bucketMetadata.URL = *c.targetURL
bucketMetadata.Type = os.ModeDir
c.mutex.Unlock()
return &client.Content{URL: *c.targetURL, Type: os.ModeDir}, nil
return bucketMetadata, 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)
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 := clientContent{}
content.URL = *c.targetURL
content.Type = os.ModeDir
return &content, nil
}
return nil, probe.NewError(PathNotFound{Path: c.targetURL.Path})
}
return nil, probe.NewError(e)
}
bucketMetadata := new(client.Content)
bucketMetadata.URL = *c.targetURL
bucketMetadata.Type = os.ModeDir
objectMetadata.URL = *c.targetURL
objectMetadata.Time = metadata.LastModified
objectMetadata.Size = metadata.Size
objectMetadata.Type = os.FileMode(0664)
c.mutex.Unlock()
return bucketMetadata, nil
return objectMetadata, nil
}
func isAmazon(host string) bool {
@@ -389,11 +438,11 @@ func (c *s3Client) url2BucketAndObject() (bucketName, objectName string) {
/// Bucket API operations.
// List - list at delimited path, if not recursive.
func (c *s3Client) List(recursive, incomplete bool) <-chan *client.Content {
func (c *s3Client) List(recursive, incomplete bool) <-chan *clientContent {
c.mutex.Lock()
defer c.mutex.Unlock()
contentCh := make(chan *client.Content)
contentCh := make(chan *clientContent)
if incomplete {
if recursive {
go c.listIncompleteRecursiveInRoutine(contentCh)
@@ -410,7 +459,7 @@ func (c *s3Client) List(recursive, incomplete bool) <-chan *client.Content {
return contentCh
}
func (c *s3Client) listIncompleteInRoutine(contentCh chan *client.Content) {
func (c *s3Client) listIncompleteInRoutine(contentCh chan *clientContent) {
defer close(contentCh)
// get bucket and object from URL.
b, o := c.url2BucketAndObject()
@@ -418,7 +467,7 @@ func (c *s3Client) listIncompleteInRoutine(contentCh chan *client.Content) {
case b == "" && o == "":
buckets, err := c.api.ListBuckets()
if err != nil {
contentCh <- &client.Content{
contentCh <- &clientContent{
Err: probe.NewError(err),
}
return
@@ -427,12 +476,12 @@ func (c *s3Client) listIncompleteInRoutine(contentCh chan *client.Content) {
for _, bucket := range buckets {
for object := range c.api.ListIncompleteUploads(bucket.Name, o, isRecursive, nil) {
if object.Err != nil {
contentCh <- &client.Content{
contentCh <- &clientContent{
Err: probe.NewError(object.Err),
}
return
}
content := new(client.Content)
content := &clientContent{}
url := *c.targetURL
// Join bucket with - incoming object key.
url.Path = filepath.Join(string(url.Separator), bucket.Name, object.Key)
@@ -458,12 +507,12 @@ func (c *s3Client) listIncompleteInRoutine(contentCh chan *client.Content) {
isRecursive := false
for object := range c.api.ListIncompleteUploads(b, o, isRecursive, nil) {
if object.Err != nil {
contentCh <- &client.Content{
contentCh <- &clientContent{
Err: probe.NewError(object.Err),
}
return
}
content := new(client.Content)
content := &clientContent{}
url := *c.targetURL
// Join bucket with - incoming object key.
url.Path = filepath.Join(string(url.Separator), b, object.Key)
@@ -487,7 +536,7 @@ func (c *s3Client) listIncompleteInRoutine(contentCh chan *client.Content) {
}
}
func (c *s3Client) listIncompleteRecursiveInRoutine(contentCh chan *client.Content) {
func (c *s3Client) listIncompleteRecursiveInRoutine(contentCh chan *clientContent) {
defer close(contentCh)
// get bucket and object from URL.
b, o := c.url2BucketAndObject()
@@ -495,7 +544,7 @@ func (c *s3Client) listIncompleteRecursiveInRoutine(contentCh chan *client.Conte
case b == "" && o == "":
buckets, err := c.api.ListBuckets()
if err != nil {
contentCh <- &client.Content{
contentCh <- &clientContent{
Err: probe.NewError(err),
}
return
@@ -504,14 +553,14 @@ func (c *s3Client) listIncompleteRecursiveInRoutine(contentCh chan *client.Conte
for _, bucket := range buckets {
for object := range c.api.ListIncompleteUploads(bucket.Name, o, isRecursive, nil) {
if object.Err != nil {
contentCh <- &client.Content{
contentCh <- &clientContent{
Err: probe.NewError(object.Err),
}
return
}
url := *c.targetURL
url.Path = filepath.Join(url.Path, bucket.Name, object.Key)
content := new(client.Content)
content := &clientContent{}
content.URL = url
content.Size = object.Size
content.Time = object.Initiated
@@ -523,7 +572,7 @@ func (c *s3Client) listIncompleteRecursiveInRoutine(contentCh chan *client.Conte
isRecursive := true
for object := range c.api.ListIncompleteUploads(b, o, isRecursive, nil) {
if object.Err != nil {
contentCh <- &client.Content{
contentCh <- &clientContent{
Err: probe.NewError(object.Err),
}
return
@@ -534,7 +583,7 @@ func (c *s3Client) listIncompleteRecursiveInRoutine(contentCh chan *client.Conte
if c.virtualStyle {
url.Path = filepath.Join(string(url.Separator), object.Key)
}
content := new(client.Content)
content := &clientContent{}
content.URL = url
content.Size = object.Size
content.Time = object.Initiated
@@ -544,23 +593,23 @@ func (c *s3Client) listIncompleteRecursiveInRoutine(contentCh chan *client.Conte
}
}
func (c *s3Client) listInRoutine(contentCh chan *client.Content) {
func (c *s3Client) listInRoutine(contentCh chan *clientContent) {
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),
buckets, e := c.api.ListBuckets()
if e != nil {
contentCh <- &clientContent{
Err: probe.NewError(e),
}
return
}
for _, bucket := range buckets {
url := *c.targetURL
url.Path = filepath.Join(url.Path, bucket.Name)
content := new(client.Content)
content := &clientContent{}
content.URL = url
content.Size = 0
content.Time = bucket.CreationDate
@@ -568,21 +617,28 @@ func (c *s3Client) listInRoutine(contentCh chan *client.Content) {
contentCh <- content
}
case b != "" && !strings.HasSuffix(c.targetURL.Path, string(c.targetURL.Separator)) && o == "":
e := c.api.BucketExists(b)
buckets, e := c.api.ListBuckets()
if e != nil {
contentCh <- &client.Content{
contentCh <- &clientContent{
Err: probe.NewError(e),
}
}
content := new(client.Content)
content.URL = *c.targetURL
content.Type = os.ModeDir
contentCh <- content
for _, bucket := range buckets {
if bucket.Name == b {
content := &clientContent{}
content.URL = *c.targetURL
content.Size = 0
content.Time = bucket.CreationDate
content.Type = os.ModeDir
contentCh <- content
break
}
}
default:
metadata, e := c.api.StatObject(b, o)
switch e.(type) {
case nil:
content := new(client.Content)
content := &clientContent{}
content.URL = *c.targetURL
content.Time = metadata.LastModified
content.Size = metadata.Size
@@ -592,12 +648,12 @@ func (c *s3Client) listInRoutine(contentCh chan *client.Content) {
isRecursive := false
for object := range c.api.ListObjects(b, o, isRecursive, nil) {
if object.Err != nil {
contentCh <- &client.Content{
contentCh <- &clientContent{
Err: probe.NewError(object.Err),
}
return
}
content := new(client.Content)
content := &clientContent{}
url := *c.targetURL
// Join bucket and incoming object key.
url.Path = filepath.Join(string(url.Separator), b, object.Key)
@@ -622,7 +678,7 @@ func (c *s3Client) listInRoutine(contentCh chan *client.Content) {
}
}
func (c *s3Client) listRecursiveInRoutine(contentCh chan *client.Content) {
func (c *s3Client) listRecursiveInRoutine(contentCh chan *clientContent) {
defer close(contentCh)
// get bucket and object from URL.
b, o := c.url2BucketAndObject()
@@ -630,7 +686,7 @@ func (c *s3Client) listRecursiveInRoutine(contentCh chan *client.Content) {
case b == "" && o == "":
buckets, err := c.api.ListBuckets()
if err != nil {
contentCh <- &client.Content{
contentCh <- &clientContent{
Err: probe.NewError(err),
}
return
@@ -638,7 +694,7 @@ func (c *s3Client) listRecursiveInRoutine(contentCh chan *client.Content) {
for _, bucket := range buckets {
bucketURL := *c.targetURL
bucketURL.Path = filepath.Join(bucketURL.Path, bucket.Name)
contentCh <- &client.Content{
contentCh <- &clientContent{
URL: bucketURL,
Type: os.ModeDir,
Time: bucket.CreationDate,
@@ -646,12 +702,12 @@ func (c *s3Client) listRecursiveInRoutine(contentCh chan *client.Content) {
isRecursive := true
for object := range c.api.ListObjects(bucket.Name, o, isRecursive, nil) {
if object.Err != nil {
contentCh <- &client.Content{
contentCh <- &clientContent{
Err: probe.NewError(object.Err),
}
continue
}
content := new(client.Content)
content := &clientContent{}
objectURL := *c.targetURL
objectURL.Path = filepath.Join(objectURL.Path, bucket.Name, object.Key)
content.URL = objectURL
@@ -665,12 +721,12 @@ func (c *s3Client) listRecursiveInRoutine(contentCh chan *client.Content) {
isRecursive := true
for object := range c.api.ListObjects(b, o, isRecursive, nil) {
if object.Err != nil {
contentCh <- &client.Content{
contentCh <- &clientContent{
Err: probe.NewError(object.Err),
}
continue
}
content := new(client.Content)
content := &clientContent{}
url := *c.targetURL
// Join bucket and incoming object key.
url.Path = filepath.Join(string(url.Separator), b, object.Key)
@@ -690,11 +746,13 @@ func (c *s3Client) listRecursiveInRoutine(contentCh chan *client.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)
// No additional request parameters are set for the time being.
reqParams := make(url.Values)
presignedURL, e := c.api.PresignedGetObject(bucket, object, expires, reqParams)
if e != nil {
return "", probe.NewError(e)
}
return presignedURL, nil
return presignedURL.String(), nil
}
// ShareUpload - get data for presigned post http form upload.
@@ -720,6 +778,6 @@ func (c *s3Client) ShareUpload(isRecursive bool, expires time.Duration, contentT
return nil, probe.NewError(e)
}
}
m, e := c.api.PresignedPostPolicy(p)
_, m, e := c.api.PresignedPostPolicy(p)
return m, probe.NewError(e)
}
+10 -29
View File
@@ -14,7 +14,7 @@
* limitations under the License.
*/
package s3
package main
// bucketHandler is an http.Handler that verifies bucket responses and validates incoming requests
import (
@@ -23,11 +23,8 @@ import (
"net/http"
"net/http/httptest"
"strconv"
"testing"
"time"
"github.com/minio/mc/pkg/client"
. "gopkg.in/check.v1"
)
@@ -60,13 +57,6 @@ func (h bucketHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
case r.Method == "PUT":
switch {
case r.URL.Path == h.resource:
// Handler for incoming SetBucketACL request.
_, ok := r.URL.Query()["acl"]
if ok {
if r.Header.Get("x-amz-acl") != "public-read-write" {
w.WriteHeader(http.StatusNotImplemented)
}
}
w.WriteHeader(http.StatusOK)
default:
w.WriteHeader(http.StatusBadRequest)
@@ -168,36 +158,27 @@ func (h objectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
}
func Test(t *testing.T) { TestingT(t) }
type MySuite struct{}
var _ = Suite(&MySuite{})
// Test bucket operations.
func (s *MySuite) TestBucketOperations(c *C) {
func (s *TestSuite) TestBucketOperations(c *C) {
bucket := bucketHandler(bucketHandler{
resource: "/bucket/",
})
server := httptest.NewServer(bucket)
defer server.Close()
conf := new(client.Config)
conf := new(Config)
conf.HostURL = server.URL + bucket.resource
conf.AccessKey = "WLGDGYAQYIGI833EV05A"
conf.SecretKey = "BYvgJM101sHngl2uzjXS/OBF/aMxAN06JrJ3qJlF"
conf.Signature = "S3v4"
s3c, err := New(conf)
s3c, err := s3New(conf)
c.Assert(err, IsNil)
err = s3c.MakeBucket("us-east-1")
c.Assert(err, IsNil)
err = s3c.SetBucketAccess("public-read-write")
c.Assert(err, IsNil)
conf.HostURL = server.URL + string(s3c.GetURL().Separator)
s3c, err = New(conf)
s3c, err = s3New(conf)
c.Assert(err, IsNil)
for content := range s3c.List(false, false) {
@@ -206,7 +187,7 @@ func (s *MySuite) TestBucketOperations(c *C) {
}
conf.HostURL = server.URL + "/bucket"
s3c, err = New(conf)
s3c, err = s3New(conf)
c.Assert(err, IsNil)
for content := range s3c.List(false, false) {
@@ -215,7 +196,7 @@ func (s *MySuite) TestBucketOperations(c *C) {
}
conf.HostURL = server.URL + "/bucket/"
s3c, err = New(conf)
s3c, err = s3New(conf)
c.Assert(err, IsNil)
for content := range s3c.List(false, false) {
@@ -225,7 +206,7 @@ func (s *MySuite) TestBucketOperations(c *C) {
}
// Test all object operations.
func (s *MySuite) TestObjectOperations(c *C) {
func (s *TestSuite) TestObjectOperations(c *C) {
object := objectHandler(objectHandler{
resource: "/bucket/object",
data: []byte("Hello, World"),
@@ -233,12 +214,12 @@ func (s *MySuite) TestObjectOperations(c *C) {
server := httptest.NewServer(object)
defer server.Close()
conf := new(client.Config)
conf := new(Config)
conf.HostURL = server.URL + object.resource
conf.AccessKey = "WLGDGYAQYIGI833EV05A"
conf.SecretKey = "BYvgJM101sHngl2uzjXS/OBF/aMxAN06JrJ3qJlF"
conf.Signature = "S3v4"
s3c, err := New(conf)
s3c, err := s3New(conf)
c.Assert(err, IsNil)
var reader io.Reader
+96 -22
View File
@@ -14,19 +14,22 @@
* limitations under the License.
*/
package client
package main
import (
"bytes"
"mime"
"path/filepath"
"regexp"
"runtime"
"strings"
"github.com/minio/minio/pkg/probe"
)
// URL client url structure
type URL struct {
Type URLType
// url client url structure
type clientURL struct {
Type clientURLType
Scheme string
Host string
Path string
@@ -34,13 +37,13 @@ type URL struct {
Separator rune
}
// URLType - enum of different url types
type URLType int
// clientURLType - enum of different url types
type clientURLType int
// enum types
const (
Object = iota // Minio and S3 compatible cloud storage
Filesystem // POSIX compatible file systems
objectStorage = iota // Minio and S3 compatible cloud storage
fileSystem // POSIX compatible file systems
)
// Maybe rawurl is of the form scheme:path. (Scheme must be [a-zA-Z][a-zA-Z0-9+-.]*)
@@ -87,10 +90,9 @@ func getHost(authority string) (host string) {
return authority
}
// NewURL returns an abstracted URL for filesystems and object storage.
func NewURL(urlStr string) *URL {
// newClientURL returns an abstracted URL for filesystems and object storage.
func newClientURL(urlStr string) *clientURL {
scheme, rest := getScheme(urlStr)
rest, _ = splitSpecial(rest, "?", true)
if strings.HasPrefix(rest, "//") {
// if rest has '//' prefix, skip them
var authority string
@@ -100,9 +102,9 @@ func NewURL(urlStr string) *URL {
}
host := getHost(authority)
if host != "" && (scheme == "http" || scheme == "https") {
return &URL{
return &clientURL{
Scheme: scheme,
Type: Object,
Type: objectStorage,
Host: host,
Path: rest,
SchemeSeparator: "://",
@@ -110,15 +112,15 @@ func NewURL(urlStr string) *URL {
}
}
}
return &URL{
Type: Filesystem,
return &clientURL{
Type: fileSystem,
Path: rest,
Separator: filepath.Separator,
}
}
// JoinURLs join two input urls and returns a url
func JoinURLs(url1, url2 *URL) *URL {
// joinURLs join two input urls and returns a url
func joinURLs(url1, url2 *clientURL) *clientURL {
var url1Path, url2Path string
url1Path = filepath.ToSlash(url1.Path)
url2Path = filepath.ToSlash(url2.Path)
@@ -131,14 +133,14 @@ func JoinURLs(url1, url2 *URL) *URL {
}
// String convert URL into its canonical form.
func (u URL) String() string {
func (u clientURL) String() string {
var buf bytes.Buffer
// if fileystem no translation needed, return as is.
if u.Type == Filesystem {
// if fileSystem no translation needed, return as is.
if u.Type == fileSystem {
return u.Path
}
// if Object convert from any non standard paths to a supported URL path style.
if u.Type == Object {
// if objectStorage convert from any non standard paths to a supported URL path style.
if u.Type == objectStorage {
buf.WriteString(u.Scheme)
buf.WriteByte(':')
buf.WriteString("//")
@@ -160,3 +162,75 @@ func (u URL) String() string {
}
return buf.String()
}
func isURLVirtualHostStyle(hostURL string) bool {
matchS3, _ := filepath.Match("*.s3*.amazonaws.com", hostURL)
matchGoogle, _ := filepath.Match("*.storage.googleapis.com", hostURL)
return matchS3 || matchGoogle
}
// urlJoinPath Join a path to existing URL.
func urlJoinPath(url1, url2 string) string {
u1 := newClientURL(url1)
u2 := newClientURL(url2)
return joinURLs(u1, u2).String()
}
// url2Stat returns stat info for URL.
func url2Stat(urlStr string) (client Client, content *clientContent, err *probe.Error) {
client, err = newClient(urlStr)
if err != nil {
return nil, nil, err.Trace(urlStr)
}
content, err = client.Stat()
if err != nil {
return nil, nil, err.Trace(urlStr)
}
return client, content, nil
}
// url2Alias separates alias and path from the URL. Aliased URL is of
// the form [/]alias/path/to/blah.
func url2Alias(aliasedURL string) (alias, path string) {
// Save aliased url.
urlStr := aliasedURL
// Convert '/' on windows to filepath.Separator.
urlStr = filepath.FromSlash(urlStr)
// Remove '/' prefix before alias, if any.
urlStr = strings.TrimPrefix(urlStr, string(filepath.Separator))
// Remove everything after alias (i.e. after '/').
urlParts := strings.SplitN(urlStr, string(filepath.Separator), 2)
if len(urlParts) == 2 {
// Convert windows style path separator to Unix style.
return urlParts[0], urlParts[1]
}
return urlParts[0], ""
}
// isURLPrefixExists - check if object key prefix exists.
func isURLPrefixExists(urlPrefix string, incomplete bool) bool {
clnt, err := newClient(urlPrefix)
if err != nil {
return false
}
isRecursive := false
isIncomplete := incomplete
for entry := range clnt.List(isRecursive, isIncomplete) {
return entry.Err == nil
}
return false
}
// guessURLContentType - guess content-type of the URL.
// on failure just return 'application/octet-stream'.
func guessURLContentType(urlStr string) string {
url := newClientURL(urlStr)
contentType := mime.TypeByExtension(filepath.Ext(url.Path))
if contentType == "" {
contentType = "application/octet-stream"
}
return contentType
}
+14
View File
@@ -18,6 +18,20 @@ package main
import . "gopkg.in/check.v1"
// TestURL - tests url parsing and fields.
func (s *TestSuite) TestURL(c *C) {
urlStr := "foo?.go"
url := newClientURL(urlStr)
c.Assert(url.Path, Equals, "foo?.go")
urlStr = "https://s3.amazonaws.com/mybucket/foo?.go"
url = newClientURL(urlStr)
c.Assert(url.Scheme, Equals, "https")
c.Assert(url.Host, Equals, "s3.amazonaws.com")
c.Assert(url.Path, Equals, "/mybucket/foo?.go")
}
// TestURLJoinPath - tests joining two different urls.
func (s *TestSuite) TestURLJoinPath(c *C) {
// Join two URLs
url1 := "http://s3.mycompany.io/dev"
+12 -9
View File
@@ -14,30 +14,33 @@
* limitations under the License.
*/
package client
package main
import (
"io"
"os"
"time"
"github.com/minio/minio-xl/pkg/probe"
"github.com/minio/minio/pkg/probe"
)
// Client - client interface
type Client interface {
// Common operations
Stat() (content *Content, err *probe.Error)
List(recursive, incomplete bool) <-chan *Content
Stat() (content *clientContent, err *probe.Error)
List(recursive, incomplete bool) <-chan *clientContent
// Bucket operations
MakeBucket(region string) *probe.Error
GetBucketAccess() (access string, error *probe.Error)
SetBucketAccess(access string) *probe.Error
// Access policy operations.
GetAccess() (access string, error *probe.Error)
SetAccess(access string) *probe.Error
// I/O operations
Get() (reader io.Reader, err *probe.Error)
Put(reader io.Reader, size int64, contentType string, progress io.Reader) (n int64, err *probe.Error)
Copy(source string, size int64, progress io.Reader) *probe.Error
// I/O operations with expiration
ShareDownload(expires time.Duration) (string, *probe.Error)
@@ -47,12 +50,12 @@ type Client interface {
Remove(incomplete bool) *probe.Error
// GetURL returns back internal url
GetURL() URL
GetURL() clientURL
}
// Content container for content metadata
type Content struct {
URL URL
type clientContent struct {
URL clientURL
Time time.Time
Size int64
Type os.FileMode
+47 -12
View File
@@ -23,15 +23,13 @@ import (
"runtime"
"strings"
"github.com/minio/mc/pkg/client"
"github.com/minio/mc/pkg/client/fs"
"github.com/minio/mc/pkg/client/s3"
"github.com/minio/minio-xl/pkg/probe"
"github.com/minio/mc/pkg/console"
"github.com/minio/minio/pkg/probe"
)
// Check if the target URL represents folder. It may or may not exist yet.
func isTargetURLDir(targetURL string) bool {
targetURLParse := client.NewURL(targetURL)
targetURLParse := newClientURL(targetURL)
_, targetContent, err := url2Stat(targetURL)
if err != nil {
_, aliasedTargetURL, _ := mustExpandAlias(targetURL)
@@ -98,15 +96,28 @@ func putTargetStream(urlStr string, reader io.Reader, size int64) (int64, *probe
return putTargetStreamFromAlias(alias, urlStrFull, reader, size, nil)
}
// copyTargetStreamFromAlias copies to URL from source.
func copySourceStreamFromAlias(alias string, urlStr string, source string, size int64, progress io.Reader) *probe.Error {
targetClnt, err := newClientFromAlias(alias, urlStr)
if err != nil {
return err.Trace(alias, urlStr)
}
err = targetClnt.Copy(source, size, progress)
if err != nil {
return err.Trace(alias, urlStr)
}
return nil
}
// 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) {
func newClientFromAlias(alias string, urlStr string) (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)
fsClient, err := fsNew(urlStr)
if err != nil {
return nil, err.Trace(alias, urlStr)
}
@@ -115,9 +126,33 @@ func newClientFromAlias(alias string, urlStr string) (client.Client, *probe.Erro
// 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 := new(Config)
// secretKey retrieved from the environement overrides the one
// present in the config file
keysPairEnv := os.Getenv("MC_SECRET_" + alias)
keysPairArray := strings.Split(keysPairEnv, ":")
var accessKeyEnv, secretKeyEnv string
if len(keysPairArray) >= 1 {
accessKeyEnv = keysPairArray[0]
}
if len(keysPairArray) >= 2 {
secretKeyEnv = keysPairArray[1]
}
if len(keysPairEnv) > 0 &&
isValidAccessKey(accessKeyEnv) && isValidSecretKey(secretKeyEnv) {
s3Config.AccessKey = accessKeyEnv
s3Config.SecretKey = secretKeyEnv
} else {
if len(keysPairEnv) > 0 {
console.Errorln("Access/Secret keys associated to `" + alias + "' " +
"are found in your environment but not suitable for use. " +
"Falling back to the standard config.")
}
s3Config.AccessKey = hostCfg.AccessKey
s3Config.SecretKey = hostCfg.SecretKey
}
s3Config.Signature = hostCfg.API
s3Config.AppName = "mc"
s3Config.AppVersion = mcVersion
@@ -125,7 +160,7 @@ func newClientFromAlias(alias string, urlStr string) (client.Client, *probe.Erro
s3Config.HostURL = urlStr
s3Config.Debug = globalDebug
s3Client, err := s3.New(s3Config)
s3Client, err := s3New(s3Config)
if err != nil {
return nil, err.Trace(alias, urlStr)
}
@@ -136,7 +171,7 @@ func newClientFromAlias(alias string, urlStr string) (client.Client, *probe.Erro
var urlRgx = regexp.MustCompile("^https?://")
// newClient gives a new client interface
func newClient(aliasedURL string) (client.Client, *probe.Error) {
func newClient(aliasedURL string) (Client, *probe.Error) {
alias, urlStrFull, hostCfg, err := expandAlias(aliasedURL)
if err != nil {
return nil, err.Trace(aliasedURL)
+2 -3
View File
@@ -20,9 +20,8 @@ import (
"fmt"
"strings"
"github.com/minio/mc/pkg/client"
"github.com/minio/mc/pkg/console"
"github.com/minio/minio-xl/pkg/quick"
"github.com/minio/minio/pkg/quick"
)
func fixConfig() {
@@ -132,7 +131,7 @@ func fixConfigV6ForHosts() {
newCfgV6.Aliases[k] = v
}
url := new(client.URL)
url := &clientURL{}
// Copy hosts.
for host, hostCfgV6 := range brokenMcCfgV6.Data().(*configV6).Hosts {
// Already fixed - Copy and move on.
+15 -17
View File
@@ -24,7 +24,7 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/console"
"github.com/minio/minio-xl/pkg/probe"
"github.com/minio/minio/pkg/probe"
)
var (
@@ -58,11 +58,11 @@ FLAGS:
EXAMPLES:
1. Add Amazon S3 storage service under "myphotos" alias. For security reasons turn off bash history momentarily.
$ set +o history
$ mc config {{.Name}} add myphotos https://s3.amazonaws.com BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12
$ mc config {{.Name}} add myphotos https://s3.amazonaws.com BKIKJAA5BMMU2RHO6IBB V8f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12
$ set -o history
2. Add Google Cloud Storage service under "goodisk" alias.
$ mc config {{.Name}} add goodisk https://storage.googleapis.com BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 S3v2
$ mc config {{.Name}} add goodisk https://storage.googleapis.com BKIKJAA5BMMU2RHO6IBB V8f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 S3v2
3. List all hosts.
$ mc config {{.Name}} list
@@ -165,11 +165,9 @@ func checkConfigHostAddSyntax(ctx *cli.Context) {
"Invalid secret key ‘"+secretKey+"’.")
}
switch api {
case "S3v2", "S3v4", "":
default:
if api != "" && !isValidAPI(api) { // Empty value set to default "S3v4".
fatalIf(errInvalidArgument().Trace(api),
"Unrecognized API signature. Valid options are ‘[ S3v4, S3v2 ]’.")
"Unrecognized API signature. Valid options are ‘[S3v4, S3v2]’.")
}
}
@@ -214,10 +212,10 @@ func mainConfigHost(ctx *cli.Context) {
accessKey := args.Get(2)
secretKey := args.Get(3)
api := args.Get(4)
if strings.TrimSpace(api) == "" {
if api == "" {
api = "S3v4"
}
hostCfg := hostConfigV7{
hostCfg := hostConfigV8{
URL: url,
AccessKey: accessKey,
SecretKey: secretKey,
@@ -233,23 +231,23 @@ func mainConfigHost(ctx *cli.Context) {
}
// addHost - add a host config.
func addHost(alias string, hostCfgV7 hostConfigV7) {
mcCfgV7, err := loadMcConfig()
func addHost(alias string, hostCfgV8 hostConfigV8) {
mcCfgV8, err := loadMcConfig()
fatalIf(err.Trace(globalMCConfigVersion), "Unable to load config ‘"+mustGetMcConfigPath()+"’.")
// Add new host.
mcCfgV7.Hosts[alias] = hostCfgV7
mcCfgV8.Hosts[alias] = hostCfgV8
err = saveMcConfig(mcCfgV7)
err = saveMcConfig(mcCfgV8)
fatalIf(err.Trace(alias), "Unable to update hosts in config version ‘"+mustGetMcConfigPath()+"’.")
printMsg(hostMessage{
op: "add",
Alias: alias,
URL: hostCfgV7.URL,
AccessKey: hostCfgV7.AccessKey,
SecretKey: hostCfgV7.SecretKey,
API: hostCfgV7.API,
URL: hostCfgV8.URL,
AccessKey: hostCfgV8.AccessKey,
SecretKey: hostCfgV8.SecretKey,
API: hostCfgV8.API,
})
}
+58 -1
View File
@@ -21,7 +21,7 @@ import (
"strings"
"github.com/minio/mc/pkg/console"
"github.com/minio/minio-xl/pkg/quick"
"github.com/minio/minio/pkg/quick"
)
// migrate config files from the any older version to the latest.
@@ -40,6 +40,8 @@ func migrateConfig() {
migrateConfigV5ToV6()
// Migrate config V6 to V7
migrateConfigV6ToV7()
// Migrate config V7 to V8
migrateConfigV7ToV8()
}
// Migrate from config version 1.0 to 1.0.1. Populate example entries and save it back.
@@ -332,8 +334,24 @@ func migrateConfigV6ToV7() {
cfgV7 := newConfigV7()
aliasIndex := 0
// old Aliases.
oldAliases := mcCfgV6.Data().(*configV6).Aliases
// We dropped alias support in v7. We only need to migrate host configs.
for host, hostCfgV6 := range mcCfgV6.Data().(*configV6).Hosts {
// Look through old aliases, if found any matching save those entries.
for aliasName, aliasedHost := range oldAliases {
if aliasedHost == host {
cfgV7.Hosts[aliasName] = hostConfigV7{
URL: host,
AccessKey: hostCfgV6.AccessKeyID,
SecretKey: hostCfgV6.SecretAccessKey,
API: hostCfgV6.API,
}
continue
}
}
if hostCfgV6.AccessKeyID == "YOUR-ACCESS-KEY-ID-HERE" ||
hostCfgV6.SecretAccessKey == "YOUR-SECRET-ACCESS-KEY-HERE" ||
hostCfgV6.AccessKeyID == "" ||
@@ -378,3 +396,42 @@ func migrateConfigV6ToV7() {
console.Infof("Successfully migrated %s from version ‘6’ to version ‘7’.\n", mustGetMcConfigPath())
}
// Migrate config version ‘7’ to ‘8'. Remove hosts
// 'play.minio.io:9002' and 'dl.minio.io:9000'.
func migrateConfigV7ToV8() {
if !isMcConfigExists() {
return
}
mcCfgV7, err := quick.Load(mustGetMcConfigPath(), newConfigV7())
fatalIf(err.Trace(), "Unable to load mc config V7.")
if mcCfgV7.Version() != "7" {
return
}
cfgV8 := newConfigV8()
// We dropped alias support in v7. We only need to migrate host configs.
for host, hostCfgV7 := range mcCfgV7.Data().(*configV7).Hosts {
// Ignore 'player', 'play' and 'dl' aliases.
if host == "player" || host == "dl" || host == "play" {
continue
}
hostCfgV8 := hostConfigV8{}
hostCfgV8.URL = hostCfgV7.URL
hostCfgV8.AccessKey = hostCfgV7.AccessKey
hostCfgV8.SecretKey = hostCfgV7.SecretKey
hostCfgV8.API = hostCfgV7.API
cfgV8.Hosts[host] = hostCfgV8
}
// Load default settings.
cfgV8.loadDefaults()
mcNewCfgV8, err := quick.New(cfgV8)
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘8’.")
err = mcNewCfgV8.Save(mustGetMcConfigPath())
fatalIf(err.Trace(), "Unable to save config version ‘8’.")
console.Infof("Successfully migrated %s from version ‘7’ to version ‘8’.\n", mustGetMcConfigPath())
}
+81 -1
View File
@@ -160,5 +160,85 @@ func newConfigV6() *configV6 {
return conf
}
/////////////////// Config V7 ///////////////////
/////////////////// Config V6 ///////////////////
// hostConfig configuration of a host - version '7'.
type hostConfigV7 struct {
URL string `json:"url"`
AccessKey string `json:"accessKey"`
SecretKey string `json:"secretKey"`
API string `json:"api"`
}
// configV7 config version.
type configV7 struct {
Version string `json:"version"`
Hosts map[string]hostConfigV7 `json:"hosts"`
}
// newConfigV7 - new config version '7'.
func newConfigV7() *configV7 {
cfg := new(configV7)
cfg.Version = "7"
cfg.Hosts = make(map[string]hostConfigV7)
return cfg
}
func (c *configV7) loadDefaults() {
// Minio server running locally.
c.setHost("local", hostConfigV7{
URL: "http://localhost:9000",
AccessKey: "",
SecretKey: "",
API: "S3v4",
})
// Amazon S3 cloud storage service.
c.setHost("s3", hostConfigV7{
URL: "https://s3.amazonaws.com",
AccessKey: defaultAccessKey,
SecretKey: defaultSecretKey,
API: "S3v4",
})
// Google cloud storage service.
c.setHost("gcs", hostConfigV7{
URL: "https://storage.googleapis.com",
AccessKey: defaultAccessKey,
SecretKey: defaultSecretKey,
API: "S3v2",
})
// Minio anonymous server for demo.
c.setHost("play", hostConfigV7{
URL: "https://play.minio.io:9000",
AccessKey: "",
SecretKey: "",
API: "S3v4",
})
// Minio demo server with public secret and access keys.
c.setHost("player", hostConfigV7{
URL: "https://play.minio.io:9002",
AccessKey: "Q3AM3UQ867SPQQA43P2F",
SecretKey: "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG",
API: "S3v4",
})
// Minio public download service.
c.setHost("dl", hostConfigV7{
URL: "https://dl.minio.io:9000",
AccessKey: "",
SecretKey: "",
API: "S3v4",
})
}
// SetHost sets host config if not empty.
func (c *configV7) setHost(alias string, cfg hostConfigV7) {
if _, ok := c.Hosts[alias]; !ok {
c.Hosts[alias] = cfg
}
}
/////////////////// Config V8 ///////////////////
// RESERVED FOR FUTURE
+33 -7
View File
@@ -1,19 +1,35 @@
/*
* Minio Client (C) 2015, 2016 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package main
import (
"regexp"
"strings"
"github.com/minio/mc/pkg/client"
)
var validAPIs = []string{"S3v4", "S3v2"}
// isValidSecretKey - validate secret key.
func isValidSecretKey(secretKey string) bool {
if secretKey == "" {
return true
}
regex := regexp.MustCompile("^.{40}$")
return regex.MatchString(secretKey)
regex := regexp.MustCompile(`.{8,40}$`)
return regex.MatchString(secretKey) && !strings.ContainsAny(secretKey, "$%^~`!|&*#@")
}
// isValidAccessKey - validate access key.
@@ -21,8 +37,8 @@ func isValidAccessKey(accessKey string) bool {
if accessKey == "" {
return true
}
regex := regexp.MustCompile("^[A-Z0-9\\-\\.\\_\\~]{20}$")
return regex.MatchString(accessKey)
regex := regexp.MustCompile(`.{5,40}$`)
return regex.MatchString(accessKey) && !strings.ContainsAny(accessKey, "$%^~`!|&*#@")
}
// isValidHostURL - validate input host url.
@@ -30,7 +46,7 @@ func isValidHostURL(hostURL string) bool {
if strings.TrimSpace(hostURL) == "" {
return false
}
url := client.NewURL(hostURL)
url := newClientURL(hostURL)
if url.Scheme != "https" && url.Scheme != "http" {
return false
}
@@ -39,3 +55,13 @@ func isValidHostURL(hostURL string) bool {
}
return true
}
// isValidAPI - Validates if API signature string of supported type.
func isValidAPI(api string) bool {
switch strings.ToLower(api) {
case "s3v2", "s3v4":
return true
default:
return false
}
}
+29 -45
View File
@@ -19,8 +19,8 @@ package main
import (
"sync"
"github.com/minio/minio-xl/pkg/probe"
"github.com/minio/minio-xl/pkg/quick"
"github.com/minio/minio/pkg/probe"
"github.com/minio/minio/pkg/quick"
)
const (
@@ -30,44 +30,44 @@ const (
var (
// set once during first load.
cacheCfgV7 *configV7
cacheCfgV8 *configV8
// All access to mc config file should be synchronized.
cfgMutex = &sync.RWMutex{}
)
// hostConfig configuration of a host.
type hostConfigV7 struct {
type hostConfigV8 struct {
URL string `json:"url"`
AccessKey string `json:"accessKey"`
SecretKey string `json:"secretKey"`
API string `json:"api"`
}
// configV7 config version.
type configV7 struct {
// configV8 config version.
type configV8 struct {
Version string `json:"version"`
Hosts map[string]hostConfigV7 `json:"hosts"`
Hosts map[string]hostConfigV8 `json:"hosts"`
}
// newConfigV7 - new config version.
func newConfigV7() *configV7 {
cfg := new(configV7)
// newConfigV8 - new config version.
func newConfigV8() *configV8 {
cfg := new(configV8)
cfg.Version = globalMCConfigVersion
cfg.Hosts = make(map[string]hostConfigV7)
cfg.Hosts = make(map[string]hostConfigV8)
return cfg
}
// SetHost sets host config if not empty.
func (c *configV7) setHost(alias string, cfg hostConfigV7) {
func (c *configV8) setHost(alias string, cfg hostConfigV8) {
if _, ok := c.Hosts[alias]; !ok {
c.Hosts[alias] = cfg
}
}
// load default values for missing entries.
func (c *configV7) loadDefaults() {
func (c *configV8) loadDefaults() {
// Minio server running locally.
c.setHost("local", hostConfigV7{
c.setHost("local", hostConfigV8{
URL: "http://localhost:9000",
AccessKey: "",
SecretKey: "",
@@ -75,7 +75,7 @@ func (c *configV7) loadDefaults() {
})
// Amazon S3 cloud storage service.
c.setHost("s3", hostConfigV7{
c.setHost("s3", hostConfigV8{
URL: "https://s3.amazonaws.com",
AccessKey: defaultAccessKey,
SecretKey: defaultSecretKey,
@@ -83,7 +83,7 @@ func (c *configV7) loadDefaults() {
})
// Google cloud storage service.
c.setHost("gcs", hostConfigV7{
c.setHost("gcs", hostConfigV8{
URL: "https://storage.googleapis.com",
AccessKey: defaultAccessKey,
SecretKey: defaultSecretKey,
@@ -91,67 +91,51 @@ func (c *configV7) loadDefaults() {
})
// Minio anonymous server for demo.
c.setHost("play", hostConfigV7{
c.setHost("play", hostConfigV8{
URL: "https://play.minio.io:9000",
AccessKey: "",
SecretKey: "",
API: "S3v4",
})
// Minio demo server with public secret and access keys.
c.setHost("player", hostConfigV7{
URL: "https://play.minio.io:9002",
AccessKey: "Q3AM3UQ867SPQQA43P2F",
SecretKey: "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG",
API: "S3v4",
})
// Minio public download service.
c.setHost("dl", hostConfigV7{
URL: "https://dl.minio.io:9000",
AccessKey: "",
SecretKey: "",
API: "S3v4",
})
}
// loadConfigV7 - loads a new config.
func loadConfigV7() (*configV7, *probe.Error) {
// loadConfigV8 - loads a new config.
func loadConfigV8() (*configV8, *probe.Error) {
cfgMutex.RLock()
defer cfgMutex.RUnlock()
// Cached in private global variable.
if cacheCfgV7 != nil {
return cacheCfgV7, nil
if cacheCfgV8 != nil {
return cacheCfgV8, nil
}
if !isMcConfigExists() {
return nil, errInvalidArgument().Trace()
}
mcCfgV7, err := quick.Load(mustGetMcConfigPath(), newConfigV7())
mcCfgV8, err := quick.Load(mustGetMcConfigPath(), newConfigV8())
fatalIf(err.Trace(), "Unable to load mc config file ‘"+mustGetMcConfigPath()+"’.")
cfgV7 := mcCfgV7.Data().(*configV7)
cfgV8 := mcCfgV8.Data().(*configV8)
// cache it.
cacheCfgV7 = cfgV7
cacheCfgV8 = cfgV8
return cfgV7, nil
return cfgV8, nil
}
// saveConfigV7 - saves an updated config.
func saveConfigV7(cfgV7 *configV7) *probe.Error {
// saveConfigV8 - saves an updated config.
func saveConfigV8(cfgV8 *configV8) *probe.Error {
cfgMutex.Lock()
defer cfgMutex.Unlock()
qs, err := quick.New(cfgV7)
qs, err := quick.New(cfgV8)
if err != nil {
return err.Trace()
}
// update the cache.
cacheCfgV7 = cfgV7
cacheCfgV8 = cfgV8
return qs.Save(mustGetMcConfigPath()).Trace(mustGetMcConfigPath())
}
+78
View File
@@ -0,0 +1,78 @@
/*
* Minio Client (C) 2015 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package main
import (
"bytes"
"fmt"
"strings"
)
// Check if version of the config is valid
func validateConfigVersion(config *configV8) (bool, string) {
if config.Version != globalMCConfigVersion {
return false, fmt.Sprintf("Config version %s does not match GlobalMCConfiguration %s.\n",
config.Version, globalMCConfigVersion)
}
return true, ""
}
// Verifies the config file of the Minio Client
func validateConfigFile(config *configV8) (bool, []string) {
ok, err := validateConfigVersion(config)
var validationSuccessful = true
var errors []string
if !ok {
validationSuccessful = false
errors = append(errors, err)
}
hosts := config.Hosts
for _, hostConfig := range hosts {
hostConfigHealthOk, hostErrors := validateConfigHost(hostConfig)
if !hostConfigHealthOk {
validationSuccessful = false
errors = append(errors, hostErrors...)
}
}
return validationSuccessful, errors
}
func validateConfigHost(host hostConfigV8) (bool, []string) {
var validationSuccessful = true
var hostErrors []string
api := host.API
validAPI := isValidAPI(strings.ToLower(api))
if !validAPI {
var errorMsg bytes.Buffer
errorMsg.WriteString(fmt.Sprintf(
"%s API for host %s is not Valid. It is not part of any of the following APIs:\n",
api, host.URL))
for index, validAPI := range validAPIs {
errorMsg.WriteString(fmt.Sprintf("%d. %s\n", index+1, validAPI))
}
validationSuccessful = false
hostErrors = append(hostErrors, errorMsg.String())
}
url := host.URL
validURL := isValidHostURL(url)
if !validURL {
validationSuccessful = false
msg := fmt.Sprintf("URL %s for host %s is not valid. Could not parse it.\n", url, host.URL)
hostErrors = append(hostErrors, msg)
}
return validationSuccessful, hostErrors
}
+24 -25
View File
@@ -22,16 +22,13 @@ import (
"regexp"
"runtime"
"github.com/minio/minio-xl/pkg/probe"
"github.com/minio/minio/pkg/user"
"github.com/minio/go-homedir"
"github.com/minio/minio/pkg/probe"
)
// mcCustomConfigDir contains the whole path to config dir. Only access via get/set functions.
var mcCustomConfigDir string
// mcCustomConfigPath contains the whole path to config file. Only access via get/set functions.
var mcCustomConfigPath string
// setMcConfigDir - set a custom minio client config folder.
func setMcConfigDir(configDir string) {
mcCustomConfigDir = configDir
@@ -42,17 +39,18 @@ func getMcConfigDir() (string, *probe.Error) {
if mcCustomConfigDir != "" {
return mcCustomConfigDir, nil
}
homeDir, e := user.HomeDir()
homeDir, e := homedir.Dir()
if e != nil {
return "", probe.NewError(e)
}
var configDir string
// For windows the path is slightly different
switch runtime.GOOS {
case "windows":
return filepath.Join(homeDir, globalMCConfigWindowsDir), nil
default:
return filepath.Join(homeDir, globalMCConfigDir), nil
if runtime.GOOS == "windows" {
configDir = filepath.Join(homeDir, globalMCConfigWindowsDir)
} else {
configDir = filepath.Join(homeDir, globalMCConfigDir)
}
return configDir, nil
}
// mustGetMcConfigDir - construct minio client config folder or fail
@@ -77,8 +75,8 @@ func createMcConfigDir() *probe.Error {
// getMcConfigPath - construct minio client configuration path
func getMcConfigPath() (string, *probe.Error) {
if mcCustomConfigPath != "" {
return mcCustomConfigPath, nil
if mcCustomConfigDir != "" {
return filepath.Join(mcCustomConfigDir, globalMCConfigFile), nil
}
dir, err := getMcConfigDir()
if err != nil {
@@ -96,27 +94,28 @@ func mustGetMcConfigPath() string {
}
// newMcConfig - initializes a new version '6' config.
func newMcConfig() *configV7 {
cfg := newConfigV7()
func newMcConfig() *configV8 {
cfg := newConfigV8()
cfg.loadDefaults()
return cfg
}
// loadMcConfigCached - returns loadMcConfig with a closure for config cache.
func loadMcConfigFactory() func() (*configV7, *probe.Error) {
func loadMcConfigFactory() func() (*configV8, *probe.Error) {
// Load once and cache in a closure.
cfgCache, err := loadConfigV7()
cfgCache, err := loadConfigV8()
// loadMcConfig - reads configuration file and returns config.
return func() (*configV7, *probe.Error) {
return func() (*configV8, *probe.Error) {
return cfgCache, err
}
}
var loadMcConfig = loadMcConfigFactory()
// loadMcConfig - returns configuration, initialized later.
var loadMcConfig func() (*configV8, *probe.Error)
// saveMcConfig - saves configuration file and returns error if any.
func saveMcConfig(config *configV7) *probe.Error {
func saveMcConfig(config *configV8) *probe.Error {
if config == nil {
return errInvalidArgument().Trace()
}
@@ -127,7 +126,7 @@ func saveMcConfig(config *configV7) *probe.Error {
}
// Save the config.
if err := saveConfigV7(config); err != nil {
if err := saveConfigV8(config); err != nil {
return err.Trace(mustGetMcConfigPath())
}
@@ -154,7 +153,7 @@ func isValidAlias(alias string) bool {
}
// getHostConfig retrieves host specific configuration such as access keys, signature type.
func getHostConfig(alias string) (*hostConfigV7, *probe.Error) {
func getHostConfig(alias string) (*hostConfigV8, *probe.Error) {
mcCfg, err := loadMcConfig()
if err != nil {
return nil, err.Trace(alias)
@@ -171,13 +170,13 @@ func getHostConfig(alias string) (*hostConfigV7, *probe.Error) {
}
// mustGetHostConfig retrieves host specific configuration such as access keys, signature type.
func mustGetHostConfig(alias string) *hostConfigV7 {
func mustGetHostConfig(alias string) *hostConfigV8 {
hostCfg, _ := getHostConfig(alias)
return hostCfg
}
// expandAlias expands aliased URL if any match is found, returns as is otherwise.
func expandAlias(aliasedURL string) (alias string, urlStr string, hostCfg *hostConfigV7, err *probe.Error) {
func expandAlias(aliasedURL string) (alias string, urlStr string, hostCfg *hostConfigV8, err *probe.Error) {
// Extract alias from the URL.
alias, path := url2Alias(aliasedURL)
@@ -189,7 +188,7 @@ func expandAlias(aliasedURL string) (alias string, urlStr string, hostCfg *hostC
}
// mustExpandAlias expands aliased URL if any match is found, returns as is otherwise.
func mustExpandAlias(aliasedURL string) (alias string, urlStr string, hostCfg *hostConfigV7) {
func mustExpandAlias(aliasedURL string) (alias string, urlStr string, hostCfg *hostConfigV8) {
alias, urlStr, hostCfg, _ = expandAlias(aliasedURL)
return alias, urlStr, hostCfg
}
+62 -34
View File
@@ -29,9 +29,8 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/client"
"github.com/minio/mc/pkg/console"
"github.com/minio/minio-xl/pkg/probe"
"github.com/minio/minio/pkg/probe"
"github.com/minio/pb"
)
@@ -113,16 +112,21 @@ type copyStatMessage struct {
Speed float64
}
const (
// 5GiB.
fiveGB = 5 * 1024 * 1024 * 1024
)
// copyStatMessage copy accounting message
func (c copyStatMessage) String() string {
speedBox := pb.FormatBytes(int64(c.Speed))
speedBox := pb.Format(int64(c.Speed)).To(pb.U_BYTES).String()
if speedBox == "" {
speedBox = "0 MB"
} else {
speedBox = speedBox + "/s"
}
message := fmt.Sprintf("Total: %s, Transferred: %s, Speed: %s", pb.FormatBytes(c.Total),
pb.FormatBytes(c.Transferred), speedBox)
message := fmt.Sprintf("Total: %s, Transferred: %s, Speed: %s", pb.Format(c.Total).To(pb.U_BYTES),
pb.Format(c.Transferred).To(pb.U_BYTES), speedBox)
return message
}
@@ -143,12 +147,6 @@ func doCopy(cpURLs copyURLs, progressReader *progressBar, accountingReader *acco
targetURL := cpURLs.TargetContent.URL
length := cpURLs.SourceContent.Size
reader, err := getSourceStreamFromAlias(sourceAlias, sourceURL.String())
if err != nil {
cpURLs.Error = err.Trace(sourceURL.String())
return cpURLs
}
var progress io.Reader
if globalQuiet || globalJSON {
sourcePath := filepath.ToSlash(filepath.Join(sourceAlias, sourceURL.Path))
@@ -165,10 +163,50 @@ func doCopy(cpURLs copyURLs, progressReader *progressBar, accountingReader *acco
// Set up progress reader.
progress = progressReader.ProgressBar
}
_, err = putTargetStreamFromAlias(targetAlias, targetURL.String(), reader, length, progress)
if err != nil {
cpURLs.Error = err.Trace(targetURL.String())
return cpURLs
// If source size is <= 5GB and operation is across same server type try to use Copy.
if length <= fiveGB && (sourceURL.Type == targetURL.Type) {
// FS -> FS Copy includes alias in path.
if sourceURL.Type == fileSystem {
sourcePath := filepath.ToSlash(filepath.Join(sourceAlias, sourceURL.Path))
err := copySourceStreamFromAlias(targetAlias, targetURL.String(), sourcePath, length, progress)
if err != nil {
cpURLs.Error = err.Trace(sourceURL.String())
return cpURLs
}
} else if sourceURL.Type == objectStorage {
// If source/target are object storage their aliases must be the same.
if sourceAlias == targetAlias {
// Do not include alias inside path for ObjStore -> ObjStore.
err := copySourceStreamFromAlias(targetAlias, targetURL.String(), sourceURL.Path, length, progress)
if err != nil {
cpURLs.Error = err.Trace(sourceURL.String())
return cpURLs
}
} else {
reader, err := getSourceStreamFromAlias(sourceAlias, sourceURL.String())
if err != nil {
cpURLs.Error = err.Trace(sourceURL.String())
return cpURLs
}
_, err = putTargetStreamFromAlias(targetAlias, targetURL.String(), reader, length, progress)
if err != nil {
cpURLs.Error = err.Trace(targetURL.String())
return cpURLs
}
}
}
} else {
// Standard GET/PUT for size > 5GB.
reader, err := getSourceStreamFromAlias(sourceAlias, sourceURL.String())
if err != nil {
cpURLs.Error = err.Trace(sourceURL.String())
return cpURLs
}
_, err = putTargetStreamFromAlias(targetAlias, targetURL.String(), reader, length, progress)
if err != nil {
cpURLs.Error = err.Trace(targetURL.String())
return cpURLs
}
}
cpURLs.Error = nil // just for safety
return cpURLs
@@ -183,7 +221,7 @@ func doCopyFake(cpURLs copyURLs, progressReader *progressBar) copyURLs {
}
// doPrepareCopyURLs scans the source URL and prepares a list of objects for copying.
func doPrepareCopyURLs(session *sessionV6, trapCh <-chan bool) {
func doPrepareCopyURLs(session *sessionV7, trapCh <-chan bool) {
// Separate source and target. 'cp' can take only one target,
// but any number of sources.
sourceURLs := session.Header.CommandArgs[:len(session.Header.CommandArgs)-1]
@@ -205,8 +243,7 @@ func doPrepareCopyURLs(session *sessionV6, trapCh <-chan bool) {
URLsCh := prepareCopyURLs(sourceURLs, targetURL, isRecursive)
done := false
for done == false {
for !done {
select {
case cpURLs, ok := <-URLsCh:
if !ok { // Done with URL preparation
@@ -252,7 +289,7 @@ func doPrepareCopyURLs(session *sessionV6, trapCh <-chan bool) {
session.Save()
}
func doCopySession(session *sessionV6) {
func doCopySession(session *sessionV7) {
trapCh := signalTrap(os.Interrupt, syscall.SIGTERM)
if !session.HasData() {
@@ -266,7 +303,7 @@ func doCopySession(session *sessionV6) {
urlScanner := bufio.NewScanner(session.NewDataReader())
// isCopied returns true if an object has been already copied
// or not. This is useful when we resume from a session.
isCopied := isCopiedFactory(session.Header.LastCopied)
isCopied := isLastFactory(session.Header.LastCopied)
// Enable progress bar reader only during default mode.
var progressReader *progressBar
@@ -311,19 +348,10 @@ func doCopySession(session *sessionV6) {
// For all non critical errors we can continue for the
// remaining files.
switch cpURLs.Error.ToGoError().(type) {
// Handle this specifically for filesystem related
// errors.
case client.BrokenSymlink:
// Handle this specifically for filesystem related errors.
case BrokenSymlink, TooManyLevelsSymlink, PathNotFound, PathInsufficientPermission:
continue
case client.TooManyLevelsSymlink:
continue
case client.PathNotFound:
continue
case client.PathInsufficientPermission:
continue
case client.ObjectAlreadyExists:
continue
case client.BucketDoesNotExist:
case BucketNameEmpty, ObjectMissing, ObjectAlreadyExists, BucketDoesNotExist, BucketInvalid:
continue
}
// For critical errors we should exit. Session
@@ -356,7 +384,7 @@ func doCopySession(session *sessionV6) {
wg.Wait()
if !globalQuiet && !globalJSON {
if progressReader.ProgressBar.Total > 0 {
if progressReader.ProgressBar.Get() > 0 {
progressReader.ProgressBar.Finish()
}
} else {
@@ -381,7 +409,7 @@ func mainCopy(ctx *cli.Context) {
// Additional command speific theme customization.
console.SetColor("Copy", color.New(color.FgGreen, color.Bold))
session := newSessionV6()
session := newSessionV7()
session.Header.CommandType = "cp"
session.Header.CommandBoolFlags["recursive"] = ctx.Bool("recursive")
+9 -2
View File
@@ -20,7 +20,6 @@ import (
"fmt"
"github.com/minio/cli"
"github.com/minio/mc/pkg/client"
)
func checkCopySyntax(ctx *cli.Context) {
@@ -39,8 +38,16 @@ func checkCopySyntax(ctx *cli.Context) {
isRecursive := ctx.Bool("recursive")
/****** Generic Invalid Rules *******/
// Verify if source(s) exists.
for _, srcURL := range srcURLs {
_, _, err := url2Stat(srcURL)
if err != nil {
fatalIf(err.Trace(srcURL), fmt.Sprintf("Unable to stat '%s'.", srcURL))
}
}
// Check if bucket name is passed for URL type arguments.
url := client.NewURL(tgtURL)
url := newClientURL(tgtURL)
if url.Host != "" {
// This check is for type URL.
if !isURLVirtualHostStyle(url.Host) {
+20 -21
View File
@@ -20,15 +20,14 @@ import (
"path/filepath"
"strings"
"github.com/minio/mc/pkg/client"
"github.com/minio/minio-xl/pkg/probe"
"github.com/minio/minio/pkg/probe"
)
type copyURLs struct {
SourceAlias string
SourceContent *client.Content
SourceContent *clientContent
TargetAlias string
TargetContent *client.Content
TargetContent *clientContent
Error *probe.Error `json:"-"`
}
@@ -57,7 +56,7 @@ const (
copyURLsTypeD
)
// guessCopyURLType guesses the type of URL. This approach all allows prepareURL
// guessCopyURLType guesses the type of clientURL. This approach all allows prepareURL
// functions to accurately report failure causes.
func guessCopyURLType(sourceURLs []string, targetURL string, isRecursive bool) (copyURLsType, *probe.Error) {
if len(sourceURLs) == 1 { // 1 Source, 1 Target
@@ -90,11 +89,11 @@ func guessCopyURLType(sourceURLs []string, targetURL string, isRecursive bool) (
}
// SINGLE SOURCE - Type A: copy(f, f) -> copy(f, f)
// prepareCopyURLsTypeA - prepares target and source URLs for copying.
// prepareCopyURLsTypeA - prepares target and source clientURLs for copying.
func prepareCopyURLsTypeA(sourceURL string, targetURL string) copyURLs {
// Extract alias before fiddling with the URL.
// Extract alias before fiddling with the clientURL.
sourceAlias, _, _ := mustExpandAlias(sourceURL)
// Find alias and expanded URL.
// Find alias and expanded clientURL.
targetAlias, targetURL, _ := mustExpandAlias(targetURL)
_, sourceContent, err := url2Stat(sourceURL)
@@ -116,21 +115,21 @@ func prepareCopyURLsTypeA(sourceURL string, targetURL string) copyURLs {
}
// prepareCopyContentTypeA - makes CopyURLs content for copying.
func makeCopyContentTypeA(sourceAlias string, sourceContent *client.Content, targetAlias string, targetURL string) copyURLs {
func makeCopyContentTypeA(sourceAlias string, sourceContent *clientContent, targetAlias string, targetURL string) copyURLs {
return copyURLs{
SourceAlias: sourceAlias,
SourceContent: sourceContent,
TargetAlias: targetAlias,
TargetContent: &client.Content{URL: *client.NewURL(targetURL)},
TargetContent: &clientContent{URL: *newClientURL(targetURL)},
}
}
// SINGLE SOURCE - Type B: copy(f, d) -> copy(f, d/f) -> A
// prepareCopyURLsTypeB - prepares target and source URLs for copying.
// prepareCopyURLsTypeB - prepares target and source clientURLs for copying.
func prepareCopyURLsTypeB(sourceURL string, targetURL string) copyURLs {
// Extract alias before fiddling with the URL.
// Extract alias before fiddling with the clientURL.
sourceAlias, _, _ := mustExpandAlias(sourceURL)
// Find alias and expanded URL.
// Find alias and expanded clientURL.
targetAlias, targetURL, _ := mustExpandAlias(targetURL)
_, sourceContent, err := url2Stat(sourceURL)
@@ -152,19 +151,19 @@ func prepareCopyURLsTypeB(sourceURL string, targetURL string) copyURLs {
}
// makeCopyContentTypeB - CopyURLs content for copying.
func makeCopyContentTypeB(sourceAlias string, sourceContent *client.Content, targetAlias string, targetURL string) copyURLs {
func makeCopyContentTypeB(sourceAlias string, sourceContent *clientContent, targetAlias string, targetURL string) copyURLs {
// All OK.. We can proceed. Type B: source is a file, target is a folder and exists.
targetURLParse := client.NewURL(targetURL)
targetURLParse := newClientURL(targetURL)
targetURLParse.Path = filepath.ToSlash(filepath.Join(targetURLParse.Path, filepath.Base(sourceContent.URL.Path)))
return makeCopyContentTypeA(sourceAlias, sourceContent, targetAlias, targetURLParse.String())
}
// SINGLE SOURCE - Type C: copy(d1..., d2) -> []copy(d1/f, d1/d2/f) -> []A
// prepareCopyRecursiveURLTypeC - prepares target and source URLs for copying.
// prepareCopyRecursiveURLTypeC - prepares target and source clientURLs for copying.
func prepareCopyURLsTypeC(sourceURL, targetURL string, isRecursive bool) <-chan copyURLs {
// Extract alias before fiddling with the URL.
// Extract alias before fiddling with the clientURL.
sourceAlias, _, _ := mustExpandAlias(sourceURL)
// Find alias and expanded URL.
// Find alias and expanded clientURL.
targetAlias, targetURL, _ := mustExpandAlias(targetURL)
copyURLsCh := make(chan copyURLs)
@@ -197,7 +196,7 @@ func prepareCopyURLsTypeC(sourceURL, targetURL string, isRecursive bool) <-chan
}
// makeCopyContentTypeC - CopyURLs content for copying.
func makeCopyContentTypeC(sourceAlias string, sourceURL client.URL, sourceContent *client.Content, targetAlias string, targetURL string) copyURLs {
func makeCopyContentTypeC(sourceAlias string, sourceURL clientURL, sourceContent *clientContent, targetAlias string, targetURL string) copyURLs {
newSourceURL := sourceContent.URL
pathSeparatorIndex := strings.LastIndex(sourceURL.Path, string(sourceURL.Separator))
newSourceSuffix := filepath.ToSlash(newSourceURL.Path)
@@ -210,7 +209,7 @@ func makeCopyContentTypeC(sourceAlias string, sourceURL client.URL, sourceConten
}
// MULTI-SOURCE - Type D: copy([](f|d...), d) -> []B
// prepareCopyURLsTypeE - prepares target and source URLs for copying.
// prepareCopyURLsTypeE - prepares target and source clientURLs 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) {
@@ -224,7 +223,7 @@ func prepareCopyURLsTypeD(sourceURLs []string, targetURL string, isRecursive boo
return copyURLsCh
}
// prepareCopyURLs - prepares target and source URLs for copying.
// prepareCopyURLs - prepares target and source clientURLs for copying.
func prepareCopyURLs(sourceURLs []string, targetURL string, isRecursive bool) <-chan copyURLs {
copyURLsCh := make(chan copyURLs)
go func(sourceURLs []string, targetURL string, copyURLsCh chan copyURLs) {
+27 -46
View File
@@ -23,9 +23,8 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/client"
"github.com/minio/mc/pkg/console"
"github.com/minio/minio-xl/pkg/probe"
"github.com/minio/minio/pkg/probe"
)
// diff specific flags.
@@ -68,24 +67,29 @@ EXAMPLES:
// diffMessage json container for diff messages
type diffMessage struct {
Status string `json:"status"`
FirstURL string `json:"first"`
SecondURL string `json:"second"`
Diff string `json:"diff"`
Error *probe.Error `json:"error,omitempty"`
Status string `json:"status"`
FirstURL string `json:"first"`
SecondURL string `json:"second"`
Diff differType `json:"diff"`
Error *probe.Error `json:"error,omitempty"`
firstContent *clientContent
secondContent *clientContent
}
// String colorized diff message
func (d diffMessage) String() string {
msg := ""
switch d.Diff {
case "only-in-first":
case differInFirst:
msg = console.Colorize("DiffMessage",
"‘"+d.FirstURL+"’"+" and "+"‘"+d.SecondURL+"’") + console.Colorize("DiffOnlyInFirst", " - only in first.")
case "type":
"‘"+d.FirstURL+"’") + console.Colorize("DiffOnlyInFirst", " - only in first.")
case differInSecond:
msg = console.Colorize("DiffMessage",
"‘"+d.SecondURL+"’") + console.Colorize("DiffOnlyInSecond", " - only in second.")
case differInType:
msg = console.Colorize("DiffMessage",
"‘"+d.FirstURL+"’"+" and "+"‘"+d.SecondURL+"’") + console.Colorize("DiffType", " - differ in type.")
case "size":
case differInSize:
msg = console.Colorize("DiffMessage",
"‘"+d.FirstURL+"’"+" and "+"‘"+d.SecondURL+"’") + console.Colorize("DiffSize", " - differ in size.")
default:
@@ -101,7 +105,7 @@ func (d diffMessage) JSON() string {
d.Status = "success"
diffJSONBytes, e := json.Marshal(d)
fatalIf(probe.NewError(e),
"Unable to marshal diff message ‘"+d.FirstURL+"’, ‘"+d.SecondURL+"’ and ‘"+d.Diff+"’.")
"Unable to marshal diff message ‘"+d.FirstURL+"’, ‘"+d.SecondURL+"’ and ‘"+string(d.Diff)+"’.")
return string(diffJSONBytes)
}
@@ -125,6 +129,7 @@ func checkDiffSyntax(ctx *cli.Context) {
if err != nil {
fatalIf(err.Trace(firstURL), fmt.Sprintf("Unable to stat '%s'.", firstURL))
}
// Verify if its a directory.
if !firstContent.Type.IsDir() {
fatalIf(errInvalidArgument().Trace(firstURL), fmt.Sprintf("‘%s’ is not a folder.", firstURL))
@@ -135,6 +140,7 @@ func checkDiffSyntax(ctx *cli.Context) {
if err != nil {
fatalIf(err.Trace(secondURL), fmt.Sprintf("Unable to stat '%s'.", secondURL))
}
// Verify if its a directory.
if !secondContent.Type.IsDir() {
fatalIf(errInvalidArgument().Trace(secondURL), fmt.Sprintf("‘%s’ is not a folder.", secondURL))
@@ -144,11 +150,11 @@ func checkDiffSyntax(ctx *cli.Context) {
// doDiffMain runs the diff.
func doDiffMain(firstURL, secondURL string) {
// Source and targets are always directories
sourceSeparator := string(client.NewURL(firstURL).Separator)
sourceSeparator := string(newClientURL(firstURL).Separator)
if !strings.HasSuffix(firstURL, sourceSeparator) {
firstURL = firstURL + sourceSeparator
}
targetSeparator := string(client.NewURL(secondURL).Separator)
targetSeparator := string(newClientURL(secondURL).Separator)
if !strings.HasSuffix(secondURL, targetSeparator) {
secondURL = secondURL + targetSeparator
}
@@ -162,42 +168,16 @@ func doDiffMain(firstURL, secondURL string) {
fatalIf(err.Trace(firstAlias, firstURL, secondAlias, secondURL),
fmt.Sprintf("Failed to diff '%s' and '%s'", firstURL, secondURL))
}
difference, err := objectDifferenceFactory(secondAlias, secondURL)
secondClient, err := newClientFromAlias(secondAlias, secondURL)
if err != nil {
fatalIf(err.Trace(firstAlias, firstURL, secondAlias, secondURL),
fmt.Sprintf("Failed to diff '%s' and '%s'", firstURL, secondURL))
}
isRecursive := true
isIncomplete := false
for sourceContent := range firstClient.List(isRecursive, isIncomplete) {
if sourceContent.Err != nil {
switch sourceContent.Err.ToGoError().(type) {
// Handle this specifically for filesystem related errors.
case client.BrokenSymlink, client.TooManyLevelsSymlink, client.PathNotFound, client.PathInsufficientPermission:
errorIf(sourceContent.Err.Trace(firstURL, secondURL), fmt.Sprintf("Failed on '%s'", firstURL))
default:
fatalIf(sourceContent.Err.Trace(firstURL, secondURL), fmt.Sprintf("Failed on '%s'", firstURL))
}
continue
}
if sourceContent.Type.IsDir() {
continue
}
suffix := strings.TrimPrefix(sourceContent.URL.String(), firstURL)
differ, err := difference(suffix, sourceContent.Type, sourceContent.Size)
if err != nil {
errorIf(sourceContent.Err.Trace(secondURL, suffix),
fmt.Sprintf("Failed on '%s'", urlJoinPath(secondURL, suffix)))
continue
}
if differ == differNone {
continue
}
printMsg(diffMessage{
FirstURL: sourceContent.URL.String(),
SecondURL: urlJoinPath(secondURL, suffix),
Diff: differ,
})
// Diff first and second urls.
for diffMsg := range objectDifference(firstClient, secondClient, firstURL, secondURL) {
printMsg(diffMsg)
}
}
@@ -214,6 +194,7 @@ func mainDiff(ctx *cli.Context) {
console.SetColor("DiffOnlyInFirst", color.New(color.FgRed, color.Bold))
console.SetColor("DiffType", color.New(color.FgYellow, color.Bold))
console.SetColor("DiffSize", color.New(color.FgMagenta, color.Bold))
console.SetColor("DiffTime", color.New(color.FgYellow, color.Bold))
URLs := ctx.Args()
firstURL := URLs[0]
+150 -54
View File
@@ -17,73 +17,169 @@
package main
import (
"os"
"github.com/minio/mc/pkg/client"
"github.com/minio/minio-xl/pkg/probe"
"fmt"
"strings"
)
// 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)
// differType difference in type.
type differType int
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
differInNone differType = iota // does not differ
differInSize // differs in size
differInType // only in source
differInFirst // only in target
differInSecond // differs in type, exfile/directory
)
// 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)
func (d differType) String() string {
switch d {
case differInNone:
return ""
case differInSize:
return "size"
case differInType:
return "type"
case differInFirst:
return "only-in-first"
case differInSecond:
return "only-in-second"
}
isIncomplete := false
isRecursive := true
ch := clnt.List(isRecursive, isIncomplete)
current := targetURL
reachedEOF := false
ok := false
var content *client.Content
return "unknown"
}
// objectDifference function finds the difference between all objects
// recursively in sorted order from source and target.
func objectDifference(sourceClnt, targetClnt Client, sourceURL, targetURL string) (diffCh chan diffMessage) {
var (
srcEOF, tgtEOF bool
srcOk, tgtOk bool
srcCtnt, tgtCtnt *clientContent
srcSuffix, tgtSuffix string
)
// Set default values for listing.
isRecursive := true // recursive is always true for diff.
isIncomplete := false // we will not compare any incomplete objects.
srcCh := sourceClnt.List(isRecursive, isIncomplete)
tgtCh := targetClnt.List(isRecursive, isIncomplete)
diffCh = make(chan diffMessage, 1000)
go func() {
srcCtnt, srcOk = <-srcCh
tgtCtnt, tgtOk = <-tgtCh
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
srcEOF = !srcOk
tgtEOF = !tgtOk
// No objects from source AND target: Finish
if srcEOF && tgtEOF {
close(diffCh)
break
}
if !srcEOF && srcCtnt.Err != nil {
switch srcCtnt.Err.ToGoError().(type) {
// Handle this specifically for filesystem related errors.
case BrokenSymlink, TooManyLevelsSymlink, PathNotFound, PathInsufficientPermission:
errorIf(srcCtnt.Err.Trace(sourceURL, targetURL), fmt.Sprintf("Failed on '%s'", sourceURL))
default:
fatalIf(srcCtnt.Err.Trace(sourceURL, targetURL), fmt.Sprintf("Failed on '%s'", sourceURL))
}
srcCtnt, srcOk = <-srcCh
continue
}
if !tgtEOF && tgtCtnt.Err != nil {
switch tgtCtnt.Err.ToGoError().(type) {
// Handle this specifically for filesystem related errors.
case BrokenSymlink, TooManyLevelsSymlink, PathNotFound, PathInsufficientPermission:
errorIf(tgtCtnt.Err.Trace(sourceURL, targetURL), fmt.Sprintf("Failed on '%s'", targetURL))
default:
fatalIf(tgtCtnt.Err.Trace(sourceURL, targetURL), fmt.Sprintf("Failed on '%s'", targetURL))
}
tgtCtnt, tgtOk = <-tgtCh
continue
}
// If source doesn't have objects anymore, comparison becomes obvious
if srcEOF {
diffCh <- diffMessage{
SecondURL: tgtCtnt.URL.String(),
Diff: differInSecond,
secondContent: tgtCtnt,
}
tgtCtnt, tgtOk = <-tgtCh
continue
}
// The same for target
if tgtEOF {
diffCh <- diffMessage{
FirstURL: srcCtnt.URL.String(),
Diff: differInFirst,
firstContent: srcCtnt,
}
srcCtnt, srcOk = <-srcCh
continue
}
srcSuffix = strings.TrimPrefix(srcCtnt.URL.String(), sourceURL)
tgtSuffix = strings.TrimPrefix(tgtCtnt.URL.String(), targetURL)
current := urlJoinPath(targetURL, srcSuffix)
expected := urlJoinPath(targetURL, tgtSuffix)
if expected > current {
diffCh <- diffMessage{
FirstURL: srcCtnt.URL.String(),
Diff: differInFirst,
firstContent: srcCtnt,
}
srcCtnt, srcOk = <-srcCh
continue
}
if expected == current {
tgtType := content.Type
tgtSize := content.Size
if srcType.IsRegular() && !tgtType.IsRegular() {
// Type differes. Source is never a directory
return differType, nil
srcType, tgtType := srcCtnt.Type, tgtCtnt.Type
srcSize, tgtSize := srcCtnt.Size, tgtCtnt.Size
if srcType.IsRegular() && !tgtType.IsRegular() ||
!srcType.IsRegular() && tgtType.IsRegular() {
// Type differes. Source is never a directory.
diffCh <- diffMessage{
FirstURL: srcCtnt.URL.String(),
SecondURL: tgtCtnt.URL.String(),
Diff: differInType,
firstContent: srcCtnt,
secondContent: tgtCtnt,
}
} else if (srcType.IsRegular() && tgtType.IsRegular()) && srcSize != tgtSize {
// Regular files differing in size.
diffCh <- diffMessage{
FirstURL: srcCtnt.URL.String(),
SecondURL: tgtCtnt.URL.String(),
Diff: differInSize,
firstContent: srcCtnt,
secondContent: tgtCtnt,
}
}
if (srcType.IsRegular() && tgtType.IsRegular()) && srcSize != tgtSize {
// regular files differing in size
return differSize, nil
}
return differNone, nil // available in the target
// No differ
srcCtnt, srcOk = <-srcCh
tgtCtnt, tgtOk = <-tgtCh
continue
}
content, ok = <-ch
if !ok {
reachedEOF = true
return differOnlyFirst, nil
// Differ in second
diffCh <- diffMessage{
SecondURL: tgtCtnt.URL.String(),
Diff: differInSecond,
secondContent: tgtCtnt,
}
if content.Err != nil {
return "", content.Err.Trace()
}
current = content.URL.String()
tgtCtnt, tgtOk = <-tgtCh
continue
}
}
return difference, nil
}()
return diffCh
}
+1 -1
View File
@@ -21,7 +21,7 @@ import (
"fmt"
"github.com/minio/mc/pkg/console"
"github.com/minio/minio-xl/pkg/probe"
"github.com/minio/minio/pkg/probe"
)
// causeMessage container for golang error messages
@@ -16,7 +16,7 @@
* limitations under the License.
*/
package fs
package main
func normalizePath(path string) string {
return path
@@ -16,7 +16,7 @@
* limitations under the License.
*/
package fs
package main
import (
"path/filepath"
+10 -3
View File
@@ -24,7 +24,11 @@ import (
// mc configuration related constants.
const (
globalMCConfigVersion = "7"
minGoVersion = ">= 1.6" // mc requires at least Go v1.6
)
const (
globalMCConfigVersion = "8"
globalMCConfigDir = ".mc/"
globalMCConfigWindowsDir = "mc\\"
@@ -33,6 +37,9 @@ const (
// session config and shared urls related constants
globalSessionDir = "session"
globalSharedURLsDataDir = "share"
// Profile directory for dumping profiler outputs.
globalProfileDir = "profile"
)
var (
@@ -51,12 +58,12 @@ func setGlobals(quiet, debug, json, noColor bool) {
globalNoColor = noColor
// Enable debug messages if requested.
if globalDebug == true {
if globalDebug {
console.DebugPrint = true
}
// Disable colorified messages if requested.
if globalNoColor == true {
if globalNoColor {
console.SetColorOff()
}
}
+23 -2
View File
@@ -21,7 +21,6 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/client"
"github.com/minio/mc/pkg/console"
)
@@ -97,6 +96,11 @@ func checkListSyntax(ctx *cli.Context) {
for _, url := range URLs {
_, _, err := url2Stat(url)
if err != nil && !isURLPrefixExists(url, isIncomplete) {
// Bucket name empty is a valid error for 'ls myminio',
// treat it as such.
if _, ok := err.ToGoError().(BucketNameEmpty); ok {
continue
}
fatalIf(err.Trace(url), "Unable to stat ‘"+url+"’.")
}
}
@@ -127,10 +131,27 @@ func mainList(ctx *cli.Context) {
}
for _, targetURL := range args {
var clnt client.Client
var clnt Client
clnt, err := newClient(targetURL)
fatalIf(err.Trace(targetURL), "Unable to initialize target ‘"+targetURL+"’.")
var st *clientContent
if st, err = clnt.Stat(); err != nil {
switch err.ToGoError().(type) {
case BucketNameEmpty:
// For aliases like ``mc ls s3`` it's acceptable to receive BucketNameEmpty error.
// Nothing to do.
default:
fatalIf(err.Trace(targetURL), "Unable to initialize target ‘"+targetURL+"’.")
}
} else if st.Type.IsDir() {
if !strings.HasSuffix(targetURL, string(clnt.GetURL().Separator)) {
targetURL = targetURL + string(clnt.GetURL().Separator)
}
clnt, err = newClient(targetURL)
fatalIf(err.Trace(targetURL), "Unable to initialize target ‘"+targetURL+"’.")
}
err = doList(clnt, isRecursive, isIncomplete)
if err != nil {
errorIf(err.Trace(clnt.GetURL().String()), "Unable to list target ‘"+clnt.GetURL().String()+"’.")
+7 -8
View File
@@ -25,9 +25,8 @@ import (
"time"
"github.com/dustin/go-humanize"
"github.com/minio/mc/pkg/client"
"github.com/minio/mc/pkg/console"
"github.com/minio/minio-xl/pkg/probe"
"github.com/minio/minio/pkg/probe"
)
// printDate - human friendly formatted date.
@@ -67,7 +66,7 @@ func (c contentMessage) JSON() string {
}
// parseContent parse client Content container into printer struct.
func parseContent(c *client.Content) contentMessage {
func parseContent(c *clientContent) contentMessage {
content := contentMessage{}
content.Time = c.Time.Local()
@@ -105,7 +104,7 @@ func parseContent(c *client.Content) contentMessage {
}
// doList - list all entities inside a folder.
func doList(clnt client.Client, isRecursive, isIncomplete bool) *probe.Error {
func doList(clnt Client, isRecursive, isIncomplete bool) *probe.Error {
prefixPath := clnt.GetURL().Path
separator := string(clnt.GetURL().Separator)
if !strings.HasSuffix(prefixPath, separator) {
@@ -115,16 +114,16 @@ func doList(clnt client.Client, isRecursive, isIncomplete bool) *probe.Error {
if content.Err != nil {
switch content.Err.ToGoError().(type) {
// handle this specifically for filesystem related errors.
case client.BrokenSymlink:
case BrokenSymlink:
errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list broken link.")
continue
case client.TooManyLevelsSymlink:
case TooManyLevelsSymlink:
errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list too many levels link.")
continue
case client.PathNotFound:
case PathNotFound:
errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list folder.")
continue
case client.PathInsufficientPermission:
case PathInsufficientPermission:
errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list folder.")
continue
}
+74 -15
View File
@@ -17,17 +17,19 @@
package main
import (
"bytes"
"fmt"
"os"
"path/filepath"
"runtime"
"sort"
"strconv"
"github.com/minio/cli"
"github.com/minio/minio-xl/pkg/probe"
"github.com/minio/minio/pkg/contentdb"
"github.com/minio/mc/pkg/console"
"github.com/minio/minio/pkg/probe"
"github.com/minio/pb"
"github.com/olekukonko/ts"
"github.com/pkg/profile"
)
var (
@@ -80,9 +82,26 @@ func commandNotFound(ctx *cli.Context, command string) {
// Check for sane config environment early on and gracefully report.
func checkConfig() {
// Refresh the config once.
loadMcConfig = loadMcConfigFactory()
// Ensures config file is sane.
_, err := loadMcConfig()
config, err := loadMcConfig()
// Verify if the path is accesible before validating the config
fatalIf(err.Trace(mustGetMcConfigPath()), "Unable to access configuration file.")
// Validate and print error messges
ok, errMsgs := validateConfigFile(config)
if !ok {
var errorMsg bytes.Buffer
for index, errMsg := range errMsgs {
// Print atmost 10 errors
if index > 10 {
break
}
errorMsg.WriteString(errMsg + "\n")
}
console.Fatalln(errorMsg.String())
}
}
func migrate() {
@@ -108,10 +127,10 @@ func getSystemData() map[string]string {
memstats := &runtime.MemStats{}
runtime.ReadMemStats(memstats)
mem := fmt.Sprintf("Used: %s | Allocated: %s | UsedHeap: %s | AllocatedHeap: %s",
pb.FormatBytes(int64(memstats.Alloc)),
pb.FormatBytes(int64(memstats.TotalAlloc)),
pb.FormatBytes(int64(memstats.HeapAlloc)),
pb.FormatBytes(int64(memstats.HeapSys)))
pb.Format(int64(memstats.Alloc)).To(pb.U_BYTES),
pb.Format(int64(memstats.TotalAlloc)).To(pb.U_BYTES),
pb.Format(int64(memstats.HeapAlloc)).To(pb.U_BYTES),
pb.Format(int64(memstats.HeapSys)).To(pb.U_BYTES))
platform := fmt.Sprintf("Host: %s | OS: %s | Arch: %s", host, runtime.GOOS, runtime.GOARCH)
goruntime := fmt.Sprintf("Version: %s | CPUs: %s", runtime.Version(), strconv.Itoa(runtime.NumCPU()))
return map[string]string{
@@ -121,19 +140,44 @@ func getSystemData() map[string]string {
}
}
func registerBefore(ctx *cli.Context) error {
setMcConfigDir(ctx.GlobalString("config-folder"))
// initMC - initialize 'mc'.
func initMC() {
// Check if mc config exists.
if !isMcConfigExists() {
err := saveMcConfig(newMcConfig())
fatalIf(err.Trace(), "Unable to save new mc config.")
// Verify golang runtime.
verifyMCRuntime()
console.Infoln("Configuration written to ‘" + mustGetMcConfigPath() + "’. Please update your access credentials.")
}
// Check if mc session folder exists.
if !isSessionDirExists() {
fatalIf(createSessionDir().Trace(), "Unable to create session config folder.")
}
// Check if mc share folder exists.
if !isShareDirExists() {
initShareConfig()
}
}
func registerBefore(ctx *cli.Context) error {
// Check if mc was compiled using a supported version of Golang.
checkGoVersion()
// Set the config folder.
setMcConfigDir(ctx.GlobalString("config-folder"))
// Migrate any old version of config / state files to newer format.
migrate()
// Initialize default config files.
initMC()
// Set global flags.
setGlobalsFromContext(ctx)
// Checkconfig if it can be read.
// Check if config can be read.
checkConfig()
return nil
@@ -186,17 +230,32 @@ func registerApp() *cli.App {
return app
}
// mustGetProfilePath must get location that the profile will be written to.
func mustGetProfileDir() string {
return filepath.Join(mustGetMcConfigDir(), globalProfileDir)
}
func main() {
// Enable profiling supported modes are [cpu, mem, block].
// ``MC_PROFILER`` supported options are [cpu, mem, block].
switch os.Getenv("MC_PROFILER") {
case "cpu":
defer profile.Start(profile.CPUProfile, profile.ProfilePath(mustGetProfileDir())).Stop()
case "mem":
defer profile.Start(profile.MemProfile, profile.ProfilePath(mustGetProfileDir())).Stop()
case "block":
defer profile.Start(profile.BlockProfile, profile.ProfilePath(mustGetProfileDir())).Stop()
}
probe.Init() // Set project's root source path.
probe.SetAppInfo("Release-Tag", 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 {
if _, e := pb.GetTerminalWidth(); e != nil {
globalQuiet = true
}
if globalDebug {
+1 -1
View File
@@ -22,7 +22,7 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/console"
"github.com/minio/minio-xl/pkg/probe"
"github.com/minio/minio/pkg/probe"
)
var (
+34 -16
View File
@@ -24,6 +24,7 @@ import (
"net/http/httptest"
"github.com/hashicorp/go-version"
"github.com/minio/cli"
. "gopkg.in/check.v1"
)
@@ -46,18 +47,38 @@ func (s *TestSuite) TearDownSuite(c *C) {
}
func (s *TestSuite) TestValidPERMS(c *C) {
perms := accessPerms("private")
perms := accessPerms("none")
c.Assert(perms.isValidAccessPERM(), Equals, true)
c.Assert(perms.String(), Equals, "private")
perms = accessPerms("public")
c.Assert(string(perms), Equals, "none")
perms = accessPerms("readwrite")
c.Assert(perms.isValidAccessPERM(), Equals, true)
c.Assert(perms.String(), Equals, "public-read-write")
c.Assert(string(perms), Equals, "readwrite")
perms = accessPerms("readonly")
c.Assert(perms.isValidAccessPERM(), Equals, true)
c.Assert(perms.String(), Equals, "public-read")
perms = accessPerms("authorized")
c.Assert(string(perms), Equals, "readonly")
perms = accessPerms("writeonly")
c.Assert(perms.isValidAccessPERM(), Equals, true)
c.Assert(perms.String(), Equals, "authenticated-read")
c.Assert(string(perms), Equals, "writeonly")
}
// Tests valid and invalid secret keys.
func (s *TestSuite) TestValidSecretKeys(c *C) {
c.Assert(isValidSecretKey("password"), Equals, true)
c.Assert(isValidSecretKey("BYvgJM101sHngl2uzjXS/OBF/aMxAN06JrJ3qJlF"), Equals, true)
c.Assert(isValidSecretKey("aaa"), Equals, false)
c.Assert(isValidSecretKey("password%%"), Equals, false)
}
// Tests valid and invalid access keys.
func (s *TestSuite) TestValidAccessKeys(c *C) {
c.Assert(isValidAccessKey("c67W2-r4MAyAYScRl"), Equals, true)
c.Assert(isValidAccessKey("EXOb76bfeb1234562iu679f11588"), Equals, true)
c.Assert(isValidAccessKey("BYvgJM101sHngl2uzjXS/OBF/aMxAN06JrJ3qJlF"), Equals, true)
c.Assert(isValidAccessKey("admin"), Equals, true)
c.Assert(isValidAccessKey("aaa"), Equals, false)
c.Assert(isValidAccessKey("$$%%%%%3333"), Equals, false)
}
func (s *TestSuite) TestInvalidPERMS(c *C) {
@@ -76,11 +97,7 @@ func (s *TestSuite) TestGetMcConfigPath(c *C) {
dir, err := getMcConfigPath()
c.Assert(err, IsNil)
switch runtime.GOOS {
case "linux":
fallthrough
case "freebsd":
fallthrough
case "darwin":
case "linux", "freebsd", "darwin", "solaris":
c.Assert(dir, Equals, filepath.Join(mustGetMcConfigDir(), "config.json"))
case "windows":
c.Assert(dir, Equals, filepath.Join(mustGetMcConfigDir(), "config.json"))
@@ -125,8 +142,9 @@ func (s *TestSuite) TestCommonPrefix(c *C) {
}
func (s *TestSuite) TestVersions(c *C) {
v1 := newVersion("1.5.1")
v2 := newVersion("1.5.0")
c.Assert(v2.LessThan(v1), Equals, true)
c.Assert(v1.LessThan(v2), Equals, false)
v1, e := version.NewVersion("1.6")
c.Assert(e, IsNil)
v2, e := version.NewConstraint(">= 1.5.0")
c.Assert(e, IsNil)
c.Assert(v2.Check(v1), Equals, true)
}
+171 -59
View File
@@ -1,5 +1,5 @@
/*
* Minio Client, (C) 2015 Minio, Inc.
* Minio Client, (C) 2015, 2016 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -28,9 +28,8 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/client"
"github.com/minio/mc/pkg/console"
"github.com/minio/minio-xl/pkg/probe"
"github.com/minio/minio/pkg/probe"
"github.com/minio/pb"
)
@@ -45,6 +44,14 @@ var (
Name: "force",
Usage: "Force overwrite of an existing target(s).",
},
cli.BoolFlag{
Name: "fake",
Usage: "Perform a fake mirror operation.",
},
cli.BoolFlag{
Name: "remove",
Usage: "Remove extraneous file(s) on target.",
},
}
)
@@ -72,6 +79,16 @@ EXAMPLES:
3. Mirror a bucket from aliased Amazon S3 cloud storage to a folder on Windows.
$ mc {{.Name}} s3\documents\2014\ C:\backup\2014
4. Mirror a bucket from aliased Amazon S3 cloud storage to a local folder use '--force' to overwrite destination.
$ mc {{.Name}} --force s3/miniocloud miniocloud-backup
5. Fake mirror a bucket from Minio cloud storage to a bucket on Amazon S3 cloud storage.
$ mc {{.Name}} --fake play/photos/2014 s3/backup-photos/2014
6. Mirror a bucket from Minio cloud storage to a bucket on Amazon S3 cloud storage and remove any extraneous
files on Amazon S3 cloud storage. NOTE: '--remove' is only supported with '--force'.
$ mc {{.Name}} --force --remove play/photos/2014 s3/backup-photos/2014
`,
}
@@ -105,19 +122,38 @@ type mirrorStatMessage struct {
// mirrorStatMessage mirror accounting message
func (c mirrorStatMessage) String() string {
speedBox := pb.FormatBytes(int64(c.Speed))
speedBox := pb.Format(int64(c.Speed)).To(pb.U_BYTES).String()
if speedBox == "" {
speedBox = "0 MB"
} else {
speedBox = speedBox + "/s"
}
message := fmt.Sprintf("Total: %s, Transferred: %s, Speed: %s", pb.FormatBytes(c.Total),
pb.FormatBytes(c.Transferred), speedBox)
message := fmt.Sprintf("Total: %s, Transferred: %s, Speed: %s", pb.Format(c.Total).To(pb.U_BYTES),
pb.Format(c.Transferred).To(pb.U_BYTES), speedBox)
return message
}
// doRemove - removes files on target.
func doRemove(sURLs mirrorURLs, fakeRemove bool) mirrorURLs {
targetAlias := sURLs.TargetAlias
targetURL := sURLs.TargetContent.URL
// We are not removing incomplete uploads.
isIncomplete := false
// Remove extraneous file on target.
err := rm(targetAlias, targetURL.String(), isIncomplete, fakeRemove)
if err != nil {
sURLs.Error = err.Trace(targetAlias, targetURL.String())
return sURLs
}
sURLs.Error = nil // just for safety
return sURLs
}
// 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 {
func doMirror(sURLs mirrorURLs, progressReader *progressBar, accountingReader *accounter, fakeMirror bool) mirrorURLs {
if sURLs.Error != nil { // Errorneous sURLs passed.
sURLs.Error = sURLs.Error.Trace()
return sURLs
@@ -133,12 +169,6 @@ func doMirror(sURLs mirrorURLs, progressReader *progressBar, accountingReader *a
progressReader = progressReader.SetCaption(sourceURL.String() + ": ")
}
reader, err := getSourceStreamFromAlias(sourceAlias, sourceURL.String())
if err != nil {
sURLs.Error = err.Trace(sourceURL.String())
return sURLs
}
var progress io.Reader
if globalQuiet || globalJSON {
sourcePath := filepath.ToSlash(filepath.Join(sourceAlias, sourceURL.Path))
@@ -154,26 +184,69 @@ func doMirror(sURLs mirrorURLs, progressReader *progressBar, accountingReader *a
// Set up progress bar.
progress = progressReader.ProgressBar
}
_, err = putTargetStreamFromAlias(targetAlias, targetURL.String(), reader, length, progress)
if err != nil {
sURLs.Error = err.Trace(targetURL.String())
// For a fake mirror make sure we update respective progress bars
// and accounting readers under relevant conditions.
if fakeMirror {
if !globalJSON && !globalQuiet {
progressReader.ProgressBar.Add64(sURLs.SourceContent.Size)
} else {
accountingReader.Add(sURLs.SourceContent.Size)
}
sURLs.Error = nil
return sURLs
}
// If source size is <= 5GB and operation is across same server type try to use Copy.
if length <= fiveGB && sourceURL.Type == targetURL.Type {
// FS -> FS Copy includes alias in path.
if sourceURL.Type == fileSystem {
sourcePath := filepath.ToSlash(filepath.Join(sourceAlias, sourceURL.Path))
err := copySourceStreamFromAlias(targetAlias, targetURL.String(), sourcePath, length, progress)
if err != nil {
sURLs.Error = err.Trace(sourceURL.String())
return sURLs
}
} else if sourceURL.Type == objectStorage {
if sourceAlias == targetAlias {
// If source/target are object storage their aliases must be the same
// Do not include alias inside path for ObjStore -> ObjStore.
err := copySourceStreamFromAlias(targetAlias, targetURL.String(), sourceURL.Path, length, progress)
if err != nil {
sURLs.Error = err.Trace(sourceURL.String())
return sURLs
}
} else {
reader, err := getSourceStreamFromAlias(sourceAlias, sourceURL.String())
if err != nil {
sURLs.Error = err.Trace(sourceURL.String())
return sURLs
}
_, err = putTargetStreamFromAlias(targetAlias, targetURL.String(), reader, length, progress)
if err != nil {
sURLs.Error = err.Trace(targetURL.String())
return sURLs
}
}
}
} else {
// Standard GET/PUT for size > 5GB
reader, err := getSourceStreamFromAlias(sourceAlias, sourceURL.String())
if err != nil {
sURLs.Error = err.Trace(sourceURL.String())
return sURLs
}
_, err = putTargetStreamFromAlias(targetAlias, targetURL.String(), reader, length, progress)
if err != nil {
sURLs.Error = err.Trace(targetURL.String())
return sURLs
}
}
sURLs.Error = nil // just for safety
return sURLs
}
// doMirrorFake - Perform a fake mirror to update the progress bar appropriately.
func doMirrorFake(sURLs mirrorURLs, progressReader *progressBar) mirrorURLs {
if !globalDebug && !globalJSON {
progressReader.ProgressBar.Add64(sURLs.SourceContent.Size)
}
return sURLs
}
// doPrepareMirrorURLs scans the source URL and prepares a list of objects for mirroring.
func doPrepareMirrorURLs(session *sessionV6, isForce bool, trapCh <-chan bool) {
func doPrepareMirrorURLs(session *sessionV7, isForce bool, isFake bool, isRemove bool, trapCh <-chan bool) {
sourceURL := session.Header.CommandArgs[0] // first one is source.
targetURL := session.Header.CommandArgs[1]
var totalBytes int64
@@ -187,9 +260,9 @@ func doPrepareMirrorURLs(session *sessionV6, isForce bool, trapCh <-chan bool) {
scanBar = scanBarFactory()
}
URLsCh := prepareMirrorURLs(sourceURL, targetURL, isForce)
URLsCh := prepareMirrorURLs(sourceURL, targetURL, isForce, isFake, isRemove)
done := false
for done == false {
for !done {
select {
case sURLs, ok := <-URLsCh:
if !ok { // Done with URL prepration
@@ -214,10 +287,18 @@ func doPrepareMirrorURLs(session *sessionV6, isForce bool, trapCh <-chan bool) {
}
fmt.Fprintln(dataFP, string(jsonData))
if !globalQuiet && !globalJSON {
scanBar(sURLs.SourceContent.URL.String())
// Source content is empty if removal is requested,
// put targetContent on to scan bar.
if sURLs.SourceContent != nil {
scanBar(sURLs.SourceContent.URL.String())
} else if sURLs.TargetContent != nil && isRemove {
scanBar(sURLs.TargetContent.URL.String())
}
}
// Remember totalBytes only for mirror not for removal,
if sURLs.SourceContent != nil {
totalBytes += sURLs.SourceContent.Size
}
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
@@ -234,12 +315,16 @@ func doPrepareMirrorURLs(session *sessionV6, isForce bool, trapCh <-chan bool) {
}
// Session'fied mirror command.
func doMirrorSession(session *sessionV6) {
func doMirrorSession(session *sessionV7) {
isForce := session.Header.CommandBoolFlags["force"]
isFake := session.Header.CommandBoolFlags["fake"]
isRemove := session.Header.CommandBoolFlags["remove"]
// Initialize signal trap.
trapCh := signalTrap(os.Interrupt, syscall.SIGTERM)
if !session.HasData() {
doPrepareMirrorURLs(session, isForce, trapCh)
doPrepareMirrorURLs(session, isForce, isFake, isRemove, trapCh)
}
// Enable accounting reader by default.
@@ -256,7 +341,11 @@ func doMirrorSession(session *sessionV6) {
// isCopied returns true if an object has been already copied
// or not. This is useful when we resume from a session.
isCopied := isCopiedFactory(session.Header.LastCopied)
isCopied := isLastFactory(session.Header.LastCopied)
// isRemoved returns true if an object has been already removed or
// not. This is useful when we resume from a session.
isRemoved := isLastFactory(session.Header.LastRemoved)
// Wait on status of doMirror() operation.
var statusCh = make(chan mirrorURLs)
@@ -282,53 +371,72 @@ func doMirrorSession(session *sessionV6) {
return
}
if sURLs.Error == nil {
session.Header.LastCopied = sURLs.SourceContent.URL.String()
session.Save()
if sURLs.SourceContent != nil {
session.Header.LastCopied = sURLs.SourceContent.URL.String()
session.Save()
} else if sURLs.TargetContent != nil && isRemove {
session.Header.LastRemoved = sURLs.TargetContent.URL.String()
session.Save()
// Construct user facing message and path.
targetPath := filepath.ToSlash(filepath.Join(sURLs.TargetAlias, sURLs.TargetContent.URL.Path))
if !globalQuiet && !globalJSON {
console.Eraseline()
}
printMsg(rmMessage{
Status: "success",
URL: targetPath,
})
}
} else {
// Print in new line and adjust to top so that we
// don't print over the ongoing progress bar.
if !globalQuiet && !globalJSON {
console.Eraseline()
}
errorIf(sURLs.Error.Trace(sURLs.SourceContent.URL.String()),
fmt.Sprintf("Failed to copy ‘%s’.", sURLs.SourceContent.URL.String()))
if sURLs.SourceContent != nil {
errorIf(sURLs.Error.Trace(sURLs.SourceContent.URL.String()),
fmt.Sprintf("Failed to copy ‘%s’.", sURLs.SourceContent.URL.String()))
} else {
// When sURLs.SourceContent is nil, we know that we have an error related to removing
errorIf(sURLs.Error.Trace(sURLs.TargetContent.URL.String()),
fmt.Sprintf("Failed to remove ‘%s’.", sURLs.TargetContent.URL.String()))
}
// For all non critical errors we can continue for the
// remaining files.
switch sURLs.Error.ToGoError().(type) {
// Handle this specifically for filesystem related
// errors.
case client.BrokenSymlink:
// Handle this specifically for filesystem related errors.
case BrokenSymlink, TooManyLevelsSymlink, PathNotFound, PathInsufficientPermission:
continue
case client.TooManyLevelsSymlink:
continue
case client.PathNotFound:
continue
case client.PathInsufficientPermission:
continue
case client.ObjectAlreadyExists:
continue
case client.BucketDoesNotExist:
case BucketNameEmpty, ObjectMissing, ObjectAlreadyExists, BucketDoesNotExist, BucketInvalid:
continue
}
// For critical errors we should exit. Session
// can be resumed after the user figures out
// the problem.
// the problem.
session.CloseAndDie()
}
}
}
}()
// Loop through all urls.
// Loop through all urls and mirror.
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)
if sURLs.SourceContent != nil {
// Verify if previously copied or if its a fake mirror, set
// fake mirror accordingly.
fakeMirror := isCopied(sURLs.SourceContent.URL.String()) || isFake
// Perform mirror operation.
statusCh <- doMirror(sURLs, progressReader, accntReader, fakeMirror)
} else if sURLs.TargetContent != nil && isRemove {
fakeRemove := isRemoved(sURLs.TargetContent.URL.String()) || isFake
// Perform remove operation.
statusCh <- doRemove(sURLs, fakeRemove)
}
}
@@ -339,7 +447,7 @@ func doMirrorSession(session *sessionV6) {
wg.Wait()
if !globalQuiet && !globalJSON {
if progressReader.ProgressBar.Total > 0 {
if progressReader.ProgressBar.Get() > 0 {
progressReader.ProgressBar.Finish()
}
} else {
@@ -365,7 +473,7 @@ func mainMirror(ctx *cli.Context) {
console.SetColor("Mirror", color.New(color.FgGreen, color.Bold))
var e error
session := newSessionV6()
session := newSessionV7()
session.Header.CommandType = "mirror"
session.Header.RootPath, e = os.Getwd()
if e != nil {
@@ -375,7 +483,11 @@ func mainMirror(ctx *cli.Context) {
// Set command flags from context.
isForce := ctx.Bool("force")
isFake := ctx.Bool("fake")
isRemove := ctx.Bool("remove")
session.Header.CommandBoolFlags["force"] = isForce
session.Header.CommandBoolFlags["fake"] = isFake
session.Header.CommandBoolFlags["remove"] = isRemove
// extract URLs.
session.Header.CommandArgs = ctx.Args()
+80 -55
View File
@@ -1,5 +1,5 @@
/*
* Minio Client (C) 2015 Minio, Inc.
* Minio Client (C) 2015, 2016 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,15 +21,14 @@ import (
"strings"
"github.com/minio/cli"
"github.com/minio/mc/pkg/client"
"github.com/minio/minio-xl/pkg/probe"
"github.com/minio/minio/pkg/probe"
)
type mirrorURLs struct {
SourceAlias string
SourceContent *client.Content
SourceContent *clientContent
TargetAlias string
TargetContent *client.Content
TargetContent *clientContent
Error *probe.Error `json:"-"`
}
@@ -37,8 +36,11 @@ func (m mirrorURLs) isEmpty() bool {
if m.SourceContent == nil && m.TargetContent == nil && m.Error == nil {
return true
}
if m.SourceContent.Size == 0 && m.TargetContent == nil && m.Error == nil {
return true
// If remove flag is set then sourceContent is usually nil.
if m.SourceContent != nil {
if m.SourceContent.Size == 0 && m.TargetContent == nil && m.Error == nil {
return true
}
}
return false
}
@@ -75,7 +77,7 @@ func checkMirrorSyntax(ctx *cli.Context) {
fatalIf(errInvalidArgument().Trace(), "Invalid target arguments to mirror command.")
}
url := client.NewURL(tgtURL)
url := newClientURL(tgtURL)
if url.Host != "" {
if !isURLVirtualHostStyle(url.Host) {
if url.Path == string(url.Separator) {
@@ -85,19 +87,19 @@ func checkMirrorSyntax(ctx *cli.Context) {
}
}
_, _, 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))
// we die on any error other than PathNotFound - destination directory need not exist.
if _, ok := err.ToGoError().(PathNotFound); !ok {
fatalIf(err.Trace(tgtURL), fmt.Sprintf("Unable to stat target ‘%s’.", tgtURL))
}
}
func deltaSourceTargets(sourceURL string, targetURL string, isForce bool, mirrorURLsCh chan<- mirrorURLs) {
func deltaSourceTarget(sourceURL string, targetURL string, isForce bool, isFake bool, isRemove bool, mirrorURLsCh chan<- mirrorURLs) {
// source and targets are always directories
sourceSeparator := string(client.NewURL(sourceURL).Separator)
sourceSeparator := string(newClientURL(sourceURL).Separator)
if !strings.HasSuffix(sourceURL, sourceSeparator) {
sourceURL = sourceURL + sourceSeparator
}
targetSeparator := string(client.NewURL(targetURL).Separator)
targetSeparator := string(newClientURL(targetURL).Separator)
if !strings.HasSuffix(targetURL, targetSeparator) {
targetURL = targetURL + targetSeparator
}
@@ -108,61 +110,84 @@ func deltaSourceTargets(sourceURL string, targetURL string, isForce bool, mirror
defer close(mirrorURLsCh)
objectDifferenceTarget, err := objectDifferenceFactory(targetAlias, targetURL)
if err != nil {
mirrorURLsCh <- mirrorURLs{Error: err.Trace(targetAlias, targetURL)}
return
}
sourceClient, err := newClientFromAlias(sourceAlias, sourceURL)
sourceClnt, 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 {
targetClnt, err := newClientFromAlias(targetAlias, targetURL)
if err != nil {
mirrorURLsCh <- mirrorURLs{Error: err.Trace(targetAlias, targetURL)}
return
}
// List both source and target, compare and return values through channel.
for diffMsg := range objectDifference(sourceClnt, targetClnt, sourceURL, targetURL) {
switch diffMsg.Diff {
case differInNone:
// No difference, continue.
continue
case differInType:
mirrorURLsCh <- mirrorURLs{Error: errInvalidTarget(diffMsg.SecondURL)}
continue
case differInSize:
if !isForce && !isFake {
// Size differs and force not set
mirrorURLsCh <- mirrorURLs{Error: errOverWriteNotAllowed(diffMsg.SecondURL)}
continue
}
sourceSuffix := strings.TrimPrefix(diffMsg.FirstURL, sourceURL)
// Either available only in source or size differs and force is set
targetPath := urlJoinPath(targetURL, sourceSuffix)
sourceContent := diffMsg.firstContent
targetContent := &clientContent{URL: *newClientURL(targetPath)}
mirrorURLsCh <- mirrorURLs{
Error: sourceContent.Err.Trace(sourceClient.GetURL().String()),
SourceAlias: sourceAlias,
SourceContent: sourceContent,
TargetAlias: targetAlias,
TargetContent: targetContent,
}
continue
}
if sourceContent.Type.IsDir() {
case differInFirst:
sourceSuffix := strings.TrimPrefix(diffMsg.FirstURL, sourceURL)
// Either available only in source or size differs and force is set
targetPath := urlJoinPath(targetURL, sourceSuffix)
sourceContent := diffMsg.firstContent
targetContent := &clientContent{URL: *newClientURL(targetPath)}
mirrorURLsCh <- mirrorURLs{
SourceAlias: sourceAlias,
SourceContent: sourceContent,
TargetAlias: targetAlias,
TargetContent: targetContent,
}
case differInSecond:
if isRemove {
if !isForce && !isFake {
// Object removal not allowed if force is not set.
mirrorURLsCh <- mirrorURLs{
Error: errDeleteNotAllowed(diffMsg.SecondURL),
}
continue
}
mirrorURLsCh <- mirrorURLs{
TargetAlias: targetAlias,
TargetContent: diffMsg.secondContent,
}
}
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())}
default:
mirrorURLsCh <- mirrorURLs{
Error: errUnrecognizedDiffType(diffMsg.Diff).Trace(diffMsg.FirstURL, diffMsg.SecondURL),
}
continue
}
if differ == differNone {
// no difference, continue
continue
}
if differ == differType {
mirrorURLsCh <- mirrorURLs{Error: errInvalidTarget(suffix)}
continue
}
if differ == differSize && !isForce {
// size differs and force not set
mirrorURLsCh <- mirrorURLs{Error: errOverWriteNotAllowed(sourceContent.URL.String())}
continue
}
// either available only in source or size differs and force is set
targetPath := urlJoinPath(targetURL, suffix)
targetContent := &client.Content{URL: *client.NewURL(targetPath)}
mirrorURLsCh <- mirrorURLs{
SourceAlias: sourceAlias,
SourceContent: sourceContent,
TargetAlias: targetAlias,
TargetContent: targetContent,
}
}
}
func prepareMirrorURLs(sourceURL string, targetURL string, isForce bool) <-chan mirrorURLs {
// Prepares urls that need to be copied or removed based on requested options.
func prepareMirrorURLs(sourceURL string, targetURL string, isForce bool, isFake bool, isRemove bool) <-chan mirrorURLs {
mirrorURLsCh := make(chan mirrorURLs)
go deltaSourceTargets(sourceURL, targetURL, isForce, mirrorURLsCh)
go deltaSourceTarget(sourceURL, targetURL, isForce, isFake, isRemove, mirrorURLsCh)
return mirrorURLsCh
}
+4 -6
View File
@@ -23,8 +23,8 @@ import (
"strings"
"github.com/fatih/color"
"github.com/minio/minio-xl/pkg/probe"
"github.com/olekukonko/ts"
"github.com/minio/minio/pkg/probe"
"github.com/minio/pb"
)
// colorizeUpdateMessage - inspired from Yeoman project npm package https://github.com/yeoman/update-notifier.
@@ -49,15 +49,13 @@ func colorizeUpdateMessage(updateString string) (string, *probe.Error) {
line1Rest := maxContentWidth - line1Length
line2Rest := maxContentWidth - line2Length
// Fetch terminal size to calculate optimal box size.
terminal, e := ts.GetSize()
termWidth, e := pb.GetTerminalWidth()
if e != nil {
return "", probe.NewError(e)
}
var message string
switch {
case len(line2Str) > terminal.Col():
case len(line2Str) > termWidth:
message = "\n" + line1InColor + "\n" + line2InColor + "\n"
default:
// on windows terminal turn off unicode characters.
+2 -2
View File
@@ -21,7 +21,7 @@ import (
"syscall"
"github.com/minio/cli"
"github.com/minio/minio-xl/pkg/probe"
"github.com/minio/minio/pkg/probe"
)
var (
@@ -55,7 +55,7 @@ EXAMPLES:
2. Write contents of stdin to an object on Amazon S3 cloud storage.
$ mc {{.Name}} s3/personalbuck/meeting-notes.txt
3. Copy an ISO image to an object on Amazon S3 cloud storage and Google Cloud Storage simultaneously.
3. Copy an ISO image to an object on Amazon S3 cloud storage.
$ cat debian-8.2.iso | mc {{.Name}} s3/ferenginar/gnuos.iso
4. Stream MySQL database dump to Amazon S3 directly.
-69
View File
@@ -1,69 +0,0 @@
/*
* Minio Client (C) 2015 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package client
import (
"testing"
. "gopkg.in/check.v1"
)
func Test(t *testing.T) { TestingT(t) }
type MySuite struct{}
var _ = Suite(&MySuite{})
func (s *MySuite) TestURLParse(c *C) {
u := NewURL("http://s3.example.com")
c.Assert(u.Scheme, Equals, "http")
c.Assert(u.Host, Equals, "s3.example.com")
c.Assert(u.Path, Equals, "/")
c.Assert(u.SchemeSeparator, Equals, "://")
u = NewURL("http://s3.example.com/path/new")
c.Assert(u.Scheme, Equals, "http")
c.Assert(u.Host, Equals, "s3.example.com")
c.Assert(u.Path, Equals, "/path/new")
c.Assert(u.SchemeSeparator, Equals, "://")
u = NewURL(":::://s3.example.com/path/new")
c.Assert(u.Scheme, Equals, "")
c.Assert(u.Host, Equals, "")
c.Assert(u.Path, Equals, ":::://s3.example.com/path/new")
c.Assert(u.SchemeSeparator, Equals, "")
u = NewURL("localhost:9000")
c.Assert(u.Scheme, Equals, "")
c.Assert(u.Host, Equals, "")
c.Assert(u.Path, Equals, "localhost:9000")
c.Assert(u.SchemeSeparator, Equals, "")
}
func (s *MySuite) TestPathParse(c *C) {
u := NewURL("path/test")
c.Assert(u.Scheme, Equals, "")
c.Assert(u.Host, Equals, "")
c.Assert(u.Path, Equals, "path/test")
c.Assert(u.SchemeSeparator, Equals, "")
u = NewURL("/path/test")
c.Assert(u.Scheme, Equals, "")
c.Assert(u.Host, Equals, "")
c.Assert(u.Path, Equals, "/path/test")
c.Assert(u.SchemeSeparator, Equals, "")
}
-1
View File
@@ -1 +0,0 @@
*#
-86
View File
@@ -1,86 +0,0 @@
/*
* Minio Client (C) 2015 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this fs except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package fs
import (
"os"
"path/filepath"
"runtime"
"strings"
"github.com/minio/mc/pkg/client"
"github.com/minio/minio-xl/pkg/probe"
)
// toClientError error constructs a typed client error for known filesystem errors.
func (f *fsClient) toClientError(e error, fpath string) *probe.Error {
if os.IsPermission(e) {
return probe.NewError(client.PathInsufficientPermission{Path: fpath})
}
if os.IsNotExist(e) {
return probe.NewError(client.PathNotFound{Path: fpath})
}
return probe.NewError(e)
}
// handle windows symlinks - eg: junction files.
func (f *fsClient) handleWindowsSymlinks(fpath string) (os.FileInfo, *probe.Error) {
// On windows there are directory symlinks which are called junction files.
// These files carry special meaning on windows they cannot be,
// accessed with regular operations.
file, e := os.Lstat(fpath)
if e != nil {
err := f.toClientError(e, fpath)
return nil, err.Trace(fpath)
}
return file, nil
}
// fsStat - wrapper function to get file stat.
func (f *fsClient) fsStat() (os.FileInfo, *probe.Error) {
fpath := f.PathURL.Path
// Golang strips trailing / if you clean(..) or
// EvalSymlinks(..). Adding '.' prevents it from doing so.
if strings.HasSuffix(fpath, string(f.PathURL.Separator)) {
fpath = fpath + "."
}
fpath, e := filepath.EvalSymlinks(fpath)
if e != nil {
if os.IsPermission(e) {
if runtime.GOOS == "windows" {
return f.handleWindowsSymlinks(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
}
-168
View File
@@ -1,168 +0,0 @@
/*
* Minio Client (C) 2015 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this 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
}
+2 -2
View File
@@ -24,8 +24,8 @@ import (
"path/filepath"
"github.com/fatih/color"
"github.com/mattn/go-colorable"
"github.com/mattn/go-isatty"
"github.com/shiena/ansicolor"
)
var (
@@ -37,7 +37,7 @@ var (
// Used internally by console.
privateMutex = &sync.Mutex{}
stderrColoredOutput = ansicolor.NewAnsiColorWriter(os.Stderr)
stderrColoredOutput = colorable.NewColorableStderr()
// Print prints a message.
Print = func(data ...interface{}) {
+8
View File
@@ -36,6 +36,14 @@ type RoundTripTrace struct {
Transport http.RoundTripper // HTTP transport that needs to be intercepted
}
// CancelRequest implements functinality to cancel an underlying request.
func (t RoundTripTrace) CancelRequest(req *http.Request) {
transport, ok := t.Transport.(*http.Transport)
if ok {
transport.CancelRequest(req)
}
}
// RoundTrip executes user provided request and response hooks for each HTTP call.
func (t RoundTripTrace) RoundTrip(req *http.Request) (res *http.Response, err error) {
timeStamp := time.Now()
+143
View File
@@ -0,0 +1,143 @@
/*
* Minio Cloud Storage, (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 ioutils
import (
"errors"
"io"
"os"
"path/filepath"
"sort"
)
// IsDirEmpty Check if a directory is empty
func IsDirEmpty(dirname string) (status bool, err error) {
f, err := os.Open(dirname)
if err == nil {
defer f.Close()
if _, err = f.Readdirnames(1); err == io.EOF {
status = true
err = nil
}
}
return
}
// FTW walks the file tree rooted at root, calling walkFn for each file or
// directory in the tree, including root.
func FTW(root string, walkFn FTWFunc) error {
info, err := os.Lstat(root)
if err != nil {
return walkFn(root, nil, err)
}
return walk(root, info, walkFn)
}
// byName implements sort.Interface for sorting os.FileInfo list.
type byName []os.FileInfo
func (f byName) Len() int { return len(f) }
func (f byName) Swap(i, j int) { f[i], f[j] = f[j], f[i] }
func (f byName) Less(i, j int) bool {
n1 := f[i].Name()
if f[i].IsDir() {
n1 = n1 + string(os.PathSeparator)
}
n2 := f[j].Name()
if f[j].IsDir() {
n2 = n2 + string(os.PathSeparator)
}
return n1 < n2
}
// readDir reads the directory named by dirname and returns
// a sorted list of directory entries.
func readDir(dirname string) (fi []os.FileInfo, err error) {
f, err := os.Open(dirname)
if err == nil {
defer f.Close()
if fi, err = f.Readdir(-1); fi != nil {
sort.Sort(byName(fi))
}
}
return
}
// FTWFunc 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 FTWFunc func(path string, info os.FileInfo, err error) error
// ErrSkipDir is used as a return value from WalkFuncs to indicate that
// the directory named in the call is to be skipped. It is not returned
// as an error by any function.
var ErrSkipDir = errors.New("skip this directory")
// ErrSkipFile is used as a return value from WalkFuncs to indicate that
// the file named in the call is to be skipped. It is not returned
// as an error by any function.
var ErrSkipFile = errors.New("skip this file")
// ErrDirNotEmpty is used to throw error on directories which have atleast one regular
// file or a symlink left
var ErrDirNotEmpty = errors.New("directory not empty")
// walk recursively descends path, calling walkFn.
func walk(path string, info os.FileInfo, walkFn FTWFunc) error {
err := walkFn(path, info, nil)
if err != nil {
if info.Mode().IsDir() && err == ErrSkipDir {
return nil
}
if info.Mode().IsRegular() && err == ErrSkipFile {
return nil
}
return err
}
if !info.IsDir() {
return nil
}
fis, err := readDir(path)
if err != nil {
return walkFn(path, info, err)
}
for _, fileInfo := range fis {
filename := filepath.Join(path, fileInfo.Name())
if err != nil {
if err = walkFn(filename, fileInfo, err); err != nil && err != ErrSkipDir && err != ErrSkipFile {
return err
}
} else {
err = walk(filename, fileInfo, walkFn)
if err != nil {
if err == ErrSkipDir || err == ErrSkipFile {
return nil
}
return err
}
}
}
return nil
}
@@ -1,5 +1,5 @@
/*
* Minio Cloud Storage, (C) 2015 Minio, Inc.
* Minio Cloud Storage, (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.
@@ -14,12 +14,14 @@
* limitations under the License.
*/
package user_test
package ioutils_test
import (
"io/ioutil"
"os"
"testing"
"github.com/minio/minio/pkg/user"
"github.com/minio/minio/pkg/ioutils"
. "gopkg.in/check.v1"
)
@@ -30,12 +32,12 @@ type MySuite struct{}
var _ = Suite(&MySuite{})
func (s *MySuite) TestUser(c *C) {
_, err := user.Current()
func (s *MySuite) TestIoutils(c *C) {
path, err := ioutil.TempDir(os.TempDir(), "minio-ioutils_test")
c.Assert(err, IsNil)
}
defer os.RemoveAll(path)
func (s *MySuite) TestHomeDir(c *C) {
_, err := user.HomeDir()
status, err := ioutils.IsDirEmpty(path)
c.Assert(err, IsNil)
c.Assert(status, Equals, true)
}
-5
View File
@@ -1,5 +0,0 @@
SET MC_RELEASE=OFFICIAL
SET GO15VENDOREXPERIMENT=1
go run buildscripts/gen-ldflags.go > temp.txt
SET /p LDFLAGS=<temp.txt
go build -ldflags="%LDFLAGS%" -o %GOPATH%\bin\mc.exe
-6
View File
@@ -1,6 +0,0 @@
#!/bin/bash
echo -n "Making official release binaries.. "
export MC_RELEASE=OFFICIAL
make 1>/dev/null
echo "Binaries built at ${GOPATH}/bin/mc"
+4 -3
View File
@@ -25,7 +25,7 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/console"
"github.com/minio/minio-xl/pkg/probe"
"github.com/minio/minio/pkg/probe"
)
// rm specific flags.
@@ -113,6 +113,7 @@ func checkRmSyntax(ctx *cli.Context) {
// Set command flags from context.
isForce := ctx.Bool("force")
isRecursive := ctx.Bool("recursive")
isFake := ctx.Bool("fake")
if !ctx.Args().Present() {
exitCode := 1
@@ -120,7 +121,7 @@ func checkRmSyntax(ctx *cli.Context) {
}
// For all recursive operations make sure to check for 'force' flag.
if isRecursive && !isForce {
if isRecursive && !isForce && !isFake {
fatalIf(errDummy().Trace(),
"Recursive removal requires --force option. Please review carefully before performing this *DANGEROUS* operation.")
}
@@ -202,7 +203,7 @@ func mainRm(ctx *cli.Context) {
// Support multiple targets.
for _, url := range ctx.Args() {
targetAlias, targetURL, _ := mustExpandAlias(url)
if isRecursive && isForce {
if isRecursive && isForce || isFake {
rmAll(targetAlias, targetURL, isRecursive, isIncomplete, isFake)
} else {
if err := rm(targetAlias, targetURL, isIncomplete, isFake); err != nil {
+45
View File
@@ -0,0 +1,45 @@
/*
* Minio Client (C) 2014, 2015, 2016 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package main
import (
"fmt"
"runtime"
"github.com/hashicorp/go-version"
"github.com/minio/mc/pkg/console"
)
// check if minimum Go version is met.
func checkGoVersion() {
// Current version.
curVersion, e := version.NewVersion(runtime.Version()[2:])
if e != nil {
console.Fatalln("Unable to determine current go version.", e)
}
// Prepare version constraint.
constraints, e := version.NewConstraint(minGoVersion)
if e != nil {
console.Fatalln("Unable to check go version.")
}
// Check for minimum version.
if !constraints.Check(curVersion) {
console.Fatalln(fmt.Sprintf("Please recompile Minio with Golang version %s.", minGoVersion))
}
}
+6 -8
View File
@@ -22,8 +22,8 @@ import (
"github.com/dustin/go-humanize"
"github.com/minio/mc/pkg/console"
"github.com/minio/minio-xl/pkg/probe"
"github.com/olekukonko/ts"
"github.com/minio/minio/pkg/probe"
"github.com/minio/pb"
)
/******************************** Scan Bar ************************************/
@@ -47,13 +47,11 @@ func scanBarFactory() scanBarFunc {
prevLineSize := 0
prevSource := ""
fileCount := 0
termSize, e := ts.GetSize()
if e != nil {
fatalIf(probe.NewError(e), "Unable to get terminal size. Please use --quiet option.")
}
termWidth := termSize.Col()
cursorCh := cursorAnimate()
termWidth, e := pb.GetTerminalWidth()
fatalIf(probe.NewError(e), "Unable to get terminal size. Please use --quiet option.")
// Cursor animate channel.
cursorCh := cursorAnimate()
return func(source string) {
scanPrefix := fmt.Sprintf("[%s] %s ", humanize.Comma(int64(fileCount)), string(<-cursorCh))
cmnPrefix := commonPrefix(source, prevSource)
+28 -13
View File
@@ -26,7 +26,7 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/console"
"github.com/minio/minio-xl/pkg/probe"
"github.com/minio/minio/pkg/probe"
)
var (
@@ -77,7 +77,7 @@ EXAMPLES:
}
// bySessionWhen is a type for sorting session metadata by time.
type bySessionWhen []*sessionV6
type bySessionWhen []*sessionV7
func (b bySessionWhen) Len() int { return len(b) }
func (b bySessionWhen) Swap(i, j int) { b[i], b[j] = b[j], b[i] }
@@ -85,19 +85,19 @@ func (b bySessionWhen) Less(i, j int) bool { return b[i].Header.When.Before(b[j]
// listSessions list all current sessions.
func listSessions() *probe.Error {
var bySessions []*sessionV6
var bySessions []*sessionV7
for _, sid := range getSessionIDs() {
s, err := loadSessionV6(sid)
session, err := loadSessionV7(sid)
if err != nil {
return err.Trace(sid)
continue // Skip 'broken' session during listing
}
bySessions = append(bySessions, s)
session.Close() // Session close right here.
bySessions = append(bySessions, session)
}
// sort sessions based on time.
sort.Sort(bySessionWhen(bySessions))
for _, session := range bySessions {
printMsg(session)
session.Close()
}
return nil
}
@@ -110,7 +110,15 @@ type clearSessionMessage struct {
// String colorized clear session message.
func (c clearSessionMessage) String() string {
return console.Colorize("ClearSession", "Session ‘"+c.SessionID+"’ cleared successfully.")
msg := "Session ‘" + c.SessionID + "’"
var colorizedMsg string
switch c.Status {
case "success":
colorizedMsg = console.Colorize("ClearSession", msg+" cleared succesfully.")
case "forced":
colorizedMsg = console.Colorize("ClearSession", msg+" cleared forcefully.")
}
return colorizedMsg
}
// JSON jsonified clear session message.
@@ -125,7 +133,7 @@ func (c clearSessionMessage) JSON() string {
func clearSession(sid string) {
if sid == "all" {
for _, sid := range getSessionIDs() {
session, err := loadSessionV6(sid)
session, err := loadSessionV7(sid)
fatalIf(err.Trace(sid), "Unable to load session ‘"+sid+"’.")
fatalIf(session.Delete().Trace(sid), "Unable to load session ‘"+sid+"’.")
@@ -139,8 +147,15 @@ func clearSession(sid string) {
fatalIf(errDummy().Trace(sid), "Session ‘"+sid+"’ not found.")
}
session, err := loadSessionV6(sid)
fatalIf(err.Trace(sid), "Unable to load session ‘"+sid+"’.")
session, err := loadSessionV7(sid)
if err != nil {
// `mc session clear <broken-session-id>` assumes that user is aware that the session is unuseful
// and wants the associated session files to be removed
removeSessionFile(sid)
removeSessionDataFile(sid)
printMsg(clearSessionMessage{Status: "forced", SessionID: sid})
return
}
if session != nil {
fatalIf(session.Delete().Trace(sid), "Unable to load session ‘"+sid+"’.")
@@ -148,7 +163,7 @@ func clearSession(sid string) {
}
}
func sessionExecute(s *sessionV6) {
func sessionExecute(s *sessionV7) {
switch s.Header.CommandType {
case "cp":
doCopySession(s)
@@ -230,7 +245,7 @@ func mainSession(ctx *cli.Context) {
}
fatalIf(errDummy().Trace(sid), errorMsg)
}
s, err := loadSessionV6(sid)
s, err := loadSessionV7(sid)
fatalIf(err.Trace(sid), "Unable to load session.")
// Restore the state of global variables from this previous session.
+100
View File
@@ -0,0 +1,100 @@
/*
* 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 main
import (
"os"
"strconv"
"github.com/minio/mc/pkg/console"
"github.com/minio/minio/pkg/probe"
"github.com/minio/minio/pkg/quick"
)
// Migrates session header version '6' to '7'. Only change is
// LastRemoved field which was added in version '7'.
func migrateSessionV6ToV7() {
for _, sid := range getSessionIDs() {
sV6Header, err := loadSessionV6Header(sid)
fatalIf(err.Trace(sid), "Unable to load version ‘6’. Migration failed please report this issue at https://github.com/minio/mc/issues.")
if sV6Header.Version == "7" { // It is new format.
continue
}
sessionFile, err := getSessionFile(sid)
fatalIf(err.Trace(sid), "Unable to get session file.")
// Initialize v7 header and migrate to new config.
sV7Header := &sessionV7Header{}
sV7Header.Version = "7"
sV7Header.When = sV6Header.When
sV7Header.RootPath = sV6Header.RootPath
sV7Header.GlobalBoolFlags = sV6Header.GlobalBoolFlags
sV7Header.GlobalIntFlags = sV6Header.GlobalIntFlags
sV7Header.GlobalStringFlags = sV6Header.GlobalStringFlags
sV7Header.CommandType = sV6Header.CommandType
sV7Header.CommandArgs = sV6Header.CommandArgs
sV7Header.CommandBoolFlags = sV6Header.CommandBoolFlags
sV7Header.CommandIntFlags = sV6Header.CommandIntFlags
sV7Header.CommandStringFlags = sV6Header.CommandStringFlags
sV7Header.LastCopied = sV6Header.LastCopied
sV7Header.LastRemoved = ""
sV7Header.TotalBytes = sV6Header.TotalBytes
sV7Header.TotalObjects = sV6Header.TotalObjects
qs, err := quick.New(sV7Header)
fatalIf(err.Trace(sid), "Unable to initialize quick config for session '7' header.")
err = qs.Save(sessionFile)
fatalIf(err.Trace(sid, sessionFile), "Unable to migrate session from '6' to '7'.")
console.Println("Successfully migrated ‘" + sessionFile + "’ from version ‘" + sV6Header.Version + "’ to " + "‘" + sV7Header.Version + "’.")
}
}
// Migrate session version '5' to version '6', all older sessions are
// in-fact removed and not migrated. All session files from '6' and
// above should be migrated - See: migrateSessionV6ToV7().
func migrateSessionV5ToV6() {
for _, sid := range getSessionIDs() {
sV6Header, err := loadSessionV6Header(sid)
fatalIf(err.Trace(sid), "Unable to load version ‘6’. Migration failed please report this issue at https://github.com/minio/mc/issues.")
sessionVersion, e := strconv.Atoi(sV6Header.Version)
fatalIf(probe.NewError(e), "Unable to load version ‘6’. Migration failed please report this issue at https://github.com/minio/mc/issues.")
if sessionVersion > 5 { // It is new format.
continue
}
/*** Remove all session files older than v6 ***/
sessionFile, err := getSessionFile(sid)
fatalIf(err.Trace(sid), "Unable to get session file.")
sessionDataFile, err := getSessionDataFile(sid)
fatalIf(err.Trace(sid), "Unable to get session data file.")
console.Println("Removing unsupported session file ‘" + sessionFile + "’ version ‘" + sV6Header.Version + "’.")
if e := os.Remove(sessionFile); e != nil {
fatalIf(probe.NewError(e), "Unable to remove version ‘"+sV6Header.Version+"’ session file ‘"+sessionFile+"’.")
}
if e := os.Remove(sessionDataFile); e != nil {
fatalIf(probe.NewError(e), "Unable to remove version ‘"+sV6Header.Version+"’ session data file ‘"+sessionDataFile+"’.")
}
}
}
+76
View File
@@ -0,0 +1,76 @@
/*
* Minio Client (C) 2016 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package main
import (
"os"
"time"
"github.com/minio/minio/pkg/probe"
"github.com/minio/minio/pkg/quick"
)
/////////////////// Session V6 ///////////////////
// sessionV6Header for resumable sessions.
type sessionV6Header struct {
Version string `json:"version"`
When time.Time `json:"time"`
RootPath string `json:"workingFolder"`
GlobalBoolFlags map[string]bool `json:"globalBoolFlags"`
GlobalIntFlags map[string]int `json:"globalIntFlags"`
GlobalStringFlags map[string]string `json:"globalStringFlags"`
CommandType string `json:"commandType"`
CommandArgs []string `json:"cmdArgs"`
CommandBoolFlags map[string]bool `json:"cmdBoolFlags"`
CommandIntFlags map[string]int `json:"cmdIntFlags"`
CommandStringFlags map[string]string `json:"cmdStringFlags"`
LastCopied string `json:"lastCopied"`
TotalBytes int64 `json:"totalBytes"`
TotalObjects int `json:"totalObjects"`
}
func loadSessionV6Header(sid string) (*sessionV6Header, *probe.Error) {
if !isSessionDirExists() {
return nil, errInvalidArgument().Trace()
}
sessionFile, err := getSessionFile(sid)
if err != nil {
return nil, err.Trace(sid)
}
if _, e := os.Stat(sessionFile); e != nil {
return nil, probe.NewError(e)
}
sV6Header := &sessionV6Header{}
sV6Header.Version = "6"
qs, err := quick.New(sV6Header)
if err != nil {
return nil, err.Trace(sid, sV6Header.Version)
}
err = qs.Load(sessionFile)
if err != nil {
return nil, err.Trace(sid, sV6Header.Version)
}
sV6Header = qs.Data().(*sessionV6Header)
return sV6Header, nil
}
/////////////////// Session V7 ///////////////////
// RESERVED FOR FUTURE
+104 -80
View File
@@ -28,37 +28,12 @@ import (
"time"
"github.com/minio/mc/pkg/console"
"github.com/minio/minio-xl/pkg/probe"
"github.com/minio/minio-xl/pkg/quick"
"github.com/minio/minio/pkg/probe"
"github.com/minio/minio/pkg/quick"
)
func migrateSessionV5ToV6() {
for _, sid := range getSessionIDs() {
sessionV6, err := loadSessionV6(sid)
fatalIf(err.Trace(sid), "Unable to load version ‘6’. Migration failed please report this issue at https://github.com/minio/mc/issues.")
if sessionV6.Header.Version == "6" { // It is new format.
return
}
/*** Remove all session files older than v6 ***/
sessionFile, err := getSessionFile(sid)
fatalIf(err.Trace(sid), "Unable to get session file.")
sessionDataFile, err := getSessionDataFile(sid)
fatalIf(err.Trace(sid), "Unable to get session data file.")
console.Println("Removing unsupported session file ‘" + sessionFile + "’ version ‘" + sessionV6.Header.Version + "’.")
if e := os.Remove(sessionFile); e != nil {
fatalIf(probe.NewError(e), "Unable to remove version ‘"+sessionV6.Header.Version+"’ session file ‘"+sessionFile+"’.")
}
if e := os.Remove(sessionDataFile); e != nil {
fatalIf(probe.NewError(e), "Unable to remove version ‘"+sessionV6.Header.Version+"’ session data file ‘"+sessionDataFile+"’.")
}
}
}
// sessionV6Header for resumable sessions.
type sessionV6Header struct {
// sessionV7Header for resumable sessions.
type sessionV7Header struct {
Version string `json:"version"`
When time.Time `json:"time"`
RootPath string `json:"workingFolder"`
@@ -71,6 +46,7 @@ type sessionV6Header struct {
CommandIntFlags map[string]int `json:"cmdIntFlags"`
CommandStringFlags map[string]string `json:"cmdStringFlags"`
LastCopied string `json:"lastCopied"`
LastRemoved string `json:"lastRemoved"`
TotalBytes int64 `json:"totalBytes"`
TotalObjects int `json:"totalObjects"`
}
@@ -84,9 +60,9 @@ type sessionMessage struct {
CommandArgs []string `json:"commandArgs"`
}
// sessionV6 resumable session container.
type sessionV6 struct {
Header *sessionV6Header
// sessionV7 resumable session container.
type sessionV7 struct {
Header *sessionV7Header
SessionID string
mutex *sync.Mutex
DataFP *sessionDataFP
@@ -105,7 +81,7 @@ func (file *sessionDataFP) Write(p []byte) (int, error) {
}
// String colorized session message.
func (s sessionV6) String() string {
func (s sessionV7) String() string {
message := console.Colorize("SessionID", fmt.Sprintf("%s -> ", s.SessionID))
message = message + console.Colorize("SessionTime", fmt.Sprintf("[%s]", s.Header.When.Local().Format(printDate)))
message = message + console.Colorize("Command", fmt.Sprintf(" %s %s", s.Header.CommandType, strings.Join(s.Header.CommandArgs, " ")))
@@ -113,7 +89,7 @@ func (s sessionV6) String() string {
}
// JSON jsonified session message.
func (s sessionV6) JSON() string {
func (s sessionV7) JSON() string {
sessionMsg := sessionMessage{
SessionID: s.SessionID,
Time: s.Header.When.Local(),
@@ -127,8 +103,8 @@ func (s sessionV6) JSON() string {
return string(sessionBytes)
}
// loadSessionV6 - reads session file if exists and re-initiates internal variables
func loadSessionV6(sid string) (*sessionV6, *probe.Error) {
// loadSessionV7 - reads session file if exists and re-initiates internal variables
func loadSessionV7(sid string) (*sessionV7, *probe.Error) {
if !isSessionDirExists() {
return nil, errInvalidArgument().Trace()
}
@@ -141,10 +117,10 @@ func loadSessionV6(sid string) (*sessionV6, *probe.Error) {
return nil, probe.NewError(e)
}
s := &sessionV6{}
s.Header = &sessionV6Header{}
s := &sessionV7{}
s.Header = &sessionV7Header{}
s.SessionID = sid
s.Header.Version = "5"
s.Header.Version = "7"
qs, err := quick.New(s.Header)
if err != nil {
return nil, err.Trace(sid, s.Header.Version)
@@ -155,27 +131,27 @@ func loadSessionV6(sid string) (*sessionV6, *probe.Error) {
}
s.mutex = new(sync.Mutex)
s.Header = qs.Data().(*sessionV6Header)
s.Header = qs.Data().(*sessionV7Header)
sessionDataFile, err := getSessionDataFile(s.SessionID)
if err != nil {
return nil, err.Trace(sid, s.Header.Version)
}
var e error
dataFile, e := os.Open(sessionDataFile)
fatalIf(probe.NewError(e), "Unable to open session data file \""+sessionDataFile+"\".")
if e != nil {
return nil, probe.NewError(e)
}
s.DataFP = &sessionDataFP{false, dataFile}
return s, nil
}
// newSessionV6 provides a new session.
func newSessionV6() *sessionV6 {
s := &sessionV6{}
s.Header = &sessionV6Header{}
s.Header.Version = "6"
// newSessionV7 provides a new session.
func newSessionV7() *sessionV7 {
s := &sessionV7{}
s.Header = &sessionV7Header{}
s.Header.Version = "7"
// map of command and files copied.
s.Header.GlobalBoolFlags = make(map[string]bool)
s.Header.GlobalIntFlags = make(map[string]int)
@@ -203,29 +179,26 @@ func newSessionV6() *sessionV6 {
}
// HasData provides true if this is a session resume, false otherwise.
func (s sessionV6) HasData() bool {
if s.Header.LastCopied == "" {
return false
}
return true
func (s sessionV7) HasData() bool {
return s.Header.LastCopied != "" || s.Header.LastRemoved != ""
}
// NewDataReader provides reader interface to session data file.
func (s *sessionV6) NewDataReader() io.Reader {
func (s *sessionV7) NewDataReader() io.Reader {
// DataFP is always intitialized, either via new or load functions.
s.DataFP.Seek(0, os.SEEK_SET)
return io.Reader(s.DataFP)
}
// NewDataReader provides writer interface to session data file.
func (s *sessionV6) NewDataWriter() io.Writer {
func (s *sessionV7) 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 {
func (s *sessionV7) Save() *probe.Error {
s.mutex.Lock()
defer s.mutex.Unlock()
@@ -250,7 +223,7 @@ func (s *sessionV6) Save() *probe.Error {
// setGlobals captures the state of global variables into session header.
// Used by newSession.
func (s *sessionV6) setGlobals() {
func (s *sessionV7) setGlobals() {
s.Header.GlobalBoolFlags["quiet"] = globalQuiet
s.Header.GlobalBoolFlags["debug"] = globalDebug
s.Header.GlobalBoolFlags["json"] = globalJSON
@@ -259,7 +232,7 @@ func (s *sessionV6) setGlobals() {
// RestoreGlobals restores the state of global variables.
// Used by resumeSession.
func (s sessionV6) restoreGlobals() {
func (s sessionV7) restoreGlobals() {
quiet := s.Header.GlobalBoolFlags["quiet"]
debug := s.Header.GlobalBoolFlags["debug"]
json := s.Header.GlobalBoolFlags["json"]
@@ -267,8 +240,62 @@ func (s sessionV6) restoreGlobals() {
setGlobals(quiet, debug, json, noColor)
}
// IsModified - returns if in memory session header has changed from
// its on disk value.
func (s *sessionV7) isModified(sessionFile string) (bool, *probe.Error) {
qs, err := quick.New(s.Header)
if err != nil {
return false, err.Trace(s.SessionID)
}
var currentHeader = &sessionV7Header{}
currentQS, err := quick.Load(sessionFile, currentHeader)
if err != nil {
// If session does not exist for the first, return modified to
// be true.
if os.IsNotExist(err.ToGoError()) {
return true, nil
}
// For all other errors return.
return false, err.Trace(s.SessionID)
}
changedFields, err := qs.DeepDiff(currentQS)
if err != nil {
return false, err.Trace(s.SessionID)
}
// Returns true if there are changed entries.
return len(changedFields) > 0, nil
}
// save - wrapper for quick.Save and saves only if sessionHeader is
// modified.
func (s *sessionV7) save() *probe.Error {
sessionFile, err := getSessionFile(s.SessionID)
if err != nil {
return err.Trace(s.SessionID)
}
// Verify if sessionFile is modified.
modified, err := s.isModified(sessionFile)
if err != nil {
return err.Trace(s.SessionID)
}
// Header is modified, we save it.
if modified {
qs, err := quick.New(s.Header)
if err != nil {
return err.Trace(s.SessionID)
}
// Save an return.
return qs.Save(sessionFile).Trace(sessionFile)
}
return nil
}
// Close ends this session and removes all associated session files.
func (s *sessionV6) Close() *probe.Error {
func (s *sessionV7) Close() *probe.Error {
s.mutex.Lock()
defer s.mutex.Unlock()
@@ -276,20 +303,12 @@ func (s *sessionV6) Close() *probe.Error {
return probe.NewError(err)
}
qs, err := quick.New(s.Header)
if err != nil {
return err.Trace()
}
sessionFile, err := getSessionFile(s.SessionID)
if err != nil {
return err.Trace(s.SessionID)
}
return qs.Save(sessionFile).Trace(sessionFile)
// Attempt to save the header if modified.
return s.save()
}
// Delete removes all the session files.
func (s *sessionV6) Delete() *probe.Error {
func (s *sessionV7) Delete() *probe.Error {
s.mutex.Lock()
defer s.mutex.Unlock()
@@ -300,45 +319,50 @@ func (s *sessionV6) Delete() *probe.Error {
// the file is closed already
s.DataFP.Close()
// Remove the data file.
if e := os.Remove(name); e != nil {
return probe.NewError(e)
}
}
// Fetch the session file.
sessionFile, err := getSessionFile(s.SessionID)
if err != nil {
return err.Trace(s.SessionID)
}
// Remove session file
if e := os.Remove(sessionFile); e != nil {
return probe.NewError(e)
}
// Remove session backup file if any, ignore any error.
os.Remove(sessionFile + ".old")
return nil
}
// Close a session and exit.
func (s sessionV6) CloseAndDie() {
func (s sessionV7) CloseAndDie() {
s.Close()
console.Fatalln("Session safely terminated. To resume session ‘mc session resume " + s.SessionID + "’")
}
// Create a factory function to simplify checking if an
// object has been copied or not.
// isCopied(URL) -> true or false
func isCopiedFactory(lastCopied string) func(string) bool {
copied := true // closure
// Create a factory function to simplify checking if
// object was last operated on.
func isLastFactory(lastURL string) func(string) bool {
last := true // closure
return func(sourceURL string) bool {
if sourceURL == "" {
fatalIf(errInvalidArgument().Trace(), "Empty source argument passed.")
}
if lastCopied == "" {
if lastURL == "" {
return false
}
if copied {
if lastCopied == sourceURL {
copied = false // from next call onwards we say false.
if last {
if lastURL == sourceURL {
last = false // from next call onwards we say false.
}
return true
}
+22 -1
View File
@@ -21,13 +21,16 @@ import (
"path/filepath"
"strings"
"github.com/minio/minio-xl/pkg/probe"
"github.com/minio/minio/pkg/probe"
)
// migrateSession migrates all previous migration to latest.
func migrateSession() {
// We no longer support sessions older than v5. They will be removed.
migrateSessionV5ToV6()
// Migrate V6 to V7.
migrateSessionV6ToV7()
}
// createSessionDir - create session directory.
@@ -112,3 +115,21 @@ func getSessionIDs() (sids []string) {
}
return sids
}
// removeSessionFile - remove the session file, ending with .json
func removeSessionFile(sid string) {
sessionFile, err := getSessionFile(sid)
if err != nil {
return
}
os.Remove(sessionFile)
}
// removeSessionDataFile - remove the session data file, ending with .data
func removeSessionDataFile(sid string) {
dataFile, err := getSessionDataFile(sid)
if err != nil {
return
}
os.Remove(dataFile)
}
+9 -2
View File
@@ -17,6 +17,7 @@
package main
import (
"os"
"regexp"
. "gopkg.in/check.v1"
@@ -34,14 +35,17 @@ func (s *TestSuite) TestSession(c *C) {
c.Assert(err, IsNil)
c.Assert(isSessionDirExists(), Equals, true)
session := newSessionV6()
session := newSessionV7()
c.Assert(session.Header.CommandArgs, IsNil)
c.Assert(len(session.SessionID), Equals, 8)
_, e := os.Stat(session.DataFP.Name())
c.Assert(e, IsNil)
err = session.Close()
c.Assert(err, IsNil)
c.Assert(isSessionExists(session.SessionID), Equals, true)
savedSession, err := loadSessionV6(session.SessionID)
savedSession, err := loadSessionV7(session.SessionID)
c.Assert(err, IsNil)
c.Assert(session.SessionID, Equals, savedSession.SessionID)
@@ -50,4 +54,7 @@ func (s *TestSuite) TestSession(c *C) {
err = savedSession.Delete()
c.Assert(err, IsNil)
c.Assert(isSessionExists(session.SessionID), Equals, false)
_, e = os.Stat(session.DataFP.Name())
c.Assert(e, NotNil)
}
+2 -2
View File
@@ -21,8 +21,8 @@ import (
"sync"
"time"
"github.com/minio/minio-xl/pkg/probe"
"github.com/minio/minio-xl/pkg/quick"
"github.com/minio/minio/pkg/probe"
"github.com/minio/minio/pkg/quick"
)
// shareEntryV1 - container for each download/upload entries.
+1 -1
View File
@@ -20,7 +20,7 @@ import (
"time"
"github.com/minio/cli"
"github.com/minio/minio-xl/pkg/probe"
"github.com/minio/minio/pkg/probe"
)
var (
+1 -1
View File
@@ -21,7 +21,7 @@ import (
"time"
"github.com/minio/cli"
"github.com/minio/minio-xl/pkg/probe"
"github.com/minio/minio/pkg/probe"
)
var (
+1 -1
View File
@@ -22,7 +22,7 @@ import (
"github.com/minio/cli"
"github.com/minio/mc/pkg/console"
"github.com/minio/minio-xl/pkg/probe"
"github.com/minio/minio/pkg/probe"
)
var (
+3 -4
View File
@@ -22,8 +22,7 @@ import (
"time"
"github.com/minio/cli"
"github.com/minio/mc/pkg/client"
"github.com/minio/minio-xl/pkg/probe"
"github.com/minio/minio/pkg/probe"
)
var (
@@ -101,7 +100,7 @@ func checkShareUploadSyntax(ctx *cli.Context) {
}
for _, targetURL := range ctx.Args() {
url := client.NewURL(targetURL)
url := newClientURL(targetURL)
if strings.HasSuffix(targetURL, string(url.Separator)) && !isRecursive {
fatalIf(errInvalidArgument().Trace(targetURL),
"Use --recursive option to generate curl command for prefixes.")
@@ -111,7 +110,7 @@ func checkShareUploadSyntax(ctx *cli.Context) {
// makeCurlCmd constructs curl command-line.
func makeCurlCmd(key string, isRecursive bool, uploadInfo map[string]string) string {
URL := client.NewURL(key)
URL := newClientURL(key)
postURL := URL.Scheme + URL.SchemeSeparator + URL.Host + string(URL.Separator)
if !isBucketVirtualStyle(URL.Host) {
postURL = postURL + uploadInfo["bucket"]
+1 -1
View File
@@ -28,7 +28,7 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/console"
"github.com/minio/minio-xl/pkg/probe"
"github.com/minio/minio/pkg/probe"
)
const (
+3
View File
@@ -38,6 +38,9 @@ func signalTrap(sig ...os.Signal) <-chan bool {
// Wait for the signal.
<-sigCh
// Once signal has been received stop signal Notify handler.
signal.Stop(sigCh)
// Notify the caller.
trapCh <- true
}(trapCh)
+34
View File
@@ -0,0 +1,34 @@
#!/bin/bash
# Testing mc cat
# 1. Pass a variable as stdin
# 2. Assert result returned by mc cat is the same
# 3. Repeat the same for mc pipe with no arguments
# 4. Take a random string to test for non existant files
dummy_string="asdasd"
cat_result=`mc cat <<< $dummy_string`
if [ "$cat_result" == "$dummy_string" ]; then
echo "mc cat STDIN Test Passed"
else
echo "mc cat STDIN Test Failed"
fi
pipe_result=`mc pipe <<< $dummy_string`
if [ "$pipe_result" == "$dummy_string" ]; then
echo "mc pipe STDIN Test Passed"
else
echo "mc pipe STDIN Test Failed"
fi
random_string="asd.jasd"
cat_json_result=`mc cat --json $random_string`
if [[ "$cat_json_result" == *"\"status\":\"error\""* ]]
then
echo "mc cat Non-Existent File Test Passed"
else
echo "mc cat Non-Existent File Test Failed"
fi
+32
View File
@@ -0,0 +1,32 @@
#!/bin/bash
# Testing mc config hosts
# 1. Get number of previous hosts
# 2. Add a host
# 3. Assert the increase in number of hosts by one.
# 4. Delete the new host
initial_count=`mc config host list | wc -l`
add_test_result=`mc config --json host add testdisk https://storage.googleapis.com BKIKJAA5BMMU2RHO6IBB V8f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 S3v2`
final_count=`mc config host list | wc -l`
remove_test_result=`mc config host remove testdisk`
if [ "$add_test_result" == "Added ‘testdisk’ successfully." ]; then
echo "mc config host add Test Passed";
else
echo "mc config host add Test Failed";
fi
if [ $((initial_count + 1)) -ne $final_count ]; then
echo "mc config host list Test Failed";
else
echo "mc config host list Test Passed";
fi
if [ "$remove_test_result" == "Removed ‘testdisk’ successfully." ]; then
echo "mc config host remove Test Passed";
else
echo "mc config host remove Test Failed";
fi
+8 -1
View File
@@ -19,7 +19,7 @@ package main
import (
"errors"
"github.com/minio/minio-xl/pkg/probe"
"github.com/minio/minio/pkg/probe"
)
var (
@@ -31,6 +31,10 @@ var (
return probe.NewError(errors.New("Invalid arguments provided, cannot proceed.")).Untrace()
}
errUnrecognizedDiffType = func(diff differType) *probe.Error {
return probe.NewError(errors.New("Unrecognized diffType: " + diff.String() + " provided.")).Untrace()
}
errInvalidAliasedURL = func(URL string) *probe.Error {
return probe.NewError(errors.New("Use ‘mc config host add mycloud " + URL + " ...’ to add an alias. Use the alias for S3 operations.")).Untrace()
}
@@ -51,6 +55,9 @@ var (
return probe.NewError(errors.New("Overwrite not allowed for ‘" + URL + "’. Use ‘--force’ to override this behavior."))
}
errDeleteNotAllowed = func(URL string) *probe.Error {
return probe.NewError(errors.New("Delete not allowed for ‘" + URL + "’. Use ‘--force’ to override this behavior."))
}
errSourceIsDir = func(URL string) *probe.Error {
return probe.NewError(errors.New("Source ‘" + URL + "’ is a folder.")).Untrace()
}
+26 -12
View File
@@ -28,7 +28,7 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/console"
"github.com/minio/minio-xl/pkg/probe"
"github.com/minio/minio/pkg/probe"
)
// command specific flags.
@@ -121,8 +121,9 @@ func parseReleaseData(data string) (time.Time, *probe.Error) {
if releaseDateSplits[0] != "mc" {
return time.Time{}, probe.NewError(errors.New("Update data malformed, missing mc tag"))
}
if releaseDateSplits[1] != "OFFICIAL" {
return time.Time{}, probe.NewError(errors.New("Update data malformed, missing OFFICIAL tag"))
// "OFFICIAL" tag is still kept for backward compatibility, we should remove this for the next release.
if releaseDateSplits[1] != "RELEASE" && releaseDateSplits[1] != "OFFICIAL" {
return time.Time{}, probe.NewError(errors.New("Update data malformed, missing RELEASE tag"))
}
dateSplits := strings.SplitN(releaseDateSplits[2], "T", 2)
if len(dateSplits) < 2 {
@@ -140,11 +141,30 @@ func parseReleaseData(data string) (time.Time, *probe.Error) {
// verify updates for releases.
func getReleaseUpdate(updateURL string) {
newUpdateURL := updateURL + "/" + runtime.GOOS + "-" + runtime.GOARCH + "/mc.shasum"
data, e := http.Get(newUpdateURL)
// Construct a new update url.
newUpdateURLPrefix := updateURL + "/" + runtime.GOOS + "-" + runtime.GOARCH
newUpdateURL := newUpdateURLPrefix + "/mc.shasum"
// Instantiate a new client with 3 sec timeout.
client := &http.Client{
Timeout: 3000 * time.Millisecond,
}
// Get the downloadURL.
var downloadURL string
switch runtime.GOOS {
case "windows":
// For windows and darwin.
downloadURL = newUpdateURLPrefix + "/mc.exe"
default:
// For all other operating systems.
downloadURL = newUpdateURLPrefix + "/mc"
}
data, e := client.Get(newUpdateURL)
fatalIf(probe.NewError(e), "Unable to read from update URL ‘"+newUpdateURL+"’.")
if mcVersion == "UNOFFICIAL.GOGET" {
if strings.HasPrefix(mcVersion, "DEVELOPMENT.GOGET") {
fatalIf(errDummy().Trace(newUpdateURL),
"Update mechanism is not supported for ‘go get’ based binary builds. Please download official releases from https://minio.io/#minio")
}
@@ -168,12 +188,6 @@ func getReleaseUpdate(updateURL string) {
"Unable to validate any update available at this time. Please open an issue at https://github.com/minio/mc/issues")
}
var downloadURL string
if runtime.GOOS == "windows" {
downloadURL = updateURL + "/" + runtime.GOOS + "-" + runtime.GOARCH + "/mc.exe"
} else {
downloadURL = updateURL + "/" + runtime.GOOS + "-" + runtime.GOARCH + "/mc"
}
updateMsg := updateMessage{
Download: downloadURL,
Version: mcVersion,
-102
View File
@@ -1,102 +0,0 @@
/*
* Minio Client (C) 2015 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package main
import (
"path/filepath"
"strings"
"github.com/minio/mc/pkg/client"
"github.com/minio/minio-xl/pkg/probe"
"github.com/minio/minio/pkg/contentdb"
)
func isURLVirtualHostStyle(hostURL string) bool {
matchS3, _ := filepath.Match("*.s3*.amazonaws.com", hostURL)
matchGoogle, _ := filepath.Match("*.storage.googleapis.com", hostURL)
return matchS3 || matchGoogle
}
// urlJoinPath Join a path to existing URL.
func urlJoinPath(url1, url2 string) string {
u1 := client.NewURL(url1)
u2 := client.NewURL(url2)
return client.JoinURLs(u1, u2).String()
}
// url2Stat returns stat info for URL.
func url2Stat(urlStr string) (client client.Client, content *client.Content, err *probe.Error) {
client, err = newClient(urlStr)
if err != nil {
return nil, nil, err.Trace(urlStr)
}
content, err = client.Stat()
if err != nil {
return nil, nil, err.Trace(urlStr)
}
return client, content, nil
}
// url2Alias separates alias and path from the URL. Aliased URL is of
// the form [/]alias/path/to/blah.
func url2Alias(aliasedURL string) (alias, path string) {
// Save aliased url.
urlStr := aliasedURL
// Convert '/' on windows to filepath.Separator.
urlStr = filepath.FromSlash(urlStr)
// Remove '/' prefix before alias, if any.
urlStr = strings.TrimPrefix(urlStr, string(filepath.Separator))
// Remove everything after alias (i.e. after '/').
urlParts := strings.SplitN(urlStr, string(filepath.Separator), 2)
if len(urlParts) == 2 {
// Convert windows style path separator to Unix style.
return urlParts[0], urlParts[1]
}
return urlParts[0], ""
}
// isURLPrefixExists - check if object key prefix exists.
func isURLPrefixExists(urlPrefix string, incomplete bool) bool {
clnt, err := newClient(urlPrefix)
if err != nil {
return false
}
isRecursive := true
isIncomplete := incomplete
for entry := range clnt.List(isRecursive, isIncomplete) {
if entry.Err != nil {
return false
}
return true
}
return false
}
// guessURLContentType - guess content-type of the URL.
// on failure just return 'application/octet-stream'.
func guessURLContentType(urlStr string) string {
url := client.NewURL(urlStr)
extension := strings.TrimPrefix(filepath.Ext(url.Path), ".")
contentType, e := contentdb.Lookup(extension)
if e != nil {
return "application/octet-stream"
}
return contentType
}
+1 -1
View File
@@ -143,7 +143,7 @@ c.Println("This prints again cyan...")
## Credits
* [Fatih Arslan](https://github.com/fatih)
* Windows support via @shiena: [ansicolor](https://github.com/shiena/ansicolor)
* Windows support via @mattn: [colorable](https://github.com/mattn/go-colorable)
## License
+51 -2
View File
@@ -6,8 +6,8 @@ import (
"strconv"
"strings"
"github.com/mattn/go-colorable"
"github.com/mattn/go-isatty"
"github.com/shiena/ansicolor"
)
// NoColor defines if the output is colorized or not. It's dynamically set to
@@ -53,6 +53,18 @@ const (
FgWhite
)
// Foreground Hi-Intensity text colors
const (
FgHiBlack Attribute = iota + 90
FgHiRed
FgHiGreen
FgHiYellow
FgHiBlue
FgHiMagenta
FgHiCyan
FgHiWhite
)
// Background text colors
const (
BgBlack Attribute = iota + 40
@@ -65,6 +77,18 @@ const (
BgWhite
)
// Background Hi-Intensity text colors
const (
BgHiBlack Attribute = iota + 100
BgHiRed
BgHiGreen
BgHiYellow
BgHiBlue
BgHiMagenta
BgHiCyan
BgHiWhite
)
// New returns a newly created color object.
func New(value ...Attribute) *Color {
c := &Color{params: make([]Attribute, 0)}
@@ -123,7 +147,7 @@ func (c *Color) prepend(value Attribute) {
// Output defines the standard output of the print functions. By default
// os.Stdout is used.
var Output = ansicolor.NewAnsiColorWriter(os.Stdout)
var Output = colorable.NewColorableStdout()
// Print formats using the default formats for its operands and writes to
// standard output. Spaces are added between operands when neither is a
@@ -259,6 +283,31 @@ func (c *Color) isNoColorSet() bool {
return NoColor
}
// Equals returns a boolean value indicating whether two colors are equal.
func (c *Color) Equals(c2 *Color) bool {
if len(c.params) != len(c2.params) {
return false
}
for _, attr := range c.params {
if !c2.attrExists(attr) {
return false
}
}
return true
}
func (c *Color) attrExists(a Attribute) bool {
for _, attr := range c.params {
if attr == a {
return true
}
}
return false
}
func boolPtr(v bool) *bool {
return &v
}
+54 -4
View File
@@ -3,10 +3,9 @@ package color
import (
"bytes"
"fmt"
"os"
"testing"
"github.com/shiena/ansicolor"
"github.com/mattn/go-colorable"
)
// Testing colors is kinda different. First we test for given colors and their
@@ -16,6 +15,8 @@ func TestColor(t *testing.T) {
rb := new(bytes.Buffer)
Output = rb
NoColor = false
testColors := []struct {
text string
code Attribute
@@ -28,6 +29,14 @@ func TestColor(t *testing.T) {
{text: "magent", code: FgMagenta},
{text: "cyan", code: FgCyan},
{text: "white", code: FgWhite},
{text: "hblack", code: FgHiBlack},
{text: "hred", code: FgHiRed},
{text: "hgreen", code: FgHiGreen},
{text: "hyellow", code: FgHiYellow},
{text: "hblue", code: FgHiBlue},
{text: "hmagent", code: FgHiMagenta},
{text: "hcyan", code: FgHiCyan},
{text: "hwhite", code: FgHiWhite},
}
for _, c := range testColors {
@@ -46,6 +55,40 @@ func TestColor(t *testing.T) {
}
}
func TestColorEquals(t *testing.T) {
fgblack1 := New(FgBlack)
fgblack2 := New(FgBlack)
bgblack := New(BgBlack)
fgbgblack := New(FgBlack, BgBlack)
fgblackbgred := New(FgBlack, BgRed)
fgred := New(FgRed)
bgred := New(BgRed)
if !fgblack1.Equals(fgblack2) {
t.Error("Two black colors are not equal")
}
if fgblack1.Equals(bgblack) {
t.Error("Fg and bg black colors are equal")
}
if fgblack1.Equals(fgbgblack) {
t.Error("Fg black equals fg/bg black color")
}
if fgblack1.Equals(fgred) {
t.Error("Fg black equals Fg red")
}
if fgblack1.Equals(bgred) {
t.Error("Fg black equals Bg red")
}
if fgblack1.Equals(fgblackbgred) {
t.Error("Fg black equals fg black bg red")
}
}
func TestNoColor(t *testing.T) {
rb := new(bytes.Buffer)
Output = rb
@@ -62,6 +105,14 @@ func TestNoColor(t *testing.T) {
{text: "magent", code: FgMagenta},
{text: "cyan", code: FgCyan},
{text: "white", code: FgWhite},
{text: "hblack", code: FgHiBlack},
{text: "hred", code: FgHiRed},
{text: "hgreen", code: FgHiGreen},
{text: "hyellow", code: FgHiYellow},
{text: "hblue", code: FgHiBlue},
{text: "hmagent", code: FgHiMagenta},
{text: "hcyan", code: FgHiCyan},
{text: "hwhite", code: FgHiWhite},
}
for _, c := range testColors {
@@ -94,8 +145,7 @@ func TestNoColor(t *testing.T) {
func TestColorVisual(t *testing.T) {
// First Visual Test
fmt.Println("")
Output = ansicolor.NewAnsiColorWriter(os.Stdout)
Output = colorable.NewColorableStdout()
New(FgRed).Printf("red\t")
New(BgRed).Print(" ")
+354
View File
@@ -0,0 +1,354 @@
Mozilla Public License, version 2.0
1. Definitions
1.1. “Contributor”
means each individual or legal entity that creates, contributes to the
creation of, or owns Covered Software.
1.2. “Contributor Version”
means the combination of the Contributions of others (if any) used by a
Contributor and that particular Contributor’s Contribution.
1.3. “Contribution”
means Covered Software of a particular Contributor.
1.4. “Covered Software”
means Source Code Form to which the initial Contributor has attached the
notice in Exhibit A, the Executable Form of such Source Code Form, and
Modifications of such Source Code Form, in each case including portions
thereof.
1.5. “Incompatible With Secondary Licenses”
means
a. that the initial Contributor has attached the notice described in
Exhibit B to the Covered Software; or
b. that the Covered Software was made available under the terms of version
1.1 or earlier of the License, but not also under the terms of a
Secondary License.
1.6. “Executable Form”
means any form of the work other than Source Code Form.
1.7. “Larger Work”
means a work that combines Covered Software with other material, in a separate
file or files, that is not Covered Software.
1.8. “License”
means this document.
1.9. “Licensable”
means having the right to grant, to the maximum extent possible, whether at the
time of the initial grant or subsequently, any and all of the rights conveyed by
this License.
1.10. “Modifications”
means any of the following:
a. any file in Source Code Form that results from an addition to, deletion
from, or modification of the contents of Covered Software; or
b. any new file in Source Code Form that contains any Covered Software.
1.11. “Patent Claims” of a Contributor
means any patent claim(s), including without limitation, method, process,
and apparatus claims, in any patent Licensable by such Contributor that
would be infringed, but for the grant of the License, by the making,
using, selling, offering for sale, having made, import, or transfer of
either its Contributions or its Contributor Version.
1.12. “Secondary License”
means either the GNU General Public License, Version 2.0, the GNU Lesser
General Public License, Version 2.1, the GNU Affero General Public
License, Version 3.0, or any later versions of those licenses.
1.13. “Source Code Form”
means the form of the work preferred for making modifications.
1.14. “You” (or “Your”)
means an individual or a legal entity exercising rights under this
License. For legal entities, “You” includes any entity that controls, is
controlled by, or is under common control with You. For purposes of this
definition, “control” means (a) the power, direct or indirect, to cause
the direction or management of such entity, whether by contract or
otherwise, or (b) ownership of more than fifty percent (50%) of the
outstanding shares or beneficial ownership of such entity.
2. License Grants and Conditions
2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
a. under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or as
part of a Larger Work; and
b. under Patent Claims of such Contributor to make, use, sell, offer for
sale, have made, import, and otherwise transfer either its Contributions
or its Contributor Version.
2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contribution become
effective for each Contribution on the date the Contributor first distributes
such Contribution.
2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted under this
License. No additional rights or licenses will be implied from the distribution
or licensing of Covered Software under this License. Notwithstanding Section
2.1(b) above, no patent license is granted by a Contributor:
a. for any code that a Contributor has removed from Covered Software; or
b. for infringements caused by: (i) Your and any other third party’s
modifications of Covered Software, or (ii) the combination of its
Contributions with other software (except as part of its Contributor
Version); or
c. under Patent Claims infringed by Covered Software in the absence of its
Contributions.
This License does not grant any rights in the trademarks, service marks, or
logos of any Contributor (except as may be necessary to comply with the
notice requirements in Section 3.4).
2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this License
(see Section 10.2) or under the terms of a Secondary License (if permitted
under the terms of Section 3.3).
2.5. Representation
Each Contributor represents that the Contributor believes its Contributions
are its original creation(s) or it has sufficient rights to grant the
rights to its Contributions conveyed by this License.
2.6. Fair Use
This License is not intended to limit any rights You have under applicable
copyright doctrines of fair use, fair dealing, or other equivalents.
2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in
Section 2.1.
3. Responsibilities
3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under the
terms of this License. You must inform recipients that the Source Code Form
of the Covered Software is governed by the terms of this License, and how
they can obtain a copy of this License. You may not attempt to alter or
restrict the recipients’ rights in the Source Code Form.
3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
a. such Covered Software must also be made available in Source Code Form,
as described in Section 3.1, and You must inform recipients of the
Executable Form how they can obtain a copy of such Source Code Form by
reasonable means in a timely manner, at a charge no more than the cost
of distribution to the recipient; and
b. You may distribute such Executable Form under the terms of this License,
or sublicense it under different terms, provided that the license for
the Executable Form does not attempt to limit or alter the recipients’
rights in the Source Code Form under this License.
3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for the
Covered Software. If the Larger Work is a combination of Covered Software
with a work governed by one or more Secondary Licenses, and the Covered
Software is not Incompatible With Secondary Licenses, this License permits
You to additionally distribute such Covered Software under the terms of
such Secondary License(s), so that the recipient of the Larger Work may, at
their option, further distribute the Covered Software under the terms of
either this License or such Secondary License(s).
3.4. Notices
You may not remove or alter the substance of any license notices (including
copyright notices, patent notices, disclaimers of warranty, or limitations
of liability) contained within the Source Code Form of the Covered
Software, except that You may alter any license notices to the extent
required to remedy known factual inaccuracies.
3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on behalf
of any Contributor. You must make it absolutely clear that any such
warranty, support, indemnity, or liability obligation is offered by You
alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.
4. Inability to Comply Due to Statute or Regulation
If it is impossible for You to comply with any of the terms of this License
with respect to some or all of the Covered Software due to statute, judicial
order, or regulation then You must: (a) comply with the terms of this License
to the maximum extent possible; and (b) describe the limitations and the code
they affect. Such description must be placed in a text file included with all
distributions of the Covered Software under this License. Except to the
extent prohibited by statute or regulation, such description must be
sufficiently detailed for a recipient of ordinary skill to be able to
understand it.
5. Termination
5.1. The rights granted under this License will terminate automatically if You
fail to comply with any of its terms. However, if You become compliant,
then the rights granted under this License from a particular Contributor
are reinstated (a) provisionally, unless and until such Contributor
explicitly and finally terminates Your grants, and (b) on an ongoing basis,
if such Contributor fails to notify You of the non-compliance by some
reasonable means prior to 60 days after You have come back into compliance.
Moreover, Your grants from a particular Contributor are reinstated on an
ongoing basis if such Contributor notifies You of the non-compliance by
some reasonable means, this is the first time You have received notice of
non-compliance with this License from such Contributor, and You become
compliant prior to 30 days after Your receipt of the notice.
5.2. If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions, counter-claims,
and cross-claims) alleging that a Contributor Version directly or
indirectly infringes any patent, then the rights granted to You by any and
all Contributors for the Covered Software under Section 2.1 of this License
shall terminate.
5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user
license agreements (excluding distributors and resellers) which have been
validly granted by You or Your distributors under this License prior to
termination shall survive termination.
6. Disclaimer of Warranty
Covered Software is provided under this License on an “as is” basis, without
warranty of any kind, either expressed, implied, or statutory, including,
without limitation, warranties that the Covered Software is free of defects,
merchantable, fit for a particular purpose or non-infringing. The entire
risk as to the quality and performance of the Covered Software is with You.
Should any Covered Software prove defective in any respect, You (not any
Contributor) assume the cost of any necessary servicing, repair, or
correction. This disclaimer of warranty constitutes an essential part of this
License. No use of any Covered Software is authorized under this License
except under this disclaimer.
7. Limitation of Liability
Under no circumstances and under no legal theory, whether tort (including
negligence), contract, or otherwise, shall any Contributor, or anyone who
distributes Covered Software as permitted above, be liable to You for any
direct, indirect, special, incidental, or consequential damages of any
character including, without limitation, damages for lost profits, loss of
goodwill, work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses, even if such party shall have been
informed of the possibility of such damages. This limitation of liability
shall not apply to liability for death or personal injury resulting from such
party’s negligence to the extent applicable law prohibits such limitation.
Some jurisdictions do not allow the exclusion or limitation of incidental or
consequential damages, so this exclusion and limitation may not apply to You.
8. Litigation
Any litigation relating to this License may be brought only in the courts of
a jurisdiction where the defendant maintains its principal place of business
and such litigation shall be governed by laws of that jurisdiction, without
reference to its conflict-of-law provisions. Nothing in this Section shall
prevent a party’s ability to bring cross-claims or counter-claims.
9. Miscellaneous
This License represents the complete agreement concerning the subject matter
hereof. If any provision of this License is held to be unenforceable, such
provision shall be reformed only to the extent necessary to make it
enforceable. Any law or regulation which provides that the language of a
contract shall be construed against the drafter shall not be used to construe
this License against a Contributor.
10. Versions of the License
10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version of
the License under which You originally received the Covered Software, or
under the terms of any subsequent version published by the license
steward.
10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a modified
version of this License if you rename the license and remove any
references to the name of the license steward (except to note that such
modified license differs from this License).
10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses
If You choose to distribute Source Code Form that is Incompatible With
Secondary Licenses under the terms of this version of the License, the
notice described in Exhibit B of this License must be attached.
Exhibit A - Source Code Form License Notice
This Source Code Form is subject to the
terms of the Mozilla Public License, v.
2.0. If a copy of the MPL was not
distributed with this file, You can
obtain one at
http://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular file, then
You may include the notice in a location (such as a LICENSE file in a relevant
directory) where a recipient would be likely to look for such a notice.
You may add additional accurate notices of copyright ownership.
Exhibit B - “Incompatible With Secondary Licenses” Notice
This Source Code Form is “Incompatible
With Secondary Licenses”, as defined by
the Mozilla Public License, v. 2.0.
+65
View File
@@ -0,0 +1,65 @@
# Versioning Library for Go
[![Build Status](https://travis-ci.org/hashicorp/go-version.svg?branch=master)](https://travis-ci.org/hashicorp/go-version)
go-version is a library for parsing versions and version constraints,
and verifying versions against a set of constraints. go-version
can sort a collection of versions properly, handles prerelease/beta
versions, can increment versions, etc.
Versions used with go-version must follow [SemVer](http://semver.org/).
## Installation and Usage
Package documentation can be found on
[GoDoc](http://godoc.org/github.com/hashicorp/go-version).
Installation can be done with a normal `go get`:
```
$ go get github.com/hashicorp/go-version
```
#### Version Parsing and Comparison
```go
v1, err := version.NewVersion("1.2")
v2, err := version.NewVersion("1.5+metadata")
// Comparison example. There is also GreaterThan, Equal, and just
// a simple Compare that returns an int allowing easy >=, <=, etc.
if v1.LessThan(v2) {
fmt.Printf("%s is less than %s", v1, v2)
}
```
#### Version Constraints
```go
v1, err := version.NewVersion("1.2")
// Constraints example.
constraints, err := version.NewConstraint(">= 1.0, < 1.4")
if constraints.Check(v1) {
fmt.Printf("%s satisfies constraints %s", v1, constraints)
}
```
#### Version Sorting
```go
versionsRaw := []string{"1.1", "0.7.1", "1.4-beta", "1.4", "2"}
versions := make([]*version.Version, len(versionsRaw))
for i, raw := range versionsRaw {
v, _ := version.NewVersion(raw)
versions[i] = v
}
// After this, the versions are properly sorted
sort.Sort(version.Collection(versions))
```
## Issues and Contributing
If you find an issue with this library, please report an issue. If you'd
like, we welcome any contributions. Fork this library and submit a pull
request.
+156
View File
@@ -0,0 +1,156 @@
package version
import (
"fmt"
"regexp"
"strings"
)
// Constraint represents a single constraint for a version, such as
// ">= 1.0".
type Constraint struct {
f constraintFunc
check *Version
original string
}
// Constraints is a slice of constraints. We make a custom type so that
// we can add methods to it.
type Constraints []*Constraint
type constraintFunc func(v, c *Version) bool
var constraintOperators map[string]constraintFunc
var constraintRegexp *regexp.Regexp
func init() {
constraintOperators = map[string]constraintFunc{
"": constraintEqual,
"=": constraintEqual,
"!=": constraintNotEqual,
">": constraintGreaterThan,
"<": constraintLessThan,
">=": constraintGreaterThanEqual,
"<=": constraintLessThanEqual,
"~>": constraintPessimistic,
}
ops := make([]string, 0, len(constraintOperators))
for k, _ := range constraintOperators {
ops = append(ops, regexp.QuoteMeta(k))
}
constraintRegexp = regexp.MustCompile(fmt.Sprintf(
`^\s*(%s)\s*(%s)\s*$`,
strings.Join(ops, "|"),
VersionRegexpRaw))
}
// NewConstraint will parse one or more constraints from the given
// constraint string. The string must be a comma-separated list of
// constraints.
func NewConstraint(v string) (Constraints, error) {
vs := strings.Split(v, ",")
result := make([]*Constraint, len(vs))
for i, single := range vs {
c, err := parseSingle(single)
if err != nil {
return nil, err
}
result[i] = c
}
return Constraints(result), nil
}
// Check tests if a version satisfies all the constraints.
func (cs Constraints) Check(v *Version) bool {
for _, c := range cs {
if !c.Check(v) {
return false
}
}
return true
}
// Returns the string format of the constraints
func (cs Constraints) String() string {
csStr := make([]string, len(cs))
for i, c := range cs {
csStr[i] = c.String()
}
return strings.Join(csStr, ",")
}
// Check tests if a constraint is validated by the given version.
func (c *Constraint) Check(v *Version) bool {
return c.f(v, c.check)
}
func (c *Constraint) String() string {
return c.original
}
func parseSingle(v string) (*Constraint, error) {
matches := constraintRegexp.FindStringSubmatch(v)
if matches == nil {
return nil, fmt.Errorf("Malformed constraint: %s", v)
}
check, err := NewVersion(matches[2])
if err != nil {
return nil, err
}
return &Constraint{
f: constraintOperators[matches[1]],
check: check,
original: v,
}, nil
}
//-------------------------------------------------------------------
// Constraint functions
//-------------------------------------------------------------------
func constraintEqual(v, c *Version) bool {
return v.Equal(c)
}
func constraintNotEqual(v, c *Version) bool {
return !v.Equal(c)
}
func constraintGreaterThan(v, c *Version) bool {
return v.Compare(c) == 1
}
func constraintLessThan(v, c *Version) bool {
return v.Compare(c) == -1
}
func constraintGreaterThanEqual(v, c *Version) bool {
return v.Compare(c) >= 0
}
func constraintLessThanEqual(v, c *Version) bool {
return v.Compare(c) <= 0
}
func constraintPessimistic(v, c *Version) bool {
if v.LessThan(c) {
return false
}
for i := 0; i < c.si-1; i++ {
if v.segments[i] != c.segments[i] {
return false
}
}
return true
}
+251
View File
@@ -0,0 +1,251 @@
package version
import (
"bytes"
"fmt"
"reflect"
"regexp"
"strconv"
"strings"
)
// The compiled regular expression used to test the validity of a version.
var versionRegexp *regexp.Regexp
// The raw regular expression string used for testing the validity
// of a version.
const VersionRegexpRaw string = `v?([0-9]+(\.[0-9]+){0,2})` +
`(-([0-9A-Za-z\-]+(\.[0-9A-Za-z\-]+)*))?` +
`(\+([0-9A-Za-z\-]+(\.[0-9A-Za-z\-]+)*))?` +
`?`
// Version represents a single version.
type Version struct {
metadata string
pre string
segments []int
si int
}
func init() {
versionRegexp = regexp.MustCompile("^" + VersionRegexpRaw + "$")
}
// NewVersion parses the given version and returns a new
// Version.
func NewVersion(v string) (*Version, error) {
matches := versionRegexp.FindStringSubmatch(v)
if matches == nil {
return nil, fmt.Errorf("Malformed version: %s", v)
}
segmentsStr := strings.Split(matches[1], ".")
segments := make([]int, len(segmentsStr), 3)
si := 0
for i, str := range segmentsStr {
val, err := strconv.ParseInt(str, 10, 32)
if err != nil {
return nil, fmt.Errorf(
"Error parsing version: %s", err)
}
segments[i] = int(val)
si += 1
}
for i := len(segments); i < 3; i++ {
segments = append(segments, 0)
}
return &Version{
metadata: matches[7],
pre: matches[4],
segments: segments,
si: si,
}, nil
}
// Must is a helper that wraps a call to a function returning (*Version, error)
// and panics if error is non-nil.
func Must(v *Version, err error) *Version {
if err != nil {
panic(err)
}
return v
}
// Compare compares this version to another version. This
// returns -1, 0, or 1 if this version is smaller, equal,
// or larger than the other version, respectively.
//
// If you want boolean results, use the LessThan, Equal,
// or GreaterThan methods.
func (v *Version) Compare(other *Version) int {
// A quick, efficient equality check
if v.String() == other.String() {
return 0
}
segmentsSelf := v.Segments()
segmentsOther := other.Segments()
// If the segments are the same, we must compare on prerelease info
if reflect.DeepEqual(segmentsSelf, segmentsOther) {
preSelf := v.Prerelease()
preOther := other.Prerelease()
if preSelf == "" && preOther == "" {
return 0
}
if preSelf == "" {
return 1
}
if preOther == "" {
return -1
}
return comparePrereleases(preSelf, preOther)
}
// Compare the segments
for i := 0; i < len(segmentsSelf); i++ {
lhs := segmentsSelf[i]
rhs := segmentsOther[i]
if lhs == rhs {
continue
} else if lhs < rhs {
return -1
} else {
return 1
}
}
panic("should not be reached")
}
func comparePart(preSelf string, preOther string) int {
if preSelf == preOther {
return 0
}
// if a part is empty, we use the other to decide
if preSelf == "" {
_, notIsNumeric := strconv.ParseInt(preOther, 10, 64)
if notIsNumeric == nil {
return -1
}
return 1
}
if preOther == "" {
_, notIsNumeric := strconv.ParseInt(preSelf, 10, 64)
if notIsNumeric == nil {
return 1
}
return -1
}
if preSelf > preOther {
return 1
}
return -1
}
func comparePrereleases(v string, other string) int {
// the same pre release!
if v == other {
return 0
}
// split both pre releases for analyse their parts
selfPreReleaseMeta := strings.Split(v, ".")
otherPreReleaseMeta := strings.Split(other, ".")
selfPreReleaseLen := len(selfPreReleaseMeta)
otherPreReleaseLen := len(otherPreReleaseMeta)
biggestLen := otherPreReleaseLen
if selfPreReleaseLen > otherPreReleaseLen {
biggestLen = selfPreReleaseLen
}
// loop for parts to find the first difference
for i := 0; i < biggestLen; i = i + 1 {
partSelfPre := ""
if i < selfPreReleaseLen {
partSelfPre = selfPreReleaseMeta[i]
}
partOtherPre := ""
if i < otherPreReleaseLen {
partOtherPre = otherPreReleaseMeta[i]
}
compare := comparePart(partSelfPre, partOtherPre)
// if parts are equals, continue the loop
if compare != 0 {
return compare
}
}
return 0
}
// Equal tests if two versions are equal.
func (v *Version) Equal(o *Version) bool {
return v.Compare(o) == 0
}
// GreaterThan tests if this version is greater than another version.
func (v *Version) GreaterThan(o *Version) bool {
return v.Compare(o) > 0
}
// LessThan tests if this version is less than another version.
func (v *Version) LessThan(o *Version) bool {
return v.Compare(o) < 0
}
// Metadata returns any metadata that was part of the version
// string.
//
// Metadata is anything that comes after the "+" in the version.
// For example, with "1.2.3+beta", the metadata is "beta".
func (v *Version) Metadata() string {
return v.metadata
}
// Prerelease returns any prerelease data that is part of the version,
// or blank if there is no prerelease data.
//
// Prerelease information is anything that comes after the "-" in the
// version (but before any metadata). For example, with "1.2.3-beta",
// the prerelease information is "beta".
func (v *Version) Prerelease() string {
return v.pre
}
// Segments returns the numeric segments of the version as a slice.
//
// This excludes any metadata or pre-release information. For example,
// for a version "1.2.3-beta", segments will return a slice of
// 1, 2, 3.
func (v *Version) Segments() []int {
return v.segments
}
// String returns the full version string included pre-release
// and metadata information.
func (v *Version) String() string {
var buf bytes.Buffer
fmt.Fprintf(&buf, "%d.%d.%d", v.segments[0], v.segments[1], v.segments[2])
if v.pre != "" {
fmt.Fprintf(&buf, "-%s", v.pre)
}
if v.metadata != "" {
fmt.Fprintf(&buf, "+%s", v.metadata)
}
return buf.String()
}
+17
View File
@@ -0,0 +1,17 @@
package version
// Collection is a type that implements the sort.Interface interface
// so that versions can be sorted.
type Collection []*Version
func (v Collection) Len() int {
return len(v)
}
func (v Collection) Less(i, j int) bool {
return v[i].LessThan(v[j])
}
func (v Collection) Swap(i, j int) {
v[i], v[j] = v[j], v[i]
}
@@ -1,6 +1,6 @@
The MIT License (MIT)
Copyright (c) [2014] [shiena]
Copyright (c) 2016 Yasuhiro Matsumoto
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
+43
View File
@@ -0,0 +1,43 @@
# go-colorable
Colorable writer for windows.
For example, most of logger packages doesn't show colors on windows. (I know we can do it with ansicon. But I don't want.)
This package is possible to handle escape sequence for ansi color on windows.
## Too Bad!
![](https://raw.githubusercontent.com/mattn/go-colorable/gh-pages/bad.png)
## So Good!
![](https://raw.githubusercontent.com/mattn/go-colorable/gh-pages/good.png)
## Usage
```go
logrus.SetFormatter(&logrus.TextFormatter{ForceColors: true})
logrus.SetOutput(colorable.NewColorableStdout())
logrus.Info("succeeded")
logrus.Warn("not correct")
logrus.Error("something error")
logrus.Fatal("panic")
```
You can compile above code on non-windows OSs.
## Installation
```
$ go get github.com/mattn/go-colorable
```
# License
MIT
# Author
Yasuhiro Matsumoto (a.k.a mattn)
+16
View File
@@ -0,0 +1,16 @@
// +build !windows
package colorable
import (
"io"
"os"
)
func NewColorableStdout() io.Writer {
return os.Stdout
}
func NewColorableStderr() io.Writer {
return os.Stderr
}
+782
View File
@@ -0,0 +1,782 @@
package colorable
import (
"bytes"
"fmt"
"io"
"math"
"os"
"strconv"
"strings"
"syscall"
"unsafe"
"github.com/mattn/go-isatty"
)
const (
foregroundBlue = 0x1
foregroundGreen = 0x2
foregroundRed = 0x4
foregroundIntensity = 0x8
foregroundMask = (foregroundRed | foregroundBlue | foregroundGreen | foregroundIntensity)
backgroundBlue = 0x10
backgroundGreen = 0x20
backgroundRed = 0x40
backgroundIntensity = 0x80
backgroundMask = (backgroundRed | backgroundBlue | backgroundGreen | backgroundIntensity)
)
type wchar uint16
type short int16
type dword uint32
type word uint16
type coord struct {
x short
y short
}
type smallRect struct {
left short
top short
right short
bottom short
}
type consoleScreenBufferInfo struct {
size coord
cursorPosition coord
attributes word
window smallRect
maximumWindowSize coord
}
var (
kernel32 = syscall.NewLazyDLL("kernel32.dll")
procGetConsoleScreenBufferInfo = kernel32.NewProc("GetConsoleScreenBufferInfo")
procSetConsoleTextAttribute = kernel32.NewProc("SetConsoleTextAttribute")
procSetConsoleCursorPosition = kernel32.NewProc("SetConsoleCursorPosition")
procFillConsoleOutputCharacter = kernel32.NewProc("FillConsoleOutputCharacterW")
procFillConsoleOutputAttribute = kernel32.NewProc("FillConsoleOutputAttribute")
)
type Writer struct {
out io.Writer
handle syscall.Handle
lastbuf bytes.Buffer
oldattr word
}
func NewColorableStdout() io.Writer {
var csbi consoleScreenBufferInfo
out := os.Stdout
if !isatty.IsTerminal(out.Fd()) {
return out
}
handle := syscall.Handle(out.Fd())
procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi)))
return &Writer{out: out, handle: handle, oldattr: csbi.attributes}
}
func NewColorableStderr() io.Writer {
var csbi consoleScreenBufferInfo
out := os.Stderr
if !isatty.IsTerminal(out.Fd()) {
return out
}
handle := syscall.Handle(out.Fd())
procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi)))
return &Writer{out: out, handle: handle, oldattr: csbi.attributes}
}
var color256 = map[int]int{
0: 0x000000,
1: 0x800000,
2: 0x008000,
3: 0x808000,
4: 0x000080,
5: 0x800080,
6: 0x008080,
7: 0xc0c0c0,
8: 0x808080,
9: 0xff0000,
10: 0x00ff00,
11: 0xffff00,
12: 0x0000ff,
13: 0xff00ff,
14: 0x00ffff,
15: 0xffffff,
16: 0x000000,
17: 0x00005f,
18: 0x000087,
19: 0x0000af,
20: 0x0000d7,
21: 0x0000ff,
22: 0x005f00,
23: 0x005f5f,
24: 0x005f87,
25: 0x005faf,
26: 0x005fd7,
27: 0x005fff,
28: 0x008700,
29: 0x00875f,
30: 0x008787,
31: 0x0087af,
32: 0x0087d7,
33: 0x0087ff,
34: 0x00af00,
35: 0x00af5f,
36: 0x00af87,
37: 0x00afaf,
38: 0x00afd7,
39: 0x00afff,
40: 0x00d700,
41: 0x00d75f,
42: 0x00d787,
43: 0x00d7af,
44: 0x00d7d7,
45: 0x00d7ff,
46: 0x00ff00,
47: 0x00ff5f,
48: 0x00ff87,
49: 0x00ffaf,
50: 0x00ffd7,
51: 0x00ffff,
52: 0x5f0000,
53: 0x5f005f,
54: 0x5f0087,
55: 0x5f00af,
56: 0x5f00d7,
57: 0x5f00ff,
58: 0x5f5f00,
59: 0x5f5f5f,
60: 0x5f5f87,
61: 0x5f5faf,
62: 0x5f5fd7,
63: 0x5f5fff,
64: 0x5f8700,
65: 0x5f875f,
66: 0x5f8787,
67: 0x5f87af,
68: 0x5f87d7,
69: 0x5f87ff,
70: 0x5faf00,
71: 0x5faf5f,
72: 0x5faf87,
73: 0x5fafaf,
74: 0x5fafd7,
75: 0x5fafff,
76: 0x5fd700,
77: 0x5fd75f,
78: 0x5fd787,
79: 0x5fd7af,
80: 0x5fd7d7,
81: 0x5fd7ff,
82: 0x5fff00,
83: 0x5fff5f,
84: 0x5fff87,
85: 0x5fffaf,
86: 0x5fffd7,
87: 0x5fffff,
88: 0x870000,
89: 0x87005f,
90: 0x870087,
91: 0x8700af,
92: 0x8700d7,
93: 0x8700ff,
94: 0x875f00,
95: 0x875f5f,
96: 0x875f87,
97: 0x875faf,
98: 0x875fd7,
99: 0x875fff,
100: 0x878700,
101: 0x87875f,
102: 0x878787,
103: 0x8787af,
104: 0x8787d7,
105: 0x8787ff,
106: 0x87af00,
107: 0x87af5f,
108: 0x87af87,
109: 0x87afaf,
110: 0x87afd7,
111: 0x87afff,
112: 0x87d700,
113: 0x87d75f,
114: 0x87d787,
115: 0x87d7af,
116: 0x87d7d7,
117: 0x87d7ff,
118: 0x87ff00,
119: 0x87ff5f,
120: 0x87ff87,
121: 0x87ffaf,
122: 0x87ffd7,
123: 0x87ffff,
124: 0xaf0000,
125: 0xaf005f,
126: 0xaf0087,
127: 0xaf00af,
128: 0xaf00d7,
129: 0xaf00ff,
130: 0xaf5f00,
131: 0xaf5f5f,
132: 0xaf5f87,
133: 0xaf5faf,
134: 0xaf5fd7,
135: 0xaf5fff,
136: 0xaf8700,
137: 0xaf875f,
138: 0xaf8787,
139: 0xaf87af,
140: 0xaf87d7,
141: 0xaf87ff,
142: 0xafaf00,
143: 0xafaf5f,
144: 0xafaf87,
145: 0xafafaf,
146: 0xafafd7,
147: 0xafafff,
148: 0xafd700,
149: 0xafd75f,
150: 0xafd787,
151: 0xafd7af,
152: 0xafd7d7,
153: 0xafd7ff,
154: 0xafff00,
155: 0xafff5f,
156: 0xafff87,
157: 0xafffaf,
158: 0xafffd7,
159: 0xafffff,
160: 0xd70000,
161: 0xd7005f,
162: 0xd70087,
163: 0xd700af,
164: 0xd700d7,
165: 0xd700ff,
166: 0xd75f00,
167: 0xd75f5f,
168: 0xd75f87,
169: 0xd75faf,
170: 0xd75fd7,
171: 0xd75fff,
172: 0xd78700,
173: 0xd7875f,
174: 0xd78787,
175: 0xd787af,
176: 0xd787d7,
177: 0xd787ff,
178: 0xd7af00,
179: 0xd7af5f,
180: 0xd7af87,
181: 0xd7afaf,
182: 0xd7afd7,
183: 0xd7afff,
184: 0xd7d700,
185: 0xd7d75f,
186: 0xd7d787,
187: 0xd7d7af,
188: 0xd7d7d7,
189: 0xd7d7ff,
190: 0xd7ff00,
191: 0xd7ff5f,
192: 0xd7ff87,
193: 0xd7ffaf,
194: 0xd7ffd7,
195: 0xd7ffff,
196: 0xff0000,
197: 0xff005f,
198: 0xff0087,
199: 0xff00af,
200: 0xff00d7,
201: 0xff00ff,
202: 0xff5f00,
203: 0xff5f5f,
204: 0xff5f87,
205: 0xff5faf,
206: 0xff5fd7,
207: 0xff5fff,
208: 0xff8700,
209: 0xff875f,
210: 0xff8787,
211: 0xff87af,
212: 0xff87d7,
213: 0xff87ff,
214: 0xffaf00,
215: 0xffaf5f,
216: 0xffaf87,
217: 0xffafaf,
218: 0xffafd7,
219: 0xffafff,
220: 0xffd700,
221: 0xffd75f,
222: 0xffd787,
223: 0xffd7af,
224: 0xffd7d7,
225: 0xffd7ff,
226: 0xffff00,
227: 0xffff5f,
228: 0xffff87,
229: 0xffffaf,
230: 0xffffd7,
231: 0xffffff,
232: 0x080808,
233: 0x121212,
234: 0x1c1c1c,
235: 0x262626,
236: 0x303030,
237: 0x3a3a3a,
238: 0x444444,
239: 0x4e4e4e,
240: 0x585858,
241: 0x626262,
242: 0x6c6c6c,
243: 0x767676,
244: 0x808080,
245: 0x8a8a8a,
246: 0x949494,
247: 0x9e9e9e,
248: 0xa8a8a8,
249: 0xb2b2b2,
250: 0xbcbcbc,
251: 0xc6c6c6,
252: 0xd0d0d0,
253: 0xdadada,
254: 0xe4e4e4,
255: 0xeeeeee,
}
func (w *Writer) Write(data []byte) (n int, err error) {
var csbi consoleScreenBufferInfo
procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi)))
er := bytes.NewBuffer(data)
loop:
for {
r1, _, err := procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi)))
if r1 == 0 {
break loop
}
c1, _, err := er.ReadRune()
if err != nil {
break loop
}
if c1 != 0x1b {
fmt.Fprint(w.out, string(c1))
continue
}
c2, _, err := er.ReadRune()
if err != nil {
w.lastbuf.WriteRune(c1)
break loop
}
if c2 != 0x5b {
w.lastbuf.WriteRune(c1)
w.lastbuf.WriteRune(c2)
continue
}
var buf bytes.Buffer
var m rune
for {
c, _, err := er.ReadRune()
if err != nil {
w.lastbuf.WriteRune(c1)
w.lastbuf.WriteRune(c2)
w.lastbuf.Write(buf.Bytes())
break loop
}
if ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || c == '@' {
m = c
break
}
buf.Write([]byte(string(c)))
}
var csbi consoleScreenBufferInfo
switch m {
case 'A':
n, err = strconv.Atoi(buf.String())
if err != nil {
continue
}
procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi)))
csbi.cursorPosition.y -= short(n)
procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition)))
case 'B':
n, err = strconv.Atoi(buf.String())
if err != nil {
continue
}
procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi)))
csbi.cursorPosition.y += short(n)
procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition)))
case 'C':
n, err = strconv.Atoi(buf.String())
if err != nil {
continue
}
procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi)))
csbi.cursorPosition.x -= short(n)
procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition)))
case 'D':
n, err = strconv.Atoi(buf.String())
if err != nil {
continue
}
if n, err = strconv.Atoi(buf.String()); err == nil {
var csbi consoleScreenBufferInfo
procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi)))
csbi.cursorPosition.x += short(n)
procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition)))
}
case 'E':
n, err = strconv.Atoi(buf.String())
if err != nil {
continue
}
procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi)))
csbi.cursorPosition.x = 0
csbi.cursorPosition.y += short(n)
procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition)))
case 'F':
n, err = strconv.Atoi(buf.String())
if err != nil {
continue
}
procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi)))
csbi.cursorPosition.x = 0
csbi.cursorPosition.y -= short(n)
procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition)))
case 'G':
n, err = strconv.Atoi(buf.String())
if err != nil {
continue
}
procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi)))
csbi.cursorPosition.x = short(n)
procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition)))
case 'H':
token := strings.Split(buf.String(), ";")
if len(token) != 2 {
continue
}
n1, err := strconv.Atoi(token[0])
if err != nil {
continue
}
n2, err := strconv.Atoi(token[1])
if err != nil {
continue
}
csbi.cursorPosition.x = short(n2)
csbi.cursorPosition.x = short(n1)
procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition)))
case 'J':
n, err := strconv.Atoi(buf.String())
if err != nil {
continue
}
var cursor coord
switch n {
case 0:
cursor = coord{x: csbi.cursorPosition.x, y: csbi.cursorPosition.y}
case 1:
cursor = coord{x: csbi.window.left, y: csbi.window.top}
case 2:
cursor = coord{x: csbi.window.left, y: csbi.window.top}
}
var count, written dword
count = dword(csbi.size.x - csbi.cursorPosition.x + (csbi.size.y-csbi.cursorPosition.y)*csbi.size.x)
procFillConsoleOutputCharacter.Call(uintptr(w.handle), uintptr(' '), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written)))
procFillConsoleOutputAttribute.Call(uintptr(w.handle), uintptr(csbi.attributes), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written)))
case 'K':
n, err := strconv.Atoi(buf.String())
if err != nil {
continue
}
var cursor coord
switch n {
case 0:
cursor = coord{x: csbi.cursorPosition.x, y: csbi.cursorPosition.y}
case 1:
cursor = coord{x: csbi.window.left, y: csbi.window.top + csbi.cursorPosition.y}
case 2:
cursor = coord{x: csbi.window.left, y: csbi.window.top + csbi.cursorPosition.y}
}
var count, written dword
count = dword(csbi.size.x - csbi.cursorPosition.x)
procFillConsoleOutputCharacter.Call(uintptr(w.handle), uintptr(' '), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written)))
procFillConsoleOutputAttribute.Call(uintptr(w.handle), uintptr(csbi.attributes), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written)))
case 'm':
attr := csbi.attributes
cs := buf.String()
if cs == "" {
procSetConsoleTextAttribute.Call(uintptr(w.handle), uintptr(w.oldattr))
continue
}
token := strings.Split(cs, ";")
for i := 0; i < len(token); i += 1 {
ns := token[i]
if n, err = strconv.Atoi(ns); err == nil {
switch {
case n == 0 || n == 100:
attr = w.oldattr
case 1 <= n && n <= 5:
attr |= foregroundIntensity
case n == 7:
attr = ((attr & foregroundMask) << 4) | ((attr & backgroundMask) >> 4)
case 22 == n || n == 25 || n == 25:
attr |= foregroundIntensity
case n == 27:
attr = ((attr & foregroundMask) << 4) | ((attr & backgroundMask) >> 4)
case 30 <= n && n <= 37:
attr = (attr & backgroundMask)
if (n-30)&1 != 0 {
attr |= foregroundRed
}
if (n-30)&2 != 0 {
attr |= foregroundGreen
}
if (n-30)&4 != 0 {
attr |= foregroundBlue
}
case n == 38: // set foreground color.
if i < len(token)-2 && (token[i+1] == "5" || token[i+1] == "05") {
if n256, err := strconv.Atoi(token[i+2]); err == nil {
if n256foreAttr == nil {
n256setup()
}
attr &= backgroundMask
attr |= n256foreAttr[n256]
i += 2
}
} else {
attr = attr & (w.oldattr & backgroundMask)
}
case n == 39: // reset foreground color.
attr &= backgroundMask
attr |= w.oldattr & foregroundMask
case 40 <= n && n <= 47:
attr = (attr & foregroundMask)
if (n-40)&1 != 0 {
attr |= backgroundRed
}
if (n-40)&2 != 0 {
attr |= backgroundGreen
}
if (n-40)&4 != 0 {
attr |= backgroundBlue
}
case n == 48: // set background color.
if i < len(token)-2 && token[i+1] == "5" {
if n256, err := strconv.Atoi(token[i+2]); err == nil {
if n256backAttr == nil {
n256setup()
}
attr &= foregroundMask
attr |= n256backAttr[n256]
i += 2
}
} else {
attr = attr & (w.oldattr & foregroundMask)
}
case n == 49: // reset foreground color.
attr &= foregroundMask
attr |= w.oldattr & backgroundMask
case 90 <= n && n <= 97:
attr = (attr & backgroundMask)
attr |= foregroundIntensity
if (n-90)&1 != 0 {
attr |= foregroundRed
}
if (n-90)&2 != 0 {
attr |= foregroundGreen
}
if (n-90)&4 != 0 {
attr |= foregroundBlue
}
case 100 <= n && n <= 107:
attr = (attr & foregroundMask)
attr |= backgroundIntensity
if (n-100)&1 != 0 {
attr |= backgroundRed
}
if (n-100)&2 != 0 {
attr |= backgroundGreen
}
if (n-100)&4 != 0 {
attr |= backgroundBlue
}
}
procSetConsoleTextAttribute.Call(uintptr(w.handle), uintptr(attr))
}
}
}
}
return len(data) - w.lastbuf.Len(), nil
}
type consoleColor struct {
rgb int
red bool
green bool
blue bool
intensity bool
}
func (c consoleColor) foregroundAttr() (attr word) {
if c.red {
attr |= foregroundRed
}
if c.green {
attr |= foregroundGreen
}
if c.blue {
attr |= foregroundBlue
}
if c.intensity {
attr |= foregroundIntensity
}
return
}
func (c consoleColor) backgroundAttr() (attr word) {
if c.red {
attr |= backgroundRed
}
if c.green {
attr |= backgroundGreen
}
if c.blue {
attr |= backgroundBlue
}
if c.intensity {
attr |= backgroundIntensity
}
return
}
var color16 = []consoleColor{
consoleColor{0x000000, false, false, false, false},
consoleColor{0x000080, false, false, true, false},
consoleColor{0x008000, false, true, false, false},
consoleColor{0x008080, false, true, true, false},
consoleColor{0x800000, true, false, false, false},
consoleColor{0x800080, true, false, true, false},
consoleColor{0x808000, true, true, false, false},
consoleColor{0xc0c0c0, true, true, true, false},
consoleColor{0x808080, false, false, false, true},
consoleColor{0x0000ff, false, false, true, true},
consoleColor{0x00ff00, false, true, false, true},
consoleColor{0x00ffff, false, true, true, true},
consoleColor{0xff0000, true, false, false, true},
consoleColor{0xff00ff, true, false, true, true},
consoleColor{0xffff00, true, true, false, true},
consoleColor{0xffffff, true, true, true, true},
}
type hsv struct {
h, s, v float32
}
func (a hsv) dist(b hsv) float32 {
dh := a.h - b.h
switch {
case dh > 0.5:
dh = 1 - dh
case dh < -0.5:
dh = -1 - dh
}
ds := a.s - b.s
dv := a.v - b.v
return float32(math.Sqrt(float64(dh*dh + ds*ds + dv*dv)))
}
func toHSV(rgb int) hsv {
r, g, b := float32((rgb&0xFF0000)>>16)/256.0,
float32((rgb&0x00FF00)>>8)/256.0,
float32(rgb&0x0000FF)/256.0
min, max := minmax3f(r, g, b)
h := max - min
if h > 0 {
if max == r {
h = (g - b) / h
if h < 0 {
h += 6
}
} else if max == g {
h = 2 + (b-r)/h
} else {
h = 4 + (r-g)/h
}
}
h /= 6.0
s := max - min
if max != 0 {
s /= max
}
v := max
return hsv{h: h, s: s, v: v}
}
type hsvTable []hsv
func toHSVTable(rgbTable []consoleColor) hsvTable {
t := make(hsvTable, len(rgbTable))
for i, c := range rgbTable {
t[i] = toHSV(c.rgb)
}
return t
}
func (t hsvTable) find(rgb int) consoleColor {
hsv := toHSV(rgb)
n := 7
l := float32(5.0)
for i, p := range t {
d := hsv.dist(p)
if d < l {
l, n = d, i
}
}
return color16[n]
}
func minmax3f(a, b, c float32) (min, max float32) {
if a < b {
if b < c {
return a, c
} else if a < c {
return a, b
} else {
return c, b
}
} else {
if a < c {
return b, c
} else if b < c {
return b, a
} else {
return c, a
}
}
}
var n256foreAttr []word
var n256backAttr []word
func n256setup() {
n256foreAttr = make([]word, 256)
n256backAttr = make([]word, 256)
t := toHSVTable(color16)
for i, rgb := range color256 {
c := t.find(rgb)
n256foreAttr[i] = c.foregroundAttr()
n256backAttr[i] = c.backgroundAttr()
}
}
+9
View File
@@ -0,0 +1,9 @@
// +build appengine
package isatty
// IsTerminal returns true if the file descriptor is terminal which
// is always false on on appengine classic which is a sandboxed PaaS.
func IsTerminal(fd uintptr) bool {
return false
}
+1
View File
@@ -1,4 +1,5 @@
// +build darwin freebsd openbsd netbsd
// +build !appengine
package isatty
+1
View File
@@ -1,4 +1,5 @@
// +build linux
// +build !appengine
package isatty
+16
View File
@@ -0,0 +1,16 @@
// +build solaris
// +build !appengine
package isatty
import (
"golang.org/x/sys/unix"
)
// IsTerminal returns true if the given file descriptor is a terminal.
// see: http://src.illumos.org/source/xref/illumos-gate/usr/src/lib/libbc/libc/gen/common/isatty.c
func IsTerminal(fd uintptr) bool {
var termio unix.Termio
err := unix.IoctlSetTermio(int(fd), unix.TCGETA, &termio)
return err == nil
}

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