From 40e93550c7d13f5f25708509111f188369d395b3 Mon Sep 17 00:00:00 2001 From: radekska Date: Mon, 25 Nov 2024 12:02:40 +0100 Subject: [PATCH 01/24] add ServiceAccountsAPI and regen SDK --- Makefile | 2 +- castai/sdk/api.gen.go | 297 +++++++++ castai/sdk/client.gen.go | 1241 +++++++++++++++++++++++++++++++++---- castai/sdk/mock/client.go | 315 ++++++++++ 4 files changed, 1735 insertions(+), 120 deletions(-) diff --git a/Makefile b/Makefile index efd47214..ff8dbc35 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,6 @@ SHELL := /bin/bash -export API_TAGS ?= ExternalClusterAPI,PoliciesAPI,NodeConfigurationAPI,NodeTemplatesAPI,AuthTokenAPI,ScheduledRebalancingAPI,InventoryAPI,UsersAPI,OperationsAPI,EvictorAPI,SSOAPI,CommitmentsAPI,WorkloadOptimizationAPI +export API_TAGS ?= ExternalClusterAPI,PoliciesAPI,NodeConfigurationAPI,NodeTemplatesAPI,AuthTokenAPI,ScheduledRebalancingAPI,InventoryAPI,UsersAPI,OperationsAPI,EvictorAPI,SSOAPI,CommitmentsAPI,WorkloadOptimizationAPI,ServiceAccountsAPI export SWAGGER_LOCATION ?= https://api.cast.ai/v1/spec/openapi.json default: build diff --git a/castai/sdk/api.gen.go b/castai/sdk/api.gen.go index b21e9005..7a168c1f 100644 --- a/castai/sdk/api.gen.go +++ b/castai/sdk/api.gen.go @@ -23,6 +23,28 @@ const ( CastaiEvictorV1LabelSelectorExpressionOperatorNotIn CastaiEvictorV1LabelSelectorExpressionOperator = "NotIn" ) +// Defines values for CastaiFeaturesV1EntityType. +const ( + ClusterId CastaiFeaturesV1EntityType = "clusterId" + Environment CastaiFeaturesV1EntityType = "environment" + OrganizationId CastaiFeaturesV1EntityType = "organizationId" + UserId CastaiFeaturesV1EntityType = "userId" +) + +// Defines values for CastaiFeaturesV1LogicalOperator. +const ( + And CastaiFeaturesV1LogicalOperator = "and" + LogicalUnspecified CastaiFeaturesV1LogicalOperator = "logical_unspecified" + Or CastaiFeaturesV1LogicalOperator = "or" +) + +// Defines values for CastaiFeaturesV1Operator. +const ( + Equals CastaiFeaturesV1Operator = "equals" + NotEquals CastaiFeaturesV1Operator = "not_equals" + OperatorUnspecified CastaiFeaturesV1Operator = "operator_unspecified" +) + // Defines values for CastaiInventoryV1beta1AttachableGPUDeviceManufacturer. const ( CastaiInventoryV1beta1AttachableGPUDeviceManufacturerAMD CastaiInventoryV1beta1AttachableGPUDeviceManufacturer = "AMD" @@ -339,6 +361,18 @@ type ExternalClusterAPIGKECreateSARequest struct { Gke *ExternalclusterV1UpdateGKEClusterParams `json:"gke,omitempty"` } +// CreateServiceAccountKeyRequest is the request for creating a service account key. +type ServiceAccountsAPICreateServiceAccountKeyRequest struct { + // Key is the readable version of the service account key. + Key CastaiServiceaccountsV1beta1CreateServiceAccountKeyRequestKey `json:"key"` +} + +// CreateServiceAccountRequest is the request for creating a service account. +type ServiceAccountsAPICreateServiceAccountRequest struct { + // ServiceAccounts is the readable version of the service accounts. + ServiceAccount CastaiServiceaccountsV1beta1CreateServiceAccountRequestServiceAccount `json:"serviceAccount"` +} + // UsersAPIUpdateOrganizationUserRequest defines model for UsersAPI_UpdateOrganizationUser_request. type UsersAPIUpdateOrganizationUserRequest struct { Role *string `json:"role,omitempty"` @@ -471,6 +505,63 @@ type CastaiEvictorV1PodSelector struct { Namespace *string `json:"namespace,omitempty"` } +// Comparison represents a entity to entity ID comparison. +type CastaiFeaturesV1Comparison struct { + // The entity ID to compare against (e.g., "da7a9f8d-ed18-40c3-89a7-93a81283af62"). + EntityId *string `json:"entityId,omitempty"` + + // EntityType defines available entity types for feature flag enablement. + // + // - organizationId: Represents the main identifier(organization_id) for organization in Cast AI. + // - clusterId: Represents the main identifier(cluster_id) for cluster in Cast AI. + // - userId: Represents the user identifier(username) which is used to identify a user in users service. + // - environment: Represents the identifier which is used to identify an environment in Cast AI. + EntityType *CastaiFeaturesV1EntityType `json:"entityType,omitempty"` + + // Operator defines available operators for targeting rules. + // + // - operator_unspecified: unspecified operator. + // - equals: Represents the equals operator, ==. + // - not_equals: Represents the not equals operator, !=. + Operator *CastaiFeaturesV1Operator `json:"operator,omitempty"` +} + +// Represents a condition, which can be a comparison or a nested query. +type CastaiFeaturesV1Condition struct { + // Comparison represents a entity to entity ID comparison. + Comparison *CastaiFeaturesV1Comparison `json:"comparison,omitempty"` + + // QueryExpression represents a logical operation with conditions. + NestedQuery *CastaiFeaturesV1QueryExpression `json:"nestedQuery,omitempty"` +} + +// EntityType defines available entity types for feature flag enablement. +// +// - organizationId: Represents the main identifier(organization_id) for organization in Cast AI. +// - clusterId: Represents the main identifier(cluster_id) for cluster in Cast AI. +// - userId: Represents the user identifier(username) which is used to identify a user in users service. +// - environment: Represents the identifier which is used to identify an environment in Cast AI. +type CastaiFeaturesV1EntityType string + +// LogicalOperator defines available logical operators for targeting rules. +type CastaiFeaturesV1LogicalOperator string + +// Operator defines available operators for targeting rules. +// +// - operator_unspecified: unspecified operator. +// - equals: Represents the equals operator, ==. +// - not_equals: Represents the not equals operator, !=. +type CastaiFeaturesV1Operator string + +// QueryExpression represents a logical operation with conditions. +type CastaiFeaturesV1QueryExpression struct { + // Represents evaluation conditions. + Conditions []CastaiFeaturesV1Condition `json:"conditions"` + + // LogicalOperator defines available logical operators for targeting rules. + LogicalOperator CastaiFeaturesV1LogicalOperator `json:"logicalOperator"` +} + // CastaiInventoryV1beta1AddReservationResponse defines model for castai.inventory.v1beta1.AddReservationResponse. type CastaiInventoryV1beta1AddReservationResponse struct { Reservation *CastaiInventoryV1beta1ReservationDetails `json:"reservation,omitempty"` @@ -1175,6 +1266,186 @@ type CastaiOperationsV1beta1OperationError struct { Reason *string `json:"reason,omitempty"` } +// Page defines how many and which fields should be returned. +type CastaiPaginationV1beta1Page struct { + // Cursor that defines token indicating where to start the next page. + // Empty value indicates to start from beginning of the dataset. + Cursor *string `json:"cursor,omitempty"` + Limit *string `json:"limit,omitempty"` +} + +// Key is the readable version of the service account key. +type CastaiServiceaccountsV1beta1CreateServiceAccountKeyRequestKey struct { + // ExpiresAt is the expiration time of the key. + // A null value means that the key will never expire. + ExpiresAt *time.Time `json:"expiresAt,omitempty"` + + // Name is the name of the service account key. + Name string `json:"name"` +} + +// CreateServiceAccountKeyResponse is the response for creating a service account key. +type CastaiServiceaccountsV1beta1CreateServiceAccountKeyResponse struct { + // Active determines if the key is active. + Active *bool `json:"active,omitempty"` + + // CreatedAt is the creation time of the key. + CreatedAt *time.Time `json:"createdAt,omitempty"` + + // ExpiresAt is the expiration time of the key. + ExpiresAt *time.Time `json:"expiresAt,omitempty"` + + // ID is the unique identifier of the key. + Id *string `json:"id,omitempty"` + + // Name is the name of the key. + Name *string `json:"name,omitempty"` + + // Token is the full secret key. + Token *string `json:"token,omitempty"` +} + +// ServiceAccounts is the readable version of the service accounts. +type CastaiServiceaccountsV1beta1CreateServiceAccountRequestServiceAccount struct { + // Description is the description of the role binding. + Description *string `json:"description,omitempty"` + + // Name is the name of the service account. + Name string `json:"name"` +} + +// CreateServiceAccountResponse is the response for creating a service account. +type CastaiServiceaccountsV1beta1CreateServiceAccountResponse struct { + Author *CastaiServiceaccountsV1beta1CreateServiceAccountResponseAuthor `json:"author,omitempty"` + CreatedAt *time.Time `json:"createdAt,omitempty"` + Description *string `json:"description,omitempty"` + Id *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` +} + +// CastaiServiceaccountsV1beta1CreateServiceAccountResponseAuthor defines model for castai.serviceaccounts.v1beta1.CreateServiceAccountResponse.Author. +type CastaiServiceaccountsV1beta1CreateServiceAccountResponseAuthor struct { + Email *string `json:"email,omitempty"` + Id *string `json:"id,omitempty"` +} + +// DeleteServiceAccountKeyResponse is the response for deleting a service account key. +type CastaiServiceaccountsV1beta1DeleteServiceAccountKeyResponse = map[string]interface{} + +// DeleteServiceAccountResponse is the response for deleting a service account. +type CastaiServiceaccountsV1beta1DeleteServiceAccountResponse = map[string]interface{} + +// GetServiceAccountResponse is the response for getting a service account. +type CastaiServiceaccountsV1beta1GetServiceAccountResponse struct { + // ServiceAccount represents a service account. + ServiceAccount CastaiServiceaccountsV1beta1ServiceAccount `json:"serviceAccount"` +} + +// ListServiceAccountsResponse is the response for listing service accounts. +type CastaiServiceaccountsV1beta1ListServiceAccountsResponse struct { + // Page defines how many and which fields should be returned. + NextPage CastaiPaginationV1beta1Page `json:"nextPage"` + + // ServiceAccounts is the list of service accounts. + ServiceAccounts *[]CastaiServiceaccountsV1beta1ListServiceAccountsResponseServiceAccount `json:"serviceAccounts,omitempty"` + + // TotalCount is the total number of service accounts in the dataset. + TotalCount *string `json:"totalCount,omitempty"` +} + +// ServiceAccounts is the readable version of the service accounts. +type CastaiServiceaccountsV1beta1ListServiceAccountsResponseServiceAccount struct { + // Author is the author of the service account. + Author *CastaiServiceaccountsV1beta1ListServiceAccountsResponseServiceAccountAuthor `json:"author,omitempty"` + + // CreatedAt is the timestamp when the service account was created. + CreatedAt *time.Time `json:"createdAt,omitempty"` + + // Description is the description of the role binding. + Description *string `json:"description,omitempty"` + + // ID is the unique identifier of the service account. + Id *string `json:"id,omitempty"` + + // Keys is the list of keys associated with the service account. + Keys *[]CastaiServiceaccountsV1beta1ListServiceAccountsResponseServiceAccountKey `json:"keys,omitempty"` + + // Name is the name of the service account. + Name *string `json:"name,omitempty"` +} + +// Author is the author of the service account. +type CastaiServiceaccountsV1beta1ListServiceAccountsResponseServiceAccountAuthor struct { + // Email is the email of the author. + Email *string `json:"email,omitempty"` + + // ID is the unique identifier of the author. + Id *string `json:"id,omitempty"` + + // Kind is the kind of the author. + Kind *string `json:"kind,omitempty"` +} + +// Key is the key for the service account. +type CastaiServiceaccountsV1beta1ListServiceAccountsResponseServiceAccountKey struct { + // Active determines if the key is active. + Active *bool `json:"active,omitempty"` + + // ExpiresAt is the expiration time of the key. + ExpiresAt *time.Time `json:"expiresAt,omitempty"` + + // ID is the unique identifier of the key. + Id *string `json:"id,omitempty"` + + // LastUsedAt is the last time the key was used. + LastUsedAt *time.Time `json:"lastUsedAt,omitempty"` + + // Name is the name of the key. + Name *string `json:"name,omitempty"` + + // Prefix is the prefix of the key. + Prefix *string `json:"prefix,omitempty"` +} + +// ServiceAccount represents a service account. +type CastaiServiceaccountsV1beta1ServiceAccount struct { + // CreatedAt is the timestamp when the service account was created. + CreatedAt *time.Time `json:"createdAt,omitempty"` + + // CreatedBy is the user who created the service account. + CreatedBy *string `json:"createdBy,omitempty"` + + // Description is the description of the service account. + Description *string `json:"description,omitempty"` + + // ID is the unique identifier of the service account. + Id *string `json:"id,omitempty"` + + // Name is the name of the service account. + Name string `json:"name"` +} + +// UpdateServiceAccountKeyResponse is the response for updating a service account key. +type CastaiServiceaccountsV1beta1UpdateServiceAccountKeyResponse struct { + // Active determines if the key is active. + Active *bool `json:"active,omitempty"` + + // ExpiresAt is the expiration time of the key. + ExpiresAt *time.Time `json:"expiresAt,omitempty"` + + // ID is the unique identifier of the key. + Id *string `json:"id,omitempty"` + + // LastUsedAt is the last time the key was used. + LastUsedAt *time.Time `json:"lastUsedAt,omitempty"` + + // Name is the name of the key. + Name *string `json:"name,omitempty"` + + // Prefix is the prefix of the key. + Prefix *string `json:"prefix,omitempty"` +} + // AzureAAD represents a Azure AAD connector. type CastaiSsoV1beta1AzureAAD struct { // ADDomain is the domain of the Azure AD. @@ -4231,6 +4502,26 @@ type InventoryAPIAddReservationJSONBody = CastaiInventoryV1beta1GenericReservati // InventoryAPIOverwriteReservationsJSONBody defines parameters for InventoryAPIOverwriteReservations. type InventoryAPIOverwriteReservationsJSONBody = CastaiInventoryV1beta1GenericReservationsList +// ServiceAccountsAPIListServiceAccountsParams defines parameters for ServiceAccountsAPIListServiceAccounts. +type ServiceAccountsAPIListServiceAccountsParams struct { + PageLimit *string `form:"page.limit,omitempty" json:"page.limit,omitempty"` + + // Cursor that defines token indicating where to start the next page. + // Empty value indicates to start from beginning of the dataset. + PageCursor *string `form:"page.cursor,omitempty" json:"page.cursor,omitempty"` +} + +// ServiceAccountsAPICreateServiceAccountJSONBody defines parameters for ServiceAccountsAPICreateServiceAccount. +type ServiceAccountsAPICreateServiceAccountJSONBody = ServiceAccountsAPICreateServiceAccountRequest + +// ServiceAccountsAPICreateServiceAccountKeyJSONBody defines parameters for ServiceAccountsAPICreateServiceAccountKey. +type ServiceAccountsAPICreateServiceAccountKeyJSONBody = ServiceAccountsAPICreateServiceAccountKeyRequest + +// ServiceAccountsAPIUpdateServiceAccountKeyParams defines parameters for ServiceAccountsAPIUpdateServiceAccountKey. +type ServiceAccountsAPIUpdateServiceAccountKeyParams struct { + KeyActive bool `form:"key.active" json:"key.active"` +} + // UsersAPIRemoveOrganizationUsersParams defines parameters for UsersAPIRemoveOrganizationUsers. type UsersAPIRemoveOrganizationUsersParams struct { // Users is the list of user ids to remove. @@ -4478,6 +4769,12 @@ type InventoryAPIAddReservationJSONRequestBody = InventoryAPIAddReservationJSONB // InventoryAPIOverwriteReservationsJSONRequestBody defines body for InventoryAPIOverwriteReservations for application/json ContentType. type InventoryAPIOverwriteReservationsJSONRequestBody = InventoryAPIOverwriteReservationsJSONBody +// ServiceAccountsAPICreateServiceAccountJSONRequestBody defines body for ServiceAccountsAPICreateServiceAccount for application/json ContentType. +type ServiceAccountsAPICreateServiceAccountJSONRequestBody = ServiceAccountsAPICreateServiceAccountJSONBody + +// ServiceAccountsAPICreateServiceAccountKeyJSONRequestBody defines body for ServiceAccountsAPICreateServiceAccountKey for application/json ContentType. +type ServiceAccountsAPICreateServiceAccountKeyJSONRequestBody = ServiceAccountsAPICreateServiceAccountKeyJSONBody + // UsersAPIAddUserToOrganizationJSONRequestBody defines body for UsersAPIAddUserToOrganization for application/json ContentType. type UsersAPIAddUserToOrganizationJSONRequestBody = UsersAPIAddUserToOrganizationJSONBody diff --git a/castai/sdk/client.gen.go b/castai/sdk/client.gen.go index d4cb5ab9..6b20aae4 100644 --- a/castai/sdk/client.gen.go +++ b/castai/sdk/client.gen.go @@ -377,6 +377,28 @@ type ClientInterface interface { // InventoryAPIDeleteReservation request InventoryAPIDeleteReservation(ctx context.Context, organizationId string, reservationId string, reqEditors ...RequestEditorFn) (*http.Response, error) + // ServiceAccountsAPIListServiceAccounts request + ServiceAccountsAPIListServiceAccounts(ctx context.Context, organizationId string, params *ServiceAccountsAPIListServiceAccountsParams, reqEditors ...RequestEditorFn) (*http.Response, error) + + // ServiceAccountsAPICreateServiceAccount request with any body + ServiceAccountsAPICreateServiceAccountWithBody(ctx context.Context, organizationId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + ServiceAccountsAPICreateServiceAccount(ctx context.Context, organizationId string, body ServiceAccountsAPICreateServiceAccountJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // ServiceAccountsAPIDeleteServiceAccount request + ServiceAccountsAPIDeleteServiceAccount(ctx context.Context, organizationId string, serviceAccountId string, reqEditors ...RequestEditorFn) (*http.Response, error) + + // ServiceAccountsAPICreateServiceAccountKey request with any body + ServiceAccountsAPICreateServiceAccountKeyWithBody(ctx context.Context, organizationId string, serviceAccountId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + ServiceAccountsAPICreateServiceAccountKey(ctx context.Context, organizationId string, serviceAccountId string, body ServiceAccountsAPICreateServiceAccountKeyJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // ServiceAccountsAPIUpdateServiceAccountKey request + ServiceAccountsAPIUpdateServiceAccountKey(ctx context.Context, organizationId string, serviceAccountId string, keyId string, params *ServiceAccountsAPIUpdateServiceAccountKeyParams, reqEditors ...RequestEditorFn) (*http.Response, error) + + // ServiceAccountsAPIDeleteServiceAccountKey request + ServiceAccountsAPIDeleteServiceAccountKey(ctx context.Context, organizationId string, serviceAccountId string, keyId string, reqEditors ...RequestEditorFn) (*http.Response, error) + // UsersAPIRemoveOrganizationUsers request UsersAPIRemoveOrganizationUsers(ctx context.Context, organizationId string, params *UsersAPIRemoveOrganizationUsersParams, reqEditors ...RequestEditorFn) (*http.Response, error) @@ -474,6 +496,9 @@ type ClientInterface interface { // ExternalClusterAPIGetCredentialsScriptTemplate request ExternalClusterAPIGetCredentialsScriptTemplate(ctx context.Context, provider string, params *ExternalClusterAPIGetCredentialsScriptTemplateParams, reqEditors ...RequestEditorFn) (*http.Response, error) + // ServiceAccountsAPIGetServiceAccount request + ServiceAccountsAPIGetServiceAccount(ctx context.Context, id string, reqEditors ...RequestEditorFn) (*http.Response, error) + // SSOAPIListSSOConnections request SSOAPIListSSOConnections(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) @@ -1815,6 +1840,102 @@ func (c *Client) InventoryAPIDeleteReservation(ctx context.Context, organization return c.Client.Do(req) } +func (c *Client) ServiceAccountsAPIListServiceAccounts(ctx context.Context, organizationId string, params *ServiceAccountsAPIListServiceAccountsParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewServiceAccountsAPIListServiceAccountsRequest(c.Server, organizationId, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) ServiceAccountsAPICreateServiceAccountWithBody(ctx context.Context, organizationId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewServiceAccountsAPICreateServiceAccountRequestWithBody(c.Server, organizationId, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) ServiceAccountsAPICreateServiceAccount(ctx context.Context, organizationId string, body ServiceAccountsAPICreateServiceAccountJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewServiceAccountsAPICreateServiceAccountRequest(c.Server, organizationId, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) ServiceAccountsAPIDeleteServiceAccount(ctx context.Context, organizationId string, serviceAccountId string, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewServiceAccountsAPIDeleteServiceAccountRequest(c.Server, organizationId, serviceAccountId) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) ServiceAccountsAPICreateServiceAccountKeyWithBody(ctx context.Context, organizationId string, serviceAccountId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewServiceAccountsAPICreateServiceAccountKeyRequestWithBody(c.Server, organizationId, serviceAccountId, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) ServiceAccountsAPICreateServiceAccountKey(ctx context.Context, organizationId string, serviceAccountId string, body ServiceAccountsAPICreateServiceAccountKeyJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewServiceAccountsAPICreateServiceAccountKeyRequest(c.Server, organizationId, serviceAccountId, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) ServiceAccountsAPIUpdateServiceAccountKey(ctx context.Context, organizationId string, serviceAccountId string, keyId string, params *ServiceAccountsAPIUpdateServiceAccountKeyParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewServiceAccountsAPIUpdateServiceAccountKeyRequest(c.Server, organizationId, serviceAccountId, keyId, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) ServiceAccountsAPIDeleteServiceAccountKey(ctx context.Context, organizationId string, serviceAccountId string, keyId string, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewServiceAccountsAPIDeleteServiceAccountKeyRequest(c.Server, organizationId, serviceAccountId, keyId) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + func (c *Client) UsersAPIRemoveOrganizationUsers(ctx context.Context, organizationId string, params *UsersAPIRemoveOrganizationUsersParams, reqEditors ...RequestEditorFn) (*http.Response, error) { req, err := NewUsersAPIRemoveOrganizationUsersRequest(c.Server, organizationId, params) if err != nil { @@ -2235,6 +2356,18 @@ func (c *Client) ExternalClusterAPIGetCredentialsScriptTemplate(ctx context.Cont return c.Client.Do(req) } +func (c *Client) ServiceAccountsAPIGetServiceAccount(ctx context.Context, id string, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewServiceAccountsAPIGetServiceAccountRequest(c.Server, id) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + func (c *Client) SSOAPIListSSOConnections(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) { req, err := NewSSOAPIListSSOConnectionsRequest(c.Server) if err != nil { @@ -6138,8 +6271,8 @@ func NewInventoryAPIDeleteReservationRequest(server string, organizationId strin return req, nil } -// NewUsersAPIRemoveOrganizationUsersRequest generates requests for UsersAPIRemoveOrganizationUsers -func NewUsersAPIRemoveOrganizationUsersRequest(server string, organizationId string, params *UsersAPIRemoveOrganizationUsersParams) (*http.Request, error) { +// NewServiceAccountsAPIListServiceAccountsRequest generates requests for ServiceAccountsAPIListServiceAccounts +func NewServiceAccountsAPIListServiceAccountsRequest(server string, organizationId string, params *ServiceAccountsAPIListServiceAccountsParams) (*http.Request, error) { var err error var pathParam0 string @@ -6154,7 +6287,7 @@ func NewUsersAPIRemoveOrganizationUsersRequest(server string, organizationId str return nil, err } - operationPath := fmt.Sprintf("/v1/organizations/%s/users", pathParam0) + operationPath := fmt.Sprintf("/v1/organizations/%s/service-accounts", pathParam0) if operationPath[0] == '/' { operationPath = "." + operationPath } @@ -6166,59 +6299,25 @@ func NewUsersAPIRemoveOrganizationUsersRequest(server string, organizationId str queryValues := queryURL.Query() - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "users", runtime.ParamLocationQuery, params.Users); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { - return nil, err - } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) + if params.PageLimit != nil { + + if queryFrag, err := runtime.StyleParamWithLocation("form", true, "page.limit", runtime.ParamLocationQuery, *params.PageLimit); err != nil { + return nil, err + } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + return nil, err + } else { + for k, v := range parsed { + for _, v2 := range v { + queryValues.Add(k, v2) + } } } - } - - queryURL.RawQuery = queryValues.Encode() - - req, err := http.NewRequest("DELETE", queryURL.String(), nil) - if err != nil { - return nil, err - } - - return req, nil -} - -// NewUsersAPIListOrganizationUsersRequest generates requests for UsersAPIListOrganizationUsers -func NewUsersAPIListOrganizationUsersRequest(server string, organizationId string, params *UsersAPIListOrganizationUsersParams) (*http.Request, error) { - var err error - - var pathParam0 string - - pathParam0, err = runtime.StyleParamWithLocation("simple", false, "organizationId", runtime.ParamLocationPath, organizationId) - if err != nil { - return nil, err - } - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/v1/organizations/%s/users", pathParam0) - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err } - queryValues := queryURL.Query() - - if params.IncludeGroups != nil { + if params.PageCursor != nil { - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "includeGroups", runtime.ParamLocationQuery, *params.IncludeGroups); err != nil { + if queryFrag, err := runtime.StyleParamWithLocation("form", true, "page.cursor", runtime.ParamLocationQuery, *params.PageCursor); err != nil { return nil, err } else if parsed, err := url.ParseQuery(queryFrag); err != nil { return nil, err @@ -6242,19 +6341,19 @@ func NewUsersAPIListOrganizationUsersRequest(server string, organizationId strin return req, nil } -// NewUsersAPIAddUserToOrganizationRequest calls the generic UsersAPIAddUserToOrganization builder with application/json body -func NewUsersAPIAddUserToOrganizationRequest(server string, organizationId string, body UsersAPIAddUserToOrganizationJSONRequestBody) (*http.Request, error) { +// NewServiceAccountsAPICreateServiceAccountRequest calls the generic ServiceAccountsAPICreateServiceAccount builder with application/json body +func NewServiceAccountsAPICreateServiceAccountRequest(server string, organizationId string, body ServiceAccountsAPICreateServiceAccountJSONRequestBody) (*http.Request, error) { var bodyReader io.Reader buf, err := json.Marshal(body) if err != nil { return nil, err } bodyReader = bytes.NewReader(buf) - return NewUsersAPIAddUserToOrganizationRequestWithBody(server, organizationId, "application/json", bodyReader) + return NewServiceAccountsAPICreateServiceAccountRequestWithBody(server, organizationId, "application/json", bodyReader) } -// NewUsersAPIAddUserToOrganizationRequestWithBody generates requests for UsersAPIAddUserToOrganization with any type of body -func NewUsersAPIAddUserToOrganizationRequestWithBody(server string, organizationId string, contentType string, body io.Reader) (*http.Request, error) { +// NewServiceAccountsAPICreateServiceAccountRequestWithBody generates requests for ServiceAccountsAPICreateServiceAccount with any type of body +func NewServiceAccountsAPICreateServiceAccountRequestWithBody(server string, organizationId string, contentType string, body io.Reader) (*http.Request, error) { var err error var pathParam0 string @@ -6269,7 +6368,7 @@ func NewUsersAPIAddUserToOrganizationRequestWithBody(server string, organization return nil, err } - operationPath := fmt.Sprintf("/v1/organizations/%s/users", pathParam0) + operationPath := fmt.Sprintf("/v1/organizations/%s/service-accounts", pathParam0) if operationPath[0] == '/' { operationPath = "." + operationPath } @@ -6289,8 +6388,8 @@ func NewUsersAPIAddUserToOrganizationRequestWithBody(server string, organization return req, nil } -// NewUsersAPIRemoveUserFromOrganizationRequest generates requests for UsersAPIRemoveUserFromOrganization -func NewUsersAPIRemoveUserFromOrganizationRequest(server string, organizationId string, userId string) (*http.Request, error) { +// NewServiceAccountsAPIDeleteServiceAccountRequest generates requests for ServiceAccountsAPIDeleteServiceAccount +func NewServiceAccountsAPIDeleteServiceAccountRequest(server string, organizationId string, serviceAccountId string) (*http.Request, error) { var err error var pathParam0 string @@ -6302,7 +6401,7 @@ func NewUsersAPIRemoveUserFromOrganizationRequest(server string, organizationId var pathParam1 string - pathParam1, err = runtime.StyleParamWithLocation("simple", false, "userId", runtime.ParamLocationPath, userId) + pathParam1, err = runtime.StyleParamWithLocation("simple", false, "serviceAccountId", runtime.ParamLocationPath, serviceAccountId) if err != nil { return nil, err } @@ -6312,7 +6411,7 @@ func NewUsersAPIRemoveUserFromOrganizationRequest(server string, organizationId return nil, err } - operationPath := fmt.Sprintf("/v1/organizations/%s/users/%s", pathParam0, pathParam1) + operationPath := fmt.Sprintf("/v1/organizations/%s/service-accounts/%s", pathParam0, pathParam1) if operationPath[0] == '/' { operationPath = "." + operationPath } @@ -6330,19 +6429,19 @@ func NewUsersAPIRemoveUserFromOrganizationRequest(server string, organizationId return req, nil } -// NewUsersAPIUpdateOrganizationUserRequest calls the generic UsersAPIUpdateOrganizationUser builder with application/json body -func NewUsersAPIUpdateOrganizationUserRequest(server string, organizationId string, userId string, body UsersAPIUpdateOrganizationUserJSONRequestBody) (*http.Request, error) { +// NewServiceAccountsAPICreateServiceAccountKeyRequest calls the generic ServiceAccountsAPICreateServiceAccountKey builder with application/json body +func NewServiceAccountsAPICreateServiceAccountKeyRequest(server string, organizationId string, serviceAccountId string, body ServiceAccountsAPICreateServiceAccountKeyJSONRequestBody) (*http.Request, error) { var bodyReader io.Reader buf, err := json.Marshal(body) if err != nil { return nil, err } bodyReader = bytes.NewReader(buf) - return NewUsersAPIUpdateOrganizationUserRequestWithBody(server, organizationId, userId, "application/json", bodyReader) + return NewServiceAccountsAPICreateServiceAccountKeyRequestWithBody(server, organizationId, serviceAccountId, "application/json", bodyReader) } -// NewUsersAPIUpdateOrganizationUserRequestWithBody generates requests for UsersAPIUpdateOrganizationUser with any type of body -func NewUsersAPIUpdateOrganizationUserRequestWithBody(server string, organizationId string, userId string, contentType string, body io.Reader) (*http.Request, error) { +// NewServiceAccountsAPICreateServiceAccountKeyRequestWithBody generates requests for ServiceAccountsAPICreateServiceAccountKey with any type of body +func NewServiceAccountsAPICreateServiceAccountKeyRequestWithBody(server string, organizationId string, serviceAccountId string, contentType string, body io.Reader) (*http.Request, error) { var err error var pathParam0 string @@ -6354,7 +6453,7 @@ func NewUsersAPIUpdateOrganizationUserRequestWithBody(server string, organizatio var pathParam1 string - pathParam1, err = runtime.StyleParamWithLocation("simple", false, "userId", runtime.ParamLocationPath, userId) + pathParam1, err = runtime.StyleParamWithLocation("simple", false, "serviceAccountId", runtime.ParamLocationPath, serviceAccountId) if err != nil { return nil, err } @@ -6364,7 +6463,7 @@ func NewUsersAPIUpdateOrganizationUserRequestWithBody(server string, organizatio return nil, err } - operationPath := fmt.Sprintf("/v1/organizations/%s/users/%s", pathParam0, pathParam1) + operationPath := fmt.Sprintf("/v1/organizations/%s/service-accounts/%s/keys", pathParam0, pathParam1) if operationPath[0] == '/' { operationPath = "." + operationPath } @@ -6374,7 +6473,7 @@ func NewUsersAPIUpdateOrganizationUserRequestWithBody(server string, organizatio return nil, err } - req, err := http.NewRequest("PUT", queryURL.String(), body) + req, err := http.NewRequest("POST", queryURL.String(), body) if err != nil { return nil, err } @@ -6384,8 +6483,8 @@ func NewUsersAPIUpdateOrganizationUserRequestWithBody(server string, organizatio return req, nil } -// NewUsersAPIListUserGroupsRequest generates requests for UsersAPIListUserGroups -func NewUsersAPIListUserGroupsRequest(server string, organizationId string, userId string) (*http.Request, error) { +// NewServiceAccountsAPIUpdateServiceAccountKeyRequest generates requests for ServiceAccountsAPIUpdateServiceAccountKey +func NewServiceAccountsAPIUpdateServiceAccountKeyRequest(server string, organizationId string, serviceAccountId string, keyId string, params *ServiceAccountsAPIUpdateServiceAccountKeyParams) (*http.Request, error) { var err error var pathParam0 string @@ -6397,7 +6496,14 @@ func NewUsersAPIListUserGroupsRequest(server string, organizationId string, user var pathParam1 string - pathParam1, err = runtime.StyleParamWithLocation("simple", false, "userId", runtime.ParamLocationPath, userId) + pathParam1, err = runtime.StyleParamWithLocation("simple", false, "serviceAccountId", runtime.ParamLocationPath, serviceAccountId) + if err != nil { + return nil, err + } + + var pathParam2 string + + pathParam2, err = runtime.StyleParamWithLocation("simple", false, "key.id", runtime.ParamLocationPath, keyId) if err != nil { return nil, err } @@ -6407,7 +6513,7 @@ func NewUsersAPIListUserGroupsRequest(server string, organizationId string, user return nil, err } - operationPath := fmt.Sprintf("/v1/organizations/%s/users/%s/groups", pathParam0, pathParam1) + operationPath := fmt.Sprintf("/v1/organizations/%s/service-accounts/%s/keys/%s", pathParam0, pathParam1, pathParam2) if operationPath[0] == '/' { operationPath = "." + operationPath } @@ -6417,7 +6523,23 @@ func NewUsersAPIListUserGroupsRequest(server string, organizationId string, user return nil, err } - req, err := http.NewRequest("GET", queryURL.String(), nil) + queryValues := queryURL.Query() + + if queryFrag, err := runtime.StyleParamWithLocation("form", true, "key.active", runtime.ParamLocationQuery, params.KeyActive); err != nil { + return nil, err + } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + return nil, err + } else { + for k, v := range parsed { + for _, v2 := range v { + queryValues.Add(k, v2) + } + } + } + + queryURL.RawQuery = queryValues.Encode() + + req, err := http.NewRequest("PATCH", queryURL.String(), nil) if err != nil { return nil, err } @@ -6425,16 +6547,37 @@ func NewUsersAPIListUserGroupsRequest(server string, organizationId string, user return req, nil } -// NewScheduledRebalancingAPIListRebalancingSchedulesRequest generates requests for ScheduledRebalancingAPIListRebalancingSchedules -func NewScheduledRebalancingAPIListRebalancingSchedulesRequest(server string) (*http.Request, error) { +// NewServiceAccountsAPIDeleteServiceAccountKeyRequest generates requests for ServiceAccountsAPIDeleteServiceAccountKey +func NewServiceAccountsAPIDeleteServiceAccountKeyRequest(server string, organizationId string, serviceAccountId string, keyId string) (*http.Request, error) { var err error + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithLocation("simple", false, "organizationId", runtime.ParamLocationPath, organizationId) + if err != nil { + return nil, err + } + + var pathParam1 string + + pathParam1, err = runtime.StyleParamWithLocation("simple", false, "serviceAccountId", runtime.ParamLocationPath, serviceAccountId) + if err != nil { + return nil, err + } + + var pathParam2 string + + pathParam2, err = runtime.StyleParamWithLocation("simple", false, "keyId", runtime.ParamLocationPath, keyId) + if err != nil { + return nil, err + } + serverURL, err := url.Parse(server) if err != nil { return nil, err } - operationPath := fmt.Sprintf("/v1/rebalancing-schedules") + operationPath := fmt.Sprintf("/v1/organizations/%s/service-accounts/%s/keys/%s", pathParam0, pathParam1, pathParam2) if operationPath[0] == '/' { operationPath = "." + operationPath } @@ -6444,7 +6587,7 @@ func NewScheduledRebalancingAPIListRebalancingSchedulesRequest(server string) (* return nil, err } - req, err := http.NewRequest("GET", queryURL.String(), nil) + req, err := http.NewRequest("DELETE", queryURL.String(), nil) if err != nil { return nil, err } @@ -6452,27 +6595,23 @@ func NewScheduledRebalancingAPIListRebalancingSchedulesRequest(server string) (* return req, nil } -// NewScheduledRebalancingAPICreateRebalancingScheduleRequest calls the generic ScheduledRebalancingAPICreateRebalancingSchedule builder with application/json body -func NewScheduledRebalancingAPICreateRebalancingScheduleRequest(server string, body ScheduledRebalancingAPICreateRebalancingScheduleJSONRequestBody) (*http.Request, error) { - var bodyReader io.Reader - buf, err := json.Marshal(body) +// NewUsersAPIRemoveOrganizationUsersRequest generates requests for UsersAPIRemoveOrganizationUsers +func NewUsersAPIRemoveOrganizationUsersRequest(server string, organizationId string, params *UsersAPIRemoveOrganizationUsersParams) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithLocation("simple", false, "organizationId", runtime.ParamLocationPath, organizationId) if err != nil { return nil, err } - bodyReader = bytes.NewReader(buf) - return NewScheduledRebalancingAPICreateRebalancingScheduleRequestWithBody(server, "application/json", bodyReader) -} - -// NewScheduledRebalancingAPICreateRebalancingScheduleRequestWithBody generates requests for ScheduledRebalancingAPICreateRebalancingSchedule with any type of body -func NewScheduledRebalancingAPICreateRebalancingScheduleRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) { - var err error serverURL, err := url.Parse(server) if err != nil { return nil, err } - operationPath := fmt.Sprintf("/v1/rebalancing-schedules") + operationPath := fmt.Sprintf("/v1/organizations/%s/users", pathParam0) if operationPath[0] == '/' { operationPath = "." + operationPath } @@ -6482,12 +6621,330 @@ func NewScheduledRebalancingAPICreateRebalancingScheduleRequestWithBody(server s return nil, err } - req, err := http.NewRequest("POST", queryURL.String(), body) - if err != nil { - return nil, err - } - - req.Header.Add("Content-Type", contentType) + queryValues := queryURL.Query() + + if queryFrag, err := runtime.StyleParamWithLocation("form", true, "users", runtime.ParamLocationQuery, params.Users); err != nil { + return nil, err + } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + return nil, err + } else { + for k, v := range parsed { + for _, v2 := range v { + queryValues.Add(k, v2) + } + } + } + + queryURL.RawQuery = queryValues.Encode() + + req, err := http.NewRequest("DELETE", queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewUsersAPIListOrganizationUsersRequest generates requests for UsersAPIListOrganizationUsers +func NewUsersAPIListOrganizationUsersRequest(server string, organizationId string, params *UsersAPIListOrganizationUsersParams) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithLocation("simple", false, "organizationId", runtime.ParamLocationPath, organizationId) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/v1/organizations/%s/users", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + queryValues := queryURL.Query() + + if params.IncludeGroups != nil { + + if queryFrag, err := runtime.StyleParamWithLocation("form", true, "includeGroups", runtime.ParamLocationQuery, *params.IncludeGroups); err != nil { + return nil, err + } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + return nil, err + } else { + for k, v := range parsed { + for _, v2 := range v { + queryValues.Add(k, v2) + } + } + } + + } + + queryURL.RawQuery = queryValues.Encode() + + req, err := http.NewRequest("GET", queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewUsersAPIAddUserToOrganizationRequest calls the generic UsersAPIAddUserToOrganization builder with application/json body +func NewUsersAPIAddUserToOrganizationRequest(server string, organizationId string, body UsersAPIAddUserToOrganizationJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewUsersAPIAddUserToOrganizationRequestWithBody(server, organizationId, "application/json", bodyReader) +} + +// NewUsersAPIAddUserToOrganizationRequestWithBody generates requests for UsersAPIAddUserToOrganization with any type of body +func NewUsersAPIAddUserToOrganizationRequestWithBody(server string, organizationId string, contentType string, body io.Reader) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithLocation("simple", false, "organizationId", runtime.ParamLocationPath, organizationId) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/v1/organizations/%s/users", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("POST", queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewUsersAPIRemoveUserFromOrganizationRequest generates requests for UsersAPIRemoveUserFromOrganization +func NewUsersAPIRemoveUserFromOrganizationRequest(server string, organizationId string, userId string) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithLocation("simple", false, "organizationId", runtime.ParamLocationPath, organizationId) + if err != nil { + return nil, err + } + + var pathParam1 string + + pathParam1, err = runtime.StyleParamWithLocation("simple", false, "userId", runtime.ParamLocationPath, userId) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/v1/organizations/%s/users/%s", pathParam0, pathParam1) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("DELETE", queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewUsersAPIUpdateOrganizationUserRequest calls the generic UsersAPIUpdateOrganizationUser builder with application/json body +func NewUsersAPIUpdateOrganizationUserRequest(server string, organizationId string, userId string, body UsersAPIUpdateOrganizationUserJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewUsersAPIUpdateOrganizationUserRequestWithBody(server, organizationId, userId, "application/json", bodyReader) +} + +// NewUsersAPIUpdateOrganizationUserRequestWithBody generates requests for UsersAPIUpdateOrganizationUser with any type of body +func NewUsersAPIUpdateOrganizationUserRequestWithBody(server string, organizationId string, userId string, contentType string, body io.Reader) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithLocation("simple", false, "organizationId", runtime.ParamLocationPath, organizationId) + if err != nil { + return nil, err + } + + var pathParam1 string + + pathParam1, err = runtime.StyleParamWithLocation("simple", false, "userId", runtime.ParamLocationPath, userId) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/v1/organizations/%s/users/%s", pathParam0, pathParam1) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("PUT", queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewUsersAPIListUserGroupsRequest generates requests for UsersAPIListUserGroups +func NewUsersAPIListUserGroupsRequest(server string, organizationId string, userId string) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithLocation("simple", false, "organizationId", runtime.ParamLocationPath, organizationId) + if err != nil { + return nil, err + } + + var pathParam1 string + + pathParam1, err = runtime.StyleParamWithLocation("simple", false, "userId", runtime.ParamLocationPath, userId) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/v1/organizations/%s/users/%s/groups", pathParam0, pathParam1) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("GET", queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewScheduledRebalancingAPIListRebalancingSchedulesRequest generates requests for ScheduledRebalancingAPIListRebalancingSchedules +func NewScheduledRebalancingAPIListRebalancingSchedulesRequest(server string) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/v1/rebalancing-schedules") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("GET", queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewScheduledRebalancingAPICreateRebalancingScheduleRequest calls the generic ScheduledRebalancingAPICreateRebalancingSchedule builder with application/json body +func NewScheduledRebalancingAPICreateRebalancingScheduleRequest(server string, body ScheduledRebalancingAPICreateRebalancingScheduleJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewScheduledRebalancingAPICreateRebalancingScheduleRequestWithBody(server, "application/json", bodyReader) +} + +// NewScheduledRebalancingAPICreateRebalancingScheduleRequestWithBody generates requests for ScheduledRebalancingAPICreateRebalancingSchedule with any type of body +func NewScheduledRebalancingAPICreateRebalancingScheduleRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/v1/rebalancing-schedules") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("POST", queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) return req, nil } @@ -7376,6 +7833,40 @@ func NewExternalClusterAPIGetCredentialsScriptTemplateRequest(server string, pro return req, nil } +// NewServiceAccountsAPIGetServiceAccountRequest generates requests for ServiceAccountsAPIGetServiceAccount +func NewServiceAccountsAPIGetServiceAccountRequest(server string, id string) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithLocation("simple", false, "id", runtime.ParamLocationPath, id) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/v1/service-accounts/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("GET", queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + // NewSSOAPIListSSOConnectionsRequest generates requests for SSOAPIListSSOConnections func NewSSOAPIListSSOConnectionsRequest(server string) (*http.Request, error) { var err error @@ -8772,6 +9263,28 @@ type ClientWithResponsesInterface interface { // InventoryAPIDeleteReservation request InventoryAPIDeleteReservationWithResponse(ctx context.Context, organizationId string, reservationId string) (*InventoryAPIDeleteReservationResponse, error) + // ServiceAccountsAPIListServiceAccounts request + ServiceAccountsAPIListServiceAccountsWithResponse(ctx context.Context, organizationId string, params *ServiceAccountsAPIListServiceAccountsParams) (*ServiceAccountsAPIListServiceAccountsResponse, error) + + // ServiceAccountsAPICreateServiceAccount request with any body + ServiceAccountsAPICreateServiceAccountWithBodyWithResponse(ctx context.Context, organizationId string, contentType string, body io.Reader) (*ServiceAccountsAPICreateServiceAccountResponse, error) + + ServiceAccountsAPICreateServiceAccountWithResponse(ctx context.Context, organizationId string, body ServiceAccountsAPICreateServiceAccountJSONRequestBody) (*ServiceAccountsAPICreateServiceAccountResponse, error) + + // ServiceAccountsAPIDeleteServiceAccount request + ServiceAccountsAPIDeleteServiceAccountWithResponse(ctx context.Context, organizationId string, serviceAccountId string) (*ServiceAccountsAPIDeleteServiceAccountResponse, error) + + // ServiceAccountsAPICreateServiceAccountKey request with any body + ServiceAccountsAPICreateServiceAccountKeyWithBodyWithResponse(ctx context.Context, organizationId string, serviceAccountId string, contentType string, body io.Reader) (*ServiceAccountsAPICreateServiceAccountKeyResponse, error) + + ServiceAccountsAPICreateServiceAccountKeyWithResponse(ctx context.Context, organizationId string, serviceAccountId string, body ServiceAccountsAPICreateServiceAccountKeyJSONRequestBody) (*ServiceAccountsAPICreateServiceAccountKeyResponse, error) + + // ServiceAccountsAPIUpdateServiceAccountKey request + ServiceAccountsAPIUpdateServiceAccountKeyWithResponse(ctx context.Context, organizationId string, serviceAccountId string, keyId string, params *ServiceAccountsAPIUpdateServiceAccountKeyParams) (*ServiceAccountsAPIUpdateServiceAccountKeyResponse, error) + + // ServiceAccountsAPIDeleteServiceAccountKey request + ServiceAccountsAPIDeleteServiceAccountKeyWithResponse(ctx context.Context, organizationId string, serviceAccountId string, keyId string) (*ServiceAccountsAPIDeleteServiceAccountKeyResponse, error) + // UsersAPIRemoveOrganizationUsers request UsersAPIRemoveOrganizationUsersWithResponse(ctx context.Context, organizationId string, params *UsersAPIRemoveOrganizationUsersParams) (*UsersAPIRemoveOrganizationUsersResponse, error) @@ -8869,6 +9382,9 @@ type ClientWithResponsesInterface interface { // ExternalClusterAPIGetCredentialsScriptTemplate request ExternalClusterAPIGetCredentialsScriptTemplateWithResponse(ctx context.Context, provider string, params *ExternalClusterAPIGetCredentialsScriptTemplateParams) (*ExternalClusterAPIGetCredentialsScriptTemplateResponse, error) + // ServiceAccountsAPIGetServiceAccount request + ServiceAccountsAPIGetServiceAccountWithResponse(ctx context.Context, id string) (*ServiceAccountsAPIGetServiceAccountResponse, error) + // SSOAPIListSSOConnections request SSOAPIListSSOConnectionsWithResponse(ctx context.Context) (*SSOAPIListSSOConnectionsResponse, error) @@ -11121,11 +11637,191 @@ func (r InventoryAPISyncClusterResourcesResponse) GetBody() []byte { type InventoryAPIGetReservationsResponse struct { Body []byte HTTPResponse *http.Response - JSON200 *CastaiInventoryV1beta1GetReservationsResponse + JSON200 *CastaiInventoryV1beta1GetReservationsResponse +} + +// Status returns HTTPResponse.Status +func (r InventoryAPIGetReservationsResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r InventoryAPIGetReservationsResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 +// Body returns body of byte array +func (r InventoryAPIGetReservationsResponse) GetBody() []byte { + return r.Body +} + +// TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 + +type InventoryAPIAddReservationResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *CastaiInventoryV1beta1AddReservationResponse +} + +// Status returns HTTPResponse.Status +func (r InventoryAPIAddReservationResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r InventoryAPIAddReservationResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 +// Body returns body of byte array +func (r InventoryAPIAddReservationResponse) GetBody() []byte { + return r.Body +} + +// TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 + +type InventoryAPIGetReservationsBalanceResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *CastaiInventoryV1beta1GetReservationsBalanceResponse +} + +// Status returns HTTPResponse.Status +func (r InventoryAPIGetReservationsBalanceResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r InventoryAPIGetReservationsBalanceResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 +// Body returns body of byte array +func (r InventoryAPIGetReservationsBalanceResponse) GetBody() []byte { + return r.Body +} + +// TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 + +type InventoryAPIOverwriteReservationsResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *CastaiInventoryV1beta1OverwriteReservationsResponse +} + +// Status returns HTTPResponse.Status +func (r InventoryAPIOverwriteReservationsResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r InventoryAPIOverwriteReservationsResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 +// Body returns body of byte array +func (r InventoryAPIOverwriteReservationsResponse) GetBody() []byte { + return r.Body +} + +// TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 + +type InventoryAPIDeleteReservationResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *map[string]interface{} +} + +// Status returns HTTPResponse.Status +func (r InventoryAPIDeleteReservationResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r InventoryAPIDeleteReservationResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 +// Body returns body of byte array +func (r InventoryAPIDeleteReservationResponse) GetBody() []byte { + return r.Body +} + +// TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 + +type ServiceAccountsAPIListServiceAccountsResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *CastaiServiceaccountsV1beta1ListServiceAccountsResponse +} + +// Status returns HTTPResponse.Status +func (r ServiceAccountsAPIListServiceAccountsResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r ServiceAccountsAPIListServiceAccountsResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 +// Body returns body of byte array +func (r ServiceAccountsAPIListServiceAccountsResponse) GetBody() []byte { + return r.Body +} + +// TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 + +type ServiceAccountsAPICreateServiceAccountResponse struct { + Body []byte + HTTPResponse *http.Response + JSON201 *CastaiServiceaccountsV1beta1CreateServiceAccountResponse } // Status returns HTTPResponse.Status -func (r InventoryAPIGetReservationsResponse) Status() string { +func (r ServiceAccountsAPICreateServiceAccountResponse) Status() string { if r.HTTPResponse != nil { return r.HTTPResponse.Status } @@ -11133,7 +11829,7 @@ func (r InventoryAPIGetReservationsResponse) Status() string { } // StatusCode returns HTTPResponse.StatusCode -func (r InventoryAPIGetReservationsResponse) StatusCode() int { +func (r ServiceAccountsAPICreateServiceAccountResponse) StatusCode() int { if r.HTTPResponse != nil { return r.HTTPResponse.StatusCode } @@ -11142,20 +11838,21 @@ func (r InventoryAPIGetReservationsResponse) StatusCode() int { // TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 // Body returns body of byte array -func (r InventoryAPIGetReservationsResponse) GetBody() []byte { +func (r ServiceAccountsAPICreateServiceAccountResponse) GetBody() []byte { return r.Body } // TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 -type InventoryAPIAddReservationResponse struct { +type ServiceAccountsAPIDeleteServiceAccountResponse struct { Body []byte HTTPResponse *http.Response - JSON200 *CastaiInventoryV1beta1AddReservationResponse + JSON200 *CastaiServiceaccountsV1beta1DeleteServiceAccountResponse + JSON204 *map[string]interface{} } // Status returns HTTPResponse.Status -func (r InventoryAPIAddReservationResponse) Status() string { +func (r ServiceAccountsAPIDeleteServiceAccountResponse) Status() string { if r.HTTPResponse != nil { return r.HTTPResponse.Status } @@ -11163,7 +11860,7 @@ func (r InventoryAPIAddReservationResponse) Status() string { } // StatusCode returns HTTPResponse.StatusCode -func (r InventoryAPIAddReservationResponse) StatusCode() int { +func (r ServiceAccountsAPIDeleteServiceAccountResponse) StatusCode() int { if r.HTTPResponse != nil { return r.HTTPResponse.StatusCode } @@ -11172,20 +11869,21 @@ func (r InventoryAPIAddReservationResponse) StatusCode() int { // TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 // Body returns body of byte array -func (r InventoryAPIAddReservationResponse) GetBody() []byte { +func (r ServiceAccountsAPIDeleteServiceAccountResponse) GetBody() []byte { return r.Body } // TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 -type InventoryAPIGetReservationsBalanceResponse struct { +type ServiceAccountsAPICreateServiceAccountKeyResponse struct { Body []byte HTTPResponse *http.Response - JSON200 *CastaiInventoryV1beta1GetReservationsBalanceResponse + JSON200 *CastaiServiceaccountsV1beta1CreateServiceAccountKeyResponse + JSON201 *map[string]interface{} } // Status returns HTTPResponse.Status -func (r InventoryAPIGetReservationsBalanceResponse) Status() string { +func (r ServiceAccountsAPICreateServiceAccountKeyResponse) Status() string { if r.HTTPResponse != nil { return r.HTTPResponse.Status } @@ -11193,7 +11891,7 @@ func (r InventoryAPIGetReservationsBalanceResponse) Status() string { } // StatusCode returns HTTPResponse.StatusCode -func (r InventoryAPIGetReservationsBalanceResponse) StatusCode() int { +func (r ServiceAccountsAPICreateServiceAccountKeyResponse) StatusCode() int { if r.HTTPResponse != nil { return r.HTTPResponse.StatusCode } @@ -11202,20 +11900,20 @@ func (r InventoryAPIGetReservationsBalanceResponse) StatusCode() int { // TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 // Body returns body of byte array -func (r InventoryAPIGetReservationsBalanceResponse) GetBody() []byte { +func (r ServiceAccountsAPICreateServiceAccountKeyResponse) GetBody() []byte { return r.Body } // TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 -type InventoryAPIOverwriteReservationsResponse struct { +type ServiceAccountsAPIUpdateServiceAccountKeyResponse struct { Body []byte HTTPResponse *http.Response - JSON200 *CastaiInventoryV1beta1OverwriteReservationsResponse + JSON200 *CastaiServiceaccountsV1beta1UpdateServiceAccountKeyResponse } // Status returns HTTPResponse.Status -func (r InventoryAPIOverwriteReservationsResponse) Status() string { +func (r ServiceAccountsAPIUpdateServiceAccountKeyResponse) Status() string { if r.HTTPResponse != nil { return r.HTTPResponse.Status } @@ -11223,7 +11921,7 @@ func (r InventoryAPIOverwriteReservationsResponse) Status() string { } // StatusCode returns HTTPResponse.StatusCode -func (r InventoryAPIOverwriteReservationsResponse) StatusCode() int { +func (r ServiceAccountsAPIUpdateServiceAccountKeyResponse) StatusCode() int { if r.HTTPResponse != nil { return r.HTTPResponse.StatusCode } @@ -11232,20 +11930,20 @@ func (r InventoryAPIOverwriteReservationsResponse) StatusCode() int { // TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 // Body returns body of byte array -func (r InventoryAPIOverwriteReservationsResponse) GetBody() []byte { +func (r ServiceAccountsAPIUpdateServiceAccountKeyResponse) GetBody() []byte { return r.Body } // TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 -type InventoryAPIDeleteReservationResponse struct { +type ServiceAccountsAPIDeleteServiceAccountKeyResponse struct { Body []byte HTTPResponse *http.Response - JSON200 *map[string]interface{} + JSON200 *CastaiServiceaccountsV1beta1DeleteServiceAccountKeyResponse } // Status returns HTTPResponse.Status -func (r InventoryAPIDeleteReservationResponse) Status() string { +func (r ServiceAccountsAPIDeleteServiceAccountKeyResponse) Status() string { if r.HTTPResponse != nil { return r.HTTPResponse.Status } @@ -11253,7 +11951,7 @@ func (r InventoryAPIDeleteReservationResponse) Status() string { } // StatusCode returns HTTPResponse.StatusCode -func (r InventoryAPIDeleteReservationResponse) StatusCode() int { +func (r ServiceAccountsAPIDeleteServiceAccountKeyResponse) StatusCode() int { if r.HTTPResponse != nil { return r.HTTPResponse.StatusCode } @@ -11262,7 +11960,7 @@ func (r InventoryAPIDeleteReservationResponse) StatusCode() int { // TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 // Body returns body of byte array -func (r InventoryAPIDeleteReservationResponse) GetBody() []byte { +func (r ServiceAccountsAPIDeleteServiceAccountKeyResponse) GetBody() []byte { return r.Body } @@ -12075,6 +12773,36 @@ func (r ExternalClusterAPIGetCredentialsScriptTemplateResponse) GetBody() []byte // TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 +type ServiceAccountsAPIGetServiceAccountResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *CastaiServiceaccountsV1beta1GetServiceAccountResponse +} + +// Status returns HTTPResponse.Status +func (r ServiceAccountsAPIGetServiceAccountResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r ServiceAccountsAPIGetServiceAccountResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 +// Body returns body of byte array +func (r ServiceAccountsAPIGetServiceAccountResponse) GetBody() []byte { + return r.Body +} + +// TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 + type SSOAPIListSSOConnectionsResponse struct { Body []byte HTTPResponse *http.Response @@ -13651,6 +14379,76 @@ func (c *ClientWithResponses) InventoryAPIDeleteReservationWithResponse(ctx cont return ParseInventoryAPIDeleteReservationResponse(rsp) } +// ServiceAccountsAPIListServiceAccountsWithResponse request returning *ServiceAccountsAPIListServiceAccountsResponse +func (c *ClientWithResponses) ServiceAccountsAPIListServiceAccountsWithResponse(ctx context.Context, organizationId string, params *ServiceAccountsAPIListServiceAccountsParams) (*ServiceAccountsAPIListServiceAccountsResponse, error) { + rsp, err := c.ServiceAccountsAPIListServiceAccounts(ctx, organizationId, params) + if err != nil { + return nil, err + } + return ParseServiceAccountsAPIListServiceAccountsResponse(rsp) +} + +// ServiceAccountsAPICreateServiceAccountWithBodyWithResponse request with arbitrary body returning *ServiceAccountsAPICreateServiceAccountResponse +func (c *ClientWithResponses) ServiceAccountsAPICreateServiceAccountWithBodyWithResponse(ctx context.Context, organizationId string, contentType string, body io.Reader) (*ServiceAccountsAPICreateServiceAccountResponse, error) { + rsp, err := c.ServiceAccountsAPICreateServiceAccountWithBody(ctx, organizationId, contentType, body) + if err != nil { + return nil, err + } + return ParseServiceAccountsAPICreateServiceAccountResponse(rsp) +} + +func (c *ClientWithResponses) ServiceAccountsAPICreateServiceAccountWithResponse(ctx context.Context, organizationId string, body ServiceAccountsAPICreateServiceAccountJSONRequestBody) (*ServiceAccountsAPICreateServiceAccountResponse, error) { + rsp, err := c.ServiceAccountsAPICreateServiceAccount(ctx, organizationId, body) + if err != nil { + return nil, err + } + return ParseServiceAccountsAPICreateServiceAccountResponse(rsp) +} + +// ServiceAccountsAPIDeleteServiceAccountWithResponse request returning *ServiceAccountsAPIDeleteServiceAccountResponse +func (c *ClientWithResponses) ServiceAccountsAPIDeleteServiceAccountWithResponse(ctx context.Context, organizationId string, serviceAccountId string) (*ServiceAccountsAPIDeleteServiceAccountResponse, error) { + rsp, err := c.ServiceAccountsAPIDeleteServiceAccount(ctx, organizationId, serviceAccountId) + if err != nil { + return nil, err + } + return ParseServiceAccountsAPIDeleteServiceAccountResponse(rsp) +} + +// ServiceAccountsAPICreateServiceAccountKeyWithBodyWithResponse request with arbitrary body returning *ServiceAccountsAPICreateServiceAccountKeyResponse +func (c *ClientWithResponses) ServiceAccountsAPICreateServiceAccountKeyWithBodyWithResponse(ctx context.Context, organizationId string, serviceAccountId string, contentType string, body io.Reader) (*ServiceAccountsAPICreateServiceAccountKeyResponse, error) { + rsp, err := c.ServiceAccountsAPICreateServiceAccountKeyWithBody(ctx, organizationId, serviceAccountId, contentType, body) + if err != nil { + return nil, err + } + return ParseServiceAccountsAPICreateServiceAccountKeyResponse(rsp) +} + +func (c *ClientWithResponses) ServiceAccountsAPICreateServiceAccountKeyWithResponse(ctx context.Context, organizationId string, serviceAccountId string, body ServiceAccountsAPICreateServiceAccountKeyJSONRequestBody) (*ServiceAccountsAPICreateServiceAccountKeyResponse, error) { + rsp, err := c.ServiceAccountsAPICreateServiceAccountKey(ctx, organizationId, serviceAccountId, body) + if err != nil { + return nil, err + } + return ParseServiceAccountsAPICreateServiceAccountKeyResponse(rsp) +} + +// ServiceAccountsAPIUpdateServiceAccountKeyWithResponse request returning *ServiceAccountsAPIUpdateServiceAccountKeyResponse +func (c *ClientWithResponses) ServiceAccountsAPIUpdateServiceAccountKeyWithResponse(ctx context.Context, organizationId string, serviceAccountId string, keyId string, params *ServiceAccountsAPIUpdateServiceAccountKeyParams) (*ServiceAccountsAPIUpdateServiceAccountKeyResponse, error) { + rsp, err := c.ServiceAccountsAPIUpdateServiceAccountKey(ctx, organizationId, serviceAccountId, keyId, params) + if err != nil { + return nil, err + } + return ParseServiceAccountsAPIUpdateServiceAccountKeyResponse(rsp) +} + +// ServiceAccountsAPIDeleteServiceAccountKeyWithResponse request returning *ServiceAccountsAPIDeleteServiceAccountKeyResponse +func (c *ClientWithResponses) ServiceAccountsAPIDeleteServiceAccountKeyWithResponse(ctx context.Context, organizationId string, serviceAccountId string, keyId string) (*ServiceAccountsAPIDeleteServiceAccountKeyResponse, error) { + rsp, err := c.ServiceAccountsAPIDeleteServiceAccountKey(ctx, organizationId, serviceAccountId, keyId) + if err != nil { + return nil, err + } + return ParseServiceAccountsAPIDeleteServiceAccountKeyResponse(rsp) +} + // UsersAPIRemoveOrganizationUsersWithResponse request returning *UsersAPIRemoveOrganizationUsersResponse func (c *ClientWithResponses) UsersAPIRemoveOrganizationUsersWithResponse(ctx context.Context, organizationId string, params *UsersAPIRemoveOrganizationUsersParams) (*UsersAPIRemoveOrganizationUsersResponse, error) { rsp, err := c.UsersAPIRemoveOrganizationUsers(ctx, organizationId, params) @@ -13958,6 +14756,15 @@ func (c *ClientWithResponses) ExternalClusterAPIGetCredentialsScriptTemplateWith return ParseExternalClusterAPIGetCredentialsScriptTemplateResponse(rsp) } +// ServiceAccountsAPIGetServiceAccountWithResponse request returning *ServiceAccountsAPIGetServiceAccountResponse +func (c *ClientWithResponses) ServiceAccountsAPIGetServiceAccountWithResponse(ctx context.Context, id string) (*ServiceAccountsAPIGetServiceAccountResponse, error) { + rsp, err := c.ServiceAccountsAPIGetServiceAccount(ctx, id) + if err != nil { + return nil, err + } + return ParseServiceAccountsAPIGetServiceAccountResponse(rsp) +} + // SSOAPIListSSOConnectionsWithResponse request returning *SSOAPIListSSOConnectionsResponse func (c *ClientWithResponses) SSOAPIListSSOConnectionsWithResponse(ctx context.Context) (*SSOAPIListSSOConnectionsResponse, error) { rsp, err := c.SSOAPIListSSOConnections(ctx) @@ -16204,6 +17011,176 @@ func ParseInventoryAPIDeleteReservationResponse(rsp *http.Response) (*InventoryA return response, nil } +// ParseServiceAccountsAPIListServiceAccountsResponse parses an HTTP response from a ServiceAccountsAPIListServiceAccountsWithResponse call +func ParseServiceAccountsAPIListServiceAccountsResponse(rsp *http.Response) (*ServiceAccountsAPIListServiceAccountsResponse, error) { + bodyBytes, err := ioutil.ReadAll(rsp.Body) + defer rsp.Body.Close() + if err != nil { + return nil, err + } + + response := &ServiceAccountsAPIListServiceAccountsResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest CastaiServiceaccountsV1beta1ListServiceAccountsResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + } + + return response, nil +} + +// ParseServiceAccountsAPICreateServiceAccountResponse parses an HTTP response from a ServiceAccountsAPICreateServiceAccountWithResponse call +func ParseServiceAccountsAPICreateServiceAccountResponse(rsp *http.Response) (*ServiceAccountsAPICreateServiceAccountResponse, error) { + bodyBytes, err := ioutil.ReadAll(rsp.Body) + defer rsp.Body.Close() + if err != nil { + return nil, err + } + + response := &ServiceAccountsAPICreateServiceAccountResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 201: + var dest CastaiServiceaccountsV1beta1CreateServiceAccountResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON201 = &dest + + } + + return response, nil +} + +// ParseServiceAccountsAPIDeleteServiceAccountResponse parses an HTTP response from a ServiceAccountsAPIDeleteServiceAccountWithResponse call +func ParseServiceAccountsAPIDeleteServiceAccountResponse(rsp *http.Response) (*ServiceAccountsAPIDeleteServiceAccountResponse, error) { + bodyBytes, err := ioutil.ReadAll(rsp.Body) + defer rsp.Body.Close() + if err != nil { + return nil, err + } + + response := &ServiceAccountsAPIDeleteServiceAccountResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest CastaiServiceaccountsV1beta1DeleteServiceAccountResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 204: + var dest map[string]interface{} + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON204 = &dest + + } + + return response, nil +} + +// ParseServiceAccountsAPICreateServiceAccountKeyResponse parses an HTTP response from a ServiceAccountsAPICreateServiceAccountKeyWithResponse call +func ParseServiceAccountsAPICreateServiceAccountKeyResponse(rsp *http.Response) (*ServiceAccountsAPICreateServiceAccountKeyResponse, error) { + bodyBytes, err := ioutil.ReadAll(rsp.Body) + defer rsp.Body.Close() + if err != nil { + return nil, err + } + + response := &ServiceAccountsAPICreateServiceAccountKeyResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest CastaiServiceaccountsV1beta1CreateServiceAccountKeyResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 201: + var dest map[string]interface{} + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON201 = &dest + + } + + return response, nil +} + +// ParseServiceAccountsAPIUpdateServiceAccountKeyResponse parses an HTTP response from a ServiceAccountsAPIUpdateServiceAccountKeyWithResponse call +func ParseServiceAccountsAPIUpdateServiceAccountKeyResponse(rsp *http.Response) (*ServiceAccountsAPIUpdateServiceAccountKeyResponse, error) { + bodyBytes, err := ioutil.ReadAll(rsp.Body) + defer rsp.Body.Close() + if err != nil { + return nil, err + } + + response := &ServiceAccountsAPIUpdateServiceAccountKeyResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest CastaiServiceaccountsV1beta1UpdateServiceAccountKeyResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + } + + return response, nil +} + +// ParseServiceAccountsAPIDeleteServiceAccountKeyResponse parses an HTTP response from a ServiceAccountsAPIDeleteServiceAccountKeyWithResponse call +func ParseServiceAccountsAPIDeleteServiceAccountKeyResponse(rsp *http.Response) (*ServiceAccountsAPIDeleteServiceAccountKeyResponse, error) { + bodyBytes, err := ioutil.ReadAll(rsp.Body) + defer rsp.Body.Close() + if err != nil { + return nil, err + } + + response := &ServiceAccountsAPIDeleteServiceAccountKeyResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest CastaiServiceaccountsV1beta1DeleteServiceAccountKeyResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + } + + return response, nil +} + // ParseUsersAPIRemoveOrganizationUsersResponse parses an HTTP response from a UsersAPIRemoveOrganizationUsersWithResponse call func ParseUsersAPIRemoveOrganizationUsersResponse(rsp *http.Response) (*UsersAPIRemoveOrganizationUsersResponse, error) { bodyBytes, err := ioutil.ReadAll(rsp.Body) @@ -16876,6 +17853,32 @@ func ParseExternalClusterAPIGetCredentialsScriptTemplateResponse(rsp *http.Respo return response, nil } +// ParseServiceAccountsAPIGetServiceAccountResponse parses an HTTP response from a ServiceAccountsAPIGetServiceAccountWithResponse call +func ParseServiceAccountsAPIGetServiceAccountResponse(rsp *http.Response) (*ServiceAccountsAPIGetServiceAccountResponse, error) { + bodyBytes, err := ioutil.ReadAll(rsp.Body) + defer rsp.Body.Close() + if err != nil { + return nil, err + } + + response := &ServiceAccountsAPIGetServiceAccountResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest CastaiServiceaccountsV1beta1GetServiceAccountResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + } + + return response, nil +} + // ParseSSOAPIListSSOConnectionsResponse parses an HTTP response from a SSOAPIListSSOConnectionsWithResponse call func ParseSSOAPIListSSOConnectionsResponse(rsp *http.Response) (*SSOAPIListSSOConnectionsResponse, error) { bodyBytes, err := ioutil.ReadAll(rsp.Body) diff --git a/castai/sdk/mock/client.go b/castai/sdk/mock/client.go index 255a1092..75bff2c0 100644 --- a/castai/sdk/mock/client.go +++ b/castai/sdk/mock/client.go @@ -2575,6 +2575,186 @@ func (mr *MockClientInterfaceMockRecorder) ScheduledRebalancingAPIUpdateRebalanc return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ScheduledRebalancingAPIUpdateRebalancingScheduleWithBody", reflect.TypeOf((*MockClientInterface)(nil).ScheduledRebalancingAPIUpdateRebalancingScheduleWithBody), varargs...) } +// ServiceAccountsAPICreateServiceAccount mocks base method. +func (m *MockClientInterface) ServiceAccountsAPICreateServiceAccount(ctx context.Context, organizationId string, body sdk.ServiceAccountsAPICreateServiceAccountJSONRequestBody, reqEditors ...sdk.RequestEditorFn) (*http.Response, error) { + m.ctrl.T.Helper() + varargs := []interface{}{ctx, organizationId, body} + for _, a := range reqEditors { + varargs = append(varargs, a) + } + ret := m.ctrl.Call(m, "ServiceAccountsAPICreateServiceAccount", varargs...) + ret0, _ := ret[0].(*http.Response) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// ServiceAccountsAPICreateServiceAccount indicates an expected call of ServiceAccountsAPICreateServiceAccount. +func (mr *MockClientInterfaceMockRecorder) ServiceAccountsAPICreateServiceAccount(ctx, organizationId, body interface{}, reqEditors ...interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + varargs := append([]interface{}{ctx, organizationId, body}, reqEditors...) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ServiceAccountsAPICreateServiceAccount", reflect.TypeOf((*MockClientInterface)(nil).ServiceAccountsAPICreateServiceAccount), varargs...) +} + +// ServiceAccountsAPICreateServiceAccountKey mocks base method. +func (m *MockClientInterface) ServiceAccountsAPICreateServiceAccountKey(ctx context.Context, organizationId, serviceAccountId string, body sdk.ServiceAccountsAPICreateServiceAccountKeyJSONRequestBody, reqEditors ...sdk.RequestEditorFn) (*http.Response, error) { + m.ctrl.T.Helper() + varargs := []interface{}{ctx, organizationId, serviceAccountId, body} + for _, a := range reqEditors { + varargs = append(varargs, a) + } + ret := m.ctrl.Call(m, "ServiceAccountsAPICreateServiceAccountKey", varargs...) + ret0, _ := ret[0].(*http.Response) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// ServiceAccountsAPICreateServiceAccountKey indicates an expected call of ServiceAccountsAPICreateServiceAccountKey. +func (mr *MockClientInterfaceMockRecorder) ServiceAccountsAPICreateServiceAccountKey(ctx, organizationId, serviceAccountId, body interface{}, reqEditors ...interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + varargs := append([]interface{}{ctx, organizationId, serviceAccountId, body}, reqEditors...) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ServiceAccountsAPICreateServiceAccountKey", reflect.TypeOf((*MockClientInterface)(nil).ServiceAccountsAPICreateServiceAccountKey), varargs...) +} + +// ServiceAccountsAPICreateServiceAccountKeyWithBody mocks base method. +func (m *MockClientInterface) ServiceAccountsAPICreateServiceAccountKeyWithBody(ctx context.Context, organizationId, serviceAccountId, contentType string, body io.Reader, reqEditors ...sdk.RequestEditorFn) (*http.Response, error) { + m.ctrl.T.Helper() + varargs := []interface{}{ctx, organizationId, serviceAccountId, contentType, body} + for _, a := range reqEditors { + varargs = append(varargs, a) + } + ret := m.ctrl.Call(m, "ServiceAccountsAPICreateServiceAccountKeyWithBody", varargs...) + ret0, _ := ret[0].(*http.Response) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// ServiceAccountsAPICreateServiceAccountKeyWithBody indicates an expected call of ServiceAccountsAPICreateServiceAccountKeyWithBody. +func (mr *MockClientInterfaceMockRecorder) ServiceAccountsAPICreateServiceAccountKeyWithBody(ctx, organizationId, serviceAccountId, contentType, body interface{}, reqEditors ...interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + varargs := append([]interface{}{ctx, organizationId, serviceAccountId, contentType, body}, reqEditors...) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ServiceAccountsAPICreateServiceAccountKeyWithBody", reflect.TypeOf((*MockClientInterface)(nil).ServiceAccountsAPICreateServiceAccountKeyWithBody), varargs...) +} + +// ServiceAccountsAPICreateServiceAccountWithBody mocks base method. +func (m *MockClientInterface) ServiceAccountsAPICreateServiceAccountWithBody(ctx context.Context, organizationId, contentType string, body io.Reader, reqEditors ...sdk.RequestEditorFn) (*http.Response, error) { + m.ctrl.T.Helper() + varargs := []interface{}{ctx, organizationId, contentType, body} + for _, a := range reqEditors { + varargs = append(varargs, a) + } + ret := m.ctrl.Call(m, "ServiceAccountsAPICreateServiceAccountWithBody", varargs...) + ret0, _ := ret[0].(*http.Response) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// ServiceAccountsAPICreateServiceAccountWithBody indicates an expected call of ServiceAccountsAPICreateServiceAccountWithBody. +func (mr *MockClientInterfaceMockRecorder) ServiceAccountsAPICreateServiceAccountWithBody(ctx, organizationId, contentType, body interface{}, reqEditors ...interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + varargs := append([]interface{}{ctx, organizationId, contentType, body}, reqEditors...) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ServiceAccountsAPICreateServiceAccountWithBody", reflect.TypeOf((*MockClientInterface)(nil).ServiceAccountsAPICreateServiceAccountWithBody), varargs...) +} + +// ServiceAccountsAPIDeleteServiceAccount mocks base method. +func (m *MockClientInterface) ServiceAccountsAPIDeleteServiceAccount(ctx context.Context, organizationId, serviceAccountId string, reqEditors ...sdk.RequestEditorFn) (*http.Response, error) { + m.ctrl.T.Helper() + varargs := []interface{}{ctx, organizationId, serviceAccountId} + for _, a := range reqEditors { + varargs = append(varargs, a) + } + ret := m.ctrl.Call(m, "ServiceAccountsAPIDeleteServiceAccount", varargs...) + ret0, _ := ret[0].(*http.Response) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// ServiceAccountsAPIDeleteServiceAccount indicates an expected call of ServiceAccountsAPIDeleteServiceAccount. +func (mr *MockClientInterfaceMockRecorder) ServiceAccountsAPIDeleteServiceAccount(ctx, organizationId, serviceAccountId interface{}, reqEditors ...interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + varargs := append([]interface{}{ctx, organizationId, serviceAccountId}, reqEditors...) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ServiceAccountsAPIDeleteServiceAccount", reflect.TypeOf((*MockClientInterface)(nil).ServiceAccountsAPIDeleteServiceAccount), varargs...) +} + +// ServiceAccountsAPIDeleteServiceAccountKey mocks base method. +func (m *MockClientInterface) ServiceAccountsAPIDeleteServiceAccountKey(ctx context.Context, organizationId, serviceAccountId, keyId string, reqEditors ...sdk.RequestEditorFn) (*http.Response, error) { + m.ctrl.T.Helper() + varargs := []interface{}{ctx, organizationId, serviceAccountId, keyId} + for _, a := range reqEditors { + varargs = append(varargs, a) + } + ret := m.ctrl.Call(m, "ServiceAccountsAPIDeleteServiceAccountKey", varargs...) + ret0, _ := ret[0].(*http.Response) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// ServiceAccountsAPIDeleteServiceAccountKey indicates an expected call of ServiceAccountsAPIDeleteServiceAccountKey. +func (mr *MockClientInterfaceMockRecorder) ServiceAccountsAPIDeleteServiceAccountKey(ctx, organizationId, serviceAccountId, keyId interface{}, reqEditors ...interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + varargs := append([]interface{}{ctx, organizationId, serviceAccountId, keyId}, reqEditors...) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ServiceAccountsAPIDeleteServiceAccountKey", reflect.TypeOf((*MockClientInterface)(nil).ServiceAccountsAPIDeleteServiceAccountKey), varargs...) +} + +// ServiceAccountsAPIGetServiceAccount mocks base method. +func (m *MockClientInterface) ServiceAccountsAPIGetServiceAccount(ctx context.Context, id string, reqEditors ...sdk.RequestEditorFn) (*http.Response, error) { + m.ctrl.T.Helper() + varargs := []interface{}{ctx, id} + for _, a := range reqEditors { + varargs = append(varargs, a) + } + ret := m.ctrl.Call(m, "ServiceAccountsAPIGetServiceAccount", varargs...) + ret0, _ := ret[0].(*http.Response) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// ServiceAccountsAPIGetServiceAccount indicates an expected call of ServiceAccountsAPIGetServiceAccount. +func (mr *MockClientInterfaceMockRecorder) ServiceAccountsAPIGetServiceAccount(ctx, id interface{}, reqEditors ...interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + varargs := append([]interface{}{ctx, id}, reqEditors...) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ServiceAccountsAPIGetServiceAccount", reflect.TypeOf((*MockClientInterface)(nil).ServiceAccountsAPIGetServiceAccount), varargs...) +} + +// ServiceAccountsAPIListServiceAccounts mocks base method. +func (m *MockClientInterface) ServiceAccountsAPIListServiceAccounts(ctx context.Context, organizationId string, params *sdk.ServiceAccountsAPIListServiceAccountsParams, reqEditors ...sdk.RequestEditorFn) (*http.Response, error) { + m.ctrl.T.Helper() + varargs := []interface{}{ctx, organizationId, params} + for _, a := range reqEditors { + varargs = append(varargs, a) + } + ret := m.ctrl.Call(m, "ServiceAccountsAPIListServiceAccounts", varargs...) + ret0, _ := ret[0].(*http.Response) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// ServiceAccountsAPIListServiceAccounts indicates an expected call of ServiceAccountsAPIListServiceAccounts. +func (mr *MockClientInterfaceMockRecorder) ServiceAccountsAPIListServiceAccounts(ctx, organizationId, params interface{}, reqEditors ...interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + varargs := append([]interface{}{ctx, organizationId, params}, reqEditors...) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ServiceAccountsAPIListServiceAccounts", reflect.TypeOf((*MockClientInterface)(nil).ServiceAccountsAPIListServiceAccounts), varargs...) +} + +// ServiceAccountsAPIUpdateServiceAccountKey mocks base method. +func (m *MockClientInterface) ServiceAccountsAPIUpdateServiceAccountKey(ctx context.Context, organizationId, serviceAccountId, keyId string, params *sdk.ServiceAccountsAPIUpdateServiceAccountKeyParams, reqEditors ...sdk.RequestEditorFn) (*http.Response, error) { + m.ctrl.T.Helper() + varargs := []interface{}{ctx, organizationId, serviceAccountId, keyId, params} + for _, a := range reqEditors { + varargs = append(varargs, a) + } + ret := m.ctrl.Call(m, "ServiceAccountsAPIUpdateServiceAccountKey", varargs...) + ret0, _ := ret[0].(*http.Response) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// ServiceAccountsAPIUpdateServiceAccountKey indicates an expected call of ServiceAccountsAPIUpdateServiceAccountKey. +func (mr *MockClientInterfaceMockRecorder) ServiceAccountsAPIUpdateServiceAccountKey(ctx, organizationId, serviceAccountId, keyId, params interface{}, reqEditors ...interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + varargs := append([]interface{}{ctx, organizationId, serviceAccountId, keyId, params}, reqEditors...) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ServiceAccountsAPIUpdateServiceAccountKey", reflect.TypeOf((*MockClientInterface)(nil).ServiceAccountsAPIUpdateServiceAccountKey), varargs...) +} + // UsersAPIAddUserToOrganization mocks base method. func (m *MockClientInterface) UsersAPIAddUserToOrganization(ctx context.Context, organizationId string, body sdk.UsersAPIAddUserToOrganizationJSONRequestBody, reqEditors ...sdk.RequestEditorFn) (*http.Response, error) { m.ctrl.T.Helper() @@ -5353,6 +5533,141 @@ func (mr *MockClientWithResponsesInterfaceMockRecorder) ScheduledRebalancingAPIU return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ScheduledRebalancingAPIUpdateRebalancingScheduleWithResponse", reflect.TypeOf((*MockClientWithResponsesInterface)(nil).ScheduledRebalancingAPIUpdateRebalancingScheduleWithResponse), ctx, params, body) } +// ServiceAccountsAPICreateServiceAccountKeyWithBodyWithResponse mocks base method. +func (m *MockClientWithResponsesInterface) ServiceAccountsAPICreateServiceAccountKeyWithBodyWithResponse(ctx context.Context, organizationId, serviceAccountId, contentType string, body io.Reader) (*sdk.ServiceAccountsAPICreateServiceAccountKeyResponse, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "ServiceAccountsAPICreateServiceAccountKeyWithBodyWithResponse", ctx, organizationId, serviceAccountId, contentType, body) + ret0, _ := ret[0].(*sdk.ServiceAccountsAPICreateServiceAccountKeyResponse) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// ServiceAccountsAPICreateServiceAccountKeyWithBodyWithResponse indicates an expected call of ServiceAccountsAPICreateServiceAccountKeyWithBodyWithResponse. +func (mr *MockClientWithResponsesInterfaceMockRecorder) ServiceAccountsAPICreateServiceAccountKeyWithBodyWithResponse(ctx, organizationId, serviceAccountId, contentType, body interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ServiceAccountsAPICreateServiceAccountKeyWithBodyWithResponse", reflect.TypeOf((*MockClientWithResponsesInterface)(nil).ServiceAccountsAPICreateServiceAccountKeyWithBodyWithResponse), ctx, organizationId, serviceAccountId, contentType, body) +} + +// ServiceAccountsAPICreateServiceAccountKeyWithResponse mocks base method. +func (m *MockClientWithResponsesInterface) ServiceAccountsAPICreateServiceAccountKeyWithResponse(ctx context.Context, organizationId, serviceAccountId string, body sdk.ServiceAccountsAPICreateServiceAccountKeyJSONRequestBody) (*sdk.ServiceAccountsAPICreateServiceAccountKeyResponse, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "ServiceAccountsAPICreateServiceAccountKeyWithResponse", ctx, organizationId, serviceAccountId, body) + ret0, _ := ret[0].(*sdk.ServiceAccountsAPICreateServiceAccountKeyResponse) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// ServiceAccountsAPICreateServiceAccountKeyWithResponse indicates an expected call of ServiceAccountsAPICreateServiceAccountKeyWithResponse. +func (mr *MockClientWithResponsesInterfaceMockRecorder) ServiceAccountsAPICreateServiceAccountKeyWithResponse(ctx, organizationId, serviceAccountId, body interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ServiceAccountsAPICreateServiceAccountKeyWithResponse", reflect.TypeOf((*MockClientWithResponsesInterface)(nil).ServiceAccountsAPICreateServiceAccountKeyWithResponse), ctx, organizationId, serviceAccountId, body) +} + +// ServiceAccountsAPICreateServiceAccountWithBodyWithResponse mocks base method. +func (m *MockClientWithResponsesInterface) ServiceAccountsAPICreateServiceAccountWithBodyWithResponse(ctx context.Context, organizationId, contentType string, body io.Reader) (*sdk.ServiceAccountsAPICreateServiceAccountResponse, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "ServiceAccountsAPICreateServiceAccountWithBodyWithResponse", ctx, organizationId, contentType, body) + ret0, _ := ret[0].(*sdk.ServiceAccountsAPICreateServiceAccountResponse) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// ServiceAccountsAPICreateServiceAccountWithBodyWithResponse indicates an expected call of ServiceAccountsAPICreateServiceAccountWithBodyWithResponse. +func (mr *MockClientWithResponsesInterfaceMockRecorder) ServiceAccountsAPICreateServiceAccountWithBodyWithResponse(ctx, organizationId, contentType, body interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ServiceAccountsAPICreateServiceAccountWithBodyWithResponse", reflect.TypeOf((*MockClientWithResponsesInterface)(nil).ServiceAccountsAPICreateServiceAccountWithBodyWithResponse), ctx, organizationId, contentType, body) +} + +// ServiceAccountsAPICreateServiceAccountWithResponse mocks base method. +func (m *MockClientWithResponsesInterface) ServiceAccountsAPICreateServiceAccountWithResponse(ctx context.Context, organizationId string, body sdk.ServiceAccountsAPICreateServiceAccountJSONRequestBody) (*sdk.ServiceAccountsAPICreateServiceAccountResponse, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "ServiceAccountsAPICreateServiceAccountWithResponse", ctx, organizationId, body) + ret0, _ := ret[0].(*sdk.ServiceAccountsAPICreateServiceAccountResponse) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// ServiceAccountsAPICreateServiceAccountWithResponse indicates an expected call of ServiceAccountsAPICreateServiceAccountWithResponse. +func (mr *MockClientWithResponsesInterfaceMockRecorder) ServiceAccountsAPICreateServiceAccountWithResponse(ctx, organizationId, body interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ServiceAccountsAPICreateServiceAccountWithResponse", reflect.TypeOf((*MockClientWithResponsesInterface)(nil).ServiceAccountsAPICreateServiceAccountWithResponse), ctx, organizationId, body) +} + +// ServiceAccountsAPIDeleteServiceAccountKeyWithResponse mocks base method. +func (m *MockClientWithResponsesInterface) ServiceAccountsAPIDeleteServiceAccountKeyWithResponse(ctx context.Context, organizationId, serviceAccountId, keyId string) (*sdk.ServiceAccountsAPIDeleteServiceAccountKeyResponse, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "ServiceAccountsAPIDeleteServiceAccountKeyWithResponse", ctx, organizationId, serviceAccountId, keyId) + ret0, _ := ret[0].(*sdk.ServiceAccountsAPIDeleteServiceAccountKeyResponse) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// ServiceAccountsAPIDeleteServiceAccountKeyWithResponse indicates an expected call of ServiceAccountsAPIDeleteServiceAccountKeyWithResponse. +func (mr *MockClientWithResponsesInterfaceMockRecorder) ServiceAccountsAPIDeleteServiceAccountKeyWithResponse(ctx, organizationId, serviceAccountId, keyId interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ServiceAccountsAPIDeleteServiceAccountKeyWithResponse", reflect.TypeOf((*MockClientWithResponsesInterface)(nil).ServiceAccountsAPIDeleteServiceAccountKeyWithResponse), ctx, organizationId, serviceAccountId, keyId) +} + +// ServiceAccountsAPIDeleteServiceAccountWithResponse mocks base method. +func (m *MockClientWithResponsesInterface) ServiceAccountsAPIDeleteServiceAccountWithResponse(ctx context.Context, organizationId, serviceAccountId string) (*sdk.ServiceAccountsAPIDeleteServiceAccountResponse, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "ServiceAccountsAPIDeleteServiceAccountWithResponse", ctx, organizationId, serviceAccountId) + ret0, _ := ret[0].(*sdk.ServiceAccountsAPIDeleteServiceAccountResponse) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// ServiceAccountsAPIDeleteServiceAccountWithResponse indicates an expected call of ServiceAccountsAPIDeleteServiceAccountWithResponse. +func (mr *MockClientWithResponsesInterfaceMockRecorder) ServiceAccountsAPIDeleteServiceAccountWithResponse(ctx, organizationId, serviceAccountId interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ServiceAccountsAPIDeleteServiceAccountWithResponse", reflect.TypeOf((*MockClientWithResponsesInterface)(nil).ServiceAccountsAPIDeleteServiceAccountWithResponse), ctx, organizationId, serviceAccountId) +} + +// ServiceAccountsAPIGetServiceAccountWithResponse mocks base method. +func (m *MockClientWithResponsesInterface) ServiceAccountsAPIGetServiceAccountWithResponse(ctx context.Context, id string) (*sdk.ServiceAccountsAPIGetServiceAccountResponse, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "ServiceAccountsAPIGetServiceAccountWithResponse", ctx, id) + ret0, _ := ret[0].(*sdk.ServiceAccountsAPIGetServiceAccountResponse) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// ServiceAccountsAPIGetServiceAccountWithResponse indicates an expected call of ServiceAccountsAPIGetServiceAccountWithResponse. +func (mr *MockClientWithResponsesInterfaceMockRecorder) ServiceAccountsAPIGetServiceAccountWithResponse(ctx, id interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ServiceAccountsAPIGetServiceAccountWithResponse", reflect.TypeOf((*MockClientWithResponsesInterface)(nil).ServiceAccountsAPIGetServiceAccountWithResponse), ctx, id) +} + +// ServiceAccountsAPIListServiceAccountsWithResponse mocks base method. +func (m *MockClientWithResponsesInterface) ServiceAccountsAPIListServiceAccountsWithResponse(ctx context.Context, organizationId string, params *sdk.ServiceAccountsAPIListServiceAccountsParams) (*sdk.ServiceAccountsAPIListServiceAccountsResponse, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "ServiceAccountsAPIListServiceAccountsWithResponse", ctx, organizationId, params) + ret0, _ := ret[0].(*sdk.ServiceAccountsAPIListServiceAccountsResponse) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// ServiceAccountsAPIListServiceAccountsWithResponse indicates an expected call of ServiceAccountsAPIListServiceAccountsWithResponse. +func (mr *MockClientWithResponsesInterfaceMockRecorder) ServiceAccountsAPIListServiceAccountsWithResponse(ctx, organizationId, params interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ServiceAccountsAPIListServiceAccountsWithResponse", reflect.TypeOf((*MockClientWithResponsesInterface)(nil).ServiceAccountsAPIListServiceAccountsWithResponse), ctx, organizationId, params) +} + +// ServiceAccountsAPIUpdateServiceAccountKeyWithResponse mocks base method. +func (m *MockClientWithResponsesInterface) ServiceAccountsAPIUpdateServiceAccountKeyWithResponse(ctx context.Context, organizationId, serviceAccountId, keyId string, params *sdk.ServiceAccountsAPIUpdateServiceAccountKeyParams) (*sdk.ServiceAccountsAPIUpdateServiceAccountKeyResponse, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "ServiceAccountsAPIUpdateServiceAccountKeyWithResponse", ctx, organizationId, serviceAccountId, keyId, params) + ret0, _ := ret[0].(*sdk.ServiceAccountsAPIUpdateServiceAccountKeyResponse) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// ServiceAccountsAPIUpdateServiceAccountKeyWithResponse indicates an expected call of ServiceAccountsAPIUpdateServiceAccountKeyWithResponse. +func (mr *MockClientWithResponsesInterfaceMockRecorder) ServiceAccountsAPIUpdateServiceAccountKeyWithResponse(ctx, organizationId, serviceAccountId, keyId, params interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ServiceAccountsAPIUpdateServiceAccountKeyWithResponse", reflect.TypeOf((*MockClientWithResponsesInterface)(nil).ServiceAccountsAPIUpdateServiceAccountKeyWithResponse), ctx, organizationId, serviceAccountId, keyId, params) +} + // UsersAPIAddUserToOrganizationWithBodyWithResponse mocks base method. func (m *MockClientWithResponsesInterface) UsersAPIAddUserToOrganizationWithBodyWithResponse(ctx context.Context, organizationId, contentType string, body io.Reader) (*sdk.UsersAPIAddUserToOrganizationResponse, error) { m.ctrl.T.Helper() From bb351566e66d1c6883b77ac348020a0bfcf92dd7 Mon Sep 17 00:00:00 2001 From: radekska Date: Mon, 25 Nov 2024 12:32:36 +0100 Subject: [PATCH 02/24] wip --- castai/provider.go | 1 + castai/resource_service_account.go | 165 +++++++++++++++++++++++++++++ 2 files changed, 166 insertions(+) create mode 100644 castai/resource_service_account.go diff --git a/castai/provider.go b/castai/provider.go index a227f8b8..8e4904c6 100644 --- a/castai/provider.go +++ b/castai/provider.go @@ -52,6 +52,7 @@ func Provider(version string) *schema.Provider { "castai_commitments": resourceCommitments(), "castai_organization_members": resourceOrganizationMembers(), "castai_sso_connection": resourceSSOConnection(), + "castai_service_account": resourceServiceAccount(), "castai_workload_scaling_policy": resourceWorkloadScalingPolicy(), }, diff --git a/castai/resource_service_account.go b/castai/resource_service_account.go new file mode 100644 index 00000000..b5615cd8 --- /dev/null +++ b/castai/resource_service_account.go @@ -0,0 +1,165 @@ +package castai + +import ( + "context" + "time" + + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + + "github.com/castai/terraform-provider-castai/castai/sdk" +) + +const ( + FieldServiceAccountOrganizationID = "organization_id" + FieldServiceAccountName = "name" + FieldServiceAccountID = "service_account_id" + FieldServiceAccountDescription = "description" + + FieldServiceAccountKeyOrganizationID = "organization_id" + FieldServiceAccountKeyName = "name" + FieldServiceAccountKeyDescription = "description" +) + +func resourceServiceAccount() *schema.Resource { + return &schema.Resource{ + CreateContext: resourceServiceAccountCreate, + ReadContext: resourceServiceAccountRead, + UpdateContext: resourceServiceAccountUpdate, + DeleteContext: resourceServiceAccountDelete, + + Description: "Service Account resource allows managing CAST AI service accounts.", + Timeouts: &schema.ResourceTimeout{ + Create: schema.DefaultTimeout(3 * time.Minute), + Update: schema.DefaultTimeout(3 * time.Minute), + Delete: schema.DefaultTimeout(3 * time.Minute), + }, + Schema: map[string]*schema.Schema{ + FieldServiceAccountOrganizationID: { + Type: schema.TypeString, + Required: true, + ForceNew: true, + Description: "ID of the organization.", + }, + FieldServiceAccountName: { + Type: schema.TypeString, + Required: true, + Description: "Name of the service account.", + }, + FieldServiceAccountDescription: { + Type: schema.TypeString, + Required: false, + Description: "Description of the service account.", + }, + }, + } +} + +func resourceServiceAccountRead(ctx context.Context, data *schema.ResourceData, meta interface{}) diag.Diagnostics { + if data.Id() == "" { + return nil + } + + client := meta.(*ProviderConfig).api + resp, err := client.ServiceAccountsAPIGetServiceAccountWithResponse(ctx, data.Id()) + if err := sdk.CheckOKResponse(resp, err); err != nil { + return diag.Errorf("getting service account: %v", err) + } + + serviceAccount := resp.JSON200 + + if err := data.Set(FieldServiceAccountName, serviceAccount.ServiceAccount.Name); err != nil { + return diag.Errorf("setting service account name: %v", err) + } + if err := data.Set(FieldServiceAccountDescription, serviceAccount.ServiceAccount.Description); err != nil { + return diag.Errorf("setting service account description: %v", err) + } + + return nil +} + +func resourceServiceAccountCreate(ctx context.Context, data *schema.ResourceData, meta interface{}) diag.Diagnostics { + client := meta.(*ProviderConfig).api + + organizationID := data.Get(FieldServiceAccountOrganizationID).(string) + name := data.Get(FieldServiceAccountName).(string) + description := data.Get(FieldServiceAccountDescription).(string) + + resp, err := client.ServiceAccountsAPICreateServiceAccountWithResponse(ctx, organizationID, sdk.ServiceAccountsAPICreateServiceAccountRequest{ + ServiceAccount: sdk.CastaiServiceaccountsV1beta1CreateServiceAccountRequestServiceAccount{ + Description: &description, + Name: name, + }, + }) + + if err := sdk.CheckOKResponse(resp, err); err != nil { + return diag.Errorf("creating service account: %v", err) + } + + data.SetId(*resp.JSON201.Id) + + return nil +} + +func resourceServiceAccountDelete(ctx context.Context, data *schema.ResourceData, meta interface{}) diag.Diagnostics { + return nil +} + +func resourceServiceAccountUpdate(ctx context.Context, data *schema.ResourceData, meta interface{}) diag.Diagnostics { + return nil +} + +func resourceServiceAccountKey() *schema.Resource { + return &schema.Resource{ + ReadContext: resourceServiceAccountKeyRead, + CreateContext: resourceServiceAccountKeyCreate, + UpdateContext: resourceServiceAccountKeyUpdate, + DeleteContext: resourceServiceAccountKeyDelete, + Description: "Service Account Key resource allows managing CAST AI service account keys.", + Timeouts: &schema.ResourceTimeout{ + Create: schema.DefaultTimeout(3 * time.Minute), + Update: schema.DefaultTimeout(3 * time.Minute), + Delete: schema.DefaultTimeout(3 * time.Minute), + }, + Schema: map[string]*schema.Schema{ + FieldServiceAccountKeyOrganizationID: { + Type: schema.TypeString, + Required: true, + ForceNew: true, + Description: "ID of the organization.", + }, + FieldServiceAccountID: { + Type: schema.TypeString, + Required: true, + ForceNew: true, + Description: "ID of the service account.", + }, + FieldServiceAccountKeyName: { + Type: schema.TypeString, + Required: true, + Description: "Name of the service account key.", + }, + FieldServiceAccountKeyDescription: { + Type: schema.TypeString, + Required: false, + Description: "Description of the service account key.", + }, + }, + } +} + +func resourceServiceAccountKeyRead(ctx context.Context, data *schema.ResourceData, meta interface{}) diag.Diagnostics { + return nil +} + +func resourceServiceAccountKeyCreate(ctx context.Context, data *schema.ResourceData, meta interface{}) diag.Diagnostics { + return nil +} + +func resourceServiceAccountKeyDelete(ctx context.Context, data *schema.ResourceData, meta interface{}) diag.Diagnostics { + return nil +} + +func resourceServiceAccountKeyUpdate(ctx context.Context, data *schema.ResourceData, meta interface{}) diag.Diagnostics { + return nil +} From e763a03e001ff9b8fde6689bfab297ba482e3410 Mon Sep 17 00:00:00 2001 From: radekska Date: Mon, 25 Nov 2024 14:47:43 +0100 Subject: [PATCH 03/24] wip --- castai/resource_service_account.go | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/castai/resource_service_account.go b/castai/resource_service_account.go index b5615cd8..fb3015f4 100644 --- a/castai/resource_service_account.go +++ b/castai/resource_service_account.go @@ -102,6 +102,15 @@ func resourceServiceAccountCreate(ctx context.Context, data *schema.ResourceData } func resourceServiceAccountDelete(ctx context.Context, data *schema.ResourceData, meta interface{}) diag.Diagnostics { + client := meta.(*ProviderConfig).api + organizationID := data.Get(FieldServiceAccountOrganizationID).(string) + serviceAccountID := data.Id() + + + resp, err := client.ServiceAccountsAPIDeleteServiceAccountWithResponse(ctx, organizationID, serviceAccountID) + if err := sdk.CheckResponseNoContent(resp, err); err != nil { + return diag.Errorf("deleteting service account: %v", err) + } return nil } From edfbe5011686da9c13f8dd32e9795b8c53a2da96 Mon Sep 17 00:00:00 2001 From: radekska Date: Tue, 26 Nov 2024 14:10:29 +0100 Subject: [PATCH 04/24] regen --- castai/resource_service_account.go | 42 +-- castai/sdk/api.gen.go | 69 +++-- castai/sdk/client.gen.go | 405 ++++++++++++++++++++--------- castai/sdk/mock/client.go | 51 +++- docs/resources/service_account.md | 41 +++ 5 files changed, 443 insertions(+), 165 deletions(-) create mode 100644 docs/resources/service_account.md diff --git a/castai/resource_service_account.go b/castai/resource_service_account.go index fb3015f4..e0d15d88 100644 --- a/castai/resource_service_account.go +++ b/castai/resource_service_account.go @@ -34,6 +34,7 @@ func resourceServiceAccount() *schema.Resource { Update: schema.DefaultTimeout(3 * time.Minute), Delete: schema.DefaultTimeout(3 * time.Minute), }, + Schema: map[string]*schema.Schema{ FieldServiceAccountOrganizationID: { Type: schema.TypeString, @@ -48,7 +49,7 @@ func resourceServiceAccount() *schema.Resource { }, FieldServiceAccountDescription: { Type: schema.TypeString, - Required: false, + Optional: true, Description: "Description of the service account.", }, }, @@ -60,20 +61,20 @@ func resourceServiceAccountRead(ctx context.Context, data *schema.ResourceData, return nil } - client := meta.(*ProviderConfig).api - resp, err := client.ServiceAccountsAPIGetServiceAccountWithResponse(ctx, data.Id()) - if err := sdk.CheckOKResponse(resp, err); err != nil { - return diag.Errorf("getting service account: %v", err) - } - - serviceAccount := resp.JSON200 - - if err := data.Set(FieldServiceAccountName, serviceAccount.ServiceAccount.Name); err != nil { - return diag.Errorf("setting service account name: %v", err) - } - if err := data.Set(FieldServiceAccountDescription, serviceAccount.ServiceAccount.Description); err != nil { - return diag.Errorf("setting service account description: %v", err) - } + // client := meta.(*ProviderConfig).api + // resp, err := client.ServiceAccountsAPIGetServiceAccountWithResponse(ctx, data.Id()) + // if err := sdk.CheckOKResponse(resp, err); err != nil { + // return diag.Errorf("getting service account: %v", err) + // } + // + // serviceAccount := resp.JSON200 + // + // if err := data.Set(FieldServiceAccountName, serviceAccount.ServiceAccount.Name); err != nil { + // return diag.Errorf("setting service account name: %v", err) + // } + // if err := data.Set(FieldServiceAccountDescription, serviceAccount.ServiceAccount.Description); err != nil { + // return diag.Errorf("setting service account description: %v", err) + // } return nil } @@ -158,6 +159,17 @@ func resourceServiceAccountKey() *schema.Resource { } func resourceServiceAccountKeyRead(ctx context.Context, data *schema.ResourceData, meta interface{}) diag.Diagnostics { + // client := meta.(*ProviderConfig).api + // serviceAccountID := data.Get(FieldServiceAccountID).(string) + // // organizationID := data.Get(FieldServiceAccountKeyOrganizationID) + // + // resp, err := client.ServiceAccountsAPIGetServiceAccountWithResponse(ctx,serviceAccountID) + // + // if err := sdk.CheckGetResponse(resp, err); err != nil{ + // return diag.Errorf("getting service account: %v", err) + // } + // + // resp.JSON200.ServiceAccount return nil } diff --git a/castai/sdk/api.gen.go b/castai/sdk/api.gen.go index 7a168c1f..3d501f80 100644 --- a/castai/sdk/api.gen.go +++ b/castai/sdk/api.gen.go @@ -862,6 +862,12 @@ type CastaiInventoryV1beta1GetCommitmentResponse struct { Commitment *CastaiInventoryV1beta1Commitment `json:"commitment,omitempty"` } +// CastaiInventoryV1beta1GetCommitmentUsageHistoryResponse defines model for castai.inventory.v1beta1.GetCommitmentUsageHistoryResponse. +type CastaiInventoryV1beta1GetCommitmentUsageHistoryResponse struct { + Items *[]CastaiInventoryV1beta1UsageAtTime `json:"items,omitempty"` + Summary *CastaiInventoryV1beta1Usage `json:"summary,omitempty"` +} + // CastaiInventoryV1beta1GetCommitmentsAssignmentsResponse defines model for castai.inventory.v1beta1.GetCommitmentsAssignmentsResponse. type CastaiInventoryV1beta1GetCommitmentsAssignmentsResponse struct { CommitmentsAssignments *[]CastaiInventoryV1beta1CommitmentAssignment `json:"commitmentsAssignments,omitempty"` @@ -1221,6 +1227,22 @@ type CastaiInventoryV1beta1UpdateCommitmentResponse struct { Commitments *CastaiInventoryV1beta1Commitment `json:"commitments,omitempty"` } +// CastaiInventoryV1beta1Usage defines model for castai.inventory.v1beta1.Usage. +type CastaiInventoryV1beta1Usage struct { + CpuCommitted *float64 `json:"cpuCommitted,omitempty"` + CpuUsed *float64 `json:"cpuUsed,omitempty"` + CpuUsedPercent *float64 `json:"cpuUsedPercent,omitempty"` + MemoryCommittedMib *float64 `json:"memoryCommittedMib,omitempty"` + MemoryUsedMib *float64 `json:"memoryUsedMib,omitempty"` + MemoryUsedPercent *float64 `json:"memoryUsedPercent,omitempty"` +} + +// CastaiInventoryV1beta1UsageAtTime defines model for castai.inventory.v1beta1.UsageAtTime. +type CastaiInventoryV1beta1UsageAtTime struct { + Usage *CastaiInventoryV1beta1Usage `json:"usage,omitempty"` + UsageTime *time.Time `json:"usageTime,omitempty"` +} + // CastaiInventoryV1beta1UsageDistribution defines model for castai.inventory.v1beta1.UsageDistribution. type CastaiInventoryV1beta1UsageDistribution struct { Cpu *float64 `json:"cpu,omitempty"` @@ -1319,6 +1341,7 @@ type CastaiServiceaccountsV1beta1CreateServiceAccountResponse struct { Author *CastaiServiceaccountsV1beta1CreateServiceAccountResponseAuthor `json:"author,omitempty"` CreatedAt *time.Time `json:"createdAt,omitempty"` Description *string `json:"description,omitempty"` + Email *string `json:"email,omitempty"` Id *string `json:"id,omitempty"` Name *string `json:"name,omitempty"` } @@ -1337,7 +1360,7 @@ type CastaiServiceaccountsV1beta1DeleteServiceAccountResponse = map[string]inter // GetServiceAccountResponse is the response for getting a service account. type CastaiServiceaccountsV1beta1GetServiceAccountResponse struct { - // ServiceAccount represents a service account. + // ServiceAccounts is the readable version of the service accounts. ServiceAccount CastaiServiceaccountsV1beta1ServiceAccount `json:"serviceAccount"` } @@ -1347,16 +1370,16 @@ type CastaiServiceaccountsV1beta1ListServiceAccountsResponse struct { NextPage CastaiPaginationV1beta1Page `json:"nextPage"` // ServiceAccounts is the list of service accounts. - ServiceAccounts *[]CastaiServiceaccountsV1beta1ListServiceAccountsResponseServiceAccount `json:"serviceAccounts,omitempty"` + ServiceAccounts *[]CastaiServiceaccountsV1beta1ServiceAccount `json:"serviceAccounts,omitempty"` // TotalCount is the total number of service accounts in the dataset. TotalCount *string `json:"totalCount,omitempty"` } // ServiceAccounts is the readable version of the service accounts. -type CastaiServiceaccountsV1beta1ListServiceAccountsResponseServiceAccount struct { +type CastaiServiceaccountsV1beta1ServiceAccount struct { // Author is the author of the service account. - Author *CastaiServiceaccountsV1beta1ListServiceAccountsResponseServiceAccountAuthor `json:"author,omitempty"` + Author *CastaiServiceaccountsV1beta1ServiceAccountAuthor `json:"author,omitempty"` // CreatedAt is the timestamp when the service account was created. CreatedAt *time.Time `json:"createdAt,omitempty"` @@ -1364,18 +1387,21 @@ type CastaiServiceaccountsV1beta1ListServiceAccountsResponseServiceAccount struc // Description is the description of the role binding. Description *string `json:"description,omitempty"` + // Email is the email of the service account. + Email *string `json:"email,omitempty"` + // ID is the unique identifier of the service account. Id *string `json:"id,omitempty"` // Keys is the list of keys associated with the service account. - Keys *[]CastaiServiceaccountsV1beta1ListServiceAccountsResponseServiceAccountKey `json:"keys,omitempty"` + Keys *[]CastaiServiceaccountsV1beta1ServiceAccountKey `json:"keys,omitempty"` // Name is the name of the service account. Name *string `json:"name,omitempty"` } // Author is the author of the service account. -type CastaiServiceaccountsV1beta1ListServiceAccountsResponseServiceAccountAuthor struct { +type CastaiServiceaccountsV1beta1ServiceAccountAuthor struct { // Email is the email of the author. Email *string `json:"email,omitempty"` @@ -1387,7 +1413,7 @@ type CastaiServiceaccountsV1beta1ListServiceAccountsResponseServiceAccountAuthor } // Key is the key for the service account. -type CastaiServiceaccountsV1beta1ListServiceAccountsResponseServiceAccountKey struct { +type CastaiServiceaccountsV1beta1ServiceAccountKey struct { // Active determines if the key is active. Active *bool `json:"active,omitempty"` @@ -1407,24 +1433,6 @@ type CastaiServiceaccountsV1beta1ListServiceAccountsResponseServiceAccountKey st Prefix *string `json:"prefix,omitempty"` } -// ServiceAccount represents a service account. -type CastaiServiceaccountsV1beta1ServiceAccount struct { - // CreatedAt is the timestamp when the service account was created. - CreatedAt *time.Time `json:"createdAt,omitempty"` - - // CreatedBy is the user who created the service account. - CreatedBy *string `json:"createdBy,omitempty"` - - // Description is the description of the service account. - Description *string `json:"description,omitempty"` - - // ID is the unique identifier of the service account. - Id *string `json:"id,omitempty"` - - // Name is the name of the service account. - Name string `json:"name"` -} - // UpdateServiceAccountKeyResponse is the response for updating a service account key. type CastaiServiceaccountsV1beta1UpdateServiceAccountKeyResponse struct { // Active determines if the key is active. @@ -3914,6 +3922,7 @@ type WorkloadoptimizationV1RecommendedPodCountChangedEvent struct { type WorkloadoptimizationV1RecommendedRequestsChangedEvent struct { ApplyType WorkloadoptimizationV1ApplyType `json:"applyType"` Current WorkloadoptimizationV1RecommendedRequestsChangedEventChange `json:"current"` + DebugData *map[string]interface{} `json:"debugData,omitempty"` Previous WorkloadoptimizationV1RecommendedRequestsChangedEventChange `json:"previous"` } @@ -4309,6 +4318,16 @@ type WorkloadoptimizationV1WorkloadScalingPolicy struct { UpdatedAt time.Time `json:"updatedAt"` } +// CommitmentsAPIGetCommitmentUsageHistoryParams defines parameters for CommitmentsAPIGetCommitmentUsageHistory. +type CommitmentsAPIGetCommitmentUsageHistoryParams struct { + StartTime time.Time `form:"startTime" json:"startTime"` + EndTime time.Time `form:"endTime" json:"endTime"` + AggregationInterval CommitmentsAPIGetCommitmentUsageHistoryParamsAggregationInterval `form:"aggregationInterval" json:"aggregationInterval"` +} + +// CommitmentsAPIGetCommitmentUsageHistoryParamsAggregationInterval defines parameters for CommitmentsAPIGetCommitmentUsageHistory. +type CommitmentsAPIGetCommitmentUsageHistoryParamsAggregationInterval string + // AuthTokenAPIListAuthTokensParams defines parameters for AuthTokenAPIListAuthTokens. type AuthTokenAPIListAuthTokensParams struct { // User id to filter by, if this is set we will only return tokens that have this user id. diff --git a/castai/sdk/client.gen.go b/castai/sdk/client.gen.go index 6b20aae4..b4877d63 100644 --- a/castai/sdk/client.gen.go +++ b/castai/sdk/client.gen.go @@ -90,6 +90,9 @@ func WithRequestEditorFn(fn RequestEditorFn) ClientOption { // The interface specification for the client above. type ClientInterface interface { + // CommitmentsAPIGetCommitmentUsageHistory request + CommitmentsAPIGetCommitmentUsageHistory(ctx context.Context, organizationId string, commitmentId string, params *CommitmentsAPIGetCommitmentUsageHistoryParams, reqEditors ...RequestEditorFn) (*http.Response, error) + // AuthTokenAPIListAuthTokens request AuthTokenAPIListAuthTokens(ctx context.Context, params *AuthTokenAPIListAuthTokensParams, reqEditors ...RequestEditorFn) (*http.Response, error) @@ -388,6 +391,9 @@ type ClientInterface interface { // ServiceAccountsAPIDeleteServiceAccount request ServiceAccountsAPIDeleteServiceAccount(ctx context.Context, organizationId string, serviceAccountId string, reqEditors ...RequestEditorFn) (*http.Response, error) + // ServiceAccountsAPIGetServiceAccount request + ServiceAccountsAPIGetServiceAccount(ctx context.Context, organizationId string, serviceAccountId string, reqEditors ...RequestEditorFn) (*http.Response, error) + // ServiceAccountsAPICreateServiceAccountKey request with any body ServiceAccountsAPICreateServiceAccountKeyWithBody(ctx context.Context, organizationId string, serviceAccountId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) @@ -496,9 +502,6 @@ type ClientInterface interface { // ExternalClusterAPIGetCredentialsScriptTemplate request ExternalClusterAPIGetCredentialsScriptTemplate(ctx context.Context, provider string, params *ExternalClusterAPIGetCredentialsScriptTemplateParams, reqEditors ...RequestEditorFn) (*http.Response, error) - // ServiceAccountsAPIGetServiceAccount request - ServiceAccountsAPIGetServiceAccount(ctx context.Context, id string, reqEditors ...RequestEditorFn) (*http.Response, error) - // SSOAPIListSSOConnections request SSOAPIListSSOConnections(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) @@ -580,6 +583,18 @@ type ClientInterface interface { WorkloadOptimizationAPIUpdateWorkloadV2(ctx context.Context, clusterId string, workloadId string, body WorkloadOptimizationAPIUpdateWorkloadV2JSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) } +func (c *Client) CommitmentsAPIGetCommitmentUsageHistory(ctx context.Context, organizationId string, commitmentId string, params *CommitmentsAPIGetCommitmentUsageHistoryParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewCommitmentsAPIGetCommitmentUsageHistoryRequest(c.Server, organizationId, commitmentId, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + func (c *Client) AuthTokenAPIListAuthTokens(ctx context.Context, params *AuthTokenAPIListAuthTokensParams, reqEditors ...RequestEditorFn) (*http.Response, error) { req, err := NewAuthTokenAPIListAuthTokensRequest(c.Server, params) if err != nil { @@ -1888,6 +1903,18 @@ func (c *Client) ServiceAccountsAPIDeleteServiceAccount(ctx context.Context, org return c.Client.Do(req) } +func (c *Client) ServiceAccountsAPIGetServiceAccount(ctx context.Context, organizationId string, serviceAccountId string, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewServiceAccountsAPIGetServiceAccountRequest(c.Server, organizationId, serviceAccountId) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + func (c *Client) ServiceAccountsAPICreateServiceAccountKeyWithBody(ctx context.Context, organizationId string, serviceAccountId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { req, err := NewServiceAccountsAPICreateServiceAccountKeyRequestWithBody(c.Server, organizationId, serviceAccountId, contentType, body) if err != nil { @@ -2356,18 +2383,6 @@ func (c *Client) ExternalClusterAPIGetCredentialsScriptTemplate(ctx context.Cont return c.Client.Do(req) } -func (c *Client) ServiceAccountsAPIGetServiceAccount(ctx context.Context, id string, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewServiceAccountsAPIGetServiceAccountRequest(c.Server, id) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - func (c *Client) SSOAPIListSSOConnections(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) { req, err := NewSSOAPIListSSOConnectionsRequest(c.Server) if err != nil { @@ -2716,6 +2731,87 @@ func (c *Client) WorkloadOptimizationAPIUpdateWorkloadV2(ctx context.Context, cl return c.Client.Do(req) } +// NewCommitmentsAPIGetCommitmentUsageHistoryRequest generates requests for CommitmentsAPIGetCommitmentUsageHistory +func NewCommitmentsAPIGetCommitmentUsageHistoryRequest(server string, organizationId string, commitmentId string, params *CommitmentsAPIGetCommitmentUsageHistoryParams) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithLocation("simple", false, "organizationId", runtime.ParamLocationPath, organizationId) + if err != nil { + return nil, err + } + + var pathParam1 string + + pathParam1, err = runtime.StyleParamWithLocation("simple", false, "commitmentId", runtime.ParamLocationPath, commitmentId) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/savings/v1beta/organizations/%s/commitments/%s:getUsageHistory", pathParam0, pathParam1) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + queryValues := queryURL.Query() + + if queryFrag, err := runtime.StyleParamWithLocation("form", true, "startTime", runtime.ParamLocationQuery, params.StartTime); err != nil { + return nil, err + } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + return nil, err + } else { + for k, v := range parsed { + for _, v2 := range v { + queryValues.Add(k, v2) + } + } + } + + if queryFrag, err := runtime.StyleParamWithLocation("form", true, "endTime", runtime.ParamLocationQuery, params.EndTime); err != nil { + return nil, err + } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + return nil, err + } else { + for k, v := range parsed { + for _, v2 := range v { + queryValues.Add(k, v2) + } + } + } + + if queryFrag, err := runtime.StyleParamWithLocation("form", true, "aggregationInterval", runtime.ParamLocationQuery, params.AggregationInterval); err != nil { + return nil, err + } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + return nil, err + } else { + for k, v := range parsed { + for _, v2 := range v { + queryValues.Add(k, v2) + } + } + } + + queryURL.RawQuery = queryValues.Encode() + + req, err := http.NewRequest("GET", queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + // NewAuthTokenAPIListAuthTokensRequest generates requests for AuthTokenAPIListAuthTokens func NewAuthTokenAPIListAuthTokensRequest(server string, params *AuthTokenAPIListAuthTokensParams) (*http.Request, error) { var err error @@ -6429,6 +6525,47 @@ func NewServiceAccountsAPIDeleteServiceAccountRequest(server string, organizatio return req, nil } +// NewServiceAccountsAPIGetServiceAccountRequest generates requests for ServiceAccountsAPIGetServiceAccount +func NewServiceAccountsAPIGetServiceAccountRequest(server string, organizationId string, serviceAccountId string) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithLocation("simple", false, "organizationId", runtime.ParamLocationPath, organizationId) + if err != nil { + return nil, err + } + + var pathParam1 string + + pathParam1, err = runtime.StyleParamWithLocation("simple", false, "serviceAccountId", runtime.ParamLocationPath, serviceAccountId) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/v1/organizations/%s/service-accounts/%s", pathParam0, pathParam1) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("GET", queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + // NewServiceAccountsAPICreateServiceAccountKeyRequest calls the generic ServiceAccountsAPICreateServiceAccountKey builder with application/json body func NewServiceAccountsAPICreateServiceAccountKeyRequest(server string, organizationId string, serviceAccountId string, body ServiceAccountsAPICreateServiceAccountKeyJSONRequestBody) (*http.Request, error) { var bodyReader io.Reader @@ -7833,40 +7970,6 @@ func NewExternalClusterAPIGetCredentialsScriptTemplateRequest(server string, pro return req, nil } -// NewServiceAccountsAPIGetServiceAccountRequest generates requests for ServiceAccountsAPIGetServiceAccount -func NewServiceAccountsAPIGetServiceAccountRequest(server string, id string) (*http.Request, error) { - var err error - - var pathParam0 string - - pathParam0, err = runtime.StyleParamWithLocation("simple", false, "id", runtime.ParamLocationPath, id) - if err != nil { - return nil, err - } - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/v1/service-accounts/%s", pathParam0) - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("GET", queryURL.String(), nil) - if err != nil { - return nil, err - } - - return req, nil -} - // NewSSOAPIListSSOConnectionsRequest generates requests for SSOAPIListSSOConnections func NewSSOAPIListSSOConnectionsRequest(server string) (*http.Request, error) { var err error @@ -8976,6 +9079,9 @@ func WithBaseURL(baseURL string) ClientOption { // ClientWithResponsesInterface is the interface specification for the client with responses above. type ClientWithResponsesInterface interface { + // CommitmentsAPIGetCommitmentUsageHistory request + CommitmentsAPIGetCommitmentUsageHistoryWithResponse(ctx context.Context, organizationId string, commitmentId string, params *CommitmentsAPIGetCommitmentUsageHistoryParams) (*CommitmentsAPIGetCommitmentUsageHistoryResponse, error) + // AuthTokenAPIListAuthTokens request AuthTokenAPIListAuthTokensWithResponse(ctx context.Context, params *AuthTokenAPIListAuthTokensParams) (*AuthTokenAPIListAuthTokensResponse, error) @@ -9274,6 +9380,9 @@ type ClientWithResponsesInterface interface { // ServiceAccountsAPIDeleteServiceAccount request ServiceAccountsAPIDeleteServiceAccountWithResponse(ctx context.Context, organizationId string, serviceAccountId string) (*ServiceAccountsAPIDeleteServiceAccountResponse, error) + // ServiceAccountsAPIGetServiceAccount request + ServiceAccountsAPIGetServiceAccountWithResponse(ctx context.Context, organizationId string, serviceAccountId string) (*ServiceAccountsAPIGetServiceAccountResponse, error) + // ServiceAccountsAPICreateServiceAccountKey request with any body ServiceAccountsAPICreateServiceAccountKeyWithBodyWithResponse(ctx context.Context, organizationId string, serviceAccountId string, contentType string, body io.Reader) (*ServiceAccountsAPICreateServiceAccountKeyResponse, error) @@ -9382,9 +9491,6 @@ type ClientWithResponsesInterface interface { // ExternalClusterAPIGetCredentialsScriptTemplate request ExternalClusterAPIGetCredentialsScriptTemplateWithResponse(ctx context.Context, provider string, params *ExternalClusterAPIGetCredentialsScriptTemplateParams) (*ExternalClusterAPIGetCredentialsScriptTemplateResponse, error) - // ServiceAccountsAPIGetServiceAccount request - ServiceAccountsAPIGetServiceAccountWithResponse(ctx context.Context, id string) (*ServiceAccountsAPIGetServiceAccountResponse, error) - // SSOAPIListSSOConnections request SSOAPIListSSOConnectionsWithResponse(ctx context.Context) (*SSOAPIListSSOConnectionsResponse, error) @@ -9475,6 +9581,36 @@ type Response interface { // TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 +type CommitmentsAPIGetCommitmentUsageHistoryResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *CastaiInventoryV1beta1GetCommitmentUsageHistoryResponse +} + +// Status returns HTTPResponse.Status +func (r CommitmentsAPIGetCommitmentUsageHistoryResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r CommitmentsAPIGetCommitmentUsageHistoryResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 +// Body returns body of byte array +func (r CommitmentsAPIGetCommitmentUsageHistoryResponse) GetBody() []byte { + return r.Body +} + +// TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 + type AuthTokenAPIListAuthTokensResponse struct { Body []byte HTTPResponse *http.Response @@ -11875,6 +12011,36 @@ func (r ServiceAccountsAPIDeleteServiceAccountResponse) GetBody() []byte { // TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 +type ServiceAccountsAPIGetServiceAccountResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *CastaiServiceaccountsV1beta1GetServiceAccountResponse +} + +// Status returns HTTPResponse.Status +func (r ServiceAccountsAPIGetServiceAccountResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r ServiceAccountsAPIGetServiceAccountResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 +// Body returns body of byte array +func (r ServiceAccountsAPIGetServiceAccountResponse) GetBody() []byte { + return r.Body +} + +// TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 + type ServiceAccountsAPICreateServiceAccountKeyResponse struct { Body []byte HTTPResponse *http.Response @@ -12773,36 +12939,6 @@ func (r ExternalClusterAPIGetCredentialsScriptTemplateResponse) GetBody() []byte // TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 -type ServiceAccountsAPIGetServiceAccountResponse struct { - Body []byte - HTTPResponse *http.Response - JSON200 *CastaiServiceaccountsV1beta1GetServiceAccountResponse -} - -// Status returns HTTPResponse.Status -func (r ServiceAccountsAPIGetServiceAccountResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r ServiceAccountsAPIGetServiceAccountResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -// TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 -// Body returns body of byte array -func (r ServiceAccountsAPIGetServiceAccountResponse) GetBody() []byte { - return r.Body -} - -// TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 - type SSOAPIListSSOConnectionsResponse struct { Body []byte HTTPResponse *http.Response @@ -13462,6 +13598,15 @@ func (r WorkloadOptimizationAPIUpdateWorkloadV2Response) GetBody() []byte { // TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 +// CommitmentsAPIGetCommitmentUsageHistoryWithResponse request returning *CommitmentsAPIGetCommitmentUsageHistoryResponse +func (c *ClientWithResponses) CommitmentsAPIGetCommitmentUsageHistoryWithResponse(ctx context.Context, organizationId string, commitmentId string, params *CommitmentsAPIGetCommitmentUsageHistoryParams) (*CommitmentsAPIGetCommitmentUsageHistoryResponse, error) { + rsp, err := c.CommitmentsAPIGetCommitmentUsageHistory(ctx, organizationId, commitmentId, params) + if err != nil { + return nil, err + } + return ParseCommitmentsAPIGetCommitmentUsageHistoryResponse(rsp) +} + // AuthTokenAPIListAuthTokensWithResponse request returning *AuthTokenAPIListAuthTokensResponse func (c *ClientWithResponses) AuthTokenAPIListAuthTokensWithResponse(ctx context.Context, params *AuthTokenAPIListAuthTokensParams) (*AuthTokenAPIListAuthTokensResponse, error) { rsp, err := c.AuthTokenAPIListAuthTokens(ctx, params) @@ -14414,6 +14559,15 @@ func (c *ClientWithResponses) ServiceAccountsAPIDeleteServiceAccountWithResponse return ParseServiceAccountsAPIDeleteServiceAccountResponse(rsp) } +// ServiceAccountsAPIGetServiceAccountWithResponse request returning *ServiceAccountsAPIGetServiceAccountResponse +func (c *ClientWithResponses) ServiceAccountsAPIGetServiceAccountWithResponse(ctx context.Context, organizationId string, serviceAccountId string) (*ServiceAccountsAPIGetServiceAccountResponse, error) { + rsp, err := c.ServiceAccountsAPIGetServiceAccount(ctx, organizationId, serviceAccountId) + if err != nil { + return nil, err + } + return ParseServiceAccountsAPIGetServiceAccountResponse(rsp) +} + // ServiceAccountsAPICreateServiceAccountKeyWithBodyWithResponse request with arbitrary body returning *ServiceAccountsAPICreateServiceAccountKeyResponse func (c *ClientWithResponses) ServiceAccountsAPICreateServiceAccountKeyWithBodyWithResponse(ctx context.Context, organizationId string, serviceAccountId string, contentType string, body io.Reader) (*ServiceAccountsAPICreateServiceAccountKeyResponse, error) { rsp, err := c.ServiceAccountsAPICreateServiceAccountKeyWithBody(ctx, organizationId, serviceAccountId, contentType, body) @@ -14756,15 +14910,6 @@ func (c *ClientWithResponses) ExternalClusterAPIGetCredentialsScriptTemplateWith return ParseExternalClusterAPIGetCredentialsScriptTemplateResponse(rsp) } -// ServiceAccountsAPIGetServiceAccountWithResponse request returning *ServiceAccountsAPIGetServiceAccountResponse -func (c *ClientWithResponses) ServiceAccountsAPIGetServiceAccountWithResponse(ctx context.Context, id string) (*ServiceAccountsAPIGetServiceAccountResponse, error) { - rsp, err := c.ServiceAccountsAPIGetServiceAccount(ctx, id) - if err != nil { - return nil, err - } - return ParseServiceAccountsAPIGetServiceAccountResponse(rsp) -} - // SSOAPIListSSOConnectionsWithResponse request returning *SSOAPIListSSOConnectionsResponse func (c *ClientWithResponses) SSOAPIListSSOConnectionsWithResponse(ctx context.Context) (*SSOAPIListSSOConnectionsResponse, error) { rsp, err := c.SSOAPIListSSOConnections(ctx) @@ -15019,6 +15164,32 @@ func (c *ClientWithResponses) WorkloadOptimizationAPIUpdateWorkloadV2WithRespons return ParseWorkloadOptimizationAPIUpdateWorkloadV2Response(rsp) } +// ParseCommitmentsAPIGetCommitmentUsageHistoryResponse parses an HTTP response from a CommitmentsAPIGetCommitmentUsageHistoryWithResponse call +func ParseCommitmentsAPIGetCommitmentUsageHistoryResponse(rsp *http.Response) (*CommitmentsAPIGetCommitmentUsageHistoryResponse, error) { + bodyBytes, err := ioutil.ReadAll(rsp.Body) + defer rsp.Body.Close() + if err != nil { + return nil, err + } + + response := &CommitmentsAPIGetCommitmentUsageHistoryResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest CastaiInventoryV1beta1GetCommitmentUsageHistoryResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + } + + return response, nil +} + // ParseAuthTokenAPIListAuthTokensResponse parses an HTTP response from a AuthTokenAPIListAuthTokensWithResponse call func ParseAuthTokenAPIListAuthTokensResponse(rsp *http.Response) (*AuthTokenAPIListAuthTokensResponse, error) { bodyBytes, err := ioutil.ReadAll(rsp.Body) @@ -17096,6 +17267,32 @@ func ParseServiceAccountsAPIDeleteServiceAccountResponse(rsp *http.Response) (*S return response, nil } +// ParseServiceAccountsAPIGetServiceAccountResponse parses an HTTP response from a ServiceAccountsAPIGetServiceAccountWithResponse call +func ParseServiceAccountsAPIGetServiceAccountResponse(rsp *http.Response) (*ServiceAccountsAPIGetServiceAccountResponse, error) { + bodyBytes, err := ioutil.ReadAll(rsp.Body) + defer rsp.Body.Close() + if err != nil { + return nil, err + } + + response := &ServiceAccountsAPIGetServiceAccountResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest CastaiServiceaccountsV1beta1GetServiceAccountResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + } + + return response, nil +} + // ParseServiceAccountsAPICreateServiceAccountKeyResponse parses an HTTP response from a ServiceAccountsAPICreateServiceAccountKeyWithResponse call func ParseServiceAccountsAPICreateServiceAccountKeyResponse(rsp *http.Response) (*ServiceAccountsAPICreateServiceAccountKeyResponse, error) { bodyBytes, err := ioutil.ReadAll(rsp.Body) @@ -17853,32 +18050,6 @@ func ParseExternalClusterAPIGetCredentialsScriptTemplateResponse(rsp *http.Respo return response, nil } -// ParseServiceAccountsAPIGetServiceAccountResponse parses an HTTP response from a ServiceAccountsAPIGetServiceAccountWithResponse call -func ParseServiceAccountsAPIGetServiceAccountResponse(rsp *http.Response) (*ServiceAccountsAPIGetServiceAccountResponse, error) { - bodyBytes, err := ioutil.ReadAll(rsp.Body) - defer rsp.Body.Close() - if err != nil { - return nil, err - } - - response := &ServiceAccountsAPIGetServiceAccountResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest CastaiServiceaccountsV1beta1GetServiceAccountResponse - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON200 = &dest - - } - - return response, nil -} - // ParseSSOAPIListSSOConnectionsResponse parses an HTTP response from a SSOAPIListSSOConnectionsWithResponse call func ParseSSOAPIListSSOConnectionsResponse(rsp *http.Response) (*SSOAPIListSSOConnectionsResponse, error) { bodyBytes, err := ioutil.ReadAll(rsp.Body) diff --git a/castai/sdk/mock/client.go b/castai/sdk/mock/client.go index 75bff2c0..d2f0ee0c 100644 --- a/castai/sdk/mock/client.go +++ b/castai/sdk/mock/client.go @@ -315,6 +315,26 @@ func (mr *MockClientInterfaceMockRecorder) CommitmentsAPIGetCommitmentAssignment return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CommitmentsAPIGetCommitmentAssignments", reflect.TypeOf((*MockClientInterface)(nil).CommitmentsAPIGetCommitmentAssignments), varargs...) } +// CommitmentsAPIGetCommitmentUsageHistory mocks base method. +func (m *MockClientInterface) CommitmentsAPIGetCommitmentUsageHistory(ctx context.Context, organizationId, commitmentId string, params *sdk.CommitmentsAPIGetCommitmentUsageHistoryParams, reqEditors ...sdk.RequestEditorFn) (*http.Response, error) { + m.ctrl.T.Helper() + varargs := []interface{}{ctx, organizationId, commitmentId, params} + for _, a := range reqEditors { + varargs = append(varargs, a) + } + ret := m.ctrl.Call(m, "CommitmentsAPIGetCommitmentUsageHistory", varargs...) + ret0, _ := ret[0].(*http.Response) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// CommitmentsAPIGetCommitmentUsageHistory indicates an expected call of CommitmentsAPIGetCommitmentUsageHistory. +func (mr *MockClientInterfaceMockRecorder) CommitmentsAPIGetCommitmentUsageHistory(ctx, organizationId, commitmentId, params interface{}, reqEditors ...interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + varargs := append([]interface{}{ctx, organizationId, commitmentId, params}, reqEditors...) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CommitmentsAPIGetCommitmentUsageHistory", reflect.TypeOf((*MockClientInterface)(nil).CommitmentsAPIGetCommitmentUsageHistory), varargs...) +} + // CommitmentsAPIGetCommitments mocks base method. func (m *MockClientInterface) CommitmentsAPIGetCommitments(ctx context.Context, params *sdk.CommitmentsAPIGetCommitmentsParams, reqEditors ...sdk.RequestEditorFn) (*http.Response, error) { m.ctrl.T.Helper() @@ -2696,9 +2716,9 @@ func (mr *MockClientInterfaceMockRecorder) ServiceAccountsAPIDeleteServiceAccoun } // ServiceAccountsAPIGetServiceAccount mocks base method. -func (m *MockClientInterface) ServiceAccountsAPIGetServiceAccount(ctx context.Context, id string, reqEditors ...sdk.RequestEditorFn) (*http.Response, error) { +func (m *MockClientInterface) ServiceAccountsAPIGetServiceAccount(ctx context.Context, organizationId, serviceAccountId string, reqEditors ...sdk.RequestEditorFn) (*http.Response, error) { m.ctrl.T.Helper() - varargs := []interface{}{ctx, id} + varargs := []interface{}{ctx, organizationId, serviceAccountId} for _, a := range reqEditors { varargs = append(varargs, a) } @@ -2709,9 +2729,9 @@ func (m *MockClientInterface) ServiceAccountsAPIGetServiceAccount(ctx context.Co } // ServiceAccountsAPIGetServiceAccount indicates an expected call of ServiceAccountsAPIGetServiceAccount. -func (mr *MockClientInterfaceMockRecorder) ServiceAccountsAPIGetServiceAccount(ctx, id interface{}, reqEditors ...interface{}) *gomock.Call { +func (mr *MockClientInterfaceMockRecorder) ServiceAccountsAPIGetServiceAccount(ctx, organizationId, serviceAccountId interface{}, reqEditors ...interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - varargs := append([]interface{}{ctx, id}, reqEditors...) + varargs := append([]interface{}{ctx, organizationId, serviceAccountId}, reqEditors...) return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ServiceAccountsAPIGetServiceAccount", reflect.TypeOf((*MockClientInterface)(nil).ServiceAccountsAPIGetServiceAccount), varargs...) } @@ -3823,6 +3843,21 @@ func (mr *MockClientWithResponsesInterfaceMockRecorder) CommitmentsAPIGetCommitm return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CommitmentsAPIGetCommitmentAssignmentsWithResponse", reflect.TypeOf((*MockClientWithResponsesInterface)(nil).CommitmentsAPIGetCommitmentAssignmentsWithResponse), ctx, commitmentId) } +// CommitmentsAPIGetCommitmentUsageHistoryWithResponse mocks base method. +func (m *MockClientWithResponsesInterface) CommitmentsAPIGetCommitmentUsageHistoryWithResponse(ctx context.Context, organizationId, commitmentId string, params *sdk.CommitmentsAPIGetCommitmentUsageHistoryParams) (*sdk.CommitmentsAPIGetCommitmentUsageHistoryResponse, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "CommitmentsAPIGetCommitmentUsageHistoryWithResponse", ctx, organizationId, commitmentId, params) + ret0, _ := ret[0].(*sdk.CommitmentsAPIGetCommitmentUsageHistoryResponse) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// CommitmentsAPIGetCommitmentUsageHistoryWithResponse indicates an expected call of CommitmentsAPIGetCommitmentUsageHistoryWithResponse. +func (mr *MockClientWithResponsesInterfaceMockRecorder) CommitmentsAPIGetCommitmentUsageHistoryWithResponse(ctx, organizationId, commitmentId, params interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CommitmentsAPIGetCommitmentUsageHistoryWithResponse", reflect.TypeOf((*MockClientWithResponsesInterface)(nil).CommitmentsAPIGetCommitmentUsageHistoryWithResponse), ctx, organizationId, commitmentId, params) +} + // CommitmentsAPIGetCommitmentWithResponse mocks base method. func (m *MockClientWithResponsesInterface) CommitmentsAPIGetCommitmentWithResponse(ctx context.Context, commitmentId string, params *sdk.CommitmentsAPIGetCommitmentParams) (*sdk.CommitmentsAPIGetCommitmentResponse, error) { m.ctrl.T.Helper() @@ -5624,18 +5659,18 @@ func (mr *MockClientWithResponsesInterfaceMockRecorder) ServiceAccountsAPIDelete } // ServiceAccountsAPIGetServiceAccountWithResponse mocks base method. -func (m *MockClientWithResponsesInterface) ServiceAccountsAPIGetServiceAccountWithResponse(ctx context.Context, id string) (*sdk.ServiceAccountsAPIGetServiceAccountResponse, error) { +func (m *MockClientWithResponsesInterface) ServiceAccountsAPIGetServiceAccountWithResponse(ctx context.Context, organizationId, serviceAccountId string) (*sdk.ServiceAccountsAPIGetServiceAccountResponse, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ServiceAccountsAPIGetServiceAccountWithResponse", ctx, id) + ret := m.ctrl.Call(m, "ServiceAccountsAPIGetServiceAccountWithResponse", ctx, organizationId, serviceAccountId) ret0, _ := ret[0].(*sdk.ServiceAccountsAPIGetServiceAccountResponse) ret1, _ := ret[1].(error) return ret0, ret1 } // ServiceAccountsAPIGetServiceAccountWithResponse indicates an expected call of ServiceAccountsAPIGetServiceAccountWithResponse. -func (mr *MockClientWithResponsesInterfaceMockRecorder) ServiceAccountsAPIGetServiceAccountWithResponse(ctx, id interface{}) *gomock.Call { +func (mr *MockClientWithResponsesInterfaceMockRecorder) ServiceAccountsAPIGetServiceAccountWithResponse(ctx, organizationId, serviceAccountId interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ServiceAccountsAPIGetServiceAccountWithResponse", reflect.TypeOf((*MockClientWithResponsesInterface)(nil).ServiceAccountsAPIGetServiceAccountWithResponse), ctx, id) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ServiceAccountsAPIGetServiceAccountWithResponse", reflect.TypeOf((*MockClientWithResponsesInterface)(nil).ServiceAccountsAPIGetServiceAccountWithResponse), ctx, organizationId, serviceAccountId) } // ServiceAccountsAPIListServiceAccountsWithResponse mocks base method. diff --git a/docs/resources/service_account.md b/docs/resources/service_account.md new file mode 100644 index 00000000..3eaf6bdc --- /dev/null +++ b/docs/resources/service_account.md @@ -0,0 +1,41 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "castai_service_account Resource - terraform-provider-castai" +subcategory: "" +description: |- + Service Account resource allows managing CAST AI service accounts. +--- + +# castai_service_account (Resource) + +Service Account resource allows managing CAST AI service accounts. + + + + +## Schema + +### Required + +- `name` (String) Name of the service account. +- `organization_id` (String) ID of the organization. + +### Optional + +- `description` (String) Description of the service account. +- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) + +### Read-Only + +- `id` (String) The ID of this resource. + + +### Nested Schema for `timeouts` + +Optional: + +- `create` (String) +- `delete` (String) +- `update` (String) + + From e21cb2da981c38697bd7fda705b197e1cbcedd81 Mon Sep 17 00:00:00 2001 From: radekska Date: Tue, 26 Nov 2024 15:09:17 +0100 Subject: [PATCH 05/24] wip --- castai/resource_service_account.go | 74 ++++++++++++++++++++++-------- castai/sdk/utils_response.go | 4 ++ docs/resources/service_account.md | 12 +++++ examples/localdev/versions.tf | 9 +++- 4 files changed, 79 insertions(+), 20 deletions(-) diff --git a/castai/resource_service_account.go b/castai/resource_service_account.go index e0d15d88..d5299ca1 100644 --- a/castai/resource_service_account.go +++ b/castai/resource_service_account.go @@ -15,6 +15,12 @@ const ( FieldServiceAccountName = "name" FieldServiceAccountID = "service_account_id" FieldServiceAccountDescription = "description" + FieldServiceAccountEmail = "email" + + FieldServiceAccountAuthor = "author" + FieldServiceAccountAuthorID = "id" + FieldServiceAccountAuthorEmail = "email" + FieldServiceAccountAuthorKind = "kind" FieldServiceAccountKeyOrganizationID = "organization_id" FieldServiceAccountKeyName = "name" @@ -34,7 +40,7 @@ func resourceServiceAccount() *schema.Resource { Update: schema.DefaultTimeout(3 * time.Minute), Delete: schema.DefaultTimeout(3 * time.Minute), }, - + Schema: map[string]*schema.Schema{ FieldServiceAccountOrganizationID: { Type: schema.TypeString, @@ -52,29 +58,62 @@ func resourceServiceAccount() *schema.Resource { Optional: true, Description: "Description of the service account.", }, + FieldServiceAccountEmail: { + Type: schema.TypeString, + Computed: true, + Description: "Email of the service account.", + }, + FieldServiceAccountAuthor: { + Type: schema.TypeList, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + FieldServiceAccountAuthorID: {Type: schema.TypeString, Computed: true}, + FieldServiceAccountAuthorEmail: {Type: schema.TypeString, Computed: true}, + FieldServiceAccountAuthorKind: {Type: schema.TypeString, Computed: true}, + }, + }, + Computed: true, + Description: "Author of the service account.", + }, }, } } func resourceServiceAccountRead(ctx context.Context, data *schema.ResourceData, meta interface{}) diag.Diagnostics { + client := meta.(*ProviderConfig).api + if data.Id() == "" { return nil } - // client := meta.(*ProviderConfig).api - // resp, err := client.ServiceAccountsAPIGetServiceAccountWithResponse(ctx, data.Id()) - // if err := sdk.CheckOKResponse(resp, err); err != nil { - // return diag.Errorf("getting service account: %v", err) - // } - // - // serviceAccount := resp.JSON200 - // - // if err := data.Set(FieldServiceAccountName, serviceAccount.ServiceAccount.Name); err != nil { - // return diag.Errorf("setting service account name: %v", err) - // } - // if err := data.Set(FieldServiceAccountDescription, serviceAccount.ServiceAccount.Description); err != nil { - // return diag.Errorf("setting service account description: %v", err) - // } + organizationID := data.Get(FieldServiceAccountOrganizationID).(string) + + resp, err := client.ServiceAccountsAPIGetServiceAccountWithResponse(ctx, organizationID, data.Id()) + if err := sdk.CheckOKResponse(resp, err); err != nil { + return diag.Errorf("getting service account: %v", err) + } + + serviceAccount := resp.JSON200 + + if err := data.Set(FieldServiceAccountName, serviceAccount.ServiceAccount.Name); err != nil { + return diag.Errorf("setting service account name: %v", err) + } + + if err := data.Set(FieldServiceAccountEmail, serviceAccount.ServiceAccount.Email); err != nil { + return diag.Errorf("setting service account email: %v", err) + } + + if err := data.Set(FieldServiceAccountDescription, serviceAccount.ServiceAccount.Description); err != nil { + return diag.Errorf("setting service account description: %v", err) + } + + + // TODO: how to set a struct into terraform slice of struct. + if err := data.Set(FieldServiceAccountAuthor, []*sdk.CastaiServiceaccountsV1beta1ServiceAccountAuthor{ + serviceAccount.ServiceAccount.Author, + }); err != nil { + return diag.Errorf("setting service account author: %v", err) + } return nil } @@ -93,13 +132,13 @@ func resourceServiceAccountCreate(ctx context.Context, data *schema.ResourceData }, }) - if err := sdk.CheckOKResponse(resp, err); err != nil { + if err := sdk.CheckResponseCreated(resp, err); err != nil { return diag.Errorf("creating service account: %v", err) } data.SetId(*resp.JSON201.Id) - return nil + return resourceServiceAccountRead(ctx, data, meta) } func resourceServiceAccountDelete(ctx context.Context, data *schema.ResourceData, meta interface{}) diag.Diagnostics { @@ -107,7 +146,6 @@ func resourceServiceAccountDelete(ctx context.Context, data *schema.ResourceData organizationID := data.Get(FieldServiceAccountOrganizationID).(string) serviceAccountID := data.Id() - resp, err := client.ServiceAccountsAPIDeleteServiceAccountWithResponse(ctx, organizationID, serviceAccountID) if err := sdk.CheckResponseNoContent(resp, err); err != nil { return diag.Errorf("deleteting service account: %v", err) diff --git a/castai/sdk/utils_response.go b/castai/sdk/utils_response.go index 16a0058f..bdcaf39c 100644 --- a/castai/sdk/utils_response.go +++ b/castai/sdk/utils_response.go @@ -18,6 +18,10 @@ func CheckResponseNoContent(response Response, err error) error { return checkResponse(response, err, http.StatusNoContent) } +func CheckResponseCreated(response Response, err error) error { + return checkResponse(response, err, http.StatusCreated) +} + func StatusOk(resp Response) error { return checkResponse(resp, nil, http.StatusOK) } diff --git a/docs/resources/service_account.md b/docs/resources/service_account.md index 3eaf6bdc..762b6e9b 100644 --- a/docs/resources/service_account.md +++ b/docs/resources/service_account.md @@ -27,6 +27,8 @@ Service Account resource allows managing CAST AI service accounts. ### Read-Only +- `author` (List of Object) Author of the service account. (see [below for nested schema](#nestedatt--author)) +- `email` (String) Email of the service account. - `id` (String) The ID of this resource. @@ -39,3 +41,13 @@ Optional: - `update` (String) + +### Nested Schema for `author` + +Read-Only: + +- `email` (String) +- `id` (String) +- `kind` (String) + + diff --git a/examples/localdev/versions.tf b/examples/localdev/versions.tf index a9ba01d6..8c654251 100644 --- a/examples/localdev/versions.tf +++ b/examples/localdev/versions.tf @@ -1,9 +1,14 @@ terraform { required_providers { castai = { - source = "castai/castai" - version = "0.0.0-local" + source = "castai/castai" } + } required_version = ">= 0.13" } + +provider "castai" { + api_url = var.castai_api_url + api_token = var.castai_api_token +} From 4199ec1b469ee5aedbdc0007823a60a093b2ae2c Mon Sep 17 00:00:00 2001 From: radekska Date: Sun, 1 Dec 2024 16:09:35 +0100 Subject: [PATCH 06/24] wip --- castai/resource_service_account.go | 48 +++-- castai/sdk/api.gen.go | 84 +++++++- castai/sdk/client.gen.go | 308 +++++++++++++++++++++++++++++ castai/sdk/mock/client.go | 140 +++++++++++++ 4 files changed, 561 insertions(+), 19 deletions(-) diff --git a/castai/resource_service_account.go b/castai/resource_service_account.go index d5299ca1..33c3ef3b 100644 --- a/castai/resource_service_account.go +++ b/castai/resource_service_account.go @@ -2,6 +2,7 @@ package castai import ( "context" + "net/http" "time" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" @@ -31,7 +32,6 @@ func resourceServiceAccount() *schema.Resource { return &schema.Resource{ CreateContext: resourceServiceAccountCreate, ReadContext: resourceServiceAccountRead, - UpdateContext: resourceServiceAccountUpdate, DeleteContext: resourceServiceAccountDelete, Description: "Service Account resource allows managing CAST AI service accounts.", @@ -51,11 +51,13 @@ func resourceServiceAccount() *schema.Resource { FieldServiceAccountName: { Type: schema.TypeString, Required: true, + ForceNew: true, Description: "Name of the service account.", }, FieldServiceAccountDescription: { Type: schema.TypeString, Optional: true, + ForceNew: true, Description: "Description of the service account.", }, FieldServiceAccountEmail: { @@ -89,6 +91,9 @@ func resourceServiceAccountRead(ctx context.Context, data *schema.ResourceData, organizationID := data.Get(FieldServiceAccountOrganizationID).(string) resp, err := client.ServiceAccountsAPIGetServiceAccountWithResponse(ctx, organizationID, data.Id()) + if resp.StatusCode() == http.StatusNotFound { + return diag.Errorf("getting service account: service account [%s] not found", data.Id()) + } if err := sdk.CheckOKResponse(resp, err); err != nil { return diag.Errorf("getting service account: %v", err) } @@ -107,14 +112,10 @@ func resourceServiceAccountRead(ctx context.Context, data *schema.ResourceData, return diag.Errorf("setting service account description: %v", err) } - - // TODO: how to set a struct into terraform slice of struct. - if err := data.Set(FieldServiceAccountAuthor, []*sdk.CastaiServiceaccountsV1beta1ServiceAccountAuthor{ - serviceAccount.ServiceAccount.Author, - }); err != nil { + authorData := flattenServiceAccountAuthor(serviceAccount.ServiceAccount.Author) + if err := data.Set(FieldServiceAccountAuthor, authorData); err != nil { return diag.Errorf("setting service account author: %v", err) } - return nil } @@ -146,14 +147,13 @@ func resourceServiceAccountDelete(ctx context.Context, data *schema.ResourceData organizationID := data.Get(FieldServiceAccountOrganizationID).(string) serviceAccountID := data.Id() - resp, err := client.ServiceAccountsAPIDeleteServiceAccountWithResponse(ctx, organizationID, serviceAccountID) - if err := sdk.CheckResponseNoContent(resp, err); err != nil { + resp, err := client.ServiceAccountsAPIDeleteServiceAccount(ctx, organizationID, serviceAccountID) + if err != nil { return diag.Errorf("deleteting service account: %v", err) } - return nil -} - -func resourceServiceAccountUpdate(ctx context.Context, data *schema.ResourceData, meta interface{}) diag.Diagnostics { + if resp.StatusCode != http.StatusNoContent { + return diag.Errorf("deleteting service account: expected status: [204], received status: [%d]", resp.StatusCode) + } return nil } @@ -222,3 +222,25 @@ func resourceServiceAccountKeyDelete(ctx context.Context, data *schema.ResourceD func resourceServiceAccountKeyUpdate(ctx context.Context, data *schema.ResourceData, meta interface{}) diag.Diagnostics { return nil } + +func flattenServiceAccountAuthor(author *sdk.CastaiServiceaccountsV1beta1ServiceAccountAuthor) []map[string]interface{} { + if author == nil { + return []map[string]interface{}{} + } + + return []map[string]interface{}{ + { + FieldServiceAccountAuthorID: stringValue(author.Id), + FieldServiceAccountAuthorEmail: stringValue(author.Email), + FieldServiceAccountAuthorKind: stringValue(author.Kind), + }, + } +} + +// Helper function to handle nil pointers +func stringValue(value *string) string { + if value == nil { + return "" + } + return *value +} diff --git a/castai/sdk/api.gen.go b/castai/sdk/api.gen.go index 3d501f80..69593858 100644 --- a/castai/sdk/api.gen.go +++ b/castai/sdk/api.gen.go @@ -355,6 +355,18 @@ const ( WorkloadoptimizationV1ResourcePoliciesFunctionQUANTILE WorkloadoptimizationV1ResourcePoliciesFunction = "QUANTILE" ) +// CommitmentsAPIBatchDeleteCommitmentsRequest defines model for CommitmentsAPI_BatchDeleteCommitments_request. +type CommitmentsAPIBatchDeleteCommitmentsRequest struct { + // IDs of commitments to delete. A maximum of 1000 commitments can be deleted in a batch. + CommitmentIds []string `json:"commitmentIds"` +} + +// CommitmentsAPIBatchUpdateCommitmentsRequest defines model for CommitmentsAPI_BatchUpdateCommitments_request. +type CommitmentsAPIBatchUpdateCommitmentsRequest struct { + // Commitments to update. A maximum of 1000 commitments can be modified in a batch. + Requests []CastaiInventoryV1beta1UpdateCommitmentRequest `json:"requests"` +} + // ExternalClusterAPIGKECreateSARequest defines model for ExternalClusterAPI_GKECreateSA_request. type ExternalClusterAPIGKECreateSARequest struct { // UpdateGKEClusterParams defines updatable GKE cluster configuration. @@ -640,6 +652,11 @@ type CastaiInventoryV1beta1AzureReservationImport struct { Type *string `json:"type,omitempty"` } +// CastaiInventoryV1beta1BatchUpdateCommitmentsResponse defines model for castai.inventory.v1beta1.BatchUpdateCommitmentsResponse. +type CastaiInventoryV1beta1BatchUpdateCommitmentsResponse struct { + Commitments *[]CastaiInventoryV1beta1Commitment `json:"commitments,omitempty"` +} + // CPUPlatform describes the CPU platforms the instance type can be equipped with. type CastaiInventoryV1beta1CPUPlatform struct { // All Core Turbo Frequency (GHz). Only available for GCP. @@ -673,7 +690,10 @@ type CastaiInventoryV1beta1ClusterAggregatedUsage struct { // CastaiInventoryV1beta1Commitment defines model for castai.inventory.v1beta1.Commitment. type CastaiInventoryV1beta1Commitment struct { // Allowed usage specifies the part of the commitment that is allowed to be used. 1.0 means 100% of the commitment. Currently it's only supported for GCP CUDs. - AllowedUsage *float32 `json:"allowedUsage,omitempty"` + AllowedUsage *float32 `json:"allowedUsage,omitempty"` + + // Assign commitment to all existing and future clusters that fall within the region of this commitment. + AutoAssignment *bool `json:"autoAssignment,omitempty"` AzureReservationContext *CastaiInventoryV1beta1AzureReservation `json:"azureReservationContext,omitempty"` EndDate *time.Time `json:"endDate"` GcpResourceCudContext *CastaiInventoryV1beta1GCPResourceCUD `json:"gcpResourceCudContext,omitempty"` @@ -1206,8 +1226,11 @@ type CastaiInventoryV1beta1StorageInfoDeviceType string // CastaiInventoryV1beta1UpdateCommitmentInput defines model for castai.inventory.v1beta1.UpdateCommitmentInput. type CastaiInventoryV1beta1UpdateCommitmentInput struct { // Allowed usage specifies the part of the commitment that is allowed to be used. 1.0 means 100% of the commitment. Currently it's only supported for GCP CUDs. - AllowedUsage *float32 `json:"allowedUsage"` - Prioritization *bool `json:"prioritization"` + AllowedUsage *float32 `json:"allowedUsage"` + + // Assign commitment to all existing and future clusters that fall within the region of this commitment. + AutoAssignment *bool `json:"autoAssignment"` + Prioritization *bool `json:"prioritization"` // Scaling strategy specifies how to use commitment by autoscaler. // @@ -1222,6 +1245,12 @@ type CastaiInventoryV1beta1UpdateCommitmentInput struct { Status *CastaiInventoryV1beta1CommitmentStatus `json:"status,omitempty"` } +// CastaiInventoryV1beta1UpdateCommitmentRequest defines model for castai.inventory.v1beta1.UpdateCommitmentRequest. +type CastaiInventoryV1beta1UpdateCommitmentRequest struct { + Commitment *CastaiInventoryV1beta1UpdateCommitmentInput `json:"commitment,omitempty"` + CommitmentId string `json:"commitmentId"` +} + // CastaiInventoryV1beta1UpdateCommitmentResponse defines model for castai.inventory.v1beta1.UpdateCommitmentResponse. type CastaiInventoryV1beta1UpdateCommitmentResponse struct { Commitments *CastaiInventoryV1beta1Commitment `json:"commitments,omitempty"` @@ -1845,6 +1874,15 @@ type ExternalclusterV1AddNodeResponse struct { OperationId string `json:"operationId"` } +// AnywhereClusterParams defines Anywhere-specific arguments. +type ExternalclusterV1AnywhereClusterParams struct { + // Name of the cluster. + ClusterName *string `json:"clusterName,omitempty"` + + // NamespaceID as unique identifier for the cluster. + KubeSystemNamespaceId string `json:"kubeSystemNamespaceId"` +} + // CloudEvent represents a remote event that happened in the cloud, e.g. "node added". type ExternalclusterV1CloudEvent struct { // Event type. @@ -1874,6 +1912,9 @@ type ExternalclusterV1Cluster struct { // All available zones in cluster's region. AllRegionZones *[]ExternalclusterV1Zone `json:"allRegionZones,omitempty"` + // AnywhereClusterParams defines Anywhere-specific arguments. + Anywhere *ExternalclusterV1AnywhereClusterParams `json:"anywhere,omitempty"` + // User friendly unique cluster identifier. ClusterNameId *string `json:"clusterNameId,omitempty"` @@ -2383,6 +2424,9 @@ type ExternalclusterV1RegisterClusterRequest struct { // AKSClusterParams defines AKS-specific arguments. Aks *ExternalclusterV1AKSClusterParams `json:"aks,omitempty"` + // AnywhereClusterParams defines Anywhere-specific arguments. + Anywhere *ExternalclusterV1AnywhereClusterParams `json:"anywhere,omitempty"` + // EKSClusterParams defines EKS-specific arguments. Eks *ExternalclusterV1EKSClusterParams `json:"eks,omitempty"` @@ -2513,7 +2557,7 @@ type NodeconfigV1AKSConfig struct { // List of supported image families (OSes) for AKS. ImageFamily *NodeconfigV1AKSConfigImageFamily `json:"imageFamily,omitempty"` - // List of load balancers to be used for the cluster. + // List of load balancers to attach nodes to. Populating this field disables Cast's default load balancer autodiscovery mechanism. LoadBalancers *[]NodeconfigV1AKSConfigLoadBalancers `json:"loadBalancers,omitempty"` // Maximum number of pods that can be run on a node, which affects how many IP addresses you will need for each node. @@ -2530,15 +2574,31 @@ type NodeconfigV1AKSConfigImageFamily string // NodeconfigV1AKSConfigLoadBalancers defines model for nodeconfig.v1.AKSConfig.LoadBalancers. type NodeconfigV1AKSConfigLoadBalancers struct { - // List of backend pools to be used for the load balancer. + // The full ID of the load balancer in Azure. + // For backwards compatibility, the field is not required but it should be treated as required for any new clients. + Id *string `json:"id,omitempty"` + + // List of IP-based backend pools to attach each node's IP to. IpBasedBackendPools *[]NodeconfigV1AKSConfigLoadBalancersIPBasedBackendPool `json:"ipBasedBackendPools,omitempty"` - // Name of the load balancer. + // Deprecated: Use ID instead + // Name of the load balancer. It is assumed to reside in the cluster's infrastructure resource group. + // Only available for backwards compatibility and only accounted for in IP-based backend pools. Name *string `json:"name,omitempty"` + + // List of NIC-based backend pools to attach each node's NIC to. + NicBasedBackendPools *[]NodeconfigV1AKSConfigLoadBalancersNICBasedBackendPool `json:"nicBasedBackendPools,omitempty"` } // NodeconfigV1AKSConfigLoadBalancersIPBasedBackendPool defines model for nodeconfig.v1.AKSConfig.LoadBalancers.IPBasedBackendPool. type NodeconfigV1AKSConfigLoadBalancersIPBasedBackendPool struct { + // Name of the backend pool as defined in Azure. Backend pools must have unique names within the load balancer. + Name *string `json:"name,omitempty"` +} + +// NodeconfigV1AKSConfigLoadBalancersNICBasedBackendPool defines model for nodeconfig.v1.AKSConfig.LoadBalancers.NICBasedBackendPool. +type NodeconfigV1AKSConfigLoadBalancersNICBasedBackendPool struct { + // Name of the backend pool as defined in Azure. Backend pools must have unique names within the load balancer. Name *string `json:"name,omitempty"` } @@ -4318,6 +4378,12 @@ type WorkloadoptimizationV1WorkloadScalingPolicy struct { UpdatedAt time.Time `json:"updatedAt"` } +// CommitmentsAPIBatchDeleteCommitmentsJSONBody defines parameters for CommitmentsAPIBatchDeleteCommitments. +type CommitmentsAPIBatchDeleteCommitmentsJSONBody = CommitmentsAPIBatchDeleteCommitmentsRequest + +// CommitmentsAPIBatchUpdateCommitmentsJSONBody defines parameters for CommitmentsAPIBatchUpdateCommitments. +type CommitmentsAPIBatchUpdateCommitmentsJSONBody = CommitmentsAPIBatchUpdateCommitmentsRequest + // CommitmentsAPIGetCommitmentUsageHistoryParams defines parameters for CommitmentsAPIGetCommitmentUsageHistory. type CommitmentsAPIGetCommitmentUsageHistoryParams struct { StartTime time.Time `form:"startTime" json:"startTime"` @@ -4704,6 +4770,12 @@ type InventoryAPIListZonesParams struct { // WorkloadOptimizationAPIUpdateWorkloadV2JSONBody defines parameters for WorkloadOptimizationAPIUpdateWorkloadV2. type WorkloadOptimizationAPIUpdateWorkloadV2JSONBody = WorkloadoptimizationV1UpdateWorkloadV2 +// CommitmentsAPIBatchDeleteCommitmentsJSONRequestBody defines body for CommitmentsAPIBatchDeleteCommitments for application/json ContentType. +type CommitmentsAPIBatchDeleteCommitmentsJSONRequestBody = CommitmentsAPIBatchDeleteCommitmentsJSONBody + +// CommitmentsAPIBatchUpdateCommitmentsJSONRequestBody defines body for CommitmentsAPIBatchUpdateCommitments for application/json ContentType. +type CommitmentsAPIBatchUpdateCommitmentsJSONRequestBody = CommitmentsAPIBatchUpdateCommitmentsJSONBody + // AuthTokenAPICreateAuthTokenJSONRequestBody defines body for AuthTokenAPICreateAuthToken for application/json ContentType. type AuthTokenAPICreateAuthTokenJSONRequestBody = AuthTokenAPICreateAuthTokenJSONBody diff --git a/castai/sdk/client.gen.go b/castai/sdk/client.gen.go index b4877d63..dfa60ec4 100644 --- a/castai/sdk/client.gen.go +++ b/castai/sdk/client.gen.go @@ -90,6 +90,16 @@ func WithRequestEditorFn(fn RequestEditorFn) ClientOption { // The interface specification for the client above. type ClientInterface interface { + // CommitmentsAPIBatchDeleteCommitments request with any body + CommitmentsAPIBatchDeleteCommitmentsWithBody(ctx context.Context, organizationId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + CommitmentsAPIBatchDeleteCommitments(ctx context.Context, organizationId string, body CommitmentsAPIBatchDeleteCommitmentsJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // CommitmentsAPIBatchUpdateCommitments request with any body + CommitmentsAPIBatchUpdateCommitmentsWithBody(ctx context.Context, organizationId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + CommitmentsAPIBatchUpdateCommitments(ctx context.Context, organizationId string, body CommitmentsAPIBatchUpdateCommitmentsJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + // CommitmentsAPIGetCommitmentUsageHistory request CommitmentsAPIGetCommitmentUsageHistory(ctx context.Context, organizationId string, commitmentId string, params *CommitmentsAPIGetCommitmentUsageHistoryParams, reqEditors ...RequestEditorFn) (*http.Response, error) @@ -583,6 +593,54 @@ type ClientInterface interface { WorkloadOptimizationAPIUpdateWorkloadV2(ctx context.Context, clusterId string, workloadId string, body WorkloadOptimizationAPIUpdateWorkloadV2JSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) } +func (c *Client) CommitmentsAPIBatchDeleteCommitmentsWithBody(ctx context.Context, organizationId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewCommitmentsAPIBatchDeleteCommitmentsRequestWithBody(c.Server, organizationId, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) CommitmentsAPIBatchDeleteCommitments(ctx context.Context, organizationId string, body CommitmentsAPIBatchDeleteCommitmentsJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewCommitmentsAPIBatchDeleteCommitmentsRequest(c.Server, organizationId, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) CommitmentsAPIBatchUpdateCommitmentsWithBody(ctx context.Context, organizationId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewCommitmentsAPIBatchUpdateCommitmentsRequestWithBody(c.Server, organizationId, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) CommitmentsAPIBatchUpdateCommitments(ctx context.Context, organizationId string, body CommitmentsAPIBatchUpdateCommitmentsJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewCommitmentsAPIBatchUpdateCommitmentsRequest(c.Server, organizationId, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + func (c *Client) CommitmentsAPIGetCommitmentUsageHistory(ctx context.Context, organizationId string, commitmentId string, params *CommitmentsAPIGetCommitmentUsageHistoryParams, reqEditors ...RequestEditorFn) (*http.Response, error) { req, err := NewCommitmentsAPIGetCommitmentUsageHistoryRequest(c.Server, organizationId, commitmentId, params) if err != nil { @@ -2731,6 +2789,100 @@ func (c *Client) WorkloadOptimizationAPIUpdateWorkloadV2(ctx context.Context, cl return c.Client.Do(req) } +// NewCommitmentsAPIBatchDeleteCommitmentsRequest calls the generic CommitmentsAPIBatchDeleteCommitments builder with application/json body +func NewCommitmentsAPIBatchDeleteCommitmentsRequest(server string, organizationId string, body CommitmentsAPIBatchDeleteCommitmentsJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewCommitmentsAPIBatchDeleteCommitmentsRequestWithBody(server, organizationId, "application/json", bodyReader) +} + +// NewCommitmentsAPIBatchDeleteCommitmentsRequestWithBody generates requests for CommitmentsAPIBatchDeleteCommitments with any type of body +func NewCommitmentsAPIBatchDeleteCommitmentsRequestWithBody(server string, organizationId string, contentType string, body io.Reader) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithLocation("simple", false, "organizationId", runtime.ParamLocationPath, organizationId) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/savings/v1/organizations/%s/commitments:batchDelete", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("POST", queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewCommitmentsAPIBatchUpdateCommitmentsRequest calls the generic CommitmentsAPIBatchUpdateCommitments builder with application/json body +func NewCommitmentsAPIBatchUpdateCommitmentsRequest(server string, organizationId string, body CommitmentsAPIBatchUpdateCommitmentsJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewCommitmentsAPIBatchUpdateCommitmentsRequestWithBody(server, organizationId, "application/json", bodyReader) +} + +// NewCommitmentsAPIBatchUpdateCommitmentsRequestWithBody generates requests for CommitmentsAPIBatchUpdateCommitments with any type of body +func NewCommitmentsAPIBatchUpdateCommitmentsRequestWithBody(server string, organizationId string, contentType string, body io.Reader) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithLocation("simple", false, "organizationId", runtime.ParamLocationPath, organizationId) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/savings/v1/organizations/%s/commitments:batchUpdate", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("POST", queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + // NewCommitmentsAPIGetCommitmentUsageHistoryRequest generates requests for CommitmentsAPIGetCommitmentUsageHistory func NewCommitmentsAPIGetCommitmentUsageHistoryRequest(server string, organizationId string, commitmentId string, params *CommitmentsAPIGetCommitmentUsageHistoryParams) (*http.Request, error) { var err error @@ -9079,6 +9231,16 @@ func WithBaseURL(baseURL string) ClientOption { // ClientWithResponsesInterface is the interface specification for the client with responses above. type ClientWithResponsesInterface interface { + // CommitmentsAPIBatchDeleteCommitments request with any body + CommitmentsAPIBatchDeleteCommitmentsWithBodyWithResponse(ctx context.Context, organizationId string, contentType string, body io.Reader) (*CommitmentsAPIBatchDeleteCommitmentsResponse, error) + + CommitmentsAPIBatchDeleteCommitmentsWithResponse(ctx context.Context, organizationId string, body CommitmentsAPIBatchDeleteCommitmentsJSONRequestBody) (*CommitmentsAPIBatchDeleteCommitmentsResponse, error) + + // CommitmentsAPIBatchUpdateCommitments request with any body + CommitmentsAPIBatchUpdateCommitmentsWithBodyWithResponse(ctx context.Context, organizationId string, contentType string, body io.Reader) (*CommitmentsAPIBatchUpdateCommitmentsResponse, error) + + CommitmentsAPIBatchUpdateCommitmentsWithResponse(ctx context.Context, organizationId string, body CommitmentsAPIBatchUpdateCommitmentsJSONRequestBody) (*CommitmentsAPIBatchUpdateCommitmentsResponse, error) + // CommitmentsAPIGetCommitmentUsageHistory request CommitmentsAPIGetCommitmentUsageHistoryWithResponse(ctx context.Context, organizationId string, commitmentId string, params *CommitmentsAPIGetCommitmentUsageHistoryParams) (*CommitmentsAPIGetCommitmentUsageHistoryResponse, error) @@ -9581,6 +9743,66 @@ type Response interface { // TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 +type CommitmentsAPIBatchDeleteCommitmentsResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *map[string]interface{} +} + +// Status returns HTTPResponse.Status +func (r CommitmentsAPIBatchDeleteCommitmentsResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r CommitmentsAPIBatchDeleteCommitmentsResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 +// Body returns body of byte array +func (r CommitmentsAPIBatchDeleteCommitmentsResponse) GetBody() []byte { + return r.Body +} + +// TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 + +type CommitmentsAPIBatchUpdateCommitmentsResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *CastaiInventoryV1beta1BatchUpdateCommitmentsResponse +} + +// Status returns HTTPResponse.Status +func (r CommitmentsAPIBatchUpdateCommitmentsResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r CommitmentsAPIBatchUpdateCommitmentsResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 +// Body returns body of byte array +func (r CommitmentsAPIBatchUpdateCommitmentsResponse) GetBody() []byte { + return r.Body +} + +// TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 + type CommitmentsAPIGetCommitmentUsageHistoryResponse struct { Body []byte HTTPResponse *http.Response @@ -13598,6 +13820,40 @@ func (r WorkloadOptimizationAPIUpdateWorkloadV2Response) GetBody() []byte { // TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 +// CommitmentsAPIBatchDeleteCommitmentsWithBodyWithResponse request with arbitrary body returning *CommitmentsAPIBatchDeleteCommitmentsResponse +func (c *ClientWithResponses) CommitmentsAPIBatchDeleteCommitmentsWithBodyWithResponse(ctx context.Context, organizationId string, contentType string, body io.Reader) (*CommitmentsAPIBatchDeleteCommitmentsResponse, error) { + rsp, err := c.CommitmentsAPIBatchDeleteCommitmentsWithBody(ctx, organizationId, contentType, body) + if err != nil { + return nil, err + } + return ParseCommitmentsAPIBatchDeleteCommitmentsResponse(rsp) +} + +func (c *ClientWithResponses) CommitmentsAPIBatchDeleteCommitmentsWithResponse(ctx context.Context, organizationId string, body CommitmentsAPIBatchDeleteCommitmentsJSONRequestBody) (*CommitmentsAPIBatchDeleteCommitmentsResponse, error) { + rsp, err := c.CommitmentsAPIBatchDeleteCommitments(ctx, organizationId, body) + if err != nil { + return nil, err + } + return ParseCommitmentsAPIBatchDeleteCommitmentsResponse(rsp) +} + +// CommitmentsAPIBatchUpdateCommitmentsWithBodyWithResponse request with arbitrary body returning *CommitmentsAPIBatchUpdateCommitmentsResponse +func (c *ClientWithResponses) CommitmentsAPIBatchUpdateCommitmentsWithBodyWithResponse(ctx context.Context, organizationId string, contentType string, body io.Reader) (*CommitmentsAPIBatchUpdateCommitmentsResponse, error) { + rsp, err := c.CommitmentsAPIBatchUpdateCommitmentsWithBody(ctx, organizationId, contentType, body) + if err != nil { + return nil, err + } + return ParseCommitmentsAPIBatchUpdateCommitmentsResponse(rsp) +} + +func (c *ClientWithResponses) CommitmentsAPIBatchUpdateCommitmentsWithResponse(ctx context.Context, organizationId string, body CommitmentsAPIBatchUpdateCommitmentsJSONRequestBody) (*CommitmentsAPIBatchUpdateCommitmentsResponse, error) { + rsp, err := c.CommitmentsAPIBatchUpdateCommitments(ctx, organizationId, body) + if err != nil { + return nil, err + } + return ParseCommitmentsAPIBatchUpdateCommitmentsResponse(rsp) +} + // CommitmentsAPIGetCommitmentUsageHistoryWithResponse request returning *CommitmentsAPIGetCommitmentUsageHistoryResponse func (c *ClientWithResponses) CommitmentsAPIGetCommitmentUsageHistoryWithResponse(ctx context.Context, organizationId string, commitmentId string, params *CommitmentsAPIGetCommitmentUsageHistoryParams) (*CommitmentsAPIGetCommitmentUsageHistoryResponse, error) { rsp, err := c.CommitmentsAPIGetCommitmentUsageHistory(ctx, organizationId, commitmentId, params) @@ -15164,6 +15420,58 @@ func (c *ClientWithResponses) WorkloadOptimizationAPIUpdateWorkloadV2WithRespons return ParseWorkloadOptimizationAPIUpdateWorkloadV2Response(rsp) } +// ParseCommitmentsAPIBatchDeleteCommitmentsResponse parses an HTTP response from a CommitmentsAPIBatchDeleteCommitmentsWithResponse call +func ParseCommitmentsAPIBatchDeleteCommitmentsResponse(rsp *http.Response) (*CommitmentsAPIBatchDeleteCommitmentsResponse, error) { + bodyBytes, err := ioutil.ReadAll(rsp.Body) + defer rsp.Body.Close() + if err != nil { + return nil, err + } + + response := &CommitmentsAPIBatchDeleteCommitmentsResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest map[string]interface{} + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + } + + return response, nil +} + +// ParseCommitmentsAPIBatchUpdateCommitmentsResponse parses an HTTP response from a CommitmentsAPIBatchUpdateCommitmentsWithResponse call +func ParseCommitmentsAPIBatchUpdateCommitmentsResponse(rsp *http.Response) (*CommitmentsAPIBatchUpdateCommitmentsResponse, error) { + bodyBytes, err := ioutil.ReadAll(rsp.Body) + defer rsp.Body.Close() + if err != nil { + return nil, err + } + + response := &CommitmentsAPIBatchUpdateCommitmentsResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest CastaiInventoryV1beta1BatchUpdateCommitmentsResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + } + + return response, nil +} + // ParseCommitmentsAPIGetCommitmentUsageHistoryResponse parses an HTTP response from a CommitmentsAPIGetCommitmentUsageHistoryWithResponse call func ParseCommitmentsAPIGetCommitmentUsageHistoryResponse(rsp *http.Response) (*CommitmentsAPIGetCommitmentUsageHistoryResponse, error) { bodyBytes, err := ioutil.ReadAll(rsp.Body) diff --git a/castai/sdk/mock/client.go b/castai/sdk/mock/client.go index d2f0ee0c..cf8170f2 100644 --- a/castai/sdk/mock/client.go +++ b/castai/sdk/mock/client.go @@ -215,6 +215,86 @@ func (mr *MockClientInterfaceMockRecorder) AuthTokenAPIUpdateAuthTokenWithBody(c return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AuthTokenAPIUpdateAuthTokenWithBody", reflect.TypeOf((*MockClientInterface)(nil).AuthTokenAPIUpdateAuthTokenWithBody), varargs...) } +// CommitmentsAPIBatchDeleteCommitments mocks base method. +func (m *MockClientInterface) CommitmentsAPIBatchDeleteCommitments(ctx context.Context, organizationId string, body sdk.CommitmentsAPIBatchDeleteCommitmentsJSONRequestBody, reqEditors ...sdk.RequestEditorFn) (*http.Response, error) { + m.ctrl.T.Helper() + varargs := []interface{}{ctx, organizationId, body} + for _, a := range reqEditors { + varargs = append(varargs, a) + } + ret := m.ctrl.Call(m, "CommitmentsAPIBatchDeleteCommitments", varargs...) + ret0, _ := ret[0].(*http.Response) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// CommitmentsAPIBatchDeleteCommitments indicates an expected call of CommitmentsAPIBatchDeleteCommitments. +func (mr *MockClientInterfaceMockRecorder) CommitmentsAPIBatchDeleteCommitments(ctx, organizationId, body interface{}, reqEditors ...interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + varargs := append([]interface{}{ctx, organizationId, body}, reqEditors...) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CommitmentsAPIBatchDeleteCommitments", reflect.TypeOf((*MockClientInterface)(nil).CommitmentsAPIBatchDeleteCommitments), varargs...) +} + +// CommitmentsAPIBatchDeleteCommitmentsWithBody mocks base method. +func (m *MockClientInterface) CommitmentsAPIBatchDeleteCommitmentsWithBody(ctx context.Context, organizationId, contentType string, body io.Reader, reqEditors ...sdk.RequestEditorFn) (*http.Response, error) { + m.ctrl.T.Helper() + varargs := []interface{}{ctx, organizationId, contentType, body} + for _, a := range reqEditors { + varargs = append(varargs, a) + } + ret := m.ctrl.Call(m, "CommitmentsAPIBatchDeleteCommitmentsWithBody", varargs...) + ret0, _ := ret[0].(*http.Response) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// CommitmentsAPIBatchDeleteCommitmentsWithBody indicates an expected call of CommitmentsAPIBatchDeleteCommitmentsWithBody. +func (mr *MockClientInterfaceMockRecorder) CommitmentsAPIBatchDeleteCommitmentsWithBody(ctx, organizationId, contentType, body interface{}, reqEditors ...interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + varargs := append([]interface{}{ctx, organizationId, contentType, body}, reqEditors...) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CommitmentsAPIBatchDeleteCommitmentsWithBody", reflect.TypeOf((*MockClientInterface)(nil).CommitmentsAPIBatchDeleteCommitmentsWithBody), varargs...) +} + +// CommitmentsAPIBatchUpdateCommitments mocks base method. +func (m *MockClientInterface) CommitmentsAPIBatchUpdateCommitments(ctx context.Context, organizationId string, body sdk.CommitmentsAPIBatchUpdateCommitmentsJSONRequestBody, reqEditors ...sdk.RequestEditorFn) (*http.Response, error) { + m.ctrl.T.Helper() + varargs := []interface{}{ctx, organizationId, body} + for _, a := range reqEditors { + varargs = append(varargs, a) + } + ret := m.ctrl.Call(m, "CommitmentsAPIBatchUpdateCommitments", varargs...) + ret0, _ := ret[0].(*http.Response) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// CommitmentsAPIBatchUpdateCommitments indicates an expected call of CommitmentsAPIBatchUpdateCommitments. +func (mr *MockClientInterfaceMockRecorder) CommitmentsAPIBatchUpdateCommitments(ctx, organizationId, body interface{}, reqEditors ...interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + varargs := append([]interface{}{ctx, organizationId, body}, reqEditors...) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CommitmentsAPIBatchUpdateCommitments", reflect.TypeOf((*MockClientInterface)(nil).CommitmentsAPIBatchUpdateCommitments), varargs...) +} + +// CommitmentsAPIBatchUpdateCommitmentsWithBody mocks base method. +func (m *MockClientInterface) CommitmentsAPIBatchUpdateCommitmentsWithBody(ctx context.Context, organizationId, contentType string, body io.Reader, reqEditors ...sdk.RequestEditorFn) (*http.Response, error) { + m.ctrl.T.Helper() + varargs := []interface{}{ctx, organizationId, contentType, body} + for _, a := range reqEditors { + varargs = append(varargs, a) + } + ret := m.ctrl.Call(m, "CommitmentsAPIBatchUpdateCommitmentsWithBody", varargs...) + ret0, _ := ret[0].(*http.Response) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// CommitmentsAPIBatchUpdateCommitmentsWithBody indicates an expected call of CommitmentsAPIBatchUpdateCommitmentsWithBody. +func (mr *MockClientInterfaceMockRecorder) CommitmentsAPIBatchUpdateCommitmentsWithBody(ctx, organizationId, contentType, body interface{}, reqEditors ...interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + varargs := append([]interface{}{ctx, organizationId, contentType, body}, reqEditors...) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CommitmentsAPIBatchUpdateCommitmentsWithBody", reflect.TypeOf((*MockClientInterface)(nil).CommitmentsAPIBatchUpdateCommitmentsWithBody), varargs...) +} + // CommitmentsAPICreateCommitmentAssignment mocks base method. func (m *MockClientInterface) CommitmentsAPICreateCommitmentAssignment(ctx context.Context, params *sdk.CommitmentsAPICreateCommitmentAssignmentParams, reqEditors ...sdk.RequestEditorFn) (*http.Response, error) { m.ctrl.T.Helper() @@ -3783,6 +3863,66 @@ func (mr *MockClientWithResponsesInterfaceMockRecorder) AuthTokenAPIUpdateAuthTo return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AuthTokenAPIUpdateAuthTokenWithResponse", reflect.TypeOf((*MockClientWithResponsesInterface)(nil).AuthTokenAPIUpdateAuthTokenWithResponse), ctx, id, body) } +// CommitmentsAPIBatchDeleteCommitmentsWithBodyWithResponse mocks base method. +func (m *MockClientWithResponsesInterface) CommitmentsAPIBatchDeleteCommitmentsWithBodyWithResponse(ctx context.Context, organizationId, contentType string, body io.Reader) (*sdk.CommitmentsAPIBatchDeleteCommitmentsResponse, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "CommitmentsAPIBatchDeleteCommitmentsWithBodyWithResponse", ctx, organizationId, contentType, body) + ret0, _ := ret[0].(*sdk.CommitmentsAPIBatchDeleteCommitmentsResponse) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// CommitmentsAPIBatchDeleteCommitmentsWithBodyWithResponse indicates an expected call of CommitmentsAPIBatchDeleteCommitmentsWithBodyWithResponse. +func (mr *MockClientWithResponsesInterfaceMockRecorder) CommitmentsAPIBatchDeleteCommitmentsWithBodyWithResponse(ctx, organizationId, contentType, body interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CommitmentsAPIBatchDeleteCommitmentsWithBodyWithResponse", reflect.TypeOf((*MockClientWithResponsesInterface)(nil).CommitmentsAPIBatchDeleteCommitmentsWithBodyWithResponse), ctx, organizationId, contentType, body) +} + +// CommitmentsAPIBatchDeleteCommitmentsWithResponse mocks base method. +func (m *MockClientWithResponsesInterface) CommitmentsAPIBatchDeleteCommitmentsWithResponse(ctx context.Context, organizationId string, body sdk.CommitmentsAPIBatchDeleteCommitmentsJSONRequestBody) (*sdk.CommitmentsAPIBatchDeleteCommitmentsResponse, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "CommitmentsAPIBatchDeleteCommitmentsWithResponse", ctx, organizationId, body) + ret0, _ := ret[0].(*sdk.CommitmentsAPIBatchDeleteCommitmentsResponse) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// CommitmentsAPIBatchDeleteCommitmentsWithResponse indicates an expected call of CommitmentsAPIBatchDeleteCommitmentsWithResponse. +func (mr *MockClientWithResponsesInterfaceMockRecorder) CommitmentsAPIBatchDeleteCommitmentsWithResponse(ctx, organizationId, body interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CommitmentsAPIBatchDeleteCommitmentsWithResponse", reflect.TypeOf((*MockClientWithResponsesInterface)(nil).CommitmentsAPIBatchDeleteCommitmentsWithResponse), ctx, organizationId, body) +} + +// CommitmentsAPIBatchUpdateCommitmentsWithBodyWithResponse mocks base method. +func (m *MockClientWithResponsesInterface) CommitmentsAPIBatchUpdateCommitmentsWithBodyWithResponse(ctx context.Context, organizationId, contentType string, body io.Reader) (*sdk.CommitmentsAPIBatchUpdateCommitmentsResponse, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "CommitmentsAPIBatchUpdateCommitmentsWithBodyWithResponse", ctx, organizationId, contentType, body) + ret0, _ := ret[0].(*sdk.CommitmentsAPIBatchUpdateCommitmentsResponse) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// CommitmentsAPIBatchUpdateCommitmentsWithBodyWithResponse indicates an expected call of CommitmentsAPIBatchUpdateCommitmentsWithBodyWithResponse. +func (mr *MockClientWithResponsesInterfaceMockRecorder) CommitmentsAPIBatchUpdateCommitmentsWithBodyWithResponse(ctx, organizationId, contentType, body interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CommitmentsAPIBatchUpdateCommitmentsWithBodyWithResponse", reflect.TypeOf((*MockClientWithResponsesInterface)(nil).CommitmentsAPIBatchUpdateCommitmentsWithBodyWithResponse), ctx, organizationId, contentType, body) +} + +// CommitmentsAPIBatchUpdateCommitmentsWithResponse mocks base method. +func (m *MockClientWithResponsesInterface) CommitmentsAPIBatchUpdateCommitmentsWithResponse(ctx context.Context, organizationId string, body sdk.CommitmentsAPIBatchUpdateCommitmentsJSONRequestBody) (*sdk.CommitmentsAPIBatchUpdateCommitmentsResponse, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "CommitmentsAPIBatchUpdateCommitmentsWithResponse", ctx, organizationId, body) + ret0, _ := ret[0].(*sdk.CommitmentsAPIBatchUpdateCommitmentsResponse) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// CommitmentsAPIBatchUpdateCommitmentsWithResponse indicates an expected call of CommitmentsAPIBatchUpdateCommitmentsWithResponse. +func (mr *MockClientWithResponsesInterfaceMockRecorder) CommitmentsAPIBatchUpdateCommitmentsWithResponse(ctx, organizationId, body interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CommitmentsAPIBatchUpdateCommitmentsWithResponse", reflect.TypeOf((*MockClientWithResponsesInterface)(nil).CommitmentsAPIBatchUpdateCommitmentsWithResponse), ctx, organizationId, body) +} + // CommitmentsAPICreateCommitmentAssignmentWithResponse mocks base method. func (m *MockClientWithResponsesInterface) CommitmentsAPICreateCommitmentAssignmentWithResponse(ctx context.Context, params *sdk.CommitmentsAPICreateCommitmentAssignmentParams) (*sdk.CommitmentsAPICreateCommitmentAssignmentResponse, error) { m.ctrl.T.Helper() From 4734acb5e1e2ea2063492fa736e767b475702a36 Mon Sep 17 00:00:00 2001 From: radekska Date: Mon, 2 Dec 2024 15:14:08 +0100 Subject: [PATCH 07/24] bring back versions --- examples/localdev/versions.tf | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/examples/localdev/versions.tf b/examples/localdev/versions.tf index 8c654251..a9ba01d6 100644 --- a/examples/localdev/versions.tf +++ b/examples/localdev/versions.tf @@ -1,14 +1,9 @@ terraform { required_providers { castai = { - source = "castai/castai" + source = "castai/castai" + version = "0.0.0-local" } - } required_version = ">= 0.13" } - -provider "castai" { - api_url = var.castai_api_url - api_token = var.castai_api_token -} From c6d7080831cba389fad92278ff0d68c884d3c216 Mon Sep 17 00:00:00 2001 From: radekska Date: Tue, 3 Dec 2024 10:39:27 +0100 Subject: [PATCH 08/24] add examples --- docs/resources/service_account.md | 14 +++++++++++++- .../resources/castai_service_account/resource.tf | 5 +++++ 2 files changed, 18 insertions(+), 1 deletion(-) create mode 100644 examples/resources/castai_service_account/resource.tf diff --git a/docs/resources/service_account.md b/docs/resources/service_account.md index 762b6e9b..7f5fb071 100644 --- a/docs/resources/service_account.md +++ b/docs/resources/service_account.md @@ -10,7 +10,19 @@ description: |- Service Account resource allows managing CAST AI service accounts. - +## Example Usage + +```terraform +resource "castai_serv" "service_account" { + name = "aad_connection" + email_domain = "aad_connection@test.com" + aad { + client_id = azuread_application.castai_sso.client_id + client_secret = azuread_application_password.castai_sso.value + ad_domain = azuread_application.castai_sso.publisher_domain + } +} +``` ## Schema diff --git a/examples/resources/castai_service_account/resource.tf b/examples/resources/castai_service_account/resource.tf new file mode 100644 index 00000000..9c3f4563 --- /dev/null +++ b/examples/resources/castai_service_account/resource.tf @@ -0,0 +1,5 @@ +resource "castai_service_account" "service_account" { + organization_id = organization.id + name = "service-account-name" + description = "service account description" +} From 9aff9ca25603604f1b3c43d688438884bd20fc6c Mon Sep 17 00:00:00 2001 From: radekska Date: Mon, 9 Dec 2024 08:56:00 +0100 Subject: [PATCH 09/24] wip --- castai/resource_service_account.go | 47 ++++- castai/sdk/api.gen.go | 74 ++----- castai/sdk/client.gen.go | 322 ++++++++++++++--------------- castai/sdk/mock/client.go | 140 ++++++------- 4 files changed, 294 insertions(+), 289 deletions(-) diff --git a/castai/resource_service_account.go b/castai/resource_service_account.go index c0b1491d..91ea5567 100644 --- a/castai/resource_service_account.go +++ b/castai/resource_service_account.go @@ -5,6 +5,7 @@ import ( "net/http" "time" + "github.com/hashicorp/terraform-plugin-log/tflog" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" @@ -86,14 +87,28 @@ func resourceServiceAccountRead(ctx context.Context, data *schema.ResourceData, organizationID := data.Get(FieldServiceAccountOrganizationID).(string) + tflog.Info(ctx, "reading service account", map[string]interface{}{ + "resource_id": data.Id(), + "organization_id": organizationID, + }) + resp, err := client.ServiceAccountsAPIGetServiceAccountWithResponse(ctx, organizationID, data.Id()) if resp.StatusCode() == http.StatusNotFound { - return diag.Errorf("getting service account: service account [%s] not found", data.Id()) + tflog.Warn(ctx, "resource is not found, removing from state", map[string]interface{}{ + "resource_id": data.Id(), + "organization_id": organizationID, + }) + data.SetId("") // Mark resource as deleted + return nil } if err := sdk.CheckOKResponse(resp, err); err != nil { return diag.Errorf("getting service account: %v", err) } + tflog.Info(ctx, "found service account", map[string]interface{}{ + "resource_id": data.Id(), + "organization_id": organizationID, + }) serviceAccount := resp.JSON200 if err := data.Set(FieldServiceAccountName, serviceAccount.ServiceAccount.Name); err != nil { @@ -122,17 +137,26 @@ func resourceServiceAccountCreate(ctx context.Context, data *schema.ResourceData name := data.Get(FieldServiceAccountName).(string) description := data.Get(FieldServiceAccountDescription).(string) - resp, err := client.ServiceAccountsAPICreateServiceAccountWithResponse(ctx, organizationID, sdk.ServiceAccountsAPICreateServiceAccountRequest{ - ServiceAccount: sdk.CastaiServiceaccountsV1beta1CreateServiceAccountRequestServiceAccount{ - Name: name, - Description: &description, - }, + tflog.Info(ctx, "creating service account", map[string]interface{}{ + "name": name, + "description": description, + "organization_id": organizationID, }) + resp, err := client.ServiceAccountsAPICreateServiceAccountWithResponse(ctx, organizationID, sdk.CastaiServiceaccountsV1beta1CreateServiceAccountRequestServiceAccount{ + Name: name, + Description: &description, + }, + ) + if err := sdk.CheckResponseCreated(resp, err); err != nil { return diag.Errorf("creating service account: %v", err) } + tflog.Info(ctx, "created service account", map[string]interface{}{ + "resource_id": *resp.JSON201.Id, + "organization_id": organizationID, + }) data.SetId(*resp.JSON201.Id) return resourceServiceAccountRead(ctx, data, meta) @@ -143,6 +167,11 @@ func resourceServiceAccountDelete(ctx context.Context, data *schema.ResourceData organizationID := data.Get(FieldServiceAccountOrganizationID).(string) serviceAccountID := data.Id() + tflog.Info(ctx, "deleting service account", map[string]interface{}{ + "resource_id": serviceAccountID, + "organization_id": organizationID, + }) + resp, err := client.ServiceAccountsAPIDeleteServiceAccount(ctx, organizationID, serviceAccountID) if err != nil { return diag.Errorf("deleting service account: %v", err) @@ -150,6 +179,12 @@ func resourceServiceAccountDelete(ctx context.Context, data *schema.ResourceData if resp.StatusCode != http.StatusNoContent { return diag.Errorf("deleteting service account: expected status: [204], received status: [%d]", resp.StatusCode) } + + tflog.Info(ctx, "deleted service account", map[string]interface{}{ + "resource_id": serviceAccountID, + "organization_id": organizationID, + }) + return nil } diff --git a/castai/sdk/api.gen.go b/castai/sdk/api.gen.go index 69593858..06a18669 100644 --- a/castai/sdk/api.gen.go +++ b/castai/sdk/api.gen.go @@ -379,10 +379,9 @@ type ServiceAccountsAPICreateServiceAccountKeyRequest struct { Key CastaiServiceaccountsV1beta1CreateServiceAccountKeyRequestKey `json:"key"` } -// CreateServiceAccountRequest is the request for creating a service account. -type ServiceAccountsAPICreateServiceAccountRequest struct { - // ServiceAccounts is the readable version of the service accounts. - ServiceAccount CastaiServiceaccountsV1beta1CreateServiceAccountRequestServiceAccount `json:"serviceAccount"` +// UpdateServiceAccountRequest is the request for updating a service account. +type ServiceAccountsAPIUpdateServiceAccountRequest struct { + ServiceAccount CastaiServiceaccountsV1beta1UpdateServiceAccountRequestServiceAccount `json:"serviceAccount"` } // UsersAPIUpdateOrganizationUserRequest defines model for UsersAPI_UpdateOrganizationUser_request. @@ -1483,6 +1482,18 @@ type CastaiServiceaccountsV1beta1UpdateServiceAccountKeyResponse struct { Prefix *string `json:"prefix,omitempty"` } +// CastaiServiceaccountsV1beta1UpdateServiceAccountRequestServiceAccount defines model for castai.serviceaccounts.v1beta1.UpdateServiceAccountRequest.ServiceAccount. +type CastaiServiceaccountsV1beta1UpdateServiceAccountRequestServiceAccount struct { + Description *string `json:"description,omitempty"` + Name string `json:"name"` +} + +// UpdateServiceAccountResponse is the response for updating a service account. +type CastaiServiceaccountsV1beta1UpdateServiceAccountResponse struct { + // ServiceAccounts is the readable version of the service accounts. + ServiceAccount CastaiServiceaccountsV1beta1ServiceAccount `json:"serviceAccount"` +} + // AzureAAD represents a Azure AAD connector. type CastaiSsoV1beta1AzureAAD struct { // ADDomain is the domain of the Azure AD. @@ -4146,18 +4157,6 @@ type WorkloadoptimizationV1TimeSeriesMetric struct { Value float64 `json:"value"` } -// WorkloadoptimizationV1UpdateWorkload defines model for workloadoptimization.v1.UpdateWorkload. -type WorkloadoptimizationV1UpdateWorkload struct { - // Defines the scaling policy ID assigned to the workload. - ScalingPolicyId string `json:"scalingPolicyId"` - WorkloadConfig *WorkloadoptimizationV1WorkloadConfigUpdate `json:"workloadConfig,omitempty"` -} - -// WorkloadoptimizationV1UpdateWorkloadResponse defines model for workloadoptimization.v1.UpdateWorkloadResponse. -type WorkloadoptimizationV1UpdateWorkloadResponse struct { - Workload *WorkloadoptimizationV1Workload `json:"workload,omitempty"` -} - // WorkloadoptimizationV1UpdateWorkloadResponseV2 defines model for workloadoptimization.v1.UpdateWorkloadResponseV2. type WorkloadoptimizationV1UpdateWorkloadResponseV2 struct { Workload *WorkloadoptimizationV1Workload `json:"workload,omitempty"` @@ -4252,38 +4251,9 @@ type WorkloadoptimizationV1Workload struct { ScalingPolicyId string `json:"scalingPolicyId"` UpdatedAt time.Time `json:"updatedAt"` Version string `json:"version"` - WorkloadConfig WorkloadoptimizationV1WorkloadConfig `json:"workloadConfig"` WorkloadConfigV2 WorkloadoptimizationV1WorkloadConfigV2 `json:"workloadConfigV2"` } -// WorkloadoptimizationV1WorkloadConfig defines model for workloadoptimization.v1.WorkloadConfig. -type WorkloadoptimizationV1WorkloadConfig struct { - AntiAffinity WorkloadoptimizationV1AntiAffinitySettings `json:"antiAffinity"` - ContainerConstraints []WorkloadoptimizationV1ContainerConstraints `json:"containerConstraints"` - Cpu WorkloadoptimizationV1ResourceConfig `json:"cpu"` - - // Defines possible options for workload management. - // READ_ONLY - workload watched (metrics collected), but no actions may be performed by CAST AI. - // MANAGED - workload watched (metrics collected), CAST AI may perform actions on the workload. - ManagementOption WorkloadoptimizationV1ManagementOption `json:"managementOption"` - Memory WorkloadoptimizationV1ResourceConfig `json:"memory"` - MemoryEvent *WorkloadoptimizationV1MemoryEventSettings `json:"memoryEvent,omitempty"` -} - -// WorkloadoptimizationV1WorkloadConfigUpdate defines model for workloadoptimization.v1.WorkloadConfigUpdate. -type WorkloadoptimizationV1WorkloadConfigUpdate struct { - AntiAffinity *WorkloadoptimizationV1AntiAffinitySettings `json:"antiAffinity,omitempty"` - ContainerConfig *[]WorkloadoptimizationV1ContainerConfigUpdate `json:"containerConfig,omitempty"` - Cpu *WorkloadoptimizationV1WorkloadResourceConfigUpdate `json:"cpu,omitempty"` - - // Defines possible options for workload management. - // READ_ONLY - workload watched (metrics collected), but no actions may be performed by CAST AI. - // MANAGED - workload watched (metrics collected), CAST AI may perform actions on the workload. - ManagementOption *WorkloadoptimizationV1ManagementOption `json:"managementOption,omitempty"` - Memory *WorkloadoptimizationV1WorkloadResourceConfigUpdate `json:"memory,omitempty"` - MemoryEvent *WorkloadoptimizationV1MemoryEventSettings `json:"memoryEvent,omitempty"` -} - // WorkloadoptimizationV1WorkloadConfigUpdateV2 defines model for workloadoptimization.v1.WorkloadConfigUpdateV2. type WorkloadoptimizationV1WorkloadConfigUpdateV2 struct { HpaConfig *WorkloadoptimizationV1HPAConfigUpdate `json:"hpaConfig,omitempty"` @@ -4597,7 +4567,10 @@ type ServiceAccountsAPIListServiceAccountsParams struct { } // ServiceAccountsAPICreateServiceAccountJSONBody defines parameters for ServiceAccountsAPICreateServiceAccount. -type ServiceAccountsAPICreateServiceAccountJSONBody = ServiceAccountsAPICreateServiceAccountRequest +type ServiceAccountsAPICreateServiceAccountJSONBody = CastaiServiceaccountsV1beta1CreateServiceAccountRequestServiceAccount + +// ServiceAccountsAPIUpdateServiceAccountJSONBody defines parameters for ServiceAccountsAPIUpdateServiceAccount. +type ServiceAccountsAPIUpdateServiceAccountJSONBody = ServiceAccountsAPIUpdateServiceAccountRequest // ServiceAccountsAPICreateServiceAccountKeyJSONBody defines parameters for ServiceAccountsAPICreateServiceAccountKey. type ServiceAccountsAPICreateServiceAccountKeyJSONBody = ServiceAccountsAPICreateServiceAccountKeyRequest @@ -4753,9 +4726,6 @@ type WorkloadOptimizationAPIGetWorkloadParams struct { ToTime *time.Time `form:"toTime,omitempty" json:"toTime,omitempty"` } -// WorkloadOptimizationAPIUpdateWorkloadJSONBody defines parameters for WorkloadOptimizationAPIUpdateWorkload. -type WorkloadOptimizationAPIUpdateWorkloadJSONBody = WorkloadoptimizationV1UpdateWorkload - // WorkloadOptimizationAPIGetInstallCmdParams defines parameters for WorkloadOptimizationAPIGetInstallCmd. type WorkloadOptimizationAPIGetInstallCmdParams struct { ClusterId string `form:"clusterId" json:"clusterId"` @@ -4863,6 +4833,9 @@ type InventoryAPIOverwriteReservationsJSONRequestBody = InventoryAPIOverwriteRes // ServiceAccountsAPICreateServiceAccountJSONRequestBody defines body for ServiceAccountsAPICreateServiceAccount for application/json ContentType. type ServiceAccountsAPICreateServiceAccountJSONRequestBody = ServiceAccountsAPICreateServiceAccountJSONBody +// ServiceAccountsAPIUpdateServiceAccountJSONRequestBody defines body for ServiceAccountsAPIUpdateServiceAccount for application/json ContentType. +type ServiceAccountsAPIUpdateServiceAccountJSONRequestBody = ServiceAccountsAPIUpdateServiceAccountJSONBody + // ServiceAccountsAPICreateServiceAccountKeyJSONRequestBody defines body for ServiceAccountsAPICreateServiceAccountKey for application/json ContentType. type ServiceAccountsAPICreateServiceAccountKeyJSONRequestBody = ServiceAccountsAPICreateServiceAccountKeyJSONBody @@ -4905,9 +4878,6 @@ type WorkloadOptimizationAPIUpdateWorkloadScalingPolicyJSONRequestBody = Workloa // WorkloadOptimizationAPIAssignScalingPolicyWorkloadsJSONRequestBody defines body for WorkloadOptimizationAPIAssignScalingPolicyWorkloads for application/json ContentType. type WorkloadOptimizationAPIAssignScalingPolicyWorkloadsJSONRequestBody = WorkloadOptimizationAPIAssignScalingPolicyWorkloadsJSONBody -// WorkloadOptimizationAPIUpdateWorkloadJSONRequestBody defines body for WorkloadOptimizationAPIUpdateWorkload for application/json ContentType. -type WorkloadOptimizationAPIUpdateWorkloadJSONRequestBody = WorkloadOptimizationAPIUpdateWorkloadJSONBody - // WorkloadOptimizationAPIUpdateWorkloadV2JSONRequestBody defines body for WorkloadOptimizationAPIUpdateWorkloadV2 for application/json ContentType. type WorkloadOptimizationAPIUpdateWorkloadV2JSONRequestBody = WorkloadOptimizationAPIUpdateWorkloadV2JSONBody diff --git a/castai/sdk/client.gen.go b/castai/sdk/client.gen.go index dfa60ec4..ea75f70f 100644 --- a/castai/sdk/client.gen.go +++ b/castai/sdk/client.gen.go @@ -404,6 +404,11 @@ type ClientInterface interface { // ServiceAccountsAPIGetServiceAccount request ServiceAccountsAPIGetServiceAccount(ctx context.Context, organizationId string, serviceAccountId string, reqEditors ...RequestEditorFn) (*http.Response, error) + // ServiceAccountsAPIUpdateServiceAccount request with any body + ServiceAccountsAPIUpdateServiceAccountWithBody(ctx context.Context, organizationId string, serviceAccountId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + ServiceAccountsAPIUpdateServiceAccount(ctx context.Context, organizationId string, serviceAccountId string, body ServiceAccountsAPIUpdateServiceAccountJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + // ServiceAccountsAPICreateServiceAccountKey request with any body ServiceAccountsAPICreateServiceAccountKeyWithBody(ctx context.Context, organizationId string, serviceAccountId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) @@ -573,11 +578,6 @@ type ClientInterface interface { // WorkloadOptimizationAPIGetWorkload request WorkloadOptimizationAPIGetWorkload(ctx context.Context, clusterId string, workloadId string, params *WorkloadOptimizationAPIGetWorkloadParams, reqEditors ...RequestEditorFn) (*http.Response, error) - // WorkloadOptimizationAPIUpdateWorkload request with any body - WorkloadOptimizationAPIUpdateWorkloadWithBody(ctx context.Context, clusterId string, workloadId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) - - WorkloadOptimizationAPIUpdateWorkload(ctx context.Context, clusterId string, workloadId string, body WorkloadOptimizationAPIUpdateWorkloadJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) - // WorkloadOptimizationAPIGetInstallCmd request WorkloadOptimizationAPIGetInstallCmd(ctx context.Context, params *WorkloadOptimizationAPIGetInstallCmdParams, reqEditors ...RequestEditorFn) (*http.Response, error) @@ -1973,6 +1973,30 @@ func (c *Client) ServiceAccountsAPIGetServiceAccount(ctx context.Context, organi return c.Client.Do(req) } +func (c *Client) ServiceAccountsAPIUpdateServiceAccountWithBody(ctx context.Context, organizationId string, serviceAccountId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewServiceAccountsAPIUpdateServiceAccountRequestWithBody(c.Server, organizationId, serviceAccountId, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) ServiceAccountsAPIUpdateServiceAccount(ctx context.Context, organizationId string, serviceAccountId string, body ServiceAccountsAPIUpdateServiceAccountJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewServiceAccountsAPIUpdateServiceAccountRequest(c.Server, organizationId, serviceAccountId, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + func (c *Client) ServiceAccountsAPICreateServiceAccountKeyWithBody(ctx context.Context, organizationId string, serviceAccountId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { req, err := NewServiceAccountsAPICreateServiceAccountKeyRequestWithBody(c.Server, organizationId, serviceAccountId, contentType, body) if err != nil { @@ -2705,30 +2729,6 @@ func (c *Client) WorkloadOptimizationAPIGetWorkload(ctx context.Context, cluster return c.Client.Do(req) } -func (c *Client) WorkloadOptimizationAPIUpdateWorkloadWithBody(ctx context.Context, clusterId string, workloadId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewWorkloadOptimizationAPIUpdateWorkloadRequestWithBody(c.Server, clusterId, workloadId, contentType, body) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) WorkloadOptimizationAPIUpdateWorkload(ctx context.Context, clusterId string, workloadId string, body WorkloadOptimizationAPIUpdateWorkloadJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewWorkloadOptimizationAPIUpdateWorkloadRequest(c.Server, clusterId, workloadId, body) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - func (c *Client) WorkloadOptimizationAPIGetInstallCmd(ctx context.Context, params *WorkloadOptimizationAPIGetInstallCmdParams, reqEditors ...RequestEditorFn) (*http.Response, error) { req, err := NewWorkloadOptimizationAPIGetInstallCmdRequest(c.Server, params) if err != nil { @@ -6718,6 +6718,60 @@ func NewServiceAccountsAPIGetServiceAccountRequest(server string, organizationId return req, nil } +// NewServiceAccountsAPIUpdateServiceAccountRequest calls the generic ServiceAccountsAPIUpdateServiceAccount builder with application/json body +func NewServiceAccountsAPIUpdateServiceAccountRequest(server string, organizationId string, serviceAccountId string, body ServiceAccountsAPIUpdateServiceAccountJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewServiceAccountsAPIUpdateServiceAccountRequestWithBody(server, organizationId, serviceAccountId, "application/json", bodyReader) +} + +// NewServiceAccountsAPIUpdateServiceAccountRequestWithBody generates requests for ServiceAccountsAPIUpdateServiceAccount with any type of body +func NewServiceAccountsAPIUpdateServiceAccountRequestWithBody(server string, organizationId string, serviceAccountId string, contentType string, body io.Reader) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithLocation("simple", false, "organizationId", runtime.ParamLocationPath, organizationId) + if err != nil { + return nil, err + } + + var pathParam1 string + + pathParam1, err = runtime.StyleParamWithLocation("simple", false, "serviceAccountId", runtime.ParamLocationPath, serviceAccountId) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/v1/organizations/%s/service-accounts/%s", pathParam0, pathParam1) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("PATCH", queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + // NewServiceAccountsAPICreateServiceAccountKeyRequest calls the generic ServiceAccountsAPICreateServiceAccountKey builder with application/json body func NewServiceAccountsAPICreateServiceAccountKeyRequest(server string, organizationId string, serviceAccountId string, body ServiceAccountsAPICreateServiceAccountKeyJSONRequestBody) (*http.Request, error) { var bodyReader io.Reader @@ -8947,60 +9001,6 @@ func NewWorkloadOptimizationAPIGetWorkloadRequest(server string, clusterId strin return req, nil } -// NewWorkloadOptimizationAPIUpdateWorkloadRequest calls the generic WorkloadOptimizationAPIUpdateWorkload builder with application/json body -func NewWorkloadOptimizationAPIUpdateWorkloadRequest(server string, clusterId string, workloadId string, body WorkloadOptimizationAPIUpdateWorkloadJSONRequestBody) (*http.Request, error) { - var bodyReader io.Reader - buf, err := json.Marshal(body) - if err != nil { - return nil, err - } - bodyReader = bytes.NewReader(buf) - return NewWorkloadOptimizationAPIUpdateWorkloadRequestWithBody(server, clusterId, workloadId, "application/json", bodyReader) -} - -// NewWorkloadOptimizationAPIUpdateWorkloadRequestWithBody generates requests for WorkloadOptimizationAPIUpdateWorkload with any type of body -func NewWorkloadOptimizationAPIUpdateWorkloadRequestWithBody(server string, clusterId string, workloadId string, contentType string, body io.Reader) (*http.Request, error) { - var err error - - var pathParam0 string - - pathParam0, err = runtime.StyleParamWithLocation("simple", false, "clusterId", runtime.ParamLocationPath, clusterId) - if err != nil { - return nil, err - } - - var pathParam1 string - - pathParam1, err = runtime.StyleParamWithLocation("simple", false, "workloadId", runtime.ParamLocationPath, workloadId) - if err != nil { - return nil, err - } - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/v1/workload-autoscaling/clusters/%s/workloads/%s", pathParam0, pathParam1) - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("PUT", queryURL.String(), body) - if err != nil { - return nil, err - } - - req.Header.Add("Content-Type", contentType) - - return req, nil -} - // NewWorkloadOptimizationAPIGetInstallCmdRequest generates requests for WorkloadOptimizationAPIGetInstallCmd func NewWorkloadOptimizationAPIGetInstallCmdRequest(server string, params *WorkloadOptimizationAPIGetInstallCmdParams) (*http.Request, error) { var err error @@ -9545,6 +9545,11 @@ type ClientWithResponsesInterface interface { // ServiceAccountsAPIGetServiceAccount request ServiceAccountsAPIGetServiceAccountWithResponse(ctx context.Context, organizationId string, serviceAccountId string) (*ServiceAccountsAPIGetServiceAccountResponse, error) + // ServiceAccountsAPIUpdateServiceAccount request with any body + ServiceAccountsAPIUpdateServiceAccountWithBodyWithResponse(ctx context.Context, organizationId string, serviceAccountId string, contentType string, body io.Reader) (*ServiceAccountsAPIUpdateServiceAccountResponse, error) + + ServiceAccountsAPIUpdateServiceAccountWithResponse(ctx context.Context, organizationId string, serviceAccountId string, body ServiceAccountsAPIUpdateServiceAccountJSONRequestBody) (*ServiceAccountsAPIUpdateServiceAccountResponse, error) + // ServiceAccountsAPICreateServiceAccountKey request with any body ServiceAccountsAPICreateServiceAccountKeyWithBodyWithResponse(ctx context.Context, organizationId string, serviceAccountId string, contentType string, body io.Reader) (*ServiceAccountsAPICreateServiceAccountKeyResponse, error) @@ -9714,11 +9719,6 @@ type ClientWithResponsesInterface interface { // WorkloadOptimizationAPIGetWorkload request WorkloadOptimizationAPIGetWorkloadWithResponse(ctx context.Context, clusterId string, workloadId string, params *WorkloadOptimizationAPIGetWorkloadParams) (*WorkloadOptimizationAPIGetWorkloadResponse, error) - // WorkloadOptimizationAPIUpdateWorkload request with any body - WorkloadOptimizationAPIUpdateWorkloadWithBodyWithResponse(ctx context.Context, clusterId string, workloadId string, contentType string, body io.Reader) (*WorkloadOptimizationAPIUpdateWorkloadResponse, error) - - WorkloadOptimizationAPIUpdateWorkloadWithResponse(ctx context.Context, clusterId string, workloadId string, body WorkloadOptimizationAPIUpdateWorkloadJSONRequestBody) (*WorkloadOptimizationAPIUpdateWorkloadResponse, error) - // WorkloadOptimizationAPIGetInstallCmd request WorkloadOptimizationAPIGetInstallCmdWithResponse(ctx context.Context, params *WorkloadOptimizationAPIGetInstallCmdParams) (*WorkloadOptimizationAPIGetInstallCmdResponse, error) @@ -12263,6 +12263,36 @@ func (r ServiceAccountsAPIGetServiceAccountResponse) GetBody() []byte { // TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 +type ServiceAccountsAPIUpdateServiceAccountResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *CastaiServiceaccountsV1beta1UpdateServiceAccountResponse +} + +// Status returns HTTPResponse.Status +func (r ServiceAccountsAPIUpdateServiceAccountResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r ServiceAccountsAPIUpdateServiceAccountResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 +// Body returns body of byte array +func (r ServiceAccountsAPIUpdateServiceAccountResponse) GetBody() []byte { + return r.Body +} + +// TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 + type ServiceAccountsAPICreateServiceAccountKeyResponse struct { Body []byte HTTPResponse *http.Response @@ -13671,36 +13701,6 @@ func (r WorkloadOptimizationAPIGetWorkloadResponse) GetBody() []byte { // TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 -type WorkloadOptimizationAPIUpdateWorkloadResponse struct { - Body []byte - HTTPResponse *http.Response - JSON200 *WorkloadoptimizationV1UpdateWorkloadResponse -} - -// Status returns HTTPResponse.Status -func (r WorkloadOptimizationAPIUpdateWorkloadResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r WorkloadOptimizationAPIUpdateWorkloadResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -// TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 -// Body returns body of byte array -func (r WorkloadOptimizationAPIUpdateWorkloadResponse) GetBody() []byte { - return r.Body -} - -// TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 - type WorkloadOptimizationAPIGetInstallCmdResponse struct { Body []byte HTTPResponse *http.Response @@ -14824,6 +14824,23 @@ func (c *ClientWithResponses) ServiceAccountsAPIGetServiceAccountWithResponse(ct return ParseServiceAccountsAPIGetServiceAccountResponse(rsp) } +// ServiceAccountsAPIUpdateServiceAccountWithBodyWithResponse request with arbitrary body returning *ServiceAccountsAPIUpdateServiceAccountResponse +func (c *ClientWithResponses) ServiceAccountsAPIUpdateServiceAccountWithBodyWithResponse(ctx context.Context, organizationId string, serviceAccountId string, contentType string, body io.Reader) (*ServiceAccountsAPIUpdateServiceAccountResponse, error) { + rsp, err := c.ServiceAccountsAPIUpdateServiceAccountWithBody(ctx, organizationId, serviceAccountId, contentType, body) + if err != nil { + return nil, err + } + return ParseServiceAccountsAPIUpdateServiceAccountResponse(rsp) +} + +func (c *ClientWithResponses) ServiceAccountsAPIUpdateServiceAccountWithResponse(ctx context.Context, organizationId string, serviceAccountId string, body ServiceAccountsAPIUpdateServiceAccountJSONRequestBody) (*ServiceAccountsAPIUpdateServiceAccountResponse, error) { + rsp, err := c.ServiceAccountsAPIUpdateServiceAccount(ctx, organizationId, serviceAccountId, body) + if err != nil { + return nil, err + } + return ParseServiceAccountsAPIUpdateServiceAccountResponse(rsp) +} + // ServiceAccountsAPICreateServiceAccountKeyWithBodyWithResponse request with arbitrary body returning *ServiceAccountsAPICreateServiceAccountKeyResponse func (c *ClientWithResponses) ServiceAccountsAPICreateServiceAccountKeyWithBodyWithResponse(ctx context.Context, organizationId string, serviceAccountId string, contentType string, body io.Reader) (*ServiceAccountsAPICreateServiceAccountKeyResponse, error) { rsp, err := c.ServiceAccountsAPICreateServiceAccountKeyWithBody(ctx, organizationId, serviceAccountId, contentType, body) @@ -15359,23 +15376,6 @@ func (c *ClientWithResponses) WorkloadOptimizationAPIGetWorkloadWithResponse(ctx return ParseWorkloadOptimizationAPIGetWorkloadResponse(rsp) } -// WorkloadOptimizationAPIUpdateWorkloadWithBodyWithResponse request with arbitrary body returning *WorkloadOptimizationAPIUpdateWorkloadResponse -func (c *ClientWithResponses) WorkloadOptimizationAPIUpdateWorkloadWithBodyWithResponse(ctx context.Context, clusterId string, workloadId string, contentType string, body io.Reader) (*WorkloadOptimizationAPIUpdateWorkloadResponse, error) { - rsp, err := c.WorkloadOptimizationAPIUpdateWorkloadWithBody(ctx, clusterId, workloadId, contentType, body) - if err != nil { - return nil, err - } - return ParseWorkloadOptimizationAPIUpdateWorkloadResponse(rsp) -} - -func (c *ClientWithResponses) WorkloadOptimizationAPIUpdateWorkloadWithResponse(ctx context.Context, clusterId string, workloadId string, body WorkloadOptimizationAPIUpdateWorkloadJSONRequestBody) (*WorkloadOptimizationAPIUpdateWorkloadResponse, error) { - rsp, err := c.WorkloadOptimizationAPIUpdateWorkload(ctx, clusterId, workloadId, body) - if err != nil { - return nil, err - } - return ParseWorkloadOptimizationAPIUpdateWorkloadResponse(rsp) -} - // WorkloadOptimizationAPIGetInstallCmdWithResponse request returning *WorkloadOptimizationAPIGetInstallCmdResponse func (c *ClientWithResponses) WorkloadOptimizationAPIGetInstallCmdWithResponse(ctx context.Context, params *WorkloadOptimizationAPIGetInstallCmdParams) (*WorkloadOptimizationAPIGetInstallCmdResponse, error) { rsp, err := c.WorkloadOptimizationAPIGetInstallCmd(ctx, params) @@ -17601,6 +17601,32 @@ func ParseServiceAccountsAPIGetServiceAccountResponse(rsp *http.Response) (*Serv return response, nil } +// ParseServiceAccountsAPIUpdateServiceAccountResponse parses an HTTP response from a ServiceAccountsAPIUpdateServiceAccountWithResponse call +func ParseServiceAccountsAPIUpdateServiceAccountResponse(rsp *http.Response) (*ServiceAccountsAPIUpdateServiceAccountResponse, error) { + bodyBytes, err := ioutil.ReadAll(rsp.Body) + defer rsp.Body.Close() + if err != nil { + return nil, err + } + + response := &ServiceAccountsAPIUpdateServiceAccountResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest CastaiServiceaccountsV1beta1UpdateServiceAccountResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + } + + return response, nil +} + // ParseServiceAccountsAPICreateServiceAccountKeyResponse parses an HTTP response from a ServiceAccountsAPICreateServiceAccountKeyWithResponse call func ParseServiceAccountsAPICreateServiceAccountKeyResponse(rsp *http.Response) (*ServiceAccountsAPICreateServiceAccountKeyResponse, error) { bodyBytes, err := ioutil.ReadAll(rsp.Body) @@ -18800,32 +18826,6 @@ func ParseWorkloadOptimizationAPIGetWorkloadResponse(rsp *http.Response) (*Workl return response, nil } -// ParseWorkloadOptimizationAPIUpdateWorkloadResponse parses an HTTP response from a WorkloadOptimizationAPIUpdateWorkloadWithResponse call -func ParseWorkloadOptimizationAPIUpdateWorkloadResponse(rsp *http.Response) (*WorkloadOptimizationAPIUpdateWorkloadResponse, error) { - bodyBytes, err := ioutil.ReadAll(rsp.Body) - defer rsp.Body.Close() - if err != nil { - return nil, err - } - - response := &WorkloadOptimizationAPIUpdateWorkloadResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest WorkloadoptimizationV1UpdateWorkloadResponse - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON200 = &dest - - } - - return response, nil -} - // ParseWorkloadOptimizationAPIGetInstallCmdResponse parses an HTTP response from a WorkloadOptimizationAPIGetInstallCmdWithResponse call func ParseWorkloadOptimizationAPIGetInstallCmdResponse(rsp *http.Response) (*WorkloadOptimizationAPIGetInstallCmdResponse, error) { bodyBytes, err := ioutil.ReadAll(rsp.Body) diff --git a/castai/sdk/mock/client.go b/castai/sdk/mock/client.go index cf8170f2..476b0b37 100644 --- a/castai/sdk/mock/client.go +++ b/castai/sdk/mock/client.go @@ -2835,6 +2835,26 @@ func (mr *MockClientInterfaceMockRecorder) ServiceAccountsAPIListServiceAccounts return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ServiceAccountsAPIListServiceAccounts", reflect.TypeOf((*MockClientInterface)(nil).ServiceAccountsAPIListServiceAccounts), varargs...) } +// ServiceAccountsAPIUpdateServiceAccount mocks base method. +func (m *MockClientInterface) ServiceAccountsAPIUpdateServiceAccount(ctx context.Context, organizationId, serviceAccountId string, body sdk.ServiceAccountsAPIUpdateServiceAccountJSONRequestBody, reqEditors ...sdk.RequestEditorFn) (*http.Response, error) { + m.ctrl.T.Helper() + varargs := []interface{}{ctx, organizationId, serviceAccountId, body} + for _, a := range reqEditors { + varargs = append(varargs, a) + } + ret := m.ctrl.Call(m, "ServiceAccountsAPIUpdateServiceAccount", varargs...) + ret0, _ := ret[0].(*http.Response) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// ServiceAccountsAPIUpdateServiceAccount indicates an expected call of ServiceAccountsAPIUpdateServiceAccount. +func (mr *MockClientInterfaceMockRecorder) ServiceAccountsAPIUpdateServiceAccount(ctx, organizationId, serviceAccountId, body interface{}, reqEditors ...interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + varargs := append([]interface{}{ctx, organizationId, serviceAccountId, body}, reqEditors...) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ServiceAccountsAPIUpdateServiceAccount", reflect.TypeOf((*MockClientInterface)(nil).ServiceAccountsAPIUpdateServiceAccount), varargs...) +} + // ServiceAccountsAPIUpdateServiceAccountKey mocks base method. func (m *MockClientInterface) ServiceAccountsAPIUpdateServiceAccountKey(ctx context.Context, organizationId, serviceAccountId, keyId string, params *sdk.ServiceAccountsAPIUpdateServiceAccountKeyParams, reqEditors ...sdk.RequestEditorFn) (*http.Response, error) { m.ctrl.T.Helper() @@ -2855,6 +2875,26 @@ func (mr *MockClientInterfaceMockRecorder) ServiceAccountsAPIUpdateServiceAccoun return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ServiceAccountsAPIUpdateServiceAccountKey", reflect.TypeOf((*MockClientInterface)(nil).ServiceAccountsAPIUpdateServiceAccountKey), varargs...) } +// ServiceAccountsAPIUpdateServiceAccountWithBody mocks base method. +func (m *MockClientInterface) ServiceAccountsAPIUpdateServiceAccountWithBody(ctx context.Context, organizationId, serviceAccountId, contentType string, body io.Reader, reqEditors ...sdk.RequestEditorFn) (*http.Response, error) { + m.ctrl.T.Helper() + varargs := []interface{}{ctx, organizationId, serviceAccountId, contentType, body} + for _, a := range reqEditors { + varargs = append(varargs, a) + } + ret := m.ctrl.Call(m, "ServiceAccountsAPIUpdateServiceAccountWithBody", varargs...) + ret0, _ := ret[0].(*http.Response) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// ServiceAccountsAPIUpdateServiceAccountWithBody indicates an expected call of ServiceAccountsAPIUpdateServiceAccountWithBody. +func (mr *MockClientInterfaceMockRecorder) ServiceAccountsAPIUpdateServiceAccountWithBody(ctx, organizationId, serviceAccountId, contentType, body interface{}, reqEditors ...interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + varargs := append([]interface{}{ctx, organizationId, serviceAccountId, contentType, body}, reqEditors...) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ServiceAccountsAPIUpdateServiceAccountWithBody", reflect.TypeOf((*MockClientInterface)(nil).ServiceAccountsAPIUpdateServiceAccountWithBody), varargs...) +} + // UsersAPIAddUserToOrganization mocks base method. func (m *MockClientInterface) UsersAPIAddUserToOrganization(ctx context.Context, organizationId string, body sdk.UsersAPIAddUserToOrganizationJSONRequestBody, reqEditors ...sdk.RequestEditorFn) (*http.Response, error) { m.ctrl.T.Helper() @@ -3615,26 +3655,6 @@ func (mr *MockClientInterfaceMockRecorder) WorkloadOptimizationAPIListWorkloads( return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "WorkloadOptimizationAPIListWorkloads", reflect.TypeOf((*MockClientInterface)(nil).WorkloadOptimizationAPIListWorkloads), varargs...) } -// WorkloadOptimizationAPIUpdateWorkload mocks base method. -func (m *MockClientInterface) WorkloadOptimizationAPIUpdateWorkload(ctx context.Context, clusterId, workloadId string, body sdk.WorkloadOptimizationAPIUpdateWorkloadJSONRequestBody, reqEditors ...sdk.RequestEditorFn) (*http.Response, error) { - m.ctrl.T.Helper() - varargs := []interface{}{ctx, clusterId, workloadId, body} - for _, a := range reqEditors { - varargs = append(varargs, a) - } - ret := m.ctrl.Call(m, "WorkloadOptimizationAPIUpdateWorkload", varargs...) - ret0, _ := ret[0].(*http.Response) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// WorkloadOptimizationAPIUpdateWorkload indicates an expected call of WorkloadOptimizationAPIUpdateWorkload. -func (mr *MockClientInterfaceMockRecorder) WorkloadOptimizationAPIUpdateWorkload(ctx, clusterId, workloadId, body interface{}, reqEditors ...interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - varargs := append([]interface{}{ctx, clusterId, workloadId, body}, reqEditors...) - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "WorkloadOptimizationAPIUpdateWorkload", reflect.TypeOf((*MockClientInterface)(nil).WorkloadOptimizationAPIUpdateWorkload), varargs...) -} - // WorkloadOptimizationAPIUpdateWorkloadScalingPolicy mocks base method. func (m *MockClientInterface) WorkloadOptimizationAPIUpdateWorkloadScalingPolicy(ctx context.Context, clusterId, policyId string, body sdk.WorkloadOptimizationAPIUpdateWorkloadScalingPolicyJSONRequestBody, reqEditors ...sdk.RequestEditorFn) (*http.Response, error) { m.ctrl.T.Helper() @@ -3715,26 +3735,6 @@ func (mr *MockClientInterfaceMockRecorder) WorkloadOptimizationAPIUpdateWorkload return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "WorkloadOptimizationAPIUpdateWorkloadV2WithBody", reflect.TypeOf((*MockClientInterface)(nil).WorkloadOptimizationAPIUpdateWorkloadV2WithBody), varargs...) } -// WorkloadOptimizationAPIUpdateWorkloadWithBody mocks base method. -func (m *MockClientInterface) WorkloadOptimizationAPIUpdateWorkloadWithBody(ctx context.Context, clusterId, workloadId, contentType string, body io.Reader, reqEditors ...sdk.RequestEditorFn) (*http.Response, error) { - m.ctrl.T.Helper() - varargs := []interface{}{ctx, clusterId, workloadId, contentType, body} - for _, a := range reqEditors { - varargs = append(varargs, a) - } - ret := m.ctrl.Call(m, "WorkloadOptimizationAPIUpdateWorkloadWithBody", varargs...) - ret0, _ := ret[0].(*http.Response) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// WorkloadOptimizationAPIUpdateWorkloadWithBody indicates an expected call of WorkloadOptimizationAPIUpdateWorkloadWithBody. -func (mr *MockClientInterfaceMockRecorder) WorkloadOptimizationAPIUpdateWorkloadWithBody(ctx, clusterId, workloadId, contentType, body interface{}, reqEditors ...interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - varargs := append([]interface{}{ctx, clusterId, workloadId, contentType, body}, reqEditors...) - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "WorkloadOptimizationAPIUpdateWorkloadWithBody", reflect.TypeOf((*MockClientInterface)(nil).WorkloadOptimizationAPIUpdateWorkloadWithBody), varargs...) -} - // MockClientWithResponsesInterface is a mock of ClientWithResponsesInterface interface. type MockClientWithResponsesInterface struct { ctrl *gomock.Controller @@ -5843,6 +5843,36 @@ func (mr *MockClientWithResponsesInterfaceMockRecorder) ServiceAccountsAPIUpdate return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ServiceAccountsAPIUpdateServiceAccountKeyWithResponse", reflect.TypeOf((*MockClientWithResponsesInterface)(nil).ServiceAccountsAPIUpdateServiceAccountKeyWithResponse), ctx, organizationId, serviceAccountId, keyId, params) } +// ServiceAccountsAPIUpdateServiceAccountWithBodyWithResponse mocks base method. +func (m *MockClientWithResponsesInterface) ServiceAccountsAPIUpdateServiceAccountWithBodyWithResponse(ctx context.Context, organizationId, serviceAccountId, contentType string, body io.Reader) (*sdk.ServiceAccountsAPIUpdateServiceAccountResponse, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "ServiceAccountsAPIUpdateServiceAccountWithBodyWithResponse", ctx, organizationId, serviceAccountId, contentType, body) + ret0, _ := ret[0].(*sdk.ServiceAccountsAPIUpdateServiceAccountResponse) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// ServiceAccountsAPIUpdateServiceAccountWithBodyWithResponse indicates an expected call of ServiceAccountsAPIUpdateServiceAccountWithBodyWithResponse. +func (mr *MockClientWithResponsesInterfaceMockRecorder) ServiceAccountsAPIUpdateServiceAccountWithBodyWithResponse(ctx, organizationId, serviceAccountId, contentType, body interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ServiceAccountsAPIUpdateServiceAccountWithBodyWithResponse", reflect.TypeOf((*MockClientWithResponsesInterface)(nil).ServiceAccountsAPIUpdateServiceAccountWithBodyWithResponse), ctx, organizationId, serviceAccountId, contentType, body) +} + +// ServiceAccountsAPIUpdateServiceAccountWithResponse mocks base method. +func (m *MockClientWithResponsesInterface) ServiceAccountsAPIUpdateServiceAccountWithResponse(ctx context.Context, organizationId, serviceAccountId string, body sdk.ServiceAccountsAPIUpdateServiceAccountJSONRequestBody) (*sdk.ServiceAccountsAPIUpdateServiceAccountResponse, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "ServiceAccountsAPIUpdateServiceAccountWithResponse", ctx, organizationId, serviceAccountId, body) + ret0, _ := ret[0].(*sdk.ServiceAccountsAPIUpdateServiceAccountResponse) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// ServiceAccountsAPIUpdateServiceAccountWithResponse indicates an expected call of ServiceAccountsAPIUpdateServiceAccountWithResponse. +func (mr *MockClientWithResponsesInterfaceMockRecorder) ServiceAccountsAPIUpdateServiceAccountWithResponse(ctx, organizationId, serviceAccountId, body interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ServiceAccountsAPIUpdateServiceAccountWithResponse", reflect.TypeOf((*MockClientWithResponsesInterface)(nil).ServiceAccountsAPIUpdateServiceAccountWithResponse), ctx, organizationId, serviceAccountId, body) +} + // UsersAPIAddUserToOrganizationWithBodyWithResponse mocks base method. func (m *MockClientWithResponsesInterface) UsersAPIAddUserToOrganizationWithBodyWithResponse(ctx context.Context, organizationId, contentType string, body io.Reader) (*sdk.UsersAPIAddUserToOrganizationResponse, error) { m.ctrl.T.Helper() @@ -6473,36 +6503,6 @@ func (mr *MockClientWithResponsesInterfaceMockRecorder) WorkloadOptimizationAPIU return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "WorkloadOptimizationAPIUpdateWorkloadV2WithResponse", reflect.TypeOf((*MockClientWithResponsesInterface)(nil).WorkloadOptimizationAPIUpdateWorkloadV2WithResponse), ctx, clusterId, workloadId, body) } -// WorkloadOptimizationAPIUpdateWorkloadWithBodyWithResponse mocks base method. -func (m *MockClientWithResponsesInterface) WorkloadOptimizationAPIUpdateWorkloadWithBodyWithResponse(ctx context.Context, clusterId, workloadId, contentType string, body io.Reader) (*sdk.WorkloadOptimizationAPIUpdateWorkloadResponse, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "WorkloadOptimizationAPIUpdateWorkloadWithBodyWithResponse", ctx, clusterId, workloadId, contentType, body) - ret0, _ := ret[0].(*sdk.WorkloadOptimizationAPIUpdateWorkloadResponse) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// WorkloadOptimizationAPIUpdateWorkloadWithBodyWithResponse indicates an expected call of WorkloadOptimizationAPIUpdateWorkloadWithBodyWithResponse. -func (mr *MockClientWithResponsesInterfaceMockRecorder) WorkloadOptimizationAPIUpdateWorkloadWithBodyWithResponse(ctx, clusterId, workloadId, contentType, body interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "WorkloadOptimizationAPIUpdateWorkloadWithBodyWithResponse", reflect.TypeOf((*MockClientWithResponsesInterface)(nil).WorkloadOptimizationAPIUpdateWorkloadWithBodyWithResponse), ctx, clusterId, workloadId, contentType, body) -} - -// WorkloadOptimizationAPIUpdateWorkloadWithResponse mocks base method. -func (m *MockClientWithResponsesInterface) WorkloadOptimizationAPIUpdateWorkloadWithResponse(ctx context.Context, clusterId, workloadId string, body sdk.WorkloadOptimizationAPIUpdateWorkloadJSONRequestBody) (*sdk.WorkloadOptimizationAPIUpdateWorkloadResponse, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "WorkloadOptimizationAPIUpdateWorkloadWithResponse", ctx, clusterId, workloadId, body) - ret0, _ := ret[0].(*sdk.WorkloadOptimizationAPIUpdateWorkloadResponse) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// WorkloadOptimizationAPIUpdateWorkloadWithResponse indicates an expected call of WorkloadOptimizationAPIUpdateWorkloadWithResponse. -func (mr *MockClientWithResponsesInterfaceMockRecorder) WorkloadOptimizationAPIUpdateWorkloadWithResponse(ctx, clusterId, workloadId, body interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "WorkloadOptimizationAPIUpdateWorkloadWithResponse", reflect.TypeOf((*MockClientWithResponsesInterface)(nil).WorkloadOptimizationAPIUpdateWorkloadWithResponse), ctx, clusterId, workloadId, body) -} - // MockResponse is a mock of Response interface. type MockResponse struct { ctrl *gomock.Controller From 62390bbf99764f50b51dd50a5a33c8a88559608f Mon Sep 17 00:00:00 2001 From: radekska Date: Mon, 9 Dec 2024 09:10:07 +0100 Subject: [PATCH 10/24] wip --- castai/resource_service_account.go | 44 +++++++++++++++++++++++-- castai/resource_service_account_test.go | 13 ++++---- docs/resources/service_account.md | 12 +++---- 3 files changed, 52 insertions(+), 17 deletions(-) diff --git a/castai/resource_service_account.go b/castai/resource_service_account.go index 91ea5567..8c2db17b 100644 --- a/castai/resource_service_account.go +++ b/castai/resource_service_account.go @@ -29,6 +29,7 @@ func resourceServiceAccount() *schema.Resource { return &schema.Resource{ CreateContext: resourceServiceAccountCreate, ReadContext: resourceServiceAccountRead, + UpdateContext: resourceServiceAccountUpdate, DeleteContext: resourceServiceAccountDelete, Description: "Service Account resource allows managing CAST AI service accounts.", @@ -48,13 +49,11 @@ func resourceServiceAccount() *schema.Resource { FieldServiceAccountName: { Type: schema.TypeString, Required: true, - ForceNew: true, Description: "Name of the service account.", }, FieldServiceAccountDescription: { Type: schema.TypeString, Optional: true, - ForceNew: true, Description: "Description of the service account.", }, FieldServiceAccountEmail: { @@ -162,6 +161,47 @@ func resourceServiceAccountCreate(ctx context.Context, data *schema.ResourceData return resourceServiceAccountRead(ctx, data, meta) } +func resourceServiceAccountUpdate(ctx context.Context, data *schema.ResourceData, meta interface{}) diag.Diagnostics { + client := meta.(*ProviderConfig).api + + serviceAccountID := data.Id() + organizationID := data.Get(FieldServiceAccountOrganizationID).(string) + name := data.Get(FieldServiceAccountName).(string) + description := data.Get(FieldServiceAccountDescription).(string) + + tflog.Info(ctx, "updating service account", map[string]interface{}{ + "resource_id": serviceAccountID, + "name": name, + "description": description, + "organization_id": organizationID, + }) + + resp, err := client.ServiceAccountsAPIUpdateServiceAccountWithResponse( + ctx, + organizationID, + serviceAccountID, + sdk.ServiceAccountsAPIUpdateServiceAccountRequest{ + ServiceAccount: sdk.CastaiServiceaccountsV1beta1UpdateServiceAccountRequestServiceAccount{ + Name: name, + Description: &description, + }, + }, + ) + + if err := sdk.CheckOKResponse(resp, err); err != nil { + return diag.Errorf("updating service account: %v", err) + } + + tflog.Info(ctx, "created service account", map[string]interface{}{ + "resource_id": serviceAccountID, + "organization_id": organizationID, + "name": name, + "description": description, + }) + + return resourceServiceAccountRead(ctx, data, meta) +} + func resourceServiceAccountDelete(ctx context.Context, data *schema.ResourceData, meta interface{}) diag.Diagnostics { client := meta.(*ProviderConfig).api organizationID := data.Get(FieldServiceAccountOrganizationID).(string) diff --git a/castai/resource_service_account_test.go b/castai/resource_service_account_test.go index 36e6c938..d7e47571 100644 --- a/castai/resource_service_account_test.go +++ b/castai/resource_service_account_test.go @@ -42,7 +42,7 @@ func TestServiceAccountReadContext(t *testing.T) { r.Equal("service account ID is not set", result[0].Summary) }) - t.Run("when ServiceAccountAPI respond with 404 then return error", func(t *testing.T) { + t.Run("when ServiceAccountAPI respond with 404 then remove form the state gracefully", func(t *testing.T) { r := require.New(t) mockClient := mock_sdk.NewMockClientInterface(gomock.NewController(t)) @@ -72,10 +72,9 @@ func TestServiceAccountReadContext(t *testing.T) { result := resource.ReadContext(ctx, data, provider) - r.NotNil(result) - r.True(result.HasError()) - r.Len(result, 1) - r.Equal("getting service account: service account [b11f5945-22ca-4101-a86e-d6e37f44a415] not found", result[0].Summary) + r.Nil(result) + r.False(result.HasError()) + r.Empty(data.Id()) }) t.Run("when ServiceAccountAPI respond with 500 then return error", func(t *testing.T) { @@ -212,8 +211,8 @@ func TestServiceAccountCreateContext(t *testing.T) { ServiceAccountsAPICreateServiceAccount(gomock.Any(), organizationID, gomock.Any()). DoAndReturn(func(_ context.Context, orgID string, req sdk.ServiceAccountsAPICreateServiceAccountJSONRequestBody) (*http.Response, error) { r.Equal(organizationID, orgID) - r.Equal(name, req.ServiceAccount.Name) - r.Equal(description, *req.ServiceAccount.Description) + r.Equal(name, req.Name) + r.Equal(description, *req.Description) resp := &sdk.CastaiServiceaccountsV1beta1CreateServiceAccountResponse{ Id: &serviceAccountID, diff --git a/docs/resources/service_account.md b/docs/resources/service_account.md index 7f5fb071..eec7cd30 100644 --- a/docs/resources/service_account.md +++ b/docs/resources/service_account.md @@ -13,14 +13,10 @@ Service Account resource allows managing CAST AI service accounts. ## Example Usage ```terraform -resource "castai_serv" "service_account" { - name = "aad_connection" - email_domain = "aad_connection@test.com" - aad { - client_id = azuread_application.castai_sso.client_id - client_secret = azuread_application_password.castai_sso.value - ad_domain = azuread_application.castai_sso.publisher_domain - } +resource "castai_service_account" "service_account" { + organization_id = organization.id + name = "service-account-name" + description = "service account description" } ``` From 81166771f4f22a7f6aced59eb50b52ff80c7f74c Mon Sep 17 00:00:00 2001 From: radekska Date: Mon, 9 Dec 2024 09:17:20 +0100 Subject: [PATCH 11/24] wip --- castai/resource_service_account_test.go | 86 ++++++++++++++++++++++++- 1 file changed, 83 insertions(+), 3 deletions(-) diff --git a/castai/resource_service_account_test.go b/castai/resource_service_account_test.go index d7e47571..f951b10b 100644 --- a/castai/resource_service_account_test.go +++ b/castai/resource_service_account_test.go @@ -438,13 +438,10 @@ func TestServiceAccountDeleteContext(t *testing.T) { organizationID := "4e4cd9eb-82eb-407e-a926-e5fef81cab50" serviceAccountID := "4e4cd9eb-82eb-407e-a926-e5fef81cab51" - body := io.NopCloser(bytes.NewReader([]byte("mock error response"))) - mockClient.EXPECT(). ServiceAccountsAPIDeleteServiceAccount(gomock.Any(), organizationID, gomock.Any()). Return(&http.Response{ StatusCode: http.StatusNoContent, - Body: body, }, nil) resource := resourceServiceAccount() @@ -467,3 +464,86 @@ func TestServiceAccountDeleteContext(t *testing.T) { r.Empty(data.Get(FieldServiceAccountAuthor)) }) } + +func TestServiceAccountUpdateContext(t *testing.T) { + t.Run("when ServiceAccountsAPI responds with an error then return error", func(t *testing.T) { + r := require.New(t) + mockClient := mock_sdk.NewMockClientInterface(gomock.NewController(t)) + ctx := context.Background() + provider := &ProviderConfig{ + api: &sdk.ClientWithResponses{ + ClientInterface: mockClient, + }, + } + + organizationID := "4e4cd9eb-82eb-407e-a926-e5fef81cab50" + serviceAccountID := "4e4cd9eb-82eb-407e-a926-e5fef81cab51" + + + mockClient.EXPECT(). + ServiceAccountsAPIUpdateServiceAccount(gomock.Any(), organizationID, serviceAccountID, gomock.Any()). + Return(nil, fmt.Errorf("mock network error")) + + resource := resourceServiceAccount() + stateValue := cty.ObjectVal(map[string]cty.Value{ + "organization_id": cty.StringVal(organizationID), + "name": cty.StringVal("new name"), + "description": cty.StringVal("new description"), + }) + state := terraform.NewInstanceStateShimmedFromValue(stateValue, 0) + state.ID = serviceAccountID + data := resource.Data(state) + + result := resource.UpdateContext(ctx, data, provider) + + r.NotNil(result) + r.True(result.HasError()) + r.Len(result, 1) + r.Equal("updating service account: mock network error", result[0].Summary) + }) + + t.Run("when ServiceAccountsAPI responds with non-200 status then return error", func(t *testing.T) { + r := require.New(t) + mockClient := mock_sdk.NewMockClientInterface(gomock.NewController(t)) + ctx := context.Background() + provider := &ProviderConfig{ + api: &sdk.ClientWithResponses{ + ClientInterface: mockClient, + }, + } + + organizationID := "4e4cd9eb-82eb-407e-a926-e5fef81cab50" + serviceAccountID := "4e4cd9eb-82eb-407e-a926-e5fef81cab51" + + body := io.NopCloser(bytes.NewReader([]byte("mock error response"))) + + mockClient.EXPECT(). + ServiceAccountsAPIUpdateServiceAccount(gomock.Any(), organizationID, serviceAccountID, gomock.Any()). + Return(&http.Response{ + StatusCode: http.StatusInternalServerError, + Body: body, + }, nil) + + resource := resourceServiceAccount() + stateValue := cty.ObjectVal(map[string]cty.Value{ + "organization_id": cty.StringVal(organizationID), + "name": cty.StringVal("new name"), + "description": cty.StringVal("new description"), + }) + state := terraform.NewInstanceStateShimmedFromValue(stateValue, 0) + state.ID = serviceAccountID + data := resource.Data(state) + + result := resource.UpdateContext(ctx, data, provider) + + r.NotNil(result) + r.True(result.HasError()) + r.Len(result, 1) + r.Equal("updating service account: expected status code 200, received: status=500 body=mock error response", result[0].Summary) + }) + + t.Run("when ServiceAccountsAPI responds with 200 then return nil", func(t *testing.T) { + // r := require.New(t) + // mockClient := mock_sdk.NewMockClientInterface(gomock.NewController(t)) + }) +} From 2bea5058096d283c6daa73528a5666e108423d6a Mon Sep 17 00:00:00 2001 From: radekska Date: Mon, 9 Dec 2024 09:38:42 +0100 Subject: [PATCH 12/24] done --- castai/resource_service_account_test.go | 67 ++++++++++++++++++- .../castai_service_account/resource.tf | 4 +- 2 files changed, 66 insertions(+), 5 deletions(-) diff --git a/castai/resource_service_account_test.go b/castai/resource_service_account_test.go index f951b10b..62ab2b31 100644 --- a/castai/resource_service_account_test.go +++ b/castai/resource_service_account_test.go @@ -479,7 +479,6 @@ func TestServiceAccountUpdateContext(t *testing.T) { organizationID := "4e4cd9eb-82eb-407e-a926-e5fef81cab50" serviceAccountID := "4e4cd9eb-82eb-407e-a926-e5fef81cab51" - mockClient.EXPECT(). ServiceAccountsAPIUpdateServiceAccount(gomock.Any(), organizationID, serviceAccountID, gomock.Any()). Return(nil, fmt.Errorf("mock network error")) @@ -543,7 +542,69 @@ func TestServiceAccountUpdateContext(t *testing.T) { }) t.Run("when ServiceAccountsAPI responds with 200 then return nil", func(t *testing.T) { - // r := require.New(t) - // mockClient := mock_sdk.NewMockClientInterface(gomock.NewController(t)) + r := require.New(t) + mockClient := mock_sdk.NewMockClientInterface(gomock.NewController(t)) + ctx := context.Background() + provider := &ProviderConfig{ + api: &sdk.ClientWithResponses{ + ClientInterface: mockClient, + }, + } + + userID := "4e4cd9eb-82eb-407e-a926-e5fef81cab49" + organizationID := "4e4cd9eb-82eb-407e-a926-e5fef81cab50" + serviceAccountID := "4e4cd9eb-82eb-407e-a926-e5fef81cab51" + name := "name" + description := "description" + + body := io.NopCloser(bytes.NewReader([]byte(`{ + "serviceAccount": { + "name": "new", + "description": "new description" + }}`))) + readBody := io.NopCloser(bytes.NewReader([]byte(fmt.Sprintf(`{ + "serviceAccount": { + "id": %q, + "name": "new", + "email": "service-account-email", + "description": "new description", + "createdAt": "2024-12-01T15:19:40.384Z", + "author": { + "id": %q, + "kind": "user", + "email": "user-email" + }, + "keys": [] + }}`, serviceAccountID,userID)))) + + mockClient.EXPECT(). + ServiceAccountsAPIUpdateServiceAccount(gomock.Any(), organizationID, serviceAccountID, gomock.Any()). + Return(&http.Response{ + StatusCode: http.StatusOK, + Body: body, + }, nil) + mockClient.EXPECT(). + ServiceAccountsAPIGetServiceAccount(gomock.Any(), organizationID, serviceAccountID). + Return(&http.Response{ + StatusCode: http.StatusOK, + Body: readBody, + Header: map[string][]string{"Content-Type": {"json"}}, + }, nil) + + resource := resourceServiceAccount() + stateValue := cty.ObjectVal(map[string]cty.Value{ + "organization_id": cty.StringVal(organizationID), + "name": cty.StringVal(name), + "description": cty.StringVal(description), + }) + state := terraform.NewInstanceStateShimmedFromValue(stateValue, 0) + state.ID = serviceAccountID + data := resource.Data(state) + + result := resource.UpdateContext(ctx, data, provider) + + r.Nil(result) + r.Equal("new", data.Get("name")) + r.Equal("new description", data.Get("description")) }) } diff --git a/examples/resources/castai_service_account/resource.tf b/examples/resources/castai_service_account/resource.tf index 9c3f4563..5caf87f5 100644 --- a/examples/resources/castai_service_account/resource.tf +++ b/examples/resources/castai_service_account/resource.tf @@ -1,5 +1,5 @@ resource "castai_service_account" "service_account" { organization_id = organization.id - name = "service-account-name" - description = "service account description" + name = "service-account-name" + description = "service account description" } From 087bbc693125926a18422576aee11fab0a2c27d4 Mon Sep 17 00:00:00 2001 From: radekska Date: Mon, 9 Dec 2024 12:15:41 +0100 Subject: [PATCH 13/24] review fixes --- castai/resource_service_account.go | 38 ++++++++++++++++++++++++++---- 1 file changed, 34 insertions(+), 4 deletions(-) diff --git a/castai/resource_service_account.go b/castai/resource_service_account.go index 8c2db17b..6928d6bb 100644 --- a/castai/resource_service_account.go +++ b/castai/resource_service_account.go @@ -2,6 +2,7 @@ package castai import ( "context" + "fmt" "net/http" "time" @@ -84,7 +85,10 @@ func resourceServiceAccountRead(ctx context.Context, data *schema.ResourceData, return diag.Errorf("service account ID is not set") } - organizationID := data.Get(FieldServiceAccountOrganizationID).(string) + organizationID, err := getOrganizationID(ctx, data, meta) + if err != nil { + return diag.FromErr(err) + } tflog.Info(ctx, "reading service account", map[string]interface{}{ "resource_id": data.Id(), @@ -132,7 +136,11 @@ func resourceServiceAccountRead(ctx context.Context, data *schema.ResourceData, func resourceServiceAccountCreate(ctx context.Context, data *schema.ResourceData, meta interface{}) diag.Diagnostics { client := meta.(*ProviderConfig).api - organizationID := data.Get(FieldServiceAccountOrganizationID).(string) + organizationID, err := getOrganizationID(ctx, data, meta) + if err != nil { + return diag.FromErr(err) + } + name := data.Get(FieldServiceAccountName).(string) description := data.Get(FieldServiceAccountDescription).(string) @@ -164,8 +172,12 @@ func resourceServiceAccountCreate(ctx context.Context, data *schema.ResourceData func resourceServiceAccountUpdate(ctx context.Context, data *schema.ResourceData, meta interface{}) diag.Diagnostics { client := meta.(*ProviderConfig).api + organizationID, err := getOrganizationID(ctx, data, meta) + if err != nil { + return diag.FromErr(err) + } + serviceAccountID := data.Id() - organizationID := data.Get(FieldServiceAccountOrganizationID).(string) name := data.Get(FieldServiceAccountName).(string) description := data.Get(FieldServiceAccountDescription).(string) @@ -204,7 +216,10 @@ func resourceServiceAccountUpdate(ctx context.Context, data *schema.ResourceData func resourceServiceAccountDelete(ctx context.Context, data *schema.ResourceData, meta interface{}) diag.Diagnostics { client := meta.(*ProviderConfig).api - organizationID := data.Get(FieldServiceAccountOrganizationID).(string) + organizationID, err := getOrganizationID(ctx, data, meta) + if err != nil { + return diag.FromErr(err) + } serviceAccountID := data.Id() tflog.Info(ctx, "deleting service account", map[string]interface{}{ @@ -248,3 +263,18 @@ func stringValue(value *string) string { } return *value } + +func getOrganizationID(ctx context.Context, data *schema.ResourceData, meta interface{}) (string, error) { + var organizationID string + var err error + + organizationID = data.Get(FieldServiceAccountOrganizationID).(string) + if organizationID == "" { + organizationID, err = getDefaultOrganizationId(ctx, meta) + if err != nil { + return "", fmt.Errorf("getting organization ID: %w", err) + } + } + + return organizationID, nil +} From bd0677a2cb67cef4d2b636f459c9713ab45225ab Mon Sep 17 00:00:00 2001 From: radekska Date: Mon, 9 Dec 2024 12:18:32 +0100 Subject: [PATCH 14/24] merge fixes --- Makefile | 3 +- castai/sdk/api.gen.go | 312 ++++++- castai/sdk/client.gen.go | 1288 +++++++++++++++++++++++++++-- docs/resources/service_account.md | 4 +- 4 files changed, 1519 insertions(+), 88 deletions(-) diff --git a/Makefile b/Makefile index 65454750..ef22e707 100644 --- a/Makefile +++ b/Makefile @@ -1,7 +1,6 @@ SHELL := /bin/bash -export API_TAGS ?= ExternalClusterAPI,PoliciesAPI,NodeConfigurationAPI,NodeTemplatesAPI,AuthTokenAPI,ScheduledRebalancingAPI,InventoryAPI,UsersAPI,OperationsAPI,EvictorAPI,SSOAPI,CommitmentsAPI,WorkloadOptimizationAPI,ServiceAccountsAPI -export API_TAGS ?= ExternalClusterAPI,PoliciesAPI,NodeConfigurationAPI,NodeTemplatesAPI,AuthTokenAPI,ScheduledRebalancingAPI,InventoryAPI,UsersAPI,OperationsAPI,EvictorAPI,SSOAPI,CommitmentsAPI,WorkloadOptimizationAPI,RbacServiceAPI +export API_TAGS ?= ExternalClusterAPI,PoliciesAPI,NodeConfigurationAPI,NodeTemplatesAPI,AuthTokenAPI,ScheduledRebalancingAPI,InventoryAPI,UsersAPI,OperationsAPI,EvictorAPI,SSOAPI,CommitmentsAPI,WorkloadOptimizationAPI,ServiceAccountsAPI,RbacServiceAPI export SWAGGER_LOCATION ?= https://api.cast.ai/v1/spec/openapi.json default: build diff --git a/castai/sdk/api.gen.go b/castai/sdk/api.gen.go index 06a18669..d2c0d3c1 100644 --- a/castai/sdk/api.gen.go +++ b/castai/sdk/api.gen.go @@ -122,6 +122,20 @@ const ( Ssd CastaiInventoryV1beta1StorageInfoDeviceType = "ssd" ) +// Defines values for CastaiRbacV1beta1MemberKind. +const ( + SERVICEACCOUNT CastaiRbacV1beta1MemberKind = "SERVICE_ACCOUNT" + USER CastaiRbacV1beta1MemberKind = "USER" +) + +// Defines values for CastaiRbacV1beta1PoliciesState. +const ( + CastaiRbacV1beta1PoliciesStateACCEPTED CastaiRbacV1beta1PoliciesState = "ACCEPTED" + CastaiRbacV1beta1PoliciesStateCREATED CastaiRbacV1beta1PoliciesState = "CREATED" + CastaiRbacV1beta1PoliciesStateFAILED CastaiRbacV1beta1PoliciesState = "FAILED" + CastaiRbacV1beta1PoliciesStateUNKNOWN CastaiRbacV1beta1PoliciesState = "UNKNOWN" +) + // Defines values for CastaiSsoV1beta1OIDCType. const ( CastaiSsoV1beta1OIDCTypeTYPEBACKCHANNEL CastaiSsoV1beta1OIDCType = "TYPE_BACK_CHANNEL" @@ -297,9 +311,9 @@ const ( // Defines values for WorkloadoptimizationV1ApplyType. const ( - DEFERRED WorkloadoptimizationV1ApplyType = "DEFERRED" - IMMEDIATE WorkloadoptimizationV1ApplyType = "IMMEDIATE" - UNKNOWN WorkloadoptimizationV1ApplyType = "UNKNOWN" + WorkloadoptimizationV1ApplyTypeDEFERRED WorkloadoptimizationV1ApplyType = "DEFERRED" + WorkloadoptimizationV1ApplyTypeIMMEDIATE WorkloadoptimizationV1ApplyType = "IMMEDIATE" + WorkloadoptimizationV1ApplyTypeUNKNOWN WorkloadoptimizationV1ApplyType = "UNKNOWN" ) // Defines values for WorkloadoptimizationV1EventType. @@ -373,6 +387,29 @@ type ExternalClusterAPIGKECreateSARequest struct { Gke *ExternalclusterV1UpdateGKEClusterParams `json:"gke,omitempty"` } +// GroupsIsTheGroupsToBeUpdated defines model for Groups_is_the_groups_to_be_updated_. +type GroupsIsTheGroupsToBeUpdated struct { + Definition CastaiRbacV1beta1UpdateGroupRequestGroupDefinition `json:"definition"` + + // Description is the description of the group. + Description *string `json:"description,omitempty"` + + // Name is the name of the group. + Name string `json:"name"` +} + +// RoleBindingIsTheRoleBindingToBeUpdated defines model for RoleBinding_is_the_role_binding_to_be_updated_. +type RoleBindingIsTheRoleBindingToBeUpdated struct { + // Definition represents the role binding definition. + Definition CastaiRbacV1beta1RoleBindingDefinition `json:"definition"` + + // Description is the description of the role binding. + Description *string `json:"description,omitempty"` + + // Name is the name of the role binding. + Name string `json:"name"` +} + // CreateServiceAccountKeyRequest is the request for creating a service account key. type ServiceAccountsAPICreateServiceAccountKeyRequest struct { // Key is the readable version of the service account key. @@ -1324,6 +1361,251 @@ type CastaiPaginationV1beta1Page struct { Limit *string `json:"limit,omitempty"` } +// CastaiRbacV1beta1Author defines model for castai.rbac.v1beta1.Author. +type CastaiRbacV1beta1Author struct { + // Email is the email of the author. + Email *string `json:"email,omitempty"` + + // ID is the unique identifier of the author. + Id *string `json:"id,omitempty"` +} + +// ClusterScope represents the resource scope of the cluster. +// Resource can be any resources inside the organization. +type CastaiRbacV1beta1ClusterScope struct { + // ID is the unique identifier of the resource. + Id string `json:"id"` +} + +// CastaiRbacV1beta1CreateGroupRequestGroup defines model for castai.rbac.v1beta1.CreateGroupRequest.Group. +type CastaiRbacV1beta1CreateGroupRequestGroup struct { + Definition CastaiRbacV1beta1CreateGroupRequestGroupDefinition `json:"definition"` + + // Description is the description of the group. + Description *string `json:"description,omitempty"` + + // Name is the name of the group. + Name string `json:"name"` +} + +// CastaiRbacV1beta1CreateGroupRequestGroupDefinition defines model for castai.rbac.v1beta1.CreateGroupRequest.GroupDefinition. +type CastaiRbacV1beta1CreateGroupRequestGroupDefinition struct { + // Members is a list of members. + Members *[]CastaiRbacV1beta1Member `json:"members,omitempty"` +} + +// CastaiRbacV1beta1CreateRoleBindingsRequestRoleBinding defines model for castai.rbac.v1beta1.CreateRoleBindingsRequest.RoleBinding. +type CastaiRbacV1beta1CreateRoleBindingsRequestRoleBinding struct { + // Definition represents the role binding definition. + Definition CastaiRbacV1beta1RoleBindingDefinition `json:"definition"` + + // Description is the description of the role binding. + Description *string `json:"description,omitempty"` + + // Name is the name of the role binding. + Name string `json:"name"` +} + +// CastaiRbacV1beta1DeleteGroupResponse defines model for castai.rbac.v1beta1.DeleteGroupResponse. +type CastaiRbacV1beta1DeleteGroupResponse = map[string]interface{} + +// CastaiRbacV1beta1DeleteRoleBindingResponse defines model for castai.rbac.v1beta1.DeleteRoleBindingResponse. +type CastaiRbacV1beta1DeleteRoleBindingResponse = map[string]interface{} + +// CastaiRbacV1beta1Group defines model for castai.rbac.v1beta1.Group. +type CastaiRbacV1beta1Group struct { + // CreatedAt is the timestamp when the group was created. + CreatedAt *time.Time `json:"createdAt,omitempty"` + Definition CastaiRbacV1beta1GroupDefinition `json:"definition"` + + // Description is the description of the group. + Description *string `json:"description,omitempty"` + + // ID is the unique identifier of the group. + Id *string `json:"id,omitempty"` + + // Name is the name of the group. + Name *string `json:"name,omitempty"` + + // OrganizationID is the unique identifier of the organization. + OrganizationId *string `json:"organizationId,omitempty"` + + // UpdatedAt is the timestamp when the group was last updated. + UpdatedAt *time.Time `json:"updatedAt,omitempty"` +} + +// CastaiRbacV1beta1GroupDefinition defines model for castai.rbac.v1beta1.GroupDefinition. +type CastaiRbacV1beta1GroupDefinition struct { + Author CastaiRbacV1beta1Author `json:"author"` + + // Members is a list of members. + Members *[]CastaiRbacV1beta1Member `json:"members,omitempty"` +} + +// GroupSubject represents the group subject. +type CastaiRbacV1beta1GroupSubject struct { + // ID is the unique identifier of the group. + Id string `json:"id"` + + // Name is the name of the group. + Name *string `json:"name,omitempty"` +} + +// CastaiRbacV1beta1Member defines model for castai.rbac.v1beta1.Member. +type CastaiRbacV1beta1Member struct { + // AddedAt is the timestamp when the user has been added to the group. + AddedAt *time.Time `json:"addedAt,omitempty"` + + // Email is the email of the member. + Email string `json:"email"` + + // ID is the internal unique identifier of the member. + Id string `json:"id"` + + // Kind represents the type of the member. + Kind CastaiRbacV1beta1MemberKind `json:"kind"` + + // LastLoginAt is the timestamp of the time when the user last time logged in. + LastLoginAt *time.Time `json:"lastLoginAt,omitempty"` +} + +// Kind represents the type of the member. +type CastaiRbacV1beta1MemberKind string + +// OrganizationScope represents the organization scope. +type CastaiRbacV1beta1OrganizationScope struct { + // ID is the unique identifier of the organization. + Id string `json:"id"` +} + +// PoliciesState represents the state of the policies generation. +// +// - ACCEPTED: ACCEPTED is the state when the policies async generation is ongoing. +// - CREATED: CREATED is the state when the policies have been generated. +// - FAILED: FAILED is the state when the policies generation failed. +type CastaiRbacV1beta1PoliciesState string + +// CastaiRbacV1beta1PolicyID defines model for castai.rbac.v1beta1.PolicyID. +type CastaiRbacV1beta1PolicyID struct { + Id string `json:"id"` +} + +// ResourceScope represents the resource scope. +// Resource can be any resources inside the organization. +type CastaiRbacV1beta1ResourceScope struct { + // ID is the unique identifier of the resource. + Id string `json:"id"` +} + +// CastaiRbacV1beta1RoleBinding defines model for castai.rbac.v1beta1.RoleBinding. +type CastaiRbacV1beta1RoleBinding struct { + // CreatedAt is the timestamp when the role binding was created. + CreatedAt *time.Time `json:"createdAt,omitempty"` + + // Definition represents the role binding definition. + Definition CastaiRbacV1beta1RoleBindingDefinition `json:"definition"` + + // Description is the description of the role binding. + Description *string `json:"description,omitempty"` + + // ID is the unique identifier of the role binding. + Id *string `json:"id,omitempty"` + + // Name is the name of the role binding. + Name *string `json:"name,omitempty"` + OrganizationId *string `json:"organizationId,omitempty"` + + // Status is the status of the role binding, reflecting the state of the related policies generation. + Status *[]CastaiRbacV1beta1RoleBindingStatus `json:"status,omitempty"` + + // UpdatedAt is the timestamp when the role binding was last updated. + UpdatedAt *time.Time `json:"updatedAt,omitempty"` +} + +// Definition represents the role binding definition. +type CastaiRbacV1beta1RoleBindingDefinition struct { + // RoleID is the unique identifier of the role. + RoleId string `json:"roleId"` + + // Scope represents the scope of the role binding. + Scope CastaiRbacV1beta1Scope `json:"scope"` + + // Subjects is a list of subjects. + Subjects *[]CastaiRbacV1beta1Subject `json:"subjects,omitempty"` +} + +// RoleBindingStatus is the status of the role binding, reflecting the state of the related policies generation. +type CastaiRbacV1beta1RoleBindingStatus struct { + // Message is providing more information about the state. + Message *string `json:"message,omitempty"` + + // Policies are the unique identifiers of the related policies. + Policies *[]CastaiRbacV1beta1PolicyID `json:"policies,omitempty"` + + // PoliciesState represents the state of the policies generation. + // + // - ACCEPTED: ACCEPTED is the state when the policies async generation is ongoing. + // - CREATED: CREATED is the state when the policies have been generated. + // - FAILED: FAILED is the state when the policies generation failed. + State CastaiRbacV1beta1PoliciesState `json:"state"` + + // UpdatedAt is the timestamp when the status was last updated. + UpdatedAt *time.Time `json:"updatedAt,omitempty"` +} + +// Scope represents the scope of the role binding. +type CastaiRbacV1beta1Scope struct { + // ClusterScope represents the resource scope of the cluster. + // Resource can be any resources inside the organization. + Cluster *CastaiRbacV1beta1ClusterScope `json:"cluster,omitempty"` + + // OrganizationScope represents the organization scope. + Organization *CastaiRbacV1beta1OrganizationScope `json:"organization,omitempty"` + + // ResourceScope represents the resource scope. + // Resource can be any resources inside the organization. + Resource *CastaiRbacV1beta1ResourceScope `json:"resource,omitempty"` +} + +// ServiceAccountSubject represents the service account subject. +type CastaiRbacV1beta1ServiceAccountSubject struct { + // ID is the unique identifier of the service account. + Id string `json:"id"` + + // Name is the name of the service account. + Name *string `json:"name,omitempty"` +} + +// Subject represents the subject of the role binding. +type CastaiRbacV1beta1Subject struct { + // GroupSubject represents the group subject. + Group *CastaiRbacV1beta1GroupSubject `json:"group,omitempty"` + + // ServiceAccountSubject represents the service account subject. + ServiceAccount *CastaiRbacV1beta1ServiceAccountSubject `json:"serviceAccount,omitempty"` + + // UserSubject represents the user subject. + User *CastaiRbacV1beta1UserSubject `json:"user,omitempty"` +} + +// CastaiRbacV1beta1UpdateGroupRequestGroupDefinition defines model for castai.rbac.v1beta1.UpdateGroupRequest.GroupDefinition. +type CastaiRbacV1beta1UpdateGroupRequestGroupDefinition struct { + // Members is a list of members. + Members []CastaiRbacV1beta1Member `json:"members"` +} + +// UserSubject represents the user subject. +type CastaiRbacV1beta1UserSubject struct { + // Email is the email of the user. + Email *string `json:"email,omitempty"` + + // ID is the unique identifier of the user. + Id string `json:"id"` + + // Name is the name of the user. + Name *string `json:"name,omitempty"` +} + // Key is the readable version of the service account key. type CastaiServiceaccountsV1beta1CreateServiceAccountKeyRequestKey struct { // ExpiresAt is the expiration time of the key. @@ -4551,12 +4833,24 @@ type UsersAPICreateOrganizationJSONBody = CastaiUsersV1beta1Organization // UsersAPIEditOrganizationJSONBody defines parameters for UsersAPIEditOrganization. type UsersAPIEditOrganizationJSONBody = CastaiUsersV1beta1Organization +// RbacServiceAPICreateGroupJSONBody defines parameters for RbacServiceAPICreateGroup. +type RbacServiceAPICreateGroupJSONBody = CastaiRbacV1beta1CreateGroupRequestGroup + +// RbacServiceAPIUpdateGroupJSONBody defines parameters for RbacServiceAPIUpdateGroup. +type RbacServiceAPIUpdateGroupJSONBody = GroupsIsTheGroupsToBeUpdated + // InventoryAPIAddReservationJSONBody defines parameters for InventoryAPIAddReservation. type InventoryAPIAddReservationJSONBody = CastaiInventoryV1beta1GenericReservation // InventoryAPIOverwriteReservationsJSONBody defines parameters for InventoryAPIOverwriteReservations. type InventoryAPIOverwriteReservationsJSONBody = CastaiInventoryV1beta1GenericReservationsList +// RbacServiceAPICreateRoleBindingsJSONBody defines parameters for RbacServiceAPICreateRoleBindings. +type RbacServiceAPICreateRoleBindingsJSONBody = []CastaiRbacV1beta1CreateRoleBindingsRequestRoleBinding + +// RbacServiceAPIUpdateRoleBindingJSONBody defines parameters for RbacServiceAPIUpdateRoleBinding. +type RbacServiceAPIUpdateRoleBindingJSONBody = RoleBindingIsTheRoleBindingToBeUpdated + // ServiceAccountsAPIListServiceAccountsParams defines parameters for ServiceAccountsAPIListServiceAccounts. type ServiceAccountsAPIListServiceAccountsParams struct { PageLimit *string `form:"page.limit,omitempty" json:"page.limit,omitempty"` @@ -4824,12 +5118,24 @@ type UsersAPICreateOrganizationJSONRequestBody = UsersAPICreateOrganizationJSONB // UsersAPIEditOrganizationJSONRequestBody defines body for UsersAPIEditOrganization for application/json ContentType. type UsersAPIEditOrganizationJSONRequestBody = UsersAPIEditOrganizationJSONBody +// RbacServiceAPICreateGroupJSONRequestBody defines body for RbacServiceAPICreateGroup for application/json ContentType. +type RbacServiceAPICreateGroupJSONRequestBody = RbacServiceAPICreateGroupJSONBody + +// RbacServiceAPIUpdateGroupJSONRequestBody defines body for RbacServiceAPIUpdateGroup for application/json ContentType. +type RbacServiceAPIUpdateGroupJSONRequestBody = RbacServiceAPIUpdateGroupJSONBody + // InventoryAPIAddReservationJSONRequestBody defines body for InventoryAPIAddReservation for application/json ContentType. type InventoryAPIAddReservationJSONRequestBody = InventoryAPIAddReservationJSONBody // InventoryAPIOverwriteReservationsJSONRequestBody defines body for InventoryAPIOverwriteReservations for application/json ContentType. type InventoryAPIOverwriteReservationsJSONRequestBody = InventoryAPIOverwriteReservationsJSONBody +// RbacServiceAPICreateRoleBindingsJSONRequestBody defines body for RbacServiceAPICreateRoleBindings for application/json ContentType. +type RbacServiceAPICreateRoleBindingsJSONRequestBody = RbacServiceAPICreateRoleBindingsJSONBody + +// RbacServiceAPIUpdateRoleBindingJSONRequestBody defines body for RbacServiceAPIUpdateRoleBinding for application/json ContentType. +type RbacServiceAPIUpdateRoleBindingJSONRequestBody = RbacServiceAPIUpdateRoleBindingJSONBody + // ServiceAccountsAPICreateServiceAccountJSONRequestBody defines body for ServiceAccountsAPICreateServiceAccount for application/json ContentType. type ServiceAccountsAPICreateServiceAccountJSONRequestBody = ServiceAccountsAPICreateServiceAccountJSONBody diff --git a/castai/sdk/client.gen.go b/castai/sdk/client.gen.go index ea75f70f..bccd2fdd 100644 --- a/castai/sdk/client.gen.go +++ b/castai/sdk/client.gen.go @@ -371,6 +371,22 @@ type ClientInterface interface { // InventoryAPISyncClusterResources request InventoryAPISyncClusterResources(ctx context.Context, organizationId string, clusterId string, reqEditors ...RequestEditorFn) (*http.Response, error) + // RbacServiceAPICreateGroup request with any body + RbacServiceAPICreateGroupWithBody(ctx context.Context, organizationId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + RbacServiceAPICreateGroup(ctx context.Context, organizationId string, body RbacServiceAPICreateGroupJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // RbacServiceAPIUpdateGroup request with any body + RbacServiceAPIUpdateGroupWithBody(ctx context.Context, organizationId string, groupId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + RbacServiceAPIUpdateGroup(ctx context.Context, organizationId string, groupId string, body RbacServiceAPIUpdateGroupJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // RbacServiceAPIDeleteGroup request + RbacServiceAPIDeleteGroup(ctx context.Context, organizationId string, id string, reqEditors ...RequestEditorFn) (*http.Response, error) + + // RbacServiceAPIGetGroup request + RbacServiceAPIGetGroup(ctx context.Context, organizationId string, id string, reqEditors ...RequestEditorFn) (*http.Response, error) + // InventoryAPIGetReservations request InventoryAPIGetReservations(ctx context.Context, organizationId string, reqEditors ...RequestEditorFn) (*http.Response, error) @@ -390,6 +406,22 @@ type ClientInterface interface { // InventoryAPIDeleteReservation request InventoryAPIDeleteReservation(ctx context.Context, organizationId string, reservationId string, reqEditors ...RequestEditorFn) (*http.Response, error) + // RbacServiceAPICreateRoleBindings request with any body + RbacServiceAPICreateRoleBindingsWithBody(ctx context.Context, organizationId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + RbacServiceAPICreateRoleBindings(ctx context.Context, organizationId string, body RbacServiceAPICreateRoleBindingsJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // RbacServiceAPIDeleteRoleBinding request + RbacServiceAPIDeleteRoleBinding(ctx context.Context, organizationId string, id string, reqEditors ...RequestEditorFn) (*http.Response, error) + + // RbacServiceAPIGetRoleBinding request + RbacServiceAPIGetRoleBinding(ctx context.Context, organizationId string, id string, reqEditors ...RequestEditorFn) (*http.Response, error) + + // RbacServiceAPIUpdateRoleBinding request with any body + RbacServiceAPIUpdateRoleBindingWithBody(ctx context.Context, organizationId string, roleBindingId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + RbacServiceAPIUpdateRoleBinding(ctx context.Context, organizationId string, roleBindingId string, body RbacServiceAPIUpdateRoleBindingJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + // ServiceAccountsAPIListServiceAccounts request ServiceAccountsAPIListServiceAccounts(ctx context.Context, organizationId string, params *ServiceAccountsAPIListServiceAccountsParams, reqEditors ...RequestEditorFn) (*http.Response, error) @@ -1829,6 +1861,78 @@ func (c *Client) InventoryAPISyncClusterResources(ctx context.Context, organizat return c.Client.Do(req) } +func (c *Client) RbacServiceAPICreateGroupWithBody(ctx context.Context, organizationId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewRbacServiceAPICreateGroupRequestWithBody(c.Server, organizationId, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) RbacServiceAPICreateGroup(ctx context.Context, organizationId string, body RbacServiceAPICreateGroupJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewRbacServiceAPICreateGroupRequest(c.Server, organizationId, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) RbacServiceAPIUpdateGroupWithBody(ctx context.Context, organizationId string, groupId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewRbacServiceAPIUpdateGroupRequestWithBody(c.Server, organizationId, groupId, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) RbacServiceAPIUpdateGroup(ctx context.Context, organizationId string, groupId string, body RbacServiceAPIUpdateGroupJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewRbacServiceAPIUpdateGroupRequest(c.Server, organizationId, groupId, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) RbacServiceAPIDeleteGroup(ctx context.Context, organizationId string, id string, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewRbacServiceAPIDeleteGroupRequest(c.Server, organizationId, id) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) RbacServiceAPIGetGroup(ctx context.Context, organizationId string, id string, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewRbacServiceAPIGetGroupRequest(c.Server, organizationId, id) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + func (c *Client) InventoryAPIGetReservations(ctx context.Context, organizationId string, reqEditors ...RequestEditorFn) (*http.Response, error) { req, err := NewInventoryAPIGetReservationsRequest(c.Server, organizationId) if err != nil { @@ -1913,6 +2017,78 @@ func (c *Client) InventoryAPIDeleteReservation(ctx context.Context, organization return c.Client.Do(req) } +func (c *Client) RbacServiceAPICreateRoleBindingsWithBody(ctx context.Context, organizationId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewRbacServiceAPICreateRoleBindingsRequestWithBody(c.Server, organizationId, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) RbacServiceAPICreateRoleBindings(ctx context.Context, organizationId string, body RbacServiceAPICreateRoleBindingsJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewRbacServiceAPICreateRoleBindingsRequest(c.Server, organizationId, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) RbacServiceAPIDeleteRoleBinding(ctx context.Context, organizationId string, id string, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewRbacServiceAPIDeleteRoleBindingRequest(c.Server, organizationId, id) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) RbacServiceAPIGetRoleBinding(ctx context.Context, organizationId string, id string, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewRbacServiceAPIGetRoleBindingRequest(c.Server, organizationId, id) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) RbacServiceAPIUpdateRoleBindingWithBody(ctx context.Context, organizationId string, roleBindingId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewRbacServiceAPIUpdateRoleBindingRequestWithBody(c.Server, organizationId, roleBindingId, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) RbacServiceAPIUpdateRoleBinding(ctx context.Context, organizationId string, roleBindingId string, body RbacServiceAPIUpdateRoleBindingJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewRbacServiceAPIUpdateRoleBindingRequest(c.Server, organizationId, roleBindingId, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + func (c *Client) ServiceAccountsAPIListServiceAccounts(ctx context.Context, organizationId string, params *ServiceAccountsAPIListServiceAccountsParams, reqEditors ...RequestEditorFn) (*http.Response, error) { req, err := NewServiceAccountsAPIListServiceAccountsRequest(c.Server, organizationId, params) if err != nil { @@ -6316,8 +6492,19 @@ func NewInventoryAPISyncClusterResourcesRequest(server string, organizationId st return req, nil } -// NewInventoryAPIGetReservationsRequest generates requests for InventoryAPIGetReservations -func NewInventoryAPIGetReservationsRequest(server string, organizationId string) (*http.Request, error) { +// NewRbacServiceAPICreateGroupRequest calls the generic RbacServiceAPICreateGroup builder with application/json body +func NewRbacServiceAPICreateGroupRequest(server string, organizationId string, body RbacServiceAPICreateGroupJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewRbacServiceAPICreateGroupRequestWithBody(server, organizationId, "application/json", bodyReader) +} + +// NewRbacServiceAPICreateGroupRequestWithBody generates requests for RbacServiceAPICreateGroup with any type of body +func NewRbacServiceAPICreateGroupRequestWithBody(server string, organizationId string, contentType string, body io.Reader) (*http.Request, error) { var err error var pathParam0 string @@ -6332,7 +6519,7 @@ func NewInventoryAPIGetReservationsRequest(server string, organizationId string) return nil, err } - operationPath := fmt.Sprintf("/v1/organizations/%s/reservations", pathParam0) + operationPath := fmt.Sprintf("/v1/organizations/%s/groups", pathParam0) if operationPath[0] == '/' { operationPath = "." + operationPath } @@ -6342,27 +6529,29 @@ func NewInventoryAPIGetReservationsRequest(server string, organizationId string) return nil, err } - req, err := http.NewRequest("GET", queryURL.String(), nil) + req, err := http.NewRequest("POST", queryURL.String(), body) if err != nil { return nil, err } + req.Header.Add("Content-Type", contentType) + return req, nil } -// NewInventoryAPIAddReservationRequest calls the generic InventoryAPIAddReservation builder with application/json body -func NewInventoryAPIAddReservationRequest(server string, organizationId string, body InventoryAPIAddReservationJSONRequestBody) (*http.Request, error) { +// NewRbacServiceAPIUpdateGroupRequest calls the generic RbacServiceAPIUpdateGroup builder with application/json body +func NewRbacServiceAPIUpdateGroupRequest(server string, organizationId string, groupId string, body RbacServiceAPIUpdateGroupJSONRequestBody) (*http.Request, error) { var bodyReader io.Reader buf, err := json.Marshal(body) if err != nil { return nil, err } bodyReader = bytes.NewReader(buf) - return NewInventoryAPIAddReservationRequestWithBody(server, organizationId, "application/json", bodyReader) + return NewRbacServiceAPIUpdateGroupRequestWithBody(server, organizationId, groupId, "application/json", bodyReader) } -// NewInventoryAPIAddReservationRequestWithBody generates requests for InventoryAPIAddReservation with any type of body -func NewInventoryAPIAddReservationRequestWithBody(server string, organizationId string, contentType string, body io.Reader) (*http.Request, error) { +// NewRbacServiceAPIUpdateGroupRequestWithBody generates requests for RbacServiceAPIUpdateGroup with any type of body +func NewRbacServiceAPIUpdateGroupRequestWithBody(server string, organizationId string, groupId string, contentType string, body io.Reader) (*http.Request, error) { var err error var pathParam0 string @@ -6372,12 +6561,19 @@ func NewInventoryAPIAddReservationRequestWithBody(server string, organizationId return nil, err } + var pathParam1 string + + pathParam1, err = runtime.StyleParamWithLocation("simple", false, "group.id", runtime.ParamLocationPath, groupId) + if err != nil { + return nil, err + } + serverURL, err := url.Parse(server) if err != nil { return nil, err } - operationPath := fmt.Sprintf("/v1/organizations/%s/reservations", pathParam0) + operationPath := fmt.Sprintf("/v1/organizations/%s/groups/%s", pathParam0, pathParam1) if operationPath[0] == '/' { operationPath = "." + operationPath } @@ -6387,7 +6583,7 @@ func NewInventoryAPIAddReservationRequestWithBody(server string, organizationId return nil, err } - req, err := http.NewRequest("POST", queryURL.String(), body) + req, err := http.NewRequest("PATCH", queryURL.String(), body) if err != nil { return nil, err } @@ -6397,8 +6593,8 @@ func NewInventoryAPIAddReservationRequestWithBody(server string, organizationId return req, nil } -// NewInventoryAPIGetReservationsBalanceRequest generates requests for InventoryAPIGetReservationsBalance -func NewInventoryAPIGetReservationsBalanceRequest(server string, organizationId string) (*http.Request, error) { +// NewRbacServiceAPIDeleteGroupRequest generates requests for RbacServiceAPIDeleteGroup +func NewRbacServiceAPIDeleteGroupRequest(server string, organizationId string, id string) (*http.Request, error) { var err error var pathParam0 string @@ -6408,12 +6604,19 @@ func NewInventoryAPIGetReservationsBalanceRequest(server string, organizationId return nil, err } + var pathParam1 string + + pathParam1, err = runtime.StyleParamWithLocation("simple", false, "id", runtime.ParamLocationPath, id) + if err != nil { + return nil, err + } + serverURL, err := url.Parse(server) if err != nil { return nil, err } - operationPath := fmt.Sprintf("/v1/organizations/%s/reservations/balance", pathParam0) + operationPath := fmt.Sprintf("/v1/organizations/%s/groups/%s", pathParam0, pathParam1) if operationPath[0] == '/' { operationPath = "." + operationPath } @@ -6423,7 +6626,7 @@ func NewInventoryAPIGetReservationsBalanceRequest(server string, organizationId return nil, err } - req, err := http.NewRequest("GET", queryURL.String(), nil) + req, err := http.NewRequest("DELETE", queryURL.String(), nil) if err != nil { return nil, err } @@ -6431,19 +6634,8 @@ func NewInventoryAPIGetReservationsBalanceRequest(server string, organizationId return req, nil } -// NewInventoryAPIOverwriteReservationsRequest calls the generic InventoryAPIOverwriteReservations builder with application/json body -func NewInventoryAPIOverwriteReservationsRequest(server string, organizationId string, body InventoryAPIOverwriteReservationsJSONRequestBody) (*http.Request, error) { - var bodyReader io.Reader - buf, err := json.Marshal(body) - if err != nil { - return nil, err - } - bodyReader = bytes.NewReader(buf) - return NewInventoryAPIOverwriteReservationsRequestWithBody(server, organizationId, "application/json", bodyReader) -} - -// NewInventoryAPIOverwriteReservationsRequestWithBody generates requests for InventoryAPIOverwriteReservations with any type of body -func NewInventoryAPIOverwriteReservationsRequestWithBody(server string, organizationId string, contentType string, body io.Reader) (*http.Request, error) { +// NewRbacServiceAPIGetGroupRequest generates requests for RbacServiceAPIGetGroup +func NewRbacServiceAPIGetGroupRequest(server string, organizationId string, id string) (*http.Request, error) { var err error var pathParam0 string @@ -6453,12 +6645,19 @@ func NewInventoryAPIOverwriteReservationsRequestWithBody(server string, organiza return nil, err } + var pathParam1 string + + pathParam1, err = runtime.StyleParamWithLocation("simple", false, "id", runtime.ParamLocationPath, id) + if err != nil { + return nil, err + } + serverURL, err := url.Parse(server) if err != nil { return nil, err } - operationPath := fmt.Sprintf("/v1/organizations/%s/reservations/overwrite", pathParam0) + operationPath := fmt.Sprintf("/v1/organizations/%s/groups/%s", pathParam0, pathParam1) if operationPath[0] == '/' { operationPath = "." + operationPath } @@ -6468,18 +6667,16 @@ func NewInventoryAPIOverwriteReservationsRequestWithBody(server string, organiza return nil, err } - req, err := http.NewRequest("POST", queryURL.String(), body) + req, err := http.NewRequest("GET", queryURL.String(), nil) if err != nil { return nil, err } - req.Header.Add("Content-Type", contentType) - return req, nil } -// NewInventoryAPIDeleteReservationRequest generates requests for InventoryAPIDeleteReservation -func NewInventoryAPIDeleteReservationRequest(server string, organizationId string, reservationId string) (*http.Request, error) { +// NewInventoryAPIGetReservationsRequest generates requests for InventoryAPIGetReservations +func NewInventoryAPIGetReservationsRequest(server string, organizationId string) (*http.Request, error) { var err error var pathParam0 string @@ -6489,19 +6686,12 @@ func NewInventoryAPIDeleteReservationRequest(server string, organizationId strin return nil, err } - var pathParam1 string - - pathParam1, err = runtime.StyleParamWithLocation("simple", false, "reservationId", runtime.ParamLocationPath, reservationId) - if err != nil { - return nil, err - } - serverURL, err := url.Parse(server) if err != nil { return nil, err } - operationPath := fmt.Sprintf("/v1/organizations/%s/reservations/%s", pathParam0, pathParam1) + operationPath := fmt.Sprintf("/v1/organizations/%s/reservations", pathParam0) if operationPath[0] == '/' { operationPath = "." + operationPath } @@ -6511,7 +6701,7 @@ func NewInventoryAPIDeleteReservationRequest(server string, organizationId strin return nil, err } - req, err := http.NewRequest("DELETE", queryURL.String(), nil) + req, err := http.NewRequest("GET", queryURL.String(), nil) if err != nil { return nil, err } @@ -6519,8 +6709,19 @@ func NewInventoryAPIDeleteReservationRequest(server string, organizationId strin return req, nil } -// NewServiceAccountsAPIListServiceAccountsRequest generates requests for ServiceAccountsAPIListServiceAccounts -func NewServiceAccountsAPIListServiceAccountsRequest(server string, organizationId string, params *ServiceAccountsAPIListServiceAccountsParams) (*http.Request, error) { +// NewInventoryAPIAddReservationRequest calls the generic InventoryAPIAddReservation builder with application/json body +func NewInventoryAPIAddReservationRequest(server string, organizationId string, body InventoryAPIAddReservationJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewInventoryAPIAddReservationRequestWithBody(server, organizationId, "application/json", bodyReader) +} + +// NewInventoryAPIAddReservationRequestWithBody generates requests for InventoryAPIAddReservation with any type of body +func NewInventoryAPIAddReservationRequestWithBody(server string, organizationId string, contentType string, body io.Reader) (*http.Request, error) { var err error var pathParam0 string @@ -6535,7 +6736,7 @@ func NewServiceAccountsAPIListServiceAccountsRequest(server string, organization return nil, err } - operationPath := fmt.Sprintf("/v1/organizations/%s/service-accounts", pathParam0) + operationPath := fmt.Sprintf("/v1/organizations/%s/reservations", pathParam0) if operationPath[0] == '/' { operationPath = "." + operationPath } @@ -6545,25 +6746,366 @@ func NewServiceAccountsAPIListServiceAccountsRequest(server string, organization return nil, err } - queryValues := queryURL.Query() + req, err := http.NewRequest("POST", queryURL.String(), body) + if err != nil { + return nil, err + } - if params.PageLimit != nil { + req.Header.Add("Content-Type", contentType) - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "page.limit", runtime.ParamLocationQuery, *params.PageLimit); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { - return nil, err - } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } - } - } + return req, nil +} - } +// NewInventoryAPIGetReservationsBalanceRequest generates requests for InventoryAPIGetReservationsBalance +func NewInventoryAPIGetReservationsBalanceRequest(server string, organizationId string) (*http.Request, error) { + var err error - if params.PageCursor != nil { + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithLocation("simple", false, "organizationId", runtime.ParamLocationPath, organizationId) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/v1/organizations/%s/reservations/balance", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("GET", queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewInventoryAPIOverwriteReservationsRequest calls the generic InventoryAPIOverwriteReservations builder with application/json body +func NewInventoryAPIOverwriteReservationsRequest(server string, organizationId string, body InventoryAPIOverwriteReservationsJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewInventoryAPIOverwriteReservationsRequestWithBody(server, organizationId, "application/json", bodyReader) +} + +// NewInventoryAPIOverwriteReservationsRequestWithBody generates requests for InventoryAPIOverwriteReservations with any type of body +func NewInventoryAPIOverwriteReservationsRequestWithBody(server string, organizationId string, contentType string, body io.Reader) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithLocation("simple", false, "organizationId", runtime.ParamLocationPath, organizationId) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/v1/organizations/%s/reservations/overwrite", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("POST", queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewInventoryAPIDeleteReservationRequest generates requests for InventoryAPIDeleteReservation +func NewInventoryAPIDeleteReservationRequest(server string, organizationId string, reservationId string) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithLocation("simple", false, "organizationId", runtime.ParamLocationPath, organizationId) + if err != nil { + return nil, err + } + + var pathParam1 string + + pathParam1, err = runtime.StyleParamWithLocation("simple", false, "reservationId", runtime.ParamLocationPath, reservationId) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/v1/organizations/%s/reservations/%s", pathParam0, pathParam1) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("DELETE", queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewRbacServiceAPICreateRoleBindingsRequest calls the generic RbacServiceAPICreateRoleBindings builder with application/json body +func NewRbacServiceAPICreateRoleBindingsRequest(server string, organizationId string, body RbacServiceAPICreateRoleBindingsJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewRbacServiceAPICreateRoleBindingsRequestWithBody(server, organizationId, "application/json", bodyReader) +} + +// NewRbacServiceAPICreateRoleBindingsRequestWithBody generates requests for RbacServiceAPICreateRoleBindings with any type of body +func NewRbacServiceAPICreateRoleBindingsRequestWithBody(server string, organizationId string, contentType string, body io.Reader) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithLocation("simple", false, "organizationId", runtime.ParamLocationPath, organizationId) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/v1/organizations/%s/role-bindings", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("POST", queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewRbacServiceAPIDeleteRoleBindingRequest generates requests for RbacServiceAPIDeleteRoleBinding +func NewRbacServiceAPIDeleteRoleBindingRequest(server string, organizationId string, id string) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithLocation("simple", false, "organizationId", runtime.ParamLocationPath, organizationId) + if err != nil { + return nil, err + } + + var pathParam1 string + + pathParam1, err = runtime.StyleParamWithLocation("simple", false, "id", runtime.ParamLocationPath, id) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/v1/organizations/%s/role-bindings/%s", pathParam0, pathParam1) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("DELETE", queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewRbacServiceAPIGetRoleBindingRequest generates requests for RbacServiceAPIGetRoleBinding +func NewRbacServiceAPIGetRoleBindingRequest(server string, organizationId string, id string) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithLocation("simple", false, "organizationId", runtime.ParamLocationPath, organizationId) + if err != nil { + return nil, err + } + + var pathParam1 string + + pathParam1, err = runtime.StyleParamWithLocation("simple", false, "id", runtime.ParamLocationPath, id) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/v1/organizations/%s/role-bindings/%s", pathParam0, pathParam1) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("GET", queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewRbacServiceAPIUpdateRoleBindingRequest calls the generic RbacServiceAPIUpdateRoleBinding builder with application/json body +func NewRbacServiceAPIUpdateRoleBindingRequest(server string, organizationId string, roleBindingId string, body RbacServiceAPIUpdateRoleBindingJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewRbacServiceAPIUpdateRoleBindingRequestWithBody(server, organizationId, roleBindingId, "application/json", bodyReader) +} + +// NewRbacServiceAPIUpdateRoleBindingRequestWithBody generates requests for RbacServiceAPIUpdateRoleBinding with any type of body +func NewRbacServiceAPIUpdateRoleBindingRequestWithBody(server string, organizationId string, roleBindingId string, contentType string, body io.Reader) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithLocation("simple", false, "organizationId", runtime.ParamLocationPath, organizationId) + if err != nil { + return nil, err + } + + var pathParam1 string + + pathParam1, err = runtime.StyleParamWithLocation("simple", false, "roleBinding.id", runtime.ParamLocationPath, roleBindingId) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/v1/organizations/%s/role-bindings/%s", pathParam0, pathParam1) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("PATCH", queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewServiceAccountsAPIListServiceAccountsRequest generates requests for ServiceAccountsAPIListServiceAccounts +func NewServiceAccountsAPIListServiceAccountsRequest(server string, organizationId string, params *ServiceAccountsAPIListServiceAccountsParams) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithLocation("simple", false, "organizationId", runtime.ParamLocationPath, organizationId) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/v1/organizations/%s/service-accounts", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + queryValues := queryURL.Query() + + if params.PageLimit != nil { + + if queryFrag, err := runtime.StyleParamWithLocation("form", true, "page.limit", runtime.ParamLocationQuery, *params.PageLimit); err != nil { + return nil, err + } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + return nil, err + } else { + for k, v := range parsed { + for _, v2 := range v { + queryValues.Add(k, v2) + } + } + } + + } + + if params.PageCursor != nil { if queryFrag, err := runtime.StyleParamWithLocation("form", true, "page.cursor", runtime.ParamLocationQuery, *params.PageCursor); err != nil { return nil, err @@ -9512,6 +10054,22 @@ type ClientWithResponsesInterface interface { // InventoryAPISyncClusterResources request InventoryAPISyncClusterResourcesWithResponse(ctx context.Context, organizationId string, clusterId string) (*InventoryAPISyncClusterResourcesResponse, error) + // RbacServiceAPICreateGroup request with any body + RbacServiceAPICreateGroupWithBodyWithResponse(ctx context.Context, organizationId string, contentType string, body io.Reader) (*RbacServiceAPICreateGroupResponse, error) + + RbacServiceAPICreateGroupWithResponse(ctx context.Context, organizationId string, body RbacServiceAPICreateGroupJSONRequestBody) (*RbacServiceAPICreateGroupResponse, error) + + // RbacServiceAPIUpdateGroup request with any body + RbacServiceAPIUpdateGroupWithBodyWithResponse(ctx context.Context, organizationId string, groupId string, contentType string, body io.Reader) (*RbacServiceAPIUpdateGroupResponse, error) + + RbacServiceAPIUpdateGroupWithResponse(ctx context.Context, organizationId string, groupId string, body RbacServiceAPIUpdateGroupJSONRequestBody) (*RbacServiceAPIUpdateGroupResponse, error) + + // RbacServiceAPIDeleteGroup request + RbacServiceAPIDeleteGroupWithResponse(ctx context.Context, organizationId string, id string) (*RbacServiceAPIDeleteGroupResponse, error) + + // RbacServiceAPIGetGroup request + RbacServiceAPIGetGroupWithResponse(ctx context.Context, organizationId string, id string) (*RbacServiceAPIGetGroupResponse, error) + // InventoryAPIGetReservations request InventoryAPIGetReservationsWithResponse(ctx context.Context, organizationId string) (*InventoryAPIGetReservationsResponse, error) @@ -9531,6 +10089,22 @@ type ClientWithResponsesInterface interface { // InventoryAPIDeleteReservation request InventoryAPIDeleteReservationWithResponse(ctx context.Context, organizationId string, reservationId string) (*InventoryAPIDeleteReservationResponse, error) + // RbacServiceAPICreateRoleBindings request with any body + RbacServiceAPICreateRoleBindingsWithBodyWithResponse(ctx context.Context, organizationId string, contentType string, body io.Reader) (*RbacServiceAPICreateRoleBindingsResponse, error) + + RbacServiceAPICreateRoleBindingsWithResponse(ctx context.Context, organizationId string, body RbacServiceAPICreateRoleBindingsJSONRequestBody) (*RbacServiceAPICreateRoleBindingsResponse, error) + + // RbacServiceAPIDeleteRoleBinding request + RbacServiceAPIDeleteRoleBindingWithResponse(ctx context.Context, organizationId string, id string) (*RbacServiceAPIDeleteRoleBindingResponse, error) + + // RbacServiceAPIGetRoleBinding request + RbacServiceAPIGetRoleBindingWithResponse(ctx context.Context, organizationId string, id string) (*RbacServiceAPIGetRoleBindingResponse, error) + + // RbacServiceAPIUpdateRoleBinding request with any body + RbacServiceAPIUpdateRoleBindingWithBodyWithResponse(ctx context.Context, organizationId string, roleBindingId string, contentType string, body io.Reader) (*RbacServiceAPIUpdateRoleBindingResponse, error) + + RbacServiceAPIUpdateRoleBindingWithResponse(ctx context.Context, organizationId string, roleBindingId string, body RbacServiceAPIUpdateRoleBindingJSONRequestBody) (*RbacServiceAPIUpdateRoleBindingResponse, error) + // ServiceAccountsAPIListServiceAccounts request ServiceAccountsAPIListServiceAccountsWithResponse(ctx context.Context, organizationId string, params *ServiceAccountsAPIListServiceAccountsParams) (*ServiceAccountsAPIListServiceAccountsResponse, error) @@ -11992,6 +12566,126 @@ func (r InventoryAPISyncClusterResourcesResponse) GetBody() []byte { // TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 +type RbacServiceAPICreateGroupResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *CastaiRbacV1beta1Group +} + +// Status returns HTTPResponse.Status +func (r RbacServiceAPICreateGroupResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r RbacServiceAPICreateGroupResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 +// Body returns body of byte array +func (r RbacServiceAPICreateGroupResponse) GetBody() []byte { + return r.Body +} + +// TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 + +type RbacServiceAPIUpdateGroupResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *CastaiRbacV1beta1Group +} + +// Status returns HTTPResponse.Status +func (r RbacServiceAPIUpdateGroupResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r RbacServiceAPIUpdateGroupResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 +// Body returns body of byte array +func (r RbacServiceAPIUpdateGroupResponse) GetBody() []byte { + return r.Body +} + +// TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 + +type RbacServiceAPIDeleteGroupResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *CastaiRbacV1beta1DeleteGroupResponse +} + +// Status returns HTTPResponse.Status +func (r RbacServiceAPIDeleteGroupResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r RbacServiceAPIDeleteGroupResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 +// Body returns body of byte array +func (r RbacServiceAPIDeleteGroupResponse) GetBody() []byte { + return r.Body +} + +// TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 + +type RbacServiceAPIGetGroupResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *CastaiRbacV1beta1Group +} + +// Status returns HTTPResponse.Status +func (r RbacServiceAPIGetGroupResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r RbacServiceAPIGetGroupResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 +// Body returns body of byte array +func (r RbacServiceAPIGetGroupResponse) GetBody() []byte { + return r.Body +} + +// TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 + type InventoryAPIGetReservationsResponse struct { Body []byte HTTPResponse *http.Response @@ -12022,14 +12716,134 @@ func (r InventoryAPIGetReservationsResponse) GetBody() []byte { // TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 -type InventoryAPIAddReservationResponse struct { +type InventoryAPIAddReservationResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *CastaiInventoryV1beta1AddReservationResponse +} + +// Status returns HTTPResponse.Status +func (r InventoryAPIAddReservationResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r InventoryAPIAddReservationResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 +// Body returns body of byte array +func (r InventoryAPIAddReservationResponse) GetBody() []byte { + return r.Body +} + +// TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 + +type InventoryAPIGetReservationsBalanceResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *CastaiInventoryV1beta1GetReservationsBalanceResponse +} + +// Status returns HTTPResponse.Status +func (r InventoryAPIGetReservationsBalanceResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r InventoryAPIGetReservationsBalanceResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 +// Body returns body of byte array +func (r InventoryAPIGetReservationsBalanceResponse) GetBody() []byte { + return r.Body +} + +// TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 + +type InventoryAPIOverwriteReservationsResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *CastaiInventoryV1beta1OverwriteReservationsResponse +} + +// Status returns HTTPResponse.Status +func (r InventoryAPIOverwriteReservationsResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r InventoryAPIOverwriteReservationsResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 +// Body returns body of byte array +func (r InventoryAPIOverwriteReservationsResponse) GetBody() []byte { + return r.Body +} + +// TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 + +type InventoryAPIDeleteReservationResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *map[string]interface{} +} + +// Status returns HTTPResponse.Status +func (r InventoryAPIDeleteReservationResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r InventoryAPIDeleteReservationResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 +// Body returns body of byte array +func (r InventoryAPIDeleteReservationResponse) GetBody() []byte { + return r.Body +} + +// TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 + +type RbacServiceAPICreateRoleBindingsResponse struct { Body []byte HTTPResponse *http.Response - JSON200 *CastaiInventoryV1beta1AddReservationResponse + JSON200 *[]CastaiRbacV1beta1RoleBinding } // Status returns HTTPResponse.Status -func (r InventoryAPIAddReservationResponse) Status() string { +func (r RbacServiceAPICreateRoleBindingsResponse) Status() string { if r.HTTPResponse != nil { return r.HTTPResponse.Status } @@ -12037,7 +12851,7 @@ func (r InventoryAPIAddReservationResponse) Status() string { } // StatusCode returns HTTPResponse.StatusCode -func (r InventoryAPIAddReservationResponse) StatusCode() int { +func (r RbacServiceAPICreateRoleBindingsResponse) StatusCode() int { if r.HTTPResponse != nil { return r.HTTPResponse.StatusCode } @@ -12046,20 +12860,20 @@ func (r InventoryAPIAddReservationResponse) StatusCode() int { // TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 // Body returns body of byte array -func (r InventoryAPIAddReservationResponse) GetBody() []byte { +func (r RbacServiceAPICreateRoleBindingsResponse) GetBody() []byte { return r.Body } // TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 -type InventoryAPIGetReservationsBalanceResponse struct { +type RbacServiceAPIDeleteRoleBindingResponse struct { Body []byte HTTPResponse *http.Response - JSON200 *CastaiInventoryV1beta1GetReservationsBalanceResponse + JSON200 *CastaiRbacV1beta1DeleteRoleBindingResponse } // Status returns HTTPResponse.Status -func (r InventoryAPIGetReservationsBalanceResponse) Status() string { +func (r RbacServiceAPIDeleteRoleBindingResponse) Status() string { if r.HTTPResponse != nil { return r.HTTPResponse.Status } @@ -12067,7 +12881,7 @@ func (r InventoryAPIGetReservationsBalanceResponse) Status() string { } // StatusCode returns HTTPResponse.StatusCode -func (r InventoryAPIGetReservationsBalanceResponse) StatusCode() int { +func (r RbacServiceAPIDeleteRoleBindingResponse) StatusCode() int { if r.HTTPResponse != nil { return r.HTTPResponse.StatusCode } @@ -12076,20 +12890,20 @@ func (r InventoryAPIGetReservationsBalanceResponse) StatusCode() int { // TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 // Body returns body of byte array -func (r InventoryAPIGetReservationsBalanceResponse) GetBody() []byte { +func (r RbacServiceAPIDeleteRoleBindingResponse) GetBody() []byte { return r.Body } // TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 -type InventoryAPIOverwriteReservationsResponse struct { +type RbacServiceAPIGetRoleBindingResponse struct { Body []byte HTTPResponse *http.Response - JSON200 *CastaiInventoryV1beta1OverwriteReservationsResponse + JSON200 *CastaiRbacV1beta1RoleBinding } // Status returns HTTPResponse.Status -func (r InventoryAPIOverwriteReservationsResponse) Status() string { +func (r RbacServiceAPIGetRoleBindingResponse) Status() string { if r.HTTPResponse != nil { return r.HTTPResponse.Status } @@ -12097,7 +12911,7 @@ func (r InventoryAPIOverwriteReservationsResponse) Status() string { } // StatusCode returns HTTPResponse.StatusCode -func (r InventoryAPIOverwriteReservationsResponse) StatusCode() int { +func (r RbacServiceAPIGetRoleBindingResponse) StatusCode() int { if r.HTTPResponse != nil { return r.HTTPResponse.StatusCode } @@ -12106,20 +12920,20 @@ func (r InventoryAPIOverwriteReservationsResponse) StatusCode() int { // TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 // Body returns body of byte array -func (r InventoryAPIOverwriteReservationsResponse) GetBody() []byte { +func (r RbacServiceAPIGetRoleBindingResponse) GetBody() []byte { return r.Body } // TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 -type InventoryAPIDeleteReservationResponse struct { +type RbacServiceAPIUpdateRoleBindingResponse struct { Body []byte HTTPResponse *http.Response - JSON200 *map[string]interface{} + JSON200 *CastaiRbacV1beta1RoleBinding } // Status returns HTTPResponse.Status -func (r InventoryAPIDeleteReservationResponse) Status() string { +func (r RbacServiceAPIUpdateRoleBindingResponse) Status() string { if r.HTTPResponse != nil { return r.HTTPResponse.Status } @@ -12127,7 +12941,7 @@ func (r InventoryAPIDeleteReservationResponse) Status() string { } // StatusCode returns HTTPResponse.StatusCode -func (r InventoryAPIDeleteReservationResponse) StatusCode() int { +func (r RbacServiceAPIUpdateRoleBindingResponse) StatusCode() int { if r.HTTPResponse != nil { return r.HTTPResponse.StatusCode } @@ -12136,7 +12950,7 @@ func (r InventoryAPIDeleteReservationResponse) StatusCode() int { // TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 // Body returns body of byte array -func (r InventoryAPIDeleteReservationResponse) GetBody() []byte { +func (r RbacServiceAPIUpdateRoleBindingResponse) GetBody() []byte { return r.Body } @@ -14719,6 +15533,58 @@ func (c *ClientWithResponses) InventoryAPISyncClusterResourcesWithResponse(ctx c return ParseInventoryAPISyncClusterResourcesResponse(rsp) } +// RbacServiceAPICreateGroupWithBodyWithResponse request with arbitrary body returning *RbacServiceAPICreateGroupResponse +func (c *ClientWithResponses) RbacServiceAPICreateGroupWithBodyWithResponse(ctx context.Context, organizationId string, contentType string, body io.Reader) (*RbacServiceAPICreateGroupResponse, error) { + rsp, err := c.RbacServiceAPICreateGroupWithBody(ctx, organizationId, contentType, body) + if err != nil { + return nil, err + } + return ParseRbacServiceAPICreateGroupResponse(rsp) +} + +func (c *ClientWithResponses) RbacServiceAPICreateGroupWithResponse(ctx context.Context, organizationId string, body RbacServiceAPICreateGroupJSONRequestBody) (*RbacServiceAPICreateGroupResponse, error) { + rsp, err := c.RbacServiceAPICreateGroup(ctx, organizationId, body) + if err != nil { + return nil, err + } + return ParseRbacServiceAPICreateGroupResponse(rsp) +} + +// RbacServiceAPIUpdateGroupWithBodyWithResponse request with arbitrary body returning *RbacServiceAPIUpdateGroupResponse +func (c *ClientWithResponses) RbacServiceAPIUpdateGroupWithBodyWithResponse(ctx context.Context, organizationId string, groupId string, contentType string, body io.Reader) (*RbacServiceAPIUpdateGroupResponse, error) { + rsp, err := c.RbacServiceAPIUpdateGroupWithBody(ctx, organizationId, groupId, contentType, body) + if err != nil { + return nil, err + } + return ParseRbacServiceAPIUpdateGroupResponse(rsp) +} + +func (c *ClientWithResponses) RbacServiceAPIUpdateGroupWithResponse(ctx context.Context, organizationId string, groupId string, body RbacServiceAPIUpdateGroupJSONRequestBody) (*RbacServiceAPIUpdateGroupResponse, error) { + rsp, err := c.RbacServiceAPIUpdateGroup(ctx, organizationId, groupId, body) + if err != nil { + return nil, err + } + return ParseRbacServiceAPIUpdateGroupResponse(rsp) +} + +// RbacServiceAPIDeleteGroupWithResponse request returning *RbacServiceAPIDeleteGroupResponse +func (c *ClientWithResponses) RbacServiceAPIDeleteGroupWithResponse(ctx context.Context, organizationId string, id string) (*RbacServiceAPIDeleteGroupResponse, error) { + rsp, err := c.RbacServiceAPIDeleteGroup(ctx, organizationId, id) + if err != nil { + return nil, err + } + return ParseRbacServiceAPIDeleteGroupResponse(rsp) +} + +// RbacServiceAPIGetGroupWithResponse request returning *RbacServiceAPIGetGroupResponse +func (c *ClientWithResponses) RbacServiceAPIGetGroupWithResponse(ctx context.Context, organizationId string, id string) (*RbacServiceAPIGetGroupResponse, error) { + rsp, err := c.RbacServiceAPIGetGroup(ctx, organizationId, id) + if err != nil { + return nil, err + } + return ParseRbacServiceAPIGetGroupResponse(rsp) +} + // InventoryAPIGetReservationsWithResponse request returning *InventoryAPIGetReservationsResponse func (c *ClientWithResponses) InventoryAPIGetReservationsWithResponse(ctx context.Context, organizationId string) (*InventoryAPIGetReservationsResponse, error) { rsp, err := c.InventoryAPIGetReservations(ctx, organizationId) @@ -14780,6 +15646,58 @@ func (c *ClientWithResponses) InventoryAPIDeleteReservationWithResponse(ctx cont return ParseInventoryAPIDeleteReservationResponse(rsp) } +// RbacServiceAPICreateRoleBindingsWithBodyWithResponse request with arbitrary body returning *RbacServiceAPICreateRoleBindingsResponse +func (c *ClientWithResponses) RbacServiceAPICreateRoleBindingsWithBodyWithResponse(ctx context.Context, organizationId string, contentType string, body io.Reader) (*RbacServiceAPICreateRoleBindingsResponse, error) { + rsp, err := c.RbacServiceAPICreateRoleBindingsWithBody(ctx, organizationId, contentType, body) + if err != nil { + return nil, err + } + return ParseRbacServiceAPICreateRoleBindingsResponse(rsp) +} + +func (c *ClientWithResponses) RbacServiceAPICreateRoleBindingsWithResponse(ctx context.Context, organizationId string, body RbacServiceAPICreateRoleBindingsJSONRequestBody) (*RbacServiceAPICreateRoleBindingsResponse, error) { + rsp, err := c.RbacServiceAPICreateRoleBindings(ctx, organizationId, body) + if err != nil { + return nil, err + } + return ParseRbacServiceAPICreateRoleBindingsResponse(rsp) +} + +// RbacServiceAPIDeleteRoleBindingWithResponse request returning *RbacServiceAPIDeleteRoleBindingResponse +func (c *ClientWithResponses) RbacServiceAPIDeleteRoleBindingWithResponse(ctx context.Context, organizationId string, id string) (*RbacServiceAPIDeleteRoleBindingResponse, error) { + rsp, err := c.RbacServiceAPIDeleteRoleBinding(ctx, organizationId, id) + if err != nil { + return nil, err + } + return ParseRbacServiceAPIDeleteRoleBindingResponse(rsp) +} + +// RbacServiceAPIGetRoleBindingWithResponse request returning *RbacServiceAPIGetRoleBindingResponse +func (c *ClientWithResponses) RbacServiceAPIGetRoleBindingWithResponse(ctx context.Context, organizationId string, id string) (*RbacServiceAPIGetRoleBindingResponse, error) { + rsp, err := c.RbacServiceAPIGetRoleBinding(ctx, organizationId, id) + if err != nil { + return nil, err + } + return ParseRbacServiceAPIGetRoleBindingResponse(rsp) +} + +// RbacServiceAPIUpdateRoleBindingWithBodyWithResponse request with arbitrary body returning *RbacServiceAPIUpdateRoleBindingResponse +func (c *ClientWithResponses) RbacServiceAPIUpdateRoleBindingWithBodyWithResponse(ctx context.Context, organizationId string, roleBindingId string, contentType string, body io.Reader) (*RbacServiceAPIUpdateRoleBindingResponse, error) { + rsp, err := c.RbacServiceAPIUpdateRoleBindingWithBody(ctx, organizationId, roleBindingId, contentType, body) + if err != nil { + return nil, err + } + return ParseRbacServiceAPIUpdateRoleBindingResponse(rsp) +} + +func (c *ClientWithResponses) RbacServiceAPIUpdateRoleBindingWithResponse(ctx context.Context, organizationId string, roleBindingId string, body RbacServiceAPIUpdateRoleBindingJSONRequestBody) (*RbacServiceAPIUpdateRoleBindingResponse, error) { + rsp, err := c.RbacServiceAPIUpdateRoleBinding(ctx, organizationId, roleBindingId, body) + if err != nil { + return nil, err + } + return ParseRbacServiceAPIUpdateRoleBindingResponse(rsp) +} + // ServiceAccountsAPIListServiceAccountsWithResponse request returning *ServiceAccountsAPIListServiceAccountsResponse func (c *ClientWithResponses) ServiceAccountsAPIListServiceAccountsWithResponse(ctx context.Context, organizationId string, params *ServiceAccountsAPIListServiceAccountsParams) (*ServiceAccountsAPIListServiceAccountsResponse, error) { rsp, err := c.ServiceAccountsAPIListServiceAccounts(ctx, organizationId, params) @@ -17360,6 +18278,110 @@ func ParseInventoryAPISyncClusterResourcesResponse(rsp *http.Response) (*Invento return response, nil } +// ParseRbacServiceAPICreateGroupResponse parses an HTTP response from a RbacServiceAPICreateGroupWithResponse call +func ParseRbacServiceAPICreateGroupResponse(rsp *http.Response) (*RbacServiceAPICreateGroupResponse, error) { + bodyBytes, err := ioutil.ReadAll(rsp.Body) + defer rsp.Body.Close() + if err != nil { + return nil, err + } + + response := &RbacServiceAPICreateGroupResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest CastaiRbacV1beta1Group + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + } + + return response, nil +} + +// ParseRbacServiceAPIUpdateGroupResponse parses an HTTP response from a RbacServiceAPIUpdateGroupWithResponse call +func ParseRbacServiceAPIUpdateGroupResponse(rsp *http.Response) (*RbacServiceAPIUpdateGroupResponse, error) { + bodyBytes, err := ioutil.ReadAll(rsp.Body) + defer rsp.Body.Close() + if err != nil { + return nil, err + } + + response := &RbacServiceAPIUpdateGroupResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest CastaiRbacV1beta1Group + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + } + + return response, nil +} + +// ParseRbacServiceAPIDeleteGroupResponse parses an HTTP response from a RbacServiceAPIDeleteGroupWithResponse call +func ParseRbacServiceAPIDeleteGroupResponse(rsp *http.Response) (*RbacServiceAPIDeleteGroupResponse, error) { + bodyBytes, err := ioutil.ReadAll(rsp.Body) + defer rsp.Body.Close() + if err != nil { + return nil, err + } + + response := &RbacServiceAPIDeleteGroupResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest CastaiRbacV1beta1DeleteGroupResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + } + + return response, nil +} + +// ParseRbacServiceAPIGetGroupResponse parses an HTTP response from a RbacServiceAPIGetGroupWithResponse call +func ParseRbacServiceAPIGetGroupResponse(rsp *http.Response) (*RbacServiceAPIGetGroupResponse, error) { + bodyBytes, err := ioutil.ReadAll(rsp.Body) + defer rsp.Body.Close() + if err != nil { + return nil, err + } + + response := &RbacServiceAPIGetGroupResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest CastaiRbacV1beta1Group + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + } + + return response, nil +} + // ParseInventoryAPIGetReservationsResponse parses an HTTP response from a InventoryAPIGetReservationsWithResponse call func ParseInventoryAPIGetReservationsResponse(rsp *http.Response) (*InventoryAPIGetReservationsResponse, error) { bodyBytes, err := ioutil.ReadAll(rsp.Body) @@ -17490,6 +18512,110 @@ func ParseInventoryAPIDeleteReservationResponse(rsp *http.Response) (*InventoryA return response, nil } +// ParseRbacServiceAPICreateRoleBindingsResponse parses an HTTP response from a RbacServiceAPICreateRoleBindingsWithResponse call +func ParseRbacServiceAPICreateRoleBindingsResponse(rsp *http.Response) (*RbacServiceAPICreateRoleBindingsResponse, error) { + bodyBytes, err := ioutil.ReadAll(rsp.Body) + defer rsp.Body.Close() + if err != nil { + return nil, err + } + + response := &RbacServiceAPICreateRoleBindingsResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest []CastaiRbacV1beta1RoleBinding + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + } + + return response, nil +} + +// ParseRbacServiceAPIDeleteRoleBindingResponse parses an HTTP response from a RbacServiceAPIDeleteRoleBindingWithResponse call +func ParseRbacServiceAPIDeleteRoleBindingResponse(rsp *http.Response) (*RbacServiceAPIDeleteRoleBindingResponse, error) { + bodyBytes, err := ioutil.ReadAll(rsp.Body) + defer rsp.Body.Close() + if err != nil { + return nil, err + } + + response := &RbacServiceAPIDeleteRoleBindingResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest CastaiRbacV1beta1DeleteRoleBindingResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + } + + return response, nil +} + +// ParseRbacServiceAPIGetRoleBindingResponse parses an HTTP response from a RbacServiceAPIGetRoleBindingWithResponse call +func ParseRbacServiceAPIGetRoleBindingResponse(rsp *http.Response) (*RbacServiceAPIGetRoleBindingResponse, error) { + bodyBytes, err := ioutil.ReadAll(rsp.Body) + defer rsp.Body.Close() + if err != nil { + return nil, err + } + + response := &RbacServiceAPIGetRoleBindingResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest CastaiRbacV1beta1RoleBinding + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + } + + return response, nil +} + +// ParseRbacServiceAPIUpdateRoleBindingResponse parses an HTTP response from a RbacServiceAPIUpdateRoleBindingWithResponse call +func ParseRbacServiceAPIUpdateRoleBindingResponse(rsp *http.Response) (*RbacServiceAPIUpdateRoleBindingResponse, error) { + bodyBytes, err := ioutil.ReadAll(rsp.Body) + defer rsp.Body.Close() + if err != nil { + return nil, err + } + + response := &RbacServiceAPIUpdateRoleBindingResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest CastaiRbacV1beta1RoleBinding + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + } + + return response, nil +} + // ParseServiceAccountsAPIListServiceAccountsResponse parses an HTTP response from a ServiceAccountsAPIListServiceAccountsWithResponse call func ParseServiceAccountsAPIListServiceAccountsResponse(rsp *http.Response) (*ServiceAccountsAPIListServiceAccountsResponse, error) { bodyBytes, err := ioutil.ReadAll(rsp.Body) diff --git a/docs/resources/service_account.md b/docs/resources/service_account.md index eec7cd30..c83f36f8 100644 --- a/docs/resources/service_account.md +++ b/docs/resources/service_account.md @@ -15,8 +15,8 @@ Service Account resource allows managing CAST AI service accounts. ```terraform resource "castai_service_account" "service_account" { organization_id = organization.id - name = "service-account-name" - description = "service account description" + name = "service-account-name" + description = "service account description" } ``` From 19030a1e4251b83ae768d331a853ad0b3a061964 Mon Sep 17 00:00:00 2001 From: radekska Date: Tue, 10 Dec 2024 08:59:00 +0100 Subject: [PATCH 15/24] wip --- castai/provider.go | 1 + castai/resource_service_account.go | 82 ++++++++++++++++++++++++++- castai/sdk/api.gen.go | 1 + docs/resources/service_account.md | 5 +- docs/resources/service_account_key.md | 46 +++++++++++++++ 5 files changed, 132 insertions(+), 3 deletions(-) create mode 100644 docs/resources/service_account_key.md diff --git a/castai/provider.go b/castai/provider.go index 66933cf7..9fe3c29e 100644 --- a/castai/provider.go +++ b/castai/provider.go @@ -53,6 +53,7 @@ func Provider(version string) *schema.Provider { "castai_organization_members": resourceOrganizationMembers(), "castai_sso_connection": resourceSSOConnection(), "castai_service_account": resourceServiceAccount(), + "castai_service_account_key": resourceServiceAccountKey(), "castai_workload_scaling_policy": resourceWorkloadScalingPolicy(), "castai_organization_group": resourceOrganizationGroup(), "castai_role_bindings": resourceRoleBindings(), diff --git a/castai/resource_service_account.go b/castai/resource_service_account.go index 6928d6bb..ccb01cbe 100644 --- a/castai/resource_service_account.go +++ b/castai/resource_service_account.go @@ -24,6 +24,15 @@ const ( FieldServiceAccountAuthorID = "id" FieldServiceAccountAuthorEmail = "email" FieldServiceAccountAuthorKind = "kind" + + FieldServiceAccountKeyID = "id" + FieldServiceAccountKeyOrganizationID = "organization_id" + FieldServiceAccountKeyServiceAccountID = "service_account_id" + FieldServiceAccountKeyName = "name" + FieldServiceAccountKeyPrefix = "prefix" + FieldServiceAccountKeyLastUsedAt = "last_used_at" + FieldServiceAccountKeyExpiresAt = "expires_at" + FieldServiceAccountKeyActive = "active" ) func resourceServiceAccount() *schema.Resource { @@ -33,9 +42,10 @@ func resourceServiceAccount() *schema.Resource { UpdateContext: resourceServiceAccountUpdate, DeleteContext: resourceServiceAccountDelete, - Description: "Service Account resource allows managing CAST AI service accounts.", + Description: "Service account resource allows managing CAST AI service accounts.", Timeouts: &schema.ResourceTimeout{ Create: schema.DefaultTimeout(3 * time.Minute), + Read: schema.DefaultTimeout(3 * time.Minute), Update: schema.DefaultTimeout(3 * time.Minute), Delete: schema.DefaultTimeout(3 * time.Minute), }, @@ -278,3 +288,73 @@ func getOrganizationID(ctx context.Context, data *schema.ResourceData, meta inte return organizationID, nil } + +func resourceServiceAccountKey() *schema.Resource { + return &schema.Resource{ + Description: "Service account key resource allows managing CAST AI service account keys.", + CreateContext: resourceServiceAccountKeyCreate, + ReadContext: resourceServiceAccountKeyRead, + UpdateContext: resourceServiceAccountKeyUpdate, + DeleteContext: resourceServiceAccountKeyDelete, + Timeouts: &schema.ResourceTimeout{ + Create: schema.DefaultTimeout(3 * time.Minute), + Read: schema.DefaultTimeout(3 * time.Minute), + Update: schema.DefaultTimeout(3 * time.Minute), + Delete: schema.DefaultTimeout(3 * time.Minute), + }, + Schema: map[string]*schema.Schema{ + FieldServiceAccountKeyOrganizationID: { + Type: schema.TypeString, + Required: true, + Description: "ID of the organization.", + }, + FieldServiceAccountKeyServiceAccountID: { + Type: schema.TypeString, + Required: true, + Description: "ID of the service account.", + }, + FieldServiceAccountKeyName: { + Type: schema.TypeString, + Required: true, + Description: "Name of the service account key.", + }, + FieldServiceAccountKeyPrefix: { + Type: schema.TypeString, + Computed: true, + Description: "Prefix of the service account key.", + }, + FieldServiceAccountKeyLastUsedAt: { + Type: schema.TypeString, + Computed: true, + Description: "Last time the service account key was used.", + }, + FieldServiceAccountKeyExpiresAt: { + Type: schema.TypeString, + Required: true, + ForceNew: true, + Description: "Expiration date of the service account key.", + }, + FieldServiceAccountKeyActive: { + Type: schema.TypeBool, + Optional: true, + Description: "Active status of the service account key.", + }, + }, + } +} + +func resourceServiceAccountKeyRead(ctx context.Context, data *schema.ResourceData, meta interface{}) diag.Diagnostics { + return diag.Errorf("not implemented") +} + +func resourceServiceAccountKeyCreate(ctx context.Context, data *schema.ResourceData, meta interface{}) diag.Diagnostics { + return diag.Errorf("not implemented") +} + +func resourceServiceAccountKeyUpdate(ctx context.Context, data *schema.ResourceData, meta interface{}) diag.Diagnostics { + return diag.Errorf("not implemented") +} + +func resourceServiceAccountKeyDelete(ctx context.Context, data *schema.ResourceData, meta interface{}) diag.Diagnostics { + return diag.Errorf("not implemented") +} diff --git a/castai/sdk/api.gen.go b/castai/sdk/api.gen.go index d2c0d3c1..31f2dc8f 100644 --- a/castai/sdk/api.gen.go +++ b/castai/sdk/api.gen.go @@ -4464,6 +4464,7 @@ type WorkloadoptimizationV1UpdateWorkloadV2 struct { // WorkloadoptimizationV1VPAConfig defines model for workloadoptimization.v1.VPAConfig. type WorkloadoptimizationV1VPAConfig struct { AntiAffinity WorkloadoptimizationV1AntiAffinitySettings `json:"antiAffinity"` + ApplyType WorkloadoptimizationV1ApplyType `json:"applyType"` ContainerConstraints []WorkloadoptimizationV1ContainerConstraints `json:"containerConstraints"` Cpu WorkloadoptimizationV1ResourceConfig `json:"cpu"` diff --git a/docs/resources/service_account.md b/docs/resources/service_account.md index c83f36f8..9bdd8c29 100644 --- a/docs/resources/service_account.md +++ b/docs/resources/service_account.md @@ -3,12 +3,12 @@ page_title: "castai_service_account Resource - terraform-provider-castai" subcategory: "" description: |- - Service Account resource allows managing CAST AI service accounts. + Service account resource allows managing CAST AI service accounts. --- # castai_service_account (Resource) -Service Account resource allows managing CAST AI service accounts. +Service account resource allows managing CAST AI service accounts. ## Example Usage @@ -46,6 +46,7 @@ Optional: - `create` (String) - `delete` (String) +- `read` (String) - `update` (String) diff --git a/docs/resources/service_account_key.md b/docs/resources/service_account_key.md new file mode 100644 index 00000000..b18aa488 --- /dev/null +++ b/docs/resources/service_account_key.md @@ -0,0 +1,46 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "castai_service_account_key Resource - terraform-provider-castai" +subcategory: "" +description: |- + Service account key resource allows managing CAST AI service account keys. +--- + +# castai_service_account_key (Resource) + +Service account key resource allows managing CAST AI service account keys. + + + + +## Schema + +### Required + +- `expires_at` (String) Expiration date of the service account key. +- `name` (String) Name of the service account key. +- `organization_id` (String) ID of the organization. +- `service_account_id` (String) ID of the service account. + +### Optional + +- `active` (Boolean) Active status of the service account key. +- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) + +### Read-Only + +- `id` (String) The ID of this resource. +- `last_used_at` (String) Last time the service account key was used. +- `prefix` (String) Prefix of the service account key. + + +### Nested Schema for `timeouts` + +Optional: + +- `create` (String) +- `delete` (String) +- `read` (String) +- `update` (String) + + From b946f8a37e6289c8d029f08e927996dfe7a035e6 Mon Sep 17 00:00:00 2001 From: radekska Date: Wed, 11 Dec 2024 10:17:36 +0100 Subject: [PATCH 16/24] wip --- castai/resource_service_account.go | 122 ++++++++++++++++++++++++++- castai/sdk/api.gen.go | 18 ++++ castai/sdk/client.gen.go | 131 +++++++++++++++++++++++++++++ castai/sdk/mock/client.go | 35 ++++++++ 4 files changed, 304 insertions(+), 2 deletions(-) diff --git a/castai/resource_service_account.go b/castai/resource_service_account.go index ccb01cbe..3fa96b3c 100644 --- a/castai/resource_service_account.go +++ b/castai/resource_service_account.go @@ -106,6 +106,10 @@ func resourceServiceAccountRead(ctx context.Context, data *schema.ResourceData, }) resp, err := client.ServiceAccountsAPIGetServiceAccountWithResponse(ctx, organizationID, data.Id()) + if err != nil { + return diag.Errorf("getting service account: %v", err) + } + if resp.StatusCode() == http.StatusNotFound { tflog.Warn(ctx, "resource is not found, removing from state", map[string]interface{}{ "resource_id": data.Id(), @@ -344,11 +348,125 @@ func resourceServiceAccountKey() *schema.Resource { } func resourceServiceAccountKeyRead(ctx context.Context, data *schema.ResourceData, meta interface{}) diag.Diagnostics { - return diag.Errorf("not implemented") + client := meta.(*ProviderConfig).api + + if data.Id() == "" { + return diag.Errorf("service account key ID is not set") + } + + organizationID, err := getOrganizationID(ctx, data, meta) + if err != nil { + return diag.FromErr(err) + } + + serviceAccountID := data.Get(FieldServiceAccountKeyServiceAccountID).(string) + if serviceAccountID == "" { + return diag.Errorf("service account ID is not set") + } + serviceAccountKeyID := data.Id() + + logKeys := map[string]interface{}{ + "resource_id": serviceAccountKeyID, + "organization_id": organizationID, + "service_account_id": serviceAccountID, + } + + tflog.Info(ctx, "reading service account key", logKeys) + + resp, err := client.ServiceAccountsAPIGetServiceAccountKeyWithResponse(ctx, organizationID, serviceAccountID, serviceAccountKeyID) + if err != nil { + return diag.Errorf("reading service account key: %v", err) + } + if resp.StatusCode() == http.StatusNotFound { + tflog.Warn(ctx, "resource is not found, removing from state", logKeys) + data.SetId("") + return nil + } + + if err := sdk.CheckOKResponse(resp, err); err != nil { + return diag.Errorf("reading service account key: %v", err) + } + + tflog.Info(ctx, "found service account key", logKeys) + + serviceAccountKey := resp.JSON200 + + if err := data.Set(FieldServiceAccountKeyOrganizationID, organizationID); err != nil { + return diag.Errorf("setting field %s: %v", FieldServiceAccountKeyOrganizationID, err) + } + + if err := data.Set(FieldServiceAccountKeyServiceAccountID, serviceAccountID); err != nil { + return diag.Errorf("setting field %s: %v", FieldServiceAccountKeyServiceAccountID, err) + } + + if err := data.Set(FieldServiceAccountKeyName, serviceAccountKey.Key.Name); err != nil { + return diag.Errorf("setting field %s: %v", FieldServiceAccountKeyName, err) + } + + if err := data.Set(FieldServiceAccountKeyPrefix, serviceAccountKey.Key.Prefix); err != nil { + return diag.Errorf("setting field %s: %v", FieldServiceAccountKeyPrefix, err) + } + + if err := data.Set(FieldServiceAccountKeyLastUsedAt, serviceAccountKey.Key.LastUsedAt); err != nil { + return diag.Errorf("setting field %s: %v", FieldServiceAccountKeyLastUsedAt, err) + } + + if err := data.Set(FieldServiceAccountKeyExpiresAt, serviceAccountKey.Key.ExpiresAt); err != nil { + return diag.Errorf("setting field %s: %v", FieldServiceAccountKeyExpiresAt, err) + } + + if err := data.Set(FieldServiceAccountKeyActive, serviceAccountKey.Key.Active); err != nil { + return diag.Errorf("setting field %s: %v", FieldServiceAccountKeyActive, err) + } + return nil } func resourceServiceAccountKeyCreate(ctx context.Context, data *schema.ResourceData, meta interface{}) diag.Diagnostics { - return diag.Errorf("not implemented") + client := meta.(*ProviderConfig).api + + organizationID, err := getOrganizationID(ctx, data, meta) + if err != nil { + return diag.FromErr(err) + } + serviceAccountID := data.Get(FieldServiceAccountKeyServiceAccountID).(string) + name := data.Get(FieldServiceAccountKeyName).(string) + expiresAt := data.Get(FieldServiceAccountKeyExpiresAt).(string) + active := data.Get(FieldServiceAccountKeyActive).(bool) + + expiresAtParsed, err := time.Parse(time.RFC3339, expiresAt) + if err != nil { + return diag.Errorf("parsing expires_at date: %v", err) + } + + logKeys := map[string]interface{}{ + "name": name, + "organization_id": organizationID, + "service_account_id": serviceAccountID, + } + + tflog.Info(ctx, "creating service account key", logKeys) + + resp, err := client.ServiceAccountsAPICreateServiceAccountKeyWithResponse( + ctx, + organizationID, + serviceAccountID, + sdk.ServiceAccountsAPICreateServiceAccountKeyRequest{ + Key: sdk.CastaiServiceaccountsV1beta1CreateServiceAccountKeyRequestKey{ + Active: &active, + ExpiresAt: &expiresAtParsed, + Name: name, + }, + }, + ) + if err := sdk.CheckOKResponse(resp, err); err != nil { + return diag.Errorf("creating service account key: %v", err) + } + + logKeys["resource_id"] = *resp.JSON200.Id + tflog.Info(ctx, "created service account key", logKeys) + + data.SetId(*resp.JSON200.Id) + return resourceServiceAccountKeyRead(ctx, data, meta) } func resourceServiceAccountKeyUpdate(ctx context.Context, data *schema.ResourceData, meta interface{}) diag.Diagnostics { diff --git a/castai/sdk/api.gen.go b/castai/sdk/api.gen.go index 31f2dc8f..000403df 100644 --- a/castai/sdk/api.gen.go +++ b/castai/sdk/api.gen.go @@ -1424,6 +1424,9 @@ type CastaiRbacV1beta1Group struct { // ID is the unique identifier of the group. Id *string `json:"id,omitempty"` + // Method used to create group, eg.: console, terraform. + ManagedBy *string `json:"managedBy,omitempty"` + // Name is the name of the group. Name *string `json:"name,omitempty"` @@ -1511,6 +1514,9 @@ type CastaiRbacV1beta1RoleBinding struct { // ID is the unique identifier of the role binding. Id *string `json:"id,omitempty"` + // Method used to create role binding, eg.: console, terraform. + ManagedBy *string `json:"managedBy,omitempty"` + // Name is the name of the role binding. Name *string `json:"name,omitempty"` OrganizationId *string `json:"organizationId,omitempty"` @@ -1608,6 +1614,9 @@ type CastaiRbacV1beta1UserSubject struct { // Key is the readable version of the service account key. type CastaiServiceaccountsV1beta1CreateServiceAccountKeyRequestKey struct { + // Active is the active state of the key. + Active *bool `json:"active,omitempty"` + // ExpiresAt is the expiration time of the key. // A null value means that the key will never expire. ExpiresAt *time.Time `json:"expiresAt,omitempty"` @@ -1668,6 +1677,12 @@ type CastaiServiceaccountsV1beta1DeleteServiceAccountKeyResponse = map[string]in // DeleteServiceAccountResponse is the response for deleting a service account. type CastaiServiceaccountsV1beta1DeleteServiceAccountResponse = map[string]interface{} +// GetServiceAccountKeyResponse is the response for getting a service account key. +type CastaiServiceaccountsV1beta1GetServiceAccountKeyResponse struct { + // Key is the key for the service account. + Key CastaiServiceaccountsV1beta1ServiceAccountKey `json:"key"` +} + // GetServiceAccountResponse is the response for getting a service account. type CastaiServiceaccountsV1beta1GetServiceAccountResponse struct { // ServiceAccounts is the readable version of the service accounts. @@ -1706,6 +1721,9 @@ type CastaiServiceaccountsV1beta1ServiceAccount struct { // Keys is the list of keys associated with the service account. Keys *[]CastaiServiceaccountsV1beta1ServiceAccountKey `json:"keys,omitempty"` + // Method used to create role binding, eg.: console, terraform. + ManagedBy *string `json:"managedBy,omitempty"` + // Name is the name of the service account. Name *string `json:"name,omitempty"` } diff --git a/castai/sdk/client.gen.go b/castai/sdk/client.gen.go index bccd2fdd..f5975a72 100644 --- a/castai/sdk/client.gen.go +++ b/castai/sdk/client.gen.go @@ -452,6 +452,9 @@ type ClientInterface interface { // ServiceAccountsAPIDeleteServiceAccountKey request ServiceAccountsAPIDeleteServiceAccountKey(ctx context.Context, organizationId string, serviceAccountId string, keyId string, reqEditors ...RequestEditorFn) (*http.Response, error) + // ServiceAccountsAPIGetServiceAccountKey request + ServiceAccountsAPIGetServiceAccountKey(ctx context.Context, organizationId string, serviceAccountId string, keyId string, reqEditors ...RequestEditorFn) (*http.Response, error) + // UsersAPIRemoveOrganizationUsers request UsersAPIRemoveOrganizationUsers(ctx context.Context, organizationId string, params *UsersAPIRemoveOrganizationUsersParams, reqEditors ...RequestEditorFn) (*http.Response, error) @@ -2221,6 +2224,18 @@ func (c *Client) ServiceAccountsAPIDeleteServiceAccountKey(ctx context.Context, return c.Client.Do(req) } +func (c *Client) ServiceAccountsAPIGetServiceAccountKey(ctx context.Context, organizationId string, serviceAccountId string, keyId string, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewServiceAccountsAPIGetServiceAccountKeyRequest(c.Server, organizationId, serviceAccountId, keyId) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + func (c *Client) UsersAPIRemoveOrganizationUsers(ctx context.Context, organizationId string, params *UsersAPIRemoveOrganizationUsersParams, reqEditors ...RequestEditorFn) (*http.Response, error) { req, err := NewUsersAPIRemoveOrganizationUsersRequest(c.Server, organizationId, params) if err != nil { @@ -7480,6 +7495,54 @@ func NewServiceAccountsAPIDeleteServiceAccountKeyRequest(server string, organiza return req, nil } +// NewServiceAccountsAPIGetServiceAccountKeyRequest generates requests for ServiceAccountsAPIGetServiceAccountKey +func NewServiceAccountsAPIGetServiceAccountKeyRequest(server string, organizationId string, serviceAccountId string, keyId string) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithLocation("simple", false, "organizationId", runtime.ParamLocationPath, organizationId) + if err != nil { + return nil, err + } + + var pathParam1 string + + pathParam1, err = runtime.StyleParamWithLocation("simple", false, "serviceAccountId", runtime.ParamLocationPath, serviceAccountId) + if err != nil { + return nil, err + } + + var pathParam2 string + + pathParam2, err = runtime.StyleParamWithLocation("simple", false, "keyId", runtime.ParamLocationPath, keyId) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/v1/organizations/%s/service-accounts/%s/keys/%s", pathParam0, pathParam1, pathParam2) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("GET", queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + // NewUsersAPIRemoveOrganizationUsersRequest generates requests for UsersAPIRemoveOrganizationUsers func NewUsersAPIRemoveOrganizationUsersRequest(server string, organizationId string, params *UsersAPIRemoveOrganizationUsersParams) (*http.Request, error) { var err error @@ -10135,6 +10198,9 @@ type ClientWithResponsesInterface interface { // ServiceAccountsAPIDeleteServiceAccountKey request ServiceAccountsAPIDeleteServiceAccountKeyWithResponse(ctx context.Context, organizationId string, serviceAccountId string, keyId string) (*ServiceAccountsAPIDeleteServiceAccountKeyResponse, error) + // ServiceAccountsAPIGetServiceAccountKey request + ServiceAccountsAPIGetServiceAccountKeyWithResponse(ctx context.Context, organizationId string, serviceAccountId string, keyId string) (*ServiceAccountsAPIGetServiceAccountKeyResponse, error) + // UsersAPIRemoveOrganizationUsers request UsersAPIRemoveOrganizationUsersWithResponse(ctx context.Context, organizationId string, params *UsersAPIRemoveOrganizationUsersParams) (*UsersAPIRemoveOrganizationUsersResponse, error) @@ -13198,6 +13264,36 @@ func (r ServiceAccountsAPIDeleteServiceAccountKeyResponse) GetBody() []byte { // TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 +type ServiceAccountsAPIGetServiceAccountKeyResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *CastaiServiceaccountsV1beta1GetServiceAccountKeyResponse +} + +// Status returns HTTPResponse.Status +func (r ServiceAccountsAPIGetServiceAccountKeyResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r ServiceAccountsAPIGetServiceAccountKeyResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 +// Body returns body of byte array +func (r ServiceAccountsAPIGetServiceAccountKeyResponse) GetBody() []byte { + return r.Body +} + +// TODO: to have common interface. https://github.com/deepmap/oapi-codegen/issues/240 + type UsersAPIRemoveOrganizationUsersResponse struct { Body []byte HTTPResponse *http.Response @@ -15794,6 +15890,15 @@ func (c *ClientWithResponses) ServiceAccountsAPIDeleteServiceAccountKeyWithRespo return ParseServiceAccountsAPIDeleteServiceAccountKeyResponse(rsp) } +// ServiceAccountsAPIGetServiceAccountKeyWithResponse request returning *ServiceAccountsAPIGetServiceAccountKeyResponse +func (c *ClientWithResponses) ServiceAccountsAPIGetServiceAccountKeyWithResponse(ctx context.Context, organizationId string, serviceAccountId string, keyId string) (*ServiceAccountsAPIGetServiceAccountKeyResponse, error) { + rsp, err := c.ServiceAccountsAPIGetServiceAccountKey(ctx, organizationId, serviceAccountId, keyId) + if err != nil { + return nil, err + } + return ParseServiceAccountsAPIGetServiceAccountKeyResponse(rsp) +} + // UsersAPIRemoveOrganizationUsersWithResponse request returning *UsersAPIRemoveOrganizationUsersResponse func (c *ClientWithResponses) UsersAPIRemoveOrganizationUsersWithResponse(ctx context.Context, organizationId string, params *UsersAPIRemoveOrganizationUsersParams) (*UsersAPIRemoveOrganizationUsersResponse, error) { rsp, err := c.UsersAPIRemoveOrganizationUsers(ctx, organizationId, params) @@ -18838,6 +18943,32 @@ func ParseServiceAccountsAPIDeleteServiceAccountKeyResponse(rsp *http.Response) return response, nil } +// ParseServiceAccountsAPIGetServiceAccountKeyResponse parses an HTTP response from a ServiceAccountsAPIGetServiceAccountKeyWithResponse call +func ParseServiceAccountsAPIGetServiceAccountKeyResponse(rsp *http.Response) (*ServiceAccountsAPIGetServiceAccountKeyResponse, error) { + bodyBytes, err := ioutil.ReadAll(rsp.Body) + defer rsp.Body.Close() + if err != nil { + return nil, err + } + + response := &ServiceAccountsAPIGetServiceAccountKeyResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest CastaiServiceaccountsV1beta1GetServiceAccountKeyResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + } + + return response, nil +} + // ParseUsersAPIRemoveOrganizationUsersResponse parses an HTTP response from a UsersAPIRemoveOrganizationUsersWithResponse call func ParseUsersAPIRemoveOrganizationUsersResponse(rsp *http.Response) (*UsersAPIRemoveOrganizationUsersResponse, error) { bodyBytes, err := ioutil.ReadAll(rsp.Body) diff --git a/castai/sdk/mock/client.go b/castai/sdk/mock/client.go index 959a3c9a..3dcb5c4a 100644 --- a/castai/sdk/mock/client.go +++ b/castai/sdk/mock/client.go @@ -3055,6 +3055,26 @@ func (mr *MockClientInterfaceMockRecorder) ServiceAccountsAPIGetServiceAccount(c return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ServiceAccountsAPIGetServiceAccount", reflect.TypeOf((*MockClientInterface)(nil).ServiceAccountsAPIGetServiceAccount), varargs...) } +// ServiceAccountsAPIGetServiceAccountKey mocks base method. +func (m *MockClientInterface) ServiceAccountsAPIGetServiceAccountKey(ctx context.Context, organizationId, serviceAccountId, keyId string, reqEditors ...sdk.RequestEditorFn) (*http.Response, error) { + m.ctrl.T.Helper() + varargs := []interface{}{ctx, organizationId, serviceAccountId, keyId} + for _, a := range reqEditors { + varargs = append(varargs, a) + } + ret := m.ctrl.Call(m, "ServiceAccountsAPIGetServiceAccountKey", varargs...) + ret0, _ := ret[0].(*http.Response) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// ServiceAccountsAPIGetServiceAccountKey indicates an expected call of ServiceAccountsAPIGetServiceAccountKey. +func (mr *MockClientInterfaceMockRecorder) ServiceAccountsAPIGetServiceAccountKey(ctx, organizationId, serviceAccountId, keyId interface{}, reqEditors ...interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + varargs := append([]interface{}{ctx, organizationId, serviceAccountId, keyId}, reqEditors...) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ServiceAccountsAPIGetServiceAccountKey", reflect.TypeOf((*MockClientInterface)(nil).ServiceAccountsAPIGetServiceAccountKey), varargs...) +} + // ServiceAccountsAPIListServiceAccounts mocks base method. func (m *MockClientInterface) ServiceAccountsAPIListServiceAccounts(ctx context.Context, organizationId string, params *sdk.ServiceAccountsAPIListServiceAccountsParams, reqEditors ...sdk.RequestEditorFn) (*http.Response, error) { m.ctrl.T.Helper() @@ -6218,6 +6238,21 @@ func (mr *MockClientWithResponsesInterfaceMockRecorder) ServiceAccountsAPIDelete return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ServiceAccountsAPIDeleteServiceAccountWithResponse", reflect.TypeOf((*MockClientWithResponsesInterface)(nil).ServiceAccountsAPIDeleteServiceAccountWithResponse), ctx, organizationId, serviceAccountId) } +// ServiceAccountsAPIGetServiceAccountKeyWithResponse mocks base method. +func (m *MockClientWithResponsesInterface) ServiceAccountsAPIGetServiceAccountKeyWithResponse(ctx context.Context, organizationId, serviceAccountId, keyId string) (*sdk.ServiceAccountsAPIGetServiceAccountKeyResponse, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "ServiceAccountsAPIGetServiceAccountKeyWithResponse", ctx, organizationId, serviceAccountId, keyId) + ret0, _ := ret[0].(*sdk.ServiceAccountsAPIGetServiceAccountKeyResponse) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// ServiceAccountsAPIGetServiceAccountKeyWithResponse indicates an expected call of ServiceAccountsAPIGetServiceAccountKeyWithResponse. +func (mr *MockClientWithResponsesInterfaceMockRecorder) ServiceAccountsAPIGetServiceAccountKeyWithResponse(ctx, organizationId, serviceAccountId, keyId interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ServiceAccountsAPIGetServiceAccountKeyWithResponse", reflect.TypeOf((*MockClientWithResponsesInterface)(nil).ServiceAccountsAPIGetServiceAccountKeyWithResponse), ctx, organizationId, serviceAccountId, keyId) +} + // ServiceAccountsAPIGetServiceAccountWithResponse mocks base method. func (m *MockClientWithResponsesInterface) ServiceAccountsAPIGetServiceAccountWithResponse(ctx context.Context, organizationId, serviceAccountId string) (*sdk.ServiceAccountsAPIGetServiceAccountResponse, error) { m.ctrl.T.Helper() From df812ed1767090161ad0d8ff18c6b81a75bd12f6 Mon Sep 17 00:00:00 2001 From: radekska Date: Wed, 11 Dec 2024 10:24:16 +0100 Subject: [PATCH 17/24] wip --- castai/resource_service_account.go | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/castai/resource_service_account.go b/castai/resource_service_account.go index 3fa96b3c..4f42e95a 100644 --- a/castai/resource_service_account.go +++ b/castai/resource_service_account.go @@ -458,11 +458,12 @@ func resourceServiceAccountKeyCreate(ctx context.Context, data *schema.ResourceD }, }, ) - if err := sdk.CheckOKResponse(resp, err); err != nil { + if err := sdk.CheckResponseCreated(resp, err); err != nil { return diag.Errorf("creating service account key: %v", err) } - logKeys["resource_id"] = *resp.JSON200.Id + // FIXME: panic here + logKeys["resource_id"] = *resp.JSON201 tflog.Info(ctx, "created service account key", logKeys) data.SetId(*resp.JSON200.Id) From 777fb632a3f366ae44e05307d761bb15274b9a75 Mon Sep 17 00:00:00 2001 From: radekska Date: Wed, 11 Dec 2024 13:37:41 +0100 Subject: [PATCH 18/24] wip --- castai/resource_service_account.go | 120 +++++++++++++++++++++-------- castai/sdk/client.gen.go | 20 ++--- 2 files changed, 98 insertions(+), 42 deletions(-) diff --git a/castai/resource_service_account.go b/castai/resource_service_account.go index 4f42e95a..23b67f7d 100644 --- a/castai/resource_service_account.go +++ b/castai/resource_service_account.go @@ -9,6 +9,7 @@ import ( "github.com/hashicorp/terraform-plugin-log/tflog" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/castai/terraform-provider-castai/castai/sdk" ) @@ -52,15 +53,17 @@ func resourceServiceAccount() *schema.Resource { Schema: map[string]*schema.Schema{ FieldServiceAccountOrganizationID: { - Type: schema.TypeString, - Required: true, - ForceNew: true, - Description: "ID of the organization.", + Type: schema.TypeString, + Required: true, + ForceNew: true, + Description: "ID of the organization.", + ValidateDiagFunc: validation.ToDiagFunc(validation.IsUUID), }, FieldServiceAccountName: { - Type: schema.TypeString, - Required: true, - Description: "Name of the service account.", + Type: schema.TypeString, + Required: true, + Description: "Name of the service account.", + ValidateDiagFunc: validation.ToDiagFunc(validation.StringIsNotWhiteSpace), }, FieldServiceAccountDescription: { Type: schema.TypeString, @@ -241,13 +244,10 @@ func resourceServiceAccountDelete(ctx context.Context, data *schema.ResourceData "organization_id": organizationID, }) - resp, err := client.ServiceAccountsAPIDeleteServiceAccount(ctx, organizationID, serviceAccountID) - if err != nil { + resp, err := client.ServiceAccountsAPIDeleteServiceAccountWithResponse(ctx, organizationID, serviceAccountID) + if err := sdk.CheckResponseNoContent(resp, err); err != nil { return diag.Errorf("deleting service account: %v", err) } - if resp.StatusCode != http.StatusNoContent { - return diag.Errorf("deleteting service account: expected status: [204], received status: [%d]", resp.StatusCode) - } tflog.Info(ctx, "deleted service account", map[string]interface{}{ "resource_id": serviceAccountID, @@ -308,19 +308,22 @@ func resourceServiceAccountKey() *schema.Resource { }, Schema: map[string]*schema.Schema{ FieldServiceAccountKeyOrganizationID: { - Type: schema.TypeString, - Required: true, - Description: "ID of the organization.", + Type: schema.TypeString, + Required: true, + Description: "ID of the organization.", + ValidateDiagFunc: validation.ToDiagFunc(validation.IsUUID), }, FieldServiceAccountKeyServiceAccountID: { - Type: schema.TypeString, - Required: true, - Description: "ID of the service account.", + Type: schema.TypeString, + Required: true, + Description: "ID of the service account.", + ValidateDiagFunc: validation.ToDiagFunc(validation.IsUUID), }, FieldServiceAccountKeyName: { - Type: schema.TypeString, - Required: true, - Description: "Name of the service account key.", + Type: schema.TypeString, + Required: true, + Description: "Name of the service account key.", + ValidateDiagFunc: validation.ToDiagFunc(validation.StringIsNotWhiteSpace), }, FieldServiceAccountKeyPrefix: { Type: schema.TypeString, @@ -333,10 +336,11 @@ func resourceServiceAccountKey() *schema.Resource { Description: "Last time the service account key was used.", }, FieldServiceAccountKeyExpiresAt: { - Type: schema.TypeString, - Required: true, - ForceNew: true, - Description: "Expiration date of the service account key.", + Type: schema.TypeString, + Required: true, + ForceNew: true, + Description: "Expiration date of the service account key.", + ValidateDiagFunc: validation.ToDiagFunc(validation.IsRFC3339Time), }, FieldServiceAccountKeyActive: { Type: schema.TypeBool, @@ -411,8 +415,10 @@ func resourceServiceAccountKeyRead(ctx context.Context, data *schema.ResourceDat return diag.Errorf("setting field %s: %v", FieldServiceAccountKeyLastUsedAt, err) } - if err := data.Set(FieldServiceAccountKeyExpiresAt, serviceAccountKey.Key.ExpiresAt); err != nil { - return diag.Errorf("setting field %s: %v", FieldServiceAccountKeyExpiresAt, err) + if serviceAccountKey.Key.ExpiresAt != nil { + if err := data.Set(FieldServiceAccountKeyExpiresAt, serviceAccountKey.Key.ExpiresAt.String()); err != nil { + return diag.Errorf("setting field %s: %v", FieldServiceAccountKeyExpiresAt, err) + } } if err := data.Set(FieldServiceAccountKeyActive, serviceAccountKey.Key.Active); err != nil { @@ -462,18 +468,68 @@ func resourceServiceAccountKeyCreate(ctx context.Context, data *schema.ResourceD return diag.Errorf("creating service account key: %v", err) } - // FIXME: panic here - logKeys["resource_id"] = *resp.JSON201 + serviceAccountKeyID := *resp.JSON201.Id + logKeys["resource_id"] = serviceAccountKeyID tflog.Info(ctx, "created service account key", logKeys) - data.SetId(*resp.JSON200.Id) + data.SetId(serviceAccountKeyID) return resourceServiceAccountKeyRead(ctx, data, meta) } func resourceServiceAccountKeyUpdate(ctx context.Context, data *schema.ResourceData, meta interface{}) diag.Diagnostics { - return diag.Errorf("not implemented") + client := meta.(*ProviderConfig).api + organizationID, err := getOrganizationID(ctx, data, meta) + if err != nil { + return diag.FromErr(err) + } + serviceAccountID := data.Get(FieldServiceAccountKeyServiceAccountID).(string) + keyID := data.Id() + active := data.Get(FieldServiceAccountKeyActive).(bool) + + logKeys := map[string]interface{}{ + "organization_id": organizationID, + "service_account_id": serviceAccountID, + "resource_id": keyID, + } + + tflog.Info(ctx, "updating service account key", logKeys) + + resp, err := client.ServiceAccountsAPIUpdateServiceAccountKeyWithResponse(ctx, organizationID, serviceAccountID, keyID, &sdk.ServiceAccountsAPIUpdateServiceAccountKeyParams{ + KeyActive: active, + }) + + if err := sdk.CheckOKResponse(resp, err); err != nil { + return diag.Errorf("updating service account key: %v", err) + } + + tflog.Info(ctx, "updated service account key", logKeys) + + return resourceServiceAccountKeyRead(ctx, data, meta) } func resourceServiceAccountKeyDelete(ctx context.Context, data *schema.ResourceData, meta interface{}) diag.Diagnostics { - return diag.Errorf("not implemented") + client := meta.(*ProviderConfig).api + organizationID, err := getOrganizationID(ctx, data, meta) + if err != nil { + return diag.FromErr(err) + } + serviceAccountID := data.Get(FieldServiceAccountKeyServiceAccountID).(string) + keyID := data.Id() + + logKeys := map[string]interface{}{ + "organization_id": organizationID, + "service_account_id": serviceAccountID, + "resource_id": keyID, + } + + tflog.Info(ctx, "deleting service account key", logKeys) + + resp, err := client.ServiceAccountsAPIDeleteServiceAccountKeyWithResponse(ctx, organizationID, serviceAccountID, keyID) + if err := sdk.CheckResponseNoContent(resp, err); err != nil { + return diag.Errorf("deleting service account key: %v", err) + } + + tflog.Info(ctx, "deleted service account key", logKeys) + + return nil } diff --git a/castai/sdk/client.gen.go b/castai/sdk/client.gen.go index f5975a72..78bb499f 100644 --- a/castai/sdk/client.gen.go +++ b/castai/sdk/client.gen.go @@ -13176,8 +13176,7 @@ func (r ServiceAccountsAPIUpdateServiceAccountResponse) GetBody() []byte { type ServiceAccountsAPICreateServiceAccountKeyResponse struct { Body []byte HTTPResponse *http.Response - JSON200 *CastaiServiceaccountsV1beta1CreateServiceAccountKeyResponse - JSON201 *map[string]interface{} + JSON201 *CastaiServiceaccountsV1beta1CreateServiceAccountKeyResponse } // Status returns HTTPResponse.Status @@ -13238,6 +13237,7 @@ type ServiceAccountsAPIDeleteServiceAccountKeyResponse struct { Body []byte HTTPResponse *http.Response JSON200 *CastaiServiceaccountsV1beta1DeleteServiceAccountKeyResponse + JSON204 *map[string]interface{} } // Status returns HTTPResponse.Status @@ -18872,15 +18872,8 @@ func ParseServiceAccountsAPICreateServiceAccountKeyResponse(rsp *http.Response) } switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest CastaiServiceaccountsV1beta1CreateServiceAccountKeyResponse - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON200 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 201: - var dest map[string]interface{} + var dest CastaiServiceaccountsV1beta1CreateServiceAccountKeyResponse if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } @@ -18938,6 +18931,13 @@ func ParseServiceAccountsAPIDeleteServiceAccountKeyResponse(rsp *http.Response) } response.JSON200 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 204: + var dest map[string]interface{} + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON204 = &dest + } return response, nil From dcbb405d03b0cc410b5d40b2d4a64607d87c3ce6 Mon Sep 17 00:00:00 2001 From: radekska Date: Wed, 11 Dec 2024 15:24:06 +0100 Subject: [PATCH 19/24] wip --- castai/resource_service_account.go | 12 +- castai/resource_service_account_test.go | 165 +++++++++++++++++++++++- castai/sdk/api.gen.go | 14 +- castai/sdk/client.gen.go | 77 +++++++---- castai/sdk/mock/client.go | 51 ++++++-- castai/sdk/utils_response.go | 22 +++- 6 files changed, 287 insertions(+), 54 deletions(-) diff --git a/castai/resource_service_account.go b/castai/resource_service_account.go index 23b67f7d..ae7dd5a5 100644 --- a/castai/resource_service_account.go +++ b/castai/resource_service_account.go @@ -244,8 +244,8 @@ func resourceServiceAccountDelete(ctx context.Context, data *schema.ResourceData "organization_id": organizationID, }) - resp, err := client.ServiceAccountsAPIDeleteServiceAccountWithResponse(ctx, organizationID, serviceAccountID) - if err := sdk.CheckResponseNoContent(resp, err); err != nil { + resp, err := client.ServiceAccountsAPIDeleteServiceAccount(ctx, organizationID, serviceAccountID) + if err := sdk.CheckRawResponseNoContent(resp, err); err != nil { return diag.Errorf("deleting service account: %v", err) } @@ -494,8 +494,8 @@ func resourceServiceAccountKeyUpdate(ctx context.Context, data *schema.ResourceD tflog.Info(ctx, "updating service account key", logKeys) - resp, err := client.ServiceAccountsAPIUpdateServiceAccountKeyWithResponse(ctx, organizationID, serviceAccountID, keyID, &sdk.ServiceAccountsAPIUpdateServiceAccountKeyParams{ - KeyActive: active, + resp, err := client.ServiceAccountsAPIUpdateServiceAccountKeyWithResponse(ctx, organizationID, serviceAccountID, keyID, sdk.KeyIsTheServiceAccountKeyToUpdate{ + Active: active, }) if err := sdk.CheckOKResponse(resp, err); err != nil { @@ -524,8 +524,8 @@ func resourceServiceAccountKeyDelete(ctx context.Context, data *schema.ResourceD tflog.Info(ctx, "deleting service account key", logKeys) - resp, err := client.ServiceAccountsAPIDeleteServiceAccountKeyWithResponse(ctx, organizationID, serviceAccountID, keyID) - if err := sdk.CheckResponseNoContent(resp, err); err != nil { + resp, err := client.ServiceAccountsAPIDeleteServiceAccountKey(ctx, organizationID, serviceAccountID, keyID) + if err := sdk.CheckRawResponseNoContent(resp, err); err != nil { return diag.Errorf("deleting service account key: %v", err) } diff --git a/castai/resource_service_account_test.go b/castai/resource_service_account_test.go index 62ab2b31..3900472c 100644 --- a/castai/resource_service_account_test.go +++ b/castai/resource_service_account_test.go @@ -19,7 +19,7 @@ import ( mock_sdk "github.com/castai/terraform-provider-castai/castai/sdk/mock" ) -func TestServiceAccountReadContext(t *testing.T) { +func TestServiceAccount_ReadContext(t *testing.T) { t.Parallel() t.Run("when state is missing service account ID then return error", func(t *testing.T) { @@ -184,7 +184,7 @@ Tainted = false }) } -func TestServiceAccountCreateContext(t *testing.T) { +func TestServiceAccount_CreateContext(t *testing.T) { t.Parallel() t.Run("when ServiceAccountsAPI responds with 201 then populate the state", func(t *testing.T) { @@ -348,7 +348,7 @@ func TestServiceAccountCreateContext(t *testing.T) { }) } -func TestServiceAccountDeleteContext(t *testing.T) { +func TestServiceAccount_DeleteContext(t *testing.T) { t.Run("when ServiceAccountsAPI responds with an error then return error", func(t *testing.T) { r := require.New(t) mockClient := mock_sdk.NewMockClientInterface(gomock.NewController(t)) @@ -421,7 +421,7 @@ func TestServiceAccountDeleteContext(t *testing.T) { r.NotNil(result) r.True(result.HasError()) r.Len(result, 1) - r.Equal("deleteting service account: expected status: [204], received status: [500]", result[0].Summary) + r.Equal("deleting service account: expected status code 204, received: status=500 body=mock error response", result[0].Summary) }) t.Run("when ServiceAccountsAPI responds with 204 then return nil", func(t *testing.T) { @@ -465,7 +465,7 @@ func TestServiceAccountDeleteContext(t *testing.T) { }) } -func TestServiceAccountUpdateContext(t *testing.T) { +func TestServiceAccount_UpdateContext(t *testing.T) { t.Run("when ServiceAccountsAPI responds with an error then return error", func(t *testing.T) { r := require.New(t) mockClient := mock_sdk.NewMockClientInterface(gomock.NewController(t)) @@ -575,7 +575,7 @@ func TestServiceAccountUpdateContext(t *testing.T) { "email": "user-email" }, "keys": [] - }}`, serviceAccountID,userID)))) + }}`, serviceAccountID, userID)))) mockClient.EXPECT(). ServiceAccountsAPIUpdateServiceAccount(gomock.Any(), organizationID, serviceAccountID, gomock.Any()). @@ -588,7 +588,7 @@ func TestServiceAccountUpdateContext(t *testing.T) { Return(&http.Response{ StatusCode: http.StatusOK, Body: readBody, - Header: map[string][]string{"Content-Type": {"json"}}, + Header: map[string][]string{"Content-Type": {"json"}}, }, nil) resource := resourceServiceAccount() @@ -608,3 +608,154 @@ func TestServiceAccountUpdateContext(t *testing.T) { r.Equal("new description", data.Get("description")) }) } + +// TODO: test me! :( +func TestServiceAccountKey_CreateContext(t *testing.T) { + t.Parallel() + + t.Run("when ServiceAccountAPI respond with 404 then remove form the state gracefully", func(t *testing.T) { + r := require.New(t) + mockClient := mock_sdk.NewMockClientInterface(gomock.NewController(t)) + + ctx := context.Background() + provider := &ProviderConfig{ + api: &sdk.ClientWithResponses{ + ClientInterface: mockClient, + }, + } + body := io.NopCloser(bytes.NewReader([]byte(""))) + + organizationID := "4e4cd9eb-82eb-407e-a926-e5fef81cab50" + serviceAccountID := "b11f5945-22ca-4101-a86e-d6e37f44a415" + keyID := "da5664b3-87bf-4e03-9d1c-ec26049991b7" + + mockClient.EXPECT(). + ServiceAccountsAPIGetServiceAccountKey(gomock.Any(), organizationID, serviceAccountID, keyID). + Return(&http.Response{StatusCode: http.StatusNotFound, Body: body, Header: map[string][]string{"Content-Type": {"json"}}}, nil) + + stateValue := cty.ObjectVal(map[string]cty.Value{ + "organization_id": cty.StringVal(organizationID), + "service_account_id": cty.StringVal(serviceAccountID), + }) + state := terraform.NewInstanceStateShimmedFromValue(stateValue, 0) + state.ID = serviceAccountID + + resource := resourceServiceAccountKey() + data := resource.Data(state) + + result := resource.ReadContext(ctx, data, provider) + + r.Nil(result) + r.False(result.HasError()) + r.Empty(data.Id()) + }) + + t.Run("when ServiceAccountAPI respond with 500 then return error", func(t *testing.T) { + r := require.New(t) + mockClient := mock_sdk.NewMockClientInterface(gomock.NewController(t)) + + ctx := context.Background() + provider := &ProviderConfig{ + api: &sdk.ClientWithResponses{ + ClientInterface: mockClient, + }, + } + body := io.NopCloser(bytes.NewReader([]byte("panic"))) + + organizationID := "4e4cd9eb-82eb-407e-a926-e5fef81cab50" + serviceAccountID := "b11f5945-22ca-4101-a86e-d6e37f44a415" + keyID := "da5664b3-87bf-4e03-9d1c-ec26049991b7" + + mockClient.EXPECT(). + ServiceAccountsAPIGetServiceAccountKey(gomock.Any(), organizationID, serviceAccountID, keyID). + Return(&http.Response{StatusCode: http.StatusInternalServerError, Body: body, Header: map[string][]string{"Content-Type": {"json"}}}, nil) + + stateValue := cty.ObjectVal(map[string]cty.Value{ + "organization_id": cty.StringVal(organizationID), + "service_account_id": cty.StringVal(serviceAccountID), + }) + state := terraform.NewInstanceStateShimmedFromValue(stateValue, 0) + state.ID = serviceAccountID + + resource := resourceServiceAccountKey() + data := resource.Data(state) + + result := resource.ReadContext(ctx, data, provider) + + r.NotNil(result) + r.True(result.HasError()) + r.Len(result, 1) + r.Equal("getting service account key: expected status code 200, received: status=500 body=panic", result[0].Summary) + }) + + t.Run("when ServiceAccountAPI respond with 200 then populate the state", func(t *testing.T) { + r := require.New(t) + mockClient := mock_sdk.NewMockClientInterface(gomock.NewController(t)) + + ctx := context.Background() + provider := &ProviderConfig{ + api: &sdk.ClientWithResponses{ + ClientInterface: mockClient, + }, + } + + organizationID := "4e4cd9eb-82eb-407e-a926-e5fef81cab50" + serviceAccountID := "b11f5945-22ca-4101-a86e-d6e37f44a415" + userID := "671b2ebb-f361-42f0-aa2f-3049de93f8c1" + keyID := "da5664b3-87bf-4e03-9d1c-ec26049991b7" + + body := io.NopCloser(bytes.NewReader([]byte(fmt.Sprintf(`{ + "key": { + "id": %q, + "name": "test-key", + "prefix": "123q", + "lastUsedAt": "2024-12-11T13:47:20.927Z", + "expiresAt": "2024-12-11T13:47:20.927Z", + "active": true + } +}`, keyID)))) + + mockClient.EXPECT(). + ServiceAccountsAPIGetServiceAccountKey(gomock.Any(), organizationID, serviceAccountID, keyID). + Return(&http.Response{StatusCode: http.StatusOK, Body: body, Header: map[string][]string{"Content-Type": {"json"}}}, nil) + + stateValue := cty.ObjectVal(map[string]cty.Value{ + "organization_id": cty.StringVal(organizationID), + "service_account_id": cty.StringVal(serviceAccountID), + }) + state := terraform.NewInstanceStateShimmedFromValue(stateValue, 0) + state.ID = serviceAccountID + + resource := resourceServiceAccountKey() + data := resource.Data(state) + + result := resource.ReadContext(ctx, data, provider) + + r.Nil(result) + r.False(result.HasError()) + r.Equal(fmt.Sprintf(`ID = %s +author.# = 1 +author.0.email = user-email +author.0.id = %s +author.0.kind = user +description = service-account-description +email = service-account-email +name = service-account-name +organization_id = %s +Tainted = false +`, serviceAccountID, userID, organizationID), data.State().String()) + }) + +} + +func TestServiceAccountKey_ReadContext(t *testing.T) { + t.Parallel() +} + +func TestServiceAccountKey_DeleteContext(t *testing.T) { + t.Parallel() +} + +func TestServiceAccountKey_UpdateContext(t *testing.T) { + t.Parallel() +} diff --git a/castai/sdk/api.gen.go b/castai/sdk/api.gen.go index 000403df..c7a47cd2 100644 --- a/castai/sdk/api.gen.go +++ b/castai/sdk/api.gen.go @@ -398,6 +398,11 @@ type GroupsIsTheGroupsToBeUpdated struct { Name string `json:"name"` } +// KeyIsTheServiceAccountKeyToUpdate defines model for Key_is_the_service_account_key_to_update_. +type KeyIsTheServiceAccountKeyToUpdate struct { + Active bool `json:"active"` +} + // RoleBindingIsTheRoleBindingToBeUpdated defines model for RoleBinding_is_the_role_binding_to_be_updated_. type RoleBindingIsTheRoleBindingToBeUpdated struct { // Definition represents the role binding definition. @@ -4888,10 +4893,8 @@ type ServiceAccountsAPIUpdateServiceAccountJSONBody = ServiceAccountsAPIUpdateSe // ServiceAccountsAPICreateServiceAccountKeyJSONBody defines parameters for ServiceAccountsAPICreateServiceAccountKey. type ServiceAccountsAPICreateServiceAccountKeyJSONBody = ServiceAccountsAPICreateServiceAccountKeyRequest -// ServiceAccountsAPIUpdateServiceAccountKeyParams defines parameters for ServiceAccountsAPIUpdateServiceAccountKey. -type ServiceAccountsAPIUpdateServiceAccountKeyParams struct { - KeyActive bool `form:"key.active" json:"key.active"` -} +// ServiceAccountsAPIUpdateServiceAccountKeyJSONBody defines parameters for ServiceAccountsAPIUpdateServiceAccountKey. +type ServiceAccountsAPIUpdateServiceAccountKeyJSONBody = KeyIsTheServiceAccountKeyToUpdate // UsersAPIRemoveOrganizationUsersParams defines parameters for UsersAPIRemoveOrganizationUsers. type UsersAPIRemoveOrganizationUsersParams struct { @@ -5164,6 +5167,9 @@ type ServiceAccountsAPIUpdateServiceAccountJSONRequestBody = ServiceAccountsAPIU // ServiceAccountsAPICreateServiceAccountKeyJSONRequestBody defines body for ServiceAccountsAPICreateServiceAccountKey for application/json ContentType. type ServiceAccountsAPICreateServiceAccountKeyJSONRequestBody = ServiceAccountsAPICreateServiceAccountKeyJSONBody +// ServiceAccountsAPIUpdateServiceAccountKeyJSONRequestBody defines body for ServiceAccountsAPIUpdateServiceAccountKey for application/json ContentType. +type ServiceAccountsAPIUpdateServiceAccountKeyJSONRequestBody = ServiceAccountsAPIUpdateServiceAccountKeyJSONBody + // UsersAPIAddUserToOrganizationJSONRequestBody defines body for UsersAPIAddUserToOrganization for application/json ContentType. type UsersAPIAddUserToOrganizationJSONRequestBody = UsersAPIAddUserToOrganizationJSONBody diff --git a/castai/sdk/client.gen.go b/castai/sdk/client.gen.go index 78bb499f..6b501406 100644 --- a/castai/sdk/client.gen.go +++ b/castai/sdk/client.gen.go @@ -446,8 +446,10 @@ type ClientInterface interface { ServiceAccountsAPICreateServiceAccountKey(ctx context.Context, organizationId string, serviceAccountId string, body ServiceAccountsAPICreateServiceAccountKeyJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) - // ServiceAccountsAPIUpdateServiceAccountKey request - ServiceAccountsAPIUpdateServiceAccountKey(ctx context.Context, organizationId string, serviceAccountId string, keyId string, params *ServiceAccountsAPIUpdateServiceAccountKeyParams, reqEditors ...RequestEditorFn) (*http.Response, error) + // ServiceAccountsAPIUpdateServiceAccountKey request with any body + ServiceAccountsAPIUpdateServiceAccountKeyWithBody(ctx context.Context, organizationId string, serviceAccountId string, keyId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + ServiceAccountsAPIUpdateServiceAccountKey(ctx context.Context, organizationId string, serviceAccountId string, keyId string, body ServiceAccountsAPIUpdateServiceAccountKeyJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) // ServiceAccountsAPIDeleteServiceAccountKey request ServiceAccountsAPIDeleteServiceAccountKey(ctx context.Context, organizationId string, serviceAccountId string, keyId string, reqEditors ...RequestEditorFn) (*http.Response, error) @@ -2200,8 +2202,20 @@ func (c *Client) ServiceAccountsAPICreateServiceAccountKey(ctx context.Context, return c.Client.Do(req) } -func (c *Client) ServiceAccountsAPIUpdateServiceAccountKey(ctx context.Context, organizationId string, serviceAccountId string, keyId string, params *ServiceAccountsAPIUpdateServiceAccountKeyParams, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewServiceAccountsAPIUpdateServiceAccountKeyRequest(c.Server, organizationId, serviceAccountId, keyId, params) +func (c *Client) ServiceAccountsAPIUpdateServiceAccountKeyWithBody(ctx context.Context, organizationId string, serviceAccountId string, keyId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewServiceAccountsAPIUpdateServiceAccountKeyRequestWithBody(c.Server, organizationId, serviceAccountId, keyId, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) ServiceAccountsAPIUpdateServiceAccountKey(ctx context.Context, organizationId string, serviceAccountId string, keyId string, body ServiceAccountsAPIUpdateServiceAccountKeyJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewServiceAccountsAPIUpdateServiceAccountKeyRequest(c.Server, organizationId, serviceAccountId, keyId, body) if err != nil { return nil, err } @@ -7383,8 +7397,19 @@ func NewServiceAccountsAPICreateServiceAccountKeyRequestWithBody(server string, return req, nil } -// NewServiceAccountsAPIUpdateServiceAccountKeyRequest generates requests for ServiceAccountsAPIUpdateServiceAccountKey -func NewServiceAccountsAPIUpdateServiceAccountKeyRequest(server string, organizationId string, serviceAccountId string, keyId string, params *ServiceAccountsAPIUpdateServiceAccountKeyParams) (*http.Request, error) { +// NewServiceAccountsAPIUpdateServiceAccountKeyRequest calls the generic ServiceAccountsAPIUpdateServiceAccountKey builder with application/json body +func NewServiceAccountsAPIUpdateServiceAccountKeyRequest(server string, organizationId string, serviceAccountId string, keyId string, body ServiceAccountsAPIUpdateServiceAccountKeyJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewServiceAccountsAPIUpdateServiceAccountKeyRequestWithBody(server, organizationId, serviceAccountId, keyId, "application/json", bodyReader) +} + +// NewServiceAccountsAPIUpdateServiceAccountKeyRequestWithBody generates requests for ServiceAccountsAPIUpdateServiceAccountKey with any type of body +func NewServiceAccountsAPIUpdateServiceAccountKeyRequestWithBody(server string, organizationId string, serviceAccountId string, keyId string, contentType string, body io.Reader) (*http.Request, error) { var err error var pathParam0 string @@ -7423,27 +7448,13 @@ func NewServiceAccountsAPIUpdateServiceAccountKeyRequest(server string, organiza return nil, err } - queryValues := queryURL.Query() - - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "key.active", runtime.ParamLocationQuery, params.KeyActive); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { - return nil, err - } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } - } - } - - queryURL.RawQuery = queryValues.Encode() - - req, err := http.NewRequest("PATCH", queryURL.String(), nil) + req, err := http.NewRequest("PATCH", queryURL.String(), body) if err != nil { return nil, err } + req.Header.Add("Content-Type", contentType) + return req, nil } @@ -10192,8 +10203,10 @@ type ClientWithResponsesInterface interface { ServiceAccountsAPICreateServiceAccountKeyWithResponse(ctx context.Context, organizationId string, serviceAccountId string, body ServiceAccountsAPICreateServiceAccountKeyJSONRequestBody) (*ServiceAccountsAPICreateServiceAccountKeyResponse, error) - // ServiceAccountsAPIUpdateServiceAccountKey request - ServiceAccountsAPIUpdateServiceAccountKeyWithResponse(ctx context.Context, organizationId string, serviceAccountId string, keyId string, params *ServiceAccountsAPIUpdateServiceAccountKeyParams) (*ServiceAccountsAPIUpdateServiceAccountKeyResponse, error) + // ServiceAccountsAPIUpdateServiceAccountKey request with any body + ServiceAccountsAPIUpdateServiceAccountKeyWithBodyWithResponse(ctx context.Context, organizationId string, serviceAccountId string, keyId string, contentType string, body io.Reader) (*ServiceAccountsAPIUpdateServiceAccountKeyResponse, error) + + ServiceAccountsAPIUpdateServiceAccountKeyWithResponse(ctx context.Context, organizationId string, serviceAccountId string, keyId string, body ServiceAccountsAPIUpdateServiceAccountKeyJSONRequestBody) (*ServiceAccountsAPIUpdateServiceAccountKeyResponse, error) // ServiceAccountsAPIDeleteServiceAccountKey request ServiceAccountsAPIDeleteServiceAccountKeyWithResponse(ctx context.Context, organizationId string, serviceAccountId string, keyId string) (*ServiceAccountsAPIDeleteServiceAccountKeyResponse, error) @@ -15872,9 +15885,17 @@ func (c *ClientWithResponses) ServiceAccountsAPICreateServiceAccountKeyWithRespo return ParseServiceAccountsAPICreateServiceAccountKeyResponse(rsp) } -// ServiceAccountsAPIUpdateServiceAccountKeyWithResponse request returning *ServiceAccountsAPIUpdateServiceAccountKeyResponse -func (c *ClientWithResponses) ServiceAccountsAPIUpdateServiceAccountKeyWithResponse(ctx context.Context, organizationId string, serviceAccountId string, keyId string, params *ServiceAccountsAPIUpdateServiceAccountKeyParams) (*ServiceAccountsAPIUpdateServiceAccountKeyResponse, error) { - rsp, err := c.ServiceAccountsAPIUpdateServiceAccountKey(ctx, organizationId, serviceAccountId, keyId, params) +// ServiceAccountsAPIUpdateServiceAccountKeyWithBodyWithResponse request with arbitrary body returning *ServiceAccountsAPIUpdateServiceAccountKeyResponse +func (c *ClientWithResponses) ServiceAccountsAPIUpdateServiceAccountKeyWithBodyWithResponse(ctx context.Context, organizationId string, serviceAccountId string, keyId string, contentType string, body io.Reader) (*ServiceAccountsAPIUpdateServiceAccountKeyResponse, error) { + rsp, err := c.ServiceAccountsAPIUpdateServiceAccountKeyWithBody(ctx, organizationId, serviceAccountId, keyId, contentType, body) + if err != nil { + return nil, err + } + return ParseServiceAccountsAPIUpdateServiceAccountKeyResponse(rsp) +} + +func (c *ClientWithResponses) ServiceAccountsAPIUpdateServiceAccountKeyWithResponse(ctx context.Context, organizationId string, serviceAccountId string, keyId string, body ServiceAccountsAPIUpdateServiceAccountKeyJSONRequestBody) (*ServiceAccountsAPIUpdateServiceAccountKeyResponse, error) { + rsp, err := c.ServiceAccountsAPIUpdateServiceAccountKey(ctx, organizationId, serviceAccountId, keyId, body) if err != nil { return nil, err } diff --git a/castai/sdk/mock/client.go b/castai/sdk/mock/client.go index 3dcb5c4a..02e52b5a 100644 --- a/castai/sdk/mock/client.go +++ b/castai/sdk/mock/client.go @@ -3116,9 +3116,9 @@ func (mr *MockClientInterfaceMockRecorder) ServiceAccountsAPIUpdateServiceAccoun } // ServiceAccountsAPIUpdateServiceAccountKey mocks base method. -func (m *MockClientInterface) ServiceAccountsAPIUpdateServiceAccountKey(ctx context.Context, organizationId, serviceAccountId, keyId string, params *sdk.ServiceAccountsAPIUpdateServiceAccountKeyParams, reqEditors ...sdk.RequestEditorFn) (*http.Response, error) { +func (m *MockClientInterface) ServiceAccountsAPIUpdateServiceAccountKey(ctx context.Context, organizationId, serviceAccountId, keyId string, body sdk.ServiceAccountsAPIUpdateServiceAccountKeyJSONRequestBody, reqEditors ...sdk.RequestEditorFn) (*http.Response, error) { m.ctrl.T.Helper() - varargs := []interface{}{ctx, organizationId, serviceAccountId, keyId, params} + varargs := []interface{}{ctx, organizationId, serviceAccountId, keyId, body} for _, a := range reqEditors { varargs = append(varargs, a) } @@ -3129,12 +3129,32 @@ func (m *MockClientInterface) ServiceAccountsAPIUpdateServiceAccountKey(ctx cont } // ServiceAccountsAPIUpdateServiceAccountKey indicates an expected call of ServiceAccountsAPIUpdateServiceAccountKey. -func (mr *MockClientInterfaceMockRecorder) ServiceAccountsAPIUpdateServiceAccountKey(ctx, organizationId, serviceAccountId, keyId, params interface{}, reqEditors ...interface{}) *gomock.Call { +func (mr *MockClientInterfaceMockRecorder) ServiceAccountsAPIUpdateServiceAccountKey(ctx, organizationId, serviceAccountId, keyId, body interface{}, reqEditors ...interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - varargs := append([]interface{}{ctx, organizationId, serviceAccountId, keyId, params}, reqEditors...) + varargs := append([]interface{}{ctx, organizationId, serviceAccountId, keyId, body}, reqEditors...) return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ServiceAccountsAPIUpdateServiceAccountKey", reflect.TypeOf((*MockClientInterface)(nil).ServiceAccountsAPIUpdateServiceAccountKey), varargs...) } +// ServiceAccountsAPIUpdateServiceAccountKeyWithBody mocks base method. +func (m *MockClientInterface) ServiceAccountsAPIUpdateServiceAccountKeyWithBody(ctx context.Context, organizationId, serviceAccountId, keyId, contentType string, body io.Reader, reqEditors ...sdk.RequestEditorFn) (*http.Response, error) { + m.ctrl.T.Helper() + varargs := []interface{}{ctx, organizationId, serviceAccountId, keyId, contentType, body} + for _, a := range reqEditors { + varargs = append(varargs, a) + } + ret := m.ctrl.Call(m, "ServiceAccountsAPIUpdateServiceAccountKeyWithBody", varargs...) + ret0, _ := ret[0].(*http.Response) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// ServiceAccountsAPIUpdateServiceAccountKeyWithBody indicates an expected call of ServiceAccountsAPIUpdateServiceAccountKeyWithBody. +func (mr *MockClientInterfaceMockRecorder) ServiceAccountsAPIUpdateServiceAccountKeyWithBody(ctx, organizationId, serviceAccountId, keyId, contentType, body interface{}, reqEditors ...interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + varargs := append([]interface{}{ctx, organizationId, serviceAccountId, keyId, contentType, body}, reqEditors...) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ServiceAccountsAPIUpdateServiceAccountKeyWithBody", reflect.TypeOf((*MockClientInterface)(nil).ServiceAccountsAPIUpdateServiceAccountKeyWithBody), varargs...) +} + // ServiceAccountsAPIUpdateServiceAccountWithBody mocks base method. func (m *MockClientInterface) ServiceAccountsAPIUpdateServiceAccountWithBody(ctx context.Context, organizationId, serviceAccountId, contentType string, body io.Reader, reqEditors ...sdk.RequestEditorFn) (*http.Response, error) { m.ctrl.T.Helper() @@ -6283,19 +6303,34 @@ func (mr *MockClientWithResponsesInterfaceMockRecorder) ServiceAccountsAPIListSe return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ServiceAccountsAPIListServiceAccountsWithResponse", reflect.TypeOf((*MockClientWithResponsesInterface)(nil).ServiceAccountsAPIListServiceAccountsWithResponse), ctx, organizationId, params) } +// ServiceAccountsAPIUpdateServiceAccountKeyWithBodyWithResponse mocks base method. +func (m *MockClientWithResponsesInterface) ServiceAccountsAPIUpdateServiceAccountKeyWithBodyWithResponse(ctx context.Context, organizationId, serviceAccountId, keyId, contentType string, body io.Reader) (*sdk.ServiceAccountsAPIUpdateServiceAccountKeyResponse, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "ServiceAccountsAPIUpdateServiceAccountKeyWithBodyWithResponse", ctx, organizationId, serviceAccountId, keyId, contentType, body) + ret0, _ := ret[0].(*sdk.ServiceAccountsAPIUpdateServiceAccountKeyResponse) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// ServiceAccountsAPIUpdateServiceAccountKeyWithBodyWithResponse indicates an expected call of ServiceAccountsAPIUpdateServiceAccountKeyWithBodyWithResponse. +func (mr *MockClientWithResponsesInterfaceMockRecorder) ServiceAccountsAPIUpdateServiceAccountKeyWithBodyWithResponse(ctx, organizationId, serviceAccountId, keyId, contentType, body interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ServiceAccountsAPIUpdateServiceAccountKeyWithBodyWithResponse", reflect.TypeOf((*MockClientWithResponsesInterface)(nil).ServiceAccountsAPIUpdateServiceAccountKeyWithBodyWithResponse), ctx, organizationId, serviceAccountId, keyId, contentType, body) +} + // ServiceAccountsAPIUpdateServiceAccountKeyWithResponse mocks base method. -func (m *MockClientWithResponsesInterface) ServiceAccountsAPIUpdateServiceAccountKeyWithResponse(ctx context.Context, organizationId, serviceAccountId, keyId string, params *sdk.ServiceAccountsAPIUpdateServiceAccountKeyParams) (*sdk.ServiceAccountsAPIUpdateServiceAccountKeyResponse, error) { +func (m *MockClientWithResponsesInterface) ServiceAccountsAPIUpdateServiceAccountKeyWithResponse(ctx context.Context, organizationId, serviceAccountId, keyId string, body sdk.ServiceAccountsAPIUpdateServiceAccountKeyJSONRequestBody) (*sdk.ServiceAccountsAPIUpdateServiceAccountKeyResponse, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ServiceAccountsAPIUpdateServiceAccountKeyWithResponse", ctx, organizationId, serviceAccountId, keyId, params) + ret := m.ctrl.Call(m, "ServiceAccountsAPIUpdateServiceAccountKeyWithResponse", ctx, organizationId, serviceAccountId, keyId, body) ret0, _ := ret[0].(*sdk.ServiceAccountsAPIUpdateServiceAccountKeyResponse) ret1, _ := ret[1].(error) return ret0, ret1 } // ServiceAccountsAPIUpdateServiceAccountKeyWithResponse indicates an expected call of ServiceAccountsAPIUpdateServiceAccountKeyWithResponse. -func (mr *MockClientWithResponsesInterfaceMockRecorder) ServiceAccountsAPIUpdateServiceAccountKeyWithResponse(ctx, organizationId, serviceAccountId, keyId, params interface{}) *gomock.Call { +func (mr *MockClientWithResponsesInterfaceMockRecorder) ServiceAccountsAPIUpdateServiceAccountKeyWithResponse(ctx, organizationId, serviceAccountId, keyId, body interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ServiceAccountsAPIUpdateServiceAccountKeyWithResponse", reflect.TypeOf((*MockClientWithResponsesInterface)(nil).ServiceAccountsAPIUpdateServiceAccountKeyWithResponse), ctx, organizationId, serviceAccountId, keyId, params) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ServiceAccountsAPIUpdateServiceAccountKeyWithResponse", reflect.TypeOf((*MockClientWithResponsesInterface)(nil).ServiceAccountsAPIUpdateServiceAccountKeyWithResponse), ctx, organizationId, serviceAccountId, keyId, body) } // ServiceAccountsAPIUpdateServiceAccountWithBodyWithResponse mocks base method. diff --git a/castai/sdk/utils_response.go b/castai/sdk/utils_response.go index bdcaf39c..66a043ba 100644 --- a/castai/sdk/utils_response.go +++ b/castai/sdk/utils_response.go @@ -3,6 +3,7 @@ package sdk import ( "encoding/json" "fmt" + "io" "net/http" ) @@ -18,8 +19,12 @@ func CheckResponseNoContent(response Response, err error) error { return checkResponse(response, err, http.StatusNoContent) } +func CheckRawResponseNoContent(response *http.Response, err error) error { + return checkRawResponse(response, err, http.StatusNoContent) +} + func CheckResponseCreated(response Response, err error) error { - return checkResponse(response, err, http.StatusCreated) + return checkResponse(response, err, http.StatusCreated) } func StatusOk(resp Response) error { @@ -38,6 +43,21 @@ func checkResponse(response Response, err error, expectedStatus int) error { return nil } +func checkRawResponse(response *http.Response, err error, expectedStatus int) error { + if err != nil { + return err + } + + if response.StatusCode != expectedStatus { + body, err := io.ReadAll(response.Body) + if err != nil { + return fmt.Errorf("reading response body: %w", err) + } + return fmt.Errorf("expected status code %d, received: status=%d body=%s", expectedStatus, response.StatusCode, body) + } + return nil +} + type ErrorResponse struct { Message string `json:"message"` FieldViolations []struct { From e0a40bda340da172fe1565ab6fb41b1823d07358 Mon Sep 17 00:00:00 2001 From: radekska Date: Wed, 11 Dec 2024 16:42:32 +0100 Subject: [PATCH 20/24] wip --- castai/resource_service_account.go | 15 +- castai/resource_service_account_test.go | 476 ++++++++++++++++++++++-- docs/resources/service_account_key.md | 2 +- 3 files changed, 460 insertions(+), 33 deletions(-) diff --git a/castai/resource_service_account.go b/castai/resource_service_account.go index ae7dd5a5..ed636ea0 100644 --- a/castai/resource_service_account.go +++ b/castai/resource_service_account.go @@ -254,6 +254,8 @@ func resourceServiceAccountDelete(ctx context.Context, data *schema.ResourceData "organization_id": organizationID, }) + data.SetId("") + return nil } @@ -337,7 +339,8 @@ func resourceServiceAccountKey() *schema.Resource { }, FieldServiceAccountKeyExpiresAt: { Type: schema.TypeString, - Required: true, + Optional: true, + Computed: true, ForceNew: true, Description: "Expiration date of the service account key.", ValidateDiagFunc: validation.ToDiagFunc(validation.IsRFC3339Time), @@ -345,6 +348,7 @@ func resourceServiceAccountKey() *schema.Resource { FieldServiceAccountKeyActive: { Type: schema.TypeBool, Optional: true, + Computed: true, Description: "Active status of the service account key.", }, }, @@ -411,8 +415,10 @@ func resourceServiceAccountKeyRead(ctx context.Context, data *schema.ResourceDat return diag.Errorf("setting field %s: %v", FieldServiceAccountKeyPrefix, err) } - if err := data.Set(FieldServiceAccountKeyLastUsedAt, serviceAccountKey.Key.LastUsedAt); err != nil { - return diag.Errorf("setting field %s: %v", FieldServiceAccountKeyLastUsedAt, err) + if serviceAccountKey.Key.LastUsedAt != nil { + if err := data.Set(FieldServiceAccountKeyLastUsedAt, serviceAccountKey.Key.LastUsedAt.String()); err != nil { + return diag.Errorf("setting field %s: %v", FieldServiceAccountKeyLastUsedAt, err) + } } if serviceAccountKey.Key.ExpiresAt != nil { @@ -469,6 +475,7 @@ func resourceServiceAccountKeyCreate(ctx context.Context, data *schema.ResourceD } serviceAccountKeyID := *resp.JSON201.Id + logKeys["resource_id"] = serviceAccountKeyID tflog.Info(ctx, "created service account key", logKeys) @@ -531,5 +538,7 @@ func resourceServiceAccountKeyDelete(ctx context.Context, data *schema.ResourceD tflog.Info(ctx, "deleted service account key", logKeys) + data.SetId("") + return nil } diff --git a/castai/resource_service_account_test.go b/castai/resource_service_account_test.go index 3900472c..160d6a08 100644 --- a/castai/resource_service_account_test.go +++ b/castai/resource_service_account_test.go @@ -457,11 +457,7 @@ func TestServiceAccount_DeleteContext(t *testing.T) { r.Nil(result) r.False(result.HasError()) - r.Empty(data.Get(FieldServiceAccountID)) - r.Empty(data.Get(FieldServiceAccountEmail)) - r.Empty(data.Get(FieldServiceAccountName)) - r.Empty(data.Get(FieldServiceAccountDescription)) - r.Empty(data.Get(FieldServiceAccountAuthor)) + r.True(data.State().Empty()) }) } @@ -609,10 +605,170 @@ func TestServiceAccount_UpdateContext(t *testing.T) { }) } -// TODO: test me! :( func TestServiceAccountKey_CreateContext(t *testing.T) { t.Parallel() + t.Run("when ServiceAccountsAPI responds with non-201 status then return error", func(t *testing.T) { + r := require.New(t) + mockClient := mock_sdk.NewMockClientInterface(gomock.NewController(t)) + + ctx := context.Background() + provider := &ProviderConfig{ + api: &sdk.ClientWithResponses{ + ClientInterface: mockClient, + }, + } + + organizationID := "4e4cd9eb-82eb-407e-a926-e5fef81cab50" + name := "service-account-key-name" + serviceAccountID := "4e4cd9eb-82eb-407e-a926-e5fef81cab51" + expiresAt := "2024-12-01T15:19:40.384Z" + + body := io.NopCloser(bytes.NewReader([]byte("mock error response"))) + + mockClient.EXPECT(). + ServiceAccountsAPICreateServiceAccountKey(gomock.Any(), organizationID, serviceAccountID, gomock.Any()). + Return(&http.Response{ + StatusCode: http.StatusInternalServerError, + Body: body, + }, nil) + + resource := resourceServiceAccountKey() + stateValue := cty.ObjectVal(map[string]cty.Value{ + "organization_id": cty.StringVal(organizationID), + "name": cty.StringVal(name), + "service_account_id": cty.StringVal(serviceAccountID), + "expires_at": cty.StringVal(expiresAt), + }) + + state := terraform.NewInstanceStateShimmedFromValue(stateValue, 0) + data := resource.Data(state) + + result := resource.CreateContext(ctx, data, provider) + + r.NotNil(result) + r.True(result.HasError()) + r.Len(result, 1) + r.Equal("creating service account key: expected status code 201, received: status=500 body=mock error response", result[0].Summary) + }) + + t.Run("when ServiceAccountsAPI responds with an error then return error", func(t *testing.T) { + r := require.New(t) + mockClient := mock_sdk.NewMockClientInterface(gomock.NewController(t)) + + ctx := context.Background() + provider := &ProviderConfig{ + api: &sdk.ClientWithResponses{ + ClientInterface: mockClient, + }, + } + + organizationID := "4e4cd9eb-82eb-407e-a926-e5fef81cab50" + name := "service-account-key-name" + serviceAccountID := "4e4cd9eb-82eb-407e-a926-e5fef81cab51" + expiresAt := "2024-12-01T15:19:40.384Z" + + mockClient.EXPECT(). + ServiceAccountsAPICreateServiceAccountKey(gomock.Any(), organizationID, serviceAccountID, gomock.Any()). + Return(nil, fmt.Errorf("mock network error")) + + resource := resourceServiceAccountKey() + stateValue := cty.ObjectVal(map[string]cty.Value{ + "organization_id": cty.StringVal(organizationID), + "name": cty.StringVal(name), + "service_account_id": cty.StringVal(serviceAccountID), + "expires_at": cty.StringVal(expiresAt), + }) + + state := terraform.NewInstanceStateShimmedFromValue(stateValue, 0) + data := resource.Data(state) + + result := resource.CreateContext(ctx, data, provider) + + r.NotNil(result) + r.True(result.HasError()) + r.Len(result, 1) + r.Equal("creating service account key: mock network error", result[0].Summary) + }) + + t.Run("when ServiceAccountAPI respond with 201 then populate the state", func(t *testing.T) { + r := require.New(t) + mockClient := mock_sdk.NewMockClientInterface(gomock.NewController(t)) + + ctx := context.Background() + provider := &ProviderConfig{ + api: &sdk.ClientWithResponses{ + ClientInterface: mockClient, + }, + } + + organizationID := "4e4cd9eb-82eb-407e-a926-e5fef81cab50" + serviceAccountID := "b11f5945-22ca-4101-a86e-d6e37f44a415" + keyID := "da5664b3-87bf-4e03-9d1c-ec26049991b7" + expiresAt := "2024-12-01T15:19:40.384Z" + + body := io.NopCloser(bytes.NewReader([]byte(fmt.Sprintf(`{ + "key": { + "id": %q, + "name": "test-key", + "prefix": "123q", + "lastUsedAt": "2024-12-11T13:47:20.927Z", + "expiresAt": %q, + "active": true + } +}`, keyID, expiresAt)))) + + createBody := io.NopCloser(bytes.NewReader([]byte(fmt.Sprintf(`{ + "id": %q, + "name": "test-key", + "prefix": "123q", + "lastUsedAt": "2024-12-11T13:47:20.927Z", + "expiresAt": %q, + "active": true +}`, keyID, expiresAt)))) + + mockClient.EXPECT(). + ServiceAccountsAPICreateServiceAccountKey(gomock.Any(), organizationID, serviceAccountID, gomock.Any()). + Return(&http.Response{StatusCode: http.StatusCreated, Body: createBody, Header: map[string][]string{"Content-Type": {"json"}}}, nil) + + mockClient.EXPECT(). + ServiceAccountsAPIGetServiceAccountKey(gomock.Any(), organizationID, serviceAccountID, keyID). + Return(&http.Response{StatusCode: http.StatusOK, Body: body, Header: map[string][]string{"Content-Type": {"json"}}}, nil) + + stateValue := cty.ObjectVal(map[string]cty.Value{ + "organization_id": cty.StringVal(organizationID), + "service_account_id": cty.StringVal(serviceAccountID), + "expires_at": cty.StringVal(expiresAt), + }) + + state := terraform.NewInstanceStateShimmedFromValue(stateValue, 0) + state.ID = keyID + + resource := resourceServiceAccountKey() + data := resource.Data(state) + + result := resource.CreateContext(ctx, data, provider) + + r.Nil(result) + r.False(result.HasError()) + r.Equal(`ID = da5664b3-87bf-4e03-9d1c-ec26049991b7 +active = true +expires_at = 2024-12-01 15:19:40.384 +0000 UTC +last_used_at = 2024-12-11 13:47:20.927 +0000 UTC +name = test-key +organization_id = 4e4cd9eb-82eb-407e-a926-e5fef81cab50 +prefix = 123q +service_account_id = b11f5945-22ca-4101-a86e-d6e37f44a415 +Tainted = false +`, data.State().String()) + }) + + // TODO: what happens if i dont provide expiresAt nor active +} + +func TestServiceAccountKey_ReadContext(t *testing.T) { + t.Parallel() + t.Run("when ServiceAccountAPI respond with 404 then remove form the state gracefully", func(t *testing.T) { r := require.New(t) mockClient := mock_sdk.NewMockClientInterface(gomock.NewController(t)) @@ -638,7 +794,7 @@ func TestServiceAccountKey_CreateContext(t *testing.T) { "service_account_id": cty.StringVal(serviceAccountID), }) state := terraform.NewInstanceStateShimmedFromValue(stateValue, 0) - state.ID = serviceAccountID + state.ID = keyID resource := resourceServiceAccountKey() data := resource.Data(state) @@ -671,11 +827,11 @@ func TestServiceAccountKey_CreateContext(t *testing.T) { Return(&http.Response{StatusCode: http.StatusInternalServerError, Body: body, Header: map[string][]string{"Content-Type": {"json"}}}, nil) stateValue := cty.ObjectVal(map[string]cty.Value{ - "organization_id": cty.StringVal(organizationID), + "organization_id": cty.StringVal(organizationID), "service_account_id": cty.StringVal(serviceAccountID), }) state := terraform.NewInstanceStateShimmedFromValue(stateValue, 0) - state.ID = serviceAccountID + state.ID = keyID resource := resourceServiceAccountKey() data := resource.Data(state) @@ -685,10 +841,10 @@ func TestServiceAccountKey_CreateContext(t *testing.T) { r.NotNil(result) r.True(result.HasError()) r.Len(result, 1) - r.Equal("getting service account key: expected status code 200, received: status=500 body=panic", result[0].Summary) + r.Equal("reading service account key: expected status code 200, received: status=500 body=panic", result[0].Summary) }) - t.Run("when ServiceAccountAPI respond with 200 then populate the state", func(t *testing.T) { + t.Run("when ServiceAccountAPI respond with 200 then populate the state", func(t *testing.T) { r := require.New(t) mockClient := mock_sdk.NewMockClientInterface(gomock.NewController(t)) @@ -701,7 +857,6 @@ func TestServiceAccountKey_CreateContext(t *testing.T) { organizationID := "4e4cd9eb-82eb-407e-a926-e5fef81cab50" serviceAccountID := "b11f5945-22ca-4101-a86e-d6e37f44a415" - userID := "671b2ebb-f361-42f0-aa2f-3049de93f8c1" keyID := "da5664b3-87bf-4e03-9d1c-ec26049991b7" body := io.NopCloser(bytes.NewReader([]byte(fmt.Sprintf(`{ @@ -720,11 +875,11 @@ func TestServiceAccountKey_CreateContext(t *testing.T) { Return(&http.Response{StatusCode: http.StatusOK, Body: body, Header: map[string][]string{"Content-Type": {"json"}}}, nil) stateValue := cty.ObjectVal(map[string]cty.Value{ - "organization_id": cty.StringVal(organizationID), + "organization_id": cty.StringVal(organizationID), "service_account_id": cty.StringVal(serviceAccountID), }) state := terraform.NewInstanceStateShimmedFromValue(stateValue, 0) - state.ID = serviceAccountID + state.ID = keyID resource := resourceServiceAccountKey() data := resource.Data(state) @@ -733,29 +888,292 @@ func TestServiceAccountKey_CreateContext(t *testing.T) { r.Nil(result) r.False(result.HasError()) - r.Equal(fmt.Sprintf(`ID = %s -author.# = 1 -author.0.email = user-email -author.0.id = %s -author.0.kind = user -description = service-account-description -email = service-account-email -name = service-account-name -organization_id = %s + r.Equal(`ID = da5664b3-87bf-4e03-9d1c-ec26049991b7 +active = true +expires_at = 2024-12-11 13:47:20.927 +0000 UTC +last_used_at = 2024-12-11 13:47:20.927 +0000 UTC +name = test-key +organization_id = 4e4cd9eb-82eb-407e-a926-e5fef81cab50 +prefix = 123q +service_account_id = b11f5945-22ca-4101-a86e-d6e37f44a415 Tainted = false -`, serviceAccountID, userID, organizationID), data.State().String()) +`, data.State().String()) }) - -} - -func TestServiceAccountKey_ReadContext(t *testing.T) { - t.Parallel() } func TestServiceAccountKey_DeleteContext(t *testing.T) { t.Parallel() + + t.Run("when ServiceAccountsAPI responds with an error then return error", func(t *testing.T) { + r := require.New(t) + mockClient := mock_sdk.NewMockClientInterface(gomock.NewController(t)) + + ctx := context.Background() + provider := &ProviderConfig{ + api: &sdk.ClientWithResponses{ + ClientInterface: mockClient, + }, + } + + organizationID := "4e4cd9eb-82eb-407e-a926-e5fef81cab50" + serviceAccountID := "4e4cd9eb-82eb-407e-a926-e5fef81cab51" + keyID := "da5664b3-87bf-4e03-9d1c-ec26049991b7" + + mockClient.EXPECT(). + ServiceAccountsAPIDeleteServiceAccountKey(gomock.Any(), organizationID, serviceAccountID, keyID). + Return(nil, fmt.Errorf("mock network error")) + + resource := resourceServiceAccountKey() + stateValue := cty.ObjectVal(map[string]cty.Value{ + "organization_id": cty.StringVal(organizationID), + "service_account_id": cty.StringVal(serviceAccountID), + }) + + state := terraform.NewInstanceStateShimmedFromValue(stateValue, 0) + state.ID = keyID + data := resource.Data(state) + + result := resource.DeleteContext(ctx, data, provider) + + r.NotNil(result) + r.True(result.HasError()) + r.Len(result, 1) + r.Equal("deleting service account key: mock network error", result[0].Summary) + }) + + t.Run("when ServiceAccountsAPI responds with non-201 status then return error", func(t *testing.T) { + r := require.New(t) + mockClient := mock_sdk.NewMockClientInterface(gomock.NewController(t)) + + ctx := context.Background() + provider := &ProviderConfig{ + api: &sdk.ClientWithResponses{ + ClientInterface: mockClient, + }, + } + + organizationID := "4e4cd9eb-82eb-407e-a926-e5fef81cab50" + serviceAccountID := "4e4cd9eb-82eb-407e-a926-e5fef81cab51" + keyID := "da5664b3-87bf-4e03-9d1c-ec26049991b7" + + body := io.NopCloser(bytes.NewReader([]byte("mock error response"))) + + mockClient.EXPECT(). + ServiceAccountsAPIDeleteServiceAccountKey(gomock.Any(), organizationID, serviceAccountID, keyID). + Return(&http.Response{ + StatusCode: http.StatusInternalServerError, + Body: body, + }, nil) + + resource := resourceServiceAccountKey() + stateValue := cty.ObjectVal(map[string]cty.Value{ + "organization_id": cty.StringVal(organizationID), + "service_account_id": cty.StringVal(serviceAccountID), + }) + + state := terraform.NewInstanceStateShimmedFromValue(stateValue, 0) + state.ID = keyID + data := resource.Data(state) + + result := resource.DeleteContext(ctx, data, provider) + + r.NotNil(result) + r.True(result.HasError()) + r.Len(result, 1) + r.Equal("deleting service account key: expected status code 204, received: status=500 body=mock error response", result[0].Summary) + }) + + t.Run("when ServiceAccountsAPI responds with 204 then return nil", func(t *testing.T) { + r := require.New(t) + mockClient := mock_sdk.NewMockClientInterface(gomock.NewController(t)) + + ctx := context.Background() + provider := &ProviderConfig{ + api: &sdk.ClientWithResponses{ + ClientInterface: mockClient, + }, + } + + organizationID := "4e4cd9eb-82eb-407e-a926-e5fef81cab50" + serviceAccountID := "4e4cd9eb-82eb-407e-a926-e5fef81cab51" + keyID := "da5664b3-87bf-4e03-9d1c-ec26049991b7" + + mockClient.EXPECT(). + ServiceAccountsAPIDeleteServiceAccountKey(gomock.Any(), organizationID, serviceAccountID, keyID). + Return(&http.Response{ + StatusCode: http.StatusNoContent, + }, nil) + + resource := resourceServiceAccountKey() + stateValue := cty.ObjectVal(map[string]cty.Value{ + "organization_id": cty.StringVal(organizationID), + "service_account_id": cty.StringVal(serviceAccountID), + "name": cty.StringVal("key name"), + "expires_at": cty.StringVal("2022-01-01T00:00:00Z"), + "last_used_at": cty.StringVal("2022-01-01T00:00:00Z"), + "active": cty.BoolVal(true), + "prefix": cty.StringVal("key prefix"), + }) + + state := terraform.NewInstanceStateShimmedFromValue(stateValue, 0) + state.ID = keyID + data := resource.Data(state) + + result := resource.DeleteContext(ctx, data, provider) + + r.Nil(result) + r.False(result.HasError()) + r.True(data.State().Empty()) + }) } func TestServiceAccountKey_UpdateContext(t *testing.T) { t.Parallel() + + t.Run("when ServiceAccountsAPI responds with an error then return error", func(t *testing.T) { + r := require.New(t) + mockClient := mock_sdk.NewMockClientInterface(gomock.NewController(t)) + ctx := context.Background() + provider := &ProviderConfig{ + api: &sdk.ClientWithResponses{ + ClientInterface: mockClient, + }, + } + + organizationID := "4e4cd9eb-82eb-407e-a926-e5fef81cab50" + serviceAccountID := "4e4cd9eb-82eb-407e-a926-e5fef81cab51" + keyID := "da5664b3-87bf-4e03-9d1c-ec26049991b7" + + mockClient.EXPECT(). + ServiceAccountsAPIUpdateServiceAccountKey(gomock.Any(), organizationID, serviceAccountID, keyID, gomock.Any()). + Return(nil, fmt.Errorf("mock network error")) + + resource := resourceServiceAccountKey() + stateValue := cty.ObjectVal(map[string]cty.Value{ + "organization_id": cty.StringVal(organizationID), + "name": cty.StringVal("new name"), + "active": cty.BoolVal(true), + "service_account_id": cty.StringVal(serviceAccountID), + }) + state := terraform.NewInstanceStateShimmedFromValue(stateValue, 0) + state.ID = keyID + data := resource.Data(state) + + result := resource.UpdateContext(ctx, data, provider) + + r.NotNil(result) + r.True(result.HasError()) + r.Len(result, 1) + r.Equal("updating service account key: mock network error", result[0].Summary) + }) + + t.Run("when ServiceAccountsAPI responds with non-200 status then return error", func(t *testing.T) { + r := require.New(t) + mockClient := mock_sdk.NewMockClientInterface(gomock.NewController(t)) + ctx := context.Background() + provider := &ProviderConfig{ + api: &sdk.ClientWithResponses{ + ClientInterface: mockClient, + }, + } + + organizationID := "4e4cd9eb-82eb-407e-a926-e5fef81cab50" + serviceAccountID := "4e4cd9eb-82eb-407e-a926-e5fef81cab51" + keyID := "da5664b3-87bf-4e03-9d1c-ec26049991b7" + + body := io.NopCloser(bytes.NewReader([]byte("mock error response"))) + + mockClient.EXPECT(). + ServiceAccountsAPIUpdateServiceAccountKey(gomock.Any(), organizationID, serviceAccountID, keyID, gomock.Any()). + Return(&http.Response{ + StatusCode: http.StatusInternalServerError, + Body: body, + }, nil) + + resource := resourceServiceAccountKey() + stateValue := cty.ObjectVal(map[string]cty.Value{ + "organization_id": cty.StringVal(organizationID), + "service_account_id": cty.StringVal(serviceAccountID), + "name": cty.StringVal("new name"), + "active": cty.BoolVal(true), + }) + state := terraform.NewInstanceStateShimmedFromValue(stateValue, 0) + state.ID = keyID + data := resource.Data(state) + + result := resource.UpdateContext(ctx, data, provider) + + r.NotNil(result) + r.True(result.HasError()) + r.Len(result, 1) + r.Equal("updating service account key: expected status code 200, received: status=500 body=mock error response", result[0].Summary) + }) + + t.Run("when ServiceAccountsAPI responds with 200 then return nil", func(t *testing.T) { + r := require.New(t) + mockClient := mock_sdk.NewMockClientInterface(gomock.NewController(t)) + ctx := context.Background() + provider := &ProviderConfig{ + api: &sdk.ClientWithResponses{ + ClientInterface: mockClient, + }, + } + + organizationID := "4e4cd9eb-82eb-407e-a926-e5fef81cab50" + serviceAccountID := "4e4cd9eb-82eb-407e-a926-e5fef81cab51" + keyID := "da5664b3-87bf-4e03-9d1c-ec26049991b7" + expiresAt := "2024-12-11T13:47:20.927Z" + name := "test-key" + + body := io.NopCloser(bytes.NewReader([]byte(`{"active":false}`))) + readBody := io.NopCloser(bytes.NewReader([]byte(fmt.Sprintf(`{ + "key": { + "id": %q, + "name": "test-key", + "prefix": "123q", + "lastUsedAt": "2024-12-11T13:47:20.927Z", + "expiresAt": %q, + "active": false + } +}`, keyID, expiresAt)))) + + mockClient.EXPECT(). + ServiceAccountsAPIUpdateServiceAccountKey(gomock.Any(), organizationID, serviceAccountID, keyID, gomock.Any()). + Return(&http.Response{ + StatusCode: http.StatusOK, + Body: body, + }, nil) + mockClient.EXPECT(). + ServiceAccountsAPIGetServiceAccountKey(gomock.Any(), organizationID, serviceAccountID, keyID). + Return(&http.Response{ + StatusCode: http.StatusOK, + Body: readBody, + Header: map[string][]string{"Content-Type": {"json"}}, + }, nil) + + resource := resourceServiceAccountKey() + stateValue := cty.ObjectVal(map[string]cty.Value{ + "organization_id": cty.StringVal(organizationID), + "service_account_id": cty.StringVal(serviceAccountID), + "active": cty.BoolVal(true), + "name": cty.StringVal(name), + }) + state := terraform.NewInstanceStateShimmedFromValue(stateValue, 0) + state.ID = keyID + data := resource.Data(state) + + result := resource.UpdateContext(ctx, data, provider) + + r.Nil(result) + r.Equal(`ID = da5664b3-87bf-4e03-9d1c-ec26049991b7 +active = false +expires_at = 2024-12-11 13:47:20.927 +0000 UTC +last_used_at = 2024-12-11 13:47:20.927 +0000 UTC +name = test-key +organization_id = 4e4cd9eb-82eb-407e-a926-e5fef81cab50 +prefix = 123q +service_account_id = 4e4cd9eb-82eb-407e-a926-e5fef81cab51 +Tainted = false +`, data.State().String()) + }) } diff --git a/docs/resources/service_account_key.md b/docs/resources/service_account_key.md index b18aa488..4983c660 100644 --- a/docs/resources/service_account_key.md +++ b/docs/resources/service_account_key.md @@ -17,7 +17,6 @@ Service account key resource allows managing CAST AI service account keys. ### Required -- `expires_at` (String) Expiration date of the service account key. - `name` (String) Name of the service account key. - `organization_id` (String) ID of the organization. - `service_account_id` (String) ID of the service account. @@ -25,6 +24,7 @@ Service account key resource allows managing CAST AI service account keys. ### Optional - `active` (Boolean) Active status of the service account key. +- `expires_at` (String) Expiration date of the service account key. - `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) ### Read-Only From 63aa36679976315bdd4081c6876acd35522d4794 Mon Sep 17 00:00:00 2001 From: radekska Date: Wed, 11 Dec 2024 17:20:31 +0100 Subject: [PATCH 21/24] done --- castai/resource_service_account.go | 54 ++++++++++++++++++------- castai/resource_service_account_test.go | 12 +++--- castai/sdk/api.gen.go | 10 +++++ docs/resources/service_account_key.md | 4 +- 4 files changed, 58 insertions(+), 22 deletions(-) diff --git a/castai/resource_service_account.go b/castai/resource_service_account.go index ed636ea0..b056524e 100644 --- a/castai/resource_service_account.go +++ b/castai/resource_service_account.go @@ -6,6 +6,7 @@ import ( "net/http" "time" + "github.com/hashicorp/go-cty/cty" "github.com/hashicorp/terraform-plugin-log/tflog" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" @@ -338,18 +339,18 @@ func resourceServiceAccountKey() *schema.Resource { Description: "Last time the service account key was used.", }, FieldServiceAccountKeyExpiresAt: { - Type: schema.TypeString, - Optional: true, - Computed: true, - ForceNew: true, - Description: "Expiration date of the service account key.", - ValidateDiagFunc: validation.ToDiagFunc(validation.IsRFC3339Time), + Type: schema.TypeString, + Optional: true, + Default: "", + ForceNew: true, + Description: "The expiration time of the service account key in RFC3339 format. Defaults to an empty string.", + // ValidateDiagFunc: validateRFC3339TimeOrEmpty, }, FieldServiceAccountKeyActive: { Type: schema.TypeBool, Optional: true, - Computed: true, - Description: "Active status of the service account key.", + Default: true, + Description: "Whether the service account key is active. Defaults to true", }, }, } @@ -416,13 +417,13 @@ func resourceServiceAccountKeyRead(ctx context.Context, data *schema.ResourceDat } if serviceAccountKey.Key.LastUsedAt != nil { - if err := data.Set(FieldServiceAccountKeyLastUsedAt, serviceAccountKey.Key.LastUsedAt.String()); err != nil { + if err := data.Set(FieldServiceAccountKeyLastUsedAt, serviceAccountKey.Key.LastUsedAt.Format(time.RFC3339)); err != nil { return diag.Errorf("setting field %s: %v", FieldServiceAccountKeyLastUsedAt, err) } } if serviceAccountKey.Key.ExpiresAt != nil { - if err := data.Set(FieldServiceAccountKeyExpiresAt, serviceAccountKey.Key.ExpiresAt.String()); err != nil { + if err := data.Set(FieldServiceAccountKeyExpiresAt, serviceAccountKey.Key.ExpiresAt.Format(time.RFC3339)); err != nil { return diag.Errorf("setting field %s: %v", FieldServiceAccountKeyExpiresAt, err) } } @@ -434,6 +435,8 @@ func resourceServiceAccountKeyRead(ctx context.Context, data *schema.ResourceDat } func resourceServiceAccountKeyCreate(ctx context.Context, data *schema.ResourceData, meta interface{}) diag.Diagnostics { + var expiresAtTime *time.Time + client := meta.(*ProviderConfig).api organizationID, err := getOrganizationID(ctx, data, meta) @@ -445,9 +448,12 @@ func resourceServiceAccountKeyCreate(ctx context.Context, data *schema.ResourceD expiresAt := data.Get(FieldServiceAccountKeyExpiresAt).(string) active := data.Get(FieldServiceAccountKeyActive).(bool) - expiresAtParsed, err := time.Parse(time.RFC3339, expiresAt) - if err != nil { - return diag.Errorf("parsing expires_at date: %v", err) + if expiresAt != "" { + expiresAtParsed, err := time.Parse(time.RFC3339, expiresAt) + if err != nil { + return diag.Errorf("parsing expires_at date: %v", err) + } + expiresAtTime = &expiresAtParsed } logKeys := map[string]interface{}{ @@ -465,7 +471,7 @@ func resourceServiceAccountKeyCreate(ctx context.Context, data *schema.ResourceD sdk.ServiceAccountsAPICreateServiceAccountKeyRequest{ Key: sdk.CastaiServiceaccountsV1beta1CreateServiceAccountKeyRequestKey{ Active: &active, - ExpiresAt: &expiresAtParsed, + ExpiresAt: expiresAtTime, Name: name, }, }, @@ -542,3 +548,23 @@ func resourceServiceAccountKeyDelete(ctx context.Context, data *schema.ResourceD return nil } + +func validateRFC3339TimeOrEmpty(i interface{}, path cty.Path) diag.Diagnostics { + v, ok := i.(string) + if !ok || v == "" { + return nil // Allow empty strings without error + } + + _, err := time.Parse(time.RFC3339, v) + if err != nil { + return diag.Diagnostics{ + diag.Diagnostic{ + Severity: diag.Error, + Summary: "Invalid expires_at format", + Detail: "The expires_at field must be in RFC3339 format or an empty string.", + }, + } + } + + return nil +} diff --git a/castai/resource_service_account_test.go b/castai/resource_service_account_test.go index 160d6a08..e489864a 100644 --- a/castai/resource_service_account_test.go +++ b/castai/resource_service_account_test.go @@ -753,8 +753,8 @@ func TestServiceAccountKey_CreateContext(t *testing.T) { r.False(result.HasError()) r.Equal(`ID = da5664b3-87bf-4e03-9d1c-ec26049991b7 active = true -expires_at = 2024-12-01 15:19:40.384 +0000 UTC -last_used_at = 2024-12-11 13:47:20.927 +0000 UTC +expires_at = 2024-12-01T15:19:40Z +last_used_at = 2024-12-11T13:47:20Z name = test-key organization_id = 4e4cd9eb-82eb-407e-a926-e5fef81cab50 prefix = 123q @@ -890,8 +890,8 @@ func TestServiceAccountKey_ReadContext(t *testing.T) { r.False(result.HasError()) r.Equal(`ID = da5664b3-87bf-4e03-9d1c-ec26049991b7 active = true -expires_at = 2024-12-11 13:47:20.927 +0000 UTC -last_used_at = 2024-12-11 13:47:20.927 +0000 UTC +expires_at = 2024-12-11T13:47:20Z +last_used_at = 2024-12-11T13:47:20Z name = test-key organization_id = 4e4cd9eb-82eb-407e-a926-e5fef81cab50 prefix = 123q @@ -1167,8 +1167,8 @@ func TestServiceAccountKey_UpdateContext(t *testing.T) { r.Nil(result) r.Equal(`ID = da5664b3-87bf-4e03-9d1c-ec26049991b7 active = false -expires_at = 2024-12-11 13:47:20.927 +0000 UTC -last_used_at = 2024-12-11 13:47:20.927 +0000 UTC +expires_at = 2024-12-11T13:47:20Z +last_used_at = 2024-12-11T13:47:20Z name = test-key organization_id = 4e4cd9eb-82eb-407e-a926-e5fef81cab50 prefix = 123q diff --git a/castai/sdk/api.gen.go b/castai/sdk/api.gen.go index c7a47cd2..6d8204dd 100644 --- a/castai/sdk/api.gen.go +++ b/castai/sdk/api.gen.go @@ -4319,6 +4319,7 @@ type WorkloadoptimizationV1ResourceConfig struct { // QUANTILE - the quantile function. // MAX - the max function. Function WorkloadoptimizationV1ResourceConfigFunction `json:"function"` + Limit *WorkloadoptimizationV1ResourceLimitStrategy `json:"limit,omitempty"` // Period of time over which the resource recommendation is calculated (default value is 24 hours). LookBackPeriodSeconds *int32 `json:"lookBackPeriodSeconds"` @@ -4351,6 +4352,12 @@ type WorkloadoptimizationV1ResourceConfigUpdate struct { Min *float64 `json:"min"` } +// WorkloadoptimizationV1ResourceLimitStrategy defines model for workloadoptimization.v1.ResourceLimitStrategy. +type WorkloadoptimizationV1ResourceLimitStrategy struct { + Multiplier *float64 `json:"multiplier,omitempty"` + None *bool `json:"none,omitempty"` +} + // WorkloadoptimizationV1ResourceMetrics defines model for workloadoptimization.v1.ResourceMetrics. type WorkloadoptimizationV1ResourceMetrics struct { Max float64 `json:"max"` @@ -4375,6 +4382,7 @@ type WorkloadoptimizationV1ResourcePolicies struct { // QUANTILE - the quantile function. // MAX - the max function. Function WorkloadoptimizationV1ResourcePoliciesFunction `json:"function"` + Limit *WorkloadoptimizationV1ResourceLimitStrategy `json:"limit,omitempty"` // Period of time over which the resource recommendation is calculated (default value is 24 hours). LookBackPeriodSeconds *int32 `json:"lookBackPeriodSeconds"` @@ -4626,6 +4634,8 @@ type WorkloadoptimizationV1WorkloadRecommendation struct { // WorkloadoptimizationV1WorkloadResourceConfigUpdate defines model for workloadoptimization.v1.WorkloadResourceConfigUpdate. type WorkloadoptimizationV1WorkloadResourceConfigUpdate struct { + Limit *WorkloadoptimizationV1ResourceLimitStrategy `json:"limit,omitempty"` + // Period of time over which the resource recommendation is calculated (default value is 24 hours). LookBackPeriodSeconds *int32 `json:"lookBackPeriodSeconds"` diff --git a/docs/resources/service_account_key.md b/docs/resources/service_account_key.md index 4983c660..b676e452 100644 --- a/docs/resources/service_account_key.md +++ b/docs/resources/service_account_key.md @@ -23,8 +23,8 @@ Service account key resource allows managing CAST AI service account keys. ### Optional -- `active` (Boolean) Active status of the service account key. -- `expires_at` (String) Expiration date of the service account key. +- `active` (Boolean) Whether the service account key is active. Defaults to true +- `expires_at` (String) The expiration time of the service account key in RFC3339 format. Defaults to an empty string. - `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) ### Read-Only From 36d652d6b66d4bdb017566e53d6c9c348720c535 Mon Sep 17 00:00:00 2001 From: radekska Date: Wed, 11 Dec 2024 17:25:02 +0100 Subject: [PATCH 22/24] fixes --- castai/resource_service_account.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/castai/resource_service_account.go b/castai/resource_service_account.go index b056524e..2007ee14 100644 --- a/castai/resource_service_account.go +++ b/castai/resource_service_account.go @@ -344,7 +344,7 @@ func resourceServiceAccountKey() *schema.Resource { Default: "", ForceNew: true, Description: "The expiration time of the service account key in RFC3339 format. Defaults to an empty string.", - // ValidateDiagFunc: validateRFC3339TimeOrEmpty, + ValidateDiagFunc: validateRFC3339TimeOrEmpty, }, FieldServiceAccountKeyActive: { Type: schema.TypeBool, From 185f80374b9feb86aa86d38cc2e94ab5034779b7 Mon Sep 17 00:00:00 2001 From: radekska Date: Thu, 12 Dec 2024 10:30:31 +0100 Subject: [PATCH 23/24] done --- castai/resource_service_account_key.go | 1 - docs/resources/service_account_key.md | 2 +- .../resources/castai_service_account/resource.tf | 14 +++++++++++++- 3 files changed, 14 insertions(+), 3 deletions(-) diff --git a/castai/resource_service_account_key.go b/castai/resource_service_account_key.go index a9d639de..d908fa47 100644 --- a/castai/resource_service_account_key.go +++ b/castai/resource_service_account_key.go @@ -84,7 +84,6 @@ func resourceServiceAccountKey() *schema.Resource { FieldServiceAccountKeyToken: { Type: schema.TypeString, Computed: true, - Sensitive: true, Description: "The token of the service account key used for authentication.", }, }, diff --git a/docs/resources/service_account_key.md b/docs/resources/service_account_key.md index 84e9e318..d9b3ae37 100644 --- a/docs/resources/service_account_key.md +++ b/docs/resources/service_account_key.md @@ -32,7 +32,7 @@ Service account key resource allows managing CAST AI service account keys. - `id` (String) The ID of this resource. - `last_used_at` (String) Last time the service account key was used. - `prefix` (String) Prefix of the service account key. -- `token` (String, Sensitive) The token of the service account key used for authentication. +- `token` (String) The token of the service account key used for authentication. ### Nested Schema for `timeouts` diff --git a/examples/resources/castai_service_account/resource.tf b/examples/resources/castai_service_account/resource.tf index 5caf87f5..97c72248 100644 --- a/examples/resources/castai_service_account/resource.tf +++ b/examples/resources/castai_service_account/resource.tf @@ -1,5 +1,17 @@ resource "castai_service_account" "service_account" { organization_id = organization.id - name = "service-account-name" + name = "example-service-account" description = "service account description" } + +resource "castai_service_account_key" "service_account_key" { + organization_id = data.castai_organization.test.id + service_account_id = castai_service_account.service_account.id + name = "example-key" + active = true + expires_at = "2025-01-01T00:00:00Z" +} + +output "service_account_key" { + value = castai_service_account_key.service_account_key.token +} From 91ca3ee632b46f9687d006ea10c288e41cc73473 Mon Sep 17 00:00:00 2001 From: radekska Date: Thu, 12 Dec 2024 12:28:00 +0100 Subject: [PATCH 24/24] fix --- castai/resource_service_account_key.go | 3 +++ docs/resources/service_account.md | 14 +++++++++++++- 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/castai/resource_service_account_key.go b/castai/resource_service_account_key.go index d908fa47..037508b9 100644 --- a/castai/resource_service_account_key.go +++ b/castai/resource_service_account_key.go @@ -42,18 +42,21 @@ func resourceServiceAccountKey() *schema.Resource { FieldServiceAccountKeyOrganizationID: { Type: schema.TypeString, Required: true, + ForceNew: true, Description: "ID of the organization.", ValidateDiagFunc: validation.ToDiagFunc(validation.IsUUID), }, FieldServiceAccountKeyServiceAccountID: { Type: schema.TypeString, Required: true, + ForceNew: true, Description: "ID of the service account.", ValidateDiagFunc: validation.ToDiagFunc(validation.IsUUID), }, FieldServiceAccountKeyName: { Type: schema.TypeString, Required: true, + ForceNew: true, Description: "Name of the service account key.", ValidateDiagFunc: validation.ToDiagFunc(validation.StringIsNotWhiteSpace), }, diff --git a/docs/resources/service_account.md b/docs/resources/service_account.md index 9bdd8c29..81f7c160 100644 --- a/docs/resources/service_account.md +++ b/docs/resources/service_account.md @@ -15,9 +15,21 @@ Service account resource allows managing CAST AI service accounts. ```terraform resource "castai_service_account" "service_account" { organization_id = organization.id - name = "service-account-name" + name = "example-service-account" description = "service account description" } + +resource "castai_service_account_key" "service_account_key" { + organization_id = data.castai_organization.test.id + service_account_id = castai_service_account.service_account.id + name = "example-key" + active = true + expires_at = "2025-01-01T00:00:00Z" +} + +output "service_account_key" { + value = castai_service_account_key.service_account_key.token +} ```