From 0bd1edfd8fa7b8a968d6a70a6a04e1ba0fc507c5 Mon Sep 17 00:00:00 2001 From: "Anand Babu (AB) Periasamy" Date: Sat, 19 Dec 2015 22:11:06 -0800 Subject: [PATCH] new alias style and numerous cleanups. --- access-main.go | 23 +- aliasconfig.go | 74 ---- cat-main.go | 15 +- cat_test.go | 54 --- common-methods.go | 105 +++-- common_methods_test.go | 69 --- config-alias-main.go | 232 ---------- config-fix.go | 242 +++++++++++ config-host-main.go | 274 ++++++------ config-main.go | 2 - config-migrate.go | 746 ++++++++++++--------------------- config-old.go | 164 ++++++++ config-utils.go | 20 +- config-v6.go | 142 ------- config-v7.go | 157 +++++++ config-version-main.go | 69 --- config.go | 82 +++- cp-main.go | 41 +- cp-url-syntax.go | 13 +- cp-url.go | 58 ++- cp_mirror_test.go | 68 --- credentials-reader.go | 202 --------- diff-main.go | 8 +- difference.go | 2 +- globals.go | 11 +- hostconfig.go | 62 --- ls-main.go | 29 +- ls.go | 1 - main.go | 4 + mb-main.go | 14 +- mb_access_test.go | 39 -- mc_test.go | 170 +------- mirror-main.go | 42 +- mirror-url.go | 14 +- pipe-main.go | 11 +- pkg/client/client.go | 16 +- pkg/client/s3/s3.go | 4 +- rm-main.go | 24 +- session-main.go | 14 +- session-v5.go => session-v6.go | 68 +-- session.go | 2 +- session_test.go | 4 +- share-download-main.go | 22 +- share-upload-main.go | 20 +- typed-errors.go | 4 - url.go | 48 +-- verify-runtime.go | 2 +- 47 files changed, 1342 insertions(+), 2145 deletions(-) delete mode 100644 aliasconfig.go delete mode 100644 cat_test.go delete mode 100644 common_methods_test.go delete mode 100644 config-alias-main.go create mode 100644 config-fix.go create mode 100644 config-old.go delete mode 100644 config-v6.go create mode 100644 config-v7.go delete mode 100644 config-version-main.go delete mode 100644 cp_mirror_test.go delete mode 100644 credentials-reader.go delete mode 100644 hostconfig.go delete mode 100644 mb_access_test.go rename session-v5.go => session-v6.go (86%) diff --git a/access-main.go b/access-main.go index 7b37b559..425fb7d4 100644 --- a/access-main.go +++ b/access-main.go @@ -56,19 +56,19 @@ FLAGS: {{end}} EXAMPLES: 1. Set bucket to "private" on Amazon S3 cloud storage. - $ mc {{.Name}} set private s3.amazonaws.com/burningman2011 + $ mc {{.Name}} set private s3/burningman2011 2. Set bucket to "public" on Amazon S3 cloud storage. - $ mc {{.Name}} set public s3.amazonaws.com/shared + $ mc {{.Name}} set public s3/shared 3. Set bucket to "authenticated" on Amazon S3 cloud storage to provide read access to IAM Authenticated Users group. - $ mc {{.Name}} set authorized s3.amazonaws.com/shared-authenticated + $ mc {{.Name}} set authorized s3/shared-authenticated 4. Get bucket permissions. - $ mc {{.Name}} get s3.amazonaws.com/shared + $ mc {{.Name}} get s3/shared 5. Get bucket permissions. - $ mc {{.Name}} get storage.googleapis.com/miniocloud + $ mc {{.Name}} get gcs/miniocloud `, } @@ -134,7 +134,7 @@ func checkAccessSyntax(ctx *cli.Context) { // doSetAccess do set access. func doSetAccess(targetURL string, targetPERMS accessPerms) *probe.Error { - clnt, err := url2Client(targetURL) + clnt, err := newClient(targetURL) if err != nil { return err.Trace(targetURL) } @@ -146,7 +146,7 @@ func doSetAccess(targetURL string, targetPERMS accessPerms) *probe.Error { // doGetAccess do get access. func doGetAccess(targetURL string) (perms accessPerms, err *probe.Error) { - clnt, err := url2Client(targetURL) + clnt, err := newClient(targetURL) if err != nil { return "", err.Trace(targetURL) } @@ -170,10 +170,7 @@ func mainAccess(ctx *cli.Context) { switch ctx.Args().First() { case "set": perms := accessPerms(ctx.Args().Tail().First()) - - URLs, err := args2URLs(ctx.Args().Tail().Tail()) - fatalIf(err.Trace(ctx.Args().Tail().Tail()...), "Unable to convert args 2 URLs.") - + URLs := ctx.Args().Tail().Tail() for _, targetURL := range URLs { err := doSetAccess(targetURL, perms) // Upon error, print and continue. @@ -190,9 +187,7 @@ func mainAccess(ctx *cli.Context) { }) } case "get": - URLs, err := args2URLs(ctx.Args().Tail()) - fatalIf(err.Trace(ctx.Args().Tail()...), "Unable to convert args 2 URLs.") - + URLs := ctx.Args().Tail() for _, targetURL := range URLs { perms, err := doGetAccess(targetURL) if err != nil { diff --git a/aliasconfig.go b/aliasconfig.go deleted file mode 100644 index 7f571c67..00000000 --- a/aliasconfig.go +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Minio Client (C) 2015 Minio, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package main - -import ( - "os" - "regexp" - "runtime" - "strings" - - "github.com/minio/mc/pkg/client" - "github.com/minio/minio-xl/pkg/probe" -) - -// isValidAliasName - Check if aliasName is a valid alias. -func isValidAliasName(aliasName string) bool { - return regexp.MustCompile("^[a-zA-Z][a-zA-Z0-9-]+$").MatchString(aliasName) -} - -// normalizeAliasedURL - remove any preceding separators. -func normalizeAliasedURL(aliasedURL string) string { - if runtime.GOOS == "windows" { - aliasedURL = strings.Replace(aliasedURL, "/", "\\", -1) - } - aliasedURL = strings.TrimPrefix(aliasedURL, string(os.PathSeparator)) - return aliasedURL -} - -// getAliasURL expands aliased (name/path) to full URL, used by url-parser. -func getAliasURL(aliasedURL string) (string, *probe.Error) { - config, err := loadMcConfig() - if err != nil { - return aliasedURL, err.Trace(aliasedURL) - } - if strings.HasPrefix(aliasedURL, "https") || strings.HasPrefix(aliasedURL, "http") { - return aliasedURL, nil - } - for hostURL := range config.Hosts { - url := client.NewURL(hostURL) - if strings.Contains(aliasedURL, url.Host) { - return url.Scheme + url.SchemeSeparator + aliasedURL, nil - } - } - normalizedAliasURL := normalizeAliasedURL(aliasedURL) - for aliasName, aliasValue := range config.Aliases { - if strings.HasPrefix(normalizedAliasURL, aliasName) { - // Match found. Expand it. - if !strings.Contains(normalizedAliasURL, string(os.PathSeparator)) { - return aliasValue, nil - } - splits := strings.SplitN(normalizedAliasURL, string(os.PathSeparator), 2) - if len(splits) == 1 { - return aliasedURL, nil // Not an aliased URL. Return as is. - } - // Matched, but path needs to be joined. - return urlJoinPath(aliasValue, splits[1]), nil - } - } - return aliasedURL, nil // No matching alias found. Return as is. -} diff --git a/cat-main.go b/cat-main.go index c60b0c63..017cc071 100644 --- a/cat-main.go +++ b/cat-main.go @@ -54,7 +54,7 @@ FLAGS: {{end}} EXAMPLES: 1. Stream an object from Amazon S3 cloud storage to mplayer standard input. - $ mc {{.Name}} s3.amazonaws.com/ferenginar/klingon_opera_aktuh_maylotah.ogg | mplayer - + $ mc {{.Name}} s3/ferenginar/klingon_opera_aktuh_maylotah.ogg | mplayer - 2. Concantenate contents of file1.txt and stdin to standard output. $ mc {{.Name}} file1.txt - > file.txt @@ -85,14 +85,10 @@ func catURL(sourceURL string) *probe.Error { case "-": reader = os.Stdin default: - sourceClnt, err := url2Client(sourceURL) - if err != nil { - return err.Trace(sourceURL) - } // Ignore size, since os.Stat() would not return proper size all the // time for local filesystem for example /proc files. - reader, err = sourceClnt.Get(0, 0) - if err != nil { + var err *probe.Error + if reader, err = getSource(sourceURL); err != nil { return err.Trace(sourceURL) } } @@ -150,10 +146,7 @@ func mainCat(ctx *cli.Context) { } // Convert arguments to URLs: expand alias, fix format. - URLs, err := args2URLs(args) - fatalIf(err.Trace(args...), "Unable to parse arguments.") - - for _, url := range URLs { + for _, url := range args { fatalIf(catURL(url).Trace(url), "Unable to read from ‘"+url+"’.") } } diff --git a/cat_test.go b/cat_test.go deleted file mode 100644 index c116f9ad..00000000 --- a/cat_test.go +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Minio Client (C) 2015 Minio, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package main - -import ( - "bytes" - "io/ioutil" - "os" - "path/filepath" - - "github.com/minio/minio-xl/pkg/probe" - . "gopkg.in/check.v1" -) - -func (s *TestSuite) TestCat(c *C) { - /// filesystem - root, e := ioutil.TempDir(os.TempDir(), "cmd-") - c.Assert(e, IsNil) - defer os.RemoveAll(root) - - objectPath := filepath.Join(root, "object1") - objectPathServer := server.URL + "/bucket/object1" - data := "hello" - - var err *probe.Error - err = putTarget(objectPath, bytes.NewReader([]byte(data)), int64(len(data))) - c.Assert(err, IsNil) - err = putTarget(objectPathServer, bytes.NewReader([]byte(data)), int64(len(data))) - c.Assert(err, IsNil) - - var sourceURLs []string - sourceURLs = append(sourceURLs, objectPath) - sourceURLs = append(sourceURLs, objectPathServer) - for _, sourceURL := range sourceURLs { - c.Assert(catURL(sourceURL), IsNil) - } - - objectPath = filepath.Join(root, "object2") - c.Assert(catURL(objectPath), Not(IsNil)) -} diff --git a/common-methods.go b/common-methods.go index f4e44159..df48b823 100644 --- a/common-methods.go +++ b/common-methods.go @@ -47,65 +47,86 @@ func isTargetURLDir(targetURL string) bool { return true } -// getSource gets a reader from URL -func getSource(sourceURL string) (reader io.ReadSeeker, err *probe.Error) { - sourceClnt, err := url2Client(sourceURL) +// getSource gets a reader from URL. +func getSource(urlStr string) (reader io.ReadSeeker, err *probe.Error) { + alias, urlStrFull, _, err := expandAlias(urlStr) if err != nil { - return nil, err.Trace(sourceURL) + return nil, err.Trace(urlStr) + } + return getSourceFromAlias(alias, urlStrFull) +} + +// getSourceFromAlias gets a reader from URL. +func getSourceFromAlias(alias string, urlStr string) (reader io.ReadSeeker, err *probe.Error) { + sourceClnt, err := newClientFromAlias(alias, urlStr) + if err != nil { + return nil, err.Trace(alias, urlStr) } return sourceClnt.Get(0, 0) } // putTarget writes to URL from reader. If length=-1, read until EOF. -func putTarget(targetURL string, reader io.ReadSeeker, size int64) *probe.Error { - targetClnt, err := url2Client(targetURL) +func putTarget(urlStr string, reader io.ReadSeeker, size int64) *probe.Error { + alias, urlStrFull, _, err := expandAlias(urlStr) if err != nil { - return err.Trace(targetURL) + return err } - contentType := guessURLContentType(targetURL) + return putTargetFromAlias(alias, urlStrFull, reader, size) +} + +// putTargetFromAlias writes to URL from reader. If length=-1, read until EOF. +func putTargetFromAlias(alias string, urlStr string, reader io.ReadSeeker, size int64) *probe.Error { + targetClnt, err := newClientFromAlias(alias, urlStr) + if err != nil { + return err.Trace(alias, urlStr) + } + contentType := guessURLContentType(urlStr) err = targetClnt.Put(reader, size, contentType) if err != nil { - return err.Trace(targetURL) + return err.Trace(alias, urlStr) } return nil } -// getNewClient gives a new client interface -func getNewClient(urlStr string, auth hostConfig) (client.Client, *probe.Error) { - url := client.NewURL(urlStr) - switch url.Type { - case client.Object: // Minio and S3 compatible cloud storage - s3Config := new(client.Config) - s3Config.AccessKeyID = func() string { - if auth.AccessKeyID == globalAccessKeyID { - return "" - } - return auth.AccessKeyID - }() - s3Config.SecretAccessKey = func() string { - if auth.SecretAccessKey == globalSecretAccessKey { - return "" - } - return auth.SecretAccessKey - }() - s3Config.Signature = auth.API - s3Config.AppName = "Minio" - s3Config.AppVersion = mcVersion - s3Config.AppComments = []string{os.Args[0], runtime.GOOS, runtime.GOARCH} - s3Config.HostURL = urlStr - s3Config.Debug = globalDebug - - s3Client, err := s3.New(s3Config) - if err != nil { - return nil, err.Trace(urlStr) - } - return s3Client, nil - case client.Filesystem: +// newClientFromAlias gives a new client interface for matching +// alias entry in the mc config file. If no matching host config entry +// is found, fs client is returned. +func newClientFromAlias(alias string, urlStr string) (client.Client, *probe.Error) { + hostCfg := mustGetHostConfig(alias) + if hostCfg == nil { + // No matching host config. So we treat it like a + // filesystem. fsClient, err := fs.New(urlStr) if err != nil { - return nil, err.Trace(urlStr) + return nil, err.Trace(alias, urlStr) } return fsClient, nil } - return nil, errInitClient(urlStr).Trace(urlStr) + + // We have a valid alias and hostConfig. We populate the + // credentials from the match found in the config file. + s3Config := new(client.Config) + s3Config.AccessKey = hostCfg.AccessKey + s3Config.SecretKey = hostCfg.SecretKey + s3Config.Signature = hostCfg.API + s3Config.AppName = "Minio" + s3Config.AppVersion = mcVersion + s3Config.AppComments = []string{os.Args[0], runtime.GOOS, runtime.GOARCH} + s3Config.HostURL = urlStr + s3Config.Debug = globalDebug + + s3Client, err := s3.New(s3Config) + if err != nil { + return nil, err.Trace(alias, urlStr) + } + return s3Client, nil +} + +// newClient gives a new client interface +func newClient(urlStr string) (client.Client, *probe.Error) { + alias, urlStrFull, _, err := expandAlias(urlStr) + if err != nil { + return nil, err.Trace(urlStr) + } + return newClientFromAlias(alias, urlStrFull) } diff --git a/common_methods_test.go b/common_methods_test.go deleted file mode 100644 index 272d1fd6..00000000 --- a/common_methods_test.go +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Minio Client (C) 2015 Minio, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package main - -import ( - "bytes" - "io" - "io/ioutil" - "os" - "path/filepath" - - . "gopkg.in/check.v1" -) - -func (s *TestSuite) TestCommonMethods(c *C) { - /// filesystem - root, e := ioutil.TempDir(os.TempDir(), "cmd-") - c.Assert(e, IsNil) - defer os.RemoveAll(root) - - objectPath := filepath.Join(root, "object1") - - c.Assert(isTargetURLDir(root), Equals, true) - c.Assert(isTargetURLDir(objectPath), Equals, false) - - objectPathServer := server.URL + "/bucket/object1" - data := "hello" - err := putTarget(objectPath, bytes.NewReader([]byte(data)), int64(len(data))) - c.Assert(err, IsNil) - err = putTarget(objectPathServer, bytes.NewReader([]byte(data)), int64(len(data))) - c.Assert(err, IsNil) - - c.Assert(isTargetURLDir(objectPathServer), Equals, false) - c.Assert(isTargetURLDir(server.URL+"/bucket"), Equals, true) - - reader, err := getSource(objectPathServer) - c.Assert(err, IsNil) - var results bytes.Buffer - _, e = io.Copy(&results, reader) - c.Assert(e, IsNil) - c.Assert([]byte(data), DeepEquals, results.Bytes()) - - _, content, err := url2Stat(objectPathServer) - c.Assert(err, IsNil) - c.Assert(content.Type.IsRegular(), Equals, true) - - _, _, err = url2Stat(objectPath + "invalid") - c.Assert(err, Not(IsNil)) - - _, err = url2Client(objectPathServer) - c.Assert(err, IsNil) - - _, err = url2Client(objectPathServer) - c.Assert(err, IsNil) -} diff --git a/config-alias-main.go b/config-alias-main.go deleted file mode 100644 index 1fe00853..00000000 --- a/config-alias-main.go +++ /dev/null @@ -1,232 +0,0 @@ -/* - * Minio Client (C) 2015 Minio, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package main - -import ( - "encoding/json" - "fmt" - "strings" - - "github.com/fatih/color" - "github.com/minio/cli" - "github.com/minio/mc/pkg/console" - "github.com/minio/minio-xl/pkg/probe" -) - -var ( - configAliasFlags = []cli.Flag{ - cli.BoolFlag{ - Name: "help, h", - Usage: "Help of config alias.", - }, - } -) - -var configAliasCmd = cli.Command{ - Name: "alias", - Usage: "List, modify and remove aliases in configuration file.", - Action: mainConfigAlias, - Flags: append(configAliasFlags, globalFlags...), - CustomHelpTemplate: `NAME: - mc config {{.Name}} - {{.Usage}} - -USAGE: - mc config {{.Name}} [FLAGS] OPERATION [ARGS...] - -OPERATION: - remove Remove a alias. - list List all aliases. - add Add new alias. - -FLAGS: - {{range .Flags}}{{.}} - {{end}} -EXAMPLES: - 1. Add aliases for Amazon S3. - $ mc config {{.Name}} add mcloud https://miniocloud.s3.amazonaws.com - $ mc ls mcloud - - 2. Add aliases for Google Cloud Storage. - $ mc config {{.Name}} add gcscloud https://miniocloud.storage.googleapis.com - $ mc ls gcscloud - - 3. List all aliased URLs. - $ mc config {{.Name}} list - - 4. Remove an alias - $ mc config {{.Name}} remove mcloud - -`, -} - -// aliasMessage container for content message structure -type aliasMessage struct { - op string - Status string `json:"status"` - Alias string `json:"alias"` - URL string `json:"url,omitempty"` -} - -// String colorized alias message -func (a aliasMessage) String() string { - if a.op == "list" { - message := console.Colorize("Alias", fmt.Sprintf("[%s] <- ", a.Alias)) - message += console.Colorize("URL", fmt.Sprintf("%s", a.URL)) - return message - } - if a.op == "remove" { - return console.Colorize("AliasMessage", "Removed alias ‘"+a.Alias+"’ successfully.") - } - if a.op == "add" { - return console.Colorize("AliasMessage", "Added alias ‘"+a.Alias+"’ successfully.") - } - // should never come here - return "" -} - -// JSON jsonified alias message -func (a aliasMessage) JSON() string { - a.Status = "success" - jsonMessageBytes, e := json.Marshal(a) - fatalIf(probe.NewError(e), "Unable to marshal into JSON.") - - return string(jsonMessageBytes) -} - -// checkConfigAliasAddSyntax validate 'config alias add' input arguments. -func checkConfigAliasAddSyntax(ctx *cli.Context) { - if len(ctx.Args().Tail()) != 2 { - fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...), - "Incorrect number of arguments for add alias command.") - } - aliasName := ctx.Args().Tail().Get(0) - aliasedURL := ctx.Args().Tail().Get(1) - if aliasName == "" || aliasedURL == "" { - fatalIf(errDummy().Trace(), "Alias or URL cannot be empty.") - } - aliasedURL = strings.TrimSuffix(aliasedURL, "/") - if !strings.HasPrefix(aliasedURL, "http") { - fatalIf(errDummy().Trace(aliasedURL), - fmt.Sprintf("Invalid alias URL ‘%s’. Valid examples are: http://s3.amazonaws.com, https://yourbucket.example.com.", aliasedURL)) - } - if !isValidAliasName(aliasName) { - fatalIf(errDummy().Trace(aliasName), - fmt.Sprintf("Alias name ‘%s’ is invalid, valid examples are: mybucket, Area51, Grand-Nagus", aliasName)) - } -} - -// checkConfigAliasRemoveSyntax validate 'config alias remove' input argument. -func checkConfigAliasRemoveSyntax(ctx *cli.Context) { - if len(ctx.Args().Tail()) != 1 { - fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...), - "Incorrect number of arguments for remove alias command.") - } - aliasName := ctx.Args().Tail().Get(0) - if strings.TrimSpace(aliasName) == "" { - fatalIf(errDummy().Trace(), "Alias or URL cannot be empty.") - } - if !isValidAliasName(aliasName) { - fatalIf(errDummy().Trace(aliasName), - fmt.Sprintf("Alias name ‘%s’ is invalid, valid examples are: mybucket, Area51, Grand-Nagus", aliasName)) - } -} - -func checkConfigAliasSyntax(ctx *cli.Context) { - // show help if nothing is set - if !ctx.Args().Present() || ctx.Args().First() == "help" { - cli.ShowCommandHelpAndExit(ctx, "alias", 1) // last argument is exit code - } - if strings.TrimSpace(ctx.Args().First()) == "" { - cli.ShowCommandHelpAndExit(ctx, "alias", 1) // last argument is exit code - } - if len(ctx.Args().Tail()) > 2 { - fatalIf(errDummy().Trace(ctx.Args().Tail()...), "Incorrect number of arguments to alias command") - } - switch strings.TrimSpace(ctx.Args().Get(0)) { - case "add": - checkConfigAliasAddSyntax(ctx) - case "remove": - checkConfigAliasRemoveSyntax(ctx) - case "list": - default: - cli.ShowCommandHelpAndExit(ctx, "alias", 1) // last argument is exit code - } -} - -// addAlias - adds an alias entry. -func addAlias(aliasName, aliasedURL string) { - conf, err := loadMcConfig() - fatalIf(err.Trace(globalMCConfigVersion), "Unable to load config version ‘"+globalMCConfigVersion+"’.") - - conf.Aliases[aliasName] = aliasedURL - - err = saveMcConfig(conf) - fatalIf(err.Trace(aliasName, aliasedURL), "Unable to update aliases in config version ‘"+globalMCConfigVersion+"’.") - - printMsg(aliasMessage{op: "add", Alias: aliasName, URL: aliasedURL}) -} - -// removeAlias - remove a alias. -func removeAlias(aliasName string) { - conf, err := loadMcConfig() - fatalIf(err.Trace(globalMCConfigVersion), "Unable to load config version ‘"+globalMCConfigVersion+"’.") - - delete(conf.Aliases, aliasName) - - err = saveMcConfig(conf) - fatalIf(err.Trace(aliasName), "Unable to save deleted alias in config version ‘"+globalMCConfigVersion+"’.") - - printMsg(aliasMessage{op: "remove", Alias: aliasName}) -} - -// listAliases - list aliases. -func listAliases() { - conf, err := loadMcConfig() - fatalIf(err.Trace(globalMCConfigVersion), "Unable to load config version ‘"+globalMCConfigVersion+"’") - - for aliasName, aliasedURL := range conf.Aliases { - printMsg(aliasMessage{op: "list", Alias: aliasName, URL: aliasedURL}) - } -} - -func mainConfigAlias(ctx *cli.Context) { - // Set global flags from context. - setGlobalsFromContext(ctx) - - // check 'config alias' cli arguments. - checkConfigAliasSyntax(ctx) - - // Additional customization speific to each command. - console.SetColor("Alias", color.New(color.FgCyan, color.Bold)) - console.SetColor("AliasMessage", color.New(color.FgGreen, color.Bold)) - console.SetColor("URL", color.New(color.FgWhite, color.Bold)) - - arg := ctx.Args().First() - tailArgs := ctx.Args().Tail() - - switch strings.TrimSpace(arg) { - case "add": - aliasName := tailArgs.Get(0) - aliasedURL := tailArgs.Get(1) - addAlias(aliasName, aliasedURL) // add alias name for aliased URL. - case "remove": - aliasName := tailArgs.Get(0) - removeAlias(aliasName) // remove alias name. - case "list": - listAliases() // list all aliases. - } -} diff --git a/config-fix.go b/config-fix.go new file mode 100644 index 00000000..39998e15 --- /dev/null +++ b/config-fix.go @@ -0,0 +1,242 @@ +/* + * Minio Client (C) 2015 Minio, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package main + +import ( + "fmt" + "strings" + + "github.com/minio/mc/pkg/client" + "github.com/minio/mc/pkg/console" + "github.com/minio/minio-xl/pkg/quick" +) + +func fixConfig() { + // Fix config V3 + fixConfigV3() + // Fix config V6 + fixConfigV6() + // Fix config V6 for hosts + fixConfigV6ForHosts() + + /* No more fixing job. Here after we bump the version for changes always. + */ +} + +/////////////////// Broken Config V3 /////////////////// +type brokenHostConfigV3 struct { + AccessKeyID string + SecretAccessKey string +} + +type brokenConfigV3 struct { + Version string + ACL string + Access string + Aliases map[string]string + Hosts map[string]brokenHostConfigV3 +} + +// newConfigV3 - get new config broken version 3. +func newBrokenConfigV3() *brokenConfigV3 { + conf := new(brokenConfigV3) + conf.Version = "3" + conf.Aliases = make(map[string]string) + conf.Hosts = make(map[string]brokenHostConfigV3) + return conf +} + +// Fix config version ‘3’. Some v3 config files are written without +// proper hostConfig JSON tags. They may also contain unused ACL and +// Access fields. Rewrite the hostConfig with proper fields using JSON +// tags and drop the unsed (ACL, Access) fields. +func fixConfigV3() { + if !isMcConfigExists() { + return + } + brokenCfgV3 := newBrokenConfigV3() + brokenMcCfgV3, err := quick.Load(mustGetMcConfigPath(), brokenCfgV3) + fatalIf(err.Trace(), "Unable to load config.") + + if brokenMcCfgV3.Version() != "3" { + return + } + + cfgV3 := newConfigV3() + isMutated := false + for k, v := range brokenMcCfgV3.Data().(*brokenConfigV3).Aliases { + cfgV3.Aliases[k] = v + } + + for host, brokenHostCfgV3 := range brokenMcCfgV3.Data().(*brokenConfigV3).Hosts { + + // If any of these fields contains any real value anytime, + // it means we have already fixed the broken configuration. + // We don't have to regenerate again. + if brokenHostCfgV3.AccessKeyID != "" && brokenHostCfgV3.SecretAccessKey != "" { + isMutated = true + } + + // Use the correct hostConfig with JSON tags in it. + cfgV3.Hosts[host] = hostConfigV3{ + AccessKeyID: brokenHostCfgV3.AccessKeyID, + SecretAccessKey: brokenHostCfgV3.SecretAccessKey, + } + } + + // We blindly drop ACL and Access fields from the broken config v3. + + if isMutated { + mcNewConfigV3, err := quick.New(cfgV3) + fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘3’.") + + err = mcNewConfigV3.Save(mustGetMcConfigPath()) + fatalIf(err.Trace(), "Unable to save config version ‘3’.") + + console.Infof("Successfully fixed %s broken config for version ‘3’.\n", mustGetMcConfigPath()) + } +} + +// If the host key does not have http(s), fix it. +func fixConfigV6ForHosts() { + if !isMcConfigExists() { + return + } + + brokenMcCfgV6, err := quick.Load(mustGetMcConfigPath(), newConfigV6()) + fatalIf(err.Trace(), "Unable to load config.") + + if brokenMcCfgV6.Version() != "6" { + return + } + + newCfgV6 := newConfigV6() + isMutated := false + + // Copy aliases. + for k, v := range brokenMcCfgV6.Data().(*configV6).Aliases { + newCfgV6.Aliases[k] = v + } + + url := new(client.URL) + // Copy hosts. + for host, hostCfgV6 := range brokenMcCfgV6.Data().(*configV6).Hosts { + // Already fixed - Copy and move on. + if strings.HasPrefix(host, "https") || strings.HasPrefix(host, "http") { + newCfgV6.Hosts[host] = hostCfgV6 + continue + } + + // If host entry does not contain "http(s)", introduce a new entry and delete the old one. + if host == "s3.amazonaws.com" || host == "storage.googleapis.com" || + host == "localhost:9000" || host == "127.0.0.1:9000" || + host == "play.minio.io:9000" || host == "dl.minio.io:9000" { + console.Infoln("Found broken host entries, replacing " + host + " with https://" + host + ".") + url.Host = host + url.Scheme = "https" + url.SchemeSeparator = "://" + newCfgV6.Hosts[url.String()] = hostCfgV6 + isMutated = true + continue + } + } + + if isMutated { + // Save the new config back to the disk. + mcCfgV6, err := quick.New(newCfgV6) + fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘v6’.") + + err = mcCfgV6.Save(mustGetMcConfigPath()) + fatalIf(err.Trace(), "Unable to save config version ‘v6’.") + } +} + +// fixConfigV6 - fix all the unnecessary glob URLs present in existing config version 6. +func fixConfigV6() { + if !isMcConfigExists() { + return + } + config, err := quick.New(newConfigV6()) + fatalIf(err.Trace(), "Unable to initialize config.") + + err = config.Load(mustGetMcConfigPath()) + fatalIf(err.Trace(mustGetMcConfigPath()), "Unable to load config.") + + if config.Data().(*configV6).Version != "6" { + return + } + + newConfig := new(configV6) + isMutated := false + newConfig.Aliases = make(map[string]string) + newConfig.Hosts = make(map[string]hostConfigV6) + newConfig.Version = "6" + newConfig.Aliases = config.Data().(*configV6).Aliases + for host, hostCfg := range config.Data().(*configV6).Hosts { + if strings.Contains(host, "*") { + fatalIf(err.Trace(), + fmt.Sprintf("Glob style ‘*’ pattern matching is no longer supported. Please fix ‘%s’ entry manually.", host)) + } + if strings.Contains(host, "*s3*") || strings.Contains(host, "*.s3*") { + console.Infoln("Found glob url, replacing " + host + " with s3.amazonaws.com") + newConfig.Hosts["s3.amazonaws.com"] = hostCfg + isMutated = true + continue + } + if strings.Contains(host, "s3*") { + console.Infoln("Found glob url, replacing " + host + " with s3.amazonaws.com") + newConfig.Hosts["s3.amazonaws.com"] = hostCfg + isMutated = true + continue + } + if strings.Contains(host, "*amazonaws.com") || strings.Contains(host, "*.amazonaws.com") { + console.Infoln("Found glob url, replacing " + host + " with s3.amazonaws.com") + newConfig.Hosts["s3.amazonaws.com"] = hostCfg + isMutated = true + continue + } + if strings.Contains(host, "*storage.googleapis.com") { + console.Infoln("Found glob url, replacing " + host + " with storage.googleapis.com") + newConfig.Hosts["storage.googleapis.com"] = hostCfg + isMutated = true + continue + } + if strings.Contains(host, "localhost:*") { + console.Infoln("Found glob url, replacing " + host + " with localhost:9000") + newConfig.Hosts["localhost:9000"] = hostCfg + isMutated = true + continue + } + if strings.Contains(host, "127.0.0.1:*") { + console.Infoln("Found glob url, replacing " + host + " with 127.0.0.1:9000") + newConfig.Hosts["127.0.0.1:9000"] = hostCfg + isMutated = true + continue + } + // Other entries are hopefully OK. Copy them blindly. + newConfig.Hosts[host] = hostCfg + } + + if isMutated { + newConf, err := quick.New(newConfig) + fatalIf(err.Trace(), "Unable to initialize newly fixed config.") + + err = newConf.Save(mustGetMcConfigPath()) + fatalIf(err.Trace(mustGetMcConfigPath()), "Unable to save newly fixed config path.") + console.Infof("Successfully fixed %s broken config for version ‘6’.\n", mustGetMcConfigPath()) + } +} diff --git a/config-host-main.go b/config-host-main.go index 97c2b420..901ad980 100644 --- a/config-host-main.go +++ b/config-host-main.go @@ -45,95 +45,84 @@ var configHostCmd = cli.Command{ mc config {{.Name}} - {{.Usage}} USAGE: - mc config {{.Name}} OPERATION [ARGS...] + mc config {{.Name}} OPERATION OPERATION: - remove Remove a host. - list list all hosts. - add Add new host. + add ALIAS URL ACCESS-KEY SECRET-KEY [API] + remove ALIAS + list FLAGS: {{range .Flags}}{{.}} {{end}} EXAMPLES: - 1. Add host configuration for a URL, using default signature V4. For security reasons turn off bash history + 1. Add Amazon S3 storage service under "myphotos" alias. For security reasons turn off bash history momentarily. $ set +o history - $ mc config {{.Name}} add https://s3.amazonaws.com BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 + $ mc config {{.Name}} add myphotos https://s3.amazonaws.com BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 $ set -o history - 2. Add host configuration for a URL, using signature V2. For security reasons turn off bash history - $ set +o history - $ mc config {{.Name}} add https://storage.googleapis.com BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 S3v2 - $ set -o history + 2. Add Google Cloud Storage service under "goodisk" alias. + $ mc config {{.Name}} add goodisk https://storage.googleapis.com BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 S3v2 - 3. Add host configuration for a URL by importing credentials csv file. - $ mc config {{.Name}} import https://s3.amazonaws.com credentials.csv - - 4. List all hosts. + 3. List all hosts. $ mc config {{.Name}} list - 5. Remove host config. - $ mc config {{.Name}} remove https://s3.amazonaws.com - + 4. Remove "goodisk" config. + $ mc config {{.Name}} remove goodisk `, } // hostMessage container for content message structure type hostMessage struct { - op string - Status string `json:"status"` - Host string `json:"host"` - AccessKeyID string `json:"accessKeyId,omitempty"` - SecretAccessKey string `json:"secretAccessKey,omitempty"` - API string `json:"api,omitempty"` + op string + Status string `json:"status"` + Alias string `json:"alias"` + URL string `json:"URL"` + AccessKey string `json:"accessKey,omitempty"` + SecretKey string `json:"secretKey,omitempty"` + API string `json:"api,omitempty"` } // String colorized host message -func (a hostMessage) String() string { - if a.op == "list" { - message := console.Colorize("Host", fmt.Sprintf("[%s] ", a.Host)) - if a.AccessKeyID != "" || a.SecretAccessKey != "" { - message += console.Colorize("AccessKeyID", fmt.Sprintf("<- %s,", a.AccessKeyID)) - message += console.Colorize("SecretAccessKey", fmt.Sprintf(" %s,", a.SecretAccessKey)) - message += console.Colorize("API", fmt.Sprintf(" %s", a.API)) +func (h hostMessage) String() string { + switch h.op { + case "list": + message := console.Colorize("Alias", fmt.Sprintf("%s: ", h.Alias)) + message += console.Colorize("URL", fmt.Sprintf("%s", h.URL)) + if h.AccessKey != "" || h.SecretKey != "" { + message += " | " + console.Colorize("AccessKey", fmt.Sprintf("<- %s,", h.AccessKey)) + message += " | " + console.Colorize("SecretKey", fmt.Sprintf(" %s,", h.SecretKey)) + message += " | " + console.Colorize("API", fmt.Sprintf(" %s", h.API)) } return message + case "remove": + return console.Colorize("HostMessage", "Removed ‘"+h.Alias+"’ successfully.") + case "add": + return console.Colorize("HostMessage", "Added ‘"+h.Alias+"’ successfully.") + default: + return "" } - if a.op == "remove" { - return console.Colorize("HostMessage", "Removed host ‘"+a.Host+"’ successfully.") - } - if a.op == "add" { - return console.Colorize("HostMessage", "Added host ‘"+a.Host+"’ successfully.") - } - // should never reach here - return "" } // JSON jsonified host message -func (a hostMessage) JSON() string { - a.Status = "success" - jsonMessageBytes, e := json.Marshal(a) +func (h hostMessage) JSON() string { + h.Status = "success" + jsonMessageBytes, e := json.Marshal(h) fatalIf(probe.NewError(e), "Unable to marshal into JSON.") return string(jsonMessageBytes) } +// Validate command-line input args. func checkConfigHostSyntax(ctx *cli.Context) { // show help if nothing is set - if !ctx.Args().Present() || ctx.Args().First() == "help" { + if !ctx.Args().Present() { cli.ShowCommandHelpAndExit(ctx, "host", 1) // last argument is exit code } - if strings.TrimSpace(ctx.Args().First()) == "" { - cli.ShowCommandHelpAndExit(ctx, "host", 1) // last argument is exit code - } - if len(ctx.Args().Tail()) > 4 { - fatalIf(errDummy().Trace(ctx.Args().Tail()...), "Incorrect number of arguments to host command") - } + switch strings.TrimSpace(ctx.Args().First()) { case "add": checkConfigHostAddSyntax(ctx) - case "import": - checkConfigHostImportSyntax(ctx) case "remove": checkConfigHostRemoveSyntax(ctx) case "list": @@ -142,76 +131,59 @@ func checkConfigHostSyntax(ctx *cli.Context) { } } -// checkConfigHostImportSyntax - verifies input arguments to 'config host import'. -func checkConfigHostImportSyntax(ctx *cli.Context) { - tailArgs := ctx.Args().Tail() - if len(ctx.Args().Tail()) < 2 || len(ctx.Args().Tail()) > 3 { - fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...), - "Incorrect number of arguments for import host command.") - } - - newHostURL := tailArgs.Get(0) - credentialsFile := tailArgs.Get(1) - api := tailArgs.Get(2) - - if !isValidHostURL(newHostURL) { - fatalIf(errDummy().Trace(newHostURL), - "Invalid host ‘"+newHostURL+"’. Valid options are [http://example.test.io, https://bucket.s3.amazonaws.com].") - } - if strings.TrimSpace(credentialsFile) == "" { - fatalIf(errDummy().Trace(), "Credentials file cannot be empty.") - } - if strings.TrimSpace(api) == "" { - api = "S3v4" - } - if strings.TrimSpace(api) != "S3v2" && strings.TrimSpace(api) != "S3v4" { - fatalIf(errInvalidArgument().Trace(api), - "Unrecognized api version. Valid options are ‘[ S3v4, S3v2 ]’.") - } -} - // checkConfigHostAddSyntax - verifies input arguments to 'config host add'. func checkConfigHostAddSyntax(ctx *cli.Context) { tailArgs := ctx.Args().Tail() - if len(ctx.Args().Tail()) < 3 || len(ctx.Args().Tail()) > 4 { + if len(ctx.Args().Tail()) != 5 { fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...), "Incorrect number of arguments for host add command.") } - newHostURL := tailArgs.Get(0) - accessKeyID := tailArgs.Get(1) - secretAccessKey := tailArgs.Get(2) - api := tailArgs.Get(3) - if !isValidHostURL(newHostURL) { - fatalIf(errDummy().Trace(newHostURL), - "Invalid host URL: ‘"+newHostURL+"’. Valid options are [http://example.test.io, https://bucket.s3.amazonaws.com].") + + alias := tailArgs.Get(0) + url := tailArgs.Get(1) + accessKey := tailArgs.Get(2) + secretKey := tailArgs.Get(3) + api := tailArgs.Get(4) + + if !isValidAlias(alias) { + fatalIf(errDummy().Trace(alias), "Invalid alias ‘"+alias+"’.") } - if !isValidKeys(accessKeyID, secretAccessKey) { - fatalIf(errInvalidArgument().Trace(accessKeyID, secretAccessKey), - "Invalid access key id/secret access key for ‘"+newHostURL+"’") + + if !isValidHostURL(url) { + fatalIf(errDummy().Trace(url), + "Invalid URL ‘"+url+"’.") } - if strings.TrimSpace(api) == "" { - api = "S3v4" + + if !isValidAccessKey(accessKey) { + fatalIf(errInvalidArgument().Trace(accessKey), + "Invalid access key ‘"+accessKey+"’.") } - if strings.TrimSpace(api) != "S3v2" && strings.TrimSpace(api) != "S3v4" { + + if !isValidSecretKey(secretKey) { + fatalIf(errInvalidArgument().Trace(secretKey), + "Invalid secret key ‘"+secretKey+"’.") + } + + switch api { + case "S3v2", "S3v4", "": + default: fatalIf(errInvalidArgument().Trace(api), - "Unrecognized api version. Valid options are ‘[ S3v4, S3v2 ]’.") + "Unrecognized API signature. Valid options are ‘[ S3v4, S3v2 ]’.") } } // checkConfigHostRemoveSyntax - verifies input arguments to 'config host remove'. func checkConfigHostRemoveSyntax(ctx *cli.Context) { tailArgs := ctx.Args().Tail() + if len(ctx.Args().Tail()) != 1 { - fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...), + fatalIf(errInvalidArgument().Trace(tailArgs...), "Incorrect number of arguments for remove host command.") } - if !isValidHostURL(tailArgs.Get(0)) { + + if !isValidAlias(tailArgs.Get(0)) { fatalIf(errDummy().Trace(tailArgs.Get(0)), - "Invalid host ‘"+tailArgs.Get(0)+"’. Valid options are [http://example.test.io, https://bucket.s3.amazonaws.com].") - } - if strings.TrimSpace(tailArgs.Get(0)) == "https://dl.minio.io:9000" { - fatalIf(errDummy().Trace(tailArgs.Get(0)), - "‘"+tailArgs.Get(0)+"’ is reserved hostname and cannot be removed.") + "Invalid alias ‘"+tailArgs.Get(0)+"’.") } } @@ -223,102 +195,90 @@ func mainConfigHost(ctx *cli.Context) { checkConfigHostSyntax(ctx) // Additional command speific theme customization. - console.SetColor("Host", color.New(color.FgCyan, color.Bold)) - console.SetColor("API", color.New(color.FgYellow, color.Bold)) - console.SetColor("HostMessage", color.New(color.FgGreen, color.Bold)) - console.SetColor("AccessKeyID", color.New(color.FgBlue, color.Bold)) - console.SetColor("SecretAccessKey", color.New(color.FgRed, color.Bold)) + console.SetColor("HostMessage", color.New(color.FgGreen)) + console.SetColor("Alias", color.New(color.FgCyan, color.Bold)) + console.SetColor("URL", color.New(color.FgCyan)) + console.SetColor("AccessKey", color.New(color.FgBlue)) + console.SetColor("SecretKey", color.New(color.FgBlue)) + console.SetColor("API", color.New(color.FgYellow)) - arg := ctx.Args().First() - tailArgs := ctx.Args().Tail() + cmd := ctx.Args().First() + args := ctx.Args().Tail() // Switch case through commands. - switch strings.TrimSpace(arg) { + switch strings.TrimSpace(cmd) { case "add": - hostURL := tailArgs.Get(0) - accessKeyID := tailArgs.Get(1) - secretAccessKey := tailArgs.Get(2) - api := tailArgs.Get(3) + alias := args.Get(0) + url := args.Get(1) + accessKey := args.Get(2) + secretKey := args.Get(3) + api := args.Get(4) if strings.TrimSpace(api) == "" { api = "S3v4" } - hostCfg := hostConfig{ - AccessKeyID: accessKeyID, - SecretAccessKey: secretAccessKey, - API: api, + hostCfg := hostConfigV7{ + URL: url, + AccessKey: accessKey, + SecretKey: secretKey, + API: api, } - addHost(hostURL, hostCfg) // Add a host with specified credentials. - case "import": - hostURL := tailArgs.Get(0) - credentialsFile := tailArgs.Get(1) - api := tailArgs.Get(2) - if strings.TrimSpace(api) == "" { - api = "S3v4" - } - creds, err := getCredentials(credentialsFile) - fatalIf(err.Trace(credentialsFile), "Unable to unmarshal CSV credentials file ‘"+credentialsFile+"’") - - var hostCfg hostConfig - hostCfg = hostConfig{ - AccessKeyID: creds[0].AccessKeyID, - SecretAccessKey: creds[0].SecretAccessKey, - API: api, - } - addHost(hostURL, hostCfg) // Import credentials through a CSV file for a host. + addHost(alias, hostCfg) // Add a host with specified credentials. case "remove": - hostURL := tailArgs.Get(0) - removeHost(hostURL) // Remove a host. + alias := args.Get(0) + removeHost(alias) // Remove a host. case "list": listHosts() // List all configured hosts. } } // addHost - add a host config. -func addHost(hostURL string, hostCfg hostConfig) { - conf, err := loadMcConfig() - fatalIf(err.Trace(globalMCConfigVersion), "Unable to load config version ‘"+globalMCConfigVersion+"’.") +func addHost(alias string, hostCfgV7 hostConfigV7) { + mcCfgV7, err := loadMcConfig() + fatalIf(err.Trace(globalMCConfigVersion), "Unable to load config ‘"+mustGetMcConfigPath()+"’.") // Add new host. - conf.Hosts[hostURL] = hostCfg + mcCfgV7.Hosts[alias] = hostCfgV7 - err = saveMcConfig(conf) - fatalIf(err.Trace(hostURL), "Unable to update hosts in config version ‘"+globalMCConfigVersion+"’.") + err = saveMcConfig(mcCfgV7) + fatalIf(err.Trace(alias), "Unable to update hosts in config version ‘"+mustGetMcConfigPath()+"’.") printMsg(hostMessage{ - op: "add", - Host: hostURL, - AccessKeyID: hostCfg.AccessKeyID, - SecretAccessKey: hostCfg.SecretAccessKey, - API: hostCfg.API, + op: "add", + Alias: alias, + URL: hostCfgV7.URL, + AccessKey: hostCfgV7.AccessKey, + SecretKey: hostCfgV7.SecretKey, + API: hostCfgV7.API, }) } // removeHost - removes a host. -func removeHost(hostURL string) { +func removeHost(alias string) { conf, err := loadMcConfig() fatalIf(err.Trace(globalMCConfigVersion), "Unable to load config version ‘"+globalMCConfigVersion+"’.") // Remove host. - delete(conf.Hosts, hostURL) + delete(conf.Hosts, alias) err = saveMcConfig(conf) - fatalIf(err.Trace(hostURL), "Unable to save deleted hosts in config version ‘"+globalMCConfigVersion+"’.") + fatalIf(err.Trace(alias), "Unable to save deleted hosts in config version ‘"+globalMCConfigVersion+"’.") - printMsg(hostMessage{op: "remove", Host: hostURL}) + printMsg(hostMessage{op: "remove", Alias: alias}) } // listHosts - list all host URLs. func listHosts() { conf, err := loadMcConfig() - fatalIf(err.Trace(globalMCConfigVersion), "Unable to load config version ‘"+globalMCConfigVersion+"’") + fatalIf(err.Trace(globalMCConfigVersion), "Unable to load config version ‘"+globalMCConfigVersion+"’.") for k, v := range conf.Hosts { printMsg(hostMessage{ - op: "list", - Host: k, - AccessKeyID: v.AccessKeyID, - SecretAccessKey: v.SecretAccessKey, - API: v.API, + op: "list", + Alias: k, + URL: v.URL, + AccessKey: v.AccessKey, + SecretKey: v.SecretKey, + API: v.API, }) } } diff --git a/config-main.go b/config-main.go index 3a6bfa22..c0972506 100644 --- a/config-main.go +++ b/config-main.go @@ -44,9 +44,7 @@ var configCmd = cli.Command{ Action: mainConfig, Flags: append(configFlags, globalFlags...), Subcommands: []cli.Command{ - configAliasCmd, configHostCmd, - configVersionCmd, }, CustomHelpTemplate: `NAME: {{.Name}} - {{.Usage}} diff --git a/config-migrate.go b/config-migrate.go index 82c19b29..210c7716 100644 --- a/config-migrate.go +++ b/config-migrate.go @@ -17,13 +17,14 @@ package main import ( + "fmt" "strings" - "github.com/minio/mc/pkg/client" "github.com/minio/mc/pkg/console" "github.com/minio/minio-xl/pkg/quick" ) +// migrate config files from the any older version to the latest. func migrateConfig() { // Migrate config V1 to V101 migrateConfigV1ToV101() @@ -37,544 +38,343 @@ func migrateConfig() { migrateConfigV4ToV5() // Migrate config V5 to V6 migrateConfigV5ToV6() + // Migrate config V6 to V7 + migrateConfigV6ToV7() } -func fixConfig() { - // Fix config V3 - fixConfigV3() - // Fix config V6 - fixConfigV6() - // Fix config V6 for hosts - fixConfigV6ForHosts() -} - -func fixConfigV6ForHosts() { - if !isMcConfigExists() { - return - } - config, err := quick.New(newConfigV6()) - fatalIf(err.Trace(), "Unable to initialize config.") - - err = config.Load(mustGetMcConfigPath()) - fatalIf(err.Trace(), "Unable to load config.") - - if config.Data().(*configV6).Version == "6" { - newConfig := new(configV6) - newConfig.Aliases = make(map[string]string) - newConfig.Hosts = make(map[string]hostConfig) - newConfig.Version = "6" - newConfig.Aliases = config.Data().(*configV6).Aliases - - url := new(client.URL) - for host, hostCfg := range config.Data().(*configV6).Hosts { - // Already fixed - move on. - if strings.HasPrefix(host, "https") || strings.HasPrefix(host, "http") { - newConfig.Hosts[host] = hostCfg - continue - } - if host == "s3.amazonaws.com" || host == "storage.googleapis.com" { - console.Infoln("Found hosts, replacing " + host + " with https://" + host) - url.Host = host - url.Scheme = "https" - url.SchemeSeparator = "://" - newConfig.Hosts[url.String()] = hostCfg - delete(newConfig.Hosts, host) - } - if host == "localhost:9000" || host == "127.0.0.1:9000" { - console.Infoln("Found hosts, replacing " + host + " with http://" + host) - url.Host = host - url.Scheme = "http" - url.SchemeSeparator = "://" - newConfig.Hosts[url.String()] = hostCfg - delete(newConfig.Hosts, host) - } - if host == "play.minio.io:9000" || host == "dl.minio.io:9000" { - console.Infoln("Found hosts, replacing " + host + " with https://" + host) - url.Host = host - url.Scheme = "https" - url.SchemeSeparator = "://" - newConfig.Hosts[url.String()] = hostCfg - delete(newConfig.Hosts, host) - } - } - newConf, err := quick.New(newConfig) - fatalIf(err.Trace(), "Unable to initialize newly fixed config.") - - err = newConf.Save(mustGetMcConfigPath()) - fatalIf(err.Trace(mustGetMcConfigPath()), "Unable to save newly fixed config path.") - } -} - -// fixConfigV6 - fix all the unnecessary glob URLs present in existing config version 6. -func fixConfigV6() { - if !isMcConfigExists() { - return - } - config, err := quick.New(newConfigV6()) - fatalIf(err.Trace(), "Unable to initialize config.") - - err = config.Load(mustGetMcConfigPath()) - fatalIf(err.Trace(mustGetMcConfigPath()), "Unable to load config.") - - if config.Data().(*configV6).Version == "6" { - newConfig := new(configV6) - newConfig.Aliases = make(map[string]string) - newConfig.Hosts = make(map[string]hostConfig) - newConfig.Version = "6" - newConfig.Aliases = config.Data().(*configV6).Aliases - for host, hostCfg := range config.Data().(*configV6).Hosts { - if strings.HasPrefix(host, "https") || strings.HasPrefix(host, "http") { - newConfig.Hosts[host] = hostCfg - continue - } - if strings.Contains(host, "*s3*") || strings.Contains(host, "*.s3*") { - console.Infoln("Found glob url, replacing " + host + " with s3.amazonaws.com") - newConfig.Hosts["s3.amazonaws.com"] = hostCfg - continue - } - if strings.Contains(host, "s3*") { - console.Infoln("Found glob url, replacing " + host + " with s3.amazonaws.com") - newConfig.Hosts["s3.amazonaws.com"] = hostCfg - continue - } - if strings.Contains(host, "*amazonaws.com") || strings.Contains(host, "*.amazonaws.com") { - console.Infoln("Found glob url, replacing " + host + " with s3.amazonaws.com") - newConfig.Hosts["s3.amazonaws.com"] = hostCfg - continue - } - if strings.Contains(host, "*storage.googleapis.com") { - console.Infoln("Found glob url, replacing " + host + " with storage.googleapis.com") - newConfig.Hosts["storage.googleapis.com"] = hostCfg - continue - } - if strings.Contains(host, "localhost:*") { - console.Infoln("Found glob url, replacing " + host + " with localhost:9000") - newConfig.Hosts["localhost:9000"] = hostCfg - continue - } - if strings.Contains(host, "127.0.0.1:*") { - console.Infoln("Found glob url, replacing " + host + " with 127.0.0.1:9000") - newConfig.Hosts["127.0.0.1:9000"] = hostCfg - continue - } - newConfig.Hosts[host] = hostCfg - } - newConf, err := quick.New(newConfig) - fatalIf(err.Trace(), "Unable to initialize newly fixed config.") - - err = newConf.Save(mustGetMcConfigPath()) - fatalIf(err.Trace(mustGetMcConfigPath()), "Unable to save newly fixed config path.") - } -} - -type configV5 struct { - Version string `json:"version"` - Aliases map[string]string `json:"alias"` - Hosts map[string]hostConfig `json:"hosts"` -} - -type configV4 struct { - Version string `json:"version"` - Aliases map[string]string `json:"alias"` - Hosts map[string]struct { - AccessKeyID string `json:"accessKeyId"` - SecretAccessKey string `json:"secretAccessKey"` - Signature string `json:"signature"` - } `json:"hosts"` -} - -type configV3 struct { - Version string `json:"version"` - Aliases map[string]string `json:"alias"` - // custom anonymous struct is necessary from version to 3 to version 4 - // since hostConfig{} has changed to camelcase fields for unmarshal - Hosts map[string]struct { - AccessKeyID string `json:"access-key-id"` - SecretAccessKey string `json:"secret-access-key"` - } `json:"hosts"` -} - -type configV2 struct { - Version string - Aliases map[string]string - // custom anonymous struct is necessary from version to 2 to version 3 - // since hostConfig{} has changed to lower case fields for unmarshal - Hosts map[string]struct { - AccessKeyID string - SecretAccessKey string - } -} - -// for backward compatibility -type configV101 configV2 -type configV1 configV2 - -// Migrate from config version ‘1.0’ to ‘1.0.1’ +// Migrate from config version 1.0 to 1.0.1. Populate example entries and save it back. func migrateConfigV1ToV101() { if !isMcConfigExists() { return } - mcConfigV1, err := quick.Load(mustGetMcConfigPath(), newConfigV1()) + mcCfgV1, err := quick.Load(mustGetMcConfigPath(), newConfigV1()) fatalIf(err.Trace(), "Unable to load config version ‘1’.") - // update to newer version - if mcConfigV1.Version() == "1.0.0" { - confV101 := mcConfigV1.Data().(*configV1) - confV101.Version = "1.0.1" - - localHostConfig := struct { - AccessKeyID string - SecretAccessKey string - }{} - localHostConfig.AccessKeyID = "" - localHostConfig.SecretAccessKey = "" - - s3HostConf := struct { - AccessKeyID string - SecretAccessKey string - }{} - s3HostConf.AccessKeyID = globalAccessKeyID - s3HostConf.SecretAccessKey = globalSecretAccessKey - - if _, ok := confV101.Hosts["localhost:*"]; !ok { - confV101.Hosts["localhost:*"] = localHostConfig - } - if _, ok := confV101.Hosts["127.0.0.1:*"]; !ok { - confV101.Hosts["127.0.0.1:*"] = localHostConfig - } - if _, ok := confV101.Hosts["*.s3*.amazonaws.com"]; !ok { - confV101.Hosts["*.s3*.amazonaws.com"] = s3HostConf - } - - mcNewConfigV101, err := quick.New(confV101) - fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘1.0.1’.") - - err = mcNewConfigV101.Save(mustGetMcConfigPath()) - fatalIf(err.Trace(), "Unable to save config version ‘1.0.1’.") - - console.Infof("Successfully migrated %s from version ‘1.0.0’ to version ‘1.0.1’.\n", mustGetMcConfigPath()) + // If loaded config version does not match 1.0.0, we do nothing. + if mcCfgV1.Version() != "1.0.0" { + return } + + // 1.0.1 is compatible to 1.0.0. We are just adding new entries. + cfgV101 := newConfigV101() + + // Copy aliases. + for k, v := range mcCfgV1.Data().(*configV1).Aliases { + cfgV101.Aliases[k] = v + } + + // Copy hosts. + for k, hostCfgV1 := range mcCfgV1.Data().(*configV1).Hosts { + cfgV101.Hosts[k] = hostConfigV101{ + AccessKeyID: hostCfgV1.AccessKeyID, + SecretAccessKey: hostCfgV1.SecretAccessKey, + } + } + + // Example localhost entry. + if _, ok := cfgV101.Hosts["localhost:*"]; !ok { + cfgV101.Hosts["localhost:*"] = hostConfigV101{} + } + + // Example loopback IP entry. + if _, ok := cfgV101.Hosts["127.0.0.1:*"]; !ok { + cfgV101.Hosts["127.0.0.1:*"] = hostConfigV101{} + } + + // Example AWS entry. + // Look for glob string (not glob match). We used to support glob based key matching earlier. + if _, ok := cfgV101.Hosts["*.s3*.amazonaws.com"]; !ok { + cfgV101.Hosts["*.s3*.amazonaws.com"] = hostConfigV101{ + AccessKeyID: "YOUR-ACCESS-KEY-ID-HERE", + SecretAccessKey: "YOUR-SECRET-ACCESS-KEY-HERE", + } + } + + // Save the new config back to the disk. + mcCfgV101, err := quick.New(cfgV101) + fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘1.0.1’.") + err = mcCfgV101.Save(mustGetMcConfigPath()) + fatalIf(err.Trace(), "Unable to save config version ‘1.0.1’.") + + console.Infof("Successfully migrated %s from version ‘1.0.0’ to version ‘1.0.1’.\n", mustGetMcConfigPath()) } -// Migrate from config ‘1.0.1’ to ‘2’ +// Migrate from config ‘1.0.1’ to ‘2’. Drop semantic versioning and move to integer versioning. No other changes. func migrateConfigV101ToV2() { if !isMcConfigExists() { return } - mcConfigV101, err := quick.Load(mustGetMcConfigPath(), newConfigV101()) + mcCfgV101, err := quick.Load(mustGetMcConfigPath(), newConfigV101()) fatalIf(err.Trace(), "Unable to load config version ‘1.0.1’.") // update to newer version - if mcConfigV101.Version() == "1.0.1" { - confV2 := mcConfigV101.Data().(*configV101) - confV2.Version = "2" - - mcNewConfigV2, err := quick.New(confV2) - fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘2’.") - - err = mcNewConfigV2.Save(mustGetMcConfigPath()) - fatalIf(err.Trace(), "Unable to save config version ‘2’.") - - console.Infof("Successfully migrated %s from version ‘1.0.1’ to version ‘2’.\n", mustGetMcConfigPath()) + if mcCfgV101.Version() != "1.0.1" { + return } + + cfgV2 := newConfigV2() + + // Copy aliases. + for k, v := range mcCfgV101.Data().(*configV101).Aliases { + cfgV2.Aliases[k] = v + } + + // Copy hosts. + for k, hostCfgV101 := range mcCfgV101.Data().(*configV101).Hosts { + cfgV2.Hosts[k] = hostConfigV2{ + AccessKeyID: hostCfgV101.AccessKeyID, + SecretAccessKey: hostCfgV101.SecretAccessKey, + } + } + + mcCfgV2, err := quick.New(cfgV2) + fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘2’.") + + err = mcCfgV2.Save(mustGetMcConfigPath()) + fatalIf(err.Trace(), "Unable to save config version ‘2’.") + + console.Infof("Successfully migrated %s from version ‘1.0.1’ to version ‘2’.\n", mustGetMcConfigPath()) } -// Migrate from config ‘2’ to ‘3’ +// Migrate from config ‘2’ to ‘3’. Use ‘-’ separated names for +// hostConfig using struct json tags. func migrateConfigV2ToV3() { if !isMcConfigExists() { return } - mcConfigV2, err := quick.Load(mustGetMcConfigPath(), newConfigV2()) + + mcCfgV2, err := quick.Load(mustGetMcConfigPath(), newConfigV2()) fatalIf(err.Trace(), "Unable to load mc config V2.") // update to newer version - if mcConfigV2.Version() == "2" { - confV3 := new(configV3) - confV3.Aliases = mcConfigV2.Data().(*configV2).Aliases - confV3.Hosts = make(map[string]struct { - AccessKeyID string `json:"access-key-id"` - SecretAccessKey string `json:"secret-access-key"` - }) - for host, hostConf := range mcConfigV2.Data().(*configV2).Hosts { - newHostConf := struct { - AccessKeyID string `json:"access-key-id"` - SecretAccessKey string `json:"secret-access-key"` - }{} - newHostConf.AccessKeyID = hostConf.AccessKeyID - newHostConf.SecretAccessKey = hostConf.SecretAccessKey - confV3.Hosts[host] = newHostConf - } - confV3.Version = "3" - - mcNewConfigV3, err := quick.New(confV3) - fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘3’.") - - err = mcNewConfigV3.Save(mustGetMcConfigPath()) - fatalIf(err.Trace(), "Unable to save config version ‘3’.") - - console.Infof("Successfully migrated %s from version ‘2’ to version ‘3’.\n", mustGetMcConfigPath()) + if mcCfgV2.Version() != "2" { + return } + + cfgV3 := newConfigV3() + + // Copy aliases. + for k, v := range mcCfgV2.Data().(*configV2).Aliases { + cfgV3.Aliases[k] = v + } + + // Copy hosts. + for k, hostCfgV2 := range mcCfgV2.Data().(*configV2).Hosts { + // New hostConfV3 uses struct json tags. + cfgV3.Hosts[k] = hostConfigV3{ + AccessKeyID: hostCfgV2.AccessKeyID, + SecretAccessKey: hostCfgV2.SecretAccessKey, + } + } + + mcNewCfgV3, err := quick.New(cfgV3) + fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘3’.") + + err = mcNewCfgV3.Save(mustGetMcConfigPath()) + fatalIf(err.Trace(), "Unable to save config version ‘3’.") + + console.Infof("Successfully migrated %s from version ‘2’ to version ‘3’.\n", mustGetMcConfigPath()) } -// Migrate from config version ‘3’ to ‘4’ +// Migrate from config version ‘3’ to ‘4’. Introduce API Signature +// field in host config. Also Use JavaScript notation for field names. func migrateConfigV3ToV4() { if !isMcConfigExists() { return } - mcConfigV3, err := quick.Load(mustGetMcConfigPath(), newConfigV3()) + mcCfgV3, err := quick.Load(mustGetMcConfigPath(), newConfigV3()) fatalIf(err.Trace(), "Unable to load mc config V2.") // update to newer version - if mcConfigV3.Version() == "3" { - confV4 := new(configV4) - confV4.Aliases = mcConfigV3.Data().(*configV3).Aliases - confV4.Hosts = make(map[string]struct { - AccessKeyID string `json:"accessKeyId"` - SecretAccessKey string `json:"secretAccessKey"` - Signature string `json:"signature"` - }) - for host, hostConf := range mcConfigV3.Data().(*configV3).Hosts { - confV4.Hosts[host] = struct { - AccessKeyID string `json:"accessKeyId"` - SecretAccessKey string `json:"secretAccessKey"` - Signature string `json:"signature"` - }{ - AccessKeyID: hostConf.AccessKeyID, - SecretAccessKey: hostConf.SecretAccessKey, - Signature: "v4", - } - } - confV4.Version = "4" - - mcNewConfigV4, err := quick.New(confV4) - fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘4’.") - - err = mcNewConfigV4.Save(mustGetMcConfigPath()) - fatalIf(err.Trace(), "Unable to save config version ‘4’.") - - console.Infof("Successfully migrated %s from version ‘3’ to version ‘4’.\n", mustGetMcConfigPath()) + if mcCfgV3.Version() != "3" { + return } + + cfgV4 := newConfigV4() + for k, v := range mcCfgV3.Data().(*configV3).Aliases { + cfgV4.Aliases[k] = v + } + // New hostConfig has API signature. All older entries were V4 + // only. So it is safe to assume V4 as default for all older + // entries. + // HostConfigV4 als uses JavaScript naming notation for struct JSON tags. + for host, hostCfgV3 := range mcCfgV3.Data().(*configV3).Hosts { + cfgV4.Hosts[host] = hostConfigV4{ + AccessKeyID: hostCfgV3.AccessKeyID, + SecretAccessKey: hostCfgV3.SecretAccessKey, + Signature: "v4", + } + } + + mcNewCfgV4, err := quick.New(cfgV4) + fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘4’.") + + err = mcNewCfgV4.Save(mustGetMcConfigPath()) + fatalIf(err.Trace(), "Unable to save config version ‘4’.") + + console.Infof("Successfully migrated %s from version ‘3’ to version ‘4’.\n", mustGetMcConfigPath()) + } -// Migrate config version ‘4’ to ‘5’ +// Migrate config version ‘4’ to ‘5’. Rename hostConfigV4.Signature -> hostConfigV5.API. func migrateConfigV4ToV5() { if !isMcConfigExists() { return } - mcConfigV4, err := quick.Load(mustGetMcConfigPath(), newConfigV4()) + mcCfgV4, err := quick.Load(mustGetMcConfigPath(), newConfigV4()) fatalIf(err.Trace(), "Unable to load mc config V4.") // update to newer version - if mcConfigV4.Version() == "4" { - confV5 := new(configV5) - confV5.Aliases = mcConfigV4.Data().(*configV4).Aliases - confV5.Hosts = make(map[string]hostConfig) - for host, hostConf := range mcConfigV4.Data().(*configV4).Hosts { - confV5.Hosts[host] = hostConfig{ - AccessKeyID: hostConf.AccessKeyID, - SecretAccessKey: hostConf.SecretAccessKey, - API: "S3v4", - } - } - confV5.Version = "5" - - mcNewConfigV5, err := quick.New(confV5) - fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘5’.") - - err = mcNewConfigV5.Save(mustGetMcConfigPath()) - fatalIf(err.Trace(), "Unable to save config version ‘5’.") - - console.Infof("Successfully migrated %s from version ‘4’ to version ‘5’.\n", mustGetMcConfigPath()) + if mcCfgV4.Version() != "4" { + return } + + cfgV5 := newConfigV5() + for k, v := range mcCfgV4.Data().(*configV4).Aliases { + cfgV5.Aliases[k] = v + } + for host, hostCfgV4 := range mcCfgV4.Data().(*configV4).Hosts { + cfgV5.Hosts[host] = hostConfigV5{ + AccessKeyID: hostCfgV4.AccessKeyID, + SecretAccessKey: hostCfgV4.SecretAccessKey, + API: "v4", // Rename from .Signature to .API + } + } + + mcNewCfgV5, err := quick.New(cfgV5) + fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘5’.") + + err = mcNewCfgV5.Save(mustGetMcConfigPath()) + fatalIf(err.Trace(), "Unable to save config version ‘5’.") + + console.Infof("Successfully migrated %s from version ‘4’ to version ‘5’.\n", mustGetMcConfigPath()) } -// Migrate config version ‘4’ to ‘5’ +// Migrate config version ‘5’ to ‘6’. Add google cloud storage servers +// to host config. Also remove "." from s3 aws glob rule. func migrateConfigV5ToV6() { if !isMcConfigExists() { return } - mcConfigV5, err := quick.Load(mustGetMcConfigPath(), newConfigV5()) + mcCfgV5, err := quick.Load(mustGetMcConfigPath(), newConfigV5()) fatalIf(err.Trace(), "Unable to load mc config V5.") // update to newer version - if mcConfigV5.Version() == "5" { - confV6 := new(configV6) - confV6.Aliases = mcConfigV5.Data().(*configV5).Aliases - confV6.Aliases["gcs"] = "https://storage.googleapis.com" - confV6.Hosts = make(map[string]hostConfig) - for host, hostConf := range mcConfigV5.Data().(*configV5).Hosts { - confV6.Hosts[host] = hostConfig{ - AccessKeyID: hostConf.AccessKeyID, - SecretAccessKey: hostConf.SecretAccessKey, - API: hostConf.API, - } - } - var s3Conf hostConfig - for host, hostConf := range confV6.Hosts { - if strings.Contains(host, "s3") { - if (hostConf.AccessKeyID == globalAccessKeyID) || - (hostConf.SecretAccessKey == globalSecretAccessKey) { - delete(confV6.Hosts, host) - } - if hostConf.AccessKeyID == "" || hostConf.SecretAccessKey == "" { - delete(confV6.Hosts, host) - } - s3Conf = hostConfig{ - AccessKeyID: hostConf.AccessKeyID, - SecretAccessKey: hostConf.SecretAccessKey, - API: hostConf.API, - } - break - } - } - confV6.Hosts["*s3*amazonaws.com"] = s3Conf - confV6.Hosts["*storage.googleapis.com"] = hostConfig{ - AccessKeyID: globalAccessKeyID, - SecretAccessKey: globalSecretAccessKey, - API: "S3v2", - } - confV6.Version = globalMCConfigVersion - mcNewConfigV6, err := quick.New(confV6) - fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘6’.") - - err = mcNewConfigV6.Save(mustGetMcConfigPath()) - fatalIf(err.Trace(), "Unable to save config version ‘6’.") - - console.Infof("Successfully migrated %s from version ‘5’ to version ‘6’.\n", mustGetMcConfigPath()) + if mcCfgV5.Version() != "5" { + return } + + cfgV6 := newConfigV6() + + // Add new Google Cloud Storage alias. + cfgV6.Aliases["gcs"] = "https://storage.googleapis.com" + + for k, v := range mcCfgV5.Data().(*configV5).Aliases { + cfgV6.Aliases[k] = v + } + + // Add defaults. + cfgV6.Hosts["*s3*amazonaws.com"] = hostConfigV6{ + AccessKeyID: "YOUR-ACCESS-KEY-ID-HERE", + SecretAccessKey: "YOUR-SECRET-ACCESS-KEY-HERE", + API: "S3v4", + } + cfgV6.Hosts["*storage.googleapis.com"] = hostConfigV6{ + AccessKeyID: "YOUR-ACCESS-KEY-ID-HERE", + SecretAccessKey: "YOUR-SECRET-ACCESS-KEY-HERE", + API: "S3v2", + } + + for host, hostCfgV5 := range mcCfgV5.Data().(*configV5).Hosts { + // Find any matching s3 entry and copy keys from it to newer generalized glob entry. + if strings.Contains(host, "s3") { + if (hostCfgV5.AccessKeyID == "YOUR-ACCESS-KEY-ID-HERE") || + (hostCfgV5.SecretAccessKey == "YOUR-SECRET-ACCESS-KEY-HERE") || + hostCfgV5.AccessKeyID == "" || + hostCfgV5.SecretAccessKey == "" { + continue // Skip defaults. + } + // Now we have real keys set by the user. Copy + // them over to newer glob rule. + // Original host entry has "." in the glob rule. + host = "*s3*amazonaws.com" // Use this glob entry. + } + + cfgV6.Hosts[host] = hostConfigV6{ + AccessKeyID: hostCfgV5.AccessKeyID, + SecretAccessKey: hostCfgV5.SecretAccessKey, + API: hostCfgV5.API, + } + } + + mcNewCfgV6, err := quick.New(cfgV6) + fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘6’.") + + err = mcNewCfgV6.Save(mustGetMcConfigPath()) + fatalIf(err.Trace(), "Unable to save config version ‘6’.") + + console.Infof("Successfully migrated %s from version ‘5’ to version ‘6’.\n", mustGetMcConfigPath()) } -// Fix config version ‘3’, by removing broken struct tags. -func fixConfigV3() { +// Migrate config version ‘6’ to ‘7'. Remove alias map and introduce +// named Host config. Also no more glob match for host config entries. +func migrateConfigV6ToV7() { if !isMcConfigExists() { return } - // brokenConfigV3 broken config between version 3. - type brokenConfigV3 struct { - Version string - ACL string - Access string - Aliases map[string]string - Hosts map[string]struct { - AccessKeyID string - SecretAccessKey string + + mcCfgV6, err := quick.Load(mustGetMcConfigPath(), newConfigV6()) + fatalIf(err.Trace(), "Unable to load mc config V6.") + + if mcCfgV6.Version() != "6" { + return + } + + cfgV7 := newConfigV7() + aliasIndex := 0 + // We dropped alias support in v7. We only need to migrate host configs. + for host, hostCfgV6 := range mcCfgV6.Data().(*configV6).Hosts { + if hostCfgV6.AccessKeyID == "YOUR-ACCESS-KEY-ID-HERE" || + hostCfgV6.SecretAccessKey == "YOUR-SECRET-ACCESS-KEY-HERE" || + hostCfgV6.AccessKeyID == "" || + hostCfgV6.SecretAccessKey == "" { + // Ignore default entries. configV7.loadDefaults() will re-insert them back. + } else if host == "https://s3.amazonaws.com" { + // Only one entry can exist for "s3" domain. + cfgV7.Hosts["s3"] = hostConfigV7{ + URL: host, + AccessKey: hostCfgV6.AccessKeyID, + SecretKey: hostCfgV6.SecretAccessKey, + API: hostCfgV6.API, + } + } else if host == "https://storage.googleapis.com" { + // Only one entry can exist for "gcs" domain. + cfgV7.Hosts["gcs"] = hostConfigV7{ + URL: host, + AccessKey: hostCfgV6.AccessKeyID, + SecretKey: hostCfgV6.SecretAccessKey, + API: hostCfgV6.API, + } + } else { + // Assign a generic "cloud1", cloud2..." key + // for all other entries that has valid keys set. + alias := fmt.Sprintf("cloud%d", aliasIndex) + aliasIndex++ + cfgV7.Hosts[alias] = hostConfigV7{ + URL: host, + AccessKey: hostCfgV6.AccessKeyID, + SecretKey: hostCfgV6.SecretAccessKey, + API: hostCfgV6.API, + } } } - conf := new(brokenConfigV3) - conf.Aliases = make(map[string]string) - conf.Hosts = make(map[string]struct { - AccessKeyID string - SecretAccessKey string - }) + // Load default settings. + cfgV7.loadDefaults() + mcNewCfgV7, err := quick.New(cfgV7) + fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘7’.") - mcConfigV3, err := quick.Load(mustGetMcConfigPath(), conf) - fatalIf(err.Trace(), "Unable to load config.") + err = mcNewCfgV7.Save(mustGetMcConfigPath()) + fatalIf(err.Trace(), "Unable to save config version ‘7’.") - // Update to newer version. - if len(mcConfigV3.Data().(*brokenConfigV3).Aliases) != 0 || mcConfigV3.Data().(*brokenConfigV3).ACL != "" || mcConfigV3.Data().(*brokenConfigV3).Access != "" && mcConfigV3.Version() == "3" { - confV3 := new(configV3) - confV3.Aliases = mcConfigV3.Data().(*brokenConfigV3).Aliases - confV3.Hosts = make(map[string]struct { - AccessKeyID string `json:"access-key-id"` - SecretAccessKey string `json:"secret-access-key"` - }) - for host, hostConf := range mcConfigV3.Data().(*brokenConfigV3).Hosts { - newHostConf := struct { - AccessKeyID string `json:"access-key-id"` - SecretAccessKey string `json:"secret-access-key"` - }{} - newHostConf.AccessKeyID = hostConf.AccessKeyID - newHostConf.SecretAccessKey = hostConf.SecretAccessKey - confV3.Hosts[host] = newHostConf - } - confV3.Version = "3" - - mcNewConfigV3, err := quick.New(confV3) - fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘3’.") - - err = mcNewConfigV3.Save(mustGetMcConfigPath()) - fatalIf(err.Trace(), "Unable to save config version ‘3’.") - - console.Infof("Successfully fixed %s broken config for version ‘3’.\n", mustGetMcConfigPath()) - } -} - -// newConfigV1() - get new config version 1.0.0 -func newConfigV1() *configV1 { - conf := new(configV1) - conf.Version = "1.0.0" - // make sure to allocate map's otherwise Golang - // exits silently without providing any errors - conf.Hosts = make(map[string]struct { - AccessKeyID string - SecretAccessKey string - }) - conf.Aliases = make(map[string]string) - return conf -} - -// newConfigV101() - get new config version 1.0.1 -func newConfigV101() *configV101 { - conf := new(configV101) - conf.Version = "1.0.1" - // make sure to allocate map's otherwise Golang - // exits silently without providing any errors - conf.Hosts = make(map[string]struct { - AccessKeyID string - SecretAccessKey string - }) - conf.Aliases = make(map[string]string) - return conf -} - -// newConfigV2() - get new config version 2 -func newConfigV2() *configV2 { - conf := new(configV2) - conf.Version = "2" - // make sure to allocate map's otherwise Golang - // exits silently without providing any errors - conf.Hosts = make(map[string]struct { - AccessKeyID string - SecretAccessKey string - }) - conf.Aliases = make(map[string]string) - return conf -} - -// newConfigV3 - get new config version 3 -func newConfigV3() *configV3 { - conf := new(configV3) - conf.Version = "3" - // make sure to allocate map's otherwise Golang - // exits silently without providing any errors - conf.Hosts = make(map[string]struct { - AccessKeyID string `json:"access-key-id"` - SecretAccessKey string `json:"secret-access-key"` - }) - conf.Aliases = make(map[string]string) - return conf -} - -func newConfigV4() *configV4 { - conf := new(configV4) - conf.Version = "4" - // make sure to allocate map's otherwise Golang - // exits silently without providing any errors - conf.Hosts = make(map[string]struct { - AccessKeyID string `json:"accessKeyId"` - SecretAccessKey string `json:"secretAccessKey"` - Signature string `json:"signature"` - }) - conf.Aliases = make(map[string]string) - return conf -} - -func newConfigV5() *configV5 { - conf := new(configV5) - conf.Version = "5" - // make sure to allocate map's otherwise Golang - // exits silently without providing any errors - conf.Hosts = make(map[string]hostConfig) - conf.Aliases = make(map[string]string) - return conf + console.Infof("Successfully migrated %s from version ‘6’ to version ‘7’.\n", mustGetMcConfigPath()) } diff --git a/config-old.go b/config-old.go new file mode 100644 index 00000000..59ba4af2 --- /dev/null +++ b/config-old.go @@ -0,0 +1,164 @@ +/* + * Minio Client (C) 2015 Minio, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package main + +/////////////////// Config V1 /////////////////// +type hostConfigV1 struct { + AccessKeyID string + SecretAccessKey string +} + +type configV1 struct { + Version string + Aliases map[string]string + Hosts map[string]hostConfigV1 +} + +// newConfigV1() - get new config version 1.0.0 +func newConfigV1() *configV1 { + conf := new(configV1) + conf.Version = "1.0.0" + // make sure to allocate map's otherwise Golang + // exits silently without providing any errors + conf.Aliases = make(map[string]string) + conf.Hosts = make(map[string]hostConfigV1) + return conf +} + +/////////////////// Config V101 /////////////////// +type hostConfigV101 hostConfigV1 + +type configV101 struct { + Version string + Aliases map[string]string + Hosts map[string]hostConfigV101 +} + +// newConfigV101() - get new config version 1.0.1 +func newConfigV101() *configV101 { + conf := new(configV101) + conf.Version = "1.0.1" + conf.Aliases = make(map[string]string) + conf.Hosts = make(map[string]hostConfigV101) + return conf +} + +/////////////////// Config V2 /////////////////// +type hostConfigV2 hostConfigV1 + +type configV2 struct { + Version string + Aliases map[string]string + Hosts map[string]hostConfigV2 +} + +// newConfigV2() - get new config version 2 +func newConfigV2() *configV2 { + conf := new(configV2) + conf.Version = "2" + conf.Aliases = make(map[string]string) + conf.Hosts = make(map[string]hostConfigV2) + return conf +} + +/////////////////// Config V3 /////////////////// +type hostConfigV3 struct { + AccessKeyID string `json:"access-key-id"` + SecretAccessKey string `json:"secret-access-key"` +} + +type configV3 struct { + Version string `json:"version"` + Aliases map[string]string `json:"alias"` + Hosts map[string]hostConfigV3 `json:"hosts"` +} + +// newConfigV3 - get new config version 3. +func newConfigV3() *configV3 { + conf := new(configV3) + conf.Version = "3" + conf.Aliases = make(map[string]string) + conf.Hosts = make(map[string]hostConfigV3) + return conf +} + +/////////////////// Config V4 /////////////////// +type hostConfigV4 struct { + AccessKeyID string `json:"accessKeyId"` + SecretAccessKey string `json:"secretAccessKey"` + Signature string `json:"signature"` +} + +type configV4 struct { + Version string `json:"version"` + Aliases map[string]string `json:"alias"` + Hosts map[string]hostConfigV4 `json:"hosts"` +} + +func newConfigV4() *configV4 { + conf := new(configV4) + conf.Version = "4" + conf.Aliases = make(map[string]string) + conf.Hosts = make(map[string]hostConfigV4) + return conf +} + +/////////////////// Config V5 /////////////////// +type hostConfigV5 struct { + AccessKeyID string `json:"accessKeyId"` + SecretAccessKey string `json:"secretAccessKey"` + API string `json:"api"` +} + +type configV5 struct { + Version string `json:"version"` + Aliases map[string]string `json:"alias"` + Hosts map[string]hostConfigV5 `json:"hosts"` +} + +func newConfigV5() *configV5 { + conf := new(configV5) + conf.Version = "5" + conf.Aliases = make(map[string]string) + conf.Hosts = make(map[string]hostConfigV5) + return conf +} + +/////////////////// Config V6 /////////////////// +type hostConfigV6 struct { + AccessKeyID string `json:"accessKeyId"` + SecretAccessKey string `json:"secretAccessKey"` + API string `json:"api"` +} + +type configV6 struct { + Version string `json:"version"` + Aliases map[string]string `json:"alias"` + Hosts map[string]hostConfigV6 `json:"hosts"` +} + +// newConfigV6 - new config version '6'. +func newConfigV6() *configV6 { + conf := new(configV6) + conf.Version = "6" + conf.Aliases = make(map[string]string) + conf.Hosts = make(map[string]hostConfigV6) + return conf +} + +/////////////////// Config V7 /////////////////// +// RESERVED FOR FUTURE diff --git a/config-utils.go b/config-utils.go index 2a9582d1..15aaafbc 100644 --- a/config-utils.go +++ b/config-utils.go @@ -8,29 +8,21 @@ import ( ) // isValidSecretKey - validate secret key. -func isValidSecretKey(secretAccessKey string) bool { - if secretAccessKey == "" { +func isValidSecretKey(secretKey string) bool { + if secretKey == "" { return true } regex := regexp.MustCompile("^.{40}$") - return regex.MatchString(secretAccessKey) + return regex.MatchString(secretKey) } // isValidAccessKey - validate access key. -func isValidAccessKey(accessKeyID string) bool { - if accessKeyID == "" { +func isValidAccessKey(accessKey string) bool { + if accessKey == "" { return true } regex := regexp.MustCompile("^[A-Z0-9\\-\\.\\_\\~]{20}$") - return regex.MatchString(accessKeyID) -} - -// isValidKeys validates both access and secret key. -func isValidKeys(accessKeyID, secretAccessKey string) bool { - if isValidAccessKey(accessKeyID) && isValidSecretKey(secretAccessKey) { - return true - } - return false + return regex.MatchString(accessKey) } // isValidHostURL - validate input host url. diff --git a/config-v6.go b/config-v6.go deleted file mode 100644 index 9cdcb9b4..00000000 --- a/config-v6.go +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Minio Client (C) 2015 Minio, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package main - -import ( - "sync" - - "github.com/minio/minio-xl/pkg/probe" - "github.com/minio/minio-xl/pkg/quick" -) - -// configV6 config version '6'. -type configV6 struct { - Version string `json:"version"` - Aliases map[string]string `json:"alias"` - Hosts map[string]hostConfig `json:"hosts"` -} - -// cached variables should *NEVER* be accessed directly from outside this file. -var cache sync.Pool - -// newConfigV6 - new config version '6'. -func newConfigV6() *configV6 { - conf := new(configV6) - conf.Version = globalMCConfigVersion - // make sure to allocate map's otherwise Golang - // exits silently without providing any errors. - conf.Hosts = make(map[string]hostConfig) - conf.Aliases = make(map[string]string) - - localHostConfig := hostConfig{ - AccessKeyID: "", - SecretAccessKey: "", - API: "S3v4", - } - - s3HostConf := hostConfig{ - AccessKeyID: globalAccessKeyID, - SecretAccessKey: globalSecretAccessKey, - API: "S3v4", - } - - googlHostConf := hostConfig{ - AccessKeyID: globalAccessKeyID, - SecretAccessKey: globalSecretAccessKey, - API: "S3v2", - } - - // Your example host config. - exampleHostConf := hostConfig{ - AccessKeyID: globalAccessKeyID, - SecretAccessKey: globalSecretAccessKey, - API: "S3v4", - } - - playHostConfig := hostConfig{ - AccessKeyID: "", - SecretAccessKey: "", - API: "S3v4", - } - - dlHostConfig := hostConfig{ - AccessKeyID: "", - SecretAccessKey: "", - API: "S3v4", - } - - conf.Hosts[globalExampleHostURL] = exampleHostConf - conf.Hosts["http://localhost:9000"] = localHostConfig - conf.Hosts["https://dl.minio.io:9000"] = dlHostConfig - conf.Hosts["https://s3.amazonaws.com"] = s3HostConf - conf.Hosts["https://play.minio.io:9000"] = playHostConfig - conf.Hosts["https://storage.googleapis.com"] = googlHostConf - - aliases := make(map[string]string) - aliases["s3"] = "https://s3.amazonaws.com" - aliases["dl"] = "https://dl.minio.io:9000" - aliases["gcs"] = "https://storage.googleapis.com" - aliases["play"] = "https://play.minio.io:9000" - aliases["local"] = "http://localhost:9000" - - conf.Aliases = aliases - return conf -} - -// saveConfigV6 - saves an updated config. -func saveConfigV6(config *configV6) *probe.Error { - qs, err := quick.New(config) - if err != nil { - return err.Trace() - } - return qs.Save(mustGetMcConfigPath()).Trace(mustGetMcConfigPath()) -} - -// loadConfigV6 - loads a new config. -func loadConfigV6() (*configV6, *probe.Error) { - if !isMcConfigExists() { - return nil, errInvalidArgument().Trace() - } - - configFile, err := getMcConfigPath() - if err != nil { - return nil, err.Trace() - } - - // Cached in private global variable. - if v := cache.Get(); v != nil { // Use previously cached config. - return v.(*configV6), nil - } - - conf := new(configV6) - conf.Version = globalMCConfigVersion - qconf, err := quick.New(conf) - if err != nil { - return nil, err.Trace() - } - - err = qconf.Load(configFile) - if err != nil { - return nil, err.Trace() - } - - config := qconf.Data().(*configV6) - // Save in sync pool. - cache.Put(config) - - return config, nil -} diff --git a/config-v7.go b/config-v7.go new file mode 100644 index 00000000..8108633f --- /dev/null +++ b/config-v7.go @@ -0,0 +1,157 @@ +/* + * Minio Client (C) 2015 Minio, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package main + +import ( + "sync" + + "github.com/minio/minio-xl/pkg/probe" + "github.com/minio/minio-xl/pkg/quick" +) + +const ( + defaultAccessKey = "YOUR-ACCESS-KEY-HERE" + defaultSecretKey = "YOUR-SECRET-KEY-HERE" +) + +var ( + // set once during first load. + cacheCfgV7 *configV7 + // All access to mc config file should be synchronized. + cfgMutex = &sync.RWMutex{} +) + +// hostConfig configuration of a host. +type hostConfigV7 struct { + URL string `json:"url"` + AccessKey string `json:"accessKey"` + SecretKey string `json:"secretKey"` + API string `json:"api"` +} + +// configV7 config version. +type configV7 struct { + Version string `json:"version"` + Hosts map[string]hostConfigV7 `json:"hosts"` +} + +// newConfigV7 - new config version. +func newConfigV7() *configV7 { + cfg := new(configV7) + cfg.Version = globalMCConfigVersion + cfg.Hosts = make(map[string]hostConfigV7) + return cfg +} + +// SetHost sets host config if not empty. +func (c *configV7) setHost(alias string, cfg hostConfigV7) { + if _, ok := c.Hosts[alias]; !ok { + c.Hosts[alias] = cfg + } +} + +// load default values for missing entries. +func (c *configV7) loadDefaults() { + // Minio server running locally. + c.setHost("local", hostConfigV7{ + URL: "http://localhost:9000", + AccessKey: "", + SecretKey: "", + API: "S3v4", + }) + + // Amazon S3 cloud storage service. + c.setHost("s3", hostConfigV7{ + URL: "https://s3.amazonaws.com", + AccessKey: defaultAccessKey, + SecretKey: defaultSecretKey, + API: "S3v4", + }) + + // Google cloud storage service. + c.setHost("gcs", hostConfigV7{ + URL: "https://storage.googleapis.com", + AccessKey: defaultAccessKey, + SecretKey: defaultSecretKey, + API: "S3v2", + }) + + // Minio anonymous server for demo. + c.setHost("play", hostConfigV7{ + URL: "https://play.minio.io:9000", + AccessKey: "", + SecretKey: "", + API: "S3v4", + }) + + // Minio demo server with public secret and access keys. + c.setHost("player", hostConfigV7{ + URL: "https://play.minio.io:9002", + AccessKey: "Q3AM3UQ867SPQQA43P2F", + SecretKey: "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG", + API: "S3v4", + }) + + // Minio public download service. + c.setHost("dl", hostConfigV7{ + URL: "https://dl.minio.io:9000", + AccessKey: "", + SecretKey: "", + API: "S3v4", + }) +} + +// loadConfigV7 - loads a new config. +func loadConfigV7() (*configV7, *probe.Error) { + cfgMutex.RLock() + defer cfgMutex.RUnlock() + + // Cached in private global variable. + if cacheCfgV7 != nil { + return cacheCfgV7, nil + } + + if !isMcConfigExists() { + return nil, errInvalidArgument().Trace() + } + + mcCfgV7, err := quick.Load(mustGetMcConfigPath(), newConfigV7()) + fatalIf(err.Trace(), "Unable to load mc config file ‘"+mustGetMcConfigPath()+"’.") + + cfgV7 := mcCfgV7.Data().(*configV7) + + // cache it. + cacheCfgV7 = cfgV7 + + return cfgV7, nil +} + +// saveConfigV7 - saves an updated config. +func saveConfigV7(cfgV7 *configV7) *probe.Error { + cfgMutex.Lock() + defer cfgMutex.Unlock() + + qs, err := quick.New(cfgV7) + if err != nil { + return err.Trace() + } + + // update the cache. + cacheCfgV7 = cfgV7 + + return qs.Save(mustGetMcConfigPath()).Trace(mustGetMcConfigPath()) +} diff --git a/config-version-main.go b/config-version-main.go deleted file mode 100644 index 49283788..00000000 --- a/config-version-main.go +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Minio Client (C) 2014, 2015 Minio, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package main - -import ( - "encoding/json" - - "github.com/minio/cli" - "github.com/minio/mc/pkg/console" - "github.com/minio/minio-xl/pkg/probe" -) - -var ( - configVersionFlags = []cli.Flag{ - cli.BoolFlag{ - Name: "help, h", - Usage: "Help of config version", - }, - } -) - -// Print config version. -var configVersionCmd = cli.Command{ - Name: "version", - Usage: "Print config version.", - Action: mainConfigVersion, - Flags: append(configVersionFlags, globalFlags...), - CustomHelpTemplate: `NAME: - mc config {{.Name}} - {{.Usage}} - -USAGE: - mc config {{.Name}} -`, -} - -func mainConfigVersion(ctx *cli.Context) { - // Set global flags from context. - setGlobalsFromContext(ctx) - - config, err := loadMcConfig() - fatalIf(err.Trace(), "Unable to load config version ‘"+globalMCConfigVersion+"’.") - - type Version string - if globalJSON { - tB, e := json.Marshal( - struct { - Version Version `json:"version"` - }{Version: Version(config.Version)}, - ) - fatalIf(probe.NewError(e), "Unable to construct version string.") - console.Println(string(tB)) - return - } - console.Println(config.Version) -} diff --git a/config.go b/config.go index 9dbb5f5a..347de14e 100644 --- a/config.go +++ b/config.go @@ -19,6 +19,7 @@ package main import ( "os" "path/filepath" + "regexp" "runtime" "github.com/minio/minio-xl/pkg/probe" @@ -95,29 +96,44 @@ func mustGetMcConfigPath() string { } // newMcConfig - initializes a new version '6' config. -func newMcConfig() *configV6 { - return newConfigV6() +func newMcConfig() *configV7 { + cfg := newConfigV7() + cfg.loadDefaults() + return cfg } -// loadMcConfig - reads configuration file and returns config. -func loadMcConfig() (*configV6, *probe.Error) { - conf, err := loadConfigV6() - if err != nil { - return nil, err.Trace() +// loadMcConfigCached - returns loadMcConfig with a closure for config cache. +func loadMcConfigFactory() func() (*configV7, *probe.Error) { + // Load once and cache in a closure. + cfgCache, err := loadConfigV7() + + // loadMcConfig - reads configuration file and returns config. + return func() (*configV7, *probe.Error) { + return cfgCache, err } - return conf, nil } +var loadMcConfig = loadMcConfigFactory() + // saveMcConfig - saves configuration file and returns error if any. -func saveMcConfig(config *configV6) *probe.Error { +func saveMcConfig(config *configV7) *probe.Error { if config == nil { return errInvalidArgument().Trace() } + err := createMcConfigDir() if err != nil { return err.Trace(mustGetMcConfigDir()) } - return saveConfigV6(config).Trace(mustGetMcConfigPath()) + + // Save the config. + if err := saveConfigV7(config); err != nil { + return err.Trace(mustGetMcConfigPath()) + } + + // Refresh the config cache. + loadMcConfig = loadMcConfigFactory() + return nil } // isMcConfigExists returns err if config doesn't exist. @@ -131,3 +147,49 @@ func isMcConfigExists() bool { } return true } + +// isValidAlias - Check if alias valid. +func isValidAlias(alias string) bool { + return regexp.MustCompile("^[a-zA-Z][a-zA-Z0-9-]+$").MatchString(alias) +} + +// getHostConfig retrieves host specific configuration such as access keys, signature type. +func getHostConfig(alias string) (*hostConfigV7, *probe.Error) { + mcCfg, err := loadMcConfig() + if err != nil { + return nil, err.Trace(alias) + } + + // if host is exact return quickly. + if _, ok := mcCfg.Hosts[alias]; ok { + hostCfg := mcCfg.Hosts[alias] + return &hostCfg, nil + } + + // return error if cannot be matched. + return nil, errNoMatchingHost(alias).Trace(alias) +} + +// mustGetHostConfig retrieves host specific configuration such as access keys, signature type. +func mustGetHostConfig(alias string) *hostConfigV7 { + hostCfg, _ := getHostConfig(alias) + return hostCfg +} + +// expandAlias expands aliased URL if any match is found, returns as is otherwise. +func expandAlias(aliasedURL string) (alias string, urlStr string, hostCfg *hostConfigV7, err *probe.Error) { + // Extract alias from the URL. + alias, path := url2Alias(aliasedURL) + + // Find the matching alias entry and expand the URL. + if hostCfg = mustGetHostConfig(alias); hostCfg != nil { + return alias, urlJoinPath(hostCfg.URL, path), hostCfg, nil + } + return "", aliasedURL, nil, nil // No matching entry found. Return original URL as is. +} + +// mustExpandAlias expands aliased URL if any match is found, returns as is otherwise. +func mustExpandAlias(aliasedURL string) (alias string, urlStr string, hostCfg *hostConfigV7) { + alias, urlStr, hostCfg, _ = expandAlias(aliasedURL) + return alias, urlStr, hostCfg +} diff --git a/cp-main.go b/cp-main.go index 0e277c1c..e146d877 100644 --- a/cp-main.go +++ b/cp-main.go @@ -67,16 +67,16 @@ FLAGS: {{end}} EXAMPLES: 1. Copy a list of objects from local file system to Amazon S3 cloud storage. - $ mc {{.Name}} Music/*.ogg s3.amazonaws.com/jukebox/ + $ mc {{.Name}} Music/*.ogg s3/jukebox/ 2. Copy a folder recursively from Minio cloud storage to Amazon S3 cloud storage. - $ mc {{.Name}} --recursive play.minio.io:9000/mybucket/burningman2011/ s3.amazonaws.com/mybucket/ + $ mc {{.Name}} --recursive play/mybucket/burningman2011/ s3/mybucket/ 3. Copy multiple local folders recursively to Minio cloud storage. - $ mc {{.Name}} --recursive backup/2014/ backup/2015/ play.minio.io:9000/archive/ + $ mc {{.Name}} --recursive backup/2014/ backup/2015/ play/archive/ 4. Copy a bucket recursively from aliased Amazon S3 cloud storage to local filesystem on Windows. - $ mc {{.Name}} --recursive s3/documents/2014/ C:\Backups\2014 + $ mc {{.Name}} --recursive s3\documents\2014\ C:\Backups\2014 5. Copy an object with name containing unicode characters to Amazon S3 cloud storage. $ mc {{.Name}} 本語 s3/andoria/ @@ -88,10 +88,12 @@ EXAMPLES: // copyMessage container for file copy messages type copyMessage struct { - Status string `json:"status"` - Source string `json:"source"` - Target string `json:"target"` - Length int64 `json:"length"` + Status string `json:"status"` + SourceAlias string `json:"sourceAlias,omitempty"` + Source string `json:"source"` + TargetAlias string `json:"targetAlias,omitempty"` + Target string `json:"target"` + Length int64 `json:"length"` } // String colorized copy message @@ -145,7 +147,7 @@ func doCopy(cpURLs copyURLs, progressReader *barSend, accountingReader *accounte progressReader.SetCaption(cpURLs.SourceContent.URL.String() + ": ") } - reader, err := getSource(cpURLs.SourceContent.URL.String()) + reader, err := getSourceFromAlias(cpURLs.SourceAlias, cpURLs.SourceContent.URL.String()) if err != nil { if !globalQuiet && !globalJSON { progressReader.ErrorGet(cpURLs.SourceContent.Size) @@ -158,9 +160,11 @@ func doCopy(cpURLs copyURLs, progressReader *barSend, accountingReader *accounte var newReader io.ReadSeeker if globalQuiet || globalJSON { printMsg(copyMessage{ - Source: cpURLs.SourceContent.URL.String(), - Target: cpURLs.TargetContent.URL.String(), - Length: cpURLs.SourceContent.Size, + SourceAlias: cpURLs.SourceAlias, + Source: cpURLs.SourceContent.URL.String(), + TargetAlias: cpURLs.TargetAlias, + Target: cpURLs.TargetContent.URL.String(), + Length: cpURLs.SourceContent.Size, }) // No accounting necessary for JSON output. if globalJSON { @@ -195,7 +199,7 @@ func doCopyFake(cURLs copyURLs, progressReader *barSend) { } // doPrepareCopyURLs scans the source URL and prepares a list of objects for copying. -func doPrepareCopyURLs(session *sessionV5, trapCh <-chan bool) { +func doPrepareCopyURLs(session *sessionV6, trapCh <-chan bool) { // Separate source and target. 'cp' can take only one target, // but any number of sources. sourceURLs := session.Header.CommandArgs[:len(session.Header.CommandArgs)-1] @@ -264,7 +268,7 @@ func doPrepareCopyURLs(session *sessionV5, trapCh <-chan bool) { session.Save() } -func doCopySession(session *sessionV5) { +func doCopySession(session *sessionV6) { trapCh := signalTrap(os.Interrupt, syscall.SIGTERM) if !session.HasData() { @@ -389,7 +393,7 @@ func mainCopy(ctx *cli.Context) { // Additional command speific theme customization. console.SetColor("Copy", color.New(color.FgGreen, color.Bold)) - session := newSessionV5() + session := newSessionV6() session.Header.CommandType = "cp" session.Header.CommandBoolFlags["recursive"] = ctx.Bool("recursive") @@ -400,12 +404,7 @@ func mainCopy(ctx *cli.Context) { } // extract URLs. - var err *probe.Error - if session.Header.CommandArgs, err = args2URLs(ctx.Args()); err != nil { - session.Delete() - fatalIf(err.Trace(ctx.Args()...), "One or more unknown URL types passed.") - } - + session.Header.CommandArgs = ctx.Args() doCopySession(session) session.Delete() } diff --git a/cp-url-syntax.go b/cp-url-syntax.go index 8ac67b4e..fe69175e 100644 --- a/cp-url-syntax.go +++ b/cp-url-syntax.go @@ -29,11 +29,9 @@ func checkCopySyntax(ctx *cli.Context) { } // extract URLs. - URLs, err := args2URLs(ctx.Args()) - fatalIf(err.Trace(ctx.Args()...), fmt.Sprintf("Argument parsing failed.")) - + URLs := ctx.Args() if len(URLs) < 2 { - fatalIf(err.Trace(ctx.Args()...), fmt.Sprintf("Unable to parse source and target arguments.")) + fatalIf(errDummy().Trace(ctx.Args()...), fmt.Sprintf("Unable to parse source and target arguments.")) } srcURLs := URLs[:len(URLs)-1] @@ -53,7 +51,10 @@ func checkCopySyntax(ctx *cli.Context) { } // Guess CopyURLsType based on source and target URLs. - copyURLsType := guessCopyURLType(srcURLs, tgtURL, isRecursive) + copyURLsType, err := guessCopyURLType(srcURLs, tgtURL, isRecursive) + if err != nil { + fatalIf(errInvalidArgument().Trace(), "Unable to guess the type of copy operation.") + } switch copyURLsType { case copyURLsTypeA: // File -> File. checkCopySyntaxTypeA(srcURLs, tgtURL) @@ -64,7 +65,7 @@ func checkCopySyntax(ctx *cli.Context) { case copyURLsTypeD: // File1...FileN -> Folder. checkCopySyntaxTypeD(srcURLs, tgtURL) default: - fatalIf(errInvalidArgument().Trace(), "Guessing CopyURLsType failed, Invalid arguments provided.") + fatalIf(errInvalidArgument().Trace(), "Unable to guess the type of copy operation.") } } diff --git a/cp-url.go b/cp-url.go index 6fc2d335..94c3fdd0 100644 --- a/cp-url.go +++ b/cp-url.go @@ -25,7 +25,9 @@ import ( ) type copyURLs struct { + SourceAlias string SourceContent *client.Content + TargetAlias string TargetContent *client.Content Error *probe.Error `json:"-"` } @@ -57,39 +59,43 @@ const ( // guessCopyURLType guesses the type of URL. This approach all allows prepareURL // functions to accurately report failure causes. -func guessCopyURLType(sourceURLs []string, targetURL string, isRecursive bool) copyURLsType { +func guessCopyURLType(sourceURLs []string, targetURL string, isRecursive bool) (copyURLsType, *probe.Error) { if len(sourceURLs) == 1 { // 1 Source, 1 Target sourceURL := sourceURLs[0] _, sourceContent, err := url2Stat(sourceURL) if err != nil { - return copyURLsTypeInvalid + return copyURLsTypeInvalid, err } // If recursion is ON, it is type C. // If source is a folder, it is Type C. if sourceContent.Type.IsDir() || isRecursive { - return copyURLsTypeC + return copyURLsTypeC, nil } // If target is a folder, it is Type B. if isTargetURLDir(targetURL) { - return copyURLsTypeB + return copyURLsTypeB, nil } // else Type A. - return copyURLsTypeA + return copyURLsTypeA, nil } // Multiple source args and target is a folder. It is Type D. if isTargetURLDir(targetURL) { - return copyURLsTypeD + return copyURLsTypeD, nil } - return copyURLsTypeInvalid + return copyURLsTypeInvalid, errInvalidArgument().Trace() } // SINGLE SOURCE - Type A: copy(f, f) -> copy(f, f) // prepareCopyURLsTypeA - prepares target and source URLs for copying. func prepareCopyURLsTypeA(sourceURL string, targetURL string) copyURLs { + // Extract alias before fiddling with the URL. + sourceAlias, _, _ := mustExpandAlias(sourceURL) + targetAlias, _, _ := mustExpandAlias(targetURL) + if sourceURL == targetURL { // source and target can not be same return copyURLs{Error: errSourceTargetSame(sourceURL).Trace(sourceURL)} @@ -103,18 +109,28 @@ func prepareCopyURLsTypeA(sourceURL string, targetURL string) copyURLs { // Source is not a regular file return copyURLs{Error: errInvalidSource(sourceURL).Trace(sourceURL)} } + // All OK.. We can proceed. Type A - return makeCopyContentTypeA(sourceContent, targetURL) + return makeCopyContentTypeA(sourceAlias, sourceContent, targetAlias, targetURL) } // prepareCopyContentTypeA - makes CopyURLs content for copying. -func makeCopyContentTypeA(sourceContent *client.Content, targetURL string) copyURLs { - return copyURLs{SourceContent: sourceContent, TargetContent: &client.Content{URL: *client.NewURL(targetURL)}} +func makeCopyContentTypeA(sourceAlias string, sourceContent *client.Content, targetAlias string, targetURL string) copyURLs { + return copyURLs{ + SourceAlias: sourceAlias, + SourceContent: sourceContent, + TargetAlias: targetAlias, + TargetContent: &client.Content{URL: *client.NewURL(targetURL)}, + } } // SINGLE SOURCE - Type B: copy(f, d) -> copy(f, d/f) -> A // prepareCopyURLsTypeB - prepares target and source URLs for copying. func prepareCopyURLsTypeB(sourceURL string, targetURL string) copyURLs { + // Extract alias before fiddling with the URL. + sourceAlias, _, _ := mustExpandAlias(sourceURL) + targetAlias, _, _ := mustExpandAlias(targetURL) + _, sourceContent, err := url2Stat(sourceURL) if err != nil { // Source does not exist or insufficient privileges. @@ -130,24 +146,28 @@ func prepareCopyURLsTypeB(sourceURL string, targetURL string) copyURLs { } // All OK.. We can proceed. Type B: source is a file, target is a folder and exists. - return makeCopyContentTypeB(sourceContent, targetURL) + return makeCopyContentTypeB(sourceAlias, sourceContent, targetAlias, targetURL) } // makeCopyContentTypeB - CopyURLs content for copying. -func makeCopyContentTypeB(sourceContent *client.Content, targetURL string) copyURLs { +func makeCopyContentTypeB(sourceAlias string, sourceContent *client.Content, targetAlias string, targetURL string) copyURLs { // All OK.. We can proceed. Type B: source is a file, target is a folder and exists. targetURLParse := client.NewURL(targetURL) targetURLParse.Path = filepath.Join(targetURLParse.Path, filepath.Base(sourceContent.URL.Path)) - return makeCopyContentTypeA(sourceContent, targetURLParse.String()) + return makeCopyContentTypeA(sourceAlias, sourceContent, targetAlias, targetURLParse.String()) } // SINGLE SOURCE - Type C: copy(d1..., d2) -> []copy(d1/f, d1/d2/f) -> []A // prepareCopyRecursiveURLTypeC - prepares target and source URLs for copying. func prepareCopyURLsTypeC(sourceURL, targetURL string, isRecursive bool) <-chan copyURLs { + // Extract alias before fiddling with the URL. + sourceAlias, _, _ := mustExpandAlias(sourceURL) + targetAlias, _, _ := mustExpandAlias(targetURL) + copyURLsCh := make(chan copyURLs) go func(sourceURL, targetURL string, copyURLsCh chan copyURLs) { defer close(copyURLsCh) - sourceClient, err := url2Client(sourceURL) + sourceClient, err := newClient(sourceURL) if err != nil { // Source initialization failed. copyURLsCh <- copyURLs{Error: err.Trace(sourceURL)} @@ -167,14 +187,14 @@ func prepareCopyURLsTypeC(sourceURL, targetURL string, isRecursive bool) <-chan } // All OK.. We can proceed. Type B: source is a file, target is a folder and exists. - copyURLsCh <- makeCopyContentTypeC(sourceClient.GetURL(), sourceContent, targetURL) + copyURLsCh <- makeCopyContentTypeC(sourceAlias, sourceClient.GetURL(), sourceContent, targetAlias, targetURL) } }(sourceURL, targetURL, copyURLsCh) return copyURLsCh } // makeCopyContentTypeC - CopyURLs content for copying. -func makeCopyContentTypeC(sourceURL client.URL, sourceContent *client.Content, targetURL string) copyURLs { +func makeCopyContentTypeC(sourceAlias string, sourceURL client.URL, sourceContent *client.Content, targetAlias string, targetURL string) copyURLs { newSourceURL := sourceContent.URL pathSeparatorIndex := strings.LastIndex(sourceURL.Path, string(sourceURL.Separator)) newSourceSuffix := newSourceURL.Path @@ -182,7 +202,7 @@ func makeCopyContentTypeC(sourceURL client.URL, sourceContent *client.Content, t newSourceSuffix = strings.TrimPrefix(newSourceURL.Path, sourceURL.Path[:pathSeparatorIndex]) } newTargetURL := urlJoinPath(targetURL, newSourceSuffix) - return makeCopyContentTypeA(sourceContent, newTargetURL) + return makeCopyContentTypeA(sourceAlias, sourceContent, targetAlias, newTargetURL) } // MULTI-SOURCE - Type D: copy([](f|d...), d) -> []B @@ -205,7 +225,9 @@ func prepareCopyURLs(sourceURLs []string, targetURL string, isRecursive bool) <- copyURLsCh := make(chan copyURLs) go func(sourceURLs []string, targetURL string, copyURLsCh chan copyURLs) { defer close(copyURLsCh) - switch guessCopyURLType(sourceURLs, targetURL, isRecursive) { + cpType, err := guessCopyURLType(sourceURLs, targetURL, isRecursive) + fatalIf(err.Trace(), "Unable to guess the type of copy operation.") + switch cpType { case copyURLsTypeA: copyURLsCh <- prepareCopyURLsTypeA(sourceURLs[0], targetURL) case copyURLsTypeB: diff --git a/cp_mirror_test.go b/cp_mirror_test.go deleted file mode 100644 index 10d5034d..00000000 --- a/cp_mirror_test.go +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Minio Client (C) 2015 Minio, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package main - -import . "gopkg.in/check.v1" - -func (s *TestSuite) TestCopyURLType(c *C) { - // Valid Types. - sourceURLs := []string{server.URL + "/bucket/object1"} - targetURL := server.URL + "/bucket/test" - isRecursive := false - c.Assert(guessCopyURLType(sourceURLs, targetURL, isRecursive), Equals, copyURLsTypeA) - - sourceURLs = []string{server.URL + "/bucket/object1"} - targetURL = server.URL + "/bucket" - isRecursive = false - c.Assert(guessCopyURLType(sourceURLs, targetURL, isRecursive), Equals, copyURLsTypeB) - - sourceURLs = []string{server.URL + "/bucket/"} - targetURL = server.URL + "/bucket" - isRecursive = true - c.Assert(guessCopyURLType(sourceURLs, targetURL, isRecursive), Equals, copyURLsTypeC) - - sourceURLs = []string{server.URL + "/bucket/test1.txt", server.URL + "/bucket/test2.txt"} - targetURL = server.URL + "/bucket" - isRecursive = false - c.Assert(guessCopyURLType(sourceURLs, targetURL, isRecursive), Equals, copyURLsTypeD) - - // * INVALID RULES - // ========================= - // copy(d, f) - // copy(d..., f) - // copy([]f, f) - - sourceURLs = []string{"/test/"} - targetURL = server.URL + "/bucket/test.txt" - isRecursive = false - c.Assert(guessCopyURLType(sourceURLs, targetURL, isRecursive), Equals, copyURLsTypeInvalid) - - sourceURLs = []string{"/test/"} - targetURL = server.URL + "/bucket/test.txt" - isRecursive = true - c.Assert(guessCopyURLType(sourceURLs, targetURL, isRecursive), Equals, copyURLsTypeInvalid) - - sourceURLs = []string{"/test/test1.txt", "/test/test2.txt"} - targetURL = server.URL + "/bucket/test.txt" - isRecursive = false - c.Assert(guessCopyURLType(sourceURLs, targetURL, isRecursive), Equals, copyURLsTypeInvalid) - - sourceURLs = []string{server.URL + "/bucket/", server.URL + "/bucket/"} - targetURL = "" - isRecursive = false - c.Assert(guessCopyURLType(sourceURLs, targetURL, isRecursive), Equals, copyURLsTypeInvalid) -} diff --git a/credentials-reader.go b/credentials-reader.go deleted file mode 100644 index 70d3a07a..00000000 --- a/credentials-reader.go +++ /dev/null @@ -1,202 +0,0 @@ -/* - * Minio Client (C) 2015 Minio, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. -// -// Some of the code here is borrowed from 'encoding/json' package. -package main - -import ( - "encoding/csv" - "io" - "os" - "reflect" - "runtime" - "strconv" - - "github.com/minio/minio-xl/pkg/probe" -) - -// csvReader reads records from a CSV-encoded file. -type csvReader struct { - *csv.Reader -} - -// newCSVReader returns a new csv Reader. -// additionally one can provide a line that needs to be skipped. -func newCSVReader(r io.Reader) *csvReader { - return &csvReader{ - csv.NewReader(r), - } -} - -// credential - struct to read from a CSV file. -type credential struct { - Name string - AccessKeyID string - SecretAccessKey string -} - -// getCredentials - get credentials file. -func getCredentials(credentialsFile string) ([]credential, *probe.Error) { - reader, e := os.Open(credentialsFile) - if e != nil { - return nil, probe.NewError(e) - } - creds := []credential{} - // skip the first line of the csv file, usually csv header. - skipLine := 1 - if err := newCSVReader(reader).Unmarshal(&creds, skipLine); err != nil { - return nil, err.Trace(credentialsFile) - } - if len(creds) == 0 { - return nil, errInvalidArgument().Trace(credentialsFile) - } - return creds, nil -} - -//// CSV reader block. - -/// CSV read errors. - -// An invalidUnmarshalError describes an invalid argument passed to Unmarshal. -// (The argument to Unmarshal must be a non-nil pointer.) -type invalidUnmarshalError struct { - Type reflect.Type -} - -func (e *invalidUnmarshalError) Error() string { - if e.Type == nil { - return "csv: Unmarshal(nil)" - } - if e.Type.Kind() != reflect.Ptr { - return "csv: Unmarshal(non-pointer " + e.Type.String() + ")" - } - return "csv: Unmarshal(nil " + e.Type.String() + ")" -} - -// An unmarshalTypeError describes a CSV value that was -// not appropriate for a value of a specific Go type. -type unmarshalTypeError struct { - Type reflect.Type // type of Go value it could not be assigned to -} - -func (e *unmarshalTypeError) Error() string { - return "csv: cannot unmarshal into Go value of type " + e.Type.String() -} - -/// CSV Unmarshaler. - -// Unmarshal - unmarshal everything into the input struct. -func (r *csvReader) Unmarshal(v interface{}, skipLine int) (err *probe.Error) { - // Handler for runtime errors. - defer func() { - if r := recover(); r != nil { - if _, ok := r.(runtime.Error); ok { - panic(r) - } - e := r.(error) - err = probe.NewError(e) - } - }() - { - // Check if incoming interface{} is nil. - rv := reflect.ValueOf(v) - if rv.Kind() != reflect.Ptr || rv.IsNil() { - return probe.NewError(&invalidUnmarshalError{reflect.TypeOf(v)}) - } - } - rv := reflect.ValueOf(v).Elem() - rt := reflect.TypeOf(v).Elem().Elem() - records := reflect.MakeSlice(reflect.TypeOf(v).Elem(), 0, 0) - var e error - var lineCount int - for { - record := reflect.New(rt) - { - var csvRecord []string - csvRecord, e = r.Read() - if e != nil { - break - } - lineCount++ - // Skip a particular line - if lineCount == skipLine { - continue - } - rvInternal := reflect.ValueOf(record.Interface()).Elem() - for s := 0; s < rvInternal.NumField(); s++ { - val := rvInternal.Field(s) - x := csvRecord[s] - setValue(&val, x) - } - } - records = reflect.Append(records, record.Elem()) - } - if e == io.EOF { - rv.Set(records) - return nil - } - if e != nil { - return probe.NewError(e) - } - return nil -} - -// setValue - following reflect.Value sets the actual value based on the Golang type. -// If no native type found throws an UnmarshalTypeError. -func setValue(v *reflect.Value, x string) *probe.Error { - switch v.Kind() { - case reflect.Bool: - val, e := strconv.ParseBool(x) - if e != nil { - return probe.NewError(e) - } - v.SetBool(val) - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - val, e := strconv.ParseInt(x, 10, v.Type().Bits()) - if e != nil { - return probe.NewError(e) - } - v.SetInt(val) - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - val, e := strconv.ParseUint(x, 10, v.Type().Bits()) - if e != nil { - return probe.NewError(e) - } - v.SetUint(val) - - case reflect.Float32, reflect.Float64: - val, e := strconv.ParseFloat(x, v.Type().Bits()) - if e != nil { - return probe.NewError(e) - } - v.SetFloat(val) - - case reflect.String: - v.SetString(x) - case reflect.Struct: - case reflect.Map: - case reflect.Slice: - case reflect.Array: - case reflect.Interface, reflect.Ptr: - default: - return probe.NewError(&unmarshalTypeError{v.Type()}) - } - return nil -} diff --git a/diff-main.go b/diff-main.go index 77bbf865..d679ce8d 100644 --- a/diff-main.go +++ b/diff-main.go @@ -59,7 +59,7 @@ DESCRIPTION: EXAMPLES: 1. Compare a local folder with a folder on Amazon S3 cloud storage. - $ mc {{.Name}} ~/Photos s3.amazonaws.com/MyBucket/Photos + $ mc {{.Name}} ~/Photos s3/MyBucket/Photos 2. Compare two different folders on a local filesystem. $ mc {{.Name}} ~/Photos /Media/Backup/Photos @@ -128,7 +128,7 @@ func doDiffMain(firstURL, secondURL string) { secondURL = secondURL + targetSeparator } - firstClient, err := url2Client(firstURL) + firstClient, err := newClient(firstURL) if err != nil { fatalIf(err.Trace(firstURL, secondURL), fmt.Sprintf("Failed to diff '%s' and '%s'", firstURL, secondURL)) } @@ -184,9 +184,7 @@ func mainDiff(ctx *cli.Context) { console.SetColor("DiffType", color.New(color.FgYellow, color.Bold)) console.SetColor("DiffSize", color.New(color.FgMagenta, color.Bold)) - URLs, err := args2URLs(ctx.Args()) - fatalIf(err.Trace(ctx.Args()...), "Unable to convert args 2 URLs") - + URLs := ctx.Args() firstURL := URLs[0] secondURL := URLs[1] diff --git a/difference.go b/difference.go index 8d9447b1..5159c4f7 100644 --- a/difference.go +++ b/difference.go @@ -39,7 +39,7 @@ const ( // between sourceURL and targetURL // for usage reference check diff and mirror commands func objectDifferenceFactory(targetURL string) (objectDifference, *probe.Error) { - clnt, err := url2Client(targetURL) + clnt, err := newClient(targetURL) if err != nil { return nil, err.Trace(targetURL) } diff --git a/globals.go b/globals.go index a05ea1aa..0359c4f9 100644 --- a/globals.go +++ b/globals.go @@ -24,7 +24,7 @@ import ( // mc configuration related constants. const ( - globalMCConfigVersion = "6" + globalMCConfigVersion = "7" globalMCConfigDir = ".mc/" globalMCConfigWindowsDir = "mc\\" @@ -33,15 +33,6 @@ const ( // session config and shared urls related constants globalSessionDir = "session" globalSharedURLsDataDir = "share" - - // default access and secret key - // do not pass accesskeyid and secretaccesskey through cli - // users should manually edit them, add a stub entry - globalAccessKeyID = "YOUR-ACCESS-KEY-ID-HERE" - globalSecretAccessKey = "YOUR-SECRET-ACCESS-KEY-HERE" - - // default host - globalExampleHostURL = "http://YOUR-EXAMPLE.COM" ) var ( diff --git a/hostconfig.go b/hostconfig.go deleted file mode 100644 index f644903e..00000000 --- a/hostconfig.go +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Minio Client (C) 2015 Minio, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package main - -import ( - "strings" - - "github.com/minio/mc/pkg/client" - "github.com/minio/minio-xl/pkg/probe" -) - -// hostConfig configuration of a host. -type hostConfig struct { - AccessKeyID string `json:"accessKeyId"` - SecretAccessKey string `json:"secretAccessKey"` - API string `json:"api"` -} - -// getHostConfig retrieves host specific configuration such as access keys, signature type. -func getHostConfig(URL string) (hostConfig, *probe.Error) { - config, err := loadMcConfig() - if err != nil { - return hostConfig{}, err.Trace(URL) - } - url := client.NewURL(URL) - // No host matching or keys needed for filesystem requests. - if url.Type == client.Filesystem { - hostCfg := hostConfig{ - AccessKeyID: "", - SecretAccessKey: "", - API: "fs", - } - return hostCfg, nil - } - // if host is exact return quickly. - if _, ok := config.Hosts[url.String()]; ok { - return config.Hosts[url.String()], nil - } - // if host matches a suffix return. - for savedURLStr, hostCfg := range config.Hosts { - savedURL := client.NewURL(savedURLStr) - if strings.HasSuffix(url.Host, savedURL.Host) { - return hostCfg, nil - } - } - // return error if cannot be matched. - return hostConfig{}, errNoMatchingHost(URL).Trace(URL) -} diff --git a/ls-main.go b/ls-main.go index 4ddc478f..973f872b 100644 --- a/ls-main.go +++ b/ls-main.go @@ -17,7 +17,6 @@ package main import ( - "fmt" "strings" "github.com/fatih/color" @@ -61,20 +60,20 @@ FLAGS: {{end}} EXAMPLES: 1. List buckets on Amazon S3 cloud storage. - $ mc {{.Name}} s3.amazonaws.com + $ mc {{.Name}} s3 2. List buckets and all its contents from Amazon S3 cloud storage recursively. - $ mc {{.Name}} --recursive s3.amazonaws.com + $ mc {{.Name}} --recursive s3 - 3. List files recursively on a local filesystem on Microsoft Windows. + 3. List all contents of mybucket on Amazon S3 cloud storage. + $ mc {{.Name}} s3/mybucket/ + + 4. List all contents of mybucket on Amazon S3 cloud storage on Microsoft Windows. + $ mc {{.Name}} s3\mybucket\ + + 5. List files recursively on a local filesystem on Microsoft Windows. $ mc {{.Name}} --recursive C:\Users\Worf\ - 4. List files with non-English characters on Amazon S3 cloud storage. - $ mc {{.Name}} s3/andoria/本 - - 5. List folders with space separated names on Amazon S3 cloud storage. - $ mc {{.Name}} 's3/miniocloud/Community Files/' - 6. List incomplete (previously failed) uploads of objects on Amazon S3. $ mc {{.Name}} --incomplete s3/mybucket `, @@ -92,9 +91,7 @@ func checkListSyntax(ctx *cli.Context) { } } // extract URLs. - URLs, err := args2URLs(ctx.Args()) - fatalIf(err.Trace(ctx.Args()...), fmt.Sprintf("One or more unknown URL types passed.")) - + URLs := ctx.Args() isIncomplete := ctx.Bool("incomplete") for _, url := range URLs { @@ -129,11 +126,9 @@ func mainList(ctx *cli.Context) { args = []string{"."} } - targetURLs, err := args2URLs(args) - fatalIf(err.Trace(args...), "One or more unknown URL types passed.") - for _, targetURL := range targetURLs { + for _, targetURL := range args { var clnt client.Client - clnt, err = url2Client(targetURL) + clnt, err := newClient(targetURL) fatalIf(err.Trace(targetURL), "Unable to initialize target ‘"+targetURL+"’.") err = doList(clnt, isRecursive, isIncomplete) diff --git a/ls.go b/ls.go index 21aee6b6..3a7aa0b7 100644 --- a/ls.go +++ b/ls.go @@ -111,7 +111,6 @@ func doList(clnt client.Client, isRecursive, isIncomplete bool) *probe.Error { prefixPath = prefixPath[:strings.LastIndex(prefixPath, separator)+1] } for content := range clnt.List(isRecursive, isIncomplete) { - // fmt.Println(content) if content.Err != nil { switch content.Err.ToGoError().(type) { // handle this specifically for filesystem related errors. diff --git a/main.go b/main.go index e35c22d2..6407f8e5 100644 --- a/main.go +++ b/main.go @@ -31,6 +31,7 @@ import ( ) var ( + // global flags for mc. mcFlags = []cli.Flag{ cli.BoolFlag{ Name: "help, h", @@ -87,10 +88,13 @@ func checkConfig() { func migrate() { // Fix broken config files if any. fixConfig() + // Migrate config files if any. migrateConfig() + // Migrate session files if any. migrateSession() + // Migrate shared urls if any. migrateShare() } diff --git a/mb-main.go b/mb-main.go index dda1086f..0e93fc2b 100644 --- a/mb-main.go +++ b/mb-main.go @@ -52,13 +52,10 @@ FLAGS: {{end}} EXAMPLES: 1. Create a bucket on Amazon S3 cloud storage. - $ mc {{.Name}} s3.amazonaws.com/mynewbucket + $ mc {{.Name}} s3/mynewbucket 2. Create a new bucket on Google Cloud Storage. - $ mc {{.Name}} storage.googleapis.com/miniocloud - - 3. Create a new bucket on Amazon S3 cloud storage, using virtual bucket request. - $ mc {{.Name}} ferenginar.s3.amazonaws.com + $ mc {{.Name}} gcs/miniocloud 3. Create a new directory including its missing parents (equivalent to ‘mkdir -p’). $ mc {{.Name}} /tmp/this/new/dir1 @@ -107,12 +104,9 @@ func mainMakeBucket(ctx *cli.Context) { // Additional command speific theme customization. console.SetColor("MakeBucket", color.New(color.FgGreen, color.Bold)) - URLs, err := args2URLs(ctx.Args()) - fatalIf(err.Trace(ctx.Args()...), "Unable to convert args to URLs.") - - for _, targetURL := range URLs { + for _, targetURL := range ctx.Args() { // Instantiate client for URL. - clnt, err := url2Client(targetURL) + clnt, err := newClient(targetURL) fatalIf(err.Trace(targetURL), "Invalid target ‘"+targetURL+"’.") // Make bucket. diff --git a/mb_access_test.go b/mb_access_test.go deleted file mode 100644 index 2cb017ae..00000000 --- a/mb_access_test.go +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Minio Client (C) 2015 Minio, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package main - -import . "gopkg.in/check.v1" - -func (s *TestSuite) TestMbAndAccess(c *C) { - // Instantiate client for URL. - clnt, err := url2Client(server.URL + "/bucket") - c.Assert(err, IsNil) - - // Make bucket. - err = clnt.MakeBucket() - c.Assert(err, IsNil) - - err = doSetAccess(server.URL+"/bucket", "public-read-write") - c.Assert(err, IsNil) - - err = doSetAccess(server.URL+"/bucket", "invalid") - c.Assert(err, Not(IsNil)) - - perm, err := doGetAccess(server.URL + "/bucket") - c.Assert(err, IsNil) - c.Assert(perm.isPrivate(), Equals, true) -} diff --git a/mc_test.go b/mc_test.go index 89dc3889..6639341b 100644 --- a/mc_test.go +++ b/mc_test.go @@ -17,11 +17,8 @@ package main import ( - "io/ioutil" - "os" "path/filepath" "runtime" - "sync" "testing" "time" @@ -43,120 +40,9 @@ var server *httptest.Server var app *cli.App func (s *TestSuite) SetUpSuite(c *C) { - objectAPI := objectAPIHandler(objectAPIHandler{lock: &sync.Mutex{}, bucket: "bucket", object: make(map[string][]byte)}) - server = httptest.NewServer(objectAPI) - - // do not set it elsewhere, leads to data races since this is a global flag - globalQuiet = true // quiet is set to turn of progress bar - - tmpDir, e := ioutil.TempDir(os.TempDir(), "cmd-") - c.Assert(e, IsNil) - - // For windows the path is slightly different. - if runtime.GOOS == "windows" { - customConfigDir = filepath.Join(tmpDir, globalMCConfigWindowsDir) - } else { - customConfigDir = filepath.Join(tmpDir, globalMCConfigDir) - } - setMcConfigDir(customConfigDir) - - err := createMcConfigDir() - c.Assert(err, IsNil) - - config := newMcConfig() - config.Hosts[server.URL] = hostConfig{ - AccessKeyID: "WLGDGYAQYIGI833EV05A", - SecretAccessKey: "BYvgJM101sHngl2uzjXS/OBF/aMxAN06JrJ3qJlF", - API: "S3v4", - } - - err = saveMcConfig(config) - c.Assert(err, IsNil) - - err = createSessionDir() - c.Assert(err, IsNil) - - app = registerApp() } func (s *TestSuite) TearDownSuite(c *C) { - os.RemoveAll(customConfigDir) - if server != nil { - server.Close() - } -} - -func (s *TestSuite) TestGetNewClient(c *C) { - _, err := getNewClient("http://example.com/bucket1", hostConfig{}) - c.Assert(err, IsNil) - _, err = getNewClient("https://example.com/bucket1", hostConfig{}) - c.Assert(err, IsNil) - _, err = getNewClient("C:\\Users\\Administrator\\MyDocuments", hostConfig{}) - c.Assert(err, IsNil) - _, err = getNewClient("/usr/bin/pandoc", hostConfig{}) - c.Assert(err, IsNil) - _, err = getNewClient("pkg/client", hostConfig{}) - c.Assert(err, IsNil) -} - -// setMcConfigPath - set a custom minio client config path. -func setMcConfigPath(configPath string) { - mcCustomConfigPath = configPath -} - -func (s *TestSuite) TestNewConfigV6(c *C) { - root, e := ioutil.TempDir(os.TempDir(), "mc-") - c.Assert(e, IsNil) - defer os.RemoveAll(root) - - conf := newMcConfig() - configFile := filepath.Join(root, globalMCConfigFile) - setMcConfigPath(configFile) - - err := saveMcConfig(conf) - c.Assert(err, IsNil) - - data, err := loadMcConfig() - c.Assert(err, IsNil) - - setMcConfigPath("") - - type aliases struct { - name string - url string - } - - wantAliases := []aliases{ - { - "s3", - "https://s3.amazonaws.com", - }, - { - "play", - "https://play.minio.io:9000", - }, - { - "local", - "http://localhost:9000", - }, - } - for _, alias := range wantAliases { - url, ok := data.Aliases[alias.name] - c.Assert(ok, Equals, true) - c.Assert(url, Equals, alias.url) - } - - wantHosts := []string{ - "http://localhost:9000", - "https://play.minio.io:9000", - "https://dl.minio.io:9000", - "https://s3.amazonaws.com", - "https://storage.googleapis.com", - } - for _, host := range wantHosts { - _, ok := data.Hosts[host] - c.Assert(ok, Equals, true) - } } func (s *TestSuite) TestValidPERMS(c *C) { @@ -182,18 +68,7 @@ func (s *TestSuite) TestInvalidPERMS(c *C) { func (s *TestSuite) TestGetMcConfigDir(c *C) { dir, err := getMcConfigDir() c.Assert(err, IsNil) - switch runtime.GOOS { - case "linux": - fallthrough - case "freebsd": - fallthrough - case "darwin": - c.Assert(dir, Equals, customConfigDir) - case "windows": - c.Assert(dir, Equals, customConfigDir) - default: - c.Fail() - } + c.Assert(dir, Not(Equals), "") c.Assert(mustGetMcConfigDir(), Equals, dir) } @@ -216,36 +91,14 @@ func (s *TestSuite) TestGetMcConfigPath(c *C) { } func (s *TestSuite) TestIsvalidAliasName(c *C) { - c.Check(isValidAliasName("helloWorld0"), Equals, true) - c.Check(isValidAliasName("h0SFD2k24Fdsa"), Equals, true) - c.Check(isValidAliasName("fdslka-4"), Equals, true) - c.Check(isValidAliasName("fdslka-"), Equals, true) - c.Check(isValidAliasName("helloWorld$"), Equals, false) - c.Check(isValidAliasName("h0SFD2k2#Fdsa"), Equals, false) - c.Check(isValidAliasName("0dslka-4"), Equals, false) - c.Check(isValidAliasName("-fdslka"), Equals, false) -} - -func (s *TestSuite) TestEmptyExpansions(c *C) { - url, err := getAliasURL("hello") - c.Assert(err, IsNil) - c.Assert(url, Equals, "hello") - - url, err = getAliasURL("minio://hello") - c.Assert(err, IsNil) - c.Assert(url, Equals, "minio://hello") - - url, err = getAliasURL("$#\\") - c.Assert(err, IsNil) - c.Assert(url, Equals, "$#\\") - - url, err = getAliasURL("myfoo/bar") - c.Assert(err, IsNil) - c.Assert(url, Equals, "myfoo/bar") - - url, err = getAliasURL("") - c.Assert(err, IsNil) - c.Assert(url, Equals, "") + c.Check(isValidAlias("helloWorld0"), Equals, true) + c.Check(isValidAlias("h0SFD2k24Fdsa"), Equals, true) + c.Check(isValidAlias("fdslka-4"), Equals, true) + c.Check(isValidAlias("fdslka-"), Equals, true) + c.Check(isValidAlias("helloWorld$"), Equals, false) + c.Check(isValidAlias("h0SFD2k2#Fdsa"), Equals, false) + c.Check(isValidAlias("0dslka-4"), Equals, false) + c.Check(isValidAlias("-fdslka"), Equals, false) } func (s *TestSuite) TestHumanizedTime(c *C) { @@ -277,8 +130,3 @@ func (s *TestSuite) TestVersions(c *C) { c.Assert(v2.LessThan(v1), Equals, true) c.Assert(v1.LessThan(v2), Equals, false) } - -func (s *TestSuite) TestApp(c *C) { - err := app.Run([]string{""}) - c.Assert(err, IsNil) -} diff --git a/mirror-main.go b/mirror-main.go index c9aefc39..de57501b 100644 --- a/mirror-main.go +++ b/mirror-main.go @@ -66,21 +66,23 @@ FLAGS: {{end}} EXAMPLES: 1. Mirror a bucket recursively from Minio cloud storage to a bucket on Amazon S3 cloud storage. - $ mc {{.Name}} play.minio.io:9000/photos/2014 s3.amazonaws.com/backup-photos + $ mc {{.Name}} play/photos/2014 s3/backup-photos 2. Mirror a local folder recursively to Amazon S3 cloud storage. - $ mc {{.Name}} backup/ s3.amazonaws.com/archive + $ mc {{.Name}} backup/ s3/archive 3. Mirror a bucket from aliased Amazon S3 cloud storage to a folder on Windows. - $ mc {{.Name}} s3/documents/2014/ C:\backup\2014 + $ mc {{.Name}} s3\documents\2014\ C:\backup\2014 `, } // mirrorMessage container for file mirror messages type mirrorMessage struct { - Status string `json:"status"` - Source string `json:"source"` - Target string `json:"target"` + Status string `json:"status"` + SourceAlias string `json:"sourceAlias,omitempty"` + Source string `json:"source"` + TargetAlias string `json:"targetAlias,omitempty"` + Target string `json:"target"` } // String colorized mirror message @@ -130,15 +132,17 @@ func doMirror(sURLs mirrorURLs, progressReader *barSend, accountingReader *accou return } - targetURL := sURLs.TargetContent.URL.String() + sourceAlias := sURLs.SourceAlias sourceURL := sURLs.SourceContent.URL.String() + targetAlias := sURLs.TargetAlias + targetURL := sURLs.TargetContent.URL.String() length := sURLs.SourceContent.Size if !globalQuiet && !globalJSON { progressReader.SetCaption(sourceURL + ": ") } - reader, err := getSource(sourceURL) + reader, err := getSourceFromAlias(sourceAlias, sourceURL) if err != nil { if !globalQuiet && !globalJSON { progressReader.ErrorGet(length) @@ -151,8 +155,10 @@ func doMirror(sURLs mirrorURLs, progressReader *barSend, accountingReader *accou var newReader io.ReadSeeker if globalQuiet || globalJSON { printMsg(mirrorMessage{ - Source: sourceURL, - Target: targetURL, + SourceAlias: sourceAlias, + Source: sourceURL, + TargetAlias: targetAlias, + Target: targetURL, }) if globalJSON { newReader = reader @@ -164,7 +170,7 @@ func doMirror(sURLs mirrorURLs, progressReader *barSend, accountingReader *accou // set up progress newReader = progressReader.NewProxyReader(reader) } - err = putTarget(targetURL, newReader, length) + err = putTargetFromAlias(targetAlias, targetURL, newReader, length) if err != nil { if !globalQuiet && !globalJSON { progressReader.ErrorPut(length) @@ -186,7 +192,7 @@ func doMirrorFake(sURLs mirrorURLs, progressReader *barSend) { } // doPrepareMirrorURLs scans the source URL and prepares a list of objects for mirroring. -func doPrepareMirrorURLs(session *sessionV5, isForce bool, trapCh <-chan bool) { +func doPrepareMirrorURLs(session *sessionV6, isForce bool, trapCh <-chan bool) { sourceURL := session.Header.CommandArgs[0] // first one is source. targetURL := session.Header.CommandArgs[1] var totalBytes int64 @@ -247,7 +253,7 @@ func doPrepareMirrorURLs(session *sessionV5, isForce bool, trapCh <-chan bool) { } // Session'fied mirror command. -func doMirrorSession(session *sessionV5) { +func doMirrorSession(session *sessionV6) { isForce := session.Header.CommandBoolFlags["force"] trapCh := signalTrap(os.Interrupt, syscall.SIGTERM) @@ -373,7 +379,7 @@ func mainMirror(ctx *cli.Context) { console.SetColor("Mirror", color.New(color.FgGreen, color.Bold)) var e error - session := newSessionV5() + session := newSessionV6() session.Header.CommandType = "mirror" session.Header.RootPath, e = os.Getwd() if e != nil { @@ -386,13 +392,7 @@ func mainMirror(ctx *cli.Context) { session.Header.CommandBoolFlags["force"] = isForce // extract URLs. - var err *probe.Error - session.Header.CommandArgs, err = args2URLs(ctx.Args()) - if err != nil { - session.Delete() - fatalIf(err.Trace(ctx.Args()...), fmt.Sprintf("One or more unknown argument types found in ‘%s’.", ctx.Args())) - } - + session.Header.CommandArgs = ctx.Args() doMirrorSession(session) session.Delete() } diff --git a/mirror-url.go b/mirror-url.go index 3dba773c..e66efd90 100644 --- a/mirror-url.go +++ b/mirror-url.go @@ -26,7 +26,9 @@ import ( ) type mirrorURLs struct { + SourceAlias string SourceContent *client.Content + TargetAlias string TargetContent *client.Content Error *probe.Error `json:"-"` } @@ -53,9 +55,7 @@ func checkMirrorSyntax(ctx *cli.Context) { } // extract URLs. - URLs, err := args2URLs(ctx.Args()) - fatalIf(err.Trace(ctx.Args()...), "Unable to parse arguments.") - + URLs := ctx.Args() srcURL := URLs[0] tgtURL := URLs[1] @@ -92,6 +92,10 @@ func checkMirrorSyntax(ctx *cli.Context) { } func deltaSourceTargets(sourceURL string, targetURL string, isForce bool, mirrorURLsCh chan<- mirrorURLs) { + // Extract alias before fiddling with the URL. + sourceAlias, _, _ := mustExpandAlias(sourceURL) + targetAlias, _, _ := mustExpandAlias(targetURL) + defer close(mirrorURLsCh) // source and targets are always directories @@ -110,7 +114,7 @@ func deltaSourceTargets(sourceURL string, targetURL string, isForce bool, mirror return } - sourceClient, err := url2Client(sourceURL) + sourceClient, err := newClient(sourceURL) if err != nil { mirrorURLsCh <- mirrorURLs{Error: err.Trace(sourceURL)} return @@ -147,7 +151,9 @@ func deltaSourceTargets(sourceURL string, targetURL string, isForce bool, mirror targetPath := urlJoinPath(targetURL, suffix) targetContent := &client.Content{URL: *client.NewURL(targetPath)} mirrorURLsCh <- mirrorURLs{ + SourceAlias: sourceAlias, SourceContent: sourceContent, + TargetAlias: targetAlias, TargetContent: targetContent, } } diff --git a/pipe-main.go b/pipe-main.go index bb812c06..8384d026 100644 --- a/pipe-main.go +++ b/pipe-main.go @@ -53,13 +53,13 @@ EXAMPLES: $ mc {{.Name}} /tmp/hello-world.go 2. Write contents of stdin to an object on Amazon S3 cloud storage. - $ mc {{.Name}} s3.amazonaws.com/personalbuck/meeting-notes.txt + $ mc {{.Name}} s3/personalbuck/meeting-notes.txt 3. Copy an ISO image to an object on Amazon S3 cloud storage and Google Cloud Storage simultaneously. - $ cat debian-8.2.iso | mc {{.Name}} s3.amazonaws.com/ferenginar/gnuos.iso + $ cat debian-8.2.iso | mc {{.Name}} s3/ferenginar/gnuos.iso 4. Stream MySQL database dump to Amazon S3 directly. - $ mysqldump -u root -p ******* accountsdb | mc {{.Name}} s3.amazonaws.com/ferenginar/backups/accountsdb-oct-9-2015.sql + $ mysqldump -u root -p ******* accountsdb | mc {{.Name}} s3/ferenginar/backups/accountsdb-oct-9-2015.sql `, } @@ -104,9 +104,8 @@ func mainPipe(ctx *cli.Context) { fatalIf(err.Trace("stdout"), "Unable to write to one or more targets.") } else { // extract URLs. - URLs, err := args2URLs(ctx.Args()) - fatalIf(err.Trace(ctx.Args()...), "Unable to parse arguments.") - err = pipe(URLs[0]) + URLs := ctx.Args() + err := pipe(URLs[0]) fatalIf(err.Trace(URLs[0]), "Unable to write to one or more targets.") } } diff --git a/pkg/client/client.go b/pkg/client/client.go index 722f80b2..e3e11ac6 100644 --- a/pkg/client/client.go +++ b/pkg/client/client.go @@ -61,12 +61,12 @@ type Content struct { // Config - see http://docs.amazonwebservices.com/AmazonS3/latest/dev/index.html?RESTAuthentication.html type Config struct { - AccessKeyID string - SecretAccessKey string - Signature string - HostURL string - AppName string - AppVersion string - AppComments []string - Debug bool + AccessKey string + SecretKey string + Signature string + HostURL string + AppName string + AppVersion string + AppComments []string + Debug bool } diff --git a/pkg/client/s3/s3.go b/pkg/client/s3/s3.go index 94570f9b..04ab5375 100644 --- a/pkg/client/s3/s3.go +++ b/pkg/client/s3/s3.go @@ -54,8 +54,8 @@ func New(config *client.Config) (client.Client, *probe.Error) { } } s3Conf := minio.Config{ - AccessKeyID: config.AccessKeyID, - SecretAccessKey: config.SecretAccessKey, + AccessKeyID: config.AccessKey, + SecretAccessKey: config.SecretKey, Transport: transport, Endpoint: u.Scheme + u.SchemeSeparator + u.Host, Signature: func() minio.SignatureType { diff --git a/rm-main.go b/rm-main.go index 057cc2ae..3a3056c1 100644 --- a/rm-main.go +++ b/rm-main.go @@ -73,19 +73,19 @@ EXAMPLES: $ mc {{.Name}} 1999/old-backup.tgz 2. Remove contents of a folder, excluding its sub-folders. - $ mc {{.Name}} --force s3.amazonaws.com/jazz-songs/louis/ + $ mc {{.Name}} --force s3/jazz-songs/louis/ 3. Remove contents of a folder recursively. - $ mc {{.Name}} --force --recursive s3.amazonaws.com/jazz-songs/louis/ + $ mc {{.Name}} --force --recursive s3/jazz-songs/louis/ 4. Remove all matching objects with this prefix. - $ mc {{.Name}} --force s3.amazonaws.com/ogg/gunmetal + $ mc {{.Name}} --force s3/ogg/gunmetal 5. Drop an incomplete upload of an object. - $ mc {{.Name}} --incomplete s3.amazonaws.com/jazz-songs/louis/file01.mp3 + $ mc {{.Name}} --incomplete s3/jazz-songs/louis/file01.mp3 6. Drop all incomplete uploads recursively matching this prefix. - $ mc {{.Name}} --incomplete --force --recursive s3.amazonaws.com/jazz-songs/louis/ + $ mc {{.Name}} --incomplete --force --recursive s3/jazz-songs/louis/ `, } @@ -120,9 +120,7 @@ func checkRmSyntax(ctx *cli.Context) { } if !isRecursive && !isIncomplete { - URLs, err := args2URLs(ctx.Args()) - fatalIf(err.Trace(ctx.Args()...), "Unable to parse arguments.") - for _, url := range URLs { + for _, url := range ctx.Args() { if _, _, err := url2Stat(url); err != nil { fatalIf(err.Trace(url), "Unable to stat.") } @@ -137,7 +135,7 @@ func checkRmSyntax(ctx *cli.Context) { // Remove a single object. func rm(url string, isIncomplete, isFake bool) *probe.Error { - clnt, err := url2Client(url) + clnt, err := newClient(url) if err != nil { return err.Trace(url) } @@ -156,7 +154,7 @@ func rm(url string, isIncomplete, isFake bool) *probe.Error { // Remove all objects recursively. func rmAll(url string, isRecursive, isIncomplete, isFake bool) { // Initialize new client. - clnt, err := url2Client(url) + clnt, err := newClient(url) if err != nil { errorIf(err.Trace(url), "Invalid URL ‘"+url+"’.") return // End of journey. @@ -206,12 +204,8 @@ func mainRm(ctx *cli.Context) { // Set color. console.SetColor("Remove", color.New(color.FgGreen, color.Bold)) - // Parse args. - URLs, err := args2URLs(ctx.Args()) - fatalIf(err.Trace(ctx.Args()...), "Unable to parse arguments.") - // Support multiple targets. - for _, url := range URLs { + for _, url := range ctx.Args() { if isRecursive && isForce { rmAll(url, isRecursive, isIncomplete, isFake) } else { diff --git a/session-main.go b/session-main.go index dcd85894..03c70927 100644 --- a/session-main.go +++ b/session-main.go @@ -77,7 +77,7 @@ EXAMPLES: } // bySessionWhen is a type for sorting session metadata by time. -type bySessionWhen []*sessionV5 +type bySessionWhen []*sessionV6 func (b bySessionWhen) Len() int { return len(b) } func (b bySessionWhen) Swap(i, j int) { b[i], b[j] = b[j], b[i] } @@ -85,9 +85,9 @@ func (b bySessionWhen) Less(i, j int) bool { return b[i].Header.When.Before(b[j] // listSessions list all current sessions. func listSessions() *probe.Error { - var bySessions []*sessionV5 + var bySessions []*sessionV6 for _, sid := range getSessionIDs() { - s, err := loadSessionV5(sid) + s, err := loadSessionV6(sid) if err != nil { return err.Trace(sid) } @@ -125,7 +125,7 @@ func (c clearSessionMessage) JSON() string { func clearSession(sid string) { if sid == "all" { for _, sid := range getSessionIDs() { - session, err := loadSessionV5(sid) + session, err := loadSessionV6(sid) fatalIf(err.Trace(sid), "Unable to load session ‘"+sid+"’.") fatalIf(session.Delete().Trace(sid), "Unable to load session ‘"+sid+"’.") @@ -139,7 +139,7 @@ func clearSession(sid string) { fatalIf(errDummy().Trace(sid), "Session ‘"+sid+"’ not found.") } - session, err := loadSessionV5(sid) + session, err := loadSessionV6(sid) fatalIf(err.Trace(sid), "Unable to load session ‘"+sid+"’.") if session != nil { @@ -148,7 +148,7 @@ func clearSession(sid string) { } } -func sessionExecute(s *sessionV5) { +func sessionExecute(s *sessionV6) { switch s.Header.CommandType { case "cp": doCopySession(s) @@ -230,7 +230,7 @@ func mainSession(ctx *cli.Context) { } fatalIf(errDummy().Trace(sid), errorMsg) } - s, err := loadSessionV5(sid) + s, err := loadSessionV6(sid) fatalIf(err.Trace(sid), "Unable to load session.") // Restore the state of global variables from this previous session. diff --git a/session-v5.go b/session-v6.go similarity index 86% rename from session-v5.go rename to session-v6.go index e67a565a..258409ff 100644 --- a/session-v5.go +++ b/session-v6.go @@ -32,14 +32,14 @@ import ( "github.com/minio/minio-xl/pkg/quick" ) -func migrateSessionV4ToV5() { +func migrateSessionV5ToV6() { for _, sid := range getSessionIDs() { - sessionV5, err := loadSessionV5(sid) - fatalIf(err.Trace(sid), "Unable to load version ‘5’. Migration failed please report this issue at https://github.com/minio/mc/issues.") - if sessionV5.Header.Version == "5" { // It is new format. + sessionV6, err := loadSessionV6(sid) + fatalIf(err.Trace(sid), "Unable to load version ‘6’. Migration failed please report this issue at https://github.com/minio/mc/issues.") + if sessionV6.Header.Version == "6" { // It is new format. return } - /*** Remove all session files older than v5 ***/ + /*** Remove all session files older than v6 ***/ sessionFile, err := getSessionFile(sid) fatalIf(err.Trace(sid), "Unable to get session file.") @@ -47,18 +47,18 @@ func migrateSessionV4ToV5() { sessionDataFile, err := getSessionDataFile(sid) fatalIf(err.Trace(sid), "Unable to get session data file.") - console.Println("Removing unsupported session file ‘" + sessionFile + "’ version ‘" + sessionV5.Header.Version + "’.") + console.Println("Removing unsupported session file ‘" + sessionFile + "’ version ‘" + sessionV6.Header.Version + "’.") if e := os.Remove(sessionFile); e != nil { - fatalIf(probe.NewError(e), "Unable to remove version ‘"+sessionV5.Header.Version+"’ session file ‘"+sessionFile+"’.") + fatalIf(probe.NewError(e), "Unable to remove version ‘"+sessionV6.Header.Version+"’ session file ‘"+sessionFile+"’.") } if e := os.Remove(sessionDataFile); e != nil { - fatalIf(probe.NewError(e), "Unable to remove version ‘"+sessionV5.Header.Version+"’ session data file ‘"+sessionDataFile+"’.") + fatalIf(probe.NewError(e), "Unable to remove version ‘"+sessionV6.Header.Version+"’ session data file ‘"+sessionDataFile+"’.") } } } -// sessionV5Header for resumable sessions. -type sessionV5Header struct { +// sessionV6Header for resumable sessions. +type sessionV6Header struct { Version string `json:"version"` When time.Time `json:"time"` RootPath string `json:"workingFolder"` @@ -84,9 +84,9 @@ type sessionMessage struct { CommandArgs []string `json:"commandArgs"` } -// sessionV5 resumable session container. -type sessionV5 struct { - Header *sessionV5Header +// sessionV6 resumable session container. +type sessionV6 struct { + Header *sessionV6Header SessionID string mutex *sync.Mutex DataFP *sessionDataFP @@ -105,7 +105,7 @@ func (file *sessionDataFP) Write(p []byte) (int, error) { } // String colorized session message. -func (s sessionV5) String() string { +func (s sessionV6) String() string { message := console.Colorize("SessionID", fmt.Sprintf("%s -> ", s.SessionID)) message = message + console.Colorize("SessionTime", fmt.Sprintf("[%s]", s.Header.When.Local().Format(printDate))) message = message + console.Colorize("Command", fmt.Sprintf(" %s %s", s.Header.CommandType, strings.Join(s.Header.CommandArgs, " "))) @@ -113,7 +113,7 @@ func (s sessionV5) String() string { } // JSON jsonified session message. -func (s sessionV5) JSON() string { +func (s sessionV6) JSON() string { sessionMsg := sessionMessage{ SessionID: s.SessionID, Time: s.Header.When.Local(), @@ -127,8 +127,8 @@ func (s sessionV5) JSON() string { return string(sessionBytes) } -// loadSessionV5 - reads session file if exists and re-initiates internal variables -func loadSessionV5(sid string) (*sessionV5, *probe.Error) { +// loadSessionV6 - reads session file if exists and re-initiates internal variables +func loadSessionV6(sid string) (*sessionV6, *probe.Error) { if !isSessionDirExists() { return nil, errInvalidArgument().Trace() } @@ -141,8 +141,8 @@ func loadSessionV5(sid string) (*sessionV5, *probe.Error) { return nil, probe.NewError(err) } - s := &sessionV5{} - s.Header = &sessionV5Header{} + s := &sessionV6{} + s.Header = &sessionV6Header{} s.SessionID = sid s.Header.Version = "5" qs, err := quick.New(s.Header) @@ -155,7 +155,7 @@ func loadSessionV5(sid string) (*sessionV5, *probe.Error) { } s.mutex = new(sync.Mutex) - s.Header = qs.Data().(*sessionV5Header) + s.Header = qs.Data().(*sessionV6Header) sessionDataFile, err := getSessionDataFile(s.SessionID) if err != nil { @@ -171,11 +171,11 @@ func loadSessionV5(sid string) (*sessionV5, *probe.Error) { return s, nil } -// newSessionV5 provides a new session. -func newSessionV5() *sessionV5 { - s := &sessionV5{} - s.Header = &sessionV5Header{} - s.Header.Version = "5" +// newSessionV6 provides a new session. +func newSessionV6() *sessionV6 { + s := &sessionV6{} + s.Header = &sessionV6Header{} + s.Header.Version = "6" // map of command and files copied. s.Header.GlobalBoolFlags = make(map[string]bool) s.Header.GlobalIntFlags = make(map[string]int) @@ -203,7 +203,7 @@ func newSessionV5() *sessionV5 { } // HasData provides true if this is a session resume, false otherwise. -func (s sessionV5) HasData() bool { +func (s sessionV6) HasData() bool { if s.Header.LastCopied == "" { return false } @@ -211,21 +211,21 @@ func (s sessionV5) HasData() bool { } // NewDataReader provides reader interface to session data file. -func (s *sessionV5) NewDataReader() io.Reader { +func (s *sessionV6) NewDataReader() io.Reader { // DataFP is always intitialized, either via new or load functions. s.DataFP.Seek(0, os.SEEK_SET) return io.Reader(s.DataFP) } // NewDataReader provides writer interface to session data file. -func (s *sessionV5) NewDataWriter() io.Writer { +func (s *sessionV6) NewDataWriter() io.Writer { // DataFP is always intitialized, either via new or load functions. s.DataFP.Seek(0, os.SEEK_SET) return io.Writer(s.DataFP) } // Save this session. -func (s *sessionV5) Save() *probe.Error { +func (s *sessionV6) Save() *probe.Error { s.mutex.Lock() defer s.mutex.Unlock() @@ -250,7 +250,7 @@ func (s *sessionV5) Save() *probe.Error { // setGlobals captures the state of global variables into session header. // Used by newSession. -func (s *sessionV5) setGlobals() { +func (s *sessionV6) setGlobals() { s.Header.GlobalBoolFlags["quiet"] = globalQuiet s.Header.GlobalBoolFlags["debug"] = globalDebug s.Header.GlobalBoolFlags["json"] = globalJSON @@ -259,7 +259,7 @@ func (s *sessionV5) setGlobals() { // RestoreGlobals restores the state of global variables. // Used by resumeSession. -func (s sessionV5) restoreGlobals() { +func (s sessionV6) restoreGlobals() { quiet := s.Header.GlobalBoolFlags["quiet"] debug := s.Header.GlobalBoolFlags["debug"] json := s.Header.GlobalBoolFlags["json"] @@ -268,7 +268,7 @@ func (s sessionV5) restoreGlobals() { } // Close ends this session and removes all associated session files. -func (s *sessionV5) Close() *probe.Error { +func (s *sessionV6) Close() *probe.Error { s.mutex.Lock() defer s.mutex.Unlock() @@ -289,7 +289,7 @@ func (s *sessionV5) Close() *probe.Error { } // Delete removes all the session files. -func (s *sessionV5) Delete() *probe.Error { +func (s *sessionV6) Delete() *probe.Error { s.mutex.Lock() defer s.mutex.Unlock() @@ -319,7 +319,7 @@ func (s *sessionV5) Delete() *probe.Error { } // Close a session and exit. -func (s sessionV5) CloseAndDie() { +func (s sessionV6) CloseAndDie() { s.Close() console.Infoln("Session safely terminated. To resume session ‘mc session resume " + s.SessionID + "’") os.Exit(0) diff --git a/session.go b/session.go index b35c59b3..3be11503 100644 --- a/session.go +++ b/session.go @@ -27,7 +27,7 @@ import ( // migrateSession migrates all previous migration to latest. func migrateSession() { // We no longer support sessions older than v5. They will be removed. - migrateSessionV4ToV5() + migrateSessionV5ToV6() } // createSessionDir - create session directory. diff --git a/session_test.go b/session_test.go index 6528b203..4975322f 100644 --- a/session_test.go +++ b/session_test.go @@ -34,14 +34,14 @@ func (s *TestSuite) TestSession(c *C) { c.Assert(err, IsNil) c.Assert(isSessionDirExists(), Equals, true) - session := newSessionV5() + session := newSessionV6() c.Assert(session.Header.CommandArgs, IsNil) c.Assert(len(session.SessionID), Equals, 8) err = session.Close() c.Assert(err, IsNil) - savedSession, err := loadSessionV5(session.SessionID) + savedSession, err := loadSessionV6(session.SessionID) c.Assert(err, IsNil) c.Assert(session.SessionID, Equals, savedSession.SessionID) diff --git a/share-download-main.go b/share-download-main.go index e4b13351..4e5d62e3 100644 --- a/share-download-main.go +++ b/share-download-main.go @@ -54,16 +54,16 @@ OPTIONS: {{end}} EXAMPLES: 1. Share this object with 7 days default expiry. - $ mc share {{.Name}} s3.amazonaws.com/backup/2006-Mar-1/backup.tar.gz + $ mc share {{.Name}} s3/backup/2006-Mar-1/backup.tar.gz 2. Share this object with 10 minutes expiry. - $ mc share {{.Name}} --expire=10m s3.amazonaws.com/backup/2006-Mar-1/backup.tar.gz + $ mc share {{.Name}} --expire=10m s3/backup/2006-Mar-1/backup.tar.gz 3. Share all objects under this folder with 5 days expiry. - $ mc share {{.Name}} --expire=120h s3.amazonaws.com/backup/ + $ mc share {{.Name}} --expire=120h s3/backup/ 4. Share all objects under this folder and all its sub-folders with 5 days expiry. - $ mc share {{.Name}} --recursive --expire=120h s3.amazonaws.com/backup/ + $ mc share {{.Name}} --recursive --expire=120h s3/backup/ `, } @@ -91,10 +91,7 @@ func checkShareDownloadSyntax(ctx *cli.Context) { fatalIf(errDummy().Trace(expiry.String()), "Expiry cannot be larger than 7 days.") } - URLs, err := args2URLs(ctx.Args()) // expand alias. - fatalIf(err.Trace(ctx.Args()...), "Unable to convert args to URLs.") - - for _, url := range URLs { + for _, url := range ctx.Args() { _, _, err := url2Stat(url) fatalIf(err.Trace(url), "Unable to stat ‘"+url+"’.") } @@ -102,7 +99,7 @@ func checkShareDownloadSyntax(ctx *cli.Context) { // doShareURL share files from target. func doShareDownloadURL(targetURL string, isRecursive bool, expiry time.Duration) *probe.Error { - clnt, err := url2Client(targetURL) + clnt, err := newClient(targetURL) if err != nil { return err.Trace(targetURL) } @@ -126,7 +123,7 @@ func doShareDownloadURL(targetURL string, isRecursive bool, expiry time.Duration continue } objectURL := content.URL.String() - newClnt, err := url2Client(objectURL) + newClnt, err := newClient(objectURL) if err != nil { return err.Trace(objectURL) } @@ -176,10 +173,7 @@ func mainShareDownload(ctx *cli.Context) { fatalIf(probe.NewError(e), "Unable to parse expire=‘"+ctx.String("expire")+"’.") } - URLs, err := args2URLs(ctx.Args()) // expand alias. - fatalIf(err.Trace(ctx.Args()...), "Unable to convert args to URLs.") - - for _, targetURL := range URLs { + for _, targetURL := range ctx.Args() { err := doShareDownloadURL(targetURL, isRecursive, expiry) fatalIf(err.Trace(targetURL), "Unable to share target ‘"+targetURL+"’.") } diff --git a/share-upload-main.go b/share-upload-main.go index 1639f28e..7ef3f6fe 100644 --- a/share-upload-main.go +++ b/share-upload-main.go @@ -58,16 +58,16 @@ OPTIONS: {{end}} EXAMPLES: 1. Generate a curl command to allow upload access for a single object. Command expires in 7 days (default). - $ mc share {{.Name}} s3.amazonaws.com/backup/2006-Mar-1/backup.tar.gz + $ mc share {{.Name}} s3/backup/2006-Mar-1/backup.tar.gz 2. Generate a curl command to allow upload access to a folder. Command expires in 120 hours. - $ mc share {{.Name}} --expire=120h s3.amazonaws.com/backup/2007-Mar-2/ + $ mc share {{.Name}} --expire=120h s3/backup/2007-Mar-2/ 3. Generate a curl command to allow upload access of only '.png' images to a folder. Command expires in 2 hours. - $ mc share {{.Name}} --expire=2h --content-type=image/png s3.amazonaws.com/backup/2007-Mar-2/ + $ mc share {{.Name}} --expire=2h --content-type=image/png s3/backup/2007-Mar-2/ 4. Generate a curl command to allow upload access to any objects matching the key prefix 'backup/'. Command expires in 2 hours. - $ mc share {{.Name}} --recursive --expire=2h s3.amazonaws.com/backup/2007-Mar-2/backup/ + $ mc share {{.Name}} --recursive --expire=2h s3/backup/2007-Mar-2/backup/ `, } @@ -100,10 +100,7 @@ func checkShareUploadSyntax(ctx *cli.Context) { "Expiry cannot be larger than 7 days.") } - URLs, err := args2URLs(ctx.Args()) // expand alias. - fatalIf(err.Trace(ctx.Args()...), "Unable to convert args to URLs.") - - for _, targetURL := range URLs { + for _, targetURL := range ctx.Args() { url := client.NewURL(targetURL) if strings.HasSuffix(targetURL, string(url.Separator)) && !isRecursive { fatalIf(errInvalidArgument().Trace(targetURL), @@ -155,7 +152,7 @@ func saveSharedURL(objectURL string, shareURL string, expiry time.Duration, cont // doShareUploadURL uploads files to the target. func doShareUploadURL(objectURL string, isRecursive bool, expiry time.Duration, contentType string) *probe.Error { - clnt, err := url2Client(objectURL) + clnt, err := newClient(objectURL) if err != nil { return err.Trace(objectURL) } @@ -205,10 +202,7 @@ func mainShareUpload(ctx *cli.Context) { fatalIf(probe.NewError(e), "Unable to parse expire=‘"+expireArg+"’.") } - URLs, err := args2URLs(ctx.Args()) // expand alias. - fatalIf(err.Trace(ctx.Args()...), "Unable to convert args to URLs.") - - for _, targetURL := range URLs { + for _, targetURL := range ctx.Args() { err := doShareUploadURL(targetURL, isRecursive, expiry, contentType) fatalIf(err.Trace(targetURL), "Unable to generate curl command for upload ‘"+targetURL+"’.") } diff --git a/typed-errors.go b/typed-errors.go index 5f25d41d..1f8bfdef 100644 --- a/typed-errors.go +++ b/typed-errors.go @@ -35,10 +35,6 @@ var ( return probe.NewError(errors.New("No matching host found for the given URL ‘" + URL + "’.")).Untrace() } - errInitClient = func(URL string) *probe.Error { - return probe.NewError(errors.New("Unable to initialize client for URL ‘" + URL + "’.")).Untrace() - } - errInvalidSource = func(URL string) *probe.Error { return probe.NewError(errors.New("Invalid source ‘" + URL + "’.")).Untrace() } diff --git a/url.go b/url.go index e9a78b54..4557c367 100644 --- a/url.go +++ b/url.go @@ -17,6 +17,7 @@ package main import ( + "os" "path/filepath" "strings" @@ -38,36 +39,9 @@ func urlJoinPath(url1, url2 string) string { return client.JoinURLs(u1, u2).String() } -// args2URLs extracts source and target URLs from command-line args. -func args2URLs(args []string) ([]string, *probe.Error) { - // convert arguments to URLs: expand alias, fix format... - URLs := []string{} - for _, arg := range args { - aliasedURL, err := getAliasURL(arg) - if err != nil { - return nil, err.Trace(arg) - } - URLs = append(URLs, aliasedURL) - } - return URLs, nil -} - -// url2Client convenience wrapper for getNewClient. -func url2Client(urlStr string) (client.Client, *probe.Error) { - urlConfig, err := getHostConfig(urlStr) - if err != nil { - return nil, err.Trace(urlStr) - } - client, err := getNewClient(urlStr, urlConfig) - if err != nil { - return nil, err.Trace(urlStr) - } - return client, nil -} - // url2Stat returns stat info for URL. func url2Stat(urlStr string) (client client.Client, content *client.Content, err *probe.Error) { - client, err = url2Client(urlStr) + client, err = newClient(urlStr) if err != nil { return nil, nil, err.Trace(urlStr) } @@ -78,9 +52,25 @@ func url2Stat(urlStr string) (client client.Client, content *client.Content, err return client, content, nil } +// url2Alias separates alias and path from the URL. Aliased URL is of the form [/]alias/path/to/blah. If +func url2Alias(aliasedURL string) (alias, path string) { + urlStr := aliasedURL + + // Remove "/" prefix before alias, if any. + urlStr = strings.TrimPrefix(urlStr, string(os.PathSeparator)) + + // Remove everything after alias (i.e. after "/"). + urlParts := strings.SplitN(urlStr, string(os.PathSeparator), 2) + if len(urlParts) == 2 { + // Convert windows style path separator to Unix style. + return urlParts[0], urlParts[1] + } + return urlParts[0], "" +} + // isURLPrefixExists - check if object key prefix exists. func isURLPrefixExists(urlPrefix string, incomplete bool) bool { - clnt, err := url2Client(urlPrefix) + clnt, err := newClient(urlPrefix) if err != nil { return false } diff --git a/verify-runtime.go b/verify-runtime.go index 4c9be7f7..37534037 100644 --- a/verify-runtime.go +++ b/verify-runtime.go @@ -108,7 +108,7 @@ func verifyMCRuntime() { err := saveMcConfig(newMcConfig()) fatalIf(err.Trace(), "Unable to save new mc config.") - console.Infoln("Configuration written to [" + mustGetMcConfigPath() + "]. Please update your access credentials.") + console.Infoln("Configuration written to ‘" + mustGetMcConfigPath() + "’. Please update your access credentials.") } // Check if mc session folder exists.