From e7dab5f1cf42c685e25afe37eefcea5e5296b635 Mon Sep 17 00:00:00 2001 From: Harshavardhana Date: Sun, 2 Aug 2015 20:31:36 -0700 Subject: [PATCH] Migrating from iodine to probe --- Godeps/Godeps.json | 10 +- .../github.com/dustin/go-humanize/bigbytes.go | 2 +- .../dustin/go-humanize/bigbytes_test.go | 4 +- .../github.com/dustin/go-humanize/bytes.go | 2 +- .../dustin/go-humanize/bytes_test.go | 6 +- .../github.com/dustin/go-humanize/comma.go | 2 +- .../github.com/minio/minio/pkg/probe/probe.go | 191 ++++++++++++++++++ .../minio/minio/pkg/probe/probe_test.go | 45 +++++ .../_workspace/src/gopkg.in/check.v1/check.go | 2 +- access-main.go | 43 ++-- aliases.go | 8 +- cat-main.go | 36 ++-- cat_test.go | 6 +- common-methods.go | 81 ++++---- config-main.go | 54 ++--- config.go | 83 ++++---- cp-main.go | 11 +- cp-url.go | 114 ++++++----- diff-main.go | 22 +- diff.go | 29 ++- error.go | 37 ++++ first-time.go | 14 +- globals.go | 10 - hostconfig.go | 43 ++-- ls-main.go | 22 +- ls.go | 16 +- main.go | 7 +- mb-main.go | 34 +--- mb_access_test.go | 8 +- mirror-main.go | 14 +- mirror-url.go | 31 ++- pkg/client/client.go | 14 +- pkg/client/fs/fs.go | 115 +++++------ pkg/client/fs/fs_unix.go | 4 +- pkg/client/fs/fs_windows.go | 9 +- pkg/client/s3/httptrace.go | 13 +- pkg/client/s3/s3.go | 57 +++--- pkg/client/s3/s3_test.go | 8 +- pkg/client/s3/trace.go | 5 +- pkg/console/console.go | 4 +- pkg/quick/quick.go | 62 +++--- session-main.go | 67 +++--- session-v1.go | 17 +- session-v2.go | 54 ++--- session.go | 12 +- update-main.go | 19 +- url.go | 22 +- 47 files changed, 816 insertions(+), 653 deletions(-) create mode 100644 Godeps/_workspace/src/github.com/minio/minio/pkg/probe/probe.go create mode 100644 Godeps/_workspace/src/github.com/minio/minio/pkg/probe/probe_test.go create mode 100644 error.go diff --git a/Godeps/Godeps.json b/Godeps/Godeps.json index 9946980f..03deff95 100644 --- a/Godeps/Godeps.json +++ b/Godeps/Godeps.json @@ -7,7 +7,7 @@ "Deps": [ { "ImportPath": "github.com/dustin/go-humanize", - "Rev": "c128122e0b9b93799aef8181a537e5d8fd7081d6" + "Rev": "00897f070f09f194c26d65afae734ba4c32404e8" }, { "ImportPath": "github.com/fatih/color", @@ -33,9 +33,9 @@ "Rev": "20db439bc6671562eeff32d4cc3381eb7e824671" }, { - "ImportPath": "github.com/minio/minio/pkg/iodine", - "Comment": "release-1434511043-280-g6be5a2f", - "Rev": "6be5a2fb7ec1fb92b7474485efb4633d8cf84a8e" + "ImportPath": "github.com/minio/minio/pkg/probe", + "Comment": "release-1434511043-296-g7f13095", + "Rev": "7f1309526056653a8e07277b3e39bfc49766363a" }, { "ImportPath": "github.com/minio/pb", @@ -56,7 +56,7 @@ }, { "ImportPath": "gopkg.in/check.v1", - "Rev": "b3d3430320d4260e5fea99841af984b3badcea63" + "Rev": "11d3bc7aa68e238947792f30573146a3231fc0f1" } ] } diff --git a/Godeps/_workspace/src/github.com/dustin/go-humanize/bigbytes.go b/Godeps/_workspace/src/github.com/dustin/go-humanize/bigbytes.go index e4a814a9..6876e92e 100644 --- a/Godeps/_workspace/src/github.com/dustin/go-humanize/bigbytes.go +++ b/Godeps/_workspace/src/github.com/dustin/go-humanize/bigbytes.go @@ -115,7 +115,7 @@ func humanateBigBytes(s, base *big.Int, sizes []string) string { // // BigBytes(82854982) -> 83MB func BigBytes(s *big.Int) string { - sizes := []string{"B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"} + sizes := []string{"B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"} return humanateBigBytes(s, bigSIExp, sizes) } diff --git a/Godeps/_workspace/src/github.com/dustin/go-humanize/bigbytes_test.go b/Godeps/_workspace/src/github.com/dustin/go-humanize/bigbytes_test.go index da367d41..a0f977a6 100644 --- a/Godeps/_workspace/src/github.com/dustin/go-humanize/bigbytes_test.go +++ b/Godeps/_workspace/src/github.com/dustin/go-humanize/bigbytes_test.go @@ -86,8 +86,8 @@ func TestBigBytes(t *testing.T) { {"bytes(803)", bbyte(803), "803B"}, {"bytes(999)", bbyte(999), "999B"}, - {"bytes(1024)", bbyte(1024), "1.0kB"}, - {"bytes(1MB - 1)", bbyte(MByte - Byte), "1000kB"}, + {"bytes(1024)", bbyte(1024), "1.0KB"}, + {"bytes(1MB - 1)", bbyte(MByte - Byte), "1000KB"}, {"bytes(1MB)", bbyte(1024 * 1024), "1.0MB"}, {"bytes(1GB - 1K)", bbyte(GByte - KByte), "1000MB"}, diff --git a/Godeps/_workspace/src/github.com/dustin/go-humanize/bytes.go b/Godeps/_workspace/src/github.com/dustin/go-humanize/bytes.go index b7a77b52..4c4b5af1 100644 --- a/Godeps/_workspace/src/github.com/dustin/go-humanize/bytes.go +++ b/Godeps/_workspace/src/github.com/dustin/go-humanize/bytes.go @@ -86,7 +86,7 @@ func humanateBytes(s uint64, base float64, sizes []string) string { // // Bytes(82854982) -> 83MB func Bytes(s uint64) string { - sizes := []string{"B", "kB", "MB", "GB", "TB", "PB", "EB"} + sizes := []string{"B", "KB", "MB", "GB", "TB", "PB", "EB"} return humanateBytes(s, 1000, sizes) } diff --git a/Godeps/_workspace/src/github.com/dustin/go-humanize/bytes_test.go b/Godeps/_workspace/src/github.com/dustin/go-humanize/bytes_test.go index 7497fa00..76a594c1 100644 --- a/Godeps/_workspace/src/github.com/dustin/go-humanize/bytes_test.go +++ b/Godeps/_workspace/src/github.com/dustin/go-humanize/bytes_test.go @@ -80,9 +80,9 @@ func TestBytes(t *testing.T) { {"bytes(803)", Bytes(803), "803B"}, {"bytes(999)", Bytes(999), "999B"}, - {"bytes(1024)", Bytes(1024), "1.0kB"}, - {"bytes(9999)", Bytes(9999), "10kB"}, - {"bytes(1MB - 1)", Bytes(MByte - Byte), "1000kB"}, + {"bytes(1024)", Bytes(1024), "1.0KB"}, + {"bytes(9999)", Bytes(9999), "10KB"}, + {"bytes(1MB - 1)", Bytes(MByte - Byte), "1000KB"}, {"bytes(1MB)", Bytes(1024 * 1024), "1.0MB"}, {"bytes(1GB - 1K)", Bytes(GByte - KByte), "1000MB"}, diff --git a/Godeps/_workspace/src/github.com/dustin/go-humanize/comma.go b/Godeps/_workspace/src/github.com/dustin/go-humanize/comma.go index 20711c15..9d0d2ed1 100644 --- a/Godeps/_workspace/src/github.com/dustin/go-humanize/comma.go +++ b/Godeps/_workspace/src/github.com/dustin/go-humanize/comma.go @@ -18,7 +18,7 @@ func Comma(v int64) string { v = 0 - v } - parts := []string{"", "", "", "", "", "", ""} + parts := []string{"", "", "", "", "", "", "", ""} j := len(parts) - 1 for v > 999 { diff --git a/Godeps/_workspace/src/github.com/minio/minio/pkg/probe/probe.go b/Godeps/_workspace/src/github.com/minio/minio/pkg/probe/probe.go new file mode 100644 index 00000000..078d2391 --- /dev/null +++ b/Godeps/_workspace/src/github.com/minio/minio/pkg/probe/probe.go @@ -0,0 +1,191 @@ +/* + * Minimalist Object 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 probe implements a simple mechanism to trace and return errors in large programs. +package probe + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "runtime" + "strconv" + "strings" + "sync" + + "github.com/dustin/go-humanize" +) + +// GetSysInfo returns useful system statistics. +func GetSysInfo() map[string]string { + host, err := os.Hostname() + if err != nil { + host = "" + } + memstats := &runtime.MemStats{} + runtime.ReadMemStats(memstats) + return map[string]string{ + "host.name": host, + "host.os": runtime.GOOS, + "host.arch": runtime.GOARCH, + "host.lang": runtime.Version(), + "host.cpus": strconv.Itoa(runtime.NumCPU()), + "mem.used": humanize.Bytes(memstats.Alloc), + "mem.total": humanize.Bytes(memstats.Sys), + "mem.heap.used": humanize.Bytes(memstats.HeapAlloc), + "mem.heap.total": humanize.Bytes(memstats.HeapSys), + } +} + +type tracePoint struct { + Line int `json:"Line"` + Filename string `json:"File"` + Function string `json:"Func"` + Env map[string][]string `json:"Env"` +} + +// Error implements tracing error functionality. +type Error struct { + lock sync.RWMutex + e error + sysInfo map[string]string + tracePoints []tracePoint +} + +// New function instantiates an error probe for tracing. Original errors.error (golang's error +// interface) is injected in only once during this New call. Rest of the time, you +// trace the return path with Probe.Trace and finally handle reporting or quitting +// at the top level. +func New(e error) *Error { + Err := Error{sync.RWMutex{}, e, GetSysInfo(), []tracePoint{}} + return Err.trace() +} + +// Trace records the point at which it is invoked. Stack traces are important for +// debugging purposes. +func (e *Error) Trace(fields ...string) *Error { + if e == nil { + return nil + } + + e.lock.Lock() + defer e.lock.Unlock() + + return e.trace(fields...) +} + +// internal trace - records the point at which it is invoked. Stack traces are important for +// debugging purposes. +func (e *Error) trace(fields ...string) *Error { + pc, file, line, _ := runtime.Caller(2) + function := runtime.FuncForPC(pc).Name() + _, function = filepath.Split(function) + file = "..." + strings.TrimPrefix(file, os.Getenv("GOPATH")) // trim gopathSource from file + tp := tracePoint{} + if len(fields) > 0 { + tp = tracePoint{Line: line, Filename: file, Function: function, Env: map[string][]string{"Tags": fields}} + } else { + tp = tracePoint{Line: line, Filename: file, Function: function} + } + e.tracePoints = append(e.tracePoints, tp) + return e +} + +// Untrace erases last trace entry. +func (e *Error) Untrace() { + if e == nil { + return + } + e.lock.Lock() + defer e.lock.Unlock() + + l := len(e.tracePoints) + if l == 0 { + return + } + // topTP := e.tracePoints[l-1] + e.tracePoints = e.tracePoints[:l-1] +} + +// Error returns error string. +func (e *Error) Error() string { + if e == nil { + return "" + } + return e.String() +} + +// String returns error message. +func (e *Error) String() string { + if e == nil { + return "" + } + e.lock.RLock() + defer e.lock.RUnlock() + + if e.e != nil { + trace := e.e.Error() + "\n" + for i, tp := range e.tracePoints { + if len(tp.Env) > 0 { + trace += fmt.Sprintf(" (%d) %s:%d %s(..) Tags: [%s]\n", i, tp.Filename, tp.Line, tp.Function, strings.Join(tp.Env["Tags"], ", ")) + } else { + trace += fmt.Sprintf(" (%d) %s:%d %s(..)\n", i, tp.Filename, tp.Line, tp.Function) + } + } + + trace += " Host:" + e.sysInfo["host.name"] + " | " + trace += "OS:" + e.sysInfo["host.os"] + " | " + trace += "Arch:" + e.sysInfo["host.arch"] + " | " + trace += "Lang:" + e.sysInfo["host.lang"] + " | " + trace += "Mem:" + e.sysInfo["mem.used"] + "/" + e.sysInfo["mem.total"] + " | " + trace += "Heap:" + e.sysInfo["mem.heap.used"] + "/" + e.sysInfo["mem.heap.total"] + + return trace + } + return "" +} + +// JSON returns JSON formated error trace. +func (e *Error) JSON() string { + if e == nil { + return "" + } + + e.lock.RLock() + defer e.lock.RUnlock() + + anonError := struct { + SysInfo map[string]string + TracePoints []tracePoint + }{ + e.sysInfo, + e.tracePoints, + } + + // jBytes, err := json.Marshal(anonError) + jBytes, err := json.MarshalIndent(anonError, "", "\t") + if err != nil { + return "" + } + return string(jBytes) +} + +// ToError returns original emnedded error. +func (e *Error) ToError() error { + // No need to lock. "e.e" is set once during New and never changed. + return e.e +} diff --git a/Godeps/_workspace/src/github.com/minio/minio/pkg/probe/probe_test.go b/Godeps/_workspace/src/github.com/minio/minio/pkg/probe/probe_test.go new file mode 100644 index 00000000..f50e8c63 --- /dev/null +++ b/Godeps/_workspace/src/github.com/minio/minio/pkg/probe/probe_test.go @@ -0,0 +1,45 @@ +/* + * 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 probe + +import ( + "os" + "testing" +) + +func testDummy() *Error { + _, e := os.Stat("this-file-cannot-exit-234234232423423") + es := New(e) + es.Trace("this is hell", "asdf") + return es +} + +func TestProbe(t *testing.T) { + es := testDummy() + if es == nil { + t.Fail() + } + + newES := es.Trace() + if newES == nil { + t.Fail() + } + /* + fmt.Println(es) + fmt.Println(es.JSON()) + fmt.Println(es.ToError()) + */ +} diff --git a/Godeps/_workspace/src/gopkg.in/check.v1/check.go b/Godeps/_workspace/src/gopkg.in/check.v1/check.go index f302a053..c99392a2 100644 --- a/Godeps/_workspace/src/gopkg.in/check.v1/check.go +++ b/Godeps/_workspace/src/gopkg.in/check.v1/check.go @@ -335,7 +335,7 @@ func (c *C) logPanic(skip int, value interface{}) { if name == "Value.call" && strings.HasSuffix(path, valueGo) { continue } - if name == "call16" && strings.Contains(path, asmGo) { + if (name == "call16" || name == "call32") && strings.Contains(path, asmGo) { continue } c.logf("%s:%d\n in %s", nicePath(file), line, name) diff --git a/access-main.go b/access-main.go index e04edd2f..74851407 100644 --- a/access-main.go +++ b/access-main.go @@ -17,12 +17,9 @@ package main import ( - "fmt" - "github.com/minio/cli" "github.com/minio/mc/pkg/client" - "github.com/minio/mc/pkg/console" - "github.com/minio/minio/pkg/iodine" + "github.com/minio/minio/pkg/probe" ) // Help message. @@ -67,42 +64,26 @@ func runAccessCmd(ctx *cli.Context) { config := mustGetMcConfig() acl := bucketACL(ctx.Args().First()) if !acl.isValidBucketACL() { - console.Fatalf("Valid types are [private, public, readonly]. %s\n", errInvalidACL{acl: acl.String()}) + ifFatal(probe.New(errInvalidACL{acl: acl.String()})) } for _, arg := range ctx.Args().Tail() { targetURL, err := getExpandedURL(arg, config.Aliases) - if err != nil { - switch e := iodine.ToError(err).(type) { - case errUnsupportedScheme: - console.Fatalf("Unknown type of URL %s. %s\n", e.url, err) - default: - console.Fatalf("Unable to parse argument %s. %s\n", arg, err) - } - } - msg, err := doUpdateAccessCmd(targetURL, acl) - if err != nil { - console.Fatalln(msg) - } - console.Infoln(msg) + ifFatal(err) + + err = doUpdateAccessCmd(targetURL, acl) + ifFatal(err) } } -func doUpdateAccessCmd(targetURL string, targetACL bucketACL) (string, error) { - var err error +func doUpdateAccessCmd(targetURL string, targetACL bucketACL) *probe.Error { var clnt client.Client - clnt, err = target2Client(targetURL) + clnt, err := target2Client(targetURL) if err != nil { - msg := fmt.Sprintf("Unable to initialize client for ‘%s’", targetURL) - return msg, NewIodine(iodine.New(err, nil)) + return err.Trace() } - return doUpdateAccess(clnt, targetACL) -} - -func doUpdateAccess(clnt client.Client, targetACL bucketACL) (string, error) { - err := clnt.SetBucketACL(targetACL.String()) + err = clnt.SetBucketACL(targetACL.String()) if err != nil { - msg := fmt.Sprintf("Failed to add bucket access policy for URL ‘%s’", clnt.URL().String()) - return msg, NewIodine(iodine.New(err, nil)) + return err.Trace() } - return "Bucket access policy updated successfully : " + clnt.URL().String(), nil + return nil } diff --git a/aliases.go b/aliases.go index b808da7f..4964b93a 100644 --- a/aliases.go +++ b/aliases.go @@ -21,7 +21,7 @@ import ( "strings" "github.com/minio/mc/pkg/client" - "github.com/minio/minio/pkg/iodine" + "github.com/minio/minio/pkg/probe" ) // validAliasURL: use net/url.Parse to validate @@ -46,10 +46,10 @@ func isValidAliasName(aliasName string) bool { } // aliasExpand expands aliased (name:/path) to full URL, used by url-parser -func aliasExpand(aliasedURL string, aliases map[string]string) (newURL string, err error) { +func aliasExpand(aliasedURL string, aliases map[string]string) (string, *probe.Error) { u, err := client.Parse(aliasedURL) if err != nil { - return aliasedURL, iodine.New(errInvalidURL{URL: aliasedURL}, nil) + return aliasedURL, probe.New(errInvalidURL{URL: aliasedURL}) } // proper URL if u.Host != "" { @@ -69,7 +69,7 @@ func aliasExpand(aliasedURL string, aliases map[string]string) (newURL string, e trimmedURL := expandedURL + "/" + strings.TrimPrefix(strings.TrimPrefix(splits[1], "/"), "\\") u, err := client.Parse(trimmedURL) if err != nil { - return aliasedURL, iodine.New(errInvalidURL{URL: aliasedURL}, nil) + return aliasedURL, probe.New(errInvalidURL{URL: aliasedURL}) } return u.String(), nil } diff --git a/cat-main.go b/cat-main.go index 5f887751..b0f1ead6 100644 --- a/cat-main.go +++ b/cat-main.go @@ -22,8 +22,7 @@ import ( "syscall" "github.com/minio/cli" - "github.com/minio/mc/pkg/console" - "github.com/minio/minio/pkg/iodine" + "github.com/minio/minio/pkg/probe" ) // Help message. @@ -68,46 +67,35 @@ func runCatCmd(ctx *cli.Context) { // Convert arguments to URLs: expand alias, fix format... for _, arg := range ctx.Args() { sourceURL, err := getExpandedURL(arg, config.Aliases) - if err != nil { - switch e := iodine.ToError(err).(type) { - case errUnsupportedScheme: - console.Fatalf("Unknown type of URL %s. %s\n", e.url, err) - default: - console.Fatalf("Unable to parse argument %s. %s\n", arg, err) - } - } - errorMsg, err := doCatCmd(sourceURL) - if err != nil { - console.Fatalln(errorMsg) - } + ifFatal(err) + ifFatal(doCatCmd(sourceURL)) } } -func doCatCmd(sourceURL string) (string, error) { +func doCatCmd(sourceURL string) *probe.Error { sourceClnt, err := source2Client(sourceURL) if err != nil { - return "Unable to create client: " + sourceURL, NewIodine(iodine.New(err, nil)) + return err.Trace() } // ignore size, since os.Stat() would not return proper size all the time for local filesystem // for example /proc files. reader, _, err := sourceClnt.GetObject(0, 0) if err != nil { - return "Unable to retrieve file: " + sourceURL, NewIodine(iodine.New(err, nil)) + return err.Trace() } defer reader.Close() // read till EOF - _, err = io.Copy(os.Stdout, reader) - if err != nil { - switch e := iodine.ToError(err).(type) { + if _, err := io.Copy(os.Stdout, reader); err != nil { + switch e := err.(type) { case *os.PathError: if e.Err == syscall.EPIPE { // stdout closed by the user. Gracefully exit. - return "", nil + return nil } - return "Writing data to stdout failed, unexpected problem.. please report this error", iodine.New(err, nil) + return probe.New(err) default: - return "Reading data from source failed: " + sourceURL, NewIodine(iodine.New(err, nil)) + return probe.New(err) } } - return "", nil + return nil } diff --git a/cat_test.go b/cat_test.go index fdd73a79..61fd800a 100644 --- a/cat_test.go +++ b/cat_test.go @@ -45,13 +45,11 @@ func (s *CmdTestSuite) TestCatCmd(c *C) { sourceURLs = append(sourceURLs, objectPath) sourceURLs = append(sourceURLs, objectPathServer) for _, sourceURL := range sourceURLs { - _, err = doCatCmd(sourceURL) - c.Assert(err, IsNil) + c.Assert(doCatCmd(sourceURL), IsNil) } objectPath = filepath.Join(root, "object2") - _, err = doCatCmd(objectPath) - c.Assert(err, Not(IsNil)) + c.Assert(doCatCmd(objectPath), Not(IsNil)) } func (s *CmdTestSuite) TestCatContext(c *C) { diff --git a/common-methods.go b/common-methods.go index c35794e7..5b9f265d 100644 --- a/common-methods.go +++ b/common-methods.go @@ -26,7 +26,7 @@ import ( "github.com/minio/mc/pkg/client" "github.com/minio/mc/pkg/client/fs" "github.com/minio/mc/pkg/client/s3" - "github.com/minio/minio/pkg/iodine" + "github.com/minio/minio/pkg/probe" ) // Check if the target URL represents folder. It may or may not exist yet. @@ -35,46 +35,48 @@ func isTargetURLDir(targetURL string) bool { if err != nil { return false } - _, targetContent, err := url2Stat(targetURL) - if err != nil { - if targetURLParse.Path == string(targetURLParse.Separator) && targetURLParse.Scheme != "" { + { + _, targetContent, err := url2Stat(targetURL) + if err != nil { + if targetURLParse.Path == string(targetURLParse.Separator) && targetURLParse.Scheme != "" { + return false + } + if strings.HasSuffix(targetURLParse.Path, string(targetURLParse.Separator)) { + return true + } return false } - if strings.HasSuffix(targetURLParse.Path, string(targetURLParse.Separator)) { - return true + if !targetContent.Type.IsDir() { // Target is a dir. + return false } - return false - } - if !targetContent.Type.IsDir() { // Target is a dir. - return false } return true } // getSource gets a reader from URL< -func getSource(sourceURL string) (reader io.ReadCloser, length int64, err error) { +func getSource(sourceURL string) (reader io.ReadCloser, length int64, err *probe.Error) { sourceClnt, err := source2Client(sourceURL) if err != nil { - return nil, 0, NewIodine(iodine.New(err, map[string]string{"failedURL": sourceURL})) + return nil, 0, err.Trace() } return sourceClnt.GetObject(0, 0) } // putTarget writes to URL from reader. -func putTarget(targetURL string, length int64, reader io.Reader) error { +func putTarget(targetURL string, length int64, reader io.Reader) *probe.Error { targetClnt, err := target2Client(targetURL) if err != nil { - return NewIodine(iodine.New(err, nil)) + return err.Trace() } err = targetClnt.PutObject(length, reader) if err != nil { - return NewIodine(iodine.New(err, map[string]string{"failedURL": targetURL})) + return err.Trace() } return nil } // putTargets writes to URL from reader. -func putTargets(targetURLs []string, length int64, reader io.Reader) error { +func putTargets(targetURLs []string, length int64, reader io.Reader) *probe.Error { var tgtReaders []io.ReadCloser var tgtWriters []io.WriteCloser var tgtClients []client.Client @@ -82,7 +84,7 @@ func putTargets(targetURLs []string, length int64, reader io.Reader) error { for _, targetURL := range targetURLs { tgtClient, err := target2Client(targetURL) if err != nil { - return iodine.New(err, nil) + return err.Trace() } tgtClients = append(tgtClients, tgtClient) tgtReader, tgtWriter := io.Pipe() @@ -101,7 +103,7 @@ func putTargets(targetURLs []string, length int64, reader io.Reader) error { }() var wg sync.WaitGroup - errorCh := make(chan error, len(tgtClients)) + errorCh := make(chan *probe.Error, len(tgtClients)) func() { // Parallel putObject defer close(errorCh) // Each routine gets to return one err status. @@ -112,15 +114,15 @@ func putTargets(targetURLs []string, length int64, reader io.Reader) error { tgtClient := tgtClients[i] tgtReader := tgtReaders[i] - go func(targetClient client.Client, reader io.ReadCloser, errorCh chan<- error) { + go func(targetClient client.Client, reader io.ReadCloser, errorCh chan<- *probe.Error) { defer wg.Done() err := targetClient.PutObject(length, reader) if err != nil { - errorCh <- iodine.New(err, map[string]string{"failedURL": targetClient.URL().String()}) + errorCh <- err.Trace() reader.Close() return } - errorCh <- err // return nil error = success. + errorCh <- nil }(tgtClient, tgtReader, errorCh) } wg.Wait() @@ -135,10 +137,10 @@ func putTargets(targetURLs []string, length int64, reader io.Reader) error { } // getNewClient gives a new client interface -func getNewClient(urlStr string, auth hostConfig) (clnt client.Client, err error) { +func getNewClient(urlStr string, auth hostConfig) (client.Client, *probe.Error) { url, err := client.Parse(urlStr) if err != nil { - return nil, iodine.New(errInvalidURL{URL: urlStr}, map[string]string{"URL": urlStr}) + return nil, probe.New(err) } switch url.Type { case client.Object: // Minio and S3 compatible cloud storage @@ -164,62 +166,69 @@ func getNewClient(urlStr string, auth hostConfig) (clnt client.Client, err error case client.Filesystem: return fs.New(urlStr) } - return nil, iodine.New(errInvalidURL{URL: urlStr}, nil) + return nil, probe.New(errInvalidURL{URL: urlStr}) } // url2Stat - Returns client, config and its stat Content from the URL -func url2Stat(urlStr string) (client client.Client, content *client.Content, err error) { +func url2Stat(urlStr string) (client client.Client, content *client.Content, err *probe.Error) { client, err = url2Client(urlStr) if err != nil { - return nil, nil, iodine.New(err, map[string]string{"URL": urlStr}) + return nil, nil, err.Trace() } content, err = client.Stat() if err != nil { - return nil, nil, iodine.New(err, map[string]string{"URL": urlStr}) + return nil, nil, err.Trace() } return client, content, nil } -func url2Client(url string) (client.Client, error) { +func isValidURL(url string) bool { // Empty source arg? urlParse, err := client.Parse(url) if err != nil { - return nil, iodine.New(err, map[string]string{"URL": url}) + return false } if urlParse.Path == "" { - return nil, iodine.New(errInvalidURL{URL: url}, map[string]string{"URL": url}) + return false } + return true +} + +func url2Client(url string) (client.Client, *probe.Error) { + if !isValidURL(url) { + return nil, probe.New(errInvalidURL{URL: url}) + } urlconfig, err := getHostConfig(url) if err != nil { - return nil, iodine.New(err, map[string]string{"URL": url}) + return nil, err.Trace() } client, err := getNewClient(url, urlconfig) if err != nil { - return nil, iodine.New(err, map[string]string{"URL": url}) + return nil, err.Trace() } return client, nil } // source2Client returns client and hostconfig objects from the source URL. -func source2Client(sourceURL string) (client.Client, error) { +func source2Client(sourceURL string) (client.Client, *probe.Error) { sourceClient, err := url2Client(sourceURL) if err != nil { - return nil, iodine.New(errInvalidSource{URL: sourceURL}, map[string]string{"URL": sourceURL}) + return nil, err.Trace() } return sourceClient, nil } // target2Client returns client and hostconfig objects from the target URL. -func target2Client(targetURL string) (client.Client, error) { +func target2Client(targetURL string) (client.Client, *probe.Error) { targetClient, err := url2Client(targetURL) if err != nil { - return nil, iodine.New(errInvalidTarget{URL: targetURL}, map[string]string{"URL": targetURL}) + return nil, err.Trace() } return targetClient, nil } diff --git a/config-main.go b/config-main.go index 265f776a..849fa87c 100644 --- a/config-main.go +++ b/config-main.go @@ -22,7 +22,7 @@ import ( "github.com/minio/cli" "github.com/minio/mc/pkg/console" "github.com/minio/mc/pkg/quick" - "github.com/minio/minio/pkg/iodine" + "github.com/minio/minio/pkg/probe" ) // Configure minio client @@ -67,88 +67,90 @@ func runConfigCmd(ctx *cli.Context) { console.Fatalf("Incorrect number of arguments, please read \"mc config help\". %s", errInvalidArgument{}) } msg, err := doConfig(arg, tailArgs) - if err != nil { - console.Fatalln(msg) - } + ifFatal(err) console.Infoln(msg) } // saveConfig writes configuration data in json format to config file. -func saveConfig(arg string, aliases []string) error { +func saveConfig(arg string, aliases []string) *probe.Error { switch arg { case "alias": config, err := addAlias(aliases) if err != nil { - return NewIodine(iodine.New(err, nil)) + return err.Trace() } return writeConfig(config) default: - return NewIodine(iodine.New(errInvalidArgument{}, nil)) + return probe.New(errInvalidArgument{}) } } // doConfig is the handler for "mc config" sub-command. -func doConfig(arg string, aliases []string) (string, error) { +func doConfig(arg string, aliases []string) (string, *probe.Error) { configPath, err := getMcConfigPath() if err != nil { - return "Unable to determine config file path.", NewIodine(iodine.New(err, nil)) + return "Unable to determine config file path.", err.Trace() } err = saveConfig(arg, aliases) if err != nil { - switch iodine.ToError(err).(type) { + switch err.ToError().(type) { case errConfigExists: - return "Configuration file [" + configPath + "]", NewIodine(iodine.New(err, nil)) + return "Configuration file [" + configPath + "]", err.Trace() case errInvalidArgument: - return "Incorrect usage, please use \"mc config help\" ", NewIodine(iodine.New(err, nil)) + return "Incorrect usage, please use \"mc config help\" ", err.Trace() case errAliasExists: - return "Alias name: [" + aliases[0] + "]", NewIodine(iodine.New(err, nil)) + return "Alias name: [" + aliases[0] + "]", err.Trace() case errInvalidAliasName: - return "Alias [" + aliases[0] + "] is reserved word or invalid", NewIodine(iodine.New(err, nil)) + return "Alias [" + aliases[0] + "] is reserved word or invalid", err.Trace() + case errInvalidURL: - return "Alias [" + aliases[1] + "] is invalid URL", NewIodine(iodine.New(err, nil)) + return "Alias [" + aliases[1] + "] is invalid URL", err.Trace() default: // unexpected error - return "Unable to modify config file [" + configPath + "].", NewIodine(iodine.New(err, nil)) + return "Unable to modify config file [" + configPath + "].", err.Trace() } } if arg == "alias" { return "Alias written to [" + configPath + "].", nil } - return "", NewIodine(iodine.New(errUnexpected{}, nil)) + return "", probe.New(errUnexpected{}) } // addAlias - add new aliases -func addAlias(aliases []string) (quick.Config, error) { +func addAlias(aliases []string) (quick.Config, *probe.Error) { if len(aliases) < 2 { - return nil, NewIodine(iodine.New(errInvalidArgument{}, nil)) + return nil, probe.New(errInvalidArgument{}) } conf := newConfigV1() config, err := quick.New(conf) if err != nil { - return nil, NewIodine(iodine.New(err, nil)) + return nil, err.Trace() + } + err = config.Load(mustGetMcConfigPath()) + if err != nil { + return nil, err.Trace() } - config.Load(mustGetMcConfigPath()) aliasName := aliases[0] url := strings.TrimSuffix(aliases[1], "/") if strings.HasPrefix(aliasName, "http") { - return nil, NewIodine(iodine.New(errInvalidAliasName{name: aliasName}, nil)) + return nil, probe.New(errInvalidAliasName{name: aliasName}) } if !strings.HasPrefix(url, "http") { - return nil, NewIodine(iodine.New(errInvalidURL{URL: url}, nil)) + return nil, probe.New(errInvalidURL{URL: url}) } if !isValidAliasName(aliasName) { - return nil, NewIodine(iodine.New(errInvalidAliasName{name: aliasName}, nil)) + return nil, probe.New(errInvalidAliasName{name: aliasName}) } // convert interface{} back to its original struct newConf := config.Data().(*configV1) if _, ok := newConf.Aliases[aliasName]; ok { - return nil, NewIodine(iodine.New(errAliasExists{}, nil)) + return nil, probe.New(errAliasExists{}) } newConf.Aliases[aliasName] = url newConfig, err := quick.New(newConf) if err != nil { - return nil, NewIodine(iodine.New(err, nil)) + return nil, err.Trace() } return newConfig, nil } diff --git a/config.go b/config.go index a101122b..60def2cf 100644 --- a/config.go +++ b/config.go @@ -25,7 +25,7 @@ import ( "github.com/minio/mc/pkg/console" "github.com/minio/mc/pkg/quick" - "github.com/minio/minio/pkg/iodine" + "github.com/minio/minio/pkg/probe" ) type configV1 struct { @@ -46,13 +46,13 @@ func setMcConfigDir(configDir string) { } // getMcConfigDir - construct minio client config folder. -func getMcConfigDir() (string, error) { +func getMcConfigDir() (string, *probe.Error) { if mcCustomConfigDir != "" { return mcCustomConfigDir, nil } u, err := user.Current() if err != nil { - return "", NewIodine(iodine.New(err, nil)) + return "", probe.New(err) } // For windows the path is slightly different switch runtime.GOOS { @@ -66,52 +66,47 @@ func getMcConfigDir() (string, error) { // mustGetMcConfigDir - construct minio client config folder or fail func mustGetMcConfigDir() (configDir string) { configDir, err := getMcConfigDir() - if err != nil { - console.Fatalf("Unable to determine default configuration folder. %s\n", NewIodine(iodine.New(err, nil))) - } + ifFatal(err) return configDir } // createMcConfigDir - create minio client config folder -func createMcConfigDir() error { +func createMcConfigDir() *probe.Error { p, err := getMcConfigDir() if err != nil { - return NewIodine(iodine.New(err, nil)) + return err.Trace() } - err = os.MkdirAll(p, 0700) - if err != nil { - return NewIodine(iodine.New(err, nil)) + if err := os.MkdirAll(p, 0700); err != nil { + return probe.New(err) } return nil } // getMcConfigPath - construct minio client configuration path -func getMcConfigPath() (string, error) { +func getMcConfigPath() (string, *probe.Error) { dir, err := getMcConfigDir() if err != nil { - return "", NewIodine(iodine.New(err, nil)) + return "", err.Trace() } return filepath.Join(dir, mcConfigFile), nil } // mustGetMcConfigPath - similar to getMcConfigPath, ignores errors func mustGetMcConfigPath() string { - p, err := getMcConfigPath() - if err != nil { - console.Fatalf("Unable to determine default config path. %s\n", NewIodine(iodine.New(err, nil))) - } - return p + path, err := getMcConfigPath() + ifFatal(err) + return path } // getMcConfig - reads configuration file and returns config -func getMcConfig() (*configV1, error) { +func getMcConfig() (*configV1, *probe.Error) { if !isMcConfigExists() { - return nil, NewIodine(iodine.New(errInvalidArgument{}, nil)) + return nil, probe.New(errInvalidArgument{}) } configFile, err := getMcConfigPath() if err != nil { - return nil, NewIodine(iodine.New(err, nil)) + return nil, err.Trace() } // Cached in private global variable. @@ -122,12 +117,12 @@ func getMcConfig() (*configV1, error) { conf := newConfigV1() qconf, err := quick.New(conf) if err != nil { - return nil, NewIodine(iodine.New(err, nil)) + return nil, err.Trace() } err = qconf.Load(configFile) if err != nil { - return nil, NewIodine(iodine.New(err, nil)) + return nil, err.Trace() } cache.Put(qconf) return qconf.Data().(*configV1), nil @@ -137,9 +132,7 @@ func getMcConfig() (*configV1, error) { // mustGetMcConfig - reads configuration file and returns configs, exits on error func mustGetMcConfig() *configV1 { config, err := getMcConfig() - if err != nil { - console.Fatalf("Unable to retrieve mc configuration. %s\n", err) - } + ifFatal(err) return config } @@ -149,25 +142,24 @@ func isMcConfigExists() bool { if err != nil { return false } - _, err = os.Stat(configFile) - if err != nil { + if _, err := os.Stat(configFile); err != nil { return false } return true } // writeConfig - write configuration file -func writeConfig(config quick.Config) error { +func writeConfig(config quick.Config) *probe.Error { err := createMcConfigDir() if err != nil { - return NewIodine(iodine.New(err, nil)) + return err.Trace() } configPath, err := getMcConfigPath() if err != nil { - return NewIodine(iodine.New(err, nil)) + return err.Trace() } if err := config.Save(configPath); err != nil { - return NewIodine(iodine.New(err, nil)) + return err.Trace() } return nil } @@ -183,12 +175,10 @@ func migrateConfigV1ToV101() { } conf := newConfigV1() config, err := quick.New(conf) - if err != nil { - console.Fatalln(NewIodine(iodine.New(err, nil))) - } - if err := config.Load(mustGetMcConfigPath()); err != nil { - console.Fatalln(NewIodine(iodine.New(err, nil))) - } + ifFatal(err) + err = config.Load(mustGetMcConfigPath()) + ifFatal(err) + conf = config.Data().(*configV1) // version is the same return if conf.Version == mcCurrentConfigVersion { @@ -214,10 +204,13 @@ func migrateConfigV1ToV101() { conf.Hosts["*.s3*.amazonaws.com"] = s3HostConf } - newConfig, err := quick.New(conf) - if err := newConfig.Save(mustGetMcConfigPath()); err != nil { - console.Fatalln(NewIodine(iodine.New(err, nil))) + { + newConfig, err := quick.New(conf) + ifFatal(err) + err = newConfig.Save(mustGetMcConfigPath()) + ifFatal(err) } + console.Infof("Successfully migrated %s from version: %s to version: %s\n", mustGetMcConfigPath(), mcPreviousConfigVersion, mcCurrentConfigVersion) } @@ -281,11 +274,11 @@ func newConfigV101() *configV1 { } // newConfig - get new config interface -func newConfig() (config quick.Config, err error) { +func newConfig() (config quick.Config, err *probe.Error) { conf := newConfigV101() config, err = quick.New(conf) if err != nil { - return nil, NewIodine(iodine.New(err, nil)) + return nil, err.Trace() } return config, nil } @@ -293,8 +286,6 @@ func newConfig() (config quick.Config, err error) { // mustNewConfig instantiates a new config handler, exists upon error func mustNewConfig() quick.Config { config, err := newConfig() - if err != nil { - console.Fatalf("Unable to instantiate a new config handler. %s\n", NewIodine(iodine.New(err, nil))) - } + ifFatal(err) return config } diff --git a/cp-main.go b/cp-main.go index 218e2620..3aada199 100644 --- a/cp-main.go +++ b/cp-main.go @@ -28,7 +28,6 @@ import ( "github.com/minio/cli" "github.com/minio/mc/pkg/console" - "github.com/minio/minio/pkg/iodine" ) // Help message. @@ -76,7 +75,7 @@ func doCopy(cpURLs copyURLs, bar *barSend, cpQueue <-chan bool, wg *sync.WaitGro }() if cpURLs.Error != nil { - cpURLs.Error = iodine.New(cpURLs.Error, nil) + cpURLs.Error.Trace() statusCh <- cpURLs return } @@ -90,7 +89,7 @@ func doCopy(cpURLs copyURLs, bar *barSend, cpQueue <-chan bool, wg *sync.WaitGro if !globalQuietFlag || !globalJSONFlag { bar.ErrorGet(length) } - cpURLs.Error = NewIodine(iodine.New(err, map[string]string{"URL": cpURLs.SourceContent.Name})) + cpURLs.Error = err.Trace() statusCh <- cpURLs return } @@ -114,7 +113,7 @@ func doCopy(cpURLs copyURLs, bar *barSend, cpQueue <-chan bool, wg *sync.WaitGro if !globalQuietFlag || !globalJSONFlag { bar.ErrorPut(length) } - cpURLs.Error = NewIodine(iodine.New(err, map[string]string{"URL": cpURLs.SourceContent.Name})) + cpURLs.Error = err.Trace() statusCh <- cpURLs return } @@ -154,7 +153,7 @@ func doPrepareCopyURLs(session *sessionV2, trapCh <-chan bool) { break } if cpURLs.Error != nil { - console.Errorln(cpURLs.Error) + ifError(cpURLs.Error) break } @@ -221,7 +220,7 @@ func doCopyCmdSession(session *sessionV2) { session.Header.LastCopied = cpURLs.SourceContent.Name } else { console.Println() - console.Errorf("Failed to copy ‘%s’, %s\n", cpURLs.SourceContent.Name, NewIodine(iodine.New(cpURLs.Error, nil))) + ifError(cpURLs.Error) } case <-trapCh: // Receive interrupt notification. session.Close() diff --git a/cp-url.go b/cp-url.go index b8a66562..16420d61 100644 --- a/cp-url.go +++ b/cp-url.go @@ -23,13 +23,13 @@ import ( "github.com/minio/cli" "github.com/minio/mc/pkg/client" "github.com/minio/mc/pkg/console" - "github.com/minio/minio/pkg/iodine" + "github.com/minio/minio/pkg/probe" ) type copyURLs struct { SourceContent *client.Content TargetContent *client.Content - Error error + Error *probe.Error `json:"-"` } type copyURLsType uint8 @@ -64,7 +64,7 @@ func checkCopySyntax(ctx *cli.Context) { // extract URLs. URLs, err := args2URLs(ctx.Args()) if err != nil { - console.Fatalf("One or more unknown URL types found %s. %s\n", ctx.Args(), NewIodine(iodine.New(err, nil))) + console.Fatalf("One or more unknown URL types found %s. %s\n", ctx.Args(), err.Trace()) } srcURLs := URLs[:len(URLs)-1] @@ -73,15 +73,18 @@ func checkCopySyntax(ctx *cli.Context) { /****** Generic rules *******/ // Recursive URLs are not allowed in target. if isURLRecursive(tgtURL) { - console.Fatalf("Recursive option is not supported for target ‘%s’ argument. %s\n", tgtURL, NewIodine(iodine.New(errInvalidArgument{}, nil))) + console.Fatalf("Recursive option is not supported for target ‘%s’ argument. %s\n", tgtURL, probe.New(errInvalidArgument{})) } - url, err := client.Parse(tgtURL) - if err != nil { - console.Fatalf("Unable to parse target ‘%s’ argument. %s\n", tgtURL, NewIodine(iodine.New(err, nil))) - } - if url.Host != "" { - if url.Path == string(url.Separator) { - console.Fatalf("Bucket creation detected for %s, cloud storage URL's should use ‘mc mb’ to create buckets\n", tgtURL) + // scope locally + { + url, err := client.Parse(tgtURL) + if err != nil { + console.Fatalf("Unable to parse target ‘%s’ argument. %s\n", tgtURL, probe.New(err)) + } + if url.Host != "" { + if url.Path == string(url.Separator) { + console.Fatalf("Bucket creation detected for %s, cloud storage URL's should use ‘mc mb’ to create buckets\n", tgtURL) + } } } switch guessCopyURLType(srcURLs, tgtURL) { @@ -101,26 +104,26 @@ func checkCopySyntax(ctx *cli.Context) { // checkCopySyntaxTypeA verifies if the source and target are valid file arguments. func checkCopySyntaxTypeA(srcURLs []string, tgtURL string) { if len(srcURLs) != 1 { - console.Fatalf("Invalid number of source arguments to copy command. %s\n", NewIodine(iodine.New(errInvalidArgument{}, nil))) + console.Fatalf("Invalid number of source arguments to copy command. %s\n", probe.New(errInvalidArgument{})) } srcURL := srcURLs[0] _, srcContent, err := url2Stat(srcURL) // Source exist?. if err != nil { - console.Fatalf("Unable to stat source ‘%s’. %s\n", srcURL, NewIodine(iodine.New(err, nil))) + console.Fatalf("Unable to stat source ‘%s’. %s\n", srcURL, err.Trace()) } if srcContent.Type.IsDir() { - console.Fatalf("Source ‘%s’ is a folder. Use ‘%s...’ argument to copy this folder and its contents recursively. %s\n", srcURL, srcURL, NewIodine(iodine.New(errInvalidArgument{}, nil))) + console.Fatalf("Source ‘%s’ is a folder. Use ‘%s...’ argument to copy this folder and its contents recursively. %s\n", srcURL, srcURL, probe.New(errInvalidArgument{})) } if !srcContent.Type.IsRegular() { - console.Fatalf("Source ‘%s’ is not a file. %s\n", srcURL, NewIodine(iodine.New(errInvalidArgument{}, nil))) + console.Fatalf("Source ‘%s’ is not a file. %s\n", srcURL, probe.New(errInvalidArgument{})) } _, tgtContent, err := url2Stat(tgtURL) // Target exist?. if err == nil { if !tgtContent.Type.IsRegular() { - console.Fatalf("Target ‘%s’ is not a file. %s\n", tgtURL, NewIodine(iodine.New(errInvalidArgument{}, nil))) + console.Fatalf("Target ‘%s’ is not a file. %s\n", tgtURL, probe.New(errInvalidArgument{})) } } } @@ -128,26 +131,26 @@ func checkCopySyntaxTypeA(srcURLs []string, tgtURL string) { // checkCopySyntaxTypeB verifies if the source is a valid file and target is a valid dir. func checkCopySyntaxTypeB(srcURLs []string, tgtURL string) { if len(srcURLs) != 1 { - console.Fatalf("Invalid number of source arguments to copy command. %s\n", NewIodine(iodine.New(errInvalidArgument{}, nil))) + console.Fatalf("Invalid number of source arguments to copy command. %s\n", probe.New(errInvalidArgument{})) } srcURL := srcURLs[0] _, srcContent, err := url2Stat(srcURL) // Source exist?. if err != nil { - console.Fatalf("Unable to stat source ‘%s’. %s\n", srcURL, NewIodine(iodine.New(err, nil))) + console.Fatalf("Unable to stat source ‘%s’. %s\n", srcURL, probe.New(err)) } if srcContent.Type.IsDir() { - console.Fatalf("Source ‘%s’ is a folder. Use ‘%s...’ argument to copy this folder and its contents recursively. %s\n", srcURL, srcURL, NewIodine(iodine.New(errInvalidArgument{}, nil))) + console.Fatalf("Source ‘%s’ is a folder. Use ‘%s...’ argument to copy this folder and its contents recursively. %s\n", srcURL, srcURL, probe.New(errInvalidArgument{})) } if !srcContent.Type.IsRegular() { - console.Fatalf("Source ‘%s’ is not a file. %s\n", srcURL, NewIodine(iodine.New(errInvalidArgument{}, nil))) + console.Fatalf("Source ‘%s’ is not a file. %s\n", srcURL, probe.New(errInvalidArgument{})) } _, tgtContent, err := url2Stat(tgtURL) // Target exist?. if err == nil { if !tgtContent.Type.IsDir() { - console.Fatalf("Target ‘%s’ is not a folder. %s\n", tgtURL, NewIodine(iodine.New(errInvalidArgument{}, nil))) + console.Fatalf("Target ‘%s’ is not a folder. %s\n", tgtURL, probe.New(errInvalidArgument{})) } } } @@ -155,24 +158,24 @@ func checkCopySyntaxTypeB(srcURLs []string, tgtURL string) { // checkCopySyntaxTypeC verifies if the source is a valid recursive dir and target is a valid dir. func checkCopySyntaxTypeC(srcURLs []string, tgtURL string) { if len(srcURLs) != 1 { - console.Fatalf("Invalid number of source arguments to copy command. %s\n", NewIodine(iodine.New(errInvalidArgument{}, nil))) + console.Fatalf("Invalid number of source arguments to copy command. %s\n", probe.New(errInvalidArgument{})) } srcURL := srcURLs[0] srcURL = stripRecursiveURL(srcURL) _, srcContent, err := url2Stat(srcURL) // Source exist?. if err != nil { - console.Fatalf("Unable to stat source ‘%s’. %s\n", srcURL, NewIodine(iodine.New(err, nil))) + console.Fatalf("Unable to stat source ‘%s’. %s\n", srcURL, err.Trace()) } if srcContent.Type.IsRegular() { // Ellipses is supported only for folders. - console.Fatalf("Source ‘%s’ is not a folder. %s\n", stripRecursiveURL(srcURL), NewIodine(iodine.New(errInvalidArgument{}, nil))) + console.Fatalf("Source ‘%s’ is not a folder. %s\n", stripRecursiveURL(srcURL), probe.New(errInvalidArgument{})) } _, tgtContent, err := url2Stat(tgtURL) // Target exist?. if err == nil { if !tgtContent.Type.IsDir() { - console.Fatalf("Target ‘%s’ is not a folder. %s\n", tgtURL, NewIodine(iodine.New(errInvalidArgument{}, nil))) + console.Fatalf("Target ‘%s’ is not a folder. %s\n", tgtURL, probe.New(errInvalidArgument{})) } } } @@ -185,32 +188,32 @@ func checkCopySyntaxTypeD(srcURLs []string, tgtURL string) { _, srcContent, err := url2Stat(srcURL) // Source exist?. if err != nil { - console.Fatalf("Unable to stat source ‘%s’. %s\n", srcURL, NewIodine(iodine.New(err, nil))) + console.Fatalf("Unable to stat source ‘%s’. %s\n", srcURL, err.Trace()) } if !srcContent.Type.IsDir() { // Ellipses is supported only for folders. - console.Fatalf("Source ‘%s’ is not a folder. %s\n", stripRecursiveURL(srcURL), NewIodine(iodine.New(errInvalidArgument{}, nil))) + console.Fatalf("Source ‘%s’ is not a folder. %s\n", stripRecursiveURL(srcURL), probe.New(errInvalidArgument{})) } } else { // Regular URL. _, srcContent, err := url2Stat(srcURL) // Source exist?. if err != nil { - console.Fatalf("Unable to stat source ‘%s’. %s\n", srcURL, NewIodine(iodine.New(err, nil))) + console.Fatalf("Unable to stat source ‘%s’. %s\n", srcURL, err.Trace()) } if srcContent.Type.IsDir() { - console.Fatalf("Source ‘%s’ is a folder. Use ‘%s...’ argument to copy this folder and its contents recursively. %s\n", srcURL, srcURL, NewIodine(iodine.New(errInvalidArgument{}, nil))) + console.Fatalf("Source ‘%s’ is a folder. Use ‘%s...’ argument to copy this folder and its contents recursively. %s\n", srcURL, srcURL, probe.New(errInvalidArgument{})) } if !srcContent.Type.IsRegular() { - console.Fatalf("Source ‘%s’ is not a file. %s\n", srcURL, NewIodine(iodine.New(errInvalidArgument{}, nil))) + console.Fatalf("Source ‘%s’ is not a file. %s\n", srcURL, probe.New(errInvalidArgument{})) } } } _, tgtContent, err := url2Stat(tgtURL) // Target exist?. if err != nil { - console.Fatalf("Unable to stat target ‘%s’. %s\n", tgtURL, NewIodine(iodine.New(err, nil))) + console.Fatalf("Unable to stat target ‘%s’. %s\n", tgtURL, err.Trace()) } if !tgtContent.Type.IsDir() { - console.Fatalf("Target ‘%s’ is not a folder. %s\n", tgtURL, NewIodine(iodine.New(errInvalidArgument{}, nil))) + console.Fatalf("Target ‘%s’ is not a folder. %s\n", tgtURL, probe.New(errInvalidArgument{})) } } @@ -250,11 +253,11 @@ func prepareCopyURLsTypeA(sourceURL string, targetURL string) copyURLs { _, sourceContent, err := url2Stat(sourceURL) if err != nil { // Source does not exist or insufficient privileges. - return copyURLs{Error: NewIodine(iodine.New(err, nil))} + return copyURLs{Error: err.Trace()} } if !sourceContent.Type.IsRegular() { // Source is not a regular file - return copyURLs{Error: NewIodine(iodine.New(errInvalidSource{URL: sourceURL}, nil))} + return copyURLs{Error: probe.New(errInvalidSource{URL: sourceURL})} } // All OK.. We can proceed. Type A sourceContent.Name = sourceURL @@ -267,26 +270,27 @@ func prepareCopyURLsTypeB(sourceURL string, targetURL string) copyURLs { _, sourceContent, err := url2Stat(sourceURL) if err != nil { // Source does not exist or insufficient privileges. - return copyURLs{Error: NewIodine(iodine.New(err, nil))} + return copyURLs{Error: err.Trace()} } if !sourceContent.Type.IsRegular() { // Source is not a regular file. - return copyURLs{Error: NewIodine(iodine.New(errInvalidSource{URL: sourceURL}, nil))} + return copyURLs{Error: probe.New(errInvalidSource{URL: sourceURL})} } // All OK.. We can proceed. Type B: source is a file, target is a folder and exists. - sourceURLParse, err := client.Parse(sourceURL) - if err != nil { - return copyURLs{Error: NewIodine(iodine.New(errInvalidSource{URL: sourceURL}, nil))} - } + { + sourceURLParse, err := client.Parse(sourceURL) + if err != nil { + return copyURLs{Error: probe.New(errInvalidSource{URL: sourceURL})} + } - targetURLParse, err := client.Parse(targetURL) - if err != nil { - return copyURLs{Error: NewIodine(iodine.New(errInvalidTarget{URL: targetURL}, nil))} + targetURLParse, err := client.Parse(targetURL) + if err != nil { + return copyURLs{Error: probe.New(errInvalidTarget{URL: targetURL})} + } + targetURLParse.Path = filepath.Join(targetURLParse.Path, filepath.Base(sourceURLParse.Path)) + return prepareCopyURLsTypeA(sourceURL, targetURLParse.String()) } - - targetURLParse.Path = filepath.Join(targetURLParse.Path, filepath.Base(sourceURLParse.Path)) - return prepareCopyURLsTypeA(sourceURL, targetURLParse.String()) } // SINGLE SOURCE - Type C: copy(d1..., d2) -> []copy(d1/f, d1/d2/f) -> []A @@ -297,7 +301,7 @@ func prepareCopyURLsTypeC(sourceURL, targetURL string) <-chan copyURLs { defer close(copyURLsCh) if !isURLRecursive(sourceURL) { // Source is not of recursive type. - copyURLsCh <- copyURLs{Error: NewIodine(iodine.New(errSourceNotRecursive{URL: sourceURL}, nil))} + copyURLsCh <- copyURLs{Error: probe.New(errSourceNotRecursive{URL: sourceURL})} return } @@ -306,20 +310,20 @@ func prepareCopyURLsTypeC(sourceURL, targetURL string) <-chan copyURLs { sourceClient, sourceContent, err := url2Stat(sourceURL) if err != nil { // Source does not exist or insufficient privileges. - copyURLsCh <- copyURLs{Error: NewIodine(iodine.New(err, nil))} + copyURLsCh <- copyURLs{Error: err.Trace()} return } if !sourceContent.Type.IsDir() { // Source is not a dir. - copyURLsCh <- copyURLs{Error: NewIodine(iodine.New(errSourceIsNotDir{URL: sourceURL}, nil))} + copyURLsCh <- copyURLs{Error: probe.New(errSourceIsNotDir{URL: sourceURL})} return } for sourceContent := range sourceClient.List(true) { if sourceContent.Err != nil { // Listing failed. - copyURLsCh <- copyURLs{Error: NewIodine(iodine.New(sourceContent.Err, nil))} + copyURLsCh <- copyURLs{Error: sourceContent.Err.Trace()} continue } @@ -331,13 +335,13 @@ func prepareCopyURLsTypeC(sourceURL, targetURL string) <-chan copyURLs { // All OK.. We can proceed. Type B: source is a file, target is a folder and exists. sourceURLParse, err := client.Parse(sourceURL) if err != nil { - copyURLsCh <- copyURLs{Error: NewIodine(iodine.New(errInvalidSource{URL: sourceURL}, nil))} + copyURLsCh <- copyURLs{Error: probe.New(errInvalidSource{URL: sourceURL})} continue } targetURLParse, err := client.Parse(targetURL) if err != nil { - copyURLsCh <- copyURLs{Error: NewIodine(iodine.New(errInvalidTarget{URL: targetURL}, nil))} + copyURLsCh <- copyURLs{Error: probe.New(errInvalidTarget{URL: targetURL})} continue } @@ -347,7 +351,7 @@ func prepareCopyURLsTypeC(sourceURL, targetURL string) <-chan copyURLs { sourceContentURL := sourceURLDelimited + sourceContentName sourceContentParse, err := client.Parse(sourceContentURL) if err != nil { - copyURLsCh <- copyURLs{Error: NewIodine(iodine.New(errInvalidSource{URL: sourceContentName}, nil))} + copyURLsCh <- copyURLs{Error: probe.New(errInvalidSource{URL: sourceContentName})} continue } @@ -369,7 +373,7 @@ func prepareCopyURLsTypeD(sourceURLs []string, targetURL string) <-chan copyURLs if sourceURLs == nil { // Source list is empty. - copyURLsCh <- copyURLs{Error: NewIodine(iodine.New(errSourceListEmpty{}, nil))} + copyURLsCh <- copyURLs{Error: probe.New(errSourceListEmpty{})} return } @@ -407,7 +411,7 @@ func prepareCopyURLs(sourceURLs []string, targetURL string) <-chan copyURLs { copyURLsCh <- cURLs } default: - copyURLsCh <- copyURLs{Error: NewIodine(iodine.New(errInvalidArgument{}, nil))} + copyURLsCh <- copyURLs{Error: probe.New(errInvalidArgument{})} } }(sourceURLs, targetURL, copyURLsCh) diff --git a/diff-main.go b/diff-main.go index 93966421..1bce03c9 100644 --- a/diff-main.go +++ b/diff-main.go @@ -19,7 +19,7 @@ package main import ( "github.com/minio/cli" "github.com/minio/mc/pkg/console" - "github.com/minio/minio/pkg/iodine" + "github.com/minio/minio/pkg/probe" ) // Help message. @@ -61,25 +61,11 @@ func runDiffCmd(ctx *cli.Context) { firstURL := ctx.Args().First() secondURL := ctx.Args()[1] - var err error + var err *probe.Error firstURL, err = getExpandedURL(firstURL, config.Aliases) - if err != nil { - switch e := iodine.ToError(err).(type) { - case errUnsupportedScheme: - console.Fatalf("Unknown type of URL %s. %s\n", e.url, err) - default: - console.Fatalf("Unable to parse argument %s. %s\n", firstURL, err) - } - } + ifFatal(err) secondURL, err = getExpandedURL(secondURL, config.Aliases) - if err != nil { - switch e := iodine.ToError(err).(type) { - case errUnsupportedScheme: - console.Fatalf("Unknown type of URL %s. %s\n", e.url, err) - default: - console.Fatalf("Unable to parse argument %s. %s\n", secondURL, err) - } - } + ifFatal(err) if isURLRecursive(secondURL) { console.Fatalf("Second URL cannot be recursive. %s\n", errInvalidArgument{}) } diff --git a/diff.go b/diff.go index 5306a3cd..2e241697 100644 --- a/diff.go +++ b/diff.go @@ -24,7 +24,7 @@ import ( "github.com/minio/mc/pkg/client" "github.com/minio/mc/pkg/console" - "github.com/minio/minio/pkg/iodine" + "github.com/minio/minio/pkg/probe" "github.com/tchap/go-patricia/patricia" ) @@ -54,18 +54,17 @@ func mustURLJoinPath(url1, url2 string) string { } // urlJoinPath Join a path to existing URL -func urlJoinPath(url1, url2 string) (newURLStr string, err error) { +func urlJoinPath(url1, url2 string) (string, *probe.Error) { u1, err := client.Parse(url1) if err != nil { - return "", NewIodine(iodine.New(err, nil)) + return "", probe.New(err) } u2, err := client.Parse(url2) if err != nil { - return "", NewIodine(iodine.New(err, nil)) + return "", probe.New(err) } u1.Path = filepath.Join(u1.Path, u2.Path) - newURLStr = u1.String() - return newURLStr, nil + return u1.String(), nil } func doDiffInRoutine(firstURL, secondURL string, recursive bool, ch chan diff) { @@ -74,7 +73,7 @@ func doDiffInRoutine(firstURL, secondURL string, recursive bool, ch chan diff) { if err != nil { ch <- diff{ message: "Failed to stat ‘" + firstURL + "’", - err: NewIodine(iodine.New(err, nil)), + err: err.Trace(), } return } @@ -82,7 +81,7 @@ func doDiffInRoutine(firstURL, secondURL string, recursive bool, ch chan diff) { if err != nil { ch <- diff{ message: "Failed to stat ‘" + secondURL + "’", - err: NewIodine(iodine.New(err, nil)), + err: err.Trace(), } return } @@ -93,7 +92,7 @@ func doDiffInRoutine(firstURL, secondURL string, recursive bool, ch chan diff) { if err != nil { ch <- diff{ message: "Unable to construct new URL from ‘" + secondURL + "’ using ‘" + firstURL, - err: NewIodine(iodine.New(err, nil)), + err: err.Trace(), } return } @@ -155,7 +154,7 @@ func doDiffObjects(firstURL, secondURL string, ch chan diff) { default: ch <- diff{ message: "‘" + firstURL + "’ is not an object. Please report this bug with ‘--debug’ option.", - err: NewIodine(iodine.New(errNotAnObject{url: firstURL}, nil)), + err: probe.New(errNotAnObject{url: firstURL}), } return } @@ -173,7 +172,7 @@ func dodiff(firstClnt, secondClnt client.Client, ch chan diff) { if contentCh.Err != nil { ch <- diff{ message: "Failed to list ‘" + firstClnt.URL().String() + "’", - err: NewIodine(iodine.New(contentCh.Err, nil)), + err: contentCh.Err.Trace(), } return } @@ -181,7 +180,7 @@ func dodiff(firstClnt, secondClnt client.Client, ch chan diff) { if err != nil { ch <- diff{ message: "Unable to construct new URL from ‘" + firstClnt.URL().String() + "’ using ‘" + contentCh.Content.Name + "’", - err: NewIodine(iodine.New(err, nil)), + err: err.Trace(), } return } @@ -189,7 +188,7 @@ func dodiff(firstClnt, secondClnt client.Client, ch chan diff) { if err != nil { ch <- diff{ message: "Unable to construct new URL from ‘" + secondClnt.URL().String() + "’ using ‘" + contentCh.Content.Name + "’", - err: NewIodine(iodine.New(err, nil)), + err: err.Trace(), } return } @@ -244,7 +243,7 @@ func dodiffRecursive(firstClnt, secondClnt client.Client, ch chan diff) { if firstContentCh.Err != nil { ch <- diff{ message: "Failed to list ‘" + firstClnt.URL().String() + "’", - err: NewIodine(iodine.New(firstContentCh.Err, nil)), + err: firstContentCh.Err.Trace(), } return } @@ -258,7 +257,7 @@ func dodiffRecursive(firstClnt, secondClnt client.Client, ch chan diff) { if secondContentCh.Err != nil { ch <- diff{ message: "Failed to list ‘" + secondClnt.URL().String() + "’", - err: NewIodine(iodine.New(secondContentCh.Err, nil)), + err: secondContentCh.Err.Trace(), } return } diff --git a/error.go b/error.go new file mode 100644 index 00000000..98bed067 --- /dev/null +++ b/error.go @@ -0,0 +1,37 @@ +package main + +import ( + "github.com/minio/mc/pkg/console" + "github.com/minio/minio/pkg/probe" +) + +func ifFatal(err *probe.Error) { + switch err { + case nil: + // nothing to print + default: + if !globalDebugFlag { + console.Fatalln(err.ToError()) + } + console.Fatalln(err) + } +} + +func ifError(err error) { + switch e := err.(type) { + case *probe.Error: + switch e { + case nil: + // nothing to print + default: + if !globalDebugFlag { + console.Errorln(e.ToError()) + } + console.Errorln(err) + } + case nil: + // nothing to print + default: + console.Errorln(err) + } +} diff --git a/first-time.go b/first-time.go index 75bc848a..3644ac2f 100644 --- a/first-time.go +++ b/first-time.go @@ -24,7 +24,6 @@ import ( "strings" "github.com/minio/mc/pkg/console" - "github.com/minio/minio/pkg/iodine" ) var minWindowsGolangVersion = "1.5" @@ -112,19 +111,14 @@ func firstTimeRun() { console.Fatalf("Unable to create ‘mc’ config folder. %s\n", err) } config, err := newConfig() - if err != nil { - console.Fatalln(NewIodine(iodine.New(err, nil))) - } + ifFatal(err) err = writeConfig(config) - if err != nil { - console.Fatalln(NewIodine(iodine.New(err, nil))) - } + ifFatal(err) console.Infoln("Configuration written to [" + mustGetMcConfigPath() + "]. Please update your access credentials.") } if !isSessionDirExists() { - if err := createSessionDir(); err != nil { - console.Fatalf("Unable to create ‘mc’ session folder. %s\n", err) - } + err := createSessionDir() + ifFatal(err) } checkGolangVersion() } diff --git a/globals.go b/globals.go index 3e154664..9c414ab8 100644 --- a/globals.go +++ b/globals.go @@ -17,8 +17,6 @@ // This package contains all the global variables and constants. ONLY TO BE ACCESSED VIA GET/SET FUNCTIONS. package main -import "github.com/minio/minio/pkg/iodine" - var ( globalQuietFlag = false // Quiet flag set via command line globalForceFlag = false // Force flag set via command line @@ -54,11 +52,3 @@ const ( const ( exampleHostURL = "YOUR-EXAMPLE.COM" ) - -// NewIodine - iodine wrapper for debug flag behavior -func NewIodine(err error) error { - if !globalDebugFlag { - return iodine.ToError(err) - } - return err -} diff --git a/hostconfig.go b/hostconfig.go index 74dab6da..8c4ca670 100644 --- a/hostconfig.go +++ b/hostconfig.go @@ -20,7 +20,7 @@ import ( "path/filepath" "github.com/minio/mc/pkg/client" - "github.com/minio/minio/pkg/iodine" + "github.com/minio/minio/pkg/probe" ) type hostConfig struct { @@ -29,32 +29,33 @@ type hostConfig struct { } // getHostConfig retrieves host specific configuration such as access keys, certs. -func getHostConfig(URL string) (hostConfig, error) { +func getHostConfig(URL string) (hostConfig, *probe.Error) { config, err := getMcConfig() if err != nil { - return hostConfig{}, NewIodine(iodine.New(err, nil)) + return hostConfig{}, err.Trace() } - url, err := client.Parse(URL) - if err != nil { - return hostConfig{}, NewIodine(iodine.New(errInvalidURL{URL: URL}, nil)) - } - // No host matching or keys needed for filesystem requests - if url.Type == client.Filesystem { - hostCfg := hostConfig{ - AccessKeyID: "", - SecretAccessKey: "", - } - return hostCfg, nil - } - - for globURL, hostCfg := range config.Hosts { - match, err := filepath.Match(globURL, url.Host) + { + url, err := client.Parse(URL) if err != nil { - return hostConfig{}, NewIodine(iodine.New(errInvalidGlobURL{glob: globURL, request: URL}, nil)) + return hostConfig{}, probe.New(err) } - if match { + // No host matching or keys needed for filesystem requests + if url.Type == client.Filesystem { + hostCfg := hostConfig{ + AccessKeyID: "", + SecretAccessKey: "", + } return hostCfg, nil } + for globURL, hostCfg := range config.Hosts { + match, err := filepath.Match(globURL, url.Host) + if err != nil { + return hostConfig{}, probe.New(errInvalidGlobURL{glob: globURL, request: URL}) + } + if match { + return hostCfg, nil + } + } } - return hostConfig{}, NewIodine(iodine.New(errNoMatchingHost{}, nil)) + return hostConfig{}, probe.New(errNoMatchingHost{}) } diff --git a/ls-main.go b/ls-main.go index 1f2f0f89..c00db5be 100644 --- a/ls-main.go +++ b/ls-main.go @@ -18,8 +18,7 @@ package main import ( "github.com/minio/cli" - "github.com/minio/mc/pkg/console" - "github.com/minio/minio/pkg/iodine" + "github.com/minio/minio/pkg/probe" ) // Help message. @@ -84,32 +83,23 @@ func runListCmd(ctx *cli.Context) { config := mustGetMcConfig() for _, arg := range args { targetURL, err := getExpandedURL(arg, config.Aliases) - if err != nil { - switch e := iodine.ToError(err).(type) { - case errUnsupportedScheme: - console.Fatalf("Unknown type of URL %s. %s\n", e.url, err) - default: - console.Fatalf("Unable to parse argument %s. %s\n", arg, err) - } - } + ifFatal(err) // if recursive strip off the "..." newTargetURL := stripRecursiveURL(targetURL) err = doListCmd(newTargetURL, isURLRecursive(targetURL)) - if err != nil { - console.Fatalf("Failed to list : %s. %s\n", targetURL, err) - } + ifFatal(err) } } // doListCmd list files on target -func doListCmd(targetURL string, recursive bool) error { +func doListCmd(targetURL string, recursive bool) *probe.Error { clnt, err := target2Client(targetURL) if err != nil { - return NewIodine(iodine.New(err, map[string]string{"Target": targetURL})) + return err.Trace() } err = doList(clnt, recursive) if err != nil { - return NewIodine(iodine.New(err, map[string]string{"Target": targetURL})) + return err.Trace() } return nil } diff --git a/ls.go b/ls.go index c09f84ae..5538222c 100644 --- a/ls.go +++ b/ls.go @@ -25,7 +25,7 @@ import ( "github.com/dustin/go-humanize" "github.com/minio/mc/pkg/client" "github.com/minio/mc/pkg/console" - "github.com/minio/minio/pkg/iodine" + "github.com/minio/minio/pkg/probe" ) /// ls - related internal functions @@ -72,18 +72,18 @@ func parseContent(c *client.Content) Content { } // doList - list all entities inside a folder -func doList(clnt client.Client, recursive bool) error { - var err error +func doList(clnt client.Client, recursive bool) *probe.Error { + var err *probe.Error for contentCh := range clnt.List(recursive) { if contentCh.Err != nil { - switch err := iodine.ToError(contentCh.Err).(type) { + switch contentCh.Err.ToError().(type) { // handle this specifically for filesystem case client.ISBrokenSymlink: - console.Errorln(NewIodine(iodine.New(err, nil)).Error()) + ifError(contentCh.Err) continue } - if os.IsNotExist(iodine.ToError(contentCh.Err)) || os.IsPermission(iodine.ToError(contentCh.Err)) { - console.Errorln(NewIodine(iodine.New(contentCh.Err, nil)).Error()) + if os.IsNotExist(contentCh.Err.ToError()) || os.IsPermission(contentCh.Err.ToError()) { + ifError(contentCh.Err) continue } err = contentCh.Err @@ -92,7 +92,7 @@ func doList(clnt client.Client, recursive bool) error { console.Print(parseContent(contentCh.Content)) } if err != nil { - return NewIodine(iodine.New(err, map[string]string{"Target": clnt.URL().String()})) + return err.Trace() } return nil } diff --git a/main.go b/main.go index a8622120..c315fdf5 100644 --- a/main.go +++ b/main.go @@ -36,11 +36,10 @@ func checkConfig() { } // Ensures config file is sane - _, err = getMcConfig() - if err != nil { - console.Fatalf("Unable to read config file. %s\n", err) + { + _, err := getMcConfig() + ifFatal(err) } - } func migrate() { diff --git a/mb-main.go b/mb-main.go index 0dbb7ece..abf58d34 100644 --- a/mb-main.go +++ b/mb-main.go @@ -20,9 +20,8 @@ import ( "fmt" "github.com/minio/cli" - "github.com/minio/mc/pkg/client" "github.com/minio/mc/pkg/console" - "github.com/minio/minio/pkg/iodine" + "github.com/minio/minio/pkg/probe" ) // Help message. @@ -63,40 +62,25 @@ func runMakeBucketCmd(ctx *cli.Context) { config := mustGetMcConfig() for _, arg := range ctx.Args() { targetURL, err := getExpandedURL(arg, config.Aliases) - if err != nil { - switch e := iodine.ToError(err).(type) { - case errUnsupportedScheme: - console.Fatalf("Unknown type of URL %s. %s\n", e.url, err) - default: - console.Fatalf("Unable to parse argument %s. %s\n", arg, err) - } - } + ifFatal(err) msg, err := doMakeBucketCmd(targetURL) - if err != nil { - console.Fatalln(msg) - } + fmt.Println(msg) + ifFatal(err) console.Infoln(msg) } } // doMakeBucketCmd - -func doMakeBucketCmd(targetURL string) (string, error) { - var err error - var clnt client.Client - clnt, err = target2Client(targetURL) +func doMakeBucketCmd(targetURL string) (string, *probe.Error) { + clnt, err := target2Client(targetURL) if err != nil { msg := fmt.Sprintf("Unable to initialize client for ‘%s’", targetURL) - return msg, NewIodine(iodine.New(err, nil)) + return msg, err.Trace() } - return doMakeBucket(clnt) -} - -// doMakeBucket - wrapper around MakeBucket() API -func doMakeBucket(clnt client.Client) (string, error) { - err := clnt.MakeBucket() + err = clnt.MakeBucket() if err != nil { msg := fmt.Sprintf("Failed to create bucket for URL ‘%s’", clnt.URL().String()) - return msg, NewIodine(iodine.New(err, nil)) + return msg, err.Trace() } return "Bucket created successfully : " + clnt.URL().String(), nil } diff --git a/mb_access_test.go b/mb_access_test.go index 433a55c2..6d68a213 100644 --- a/mb_access_test.go +++ b/mb_access_test.go @@ -34,19 +34,19 @@ func (s *CmdTestSuite) TestMbAndAccessCmd(c *C) { _, err = doMakeBucketCmd(filepath.Join(root, "bucket")) c.Assert(err, IsNil) - _, err = doUpdateAccessCmd(filepath.Join(root, "bucket"), "public-read-write") + err = doUpdateAccessCmd(filepath.Join(root, "bucket"), "public-read-write") c.Assert(err, IsNil) - _, err = doUpdateAccessCmd(filepath.Join(root, "bucket"), "invalid") + err = doUpdateAccessCmd(filepath.Join(root, "bucket"), "invalid") c.Assert(err, Not(IsNil)) _, err = doMakeBucketCmd(server.URL + "/bucket") c.Assert(err, IsNil) - _, err = doUpdateAccessCmd(server.URL+"/bucket", "public-read-write") + err = doUpdateAccessCmd(server.URL+"/bucket", "public-read-write") c.Assert(err, IsNil) - _, err = doUpdateAccessCmd(server.URL+"/bucket", "invalid") + err = doUpdateAccessCmd(server.URL+"/bucket", "invalid") c.Assert(err, Not(IsNil)) } diff --git a/mirror-main.go b/mirror-main.go index bd79eb7b..a47f3c61 100644 --- a/mirror-main.go +++ b/mirror-main.go @@ -28,7 +28,7 @@ import ( "github.com/minio/cli" "github.com/minio/mc/pkg/console" - "github.com/minio/minio/pkg/iodine" + "github.com/minio/minio/pkg/probe" ) // Help message. @@ -73,7 +73,7 @@ func doMirror(sURLs mirrorURLs, bar *barSend, mirrorQueueCh <-chan bool, wg *syn }() if sURLs.Error != nil { // Errorneous sURLs passed. - sURLs.Error = iodine.New(sURLs.Error, nil) + sURLs.Error = sURLs.Error.Trace() statusCh <- sURLs return } @@ -87,7 +87,7 @@ func doMirror(sURLs mirrorURLs, bar *barSend, mirrorQueueCh <-chan bool, wg *syn if !globalQuietFlag || !globalJSONFlag { bar.ErrorGet(int64(length)) } - sURLs.Error = iodine.New(err, nil) + sURLs.Error = err.Trace() statusCh <- sURLs return } @@ -115,7 +115,7 @@ func doMirror(sURLs mirrorURLs, bar *barSend, mirrorQueueCh <-chan bool, wg *syn if !globalQuietFlag || !globalJSONFlag { bar.ErrorPut(int64(length)) } - sURLs.Error = iodine.New(err, nil) + sURLs.Error = err.Trace() statusCh <- sURLs return } @@ -152,7 +152,7 @@ func doPrepareMirrorURLs(session *sessionV2, trapCh <-chan bool) { break } if sURLs.Error != nil { - console.Errorln(sURLs.Error) + ifError(sURLs.Error) break } if sURLs.isEmpty() { @@ -161,7 +161,7 @@ func doPrepareMirrorURLs(session *sessionV2, trapCh <-chan bool) { jsonData, err := json.Marshal(sURLs) if err != nil { session.Close() - console.Fatalf("Unable to marshal URLs to JSON. %s\n", err) + console.Fatalf("Unable to marshal URLs to JSON. %s\n", probe.New(err)) } fmt.Fprintln(dataFP, string(jsonData)) scanBar(sURLs.SourceContent.Name) @@ -221,7 +221,7 @@ func doMirrorCmdSession(session *sessionV2) { session.Header.LastCopied = sURLs.SourceContent.Name } else { console.Println() - console.Errorf("Failed to mirror ‘%s’, %s\n", sURLs.SourceContent.Name, NewIodine(sURLs.Error)) + ifError(sURLs.Error) } case <-trapCh: // Receive interrupt notification. session.Close() diff --git a/mirror-url.go b/mirror-url.go index cf29eca0..f4a6a100 100644 --- a/mirror-url.go +++ b/mirror-url.go @@ -24,14 +24,14 @@ import ( "github.com/minio/cli" "github.com/minio/mc/pkg/client" "github.com/minio/mc/pkg/console" - "github.com/minio/minio/pkg/iodine" + "github.com/minio/minio/pkg/probe" "github.com/tchap/go-patricia/patricia" ) type mirrorURLs struct { SourceContent *client.Content TargetContents []*client.Content - Error error `json:"-"` + Error *probe.Error `json:"-"` } func (m mirrorURLs) isEmpty() bool { @@ -58,7 +58,7 @@ func checkMirrorSyntax(ctx *cli.Context) { // extract URLs. URLs, err := args2URLs(ctx.Args()) if err != nil { - console.Fatalf("One or more unknown URL types found %s. %s\n", ctx.Args(), NewIodine(iodine.New(err, nil))) + console.Fatalf("One or more unknown URL types found %s. %s\n", ctx.Args(), err.Trace()) } srcURL := URLs[0] @@ -70,7 +70,7 @@ func checkMirrorSyntax(ctx *cli.Context) { _, srcContent, err := url2Stat(srcURL) // Source exist?. if err != nil { - console.Fatalf("Unable to stat source ‘%s’. %s\n", srcURL, NewIodine(iodine.New(err, nil))) + console.Fatalf("Unable to stat source ‘%s’. %s\n", srcURL, err.Trace()) } if !srcContent.Type.IsRegular() { if srcContent.Type.IsDir() { @@ -83,7 +83,7 @@ func checkMirrorSyntax(ctx *cli.Context) { for _, tgtURL := range tgtURLs { url, err := client.Parse(tgtURL) if err != nil { - console.Fatalf("Unable to parse target ‘%s’ argument. %s\n", tgtURL, NewIodine(iodine.New(err, nil))) + console.Fatalf("Unable to parse target ‘%s’ argument. %s\n", tgtURL, err) } if url.Host != "" { if url.Path == string(url.Separator) { @@ -93,23 +93,20 @@ func checkMirrorSyntax(ctx *cli.Context) { } if len(tgtURLs) == 0 && tgtURLs == nil { - console.Fatalf("Invalid number of target arguments to mirror command. %s\n", NewIodine(iodine.New(errInvalidArgument{}, nil))) + console.Fatalf("Invalid number of target arguments to mirror command. %s\n", probe.New(errInvalidArgument{})) } srcURL = stripRecursiveURL(srcURL) _, srcContent, err := url2Stat(srcURL) - // Source exist?. - if err != nil { - console.Fatalf("Unable to stat source ‘%s’. %s\n", srcURL, NewIodine(iodine.New(err, nil))) - } + ifFatal(err) if srcContent.Type.IsRegular() { // Ellipses is supported only for folders. - console.Fatalf("Source ‘%s’ is not a folder. %s\n", stripRecursiveURL(srcURL), NewIodine(iodine.New(err, nil))) + console.Fatalf("Source ‘%s’ is not a folder. %s\n", stripRecursiveURL(srcURL), probe.New(errSourceIsNotDir{})) } for _, tgtURL := range tgtURLs { _, content, err := url2Stat(tgtURL) if err == nil { if !content.Type.IsDir() { - console.Fatalf("One of the target ‘%s’ is not a folder. cannot have mixtures of directories and files while copying directories recursively. %s\n", tgtURL, NewIodine(iodine.New(errInvalidArgument{}, nil))) + console.Fatalf("One of the target ‘%s’ is not a folder. cannot have mixtures of directories and files while copying directories recursively. %s\n", tgtURL, probe.New(errInvalidArgument{})) } } } @@ -128,6 +125,7 @@ func deltaSourceTargets(sourceClnt client.Client, targetClnts []client.Client) < defer wg.Done() for sourceContentCh := range sourceClnt.List(true) { if sourceContentCh.Err != nil { + mirrorURLsCh <- mirrorURLs{Error: sourceContentCh.Err.Trace()} return } sourceTrie.Insert(patricia.Prefix(sourceContentCh.Content.Name), sourceContentCh.Content.Size) @@ -141,6 +139,7 @@ func deltaSourceTargets(sourceClnt client.Client, targetClnts []client.Client) < targetTrie := patricia.NewTrie() for targetContentCh := range targetClnt.List(true) { if targetContentCh.Err != nil { + mirrorURLsCh <- mirrorURLs{Error: targetContentCh.Err.Trace()} return } targetTrie.Insert(patricia.Prefix(targetContentCh.Content.Name), struct{}{}) @@ -190,7 +189,7 @@ func prepareMirrorURLs(sourceURL string, targetURLs []string) <-chan mirrorURLs defer close(mirrorURLsCh) sourceClnt, err := url2Client(stripRecursiveURL(sourceURL)) if err != nil { - mirrorURLsCh <- mirrorURLs{Error: NewIodine(iodine.New(err, nil))} + mirrorURLsCh <- mirrorURLs{Error: err.Trace()} return } targetClnts := make([]client.Client, len(targetURLs)) @@ -198,19 +197,19 @@ func prepareMirrorURLs(sourceURL string, targetURLs []string) <-chan mirrorURLs targetURL = stripRecursiveURL(targetURL) targetClnt, targetContent, err := url2Stat(targetURL) if err != nil { - mirrorURLsCh <- mirrorURLs{Error: NewIodine(iodine.New(err, nil))} + mirrorURLsCh <- mirrorURLs{Error: err.Trace()} return } // if one of the targets is not dir exit if !targetContent.Type.IsDir() { - mirrorURLsCh <- mirrorURLs{Error: NewIodine(iodine.New(errInvalidTarget{URL: targetURL}, nil))} + mirrorURLsCh <- mirrorURLs{Error: probe.New(errInvalidTarget{URL: targetURL})} return } // special case, be extremely careful before changing this behavior - will lead to data loss newTargetURL := strings.TrimSuffix(targetURL, string(targetClnt.URL().Separator)) + string(targetClnt.URL().Separator) targetClnt, err = url2Client(newTargetURL) if err != nil { - mirrorURLsCh <- mirrorURLs{Error: NewIodine(iodine.New(err, nil))} + mirrorURLsCh <- mirrorURLs{Error: err.Trace()} return } targetClnts[i] = targetClnt diff --git a/pkg/client/client.go b/pkg/client/client.go index f278388a..d992470f 100644 --- a/pkg/client/client.go +++ b/pkg/client/client.go @@ -20,21 +20,23 @@ import ( "io" "os" "time" + + "github.com/minio/minio/pkg/probe" ) // Client - client interface type Client interface { // Common operations - Stat() (content *Content, err error) + Stat() (content *Content, err *probe.Error) List(recursive bool) <-chan ContentOnChannel // Bucket operations - MakeBucket() error - SetBucketACL(acl string) error + MakeBucket() *probe.Error + SetBucketACL(acl string) *probe.Error // Object operations - GetObject(offset, length int64) (body io.ReadCloser, size int64, err error) - PutObject(size int64, data io.Reader) error + GetObject(offset, length int64) (body io.ReadCloser, size int64, err *probe.Error) + PutObject(size int64, data io.Reader) *probe.Error // URL returns back internal url URL() *URL @@ -43,7 +45,7 @@ type Client interface { // ContentOnChannel - List contents on channel type ContentOnChannel struct { Content *Content - Err error + Err *probe.Error } // Content container for content metadata diff --git a/pkg/client/fs/fs.go b/pkg/client/fs/fs.go index e9fd4a0f..e186273c 100644 --- a/pkg/client/fs/fs.go +++ b/pkg/client/fs/fs.go @@ -25,7 +25,7 @@ import ( "io/ioutil" "github.com/minio/mc/pkg/client" - "github.com/minio/minio/pkg/iodine" + "github.com/minio/minio/pkg/probe" ) type fsClient struct { @@ -33,16 +33,11 @@ type fsClient struct { } // New - instantiate a new fs client -func New(path string) (client.Client, error) { +func New(path string) (client.Client, *probe.Error) { if strings.TrimSpace(path) == "" { - return nil, iodine.New(client.EmptyPath{}, nil) + return nil, probe.New(client.EmptyPath{}) } - var err error - path, err = normalizePath(path) - if err != nil { - return nil, iodine.New(err, nil) - } - return &fsClient{path: path}, nil + return &fsClient{path: normalizePath(path)}, nil } // URL get url @@ -54,7 +49,7 @@ func (f *fsClient) URL() *client.URL { /// Object operations // fsStat - wrapper function to get file stat -func (f *fsClient) fsStat() (os.FileInfo, error) { +func (f *fsClient) fsStat() (os.FileInfo, *probe.Error) { fpath := f.path // Golang strips trailing / if you clean(..) or // EvalSymlinks(..). Adding '.' prevents it from doing so. @@ -64,33 +59,33 @@ func (f *fsClient) fsStat() (os.FileInfo, error) { // Resolve symlinks fpath, err := filepath.EvalSymlinks(fpath) if os.IsNotExist(err) { - return nil, iodine.New(err, nil) + return nil, probe.New(err) } if err != nil { - return nil, iodine.New(err, nil) + return nil, probe.New(err) } st, err := os.Stat(fpath) if os.IsNotExist(err) { - return nil, iodine.New(client.NotFound{Path: fpath}, nil) + return nil, probe.New(client.NotFound{Path: fpath}) } if err != nil { - return nil, iodine.New(err, nil) + return nil, probe.New(err) } return st, nil } // PutObject - create a new file -func (f *fsClient) PutObject(size int64, data io.Reader) error { +func (f *fsClient) PutObject(size int64, data io.Reader) *probe.Error { objectDir, _ := filepath.Split(f.path) objectPath := f.path if objectDir != "" { if err := os.MkdirAll(objectDir, 0700); err != nil { - return iodine.New(err, nil) + return probe.New(err) } } fs, err := os.Create(objectPath) if err != nil { - return iodine.New(err, nil) + return probe.New(err) } defer fs.Close() @@ -98,69 +93,68 @@ func (f *fsClient) PutObject(size int64, data io.Reader) error { if size > 0 { _, err = io.CopyN(fs, data, int64(size)) if err != nil { - return iodine.New(err, nil) + return probe.New(err) } } else { // size could be 0 for virtual files on certain filesystems // for example /proc, so read till EOF for such files _, err = io.Copy(fs, data) if err != nil { - return iodine.New(err, nil) + return probe.New(err) } } return nil } // get - download an object from bucket -func (f *fsClient) get(content *client.Content) (io.ReadCloser, int64, error) { +func (f *fsClient) get() (io.ReadCloser, int64, *probe.Error) { body, err := os.Open(f.path) if err != nil { - return nil, content.Size, iodine.New(err, nil) + return nil, 0, probe.New(err) + } + { + content, err := f.getFSMetadata() + if err != nil { + return nil, content.Size, err.Trace() + } + return body, content.Size, nil } - return body, content.Size, nil } // GetObject download an full or part object from bucket // getobject returns a reader, length and nil for no errors // with errors getobject will return nil reader, length and typed errors -func (f *fsClient) GetObject(offset, length int64) (io.ReadCloser, int64, error) { - content, err := f.getFSMetadata() - if err != nil { - return nil, 0, iodine.New(err, nil) - } - if content.Type.IsDir() { - return nil, 0, iodine.New(client.ISFolder{Path: f.path}, nil) - } - if offset > content.Size || offset+length-1 > content.Size { - return nil, 0, iodine.New(client.InvalidRange{Offset: offset}, nil) +func (f *fsClient) GetObject(offset, length int64) (io.ReadCloser, int64, *probe.Error) { + if offset < 0 || length < 0 { + return nil, 0, probe.New(client.InvalidRange{Offset: offset}) } - fpath := f.path + tmppath := f.path // Golang strips trailing / if you clean(..) or // EvalSymlinks(..). Adding '.' prevents it from doing so. - if strings.HasSuffix(fpath, string(f.URL().Separator)) { - fpath = fpath + "." + if strings.HasSuffix(tmppath, string(f.URL().Separator)) { + tmppath = tmppath + "." } // Resolve symlinks - fpath, err = filepath.EvalSymlinks(fpath) + _, err := filepath.EvalSymlinks(tmppath) if os.IsNotExist(err) { - return nil, 0, iodine.New(err, nil) + return nil, 0, probe.New(err) } if err != nil { - return nil, 0, iodine.New(err, nil) + return nil, 0, probe.New(err) } if offset == 0 && length == 0 { - return f.get(content) + return f.get() } body, err := os.Open(f.path) if err != nil { - return nil, length, iodine.New(err, nil) + return nil, length, probe.New(err) } _, err = io.CopyN(ioutil.Discard, body, int64(offset)) if err != nil { - return nil, length, iodine.New(err, nil) + return nil, length, probe.New(err) } return body, length, nil } @@ -192,14 +186,14 @@ func (f *fsClient) listInRoutine(contentCh chan client.ContentOnChannel) { if os.IsNotExist(err) { contentCh <- client.ContentOnChannel{ Content: nil, - Err: iodine.New(err, nil), + Err: probe.New(err), } return } if err != nil { contentCh <- client.ContentOnChannel{ Content: nil, - Err: iodine.New(err, nil), + Err: probe.New(err), } return } @@ -208,7 +202,7 @@ func (f *fsClient) listInRoutine(contentCh chan client.ContentOnChannel) { if err != nil { contentCh <- client.ContentOnChannel{ Content: nil, - Err: iodine.New(err, nil), + Err: probe.New(err), } return } @@ -224,7 +218,7 @@ func (f *fsClient) listInRoutine(contentCh chan client.ContentOnChannel) { if err != nil { contentCh <- client.ContentOnChannel{ Content: nil, - Err: iodine.New(err, nil), + Err: probe.New(err), } return } @@ -234,7 +228,7 @@ func (f *fsClient) listInRoutine(contentCh chan client.ContentOnChannel) { if err != nil { contentCh <- client.ContentOnChannel{ Content: nil, - Err: iodine.New(err, nil), + Err: probe.New(err), } return } @@ -245,15 +239,14 @@ func (f *fsClient) listInRoutine(contentCh chan client.ContentOnChannel) { if os.IsNotExist(err) { contentCh <- client.ContentOnChannel{ Content: nil, - Err: iodine.New(client.ISBrokenSymlink{Path: file.Name()}, - map[string]string{"Target": file.Name()}), + Err: probe.New(client.ISBrokenSymlink{Path: file.Name()}), } continue } if err != nil { contentCh <- client.ContentOnChannel{ Content: nil, - Err: iodine.New(err, map[string]string{"Target": file.Name()}), + Err: probe.New(err), } continue } @@ -305,7 +298,7 @@ func (f *fsClient) listRecursiveInRoutine(contentCh chan client.ContentOnChannel if os.IsPermission(err) { return nil } - return iodine.New(err, nil) // abort + return err } if fi.Mode()&os.ModeSymlink == os.ModeSymlink { fi, err = os.Stat(fp) @@ -313,7 +306,7 @@ func (f *fsClient) listRecursiveInRoutine(contentCh chan client.ContentOnChannel if os.IsNotExist(err) || os.IsPermission(err) { // ignore broken symlinks and permission denied return nil } - return iodine.New(err, nil) + return err } } if fi.Mode().IsRegular() || fi.Mode().IsDir() { @@ -334,7 +327,7 @@ func (f *fsClient) listRecursiveInRoutine(contentCh chan client.ContentOnChannel if err != nil { contentCh <- client.ContentOnChannel{ Content: nil, - Err: iodine.New(err, nil), + Err: probe.New(err), } } } @@ -374,35 +367,35 @@ func aclToPerm(acl string) os.FileMode { } // MakeBucket - create a new bucket -func (f *fsClient) MakeBucket() error { +func (f *fsClient) MakeBucket() *probe.Error { err := os.MkdirAll(f.path, 0775) if err != nil { - return iodine.New(err, nil) + return probe.New(err) } return nil } // SetBucketACL - create a new bucket -func (f *fsClient) SetBucketACL(acl string) error { +func (f *fsClient) SetBucketACL(acl string) *probe.Error { if !isValidBucketACL(acl) { - return iodine.New(client.InvalidACLType{ACL: acl}, nil) + return probe.New(client.InvalidACLType{ACL: acl}) } err := os.MkdirAll(f.path, aclToPerm(acl)) if err != nil { - return iodine.New(err, nil) + return probe.New(err) } err = os.Chmod(f.path, aclToPerm(acl)) if err != nil { - return iodine.New(err, nil) + return probe.New(err) } return nil } // getFSMetadata - -func (f *fsClient) getFSMetadata() (content *client.Content, err error) { +func (f *fsClient) getFSMetadata() (content *client.Content, err *probe.Error) { st, err := f.fsStat() if err != nil { - return nil, iodine.New(err, nil) + return nil, err.Trace() } content = new(client.Content) content.Name = f.path @@ -413,6 +406,6 @@ func (f *fsClient) getFSMetadata() (content *client.Content, err error) { } // Stat - get metadata from path -func (f *fsClient) Stat() (content *client.Content, err error) { +func (f *fsClient) Stat() (content *client.Content, err *probe.Error) { return f.getFSMetadata() } diff --git a/pkg/client/fs/fs_unix.go b/pkg/client/fs/fs_unix.go index 0cc1d2db..b4be9ea5 100644 --- a/pkg/client/fs/fs_unix.go +++ b/pkg/client/fs/fs_unix.go @@ -18,6 +18,6 @@ package fs -func normalizePath(path string) (string, error) { - return path, nil +func normalizePath(path string) string { + return path } diff --git a/pkg/client/fs/fs_windows.go b/pkg/client/fs/fs_windows.go index 18c3491f..7cd8e6f8 100644 --- a/pkg/client/fs/fs_windows.go +++ b/pkg/client/fs/fs_windows.go @@ -21,17 +21,14 @@ package fs import ( "path/filepath" "syscall" - - "github.com/minio/minio/pkg/iodine" ) -func normalizePath(path string) (string, error) { - var err error +func normalizePath(path string) string { if filepath.VolumeName(path) == "" && filepath.HasPrefix(path, "\\") { path, err = syscall.FullPath(path) if err != nil { - return "", iodine.New(err, nil) + panic(err) } } - return path, nil + return path } diff --git a/pkg/client/s3/httptrace.go b/pkg/client/s3/httptrace.go index 5caba4ce..2cdd886a 100644 --- a/pkg/client/s3/httptrace.go +++ b/pkg/client/s3/httptrace.go @@ -22,7 +22,6 @@ import ( "github.com/minio/mc/pkg/client" "github.com/minio/mc/pkg/console" - "github.com/minio/minio/pkg/iodine" ) // HTTPTracer provides callback hook mechanism for HTTP transport. @@ -42,29 +41,27 @@ func (t RoundTripTrace) RoundTrip(req *http.Request) (res *http.Response, err er timeStamp := time.Now() if t.Transport == nil { - return nil, iodine.New(client.InvalidArgument{}, nil) + return nil, client.InvalidArgument{} } res, err = t.Transport.RoundTrip(req) if err != nil { - return res, iodine.New(err, nil) + return res, err } if t.Trace != nil { err = t.Trace.Request(req) if err != nil { - return nil, iodine.New(err, nil) + return nil, err } err = t.Trace.Response(res) if err != nil { - return nil, iodine.New(err, nil) + return nil, err } - console.Debugln("Response Time: ", time.Since(timeStamp).String()+"\n") } - - return res, iodine.New(err, nil) + return res, err } // GetNewTraceTransport returns a traceable transport diff --git a/pkg/client/s3/s3.go b/pkg/client/s3/s3.go index e8e4eaaa..01889afd 100644 --- a/pkg/client/s3/s3.go +++ b/pkg/client/s3/s3.go @@ -26,7 +26,7 @@ import ( "github.com/minio/mc/pkg/client" "github.com/minio/minio-go" - "github.com/minio/minio/pkg/iodine" + "github.com/minio/minio/pkg/probe" ) // Config - see http://docs.amazonwebservices.com/AmazonS3/latest/dev/index.html?RESTAuthentication.html @@ -56,10 +56,10 @@ type s3Client struct { } // New returns an initialized s3Client structure. if debug use a internal trace transport -func New(config *Config) (client.Client, error) { +func New(config *Config) (client.Client, *probe.Error) { u, err := client.Parse(config.HostURL) if err != nil { - return nil, iodine.New(err, nil) + return nil, probe.New(err) } var transport http.RoundTripper switch { @@ -81,7 +81,7 @@ func New(config *Config) (client.Client, error) { s3Conf.Endpoint = u.Scheme + u.SchemeSeparator + u.Host api, err := minio.New(s3Conf) if err != nil { - return nil, err + return nil, probe.New(err) } return &s3Client{api: api, hostURL: u}, nil } @@ -92,11 +92,11 @@ func (c *s3Client) URL() *client.URL { } // GetObject - get object -func (c *s3Client) GetObject(offset, length int64) (io.ReadCloser, int64, error) { +func (c *s3Client) GetObject(offset, length int64) (io.ReadCloser, int64, *probe.Error) { bucket, object := c.url2BucketAndObject() reader, metadata, err := c.api.GetPartialObject(bucket, object, offset, length) if err != nil { - return nil, length, iodine.New(err, nil) + return nil, length, probe.New(err) } return reader, metadata.Size, nil } @@ -111,7 +111,7 @@ func (e ObjectAlreadyExists) Error() string { } // PutObject - put object -func (c *s3Client) PutObject(size int64, data io.Reader) error { +func (c *s3Client) PutObject(size int64, data io.Reader) *probe.Error { // md5 is purposefully ignored since AmazonS3 does not return proper md5sum // for a multipart upload and there is no need to cross verify, // invidual parts are properly verified @@ -119,36 +119,41 @@ func (c *s3Client) PutObject(size int64, data io.Reader) error { err := c.api.PutObject(bucket, object, "application/octet-stream", size, data) if err != nil { if minio.ToErrorResponse(err).Code == "MethodNotAllowed" { - return iodine.New(ObjectAlreadyExists{Object: object}, nil) + return probe.New(ObjectAlreadyExists{Object: object}) } - return iodine.New(err, nil) + return probe.New(err) } return nil } // MakeBucket - make a new bucket -func (c *s3Client) MakeBucket() error { +func (c *s3Client) MakeBucket() *probe.Error { bucket, object := c.url2BucketAndObject() if object != "" { - return iodine.New(client.InvalidQueryURL{URL: c.hostURL.String()}, nil) + return probe.New(client.InvalidQueryURL{URL: c.hostURL.String()}) } - // location string is intentionally left out err := c.api.MakeBucket(bucket, minio.BucketACL("private")) - return iodine.New(err, nil) + if err != nil { + return probe.New(err) + } + return nil } // SetBucketACL add canned acl's on a bucket -func (c *s3Client) SetBucketACL(acl string) error { +func (c *s3Client) SetBucketACL(acl string) *probe.Error { bucket, object := c.url2BucketAndObject() if object != "" { - return iodine.New(client.InvalidQueryURL{URL: c.hostURL.String()}, nil) + return probe.New(client.InvalidQueryURL{URL: c.hostURL.String()}) } err := c.api.SetBucketACL(bucket, minio.BucketACL(acl)) - return iodine.New(err, nil) + if err != nil { + return probe.New(err) + } + return nil } // Stat - send a 'HEAD' on a bucket or object to get its metadata -func (c *s3Client) Stat() (*client.Content, error) { +func (c *s3Client) Stat() (*client.Content, *probe.Error) { objectMetadata := new(client.Content) bucket, object := c.url2BucketAndObject() switch { @@ -156,7 +161,7 @@ func (c *s3Client) Stat() (*client.Content, error) { case bucket == "" && object == "": for bucket := range c.api.ListBuckets() { if bucket.Err != nil { - return nil, iodine.New(bucket.Err, nil) + return nil, probe.New(bucket.Err) } return &client.Content{Type: os.ModeDir}, nil } @@ -169,7 +174,7 @@ func (c *s3Client) Stat() (*client.Content, error) { if errResponse.Code == "NoSuchKey" { for content := range c.List(false) { if content.Err != nil { - return nil, iodine.New(err, nil) + return nil, probe.New(content.Err) } content.Content.Type = os.ModeDir content.Content.Name = object @@ -178,7 +183,7 @@ func (c *s3Client) Stat() (*client.Content, error) { } } } - return nil, iodine.New(err, nil) + return nil, probe.New(err) } objectMetadata.Name = metadata.Key objectMetadata.Time = metadata.LastModified @@ -188,7 +193,7 @@ func (c *s3Client) Stat() (*client.Content, error) { } err := c.api.BucketExists(bucket) if err != nil { - return nil, iodine.New(err, nil) + return nil, probe.New(err) } bucketMetadata := new(client.Content) bucketMetadata.Name = bucket @@ -244,7 +249,7 @@ func (c *s3Client) listInRoutine(contentCh chan client.ContentOnChannel) { if bucket.Err != nil { contentCh <- client.ContentOnChannel{ Content: nil, - Err: bucket.Err, + Err: probe.New(bucket.Err), } return } @@ -276,7 +281,7 @@ func (c *s3Client) listInRoutine(contentCh chan client.ContentOnChannel) { if object.Err != nil { contentCh <- client.ContentOnChannel{ Content: nil, - Err: object.Err, + Err: probe.New(object.Err), } return } @@ -314,7 +319,7 @@ func (c *s3Client) listRecursiveInRoutine(contentCh chan client.ContentOnChannel if bucket.Err != nil { contentCh <- client.ContentOnChannel{ Content: nil, - Err: bucket.Err, + Err: probe.New(bucket.Err), } return } @@ -322,7 +327,7 @@ func (c *s3Client) listRecursiveInRoutine(contentCh chan client.ContentOnChannel if object.Err != nil { contentCh <- client.ContentOnChannel{ Content: nil, - Err: object.Err, + Err: probe.New(object.Err), } return } @@ -342,7 +347,7 @@ func (c *s3Client) listRecursiveInRoutine(contentCh chan client.ContentOnChannel if object.Err != nil { contentCh <- client.ContentOnChannel{ Content: nil, - Err: object.Err, + Err: probe.New(object.Err), } return } diff --git a/pkg/client/s3/s3_test.go b/pkg/client/s3/s3_test.go index bc208512..957e445e 100644 --- a/pkg/client/s3/s3_test.go +++ b/pkg/client/s3/s3_test.go @@ -188,7 +188,9 @@ func (s *MySuite) TestObjectOperations(c *C) { c.Assert(size, Equals, int64(len(object.data))) var buffer bytes.Buffer - _, err = io.CopyN(&buffer, reader, int64(size)) - c.Assert(err, IsNil) - c.Assert(buffer.Bytes(), DeepEquals, object.data) + { + _, err := io.CopyN(&buffer, reader, int64(size)) + c.Assert(err, IsNil) + c.Assert(buffer.Bytes(), DeepEquals, object.data) + } } diff --git a/pkg/client/s3/trace.go b/pkg/client/s3/trace.go index e526c1b0..878fc4a0 100644 --- a/pkg/client/s3/trace.go +++ b/pkg/client/s3/trace.go @@ -22,7 +22,6 @@ import ( "regexp" "github.com/minio/mc/pkg/console" - "github.com/minio/minio/pkg/iodine" ) // Trace - tracing structure @@ -59,7 +58,7 @@ func (t Trace) Request(req *http.Request) (err error) { // Undo req.Header.Set("Authorization", origAuth) - return iodine.New(err, nil) + return err } // Response - Trace HTTP Response @@ -68,5 +67,5 @@ func (t Trace) Response(res *http.Response) (err error) { if err == nil { console.Debug(string(resTrace)) } - return iodine.New(err, nil) + return err } diff --git a/pkg/console/console.go b/pkg/console/console.go index fd8b0a0f..0023ebcc 100644 --- a/pkg/console/console.go +++ b/pkg/console/console.go @@ -25,7 +25,7 @@ import ( "github.com/fatih/color" "github.com/mattn/go-isatty" - "github.com/minio/minio/pkg/iodine" + "github.com/minio/minio/pkg/probe" "github.com/shiena/ansicolor" ) @@ -365,7 +365,7 @@ func Unlock() { // SetTheme sets a color theme func SetTheme(themeName string) error { if !IsValidTheme(themeName) { - return iodine.New(fmt.Errorf("Unsupported theme name [%s]", themeName), nil) + return probe.New(fmt.Errorf("Unsupported theme name [%s]", themeName)) } mutex.Lock() diff --git a/pkg/quick/quick.go b/pkg/quick/quick.go index bc4488c6..f10220a9 100644 --- a/pkg/quick/quick.go +++ b/pkg/quick/quick.go @@ -20,7 +20,6 @@ package quick import ( "encoding/json" - "errors" "fmt" "io/ioutil" "os" @@ -30,18 +29,18 @@ import ( "sync" "github.com/fatih/structs" - "github.com/minio/minio/pkg/iodine" + "github.com/minio/minio/pkg/probe" ) // Config - generic config interface functions type Config interface { String() string Version() string - Save(string) error - Load(string) error + Save(string) *probe.Error + Load(string) *probe.Error Data() interface{} - Diff(Config) ([]structs.Field, error) - DeepDiff(Config) ([]structs.Field, error) + Diff(Config) ([]structs.Field, *probe.Error) + DeepDiff(Config) ([]structs.Field, *probe.Error) } // config - implements quick.Config interface @@ -51,29 +50,29 @@ type config struct { } // CheckData - checks the validity of config data. Data sould be of type struct and contain a string type field called "Version" -func CheckData(data interface{}) error { +func CheckData(data interface{}) *probe.Error { if !structs.IsStruct(data) { - return iodine.New(errors.New("Invalid argument type. Expecing \"struct\" type."), nil) + return probe.New(fmt.Errorf("Invalid argument type. Expecing \"struct\" type.")) } st := structs.New(data) f, ok := st.FieldOk("Version") if !ok { - return iodine.New(fmt.Errorf("Invalid type of struct argument. No [%s.Version] field found.", st.Name()), nil) + return probe.New(fmt.Errorf("Invalid type of struct argument. No [%s.Version] field found.", st.Name())) } if f.Kind() != reflect.String { - return iodine.New(fmt.Errorf("Invalid type of struct argument. Expecting \"string\" type [%s.Version] field.", st.Name()), nil) + return probe.New(fmt.Errorf("Invalid type of struct argument. Expecting \"string\" type [%s.Version] field.", st.Name())) } return nil } // New - instantiate a new config -func New(data interface{}) (Config, error) { +func New(data interface{}) (Config, *probe.Error) { err := CheckData(data) if err != nil { - return nil, err + return nil, err.Trace() } d := new(config) @@ -106,13 +105,13 @@ func (d config) String() string { } // Save writes config data in JSON format to a file. -func (d config) Save(filename string) (err error) { +func (d config) Save(filename string) *probe.Error { d.lock.Lock() defer d.lock.Unlock() jsonData, err := json.MarshalIndent(d.data, "", "\t") if err != nil { - return iodine.New(err, nil) + return probe.New(err) } if runtime.GOOS == "windows" { @@ -121,25 +120,25 @@ func (d config) Save(filename string) (err error) { err = ioutil.WriteFile(filename, jsonData, 0600) if err != nil { - return iodine.New(err, nil) + return probe.New(err) } return nil } // Load - loads JSON config from file and merge with currently set values -func (d *config) Load(filename string) (err error) { +func (d *config) Load(filename string) *probe.Error { (*d).lock.Lock() defer (*d).lock.Unlock() - _, err = os.Stat(filename) + _, err := os.Stat(filename) if err != nil { - return iodine.New(err, nil) + return probe.New(err) } fileData, err := ioutil.ReadFile(filename) if err != nil { - return iodine.New(err, nil) + return probe.New(err) } if runtime.GOOS == "windows" { @@ -148,22 +147,21 @@ func (d *config) Load(filename string) (err error) { err = json.Unmarshal(fileData, (*d).data) if err != nil { - return iodine.New(err, nil) + return probe.New(err) } - err = CheckData(*(*d).data) - if err != nil { - return iodine.New(err, nil) + if err := CheckData(*(*d).data); err != nil { + return err.Trace() } st := structs.New(*(*d).data) f, ok := st.FieldOk("Version") if !ok { - return iodine.New(fmt.Errorf("Argument struct [%s] does not contain field \"Version\".", st.Name()), nil) + return probe.New(fmt.Errorf("Argument struct [%s] does not contain field \"Version\".", st.Name())) } if (*d).Version() != f.Value() { - return iodine.New(errors.New("Version mismatch"), nil) + return probe.New(fmt.Errorf("Version mismatch")) } return nil @@ -175,10 +173,11 @@ func (d config) Data() interface{} { } //Diff - list fields that are in A but not in B -func (d config) Diff(c Config) (fields []structs.Field, err error) { - err = CheckData(c.Data()) +func (d config) Diff(c Config) ([]structs.Field, *probe.Error) { + var fields []structs.Field + err := CheckData(c.Data()) if err != nil { - return []structs.Field{}, iodine.New(err, nil) + return []structs.Field{}, err.Trace() } currFields := structs.Fields(d.Data()) @@ -200,10 +199,11 @@ func (d config) Diff(c Config) (fields []structs.Field, err error) { } //DeepDiff - list fields in A that are missing or not equal to fields in B -func (d config) DeepDiff(c Config) (fields []structs.Field, err error) { - err = CheckData(c.Data()) +func (d config) DeepDiff(c Config) ([]structs.Field, *probe.Error) { + var fields []structs.Field + err := CheckData(c.Data()) if err != nil { - return []structs.Field{}, iodine.New(err, nil) + return []structs.Field{}, err.Trace() } currFields := structs.Fields(d.Data()) diff --git a/session-main.go b/session-main.go index acfbee3a..351b7e32 100644 --- a/session-main.go +++ b/session-main.go @@ -23,7 +23,7 @@ import ( "github.com/minio/cli" "github.com/minio/mc/pkg/console" - "github.com/minio/minio/pkg/iodine" + "github.com/minio/minio/pkg/probe" ) // Help message. @@ -64,12 +64,12 @@ func (b bySessionWhen) Len() int { return len(b) } func (b bySessionWhen) Swap(i, j int) { b[i], b[j] = b[j], b[i] } func (b bySessionWhen) Less(i, j int) bool { return b[i].Header.When.Before(b[j].Header.When) } -func listSessions() error { +func listSessions() *probe.Error { var bySessions []*sessionV2 for _, sid := range getSessionIDs() { s, err := loadSessionV2(sid) if err != nil { - return NewIodine(iodine.New(err, nil)) + return err.Trace() } bySessions = append(bySessions, s) } @@ -85,9 +85,7 @@ func clearSession(sid string) { if sid == "all" { for _, sid := range getSessionIDs() { session, err := loadSessionV2(sid) - if err != nil { - console.Fatalf("Unable to load session ‘%s’, %s", sid, NewIodine(iodine.New(err, nil))) - } + ifFatal(err) session.Delete() } return @@ -98,9 +96,7 @@ func clearSession(sid string) { } session, err := loadSessionV2(sid) - if err != nil { - console.Fatalf("Unable to load session ‘%s’, %s", sid, NewIodine(iodine.New(err, nil))) - } + ifFatal(err) if session != nil { session.Delete() } @@ -123,17 +119,13 @@ func runSessionCmd(ctx *cli.Context) { cli.ShowCommandHelpAndExit(ctx, "session", 1) // last argument is exit code } if !isSessionDirExists() { - if err := createSessionDir(); err != nil { - console.Fatalf("Unable to create session folder. %s\n", err) - } + ifFatal(createSessionDir()) } switch strings.TrimSpace(ctx.Args().First()) { // list resumable sessions case "list": err := listSessions() - if err != nil { - console.Fatalln(err) - } + ifFatal(err) case "resume": if len(ctx.Args().Tail()) != 1 { cli.ShowCommandHelpAndExit(ctx, "session", 1) // last argument is exit code @@ -144,38 +136,37 @@ func runSessionCmd(ctx *cli.Context) { sid := strings.TrimSpace(ctx.Args().Tail().First()) - _, err := os.Stat(getSessionFile(sid)) - if err != nil { + if _, err := os.Stat(getSessionFile(sid)); err != nil { console.Fatalln(errInvalidSessionID{id: sid}) } s, err := loadSessionV2(sid) - if err != nil { - console.Fatalln(errInvalidSessionID{id: sid}) - } + ifFatal(err) // extra check for testing purposes if s == nil { return } - savedCwd, err := os.Getwd() - if err != nil { - console.Fatalln("Unable to verify your current working folder. %s\n", err) - } - if s.Header.RootPath != "" { - // chdir to RootPath - os.Chdir(s.Header.RootPath) - } + { + savedCwd, err := os.Getwd() + if err != nil { + console.Fatalln("Unable to verify your current working folder. %s\n", err) + } + if s.Header.RootPath != "" { + // chdir to RootPath + os.Chdir(s.Header.RootPath) + } - sessionExecute(s) - err = s.Close() - if err != nil { - console.Fatalf("Unable to close session file properly. %s\n", err) + sessionExecute(s) + err = s.Close() + if err != nil { + console.Fatalf("Unable to close session file properly. %s\n", err) + } + err = s.Delete() + if err != nil { + console.Fatalf("Unable to clear session files properly. %s\n", err) + } + // change dir back + os.Chdir(savedCwd) } - err = s.Delete() - if err != nil { - console.Fatalf("Unable to clear session files properly. %s\n", err) - } - // change dir back - os.Chdir(savedCwd) // purge a requested pending session, if "*" purge everything case "clear": diff --git a/session-v1.go b/session-v1.go index e70d9f6e..59d51f74 100644 --- a/session-v1.go +++ b/session-v1.go @@ -26,7 +26,7 @@ import ( "github.com/minio/mc/pkg/console" "github.com/minio/mc/pkg/quick" - "github.com/minio/minio/pkg/iodine" + "github.com/minio/minio/pkg/probe" ) type sessionV1 struct { @@ -50,13 +50,12 @@ func (s sessionV1) String() string { // loadSession - reads session file if exists and re-initiates internal variables func loadSessionV1(sid string) (*sessionV1, error) { if !isSessionDirExists() { - return nil, NewIodine(iodine.New(errInvalidArgument{}, nil)) + return nil, probe.New(errInvalidArgument{}) } sessionFile := getSessionFileV1(sid) - _, err := os.Stat(sessionFile) - if err != nil { - return nil, NewIodine(iodine.New(err, nil)) + if _, err := os.Stat(sessionFile); err != nil { + return nil, probe.New(err) } s := new(sessionV1) s.Version = "1.0.0" @@ -66,11 +65,11 @@ func loadSessionV1(sid string) (*sessionV1, error) { s.Files = make(map[string]bool) qs, err := quick.New(s) if err != nil { - return nil, NewIodine(iodine.New(err, nil)) + return nil, err.Trace() } err = qs.Load(sessionFile) if err != nil { - return nil, NewIodine(iodine.New(err, nil)) + return nil, err.Trace() } return qs.Data().(*sessionV1), nil } @@ -78,7 +77,7 @@ func loadSessionV1(sid string) (*sessionV1, error) { func getSessionIDsV1() (sids []string) { sessionList, err := filepath.Glob(getSessionDir() + "/*") if err != nil { - console.Fatalf("Unable to list session folder ‘%s’, %s", getSessionDir(), NewIodine(iodine.New(err, nil))) + console.Fatalf("Unable to list session folder ‘%s’, %s", getSessionDir(), probe.New(err)) } for _, path := range sessionList { @@ -87,7 +86,7 @@ func getSessionIDsV1() (sids []string) { if sidReg.Match([]byte(sid)) { sessionV1, err := loadSessionV1(sid) if err != nil { - console.Fatalf("Unable to load session ‘%s’, %s", sid, NewIodine(iodine.New(err, nil))) + console.Fatalf("Unable to load session ‘%s’, %s", sid, probe.New(err)) } if sessionV1.Version != "1.0.0" { continue diff --git a/session-v2.go b/session-v2.go index 9e99891d..f31f3312 100644 --- a/session-v2.go +++ b/session-v2.go @@ -26,7 +26,7 @@ import ( "github.com/minio/mc/pkg/console" "github.com/minio/mc/pkg/quick" - "github.com/minio/minio/pkg/iodine" + "github.com/minio/minio/pkg/probe" ) // migrateSessionV1ToV2 migrates all session files from v1 to v2. @@ -35,7 +35,7 @@ func migrateSessionV1ToV2() { for _, sid := range getSessionIDsV1() { err := os.Remove(getSessionFileV1(sid)) if err != nil { - console.Fatalf("Migration failed. Unable to remove old session file %s. %s\n", getSessionFileV1(sid), NewIodine(iodine.New(err, nil))) + console.Fatalf("Migration failed. Unable to remove old session file %s. %s\n", getSessionFileV1(sid), probe.New(err)) } } } @@ -107,75 +107,72 @@ func (s *sessionV2) NewDataWriter() io.Writer { } // Save this session -func (s *sessionV2) Save() error { +func (s *sessionV2) Save() *probe.Error { s.mutex.Lock() defer s.mutex.Unlock() - err := s.DataFP.Sync() - if err != nil { - return NewIodine(iodine.New(err, nil)) + if err := s.DataFP.Sync(); err != nil { + return probe.New(err) } qs, err := quick.New(s.Header) if err != nil { - return NewIodine(iodine.New(err, nil)) + return err.Trace() } return qs.Save(getSessionFile(s.SessionID)) } // Close ends this session and removes all associated session files. -func (s *sessionV2) Close() error { +func (s *sessionV2) Close() *probe.Error { s.mutex.Lock() defer s.mutex.Unlock() - err := s.DataFP.Close() - if err != nil { - return NewIodine(iodine.New(err, nil)) + if err := s.DataFP.Close(); err != nil { + return probe.New(err) } qs, err := quick.New(s.Header) if err != nil { - return NewIodine(iodine.New(err, nil)) + return err.Trace() } return qs.Save(getSessionFile(s.SessionID)) } // Delete removes all the session files. -func (s *sessionV2) Delete() error { +func (s *sessionV2) Delete() *probe.Error { s.mutex.Lock() defer s.mutex.Unlock() if s.DataFP != nil { err := os.Remove(s.DataFP.Name()) if err != nil { - return NewIodine(iodine.New(err, nil)) + return probe.New(err) } } err := os.Remove(getSessionFile(s.SessionID)) if err != nil { - return NewIodine(iodine.New(err, nil)) + return probe.New(err) } if err != nil { - return NewIodine(iodine.New(err, nil)) + return probe.New(err) } return nil } // loadSession - reads session file if exists and re-initiates internal variables -func loadSessionV2(sid string) (*sessionV2, error) { +func loadSessionV2(sid string) (*sessionV2, *probe.Error) { if !isSessionDirExists() { - return nil, NewIodine(iodine.New(errInvalidArgument{}, nil)) + return nil, probe.New(errInvalidArgument{}) } sessionFile := getSessionFile(sid) - _, err := os.Stat(sessionFile) - if err != nil { - return nil, NewIodine(iodine.New(err, nil)) + if _, err := os.Stat(sessionFile); err != nil { + return nil, probe.New(err) } s := &sessionV2{} @@ -184,19 +181,22 @@ func loadSessionV2(sid string) (*sessionV2, error) { s.Header.Version = "1.1.0" qs, err := quick.New(s.Header) if err != nil { - return nil, NewIodine(iodine.New(err, nil)) + return nil, err.Trace() } err = qs.Load(sessionFile) if err != nil { - return nil, NewIodine(iodine.New(err, nil)) + return nil, err.Trace() } s.mutex = new(sync.Mutex) s.Header = qs.Data().(*sessionV2Header) - s.DataFP, err = os.Open(getSessionDataFile(s.SessionID)) - if err != nil { - console.Fatalf("Unable to open session data file \""+getSessionDataFile(s.SessionID)+"\". %s\n", NewIodine(iodine.New(err, nil))) + { + var err error + s.DataFP, err = os.Open(getSessionDataFile(s.SessionID)) + if err != nil { + console.Fatalf("Unable to open session data file \""+getSessionDataFile(s.SessionID)+"\". %s\n", err) + } } return s, nil @@ -209,7 +209,7 @@ func isCopiedFactory(lastCopied string) func(string) bool { copied := true // closure return func(sourceURL string) bool { if sourceURL == "" { - console.Fatalf("Empty source URL passed to isCopied() function. %s\n", NewIodine(iodine.New(errUnexpected{}, nil))) + console.Fatalf("Empty source URL passed to isCopied() function. %s\n", probe.New(errUnexpected{})) } if lastCopied == "" { return false diff --git a/session.go b/session.go index b4f18d2b..f8d7e54a 100644 --- a/session.go +++ b/session.go @@ -24,7 +24,7 @@ import ( "time" "github.com/minio/mc/pkg/console" - "github.com/minio/minio/pkg/iodine" + "github.com/minio/minio/pkg/probe" ) func migrateSession() { @@ -40,9 +40,9 @@ func isSessionDirExists() bool { return true } -func createSessionDir() error { +func createSessionDir() *probe.Error { if err := os.MkdirAll(getSessionDir(), 0700); err != nil { - return NewIodine(iodine.New(err, nil)) + return probe.New(err) } return nil } @@ -78,7 +78,7 @@ func getSessionDataFile(sid string) string { func getSessionIDs() (sids []string) { sessionList, err := filepath.Glob(getSessionDir() + "/*.json") if err != nil { - console.Fatalf("Unable to list session folder ‘%s’, %s", getSessionDir(), NewIodine(iodine.New(err, nil))) + console.Fatalf("Unable to list session folder ‘%s’, %s", getSessionDir(), probe.New(err)) } for _, path := range sessionList { @@ -88,10 +88,8 @@ func getSessionIDs() (sids []string) { } func isSession(sid string) bool { - _, err := os.Stat(getSessionFile(sid)) - if err != nil { + if _, err := os.Stat(getSessionFile(sid)); err != nil { return false } - return true } diff --git a/update-main.go b/update-main.go index 472d73b1..0ee7723a 100644 --- a/update-main.go +++ b/update-main.go @@ -24,7 +24,7 @@ import ( "github.com/minio/cli" "github.com/minio/mc/pkg/console" - "github.com/minio/minio/pkg/iodine" + "github.com/minio/minio/pkg/probe" ) // Updates container to hold updates json @@ -55,14 +55,14 @@ EXAMPLES: `, } -func doUpdateCheck() (string, error) { +func doUpdateCheck() (string, *probe.Error) { clnt, err := url2Client(mcUpdateURL) if err != nil { - return "Unable to create client: " + mcUpdateURL, NewIodine(iodine.New(err, map[string]string{"failedURL": mcUpdateURL})) + return "Unable to create client: " + mcUpdateURL, err.Trace() } data, _, err := clnt.GetObject(0, 0) if err != nil { - return "Unable to read: " + mcUpdateURL, NewIodine(iodine.New(err, map[string]string{"failedURL": mcUpdateURL})) + return "Unable to read: " + mcUpdateURL, err.Trace() } current, _ := time.Parse(time.RFC3339Nano, Version) if current.IsZero() { @@ -72,9 +72,8 @@ https://dl.minio.io:9000 for continuous updates` } var updates Updates decoder := json.NewDecoder(data) - err = decoder.Decode(&updates) - if err != nil { - return "Unable to parse update fields", NewIodine(iodine.New(err, map[string]string{"failedURL": mcUpdateURL})) + if err := decoder.Decode(&updates); err != nil { + return "Unable to parse update fields", probe.New(err) } latest, _ := time.Parse(http.TimeFormat, updates.BuildDate) if latest.IsZero() { @@ -90,7 +89,7 @@ https://dl.minio.io:9000 for continuous updates` } msg, err := printUpdateNotify(updateString, "new", "old") if err != nil { - return "", err + return "", probe.New(err) } console.Println(msg) return "", nil @@ -105,9 +104,7 @@ func runUpdateCmd(ctx *cli.Context) { cli.ShowCommandHelpAndExit(ctx, "update", 1) // last argument is exit code } msg, err := doUpdateCheck() - if err != nil { - console.Fatalln(msg) - } + ifFatal(err) // no msg do not print one if msg != "" { console.Infoln(msg) diff --git a/url.go b/url.go index f51cc72f..8ea5759f 100644 --- a/url.go +++ b/url.go @@ -20,7 +20,7 @@ import ( "strings" "github.com/minio/mc/pkg/client" - "github.com/minio/minio/pkg/iodine" + "github.com/minio/minio/pkg/probe" ) // ``...`` recursiveSeparator @@ -46,29 +46,25 @@ func stripRecursiveURL(urlStr string) string { } // getExpandedURL - extracts URL string from a single cmd-line argument -func getExpandedURL(arg string, aliases map[string]string) (urlStr string, err error) { - if _, err := client.Parse(urlStr); err != nil { - // Not a valid URL. Return error - return "", NewIodine(iodine.New(errInvalidURL{arg}, nil)) - } +func getExpandedURL(arg string, aliases map[string]string) (urlStr string, err *probe.Error) { // Check and expand Alias urlStr, err = aliasExpand(arg, aliases) if err != nil { - return "", NewIodine(iodine.New(err, nil)) + return "", err.Trace() } if _, err := client.Parse(urlStr); err != nil { // Not a valid URL. Return error - return "", NewIodine(iodine.New(errInvalidURL{urlStr}, nil)) + return "", probe.New(errInvalidURL{urlStr}) } return urlStr, nil } // getExpandedURLs - extracts multiple URL strings from a single cmd-line argument -func getExpandedURLs(args []string, aliases map[string]string) (urls []string, err error) { +func getExpandedURLs(args []string, aliases map[string]string) (urls []string, err *probe.Error) { for _, arg := range args { u, err := getExpandedURL(arg, aliases) if err != nil { - return nil, NewIodine(iodine.New(err, nil)) + return nil, err.Trace() } urls = append(urls, u) } @@ -76,16 +72,16 @@ func getExpandedURLs(args []string, aliases map[string]string) (urls []string, e } // args2URLs extracts source and target URLs from command-line args. -func args2URLs(args []string) ([]string, error) { +func args2URLs(args []string) ([]string, *probe.Error) { config, err := getMcConfig() if err != nil { - return nil, NewIodine(iodine.New(err, nil)) + return nil, err.Trace() } // Convert arguments to URLs: expand alias, fix format... URLs, err := getExpandedURLs(args, config.Aliases) if err != nil { - return nil, NewIodine(iodine.New(err, nil)) + return nil, err.Trace() } return URLs, nil }