diff --git a/doc/release-notes.md b/doc/release-notes.md index a0523bfe5..25fbd653b 100644 --- a/doc/release-notes.md +++ b/doc/release-notes.md @@ -1,9 +1,51 @@ +# Release 0.14.2 +## Theme +Ziti 0.14.2 includes the following: + + * CLI enhancements + * [can't create service policy with @ identity name](https://github.com/netfoundry/ziti-cmd/issues/93) + * [Add CLI commands to allow updating policies and role attributes](https://github.com/netfoundry/ziti-cmd/issues/94) + * [CLI: read config/config-type JSON from file](https://github.com/netfoundry/ziti-cmd/issues/90) + * [Not found errors for assigned/related ids do not say which resource was not found](https://github.com/netfoundry/ziti-edge/issues/148) + * Fixes to connection setup timing + +## CLI Updates +### Names in Policy Roles +Polices can now be created from the CLI using @name. This was previously supported natively in the REST APIs, however it was stripped out for consistency. The CLI now supports this by looking up names and replacing them with IDS when they are entered. When policies are listed they will show names instead of IDs now as well. + +```shell script +$ ziti edge controller create service-policy test-names Dial -i '#all' -s '@ssh' +Found services with id db9488ba-d0af-455b-9503-c6df88f228ff for name ssh +ba233791-8fde-44ba-9509-948275e3e3bb + +$ ziti edge controller list service-policies 'name="test-names"' +id: ba233791-8fde-44ba-9509-948275e3e3bb name: test-names type: Dial service roles: [@ssh] identity roles: [#all] +results: 1-1 of 1 +``` + +### New Update Commands +There are now update commands which allow updating role attributes on edge-routers, identities and services and roles on all three policy types. + +All the update commands also allow changing the entity and policy names. + +```shell script +$ ziti edge controller update identity jsmith-laptop -a us-east,sales +$ ziti edge controller update service-policy sales-na -s o365,mattermost +``` + +### Breaking Change to CLI commands +The shorthands for some policy flags have changed + + * The shorthand for create edge-router-policy `--edge-router-roles` is now `-e`. It was `-r` + * The shorthand for create service-edge-router-policy `--edge-router-roles` is now `-e`. It was `-r` + * The shorthand for create service-policy `--service-roles` is now `-s`. It was `-r` + # Release 0.14.1 ## Theme Ziti 0.14.1 includes the following: ### Features - * [Enable graceful shutdown of bound connections]https://github.com/netfoundry/ziti-edge/issues/149 + * [Enable graceful shutdown of bound connections](https://github.com/netfoundry/ziti-edge/issues/149) ### Fixes * [Enrollments w/ 0 length bodies cause enrollment errors](https://github.com/netfoundry/ziti-edge/issues/150) @@ -1769,4 +1811,4 @@ Errors where there is the potential to report about multiple invalid field value "apiVersion": "0.0.1" } } -``` \ No newline at end of file +``` diff --git a/go.mod b/go.mod index b35345510..6adaa2205 100644 --- a/go.mod +++ b/go.mod @@ -25,10 +25,10 @@ require ( github.com/kardianos/osext v0.0.0-20190222173326-2bc1f35cddc0 github.com/keybase/go-ps v0.0.0-20190827175125-91aafc93ba19 github.com/michaelquigley/pfxlog v0.0.0-20190813191113-2be43bd0dccc - github.com/netfoundry/ziti-edge v0.14.8 - github.com/netfoundry/ziti-fabric v0.11.29 - github.com/netfoundry/ziti-foundation v0.9.15 - github.com/netfoundry/ziti-sdk-golang v0.11.30 + github.com/netfoundry/ziti-edge v0.14.15 + github.com/netfoundry/ziti-fabric v0.11.31 + github.com/netfoundry/ziti-foundation v0.9.17 + github.com/netfoundry/ziti-sdk-golang v0.11.33 github.com/pborman/uuid v1.2.0 github.com/pkg/errors v0.9.1 github.com/rcrowley/go-metrics v0.0.0-20200313005456-10cdbea86bc0 diff --git a/go.sum b/go.sum index dab6943fa..4d8a92245 100644 --- a/go.sum +++ b/go.sum @@ -226,14 +226,14 @@ github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= github.com/netfoundry/secretstream v0.1.1 h1:z6T7B5DuOtr9O+SmKaS9DzwOoGLYtgvyTzuPuR5FO7I= github.com/netfoundry/secretstream v0.1.1/go.mod h1:uasYkYSp0MmNSlKOWJ2sVzxPms8e58TS4ENq4yro86k= -github.com/netfoundry/ziti-edge v0.14.8 h1:u4jSKkJ6T6gKmyFWlsRMjsNOuaeOPThH2WvVBtxsXOk= -github.com/netfoundry/ziti-edge v0.14.8/go.mod h1:KUPJljPUWx0OAXSJzZU+0RS6jTG/R+5McxSRO0+/Sak= -github.com/netfoundry/ziti-fabric v0.11.29 h1:cB53VvdL06gyGxs3qOEWV+ATMY3ThSaMSyn2xalXdhs= -github.com/netfoundry/ziti-fabric v0.11.29/go.mod h1:SQil5oz1SQgawDm3B4RpJdYQEVc7j8ddLoaocP2Z6gA= -github.com/netfoundry/ziti-foundation v0.9.15 h1:ouP2kJrft+b60JPzoFapWjZJVGdJhkzKOCdxKjmPhDU= -github.com/netfoundry/ziti-foundation v0.9.15/go.mod h1:s4O2kYpHcFzeMpS2hkNfD6W7Ce3RhsLw30Ruj4kBRu4= -github.com/netfoundry/ziti-sdk-golang v0.11.30 h1:FCg9i1O6GPt7vwOu0fMm0ySV8dicN/s8ITy3ZXwJx9k= -github.com/netfoundry/ziti-sdk-golang v0.11.30/go.mod h1:MLXmTe6ldP1S3EL/kA3E3ZLOANIWHHE1sn0mMHcoRzQ= +github.com/netfoundry/ziti-edge v0.14.15 h1:f1Oa+S/gn4AjnQ0Ju2PTxXFG9p3mcyw6LpfwumBnda0= +github.com/netfoundry/ziti-edge v0.14.15/go.mod h1:5Akv539VhL33jhgKCfrp6DKvXpR+SjsSVFf7FVXLUIM= +github.com/netfoundry/ziti-fabric v0.11.31 h1:otjhKFvxBLJUDP06lHnDOsHwkvVDp3xdhKK/EQyb+Ek= +github.com/netfoundry/ziti-fabric v0.11.31/go.mod h1:OkTL8ftDbnWv9BBOGZB5cfOGUOwHz3VF9+dyxBJhHfo= +github.com/netfoundry/ziti-foundation v0.9.17 h1:cBI8oeeZLbZad4nCUe/fjad02h5es4tjbAA9qJID1Bs= +github.com/netfoundry/ziti-foundation v0.9.17/go.mod h1:s4O2kYpHcFzeMpS2hkNfD6W7Ce3RhsLw30Ruj4kBRu4= +github.com/netfoundry/ziti-sdk-golang v0.11.33 h1:QZHYmS8lpOjGwVHlkRHo4Flxs4muNJwDPTl6kI2GQsQ= +github.com/netfoundry/ziti-sdk-golang v0.11.33/go.mod h1:5NHKKY44BPh7BVCYBYpqqEHUUE8Tuaka1xJx+p0HQ90= github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U= github.com/oleiade/reflections v1.0.0 h1:0ir4pc6v8/PJ0yw5AEtMddfXpWBXg9cnG7SgSoJuCgY= github.com/oleiade/reflections v1.0.0/go.mod h1:RbATFBbKYkVdqmSFtx13Bb/tVhR0lgOBXunWTZKeL4w= diff --git a/ziti-probe/subcmd/run.go b/ziti-probe/subcmd/run.go index 756a8f932..42b74ef33 100644 --- a/ziti-probe/subcmd/run.go +++ b/ziti-probe/subcmd/run.go @@ -101,7 +101,7 @@ func (p *probe) run(cmd *cobra.Command, args []string) { p.ctx = ziti.NewContext() } else { if cfg, err := config.NewFromFile(args[0]); err != nil { - log.Fatalf("failed to load config from file[%s]", args[0], err) + log.WithError(err).Fatalf("failed to load config from file[%s]", args[0]) } else { cfg.ConfigTypes = append(cfg.ConfigTypes, "ziti-probe-config.v1") p.ctx = ziti.NewContextWithConfig(cfg) @@ -128,7 +128,7 @@ func (p *probe) run(cmd *cobra.Command, args []string) { _, res, err := p.indb.Ping() if err != nil { - log.Fatalf("failed to get server info", err) + log.WithError(err).Fatal("failed to get server info") } log.Info("connected to influx version = ", res) diff --git a/ziti/cmd/ziti/cmd/edge_controller/common.go b/ziti/cmd/ziti/cmd/edge_controller/common.go index 3ea7d451e..dcabc2ff0 100644 --- a/ziti/cmd/ziti/cmd/edge_controller/common.go +++ b/ziti/cmd/ziti/cmd/edge_controller/common.go @@ -24,21 +24,22 @@ import ( ) func mapNameToID(entityType string, val string) (string, error) { - // If we can parse it as a UUID, treat it as such - _, err := uuid.Parse(val) - if err == nil { + list, _, err := filterEntitiesOfType(entityType, fmt.Sprintf("id=\"%s\"", val), false, nil) + if err != nil { + return "", err + } + + if len(list) > 0 { return val, nil } - // Allow UUID formatted names to be recognized with a name: prefix - name := strings.TrimPrefix(val, "name:") - list, _, err := filterEntitiesOfType(entityType, fmt.Sprintf("name=\"%s\"", name), false, nil) + list, _, err = filterEntitiesOfType(entityType, fmt.Sprintf("name=\"%s\"", val), false, nil) if err != nil { return "", err } if len(list) < 1 { - return "", errors.Errorf("no %v found for name %v", entityType, val) + return "", errors.Errorf("no %v found with id or name %v", entityType, val) } if len(list) > 1 { diff --git a/ziti/cmd/ziti/cmd/edge_controller/create_config.go b/ziti/cmd/ziti/cmd/edge_controller/create_config.go index 6218027f9..468e245e9 100644 --- a/ziti/cmd/ziti/cmd/edge_controller/create_config.go +++ b/ziti/cmd/ziti/cmd/edge_controller/create_config.go @@ -20,6 +20,7 @@ import ( "encoding/json" "fmt" "io" + "io/ioutil" "github.com/pkg/errors" @@ -32,6 +33,7 @@ import ( type createConfigOptions struct { commonOptions + jsonFile string } // newCreateConfigCmd creates the 'edge controller create service-policy' command @@ -43,10 +45,10 @@ func newCreateConfigCmd(f cmdutil.Factory, out io.Writer, errOut io.Writer) *cob } cmd := &cobra.Command{ - Use: "config ", + Use: "config [JSON configuration data]", Short: "creates a config managed by the Ziti Edge Controller", Long: "creates a config managed by the Ziti Edge Controller", - Args: cobra.ExactArgs(3), + Args: cobra.RangeArgs(2, 3), Run: func(cmd *cobra.Command, args []string) { options.Cmd = cmd options.Args = args @@ -58,6 +60,7 @@ func newCreateConfigCmd(f cmdutil.Factory, out io.Writer, errOut io.Writer) *cob // allow interspersing positional args and flags cmd.Flags().SetInterspersed(true) + cmd.Flags().StringVarP(&options.jsonFile, "json-file", "f", "", "Read config JSON from a file instead of the command line") cmd.Flags().BoolVarP(&options.OutputJSONResponse, "output-json", "j", false, "Output the full JSON response from the Ziti Edge Controller") return cmd @@ -65,9 +68,29 @@ func newCreateConfigCmd(f cmdutil.Factory, out io.Writer, errOut io.Writer) *cob // runCreateConfig create a new config on the Ziti Edge Controller func runCreateConfig(o *createConfigOptions) error { + var jsonBytes []byte + + if len(o.Args) == 3 { + jsonBytes = []byte(o.Args[2]) + } + + if o.Cmd.Flags().Changed("json-file") { + if len(o.Args) == 3 { + return errors.New("config json specified both in file and on command line. please pick one") + } + var err error + if jsonBytes, err = ioutil.ReadFile(o.jsonFile); err != nil { + return fmt.Errorf("failed to read config json file %v: %w", o.jsonFile, err) + } + } + + if len(jsonBytes) == 0 { + return errors.New("no config json specified") + } + dataMap := map[string]interface{}{} - if err := json.Unmarshal([]byte(o.Args[2]), &dataMap); err != nil { - fmt.Printf("Attempted to parse: %v\n", o.Args[1]) + if err := json.Unmarshal(jsonBytes, &dataMap); err != nil { + fmt.Printf("Attempted to parse: %v\n", string(jsonBytes)) fmt.Printf("Failing parsing JSON: %+v\n", err) return errors.Errorf("unable to parse data as json: %v", err) } diff --git a/ziti/cmd/ziti/cmd/edge_controller/create_config_type.go b/ziti/cmd/ziti/cmd/edge_controller/create_config_type.go index bd5c212e8..510be9cfb 100644 --- a/ziti/cmd/ziti/cmd/edge_controller/create_config_type.go +++ b/ziti/cmd/ziti/cmd/edge_controller/create_config_type.go @@ -20,6 +20,7 @@ import ( "encoding/json" "fmt" "io" + "io/ioutil" "github.com/pkg/errors" @@ -32,6 +33,7 @@ import ( type createConfigTypeOptions struct { commonOptions + schemaFile string } // newCreateConfigTypeCmd creates the 'edge controller create service-policy' command @@ -58,6 +60,7 @@ func newCreateConfigTypeCmd(f cmdutil.Factory, out io.Writer, errOut io.Writer) // allow interspersing positional args and flags cmd.Flags().SetInterspersed(true) + cmd.Flags().StringVarP(&options.schemaFile, "schema-file", "f", "", "Read config type JSON schema from a file instead of the command line") cmd.Flags().BoolVarP(&options.OutputJSONResponse, "output-json", "j", false, "Output the full JSON response from the Ziti Edge Controller") return cmd @@ -67,10 +70,26 @@ func newCreateConfigTypeCmd(f cmdutil.Factory, out io.Writer, errOut io.Writer) func runCreateConfigType(o *createConfigTypeOptions) error { var schemaMap map[string]interface{} + var schemaBytes []byte + if len(o.Args) == 2 { + schemaBytes = []byte(o.Args[1]) + } + + if o.Cmd.Flags().Changed("schema-file") { + if len(o.Args) == 2 { + return errors.New("schema specified both in file and on command line. please pick one") + } + var err error + if schemaBytes, err = ioutil.ReadFile(o.schemaFile); err != nil { + return fmt.Errorf("failed to read schema file %v: %w", o.schemaFile, err) + } + } + + if len(schemaBytes) > 0 { schemaMap = map[string]interface{}{} - if err := json.Unmarshal([]byte(o.Args[1]), &schemaMap); err != nil { - fmt.Printf("Attempted to parse: %v\n", o.Args[1]) + if err := json.Unmarshal(schemaBytes, &schemaMap); err != nil { + fmt.Printf("Attempted to parse: %v\n", string(schemaBytes)) fmt.Printf("Failing parsing JSON: %+v\n", err) return errors.Errorf("unable to parse data as json: %v", err) } diff --git a/ziti/cmd/ziti/cmd/edge_controller/create_edge_router_policy.go b/ziti/cmd/ziti/cmd/edge_controller/create_edge_router_policy.go index 392cd65f4..0daac0df6 100644 --- a/ziti/cmd/ziti/cmd/edge_controller/create_edge_router_policy.go +++ b/ziti/cmd/ziti/cmd/edge_controller/create_edge_router_policy.go @@ -57,7 +57,7 @@ func newCreateEdgeRouterPolicyCmd(f cmdutil.Factory, out io.Writer, errOut io.Wr // allow interspersing positional args and flags cmd.Flags().SetInterspersed(true) - cmd.Flags().StringSliceVarP(&options.edgeRouterRoles, "edge-router-roles", "r", nil, "Edge router roles of the new edge router policy") + cmd.Flags().StringSliceVarP(&options.edgeRouterRoles, "edge-router-roles", "e", nil, "Edge router roles of the new edge router policy") cmd.Flags().StringSliceVarP(&options.identityRoles, "identity-roles", "i", nil, "Identity roles of the new edge router policy") cmd.Flags().BoolVarP(&options.OutputJSONResponse, "output-json", "j", false, "Output the full JSON response from the Ziti Edge Controller") @@ -66,11 +66,20 @@ func newCreateEdgeRouterPolicyCmd(f cmdutil.Factory, out io.Writer, errOut io.Wr // runCreateEdgeRouterPolicy create a new edgeRouterPolicy on the Ziti Edge Controller func runCreateEdgeRouterPolicy(o *createEdgeRouterPolicyOptions) error { + edgeRouterRoles, err := convertNamesToIds(o.edgeRouterRoles, "edge-routers") + if err != nil { + return err + } + + identityRoles, err := convertNamesToIds(o.identityRoles, "identities") + if err != nil { + return err + } entityData := gabs.New() setJSONValue(entityData, o.Args[0], "name") - setJSONValue(entityData, o.edgeRouterRoles, "edgeRouterRoles") - setJSONValue(entityData, o.identityRoles, "identityRoles") + setJSONValue(entityData, edgeRouterRoles, "edgeRouterRoles") + setJSONValue(entityData, identityRoles, "identityRoles") result, err := createEntityOfType("edge-router-policies", entityData.String(), &o.commonOptions) if err != nil { diff --git a/ziti/cmd/ziti/cmd/edge_controller/create_service_edge_router_policy.go b/ziti/cmd/ziti/cmd/edge_controller/create_service_edge_router_policy.go index 2ad761178..58fc8e644 100644 --- a/ziti/cmd/ziti/cmd/edge_controller/create_service_edge_router_policy.go +++ b/ziti/cmd/ziti/cmd/edge_controller/create_service_edge_router_policy.go @@ -57,7 +57,7 @@ func newCreateServiceEdgeRouterPolicyCmd(f cmdutil.Factory, out io.Writer, errOu // allow interspersing positional args and flags cmd.Flags().SetInterspersed(true) - cmd.Flags().StringSliceVarP(&options.edgeRouterRoles, "edge-router-roles", "r", nil, "Edge router roles of the new service edge router policy") + cmd.Flags().StringSliceVarP(&options.edgeRouterRoles, "edge-router-roles", "e", nil, "Edge router roles of the new service edge router policy") cmd.Flags().StringSliceVarP(&options.serviceRoles, "service-roles", "s", nil, "Identity roles of the new service edge router policy") cmd.Flags().BoolVarP(&options.OutputJSONResponse, "output-json", "j", false, "Output the full JSON response from the Ziti Edge Controller") @@ -66,11 +66,19 @@ func newCreateServiceEdgeRouterPolicyCmd(f cmdutil.Factory, out io.Writer, errOu // runCreateServiceEdgeRouterPolicy create a new edgeRouterPolicy on the Ziti Edge Controller func runCreateServiceEdgeRouterPolicy(o *createServiceEdgeRouterPolicyOptions) error { + edgeRouterRoles, err := convertNamesToIds(o.edgeRouterRoles, "edge-routers") + if err != nil { + return err + } + serviceRoles, err := convertNamesToIds(o.serviceRoles, "identities") + if err != nil { + return err + } entityData := gabs.New() setJSONValue(entityData, o.Args[0], "name") - setJSONValue(entityData, o.edgeRouterRoles, "edgeRouterRoles") - setJSONValue(entityData, o.serviceRoles, "serviceRoles") + setJSONValue(entityData, edgeRouterRoles, "edgeRouterRoles") + setJSONValue(entityData, serviceRoles, "serviceRoles") result, err := createEntityOfType("service-edge-router-policies", entityData.String(), &o.commonOptions) if err != nil { diff --git a/ziti/cmd/ziti/cmd/edge_controller/create_service_policy.go b/ziti/cmd/ziti/cmd/edge_controller/create_service_policy.go index 83c69e702..7266f1541 100644 --- a/ziti/cmd/ziti/cmd/edge_controller/create_service_policy.go +++ b/ziti/cmd/ziti/cmd/edge_controller/create_service_policy.go @@ -19,6 +19,7 @@ package edge_controller import ( "fmt" "io" + "strings" "github.com/pkg/errors" @@ -59,7 +60,7 @@ func newCreateServicePolicyCmd(f cmdutil.Factory, out io.Writer, errOut io.Write // allow interspersing positional args and flags cmd.Flags().SetInterspersed(true) - cmd.Flags().StringSliceVarP(&options.serviceRoles, "service-roles", "r", nil, "Service roles of the new service policy") + cmd.Flags().StringSliceVarP(&options.serviceRoles, "service-roles", "s", nil, "Service roles of the new service policy") cmd.Flags().StringSliceVarP(&options.identityRoles, "identity-roles", "i", nil, "Identity roles of the new service policy") cmd.Flags().BoolVarP(&options.OutputJSONResponse, "output-json", "j", false, "Output the full JSON response from the Ziti Edge Controller") @@ -73,11 +74,21 @@ func runCreateServicePolicy(o *createServicePolicyOptions) error { return errors.Errorf("Invalid policy type '%v'. Valid values: [Bind, Dial]", policyType) } + serviceRoles, err := convertNamesToIds(o.serviceRoles, "services") + if err != nil { + return err + } + + identityRoles, err := convertNamesToIds(o.identityRoles, "identities") + if err != nil { + return err + } + entityData := gabs.New() setJSONValue(entityData, o.Args[0], "name") setJSONValue(entityData, o.Args[1], "type") - setJSONValue(entityData, o.serviceRoles, "serviceRoles") - setJSONValue(entityData, o.identityRoles, "identityRoles") + setJSONValue(entityData, serviceRoles, "serviceRoles") + setJSONValue(entityData, identityRoles, "identityRoles") result, err := createEntityOfType("service-policies", entityData.String(), &o.commonOptions) if err != nil { @@ -92,3 +103,20 @@ func runCreateServicePolicy(o *createServicePolicyOptions) error { return err } + +func convertNamesToIds(roles []string, entityType string) ([]string, error) { + var result []string + for _, val := range roles { + if strings.HasPrefix(val, "@") { + idOrName := strings.TrimPrefix(val, "@") + id, err := mapNameToID(entityType, idOrName) + if err != nil { + return nil, err + } + result = append(result, "@"+id) + } else { + result = append(result, val) + } + } + return result, nil +} diff --git a/ziti/cmd/ziti/cmd/edge_controller/list.go b/ziti/cmd/ziti/cmd/edge_controller/list.go index c840f84d6..b95d7e793 100644 --- a/ziti/cmd/ziti/cmd/edge_controller/list.go +++ b/ziti/cmd/ziti/cmd/edge_controller/list.go @@ -24,6 +24,7 @@ import ( "io" "net/url" "reflect" + "strings" "github.com/Jeffail/gabs" "github.com/netfoundry/ziti-cmd/ziti/cmd/ziti/cmd/common" @@ -414,9 +415,18 @@ func outputEdgeRouterPolicies(o *commonOptions, children []*gabs.Container, pagi for _, entity := range children { id, _ := entity.Path("id").Data().(string) name, _ := entity.Path("name").Data().(string) - edgeRouterRoles := entity.Path("edgeRouterRoles").String() - identityRoles := entity.Path("identityRoles").String() - _, err := fmt.Fprintf(o.Out, "id: %v name: %v edge router roles: %v identity roles: %v\n", id, name, edgeRouterRoles, identityRoles) + + identityRoles, err := mapRoleIdsToNames(entity, "identityRoles", "identities") + if err != nil { + return err + } + + edgeRouterRoles, err := mapRoleIdsToNames(entity, "edgeRouterRoles", "edge-routers") + if err != nil { + return err + } + + _, err = fmt.Fprintf(o.Out, "id: %v name: %v edge router roles: %v identity roles: %v\n", id, name, edgeRouterRoles, identityRoles) if err != nil { return err } @@ -516,9 +526,15 @@ func outputServiceEdgeRouterPolicies(o *commonOptions, children []*gabs.Containe for _, entity := range children { id, _ := entity.Path("id").Data().(string) name, _ := entity.Path("name").Data().(string) - edgeRouterRoles := entity.Path("edgeRouterRoles").String() - serviceRoles := entity.Path("serviceRoles").String() - _, err := fmt.Fprintf(o.Out, "id: %v name: %v edge router roles: %v service roles: %v\n", id, name, edgeRouterRoles, serviceRoles) + edgeRouterRoles, err := mapRoleIdsToNames(entity, "edgeRouterRoles", "edge-routers") + if err != nil { + return err + } + serviceRoles, err := mapRoleIdsToNames(entity, "serviceRoles", "services") + if err != nil { + return err + } + _, err = fmt.Fprintf(o.Out, "id: %v name: %v edge router roles: %v service roles: %v\n", id, name, edgeRouterRoles, serviceRoles) if err != nil { return err } @@ -544,9 +560,18 @@ func outputServicePolicies(o *commonOptions, children []*gabs.Container, pagingI id, _ := entity.Path("id").Data().(string) name, _ := entity.Path("name").Data().(string) policyType, _ := entity.Path("type").Data().(string) - identityRoles := entity.Path("identityRoles").String() - serviceRoles := entity.Path("serviceRoles").String() - _, err := fmt.Fprintf(o.Out, "id: %v name: %v type: %v service roles: %v identity roles: %v\n", id, name, policyType, serviceRoles, identityRoles) + + identityRoles, err := mapRoleIdsToNames(entity, "identityRoles", "identities") + if err != nil { + return err + } + + serviceRoles, err := mapRoleIdsToNames(entity, "serviceRoles", "services") + if err != nil { + return err + } + + _, err = fmt.Fprintf(o.Out, "id: %v name: %v type: %v service roles: %v identity roles: %v\n", id, name, policyType, serviceRoles, identityRoles) if err != nil { return err } @@ -555,6 +580,26 @@ func outputServicePolicies(o *commonOptions, children []*gabs.Container, pagingI return nil } +func mapRoleIdsToNames(c *gabs.Container, path string, entityType string) ([]string, error) { + values := c.Path(path).Data().([]interface{}) + + var result []string + for _, val := range values { + str := val.(string) + if strings.HasPrefix(str, "@") { + id := strings.TrimPrefix(str, "@") + name, err := mapIdToName(entityType, id) + if err != nil { + return nil, err + } + result = append(result, "@"+name) + } else { + result = append(result, str) + } + } + return result, nil +} + // runListIdentities implements the command to list identities func runListIdentities(roleFilters []string, roleSemantic string, options *commonOptions) error { params := url.Values{} diff --git a/ziti/cmd/ziti/cmd/edge_controller/update.go b/ziti/cmd/ziti/cmd/edge_controller/update.go index 38efde312..607cc445c 100644 --- a/ziti/cmd/ziti/cmd/edge_controller/update.go +++ b/ziti/cmd/ziti/cmd/edge_controller/update.go @@ -41,7 +41,12 @@ func newUpdateCmd(f cmdutil.Factory, out io.Writer, errOut io.Writer) *cobra.Com cmd.AddCommand(newUpdateAuthenticatorCmd(f, out, errOut)) cmd.AddCommand(newUpdateConfigCmd(f, out, errOut)) cmd.AddCommand(newUpdateCaCmd(f, out, errOut)) + cmd.AddCommand(newUpdateEdgeRouterCmd(f, out, errOut)) + cmd.AddCommand(newUpdateEdgeRouterPolicyCmd(f, out, errOut)) cmd.AddCommand(newUpdateIdentityCmd(f, out, errOut)) + cmd.AddCommand(newUpdateServiceCmd(f, out, errOut)) + cmd.AddCommand(newUpdateServicePolicyCmd(f, out, errOut)) + cmd.AddCommand(newUpdateServiceEdgeRouterPolicyCmd(f, out, errOut)) return cmd } diff --git a/ziti/cmd/ziti/cmd/edge_controller/update_config.go b/ziti/cmd/ziti/cmd/edge_controller/update_config.go index cbe1b375f..f7799cda4 100644 --- a/ziti/cmd/ziti/cmd/edge_controller/update_config.go +++ b/ziti/cmd/ziti/cmd/edge_controller/update_config.go @@ -20,6 +20,7 @@ import ( "encoding/json" "fmt" "io" + "io/ioutil" "github.com/pkg/errors" @@ -32,8 +33,9 @@ import ( type updateConfigOptions struct { commonOptions - name string - data string + name string + data string + jsonFile string } // newUpdateConfigCmd updates the 'edge controller update service-policy' command @@ -62,6 +64,7 @@ func newUpdateConfigCmd(f cmdutil.Factory, out io.Writer, errOut io.Writer) *cob cmd.Flags().SetInterspersed(true) cmd.Flags().StringVarP(&options.name, "name", "n", "", "Set the name of the config") cmd.Flags().StringVarP(&options.data, "data", "d", "", "Set the data of the config") + cmd.Flags().StringVarP(&options.jsonFile, "json-file", "f", "", "Read config JSON from a file instead of the command line") cmd.Flags().BoolVarP(&options.OutputJSONResponse, "output-json", "j", false, "Output the full JSON response from the Ziti Edge Controller") return cmd @@ -76,15 +79,31 @@ func runUpdateConfig(o *updateConfigOptions) error { entityData := gabs.New() change := false - if len(o.name) > 0 { + if o.Cmd.Flags().Changed("name") { setJSONValue(entityData, o.name, "name") change = true } - if len(o.data) > 0 { + var jsonBytes []byte + + if o.Cmd.Flags().Changed("data") { + jsonBytes = []byte(o.data) + } + + if o.Cmd.Flags().Changed("json-file") { + if o.Cmd.Flags().Changed("data") { + return errors.New("only one of --data and --json-file is allowed") + } + var err error + if jsonBytes, err = ioutil.ReadFile(o.jsonFile); err != nil { + return fmt.Errorf("failed to read config json file %v: %w", o.jsonFile, err) + } + } + + if len(jsonBytes) > 0 { dataMap := map[string]interface{}{} - if err := json.Unmarshal([]byte(o.data), &dataMap); err != nil { - fmt.Printf("Attempted to parse: %v\n", o.data) + if err := json.Unmarshal(jsonBytes, &dataMap); err != nil { + fmt.Printf("Attempted to parse: %v\n", string(jsonBytes)) fmt.Printf("Failing parsing JSON: %+v\n", err) return errors.Errorf("unable to parse data as json: %v", err) } diff --git a/ziti/cmd/ziti/cmd/edge_controller/update_edge_router.go b/ziti/cmd/ziti/cmd/edge_controller/update_edge_router.go new file mode 100644 index 000000000..04ef78545 --- /dev/null +++ b/ziti/cmd/ziti/cmd/edge_controller/update_edge_router.go @@ -0,0 +1,94 @@ +/* + Copyright NetFoundry, 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 + + https://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 edge_controller + +import ( + "fmt" + "io" + + "github.com/pkg/errors" + + "github.com/Jeffail/gabs" + "github.com/netfoundry/ziti-cmd/ziti/cmd/ziti/cmd/common" + cmdutil "github.com/netfoundry/ziti-cmd/ziti/cmd/ziti/cmd/factory" + cmdhelper "github.com/netfoundry/ziti-cmd/ziti/cmd/ziti/cmd/helpers" + "github.com/spf13/cobra" +) + +type updateEdgeRouterOptions struct { + commonOptions + name string + roleAttributes []string +} + +func newUpdateEdgeRouterCmd(f cmdutil.Factory, out io.Writer, errOut io.Writer) *cobra.Command { + options := &updateEdgeRouterOptions{ + commonOptions: commonOptions{ + CommonOptions: common.CommonOptions{Factory: f, Out: out, Err: errOut}, + }, + } + + cmd := &cobra.Command{ + Use: "edge-router ", + Short: "updates an edge router managed by the Ziti Edge Controller", + Long: "updates an edge router managed by the Ziti Edge Controller", + Args: cobra.ExactArgs(1), + Run: func(cmd *cobra.Command, args []string) { + options.Cmd = cmd + options.Args = args + err := runUpdateEdgeRouter(options) + cmdhelper.CheckErr(err) + }, + SuggestFor: []string{}, + } + + // allow interspersing positional args and flags + cmd.Flags().SetInterspersed(true) + cmd.Flags().StringVarP(&options.name, "name", "n", "", "Set the name of the edge router") + cmd.Flags().BoolVarP(&options.OutputJSONResponse, "output-json", "j", false, "Output the full JSON response from the Ziti Edge Controller") + cmd.Flags().StringSliceVarP(&options.roleAttributes, "role-attributes", "a", nil, + "Set role attributes of the edge router. Use --role-attributes '' to set an empty list") + + return cmd +} + +// runUpdateEdgeRouter update a new edgeRouter on the Ziti Edge Controller +func runUpdateEdgeRouter(o *updateEdgeRouterOptions) error { + id, err := mapNameToID("edge-routers", o.Args[0]) + if err != nil { + return err + } + entityData := gabs.New() + change := false + + if o.Cmd.Flags().Changed("name") { + setJSONValue(entityData, o.name, "name") + change = true + } + + if o.Cmd.Flags().Changed("role-attributes") { + setJSONValue(entityData, o.roleAttributes, "roleAttributes") + change = true + } + + if !change { + return errors.New("no change specified. must specify at least one attribute to change") + } + + _, err = patchEntityOfType(fmt.Sprintf("edge-routers/%v", id), entityData.String(), &o.commonOptions) + return err +} diff --git a/ziti/cmd/ziti/cmd/edge_controller/update_edge_router_policy.go b/ziti/cmd/ziti/cmd/edge_controller/update_edge_router_policy.go new file mode 100644 index 000000000..6abb04bbe --- /dev/null +++ b/ziti/cmd/ziti/cmd/edge_controller/update_edge_router_policy.go @@ -0,0 +1,110 @@ +/* + Copyright NetFoundry, 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 + + https://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 edge_controller + +import ( + "fmt" + "io" + + "github.com/pkg/errors" + + "github.com/Jeffail/gabs" + "github.com/netfoundry/ziti-cmd/ziti/cmd/ziti/cmd/common" + cmdutil "github.com/netfoundry/ziti-cmd/ziti/cmd/ziti/cmd/factory" + cmdhelper "github.com/netfoundry/ziti-cmd/ziti/cmd/ziti/cmd/helpers" + "github.com/spf13/cobra" +) + +type updateEdgeRouterPolicyOptions struct { + commonOptions + name string + edgeRouterRoles []string + identityRoles []string +} + +func newUpdateEdgeRouterPolicyCmd(f cmdutil.Factory, out io.Writer, errOut io.Writer) *cobra.Command { + options := &updateEdgeRouterPolicyOptions{ + commonOptions: commonOptions{ + CommonOptions: common.CommonOptions{Factory: f, Out: out, Err: errOut}, + }, + } + + cmd := &cobra.Command{ + Use: "edge-router-policy ", + Short: "updates an edge router policy managed by the Ziti Edge Controller", + Long: "updates an edge router policy managed by the Ziti Edge Controller", + Args: cobra.ExactArgs(1), + Run: func(cmd *cobra.Command, args []string) { + options.Cmd = cmd + options.Args = args + err := runUpdateEdgeRouterPolicy(options) + cmdhelper.CheckErr(err) + }, + SuggestFor: []string{}, + } + + // allow interspersing positional args and flags + cmd.Flags().SetInterspersed(true) + cmd.Flags().StringVarP(&options.name, "name", "n", "", "Set the name of the edge router policy") + cmd.Flags().BoolVarP(&options.OutputJSONResponse, "output-json", "j", false, "Output the full JSON response from the Ziti Edge Controller") + cmd.Flags().StringSliceVarP(&options.edgeRouterRoles, "edge-router-roles", "e", nil, "Edge router roles of the edge router policy") + cmd.Flags().StringSliceVarP(&options.identityRoles, "identity-roles", "i", nil, "Identity roles of the edge router policy") + + return cmd +} + +func runUpdateEdgeRouterPolicy(o *updateEdgeRouterPolicyOptions) error { + id, err := mapNameToID("edge-router-policies", o.Args[0]) + if err != nil { + return err + } + + edgeRouterRoles, err := convertNamesToIds(o.edgeRouterRoles, "edge-routers") + if err != nil { + return err + } + + identityRoles, err := convertNamesToIds(o.identityRoles, "identities") + if err != nil { + return err + } + + entityData := gabs.New() + change := false + + if o.Cmd.Flags().Changed("name") { + setJSONValue(entityData, o.name, "name") + change = true + } + + if o.Cmd.Flags().Changed("edge-router-roles") { + setJSONValue(entityData, edgeRouterRoles, "edgeRouterRoles") + change = true + } + + if o.Cmd.Flags().Changed("identity-roles") { + setJSONValue(entityData, identityRoles, "identityRoles") + change = true + } + + if !change { + return errors.New("no change specified. must specify at least one attribute to change") + } + + _, err = patchEntityOfType(fmt.Sprintf("edge-router-policies/%v", id), entityData.String(), &o.commonOptions) + return err +} diff --git a/ziti/cmd/ziti/cmd/edge_controller/update_identity.go b/ziti/cmd/ziti/cmd/edge_controller/update_identity.go index 75c72b7c4..1f1ab36fe 100644 --- a/ziti/cmd/ziti/cmd/edge_controller/update_identity.go +++ b/ziti/cmd/ziti/cmd/edge_controller/update_identity.go @@ -31,10 +31,10 @@ import ( type updateIdentityOptions struct { commonOptions - name string + name string + roleAttributes []string } -// newUpdateIdentityCmd updates the 'edge controller update service-policy' command func newUpdateIdentityCmd(f cmdutil.Factory, out io.Writer, errOut io.Writer) *cobra.Command { options := &updateIdentityOptions{ commonOptions: commonOptions{ @@ -60,6 +60,8 @@ func newUpdateIdentityCmd(f cmdutil.Factory, out io.Writer, errOut io.Writer) *c cmd.Flags().SetInterspersed(true) cmd.Flags().StringVarP(&options.name, "name", "n", "", "Set the name of the identity") cmd.Flags().BoolVarP(&options.OutputJSONResponse, "output-json", "j", false, "Output the full JSON response from the Ziti Edge Controller") + cmd.Flags().StringSliceVarP(&options.roleAttributes, "role-attributes", "a", nil, + "Set role attributes of the identity. Use --role-attributes '' to set an empty list") return cmd } @@ -73,20 +75,20 @@ func runUpdateIdentity(o *updateIdentityOptions) error { entityData := gabs.New() change := false - if len(o.name) > 0 { + if o.Cmd.Flags().Changed("name") { setJSONValue(entityData, o.name, "name") change = true } + if o.Cmd.Flags().Changed("role-attributes") { + setJSONValue(entityData, o.roleAttributes, "roleAttributes") + change = true + } + if !change { return errors.New("no change specified. must specify at least one attribute to change") } _, err = patchEntityOfType(fmt.Sprintf("identities/%v", id), entityData.String(), &o.commonOptions) - - if err != nil { - panic(err) - } - return err } diff --git a/ziti/cmd/ziti/cmd/edge_controller/update_service.go b/ziti/cmd/ziti/cmd/edge_controller/update_service.go new file mode 100644 index 000000000..7dd57d4c4 --- /dev/null +++ b/ziti/cmd/ziti/cmd/edge_controller/update_service.go @@ -0,0 +1,101 @@ +/* + Copyright NetFoundry, 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 + + https://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 edge_controller + +import ( + "fmt" + "io" + + "github.com/pkg/errors" + + "github.com/Jeffail/gabs" + "github.com/netfoundry/ziti-cmd/ziti/cmd/ziti/cmd/common" + cmdutil "github.com/netfoundry/ziti-cmd/ziti/cmd/ziti/cmd/factory" + cmdhelper "github.com/netfoundry/ziti-cmd/ziti/cmd/ziti/cmd/helpers" + "github.com/spf13/cobra" +) + +type updateServiceOptions struct { + commonOptions + name string + terminatorStrategy string + roleAttributes []string +} + +func newUpdateServiceCmd(f cmdutil.Factory, out io.Writer, errOut io.Writer) *cobra.Command { + options := &updateServiceOptions{ + commonOptions: commonOptions{ + CommonOptions: common.CommonOptions{Factory: f, Out: out, Err: errOut}, + }, + } + + cmd := &cobra.Command{ + Use: "service ", + Short: "updates a service managed by the Ziti Edge Controller", + Long: "updates a service managed by the Ziti Edge Controller", + Args: cobra.ExactArgs(1), + Run: func(cmd *cobra.Command, args []string) { + options.Cmd = cmd + options.Args = args + err := runUpdateService(options) + cmdhelper.CheckErr(err) + }, + SuggestFor: []string{}, + } + + // allow interspersing positional args and flags + cmd.Flags().SetInterspersed(true) + cmd.Flags().StringVarP(&options.name, "name", "n", "", "Set the name of the service") + cmd.Flags().StringVar(&options.terminatorStrategy, "terminator-strategy", "", "Specifies the terminator strategy for the service") + cmd.Flags().BoolVarP(&options.OutputJSONResponse, "output-json", "j", false, "Output the full JSON response from the Ziti Edge Controller") + cmd.Flags().StringSliceVarP(&options.roleAttributes, "role-attributes", "a", nil, + "Set role attributes of the service. Use --role-attributes '' to set an empty list") + + return cmd +} + +// runUpdateService update a new service on the Ziti Edge Controller +func runUpdateService(o *updateServiceOptions) error { + id, err := mapNameToID("services", o.Args[0]) + if err != nil { + return err + } + entityData := gabs.New() + change := false + + if o.Cmd.Flags().Changed("name") { + setJSONValue(entityData, o.name, "name") + change = true + } + + if o.Cmd.Flags().Changed("role-attributes") { + setJSONValue(entityData, o.roleAttributes, "roleAttributes") + change = true + } + + if o.Cmd.Flags().Changed("terminator-strategy") { + setJSONValue(entityData, o.terminatorStrategy, "terminatorStrategy") + change = true + } + + if !change { + return errors.New("no change specified. must specify at least one attribute to change") + } + + _, err = patchEntityOfType(fmt.Sprintf("services/%v", id), entityData.String(), &o.commonOptions) + return err +} diff --git a/ziti/cmd/ziti/cmd/edge_controller/update_service_edge_router_policy.go b/ziti/cmd/ziti/cmd/edge_controller/update_service_edge_router_policy.go new file mode 100644 index 000000000..ee4567204 --- /dev/null +++ b/ziti/cmd/ziti/cmd/edge_controller/update_service_edge_router_policy.go @@ -0,0 +1,110 @@ +/* + Copyright NetFoundry, 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 + + https://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 edge_controller + +import ( + "fmt" + "io" + + "github.com/pkg/errors" + + "github.com/Jeffail/gabs" + "github.com/netfoundry/ziti-cmd/ziti/cmd/ziti/cmd/common" + cmdutil "github.com/netfoundry/ziti-cmd/ziti/cmd/ziti/cmd/factory" + cmdhelper "github.com/netfoundry/ziti-cmd/ziti/cmd/ziti/cmd/helpers" + "github.com/spf13/cobra" +) + +type updateServiceEdgeRouterPolicyOptions struct { + commonOptions + name string + edgeRouterRoles []string + serviceRoles []string +} + +func newUpdateServiceEdgeRouterPolicyCmd(f cmdutil.Factory, out io.Writer, errOut io.Writer) *cobra.Command { + options := &updateServiceEdgeRouterPolicyOptions{ + commonOptions: commonOptions{ + CommonOptions: common.CommonOptions{Factory: f, Out: out, Err: errOut}, + }, + } + + cmd := &cobra.Command{ + Use: "service-edge-router-policy ", + Short: "updates a service edge router policy managed by the Ziti Edge Controller", + Long: "updates a service edge router policy managed by the Ziti Edge Controller", + Args: cobra.ExactArgs(1), + Run: func(cmd *cobra.Command, args []string) { + options.Cmd = cmd + options.Args = args + err := runUpdateServiceEdgeRouterPolicy(options) + cmdhelper.CheckErr(err) + }, + SuggestFor: []string{}, + } + + // allow interspersing positional args and flags + cmd.Flags().SetInterspersed(true) + cmd.Flags().StringVarP(&options.name, "name", "n", "", "Set the name of the edge router policy") + cmd.Flags().BoolVarP(&options.OutputJSONResponse, "output-json", "j", false, "Output the full JSON response from the Ziti Edge Controller") + cmd.Flags().StringSliceVarP(&options.edgeRouterRoles, "edge-router-roles", "e", nil, "Edge router roles of the service edge router policy") + cmd.Flags().StringSliceVarP(&options.serviceRoles, "service-roles", "s", nil, "Service roles of the service edge router policy") + + return cmd +} + +func runUpdateServiceEdgeRouterPolicy(o *updateServiceEdgeRouterPolicyOptions) error { + id, err := mapNameToID("service-edge-router-policies", o.Args[0]) + if err != nil { + return err + } + + edgeRouterRoles, err := convertNamesToIds(o.edgeRouterRoles, "edge-routers") + if err != nil { + return err + } + + serviceRoles, err := convertNamesToIds(o.serviceRoles, "services") + if err != nil { + return err + } + + entityData := gabs.New() + change := false + + if o.Cmd.Flags().Changed("name") { + setJSONValue(entityData, o.name, "name") + change = true + } + + if o.Cmd.Flags().Changed("edge-router-roles") { + setJSONValue(entityData, edgeRouterRoles, "edgeRouterRoles") + change = true + } + + if o.Cmd.Flags().Changed("service-roles") { + setJSONValue(entityData, serviceRoles, "serviceRoles") + change = true + } + + if !change { + return errors.New("no change specified. must specify at least one attribute to change") + } + + _, err = patchEntityOfType(fmt.Sprintf("service-edge-router-policies/%v", id), entityData.String(), &o.commonOptions) + return err +} diff --git a/ziti/cmd/ziti/cmd/edge_controller/update_service_policy.go b/ziti/cmd/ziti/cmd/edge_controller/update_service_policy.go new file mode 100644 index 000000000..ec0ab3747 --- /dev/null +++ b/ziti/cmd/ziti/cmd/edge_controller/update_service_policy.go @@ -0,0 +1,110 @@ +/* + Copyright NetFoundry, 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 + + https://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 edge_controller + +import ( + "fmt" + "io" + + "github.com/pkg/errors" + + "github.com/Jeffail/gabs" + "github.com/netfoundry/ziti-cmd/ziti/cmd/ziti/cmd/common" + cmdutil "github.com/netfoundry/ziti-cmd/ziti/cmd/ziti/cmd/factory" + cmdhelper "github.com/netfoundry/ziti-cmd/ziti/cmd/ziti/cmd/helpers" + "github.com/spf13/cobra" +) + +type updateServicePolicyOptions struct { + commonOptions + name string + serviceRoles []string + identityRoles []string +} + +func newUpdateServicePolicyCmd(f cmdutil.Factory, out io.Writer, errOut io.Writer) *cobra.Command { + options := &updateServicePolicyOptions{ + commonOptions: commonOptions{ + CommonOptions: common.CommonOptions{Factory: f, Out: out, Err: errOut}, + }, + } + + cmd := &cobra.Command{ + Use: "service-policy ", + Short: "updates a service-policy managed by the Ziti Edge Controller", + Long: "updates a service-policy managed by the Ziti Edge Controller", + Args: cobra.ExactArgs(1), + Run: func(cmd *cobra.Command, args []string) { + options.Cmd = cmd + options.Args = args + err := runUpdateServicePolicy(options) + cmdhelper.CheckErr(err) + }, + SuggestFor: []string{}, + } + + // allow interspersing positional args and flags + cmd.Flags().SetInterspersed(true) + cmd.Flags().StringVarP(&options.name, "name", "n", "", "Set the name of the service policy") + cmd.Flags().BoolVarP(&options.OutputJSONResponse, "output-json", "j", false, "Output the full JSON response from the Ziti Edge Controller") + cmd.Flags().StringSliceVarP(&options.serviceRoles, "service-roles", "s", nil, "Service roles of the service policy") + cmd.Flags().StringSliceVarP(&options.identityRoles, "identity-roles", "i", nil, "Identity roles of the service policy") + + return cmd +} + +func runUpdateServicePolicy(o *updateServicePolicyOptions) error { + id, err := mapNameToID("service-policies", o.Args[0]) + if err != nil { + return err + } + + serviceRoles, err := convertNamesToIds(o.serviceRoles, "services") + if err != nil { + return err + } + + identityRoles, err := convertNamesToIds(o.identityRoles, "identities") + if err != nil { + return err + } + + entityData := gabs.New() + change := false + + if o.Cmd.Flags().Changed("name") { + setJSONValue(entityData, o.name, "name") + change = true + } + + if o.Cmd.Flags().Changed("service-roles") { + setJSONValue(entityData, serviceRoles, "serviceRoles") + change = true + } + + if o.Cmd.Flags().Changed("identity-roles") { + setJSONValue(entityData, identityRoles, "identityRoles") + change = true + } + + if !change { + return errors.New("no change specified. must specify at least one attribute to change") + } + + _, err = patchEntityOfType(fmt.Sprintf("service-policies/%v", id), entityData.String(), &o.commonOptions) + return err +}