diff --git a/docs/stackit.md b/docs/stackit.md index 150a76598..884d28368 100644 --- a/docs/stackit.md +++ b/docs/stackit.md @@ -41,6 +41,7 @@ stackit [flags] * [stackit logme](./stackit_logme.md) - Provides functionality for LogMe * [stackit logs](./stackit_logs.md) - Provides functionality for Logs * [stackit mariadb](./stackit_mariadb.md) - Provides functionality for MariaDB +* [stackit model-experiments](./stackit_model-experiments.md) - Provides functionality for AI Model Experiments * [stackit mongodbflex](./stackit_mongodbflex.md) - Provides functionality for MongoDB Flex * [stackit network](./stackit_network.md) - Provides functionality for networks * [stackit network-area](./stackit_network-area.md) - Provides functionality for STACKIT Network Area (SNA) diff --git a/docs/stackit_config_set.md b/docs/stackit_config_set.md index a89e6bc5b..51e19cfc3 100644 --- a/docs/stackit_config_set.md +++ b/docs/stackit_config_set.md @@ -47,6 +47,7 @@ stackit config set [flags] --logme-custom-endpoint string LogMe API base URL, used in calls to this API --logs-custom-endpoint string Logs API base URL, used in calls to this API --mariadb-custom-endpoint string MariaDB API base URL, used in calls to this API + --model-experiments-custom-endpoint string Model Experiments API base URL, used in calls to this API --mongodbflex-custom-endpoint string MongoDB Flex API base URL, used in calls to this API --object-storage-custom-endpoint string Object Storage API base URL, used in calls to this API --observability-custom-endpoint string Observability API base URL, used in calls to this API diff --git a/docs/stackit_config_unset.md b/docs/stackit_config_unset.md index f6c19ebc2..8b8b0ffa3 100644 --- a/docs/stackit_config_unset.md +++ b/docs/stackit_config_unset.md @@ -46,6 +46,7 @@ stackit config unset [flags] --logme-custom-endpoint[=true|false] LogMe API base URL. If unset, uses the default base URL --logs-custom-endpoint[=true|false] Logs API base URL. If unset, uses the default base URL --mariadb-custom-endpoint[=true|false] MariaDB API base URL. If unset, uses the default base URL + --model-experiments-custom-endpoint Model Experiments API base URL. If unset, uses the default base URL --mongodbflex-custom-endpoint[=true|false] MongoDB Flex API base URL. If unset, uses the default base URL --object-storage-custom-endpoint[=true|false] Object Storage API base URL. If unset, uses the default base URL --observability-custom-endpoint[=true|false] Observability API base URL. If unset, uses the default base URL diff --git a/docs/stackit_model-experiments.md b/docs/stackit_model-experiments.md new file mode 100644 index 000000000..0032ec8fd --- /dev/null +++ b/docs/stackit_model-experiments.md @@ -0,0 +1,35 @@ +## stackit model-experiments + +Provides functionality for AI Model Experiments + +### Synopsis + +Provides functionality for AI Model Experiments. + +``` +stackit model-experiments [flags] +``` + +### Options + +``` + -h, --help Help for "stackit model-experiments" +``` + +### Options inherited from parent commands + +``` + -y, --assume-yes If set, skips all confirmation prompts + --async If set, runs the command asynchronously + -o, --output-format string Output format, (one of: [json, pretty, none, yaml]) + -p, --project-id string Project ID + --region string Target region for region-specific requests + --verbosity string Verbosity of the CLI, (one of: [debug, info, warning, error]) (default "info") +``` + +### SEE ALSO + +* [stackit](./stackit.md) - Manage STACKIT resources using the command line +* [stackit model-experiments instance](./stackit_model-experiments_instance.md) - Provides functionality for AI Model Experiments instances +* [stackit model-experiments token](./stackit_model-experiments_token.md) - Provides functionality for AI Model Experiments instance tokens + diff --git a/docs/stackit_model-experiments_instance.md b/docs/stackit_model-experiments_instance.md new file mode 100644 index 000000000..9b6b762bb --- /dev/null +++ b/docs/stackit_model-experiments_instance.md @@ -0,0 +1,38 @@ +## stackit model-experiments instance + +Provides functionality for AI Model Experiments instances + +### Synopsis + +Provides functionality for AI Model Experiments instances. + +``` +stackit model-experiments instance [flags] +``` + +### Options + +``` + -h, --help Help for "stackit model-experiments instance" +``` + +### Options inherited from parent commands + +``` + -y, --assume-yes If set, skips all confirmation prompts + --async If set, runs the command asynchronously + -o, --output-format string Output format, (one of: [json, pretty, none, yaml]) + -p, --project-id string Project ID + --region string Target region for region-specific requests + --verbosity string Verbosity of the CLI, (one of: [debug, info, warning, error]) (default "info") +``` + +### SEE ALSO + +* [stackit model-experiments](./stackit_model-experiments.md) - Provides functionality for AI Model Experiments +* [stackit model-experiments instance create](./stackit_model-experiments_instance_create.md) - Creates an AI Model Experiments instance +* [stackit model-experiments instance delete](./stackit_model-experiments_instance_delete.md) - Deletes an AI Model Experiments instance +* [stackit model-experiments instance describe](./stackit_model-experiments_instance_describe.md) - Shows details of an AI Model Experiments instance +* [stackit model-experiments instance list](./stackit_model-experiments_instance_list.md) - Lists all AI Model Experiments instances +* [stackit model-experiments instance update](./stackit_model-experiments_instance_update.md) - Updates an AI Model Experiments instance + diff --git a/docs/stackit_model-experiments_instance_create.md b/docs/stackit_model-experiments_instance_create.md new file mode 100644 index 000000000..91eecbb73 --- /dev/null +++ b/docs/stackit_model-experiments_instance_create.md @@ -0,0 +1,47 @@ +## stackit model-experiments instance create + +Creates an AI Model Experiments instance + +### Synopsis + +Creates an AI Model Experiments (MLflow) instance in your STACKIT project. + +``` +stackit model-experiments instance create [flags] +``` + +### Examples + +``` + Create an AI Model Experiments instance with name "my-tracking" + $ stackit model-experiments instance create --name my-tracking + + Create an instance with a description, labels, and deleted experiment retention + $ stackit model-experiments instance create --name my-tracking --description "team tracking server" --labels env=prod,team=ml --deleted-experiment-retention 30d +``` + +### Options + +``` + --deleted-experiment-retention string Retention period for deleted experiments before permanent purge, e.g. "30d" (min 1d, max 90d) + --description string Instance description + -h, --help Help for "stackit model-experiments instance create" + --labels stringToString Labels are comma-separated key-value string pairs, e.g. "--labels env=prod,team=ml" (default []) + -n, --name string Instance name +``` + +### Options inherited from parent commands + +``` + -y, --assume-yes If set, skips all confirmation prompts + --async If set, runs the command asynchronously + -o, --output-format string Output format, (one of: [json, pretty, none, yaml]) + -p, --project-id string Project ID + --region string Target region for region-specific requests + --verbosity string Verbosity of the CLI, (one of: [debug, info, warning, error]) (default "info") +``` + +### SEE ALSO + +* [stackit model-experiments instance](./stackit_model-experiments_instance.md) - Provides functionality for AI Model Experiments instances + diff --git a/docs/stackit_model-experiments_instance_delete.md b/docs/stackit_model-experiments_instance_delete.md new file mode 100644 index 000000000..b5139f838 --- /dev/null +++ b/docs/stackit_model-experiments_instance_delete.md @@ -0,0 +1,40 @@ +## stackit model-experiments instance delete + +Deletes an AI Model Experiments instance + +### Synopsis + +Deletes an AI Model Experiments instance from a STACKIT project. + +``` +stackit model-experiments instance delete INSTANCE_ID [flags] +``` + +### Examples + +``` + Delete an AI Model Experiments instance with ID "xxx" + $ stackit model-experiments instance delete xxx +``` + +### Options + +``` + -h, --help Help for "stackit model-experiments instance delete" +``` + +### Options inherited from parent commands + +``` + -y, --assume-yes If set, skips all confirmation prompts + --async If set, runs the command asynchronously + -o, --output-format string Output format, (one of: [json, pretty, none, yaml]) + -p, --project-id string Project ID + --region string Target region for region-specific requests + --verbosity string Verbosity of the CLI, (one of: [debug, info, warning, error]) (default "info") +``` + +### SEE ALSO + +* [stackit model-experiments instance](./stackit_model-experiments_instance.md) - Provides functionality for AI Model Experiments instances + diff --git a/docs/stackit_model-experiments_instance_describe.md b/docs/stackit_model-experiments_instance_describe.md new file mode 100644 index 000000000..c70200822 --- /dev/null +++ b/docs/stackit_model-experiments_instance_describe.md @@ -0,0 +1,43 @@ +## stackit model-experiments instance describe + +Shows details of an AI Model Experiments instance + +### Synopsis + +Shows details of an AI Model Experiments instance in a STACKIT project. + +``` +stackit model-experiments instance describe INSTANCE_ID [flags] +``` + +### Examples + +``` + Show details of an AI Model Experiments instance with ID "xxx" + $ stackit model-experiments instance describe xxx + + Get details of an AI Model Experiments instance with ID "xxx" in JSON format + $ stackit model-experiments instance describe xxx --output-format json +``` + +### Options + +``` + -h, --help Help for "stackit model-experiments instance describe" +``` + +### Options inherited from parent commands + +``` + -y, --assume-yes If set, skips all confirmation prompts + --async If set, runs the command asynchronously + -o, --output-format string Output format, (one of: [json, pretty, none, yaml]) + -p, --project-id string Project ID + --region string Target region for region-specific requests + --verbosity string Verbosity of the CLI, (one of: [debug, info, warning, error]) (default "info") +``` + +### SEE ALSO + +* [stackit model-experiments instance](./stackit_model-experiments_instance.md) - Provides functionality for AI Model Experiments instances + diff --git a/docs/stackit_model-experiments_instance_list.md b/docs/stackit_model-experiments_instance_list.md new file mode 100644 index 000000000..6b22709fa --- /dev/null +++ b/docs/stackit_model-experiments_instance_list.md @@ -0,0 +1,50 @@ +## stackit model-experiments instance list + +Lists all AI Model Experiments instances + +### Synopsis + +Lists all AI Model Experiments instances in a STACKIT project. + +``` +stackit model-experiments instance list [flags] +``` + +### Examples + +``` + List AI Model Experiments instances in a project + $ stackit model-experiments instance list + + List AI Model Experiments instances in a project in region eu02 + $ stackit model-experiments instance list --region eu02 + + List AI Model Experiments instances in JSON format + $ stackit model-experiments instance list --output-format json + + List up to 10 AI Model Experiments instances + $ stackit model-experiments instance list --limit 10 +``` + +### Options + +``` + -h, --help Help for "stackit model-experiments instance list" + --limit int Maximum number of entries to list +``` + +### Options inherited from parent commands + +``` + -y, --assume-yes If set, skips all confirmation prompts + --async If set, runs the command asynchronously + -o, --output-format string Output format, (one of: [json, pretty, none, yaml]) + -p, --project-id string Project ID + --region string Target region for region-specific requests + --verbosity string Verbosity of the CLI, (one of: [debug, info, warning, error]) (default "info") +``` + +### SEE ALSO + +* [stackit model-experiments instance](./stackit_model-experiments_instance.md) - Provides functionality for AI Model Experiments instances + diff --git a/docs/stackit_model-experiments_instance_update.md b/docs/stackit_model-experiments_instance_update.md new file mode 100644 index 000000000..4c691e8a4 --- /dev/null +++ b/docs/stackit_model-experiments_instance_update.md @@ -0,0 +1,53 @@ +## stackit model-experiments instance update + +Updates an AI Model Experiments instance + +### Synopsis + +Partially updates an AI Model Experiments instance in a STACKIT project. + +``` +stackit model-experiments instance update INSTANCE_ID [flags] +``` + +### Examples + +``` + Update the name of an AI Model Experiments instance with ID "xxx" + $ stackit model-experiments instance update xxx --name my-new-name + + Update the description of an AI Model Experiments instance + $ stackit model-experiments instance update xxx --description "team tracking server" + + Update labels on an AI Model Experiments instance + $ stackit model-experiments instance update xxx --labels env=prod,team=ml + + Update multiple fields of an AI Model Experiments instance + $ stackit model-experiments instance update xxx --name my-new-name --description "team tracking server" --labels env=prod,team=ml --deleted-experiment-retention 30d +``` + +### Options + +``` + --deleted-experiment-retention string Retention period for deleted experiments before permanent purge, e.g. "30d" (min 1d, max 90d) + --description string Instance description + -h, --help Help for "stackit model-experiments instance update" + --labels stringToString Labels are comma-separated key-value string pairs, e.g. "--labels env=prod,team=ml" (default []) + -n, --name string Instance name +``` + +### Options inherited from parent commands + +``` + -y, --assume-yes If set, skips all confirmation prompts + --async If set, runs the command asynchronously + -o, --output-format string Output format, (one of: [json, pretty, none, yaml]) + -p, --project-id string Project ID + --region string Target region for region-specific requests + --verbosity string Verbosity of the CLI, (one of: [debug, info, warning, error]) (default "info") +``` + +### SEE ALSO + +* [stackit model-experiments instance](./stackit_model-experiments_instance.md) - Provides functionality for AI Model Experiments instances + diff --git a/docs/stackit_model-experiments_token.md b/docs/stackit_model-experiments_token.md new file mode 100644 index 000000000..4a92ce029 --- /dev/null +++ b/docs/stackit_model-experiments_token.md @@ -0,0 +1,38 @@ +## stackit model-experiments token + +Provides functionality for AI Model Experiments instance tokens + +### Synopsis + +Provides functionality for AI Model Experiments instance tokens. + +``` +stackit model-experiments token [flags] +``` + +### Options + +``` + -h, --help Help for "stackit model-experiments token" +``` + +### Options inherited from parent commands + +``` + -y, --assume-yes If set, skips all confirmation prompts + --async If set, runs the command asynchronously + -o, --output-format string Output format, (one of: [json, pretty, none, yaml]) + -p, --project-id string Project ID + --region string Target region for region-specific requests + --verbosity string Verbosity of the CLI, (one of: [debug, info, warning, error]) (default "info") +``` + +### SEE ALSO + +* [stackit model-experiments](./stackit_model-experiments.md) - Provides functionality for AI Model Experiments +* [stackit model-experiments token create](./stackit_model-experiments_token_create.md) - Creates an AI Model Experiments instance token +* [stackit model-experiments token delete](./stackit_model-experiments_token_delete.md) - Deletes an AI Model Experiments instance token +* [stackit model-experiments token describe](./stackit_model-experiments_token_describe.md) - Shows details of an AI Model Experiments instance token +* [stackit model-experiments token list](./stackit_model-experiments_token_list.md) - Lists all AI Model Experiments instance tokens +* [stackit model-experiments token update](./stackit_model-experiments_token_update.md) - Updates an AI Model Experiments instance token + diff --git a/docs/stackit_model-experiments_token_create.md b/docs/stackit_model-experiments_token_create.md new file mode 100644 index 000000000..2fd664183 --- /dev/null +++ b/docs/stackit_model-experiments_token_create.md @@ -0,0 +1,48 @@ +## stackit model-experiments token create + +Creates an AI Model Experiments instance token + +### Synopsis + +Creates an auth token for an AI Model Experiments instance. + +``` +stackit model-experiments token create [flags] +``` + +### Examples + +``` + Create an auth token + $ stackit model-experiments token create --instance-id xxx --name my-token + + Create an auth token with a description, labels, and time to live + $ stackit model-experiments token create --instance-id xxx --name my-token --description "service token" --labels env=prod,team=ml --ttl-duration 30d +``` + +### Options + +``` + --description string Token description + -h, --help Help for "stackit model-experiments token create" + --instance-id string ID of the instance + --labels stringToString Labels are comma-separated key-value string pairs, e.g. "--labels env=prod,team=ml" (default []) + --name string Token name + --ttl-duration string Maximum allowed duration is 6 months. If not set, defaults to 6 months. Format example: "720h" or "30d" +``` + +### Options inherited from parent commands + +``` + -y, --assume-yes If set, skips all confirmation prompts + --async If set, runs the command asynchronously + -o, --output-format string Output format, (one of: [json, pretty, none, yaml]) + -p, --project-id string Project ID + --region string Target region for region-specific requests + --verbosity string Verbosity of the CLI, (one of: [debug, info, warning, error]) (default "info") +``` + +### SEE ALSO + +* [stackit model-experiments token](./stackit_model-experiments_token.md) - Provides functionality for AI Model Experiments instance tokens + diff --git a/docs/stackit_model-experiments_token_delete.md b/docs/stackit_model-experiments_token_delete.md new file mode 100644 index 000000000..8ef619be7 --- /dev/null +++ b/docs/stackit_model-experiments_token_delete.md @@ -0,0 +1,41 @@ +## stackit model-experiments token delete + +Deletes an AI Model Experiments instance token + +### Synopsis + +Deletes an auth token from an AI Model Experiments instance. + +``` +stackit model-experiments token delete TOKEN_ID [flags] +``` + +### Examples + +``` + Delete an auth token with ID "xxx" + $ stackit model-experiments token delete xxx --instance-id yyy +``` + +### Options + +``` + -h, --help Help for "stackit model-experiments token delete" + --instance-id string ID of the instance +``` + +### Options inherited from parent commands + +``` + -y, --assume-yes If set, skips all confirmation prompts + --async If set, runs the command asynchronously + -o, --output-format string Output format, (one of: [json, pretty, none, yaml]) + -p, --project-id string Project ID + --region string Target region for region-specific requests + --verbosity string Verbosity of the CLI, (one of: [debug, info, warning, error]) (default "info") +``` + +### SEE ALSO + +* [stackit model-experiments token](./stackit_model-experiments_token.md) - Provides functionality for AI Model Experiments instance tokens + diff --git a/docs/stackit_model-experiments_token_describe.md b/docs/stackit_model-experiments_token_describe.md new file mode 100644 index 000000000..030428d5c --- /dev/null +++ b/docs/stackit_model-experiments_token_describe.md @@ -0,0 +1,44 @@ +## stackit model-experiments token describe + +Shows details of an AI Model Experiments instance token + +### Synopsis + +Shows details of an auth token for an AI Model Experiments instance. + +``` +stackit model-experiments token describe TOKEN_ID [flags] +``` + +### Examples + +``` + Show details of an auth token with ID "xxx" + $ stackit model-experiments token describe xxx --instance-id yyy + + Show details of an auth token with ID "xxx" in JSON format + $ stackit model-experiments token describe xxx --instance-id yyy --output-format json +``` + +### Options + +``` + -h, --help Help for "stackit model-experiments token describe" + --instance-id string ID of the instance +``` + +### Options inherited from parent commands + +``` + -y, --assume-yes If set, skips all confirmation prompts + --async If set, runs the command asynchronously + -o, --output-format string Output format, (one of: [json, pretty, none, yaml]) + -p, --project-id string Project ID + --region string Target region for region-specific requests + --verbosity string Verbosity of the CLI, (one of: [debug, info, warning, error]) (default "info") +``` + +### SEE ALSO + +* [stackit model-experiments token](./stackit_model-experiments_token.md) - Provides functionality for AI Model Experiments instance tokens + diff --git a/docs/stackit_model-experiments_token_list.md b/docs/stackit_model-experiments_token_list.md new file mode 100644 index 000000000..cb5641ef5 --- /dev/null +++ b/docs/stackit_model-experiments_token_list.md @@ -0,0 +1,51 @@ +## stackit model-experiments token list + +Lists all AI Model Experiments instance tokens + +### Synopsis + +Lists all auth tokens for an AI Model Experiments instance. + +``` +stackit model-experiments token list [flags] +``` + +### Examples + +``` + List all tokens for an instance + $ stackit model-experiments token list --instance-id xxx + + List tokens in region eu02 + $ stackit model-experiments token list --instance-id xxx --region eu02 + + List tokens in JSON format + $ stackit model-experiments token list --instance-id xxx --output-format json + + List up to 10 tokens for an instance + $ stackit model-experiments token list --instance-id xxx --limit 10 +``` + +### Options + +``` + -h, --help Help for "stackit model-experiments token list" + --instance-id string ID of the instance + --limit int Maximum number of entries to list +``` + +### Options inherited from parent commands + +``` + -y, --assume-yes If set, skips all confirmation prompts + --async If set, runs the command asynchronously + -o, --output-format string Output format, (one of: [json, pretty, none, yaml]) + -p, --project-id string Project ID + --region string Target region for region-specific requests + --verbosity string Verbosity of the CLI, (one of: [debug, info, warning, error]) (default "info") +``` + +### SEE ALSO + +* [stackit model-experiments token](./stackit_model-experiments_token.md) - Provides functionality for AI Model Experiments instance tokens + diff --git a/docs/stackit_model-experiments_token_update.md b/docs/stackit_model-experiments_token_update.md new file mode 100644 index 000000000..fa67d50ac --- /dev/null +++ b/docs/stackit_model-experiments_token_update.md @@ -0,0 +1,53 @@ +## stackit model-experiments token update + +Updates an AI Model Experiments instance token + +### Synopsis + +Partially updates an auth token for an AI Model Experiments instance. + +``` +stackit model-experiments token update TOKEN_ID [flags] +``` + +### Examples + +``` + Update the name of an auth token with ID "xxx" + $ stackit model-experiments token update xxx --instance-id yyy --name updated-token + + Update the description of an auth token + $ stackit model-experiments token update xxx --instance-id yyy --description "updated token" + + Update labels on an auth token + $ stackit model-experiments token update xxx --instance-id yyy --labels env=prod,team=ml + + Update multiple fields of an auth token + $ stackit model-experiments token update xxx --instance-id yyy --name updated-token --description "updated token" --labels env=prod,team=ml +``` + +### Options + +``` + --description string Token description + -h, --help Help for "stackit model-experiments token update" + --instance-id string ID of the instance + --labels stringToString Labels are comma-separated key-value string pairs, e.g. "--labels env=prod,team=ml" (default []) + --name string Token name +``` + +### Options inherited from parent commands + +``` + -y, --assume-yes If set, skips all confirmation prompts + --async If set, runs the command asynchronously + -o, --output-format string Output format, (one of: [json, pretty, none, yaml]) + -p, --project-id string Project ID + --region string Target region for region-specific requests + --verbosity string Verbosity of the CLI, (one of: [debug, info, warning, error]) (default "info") +``` + +### SEE ALSO + +* [stackit model-experiments token](./stackit_model-experiments_token.md) - Provides functionality for AI Model Experiments instance tokens + diff --git a/go.mod b/go.mod index 0f3649622..ee41be306 100644 --- a/go.mod +++ b/go.mod @@ -27,6 +27,7 @@ require ( github.com/stackitcloud/stackit-sdk-go/services/iaas v1.15.1 github.com/stackitcloud/stackit-sdk-go/services/intake v0.12.0 github.com/stackitcloud/stackit-sdk-go/services/logs v0.12.0 + github.com/stackitcloud/stackit-sdk-go/services/modelexperiments v0.3.2 github.com/stackitcloud/stackit-sdk-go/services/mongodbflex v1.14.0 github.com/stackitcloud/stackit-sdk-go/services/opensearch v1.5.0 github.com/stackitcloud/stackit-sdk-go/services/postgresflex v1.16.0 diff --git a/go.sum b/go.sum index 66913822f..48da1416f 100644 --- a/go.sum +++ b/go.sum @@ -640,6 +640,8 @@ github.com/stackitcloud/stackit-sdk-go/services/logs v0.12.0 h1:4ZUQuj5Zp9E4Ebym github.com/stackitcloud/stackit-sdk-go/services/logs v0.12.0/go.mod h1:YKBTmDJmeVeaWKnmJoyLTsZCy/FkdWcD/GXm3rAvG3c= github.com/stackitcloud/stackit-sdk-go/services/mariadb v1.4.0 h1:LFpdvASJnTv5Y/PEfwgK0pn7ixXLgcUmLt2cRTg979g= github.com/stackitcloud/stackit-sdk-go/services/mariadb v1.4.0/go.mod h1:GpFHOEVEq+Pog9dWPMvGeF4mEvB+MVLIRh3/jB1isUI= +github.com/stackitcloud/stackit-sdk-go/services/modelexperiments v0.3.2 h1:9ptgH6o+xHMoBF0X05MQQ87k+MdDsYJ21GywJc2kL9I= +github.com/stackitcloud/stackit-sdk-go/services/modelexperiments v0.3.2/go.mod h1:awsNt1BD4IYhwXI/KhEvNiU5M6zXtAvUXPZO8YBAmIA= github.com/stackitcloud/stackit-sdk-go/services/mongodbflex v1.14.0 h1:GdCzKryyTnQM+al6ntIp8gBkJfy7htUGAbAb5xxTIvc= github.com/stackitcloud/stackit-sdk-go/services/mongodbflex v1.14.0/go.mod h1:yNxGU6mwDzXX82/QfgxRzg2M3+ktVNKS1qPzT01QIi0= github.com/stackitcloud/stackit-sdk-go/services/objectstorage v1.13.0 h1:lVFUq1AVW2wgiKjtcr8FeEY+Jxw3hBXyh7I+qWW6ad4= diff --git a/internal/cmd/config/set/set.go b/internal/cmd/config/set/set.go index 477695495..d8a4e4d48 100644 --- a/internal/cmd/config/set/set.go +++ b/internal/cmd/config/set/set.go @@ -32,6 +32,7 @@ const ( loadBalancerCustomEndpointFlag = "load-balancer-custom-endpoint" logMeCustomEndpointFlag = "logme-custom-endpoint" mariaDBCustomEndpointFlag = "mariadb-custom-endpoint" + modelExperimentsCustomEndpointFlag = "model-experiments-custom-endpoint" mongoDBFlexCustomEndpointFlag = "mongodbflex-custom-endpoint" objectStorageCustomEndpointFlag = "object-storage-custom-endpoint" observabilityCustomEndpointFlag = "observability-custom-endpoint" @@ -157,6 +158,7 @@ func configureFlags(cmd *cobra.Command) { cmd.Flags().String(loadBalancerCustomEndpointFlag, "", "Load Balancer API base URL, used in calls to this API") cmd.Flags().String(logMeCustomEndpointFlag, "", "LogMe API base URL, used in calls to this API") cmd.Flags().String(mariaDBCustomEndpointFlag, "", "MariaDB API base URL, used in calls to this API") + cmd.Flags().String(modelExperimentsCustomEndpointFlag, "", "Model Experiments API base URL, used in calls to this API") cmd.Flags().String(mongoDBFlexCustomEndpointFlag, "", "MongoDB Flex API base URL, used in calls to this API") cmd.Flags().String(objectStorageCustomEndpointFlag, "", "Object Storage API base URL, used in calls to this API") cmd.Flags().String(openSearchCustomEndpointFlag, "", "OpenSearch API base URL, used in calls to this API") @@ -210,6 +212,8 @@ func configureFlags(cmd *cobra.Command) { cobra.CheckErr(err) err = viper.BindPFlag(config.MariaDBCustomEndpointKey, cmd.Flags().Lookup(mariaDBCustomEndpointFlag)) cobra.CheckErr(err) + err = viper.BindPFlag(config.ModelExperimentsCustomEndpointKey, cmd.Flags().Lookup(modelExperimentsCustomEndpointFlag)) + cobra.CheckErr(err) err = viper.BindPFlag(config.MongoDBFlexCustomEndpointKey, cmd.Flags().Lookup(mongoDBFlexCustomEndpointFlag)) cobra.CheckErr(err) err = viper.BindPFlag(config.ObjectStorageCustomEndpointKey, cmd.Flags().Lookup(objectStorageCustomEndpointFlag)) diff --git a/internal/cmd/config/unset/unset.go b/internal/cmd/config/unset/unset.go index 57600ecea..29e3a274b 100644 --- a/internal/cmd/config/unset/unset.go +++ b/internal/cmd/config/unset/unset.go @@ -35,6 +35,7 @@ const ( loadBalancerCustomEndpointFlag = "load-balancer-custom-endpoint" logMeCustomEndpointFlag = "logme-custom-endpoint" mariaDBCustomEndpointFlag = "mariadb-custom-endpoint" + modelExperimentsCustomEndpointFlag = "model-experiments-custom-endpoint" mongoDBFlexCustomEndpointFlag = "mongodbflex-custom-endpoint" objectStorageCustomEndpointFlag = "object-storage-custom-endpoint" observabilityCustomEndpointFlag = "observability-custom-endpoint" @@ -89,6 +90,7 @@ type inputModel struct { LoadBalancerCustomEndpoint bool LogMeCustomEndpoint bool MariaDBCustomEndpoint bool + ModelExperimentsCustomEndpoint bool MongoDBFlexCustomEndpoint bool ObjectStorageCustomEndpoint bool ObservabilityCustomEndpoint bool @@ -196,6 +198,9 @@ func NewCmd(params *types.CmdParams) *cobra.Command { if model.MariaDBCustomEndpoint { viper.Set(config.MariaDBCustomEndpointKey, "") } + if model.ModelExperimentsCustomEndpoint { + viper.Set(config.ModelExperimentsCustomEndpointKey, "") + } if model.MongoDBFlexCustomEndpoint { viper.Set(config.MongoDBFlexCustomEndpointKey, "") } @@ -305,6 +310,7 @@ func configureFlags(cmd *cobra.Command) { cmd.Flags().Bool(loadBalancerCustomEndpointFlag, false, "Load Balancer API base URL. If unset, uses the default base URL") cmd.Flags().Bool(logMeCustomEndpointFlag, false, "LogMe API base URL. If unset, uses the default base URL") cmd.Flags().Bool(mariaDBCustomEndpointFlag, false, "MariaDB API base URL. If unset, uses the default base URL") + cmd.Flags().Bool(modelExperimentsCustomEndpointFlag, false, "Model Experiments API base URL. If unset, uses the default base URL") cmd.Flags().Bool(mongoDBFlexCustomEndpointFlag, false, "MongoDB Flex API base URL. If unset, uses the default base URL") cmd.Flags().Bool(objectStorageCustomEndpointFlag, false, "Object Storage API base URL. If unset, uses the default base URL") cmd.Flags().Bool(openSearchCustomEndpointFlag, false, "OpenSearch API base URL. If unset, uses the default base URL") @@ -354,6 +360,7 @@ func parseInput(p *print.Printer, cmd *cobra.Command) *inputModel { LoadBalancerCustomEndpoint: flags.FlagToBoolValue(p, cmd, loadBalancerCustomEndpointFlag), LogMeCustomEndpoint: flags.FlagToBoolValue(p, cmd, logMeCustomEndpointFlag), MariaDBCustomEndpoint: flags.FlagToBoolValue(p, cmd, mariaDBCustomEndpointFlag), + ModelExperimentsCustomEndpoint: flags.FlagToBoolValue(p, cmd, modelExperimentsCustomEndpointFlag), MongoDBFlexCustomEndpoint: flags.FlagToBoolValue(p, cmd, mongoDBFlexCustomEndpointFlag), ObjectStorageCustomEndpoint: flags.FlagToBoolValue(p, cmd, objectStorageCustomEndpointFlag), ObservabilityCustomEndpoint: flags.FlagToBoolValue(p, cmd, observabilityCustomEndpointFlag), diff --git a/internal/cmd/config/unset/unset_test.go b/internal/cmd/config/unset/unset_test.go index 55008562d..1c5b5966b 100644 --- a/internal/cmd/config/unset/unset_test.go +++ b/internal/cmd/config/unset/unset_test.go @@ -22,37 +22,38 @@ func fixtureFlagValues(mods ...func(flagValues map[string]bool)) map[string]bool identityProviderCustomClientIdFlag: true, allowedUrlDomainFlag: true, - authorizationCustomEndpointFlag: true, - automationCustomEndpointFlag: true, - albWafCustomEndpointFlag: true, - dnsCustomEndpointFlag: true, - edgeCustomEndpointFlag: true, - loadBalancerCustomEndpointFlag: true, - logMeCustomEndpointFlag: true, - mariaDBCustomEndpointFlag: true, - objectStorageCustomEndpointFlag: true, - observabilityCustomEndpointFlag: true, - openSearchCustomEndpointFlag: true, - rabbitMQCustomEndpointFlag: true, - redisCustomEndpointFlag: true, - resourceManagerCustomEndpointFlag: true, - secretsManagerCustomEndpointFlag: true, - kmsCustomEndpointFlag: true, - serviceAccountCustomEndpointFlag: true, - serverBackupCustomEndpointFlag: true, - serverOsUpdateCustomEndpointFlag: true, - runCommandCustomEndpointFlag: true, - scfCustomEndpointFlag: true, - sfsCustomEndpointFlag: true, - skeCustomEndpointFlag: true, - sqlServerFlexCustomEndpointFlag: true, - iaasAlphaCustomEndpointFlag: true, - iaasCustomEndpointFlag: true, - tokenCustomEndpointFlag: true, - intakeCustomEndpointFlag: true, - logsCustomEndpointFlag: true, - cdnCustomEndpointFlag: true, - vpnCustomEndpointFlag: true, + authorizationCustomEndpointFlag: true, + automationCustomEndpointFlag: true, + albWafCustomEndpointFlag: true, + dnsCustomEndpointFlag: true, + edgeCustomEndpointFlag: true, + loadBalancerCustomEndpointFlag: true, + logMeCustomEndpointFlag: true, + mariaDBCustomEndpointFlag: true, + modelExperimentsCustomEndpointFlag: true, + objectStorageCustomEndpointFlag: true, + observabilityCustomEndpointFlag: true, + openSearchCustomEndpointFlag: true, + rabbitMQCustomEndpointFlag: true, + redisCustomEndpointFlag: true, + resourceManagerCustomEndpointFlag: true, + secretsManagerCustomEndpointFlag: true, + kmsCustomEndpointFlag: true, + serviceAccountCustomEndpointFlag: true, + serverBackupCustomEndpointFlag: true, + serverOsUpdateCustomEndpointFlag: true, + runCommandCustomEndpointFlag: true, + scfCustomEndpointFlag: true, + sfsCustomEndpointFlag: true, + skeCustomEndpointFlag: true, + sqlServerFlexCustomEndpointFlag: true, + iaasAlphaCustomEndpointFlag: true, + iaasCustomEndpointFlag: true, + tokenCustomEndpointFlag: true, + intakeCustomEndpointFlag: true, + logsCustomEndpointFlag: true, + cdnCustomEndpointFlag: true, + vpnCustomEndpointFlag: true, } for _, mod := range mods { mod(flagValues) @@ -73,37 +74,38 @@ func fixtureInputModel(mods ...func(model *inputModel)) *inputModel { IdentityProviderCustomClientID: true, AllowedUrlDomain: true, - AuthorizationCustomEndpoint: true, - AutomationCustomEndpoint: true, - AlbWafCustomEndpoint: true, - DNSCustomEndpoint: true, - EdgeCustomEndpoint: true, - LoadBalancerCustomEndpoint: true, - LogMeCustomEndpoint: true, - MariaDBCustomEndpoint: true, - ObjectStorageCustomEndpoint: true, - ObservabilityCustomEndpoint: true, - OpenSearchCustomEndpoint: true, - RabbitMQCustomEndpoint: true, - RedisCustomEndpoint: true, - ResourceManagerCustomEndpoint: true, - SecretsManagerCustomEndpoint: true, - KMSCustomEndpoint: true, - ServiceAccountCustomEndpoint: true, - ServerBackupCustomEndpoint: true, - ServerOsUpdateCustomEndpoint: true, - RunCommandCustomEndpoint: true, - ScfCustomEndpoint: true, - SfsCustomEndpoint: true, - SKECustomEndpoint: true, - SQLServerFlexCustomEndpoint: true, - IaaSAlphaCustomEndpoint: true, - IaaSCustomEndpoint: true, - TokenCustomEndpoint: true, - IntakeCustomEndpoint: true, - LogsCustomEndpoint: true, - CDNCustomEndpoint: true, - VpnCustomEndpoint: true, + AuthorizationCustomEndpoint: true, + AutomationCustomEndpoint: true, + AlbWafCustomEndpoint: true, + DNSCustomEndpoint: true, + EdgeCustomEndpoint: true, + LoadBalancerCustomEndpoint: true, + LogMeCustomEndpoint: true, + MariaDBCustomEndpoint: true, + ModelExperimentsCustomEndpoint: true, + ObjectStorageCustomEndpoint: true, + ObservabilityCustomEndpoint: true, + OpenSearchCustomEndpoint: true, + RabbitMQCustomEndpoint: true, + RedisCustomEndpoint: true, + ResourceManagerCustomEndpoint: true, + SecretsManagerCustomEndpoint: true, + KMSCustomEndpoint: true, + ServiceAccountCustomEndpoint: true, + ServerBackupCustomEndpoint: true, + ServerOsUpdateCustomEndpoint: true, + RunCommandCustomEndpoint: true, + ScfCustomEndpoint: true, + SfsCustomEndpoint: true, + SKECustomEndpoint: true, + SQLServerFlexCustomEndpoint: true, + IaaSAlphaCustomEndpoint: true, + IaaSCustomEndpoint: true, + TokenCustomEndpoint: true, + IntakeCustomEndpoint: true, + LogsCustomEndpoint: true, + CDNCustomEndpoint: true, + VpnCustomEndpoint: true, } for _, mod := range mods { mod(model) @@ -148,6 +150,7 @@ func TestParseInput(t *testing.T) { model.LoadBalancerCustomEndpoint = false model.LogMeCustomEndpoint = false model.MariaDBCustomEndpoint = false + model.ModelExperimentsCustomEndpoint = false model.ObjectStorageCustomEndpoint = false model.ObservabilityCustomEndpoint = false model.OpenSearchCustomEndpoint = false @@ -303,6 +306,16 @@ func TestParseInput(t *testing.T) { model.ServiceAccountCustomEndpoint = false }), }, + { + description: "model experiments custom endpoint empty", + flagValues: fixtureFlagValues(func(flagValues map[string]bool) { + flagValues[modelExperimentsCustomEndpointFlag] = false + }), + isValid: true, + expectedModel: fixtureInputModel(func(model *inputModel) { + model.ModelExperimentsCustomEndpoint = false + }), + }, { description: "scf custom endpoint empty", flagValues: fixtureFlagValues(func(flagValues map[string]bool) { diff --git a/internal/cmd/modelexperiments/instance/create/create.go b/internal/cmd/modelexperiments/instance/create/create.go new file mode 100644 index 000000000..4ce907549 --- /dev/null +++ b/internal/cmd/modelexperiments/instance/create/create.go @@ -0,0 +1,165 @@ +package create + +import ( + "context" + "fmt" + + "github.com/spf13/cobra" + + "github.com/stackitcloud/stackit-cli/internal/pkg/args" + cliErr "github.com/stackitcloud/stackit-cli/internal/pkg/errors" + "github.com/stackitcloud/stackit-cli/internal/pkg/examples" + "github.com/stackitcloud/stackit-cli/internal/pkg/flags" + "github.com/stackitcloud/stackit-cli/internal/pkg/globalflags" + "github.com/stackitcloud/stackit-cli/internal/pkg/print" + "github.com/stackitcloud/stackit-cli/internal/pkg/projectname" + "github.com/stackitcloud/stackit-cli/internal/pkg/services/modelexperiments/client" + "github.com/stackitcloud/stackit-cli/internal/pkg/spinner" + "github.com/stackitcloud/stackit-cli/internal/pkg/types" + + modelexperiments "github.com/stackitcloud/stackit-sdk-go/services/modelexperiments/v1api" + "github.com/stackitcloud/stackit-sdk-go/services/modelexperiments/v1api/wait" +) + +const ( + nameFlag = "name" + descriptionFlag = "description" + labelsFlag = "labels" + retentionFlag = "deleted-experiment-retention" +) + +type inputModel struct { + *globalflags.GlobalFlagModel + + Name string + Description *string + Labels *map[string]string + Retention *string +} + +func NewCmd(params *types.CmdParams) *cobra.Command { + cmd := &cobra.Command{ + Use: "create", + Short: "Creates an AI Model Experiments instance", + Long: "Creates an AI Model Experiments (MLflow) instance in your STACKIT project.", + Args: args.NoArgs, + Example: examples.Build( + examples.NewExample( + `Create an AI Model Experiments instance with name "my-tracking"`, + `$ stackit model-experiments instance create --name my-tracking`), + examples.NewExample( + `Create an instance with a description, labels, and deleted experiment retention`, + `$ stackit model-experiments instance create --name my-tracking --description "team tracking server" --labels env=prod,team=ml --deleted-experiment-retention 30d`), + ), + RunE: func(cmd *cobra.Command, _ []string) error { + ctx := context.Background() + + model, err := parseInput(params.Printer, cmd, nil) + if err != nil { + return err + } + + apiClient, err := client.ConfigureClient(params.Printer, params.CliVersion) + if err != nil { + return err + } + + projectLabel, err := projectname.GetProjectName(ctx, params.Printer, params.CliVersion, cmd) + if err != nil { + params.Printer.Debug(print.ErrorLevel, "get project name: %v", err) + projectLabel = model.ProjectId + } else if projectLabel == "" { + projectLabel = model.ProjectId + } + + prompt := fmt.Sprintf("Are you sure you want to create an AI Model Experiments instance for project %q?", projectLabel) + if err := params.Printer.PromptForConfirmation(prompt); err != nil { + return err + } + + req := buildRequest(ctx, model, apiClient) + resp, err := req.Execute() + if err != nil { + return fmt.Errorf("create AI Model Experiments instance: %w", err) + } + if resp == nil { + return fmt.Errorf("create AI Model Experiments instance: response instance is nil") + } + + if !model.Async { + err := spinner.Run(params.Printer, "Creating AI Model Experiments instance", func() error { + _, err = wait.CreateInstanceWaitHandler(ctx, apiClient.DefaultAPI, model.Region, model.ProjectId, resp.Instance.Id).WaitWithContext(ctx) + return err + }) + if err != nil { + return fmt.Errorf("wait for AI Model Experiments instance creation: %w", err) + } + } + + return outputResult(params.Printer, model, projectLabel, resp) + }, + } + configureFlags(cmd) + return cmd +} + +func configureFlags(cmd *cobra.Command) { + cmd.Flags().StringP(nameFlag, "n", "", "Instance name") + cmd.Flags().String(descriptionFlag, "", "Instance description") + cmd.Flags().StringToString(labelsFlag, nil, `Labels are comma-separated key-value string pairs, e.g. "--labels env=prod,team=ml"`) + cmd.Flags().String(retentionFlag, "", `Retention period for deleted experiments before permanent purge, e.g. "30d" (min 1d, max 90d)`) + err := flags.MarkFlagsRequired(cmd, nameFlag) + cobra.CheckErr(err) +} + +func parseInput(p *print.Printer, cmd *cobra.Command, _ []string) (*inputModel, error) { + globalFlags := globalflags.Parse(p, cmd) + if globalFlags.ProjectId == "" { + return nil, &cliErr.ProjectIdError{} + } + + model := inputModel{ + GlobalFlagModel: globalFlags, + Name: flags.FlagToStringValue(p, cmd, nameFlag), + Description: flags.FlagToStringPointer(p, cmd, descriptionFlag), + Labels: flags.FlagToStringToStringPointer(p, cmd, labelsFlag), + Retention: flags.FlagToStringPointer(p, cmd, retentionFlag), + } + + p.DebugInputModel(model) + return &model, nil +} + +func buildRequest(ctx context.Context, model *inputModel, apiClient *modelexperiments.APIClient) modelexperiments.ApiCreateInstanceRequest { + req := apiClient.DefaultAPI.CreateInstance(ctx, model.ProjectId, model.Region) + + payload := modelexperiments.CreateInstancePayload{ + Name: model.Name, + } + if model.Description != nil { + payload.Description = model.Description + } + if model.Labels != nil { + payload.Labels = model.Labels + } + if model.Retention != nil { + payload.DeletedExperimentRetention = model.Retention + } + + return req.CreateInstancePayload(payload) +} + +func outputResult(p *print.Printer, model *inputModel, projectLabel string, resp *modelexperiments.CreateInstanceResponse) error { + return p.OutputResult(model.OutputFormat, resp, func() error { + if resp == nil { + return fmt.Errorf("response instance is nil") + } + + operationState := "Created" + if model.Async { + operationState = "Triggered creation of" + } + p.Outputf("%s AI Model Experiments instance for project %q. Instance ID: %s\n", operationState, projectLabel, resp.Instance.Id) + return nil + }) +} diff --git a/internal/cmd/modelexperiments/instance/create/create_test.go b/internal/cmd/modelexperiments/instance/create/create_test.go new file mode 100644 index 000000000..1f3bfcfae --- /dev/null +++ b/internal/cmd/modelexperiments/instance/create/create_test.go @@ -0,0 +1,244 @@ +package create + +import ( + "context" + "testing" + + "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" + "github.com/google/uuid" + + modelexperiments "github.com/stackitcloud/stackit-sdk-go/services/modelexperiments/v1api" + + "github.com/stackitcloud/stackit-cli/internal/pkg/globalflags" + "github.com/stackitcloud/stackit-cli/internal/pkg/testparams" + "github.com/stackitcloud/stackit-cli/internal/pkg/testutils" + "github.com/stackitcloud/stackit-cli/internal/pkg/utils" +) + +type testCtxKey struct{} + +const ( + testRegion = "eu01" + testName = "example" +) + +var ( + testCtx = context.WithValue(context.Background(), testCtxKey{}, "foo") + testClient = &modelexperiments.APIClient{DefaultAPI: modelexperiments.DefaultAPIServiceMock{}} + testProjectId = uuid.NewString() +) + +func fixtureFlagValues(mods ...func(flagValues map[string]string)) map[string]string { + flagValues := map[string]string{ + globalflags.ProjectIdFlag: testProjectId, + nameFlag: testName, + globalflags.RegionFlag: testRegion, + } + for _, mod := range mods { + mod(flagValues) + } + return flagValues +} + +func fixtureInputModel(mods ...func(model *inputModel)) *inputModel { + model := &inputModel{ + GlobalFlagModel: &globalflags.GlobalFlagModel{ + ProjectId: testProjectId, + Region: testRegion, + Verbosity: globalflags.VerbosityDefault, + }, + Name: testName, + } + for _, mod := range mods { + mod(model) + } + return model +} + +func fixtureRequest(mods ...func(request *modelexperiments.ApiCreateInstanceRequest)) modelexperiments.ApiCreateInstanceRequest { + request := testClient.DefaultAPI.CreateInstance(testCtx, testProjectId, testRegion) + request = request.CreateInstancePayload(modelexperiments.CreateInstancePayload{ + Name: testName, + }) + for _, mod := range mods { + mod(&request) + } + return request +} + +func TestParseInput(t *testing.T) { + tests := []struct { + description string + argValues []string + flagValues map[string]string + isValid bool + expectedModel *inputModel + }{ + { + description: "base", + flagValues: fixtureFlagValues(), + isValid: true, + expectedModel: fixtureInputModel(), + }, + { + description: "no values", + flagValues: map[string]string{}, + isValid: false, + }, + { + description: "name missing", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + delete(flagValues, nameFlag) + }), + isValid: false, + }, + { + description: "with description and retention", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[descriptionFlag] = "team tracking server" + flagValues[retentionFlag] = "30d" + }), + isValid: true, + expectedModel: fixtureInputModel(func(model *inputModel) { + model.Description = utils.Ptr("team tracking server") + model.Retention = utils.Ptr("30d") + }), + }, + { + description: "with labels", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[labelsFlag] = "env=prod,team=ml" + }), + isValid: true, + expectedModel: fixtureInputModel(func(model *inputModel) { + model.Labels = &map[string]string{"env": "prod", "team": "ml"} + }), + }, + { + description: "project id missing", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + delete(flagValues, globalflags.ProjectIdFlag) + }), + isValid: false, + }, + { + description: "project id invalid 1", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[globalflags.ProjectIdFlag] = "" + }), + isValid: false, + }, + { + description: "project id invalid 2", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[globalflags.ProjectIdFlag] = "invalid-uuid" + }), + isValid: false, + }, + } + + for _, tt := range tests { + t.Run(tt.description, func(t *testing.T) { + testutils.TestParseInput(t, NewCmd, parseInput, tt.expectedModel, tt.argValues, tt.flagValues, tt.isValid) + }) + } +} + +func TestBuildRequest(t *testing.T) { + tests := []struct { + description string + model *inputModel + expectedRequest modelexperiments.ApiCreateInstanceRequest + }{ + { + description: "base", + model: fixtureInputModel(), + expectedRequest: fixtureRequest(), + }, + { + description: "with description", + model: fixtureInputModel(func(model *inputModel) { + model.Description = utils.Ptr("team tracking server") + }), + expectedRequest: fixtureRequest(func(request *modelexperiments.ApiCreateInstanceRequest) { + payload := modelexperiments.CreateInstancePayload{ + Name: testName, + Description: utils.Ptr("team tracking server"), + } + *request = request.CreateInstancePayload(payload) + }), + }, + { + description: "with labels", + model: fixtureInputModel(func(model *inputModel) { + model.Labels = &map[string]string{"env": "prod", "team": "ml"} + }), + expectedRequest: fixtureRequest(func(request *modelexperiments.ApiCreateInstanceRequest) { + payload := modelexperiments.CreateInstancePayload{ + Name: testName, + Labels: &map[string]string{"env": "prod", "team": "ml"}, + } + *request = request.CreateInstancePayload(payload) + }), + }, + { + description: "with retention", + model: fixtureInputModel(func(model *inputModel) { + model.Retention = utils.Ptr("30d") + }), + expectedRequest: fixtureRequest(func(request *modelexperiments.ApiCreateInstanceRequest) { + payload := modelexperiments.CreateInstancePayload{ + Name: testName, + DeletedExperimentRetention: utils.Ptr("30d"), + } + *request = request.CreateInstancePayload(payload) + }), + }, + } + + for _, tt := range tests { + t.Run(tt.description, func(t *testing.T) { + request := buildRequest(testCtx, tt.model, testClient) + + diff := cmp.Diff(request, tt.expectedRequest, + cmp.AllowUnexported(tt.expectedRequest), + cmpopts.EquateComparable(testCtx), + ) + if diff != "" { + t.Fatalf("Data does not match: %s", diff) + } + }) + } +} + +func TestOutputResult(t *testing.T) { + tests := []struct { + name string + resp *modelexperiments.CreateInstanceResponse + wantErr bool + }{ + { + name: "nil response", + resp: nil, + wantErr: true, + }, + { + name: "empty response", + resp: &modelexperiments.CreateInstanceResponse{}, + wantErr: false, + }, + } + params := testparams.NewTestParams() + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + model := fixtureInputModel(func(model *inputModel) { + model.OutputFormat = "" + model.Async = false + }) + if err := outputResult(params.Printer, model, "test-project", tt.resp); (err != nil) != tt.wantErr { + t.Errorf("outputResult() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} diff --git a/internal/cmd/modelexperiments/instance/delete/delete.go b/internal/cmd/modelexperiments/instance/delete/delete.go new file mode 100644 index 000000000..0ed4327c9 --- /dev/null +++ b/internal/cmd/modelexperiments/instance/delete/delete.go @@ -0,0 +1,127 @@ +package delete + +import ( + "context" + "fmt" + + "github.com/spf13/cobra" + + "github.com/stackitcloud/stackit-cli/internal/pkg/args" + cliErr "github.com/stackitcloud/stackit-cli/internal/pkg/errors" + "github.com/stackitcloud/stackit-cli/internal/pkg/examples" + "github.com/stackitcloud/stackit-cli/internal/pkg/globalflags" + "github.com/stackitcloud/stackit-cli/internal/pkg/print" + "github.com/stackitcloud/stackit-cli/internal/pkg/projectname" + "github.com/stackitcloud/stackit-cli/internal/pkg/services/modelexperiments/client" + meUtils "github.com/stackitcloud/stackit-cli/internal/pkg/services/modelexperiments/utils" + "github.com/stackitcloud/stackit-cli/internal/pkg/spinner" + "github.com/stackitcloud/stackit-cli/internal/pkg/types" + "github.com/stackitcloud/stackit-cli/internal/pkg/utils" + + modelexperiments "github.com/stackitcloud/stackit-sdk-go/services/modelexperiments/v1api" + "github.com/stackitcloud/stackit-sdk-go/services/modelexperiments/v1api/wait" +) + +const ( + instanceIdArg = "INSTANCE_ID" +) + +type inputModel struct { + *globalflags.GlobalFlagModel + InstanceId string +} + +func NewCmd(params *types.CmdParams) *cobra.Command { + cmd := &cobra.Command{ + Use: fmt.Sprintf("delete %s", instanceIdArg), + Short: "Deletes an AI Model Experiments instance", + Long: "Deletes an AI Model Experiments instance from a STACKIT project.", + Args: args.SingleArg(instanceIdArg, utils.ValidateUUID), + Example: examples.Build( + examples.NewExample( + `Delete an AI Model Experiments instance with ID "xxx"`, + `$ stackit model-experiments instance delete xxx`, + ), + ), + RunE: func(cmd *cobra.Command, args []string) error { + ctx := context.Background() + + model, err := parseInput(params.Printer, cmd, args) + if err != nil { + return err + } + + apiClient, err := client.ConfigureClient(params.Printer, params.CliVersion) + if err != nil { + return err + } + + projectLabel, err := projectname.GetProjectName(ctx, params.Printer, params.CliVersion, cmd) + if err != nil { + params.Printer.Debug(print.ErrorLevel, "get project name: %v", err) + projectLabel = model.ProjectId + } else if projectLabel == "" { + projectLabel = model.ProjectId + } + + instanceLabel, err := meUtils.GetInstanceName(ctx, apiClient.DefaultAPI, model.ProjectId, model.Region, model.InstanceId) + if err != nil { + params.Printer.Debug(print.ErrorLevel, "get instance name: %v", err) + instanceLabel = model.InstanceId + } + + prompt := fmt.Sprintf("Are you sure you want to delete AI Model Experiments instance %q from project %q?", instanceLabel, projectLabel) + + if err := params.Printer.PromptForConfirmation(prompt); err != nil { + return err + } + + req := buildRequest(ctx, model, apiClient) + + _, err = req.Execute() + if err != nil { + return fmt.Errorf("delete AI Model Experiments instance: %w", err) + } + + if !model.Async { + err := spinner.Run(params.Printer, "Deleting AI Model Experiments instance", func() error { + _, err = wait.DeleteInstanceWaitHandler(ctx, apiClient.DefaultAPI, model.Region, model.ProjectId, model.InstanceId).WaitWithContext(ctx) + return err + }) + if err != nil { + return fmt.Errorf("wait for AI Model Experiments instance deletion: %w", err) + } + } + + operationState := "Deleted" + if model.Async { + operationState = "Triggered deletion of" + } + params.Printer.Outputf("%s AI Model Experiments instance %q\n", operationState, instanceLabel) + return nil + }, + } + + return cmd +} + +func parseInput(p *print.Printer, cmd *cobra.Command, inputArgs []string) (*inputModel, error) { + globalFlags := globalflags.Parse(p, cmd) + + if globalFlags.ProjectId == "" { + return nil, &cliErr.ProjectIdError{} + } + + model := inputModel{ + GlobalFlagModel: globalFlags, + InstanceId: inputArgs[0], + } + + p.DebugInputModel(model) + + return &model, nil +} + +func buildRequest(ctx context.Context, model *inputModel, apiClient *modelexperiments.APIClient) modelexperiments.ApiDeleteInstanceRequest { + return apiClient.DefaultAPI.DeleteInstance(ctx, model.ProjectId, model.Region, model.InstanceId) +} diff --git a/internal/cmd/modelexperiments/instance/delete/delete_test.go b/internal/cmd/modelexperiments/instance/delete/delete_test.go new file mode 100644 index 000000000..e501b1dc9 --- /dev/null +++ b/internal/cmd/modelexperiments/instance/delete/delete_test.go @@ -0,0 +1,164 @@ +package delete + +import ( + "context" + "testing" + + "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" + "github.com/google/uuid" + + modelexperiments "github.com/stackitcloud/stackit-sdk-go/services/modelexperiments/v1api" + + "github.com/stackitcloud/stackit-cli/internal/pkg/globalflags" + "github.com/stackitcloud/stackit-cli/internal/pkg/testutils" +) + +type testCtxKey struct{} + +const testRegion = "eu01" + +var ( + testCtx = context.WithValue(context.Background(), testCtxKey{}, "foo") + testClient = &modelexperiments.APIClient{DefaultAPI: modelexperiments.DefaultAPIServiceMock{}} + testProjectId = uuid.NewString() + testInstanceId = uuid.NewString() +) + +func fixtureFlagValues(mods ...func(map[string]string)) map[string]string { + flagValues := map[string]string{ + globalflags.ProjectIdFlag: testProjectId, + globalflags.RegionFlag: testRegion, + } + + for _, mod := range mods { + mod(flagValues) + } + + return flagValues +} + +func fixtureArgValues(mods ...func(argValues []string)) []string { + argValues := []string{testInstanceId} + for _, mod := range mods { + mod(argValues) + } + return argValues +} + +func fixtureInputModel(mods ...func(*inputModel)) *inputModel { + model := &inputModel{ + GlobalFlagModel: &globalflags.GlobalFlagModel{ + ProjectId: testProjectId, + Region: testRegion, + Verbosity: globalflags.VerbosityDefault, + }, + InstanceId: testInstanceId, + } + + for _, mod := range mods { + mod(model) + } + + return model +} + +func fixtureRequest(mods ...func(*modelexperiments.ApiDeleteInstanceRequest)) modelexperiments.ApiDeleteInstanceRequest { + request := testClient.DefaultAPI.DeleteInstance(testCtx, testProjectId, testRegion, testInstanceId) + + for _, mod := range mods { + mod(&request) + } + + return request +} + +func TestParseInput(t *testing.T) { + tests := []struct { + description string + argValues []string + flagValues map[string]string + isValid bool + expectedModel *inputModel + }{ + { + description: "base", + argValues: fixtureArgValues(), + flagValues: fixtureFlagValues(), + isValid: true, + expectedModel: fixtureInputModel(), + }, + { + description: "project id missing", + argValues: fixtureArgValues(), + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + delete(flagValues, globalflags.ProjectIdFlag) + }), + isValid: false, + }, + { + description: "no arg values", + flagValues: fixtureFlagValues(), + isValid: false, + }, + { + description: "no values", + flagValues: map[string]string{}, + isValid: false, + }, + { + description: "no flag values", + argValues: fixtureArgValues(), + flagValues: map[string]string{}, + isValid: false, + }, + { + description: "project id invalid 1", + argValues: fixtureArgValues(), + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[globalflags.ProjectIdFlag] = "" + }), + isValid: false, + }, + { + description: "instance id missing", + argValues: []string{""}, + flagValues: fixtureFlagValues(), + isValid: false, + }, + { + description: "project id invalid 2", + argValues: fixtureArgValues(), + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[globalflags.ProjectIdFlag] = "invalid-uuid" + }), + isValid: false, + }, + { + description: "instance id invalid", + argValues: []string{"invalid-uuid"}, + flagValues: fixtureFlagValues(), + isValid: false, + }, + } + + for _, tt := range tests { + t.Run(tt.description, func(t *testing.T) { + testutils.TestParseInput(t, NewCmd, parseInput, tt.expectedModel, tt.argValues, tt.flagValues, tt.isValid) + }) + } +} + +func TestBuildRequest(t *testing.T) { + request := buildRequest(testCtx, fixtureInputModel(), testClient) + expectedRequest := fixtureRequest() + + diff := cmp.Diff(request, expectedRequest, + cmp.AllowUnexported(expectedRequest), + cmpopts.EquateComparable(testCtx), + ) + + if diff != "" { + t.Fatalf("Data does not match: %s", diff) + } +} diff --git a/internal/cmd/modelexperiments/instance/describe/describe.go b/internal/cmd/modelexperiments/instance/describe/describe.go new file mode 100644 index 000000000..5370b22cb --- /dev/null +++ b/internal/cmd/modelexperiments/instance/describe/describe.go @@ -0,0 +1,132 @@ +package describe + +import ( + "context" + "fmt" + + "github.com/spf13/cobra" + + "github.com/stackitcloud/stackit-cli/internal/pkg/args" + cliErr "github.com/stackitcloud/stackit-cli/internal/pkg/errors" + "github.com/stackitcloud/stackit-cli/internal/pkg/examples" + "github.com/stackitcloud/stackit-cli/internal/pkg/globalflags" + "github.com/stackitcloud/stackit-cli/internal/pkg/print" + "github.com/stackitcloud/stackit-cli/internal/pkg/services/modelexperiments/client" + "github.com/stackitcloud/stackit-cli/internal/pkg/tables" + "github.com/stackitcloud/stackit-cli/internal/pkg/types" + "github.com/stackitcloud/stackit-cli/internal/pkg/utils" + + modelexperiments "github.com/stackitcloud/stackit-sdk-go/services/modelexperiments/v1api" +) + +const ( + instanceIdArg = "INSTANCE_ID" +) + +type inputModel struct { + *globalflags.GlobalFlagModel + InstanceId string +} + +func NewCmd(params *types.CmdParams) *cobra.Command { + cmd := &cobra.Command{ + Use: fmt.Sprintf("describe %s", instanceIdArg), + Short: "Shows details of an AI Model Experiments instance", + Long: "Shows details of an AI Model Experiments instance in a STACKIT project.", + Args: args.SingleArg(instanceIdArg, utils.ValidateUUID), + Example: examples.Build( + examples.NewExample( + `Show details of an AI Model Experiments instance with ID "xxx"`, + `$ stackit model-experiments instance describe xxx`, + ), + examples.NewExample( + `Get details of an AI Model Experiments instance with ID "xxx" in JSON format`, + `$ stackit model-experiments instance describe xxx --output-format json`, + ), + ), + RunE: func(cmd *cobra.Command, args []string) error { + ctx := context.Background() + + model, err := parseInput(params.Printer, cmd, args) + if err != nil { + return err + } + + apiClient, err := client.ConfigureClient(params.Printer, params.CliVersion) + if err != nil { + return err + } + + req := buildRequest(ctx, model, apiClient) + + resp, err := req.Execute() + if err != nil { + return fmt.Errorf("describe AI Model Experiments instance: %w", err) + } + + return outputResult(params.Printer, model, resp) + }, + } + + return cmd +} + +func parseInput(p *print.Printer, cmd *cobra.Command, inputArgs []string) (*inputModel, error) { + globalFlags := globalflags.Parse(p, cmd) + + if globalFlags.ProjectId == "" { + return nil, &cliErr.ProjectIdError{} + } + + model := inputModel{ + GlobalFlagModel: globalFlags, + InstanceId: inputArgs[0], + } + + p.DebugInputModel(model) + + return &model, nil +} + +func buildRequest(ctx context.Context, model *inputModel, apiClient *modelexperiments.APIClient) modelexperiments.ApiGetInstanceRequest { + return apiClient.DefaultAPI.GetInstance(ctx, model.ProjectId, model.Region, model.InstanceId) +} + +func outputResult(p *print.Printer, model *inputModel, resp *modelexperiments.GetInstanceResponse) error { + if resp == nil { + return fmt.Errorf("response instance is nil") + } + + return p.OutputResult(model.OutputFormat, resp, func() error { + table := tables.NewTable() + table.AddRow("ID", resp.Instance.Id) + table.AddSeparator() + table.AddRow("NAME", resp.Instance.Name) + table.AddSeparator() + table.AddRow("REGION", utils.PtrString(resp.Instance.Region)) + table.AddSeparator() + table.AddRow("STATUS", resp.Instance.State) + table.AddSeparator() + table.AddRow("DESCRIPTION", utils.PtrString(resp.Instance.Description)) + table.AddSeparator() + table.AddRow("DELETED EXPERIMENT RETENTION", utils.PtrString(resp.Instance.DeletedExperimentRetention)) + table.AddSeparator() + table.AddRow("ERROR MESSAGE", utils.PtrString(resp.Instance.ErrorMessage)) + table.AddSeparator() + table.AddRow("ARTIFACT STORAGE NAME", utils.PtrString(resp.Instance.BucketName)) + table.AddSeparator() + table.AddRow("URL", resp.Instance.Url) + table.AddSeparator() + labels := "" + if resp.Instance.Labels != nil { + labels = fmt.Sprint(*resp.Instance.Labels) + } + table.AddRow("LABELS", labels) + table.AddSeparator() + err := table.Display(p) + if err != nil { + return fmt.Errorf("render table: %w", err) + } + return nil + }) +} diff --git a/internal/cmd/modelexperiments/instance/describe/describe_test.go b/internal/cmd/modelexperiments/instance/describe/describe_test.go new file mode 100644 index 000000000..d10f15efa --- /dev/null +++ b/internal/cmd/modelexperiments/instance/describe/describe_test.go @@ -0,0 +1,212 @@ +package describe + +import ( + "context" + "testing" + + "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" + "github.com/google/uuid" + + modelexperiments "github.com/stackitcloud/stackit-sdk-go/services/modelexperiments/v1api" + + "github.com/stackitcloud/stackit-cli/internal/pkg/globalflags" + "github.com/stackitcloud/stackit-cli/internal/pkg/testparams" + "github.com/stackitcloud/stackit-cli/internal/pkg/testutils" +) + +type testCtxKey struct{} + +const testRegion = "eu01" + +var ( + testCtx = context.WithValue(context.Background(), testCtxKey{}, "foo") + testClient = &modelexperiments.APIClient{DefaultAPI: modelexperiments.DefaultAPIServiceMock{}} + testProjectId = uuid.NewString() + testInstanceId = uuid.NewString() +) + +func fixtureFlagValues(mods ...func(map[string]string)) map[string]string { + flagValues := map[string]string{ + globalflags.ProjectIdFlag: testProjectId, + globalflags.RegionFlag: testRegion, + } + + for _, mod := range mods { + mod(flagValues) + } + + return flagValues +} + +func fixtureArgValues(mods ...func(argValues []string)) []string { + argValues := []string{ + testInstanceId, + } + + for _, mod := range mods { + mod(argValues) + } + + return argValues +} + +func fixtureInputModel(mods ...func(*inputModel)) *inputModel { + model := &inputModel{ + GlobalFlagModel: &globalflags.GlobalFlagModel{ + ProjectId: testProjectId, + Region: testRegion, + Verbosity: globalflags.VerbosityDefault, + }, + InstanceId: testInstanceId, + } + + for _, mod := range mods { + mod(model) + } + + return model +} + +func fixtureRequest(mods ...func(*modelexperiments.ApiGetInstanceRequest)) modelexperiments.ApiGetInstanceRequest { + request := testClient.DefaultAPI.GetInstance(testCtx, testProjectId, testRegion, testInstanceId) + + for _, mod := range mods { + mod(&request) + } + + return request +} + +func TestParseInput(t *testing.T) { + tests := []struct { + description string + argValues []string + flagValues map[string]string + isValid bool + expectedModel *inputModel + }{ + { + description: "base", + argValues: fixtureArgValues(), + flagValues: fixtureFlagValues(), + isValid: true, + expectedModel: fixtureInputModel(), + }, + { + description: "no values", + argValues: []string{}, + flagValues: map[string]string{}, + isValid: false, + }, + { + description: "no arg values", + argValues: []string{}, + flagValues: fixtureFlagValues(), + isValid: false, + }, + { + description: "no flag values", + argValues: fixtureArgValues(), + flagValues: map[string]string{}, + isValid: false, + }, + { + description: "project id missing", + argValues: fixtureArgValues(), + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + delete(flagValues, globalflags.ProjectIdFlag) + }), + isValid: false, + }, + { + description: "project id invalid", + argValues: fixtureArgValues(), + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[globalflags.ProjectIdFlag] = "invalid-uuid" + }), + isValid: false, + }, + { + description: "project id invalid 1", + argValues: fixtureArgValues(), + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[globalflags.ProjectIdFlag] = "" + }), + isValid: false, + }, + { + description: "instance id invalid", + argValues: []string{"invalid-uuid"}, + flagValues: fixtureFlagValues(), + isValid: false, + }, + { + description: "instance id missing", + argValues: []string{""}, + flagValues: fixtureFlagValues(), + isValid: false, + }, + } + + for _, tt := range tests { + t.Run(tt.description, func(t *testing.T) { + testutils.TestParseInput(t, NewCmd, parseInput, tt.expectedModel, tt.argValues, tt.flagValues, tt.isValid) + }) + } +} + +func TestBuildRequest(t *testing.T) { + tests := []struct { + description string + model *inputModel + expectedRequest modelexperiments.ApiGetInstanceRequest + }{ + { + description: "base", + model: fixtureInputModel(), + expectedRequest: fixtureRequest(), + }, + } + + for _, tt := range tests { + t.Run(tt.description, func(t *testing.T) { + request := buildRequest(testCtx, tt.model, testClient) + diff := cmp.Diff(request, tt.expectedRequest, cmp.AllowUnexported(tt.expectedRequest), cmpopts.EquateComparable(testCtx)) + if diff != "" { + t.Fatalf("Data does not match: %s", diff) + } + }) + } +} + +func TestOutputResult(t *testing.T) { + tests := []struct { + name string + resp *modelexperiments.GetInstanceResponse + wantErr bool + }{ + { + name: "nil response", + resp: nil, + wantErr: true, + }, + { + name: "empty instance", + resp: &modelexperiments.GetInstanceResponse{ + Instance: modelexperiments.Instance{}, + }, + wantErr: false, + }, + } + + params := testparams.NewTestParams() + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if err := outputResult(params.Printer, fixtureInputModel(), tt.resp); (err != nil) != tt.wantErr { + t.Errorf("outputResult() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} diff --git a/internal/cmd/modelexperiments/instance/instance.go b/internal/cmd/modelexperiments/instance/instance.go new file mode 100644 index 000000000..9b39d3704 --- /dev/null +++ b/internal/cmd/modelexperiments/instance/instance.go @@ -0,0 +1,36 @@ +package instance + +import ( + "github.com/spf13/cobra" + + "github.com/stackitcloud/stackit-cli/internal/cmd/modelexperiments/instance/create" + "github.com/stackitcloud/stackit-cli/internal/cmd/modelexperiments/instance/delete" + "github.com/stackitcloud/stackit-cli/internal/cmd/modelexperiments/instance/describe" + "github.com/stackitcloud/stackit-cli/internal/cmd/modelexperiments/instance/list" + "github.com/stackitcloud/stackit-cli/internal/cmd/modelexperiments/instance/update" + "github.com/stackitcloud/stackit-cli/internal/pkg/args" + "github.com/stackitcloud/stackit-cli/internal/pkg/types" + "github.com/stackitcloud/stackit-cli/internal/pkg/utils" +) + +func NewCmd(params *types.CmdParams) *cobra.Command { + cmd := &cobra.Command{ + Use: "instance", + Short: "Provides functionality for AI Model Experiments instances", + Long: "Provides functionality for AI Model Experiments instances.", + Args: args.NoArgs, + Run: utils.CmdHelp, + } + + addSubcommands(cmd, params) + + return cmd +} + +func addSubcommands(cmd *cobra.Command, params *types.CmdParams) { + cmd.AddCommand(list.NewCmd(params)) + cmd.AddCommand(create.NewCmd(params)) + cmd.AddCommand(delete.NewCmd(params)) + cmd.AddCommand(describe.NewCmd(params)) + cmd.AddCommand(update.NewCmd(params)) +} diff --git a/internal/cmd/modelexperiments/instance/list/list.go b/internal/cmd/modelexperiments/instance/list/list.go new file mode 100644 index 000000000..ecb060613 --- /dev/null +++ b/internal/cmd/modelexperiments/instance/list/list.go @@ -0,0 +1,161 @@ +package list + +import ( + "context" + "fmt" + + "github.com/spf13/cobra" + + "github.com/stackitcloud/stackit-cli/internal/pkg/args" + cliErr "github.com/stackitcloud/stackit-cli/internal/pkg/errors" + "github.com/stackitcloud/stackit-cli/internal/pkg/examples" + "github.com/stackitcloud/stackit-cli/internal/pkg/flags" + "github.com/stackitcloud/stackit-cli/internal/pkg/globalflags" + "github.com/stackitcloud/stackit-cli/internal/pkg/print" + "github.com/stackitcloud/stackit-cli/internal/pkg/projectname" + "github.com/stackitcloud/stackit-cli/internal/pkg/services/modelexperiments/client" + "github.com/stackitcloud/stackit-cli/internal/pkg/tables" + "github.com/stackitcloud/stackit-cli/internal/pkg/types" + "github.com/stackitcloud/stackit-cli/internal/pkg/utils" + + modelexperiments "github.com/stackitcloud/stackit-sdk-go/services/modelexperiments/v1api" +) + +const limitFlag = "limit" + +type inputModel struct { + *globalflags.GlobalFlagModel + Limit *int64 +} + +func NewCmd(params *types.CmdParams) *cobra.Command { + cmd := &cobra.Command{ + Use: "list", + Short: "Lists all AI Model Experiments instances", + Long: "Lists all AI Model Experiments instances in a STACKIT project.", + Args: args.NoArgs, + Example: examples.Build( + examples.NewExample( + `List AI Model Experiments instances in a project`, + `$ stackit model-experiments instance list`, + ), + examples.NewExample( + `List AI Model Experiments instances in a project in region eu02`, + `$ stackit model-experiments instance list --region eu02`, + ), + examples.NewExample( + `List AI Model Experiments instances in JSON format`, + `$ stackit model-experiments instance list --output-format json`, + ), + examples.NewExample( + `List up to 10 AI Model Experiments instances`, + `$ stackit model-experiments instance list --limit 10`, + ), + ), + RunE: func(cmd *cobra.Command, args []string) error { + ctx := context.Background() + + model, err := parseInput(params.Printer, cmd, args) + if err != nil { + return err + } + + apiClient, err := client.ConfigureClient(params.Printer, params.CliVersion) + if err != nil { + return err + } + + req := buildRequest(ctx, model, apiClient) + + resp, err := req.Execute() + if err != nil { + return fmt.Errorf("list AI Model Experiments instances: %w", err) + } + + applyLimit(resp, model.Limit) + + projectLabel, err := projectname.GetProjectName(ctx, params.Printer, params.CliVersion, cmd) + if err != nil { + params.Printer.Debug(print.ErrorLevel, "get project name: %v", err) + projectLabel = model.ProjectId + } else if projectLabel == "" { + projectLabel = model.ProjectId + } + + return outputResult(params.Printer, model, projectLabel, resp) + }, + } + + configureFlags(cmd) + + return cmd +} + +func configureFlags(cmd *cobra.Command) { + cmd.Flags().Int64(limitFlag, 0, "Maximum number of entries to list") +} + +func parseInput(p *print.Printer, cmd *cobra.Command, _ []string) (*inputModel, error) { + globalFlags := globalflags.Parse(p, cmd) + + if globalFlags.ProjectId == "" { + return nil, &cliErr.ProjectIdError{} + } + + limit := flags.FlagToInt64Pointer(p, cmd, limitFlag) + if limit != nil && *limit < 1 { + return nil, &cliErr.FlagValidationError{ + Flag: limitFlag, + Details: "must be greater than 0", + } + } + + model := inputModel{ + GlobalFlagModel: globalFlags, + Limit: limit, + } + + p.DebugInputModel(model) + + return &model, nil +} + +func buildRequest(ctx context.Context, model *inputModel, apiClient *modelexperiments.APIClient) modelexperiments.ApiListInstancesRequest { + return apiClient.DefaultAPI.ListInstances(ctx, model.ProjectId, model.Region) +} + +func applyLimit(resp *modelexperiments.ListInstancesResponse, limit *int64) { + if resp == nil || limit == nil || int64(len(resp.Instances)) <= *limit { + return + } + + resp.Instances = resp.Instances[:int(*limit)] +} + +func outputResult(p *print.Printer, model *inputModel, projectLabel string, resp *modelexperiments.ListInstancesResponse) error { + if resp == nil { + return fmt.Errorf("response is nil") + } + + return p.OutputResult(model.OutputFormat, resp, func() error { + if len(resp.Instances) == 0 { + p.Outputf("No instances found for project %q\n", projectLabel) + return nil + } + + table := tables.NewTable() + table.SetHeader("ID", "NAME", "ARTIFACT STORAGE NAME", "REGION", "STATUS") + + for _, instance := range resp.Instances { + table.AddRow( + instance.Id, + instance.Name, + instance.GetBucketName(), + utils.PtrString(instance.Region), + instance.State, + ) + } + + return table.Display(p) + }) +} diff --git a/internal/cmd/modelexperiments/instance/list/list_test.go b/internal/cmd/modelexperiments/instance/list/list_test.go new file mode 100644 index 000000000..6ce06ff38 --- /dev/null +++ b/internal/cmd/modelexperiments/instance/list/list_test.go @@ -0,0 +1,271 @@ +package list + +import ( + "context" + "strings" + "testing" + + "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" + "github.com/google/uuid" + + modelexperiments "github.com/stackitcloud/stackit-sdk-go/services/modelexperiments/v1api" + + "github.com/stackitcloud/stackit-cli/internal/pkg/globalflags" + "github.com/stackitcloud/stackit-cli/internal/pkg/testparams" + "github.com/stackitcloud/stackit-cli/internal/pkg/testutils" + "github.com/stackitcloud/stackit-cli/internal/pkg/utils" +) + +type testCtxKey struct{} + +const testRegion = "eu01" + +var ( + testCtx = context.WithValue(context.Background(), testCtxKey{}, "foo") + testClient = &modelexperiments.APIClient{DefaultAPI: modelexperiments.DefaultAPIServiceMock{}} + testProjectId = uuid.NewString() +) + +func fixtureFlagValues(mods ...func(map[string]string)) map[string]string { + flagValues := map[string]string{ + globalflags.ProjectIdFlag: testProjectId, + globalflags.RegionFlag: testRegion, + } + + for _, mod := range mods { + mod(flagValues) + } + + return flagValues +} + +func fixtureInputModel(mods ...func(*inputModel)) *inputModel { + model := &inputModel{ + GlobalFlagModel: &globalflags.GlobalFlagModel{ + ProjectId: testProjectId, + Region: testRegion, + Verbosity: globalflags.VerbosityDefault, + }, + } + + for _, mod := range mods { + mod(model) + } + + return model +} + +func fixtureRequest(mods ...func(*modelexperiments.ApiListInstancesRequest)) modelexperiments.ApiListInstancesRequest { + request := testClient.DefaultAPI.ListInstances(testCtx, testProjectId, testRegion) + + for _, mod := range mods { + mod(&request) + } + + return request +} + +func TestParseInput(t *testing.T) { + tests := []struct { + description string + argValues []string + flagValues map[string]string + isValid bool + expectedModel *inputModel + }{ + { + description: "base", + flagValues: fixtureFlagValues(), + isValid: true, + expectedModel: fixtureInputModel(), + }, + { + description: "no values", + flagValues: map[string]string{}, + isValid: false, + }, + { + description: "limit", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[limitFlag] = "10" + }), + isValid: true, + expectedModel: fixtureInputModel(func(model *inputModel) { + model.Limit = utils.Ptr(int64(10)) + }), + }, + { + description: "project id missing", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + delete(flagValues, globalflags.ProjectIdFlag) + }), + isValid: false, + }, + { + description: "project id invalid", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[globalflags.ProjectIdFlag] = "invalid-uuid" + }), + isValid: false, + }, + { + description: "project id invalid 1", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[globalflags.ProjectIdFlag] = "" + }), + isValid: false, + }, + { + description: "limit must be greater than zero", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[limitFlag] = "0" + }), + isValid: false, + }, + { + description: "limit negative", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[limitFlag] = "-1" + }), + isValid: false, + }, + { + description: "limit invalid string", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[limitFlag] = "invalid" + }), + isValid: false, + }, + } + + for _, tt := range tests { + t.Run(tt.description, func(t *testing.T) { + testutils.TestParseInput(t, NewCmd, parseInput, tt.expectedModel, tt.argValues, tt.flagValues, tt.isValid) + }) + } +} + +func TestBuildRequest(t *testing.T) { + request := buildRequest(testCtx, fixtureInputModel(), testClient) + + expectedRequest := fixtureRequest() + + diff := cmp.Diff(request, expectedRequest, cmp.AllowUnexported(expectedRequest), cmpopts.EquateComparable(testCtx)) + + if diff != "" { + t.Fatalf("Data does not match: %s", diff) + } +} + +func TestApplyLimit(t *testing.T) { + tests := []struct { + name string + instances []modelexperiments.Instance + limit *int64 + nilResp bool + wantCount int + }{ + { + name: "no limit", + instances: make([]modelexperiments.Instance, 3), + wantCount: 3, + }, + { + name: "limit below result count", + instances: make([]modelexperiments.Instance, 3), + limit: utils.Ptr(int64(2)), + wantCount: 2, + }, + { + name: "limit above result count", + instances: make([]modelexperiments.Instance, 2), + limit: utils.Ptr(int64(3)), + wantCount: 2, + }, + { + name: "nil response", + limit: utils.Ptr(int64(1)), + nilResp: true, + wantCount: 0, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + resp := &modelexperiments.ListInstancesResponse{Instances: tt.instances} + if tt.nilResp { + resp = nil + } + + applyLimit(resp, tt.limit) + + if resp == nil { + if !tt.nilResp { + t.Fatal("applyLimit() unexpectedly returned a nil response") + } + return + } + if tt.nilResp { + t.Fatal("applyLimit() changed a nil response") + } + if got := len(resp.Instances); got != tt.wantCount { + t.Errorf("applyLimit() count = %d, want %d", got, tt.wantCount) + } + }) + } +} + +func TestOutputResult(t *testing.T) { + tests := []struct { + name string + resp *modelexperiments.ListInstancesResponse + wantErr bool + wantOutput []string + }{ + { + name: "nil response", + resp: nil, + wantErr: true, + }, + { + name: "instances", + resp: &modelexperiments.ListInstancesResponse{ + Instances: []modelexperiments.Instance{ + { + Id: "instance-id", + Name: "instance-name", + BucketName: utils.Ptr("model-experiments-bucket"), + Region: utils.Ptr(testRegion), + State: "READY", + }, + }, + }, + wantErr: false, + wantOutput: []string{"ID", "NAME", "instance-id", "instance-name", "model-experiments-bucket", "READY"}, + }, + { + name: "empty instances", + resp: &modelexperiments.ListInstancesResponse{ + Instances: []modelexperiments.Instance{}, + }, + wantErr: false, + wantOutput: []string{`No instances found for project "test-project"`}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + params := testparams.NewTestParams() + if err := outputResult(params.Printer, fixtureInputModel(), "test-project", tt.resp); (err != nil) != tt.wantErr { + t.Errorf("outputResult() error = %v, wantErr %v", err, tt.wantErr) + } + + for _, expected := range tt.wantOutput { + if !strings.Contains(params.Out.String(), expected) { + t.Errorf("outputResult() output = %q, want it to contain %q", params.Out.String(), expected) + } + } + }) + } +} diff --git a/internal/cmd/modelexperiments/instance/update/update.go b/internal/cmd/modelexperiments/instance/update/update.go new file mode 100644 index 000000000..6d4413ac7 --- /dev/null +++ b/internal/cmd/modelexperiments/instance/update/update.go @@ -0,0 +1,191 @@ +package update + +import ( + "context" + "fmt" + + "github.com/spf13/cobra" + + "github.com/stackitcloud/stackit-cli/internal/pkg/args" + cliErr "github.com/stackitcloud/stackit-cli/internal/pkg/errors" + "github.com/stackitcloud/stackit-cli/internal/pkg/examples" + "github.com/stackitcloud/stackit-cli/internal/pkg/flags" + "github.com/stackitcloud/stackit-cli/internal/pkg/globalflags" + "github.com/stackitcloud/stackit-cli/internal/pkg/print" + "github.com/stackitcloud/stackit-cli/internal/pkg/projectname" + "github.com/stackitcloud/stackit-cli/internal/pkg/services/modelexperiments/client" + meUtils "github.com/stackitcloud/stackit-cli/internal/pkg/services/modelexperiments/utils" + "github.com/stackitcloud/stackit-cli/internal/pkg/types" + "github.com/stackitcloud/stackit-cli/internal/pkg/utils" + + modelexperiments "github.com/stackitcloud/stackit-sdk-go/services/modelexperiments/v1api" +) + +const ( + instanceIdArg = "INSTANCE_ID" + + nameFlag = "name" + descriptionFlag = "description" + labelsFlag = "labels" + retentionFlag = "deleted-experiment-retention" +) + +type inputModel struct { + *globalflags.GlobalFlagModel + + InstanceId string + + Name *string + Description *string + Labels *map[string]*string + Retention *string +} + +func NewCmd(params *types.CmdParams) *cobra.Command { + cmd := &cobra.Command{ + Use: fmt.Sprintf("update %s", instanceIdArg), + Short: "Updates an AI Model Experiments instance", + Long: "Partially updates an AI Model Experiments instance in a STACKIT project.", + Args: args.SingleArg(instanceIdArg, utils.ValidateUUID), + Example: examples.Build( + examples.NewExample( + `Update the name of an AI Model Experiments instance with ID "xxx"`, + `$ stackit model-experiments instance update xxx --name my-new-name`, + ), + examples.NewExample( + `Update the description of an AI Model Experiments instance`, + `$ stackit model-experiments instance update xxx --description "team tracking server"`, + ), + examples.NewExample( + `Update labels on an AI Model Experiments instance`, + `$ stackit model-experiments instance update xxx --labels env=prod,team=ml`, + ), + examples.NewExample( + `Update multiple fields of an AI Model Experiments instance`, + `$ stackit model-experiments instance update xxx --name my-new-name --description "team tracking server" --labels env=prod,team=ml --deleted-experiment-retention 30d`, + ), + ), + RunE: func(cmd *cobra.Command, args []string) error { + ctx := context.Background() + + model, err := parseInput(params.Printer, cmd, args) + if err != nil { + return err + } + + apiClient, err := client.ConfigureClient(params.Printer, params.CliVersion) + if err != nil { + return err + } + + projectLabel, err := projectname.GetProjectName(ctx, params.Printer, params.CliVersion, cmd) + if err != nil { + params.Printer.Debug(print.ErrorLevel, "get project name: %v", err) + projectLabel = model.ProjectId + } else if projectLabel == "" { + projectLabel = model.ProjectId + } + + instanceLabel, err := meUtils.GetInstanceName(ctx, apiClient.DefaultAPI, model.ProjectId, model.Region, model.InstanceId) + if err != nil { + params.Printer.Debug(print.ErrorLevel, "get instance name: %v", err) + instanceLabel = model.InstanceId + } + + prompt := fmt.Sprintf("Are you sure you want to update AI Model Experiments instance %q in project %q?", instanceLabel, projectLabel) + if err := params.Printer.PromptForConfirmation(prompt); err != nil { + return err + } + + req := buildRequest(ctx, model, apiClient) + + resp, err := req.Execute() + if err != nil { + return fmt.Errorf("update AI Model Experiments instance: %w", err) + } + + return outputResult(params.Printer, model, resp) + }, + } + + configureFlags(cmd) + + return cmd +} + +func configureFlags(cmd *cobra.Command) { + cmd.Flags().StringP(nameFlag, "n", "", "Instance name") + cmd.Flags().String(descriptionFlag, "", "Instance description") + cmd.Flags().StringToString(labelsFlag, nil, `Labels are comma-separated key-value string pairs, e.g. "--labels env=prod,team=ml"`) + cmd.Flags().String(retentionFlag, "", `Retention period for deleted experiments before permanent purge, e.g. "30d" (min 1d, max 90d)`) + cmd.MarkFlagsOneRequired(nameFlag, descriptionFlag, labelsFlag, retentionFlag) +} + +func parseInput(p *print.Printer, cmd *cobra.Command, inputArgs []string) (*inputModel, error) { + globalFlags := globalflags.Parse(p, cmd) + + if globalFlags.ProjectId == "" { + return nil, &cliErr.ProjectIdError{} + } + + labels := flags.FlagToStringToAny(p, cmd, labelsFlag) + var labelsPtr *map[string]*string + if len(labels) > 0 { + convertedLabels := make(map[string]*string, len(labels)) + for key, value := range labels { + valueCopy := fmt.Sprint(value) + convertedLabels[key] = &valueCopy + } + labelsPtr = &convertedLabels + } + + model := inputModel{ + GlobalFlagModel: globalFlags, + + InstanceId: inputArgs[0], + + Name: flags.FlagToStringPointer(p, cmd, nameFlag), + Description: flags.FlagToStringPointer(p, cmd, descriptionFlag), + Labels: labelsPtr, + Retention: flags.FlagToStringPointer(p, cmd, retentionFlag), + } + + p.DebugInputModel(model) + + return &model, nil +} + +func buildRequest(ctx context.Context, model *inputModel, apiClient *modelexperiments.APIClient) modelexperiments.ApiPartialUpdateInstanceRequest { + req := apiClient.DefaultAPI.PartialUpdateInstance(ctx, model.ProjectId, model.Region, model.InstanceId) + + payload := modelexperiments.PartialUpdateInstancePayload{} + + if model.Name != nil { + payload.Name = model.Name + } + + if model.Description != nil { + payload.Description = model.Description + } + + if model.Labels != nil { + payload.Labels = model.Labels + } + + if model.Retention != nil { + payload.DeletedExperimentRetention = model.Retention + } + + return req.PartialUpdateInstancePayload(payload) +} + +func outputResult(p *print.Printer, model *inputModel, resp *modelexperiments.PartialUpdateInstanceResponse) error { + if resp == nil { + return fmt.Errorf("response instance is nil") + } + + return p.OutputResult(model.OutputFormat, resp, func() error { + p.Outputf("Updated AI Model Experiments instance. Instance ID: %s\n", resp.Instance.Id) + return nil + }) +} diff --git a/internal/cmd/modelexperiments/instance/update/update_test.go b/internal/cmd/modelexperiments/instance/update/update_test.go new file mode 100644 index 000000000..33e55af80 --- /dev/null +++ b/internal/cmd/modelexperiments/instance/update/update_test.go @@ -0,0 +1,322 @@ +package update + +import ( + "context" + "testing" + + "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" + "github.com/google/uuid" + + modelexperiments "github.com/stackitcloud/stackit-sdk-go/services/modelexperiments/v1api" + + "github.com/stackitcloud/stackit-cli/internal/pkg/globalflags" + "github.com/stackitcloud/stackit-cli/internal/pkg/testparams" + "github.com/stackitcloud/stackit-cli/internal/pkg/testutils" + "github.com/stackitcloud/stackit-cli/internal/pkg/utils" +) + +type testCtxKey struct{} + +const ( + testRegion = "eu01" + testName = "example" +) + +var ( + testCtx = context.WithValue(context.Background(), testCtxKey{}, "foo") + testClient = &modelexperiments.APIClient{DefaultAPI: modelexperiments.DefaultAPIServiceMock{}} + testProjectId = uuid.NewString() + testInstanceId = uuid.NewString() +) + +func fixtureFlagValues(mods ...func(map[string]string)) map[string]string { + flagValues := map[string]string{ + globalflags.ProjectIdFlag: testProjectId, + globalflags.RegionFlag: testRegion, + } + + for _, mod := range mods { + mod(flagValues) + } + + return flagValues +} + +func fixtureArgValues(mods ...func(argValues []string)) []string { + argValues := []string{testInstanceId} + for _, mod := range mods { + mod(argValues) + } + return argValues +} + +func fixtureInputModel(mods ...func(*inputModel)) *inputModel { + model := &inputModel{ + GlobalFlagModel: &globalflags.GlobalFlagModel{ + ProjectId: testProjectId, + Region: testRegion, + Verbosity: globalflags.VerbosityDefault, + }, + InstanceId: testInstanceId, + } + + for _, mod := range mods { + mod(model) + } + + return model +} + +func fixtureRequest(mods ...func(*modelexperiments.ApiPartialUpdateInstanceRequest)) modelexperiments.ApiPartialUpdateInstanceRequest { + request := testClient.DefaultAPI.PartialUpdateInstance(testCtx, testProjectId, testRegion, testInstanceId) + + payload := modelexperiments.PartialUpdateInstancePayload{ + Name: utils.Ptr(testName), + } + + request = request.PartialUpdateInstancePayload(payload) + + for _, mod := range mods { + mod(&request) + } + + return request +} + +func TestParseInput(t *testing.T) { + tests := []struct { + description string + argValues []string + flagValues map[string]string + isValid bool + expectedModel *inputModel + }{ + { + description: "name", + argValues: fixtureArgValues(), + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[nameFlag] = testName + }), + isValid: true, + expectedModel: fixtureInputModel(func(model *inputModel) { + model.Name = utils.Ptr(testName) + }), + }, + { + description: "description", + argValues: fixtureArgValues(), + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[descriptionFlag] = "team tracking server" + }), + isValid: true, + expectedModel: fixtureInputModel(func(model *inputModel) { + model.Description = utils.Ptr("team tracking server") + }), + }, + { + description: "labels", + argValues: fixtureArgValues(), + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[labelsFlag] = "env=prod,team=ml" + }), + isValid: true, + expectedModel: fixtureInputModel(func(model *inputModel) { + labels := map[string]*string{ + "env": utils.Ptr("prod"), + "team": utils.Ptr("ml"), + } + model.Labels = &labels + }), + }, + { + description: "retention", + argValues: fixtureArgValues(), + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[retentionFlag] = "30d" + }), + isValid: true, + expectedModel: fixtureInputModel(func(model *inputModel) { + model.Retention = utils.Ptr("30d") + }), + }, + { + description: "no update flags", + argValues: fixtureArgValues(), + flagValues: fixtureFlagValues(), + isValid: false, + }, + { + description: "no values", + argValues: []string{}, + flagValues: map[string]string{}, + isValid: false, + }, + { + description: "no arg values", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[nameFlag] = testName + }), + isValid: false, + }, + { + description: "no flag values", + argValues: fixtureArgValues(), + flagValues: map[string]string{}, + isValid: false, + }, + { + description: "project id missing", + argValues: fixtureArgValues(), + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + delete(flagValues, globalflags.ProjectIdFlag) + flagValues[nameFlag] = testName + }), + isValid: false, + }, + { + description: "project id invalid", + argValues: fixtureArgValues(), + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[globalflags.ProjectIdFlag] = "invalid-uuid" + flagValues[nameFlag] = testName + }), + isValid: false, + }, + { + description: "project id invalid 1", + argValues: fixtureArgValues(), + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[globalflags.ProjectIdFlag] = "" + flagValues[nameFlag] = testName + }), + isValid: false, + }, + { + description: "instance id invalid", + argValues: []string{"invalid-uuid"}, + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[nameFlag] = testName + }), + isValid: false, + }, + { + description: "instance id missing", + argValues: []string{""}, + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[nameFlag] = testName + }), + isValid: false, + }, + } + + for _, tt := range tests { + t.Run(tt.description, func(t *testing.T) { + testutils.TestParseInput(t, NewCmd, parseInput, tt.expectedModel, tt.argValues, tt.flagValues, tt.isValid) + }) + } +} + +func TestBuildRequest(t *testing.T) { + tests := []struct { + description string + model *inputModel + expectedRequest modelexperiments.ApiPartialUpdateInstanceRequest + }{ + { + description: "name", + model: fixtureInputModel(func(model *inputModel) { + model.Name = utils.Ptr(testName) + }), + expectedRequest: fixtureRequest(), + }, + { + description: "description", + model: fixtureInputModel(func(model *inputModel) { + model.Description = utils.Ptr("team tracking server") + }), + expectedRequest: func() modelexperiments.ApiPartialUpdateInstanceRequest { + request := testClient.DefaultAPI.PartialUpdateInstance(testCtx, testProjectId, testRegion, testInstanceId) + + request = request.PartialUpdateInstancePayload(modelexperiments.PartialUpdateInstancePayload{Description: utils.Ptr("team tracking server")}) + + return request + }(), + }, + { + description: "labels", + model: fixtureInputModel(func(model *inputModel) { + labels := map[string]*string{ + "env": utils.Ptr("prod"), + "team": utils.Ptr("ml"), + } + model.Labels = &labels + }), + expectedRequest: func() modelexperiments.ApiPartialUpdateInstanceRequest { + request := testClient.DefaultAPI.PartialUpdateInstance(testCtx, testProjectId, testRegion, testInstanceId) + + labels := map[string]*string{ + "env": utils.Ptr("prod"), + "team": utils.Ptr("ml"), + } + return request.PartialUpdateInstancePayload(modelexperiments.PartialUpdateInstancePayload{Labels: &labels}) + }(), + }, + { + description: "retention", + model: fixtureInputModel(func(model *inputModel) { + model.Retention = utils.Ptr("30d") + }), + expectedRequest: func() modelexperiments.ApiPartialUpdateInstanceRequest { + request := testClient.DefaultAPI.PartialUpdateInstance(testCtx, testProjectId, testRegion, testInstanceId) + + request = request.PartialUpdateInstancePayload(modelexperiments.PartialUpdateInstancePayload{DeletedExperimentRetention: utils.Ptr("30d")}) + + return request + }(), + }, + } + + for _, tt := range tests { + t.Run(tt.description, func(t *testing.T) { + request := buildRequest(testCtx, tt.model, testClient) + + diff := cmp.Diff(request, tt.expectedRequest, cmp.AllowUnexported(tt.expectedRequest), cmpopts.EquateComparable(testCtx)) + + if diff != "" { + t.Fatalf("Data does not match: %s", diff) + } + }) + } +} + +func TestOutputResult(t *testing.T) { + tests := []struct { + name string + resp *modelexperiments.PartialUpdateInstanceResponse + wantErr bool + }{ + { + name: "nil response", + resp: nil, + wantErr: true, + }, + { + name: "empty instance", + resp: &modelexperiments.PartialUpdateInstanceResponse{ + Instance: modelexperiments.Instance{}, + }, + wantErr: false, + }, + } + + params := testparams.NewTestParams() + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if err := outputResult(params.Printer, fixtureInputModel(), tt.resp); (err != nil) != tt.wantErr { + t.Errorf("outputResult() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} diff --git a/internal/cmd/modelexperiments/modelexperiments.go b/internal/cmd/modelexperiments/modelexperiments.go new file mode 100644 index 000000000..50b47ea84 --- /dev/null +++ b/internal/cmd/modelexperiments/modelexperiments.go @@ -0,0 +1,30 @@ +package modelexperiments + +import ( + "github.com/spf13/cobra" + + "github.com/stackitcloud/stackit-cli/internal/cmd/modelexperiments/instance" + "github.com/stackitcloud/stackit-cli/internal/cmd/modelexperiments/token" + "github.com/stackitcloud/stackit-cli/internal/pkg/args" + "github.com/stackitcloud/stackit-cli/internal/pkg/types" + "github.com/stackitcloud/stackit-cli/internal/pkg/utils" +) + +func NewCmd(params *types.CmdParams) *cobra.Command { + cmd := &cobra.Command{ + Use: "model-experiments", + Short: "Provides functionality for AI Model Experiments", + Long: "Provides functionality for AI Model Experiments.", + Args: args.NoArgs, + Run: utils.CmdHelp, + } + + addSubcommands(cmd, params) + + return cmd +} + +func addSubcommands(cmd *cobra.Command, params *types.CmdParams) { + cmd.AddCommand(instance.NewCmd(params)) + cmd.AddCommand(token.NewCmd(params)) +} diff --git a/internal/cmd/modelexperiments/token/create/create.go b/internal/cmd/modelexperiments/token/create/create.go new file mode 100644 index 000000000..7195399a0 --- /dev/null +++ b/internal/cmd/modelexperiments/token/create/create.go @@ -0,0 +1,158 @@ +package create + +import ( + "context" + "fmt" + + "github.com/spf13/cobra" + + "github.com/stackitcloud/stackit-cli/internal/pkg/args" + cliErr "github.com/stackitcloud/stackit-cli/internal/pkg/errors" + "github.com/stackitcloud/stackit-cli/internal/pkg/examples" + "github.com/stackitcloud/stackit-cli/internal/pkg/flags" + "github.com/stackitcloud/stackit-cli/internal/pkg/globalflags" + "github.com/stackitcloud/stackit-cli/internal/pkg/print" + "github.com/stackitcloud/stackit-cli/internal/pkg/projectname" + "github.com/stackitcloud/stackit-cli/internal/pkg/services/modelexperiments/client" + meUtils "github.com/stackitcloud/stackit-cli/internal/pkg/services/modelexperiments/utils" + "github.com/stackitcloud/stackit-cli/internal/pkg/spinner" + "github.com/stackitcloud/stackit-cli/internal/pkg/types" + + modelexperiments "github.com/stackitcloud/stackit-sdk-go/services/modelexperiments/v1api" + "github.com/stackitcloud/stackit-sdk-go/services/modelexperiments/v1api/wait" +) + +const ( + instanceIDFlag = "instance-id" + nameFlag = "name" + descriptionFlag = "description" + labelsFlag = "labels" + ttlDurationFlag = "ttl-duration" +) + +type inputModel struct { + *globalflags.GlobalFlagModel + InstanceID string + Name string + Description *string + Labels *map[string]string + TTLDuration *string +} + +func NewCmd(params *types.CmdParams) *cobra.Command { + cmd := &cobra.Command{ + Use: "create", + Short: "Creates an AI Model Experiments instance token", + Long: "Creates an auth token for an AI Model Experiments instance.", + Args: args.NoArgs, + Example: examples.Build( + examples.NewExample( + "Create an auth token", + "$ stackit model-experiments token create --instance-id xxx --name my-token", + ), + examples.NewExample( + "Create an auth token with a description, labels, and time to live", + `$ stackit model-experiments token create --instance-id xxx --name my-token --description "service token" --labels env=prod,team=ml --ttl-duration 30d`, + ), + ), + RunE: func(cmd *cobra.Command, _ []string) error { + ctx := context.Background() + model, err := parseInput(params.Printer, cmd, nil) + if err != nil { + return err + } + apiClient, err := client.ConfigureClient(params.Printer, params.CliVersion) + if err != nil { + return err + } + projectLabel, err := projectname.GetProjectName(ctx, params.Printer, params.CliVersion, cmd) + if err != nil { + params.Printer.Debug(print.ErrorLevel, "get project name: %v", err) + projectLabel = model.ProjectId + } else if projectLabel == "" { + projectLabel = model.ProjectId + } + instanceLabel, err := meUtils.GetInstanceName(ctx, apiClient.DefaultAPI, model.ProjectId, model.Region, model.InstanceID) + if err != nil { + params.Printer.Debug(print.ErrorLevel, "get instance name: %v", err) + instanceLabel = model.InstanceID + } + prompt := fmt.Sprintf("Are you sure you want to create token %q for instance %q in project %q?", model.Name, instanceLabel, projectLabel) + if err := params.Printer.PromptForConfirmation(prompt); err != nil { + return err + } + resp, err := buildRequest(ctx, model, apiClient).Execute() + if err != nil { + return fmt.Errorf("create instance token: %w", err) + } + if resp == nil || resp.Token.Id == "" { + return fmt.Errorf("create instance token: response token is nil") + } + if !model.Async { + err := spinner.Run(params.Printer, "Creating instance token", func() error { + _, err = wait.CreateInstanceTokenWaitHandler(ctx, apiClient.DefaultAPI, model.Region, model.ProjectId, model.InstanceID, resp.Token.Id).WaitWithContext(ctx) + return err + }) + if err != nil { + return fmt.Errorf("wait for instance token creation: %w", err) + } + } + return outputResult(params.Printer, model, projectLabel, instanceLabel, resp) + }, + } + configureFlags(cmd) + return cmd +} + +func configureFlags(cmd *cobra.Command) { + cmd.Flags().Var(flags.UUIDFlag(), instanceIDFlag, "ID of the instance") + cmd.Flags().String(nameFlag, "", "Token name") + cmd.Flags().String(descriptionFlag, "", "Token description") + cmd.Flags().StringToString(labelsFlag, nil, `Labels are comma-separated key-value string pairs, e.g. "--labels env=prod,team=ml"`) + cmd.Flags().String(ttlDurationFlag, "", `Maximum allowed duration is 6 months. If not set, defaults to 6 months. Format example: "720h" or "30d"`) + err := flags.MarkFlagsRequired(cmd, instanceIDFlag, nameFlag) + cobra.CheckErr(err) +} + +func parseInput(p *print.Printer, cmd *cobra.Command, _ []string) (*inputModel, error) { + globalFlags := globalflags.Parse(p, cmd) + if globalFlags.ProjectId == "" { + return nil, &cliErr.ProjectIdError{} + } + labels := flags.FlagToStringToStringPointer(p, cmd, labelsFlag) + model := &inputModel{ + GlobalFlagModel: globalFlags, + InstanceID: flags.FlagToStringValue(p, cmd, instanceIDFlag), + Name: flags.FlagToStringValue(p, cmd, nameFlag), + Description: flags.FlagToStringPointer(p, cmd, descriptionFlag), + Labels: labels, + TTLDuration: flags.FlagToStringPointer(p, cmd, ttlDurationFlag), + } + p.DebugInputModel(model) + return model, nil +} + +func buildRequest(ctx context.Context, model *inputModel, apiClient *modelexperiments.APIClient) modelexperiments.ApiCreateInstanceTokenRequest { + payload := modelexperiments.CreateInstanceTokenPayload{ + Name: model.Name, + Description: model.Description, + Labels: model.Labels, + TtlDuration: model.TTLDuration, + } + return apiClient.DefaultAPI.CreateInstanceToken(ctx, model.ProjectId, model.Region, model.InstanceID).CreateInstanceTokenPayload(payload) +} + +func outputResult(p *print.Printer, model *inputModel, projectLabel, instanceLabel string, resp *modelexperiments.CreateInstanceTokenResponse) error { + return p.OutputResult(model.OutputFormat, resp, func() error { + if resp == nil { + return fmt.Errorf("response token is nil") + } + + operationState := "Created" + if model.Async { + operationState = "Triggered creation of" + } + p.Outputf("%s token %q for instance %q in project %q. Token ID: %s\nToken: %s\n", operationState, resp.Token.Name, instanceLabel, projectLabel, resp.Token.Id, resp.Token.Content) + return nil + }) +} diff --git a/internal/cmd/modelexperiments/token/create/create_test.go b/internal/cmd/modelexperiments/token/create/create_test.go new file mode 100644 index 000000000..dbedbdf8c --- /dev/null +++ b/internal/cmd/modelexperiments/token/create/create_test.go @@ -0,0 +1,236 @@ +package create + +import ( + "context" + "testing" + + "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" + "github.com/google/uuid" + + modelexperiments "github.com/stackitcloud/stackit-sdk-go/services/modelexperiments/v1api" + + "github.com/stackitcloud/stackit-cli/internal/pkg/globalflags" + "github.com/stackitcloud/stackit-cli/internal/pkg/testparams" + "github.com/stackitcloud/stackit-cli/internal/pkg/testutils" + "github.com/stackitcloud/stackit-cli/internal/pkg/utils" +) + +type testContextKey struct{} + +const ( + testRegion = "eu01" + testName = "example" +) + +var ( + testContext = context.WithValue(context.Background(), testContextKey{}, "token-create") + testClient = &modelexperiments.APIClient{DefaultAPI: modelexperiments.DefaultAPIServiceMock{}} + testProjectID = uuid.NewString() + testInstanceID = uuid.NewString() +) + +func fixtureFlagValues(mods ...func(flagValues map[string]string)) map[string]string { + flagValues := map[string]string{ + globalflags.ProjectIdFlag: testProjectID, + globalflags.RegionFlag: testRegion, + instanceIDFlag: testInstanceID, + nameFlag: testName, + } + for _, mod := range mods { + mod(flagValues) + } + return flagValues +} + +func fixtureInputModel(mods ...func(model *inputModel)) *inputModel { + model := &inputModel{ + GlobalFlagModel: &globalflags.GlobalFlagModel{ + ProjectId: testProjectID, + Region: testRegion, + Verbosity: globalflags.VerbosityDefault, + }, + InstanceID: testInstanceID, + Name: testName, + } + for _, mod := range mods { + mod(model) + } + return model +} + +func fixtureRequest(mods ...func(request *modelexperiments.ApiCreateInstanceTokenRequest)) modelexperiments.ApiCreateInstanceTokenRequest { + request := testClient.DefaultAPI.CreateInstanceToken(testContext, testProjectID, testRegion, testInstanceID). + CreateInstanceTokenPayload(modelexperiments.CreateInstanceTokenPayload{Name: testName}) + for _, mod := range mods { + mod(&request) + } + return request +} + +func TestParseInput(t *testing.T) { + tests := []struct { + description string + argValues []string + flagValues map[string]string + isValid bool + expectedModel *inputModel + }{ + { + description: "base", + flagValues: fixtureFlagValues(), + isValid: true, + expectedModel: fixtureInputModel(), + }, + { + description: "optional fields", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[descriptionFlag] = "service token" + flagValues[labelsFlag] = "env=prod,team=ml" + flagValues[ttlDurationFlag] = "5h" + }), + isValid: true, + expectedModel: fixtureInputModel(func(model *inputModel) { + model.Description = utils.Ptr("service token") + model.Labels = &map[string]string{"env": "prod", "team": "ml"} + model.TTLDuration = utils.Ptr("5h") + }), + }, + { + description: "no values", + flagValues: map[string]string{}, + isValid: false, + }, + { + description: "name missing", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + delete(flagValues, nameFlag) + }), + isValid: false, + }, + { + description: "instance id missing", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + delete(flagValues, instanceIDFlag) + }), + isValid: false, + }, + { + description: "instance id empty", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[instanceIDFlag] = "" + }), + isValid: false, + }, + { + description: "project id missing", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + delete(flagValues, globalflags.ProjectIdFlag) + }), + isValid: false, + }, + { + description: "project id invalid 1", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[globalflags.ProjectIdFlag] = "" + }), + isValid: false, + }, + { + description: "project id invalid 2", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[globalflags.ProjectIdFlag] = "invalid-uuid" + }), + isValid: false, + }, + { + description: "instance id invalid", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[instanceIDFlag] = "invalid-uuid" + }), + isValid: false, + }, + } + + for _, tt := range tests { + t.Run(tt.description, func(t *testing.T) { + testutils.TestParseInput(t, NewCmd, parseInput, tt.expectedModel, tt.argValues, tt.flagValues, tt.isValid) + }) + } +} + +func TestBuildRequest(t *testing.T) { + tests := []struct { + description string + model *inputModel + expectedRequest modelexperiments.ApiCreateInstanceTokenRequest + }{ + { + description: "base", + model: fixtureInputModel(), + expectedRequest: fixtureRequest(), + }, + { + description: "optional fields", + model: fixtureInputModel(func(model *inputModel) { + model.Description = utils.Ptr("service token") + model.Labels = &map[string]string{"env": "prod", "team": "ml"} + model.TTLDuration = utils.Ptr("5h") + }), + expectedRequest: fixtureRequest(func(request *modelexperiments.ApiCreateInstanceTokenRequest) { + payload := modelexperiments.CreateInstanceTokenPayload{ + Name: testName, + Description: utils.Ptr("service token"), + Labels: &map[string]string{"env": "prod", "team": "ml"}, + TtlDuration: utils.Ptr("5h"), + } + *request = request.CreateInstanceTokenPayload(payload) + }), + }, + } + + for _, tt := range tests { + t.Run(tt.description, func(t *testing.T) { + request := buildRequest(testContext, tt.model, testClient) + + diff := cmp.Diff(request, tt.expectedRequest, + cmp.AllowUnexported(tt.expectedRequest), + cmpopts.EquateComparable(testContext), + ) + if diff != "" { + t.Fatalf("Data does not match: %s", diff) + } + }) + } +} + +func TestOutputResult(t *testing.T) { + tests := []struct { + name string + resp *modelexperiments.CreateInstanceTokenResponse + wantErr bool + }{ + { + name: "nil response", + resp: nil, + wantErr: true, + }, + { + name: "empty response", + resp: &modelexperiments.CreateInstanceTokenResponse{}, + wantErr: false, + }, + } + params := testparams.NewTestParams() + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + model := fixtureInputModel(func(model *inputModel) { + model.OutputFormat = "" + model.Async = false + }) + if err := outputResult(params.Printer, model, "test-project", "test-instance", tt.resp); (err != nil) != tt.wantErr { + t.Errorf("outputResult() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} diff --git a/internal/cmd/modelexperiments/token/delete/delete.go b/internal/cmd/modelexperiments/token/delete/delete.go new file mode 100644 index 000000000..e1cee02e3 --- /dev/null +++ b/internal/cmd/modelexperiments/token/delete/delete.go @@ -0,0 +1,140 @@ +package delete + +import ( + "context" + "fmt" + + "github.com/spf13/cobra" + + "github.com/stackitcloud/stackit-cli/internal/pkg/args" + cliErr "github.com/stackitcloud/stackit-cli/internal/pkg/errors" + "github.com/stackitcloud/stackit-cli/internal/pkg/examples" + "github.com/stackitcloud/stackit-cli/internal/pkg/flags" + "github.com/stackitcloud/stackit-cli/internal/pkg/globalflags" + "github.com/stackitcloud/stackit-cli/internal/pkg/print" + "github.com/stackitcloud/stackit-cli/internal/pkg/projectname" + "github.com/stackitcloud/stackit-cli/internal/pkg/services/modelexperiments/client" + meUtils "github.com/stackitcloud/stackit-cli/internal/pkg/services/modelexperiments/utils" + "github.com/stackitcloud/stackit-cli/internal/pkg/spinner" + "github.com/stackitcloud/stackit-cli/internal/pkg/types" + "github.com/stackitcloud/stackit-cli/internal/pkg/utils" + + modelexperiments "github.com/stackitcloud/stackit-sdk-go/services/modelexperiments/v1api" + "github.com/stackitcloud/stackit-sdk-go/services/modelexperiments/v1api/wait" +) + +const ( + tokenIDArg = "TOKEN_ID" + instanceIDFlag = "instance-id" +) + +type inputModel struct { + *globalflags.GlobalFlagModel + TokenID string + InstanceID string +} + +func NewCmd(params *types.CmdParams) *cobra.Command { + cmd := &cobra.Command{ + Use: fmt.Sprintf("delete %s", tokenIDArg), + Short: "Deletes an AI Model Experiments instance token", + Long: "Deletes an auth token from an AI Model Experiments instance.", + Args: args.SingleArg(tokenIDArg, utils.ValidateUUID), + Example: examples.Build( + examples.NewExample( + `Delete an auth token with ID "xxx"`, + `$ stackit model-experiments token delete xxx --instance-id yyy`, + ), + ), + RunE: func(cmd *cobra.Command, inputArgs []string) error { + ctx := context.Background() + + model, err := parseInput(params.Printer, cmd, inputArgs) + if err != nil { + return err + } + + apiClient, err := client.ConfigureClient(params.Printer, params.CliVersion) + if err != nil { + return err + } + + projectLabel, err := projectname.GetProjectName(ctx, params.Printer, params.CliVersion, cmd) + if err != nil { + params.Printer.Debug(print.ErrorLevel, "get project name: %v", err) + projectLabel = model.ProjectId + } else if projectLabel == "" { + projectLabel = model.ProjectId + } + + instanceLabel, err := meUtils.GetInstanceName(ctx, apiClient.DefaultAPI, model.ProjectId, model.Region, model.InstanceID) + if err != nil { + params.Printer.Debug(print.ErrorLevel, "get instance name: %v", err) + instanceLabel = model.InstanceID + } + + tokenLabel, err := meUtils.GetTokenName(ctx, apiClient.DefaultAPI, model.ProjectId, model.Region, model.InstanceID, model.TokenID) + if err != nil { + params.Printer.Debug(print.ErrorLevel, "get token name: %v", err) + tokenLabel = model.TokenID + } + + prompt := fmt.Sprintf("Are you sure you want to delete token %q for instance %q in project %q?", tokenLabel, instanceLabel, projectLabel) + if err := params.Printer.PromptForConfirmation(prompt); err != nil { + return err + } + + if _, err := buildRequest(ctx, model, apiClient).Execute(); err != nil { + return fmt.Errorf("delete instance token: %w", err) + } + + if !model.Async { + err := spinner.Run(params.Printer, "Deleting instance token", func() error { + _, err = wait.DeleteInstanceTokenWaitHandler(ctx, apiClient.DefaultAPI, model.Region, model.ProjectId, model.InstanceID, model.TokenID).WaitWithContext(ctx) + return err + }) + if err != nil { + return fmt.Errorf("wait for instance token deletion: %w", err) + } + } + + operationState := "Deleted" + if model.Async { + operationState = "Triggered deletion of" + } + params.Printer.Outputf("%s token %q for instance %q in project %q\n", operationState, tokenLabel, instanceLabel, projectLabel) + return nil + }, + } + + configureFlags(cmd) + + return cmd +} + +func configureFlags(cmd *cobra.Command) { + cmd.Flags().Var(flags.UUIDFlag(), instanceIDFlag, "ID of the instance") + err := flags.MarkFlagsRequired(cmd, instanceIDFlag) + cobra.CheckErr(err) +} + +func parseInput(p *print.Printer, cmd *cobra.Command, inputArgs []string) (*inputModel, error) { + globalFlags := globalflags.Parse(p, cmd) + if globalFlags.ProjectId == "" { + return nil, &cliErr.ProjectIdError{} + } + + model := inputModel{ + GlobalFlagModel: globalFlags, + TokenID: inputArgs[0], + InstanceID: flags.FlagToStringValue(p, cmd, instanceIDFlag), + } + + p.DebugInputModel(model) + + return &model, nil +} + +func buildRequest(ctx context.Context, model *inputModel, apiClient *modelexperiments.APIClient) modelexperiments.ApiDeleteInstanceTokenRequest { + return apiClient.DefaultAPI.DeleteInstanceToken(ctx, model.ProjectId, model.Region, model.TokenID, model.InstanceID) +} diff --git a/internal/cmd/modelexperiments/token/delete/delete_test.go b/internal/cmd/modelexperiments/token/delete/delete_test.go new file mode 100644 index 000000000..98faa85b8 --- /dev/null +++ b/internal/cmd/modelexperiments/token/delete/delete_test.go @@ -0,0 +1,182 @@ +package delete + +import ( + "context" + "testing" + + "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" + "github.com/google/uuid" + + modelexperiments "github.com/stackitcloud/stackit-sdk-go/services/modelexperiments/v1api" + + "github.com/stackitcloud/stackit-cli/internal/pkg/globalflags" + "github.com/stackitcloud/stackit-cli/internal/pkg/testutils" +) + +type testContextKey struct{} + +const testRegion = "eu01" + +var ( + testContext = context.WithValue(context.Background(), testContextKey{}, "token-delete") + testClient = &modelexperiments.APIClient{DefaultAPI: modelexperiments.DefaultAPIServiceMock{}} + testProjectID = uuid.NewString() + testInstanceID = uuid.NewString() + testTokenID = uuid.NewString() +) + +func fixtureFlagValues(mods ...func(flagValues map[string]string)) map[string]string { + flagValues := map[string]string{ + globalflags.ProjectIdFlag: testProjectID, + globalflags.RegionFlag: testRegion, + instanceIDFlag: testInstanceID, + } + for _, mod := range mods { + mod(flagValues) + } + return flagValues +} + +func fixtureArgValues(mods ...func(argValues []string)) []string { + argValues := []string{testTokenID} + for _, mod := range mods { + mod(argValues) + } + return argValues +} + +func fixtureInputModel(mods ...func(model *inputModel)) *inputModel { + model := &inputModel{ + GlobalFlagModel: &globalflags.GlobalFlagModel{ + ProjectId: testProjectID, + Region: testRegion, + Verbosity: globalflags.VerbosityDefault, + }, + TokenID: testTokenID, + InstanceID: testInstanceID, + } + for _, mod := range mods { + mod(model) + } + return model +} + +func fixtureRequest() modelexperiments.ApiDeleteInstanceTokenRequest { + return testClient.DefaultAPI.DeleteInstanceToken(testContext, testProjectID, testRegion, testTokenID, testInstanceID) +} + +func TestParseInput(t *testing.T) { + tests := []struct { + description string + argValues []string + flagValues map[string]string + isValid bool + expectedModel *inputModel + }{ + { + description: "base", + argValues: fixtureArgValues(), + flagValues: fixtureFlagValues(), + isValid: true, + expectedModel: fixtureInputModel(), + }, + { + description: "no values", + argValues: []string{}, + flagValues: map[string]string{}, + isValid: false, + }, + { + description: "no arg values", + argValues: []string{}, + flagValues: fixtureFlagValues(), + isValid: false, + }, + { + description: "no flag values", + argValues: fixtureArgValues(), + flagValues: map[string]string{}, + isValid: false, + }, + { + description: "project id missing", + argValues: fixtureArgValues(), + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + delete(flagValues, globalflags.ProjectIdFlag) + }), + isValid: false, + }, + { + description: "project id invalid 1", + argValues: fixtureArgValues(), + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[globalflags.ProjectIdFlag] = "" + }), + isValid: false, + }, + { + description: "project id invalid 2", + argValues: fixtureArgValues(), + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[globalflags.ProjectIdFlag] = "invalid-uuid" + }), + isValid: false, + }, + { + description: "instance id missing", + argValues: fixtureArgValues(), + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + delete(flagValues, instanceIDFlag) + }), + isValid: false, + }, + { + description: "instance id empty", + argValues: fixtureArgValues(), + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[instanceIDFlag] = "" + }), + isValid: false, + }, + { + description: "instance id invalid", + argValues: fixtureArgValues(), + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[instanceIDFlag] = "invalid-uuid" + }), + isValid: false, + }, + { + description: "token id empty", + argValues: []string{""}, + flagValues: fixtureFlagValues(), + isValid: false, + }, + { + description: "token id invalid", + argValues: []string{"invalid-uuid"}, + flagValues: fixtureFlagValues(), + isValid: false, + }, + } + + for _, tt := range tests { + t.Run(tt.description, func(t *testing.T) { + testutils.TestParseInput(t, NewCmd, parseInput, tt.expectedModel, tt.argValues, tt.flagValues, tt.isValid) + }) + } +} + +func TestBuildRequest(t *testing.T) { + request := buildRequest(testContext, fixtureInputModel(), testClient) + expectedRequest := fixtureRequest() + + diff := cmp.Diff(request, expectedRequest, + cmp.AllowUnexported(expectedRequest), + cmpopts.EquateComparable(testContext), + ) + if diff != "" { + t.Fatalf("Data does not match: %s", diff) + } +} diff --git a/internal/cmd/modelexperiments/token/describe/describe.go b/internal/cmd/modelexperiments/token/describe/describe.go new file mode 100644 index 000000000..6d192bef3 --- /dev/null +++ b/internal/cmd/modelexperiments/token/describe/describe.go @@ -0,0 +1,123 @@ +package describe + +import ( + "context" + "fmt" + + "github.com/spf13/cobra" + + "github.com/stackitcloud/stackit-cli/internal/pkg/args" + cliErr "github.com/stackitcloud/stackit-cli/internal/pkg/errors" + "github.com/stackitcloud/stackit-cli/internal/pkg/examples" + "github.com/stackitcloud/stackit-cli/internal/pkg/flags" + "github.com/stackitcloud/stackit-cli/internal/pkg/globalflags" + "github.com/stackitcloud/stackit-cli/internal/pkg/print" + "github.com/stackitcloud/stackit-cli/internal/pkg/services/modelexperiments/client" + "github.com/stackitcloud/stackit-cli/internal/pkg/tables" + "github.com/stackitcloud/stackit-cli/internal/pkg/types" + "github.com/stackitcloud/stackit-cli/internal/pkg/utils" + + modelexperiments "github.com/stackitcloud/stackit-sdk-go/services/modelexperiments/v1api" +) + +const ( + tokenIDArg = "TOKEN_ID" + instanceIDFlag = "instance-id" +) + +type inputModel struct { + *globalflags.GlobalFlagModel + TokenID string + InstanceID string +} + +func NewCmd(params *types.CmdParams) *cobra.Command { + cmd := &cobra.Command{ + Use: fmt.Sprintf("describe %s", tokenIDArg), + Short: "Shows details of an AI Model Experiments instance token", + Long: "Shows details of an auth token for an AI Model Experiments instance.", + Args: args.SingleArg(tokenIDArg, utils.ValidateUUID), + Example: examples.Build( + examples.NewExample( + `Show details of an auth token with ID "xxx"`, + `$ stackit model-experiments token describe xxx --instance-id yyy`, + ), + examples.NewExample( + `Show details of an auth token with ID "xxx" in JSON format`, + `$ stackit model-experiments token describe xxx --instance-id yyy --output-format json`, + ), + ), + RunE: func(cmd *cobra.Command, inputArgs []string) error { + model, err := parseInput(params.Printer, cmd, inputArgs) + if err != nil { + return err + } + apiClient, err := client.ConfigureClient(params.Printer, params.CliVersion) + if err != nil { + return err + } + resp, err := buildRequest(context.Background(), model, apiClient).Execute() + if err != nil { + return fmt.Errorf("describe instance token: %w", err) + } + return outputResult(params.Printer, model, resp) + }, + } + configureFlags(cmd) + return cmd +} + +func configureFlags(cmd *cobra.Command) { + cmd.Flags().Var(flags.UUIDFlag(), instanceIDFlag, "ID of the instance") + err := flags.MarkFlagsRequired(cmd, instanceIDFlag) + cobra.CheckErr(err) +} + +func parseInput(p *print.Printer, cmd *cobra.Command, inputArgs []string) (*inputModel, error) { + globalFlags := globalflags.Parse(p, cmd) + if globalFlags.ProjectId == "" { + return nil, &cliErr.ProjectIdError{} + } + model := &inputModel{ + GlobalFlagModel: globalFlags, + TokenID: inputArgs[0], + InstanceID: flags.FlagToStringValue(p, cmd, instanceIDFlag), + } + p.DebugInputModel(model) + return model, nil +} + +func buildRequest(ctx context.Context, model *inputModel, apiClient *modelexperiments.APIClient) modelexperiments.ApiGetInstanceTokenRequest { + return apiClient.DefaultAPI.GetInstanceToken(ctx, model.ProjectId, model.Region, model.TokenID, model.InstanceID) +} + +func outputResult(p *print.Printer, model *inputModel, resp *modelexperiments.GetInstanceTokenResponse) error { + if resp == nil { + return fmt.Errorf("response token is nil") + } + return p.OutputResult(model.OutputFormat, resp, func() error { + table := tables.NewTable() + table.AddRow("ID", resp.Token.Id) + table.AddSeparator() + table.AddRow("NAME", resp.Token.Name) + table.AddSeparator() + table.AddRow("DESCRIPTION", utils.PtrString(resp.Token.Description)) + table.AddSeparator() + table.AddRow("REGION", resp.Token.Region) + table.AddSeparator() + table.AddRow("STATE", string(resp.Token.State)) + table.AddSeparator() + table.AddRow("VALID UNTIL", resp.Token.ValidUntil.String()) + table.AddSeparator() + labels := "" + if resp.Token.Labels != nil { + labels = fmt.Sprint(*resp.Token.Labels) + } + table.AddRow("LABELS", labels) + table.AddSeparator() + if err := table.Display(p); err != nil { + return fmt.Errorf("render table: %w", err) + } + return nil + }) +} diff --git a/internal/cmd/modelexperiments/token/describe/describe_test.go b/internal/cmd/modelexperiments/token/describe/describe_test.go new file mode 100644 index 000000000..1b6797a9a --- /dev/null +++ b/internal/cmd/modelexperiments/token/describe/describe_test.go @@ -0,0 +1,206 @@ +package describe + +import ( + "context" + "testing" + + "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" + "github.com/google/uuid" + + modelexperiments "github.com/stackitcloud/stackit-sdk-go/services/modelexperiments/v1api" + + "github.com/stackitcloud/stackit-cli/internal/pkg/globalflags" + "github.com/stackitcloud/stackit-cli/internal/pkg/testparams" + "github.com/stackitcloud/stackit-cli/internal/pkg/testutils" +) + +type testContextKey struct{} + +const testRegion = "eu01" + +var ( + testContext = context.WithValue(context.Background(), testContextKey{}, "token-describe") + testClient = &modelexperiments.APIClient{DefaultAPI: modelexperiments.DefaultAPIServiceMock{}} + testProjectID = uuid.NewString() + testInstanceID = uuid.NewString() + testTokenID = uuid.NewString() +) + +func fixtureFlagValues(mods ...func(flagValues map[string]string)) map[string]string { + flagValues := map[string]string{ + globalflags.ProjectIdFlag: testProjectID, + globalflags.RegionFlag: testRegion, + instanceIDFlag: testInstanceID, + } + for _, mod := range mods { + mod(flagValues) + } + return flagValues +} + +func fixtureArgValues(mods ...func(argValues []string)) []string { + argValues := []string{testTokenID} + for _, mod := range mods { + mod(argValues) + } + return argValues +} + +func fixtureInputModel(mods ...func(model *inputModel)) *inputModel { + model := &inputModel{ + GlobalFlagModel: &globalflags.GlobalFlagModel{ + ProjectId: testProjectID, + Region: testRegion, + Verbosity: globalflags.VerbosityDefault, + }, + TokenID: testTokenID, + InstanceID: testInstanceID, + } + for _, mod := range mods { + mod(model) + } + return model +} + +func fixtureRequest() modelexperiments.ApiGetInstanceTokenRequest { + return testClient.DefaultAPI.GetInstanceToken(testContext, testProjectID, testRegion, testTokenID, testInstanceID) +} + +func TestParseInput(t *testing.T) { + tests := []struct { + description string + argValues []string + flagValues map[string]string + isValid bool + expectedModel *inputModel + }{ + { + description: "base", + argValues: fixtureArgValues(), + flagValues: fixtureFlagValues(), + isValid: true, + expectedModel: fixtureInputModel(), + }, + { + description: "no values", + argValues: []string{}, + flagValues: map[string]string{}, + isValid: false, + }, + { + description: "no arg values", + argValues: []string{}, + flagValues: fixtureFlagValues(), + isValid: false, + }, + { + description: "no flag values", + argValues: fixtureArgValues(), + flagValues: map[string]string{}, + isValid: false, + }, + { + description: "project id missing", + argValues: fixtureArgValues(), + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + delete(flagValues, globalflags.ProjectIdFlag) + }), + isValid: false, + }, + { + description: "project id invalid 1", + argValues: fixtureArgValues(), + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[globalflags.ProjectIdFlag] = "" + }), + isValid: false, + }, + { + description: "project id invalid 2", + argValues: fixtureArgValues(), + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[globalflags.ProjectIdFlag] = "invalid-uuid" + }), + isValid: false, + }, + { + description: "instance id missing", + argValues: fixtureArgValues(), + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + delete(flagValues, instanceIDFlag) + }), + isValid: false, + }, + { + description: "instance id empty", + argValues: fixtureArgValues(), + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[instanceIDFlag] = "" + }), + isValid: false, + }, + { + description: "instance id invalid", + argValues: fixtureArgValues(), + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[instanceIDFlag] = "invalid-uuid" + }), + isValid: false, + }, + { + description: "token id empty", + argValues: []string{""}, + flagValues: fixtureFlagValues(), + isValid: false, + }, + { + description: "token id invalid", + argValues: []string{"invalid-uuid"}, + flagValues: fixtureFlagValues(), + isValid: false, + }, + } + + for _, tt := range tests { + t.Run(tt.description, func(t *testing.T) { + testutils.TestParseInput(t, NewCmd, parseInput, tt.expectedModel, tt.argValues, tt.flagValues, tt.isValid) + }) + } +} + +func TestBuildRequest(t *testing.T) { + request := buildRequest(testContext, fixtureInputModel(), testClient) + expectedRequest := fixtureRequest() + diff := cmp.Diff(request, expectedRequest, cmp.AllowUnexported(expectedRequest), cmpopts.EquateComparable(testContext)) + if diff != "" { + t.Fatalf("Data does not match: %s", diff) + } +} + +func TestOutputResult(t *testing.T) { + tests := []struct { + name string + resp *modelexperiments.GetInstanceTokenResponse + wantErr bool + }{ + { + name: "nil response", + resp: nil, + wantErr: true, + }, + { + name: "empty token", + resp: &modelexperiments.GetInstanceTokenResponse{}, + wantErr: false, + }, + } + params := testparams.NewTestParams() + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if err := outputResult(params.Printer, fixtureInputModel(), tt.resp); (err != nil) != tt.wantErr { + t.Errorf("outputResult() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} diff --git a/internal/cmd/modelexperiments/token/list/list.go b/internal/cmd/modelexperiments/token/list/list.go new file mode 100644 index 000000000..652a4f73b --- /dev/null +++ b/internal/cmd/modelexperiments/token/list/list.go @@ -0,0 +1,138 @@ +package list + +import ( + "context" + "fmt" + + "github.com/spf13/cobra" + + "github.com/stackitcloud/stackit-cli/internal/pkg/args" + cliErr "github.com/stackitcloud/stackit-cli/internal/pkg/errors" + "github.com/stackitcloud/stackit-cli/internal/pkg/examples" + "github.com/stackitcloud/stackit-cli/internal/pkg/flags" + "github.com/stackitcloud/stackit-cli/internal/pkg/globalflags" + "github.com/stackitcloud/stackit-cli/internal/pkg/print" + "github.com/stackitcloud/stackit-cli/internal/pkg/projectname" + "github.com/stackitcloud/stackit-cli/internal/pkg/services/modelexperiments/client" + meUtils "github.com/stackitcloud/stackit-cli/internal/pkg/services/modelexperiments/utils" + "github.com/stackitcloud/stackit-cli/internal/pkg/tables" + "github.com/stackitcloud/stackit-cli/internal/pkg/types" + "github.com/stackitcloud/stackit-cli/internal/pkg/utils" + + modelexperiments "github.com/stackitcloud/stackit-sdk-go/services/modelexperiments/v1api" +) + +const ( + instanceIDFlag = "instance-id" + limitFlag = "limit" +) + +type inputModel struct { + *globalflags.GlobalFlagModel + InstanceID string + Limit *int64 +} + +func NewCmd(params *types.CmdParams) *cobra.Command { + cmd := &cobra.Command{ + Use: "list", + Short: "Lists all AI Model Experiments instance tokens", + Long: "Lists all auth tokens for an AI Model Experiments instance.", + Args: args.NoArgs, + Example: examples.Build( + examples.NewExample("List all tokens for an instance", "$ stackit model-experiments token list --instance-id xxx"), + examples.NewExample("List tokens in region eu02", "$ stackit model-experiments token list --instance-id xxx --region eu02"), + examples.NewExample("List tokens in JSON format", "$ stackit model-experiments token list --instance-id xxx --output-format json"), + examples.NewExample("List up to 10 tokens for an instance", "$ stackit model-experiments token list --instance-id xxx --limit 10"), + ), + RunE: func(cmd *cobra.Command, _ []string) error { + ctx := context.Background() + model, err := parseInput(params.Printer, cmd, nil) + if err != nil { + return err + } + apiClient, err := client.ConfigureClient(params.Printer, params.CliVersion) + if err != nil { + return err + } + resp, err := buildRequest(ctx, model, apiClient).Execute() + if err != nil { + return fmt.Errorf("list instance tokens: %w", err) + } + projectLabel, err := projectname.GetProjectName(ctx, params.Printer, params.CliVersion, cmd) + if err != nil { + params.Printer.Debug(print.ErrorLevel, "get project name: %v", err) + projectLabel = model.ProjectId + } else if projectLabel == "" { + projectLabel = model.ProjectId + } + instanceLabel, err := meUtils.GetInstanceName(ctx, apiClient.DefaultAPI, model.ProjectId, model.Region, model.InstanceID) + if err != nil { + params.Printer.Debug(print.ErrorLevel, "get instance name: %v", err) + instanceLabel = model.InstanceID + } + applyLimit(resp, model.Limit) + return outputResult(params.Printer, model, projectLabel, instanceLabel, resp) + }, + } + configureFlags(cmd) + return cmd +} + +func configureFlags(cmd *cobra.Command) { + cmd.Flags().Var(flags.UUIDFlag(), instanceIDFlag, "ID of the instance") + cmd.Flags().Int64(limitFlag, 0, "Maximum number of entries to list") + err := flags.MarkFlagsRequired(cmd, instanceIDFlag) + cobra.CheckErr(err) +} + +func parseInput(p *print.Printer, cmd *cobra.Command, _ []string) (*inputModel, error) { + globalFlags := globalflags.Parse(p, cmd) + if globalFlags.ProjectId == "" { + return nil, &cliErr.ProjectIdError{} + } + limit := flags.FlagToInt64Pointer(p, cmd, limitFlag) + if limit != nil && *limit < 1 { + return nil, &cliErr.FlagValidationError{ + Flag: limitFlag, + Details: "must be greater than 0", + } + } + model := &inputModel{ + GlobalFlagModel: globalFlags, + InstanceID: flags.FlagToStringValue(p, cmd, instanceIDFlag), + Limit: limit, + } + p.DebugInputModel(model) + return model, nil +} + +func buildRequest(ctx context.Context, model *inputModel, apiClient *modelexperiments.APIClient) modelexperiments.ApiListInstanceTokensRequest { + return apiClient.DefaultAPI.ListInstanceTokens(ctx, model.ProjectId, model.Region, model.InstanceID) +} + +func applyLimit(resp *modelexperiments.ListInstanceTokensResponse, limit *int64) { + if resp == nil || limit == nil || int64(len(resp.Tokens)) <= *limit { + return + } + resp.Tokens = resp.Tokens[:int(*limit)] +} + +func outputResult(p *print.Printer, model *inputModel, projectLabel, instanceLabel string, resp *modelexperiments.ListInstanceTokensResponse) error { + if resp == nil { + return fmt.Errorf("response is nil") + } + return p.OutputResult(model.OutputFormat, resp, func() error { + if len(resp.Tokens) == 0 { + p.Outputf("No tokens found for instance %q in project %q\n", instanceLabel, projectLabel) + return nil + } + + table := tables.NewTable() + table.SetHeader("ID", "NAME", "DESCRIPTION", "REGION", "STATE", "VALID UNTIL") + for _, token := range resp.Tokens { + table.AddRow(token.Id, token.Name, utils.PtrString(token.Description), token.Region, token.State, token.ValidUntil.String()) + } + return table.Display(p) + }) +} diff --git a/internal/cmd/modelexperiments/token/list/list_test.go b/internal/cmd/modelexperiments/token/list/list_test.go new file mode 100644 index 000000000..21902cec3 --- /dev/null +++ b/internal/cmd/modelexperiments/token/list/list_test.go @@ -0,0 +1,278 @@ +package list + +import ( + "context" + "strings" + "testing" + + "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" + "github.com/google/uuid" + + modelexperiments "github.com/stackitcloud/stackit-sdk-go/services/modelexperiments/v1api" + + "github.com/stackitcloud/stackit-cli/internal/pkg/globalflags" + "github.com/stackitcloud/stackit-cli/internal/pkg/testparams" + "github.com/stackitcloud/stackit-cli/internal/pkg/testutils" + "github.com/stackitcloud/stackit-cli/internal/pkg/utils" +) + +type testContextKey struct{} + +const testRegion = "eu01" + +var ( + testContext = context.WithValue(context.Background(), testContextKey{}, "token-list") + testClient = &modelexperiments.APIClient{DefaultAPI: modelexperiments.DefaultAPIServiceMock{}} + testProjectID = uuid.NewString() + testInstanceID = uuid.NewString() +) + +func fixtureFlagValues(mods ...func(flagValues map[string]string)) map[string]string { + flagValues := map[string]string{ + globalflags.ProjectIdFlag: testProjectID, + globalflags.RegionFlag: testRegion, + instanceIDFlag: testInstanceID, + } + for _, mod := range mods { + mod(flagValues) + } + return flagValues +} + +func fixtureInputModel(mods ...func(model *inputModel)) *inputModel { + model := &inputModel{ + GlobalFlagModel: &globalflags.GlobalFlagModel{ + ProjectId: testProjectID, + Region: testRegion, + Verbosity: globalflags.VerbosityDefault, + }, + InstanceID: testInstanceID, + } + for _, mod := range mods { + mod(model) + } + return model +} + +func fixtureRequest() modelexperiments.ApiListInstanceTokensRequest { + return testClient.DefaultAPI.ListInstanceTokens(testContext, testProjectID, testRegion, testInstanceID) +} + +func TestParseInput(t *testing.T) { + tests := []struct { + description string + argValues []string + flagValues map[string]string + isValid bool + expectedModel *inputModel + }{ + { + description: "base", + flagValues: fixtureFlagValues(), + isValid: true, + expectedModel: fixtureInputModel(), + }, + { + description: "no values", + flagValues: map[string]string{}, + isValid: false, + }, + { + description: "project id missing", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + delete(flagValues, globalflags.ProjectIdFlag) + }), + isValid: false, + }, + { + description: "project id invalid 1", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[globalflags.ProjectIdFlag] = "" + }), + isValid: false, + }, + { + description: "project id invalid 2", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[globalflags.ProjectIdFlag] = "invalid-uuid" + }), + isValid: false, + }, + { + description: "instance id missing", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + delete(flagValues, instanceIDFlag) + }), + isValid: false, + }, + { + description: "instance id empty", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[instanceIDFlag] = "" + }), + isValid: false, + }, + { + description: "instance id invalid", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[instanceIDFlag] = "invalid-uuid" + }), + isValid: false, + }, + { + description: "limit 0", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[limitFlag] = "0" + }), + isValid: false, + }, + { + description: "limit negative", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[limitFlag] = "-1" + }), + isValid: false, + }, + { + description: "limit invalid string", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[limitFlag] = "invalid" + }), + isValid: false, + }, + { + description: "limit", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[limitFlag] = "10" + }), + isValid: true, + expectedModel: fixtureInputModel(func(model *inputModel) { + model.Limit = utils.Ptr(int64(10)) + }), + }, + } + + for _, tt := range tests { + t.Run(tt.description, func(t *testing.T) { + testutils.TestParseInput(t, NewCmd, parseInput, tt.expectedModel, tt.argValues, tt.flagValues, tt.isValid) + }) + } +} + +func TestBuildRequest(t *testing.T) { + request := buildRequest(testContext, fixtureInputModel(), testClient) + expectedRequest := fixtureRequest() + diff := cmp.Diff(request, expectedRequest, cmp.AllowUnexported(expectedRequest), cmpopts.EquateComparable(testContext)) + if diff != "" { + t.Fatalf("Data does not match: %s", diff) + } +} + +func TestApplyLimit(t *testing.T) { + tests := []struct { + name string + tokens []modelexperiments.TokenMetadata + limit *int64 + nilResp bool + wantCount int + }{ + { + name: "no limit", + tokens: make([]modelexperiments.TokenMetadata, 3), + wantCount: 3, + }, + { + name: "limit below result count", + tokens: make([]modelexperiments.TokenMetadata, 3), + limit: utils.Ptr(int64(2)), + wantCount: 2, + }, + { + name: "limit above result count", + tokens: make([]modelexperiments.TokenMetadata, 2), + limit: utils.Ptr(int64(3)), + wantCount: 2, + }, + { + name: "nil response", + limit: utils.Ptr(int64(1)), + nilResp: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + resp := &modelexperiments.ListInstanceTokensResponse{Tokens: tt.tokens} + if tt.nilResp { + resp = nil + } + + applyLimit(resp, tt.limit) + + if resp == nil { + if !tt.nilResp { + t.Fatal("applyLimit() unexpectedly returned a nil response") + } + return + } + if tt.nilResp { + t.Fatal("applyLimit() changed a nil response") + } + if got := len(resp.Tokens); got != tt.wantCount { + t.Errorf("applyLimit() count = %d, want %d", got, tt.wantCount) + } + }) + } +} + +func TestOutputResult(t *testing.T) { + tests := []struct { + name string + resp *modelexperiments.ListInstanceTokensResponse + wantErr bool + wantOutput []string + }{ + { + name: "nil response", + resp: nil, + wantErr: true, + }, + { + name: "tokens", + resp: &modelexperiments.ListInstanceTokensResponse{ + Tokens: []modelexperiments.TokenMetadata{ + { + Id: "token-id", + Name: "token-name", + Region: testRegion, + State: "READY", + }, + }, + }, + wantOutput: []string{"ID", "NAME", "token-id", "token-name", testRegion, "READY"}, + }, + { + name: "empty tokens", + resp: &modelexperiments.ListInstanceTokensResponse{ + Tokens: []modelexperiments.TokenMetadata{}, + }, + wantOutput: []string{`No tokens found for instance "test-instance" in project "test-project"`}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + params := testparams.NewTestParams() + if err := outputResult(params.Printer, fixtureInputModel(), "test-project", "test-instance", tt.resp); (err != nil) != tt.wantErr { + t.Errorf("outputResult() error = %v, wantErr %v", err, tt.wantErr) + } + + for _, expected := range tt.wantOutput { + if !strings.Contains(params.Out.String(), expected) { + t.Errorf("outputResult() output = %q, want it to contain %q", params.Out.String(), expected) + } + } + }) + } +} diff --git a/internal/cmd/modelexperiments/token/token.go b/internal/cmd/modelexperiments/token/token.go new file mode 100644 index 000000000..757cc082b --- /dev/null +++ b/internal/cmd/modelexperiments/token/token.go @@ -0,0 +1,30 @@ +package token + +import ( + "github.com/spf13/cobra" + + "github.com/stackitcloud/stackit-cli/internal/cmd/modelexperiments/token/create" + "github.com/stackitcloud/stackit-cli/internal/cmd/modelexperiments/token/delete" + "github.com/stackitcloud/stackit-cli/internal/cmd/modelexperiments/token/describe" + "github.com/stackitcloud/stackit-cli/internal/cmd/modelexperiments/token/list" + "github.com/stackitcloud/stackit-cli/internal/cmd/modelexperiments/token/update" + "github.com/stackitcloud/stackit-cli/internal/pkg/args" + "github.com/stackitcloud/stackit-cli/internal/pkg/types" + "github.com/stackitcloud/stackit-cli/internal/pkg/utils" +) + +func NewCmd(params *types.CmdParams) *cobra.Command { + cmd := &cobra.Command{ + Use: "token", + Short: "Provides functionality for AI Model Experiments instance tokens", + Long: "Provides functionality for AI Model Experiments instance tokens.", + Args: args.NoArgs, + Run: utils.CmdHelp, + } + cmd.AddCommand(list.NewCmd(params)) + cmd.AddCommand(create.NewCmd(params)) + cmd.AddCommand(delete.NewCmd(params)) + cmd.AddCommand(describe.NewCmd(params)) + cmd.AddCommand(update.NewCmd(params)) + return cmd +} diff --git a/internal/cmd/modelexperiments/token/update/update.go b/internal/cmd/modelexperiments/token/update/update.go new file mode 100644 index 000000000..739a10cf9 --- /dev/null +++ b/internal/cmd/modelexperiments/token/update/update.go @@ -0,0 +1,161 @@ +package update + +import ( + "context" + "fmt" + + "github.com/spf13/cobra" + + "github.com/stackitcloud/stackit-cli/internal/pkg/args" + cliErr "github.com/stackitcloud/stackit-cli/internal/pkg/errors" + "github.com/stackitcloud/stackit-cli/internal/pkg/examples" + "github.com/stackitcloud/stackit-cli/internal/pkg/flags" + "github.com/stackitcloud/stackit-cli/internal/pkg/globalflags" + "github.com/stackitcloud/stackit-cli/internal/pkg/print" + "github.com/stackitcloud/stackit-cli/internal/pkg/projectname" + "github.com/stackitcloud/stackit-cli/internal/pkg/services/modelexperiments/client" + meUtils "github.com/stackitcloud/stackit-cli/internal/pkg/services/modelexperiments/utils" + "github.com/stackitcloud/stackit-cli/internal/pkg/types" + "github.com/stackitcloud/stackit-cli/internal/pkg/utils" + + modelexperiments "github.com/stackitcloud/stackit-sdk-go/services/modelexperiments/v1api" +) + +const ( + tokenIDArg = "TOKEN_ID" + instanceIDFlag = "instance-id" + nameFlag = "name" + descriptionFlag = "description" + labelsFlag = "labels" +) + +type inputModel struct { + *globalflags.GlobalFlagModel + TokenID string + InstanceID string + Name *string + Description *string + Labels *map[string]*string +} + +func NewCmd(params *types.CmdParams) *cobra.Command { + cmd := &cobra.Command{ + Use: fmt.Sprintf("update %s", tokenIDArg), + Short: "Updates an AI Model Experiments instance token", + Long: "Partially updates an auth token for an AI Model Experiments instance.", + Args: args.SingleArg(tokenIDArg, utils.ValidateUUID), + Example: examples.Build( + examples.NewExample( + `Update the name of an auth token with ID "xxx"`, + `$ stackit model-experiments token update xxx --instance-id yyy --name updated-token`, + ), + examples.NewExample( + `Update the description of an auth token`, + `$ stackit model-experiments token update xxx --instance-id yyy --description "updated token"`, + ), + examples.NewExample( + `Update labels on an auth token`, + `$ stackit model-experiments token update xxx --instance-id yyy --labels env=prod,team=ml`, + ), + examples.NewExample( + `Update multiple fields of an auth token`, + `$ stackit model-experiments token update xxx --instance-id yyy --name updated-token --description "updated token" --labels env=prod,team=ml`, + ), + ), + RunE: func(cmd *cobra.Command, inputArgs []string) error { + ctx := context.Background() + model, err := parseInput(params.Printer, cmd, inputArgs) + if err != nil { + return err + } + apiClient, err := client.ConfigureClient(params.Printer, params.CliVersion) + if err != nil { + return err + } + projectLabel, err := projectname.GetProjectName(ctx, params.Printer, params.CliVersion, cmd) + if err != nil { + params.Printer.Debug(print.ErrorLevel, "get project name: %v", err) + projectLabel = model.ProjectId + } else if projectLabel == "" { + projectLabel = model.ProjectId + } + instanceLabel, err := meUtils.GetInstanceName(ctx, apiClient.DefaultAPI, model.ProjectId, model.Region, model.InstanceID) + if err != nil { + params.Printer.Debug(print.ErrorLevel, "get instance name: %v", err) + instanceLabel = model.InstanceID + } + tokenLabel, err := meUtils.GetTokenName(ctx, apiClient.DefaultAPI, model.ProjectId, model.Region, model.InstanceID, model.TokenID) + if err != nil { + params.Printer.Debug(print.ErrorLevel, "get token name: %v", err) + tokenLabel = model.TokenID + } + prompt := fmt.Sprintf("Are you sure you want to update token %q for instance %q in project %q?", tokenLabel, instanceLabel, projectLabel) + if err := params.Printer.PromptForConfirmation(prompt); err != nil { + return err + } + resp, err := buildRequest(ctx, model, apiClient).Execute() + if err != nil { + return fmt.Errorf("update instance token: %w", err) + } + return outputResult(params.Printer, model, resp) + }, + } + configureFlags(cmd) + return cmd +} + +func configureFlags(cmd *cobra.Command) { + cmd.Flags().Var(flags.UUIDFlag(), instanceIDFlag, "ID of the instance") + cmd.Flags().String(nameFlag, "", "Token name") + cmd.Flags().String(descriptionFlag, "", "Token description") + cmd.Flags().StringToString(labelsFlag, nil, `Labels are comma-separated key-value string pairs, e.g. "--labels env=prod,team=ml"`) + err := flags.MarkFlagsRequired(cmd, instanceIDFlag) + cobra.CheckErr(err) + cmd.MarkFlagsOneRequired(nameFlag, descriptionFlag, labelsFlag) +} + +func parseInput(p *print.Printer, cmd *cobra.Command, inputArgs []string) (*inputModel, error) { + globalFlags := globalflags.Parse(p, cmd) + if globalFlags.ProjectId == "" { + return nil, &cliErr.ProjectIdError{} + } + labels := flags.FlagToStringToAny(p, cmd, labelsFlag) + var labelsPtr *map[string]*string + if len(labels) > 0 { + convertedLabels := make(map[string]*string, len(labels)) + for key, value := range labels { + valueCopy := fmt.Sprint(value) + convertedLabels[key] = &valueCopy + } + labelsPtr = &convertedLabels + } + model := &inputModel{ + GlobalFlagModel: globalFlags, + TokenID: inputArgs[0], + InstanceID: flags.FlagToStringValue(p, cmd, instanceIDFlag), + Name: flags.FlagToStringPointer(p, cmd, nameFlag), + Description: flags.FlagToStringPointer(p, cmd, descriptionFlag), + Labels: labelsPtr, + } + p.DebugInputModel(model) + return model, nil +} + +func buildRequest(ctx context.Context, model *inputModel, apiClient *modelexperiments.APIClient) modelexperiments.ApiPartialUpdateInstanceTokenRequest { + payload := modelexperiments.PartialUpdateInstanceTokenPayload{ + Name: model.Name, + Description: model.Description, + Labels: model.Labels, + } + return apiClient.DefaultAPI.PartialUpdateInstanceToken(ctx, model.ProjectId, model.Region, model.TokenID, model.InstanceID).PartialUpdateInstanceTokenPayload(payload) +} + +func outputResult(p *print.Printer, model *inputModel, resp *modelexperiments.PartialUpdateInstanceTokenResponse) error { + if resp == nil { + return fmt.Errorf("response token is nil") + } + return p.OutputResult(model.OutputFormat, resp, func() error { + p.Outputf("Updated instance token %q (ID: %s)\n", resp.Token.Name, resp.Token.Id) + return nil + }) +} diff --git a/internal/cmd/modelexperiments/token/update/update_test.go b/internal/cmd/modelexperiments/token/update/update_test.go new file mode 100644 index 000000000..af673c676 --- /dev/null +++ b/internal/cmd/modelexperiments/token/update/update_test.go @@ -0,0 +1,298 @@ +package update + +import ( + "context" + "testing" + + "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" + "github.com/google/uuid" + + modelexperiments "github.com/stackitcloud/stackit-sdk-go/services/modelexperiments/v1api" + + "github.com/stackitcloud/stackit-cli/internal/pkg/globalflags" + "github.com/stackitcloud/stackit-cli/internal/pkg/testparams" + "github.com/stackitcloud/stackit-cli/internal/pkg/testutils" + "github.com/stackitcloud/stackit-cli/internal/pkg/utils" +) + +type testContextKey struct{} + +const ( + testRegion = "eu01" + testName = "updated" +) + +var ( + testContext = context.WithValue(context.Background(), testContextKey{}, "token-update") + testClient = &modelexperiments.APIClient{DefaultAPI: modelexperiments.DefaultAPIServiceMock{}} + testProjectID = uuid.NewString() + testInstanceID = uuid.NewString() + testTokenID = uuid.NewString() +) + +func fixtureFlagValues(mods ...func(flagValues map[string]string)) map[string]string { + flagValues := map[string]string{ + globalflags.ProjectIdFlag: testProjectID, + globalflags.RegionFlag: testRegion, + instanceIDFlag: testInstanceID, + } + for _, mod := range mods { + mod(flagValues) + } + return flagValues +} + +func fixtureArgValues(mods ...func(argValues []string)) []string { + argValues := []string{testTokenID} + for _, mod := range mods { + mod(argValues) + } + return argValues +} + +func fixtureInputModel(mods ...func(model *inputModel)) *inputModel { + model := &inputModel{ + GlobalFlagModel: &globalflags.GlobalFlagModel{ + ProjectId: testProjectID, + Region: testRegion, + Verbosity: globalflags.VerbosityDefault, + }, + TokenID: testTokenID, + InstanceID: testInstanceID, + } + for _, mod := range mods { + mod(model) + } + return model +} + +func fixtureRequest(payload modelexperiments.PartialUpdateInstanceTokenPayload) modelexperiments.ApiPartialUpdateInstanceTokenRequest { + return testClient.DefaultAPI.PartialUpdateInstanceToken(testContext, testProjectID, testRegion, testTokenID, testInstanceID). + PartialUpdateInstanceTokenPayload(payload) +} + +func TestParseInput(t *testing.T) { + tests := []struct { + description string + argValues []string + flagValues map[string]string + isValid bool + expectedModel *inputModel + }{ + { + description: "name", + argValues: fixtureArgValues(), + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[nameFlag] = testName + }), + isValid: true, + expectedModel: fixtureInputModel(func(model *inputModel) { + model.Name = utils.Ptr(testName) + }), + }, + { + description: "description", + argValues: fixtureArgValues(), + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[descriptionFlag] = "updated token" + }), + isValid: true, + expectedModel: fixtureInputModel(func(model *inputModel) { + model.Description = utils.Ptr("updated token") + }), + }, + { + description: "labels", + argValues: fixtureArgValues(), + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[labelsFlag] = "env=prod,team=ml" + }), + isValid: true, + expectedModel: fixtureInputModel(func(model *inputModel) { + model.Labels = &map[string]*string{ + "env": utils.Ptr("prod"), + "team": utils.Ptr("ml"), + } + }), + }, + { + description: "no update flags", + argValues: fixtureArgValues(), + flagValues: fixtureFlagValues(), + isValid: false, + }, + { + description: "no values", + argValues: []string{}, + flagValues: map[string]string{}, + isValid: false, + }, + { + description: "no arg values", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[nameFlag] = testName + }), + isValid: false, + }, + { + description: "no flag values", + argValues: fixtureArgValues(), + flagValues: map[string]string{}, + isValid: false, + }, + { + description: "project id missing", + argValues: fixtureArgValues(), + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + delete(flagValues, globalflags.ProjectIdFlag) + flagValues[nameFlag] = testName + }), + isValid: false, + }, + { + description: "project id invalid 1", + argValues: fixtureArgValues(), + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[globalflags.ProjectIdFlag] = "" + flagValues[nameFlag] = testName + }), + isValid: false, + }, + { + description: "project id invalid 2", + argValues: fixtureArgValues(), + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[globalflags.ProjectIdFlag] = "invalid-uuid" + flagValues[nameFlag] = testName + }), + isValid: false, + }, + { + description: "instance id missing", + argValues: fixtureArgValues(), + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + delete(flagValues, instanceIDFlag) + flagValues[nameFlag] = testName + }), + isValid: false, + }, + { + description: "instance id empty", + argValues: fixtureArgValues(), + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[instanceIDFlag] = "" + flagValues[nameFlag] = testName + }), + isValid: false, + }, + { + description: "instance id invalid", + argValues: fixtureArgValues(), + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[instanceIDFlag] = "invalid-uuid" + flagValues[nameFlag] = testName + }), + isValid: false, + }, + { + description: "token id empty", + argValues: []string{""}, + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[nameFlag] = testName + }), + isValid: false, + }, + { + description: "token id invalid", + argValues: []string{"invalid-uuid"}, + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[nameFlag] = testName + }), + isValid: false, + }, + } + + for _, tt := range tests { + t.Run(tt.description, func(t *testing.T) { + testutils.TestParseInput(t, NewCmd, parseInput, tt.expectedModel, tt.argValues, tt.flagValues, tt.isValid) + }) + } +} + +func TestBuildRequest(t *testing.T) { + labels := map[string]*string{ + "env": utils.Ptr("prod"), + "team": utils.Ptr("ml"), + } + tests := []struct { + description string + model *inputModel + expectedRequest modelexperiments.ApiPartialUpdateInstanceTokenRequest + }{ + { + description: "name", + model: fixtureInputModel(func(model *inputModel) { + model.Name = utils.Ptr(testName) + }), + expectedRequest: fixtureRequest(modelexperiments.PartialUpdateInstanceTokenPayload{ + Name: utils.Ptr(testName), + }), + }, + { + description: "description", + model: fixtureInputModel(func(model *inputModel) { + model.Description = utils.Ptr("updated token") + }), + expectedRequest: fixtureRequest(modelexperiments.PartialUpdateInstanceTokenPayload{ + Description: utils.Ptr("updated token"), + }), + }, + { + description: "labels", + model: fixtureInputModel(func(model *inputModel) { + model.Labels = &labels + }), + expectedRequest: fixtureRequest(modelexperiments.PartialUpdateInstanceTokenPayload{ + Labels: &labels, + }), + }, + } + + for _, tt := range tests { + t.Run(tt.description, func(t *testing.T) { + got := buildRequest(testContext, tt.model, testClient) + diff := cmp.Diff(got, tt.expectedRequest, cmp.AllowUnexported(tt.expectedRequest), cmpopts.EquateComparable(testContext)) + if diff != "" { + t.Fatalf("Data does not match: %s", diff) + } + }) + } +} + +func TestOutputResult(t *testing.T) { + tests := []struct { + name string + resp *modelexperiments.PartialUpdateInstanceTokenResponse + wantErr bool + }{ + { + name: "nil response", + resp: nil, + wantErr: true, + }, + { + name: "empty token", + resp: &modelexperiments.PartialUpdateInstanceTokenResponse{}, + wantErr: false, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + params := testparams.NewTestParams() + if err := outputResult(params.Printer, fixtureInputModel(), tt.resp); (err != nil) != tt.wantErr { + t.Errorf("outputResult() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} diff --git a/internal/cmd/root.go b/internal/cmd/root.go index 42c156ca2..99bfdbc01 100644 --- a/internal/cmd/root.go +++ b/internal/cmd/root.go @@ -20,6 +20,7 @@ import ( "github.com/stackitcloud/stackit-cli/internal/cmd/logme" "github.com/stackitcloud/stackit-cli/internal/cmd/logs" "github.com/stackitcloud/stackit-cli/internal/cmd/mariadb" + "github.com/stackitcloud/stackit-cli/internal/cmd/modelexperiments" "github.com/stackitcloud/stackit-cli/internal/cmd/mongodbflex" "github.com/stackitcloud/stackit-cli/internal/cmd/network" networkArea "github.com/stackitcloud/stackit-cli/internal/cmd/network-area" @@ -182,6 +183,7 @@ func addSubcommands(cmd *cobra.Command, params *types.CmdParams) { cmd.AddCommand(logme.NewCmd(params)) cmd.AddCommand(logs.NewCmd(params)) cmd.AddCommand(mariadb.NewCmd(params)) + cmd.AddCommand(modelexperiments.NewCmd(params)) cmd.AddCommand(mongodbflex.NewCmd(params)) cmd.AddCommand(objectstorage.NewCmd(params)) cmd.AddCommand(observability.NewCmd(params)) diff --git a/internal/pkg/config/config.go b/internal/pkg/config/config.go index 56c53899b..7db3bcbf5 100644 --- a/internal/pkg/config/config.go +++ b/internal/pkg/config/config.go @@ -23,22 +23,23 @@ const ( IdentityProviderCustomClientIdKey = "identity_provider_custom_client_id" AllowedUrlDomainKey = "allowed_url_domain" - AuthorizationCustomEndpointKey = "authorization_custom_endpoint" - AutomationCustomEndpointKey = "automation_custom_endpoint" - AlbCustomEndpoint = "alb_custom _endpoint" - AlbWafCustomEndpointKey = "alb_waf_custom_endpoint" - DNSCustomEndpointKey = "dns_custom_endpoint" - EdgeCustomEndpointKey = "edge_custom_endpoint" - LoadBalancerCustomEndpointKey = "load_balancer_custom_endpoint" - LogMeCustomEndpointKey = "logme_custom_endpoint" - MariaDBCustomEndpointKey = "mariadb_custom_endpoint" - MongoDBFlexCustomEndpointKey = "mongodbflex_custom_endpoint" - ObjectStorageCustomEndpointKey = "object_storage_custom_endpoint" - ObservabilityCustomEndpointKey = "observability_custom_endpoint" - OpenSearchCustomEndpointKey = "opensearch_custom_endpoint" - PostgresFlexCustomEndpointKey = "postgresflex_custom_endpoint" - RabbitMQCustomEndpointKey = "rabbitmq_custom_endpoint" - ScfCustomEndpointKey = "scf_custom_endpoint" + AuthorizationCustomEndpointKey = "authorization_custom_endpoint" + AutomationCustomEndpointKey = "automation_custom_endpoint" + AlbCustomEndpoint = "alb_custom _endpoint" + AlbWafCustomEndpointKey = "alb_waf_custom_endpoint" + DNSCustomEndpointKey = "dns_custom_endpoint" + EdgeCustomEndpointKey = "edge_custom_endpoint" + LoadBalancerCustomEndpointKey = "load_balancer_custom_endpoint" + LogMeCustomEndpointKey = "logme_custom_endpoint" + MariaDBCustomEndpointKey = "mariadb_custom_endpoint" + ModelExperimentsCustomEndpointKey = "model_experiments_custom_endpoint" + MongoDBFlexCustomEndpointKey = "mongodbflex_custom_endpoint" + ObjectStorageCustomEndpointKey = "object_storage_custom_endpoint" + ObservabilityCustomEndpointKey = "observability_custom_endpoint" + OpenSearchCustomEndpointKey = "opensearch_custom_endpoint" + PostgresFlexCustomEndpointKey = "postgresflex_custom_endpoint" + RabbitMQCustomEndpointKey = "rabbitmq_custom_endpoint" + ScfCustomEndpointKey = "scf_custom_endpoint" // Deprecated: Will be removed after 2027-08-31. RedisCustomEndpointKey = "redis_custom_endpoint" ResourceManagerEndpointKey = "resource_manager_custom_endpoint" @@ -119,6 +120,7 @@ var ConfigKeys = []string{ OpenSearchCustomEndpointKey, PostgresFlexCustomEndpointKey, RabbitMQCustomEndpointKey, + ModelExperimentsCustomEndpointKey, RedisCustomEndpointKey, ResourceManagerEndpointKey, RunCommandCustomEndpointKey, @@ -231,6 +233,7 @@ func setConfigDefaults() { viper.SetDefault(CDNCustomEndpointKey, "") viper.SetDefault(ValkeyCustomEndpointKey, "") viper.SetDefault(VPNCustomEndpointKey, "") + viper.SetDefault(ModelExperimentsCustomEndpointKey, "") } func getConfigFilePath(configFolder string) string { diff --git a/internal/pkg/services/modelexperiments/client/client.go b/internal/pkg/services/modelexperiments/client/client.go new file mode 100644 index 000000000..3056f32a4 --- /dev/null +++ b/internal/pkg/services/modelexperiments/client/client.go @@ -0,0 +1,14 @@ +package client + +import ( + "github.com/stackitcloud/stackit-cli/internal/pkg/config" + genericclient "github.com/stackitcloud/stackit-cli/internal/pkg/generic-client" + "github.com/stackitcloud/stackit-cli/internal/pkg/print" + + "github.com/spf13/viper" + modelexperiments "github.com/stackitcloud/stackit-sdk-go/services/modelexperiments/v1api" +) + +func ConfigureClient(p *print.Printer, cliVersion string) (*modelexperiments.APIClient, error) { + return genericclient.ConfigureClientGeneric(p, cliVersion, viper.GetString(config.ModelExperimentsCustomEndpointKey), false, modelexperiments.NewAPIClient) +} diff --git a/internal/pkg/services/modelexperiments/utils/utils.go b/internal/pkg/services/modelexperiments/utils/utils.go new file mode 100644 index 000000000..ad9de4945 --- /dev/null +++ b/internal/pkg/services/modelexperiments/utils/utils.go @@ -0,0 +1,33 @@ +package utils + +import ( + "context" + "errors" + "fmt" + + modelexperiments "github.com/stackitcloud/stackit-sdk-go/services/modelexperiments/v1api" +) + +var ErrResponseNil = errors.New("response is nil") + +func GetInstanceName(ctx context.Context, apiClient modelexperiments.DefaultAPI, projectID, regionID, instanceID string) (string, error) { + resp, err := apiClient.GetInstance(ctx, projectID, regionID, instanceID).Execute() + if err != nil { + return "", fmt.Errorf("get AI Model Experiments instance: %w", err) + } + if resp == nil || resp.Instance.Name == "" { + return "", ErrResponseNil + } + return resp.Instance.Name, nil +} + +func GetTokenName(ctx context.Context, apiClient modelexperiments.DefaultAPI, projectID, regionID, instanceID, tokenID string) (string, error) { + resp, err := apiClient.GetInstanceToken(ctx, projectID, regionID, tokenID, instanceID).Execute() + if err != nil { + return "", fmt.Errorf("get AI Model Experiments token: %w", err) + } + if resp == nil || resp.Token.Name == "" { + return "", ErrResponseNil + } + return resp.Token.Name, nil +} diff --git a/internal/pkg/services/modelexperiments/utils/utils_test.go b/internal/pkg/services/modelexperiments/utils/utils_test.go new file mode 100644 index 000000000..f47c7a9ca --- /dev/null +++ b/internal/pkg/services/modelexperiments/utils/utils_test.go @@ -0,0 +1,139 @@ +package utils + +import ( + "context" + "fmt" + "testing" + + "github.com/google/uuid" + + modelexperiments "github.com/stackitcloud/stackit-sdk-go/services/modelexperiments/v1api" + + cliutils "github.com/stackitcloud/stackit-cli/internal/pkg/utils" +) + +const ( + testRegion = "eu01" + testInstanceName = "instance" + testTokenName = "token" +) + +var ( + testProjectID = uuid.NewString() + testInstanceID = uuid.NewString() + testTokenID = uuid.NewString() +) + +type mockSettings struct { + getInstanceFails bool + getInstanceResp *modelexperiments.GetInstanceResponse + getTokenFails bool + getTokenResp *modelexperiments.GetInstanceTokenResponse +} + +func newAPIMock(settings mockSettings) modelexperiments.DefaultAPI { + return &modelexperiments.DefaultAPIServiceMock{ + GetInstanceExecuteMock: cliutils.Ptr(func(modelexperiments.ApiGetInstanceRequest) (*modelexperiments.GetInstanceResponse, error) { + if settings.getInstanceFails { + return nil, fmt.Errorf("could not get instance") + } + return settings.getInstanceResp, nil + }), + GetInstanceTokenExecuteMock: cliutils.Ptr(func(modelexperiments.ApiGetInstanceTokenRequest) (*modelexperiments.GetInstanceTokenResponse, error) { + if settings.getTokenFails { + return nil, fmt.Errorf("could not get token") + } + return settings.getTokenResp, nil + }), + } +} + +func TestGetInstanceName(t *testing.T) { + tests := []struct { + name string + settings mockSettings + want string + wantErr bool + }{ + { + name: "success", + settings: mockSettings{ + getInstanceResp: &modelexperiments.GetInstanceResponse{ + Instance: modelexperiments.Instance{Name: testInstanceName}, + }, + }, + want: testInstanceName, + }, + { + name: "request error", + settings: mockSettings{getInstanceFails: true}, + wantErr: true, + }, + { + name: "nil response", + settings: mockSettings{}, + wantErr: true, + }, + { + name: "nil instance", + settings: mockSettings{getInstanceResp: &modelexperiments.GetInstanceResponse{}}, + wantErr: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := GetInstanceName(context.Background(), newAPIMock(tt.settings), testProjectID, testRegion, testInstanceID) + if (err != nil) != tt.wantErr { + t.Fatalf("error = %v, wantErr %v", err, tt.wantErr) + } + if !tt.wantErr && got != tt.want { + t.Fatalf("name = %q, want %q", got, tt.want) + } + }) + } +} + +func TestGetTokenName(t *testing.T) { + tests := []struct { + name string + settings mockSettings + want string + wantErr bool + }{ + { + name: "success", + settings: mockSettings{ + getTokenResp: &modelexperiments.GetInstanceTokenResponse{ + Token: modelexperiments.TokenMetadata{Name: testTokenName}, + }, + }, + want: testTokenName, + }, + { + name: "request error", + settings: mockSettings{getTokenFails: true}, + wantErr: true, + }, + { + name: "nil response", + settings: mockSettings{}, + wantErr: true, + }, + { + name: "empty token name", + settings: mockSettings{getTokenResp: &modelexperiments.GetInstanceTokenResponse{}}, + wantErr: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := GetTokenName(context.Background(), newAPIMock(tt.settings), testProjectID, testRegion, testInstanceID, testTokenID) + if (err != nil) != tt.wantErr { + t.Fatalf("error = %v, wantErr %v", err, tt.wantErr) + } + if !tt.wantErr && got != tt.want { + t.Fatalf("name = %q, want %q", got, tt.want) + } + }) + } +}