diff --git a/aliases_test.go b/aliases_test.go index e6077fbf..b95cb276 100644 --- a/aliases_test.go +++ b/aliases_test.go @@ -1,8 +1,25 @@ +/* + * Modern Copy, (C) 2014, 2015 Minio, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package main import ( - . "github.com/minio-io/check" "testing" + + . "github.com/minio-io/check" ) type MySuite struct{} diff --git a/cmd-common.go b/cmd-common.go index 04f01bc6..33a6fa44 100644 --- a/cmd-common.go +++ b/cmd-common.go @@ -71,12 +71,15 @@ func getNewClient(debug bool, urlStr string) (clnt client.Client, err error) { if err != nil { return nil, iodine.New(err, nil) } - var auth s3.Auth - if hostCfg.Auth != nil { + if hostCfg.Auth == nil { + return nil, iodine.New(errInvalidAuth{}, nil) + } + auth := new(s3.Auth) + if hostCfg.Auth.AccessKeyID != "" || hostCfg.Auth.SecretAccessKey != "" { auth.AccessKeyID = hostCfg.Auth.AccessKeyID auth.SecretAccessKey = hostCfg.Auth.SecretAccessKey } - clnt = s3.GetNewClient(urlStr, &auth, mcUserAgent, debug) + clnt = s3.GetNewClient(urlStr, auth, mcUserAgent, debug) return clnt, nil case urlFile: clnt = fs.GetNewClient(urlStr) diff --git a/cmd-common_test.go b/cmd-common_test.go index bec45c3f..77cc252c 100644 --- a/cmd-common_test.go +++ b/cmd-common_test.go @@ -1,10 +1,28 @@ +/* + * Modern Copy, (C) 2014, 2015 Minio, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package main import ( - "github.com/cheggaaa/pb" - . "github.com/minio-io/check" "strings" "time" + + "github.com/cheggaaa/pb" + + . "github.com/minio-io/check" ) var _ = Suite(&MySuite{}) diff --git a/cmd-config.go b/cmd-config.go index b1d74778..463912cf 100644 --- a/cmd-config.go +++ b/cmd-config.go @@ -1,9 +1,23 @@ +/* + * Modern Copy, (C) 2014, 2015 Minio, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package main import ( "bytes" - "errors" - "fmt" "os" "path" "runtime" @@ -123,29 +137,27 @@ func checkMcConfig(config *mcConfig) (err error) { // check for version switch { case (config.Version != currentConfigVersion): - err := fmt.Errorf("Unsupported version [%d]. Current operating version is [%d]", config.Version, currentConfigVersion) - return iodine.New(err, nil) + return iodine.New(errUnsupportedVersion{old: currentConfigVersion, new: config.Version}, nil) case len(config.Hosts) > 1: for host, hostCfg := range config.Hosts { + // don't need to check for availability of AccessKeyID, not having one + // is a valid case for public buckets if host == "" { - return iodine.New(fmt.Errorf("Empty host URL"), nil) + return iodine.New(errEmptyURL{}, nil) } - if hostCfg.Auth != nil && hostCfg.Auth.AccessKeyID == "" { - return iodine.New(fmt.Errorf("AccessKeyID is empty for Host [%s]", host), nil) - } - if hostCfg.Auth != nil && hostCfg.Auth.SecretAccessKey == "" { - return iodine.New(fmt.Errorf("SecretAccessKey is empty for Host [%s]", host), nil) + if hostCfg.Auth == nil { + return iodine.New(errInvalidAuth{}, nil) } } case len(config.Aliases) > 0: for aliasName, aliasURL := range config.Aliases { _, err := url.Parse(aliasURL) if err != nil { - return iodine.New(fmt.Errorf("Unable to parse URL [%s] for alias [%s]", aliasURL, aliasName), nil) + return iodine.New(errInvalidAliasURL{alias: aliasName, url: aliasURL}, nil) } if !isValidAliasName(aliasName) { - return iodine.New(fmt.Errorf("Not a valid alias name [%s]. Valid examples are: Area51, Grand-Nagus..", aliasName), nil) + return iodine.New(errInvalidAliasName{alias: aliasName}, nil) } } } @@ -247,10 +259,11 @@ func parseConfigInput(c *cli.Context) (config *mcConfig, err error) { AccessKeyID: accessKeyID, SecretAccessKey: secretAccesskey, }}, + // local minio server can have this empty until we configure it. "http*://localhost:*": { Auth: &auth{ - AccessKeyID: accessKeyID, - SecretAccessKey: secretAccesskey, + AccessKeyID: "", + SecretAccessKey: "", }}, }, Aliases: map[string]string{ @@ -263,10 +276,10 @@ func parseConfigInput(c *cli.Context) (config *mcConfig, err error) { aliasName := alias[0] url := alias[1] if strings.HasPrefix(aliasName, "http") { - return nil, iodine.New(errors.New("invalid alias cannot use http{s}"), nil) + return nil, iodine.New(errInvalidAliasName{alias: aliasName}, nil) } if !strings.HasPrefix(url, "http") { - return nil, iodine.New(errors.New("invalid url type only supports http{s}"), nil) + return nil, iodine.New(errInvalidURL{url: url}, nil) } config = &mcConfig{ Version: currentConfigVersion, @@ -285,7 +298,7 @@ func parseConfigInput(c *cli.Context) (config *mcConfig, err error) { } return config, nil default: - return nil, iodine.New(errors.New("invalid number of arguments for --alias, requires exact 2"), nil) + return nil, iodine.New(errInvalidArgument{}, nil) } } @@ -309,22 +322,13 @@ func getHostConfig(requestURL string) (*hostConfig, error) { for globURL, cfg := range config.Hosts { match, err := filepath.Match(globURL, getHostURL(u)) if err != nil { - msg := fmt.Errorf("Error parsing glob'ed URL while comparing [%s] [%s]", globURL, requestURL) - return nil, iodine.New(msg, map[string]string{ - "globURL": globURL, - "hostURL": requestURL, - }) + return nil, iodine.New(errInvalidGlobURL{glob: globURL, request: requestURL}, nil) } if match { - var hostCfg hostConfig - if hostCfg.Auth != nil { - hostCfg.Auth.AccessKeyID = cfg.Auth.AccessKeyID - hostCfg.Auth.SecretAccessKey = cfg.Auth.SecretAccessKey - } - return &hostCfg, nil + return &cfg, nil } } - return nil, iodine.New(errors.New("No matching host config found"), nil) + return nil, iodine.New(errNoMatchingHost{}, nil) } //getBashCompletionCmd generates bash completion file. @@ -376,7 +380,7 @@ func saveConfigCmd(ctx *cli.Context) { log.Debug.Println(iodine.New(err, nil)) console.Fatalln("mc: Unable to identify config file path") } - console.Infof("Configuration written to " + configPath + ". Please update your access credentials.\n") + console.Infoln("Configuration written to " + configPath + ". Please update your access credentials.") } // doConfigCmd is the handler for "mc config" sub-command. diff --git a/cmd-config_test.go b/cmd-config_test.go index 775d21a5..983a5edc 100644 --- a/cmd-config_test.go +++ b/cmd-config_test.go @@ -1,5 +1,5 @@ /* - * Minimalist Object Storage, (C) 2014, 2015 Minio, Inc. + * Modern Copy, (C) 2014, 2015 Minio, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/cmd-cp.go b/cmd-cp.go index 2db504fd..866e9dc0 100644 --- a/cmd-cp.go +++ b/cmd-cp.go @@ -25,38 +25,7 @@ import ( "github.com/minio-io/minio/pkg/utils/log" ) -type message struct { - err error -} - -//func multiTargetGoroutine(targetURL string, md5Hex string, sourceSize int64, targetReader io.Reader, ch chan message) { -// errParams := map[string]string{ -// "url": targetURL, -// } -// targetBucket, targetObject, err := url2Object(targetURL) -// if err != nil { -// ch <- message{err: iodine.New(err, errParams)} -// } -// targetClnt, err := getNewClient(globalDebugFlag, targetURL) -// if err != nil { -// ch <- message{err: iodine.New(err, errParams)} -// } -// if err := targetClnt.Put(targetBucket, targetObject, md5Hex, sourceSize, targetReader); err != nil { -// ch <- message{err: iodine.New(err, errParams)} -// } -// ch <- message{err: nil} -// close(ch) -//} - -//func doPutMultiTarget(targetURLs []string, md5Hex string, sourceSize int64, targetReaders []io.Reader) <-chan message { -// ch := make(chan message) -// for i := 0; i < len(targetURLs); i++ { -// go multiTargetGoroutine(targetURLs[i], md5Hex, sourceSize, targetReaders[i], ch) -// } -// return ch -//} - -func getClientReader(sourceURL string) (reader io.ReadCloser, length int64, md5hex string, err error) { +func getSourceReader(sourceURL string) (reader io.ReadCloser, length int64, md5hex string, err error) { errParams := map[string]string{"sourceURL": sourceURL} // Parse URL to bucket and object names sourceBucket, sourceObject, err := url2Object(sourceURL) @@ -73,6 +42,34 @@ func getClientReader(sourceURL string) (reader io.ReadCloser, length int64, md5h return sourceClnt.Get(sourceBucket, sourceObject) } +func getTargetWriter(targetURL string, md5Hex string, length int64) (io.WriteCloser, error) { + client, err := getNewClient(false, targetURL) + if err != nil { + return nil, iodine.New(err, map[string]string{"failedURL": targetURL}) + } + targetBucket, targetObject, err := url2Object(targetURL) + if err != nil { + return nil, iodine.New(err, map[string]string{"failedURL": targetURL}) + } + return client.Put(targetBucket, targetObject, md5Hex, length) +} + +func getTargetWriters(urls []string, md5Hex string, length int64) ([]io.WriteCloser, error) { + var targetWriters []io.WriteCloser + for _, targetURL := range urls { + writer, err := getTargetWriter(targetURL, md5Hex, length) + if err != nil { + // close all writers + for _, targetWriter := range targetWriters { + targetWriter.Close() + } + return nil, iodine.New(err, map[string]string{"failedURL": targetURL}) + } + targetWriters = append(targetWriters, writer) + } + return targetWriters, nil +} + // doCopyCmd copies objects into and from a bucket or between buckets func doCopyCmd(ctx *cli.Context) { if len(ctx.Args()) < 2 { @@ -87,13 +84,13 @@ func doCopyCmd(ctx *cli.Context) { sourceURL := urlList[0] // First arg is source targetURLs := urlList[1:] // 1 or more targets - reader, length, hexMd5, err := getClientReader(sourceURL) + reader, length, hexMd5, err := getSourceReader(sourceURL) if err != nil { log.Debug.Println(iodine.New(err, nil)) console.Fatalln("Unable to read source") } - writeClosers, err := getWriters(targetURLs, hexMd5, length) + writeClosers, err := getTargetWriters(targetURLs, hexMd5, length) if err != nil { log.Debug.Println(iodine.New(err, nil)) console.Fatalln("Unable to open targets for writing") @@ -127,31 +124,3 @@ func doCopyCmd(ctx *cli.Context) { console.Fatalln("Unable to write to target") } } - -func getWriter(targetURL string, md5Hex string, length int64) (io.WriteCloser, error) { - client, err := getNewClient(false, targetURL) - if err != nil { - return nil, iodine.New(err, map[string]string{"failedURL": targetURL}) - } - targetBucket, targetObject, err := url2Object(targetURL) - if err != nil { - return nil, iodine.New(err, map[string]string{"failedURL": targetURL}) - } - return client.Put(targetBucket, targetObject, md5Hex, length) -} - -func getWriters(urls []string, md5Hex string, length int64) ([]io.WriteCloser, error) { - var targetWriters []io.WriteCloser - for _, targetURL := range urls { - writer, err := getWriter(targetURL, md5Hex, length) - if err != nil { - // close all writers - for _, targetWriter := range targetWriters { - targetWriter.Close() - } - return nil, iodine.New(err, map[string]string{"failedURL": targetURL}) - } - targetWriters = append(targetWriters, writer) - } - return targetWriters, nil -} diff --git a/errors.go b/errors.go index 67e8f4f2..ca8960e9 100644 --- a/errors.go +++ b/errors.go @@ -16,7 +16,13 @@ package main -import "strconv" +import "fmt" + +type errInvalidArgument struct{} + +func (e errInvalidArgument) Error() string { + return "invalid argument" +} type errEmptyURL struct{} @@ -29,7 +35,7 @@ type errUnsupportedScheme struct { } func (e errUnsupportedScheme) Error() string { - return "Unsuppported URL scheme: " + strconv.Itoa(int(e.scheme)) + return fmt.Sprintf("Unsuppported URL scheme: %d", e.scheme) } type errInvalidURL struct { @@ -40,6 +46,32 @@ func (e errInvalidURL) Error() string { return "Invalid URL: " + e.url } +type errInvalidGlobURL struct { + glob string + request string +} + +func (e errInvalidGlobURL) Error() string { + return "Error parsing glob'ed URL while comparing " + e.glob + " " + e.request +} + +type errInvalidAliasURL struct { + url string + alias string +} + +func (e errInvalidAliasURL) Error() string { + return "Unable to parse URL: " + e.url + " for alias: " + e.alias +} + +type errInvalidAliasName struct { + alias string +} + +func (e errInvalidAliasName) Error() string { + return "Not a valid alias name: " + e.alias + " Valid examples are: Area51, Grand-Nagus.." +} + type errInvalidBucket struct { bucket string } @@ -47,3 +79,24 @@ type errInvalidBucket struct { func (e errInvalidBucket) Error() string { return "Invalid bucket name: " + e.bucket } + +type errInvalidAuth struct{} + +func (e errInvalidAuth) Error() string { + return "invalid auth keys" +} + +type errUnsupportedVersion struct { + new uint + old uint +} + +func (e errUnsupportedVersion) Error() string { + return fmt.Sprintf("Unsupported version [%d]. Current operating version is [%d]", e.new, e.old) +} + +type errNoMatchingHost struct{} + +func (e errNoMatchingHost) Error() string { + return "No matching host found." +} diff --git a/notifier.go b/notifier.go index bab814e3..002469e2 100644 --- a/notifier.go +++ b/notifier.go @@ -1,3 +1,19 @@ +/* + * Modern Copy, (C) 2014, 2015 Minio, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package main import ( @@ -21,7 +37,7 @@ func intMax(x, y int) int { return y } -// printUpdateNotify - +// printUpdateNotify - inspired from Yeoman project npm package https://github.com/yeoman/update-notifier func printUpdateNotify(latestVersion, currentVersion string) { // TODO - make this configurable // diff --git a/pkg/client/errors.go b/pkg/client/errors.go index 52213d75..d8a6a758 100644 --- a/pkg/client/errors.go +++ b/pkg/client/errors.go @@ -1,3 +1,19 @@ +/* + * Modern Copy, (C) 2015 Minio, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package client import "strconv" diff --git a/pkg/client/fs/fs_test.go b/pkg/client/fs/fs_test.go index 2a83574f..9cb5ed1b 100644 --- a/pkg/client/fs/fs_test.go +++ b/pkg/client/fs/fs_test.go @@ -1,5 +1,5 @@ /* - * Minimalist Object Storage, (C) 2015 Minio, Inc. + * Modern Copy, (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. @@ -30,7 +30,7 @@ type MySuite struct{} var _ = Suite(&MySuite{}) -// TODO - implement these steps +// TODO - implement these func (s *MySuite) TestListBuckets(c *C) { root, err := ioutil.TempDir(os.TempDir(), "fs-") diff --git a/pkg/client/s3/object-put.go b/pkg/client/s3/object-put.go new file mode 100644 index 00000000..102db67d --- /dev/null +++ b/pkg/client/s3/object-put.go @@ -0,0 +1,114 @@ +/* + * Modern Copy, (C) 2015 Minio, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package s3 + +import ( + "encoding/base64" + "encoding/hex" + "io" + "net/http" + "strings" + "sync" + + "github.com/minio-io/minio/pkg/iodine" +) + +/// Object Operations PUT - keeping this in a separate file for readability + +// Put - upload new object to bucket +func (c *s3Client) Put(bucket, key, md5HexString string, size int64) (io.WriteCloser, error) { + r, w := io.Pipe() + blockingWriter := NewBlockingWriteCloser(w) + go func() { + req := newReq(c.keyURL(bucket, key), c.UserAgent, r) + req.Method = "PUT" + req.ContentLength = size + + // set Content-MD5 only if md5 is provided + if strings.TrimSpace(md5HexString) != "" { + md5, err := hex.DecodeString(md5HexString) + if err != nil { + err := iodine.New(err, nil) + r.CloseWithError(err) + blockingWriter.Release(err) + return + } + req.Header.Set("Content-MD5", base64.StdEncoding.EncodeToString(md5)) + } + c.signRequest(req, c.Host) + + client := http.Client{} + res, err := client.Do(req) + + if err != nil { + err := iodine.New(err, nil) + r.CloseWithError(err) + blockingWriter.Release(err) + return + } + + if res.StatusCode != http.StatusOK { + err := iodine.New(err, nil) + r.CloseWithError(err) + blockingWriter.Release(err) + return + } + blockingWriter.Release(nil) + r.Close() + }() + return blockingWriter, nil +} + +// BlockingWriteCloser is a WriteCloser that blocks until released +type BlockingWriteCloser struct { + w io.WriteCloser + release *sync.WaitGroup + err error +} + +// Write to the underlying writer +func (b *BlockingWriteCloser) Write(p []byte) (int, error) { + n, err := b.w.Write(p) + err = iodine.New(err, nil) + return n, err +} + +// Close blocks until another goroutine calls Release(error). Returns error code if either +// writer fails or Release is called with an error. +func (b *BlockingWriteCloser) Close() error { + err := b.w.Close() + if err != nil { + b.err = err + } + b.release.Wait() + return b.err +} + +// Release the Close, causing it to unblock. Only call this once. Calling it multiple times results in a panic. +func (b *BlockingWriteCloser) Release(err error) { + b.release.Done() + if err != nil { + b.err = err + } +} + +// NewBlockingWriteCloser Creates a new write closer that must be released by the read consumer. +func NewBlockingWriteCloser(w io.WriteCloser) *BlockingWriteCloser { + wg := &sync.WaitGroup{} + wg.Add(1) + return &BlockingWriteCloser{w: w, release: wg} +} diff --git a/pkg/client/s3/object.go b/pkg/client/s3/object.go index cfa1d4e0..98dea0a0 100644 --- a/pkg/client/s3/object.go +++ b/pkg/client/s3/object.go @@ -45,101 +45,14 @@ import ( "strings" "time" - "encoding/base64" - "encoding/hex" "net/http" "github.com/minio-io/mc/pkg/client" "github.com/minio-io/minio/pkg/iodine" - "sync" ) /// Object API operations -// Put - upload new object to bucket -func (c *s3Client) Put(bucket, key, md5HexString string, size int64) (io.WriteCloser, error) { - r, w := io.Pipe() - blockingWriter := NewBlockingWriteCloser(w) - go func() { - req := newReq(c.keyURL(bucket, key), c.UserAgent, r) - req.Method = "PUT" - req.ContentLength = size - - // set Content-MD5 only if md5 is provided - if strings.TrimSpace(md5HexString) != "" { - md5, err := hex.DecodeString(md5HexString) - if err != nil { - err := iodine.New(err, nil) - r.CloseWithError(err) - blockingWriter.Release(err) - return - } - req.Header.Set("Content-MD5", base64.StdEncoding.EncodeToString(md5)) - } - c.signRequest(req, c.Host) - - client := http.Client{} - res, err := client.Do(req) - - if err != nil { - err := iodine.New(err, nil) - r.CloseWithError(err) - blockingWriter.Release(err) - return - } - - if res.StatusCode != http.StatusOK { - err := iodine.New(err, nil) - r.CloseWithError(err) - blockingWriter.Release(err) - return - } - blockingWriter.Release(nil) - r.Close() - }() - return blockingWriter, nil -} - -// BlockingWriteCloser is a WriteCloser that blocks until released -type BlockingWriteCloser struct { - w io.WriteCloser - release *sync.WaitGroup - err error -} - -// Write to the underlying writer -func (b *BlockingWriteCloser) Write(p []byte) (int, error) { - n, err := b.w.Write(p) - err = iodine.New(err, nil) - return n, err -} - -// Close blocks until another goroutine calls Release(error). Returns error code if either -// writer fails or Release is called with an error. -func (b *BlockingWriteCloser) Close() error { - err := b.w.Close() - if err != nil { - b.err = err - } - b.release.Wait() - return b.err -} - -// Release the Close, causing it to unblock. Only call this once. Calling it multiple times results in a panic. -func (b *BlockingWriteCloser) Release(err error) { - b.release.Done() - if err != nil { - b.err = err - } -} - -// NewBlockingWriteCloser Creates a new write closer that must be released by the read consumer. -func NewBlockingWriteCloser(w io.WriteCloser) *BlockingWriteCloser { - wg := &sync.WaitGroup{} - wg.Add(1) - return &BlockingWriteCloser{w: w, release: wg} -} - // Stat - returns 0, "", os.ErrNotExist if not on S3 func (c *s3Client) StatObject(bucket, key string) (size int64, date time.Time, reterr error) { if bucket == "" || key == "" {