From 93071eef5b09e6df7f33ee79d692bd05ed1a0217 Mon Sep 17 00:00:00 2001 From: DeniskaRediska Date: Tue, 29 Oct 2019 16:47:21 +0300 Subject: [PATCH] add(commands for common configs) --- .version | 2 +- CHANGELOG.md | 2 + cfg/domain.go | 34 +++++++--- cfg/method_name.go | 11 +-- cfg/methods.go | 34 +++++++++- command/common.go | 67 +++++++++---------- command/commonConfig/delete.go | 96 ++++++++++++++++++++++++++ command/commonConfig/get.go | 91 +++++++++++++++++++++++++ command/commonConfig/link.go | 115 +++++++++++++++++++++++++++++++ command/commonConfig/remove.go | 71 ++++++++++++++++++++ command/commonConfig/set.go | 119 +++++++++++++++++++++++++++++++++ command/commonConfig/unlink.go | 117 ++++++++++++++++++++++++++++++++ command/delete.go | 15 +++-- command/get.go | 30 ++------- command/schema.go | 15 +++-- command/set.go | 61 +++-------------- command/status.go | 5 +- command/utils/common.go | 94 ++++++++++++++++++++++++++ command/utils/common_config.go | 14 ++++ command/utils/config.go | 14 ++++ main.go | 1 + service/common.go | 7 +- service/config.go | 63 ++++++++++++----- 23 files changed, 920 insertions(+), 158 deletions(-) create mode 100644 command/commonConfig/delete.go create mode 100644 command/commonConfig/get.go create mode 100644 command/commonConfig/link.go create mode 100644 command/commonConfig/remove.go create mode 100644 command/commonConfig/set.go create mode 100644 command/commonConfig/unlink.go create mode 100644 command/utils/common.go create mode 100644 command/utils/common_config.go create mode 100644 command/utils/config.go diff --git a/.version b/.version index e8ea05d..f0bb29e 100644 --- a/.version +++ b/.version @@ -1 +1 @@ -1.2.4 +1.3.0 diff --git a/CHANGELOG.md b/CHANGELOG.md index bb2560c..486cfbe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,5 @@ +## v1.3.0 +* add commands for common configs ## v1.2.4 * migrate invoke to config service ## v1.2.3 diff --git a/cfg/domain.go b/cfg/domain.go index 5160874..a1fd25d 100644 --- a/cfg/domain.go +++ b/cfg/domain.go @@ -7,21 +7,31 @@ import ( ) type getModuleByUuidAndNameRequest struct { - Name string - Uuid string + ModuleName string + Uuid string } type getSchemaByModuleIdRequest struct { - ModuleId int32 + ModuleId string } type Config struct { - Id int64 + Id string + Name string + CommonConfigs []string + Description string + ModuleId string + Version int32 + Active bool + CreatedAt time.Time + UpdatedAt time.Time + Data map[string]interface{} +} + +type CommonConfig struct { + Id string Name string Description string - ModuleId int32 - Version int32 - Active bool CreatedAt time.Time UpdatedAt time.Time Data map[string]interface{} @@ -36,7 +46,7 @@ type Connection struct { } type ModuleInfo struct { - Id int32 + Id string Name string Active bool CreatedAt time.Time @@ -48,10 +58,14 @@ type ModuleInfo struct { } type ConfigSchema struct { - Id int32 + Id string Version string - ModuleId int32 + ModuleId string Schema schema.Schema CreatedAt time.Time UpdatedAt time.Time } + +type deleted struct { + Deleted int +} diff --git a/cfg/method_name.go b/cfg/method_name.go index 62ddeb0..3de4830 100644 --- a/cfg/method_name.go +++ b/cfg/method_name.go @@ -1,8 +1,11 @@ package cfg const ( - getAvailableConfigs = "config/module/get_modules_info" - getConfigByModuleName = "config/config/get_config_by_instance_uuid_and_module_name" - createUpdateConfig = "config/config/create_update_config" - getSchemaByModuleId = "config/schema/get_by_module_id" + getAvailableConfigs = "config/module/get_modules_info" + getConfigByModuleName = "config/config/get_active_config_by_module_name" + createUpdateConfig = "config/config/create_update_config" + getSchemaByModuleId = "config/schema/get_by_module_id" + getCommonConfigs = "config/common_config/get_configs" + createUpdateCommonConfig = "config/common_config/create_update_config" + deleteCommonConfig = "config/common_config/delete_config" ) diff --git a/cfg/methods.go b/cfg/methods.go index 7a64d28..078cfbc 100644 --- a/cfg/methods.go +++ b/cfg/methods.go @@ -53,7 +53,7 @@ func (c *configClient) GetAvailableConfigs() ([]ModuleInfo, error) { } func (c *configClient) GetConfigByModuleName(name string) (*Config, error) { - request := &getModuleByUuidAndNameRequest{Name: name, Uuid: c.instanceUuid} + request := &getModuleByUuidAndNameRequest{ModuleName: name, Uuid: c.instanceUuid} response := new(Config) err := c.cli.Invoke(getConfigByModuleName, callerId, request, response, backend.WithMetadata(c.headers)) if err != nil { @@ -73,7 +73,7 @@ func (c *configClient) CreateUpdateConfig(request Config) (*Config, error) { } } -func (c *configClient) GetSchemaByModuleId(moduleId int32) (*ConfigSchema, error) { +func (c *configClient) GetSchemaByModuleId(moduleId string) (*ConfigSchema, error) { request := &getSchemaByModuleIdRequest{ModuleId: moduleId} response := new(ConfigSchema) err := c.cli.Invoke(getSchemaByModuleId, callerId, &request, response, backend.WithMetadata(c.headers)) @@ -84,6 +84,36 @@ func (c *configClient) GetSchemaByModuleId(moduleId int32) (*ConfigSchema, error } } +func (c *configClient) GetCommonConfigs(req []string) ([]CommonConfig, error) { + response := make([]CommonConfig, 0) + err := c.cli.Invoke(getCommonConfigs, callerId, req, &response, backend.WithMetadata(c.headers)) + if err != nil { + return nil, c.errorHandler(err) + } else { + return response, nil + } +} + +func (c *configClient) CreateUpdateCommonConfig(req CommonConfig) (*CommonConfig, error) { + response := new(CommonConfig) + err := c.cli.Invoke(createUpdateCommonConfig, callerId, req, response, backend.WithMetadata(c.headers)) + if err != nil { + return nil, c.errorHandler(err) + } else { + return response, nil + } +} + +func (c *configClient) DeleteCommonConfig(req []string) (int, error) { + response := new(deleted) + err := c.cli.Invoke(deleteCommonConfig, callerId, req, response, backend.WithMetadata(c.headers)) + if err != nil { + return 0, c.errorHandler(err) + } else { + return response.Deleted, nil + } +} + func (c *configClient) errorHandler(err error) error { errStatus, ok := status.FromError(err) if !ok { diff --git a/command/common.go b/command/common.go index 5cefbfc..0a98384 100644 --- a/command/common.go +++ b/command/common.go @@ -1,49 +1,44 @@ package command import ( - "encoding/json" "fmt" - "github.com/pkg/errors" - "isp-ctl/cfg" - "isp-ctl/service" - "strings" + "github.com/codegangsta/cli" + "isp-ctl/command/commonConfig" ) -func checkPath(pathObject string) (string, error) { - str := strings.Split(pathObject, ".") - pathObject = "" - if len(str) == 1 || str[0] != "" { - return pathObject, errors.New("path must start with '.'") +func CommonConfig() cli.Command { + return cli.Command{ + Name: "common", + Usage: "access to common configs commands", + Action: cc.action, + BashComplete: cc.bachComplete, + Subcommands: []cli.Command{ + commonConfig.Get(), + commonConfig.Set(), + commonConfig.Delete(), + commonConfig.Remove(), + commonConfig.Link(), + commonConfig.UnLink(), + }, } - for key, value := range str { - if key == 0 { - continue +} + +var cc commonConfigCommand + +type commonConfigCommand struct{} + +func (g commonConfigCommand) action(ctx *cli.Context) { + if ctx.Args().First() == "" { + fmt.Print("need use command: ") + for _, comm := range CommonConfig().Subcommands { + fmt.Printf("[%s] ", comm.Name) } - if key == 1 { - pathObject = fmt.Sprintf("%s", value) - continue - } - pathObject = fmt.Sprintf("%s.%s", pathObject, value) - } - return pathObject, nil -} - -func createUpdateConfig(stringToChange string, configuration *cfg.Config) { - if answer, err := service.Config.CreateUpdateConfig(stringToChange, configuration); err != nil { - printError(err) - } else if answer != nil { - printAnswer(answer) + fmt.Printf("\n") } } -func printAnswer(data interface{}) { - if answer, err := json.MarshalIndent(data, "", " "); err != nil { - printError(err) - } else { - service.ColorService.Print(answer) +func (g commonConfigCommand) bachComplete(ctx *cli.Context) { + for _, command := range CommonConfig().Subcommands { + fmt.Println(command.Name) } } - -func printError(err error) { - fmt.Println("ERROR:", err) -} diff --git a/command/commonConfig/delete.go b/command/commonConfig/delete.go new file mode 100644 index 0000000..5fd8416 --- /dev/null +++ b/command/commonConfig/delete.go @@ -0,0 +1,96 @@ +package commonConfig + +import ( + "encoding/json" + "fmt" + "github.com/codegangsta/cli" + "github.com/integration-system/bellows" + "github.com/pkg/errors" + "github.com/tidwall/sjson" + "isp-ctl/command/utils" + "isp-ctl/flag" + "isp-ctl/service" +) + +func Delete() cli.Command { + return cli.Command{ + Name: "delete", + Usage: "set common configurations", + Action: deleteComm.action, + BashComplete: deleteComm.bashComplete, + } +} + +var deleteComm deleteCommand + +type deleteCommand struct{} + +func (g deleteCommand) action(ctx *cli.Context) { + if err := flag.CheckGlobal(ctx); err != nil { + utils.PrintError(err) + return + } + + ccName := ctx.Args().First() + pathObject := ctx.Args().Get(1) + + if ccName == "" { + utils.PrintError(errors.New("empty config name")) + return + } + + pathObject, err := utils.CheckPath(pathObject) + if err != nil { + utils.PrintError(err) + return + } + + commonConfigs, err := service.Config.GetMapCommonConfigByName() + if err != nil { + utils.PrintError(err) + return + } + + config, ok := commonConfigs[ccName] + if !ok { + utils.PrintError(errors.Errorf("common config %s not found", ccName)) + return + } + + if pathObject == "" { + utils.CreateUpdateCommonConfig("", config) + } else { + jsonObject, err := json.Marshal(config.Data) + if err != nil { + utils.PrintError(err) + return + } + if stringToChange, err := sjson.Delete(string(jsonObject), pathObject); err != nil { + utils.PrintError(err) + } else { + utils.CreateUpdateCommonConfig(stringToChange, config) + } + } +} + +func (g deleteCommand) bashComplete(ctx *cli.Context) { + if err := flag.CheckGlobal(ctx); err != nil { + return + } + commonConfigs, err := service.Config.GetMapCommonConfigByName() + if err != nil { + return + } + switch ctx.NArg() { + case 0: + for _, config := range commonConfigs { + fmt.Println(config.Name) + } + case 1: + if config, ok := commonConfigs[ctx.Args().First()]; ok { + for key, _ := range bellows.Flatten(config.Data) { + fmt.Printf(".%v\n", key) + } + } + } +} diff --git a/command/commonConfig/get.go b/command/commonConfig/get.go new file mode 100644 index 0000000..7f36550 --- /dev/null +++ b/command/commonConfig/get.go @@ -0,0 +1,91 @@ +package commonConfig + +import ( + "encoding/json" + "fmt" + "github.com/codegangsta/cli" + "github.com/integration-system/bellows" + "github.com/pkg/errors" + "isp-ctl/command/utils" + "isp-ctl/flag" + "isp-ctl/service" +) + +func Get() cli.Command { + return cli.Command{ + Name: "get", + Usage: "get common configurations", + Action: get.action, + BashComplete: get.bashComplete, + } +} + +var get getCommand + +type getCommand struct{} + +func (g getCommand) action(ctx *cli.Context) { + if err := flag.CheckGlobal(ctx); err != nil { + utils.PrintError(err) + return + } + + ccName := ctx.Args().First() + pathObject := ctx.Args().Get(1) + + commonConfigs, err := service.Config.GetMapCommonConfigByName() + if err != nil { + utils.PrintError(err) + return + } + + if ccName == "" { + for name := range commonConfigs { + fmt.Printf("%s ", name) + } + fmt.Println() + return + } + + pathObject, err = utils.CheckPath(pathObject) + if err != nil { + utils.PrintError(err) + return + } + + config, ok := commonConfigs[ccName] + if !ok { + utils.PrintError(errors.Errorf("common config %s not found", ccName)) + return + } + + if pathObject == "" { + utils.PrintAnswer(config.Data) + } else if jsonObject, err := json.Marshal(config.Data); err != nil { + utils.PrintError(err) + } else { + utils.CheckObject(jsonObject, pathObject) + } +} + +func (g getCommand) bashComplete(ctx *cli.Context) { + if err := flag.CheckGlobal(ctx); err != nil { + return + } + commonConfigs, err := service.Config.GetMapCommonConfigByName() + if err != nil { + return + } + switch ctx.NArg() { + case 0: + for _, config := range commonConfigs { + fmt.Println(config.Name) + } + case 1: + if config, ok := commonConfigs[ctx.Args().First()]; ok { + for key, _ := range bellows.Flatten(config.Data) { + fmt.Printf(".%v\n", key) + } + } + } +} diff --git a/command/commonConfig/link.go b/command/commonConfig/link.go new file mode 100644 index 0000000..e2e53cc --- /dev/null +++ b/command/commonConfig/link.go @@ -0,0 +1,115 @@ +package commonConfig + +import ( + "fmt" + "github.com/codegangsta/cli" + "github.com/pkg/errors" + "isp-ctl/command/utils" + "isp-ctl/flag" + "isp-ctl/service" +) + +func Link() cli.Command { + return cli.Command{ + Name: "link", + Usage: "link common configurations to module configuration", + Action: link.action, + BashComplete: link.bashComplete, + } +} + +var link linkCommand + +type linkCommand struct{} + +func (g linkCommand) action(ctx *cli.Context) { + if err := flag.CheckGlobal(ctx); err != nil { + utils.PrintError(err) + return + } + + configName := ctx.Args().First() + moduleName := ctx.Args().Get(1) + + if configName == "" { + utils.PrintError(errors.New("need config name")) + return + } + + if moduleName == "" { + utils.PrintError(errors.New("need module name")) + return + } + + commonConfigs, err := service.Config.GetMapCommonConfigByName() + if err != nil { + utils.PrintError(err) + return + } + + config, ok := commonConfigs[configName] + if !ok { + utils.PrintError(errors.Errorf("common config %s not found", configName)) + return + } + + moduleConfiguration, _, err := service.Config.GetConfigurationAndJsonByModuleName(moduleName) + if err != nil { + utils.PrintError(err) + return + } + + ccIdNameMap := make(map[string]string) + for name, value := range commonConfigs { + ccIdNameMap[value.Id] = name + } + + needLink := true + for _, configId := range moduleConfiguration.CommonConfigs { + if config.Id == configId { + needLink = false + break + } + } + + if needLink { + moduleConfiguration.CommonConfigs = append(moduleConfiguration.CommonConfigs, config.Id) + if linked, err := service.Config.UpdateConfigAndGetLinkCommon(*moduleConfiguration); err != nil { + utils.PrintError(err) + } else { + for _, name := range linked { + fmt.Printf("[%s] ", ccIdNameMap[name]) + } + fmt.Printf("\n") + } + } else { + for _, name := range moduleConfiguration.CommonConfigs { + fmt.Printf("[%s] ", ccIdNameMap[name]) + } + fmt.Printf("\n") + } +} + +func (g linkCommand) bashComplete(ctx *cli.Context) { + if err := flag.CheckGlobal(ctx); err != nil { + return + } + commonConfigs, err := service.Config.GetMapCommonConfigByName() + if err != nil { + return + } + switch ctx.NArg() { + case 0: + for _, config := range commonConfigs { + fmt.Println(config.Name) + } + case 1: + if arrayOfModules, err := service.Config.GetAvailableConfigs(); err != nil { + return + } else { + for _, module := range arrayOfModules { + fmt.Println(module.Name) + } + } + } +} diff --git a/command/commonConfig/remove.go b/command/commonConfig/remove.go new file mode 100644 index 0000000..ad508af --- /dev/null +++ b/command/commonConfig/remove.go @@ -0,0 +1,71 @@ +package commonConfig + +import ( + "fmt" + "github.com/codegangsta/cli" + "github.com/pkg/errors" + "isp-ctl/command/utils" + "isp-ctl/flag" + "isp-ctl/service" +) + +func Remove() cli.Command { + return cli.Command{ + Name: "remove", + Usage: "remove common configurations", + Action: remove.action, + BashComplete: remove.bashComplete, + } +} + +var remove removeCommand + +type removeCommand struct{} + +func (g removeCommand) action(ctx *cli.Context) { + if err := flag.CheckGlobal(ctx); err != nil { + utils.PrintError(err) + return + } + + ccName := ctx.Args().First() + + if ccName == "" { + utils.PrintError(errors.New("empty common config name")) + return + } + + commonConfigs, err := service.Config.GetMapCommonConfigByName() + if err != nil { + utils.PrintError(err) + return + } + + config, ok := commonConfigs[ccName] + if !ok { + utils.PrintError(errors.Errorf("common config %s not found", ccName)) + return + } + + if deleted, err := service.Config.DeleteCommonConfig(config.Id); err != nil { + utils.PrintError(err) + } else { + fmt.Printf("count deleted config: %d\n", deleted) + } +} + +func (g removeCommand) bashComplete(ctx *cli.Context) { + if err := flag.CheckGlobal(ctx); err != nil { + return + } + commonConfigs, err := service.Config.GetMapCommonConfigByName() + if err != nil { + return + } + switch ctx.NArg() { + case 0: + for _, config := range commonConfigs { + fmt.Println(config.Name) + } + } +} diff --git a/command/commonConfig/set.go b/command/commonConfig/set.go new file mode 100644 index 0000000..988501f --- /dev/null +++ b/command/commonConfig/set.go @@ -0,0 +1,119 @@ +package commonConfig + +import ( + "encoding/json" + "fmt" + "github.com/codegangsta/cli" + "github.com/integration-system/bellows" + "github.com/pkg/errors" + "github.com/tidwall/sjson" + "io/ioutil" + "isp-ctl/cfg" + "isp-ctl/command/utils" + "isp-ctl/flag" + "isp-ctl/service" + "os" +) + +func Set() cli.Command { + return cli.Command{ + Name: "set", + Usage: "set common configurations", + Action: set.action, + BashComplete: set.bashComplete, + } +} + +var set setCommand + +type setCommand struct{} + +func (g setCommand) action(ctx *cli.Context) { + if err := flag.CheckGlobal(ctx); err != nil { + utils.PrintError(err) + return + } + + ccName := ctx.Args().First() + pathObject := ctx.Args().Get(1) + changeObject := ctx.Args().Get(2) + + if ccName == "" { + utils.PrintError(errors.New("empty config name")) + return + } + + mapConfigByName, err := service.Config.GetMapCommonConfigByName() + if err != nil { + utils.PrintError(err) + return + } + + config, ok := mapConfigByName[ccName] + if !ok { + config = cfg.CommonConfig{ + Name: ccName, + } + } + + pathObject, err = utils.CheckPath(pathObject) + if err != nil { + utils.PrintError(err) + return + } + + if changeObject == "" { + bytes, err := ioutil.ReadAll(os.Stdin) + if err != nil { + utils.PrintError(err) + return + } + changeObject = string(bytes) + } + if changeObject == "" { + utils.PrintError(errors.New("expected argument")) + return + } + + if pathObject == "" { + utils.CreateUpdateCommonConfig(changeObject, config) + return + } else { + jsonObject, err := json.Marshal(config.Data) + if err != nil { + utils.PrintError(err) + return + } + + changeArgument := utils.ParseSetObject(changeObject) + if stringToChange, err := sjson.Set(string(jsonObject), pathObject, changeArgument); err != nil { + utils.PrintError(err) + return + } else { + utils.CreateUpdateCommonConfig(stringToChange, config) + return + } + } +} + +func (g setCommand) bashComplete(ctx *cli.Context) { + if err := flag.CheckGlobal(ctx); err != nil { + return + } + commonConfigs, err := service.Config.GetMapCommonConfigByName() + if err != nil { + return + } + switch ctx.NArg() { + case 0: + for _, config := range commonConfigs { + fmt.Println(config.Name) + } + case 1: + if config, ok := commonConfigs[ctx.Args().First()]; ok { + for key, _ := range bellows.Flatten(config.Data) { + fmt.Printf(".%v\n", key) + } + } + } +} diff --git a/command/commonConfig/unlink.go b/command/commonConfig/unlink.go new file mode 100644 index 0000000..0958c2a --- /dev/null +++ b/command/commonConfig/unlink.go @@ -0,0 +1,117 @@ +package commonConfig + +import ( + "fmt" + "github.com/codegangsta/cli" + "github.com/pkg/errors" + "isp-ctl/command/utils" + "isp-ctl/flag" + "isp-ctl/service" +) + +func UnLink() cli.Command { + return cli.Command{ + Name: "unlink", + Usage: "unlink common configurations from module configuration", + Action: unlink.action, + BashComplete: unlink.bashComplete, + } +} + +var unlink unlinkCommand + +type unlinkCommand struct{} + +func (g unlinkCommand) action(ctx *cli.Context) { + if err := flag.CheckGlobal(ctx); err != nil { + utils.PrintError(err) + return + } + + configName := ctx.Args().First() + moduleName := ctx.Args().Get(1) + + if configName == "" { + utils.PrintError(errors.New("need config name")) + return + } + + if moduleName == "" { + utils.PrintError(errors.New("need module name")) + return + } + + commonConfigs, err := service.Config.GetMapCommonConfigByName() + if err != nil { + utils.PrintError(err) + return + } + + config, ok := commonConfigs[configName] + if !ok { + utils.PrintError(errors.Errorf("common config %s not found", configName)) + return + } + + moduleConfig, _, err := service.Config.GetConfigurationAndJsonByModuleName(moduleName) + if err != nil { + utils.PrintError(err) + return + } + + ccIdNameMap := make(map[string]string) + for name, value := range commonConfigs { + ccIdNameMap[value.Id] = name + } + + needUnlink := false + for i, configId := range moduleConfig.CommonConfigs { + if config.Id == configId { + copy(moduleConfig.CommonConfigs[i:], moduleConfig.CommonConfigs[i+1:]) + moduleConfig.CommonConfigs[len(moduleConfig.CommonConfigs)-1] = "" + moduleConfig.CommonConfigs = moduleConfig.CommonConfigs[:len(moduleConfig.CommonConfigs)-1] + needUnlink = true + break + } + } + + if needUnlink { + if linked, err := service.Config.UpdateConfigAndGetLinkCommon(*moduleConfig); err != nil { + utils.PrintError(err) + } else { + for _, name := range linked { + fmt.Printf("[%s] ", ccIdNameMap[name]) + } + fmt.Printf("\n") + } + } else { + for _, name := range moduleConfig.CommonConfigs { + fmt.Printf("[%s] ", ccIdNameMap[name]) + } + fmt.Printf("\n") + } +} + +func (g unlinkCommand) bashComplete(ctx *cli.Context) { + if err := flag.CheckGlobal(ctx); err != nil { + return + } + commonConfigs, err := service.Config.GetMapCommonConfigByName() + if err != nil { + return + } + switch ctx.NArg() { + case 0: + for _, config := range commonConfigs { + fmt.Println(config.Name) + } + case 1: + if arrayOfModules, err := service.Config.GetAvailableConfigs(); err != nil { + return + } else { + for _, module := range arrayOfModules { + fmt.Println(module.Name) + } + } + } +} diff --git a/command/delete.go b/command/delete.go index 77df5e8..f473455 100644 --- a/command/delete.go +++ b/command/delete.go @@ -4,6 +4,7 @@ import ( "github.com/codegangsta/cli" "github.com/tidwall/sjson" "isp-ctl/bash" + "isp-ctl/command/utils" "isp-ctl/flag" "isp-ctl/service" ) @@ -23,7 +24,7 @@ type deleteCommand struct{} func (d deleteCommand) action(ctx *cli.Context) { if err := flag.CheckGlobal(ctx); err != nil { - printError(err) + utils.PrintError(err) return } moduleName := ctx.Args().First() @@ -31,24 +32,24 @@ func (d deleteCommand) action(ctx *cli.Context) { moduleConfiguration, jsonObject, err := service.Config.GetConfigurationAndJsonByModuleName(moduleName) if err != nil { - printError(err) + utils.PrintError(err) return } - pathObject, err = checkPath(pathObject) + pathObject, err = utils.CheckPath(pathObject) if err != nil { - printError(err) + utils.PrintError(err) return } if pathObject == "" { - createUpdateConfig("", moduleConfiguration) + utils.CreateUpdateConfig("", moduleConfiguration) } else { if stringToChange, err := sjson.Delete(string(jsonObject), pathObject); err != nil { - printError(err) + utils.PrintError(err) return } else { - createUpdateConfig(stringToChange, moduleConfiguration) + utils.CreateUpdateConfig(stringToChange, moduleConfiguration) } } } diff --git a/command/get.go b/command/get.go index f33ddad..d848f6d 100644 --- a/command/get.go +++ b/command/get.go @@ -1,11 +1,9 @@ package command import ( - "encoding/json" "github.com/codegangsta/cli" - "github.com/pkg/errors" - "github.com/tidwall/gjson" "isp-ctl/bash" + "isp-ctl/command/utils" "isp-ctl/flag" "isp-ctl/service" ) @@ -25,7 +23,7 @@ type getCommand struct{} func (g getCommand) action(ctx *cli.Context) { if err := flag.CheckGlobal(ctx); err != nil { - printError(err) + utils.PrintError(err) return } moduleName := ctx.Args().First() @@ -33,33 +31,19 @@ func (g getCommand) action(ctx *cli.Context) { moduleConfiguration, jsonObject, err := service.Config.GetConfigurationAndJsonByModuleName(moduleName) if err != nil { - printError(err) + utils.PrintError(err) return } - pathObject, err = checkPath(pathObject) + pathObject, err = utils.CheckPath(pathObject) if err != nil { - printError(err) + utils.PrintError(err) return } if pathObject == "" { - printAnswer(moduleConfiguration.Data) + utils.PrintAnswer(moduleConfiguration.Data) } else { - g.checkObject(jsonObject, pathObject) - } -} - -func (g getCommand) checkObject(jsonObject []byte, depth string) { - jsonString := gjson.Get(string(jsonObject), depth) - if jsonString.Raw == "" { - printError(errors.Errorf("Path '%s' not found\n", depth)) - } else { - var data interface{} - if err := json.Unmarshal([]byte(jsonString.Raw), &data); err != nil { - printError(err) - } else { - printAnswer(data) - } + utils.CheckObject(jsonObject, pathObject) } } diff --git a/command/schema.go b/command/schema.go index e646128..3ec19de 100644 --- a/command/schema.go +++ b/command/schema.go @@ -5,6 +5,7 @@ import ( "github.com/pkg/errors" "html/template" "isp-ctl/bash" + "isp-ctl/command/utils" "isp-ctl/flag" "isp-ctl/service" "isp-ctl/tmpl" @@ -29,7 +30,7 @@ type schemaCommand struct{} func (s schemaCommand) action(ctx *cli.Context) { if err := flag.CheckGlobal(ctx); err != nil { - printError(err) + utils.PrintError(err) return } moduleName := ctx.Args().First() @@ -40,11 +41,11 @@ func (s schemaCommand) action(ctx *cli.Context) { schema["schema"] = schemaConfig switch ctx.String(flag.OutPrint.Name) { case flag.OutPrintJsonValue: - printAnswer(schema) + utils.PrintAnswer(schema) case flag.OutPrintHtmlValue: s.printHtml(schema) default: - printError(errors.Errorf( + utils.PrintError(errors.Errorf( "invalid flag value, expected %s or %s", flag.OutPrintJsonValue, flag.OutPrintHtmlValue)) } } @@ -52,10 +53,10 @@ func (s schemaCommand) action(ctx *cli.Context) { func (s schemaCommand) getSchemaConfig(moduleName string) interface{} { if configuration, _, err := service.Config.GetConfigurationAndJsonByModuleName(moduleName); err != nil { - printError(err) + utils.PrintError(err) return nil } else if schema, err := service.Config.GetSchemaByModuleId(configuration.ModuleId); err != nil { - printError(err) + utils.PrintError(err) return nil } else { return schema @@ -64,11 +65,11 @@ func (s schemaCommand) getSchemaConfig(moduleName string) interface{} { func (s schemaCommand) printHtml(schema map[string]interface{}) { if temp, err := template.New("template").Parse(tmpl.HtmlFile); err != nil { - printError(err) + utils.PrintError(err) return } else { if err := temp.ExecuteTemplate(os.Stdout, "template", schema); err != nil { - printError(err) + utils.PrintError(err) return } } diff --git a/command/set.go b/command/set.go index 6595403..fe9fe76 100644 --- a/command/set.go +++ b/command/set.go @@ -1,12 +1,12 @@ package command import ( - "encoding/json" "github.com/codegangsta/cli" "github.com/pkg/errors" "github.com/tidwall/sjson" "io/ioutil" "isp-ctl/bash" + "isp-ctl/command/utils" "isp-ctl/flag" "isp-ctl/service" "os" @@ -27,7 +27,7 @@ type setCommand struct{} func (s setCommand) action(ctx *cli.Context) { if err := flag.CheckGlobal(ctx); err != nil { - printError(err) + utils.PrintError(err) return } @@ -37,79 +37,40 @@ func (s setCommand) action(ctx *cli.Context) { moduleConfiguration, jsonObject, err := service.Config.GetConfigurationAndJsonByModuleName(moduleName) if err != nil { - printError(err) + utils.PrintError(err) return } - pathObject, err = checkPath(pathObject) + pathObject, err = utils.CheckPath(pathObject) if err != nil { - printError(err) + utils.PrintError(err) return } if changeObject == "" { bytes, err := ioutil.ReadAll(os.Stdin) if err != nil { - printError(err) + utils.PrintError(err) return } changeObject = string(bytes) } if changeObject == "" { - printError(errors.New("expected argument")) + utils.PrintError(errors.New("expected argument")) return } if pathObject == "" { - createUpdateConfig(changeObject, moduleConfiguration) + utils.CreateUpdateConfig(changeObject, moduleConfiguration) return } else { - changeArgument := s.parseObject(changeObject) + changeArgument := utils.ParseSetObject(changeObject) if stringToChange, err := sjson.Set(string(jsonObject), pathObject, changeArgument); err != nil { - printError(err) + utils.PrintError(err) return } else { - createUpdateConfig(stringToChange, moduleConfiguration) + utils.CreateUpdateConfig(stringToChange, moduleConfiguration) return } } } - -func (s setCommand) parseObject(argument string) interface{} { - tryParse := []byte(argument) - if tryParse[0] == '"' && tryParse[len(tryParse)-1] == '"' { - tryParse = tryParse[1 : len(tryParse)-1] - return string(tryParse) - } - - if argument == "null" { - return nil - } - - mapStringInterface := make(map[string]interface{}) - if err := json.Unmarshal(tryParse, &mapStringInterface); err == nil { - return mapStringInterface - } - - arrayOfObject := make([]interface{}, 0) - if err := json.Unmarshal(tryParse, &arrayOfObject); err == nil { - return arrayOfObject - } - - var integer int64 - if err := json.Unmarshal(tryParse, &integer); err == nil { - return integer - } - - var float float64 - if err := json.Unmarshal(tryParse, &float); err == nil { - return float - } - - var flag bool - if err := json.Unmarshal(tryParse, &flag); err == nil { - return flag - } - - return argument -} diff --git a/command/status.go b/command/status.go index 95b9458..db7a375 100644 --- a/command/status.go +++ b/command/status.go @@ -4,6 +4,7 @@ import ( "fmt" "github.com/codegangsta/cli" "github.com/olekukonko/tablewriter" + "isp-ctl/command/utils" "isp-ctl/flag" "isp-ctl/service" "os" @@ -32,11 +33,11 @@ type statusCommand struct{} func (statusCommand) action(ctx *cli.Context) { if err := flag.CheckGlobal(ctx); err != nil { - printError(err) + utils.PrintError(err) return } if arrayOfModules, err := service.Config.GetAvailableConfigs(); err != nil { - printError(err) + utils.PrintError(err) } else { table := tablewriter.NewWriter(os.Stdout) table.SetBorders(tablewriter.Border{Left: false, Top: false, Right: false, Bottom: false}) diff --git a/command/utils/common.go b/command/utils/common.go new file mode 100644 index 0000000..b5674a7 --- /dev/null +++ b/command/utils/common.go @@ -0,0 +1,94 @@ +package utils + +import ( + "encoding/json" + "fmt" + "github.com/pkg/errors" + "github.com/tidwall/gjson" + "isp-ctl/service" + "strings" +) + +func CheckPath(pathObject string) (string, error) { + str := strings.Split(pathObject, ".") + pathObject = "" + if len(str) == 1 || str[0] != "" { + return pathObject, errors.New("path must start with '.'") + } + for key, value := range str { + if key == 0 { + continue + } + if key == 1 { + pathObject = fmt.Sprintf("%s", value) + continue + } + pathObject = fmt.Sprintf("%s.%s", pathObject, value) + } + return pathObject, nil +} + +func PrintAnswer(data interface{}) { + if answer, err := json.MarshalIndent(data, "", " "); err != nil { + PrintError(err) + } else { + service.ColorService.Print(answer) + } +} + +func PrintError(err error) { + fmt.Println("ERROR:", err) +} + +func ParseSetObject(argument string) interface{} { + tryParse := []byte(argument) + if tryParse[0] == '"' && tryParse[len(tryParse)-1] == '"' { + tryParse = tryParse[1 : len(tryParse)-1] + return string(tryParse) + } + + if argument == "null" { + return nil + } + + mapStringInterface := make(map[string]interface{}) + if err := json.Unmarshal(tryParse, &mapStringInterface); err == nil { + return mapStringInterface + } + + arrayOfObject := make([]interface{}, 0) + if err := json.Unmarshal(tryParse, &arrayOfObject); err == nil { + return arrayOfObject + } + + var integer int64 + if err := json.Unmarshal(tryParse, &integer); err == nil { + return integer + } + + var float float64 + if err := json.Unmarshal(tryParse, &float); err == nil { + return float + } + + var flag bool + if err := json.Unmarshal(tryParse, &flag); err == nil { + return flag + } + + return argument +} + +func CheckObject(jsonObject []byte, depth string) { + jsonString := gjson.Get(string(jsonObject), depth) + if jsonString.Raw == "" { + PrintError(errors.Errorf("path '%s' not found\n", depth)) + } else { + var data interface{} + if err := json.Unmarshal([]byte(jsonString.Raw), &data); err != nil { + PrintError(err) + } else { + PrintAnswer(data) + } + } +} diff --git a/command/utils/common_config.go b/command/utils/common_config.go new file mode 100644 index 0000000..af4780e --- /dev/null +++ b/command/utils/common_config.go @@ -0,0 +1,14 @@ +package utils + +import ( + "isp-ctl/cfg" + "isp-ctl/service" +) + +func CreateUpdateCommonConfig(stringToChange string, configuration cfg.CommonConfig) { + if answer, err := service.Config.CreateUpdateCommonConfig(stringToChange, configuration); err != nil { + PrintError(err) + } else if answer != nil { + PrintAnswer(answer) + } +} diff --git a/command/utils/config.go b/command/utils/config.go new file mode 100644 index 0000000..b18c8df --- /dev/null +++ b/command/utils/config.go @@ -0,0 +1,14 @@ +package utils + +import ( + "isp-ctl/cfg" + "isp-ctl/service" +) + +func CreateUpdateConfig(stringToChange string, configuration *cfg.Config) { + if answer, err := service.Config.CreateUpdateConfig(stringToChange, configuration); err != nil { + PrintError(err) + } else if answer != nil { + PrintAnswer(answer) + } +} diff --git a/main.go b/main.go index 3c78cf2..2746ea3 100644 --- a/main.go +++ b/main.go @@ -41,6 +41,7 @@ func initCommands() { command.Set(), command.Delete(), command.Schema(), + command.CommonConfig(), } app.BashComplete = func(context *cli.Context) { for _, command := range app.Commands { diff --git a/service/common.go b/service/common.go index f446e1a..ff99be4 100644 --- a/service/common.go +++ b/service/common.go @@ -1,6 +1,11 @@ package service -var configPath string +import "isp-ctl/cfg" + +var ( + configClient = cfg.NewConfigClient() + configPath string +) func SetConfigurationPath(path string) { configPath = path diff --git a/service/config.go b/service/config.go index b386d86..79294bb 100644 --- a/service/config.go +++ b/service/config.go @@ -11,28 +11,21 @@ import ( "isp-ctl/cfg" ) -var ( - configClient = cfg.NewConfigClient() - Config = &configService{} -) +var Config configService type configService struct { UnsafeEnable bool } -func (c *configService) ReceiveConfiguration(host, uuid string) error { +func (c configService) ReceiveConfiguration(host, uuid string) error { return configClient.ReceiveConfig(host, uuid) } -func (c *configService) GetAvailableConfigs() ([]cfg.ModuleInfo, error) { - if moduleInfo, err := configClient.GetAvailableConfigs(); err != nil { - return nil, err - } else { - return moduleInfo, nil - } +func (c configService) GetAvailableConfigs() ([]cfg.ModuleInfo, error) { + return configClient.GetAvailableConfigs() } -func (c *configService) GetConfigurationAndJsonByModuleName(moduleName string) (*cfg.Config, []byte, error) { +func (c configService) GetConfigurationAndJsonByModuleName(moduleName string) (*cfg.Config, []byte, error) { if moduleName == "" { return nil, nil, errors.New("need module name") } @@ -52,7 +45,7 @@ func (c *configService) GetConfigurationAndJsonByModuleName(moduleName string) ( } } -func (c *configService) GetSchemaByModuleId(moduleId int32) (schema.Schema, error) { +func (c configService) GetSchemaByModuleId(moduleId string) (schema.Schema, error) { if configSchema, err := configClient.GetSchemaByModuleId(moduleId); err != nil { return nil, err } else { @@ -61,7 +54,7 @@ func (c *configService) GetSchemaByModuleId(moduleId int32) (schema.Schema, erro } } -func (c *configService) CreateUpdateConfig(stringToChange string, configuration *cfg.Config) (map[string]interface{}, error) { +func (c configService) CreateUpdateConfig(stringToChange string, configuration *cfg.Config) (map[string]interface{}, error) { newData := make(map[string]interface{}) if stringToChange != "" { if err := json.Unmarshal([]byte(stringToChange), &newData); err != nil { @@ -83,7 +76,47 @@ func (c *configService) CreateUpdateConfig(stringToChange string, configuration } } -func (c *configService) checkSchema(moduleId int32, object map[string]interface{}) (bool, error) { +func (c configService) UpdateConfigAndGetLinkCommon(configuration cfg.Config) ([]string, error) { + if resp, err := configClient.CreateUpdateConfig(configuration); err != nil { + return nil, err + } else { + return resp.CommonConfigs, nil + } +} + +func (c configService) GetMapCommonConfigByName() (map[string]cfg.CommonConfig, error) { + collection, err := configClient.GetCommonConfigs([]string{}) + if err != nil { + return nil, err + } + response := make(map[string]cfg.CommonConfig) + for _, config := range collection { + response[config.Name] = config + } + return response, nil +} + +func (c configService) CreateUpdateCommonConfig(stringToChange string, config cfg.CommonConfig) (map[string]interface{}, error) { + newData := make(map[string]interface{}) + if stringToChange != "" { + if err := json.Unmarshal([]byte(stringToChange), &newData); err != nil { + return nil, err + } + } + + config.Data = newData + if resp, err := configClient.CreateUpdateCommonConfig(config); err != nil { + return nil, err + } else { + return resp.Data, nil + } +} + +func (c configService) DeleteCommonConfig(configId string) (int, error) { + return configClient.DeleteCommonConfig([]string{configId}) +} + +func (c configService) checkSchema(moduleId string, object map[string]interface{}) (bool, error) { if c.UnsafeEnable { return true, nil }