From 552e30f845d6b942ac1b447ba8c28090b05e6339 Mon Sep 17 00:00:00 2001 From: m-d-key Date: Fri, 6 Nov 2026 10:15:15 -0500 Subject: [PATCH] feat: add capabiilty support to create Workbench and Job commands (WORKBENCH-4534) Signed-off-by: m-d-key --- doc/wbctl create job.md | 1 + doc/wbctl create workbench.md | 1 + doc/wbctl get capabilities.md | 23 ++ doc/wbctl get.md | 1 + doc/wbctl profile init.md | 18 + doc/wbctl profile list.md | 18 + doc/wbctl profile show.md | 19 + doc/wbctl profile.md | 28 ++ internal/cmd/create/job/job.go | 13 +- internal/cmd/create/job/job_test.go | 132 +++++- internal/cmd/create/workbench/workbench.go | 12 + .../cmd/create/workbench/workbench_test.go | 235 +++++++++-- internal/cmd/flags/flags.go | 13 + internal/cmd/flags/flags_test.go | 15 + internal/cmd/get/command.go | 16 +- internal/cmd/get/get.go | 5 + internal/cmd/get/get_internal_test.go | 1 + internal/cmd/get/get_test.go | 1 + internal/constants/constants.go | 12 + internal/i18n/i18n_messages_workbench_cli.go | 1 + internal/i18n/logmsg.go | 1 + internal/services/workbench/capabilities.go | 62 +++ .../services/workbench/capabilities_test.go | 381 ++++++++++++++++++ internal/types/types.go | 37 +- internal/types/types_test.go | 30 ++ 25 files changed, 1030 insertions(+), 46 deletions(-) create mode 100644 doc/wbctl get capabilities.md create mode 100644 doc/wbctl profile init.md create mode 100644 doc/wbctl profile list.md create mode 100644 doc/wbctl profile show.md create mode 100644 doc/wbctl profile.md create mode 100644 internal/services/workbench/capabilities.go create mode 100644 internal/services/workbench/capabilities_test.go diff --git a/doc/wbctl create job.md b/doc/wbctl create job.md index 06f3a73..cf7b2b1 100644 --- a/doc/wbctl create job.md +++ b/doc/wbctl create job.md @@ -9,6 +9,7 @@ Aliases: Flags: -a, --application string The application to run in the job. Not required if at least one service is specified. + --capability strings Capabilit(y|ies) to include in the job. -c, --command string The command to run in the job. --context string The context (volume, snapshot, or s3 bucket) for the job. --dataplane string The ID of the dataplane where the job will be created. If only one dataplane is available, this flag can be omitted. diff --git a/doc/wbctl create workbench.md b/doc/wbctl create workbench.md index a5a5eeb..2e1dd63 100644 --- a/doc/wbctl create workbench.md +++ b/doc/wbctl create workbench.md @@ -9,6 +9,7 @@ Aliases: Flags: -a, --application string The application to run in the workbench. Not required if at least one service is specified. + --capability strings Capabilit(y|ies) to include in the workbench. --dataplane string The ID of the dataplane where the workbench will be created. If only one dataplane is available, this flag can be omitted. --desired-state string The desired state of the workbench (e.g., RUNNING, STOPPED). -d, --dry-run Only print the object that would be sent, without sending it. diff --git a/doc/wbctl get capabilities.md b/doc/wbctl get capabilities.md new file mode 100644 index 0000000..4392e6f --- /dev/null +++ b/doc/wbctl get capabilities.md @@ -0,0 +1,23 @@ +
+Print a table of basic information about the Capability resources identified by an optional list of resource ids. All resources printed if no ids provided.
+
+Usage:
+  wbctl get capabilities [flags]
+
+Aliases:
+  capabilities, capability
+
+Flags:
+  -h, --help            help for capabilities
+  -o, --output string   The output format. One of: json, text. (default "text")
+      --sort string     The sort column. Direction specified by appending '.asc' or '.desc' to the column name.
+
+Global Flags:
+  -m, --auth-mode string      Authentication mode. One of: device, pkce. (default "device")
+  -e, --endpoint string       The Workbench API endpoint URL.
+      --ignore-token-cache    Ignore token cache.
+      --no-listen             Do not open a local port to listen for PKCE authentication.
+      --organization string   The organization to authenticate with the Workbench API.
+  -p, --profile string        The configuration profile to use. (default "Default")
+  -v, --verbose               Log verbosity. Repeat option for increased levels of verbose output (-v, -vv, or -vvv).
+
diff --git a/doc/wbctl get.md b/doc/wbctl get.md index fdb7fd3..38d79b5 100644 --- a/doc/wbctl get.md +++ b/doc/wbctl get.md @@ -6,6 +6,7 @@ Usage: Available Commands: applications Get one or many Application resources + capabilities Get one or many Capability resources dataplanes Get one or many Dataplane resources events Get one or many Event resources image-builds Get one or many Image-Build resources diff --git a/doc/wbctl profile init.md b/doc/wbctl profile init.md new file mode 100644 index 0000000..55b7823 --- /dev/null +++ b/doc/wbctl profile init.md @@ -0,0 +1,18 @@ +
+Creates or replaces a named profile in the config file, prompting for the profile name, endpoint, and organization
+
+Usage:
+  wbctl profile init [flags]
+
+Flags:
+  -h, --help   help for init
+
+Global Flags:
+  -m, --auth-mode string      Authentication mode. One of: device, pkce. (default "device")
+  -e, --endpoint string       The Workbench API endpoint URL.
+      --ignore-token-cache    Ignore token cache.
+      --no-listen             Do not open a local port to listen for PKCE authentication.
+      --organization string   The organization to authenticate with the Workbench API.
+  -p, --profile string        The configuration profile to use. (default "Default")
+  -v, --verbose               Log verbosity. Repeat option for increased levels of verbose output (-v, -vv, or -vvv).
+
diff --git a/doc/wbctl profile list.md b/doc/wbctl profile list.md new file mode 100644 index 0000000..62a3a4c --- /dev/null +++ b/doc/wbctl profile list.md @@ -0,0 +1,18 @@ +
+List the profiles available in the current config file.
+
+Usage:
+  wbctl profile list [flags]
+
+Flags:
+  -h, --help   help for list
+
+Global Flags:
+  -m, --auth-mode string      Authentication mode. One of: device, pkce. (default "device")
+  -e, --endpoint string       The Workbench API endpoint URL.
+      --ignore-token-cache    Ignore token cache.
+      --no-listen             Do not open a local port to listen for PKCE authentication.
+      --organization string   The organization to authenticate with the Workbench API.
+  -p, --profile string        The configuration profile to use. (default "Default")
+  -v, --verbose               Log verbosity. Repeat option for increased levels of verbose output (-v, -vv, or -vvv).
+
diff --git a/doc/wbctl profile show.md b/doc/wbctl profile show.md new file mode 100644 index 0000000..cd60749 --- /dev/null +++ b/doc/wbctl profile show.md @@ -0,0 +1,19 @@ +
+Show the values of the current profile
+
+Usage:
+  wbctl profile show [flags]
+
+Flags:
+  -h, --help            help for show
+  -o, --output string   The output format. One of: json, text. (default "text")
+
+Global Flags:
+  -m, --auth-mode string      Authentication mode. One of: device, pkce. (default "device")
+  -e, --endpoint string       The Workbench API endpoint URL.
+      --ignore-token-cache    Ignore token cache.
+      --no-listen             Do not open a local port to listen for PKCE authentication.
+      --organization string   The organization to authenticate with the Workbench API.
+  -p, --profile string        The configuration profile to use. (default "Default")
+  -v, --verbose               Log verbosity. Repeat option for increased levels of verbose output (-v, -vv, or -vvv).
+
diff --git a/doc/wbctl profile.md b/doc/wbctl profile.md new file mode 100644 index 0000000..b2cca15 --- /dev/null +++ b/doc/wbctl profile.md @@ -0,0 +1,28 @@ +
+Manages named profiles stored in the config file
+
+Usage:
+  wbctl profile [command]
+
+Aliases:
+  profile, prof
+
+Available Commands:
+  init        Create or replace a profile
+  list        List the available profiles
+  show        Show current profile
+
+Flags:
+  -h, --help   help for profile
+
+Global Flags:
+  -m, --auth-mode string      Authentication mode. One of: device, pkce. (default "device")
+  -e, --endpoint string       The Workbench API endpoint URL.
+      --ignore-token-cache    Ignore token cache.
+      --no-listen             Do not open a local port to listen for PKCE authentication.
+      --organization string   The organization to authenticate with the Workbench API.
+  -p, --profile string        The configuration profile to use. (default "Default")
+  -v, --verbose               Log verbosity. Repeat option for increased levels of verbose output (-v, -vv, or -vvv).
+
+Use "wbctl profile [command] --help" for more information about a command.
+
diff --git a/internal/cmd/create/job/job.go b/internal/cmd/create/job/job.go index 31b4a09..d95240f 100644 --- a/internal/cmd/create/job/job.go +++ b/internal/cmd/create/job/job.go @@ -60,6 +60,7 @@ func CreateCommand( flags.AddApplicationFlag(cmd, constants.JobType) flags.AddServiceFlag(cmd, constants.JobType) flags.AddEnvironmentFlag(cmd, constants.JobType) + flags.AddCapabilityFlag(cmd, constants.JobType) return cmd } @@ -210,7 +211,7 @@ func getJobRequestBody( } services := v.GetStringSlice(constants.ServiceFlag) envs := v.GetStringSlice(constants.EnvironmentFlag) - + capabilities := v.GetStringSlice(constants.CapabilityFlag) workspaceRequests, err := workbench.GetValidWorkspaceRequests(ctx, svc, volumes) if err != nil { return types.Job{}, err @@ -247,6 +248,16 @@ func getJobRequestBody( "folderName": workspaceRequests[0].MountName, } } + if len(capabilities) > 0 { + job.Mounts = make([]types.MountRequest, 0, len(capabilities)) + for _, capability := range capabilities { + job.Mounts = append(job.Mounts, types.MountRequest{ + Capability: &types.CapabilityRequest{ + ID: capability, + }, + }) + } + } job.Properties = properties return job, nil } diff --git a/internal/cmd/create/job/job_test.go b/internal/cmd/create/job/job_test.go index 252e10a..8a6c636 100644 --- a/internal/cmd/create/job/job_test.go +++ b/internal/cmd/create/job/job_test.go @@ -203,6 +203,70 @@ const ( } } } +` + expectedCreateJobRequestBodyWithCapabilities = ` +{ + "param": { + "dataplane_id": "123e4567-e89b-12d3-a456-426614174000", + "description": "job desc", + "name": "job-2", + "nodepool": "np-2", + "services": [ + { + "id": "service-1", + "env": { + "DEFAULT_MOUNTNAME": "data" + } + }, + { + "id": "service-2", + "env": { + "DEFAULT_MOUNTNAME": "data" + } + } + ], + "spec": { + "tasks": { + "default": { + "cmds": [ + "run.sh" + ] + } + }, + "version": "3" + }, + "workspaces": [ + { + "id": "ctrl-home", + "mountName": "sas" + }, + { + "id": "ctrl-data", + "mountName": "data" + } + ], + "mounts": [ + { + "capability": { + "id": "capability1" + } + }, + { + "capability": { + "id": "capability2" + } + } + ], + "properties": { + "isWorkbenchAppCreated": true, + "primaryVolume": { + "controller_id": "ctrl-home", + "folderName": "sas", + "id": "ws-home" + } + } + } +} ` expectedUpdateJobDryRunOutput = `{ "ids": [ @@ -405,20 +469,21 @@ const ( ) type createInput struct { - endpoint string - filename string - fileContent string - dryRun bool - dataplane string - name string - description string - context string - command string - application string - services []string - nodepool string - subPath string - workspaces []string + endpoint string + filename string + fileContent string + dryRun bool + dataplane string + name string + description string + context string + command string + application string + services []string + nodepool string + subPath string + workspaces []string + capabilities []string } type createExpected struct { @@ -598,6 +663,42 @@ func TestCreateJobCommand(t *testing.T) { workspacesCalls: 2, }, }, + { + name: "create success with capabilities", + input: createInput{ + dataplane: "123e4567-e89b-12d3-a456-426614174000", + name: "job-2", + description: "job desc", + command: "run.sh", + services: []string{"service-1", "service-2"}, + nodepool: "np-2", + workspaces: []string{"ws-home", "ws-data"}, + capabilities: []string{"capability1", "capability2"}, + }, + mockEndpoints: getCreateJobEndpoints(jobEndpointsConfig{ + dataplaneConfig: stubs.StubHTTPPartialGetConfig{ + ExpectedQuery: expectedDataplaneQuery, + ResponseBody: `[{"id":"123e4567-e89b-12d3-a456-426614174000"}]`, + ResponseStatus: http.StatusOK, + }, + servicesConfig: stubs.StubHTTPPartialGetConfig{ + ResponseBody: expectedServicesResponseBody, + ResponseStatus: http.StatusOK, + }, + jobConfig: stubs.StubHTTPPartialPostConfig{ + ExpectedRequestBody: expectedCreateJobRequestBodyWithCapabilities, + ResponseBody: `{"id":"job-1"}`, + ResponseStatus: http.StatusOK, + }, + }), + expected: createExpected{ + displays: []string{stubs.ExpectedDeviceAuthDisplay, expectedCreateJobID}, + createCalls: 1, + dataplanesCalls: 1, + servicesCalls: 1, + workspacesCalls: 2, + }, + }, { name: "create error", input: createInput{ @@ -1303,6 +1404,9 @@ func getCreateArgs( for _, workspaceID := range tt.input.workspaces { args = append(args, "--"+constants.WorkspaceFlag, workspaceID) } + for _, capabilityID := range tt.input.capabilities { + args = append(args, "--"+constants.CapabilityFlag, capabilityID) + } return args } diff --git a/internal/cmd/create/workbench/workbench.go b/internal/cmd/create/workbench/workbench.go index 262feb5..441fd77 100644 --- a/internal/cmd/create/workbench/workbench.go +++ b/internal/cmd/create/workbench/workbench.go @@ -55,6 +55,7 @@ func CreateCommand( flags.AddApplicationFlag(cmd, constants.WorkbenchType) flags.AddServiceFlag(cmd, constants.WorkbenchType) flags.AddDesiredStateFlag(cmd, constants.WorkbenchType) + flags.AddCapabilityFlag(cmd, constants.WorkbenchType) return cmd } @@ -193,6 +194,7 @@ func getWorkbenchRequestBody( volumes = v.GetStringSlice(constants.WorkspaceFlag) } services := v.GetStringSlice(constants.ServiceFlag) + capabilities := v.GetStringSlice(constants.CapabilityFlag) serviceRequests, err := workbench.GetServiceRequests(ctx, svc, application, services) if err != nil { @@ -212,6 +214,16 @@ func getWorkbenchRequestBody( ApplicationID: application, } setWorkspaceRequests(&wkbnch, workspaceRequests) + if len(capabilities) > 0 { + wkbnch.Mounts = make([]types.MountRequest, 0, len(capabilities)) + for _, capability := range capabilities { + wkbnch.Mounts = append(wkbnch.Mounts, types.MountRequest{ + Capability: &types.CapabilityRequest{ + ID: capability, + }, + }) + } + } return wkbnch, nil } diff --git a/internal/cmd/create/workbench/workbench_test.go b/internal/cmd/create/workbench/workbench_test.go index 94d4ab4..899402f 100644 --- a/internal/cmd/create/workbench/workbench_test.go +++ b/internal/cmd/create/workbench/workbench_test.go @@ -34,18 +34,132 @@ const ( workbenchIncompleteFileErr = "either --application or at least one --service is required\n" + " Valid Applications: application-1, application-2\n" + " Valid Services: service-1, service-2" - workbenchNoWorkspaceCreateBody = `{"param":{"application_id":"app-1", "dataplane_id":"dp-1","name":"wb-1",` + - `"services":[{"id":"svc-a"},{"id":"svc-b"}],"nodepool":"np-1","state":"STOPPED"}}` - workbenchWithWorkspaceCreateBody = `{"param":{"application_id":"app-1", "dataplane_id":"dp-1","name":"wb-2",` + - `"services":[{"id":"svc-a","env":{"DEFAULT_MOUNTNAME":"data"}},` + - `{"id":"svc-b","env":{"DEFAULT_MOUNTNAME":"data"}}],` + - `"workspaces":[{"id":"ctrl-home","mountName":"sas"},{"id":"ctrl-data",` + - `"mountName":"data"}],"nodepool":"np-2","state":"STOPPED"}}` - workbenchWithServicesCreateBody = `{"param":{"dataplane_id":"dp-1","name":"wb-2",` + - `"services":[{"id":"service-1","env":{"DEFAULT_MOUNTNAME":"data"}},` + - `{"id":"service-2","env":{"DEFAULT_MOUNTNAME":"data"}}],` + - `"workspaces":[{"id":"ctrl-home","mountName":"sas"},{"id":"ctrl-data",` + - `"mountName":"data"}],"nodepool":"np-2","state":"STOPPED"}}` + workbenchNoWorkspaceCreateBody = `{ + "param": { + "application_id": "app-1", + "dataplane_id": "dp-1", + "name": "wb-1", + "services": [ + { + "id": "svc-a" + }, + { + "id": "svc-b" + } + ], + "nodepool": "np-1", + "state": "STOPPED" + } +}` + workbenchWithWorkspaceCreateBody = `{ + "param": { + "application_id": "app-1", + "dataplane_id": "dp-1", + "name": "wb-2", + "services": [ + { + "id": "svc-a", + "env": { + "DEFAULT_MOUNTNAME": "data" + } + }, + { + "id": "svc-b", + "env": { + "DEFAULT_MOUNTNAME": "data" + } + } + ], + "workspaces": [ + { + "id": "ctrl-home", + "mountName": "sas" + }, + { + "id": "ctrl-data", + "mountName": "data" + } + ], + "nodepool": "np-2", + "state": "STOPPED" + } +}` + workbenchWithServicesCreateBody = `{ + "param": { + "dataplane_id": "dp-1", + "name": "wb-2", + "services": [ + { + "id": "service-1", + "env": { + "DEFAULT_MOUNTNAME": "data" + } + }, + { + "id": "service-2", + "env": { + "DEFAULT_MOUNTNAME": "data" + } + } + ], + "workspaces": [ + { + "id": "ctrl-home", + "mountName": "sas" + }, + { + "id": "ctrl-data", + "mountName": "data" + } + ], + "nodepool": "np-2", + "state": "STOPPED" + } +}` + workbenchWithCapabilitiesCreateBody = `{ + "param": { + "dataplane_id": "dp-1", + "name": "wb-2", + "services": [ + { + "id": "service-1", + "env": { + "DEFAULT_MOUNTNAME": "data" + } + }, + { + "id": "service-2", + "env": { + "DEFAULT_MOUNTNAME": "data" + } + } + ], + "workspaces": [ + { + "id": "ctrl-home", + "mountName": "sas" + }, + { + "id": "ctrl-data", + "mountName": "data" + } + ], + "mounts": [ + { + "capability": { + "id": "capability1" + } + }, + { + "capability": { + "id": "capability2" + } + } + ], + "nodepool": "np-2", + "state": "STOPPED" + } +}` workbenchUpdateDryRunOutput = `{ "ids": [ "wb-cli-1", @@ -65,11 +179,38 @@ const ( "state": "STOPPED" } }` - workbenchUpdateRequestBodyMapping = `{"ids":["wb-cli-1","wb-cli-2"],` + - `"workbench":{"application_id":"app-1","nodepool":"np-1",` + - `"services":[{"id":"svc-a"},{"id":"svc-b"}],"state":"STOPPED"}}` - workbenchUpdateRequestBodyWorkspace = `{"ids":["wb-cli-1"],` + - `"workbench":{"workspaces":[{"id":"ctrl-home","mountName":"sas"}]}}` + workbenchUpdateRequestBodyMapping = `{ + "ids": [ + "wb-cli-1", + "wb-cli-2" + ], + "workbench": { + "application_id": "app-1", + "nodepool": "np-1", + "services": [ + { + "id": "svc-a" + }, + { + "id": "svc-b" + } + ], + "state": "STOPPED" + } +}` + workbenchUpdateRequestBodyWorkspace = `{ + "ids": [ + "wb-cli-1" + ], + "workbench": { + "workspaces": [ + { + "id": "ctrl-home", + "mountName": "sas" + } + ] + } +}` workbenchUpdateRequestBodyIDsOnly = `{"ids":["wb-cli-1"],"workbench":{}}` workbenchUpdateFileContent = `{"id":"wb-file","nodepool":"np-file"}` workbenchUpdateFileDryRunOutput = `{ @@ -133,17 +274,18 @@ const ( ) type createInput struct { - endpoint string - filename string - fileContent string - dataplane string - name string - labels []string - application string - nodepool string - workspaces []string - services []string - dryRun bool + endpoint string + filename string + fileContent string + dataplane string + name string + labels []string + application string + nodepool string + workspaces []string + services []string + capabilities []string + dryRun bool } type createExpected struct { @@ -315,6 +457,40 @@ func TestCreateWorkbenchCommand(t *testing.T) { workspaceCalls: 2, }, }, + { + name: "create success with capabilities", + input: createInput{ + dataplane: "dp-1", + name: "wb-2", + services: []string{"service-1", "service-2"}, + nodepool: "np-2", + workspaces: []string{"ws-home", "ws-data"}, + capabilities: []string{"capability1", "capability2"}, + }, + mockEndpoints: getCreateWorkbenchEndpoints(workbenchEndpointsConfig{ + dataplaneConfig: stubs.StubHTTPPartialGetConfig{ + ExpectedQuery: `id=in.(dp-1)`, + ResponseStatus: http.StatusOK, + ResponseBody: `[{"id":"dp-1"}]`, + }, + servicesConfig: stubs.StubHTTPPartialGetConfig{ + ResponseStatus: http.StatusOK, + ResponseBody: servicesResponseBody, + }, + workbenchesConfig: stubs.StubHTTPPartialPostConfig{ + ExpectedRequestBody: workbenchWithCapabilitiesCreateBody, + ResponseStatus: http.StatusOK, + ResponseBody: `{"id":"wb-2"}`, + }, + }), + expected: createExpected{ + displays: []string{stubs.ExpectedDeviceAuthDisplay, "wb-2"}, + createCalls: 1, + dataplaneCalls: 1, + servicesCalls: 1, + workspaceCalls: 2, + }, + }, { name: "create error", input: createInput{ @@ -1017,6 +1193,9 @@ func getCreateArgs( for _, serviceID := range tt.input.services { args = append(args, "--"+constants.ServiceFlag, serviceID) } + for _, capabilityID := range tt.input.capabilities { + args = append(args, "--"+constants.CapabilityFlag, capabilityID) + } return args } diff --git a/internal/cmd/flags/flags.go b/internal/cmd/flags/flags.go index ec3b9c3..a0502f4 100644 --- a/internal/cmd/flags/flags.go +++ b/internal/cmd/flags/flags.go @@ -530,6 +530,19 @@ func AddProfileFlag(cmd *cobra.Command) { ) } +// AddCapabilityFlag adds the capability flag to the command. +func AddCapabilityFlag( + cmd *cobra.Command, + _type string, +) { + key := constants.CapabilityFlag + cmd.Flags().StringSlice( + key, + nil, + i18n.Format(i18n.FlagCapabilityUsage, i18n.A{constants.I18nArgTypeKey: _type}), + ) +} + // BindToViper binds all the flags to viper. This cannot be done when the flags // are created because multiple commands have the same flags and viper maintains // a flat list. This means that `viper.GetString("name")` will look in the last diff --git a/internal/cmd/flags/flags_test.go b/internal/cmd/flags/flags_test.go index b0e5ead..d191b5a 100644 --- a/internal/cmd/flags/flags_test.go +++ b/internal/cmd/flags/flags_test.go @@ -610,6 +610,21 @@ func TestExportedFlags(t *testing.T) { viperKey: constants.ProfileFlag, expectedValue: "Default", }, + { + name: "CapabilityFlag", + call: withType(flags.AddCapabilityFlag, constants.JobType), + args: []string{"--" + constants.CapabilityFlag, "capability-value1", + "--" + constants.CapabilityFlag, "capability-value2", + "--" + constants.CapabilityFlag, "capability-value3"}, + viperKey: constants.CapabilityFlag, + expectedValue: []string{"capability-value1", "capability-value2", "capability-value3"}, + }, + { + name: "CapabilityFlagDefault", + call: withType(flags.AddCapabilityFlag, constants.JobType), + viperKey: constants.CapabilityFlag, + expectedValue: []string{}, + }, } for _, tt := range tests { diff --git a/internal/cmd/get/command.go b/internal/cmd/get/command.go index 2937278..07dedde 100644 --- a/internal/cmd/get/command.go +++ b/internal/cmd/get/command.go @@ -31,7 +31,7 @@ func Command( return &cmd } -// nolint:funlen +// nolint:funlen,maintidx func getSubcommands( ctx context.Context, fsys afero.Fs, @@ -52,6 +52,20 @@ func getSubcommands( i18n.A{constants.I18nArgTypeKey: types.Titler.String(constants.ApplicationType)}, ), }, + { + Use: constants.CapabilitiesCommandName, + Aliases: []string{constants.CapabilityCommandName}, + Args: cobra.ArbitraryArgs, + RunE: newGetFunction(ctx, fsys, _ui, constants.CapabilityType), + Short: i18n.Format( + i18n.CmdGetTypeUsage, + i18n.A{constants.I18nArgTypeKey: types.Titler.String(constants.CapabilityType)}, + ), + Long: i18n.Format( + i18n.CmdGetTypeDescription, + i18n.A{constants.I18nArgTypeKey: types.Titler.String(constants.CapabilityType)}, + ), + }, { Use: constants.DataplanesCommandName, Aliases: []string{constants.DataplaneCommandName}, diff --git a/internal/cmd/get/get.go b/internal/cmd/get/get.go index 9c99ef3..e4b761b 100644 --- a/internal/cmd/get/get.go +++ b/internal/cmd/get/get.go @@ -41,6 +41,11 @@ var getFunctions = []types.FunctionMetadata[getterF]{ Plural: constants.ApplicationsType, F: getImpl[types.Applications](workbench.GetApplications, workbench.PrintApplications), }, + { + Singular: constants.CapabilityType, + Plural: constants.CapabilitiesType, + F: getImpl[types.Capabilities](workbench.GetCapabilities, workbench.PrintCapabilities), + }, { Singular: constants.DataplaneType, Plural: constants.DataplanesType, diff --git a/internal/cmd/get/get_internal_test.go b/internal/cmd/get/get_internal_test.go index e32dd5a..1060d4d 100644 --- a/internal/cmd/get/get_internal_test.go +++ b/internal/cmd/get/get_internal_test.go @@ -39,6 +39,7 @@ func TestNewGetFunctionErrorPaths(t *testing.T) { supportedTypes := []string{ constants.ApplicationsType, + constants.CapabilitiesType, constants.DataplanesType, constants.EventsType, constants.ImagesType, diff --git a/internal/cmd/get/get_test.go b/internal/cmd/get/get_test.go index afe9047..cf3baf4 100644 --- a/internal/cmd/get/get_test.go +++ b/internal/cmd/get/get_test.go @@ -2312,6 +2312,7 @@ func TestSupportedResourceTypes(t *testing.T) { name: "returns sorted supported get resource types", expectedTypes: []string{ constants.ApplicationsType, + constants.CapabilitiesType, constants.DataplanesType, constants.EventsType, constants.ImagesType, diff --git a/internal/constants/constants.go b/internal/constants/constants.go index ad8bcaa..c58cfe8 100644 --- a/internal/constants/constants.go +++ b/internal/constants/constants.go @@ -27,6 +27,11 @@ const ( BuildSettingGOOSKey = "GOOS" BuildSettingVCSRevisionKey = "vcs.revision" CancelCommandName = "cancel" + CapabilitiesCommandName = "capabilities" + CapabilitiesType = "capabilities" + CapabilityCommandName = "capability" + CapabilityFlag = "capability" + CapabilityType = "capability" ClientIDEnvVar = "WBCLIENTID" ClientIDFlag = "client-id" ClientSecretEnvVar = "WBCLIENTSECRET" @@ -235,7 +240,9 @@ const ( SortKeyCreationTimeStamp = "creationTimeStamp" SortKeyCurrentState = "current_state" SortKeyDefault = "default" + SortKeyDisabled = "disabled" SortKeyDisplayName = "display_name" + SortKeyEnabled = "enabled" SortKeyHomeDir = "home_dir" SortKeyImage = "image" SortKeyImageBuildID = "image_build_id" @@ -274,6 +281,7 @@ const ( StorageclassesCommandName = "storageclasses" StorageclassesType = "storageclasses" SubPathFlag = "sub-path" + TableLabeCategory = "CATEGORY" TableLabelAction = "ACTION" TableLabelAge = "AGE" TableLabelApplicationID = "APPLICATION_ID" @@ -286,6 +294,7 @@ const ( TableLabelDefault = "DEFAULT" TableLabelDescription = "DESCRIPTION" TableLabelEmail = "EMAIL" + TableLabelEnabled = "ENABLED" TableLabelHomeDir = "HOME_DIR" TableLabelID = "ID" TableLabelImage = "IMAGE" @@ -300,6 +309,7 @@ const ( TableLabelNote = "NOTE" TableLabelReady = "READY" TableLabelReason = "REASON" + TableLabelRecommended = "RECOMMENDED" TableLabelRequestAt = "REQUEST_AT" TableLabelResourceType = "RESOURCE_TYPE" TableLabelResponseAt = "RESPONSE_AT" @@ -314,6 +324,7 @@ const ( TableLabelURL = "URL" TableLabelUserName = "USERNAME" TableLabelValue = "VALUE" + TableLabelVersion = "VERSION" TableLabelVolumeID = "VOLUME_ID" TableLabelVolumeName = "VOLUME_NAME" TenantFlag = "tenant" @@ -345,6 +356,7 @@ const ( WorkbenchEndpointDataplaneNodepools = "/dataplane_nodepools" WorkbenchEndpointDataplaneStorageclasses = "/dataplane_storageclasses" WorkbenchEndpointDataplaneWorkbenchApplications = "/dataplane_workbench_applications" + WorkbenchEndpointDataplaneWorkbenchCapabilities = "/dataplane_workbench_capabilities" WorkbenchEndpointDataplaneWorkbenchServices = "/dataplane_workbench_services" WorkbenchEndpointDataplaneWorkspaceServices = "/dataplane_workspace_services" WorkbenchEndpointDataplanes = "/dataplanes" diff --git a/internal/i18n/i18n_messages_workbench_cli.go b/internal/i18n/i18n_messages_workbench_cli.go index f67256d..550a03e 100644 --- a/internal/i18n/i18n_messages_workbench_cli.go +++ b/internal/i18n/i18n_messages_workbench_cli.go @@ -109,6 +109,7 @@ var wbctlMessages = "\n" + "wbctl-cli-icu.falling.back.to.full.reauthorization.msg=falling back to full reauthorization\n" + "wbctl-cli-icu.flag.application.usage.msg=The application to run in the {type}. Not required if at least one service is specified.\n" + "wbctl-cli-icu.flag.auth.mode.usage.msg=Authentication mode. One of: device, pkce.\n" + + "wbctl-cli-icu.flag.capability.usage.msg=Capabilit(y|ies) to include in the {type}.\n" + "wbctl-cli-icu.flag.client.id.usage.msg=The client-id to authenticate with the Workbench API ($WBCLIENTID).\n" + "wbctl-cli-icu.flag.client.secret.usage.msg=The client-secret to authenticate with the Workbench API ($WBCLIENTSECRET).\n" + "wbctl-cli-icu.flag.command.usage.msg=The command to run in the job.\n" + diff --git a/internal/i18n/logmsg.go b/internal/i18n/logmsg.go index dc53005..b599e3c 100644 --- a/internal/i18n/logmsg.go +++ b/internal/i18n/logmsg.go @@ -121,6 +121,7 @@ const ( FallingBackToFullReauthorization = BundleID + ".falling.back.to.full.reauthorization.msg" FlagApplicationUsage = BundleID + ".flag.application.usage.msg" FlagAuthModeUsage = BundleID + ".flag.auth.mode.usage.msg" + FlagCapabilityUsage = BundleID + ".flag.capability.usage.msg" FlagClientIDUsage = BundleID + ".flag.client.id.usage.msg" FlagClientSecretUsage = BundleID + ".flag.client.secret.usage.msg" FlagCommandUsage = BundleID + ".flag.command.usage.msg" diff --git a/internal/services/workbench/capabilities.go b/internal/services/workbench/capabilities.go new file mode 100644 index 0000000..89d0bc9 --- /dev/null +++ b/internal/services/workbench/capabilities.go @@ -0,0 +1,62 @@ +// Copyright © 2026, SAS Institute Inc., Cary, NC, USA. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package workbench + +import ( + "context" + "strconv" + + "github.com/sassoftware/sas-ggdk/pkg/result" + "github.com/sassoftware/wbctl/internal/constants" + "github.com/sassoftware/wbctl/internal/logutil" + "github.com/sassoftware/wbctl/internal/postgrest" + "github.com/sassoftware/wbctl/internal/types" + "github.com/sassoftware/wbctl/internal/ui" +) + +// GetCapabilities gets the Capabilities supported by the WorkbenchService. If +// given any ids, only the matching resources will be returned. Otherwise, all +// resources are returned. +func GetCapabilities( + ctx context.Context, + s *WorkbenchService, + ids []string, + sortSpec string, +) (types.Capabilities, error) { + logutil.GetLogger().Info("getting capabilities", "ids", ids, "sort", sortSpec) + sortSpec = normalizeSortSpec(sortSpec, map[string][]string{ + constants.SortKeyEnabled: {constants.SortKeyDisabled}, + }) + return result.Split(Get[types.Capabilities]( + ctx, s, postgrest.Endpoint(constants.WorkbenchEndpointDataplaneWorkbenchCapabilities), IDsQuery(ids, sortSpec), + )) +} + +// PrintCapabilities returns a function that prints the given capabilities. +func PrintCapabilities(_ui ui.UI, _ string, resources types.Capabilities) error { + tbl := _ui.Table( + []string{ + constants.TableLabelID, + constants.TableLabelName, + constants.TableLabelDescription, + constants.TableLabelVersion, + constants.TableLabeCategory, + constants.TableLabelEnabled, + constants.TableLabelRecommended, + }, + ) + for _, resource := range resources { + tbl.Add( + resource.ID, + resource.Name, + resource.Description, + resource.Version, + resource.Category, + strconv.FormatBool(!resource.Disabled), + strconv.FormatBool(resource.Recommended), + ) + } + tbl.Print() + return nil +} diff --git a/internal/services/workbench/capabilities_test.go b/internal/services/workbench/capabilities_test.go new file mode 100644 index 0000000..8939de7 --- /dev/null +++ b/internal/services/workbench/capabilities_test.go @@ -0,0 +1,381 @@ +// Copyright © 2026, SAS Institute Inc., Cary, NC, USA. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package workbench_test + +import ( + "context" + "encoding/json" + "net/http" + "strings" + "testing" + + "github.com/sassoftware/wbctl/internal/constants" + "github.com/sassoftware/wbctl/internal/postgrest" + "github.com/sassoftware/wbctl/internal/services/workbench" + "github.com/sassoftware/wbctl/internal/stubs" + "github.com/sassoftware/wbctl/internal/types" + "github.com/stretchr/testify/require" +) + +const ( + capabilitiesGetOneResponseJSON = `[{ + "id":"cap-1", + "name":"Capability1", + "description":"The first capability", + "category":"language", + "disabled":false, + "version":"1.0.1" + }]` + + capabilitiesGetTwoResponseJSON = `[{ + "id":"cap-1", + "name":"Capability1", + "description":"The first capability", + "category":"language", + "disabled":false, + "version":"1.0.1" + },{ + "id":"cap-2", + "name":"Capability2", + "description":"The second capability", + "category":"language", + "disabled":true, + "version":"1.0.2" + }]` + + capabilitiesEmptyResourcesJSON = `[]` + + capabilitiesPrintTwoResourcesJSON = `[ + { + "id": "cap-1", + "name": "Capability1", + "description": "The first capability", + "category": "language", + "disabled": false, + "version": "1.0.1" + }, + { + "id": "cap-2", + "name": "Capability2", + "description": "The second capability", + "category": "language", + "disabled": true, + "version": "1.0.2" + } + ]` + + expectedCapabilitiesEmptyTable = "ID\tNAME\tDESCRIPTION\tVERSION\tCATEGORY\tENABLED" + + expectedCapabilitiesTwoRowsTable = "ID\tNAME\tDESCRIPTION\tVERSION\tCATEGORY\tENABLED\n" + + "cap-1\tCapability1\tThe first capability\t1.0.1\tlanguage\ttrue\n" + + "cap-2\tCapability2\tThe second capability\t1.0.2\tlanguage\tfalse" +) + +func TestGetCapabilities(t *testing.T) { + tests := []getTestCase[types.Capabilities]{ + { + name: "get capabilities success without ids query", + request: getRequest{}, + mockEndpoints: getCapabilitiesGetEndpoints("", http.StatusOK, capabilitiesGetOneResponseJSON), + expected: getExpected[types.Capabilities]{ + result: types.Capabilities{ + { + ID: "cap-1", + Name: "Capability1", + Description: "The first capability", + Version: "1.0.1", + Category: "language", + Disabled: false, + }, + }, + }, + }, + { + name: "get capabilities sort by name asc", + request: getRequest{ + sort: "name.asc", + }, + mockEndpoints: getCapabilitiesGetEndpoints("order=name.asc", http.StatusOK, capabilitiesGetOneResponseJSON), + expected: getExpected[types.Capabilities]{ + result: types.Capabilities{ + { + ID: "cap-1", + Name: "Capability1", + Description: "The first capability", + Version: "1.0.1", + Category: "language", + Disabled: false, + }, + }, + }, + }, + { + name: "get capabilities sort by name desc", + request: getRequest{ + sort: "name.desc", + }, + mockEndpoints: getCapabilitiesGetEndpoints("order=name.desc", http.StatusOK, capabilitiesGetOneResponseJSON), + expected: getExpected[types.Capabilities]{ + result: types.Capabilities{ + { + ID: "cap-1", + Name: "Capability1", + Description: "The first capability", + Version: "1.0.1", + Category: "language", + Disabled: false, + }, + }, + }, + }, + { + name: "get capabilities sort by id", + request: getRequest{ + sort: "id", + }, + mockEndpoints: getCapabilitiesGetEndpoints("order=id", http.StatusOK, capabilitiesGetOneResponseJSON), + expected: getExpected[types.Capabilities]{ + result: types.Capabilities{ + { + ID: "cap-1", + Name: "Capability1", + Description: "The first capability", + Version: "1.0.1", + Category: "language", + Disabled: false, + }, + }, + }, + }, + { + name: "get capabilities sort by description", + request: getRequest{ + sort: "description", + }, + mockEndpoints: getCapabilitiesGetEndpoints("order=description", http.StatusOK, capabilitiesGetOneResponseJSON), + expected: getExpected[types.Capabilities]{ + result: types.Capabilities{ + { + ID: "cap-1", + Name: "Capability1", + Description: "The first capability", + Version: "1.0.1", + Category: "language", + Disabled: false, + }, + }, + }, + }, + { + name: "get capabilities sort by category", + request: getRequest{ + sort: "category", + }, + mockEndpoints: getCapabilitiesGetEndpoints("order=category", http.StatusOK, capabilitiesGetOneResponseJSON), + expected: getExpected[types.Capabilities]{ + result: types.Capabilities{ + { + ID: "cap-1", + Name: "Capability1", + Description: "The first capability", + Version: "1.0.1", + Category: "language", + Disabled: false, + }, + }, + }, + }, + { + name: "get capabilities sort by version", + request: getRequest{ + sort: "version", + }, + mockEndpoints: getCapabilitiesGetEndpoints("order=version", http.StatusOK, capabilitiesGetOneResponseJSON), + expected: getExpected[types.Capabilities]{ + result: types.Capabilities{ + { + ID: "cap-1", + Name: "Capability1", + Description: "The first capability", + Version: "1.0.1", + Category: "language", + Disabled: false, + }, + }, + }, + }, + { + name: "get capabilities sort by enabled", + request: getRequest{ + sort: "enabled", + }, + mockEndpoints: getCapabilitiesGetEndpoints("order=disabled", http.StatusOK, capabilitiesGetOneResponseJSON), + expected: getExpected[types.Capabilities]{ + result: types.Capabilities{ + { + ID: "cap-1", + Name: "Capability1", + Description: "The first capability", + Version: "1.0.1", + Category: "language", + Disabled: false, + }, + }, + }, + }, + { + name: "get capabilities sort by name and category", + request: getRequest{ + sort: "name.asc,category.desc", + }, + mockEndpoints: getCapabilitiesGetEndpoints( + "order=name.asc,category.desc", + http.StatusOK, capabilitiesGetOneResponseJSON, + ), + expected: getExpected[types.Capabilities]{ + result: types.Capabilities{ + { + ID: "cap-1", + Name: "Capability1", + Description: "The first capability", + Version: "1.0.1", + Category: "language", + Disabled: false, + }, + }, + }, + }, + { + name: "get capabilities success with ids query", + request: getRequest{ + ids: []string{"cap-1", "cap-2"}, + }, + mockEndpoints: getCapabilitiesGetEndpoints("id=in.(cap-1,cap-2)", http.StatusOK, capabilitiesGetTwoResponseJSON), + expected: getExpected[types.Capabilities]{ + result: types.Capabilities{ + { + ID: "cap-1", + Name: "Capability1", + Description: "The first capability", + Version: "1.0.1", + Category: "language", + Disabled: false, + }, + { + ID: "cap-2", + Name: "Capability2", + Description: "The second capability", + Version: "1.0.2", + Category: "language", + Disabled: true, + }, + }, + }, + }, + { + name: "get capabilities invalid json response", + request: getRequest{ + ids: []string{"cap-1"}, + }, + mockEndpoints: getCapabilitiesGetEndpoints("id=in.(cap-1)", http.StatusOK, "["), + expected: getExpected[types.Capabilities]{ + err: "GET ${URL}/postgrest/dataplane_workbench_capabilities?id=in.%28cap-1%29 failed\n" + + " Caused by:\n" + + "\t* unexpected EOF", + }, + }, + { + name: "get capabilities non-200 from server", + request: getRequest{ + ids: []string{"cap-1"}, + }, + mockEndpoints: getCapabilitiesGetEndpoints("id=in.(cap-1)", http.StatusUnauthorized, "unauthorized"), + expected: getExpected[types.Capabilities]{ + err: "GET ${URL}/postgrest/dataplane_workbench_capabilities?id=in.%28cap-1%29 failed\n" + + " Caused by:\n" + + "\t* 401 unauthorized", + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + srv, _ := stubs.NewStubHTTPServer(t, tt.mockEndpoints) + defer srv.Close() + svc := workbench.NewWorkbenchService(srv.URL, "access-token", "csrf-token") + + actual, err := workbench.GetCapabilities(context.Background(), svc, tt.request.ids, tt.request.sort) + if tt.expected.err != "" { + require.EqualError(t, err, strings.ReplaceAll(tt.expected.err, "${URL}", srv.URL)) + return + } + + require.NoError(t, err) + require.Equal(t, tt.expected.result, actual) + }) + } +} + +func TestPrintCapabilities(t *testing.T) { + tests := []struct { + name string + resourcesJSON string + expectedTableCount int + expectedTable string + expectedPrintCalls int + }{ + { + name: "empty resources", + resourcesJSON: capabilitiesEmptyResourcesJSON, + expectedTableCount: 1, + expectedTable: expectedCapabilitiesEmptyTable, + expectedPrintCalls: 1, + }, + { + name: "prints resources", + resourcesJSON: capabilitiesPrintTwoResourcesJSON, + expectedTableCount: 1, + expectedTable: expectedCapabilitiesTwoRowsTable, + expectedPrintCalls: 1, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var resources types.Capabilities + err := json.Unmarshal([]byte(tt.resourcesJSON), &resources) + require.NoError(t, err) + + u := &stubs.StubUI{} + err = workbench.PrintCapabilities(u, "ignored-token", resources) + require.NoError(t, err) + + require.Len(t, u.Tables, tt.expectedTableCount) + tbl := u.Tables[0] + require.Equal(t, tt.expectedTable, tbl.String()) + require.Equal(t, tt.expectedPrintCalls, tbl.PrintCalls) + }) + } +} + +func getCapabilitiesGetEndpoints( + exectedQuery string, + responseStatus int, + responseBody string, +) []stubs.StubHTTPEndpoint { + return []stubs.StubHTTPEndpoint{ + { + Request: stubs.StubHTTPRequest{ + Method: http.MethodGet, + URL: postgrest.Endpoint(constants.WorkbenchEndpointDataplaneWorkbenchCapabilities), + ExpectedHeaders: authHeaders, + ExpectedQuery: exectedQuery, + }, + Response: stubs.StubHTTPResponse{ + Status: responseStatus, + Body: responseBody, + }, + }, + } +} diff --git a/internal/types/types.go b/internal/types/types.go index b05a6b9..ebef03b 100644 --- a/internal/types/types.go +++ b/internal/types/types.go @@ -44,9 +44,22 @@ type WorkspaceRequest struct { EphemeralPVC *corev1.PersistentVolumeClaimSpec `json:"ephemeralPVC,omitempty"` } -// MountRequest identifies a mount path and volume source to be mounted into a -// Job or Workbench. +// MountRequest identifies a volume or capability to be mounted into a Job or +// Workbench. type MountRequest struct { + Capability *CapabilityRequest `json:"capability,omitempty"` + Volume *VolumeRequest `json:"volume,omitempty"` +} + +// CapabilityRequest identifies a capability to be mounted into a Job or +// Workbench. +type CapabilityRequest struct { + ID string `json:"id,omitempty"` +} + +// VolumeRequest identifies a mount path and volume source to be mounted into a +// Job or Workbench. +type VolumeRequest struct { MountPath string `json:"mountPath,omitempty"` VolumeSource *VolumeSource `json:"volumeSource,omitempty"` } @@ -652,6 +665,26 @@ func AsConflictSlice(source Conflicts) []Conflict { return source } +// Capability represents a capability. +type Capability struct { + Category string `json:"category,omitempty"` + DataplaneID string `json:"dataplane_id,omitempty"` + Description string `json:"description,omitempty"` + Disabled bool `json:"disabled,omitempty"` + ID string `json:"id,omitempty"` + Name string `json:"name,omitempty"` + Recommended bool `json:"recommended,omitempty"` + Version string `json:"version,omitempty"` +} + +// Capabilities is a slice of Capability values. +type Capabilities []Capability + +// AsCapabilitySlice converts Capabilities to a plain slice. +func AsCapabilitySlice(source Capabilities) []Capability { + return source +} + // Settings is a slice of Setting values. type Settings map[string]any diff --git a/internal/types/types_test.go b/internal/types/types_test.go index 72d3fbf..164b785 100644 --- a/internal/types/types_test.go +++ b/internal/types/types_test.go @@ -50,6 +50,36 @@ func TestAsApplicationSlice(t *testing.T) { } } +func TestAsCapabilitySlice(t *testing.T) { + cases := []struct { + name string + source types.Capabilities + expected []types.Capability + }{ + { + name: "nil slice", + source: nil, + expected: nil, + }, + { + name: "non-empty slice", + source: types.Capabilities{ + {ID: "application-1"}, + }, + expected: []types.Capability{ + {ID: "application-1"}, + }, + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + actual := types.AsCapabilitySlice(tc.source) + require.Equal(t, tc.expected, actual) + }) + } +} + func TestAsConflictSlice(t *testing.T) { cases := []struct { name string