From b855e37945dfa53e5482c026d2ff98632276a404 Mon Sep 17 00:00:00 2001 From: "Anand Babu (AB) Periasamy" Date: Thu, 19 Mar 2015 18:01:09 -0700 Subject: [PATCH] new config file format and some restructuring --- aliases.go | 6 +- cmd-config.go | 133 +++++++++++++++++++++++++++----------------- cmd-cp.go | 3 +- cmd-ls.go | 6 +- cmd-mb.go | 3 +- cmd-options.go | 14 ++--- cmd-recursive-cp.go | 3 + common.go | 13 +++-- donut-options.go | 40 ++++++------- main.go | 2 +- pkg/s3/auth.go | 4 +- pkg/s3/auth_test.go | 2 +- 12 files changed, 137 insertions(+), 92 deletions(-) diff --git a/aliases.go b/aliases.go index 09169950..287d21e9 100644 --- a/aliases.go +++ b/aliases.go @@ -55,10 +55,10 @@ func aliasExpand(aliasedURL string) (newURL string, err error) { return "", err } - for _, alias := range config.Aliases { - if strings.HasPrefix(aliasedURL, alias.Name) { + for aliasName, expandedURL := range config.Aliases { + if strings.HasPrefix(aliasedURL, aliasName) { // Match found. Expand it. - return strings.Replace(aliasedURL, alias.Name+":", alias.URL, 1), nil + return strings.Replace(aliasedURL, aliasName+":", expandedURL, 1), nil } } diff --git a/cmd-config.go b/cmd-config.go index 834f59c1..9f315ddf 100644 --- a/cmd-config.go +++ b/cmd-config.go @@ -4,6 +4,7 @@ import ( "bytes" "errors" "fmt" + "log" "os" "path" "strings" @@ -22,14 +23,15 @@ const ( mcConfigFilename = "config.json" ) -type s3Config struct { +type hostConfig struct { Auth s3.Auth } type mcConfig struct { - Version uint - S3 s3Config - Aliases []mcAlias + Version uint + DefaultHost string + Hosts map[string]hostConfig + Aliases map[string]string } const ( @@ -75,22 +77,28 @@ func checkMcConfig(config *mcConfig) (err error) { return fmt.Errorf("Unsupported version [%d]. Current operating version is [%d]", config.Version, currentConfigVersion) - case config.S3.Auth.AccessKey == "": - return fmt.Errorf("Missing S3.Auth.AccessKey") - - case config.S3.Auth.SecretAccessKey == "": - return fmt.Errorf("Missing S3.Auth.SecretAccessKey") - + case len(config.Hosts) > 1: + for host, hostCfg := range config.Hosts { + if host == "" { + return fmt.Errorf("Empty host URL") + } + if hostCfg.Auth.AccessKeyID == "" { + return fmt.Errorf("AccessKeyID is empty for Host [%s]", host) + } + if hostCfg.Auth.SecretAccessKey == "" { + return fmt.Errorf("SecretAccessKey is empty for Host [%s]", host) + } + } case len(config.Aliases) > 0: - for _, alias := range config.Aliases { - _, err := url.Parse(alias.URL) + for aliasName, aliasURL := range config.Aliases { + _, err := url.Parse(aliasURL) if err != nil { return fmt.Errorf("Unable to parse URL [%s] for alias [%s]", - alias.URL, alias.Name) + aliasURL, aliasName) } - if !isValidAliasName(alias.Name) { + if !isValidAliasName(aliasName) { return fmt.Errorf("Not a valid alias name [%s]. Valid examples are: Area51, Grand-Nagus..", - alias.Name) + aliasName) } } } @@ -139,8 +147,16 @@ func getBashCompletion() { } func parseConfigInput(c *cli.Context) (config *mcConfig, err error) { - accessKey := c.String("accesskey") - secretKey := c.String("secretkey") + accessKeyID := c.String("accesskeyid") + secretAccesskey := c.String("secretkey") + + if accessKeyID == "" { + accessKeyID = "YOUR-ACCESS-KEY-ID-HERE" + } + + if secretAccesskey == "" { + secretAccesskey = "YOUR-SECRET-ACCESS-KEY-HERE" + } alias := strings.Fields(c.String("alias")) if len(alias) == 0 { @@ -158,68 +174,85 @@ func parseConfigInput(c *cli.Context) (config *mcConfig, err error) { if !strings.HasPrefix(url, "http") { return nil, errors.New("invalid url type only supports http{s}") } + config = &mcConfig{ - Version: currentConfigVersion, - S3: s3Config{ - Auth: s3.Auth{ - AccessKey: accessKey, - SecretAccessKey: secretKey, - }, + Version: currentConfigVersion, + DefaultHost: "https://s3.amazonaws.com", + Hosts: map[string]hostConfig{ + "https://s3.amazonaws.com": { + Auth: s3.Auth{ + AccessKeyID: accessKeyID, + SecretAccessKey: secretAccesskey, + }}, }, - Aliases: []mcAlias{ - { - Name: "s3", - URL: "https://s3.amazonaws.com/", - }, - { - Name: "localhost", - URL: "http://localhost:9000/", - }, - { - Name: aliasName, - URL: url, - }, + Aliases: map[string]string{ + "s3": "https://s3.amazonaws.com/", + "localhost": "http://localhost:9000/", + aliasName: url, }, } + //config.Aliases[aliasName] = url return config, nil } -func getConfig(c *cli.Context) { +// getHostConfig retrieves host specific configuration such as access keys, certs. +func getHostConfig(host string) (hostCfg *hostConfig, err error) { + _, err = url.Parse(host) + if err != nil { + return nil, err + + } + config, err := getMcConfig() + hostCfg.Auth.AccessKeyID = config.Hosts[host].Auth.AccessKeyID + hostCfg.Auth.SecretAccessKey = config.Hosts[host].Auth.SecretAccessKey + return hostCfg, nil +} + +// saveConfig writes configuration data in json format to config file. +func saveConfig(c *cli.Context) error { configData, err := parseConfigInput(c) if err != nil { - fatal(err.Error()) + return err } jsonConfig, err := json.MarshalIndent(configData, "", "\t") if err != nil { - fatal(err.Error()) + return err } err = os.MkdirAll(getMcConfigDir(), 0755) - if err != nil { - fatal(err.Error()) + if !os.IsExist(err) && err != nil { + return err } configFile, err := os.OpenFile(getMcConfigFilename(), os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600) - defer configFile.Close() if err != nil { - fatal(err.Error()) + return err } + defer configFile.Close() _, err = configFile.Write(jsonConfig) if err != nil { - fatal(err.Error()) + return err } - - msg := "Configuration written to " + getMcConfigFilename() + "\n" - info(msg) + return nil } -func doConfig(c *cli.Context) { +// doConfigCmd is the handler for "mc config" sub-command. +func doConfigCmd(c *cli.Context) { switch true { case c.Bool("completion") == true: getBashCompletion() - case c.Bool("completion") == false: - getConfig(c) + default: + err := saveConfig(c) + if os.IsExist(err) { + log.Fatalf("mc: Please rename your current configuration file [%s]\n", getMcConfigFilename()) + } + + if err != nil { + log.Fatalf("mc: Unable to generate config file [%s]. \nError: %v\n", getMcConfigFilename(), err) + } + info("Configuration written to " + getMcConfigFilename() + "\n") + } } diff --git a/cmd-cp.go b/cmd-cp.go index f1902a6a..d345e9a1 100644 --- a/cmd-cp.go +++ b/cmd-cp.go @@ -247,7 +247,8 @@ func fourthMode(s3c *s3.Client, args *cmdArgs) error { return doRecursiveCp(s3c, args) } -func doCopy(c *cli.Context) { +// doCopyCmd copies objects into and from a bucket or between buckets +func doCopyCmd(c *cli.Context) { var args *cmdArgs var err error var s3c *s3.Client diff --git a/cmd-ls.go b/cmd-ls.go index 46e5c24d..bee5ae51 100644 --- a/cmd-ls.go +++ b/cmd-ls.go @@ -30,6 +30,7 @@ const ( printDate = "2006-01-02 15:04:05 MST" ) +// printBuckets lists buckets and its meta-dat func printBuckets(v []*s3.Bucket) { for _, b := range v { msg := fmt.Sprintf("%23s %13s %s", b.CreationDate.Local().Format(printDate), "", b.Name) @@ -37,6 +38,7 @@ func printBuckets(v []*s3.Bucket) { } } +// printObjects prints a meta-data of a list of objects func printObjects(v []*s3.Item) { if len(v) > 0 { // Items are already sorted @@ -46,12 +48,14 @@ func printObjects(v []*s3.Item) { } } +// printObject prints object meta-data func printObject(date time.Time, v int64, key string) { msg := fmt.Sprintf("%23s %13s %s", date.Local().Format(printDate), pb.FormatBytes(v), key) info(msg) } -func doList(c *cli.Context) { +// doListCmd lists objects inside a bucket +func doListCmd(c *cli.Context) { var items []*s3.Item args, err := parseArgs(c) diff --git a/cmd-mb.go b/cmd-mb.go index 332d8e20..3fdb82dd 100644 --- a/cmd-mb.go +++ b/cmd-mb.go @@ -21,7 +21,8 @@ import ( "github.com/minio-io/mc/pkg/s3" ) -func doMakebucket(c *cli.Context) { +// doMakeBucketCmd creates a new bucket +func doMakeBucketCmd(c *cli.Context) { args, err := parseArgs(c) if err != nil { fatal(err.Error()) diff --git a/cmd-options.go b/cmd-options.go index 554d7df0..65a10289 100644 --- a/cmd-options.go +++ b/cmd-options.go @@ -24,7 +24,7 @@ var cpCmd = cli.Command{ Name: "cp", Usage: "copy objects", Description: `Copies a local file or dir or object or bucket to another location locally or in S3.`, - Action: doCopy, + Action: doCopyCmd, Flags: []cli.Flag{ cli.BoolFlag{ Name: "recursive, r", @@ -37,14 +37,14 @@ var lsCmd = cli.Command{ Name: "ls", Usage: "get list of objects", Description: `List Objects and common prefixes under a prefix or all Buckets`, - Action: doList, + Action: doListCmd, } var mbCmd = cli.Command{ Name: "mb", Usage: "makes a bucket", Description: "Creates an S3 bucket", - Action: doMakebucket, + Action: doMakeBucketCmd, } var configCmd = cli.Command{ @@ -55,17 +55,17 @@ var configCmd = cli.Command{ automatically created for you. Note that the configure command only writes values to the config file. It does not use any configuration values from the environment variables.`, - Action: doConfig, + Action: doConfigCmd, Flags: []cli.Flag{ cli.StringFlag{ - Name: "accesskey, k", + Name: "accesskeyid, a", Value: "", - Usage: "AWS access key id", + Usage: "AWS access key ID", }, cli.StringFlag{ Name: "secretkey, s", Value: "", - Usage: "AWS secret key id", + Usage: "AWS secret access key", }, cli.StringFlag{ Name: "alias", diff --git a/cmd-recursive-cp.go b/cmd-recursive-cp.go index e07a2780..990fcbe7 100644 --- a/cmd-recursive-cp.go +++ b/cmd-recursive-cp.go @@ -64,6 +64,7 @@ func (w *walk) putWalk(p string, i os.FileInfo, err error) error { return nil } +// isValidBucketName checks for valid bucket naming convention. Remember, bucket name is also used a DNS hostname. func isValidBucketName(p string) error { if path.IsAbs(p) { return errors.New("directory bucketname cannot be absolute") @@ -77,6 +78,7 @@ func isValidBucketName(p string) error { return nil } +// isBucketExists checks if a bucket exists func isBucketExists(name string, v []*s3.Bucket) bool { for _, b := range v { if name == b.Name { @@ -86,6 +88,7 @@ func isBucketExists(name string, v []*s3.Bucket) bool { return false } +// doRecursiveCP recursively copies objects from source to destination func doRecursiveCp(s3c *s3.Client, args *cmdArgs) error { var err error var st os.FileInfo diff --git a/common.go b/common.go index 02b3ae70..f59cec8b 100644 --- a/common.go +++ b/common.go @@ -52,17 +52,20 @@ func getNewClient(c *cli.Context) (client *s3.Client, err error) { return nil, err } - switch c.GlobalBool("debug") { - case true: + var auth s3.Auth + auth.AccessKeyID = config.Hosts[config.DefaultHost].Auth.AccessKeyID + auth.SecretAccessKey = config.Hosts[config.DefaultHost].Auth.SecretAccessKey + + if c.GlobalBool("debug") { trace := s3.Trace{ BodyTraceFlag: false, RequestTransportFlag: true, Writer: nil, } traceTransport := s3.GetNewTraceTransport(trace, http.DefaultTransport) - client = s3.GetNewClient(&config.S3.Auth, traceTransport) - case false: - client = s3.GetNewClient(&config.S3.Auth, http.DefaultTransport) + client = s3.GetNewClient(&auth, traceTransport) + } else { + client = s3.GetNewClient(&auth, http.DefaultTransport) } return client, nil diff --git a/donut-options.go b/donut-options.go index 6de2615c..91be0ccd 100644 --- a/donut-options.go +++ b/donut-options.go @@ -4,60 +4,60 @@ import ( "github.com/codegangsta/cli" ) -var format = cli.Command{ +var formatCmd = cli.Command{ Name: "format", Usage: "format disk", Description: "format a given disk", - Action: doFormat, + Action: doFormatCmd, } -var heal = cli.Command{ +var healCmd = cli.Command{ Name: "heal", Usage: "heal donut", Description: "", - Action: doHeal, + Action: doHealCmd, } -var attach = cli.Command{ +var attachCmd = cli.Command{ Name: "attach", Usage: "attach disk", Description: "", - Action: doAttach, + Action: doAttachCmd, } -var detach = cli.Command{ +var detachCmd = cli.Command{ Name: "detach", Usage: "detach disk", Description: "", - Action: doDetach, + Action: doDetachCmd, } -var rebalance = cli.Command{ +var rebalanceCmd = cli.Command{ Name: "rebalance", Usage: "rebalance ", Description: "", - Action: doRebalance, + Action: doRebalanceCmd, } var donutOptions = []cli.Command{ - format, - heal, - attach, - detach, - rebalance, + formatCmd, + healCmd, + attachCmd, + detachCmd, + rebalanceCmd, } -func doFormat(c *cli.Context) { +func doFormatCmd(c *cli.Context) { } -func doHeal(c *cli.Context) { +func doHealCmd(c *cli.Context) { } -func doAttach(c *cli.Context) { +func doAttachCmd(c *cli.Context) { } -func doDetach(c *cli.Context) { +func doDetachCmd(c *cli.Context) { } -func doRebalance(c *cli.Context) { +func doRebalanceCmd(c *cli.Context) { } diff --git a/main.go b/main.go index f5404a8d..7d914cdc 100644 --- a/main.go +++ b/main.go @@ -31,7 +31,7 @@ func init() { log.Fatalf("mc: Unable to obtain user's home directory. \nError: %s\n", err) } - // Ensures config file is sane and cached to __config private variable. + // Ensures config file is sane and cached to _config private variable. config, err := getMcConfig() if os.IsNotExist(err) { return diff --git a/pkg/s3/auth.go b/pkg/s3/auth.go index 9caf098c..82d270b7 100644 --- a/pkg/s3/auth.go +++ b/pkg/s3/auth.go @@ -57,7 +57,7 @@ import ( // Auth - see http://docs.amazonwebservices.com/AmazonS3/latest/dev/index.html?RESTAuthentication.html type Auth struct { - AccessKey string + AccessKeyID string SecretAccessKey string // Used for SSL transport layer @@ -128,7 +128,7 @@ func (a *Auth) signRequest(req *http.Request, host string) { io.WriteString(hm, ss) authHeader := new(bytes.Buffer) - fmt.Fprintf(authHeader, "AWS %s:", a.AccessKey) + fmt.Fprintf(authHeader, "AWS %s:", a.AccessKeyID) encoder := base64.NewEncoder(base64.StdEncoding, authHeader) encoder.Write(hm.Sum(nil)) encoder.Close() diff --git a/pkg/s3/auth_test.go b/pkg/s3/auth_test.go index 92342f64..7ead9d66 100644 --- a/pkg/s3/auth_test.go +++ b/pkg/s3/auth_test.go @@ -136,7 +136,7 @@ func TestBucketFromHostname(t *testing.T) { func TestsignRequest(t *testing.T) { r := req("GET /foo HTTP/1.1\n\n") - auth := &Auth{AccessKey: "key", SecretAccessKey: "secretkey"} + auth := &Auth{AccessKeyID: "key", SecretAccessKey: "secretkey"} auth.signRequest(r, "localhost:9000") if r.Header.Get("Date") == "" { t.Error("expected a Date set")