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/README.md b/README.md index b8bc2aa..061f118 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,29 @@ # ispctl -## Описание Консольная утилита для получения и переопределения конфигруации модулей isp +* [Требования](#Требования) +* [Установка](#Установка) +* [Конифгурация](#Конифгурация) +* [Использование](#Использование) +* [Описание](#Описание) +* [Примеры](#Пример) + - [ispctl status](#ispctl-status) + - [ispctl get](#ispctl-get) + - [ispctl set](#ispctl-set) + - [ispctl delete](#ispctl-delete) + - [ispctl schema](#ispctl-schema) + - [ispctl common](#ispctl-common) + * [set](#ispctl-common-set) + * [get](#ispctl-common-get) + * [delete](#ispctl-common-delete) + * [remove](#ispctl-common-remove) + * [link](#ispctl-common-link) + * [unlink](#ispctl-common-unlink) + * [contain](#ispctl-common-contain) + - [запрос с флагами](#Запрос-с-флагами) + + ## Требования * Linux @@ -25,11 +46,13 @@ instanceUuid: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx ## Использование ```bash ispctl [flag...] status -ispctl [flag...] get module_name property_path +ispctl [flag...] get module_name property_path [local_flag] ispctl [flag...] set module_name property_path [new_object] ispctl [flag...] delete module_name property_path ispctl [flag...] schema module_name [local_flag] +ispctl [flag...] common sub_command ``` + ## Описание | Команды | Описание | @@ -39,6 +62,7 @@ ispctl [flag...] schema module_name [local_flag] | `set` | изменяет объект конфигурации указанного модуля | | `delete` | удаляет объект конфигурации указанного модуля | | `schema` | возвращает схему конфигурации указанного модуля | +| `common` | комманда для взаимодействие с общими конфигурациями | | | | | Флаги | Параметры | Описание | @@ -51,15 +75,37 @@ ispctl [flag...] schema module_name [local_flag] | Аргументы | Описание | |-----------------|-------------------------------------------------------------------------------------------------------------| -| `module_name` | Модуль с которым происходит взаимодействие | +| `module_name` | Название модуля с которым происходит взаимодействие | +| `proprtry_path` | Путь к объекту конфигурации, при значении `.` работа происходит со всей конфигурацией модуля | +| `new_object` | Новый объект, значение должно быть экранировано с помощью `' '`, при отсутсвии ожидается ввод из stdin | +| | | + +| Локальные флаги | Параметры | Команды | Описание | +|-----------------|-----------|---------|---------------------------------------------------------------------------------------------------------------------------------| +| `-o` | string | schema | определяет формат вывода схемы в stdout; по умолчанию `json`; возможные значения `json`, `html` | +| `-full` | bool | get | осуществляет взаимодействие с объектами конфигурации модуля с учетом объектом общих конфигураций, которые имеют связь с модулем | +| | | | | + +### sub_command +#### common +```bash +ispctl [flag...] common set config_name property_path [new_object] +ispctl [flag...] common get [config_name] property_path +ispctl [flag...] common delete config_name property_path +ispctl [flag...] common remove config_name +ispctl [flag...] common link config_name module_name +ispctl [flag...] common unlink config_name module_name +ispctl [flag...] common contain config_name +``` + +| Аргументы | Описание | +|-----------------|-------------------------------------------------------------------------------------------------------------| +| `config_name` | Названия конфига с которым происходит взаимодействие | +| `module_name` | Название модуля с которым происходит взаимодействие | | `proprtry_path` | Путь к объекту конфигурации, при значении `.` работа происходит со всей конфигурацией модуля | | `new_object` | Новый объект, значение должно быть экранировано с помощью `' '`, при отсутсвии ожидается ввод из stdin | | | | -| Локальные флаги | Параметры | Описание | -|-----------------|-----------|--------------------------------------------------------------------------------------------------| -| `-o` | string | определяет формат вывода схемы в stdout; по умолчанию `json`; возможные значения `json`, `html` | -| | | | ## Пример ### ispctl status @@ -318,6 +364,106 @@ ispctl schema example -o html ``` +### ispctl common +#### ispctl common get +Возвращает список названий общих конфигураций или, если в первом аргументе указано название общей конфигурации, возвращает объект общей конфигурации по указанному пути + +Запрос +```bash +ispctl common get +``` +Ответ +```bash +test b c +``` +Запрос +```bash +ispctl common get test . +``` +Ответ +```bash +{ + "test": null +} +``` +#### ispctl common set +Добавляет объект в общую конфигурацию по указанному пути + +Запрос +```bash +ispctl common set test .test '{"a":"a","b":"b"}' +``` +Ответ +```bash +{ + "test": { + "a": "a", + "b": "b" + } +} +``` +#### ispctl common delete +Удаляет объект из общей конфигурации по указанному пути + +Запрос +```bash +ispctl common delete test .test.a +``` +Ответ +```bash +{ + "test": { + "b": "b" + } +} +``` +#### ispctl common link +Связывает 'common_config' к конфигурации модуля по 'module_name'. Возвращает список общих конфигураций, которые связаны с модулем + +Запрос +```bash +ispctl common link test module_example +``` +Ответ +```bash +[test] [second_common_config] +``` +#### ispctl common remove +Удаляет объект общий конфигурации, если он не связан с конфигурациями модулей. Если общая конфигурация имеет связи, выводит список модулей с которыми установлена связь + +Запрос +```bash +ispctl common remove test +``` +Ответ +```bash +config [test] not deleted, need unlink in next modules: +[module_example] +``` +#### ispctl common unlink +Отвязывает 'common_config' от конфигурации модуля по 'module_name'. Возвращает список общих конфигураций, которые связаны с модулем + +Запрос +```bash +ispctl common unlink test module_example +``` +Ответ +Ответ +```bash +[second_common_config] +``` +#### ispctl common contain +Возвращает список названий модулей, с которыми имеет связь общая конфигурация + +Запрос +```bash +isp-ctl common contain second_common_config +``` +Ответ +Ответ +```bash +[module_example] +``` ### Запрос с флагами Запрос diff --git a/bash/autocomplete.go b/bash/autocomplete.go index 541f307..a7461b3 100644 --- a/bash/autocomplete.go +++ b/bash/autocomplete.go @@ -8,45 +8,76 @@ import ( "isp-ctl/service" ) -var ( - ModuleNameAndConfigurationPath = bashAction{enableConfigurationBash: true} - ModuleName = bashAction{enableConfigurationBash: false} +const ( + CommonConfigName bashArg = "config_name" + CommonConfigData bashArg = "config_data" + ModuleName bashArg = "module_name" + ModuleData bashArg = "module_data" + Empty bashArg = "empty" ) -type ( - bashAction struct{ enableConfigurationBash bool } -) +type bashArg string -func (b bashAction) Complete(ctx *cli.Context) { +type bashCommand struct { + first bashArg + second bashArg +} + +func Get(first bashArg, second bashArg) *bashCommand { + return &bashCommand{ + first: first, + second: second, + } +} + +func (c bashCommand) Complete(ctx *cli.Context) { if err := flag.CheckGlobal(ctx); err != nil { return } + commonConfigs, err := service.Config.GetMapNameCommonConfig() + if err != nil { + return + } switch ctx.NArg() { case 0: - b.moduleNameHelper() + switch c.first { + case ModuleName: + if arrayOfModules, err := service.Config.GetAvailableConfigs(); err != nil { + return + } else { + for _, module := range arrayOfModules { + fmt.Println(module.Name) + } + } + case CommonConfigName: + for _, config := range commonConfigs { + fmt.Println(config.Name) + } + } case 1: - if b.enableConfigurationBash { - b.configurationPathHelper(ctx.Args().First(), ctx.Args().Get(1)) - } - } -} - -func (bashAction) moduleNameHelper() { - if arrayOfModules, err := service.Config.GetAvailableConfigs(); err != nil { - return - } else { - for _, module := range arrayOfModules { - fmt.Println(module.Name) - } - } -} - -func (bashAction) configurationPathHelper(moduleName, path string) { - if moduleConfiguration, _, err := service.Config.GetConfigurationAndJsonByModuleName(moduleName); err != nil { - return - } else { - for key, _ := range bellows.Flatten(moduleConfiguration.Data) { - fmt.Printf(".%v\n", key) + switch c.second { + case CommonConfigData: + if config, ok := commonConfigs[ctx.Args().First()]; ok { + for key, _ := range bellows.Flatten(config.Data) { + fmt.Printf(".%v\n", key) + } + } + case ModuleName: + if arrayOfModules, err := service.Config.GetAvailableConfigs(); err != nil { + return + } else { + for _, module := range arrayOfModules { + fmt.Println(module.Name) + } + } + case ModuleData: + if moduleConfiguration, err := service.Config.GetConfigurationByModuleName(ctx.Args().First()); err != nil { + return + } else { + for key, _ := range bellows.Flatten(moduleConfiguration.Data) { + fmt.Printf(".%v\n", key) + } + } } } } diff --git a/cfg/domain.go b/cfg/domain.go index 5160874..57411f2 100644 --- a/cfg/domain.go +++ b/cfg/domain.go @@ -7,21 +7,32 @@ 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{} + Unsafe bool +} + +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 +47,7 @@ type Connection struct { } type ModuleInfo struct { - Id int32 + Id string Name string Active bool CreatedAt time.Time @@ -48,10 +59,26 @@ 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 bool + Links Links +} + +type Links map[string][]string + +type identityRequest struct { + Id string +} + +type CompileConfigs struct { + Data map[string]interface{} + CommonConfigsIdList []string +} diff --git a/cfg/method_name.go b/cfg/method_name.go index 62ddeb0..730a1ad 100644 --- a/cfg/method_name.go +++ b/cfg/method_name.go @@ -1,8 +1,13 @@ 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" + getLinksCommonConfig = "config/common_config/get_links" + compileCommonConfigs = "config/common_config/compile" ) diff --git a/cfg/methods.go b/cfg/methods.go index 7a64d28..7f4f0b0 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,58 @@ 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(id string) (*Deleted, error) { + request := identityRequest{Id: id} + response := new(Deleted) + err := c.cli.Invoke(deleteCommonConfig, callerId, request, response, backend.WithMetadata(c.headers)) + if err != nil { + return nil, c.errorHandler(err) + } else { + return response, nil + } +} + +func (c *configClient) GetLinksCommonConfig(id string) (*Links, error) { + request := identityRequest{Id: id} + response := new(Links) + err := c.cli.Invoke(getLinksCommonConfig, callerId, request, response, backend.WithMetadata(c.headers)) + if err != nil { + return nil, c.errorHandler(err) + } else { + return response, nil + } +} + +func (c *configClient) CompileCommonConfigs(request CompileConfigs) (map[string]interface{}, error) { + response := make(map[string]interface{}) + err := c.cli.Invoke(compileCommonConfigs, callerId, request, &response, backend.WithMetadata(c.headers)) + if err != nil { + return nil, c.errorHandler(err) + } else { + return response, 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..a88ca10 100644 --- a/command/common.go +++ b/command/common.go @@ -1,49 +1,45 @@ package command import ( - "encoding/json" "fmt" - "github.com/pkg/errors" - "isp-ctl/cfg" - "isp-ctl/service" - "strings" + "github.com/codegangsta/cli" + "isp-ctl/command/common_config" ) -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{ + common_config.Get(), + common_config.Set(), + common_config.Delete(), + common_config.Remove(), + common_config.Link(), + common_config.UnLink(), + common_config.Contain(), + }, } - 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/common_config/contain.go b/command/common_config/contain.go new file mode 100644 index 0000000..f76cffe --- /dev/null +++ b/command/common_config/contain.go @@ -0,0 +1,55 @@ +package common_config + +import ( + "fmt" + "github.com/codegangsta/cli" + "github.com/pkg/errors" + "isp-ctl/bash" + "isp-ctl/command/utils" + "isp-ctl/flag" + "isp-ctl/service" +) + +func Contain() cli.Command { + return cli.Command{ + Name: "contain", + Usage: "availability common configuration in module", + Action: contain.action, + BashComplete: bash.Get(bash.CommonConfigName, bash.Empty).Complete, + } +} + +var contain containCommand + +type containCommand struct{} + +func (g containCommand) action(ctx *cli.Context) { + if err := flag.CheckGlobal(ctx); err != nil { + utils.PrintError(err) + return + } + + configName := ctx.Args().First() + + if configName == "" { + utils.PrintError(errors.New("empty common config name")) + return + } + + config, err := service.Config.GetCommonConfigByName(configName) + if err != nil { + utils.PrintError(err) + return + } + + links, err := service.Config.GetLinksCommonConfig(config.Id) + if err != nil { + utils.PrintError(err) + } else { + fmt.Printf("config [%s] linked with next modules:\n", configName) + for _, link := range links { + fmt.Printf("[%s] ", link) + } + fmt.Printf("\n") + } +} diff --git a/command/common_config/delete.go b/command/common_config/delete.go new file mode 100644 index 0000000..0b9127a --- /dev/null +++ b/command/common_config/delete.go @@ -0,0 +1,67 @@ +package common_config + +import ( + "encoding/json" + "github.com/codegangsta/cli" + "github.com/pkg/errors" + "github.com/tidwall/sjson" + "isp-ctl/bash" + "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: bash.Get(bash.CommonConfigName, bash.CommonConfigData).Complete, + } +} + +var deleteComm deleteCommand + +type deleteCommand struct{} + +func (g deleteCommand) action(ctx *cli.Context) { + if err := flag.CheckGlobal(ctx); err != nil { + utils.PrintError(err) + return + } + + configName := ctx.Args().First() + pathObject := ctx.Args().Get(1) + + if configName == "" { + utils.PrintError(errors.New("empty config name")) + return + } + + pathObject, err := utils.CheckPath(pathObject) + if err != nil { + utils.PrintError(err) + return + } + + config, err := service.Config.GetCommonConfigByName(configName) + if err != nil { + utils.PrintError(err) + 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) + } + } +} diff --git a/command/common_config/get.go b/command/common_config/get.go new file mode 100644 index 0000000..c0a51ae --- /dev/null +++ b/command/common_config/get.go @@ -0,0 +1,70 @@ +package common_config + +import ( + "encoding/json" + "fmt" + "github.com/codegangsta/cli" + "github.com/pkg/errors" + "isp-ctl/bash" + "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: bash.Get(bash.CommonConfigName, bash.CommonConfigData).Complete, + } +} + +var get getCommand + +type getCommand struct{} + +func (g getCommand) action(ctx *cli.Context) { + if err := flag.CheckGlobal(ctx); err != nil { + utils.PrintError(err) + return + } + + configName := ctx.Args().First() + pathObject := ctx.Args().Get(1) + + commonConfigs, err := service.Config.GetMapNameCommonConfig() + if err != nil { + utils.PrintError(err) + return + } + + if configName == "" { + fmt.Printf("available next common configs:\n") + 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[configName] + if !ok { + utils.PrintError(errors.Errorf("common config [%s] not found", configName)) + 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) + } +} diff --git a/command/common_config/link.go b/command/common_config/link.go new file mode 100644 index 0000000..2564981 --- /dev/null +++ b/command/common_config/link.go @@ -0,0 +1,36 @@ +package common_config + +import ( + "github.com/codegangsta/cli" + "isp-ctl/bash" + "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: bash.Get(bash.CommonConfigName, bash.ModuleName).Complete, + } +} + +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 err := service.Config.LinkCommonConfigToModule(configName, moduleName); err != nil { + utils.PrintError(err) + } +} diff --git a/command/common_config/remove.go b/command/common_config/remove.go new file mode 100644 index 0000000..f9c4f78 --- /dev/null +++ b/command/common_config/remove.go @@ -0,0 +1,56 @@ +package common_config + +import ( + "fmt" + "github.com/codegangsta/cli" + "github.com/pkg/errors" + "isp-ctl/bash" + "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: bash.Get(bash.CommonConfigName, bash.Empty).Complete, + } +} + +var remove removeCommand + +type removeCommand struct{} + +func (g removeCommand) action(ctx *cli.Context) { + if err := flag.CheckGlobal(ctx); err != nil { + utils.PrintError(err) + return + } + + configName := ctx.Args().First() + + if configName == "" { + utils.PrintError(errors.New("empty common config name")) + return + } + + config, err := service.Config.GetCommonConfigByName(configName) + if err != nil { + utils.PrintError(err) + return + } + + links, deleted, err := service.Config.DeleteCommonConfig(config.Id) + if err != nil { + utils.PrintError(err) + return + } + + if deleted { + fmt.Printf("config [%s] deleted\n", config.Name) + } else { + fmt.Printf("config [%s] not deleted, need unlink in next modules:\n%v\n", config.Name, links) + } +} diff --git a/command/common_config/set.go b/command/common_config/set.go new file mode 100644 index 0000000..d0753a5 --- /dev/null +++ b/command/common_config/set.go @@ -0,0 +1,83 @@ +package common_config + +import ( + "encoding/json" + "github.com/codegangsta/cli" + "github.com/pkg/errors" + "github.com/tidwall/sjson" + "isp-ctl/bash" + "isp-ctl/cfg" + "isp-ctl/command/utils" + "isp-ctl/flag" + "isp-ctl/service" +) + +func Set() cli.Command { + return cli.Command{ + Name: "set", + Usage: "set common configurations", + Action: set.action, + BashComplete: bash.Get(bash.CommonConfigName, bash.CommonConfigData).Complete, + } +} + +var set setCommand + +type setCommand struct{} + +func (g setCommand) action(ctx *cli.Context) { + if err := flag.CheckGlobal(ctx); err != nil { + utils.PrintError(err) + return + } + + configName := ctx.Args().First() + pathObject := ctx.Args().Get(1) + changeObject := ctx.Args().Get(2) + + if configName == "" { + utils.PrintError(errors.New("empty config name")) + return + } + + mapConfigByName, err := service.Config.GetMapNameCommonConfig() + if err != nil { + utils.PrintError(err) + return + } + + config, ok := mapConfigByName[configName] + if !ok { + config = cfg.CommonConfig{ + Name: configName, + } + } + + pathObject, err = utils.CheckPath(pathObject) + if err != nil { + utils.PrintError(err) + return + } + + changeObject, err = utils.CheckChangeObject(changeObject) + if err != nil { + utils.PrintError(err) + return + } + + if pathObject == "" { + utils.CreateUpdateCommonConfig(changeObject, config) + } 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) + } else { + utils.CreateUpdateCommonConfig(stringToChange, config) + } + } +} diff --git a/command/common_config/unlink.go b/command/common_config/unlink.go new file mode 100644 index 0000000..e776c6a --- /dev/null +++ b/command/common_config/unlink.go @@ -0,0 +1,36 @@ +package common_config + +import ( + "github.com/codegangsta/cli" + "isp-ctl/bash" + "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: bash.Get(bash.CommonConfigName, bash.ModuleName).Complete, + } +} + +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 err := service.Config.UnlinkCommonConfigFromModule(configName, moduleName); err != nil { + utils.PrintError(err) + } +} diff --git a/command/delete.go b/command/delete.go index 77df5e8..3183c8b 100644 --- a/command/delete.go +++ b/command/delete.go @@ -1,9 +1,11 @@ package command import ( + "encoding/json" "github.com/codegangsta/cli" "github.com/tidwall/sjson" "isp-ctl/bash" + "isp-ctl/command/utils" "isp-ctl/flag" "isp-ctl/service" ) @@ -13,7 +15,7 @@ func Delete() cli.Command { Name: "delete", Usage: "delete configuration by module_name", Action: deleteComm.action, - BashComplete: bash.ModuleNameAndConfigurationPath.Complete, + BashComplete: bash.Get(bash.ModuleName, bash.ModuleData).Complete, } } @@ -23,32 +25,37 @@ 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() pathObject := ctx.Args().Get(1) - moduleConfiguration, jsonObject, err := service.Config.GetConfigurationAndJsonByModuleName(moduleName) + moduleConfiguration, err := service.Config.GetConfigurationByModuleName(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) + jsonObject, err := json.Marshal(moduleConfiguration.Data) + if err != nil { + utils.PrintError(err) return + } + + if stringToChange, err := sjson.Delete(string(jsonObject), pathObject); err != nil { + utils.PrintError(err) } else { - createUpdateConfig(stringToChange, moduleConfiguration) + utils.CreateUpdateConfig(stringToChange, moduleConfiguration) } } } diff --git a/command/get.go b/command/get.go index f33ddad..d5cbb55 100644 --- a/command/get.go +++ b/command/get.go @@ -3,9 +3,8 @@ 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" ) @@ -15,7 +14,10 @@ func Get() cli.Command { Name: "get", Usage: "get configuration by module_name", Action: get.action, - BashComplete: bash.ModuleNameAndConfigurationPath.Complete, + BashComplete: bash.Get(bash.ModuleName, bash.ModuleData).Complete, + Flags: []cli.Flag{ + flag.WithCommonConfig, + }, } } @@ -25,41 +27,40 @@ 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() pathObject := ctx.Args().Get(1) - moduleConfiguration, jsonObject, err := service.Config.GetConfigurationAndJsonByModuleName(moduleName) + config, err := service.Config.GetConfigurationByModuleName(moduleName) if err != nil { - printError(err) + utils.PrintError(err) return } - pathObject, err = checkPath(pathObject) + data := config.Data + if ctx.Bool(flag.WithCommonConfig.Name) { + if data, err = service.Config.CompileDataWithCommonConfigs(data, config.CommonConfigs); err != nil { + utils.PrintError(err) + return + } + } + + pathObject, err = utils.CheckPath(pathObject) if err != nil { - printError(err) + utils.PrintError(err) return } if pathObject == "" { - printAnswer(moduleConfiguration.Data) + utils.PrintAnswer(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) + jsonObject, err := json.Marshal(data) + if err != nil { + utils.PrintError(err) + return } + utils.CheckObject(jsonObject, pathObject) } } diff --git a/command/schema.go b/command/schema.go index e646128..843d79f 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" @@ -19,7 +20,7 @@ func Schema() cli.Command { Flags: []cli.Flag{ flag.OutPrint, }, - BashComplete: bash.ModuleName.Complete, + BashComplete: bash.Get(bash.ModuleName, bash.Empty).Complete, } } @@ -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,22 +41,22 @@ 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( - "invalid flag value, expected %s or %s", flag.OutPrintJsonValue, flag.OutPrintHtmlValue)) + utils.PrintError(errors.Errorf( + "invalid flag value, expected [%s] or [%s]", flag.OutPrintJsonValue, flag.OutPrintHtmlValue)) } } } func (s schemaCommand) getSchemaConfig(moduleName string) interface{} { - if configuration, _, err := service.Config.GetConfigurationAndJsonByModuleName(moduleName); err != nil { - printError(err) + if configuration, err := service.Config.GetConfigurationByModuleName(moduleName); err != nil { + 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..9815cf9 100644 --- a/command/set.go +++ b/command/set.go @@ -3,13 +3,11 @@ 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" ) func Set() cli.Command { @@ -17,7 +15,7 @@ func Set() cli.Command { Name: "set", Usage: "set configuration by module_name", Action: set.action, - BashComplete: bash.ModuleNameAndConfigurationPath.Complete, + BashComplete: bash.Get(bash.ModuleName, bash.ModuleData).Complete, } } @@ -27,7 +25,7 @@ type setCommand struct{} func (s setCommand) action(ctx *cli.Context) { if err := flag.CheckGlobal(ctx); err != nil { - printError(err) + utils.PrintError(err) return } @@ -35,81 +33,38 @@ func (s setCommand) action(ctx *cli.Context) { pathObject := ctx.Args().Get(1) changeObject := ctx.Args().Get(2) - moduleConfiguration, jsonObject, err := service.Config.GetConfigurationAndJsonByModuleName(moduleName) + config, err := service.Config.GetConfigurationByModuleName(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) - return - } - changeObject = string(bytes) - } - if changeObject == "" { - printError(errors.New("expected argument")) + changeObject, err = utils.CheckChangeObject(changeObject) + if err != nil { + utils.PrintError(err) return } if pathObject == "" { - createUpdateConfig(changeObject, moduleConfiguration) - return + utils.CreateUpdateConfig(changeObject, config) } else { - changeArgument := s.parseObject(changeObject) + 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 { - printError(err) - return + utils.PrintError(err) } else { - createUpdateConfig(stringToChange, moduleConfiguration) - return + utils.CreateUpdateConfig(stringToChange, config) } } } - -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..18b6e46 --- /dev/null +++ b/command/utils/common.go @@ -0,0 +1,112 @@ +package utils + +import ( + "encoding/json" + "fmt" + "github.com/pkg/errors" + "github.com/tidwall/gjson" + "io/ioutil" + "isp-ctl/service" + "os" + "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 CheckChangeObject(changeObject string) (string, error) { + if changeObject == "" { + bytes, err := ioutil.ReadAll(os.Stdin) + if err != nil { + return "", err + } + changeObject = string(bytes) + } + if changeObject == "" { + return "", errors.New("expected argument") + } else { + return changeObject, 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) + os.Exit(-1) +} + +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/flag/description.go b/flag/description.go index 85a792d..5330fbd 100644 --- a/flag/description.go +++ b/flag/description.go @@ -18,6 +18,9 @@ const ( outPrintName = "o" OutPrintJsonValue = "json" OutPrintHtmlValue = "html" + + withCommonConfigName = "full" + withCommonConfigUsage = "compile data with common configs" ) var ( diff --git a/flag/structure.go b/flag/structure.go index 0dbeab2..f13e081 100644 --- a/flag/structure.go +++ b/flag/structure.go @@ -13,7 +13,8 @@ var ( Color = cli.BoolFlag{Name: colorName, Usage: colorUsage} Unsafe = cli.BoolFlag{Name: unsafeName, Usage: unsafeUsage} //---local--- - OutPrint = cli.StringFlag{Name: outPrintName, Usage: outPrintUsage, Value: OutPrintJsonValue} + OutPrint = cli.StringFlag{Name: outPrintName, Usage: outPrintUsage, Value: OutPrintJsonValue} + WithCommonConfig = cli.BoolFlag{Name: withCommonConfigName, Usage: withCommonConfigUsage} ) func CheckGlobal(c *cli.Context) error { diff --git a/main.go b/main.go index 3c78cf2..1f6773e 100644 --- a/main.go +++ b/main.go @@ -25,7 +25,8 @@ func initCommands() { ispctl [flag...] get module_name property_path ispctl [flag...] set module_name property_path [new_object] ispctl [flag...] delete module_name property_path - ispctl [flag...] schema module_name [local_flag]` + ispctl [flag...] schema module_name [local_flag] + ispctl [flag...] common ` app.Version = version app.Flags = []cli.Flag{ @@ -41,10 +42,11 @@ func initCommands() { command.Set(), command.Delete(), command.Schema(), + command.CommonConfig(), } app.BashComplete = func(context *cli.Context) { - for _, command := range app.Commands { - fmt.Println(command.Name) + for _, appCommand := range app.Commands { + fmt.Println(appCommand.Name) } } 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..5229c10 100644 --- a/service/config.go +++ b/service/config.go @@ -5,54 +5,45 @@ import ( "fmt" "github.com/integration-system/isp-lib/config/schema" "github.com/pkg/errors" - "github.com/xeipuuv/gojsonschema" + epb "google.golang.org/genproto/googleapis/rpc/errdetails" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" "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) GetConfigurationByModuleName(moduleName string) (*cfg.Config, error) { if moduleName == "" { - return nil, nil, errors.New("need module name") + return nil, errors.New("need module name") } if moduleConfiguration, err := configClient.GetConfigByModuleName(moduleName); err != nil { if errorStatus, ok := status.FromError(err); ok { switch errorStatus.Code() { case codes.NotFound: - return nil, nil, errors.Errorf("module '%s' not found", moduleName) + return nil, errors.Errorf("module [%s] not found", moduleName) } } - return nil, nil, err - } else if jsonObject, err := json.Marshal(moduleConfiguration.Data); err != nil { - return nil, nil, err + return nil, err } else { - return moduleConfiguration, jsonObject, nil + return moduleConfiguration, nil } } -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 +52,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 { @@ -69,40 +60,201 @@ func (c *configService) CreateUpdateConfig(stringToChange string, configuration } } - if ok, err := c.checkSchema(configuration.ModuleId, newData); err != nil { - return nil, err - } else if !ok { - return nil, nil - } - + configuration.Unsafe = c.UnsafeEnable configuration.Data = newData if resp, err := configClient.CreateUpdateConfig(*configuration); err != nil { + if errorStatus, ok := status.FromError(err); ok { + switch errorStatus.Code() { + case codes.InvalidArgument: + fmt.Print("doesn't match with schema:\n") + for _, value := range errorStatus.Details() { + if a, ok := value.(*epb.BadRequest); ok { + for _, value := range a.FieldViolations { + fmt.Printf("%s | %s\n", value.Field, value.Description) + } + } else { + fmt.Println(value) + } + return nil, nil + } + } + } return nil, err } else { return resp.Data, nil } } -func (c *configService) checkSchema(moduleId int32, object map[string]interface{}) (bool, error) { - if c.UnsafeEnable { - return true, nil - } - - if resp, err := configClient.GetSchemaByModuleId(moduleId); err != nil { - return false, err +func (c configService) UpdateConfigAndGetLinkCommon(configuration cfg.Config) ([]string, error) { + if resp, err := configClient.CreateUpdateConfig(configuration); err != nil { + return nil, err } else { - schemaLoader := gojsonschema.NewGoLoader(resp.Schema) - documentLoader := gojsonschema.NewGoLoader(object) - - if result, err := gojsonschema.Validate(schemaLoader, documentLoader); err != nil { - return false, err - } else if result.Valid() { - return true, nil - } else { - for _, desc := range result.Errors() { - fmt.Printf("- %s\n", desc) - } - return false, nil - } + return resp.CommonConfigs, nil } } + +func (c configService) GetCommonConfigByName(configName string) (cfg.CommonConfig, error) { + if commonConfigs, err := c.GetMapNameCommonConfig(); err != nil { + return cfg.CommonConfig{}, err + } else if config, ok := commonConfigs[configName]; !ok { + return cfg.CommonConfig{}, errors.Errorf("common config [%s] not found", configName) + } else { + return config, nil + } +} + +func (c configService) GetMapNameCommonConfig() (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) ([]string, bool, error) { + deletedInfo, err := configClient.DeleteCommonConfig(configId) + if err != nil { + return nil, false, err + } + arrayOfModuleName := make([]string, 0) + for moduleName := range deletedInfo.Links { + arrayOfModuleName = append(arrayOfModuleName, moduleName) + } + return arrayOfModuleName, deletedInfo.Deleted, nil +} + +func (c configService) GetLinksCommonConfig(configId string) ([]string, error) { + link, err := configClient.GetLinksCommonConfig(configId) + if err != nil { + return nil, err + } + arrayOfModuleName := make([]string, 0) + for moduleName := range *link { + arrayOfModuleName = append(arrayOfModuleName, moduleName) + } + return arrayOfModuleName, nil +} + +func (c configService) CompileDataWithCommonConfigs( + data map[string]interface{}, commonConfigs []string) (map[string]interface{}, error) { + + req := cfg.CompileConfigs{ + Data: data, + CommonConfigsIdList: commonConfigs, + } + var err error + data, err = configClient.CompileCommonConfigs(req) + if err != nil { + return nil, err + } else { + return data, nil + } +} + +func (c configService) UnlinkCommonConfigFromModule(configName, moduleName string) error { + return c.linked(configName, moduleName, + func(configId string, configIdentities []string) (bool, []string) { + needUnlink := false + for i, id := range configIdentities { + if configId == id { + copy(configIdentities[i:], configIdentities[i+1:]) + configIdentities[len(configIdentities)-1] = "" + configIdentities = configIdentities[:len(configIdentities)-1] + needUnlink = true + break + } + } + return needUnlink, configIdentities + }) +} + +func (c configService) LinkCommonConfigToModule(configName, moduleName string) error { + return c.linked(configName, moduleName, + func(configId string, configIdentities []string) (bool, []string) { + needLink := true + for _, id := range configIdentities { + if configId == id { + needLink = false + break + } + } + if needLink { + configIdentities = append(configIdentities, configId) + } + return needLink, configIdentities + }) +} + +func (c configService) linked(configName, moduleName string, + linkHandler func(configId string, configIdentities []string) (bool, []string)) error { + + if configName == "" { + return errors.New("empty config name") + } + + if moduleName == "" { + return errors.New("empty module name") + } + + commonConfigs, err := c.GetMapNameCommonConfig() + if err != nil { + return err + } + + config, ok := commonConfigs[configName] + if !ok { + return errors.Errorf("common config [%s] not found", configName) + } + + moduleConfig, err := c.GetConfigurationByModuleName(moduleName) + if err != nil { + return err + } + + configIdConfigNameMap := make(map[string]string) + for name, value := range commonConfigs { + configIdConfigNameMap[value.Id] = name + } + + needUpdate, newCommonConfigs := linkHandler(config.Id, moduleConfig.CommonConfigs) + + if needUpdate { + moduleConfig.CommonConfigs = newCommonConfigs + if linked, err := c.UpdateConfigAndGetLinkCommon(*moduleConfig); err != nil { + return err + } else { + fmt.Printf("module [%s] have next link:\n", moduleName) + for _, name := range linked { + fmt.Printf("[%s] ", configIdConfigNameMap[name]) + } + fmt.Printf("\n") + } + } else { + fmt.Printf("module [%s] have next link:\n", moduleName) + for _, name := range moduleConfig.CommonConfigs { + fmt.Printf("[%s] ", configIdConfigNameMap[name]) + } + fmt.Printf("\n") + } + return nil +}