From 7d624457b0d85e4459a6ad86c66727a1a529157a Mon Sep 17 00:00:00 2001 From: "Anand Babu (AB) Periasamy" Date: Fri, 21 Aug 2015 17:43:40 -0700 Subject: [PATCH] updated error messages --- access-main.go | 12 +++---- aliases.go | 2 +- cat-main.go | 8 ++--- common-methods.go | 20 +++++------ config-main.go | 45 +++++++++++------------- config_test.go | 3 ++ session-main.go | 26 +++++++------- session-v1.go | 41 ++++++++++++++-------- session-v2.go | 68 +++++++++++++++++++++++------------- session.go | 89 ++++++++++++++++++++++++++++++----------------- 10 files changed, 183 insertions(+), 131 deletions(-) diff --git a/access-main.go b/access-main.go index 012ded4e..e985701b 100644 --- a/access-main.go +++ b/access-main.go @@ -71,9 +71,8 @@ func mainAccess(ctx *cli.Context) { } for _, arg := range ctx.Args().Tail() { targetURL, err := getCanonicalizedURL(arg, config.Aliases) - fatalIf(err.Trace(), "Unable to parse URL argument ‘"+arg+"’.") - - fatalIf(doUpdateAccessCmd(targetURL, acl).Trace(), "Unable to set access permission ‘"+acl.String()+"’ for URL ‘"+targetURL+"’.") + fatalIf(err.Trace(arg), "Unable to parse URL argument ‘"+arg+"’.") + fatalIf(doUpdateAccessCmd(targetURL, acl).Trace(targetURL), "Unable to set access permission ‘"+acl.String()+"’ for URL ‘"+targetURL+"’.") } } @@ -81,11 +80,10 @@ func doUpdateAccessCmd(targetURL string, targetACL bucketACL) *probe.Error { var clnt client.Client clnt, err := target2Client(targetURL) if err != nil { - return err.Trace() + return err.Trace(targetURL) } - err = clnt.SetBucketACL(targetACL.String()) - if err != nil { - return err.Trace() + if err = clnt.SetBucketACL(targetACL.String()); err != nil { + return err.Trace(targetURL, targetACL.String()) } return nil } diff --git a/aliases.go b/aliases.go index 7d45949b..5aaa5dfb 100644 --- a/aliases.go +++ b/aliases.go @@ -54,7 +54,7 @@ func isValidAliasName(aliasName string) bool { func aliasExpand(aliasedURL string, aliases map[string]string) (string, *probe.Error) { u, err := client.Parse(aliasedURL) if err != nil { - return aliasedURL, probe.NewError(errInvalidURL{URL: aliasedURL}) + return aliasedURL, probe.NewError(err) } // proper URL if u.Host != "" { diff --git a/cat-main.go b/cat-main.go index 2ef1f102..18336466 100644 --- a/cat-main.go +++ b/cat-main.go @@ -70,11 +70,11 @@ func mainCat(ctx *cli.Context) { } if stdinMode { - fatalIf(catOut(os.Stdin).Trace(), "Unable to read from stdin") + fatalIf(catOut(os.Stdin).Trace(), "Unable to read from stdin.") } else { // Convert arguments to URLs: expand alias, fix format... for _, arg := range ctx.Args() { - fatalIf(catURL(arg).Trace(), "Unable to read from URL") + fatalIf(catURL(arg).Trace(arg), "Unable to read from ‘"+arg+"’.") } } @@ -96,11 +96,11 @@ func catURL(sourceURL string) *probe.Error { // Ignore size, since os.Stat() would not return proper size all the time for local filesystem for example /proc files. reader, _, err := sourceClnt.GetObject(0, 0) if err != nil { - return err.Trace() + return err.Trace(URL) } defer reader.Close() - return catOut(reader).Trace() + return catOut(reader).Trace(URL) } func catOut(r io.Reader) *probe.Error { diff --git a/common-methods.go b/common-methods.go index 0889353c..5e2f42d1 100644 --- a/common-methods.go +++ b/common-methods.go @@ -65,11 +65,11 @@ func getSource(sourceURL string) (reader io.ReadCloser, length int64, err *probe func putTarget(targetURL string, length int64, reader io.Reader) *probe.Error { targetClnt, err := target2Client(targetURL) if err != nil { - return err.Trace() + return err.Trace(targetURL) } err = targetClnt.PutObject(length, reader) if err != nil { - return err.Trace() + return err.Trace(targetURL) } return nil } @@ -83,7 +83,7 @@ func putTargets(targetURLs []string, length int64, reader io.Reader) *probe.Erro for _, targetURL := range targetURLs { tgtClient, err := target2Client(targetURL) if err != nil { - return err.Trace() + return err.Trace(targetURL) } tgtClients = append(tgtClients, tgtClient) tgtReader, tgtWriter := io.Pipe() @@ -129,7 +129,7 @@ func putTargets(targetURLs []string, length int64, reader io.Reader) *probe.Erro for err := range errorCh { if err != nil { // Return on first error encounter. - return err + return err.Trace() } } return nil // success. @@ -172,12 +172,12 @@ func getNewClient(urlStr string, auth hostConfig) (client.Client, *probe.Error) func url2Stat(urlStr string) (client client.Client, content *client.Content, err *probe.Error) { client, err = url2Client(urlStr) if err != nil { - return nil, nil, err.Trace() + return nil, nil, err.Trace(urlStr) } content, err = client.Stat() if err != nil { - return nil, nil, err.Trace() + return nil, nil, err.Trace(urlStr) } return client, content, nil @@ -203,12 +203,12 @@ func url2Client(url string) (client.Client, *probe.Error) { } urlconfig, err := getHostConfig(url) if err != nil { - return nil, err.Trace() + return nil, err.Trace(url) } client, err := getNewClient(url, urlconfig) if err != nil { - return nil, err.Trace() + return nil, err.Trace(url) } return client, nil @@ -218,7 +218,7 @@ func url2Client(url string) (client.Client, *probe.Error) { func source2Client(sourceURL string) (client.Client, *probe.Error) { sourceClient, err := url2Client(sourceURL) if err != nil { - return nil, err.Trace() + return nil, err.Trace(sourceURL) } return sourceClient, nil } @@ -227,7 +227,7 @@ func source2Client(sourceURL string) (client.Client, *probe.Error) { func target2Client(targetURL string) (client.Client, *probe.Error) { targetClient, err := url2Client(targetURL) if err != nil { - return nil, err.Trace() + return nil, err.Trace(targetURL) } return targetClient, nil } diff --git a/config-main.go b/config-main.go index 32c6aacf..f028934c 100644 --- a/config-main.go +++ b/config-main.go @@ -24,7 +24,6 @@ import ( "github.com/minio/mc/internal/github.com/minio/cli" "github.com/minio/mc/internal/github.com/minio/minio/pkg/probe" "github.com/minio/mc/internal/github.com/minio/minio/pkg/quick" - "github.com/minio/mc/pkg/console" ) // Configure minio client @@ -66,57 +65,53 @@ func mainConfig(ctx *cli.Context) { arg := ctx.Args().First() tailArgs := ctx.Args().Tail() if len(tailArgs) > 2 { - fatalIf(probe.NewError(errors.New("")), - "Incorrect number of arguments, please read ‘mc config help’") + fatalIf(probe.NewError(errors.New("")), "Incorrect number of arguments to config command. Please read ‘mc config help’") } - configPath, err := getMcConfigPath() - fatalIf(err, "Unable to get mc config path") switch arg { case "alias": if len(tailArgs) < 2 { cli.ShowCommandHelpAndExit(ctx, "config", 1) // last argument is exit code } - addAlias(tailArgs) + alias := tailArgs[0] + url := tailArgs[1] + addAlias(alias, url) default: cli.ShowCommandHelpAndExit(ctx, "config", 1) // last argument is exit code } - // upon success - console.Infoln("Alias written successfully to [" + configPath + "].") } // addAlias - add new aliases -func addAlias(aliases []string) { +func addAlias(alias, url string) { + if alias == "" || url == "" { + fatalIf(probe.NewError(errors.New("")), "Alias or URL cannot be empty.") + } conf := newConfigV1() config, err := quick.New(conf) - fatalIf(err.Trace(), "Unable to initialize quick config") + fatalIf(err.Trace(conf.Version), "Failed to initialize ‘quick’ configuration data structure.") err = config.Load(mustGetMcConfigPath()) fatalIf(err.Trace(), "Unable to load config path") - aliasName := aliases[0] - url := strings.TrimSuffix(aliases[1], "/") - if strings.HasPrefix(aliasName, "http") { - fatalIf(probe.NewError(errors.New("")), fmt.Sprintf("Alias name ‘%s’ is invalid, valid examples are: Area51, Grand-Nagus..", aliasName)) - } + url = strings.TrimSuffix(url, "/") if !strings.HasPrefix(url, "http") { - fatalIf(probe.NewError(errors.New("")), fmt.Sprintf("Alias URL ‘%s’ is invalid, valid examples are: http://s3.amazonaws.com, https://yourbucket.example.com...", url)) + fatalIf(probe.NewError(errors.New("")), fmt.Sprintf("Invalid alias URL ‘%s’. Valid examples are: http://s3.amazonaws.com, https://yourbucket.example.com.", url)) } - if isAliasReserved(aliasName) { - fatalIf(probe.NewError(errors.New("")), fmt.Sprintf("Alias name ‘%s’ is a reserved word, reserved words are [help, private, readonly, public, authenticated]", aliasName)) + if isAliasReserved(alias) { + fatalIf(probe.NewError(errors.New("")), fmt.Sprintf("Cannot use a reserved name ‘%s’ as an alias. Following are reserved names: [help, private, readonly, public, authenticated].", alias)) } - if !isValidAliasName(aliasName) { - fatalIf(probe.NewError(errors.New("")), fmt.Sprintf("Alias name ‘%s’ is invalid, valid examples are: Area51, Grand-Nagus..", aliasName)) + if !isValidAliasName(alias) { + fatalIf(probe.NewError(errors.New("")), fmt.Sprintf("Alias name ‘%s’ is invalid, valid examples are: mybucket, Area51, Grand-Nagus", alias)) } // convert interface{} back to its original struct newConf := config.Data().(*configV1) - if _, ok := newConf.Aliases[aliasName]; ok { - fatalIf(probe.NewError(errors.New("")), fmt.Sprintf("Specified alias name: ‘%s’ already exists.", aliasName)) + if oldURL, ok := newConf.Aliases[alias]; ok { + fatalIf(probe.NewError(errors.New("")), fmt.Sprintf("Alias ‘%s’ already exists for ‘%s’.", alias, oldURL)) } - newConf.Aliases[aliasName] = url + newConf.Aliases[alias] = url newConfig, err := quick.New(newConf) - fatalIf(err.Trace(), "Unable to initialize quick config") + fatalIf(err.Trace(conf.Version), "Failed to initialize ‘quick’ configuration data structure.") err = writeConfig(newConfig) - fatalIf(err.Trace(), "Unable to write alias name") + fatalIf(err.Trace(alias, url), "Unable to save alias ‘"+alias+"’.") } diff --git a/config_test.go b/config_test.go index 7ca3684c..54f78f00 100644 --- a/config_test.go +++ b/config_test.go @@ -34,4 +34,7 @@ func (s *CmdTestSuite) TestConfigContext(c *C) { err = app.Run([]string{os.Args[0], "config", "alias", "new", "http://test.io"}) c.Assert(err, IsNil) c.Assert(console.IsExited, Equals, false) + + // reset back + console.IsExited = false } diff --git a/session-main.go b/session-main.go index 0baf4e9a..6e15f781 100644 --- a/session-main.go +++ b/session-main.go @@ -141,36 +141,36 @@ func mainSession(ctx *cli.Context) { console.Fatalf("Session ‘%s’ not found.\n", sid) } - s, perr := loadSessionV2(sid) - fatalIf(perr.Trace(), "Unable to load session") + s, err := loadSessionV2(sid) + fatalIf(err.Trace(sid), "Unable to load session") // extra check for testing purposes if s == nil { return } - savedCwd, err := os.Getwd() + savedCwd, e := os.Getwd() if err != nil { - console.Fatalf("Unable to verify your current working folder. %s\n", err) + console.Fatalf("Unable to verify your current working folder. %s\n", e) } if s.Header.RootPath != "" { // chdir to RootPath - if err := os.Chdir(s.Header.RootPath); err != nil { - console.Fatalf("Unable to change directory to root path while resuming session. %s\n", err) + if e := os.Chdir(s.Header.RootPath); e != nil { + console.Fatalf("Unable to change directory to root path while resuming session. %s\n", e) } } sessionExecute(s) - perr = s.Close() - fatalIf(perr.Trace(), "Unable to close session file properly.") + err = s.Close() + fatalIf(err.Trace(), "Unable to close session file properly.") - perr = s.Delete() - fatalIf(perr.Trace(), "Unable to clear session files properly.") + err = s.Delete() + fatalIf(err.Trace(), "Unable to clear session files properly.") // change dir back - err = os.Chdir(savedCwd) - if err != nil { - console.Fatalf("Unable to change directory to saved path. %s\n", err) + e = os.Chdir(savedCwd) + if e != nil { + console.Fatalf("Unable to change directory to saved path. %s\n", e) } // purge a requested pending session, if "*" purge everything case "clear": diff --git a/session-v1.go b/session-v1.go index 9dae2914..83ec70e6 100644 --- a/session-v1.go +++ b/session-v1.go @@ -17,6 +17,7 @@ package main import ( + "errors" "fmt" "os" "path/filepath" @@ -51,13 +52,14 @@ func (s sessionV1) String() string { // loadSession - reads session file if exists and re-initiates internal variables func loadSessionV1(sid string) (*sessionV1, *probe.Error) { if !isSessionDirExists() { - return nil, probe.NewError(errInvalidArgument) + return nil, probe.NewError(errors.New("Session folder does not exist.")) } - sessionFile := getSessionFileV1(sid) - if _, err := os.Stat(sessionFile); err != nil { - return nil, probe.NewError(err) + sessionFile, err := getSessionFileV1(sid) + if err != nil { + return nil, err.Trace(sid) } + s := new(sessionV1) s.Version = "1.0.0" // map of command and files copied @@ -66,29 +68,28 @@ func loadSessionV1(sid string) (*sessionV1, *probe.Error) { s.Files = make(map[string]bool) qs, err := quick.New(s) if err != nil { - return nil, err.Trace() + return nil, err.Trace(s.Version) } err = qs.Load(sessionFile) if err != nil { - return nil, err.Trace() + return nil, err.Trace(sessionFile, s.Version) } return qs.Data().(*sessionV1), nil } func getSessionIDsV1() (sids []string) { - sessionList, err := filepath.Glob(getSessionDir() + "/*") - if err != nil { - console.Fatalf("Unable to list session folder ‘%s’, %s", getSessionDir(), probe.NewError(err)) - } + sessionDir, err := getSessionDir() + fatalIf(err.Trace(), "Unable to determine session folder.") + + sessionList, e := filepath.Glob(sessionDir + "/*") + fatalIf(probe.NewError(e), "Unable to access session folder ‘"+sessionDir+"’.") for _, path := range sessionList { sidReg := regexp.MustCompile("^[a-zA-Z]{8}$") sid := filepath.Base(path) if sidReg.Match([]byte(sid)) { sessionV1, err := loadSessionV1(sid) - if err != nil { - console.Fatalf("Unable to load session ‘%s’, %s", sid, err.Trace()) - } + fatalIf(err.Trace(sid), "Unable to load session ‘"+sid+"’.") if sessionV1.Version != "1.0.0" { continue } @@ -98,6 +99,16 @@ func getSessionIDsV1() (sids []string) { return sids } -func getSessionFileV1(sid string) string { - return filepath.Join(getSessionDir(), sid) +func getSessionFileV1(sid string) (string, *probe.Error) { + sessionDir, err := getSessionDir() + if err != nil { + return "", err.Trace() + } + + sessionFile := filepath.Join(sessionDir, sid) + if _, err := os.Stat(sessionFile); err != nil { + return "", probe.NewError(err) + } + + return sessionFile, nil } diff --git a/session-v2.go b/session-v2.go index 071b2cf1..980faf1c 100644 --- a/session-v2.go +++ b/session-v2.go @@ -34,10 +34,11 @@ import ( // This function should be called from the main early on. 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), probe.NewError(err)) - } + sessionFileV1, err := getSessionFileV1(sid) + fatalIf(err.Trace(sid), "Unable to determine session file for ‘"+sid+"’.") + + e := os.Remove(sessionFileV1) + fatalIf(probe.NewError(e), "Migration failed. Unable to remove old session file ‘"+sessionFileV1+"’.") } } @@ -72,11 +73,14 @@ func newSessionV2() *sessionV2 { s.Header.When = time.Now().UTC() s.mutex = new(sync.Mutex) s.SessionID = newSID(8) + + sessionDataFile, perr := getSessionDataFile(s.SessionID) + fatalIf(perr.Trace(s.SessionID), "Unable to create session data file \""+sessionDataFile+"\".") + var err error - s.DataFP, err = os.Create(getSessionDataFile(s.SessionID)) - if err != nil { - console.Fatalf("Unable to create session data file \""+getSessionDataFile(s.SessionID)+"\". %s\n", err) - } + s.DataFP, err = os.Create(sessionDataFile) + fatalIf(probe.NewError(err), "Unable to create session data file \""+sessionDataFile+"\".") + return s } @@ -118,10 +122,14 @@ func (s *sessionV2) Save() *probe.Error { qs, err := quick.New(s.Header) if err != nil { - return err.Trace() + return err.Trace(s.SessionID) } - return qs.Save(getSessionFile(s.SessionID)) + sessionFile, err := getSessionFile(s.SessionID) + if err != nil { + return err.Trace(s.SessionID) + } + return qs.Save(sessionFile).Trace() } // Close ends this session and removes all associated session files. @@ -138,7 +146,11 @@ func (s *sessionV2) Close() *probe.Error { return err.Trace() } - return qs.Save(getSessionFile(s.SessionID)) + sessionFile, err := getSessionFile(s.SessionID) + if err != nil { + return err.Trace(s.SessionID) + } + return qs.Save(sessionFile).Trace() } // Delete removes all the session files. @@ -153,12 +165,12 @@ func (s *sessionV2) Delete() *probe.Error { } } - err := os.Remove(getSessionFile(s.SessionID)) + sessionFile, err := getSessionFile(s.SessionID) if err != nil { - return probe.NewError(err) + return err.Trace(s.SessionID) } - if err != nil { + if err := os.Remove(sessionFile); err != nil { return probe.NewError(err) } @@ -170,7 +182,11 @@ func loadSessionV2(sid string) (*sessionV2, *probe.Error) { if !isSessionDirExists() { return nil, probe.NewError(errInvalidArgument) } - sessionFile := getSessionFile(sid) + sessionFile, err := getSessionFile(sid) + if err != nil { + return nil, err.Trace(sid) + } + if _, err := os.Stat(sessionFile); err != nil { return nil, probe.NewError(err) } @@ -179,23 +195,27 @@ func loadSessionV2(sid string) (*sessionV2, *probe.Error) { s.Header = &sessionV2Header{} s.SessionID = sid s.Header.Version = "1.1.0" - qs, perr := quick.New(s.Header) - if perr != nil { - return nil, perr.Trace() + qs, err := quick.New(s.Header) + if err != nil { + return nil, err.Trace() } - perr = qs.Load(sessionFile) - if perr != nil { - return nil, perr.Trace() + err = qs.Load(sessionFile) + if err != nil { + return nil, err.Trace() } s.mutex = new(sync.Mutex) s.Header = qs.Data().(*sessionV2Header) - var err error - s.DataFP, err = os.Open(getSessionDataFile(s.SessionID)) + sessionDataFile, err := getSessionDataFile(s.SessionID) if err != nil { - return nil, probe.NewError(err) + return nil, err.Trace() } + + var e error + s.DataFP, e = os.Open(sessionDataFile) + fatalIf(probe.NewError(e), "Unable to open session data file ‘"+sessionDataFile+"’.") + return s, nil } diff --git a/session.go b/session.go index 5e2f0f12..3f5695a0 100644 --- a/session.go +++ b/session.go @@ -24,7 +24,6 @@ import ( "time" "github.com/minio/mc/internal/github.com/minio/minio/pkg/probe" - "github.com/minio/mc/pkg/console" ) func migrateSession() { @@ -32,27 +31,36 @@ func migrateSession() { migrateSessionV1ToV2() } -func isSessionDirExists() bool { - _, err := os.Stat(getSessionDir()) - if err != nil { - return false - } - return true -} - func createSessionDir() *probe.Error { - if err := os.MkdirAll(getSessionDir(), 0700); err != nil { + sessionDir, err := getSessionDir() + if err != nil { + return err.Trace() + } + + if err := os.MkdirAll(sessionDir, 0700); err != nil { return probe.NewError(err) } return nil } -func getSessionDir() string { +func getSessionDir() (string, *probe.Error) { configDir, err := getMcConfigDir() if err != nil { - // TODO: revamp error handling -ab. Do not pass errors mindlessly to upper layer for a tool like mc. + return "", err.Trace() } - return filepath.Join(configDir, globalSessionDir) + + sessionDir := filepath.Join(configDir, globalSessionDir) + return sessionDir, nil +} + +func isSessionDirExists() bool { + sessionDir, err := getSessionDir() + fatalIf(err.Trace(), "Unable to determine session folder.") + + if _, e := os.Stat(sessionDir); e != nil { + return false + } + return true } var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") @@ -60,36 +68,53 @@ var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") // newSID generates a random session id of regular lower case and uppercase english characters func newSID(n int) string { rand.Seed(time.Now().UTC().UnixNano()) - b := make([]rune, n) - for i := range b { - b[i] = letters[rand.Intn(len(letters))] + sid := make([]rune, n) + for i := range sid { + sid[i] = letters[rand.Intn(len(letters))] } - return string(b) + return string(sid) } -func getSessionFile(sid string) string { - return filepath.Join(getSessionDir(), sid+".json") +func getSessionFile(sid string) (string, *probe.Error) { + sessionDir, err := getSessionDir() + if err != nil { + return "", err.Trace() + } + + sessionFile := filepath.Join(sessionDir, sid+".json") + return sessionFile, nil } -func getSessionDataFile(sid string) string { - return filepath.Join(getSessionDir(), sid+".data") +func isSession(sid string) bool { + sessionFile, err := getSessionFile(sid) + fatalIf(err.Trace(sid), "Unable to determine session filename for ‘"+sid+"’.") + + if _, e := os.Stat(sessionFile); e != nil { + return false + } + + return true // Session exists. +} + +func getSessionDataFile(sid string) (string, *probe.Error) { + sessionDir, err := getSessionDir() + if err != nil { + return "", err.Trace() + } + + sessionDataFile := filepath.Join(sessionDir, sid+".data") + return sessionDataFile, nil } func getSessionIDs() (sids []string) { - sessionList, err := filepath.Glob(getSessionDir() + "/*.json") - if err != nil { - console.Fatalf("Unable to list session folder ‘%s’, %s", getSessionDir(), probe.NewError(err)) - } + sessionDir, err := getSessionDir() + fatalIf(err.Trace(), "Unable to access session folder.") + + sessionList, e := filepath.Glob(sessionDir + "/*.json") + fatalIf(probe.NewError(e), "Unable to access session folder ‘"+sessionDir+"’.") for _, path := range sessionList { sids = append(sids, strings.TrimSuffix(filepath.Base(path), ".json")) } return sids } - -func isSession(sid string) bool { - if _, err := os.Stat(getSessionFile(sid)); err != nil { - return false - } - return true -}