From 095ae11cafc52b6722bf58d5a4e190a2028b25e0 Mon Sep 17 00:00:00 2001 From: Harshavardhana Date: Tue, 21 Apr 2015 13:43:51 -0700 Subject: [PATCH] Migrate to quick Config, qdb takes the high road --- cmd-common.go | 25 +-- cmd-config.go | 110 ++++++---- cmd-cp-recursive.go | 15 +- cmd-cp.go | 8 +- cmd-ls.go | 6 +- cmd-mb.go | 6 +- cmd-options.go | 5 +- cmd_test.go | 164 +++++++------- main.go | 3 - mock_clientManager_test.go | 6 +- pkg/qdb/qdb.go | 437 ------------------------------------- pkg/qdb/qdb_test.go | 205 ----------------- pkg/quick/quick.go | 6 +- pkg/quick/quick_test.go | 24 +- 14 files changed, 194 insertions(+), 826 deletions(-) delete mode 100644 pkg/qdb/qdb.go delete mode 100644 pkg/qdb/qdb_test.go diff --git a/cmd-common.go b/cmd-common.go index e6c8daf8..143c36bc 100644 --- a/cmd-common.go +++ b/cmd-common.go @@ -67,15 +67,15 @@ func startBar(size int64) *pb.ProgressBar { // clientManager interface for mock tests type clientManager interface { - getSourceReader(sourceURL string, sourceConfig map[string]string) (reader io.ReadCloser, length int64, md5hex string, err error) - getTargetWriter(targetURL string, targetConfig map[string]string, md5Hex string, length int64) (io.WriteCloser, error) - getNewClient(urlStr string, config map[string]string, debug bool) (clnt client.Client, err error) + getSourceReader(sourceURL string, sourceConfig *hostConfig) (reader io.ReadCloser, length int64, md5hex string, err error) + getTargetWriter(targetURL string, targetConfig *hostConfig, md5Hex string, length int64) (io.WriteCloser, error) + getNewClient(urlStr string, config *hostConfig, debug bool) (clnt client.Client, err error) } type mcClientManager struct{} // getSourceReader - -func (manager mcClientManager) getSourceReader(sourceURL string, sourceConfig map[string]string) ( +func (manager mcClientManager) getSourceReader(sourceURL string, sourceConfig *hostConfig) ( reader io.ReadCloser, length int64, md5hex string, err error) { sourceClnt, err := manager.getNewClient(sourceURL, sourceConfig, globalDebugFlag) @@ -93,7 +93,7 @@ func (manager mcClientManager) getSourceReader(sourceURL string, sourceConfig ma } // getTargetWriter - -func (manager mcClientManager) getTargetWriter(targetURL string, targetConfig map[string]string, md5Hex string, length int64) ( +func (manager mcClientManager) getTargetWriter(targetURL string, targetConfig *hostConfig, md5Hex string, length int64) ( io.WriteCloser, error) { targetClnt, err := manager.getNewClient(targetURL, targetConfig, globalDebugFlag) if err != nil { @@ -118,16 +118,15 @@ func (manager mcClientManager) getTargetWriter(targetURL string, targetConfig ma } // getNewClient gives a new client interface -func (manager mcClientManager) getNewClient(urlStr string, auth map[string]string, debug bool) (clnt client.Client, err error) { +func (manager mcClientManager) getNewClient(urlStr string, auth *hostConfig, debug bool) (clnt client.Client, err error) { switch client.GetType(urlStr) { case client.Object: // Minio and S3 compatible object storage + if auth == nil { + return nil, iodine.New(errInvalidArgument{}, nil) + } s3Config := new(s3.Config) - if _, ok := auth["Auth.AccessKeyID"]; ok { - s3Config.AccessKeyID = auth["Auth.AccessKeyID"] - } - if _, ok := auth["Auth.SecretAccessKey"]; ok { - s3Config.SecretAccessKey = auth["Auth.SecretAccessKey"] - } + s3Config.AccessKeyID = auth.AccessKeyID + s3Config.SecretAccessKey = auth.SecretAccessKey s3Config.UserAgent = mcUserAgent s3Config.HostURL = urlStr s3Config.Debug = debug @@ -149,7 +148,7 @@ func (manager mcClientManager) getNewClient(urlStr string, auth map[string]strin } // getTargetWriters - -func getTargetWriters(manager clientManager, targetURLConfigMap map[string]map[string]string, md5Hex string, length int64) ( +func getTargetWriters(manager clientManager, targetURLConfigMap map[string]*hostConfig, md5Hex string, length int64) ( []io.WriteCloser, error) { var targetWriters []io.WriteCloser for targetURL, targetConfig := range targetURLConfigMap { diff --git a/cmd-config.go b/cmd-config.go index 18342bbf..36de24df 100644 --- a/cmd-config.go +++ b/cmd-config.go @@ -29,7 +29,7 @@ import ( "github.com/minio-io/cli" "github.com/minio-io/mc/pkg/client" "github.com/minio-io/mc/pkg/console" - "github.com/minio-io/mc/pkg/qdb" + "github.com/minio-io/mc/pkg/quick" "github.com/minio-io/minio/pkg/iodine" "github.com/minio-io/minio/pkg/utils/log" ) @@ -40,8 +40,19 @@ const ( mcConfigFile = "config.json" ) +type hostConfig struct { + AccessKeyID string + SecretAccessKey string +} + +type configV1 struct { + Version string + Aliases map[string]string + Hosts map[string]*hostConfig +} + var ( - mcCurrentConfigVersion = qdb.Version{Major: 1, Minor: 0, Patch: 0} + mcCurrentConfigVersion = "1.0.0" ) const ( @@ -91,7 +102,7 @@ func mustGetMcConfigPath() string { } // getMcConfig returns the config -func getMcConfig() (config qdb.Store, err error) { +func getMcConfig() (config *configV1, err error) { if !isMcConfigExist() { return nil, iodine.New(errInvalidArgument{}, nil) } @@ -99,11 +110,12 @@ func getMcConfig() (config qdb.Store, err error) { if err != nil { return nil, iodine.New(err, nil) } - if configStore := qdb.NewStore(mcCurrentConfigVersion); configStore != nil { - if err := configStore.Load(configFile); err != nil { + conf := newConfigV1() + if config := quick.New(conf); config != nil { + if err := config.Load(configFile); err != nil { return nil, iodine.New(err, nil) } - return configStore, nil + return config.Data().(*configV1), nil } return nil, iodine.New(errInvalidArgument{}, nil) } @@ -122,7 +134,7 @@ func isMcConfigExist() bool { } // writeConfig -func writeConfig(config qdb.Store) error { +func writeConfig(config quick.Config) error { err := createMcConfigDir() if err != nil { return iodine.New(err, nil) @@ -150,43 +162,51 @@ func saveConfig(ctx *cli.Context) error { } return nil default: - configStore, err := parseConfigInput(ctx) + config, err := parseConfigInput(ctx) if err != nil { return iodine.New(err, nil) } - return writeConfig(configStore) + return writeConfig(config) } } -func newConfig() (config qdb.Store) { - configStore := qdb.NewStore(mcCurrentConfigVersion) - s3Auth := make(map[string]string) - localAuth := make(map[string]string) - - hosts := make(map[string]map[string]string) - s3Auth["Auth.AccessKeyID"] = globalAccessKeyID - s3Auth["Auth.SecretAccessKey"] = globalSecretAccessKey - hosts["http*://s3*.amazonaws.com"] = s3Auth +func newConfigV1() *configV1 { + conf := new(configV1) + conf.Version = mcCurrentConfigVersion + // make sure to allocate map's otherwise Golang + // exists silently without providing any errors + conf.Hosts = make(map[string]*hostConfig) + conf.Aliases = make(map[string]string) + return conf +} +func newConfig() (config quick.Config) { + conf := newConfigV1() + s3HostConf := new(hostConfig) + s3HostConf.AccessKeyID = globalAccessKeyID + s3HostConf.SecretAccessKey = globalSecretAccessKey // local minio server can have this empty until webcli is ready // which would make it easier to generate accesskeys and manage - localAuth["Auth.AccessKeyID"] = "" - localAuth["Auth.SecretAccessKey"] = "" - hosts["http*://localhost:*"] = localAuth + localhostConf := new(hostConfig) + localhostConf.AccessKeyID = "" + localhostConf.SecretAccessKey = "" - configStore.SetMapMapString("Hosts", hosts) + conf.Hosts["http://localhost:9000"] = localhostConf + conf.Hosts["http*://s3*.amazonaws.com"] = s3HostConf aliases := make(map[string]string) aliases["s3"] = "https://s3.amazonaws.com" aliases["localhost"] = "http://localhost:9000" + conf.Aliases = aliases + config = quick.New(conf) - configStore.SetMapString("Aliases", aliases) - return configStore + return config } -func parseConfigInput(ctx *cli.Context) (config qdb.Store, err error) { - configStore := qdb.NewStore(mcCurrentConfigVersion) - configStore.Load(mcConfigFile) +func parseConfigInput(ctx *cli.Context) (config quick.Config, err error) { + conf := newConfigV1() + config = quick.New(&conf) + config.Load(mcConfigFile) alias := strings.Fields(ctx.String("alias")) switch true { @@ -202,13 +222,14 @@ func parseConfigInput(ctx *cli.Context) (config qdb.Store, err error) { if !isValidAliasName(aliasName) { return nil, iodine.New(errInvalidAliasName{name: aliasName}, nil) } - aliases := configStore.GetMapString("Aliases") - if _, ok := aliases[aliasName]; ok { + // convert interface{} back to its original struct + newConf := config.Data().(configV1) + if _, ok := newConf.Aliases[aliasName]; ok { return nil, iodine.New(errAliasExists{name: aliasName}, nil) } - aliases[aliasName] = url - configStore.SetMapString("Aliases", aliases) - return configStore, nil + newConf.Aliases[aliasName] = url + newConfig := quick.New(newConf) + return newConfig, nil default: return nil, iodine.New(errInvalidArgument{}, nil) } @@ -219,8 +240,8 @@ func getHostURL(u *url.URL) string { return u.Scheme + "://" + u.Host } -func getHostConfigs(requestURLs []string) (hostConfigs map[string]map[string]string, err error) { - hostConfigs = make(map[string]map[string]string) +func getHostConfigs(requestURLs []string) (hostConfigs map[string]*hostConfig, err error) { + hostConfigs = make(map[string]*hostConfig) for _, requestURL := range requestURLs { hostConfigs[requestURL], err = getHostConfig(requestURL) if err != nil { @@ -231,7 +252,7 @@ func getHostConfigs(requestURLs []string) (hostConfigs map[string]map[string]str } // getHostConfig retrieves host specific configuration such as access keys, certs. -func getHostConfig(requestURL string) (map[string]string, error) { +func getHostConfig(requestURL string) (*hostConfig, error) { config, err := getMcConfig() if err != nil { return nil, iodine.New(err, nil) @@ -242,30 +263,31 @@ func getHostConfig(requestURL string) (map[string]string, error) { } // skip filesystem if client.GetType(requestURL) == client.Filesystem { - hostConfig := make(map[string]string) - hostConfig["Auth.AccessKeyID"] = "" - hostConfig["Auth.SecretAccessKey"] = "" - return hostConfig, nil + hostCfg := &hostConfig{ + AccessKeyID: "", + SecretAccessKey: "", + } + return hostCfg, nil } - for globURL, hostConfig := range config.GetMapMapString("Hosts") { + for globURL, hostCfg := range config.Hosts { match, err := filepath.Match(globURL, getHostURL(u)) if err != nil { return nil, iodine.New(errInvalidGlobURL{glob: globURL, request: requestURL}, nil) } if match { - if hostConfig == nil { + if hostCfg == nil { return nil, iodine.New(errInvalidAuth{}, nil) } // verify Auth key validity for all hosts other than localhost if !strings.Contains(getHostURL(u), "localhost") { - if !client.IsValidAccessKey(hostConfig["Auth.AccessKeyID"]) { + if !client.IsValidAccessKey(hostCfg.AccessKeyID) { return nil, iodine.New(errInvalidAuthKeys{}, nil) } - if !client.IsValidSecretKey(hostConfig["Auth.SecretAccessKey"]) { + if !client.IsValidSecretKey(hostCfg.SecretAccessKey) { return nil, iodine.New(errInvalidAuthKeys{}, nil) } } - return hostConfig, nil + return hostCfg, nil } } return nil, iodine.New(errNoMatchingHost{}, nil) diff --git a/cmd-cp-recursive.go b/cmd-cp-recursive.go index 2989e4be..c4d12de5 100644 --- a/cmd-cp-recursive.go +++ b/cmd-cp-recursive.go @@ -42,9 +42,7 @@ func getSourceURL(sourceURL, objectName string) string { } // getSourceObjectURLMap - get list of all source object and its URLs in a map -func getSourceObjectURLMap(manager clientManager, sourceURL string, sourceConfig map[string]string) ( - sourceObjectURLMap map[string]string, err error) { - +func getSourceObjectURLMap(manager clientManager, sourceURL string, sourceConfig *hostConfig) (sourceObjectURLMap map[string]string, err error) { sourceClnt, err := manager.getNewClient(sourceURL, sourceConfig, globalDebugFlag) if err != nil { return nil, iodine.New(err, nil) @@ -61,8 +59,7 @@ func getSourceObjectURLMap(manager clientManager, sourceURL string, sourceConfig } // getRecursiveTargetWriter - recursively get target writers to initiate copying data -func getRecursiveTargetWriter(manager clientManager, targetURL string, targetConfig map[string]string, md5Hex string, length int64) ( - io.WriteCloser, error) { +func getRecursiveTargetWriter(manager clientManager, targetURL string, targetConfig *hostConfig, md5Hex string, length int64) (io.WriteCloser, error) { targetClnt, err := manager.getNewClient(targetURL, targetConfig, globalDebugFlag) if err != nil { @@ -88,8 +85,7 @@ func getRecursiveTargetWriter(manager clientManager, targetURL string, targetCon } // getRecursiveTargetWriters - convenient wrapper around getRecursiveTarget -func getRecursiveTargetWriters(manager clientManager, targetURLConfigMap map[string]map[string]string, md5Hex string, length int64) ( - []io.WriteCloser, error) { +func getRecursiveTargetWriters(manager clientManager, targetURLConfigMap map[string]*hostConfig, md5Hex string, length int64) ([]io.WriteCloser, error) { var targetWriters []io.WriteCloser for targetURL, targetConfig := range targetURLConfigMap { @@ -108,7 +104,8 @@ func getRecursiveTargetWriters(manager clientManager, targetURLConfigMap map[str } // doCopyCmdRecursive - copy bucket to bucket -func doCopyCmdRecursive(manager clientManager, sourceURLConfigMap map[string]map[string]string, targetURLConfigMap map[string]map[string]string) (string, error) { +func doCopyCmdRecursive(manager clientManager, sourceURLConfigMap map[string]*hostConfig, targetURLConfigMap map[string]*hostConfig) (string, error) { + for sourceURL, sourceConfig := range sourceURLConfigMap { sourceObjectURLMap, err := getSourceObjectURLMap(manager, sourceURL, sourceConfig) if err != nil { @@ -129,7 +126,7 @@ func doCopyCmdRecursive(manager clientManager, sourceURLConfigMap map[string]map msg := fmt.Sprintf("Reading from source URL: [%s] failed", sourceURL) return msg, err } - newTargetURLConfigMap := make(map[string]map[string]string) + newTargetURLConfigMap := make(map[string]*hostConfig) // Construct full target URL path based on source object name for targetURL, targetConfig := range targetURLConfigMap { targetURL := strings.TrimSuffix(targetURL, pathSeparator) + pathSeparator + sourceObjectName diff --git a/cmd-cp.go b/cmd-cp.go index 373993f2..89a43121 100644 --- a/cmd-cp.go +++ b/cmd-cp.go @@ -40,7 +40,7 @@ func runCopyCmd(ctx *cli.Context) { } // Convert arguments to URLs: expand alias, fix format... - urls, err := getURLs(ctx.Args(), config.GetMapString("Aliases")) + urls, err := getURLs(ctx.Args(), config.Aliases) if err != nil { switch e := iodine.ToError(err).(type) { case errUnsupportedScheme: @@ -56,7 +56,7 @@ func runCopyCmd(ctx *cli.Context) { sourceURL := urls[0] // First arg is source targetURLs := urls[1:] // 1 or more targets - sourceURLConfigMap := make(map[string]map[string]string) + sourceURLConfigMap := make(map[string]*hostConfig) sourceConfig, err := getHostConfig(sourceURL) if err != nil { log.Debug.Println(iodine.New(err, nil)) @@ -95,9 +95,7 @@ func runCopyCmd(ctx *cli.Context) { } // doCopyCmd copies objects into and from a bucket or between buckets -func doCopyCmd(manager clientManager, sourceURLConfigMap map[string]map[string]string, targetURLConfigMap map[string]map[string]string) ( - string, error) { - +func doCopyCmd(manager clientManager, sourceURLConfigMap map[string]*hostConfig, targetURLConfigMap map[string]*hostConfig) (string, error) { for sourceURL, sourceConfig := range sourceURLConfigMap { reader, length, hexMd5, err := manager.getSourceReader(sourceURL, sourceConfig) if err != nil { diff --git a/cmd-ls.go b/cmd-ls.go index 121000fa..407c1c66 100644 --- a/cmd-ls.go +++ b/cmd-ls.go @@ -87,9 +87,9 @@ func runListCmd(ctx *cli.Context) { log.Debug.Println(iodine.New(err, nil)) console.Fatalf("mc: reading config file failed with following reason: [%s]\n", iodine.ToError(err)) } - targetURLConfigMap := make(map[string]map[string]string) + targetURLConfigMap := make(map[string]*hostConfig) for _, arg := range ctx.Args() { - targetURL, err := getURL(arg, config.GetMapString("Aliases")) + targetURL, err := getURL(arg, config.Aliases) if err != nil { switch iodine.ToError(err).(type) { case errUnsupportedScheme: @@ -118,7 +118,7 @@ func runListCmd(ctx *cli.Context) { } } -func doListCmd(manager clientManager, targetURLConfigMap map[string]map[string]string, debug bool) (string, error) { +func doListCmd(manager clientManager, targetURLConfigMap map[string]*hostConfig, debug bool) (string, error) { for targetURL, targetConfig := range targetURLConfigMap { clnt, err := manager.getNewClient(targetURL, targetConfig, globalDebugFlag) if err != nil { diff --git a/cmd-mb.go b/cmd-mb.go index 2911e400..f94fb4cc 100644 --- a/cmd-mb.go +++ b/cmd-mb.go @@ -38,9 +38,9 @@ func runMakeBucketCmd(ctx *cli.Context) { console.Fatalln("mc: Unable to read config") } - targetURLConfigMap := make(map[string]map[string]string) + targetURLConfigMap := make(map[string]*hostConfig) for _, arg := range ctx.Args() { - targetURL, err := getURL(arg, config.GetMapString("Aliases")) + targetURL, err := getURL(arg, config.Aliases) if err != nil { switch iodine.ToError(err).(type) { case errUnsupportedScheme: @@ -69,7 +69,7 @@ func runMakeBucketCmd(ctx *cli.Context) { } } -func doMakeBucketCmd(manager clientManager, targetURLConfigMap map[string]map[string]string, debug bool) (string, error) { +func doMakeBucketCmd(manager clientManager, targetURLConfigMap map[string]*hostConfig, debug bool) (string, error) { var err error var clnt client.Client diff --git a/cmd-options.go b/cmd-options.go index 03ef63b3..c36a95b5 100644 --- a/cmd-options.go +++ b/cmd-options.go @@ -169,10 +169,7 @@ EXAMPLES: 1. Generate mc config $ mc config generate - 2. Verify configuration - $ mc config check - - 3. Add alias URLs + 2. Add alias URLs $ mc config --alias "zek https://s3.amazonaws.com/" `, diff --git a/cmd_test.go b/cmd_test.go index bb2fafde..c5b556da 100644 --- a/cmd_test.go +++ b/cmd_test.go @@ -65,20 +65,20 @@ func (s *CmdTestSuite) TestCopyToSingleTarget(c *C) { wg.Done() }() - sourceURLConfigMap := make(map[string]map[string]string) - sourceConfigMap := make(map[string]string) - sourceConfigMap["Auth.AccessKeyID"] = "" - sourceConfigMap["Auth.SecretAccessKey"] = "" - sourceURLConfigMap[sourceURL] = sourceConfigMap + sourceURLConfigMap := make(map[string]*hostConfig) + sourceConfig := new(hostConfig) + sourceConfig.AccessKeyID = "" + sourceConfig.SecretAccessKey = "" + sourceURLConfigMap[sourceURL] = sourceConfig - targetURLConfigMap := make(map[string]map[string]string) - targetConfigMap := make(map[string]string) - targetConfigMap["Auth.AccessKeyID"] = "" - targetConfigMap["Auth.SecretAccessKey"] = "" - targetURLConfigMap[targetURL] = targetConfigMap + targetURLConfigMap := make(map[string]*hostConfig) + targetConfig := new(hostConfig) + targetConfig.AccessKeyID = "" + targetConfig.SecretAccessKey = "" + targetURLConfigMap[targetURL] = targetConfig - manager.On("getSourceReader", sourceURL, sourceConfigMap).Return(sourceReader, dataLength, hexMd5, nil).Once() - manager.On("getTargetWriter", targetURL, targetConfigMap, hexMd5, dataLength).Return(targetWriter, nil).Once() + manager.On("getSourceReader", sourceURL, sourceConfig).Return(sourceReader, dataLength, hexMd5, nil).Once() + manager.On("getTargetWriter", targetURL, targetConfig, hexMd5, dataLength).Return(targetWriter, nil).Once() msg, err := doCopyCmd(manager, sourceURLConfigMap, targetURLConfigMap) c.Assert(msg, Equals, "") c.Assert(err, IsNil) @@ -137,29 +137,29 @@ func (s *CmdTestSuite) TestCopyRecursive(c *C) { {Name: "hello2", Time: time.Now(), Size: dataLen2}, } - sourceURLConfigMap := make(map[string]map[string]string) - sourceConfigMap := make(map[string]string) - sourceConfigMap["Auth.AccessKeyID"] = "" - sourceConfigMap["Auth.SecretAccessKey"] = "" - sourceURLConfigMap[sourceURL] = sourceConfigMap + sourceURLConfigMap := make(map[string]*hostConfig) + sourceConfig := new(hostConfig) + sourceConfig.AccessKeyID = "" + sourceConfig.SecretAccessKey = "" + sourceURLConfigMap[sourceURL] = sourceConfig - targetURLConfigMap := make(map[string]map[string]string) - targetConfigMap := make(map[string]string) - targetConfigMap["Auth.AccessKeyID"] = "" - targetConfigMap["Auth.SecretAccessKey"] = "" - targetURLConfigMap[targetURL] = targetConfigMap + targetURLConfigMap := make(map[string]*hostConfig) + targetConfig := new(hostConfig) + targetConfig.AccessKeyID = "" + targetConfig.SecretAccessKey = "" + targetURLConfigMap[targetURL] = targetConfig - manager.On("getNewClient", sourceURL, sourceConfigMap, false).Return(cl1, nil).Once() + manager.On("getNewClient", sourceURL, sourceConfig, false).Return(cl1, nil).Once() cl1.On("List").Return(items, nil).Once() - manager.On("getNewClient", sourceURL+"hello1", sourceConfigMap, false).Return(cl2, nil).Once() + manager.On("getNewClient", sourceURL+"hello1", sourceConfig, false).Return(cl2, nil).Once() cl2.On("Get").Return(ioutil.NopCloser(bytes.NewBufferString(data1)), dataLen1, etag1, nil).Once() - manager.On("getNewClient", sourceURL+"hello2", sourceConfigMap, false).Return(cl3, nil).Once() + manager.On("getNewClient", sourceURL+"hello2", sourceConfig, false).Return(cl3, nil).Once() cl3.On("Get").Return(ioutil.NopCloser(bytes.NewBufferString(data2)), dataLen2, etag2, nil).Once() - manager.On("getNewClient", targetURL+"hello1", targetConfigMap, false).Return(cl4, nil).Once() + manager.On("getNewClient", targetURL+"hello1", targetConfig, false).Return(cl4, nil).Once() cl4.On("Stat").Return(nil).Once() cl4.On("Put", etag1, dataLen1).Return(writer1, nil).Once() - manager.On("getNewClient", targetURL+"hello2", targetConfigMap, false).Return(cl5, nil).Once() + manager.On("getNewClient", targetURL+"hello2", targetConfig, false).Return(cl5, nil).Once() cl5.On("Stat").Return(nil).Once() cl5.On("Put", etag2, dataLen2).Return(writer2, nil).Once() @@ -191,19 +191,19 @@ func (s *CmdTestSuite) TestCopyCmdFailures(c *C) { var nilReadCloser io.ReadCloser - sourceURLConfigMap := make(map[string]map[string]string) - sourceConfigMap := make(map[string]string) - sourceConfigMap["Auth.AccessKeyID"] = "" - sourceConfigMap["Auth.SecretAccessKey"] = "" - sourceURLConfigMap[sourceURL] = sourceConfigMap + sourceURLConfigMap := make(map[string]*hostConfig) + sourceConfig := new(hostConfig) + sourceConfig.AccessKeyID = "" + sourceConfig.SecretAccessKey = "" + sourceURLConfigMap[sourceURL] = sourceConfig - targetURLConfigMap := make(map[string]map[string]string) - targetConfigMap := make(map[string]string) - targetConfigMap["Auth.AccessKeyID"] = "" - targetConfigMap["Auth.SecretAccessKey"] = "" - targetURLConfigMap[targetURL] = targetConfigMap + targetURLConfigMap := make(map[string]*hostConfig) + targetConfig := new(hostConfig) + targetConfig.AccessKeyID = "" + targetConfig.SecretAccessKey = "" + targetURLConfigMap[targetURL] = targetConfig - manager.On("getSourceReader", sourceURL, sourceConfigMap).Return(nilReadCloser, int64(0), "", errors.New("Expected Error")).Once() + manager.On("getSourceReader", sourceURL, sourceConfig).Return(nilReadCloser, int64(0), "", errors.New("Expected Error")).Once() msg, err := doCopyCmd(manager, sourceURLConfigMap, targetURLConfigMap) c.Assert(len(msg) > 0, Equals, true) c.Assert(err, Not(IsNil)) @@ -217,8 +217,8 @@ func (s *CmdTestSuite) TestCopyCmdFailures(c *C) { dataLen1 := int64(len(data1)) reader1, writer1 := io.Pipe() - manager.On("getSourceReader", sourceURL, sourceConfigMap).Return(reader1, dataLen1, etag1, nil).Once() - manager.On("getTargetWriter", targetURL, targetConfigMap, etag1, dataLen1).Return(nil, errors.New("Expected Error")).Once() + manager.On("getSourceReader", sourceURL, sourceConfig).Return(reader1, dataLen1, etag1, nil).Once() + manager.On("getTargetWriter", targetURL, targetConfig, etag1, dataLen1).Return(nil, errors.New("Expected Error")).Once() msg, err = doCopyCmd(manager, sourceURLConfigMap, targetURLConfigMap) writer1.Close() wg.Wait() @@ -242,8 +242,8 @@ func (s *CmdTestSuite) TestCopyCmdFailures(c *C) { n3, err3 = io.Copy(&results3, reader3) wg.Done() }() - manager.On("getSourceReader", sourceURL, sourceConfigMap).Return(reader2, dataLen1, etag1, nil).Once() - manager.On("getTargetWriter", targetURL, targetConfigMap, etag1, dataLen1).Return(writer3, nil).Once() + manager.On("getSourceReader", sourceURL, sourceConfig).Return(reader2, dataLen1, etag1, nil).Once() + manager.On("getTargetWriter", targetURL, targetConfig, etag1, dataLen1).Return(writer3, nil).Once() msg, err = doCopyCmd(manager, sourceURLConfigMap, targetURLConfigMap) wg.Wait() c.Assert(len(msg) > 0, Equals, true) @@ -259,8 +259,8 @@ func (s *CmdTestSuite) TestCopyCmdFailures(c *C) { }() var failClose io.WriteCloser failClose = &FailClose{} - manager.On("getSourceReader", sourceURL, sourceConfigMap).Return(reader4, dataLen1, etag1, nil).Once() - manager.On("getTargetWriter", targetURL, targetConfigMap, etag1, dataLen1).Return(failClose, nil).Once() + manager.On("getSourceReader", sourceURL, sourceConfig).Return(reader4, dataLen1, etag1, nil).Once() + manager.On("getTargetWriter", targetURL, targetConfig, etag1, dataLen1).Return(failClose, nil).Once() msg, err = doCopyCmd(manager, sourceURLConfigMap, targetURLConfigMap) wg.Wait() c.Assert(len(msg) > 0, Equals, true) @@ -294,13 +294,13 @@ func (s *CmdTestSuite) TestLsCmdWithBucket(c *C) { {Name: "hello2", Time: time.Now(), Size: dataLen2}, } - sourceURLConfigMap := make(map[string]map[string]string) - sourceConfigMap := make(map[string]string) - sourceConfigMap["Auth.AccessKeyID"] = "" - sourceConfigMap["Auth.SecretAccessKey"] = "" - sourceURLConfigMap[sourceURL] = sourceConfigMap + sourceURLConfigMap := make(map[string]*hostConfig) + sourceConfig := new(hostConfig) + sourceConfig.AccessKeyID = "" + sourceConfig.SecretAccessKey = "" + sourceURLConfigMap[sourceURL] = sourceConfig - manager.On("getNewClient", sourceURL, sourceConfigMap, false).Return(cl1, nil).Once() + manager.On("getNewClient", sourceURL, sourceConfig, false).Return(cl1, nil).Once() cl1.On("List").Return(items, nil).Once() msg, err := doListCmd(manager, sourceURLConfigMap, false) c.Assert(msg, Equals, "") @@ -328,13 +328,13 @@ func (s *CmdTestSuite) TestLsCmdWithFilePath(c *C) { {Name: "hello2", Time: time.Now(), Size: dataLen2}, } - sourceURLConfigMap := make(map[string]map[string]string) - sourceConfigMap := make(map[string]string) - sourceConfigMap["Auth.AccessKeyID"] = "" - sourceConfigMap["Auth.SecretAccessKey"] = "" - sourceURLConfigMap[sourceURL] = sourceConfigMap + sourceURLConfigMap := make(map[string]*hostConfig) + sourceConfig := new(hostConfig) + sourceConfig.AccessKeyID = "" + sourceConfig.SecretAccessKey = "" + sourceURLConfigMap[sourceURL] = sourceConfig - manager.On("getNewClient", sourceURL, sourceConfigMap, false).Return(cl1, nil).Once() + manager.On("getNewClient", sourceURL, sourceConfig, false).Return(cl1, nil).Once() cl1.On("List").Return(items, nil).Once() msg, err := doListCmd(manager, sourceURLConfigMap, false) c.Assert(msg, Equals, "") @@ -356,13 +356,13 @@ func (s *CmdTestSuite) TestLsCmdListsBuckets(c *C) { {Name: "bucket2", Time: time.Now()}, } - sourceURLConfigMap := make(map[string]map[string]string) - sourceConfigMap := make(map[string]string) - sourceConfigMap["Auth.AccessKeyID"] = "" - sourceConfigMap["Auth.SecretAccessKey"] = "" - sourceURLConfigMap[sourceURL] = sourceConfigMap + sourceURLConfigMap := make(map[string]*hostConfig) + sourceConfig := new(hostConfig) + sourceConfig.AccessKeyID = "" + sourceConfig.SecretAccessKey = "" + sourceURLConfigMap[sourceURL] = sourceConfig - manager.On("getNewClient", sourceURL, sourceConfigMap, false).Return(cl1, nil).Once() + manager.On("getNewClient", sourceURL, sourceConfig, false).Return(cl1, nil).Once() cl1.On("List").Return(buckets, nil).Once() msg, err := doListCmd(manager, sourceURLConfigMap, false) c.Assert(msg, Equals, "") @@ -379,13 +379,13 @@ func (s *CmdTestSuite) TestMbCmd(c *C) { manager := &MockclientManager{} cl1 := &clientMocks.Client{} - sourceURLConfigMap := make(map[string]map[string]string) - sourceConfigMap := make(map[string]string) - sourceConfigMap["Auth.AccessKeyID"] = "" - sourceConfigMap["Auth.SecretAccessKey"] = "" - sourceURLConfigMap[sourceURL] = sourceConfigMap + sourceURLConfigMap := make(map[string]*hostConfig) + sourceConfig := new(hostConfig) + sourceConfig.AccessKeyID = "" + sourceConfig.SecretAccessKey = "" + sourceURLConfigMap[sourceURL] = sourceConfig - manager.On("getNewClient", sourceURL, sourceConfigMap, false).Return(cl1, nil).Once() + manager.On("getNewClient", sourceURL, sourceConfig, false).Return(cl1, nil).Once() cl1.On("PutBucket").Return(nil).Once() msg, err := doMakeBucketCmd(manager, sourceURLConfigMap, false) c.Assert(msg, Equals, "") @@ -402,25 +402,25 @@ func (s *CmdTestSuite) TestMbCmdFailures(c *C) { manager := &MockclientManager{} cl1 := &clientMocks.Client{} - sourceURLConfigMap := make(map[string]map[string]string) - sourceConfigMap := make(map[string]string) - sourceConfigMap["Auth.AccessKeyID"] = "" - sourceConfigMap["Auth.SecretAccessKey"] = "" - sourceURLConfigMap[sourceURL] = sourceConfigMap + sourceURLConfigMap := make(map[string]*hostConfig) + sourceConfig := new(hostConfig) + sourceConfig.AccessKeyID = "" + sourceConfig.SecretAccessKey = "" + sourceURLConfigMap[sourceURL] = sourceConfig - manager.On("getNewClient", sourceURL, sourceConfigMap, false).Return(nil, errors.New("Expected Failure")).Once() + manager.On("getNewClient", sourceURL, sourceConfig, false).Return(nil, errors.New("Expected Failure")).Once() msg, err := doMakeBucketCmd(manager, sourceURLConfigMap, false) c.Assert(len(msg) > 0, Equals, true) c.Assert(err, Not(IsNil)) - manager.On("getNewClient", sourceURL, sourceConfigMap, false).Return(cl1, nil).Once() + manager.On("getNewClient", sourceURL, sourceConfig, false).Return(cl1, nil).Once() cl1.On("PutBucket").Return(&net.DNSError{}).Once() cl1.On("PutBucket").Return(nil).Once() msg, err = doMakeBucketCmd(manager, sourceURLConfigMap, false) c.Assert(msg, Equals, "") c.Assert(err, IsNil) - manager.On("getNewClient", sourceURL, sourceConfigMap, false).Return(cl1, nil).Once() + manager.On("getNewClient", sourceURL, sourceConfig, false).Return(cl1, nil).Once() // we use <= rather than < since the original doesn't count in the retry retries := globalMaxRetryFlag globalMaxRetryFlag = 1 @@ -443,13 +443,13 @@ func (s *CmdTestSuite) TestMbCmdOnFile(c *C) { manager := &MockclientManager{} cl1 := &clientMocks.Client{} - sourceURLConfigMap := make(map[string]map[string]string) - sourceConfigMap := make(map[string]string) - sourceConfigMap["Auth.AccessKeyID"] = "" - sourceConfigMap["Auth.SecretAccessKey"] = "" - sourceURLConfigMap[sourceURL] = sourceConfigMap + sourceURLConfigMap := make(map[string]*hostConfig) + sourceConfig := new(hostConfig) + sourceConfig.AccessKeyID = "" + sourceConfig.SecretAccessKey = "" + sourceURLConfigMap[sourceURL] = sourceConfig - manager.On("getNewClient", sourceURL, sourceConfigMap, false).Return(cl1, nil).Once() + manager.On("getNewClient", sourceURL, sourceConfig, false).Return(cl1, nil).Once() cl1.On("PutBucket").Return(nil).Once() msg, err := doMakeBucketCmd(manager, sourceURLConfigMap, false) c.Assert(msg, Equals, "") diff --git a/main.go b/main.go index be18ab75..4292dc77 100644 --- a/main.go +++ b/main.go @@ -102,8 +102,6 @@ func main() { // SetTheme here back to DefaultTheme, Fatalf will not exit otherwise since the wrappers // anonymous func() are not assigned yet, so in essence os.Exit(1) in Fatalf is not // available and wouldn't exit here - call gets transferred to app.RunAndExitOnError() - - // On windows without this it leads to nil deference console.SetTheme(console.GetDefaultTheme()) console.Fatalf("mc: failed to set theme [%s] with following reason: [%s]\n", theme, iodine.ToError(err)) } @@ -115,7 +113,6 @@ func main() { if !isMcConfigExist() && ctx.Command.Name != "config" { console.Fatalln("mc: error ``mc`` is not configured. Please run \"mc config generate\".") } - return nil } app.RunAndExitOnError() diff --git a/mock_clientManager_test.go b/mock_clientManager_test.go index b84049fc..8fe8b54a 100644 --- a/mock_clientManager_test.go +++ b/mock_clientManager_test.go @@ -12,7 +12,7 @@ type MockclientManager struct { mock.Mock } -func (m *MockclientManager) getSourceReader(urlStr string, auth map[string]string) (io.ReadCloser, int64, string, error) { +func (m *MockclientManager) getSourceReader(urlStr string, auth *hostConfig) (io.ReadCloser, int64, string, error) { ret := m.Called(urlStr, auth) var r0 io.ReadCloser @@ -28,7 +28,7 @@ func (m *MockclientManager) getSourceReader(urlStr string, auth map[string]strin return r0, r1, r2, r3 } -func (m *MockclientManager) getTargetWriter(urlStr string, auth map[string]string, md5Hex string, length int64) (io.WriteCloser, error) { +func (m *MockclientManager) getTargetWriter(urlStr string, auth *hostConfig, md5Hex string, length int64) (io.WriteCloser, error) { ret := m.Called(urlStr, auth, md5Hex, length) var r0 io.WriteCloser @@ -42,7 +42,7 @@ func (m *MockclientManager) getTargetWriter(urlStr string, auth map[string]strin return r0, r1 } -func (m *MockclientManager) getNewClient(urlStr string, auth map[string]string, debug bool) (client.Client, error) { +func (m *MockclientManager) getNewClient(urlStr string, auth *hostConfig, debug bool) (client.Client, error) { ret := m.Called(urlStr, auth, debug) var r0 client.Client diff --git a/pkg/qdb/qdb.go b/pkg/qdb/qdb.go deleted file mode 100644 index 0ae265dc..00000000 --- a/pkg/qdb/qdb.go +++ /dev/null @@ -1,437 +0,0 @@ -/* - * qdb - Quick key value store for config files and persistent state files - * - * Mini Copy, (C) 2015 Minio, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package qdb - -import ( - "errors" - "fmt" - "os" - "reflect" - "runtime" - "strings" - "sync" - - "encoding/json" - "io/ioutil" -) - -// Store - generic db interface functions -type Store interface { - Int - Float64 - String - Map - MapMap - GetVersion() Version - Save(string) error - Load(string) error - Merge(Store) error - Diff(Store) ([]string, error) - DeepDiff(Store) ([]string, error) - GetStore() map[string]interface{} - String() string -} - -// Int - integer generic interface functions for qdb -type Int interface { - SetInt(string, int) - GetInt(string) int - SetIntSlice(string, []int) - GetIntSlice(string) []int -} - -// Float64 - float64 generic interface functions for qdb -type Float64 interface { - SetFloat64(string, float64) - GetFloat64(string) float64 - SetFloat64Slice(string, []float64) - GetFloat64Slice(string) []float64 -} - -// String - string generic interface functions for qdb -type String interface { - SetString(string, string) - GetString(string) string - SetStringSlice(string, []string) - GetStringSlice(string) []string -} - -// Map - map generic interface functions for qdb -type Map interface { - SetMapString(string, map[string]string) - GetMapString(string) map[string]string - SetMapStringSlice(string, map[string][]string) - GetMapStringSlice(string) map[string][]string -} - -// MapMap - two level map indirection interface functions for qdb -type MapMap interface { - SetMapMapString(string, map[string]map[string]string) - GetMapMapString(string) map[string]map[string]string -} - -// Version info -type Version struct { - Major int - Minor int - Patch int -} - -// Equal compares for equality between two version structures -func (v Version) Equal(newVer Version) bool { - return reflect.DeepEqual(v, newVer) -} - -// String - get version string -func (v Version) String() string { - return fmt.Sprintf("%d.%d.%d", v.Major, v.Minor, v.Patch) -} - -// Str2Version - converts string to version -func Str2Version(verStr string) Version { - var v Version - fmt.Sscanf(verStr, "%d.%d.%d", &v.Major, &v.Minor, &v.Patch) - return v -} - -// store - implements qdb.Store interface -type store struct { - store map[string]interface{} - lock *sync.RWMutex -} - -// NewStore - instantiate a new db -func NewStore(version Version) Store { - // error condition - if version.Major == 0 { - return nil - } - - db := new(store) - db.store = make(map[string]interface{}) - db.store["Version"] = version.String() - db.lock = new(sync.RWMutex) - - return db -} - -// GetVersion returns the current db file format version -func (s store) GetVersion() Version { - val, ok := s.store["Version"].(string) - if !ok { - return Version{} - } - return Str2Version(val) -} - -// SetInt sets int value -func (s *store) SetInt(key string, value int) { - (*s).lock.Lock() - defer (*s).lock.Unlock() - (*s).store[key] = value -} - -// GetInt returns int value -func (s store) GetInt(key string) int { - intVal, ok := s.store[key].(int) - if !ok { - interfaceIntVal, _ := s.store[key].(interface{}) - return int(reflect.ValueOf(interfaceIntVal).Float()) - } - return intVal -} - -// SetIntSlice sets list of int values -func (s *store) SetIntSlice(key string, values []int) { - (*s).lock.Lock() - defer (*s).lock.Unlock() - (*s).store[key] = values -} - -// GetIntSlice returns list of int values -func (s store) GetIntSlice(key string) []int { - interfaceIntSliceVal, ok := s.store[key].([]interface{}) - if !ok { - intSliceVal, _ := s.store[key].([]int) - return intSliceVal - } - var actualIntSliceVal []int - for _, v := range interfaceIntSliceVal { - vInt := reflect.ValueOf(v) - actualIntSliceVal = append(actualIntSliceVal, int(vInt.Float())) - } - return actualIntSliceVal -} - -// SetFloat64 sets 64-bit float value -func (s *store) SetFloat64(key string, value float64) { - (*s).lock.Lock() - defer (*s).lock.Unlock() - (*s).store[key] = value -} - -// GetFloat64 returns 64-bit float value -func (s store) GetFloat64(key string) float64 { - val := reflect.ValueOf(s.store[key]) - return val.Float() -} - -// SetFloat64Slice sets a list of 64-bit float values -func (s *store) SetFloat64Slice(key string, values []float64) { - (*s).lock.Lock() - defer (*s).lock.Unlock() - (*s).store[key] = values -} - -// GetFloat64Slice returns a list of 64-bit float values -func (s store) GetFloat64Slice(key string) []float64 { - interfaceFloatSliceVal, ok := s.store[key].([]interface{}) - if !ok { - floatSliceVal, _ := s.store[key].([]float64) - return floatSliceVal - } - var actualFloatSliceVal []float64 - for _, v := range interfaceFloatSliceVal { - val := reflect.ValueOf(v) - actualFloatSliceVal = append(actualFloatSliceVal, val.Float()) - } - return actualFloatSliceVal -} - -// SetString sets string value -func (s *store) SetString(key string, value string) { - (*s).lock.Lock() - defer (*s).lock.Unlock() - (*s).store[key] = value -} - -// GetString returns string value -func (s store) GetString(key string) string { - val, _ := s.store[key].(string) - return val -} - -// SetStringSlice sets list of strings -func (s *store) SetStringSlice(key string, values []string) { - (*s).lock.Lock() - defer (*s).lock.Unlock() - (*s).store[key] = values -} - -// GetStringSlice returns list of strings -func (s store) GetStringSlice(key string) []string { - interfaceStrSliceVal, ok := s.store[key].([]interface{}) - if !ok { - strSliceVal, _ := s.store[key].([]string) - return strSliceVal - } - var actualStrSliceVal []string - for _, v := range interfaceStrSliceVal { - val := reflect.ValueOf(v) - actualStrSliceVal = append(actualStrSliceVal, val.String()) - } - return actualStrSliceVal -} - -// SetMapString sets a map of strings -func (s *store) SetMapString(key string, value map[string]string) { - (*s).lock.Lock() - defer (*s).lock.Unlock() - (*s).store[key] = value -} - -// GetMapString returns a map of strings -func (s store) GetMapString(key string) map[string]string { - interfaceMapVal, ok := s.store[key].(map[string]interface{}) - if !ok { - val, _ := s.store[key].(map[string]string) - return val - } - actualMapVal := make(map[string]string) - for k, v := range interfaceMapVal { - rv := reflect.ValueOf(v) - actualMapVal[k] = rv.String() - } - return actualMapVal -} - -// SetMapStringSlice sets a map of string list -func (s *store) SetMapStringSlice(key string, value map[string][]string) { - (*s).lock.Lock() - defer (*s).lock.Unlock() - (*s).store[key] = value -} - -// GetMapStringSlice returns a map of string list -func (s store) GetMapStringSlice(key string) map[string][]string { - interfacelMapSliceVal, ok := s.store[key].(map[string]interface{}) - if !ok { - mapSliceVal, _ := s.store[key].(map[string][]string) - return mapSliceVal - } - actualMapSliceVal := make(map[string][]string) - for k, v := range interfacelMapSliceVal { - var actualStrSliceVal []string - rv, _ := v.([]interface{}) - for _, l := range rv { - val := reflect.ValueOf(l) - actualStrSliceVal = append(actualStrSliceVal, val.String()) - } - actualMapSliceVal[k] = actualStrSliceVal - } - return actualMapSliceVal -} - -// SetMapMapString sets a map of a map string -func (s *store) SetMapMapString(key string, value map[string]map[string]string) { - (*s).lock.Lock() - defer (*s).lock.Unlock() - (*s).store[key] = value -} - -// GetMapMapString gets a map of a map string -func (s *store) GetMapMapString(key string) map[string]map[string]string { - interfaceMapMapVal, ok := s.store[key].(map[string]interface{}) - if !ok { - val, _ := s.store[key].(map[string]map[string]string) - return val - } - actualMapMapVal := make(map[string]map[string]string) - for k, v := range interfaceMapMapVal { - rv, _ := v.(map[string]interface{}) - nestedActualMapVal := make(map[string]string) - for m, n := range rv { - rn := reflect.ValueOf(n) - nestedActualMapVal[m] = rn.String() - } - actualMapMapVal[k] = nestedActualMapVal - } - return actualMapMapVal -} - -// Save writes db data in JSON format to a file. -func (s store) Save(filename string) (err error) { - s.lock.Lock() - defer s.lock.Unlock() - - jsonStore, err := json.MarshalIndent(s.store, "", "\t") - if err != nil { - return err - } - - file, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600) - if err != nil { - return err - } - defer file.Close() - - if runtime.GOOS == "windows" { - jsonStore = []byte(strings.Replace(string(jsonStore), "\n", "\r\n", -1)) - } - _, err = file.Write(jsonStore) - if err != nil { - return err - } - return nil - -} - -// Load - loads JSON db from file and merge with currently set values -func (s *store) Load(filename string) (err error) { - (*s).lock.Lock() - defer (*s).lock.Unlock() - - _, err = os.Stat(filename) - if err != nil { - return err - } - - data, err := ioutil.ReadFile(filename) - if err != nil { - return err - } - - if runtime.GOOS == "windows" { - data = []byte(strings.Replace(string(data), "\r\n", "\n", -1)) - } - - var loadedStore map[string]interface{} - err = json.Unmarshal(data, &loadedStore) - if err != nil { - return err - } - - if !reflect.DeepEqual((*s).store["Version"], loadedStore["Version"]) { - return errors.New("Version mismatch") - } - - // Merge pre-set keys - for key := range loadedStore { - (*s).store[key] = loadedStore[key] - } - return nil -} - -// GetStore - grab internal store map for reading -func (s store) GetStore() map[string]interface{} { - return s.store -} - -// Merge - fast forward old keys to old+new keys -func (s *store) Merge(m Store) (err error) { - (*s).lock.Lock() - defer (*s).lock.Unlock() - - for key := range m.GetStore() { - (*s).store[key] = m.GetStore()[key] - } - return nil -} - -// Diff - returns list of keys that are in A but in B -func (s store) Diff(b Store) (keys []string, err error) { - for key := range s.store { - _, ok := b.GetStore()[key] - if !ok { - keys = append(keys, key) - } - } - return keys, nil -} - -// Diff - returns list of keys in A but not in B or of different values -func (s store) DeepDiff(b Store) (keys []string, err error) { - for key, valA := range s.store { - valB, ok := b.GetStore()[key] - if !ok { - keys = append(keys, key) - } else { - if !reflect.DeepEqual(valA, valB) { - keys = append(keys, key) - } - } - } - return keys, nil -} - -// String converts JSON db to printable string -func (s store) String() string { - dbBytes, _ := json.MarshalIndent(s.store, "", "\t") - return string(dbBytes) -} diff --git a/pkg/qdb/qdb_test.go b/pkg/qdb/qdb_test.go deleted file mode 100644 index 3d45075b..00000000 --- a/pkg/qdb/qdb_test.go +++ /dev/null @@ -1,205 +0,0 @@ -/* - * qdb - Quick key value store for config files and persistent state files - * - * Mini Copy, (C) 2015 Minio, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package qdb - -import ( - "os" - "testing" - - . "github.com/minio-io/check" -) - -func Test(t *testing.T) { TestingT(t) } - -type MySuite struct{} - -var _ = Suite(&MySuite{}) - -func (s *MySuite) TestVersion(c *C) { - cfg := NewStore(Version{1, 0, 0}) - c.Assert(cfg.GetVersion(), DeepEquals, Version{1, 0, 0}) - - c.Assert(Str2Version("1.0.0"), DeepEquals, cfg.GetVersion()) -} - -func (s *MySuite) TestSaveLoad(c *C) { - defer os.RemoveAll("test.json") - version := Version{1, 0, 0} - - cfg := NewStore(version) - cfg.SetFloat64("Pi", 3.1415) - cfg.Save("test.json") - - newCfg := NewStore(version) - newCfg.Load("test.json") - pi := newCfg.GetFloat64("Pi") - c.Assert(pi, Equals, 3.1415) -} - -func (s *MySuite) TestMerge(c *C) { - defer os.RemoveAll("test.json") - version := Version{1, 0, 0} - - cfg1 := NewStore(version) - cfg1.SetFloat64("Pi", 3.1415) - - newCfg := NewStore(version) - newCfg.SetFloat64("h", 2*3.1415) - - cfg1.Merge(newCfg) - cfg1.Save("test.json") - - cfg2 := NewStore(version) - cfg2.Load("test.json") - h := cfg2.GetFloat64("h") - c.Assert(h, Equals, 2*3.1415) -} - -func (s *MySuite) TestDiff(c *C) { - version1 := Version{1, 0, 0} - - cfg1 := NewStore(version1) - cfg1.SetFloat64("Pi", 3.1415) - cfg1.SetInt("DS", 9) - - version2 := Version{2, 0, 0} - newCfg := NewStore(version2) - newCfg.SetFloat64("Pi", 2.14) - newCfg.SetInt("DS9", 10) - - diffs, err := cfg1.Diff(newCfg) - c.Assert(err, IsNil) - c.Assert(len(diffs), Equals, 1) -} - -func (s *MySuite) TestDeepDiff(c *C) { - version1 := Version{1, 0, 0} - - cfg1 := NewStore(version1) - cfg1.SetFloat64("Pi", 3.1415) - cfg1.SetInt("DS", 9) - - version2 := Version{1, 0, 0} - newCfg := NewStore(version2) - newCfg.SetFloat64("Pi", 3.14) - newCfg.SetInt("DS", 10) - - diffs, err := cfg1.DeepDiff(newCfg) - c.Assert(err, IsNil) - c.Assert(len(diffs), Equals, 2) -} - -func (s *MySuite) TestGetSet(c *C) { - version := Version{1, 0, 0} - cfg := NewStore(version) - - cfg.SetInt("Q", 42) - c.Assert(cfg.GetInt("Q"), Equals, 42) - - cfg.SetIntSlice("Odd", []int{1, 3, 5, 7, 9}) - c.Assert(cfg.GetIntSlice("Odd"), DeepEquals, []int{1, 3, 5, 7, 9}) - - cfg.SetFloat64("Pi", 3.1415) - c.Assert(cfg.GetFloat64("Pi"), Equals, 3.1415) - - cfg.SetFloat64Slice("Pi", []float64{3.1415, 2.414}) - c.Assert(cfg.GetFloat64Slice("Pi"), DeepEquals, []float64{3.1415, 2.414}) - - cfg.SetString("Grand Nagus", "Zek") - c.Assert(cfg.GetString("Grand Nagus"), Equals, "Zek") - - cfg.SetStringSlice("Ferengi", []string{"Zek", "Brunt", "Quark", "Rom", "Nog", "Ishka"}) - c.Assert(cfg.GetStringSlice("Ferengi"), DeepEquals, []string{"Zek", "Brunt", "Quark", "Rom", "Nog", "Ishka"}) - - startrek1 := map[string]string{"Borg": "7of9", "Data": "Measure of a Man"} - startrek2 := map[string]string{"Borg": "7of9", "Data": "Measure of a Man"} - cfg.SetMapString("startrek", startrek1) - c.Assert(cfg.GetMapString("startrek"), DeepEquals, startrek2) - - startrek3 := map[string][]string{ - "Quadrants": {"Alpha", "Beta", "Gamma", "Delta"}, - "Aliens": {"Dominion", "Borg", "Klingon", "Romulan"}, - } - startrek4 := map[string][]string{ - "Quadrants": {"Alpha", "Beta", "Gamma", "Delta"}, - "Aliens": {"Dominion", "Borg", "Klingon", "Romulan"}, - } - cfg.SetMapStringSlice("startrek", startrek3) - c.Assert(cfg.GetMapStringSlice("startrek"), DeepEquals, startrek4) - - startrek5 := map[string][]string{ - "Quadrants": {"Beta", "Gamma", "Delta"}, - "Aliens": {"Dominion", "Borg", "Klingon", "Romulan"}, - } - startrek6 := map[string][]string{ - "Quadrants": {"Alpha", "Beta", "Gamma", "Delta"}, - "Aliens": {"Dominion", "Borg", "Klingon", "Romulan"}, - } - cfg.SetMapStringSlice("startrek", startrek5) - c.Assert(cfg.GetMapStringSlice("startrek"), Not(DeepEquals), startrek6) - - c.Assert(cfg.GetMapStringSlice("Startrek"), IsNil) - -} - -func (s *MySuite) TestGetSetSaveLoad(c *C) { - defer os.RemoveAll("test.json") - version := Version{1, 0, 0} - - cfg := NewStore(version) - cfg.SetInt("Q", 42) - cfg.SetIntSlice("Odd", []int{1, 3, 5, 7, 9}) - cfg.SetFloat64("Pi", 3.1415) - cfg.SetFloat64Slice("PiSlice", []float64{3.1415, 2.414}) - cfg.SetString("Grand Nagus", "Zek") - cfg.SetStringSlice("Ferengi", []string{"Zek", "Brunt", "Quark", "Rom", "Nog", "Ishka"}) - startrek1 := map[string]string{"Borg": "7of9", "Data": "Measure of a Man"} - startrek2 := map[string]string{"Borg": "7of9", "Data": "Measure of a Man"} - cfg.SetMapString("startrek", startrek1) - startrek3 := map[string][]string{ - "Quadrants": {"Alpha", "Beta", "Gamma", "Delta"}, - "Aliens": {"Dominion", "Borg", "Klingon", "Romulan"}, - } - startrek4 := map[string][]string{ - "Quadrants": {"Alpha", "Beta", "Gamma", "Delta"}, - "Aliens": {"Dominion", "Borg", "Klingon", "Romulan"}, - } - cfg.SetMapStringSlice("startrekSlice", startrek3) - - mapMapString := map[string]map[string]string{ - "Quandrants": { - "Delta": "Romulan", - }, - } - cfg.SetMapMapString("MilkyWay", mapMapString) - - cfg.Save("test.json") - - newCfg := NewStore(version) - newCfg.Load("test.json") - c.Assert(newCfg.GetInt("Q"), Equals, 42) - c.Assert(newCfg.GetIntSlice("Odd"), DeepEquals, []int{1, 3, 5, 7, 9}) - c.Assert(newCfg.GetFloat64("Pi"), Equals, 3.1415) - c.Assert(newCfg.GetFloat64Slice("PiSlice"), DeepEquals, []float64{3.1415, 2.414}) - c.Assert(newCfg.GetString("Grand Nagus"), Equals, "Zek") - c.Assert(newCfg.GetStringSlice("Ferengi"), DeepEquals, []string{"Zek", "Brunt", "Quark", "Rom", "Nog", "Ishka"}) - c.Assert(newCfg.GetMapString("startrek"), DeepEquals, startrek2) - c.Assert(newCfg.GetMapStringSlice("startrekSlice"), DeepEquals, startrek4) - c.Assert(newCfg.GetMapMapString("MilkyWay"), DeepEquals, mapMapString) -} diff --git a/pkg/quick/quick.go b/pkg/quick/quick.go index 5b2de94f..d25b9f39 100644 --- a/pkg/quick/quick.go +++ b/pkg/quick/quick.go @@ -70,16 +70,16 @@ func CheckData(data interface{}) error { } // New - instantiate a new config -func New(data interface{}) (Config, error) { +func New(data interface{}) Config { err := CheckData(data) if err != nil { - return nil, iodine.New(err, nil) + return nil } d := new(config) d.data = &data d.lock = new(sync.RWMutex) - return d, nil + return d } // Version returns the current config file format version diff --git a/pkg/quick/quick_test.go b/pkg/quick/quick_test.go index 6c80faef..0753e9ef 100644 --- a/pkg/quick/quick_test.go +++ b/pkg/quick/quick_test.go @@ -65,13 +65,13 @@ func (s *MySuite) TestSaveLoad(c *C) { Folders []string } saveMe := myStruct{"1", "guest", "nopassword", []string{"Work", "Documents", "Music"}} - config, err := New(&saveMe) - c.Assert(err, IsNil) + config := New(&saveMe) + c.Assert(config, Not(IsNil)) config.Save("test.json") loadMe := myStruct{Version: "1"} - newConfig, err := New(&loadMe) - c.Assert(err, IsNil) + newConfig := New(&loadMe) + c.Assert(newConfig, Not(IsNil)) newConfig.Load("test.json") c.Assert(config.Data(), DeepEquals, newConfig.Data()) @@ -89,8 +89,8 @@ func (s *MySuite) TestDiff(c *C) { Folders []string } saveMe := myStruct{"1", "guest", "nopassword", []string{"Work", "Documents", "Music"}} - config, err := New(&saveMe) - c.Assert(err, IsNil) + config := New(&saveMe) + c.Assert(config, Not(IsNil)) type myNewStruct struct { Version string @@ -100,8 +100,8 @@ func (s *MySuite) TestDiff(c *C) { } mismatch := myNewStruct{"1", "nopassword", []string{"Work", "documents", "Music"}} - newConfig, err := New(&mismatch) - c.Assert(err, IsNil) + newConfig := New(&mismatch) + c.Assert(newConfig, Not(IsNil)) fields, ok := config.Diff(newConfig) c.Assert(ok, IsNil) @@ -121,12 +121,12 @@ func (s *MySuite) TestDeepDiff(c *C) { Folders []string } saveMe := myStruct{"1", "guest", "nopassword", []string{"Work", "Documents", "Music"}} - config, err := New(&saveMe) - c.Assert(err, IsNil) + config := New(&saveMe) + c.Assert(config, Not(IsNil)) mismatch := myStruct{"1", "Guest", "nopassword", []string{"Work", "documents", "Music"}} - newConfig, err := New(&mismatch) - c.Assert(err, IsNil) + newConfig := New(&mismatch) + c.Assert(newConfig, Not(IsNil)) fields, err := config.DeepDiff(newConfig) c.Assert(err, IsNil)