From cebe4ae5af71f487d256df6e68eca5cf8e7669b1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Przemys=C5=82aw=20Golicz?= Date: Fri, 15 Mar 2024 12:39:26 +0100 Subject: [PATCH 01/19] remove obsolete code for runtime registration deregistration in compass --- components/provisioner/cmd/init.go | 4 +- components/provisioner/cmd/main.go | 45 +--- ...resolver_integration_with_gardener_test.go | 5 +- .../operations/queue/queues_constructor.go | 45 +--- .../wait_for_cluster_deletion.go | 39 +--- .../provisioning/wait_for_cluster_domain.go | 57 +---- .../provisioning/graphql_converter.go | 50 ++--- .../provisioning/graphql_converter_test.go | 10 +- .../internal/provisioning/service.go | 70 ++---- .../internal/provisioning/service_test.go | 40 +--- .../internal/runtime/configuration_test.go | 207 ------------------ .../internal/runtime/configurator.go | 143 ------------ .../internal/runtime/mocks/Configurator.go | 45 ---- 13 files changed, 52 insertions(+), 708 deletions(-) delete mode 100644 components/provisioner/internal/runtime/configuration_test.go delete mode 100644 components/provisioner/internal/runtime/configurator.go delete mode 100644 components/provisioner/internal/runtime/mocks/Configurator.go diff --git a/components/provisioner/cmd/init.go b/components/provisioner/cmd/init.go index 08f0fe76b6..d201aabba1 100644 --- a/components/provisioner/cmd/init.go +++ b/components/provisioner/cmd/init.go @@ -45,7 +45,6 @@ func newProvisioningService( shootUpgradeQueue queue.OperationQueue, defaultEnableKubernetesVersionAutoUpdate, defaultEnableMachineImageVersionAutoUpdate bool, - runtimeRegistrationEnabled bool, dynamicKubeconfigProvider DynamicKubeconfigProvider) provisioning.Service { uuidGenerator := uuid.NewUUIDGenerator() @@ -63,8 +62,7 @@ func newProvisioningService( provisioningQueue, deprovisioningQueue, shootUpgradeQueue, - dynamicKubeconfigProvider, - runtimeRegistrationEnabled) + dynamicKubeconfigProvider) } func newDirectorClient(config config) (director.DirectorClient, error) { diff --git a/components/provisioner/cmd/main.go b/components/provisioner/cmd/main.go index 66ddd81f79..86997bf927 100644 --- a/components/provisioner/cmd/main.go +++ b/components/provisioner/cmd/main.go @@ -26,7 +26,6 @@ import ( provisioningStages "github.com/kyma-project/control-plane/components/provisioner/internal/operations/stages/provisioning" "github.com/kyma-project/control-plane/components/provisioner/internal/persistence/database" "github.com/kyma-project/control-plane/components/provisioner/internal/provisioning/persistence/dbsession" - "github.com/kyma-project/control-plane/components/provisioner/internal/runtime" "github.com/kyma-project/control-plane/components/provisioner/internal/util/k8s" "github.com/kyma-project/control-plane/components/provisioner/pkg/gqlschema" "github.com/pkg/errors" @@ -46,8 +45,6 @@ type config struct { DirectorURL string `envconfig:"default=http://compass-director.compass-system.svc.cluster.local:3000/graphql"` SkipDirectorCertVerification bool `envconfig:"default=false"` DirectorOAuthPath string `envconfig:"APP_DIRECTOR_OAUTH_PATH,default=./dev/director.yaml"` - RuntimeRegistrationEnabled bool `envconfig:"default=true"` - RuntimeDeregistrationEnabled bool `envconfig:"default=true"` Database struct { User string `envconfig:"default=postgres"` @@ -90,7 +87,6 @@ type config struct { func (c *config) String() string { return fmt.Sprintf("Address: %s, APIEndpoint: %s, DirectorURL: %s, "+ "SkipDirectorCertVerification: %v, DirectorOAuthPath: %s, "+ - "RuntimeRegistrationEnabled %v, RuntimeDeregistrationEnabled %v, "+ "DatabaseUser: %s, DatabaseHost: %s, DatabasePort: %s, "+ "DatabaseName: %s, DatabaseSSLMode: %s, "+ "ProvisioningTimeoutClusterCreation: %s "+ @@ -105,7 +101,6 @@ func (c *config) String() string { "LogLevel: %s", c.Address, c.APIEndpoint, c.DirectorURL, c.SkipDirectorCertVerification, c.DirectorOAuthPath, - c.RuntimeDeregistrationEnabled, c.RuntimeDeregistrationEnabled, c.Database.User, c.Database.Host, c.Database.Port, c.Database.Name, c.Database.SSLMode, c.ProvisioningTimeout.ClusterCreation.String(), @@ -173,45 +168,12 @@ func main() { k8sClientProvider := k8s.NewK8sClientProvider() - runtimeConfigurator := runtime.NewRuntimeConfigurator(k8sClientProvider, directorClient) adminKubeconfigRequest := gardenerClient.SubResource("adminkubeconfig") kubeconfigProvider := gardener.NewKubeconfigProvider(shootClient, adminKubeconfigRequest, secretsInterface) - var provisioningQueue queue.OperationQueue - var shootUpgradeQueue queue.OperationQueue - - if cfg.RuntimeRegistrationEnabled { - provisioningQueue = queue.CreateProvisioningQueue( - cfg.ProvisioningTimeout, - dbsFactory, - directorClient, - shootClient, - cfg.OperatorRoleBinding, - k8sClientProvider, - runtimeConfigurator, - kubeconfigProvider) - - shootUpgradeQueue = queue.CreateShootUpgradeQueue(cfg.ProvisioningTimeout, dbsFactory, directorClient, shootClient, cfg.OperatorRoleBinding, k8sClientProvider, kubeconfigProvider) - - } else { - provisioningQueue = queue.CreateProvisioningQueueWithoutRegistration( - cfg.ProvisioningTimeout, - dbsFactory, - shootClient, - cfg.OperatorRoleBinding, - k8sClientProvider, - kubeconfigProvider) - - shootUpgradeQueue = queue.CreateShootUpgradeQueue(cfg.ProvisioningTimeout, dbsFactory, nil, shootClient, cfg.OperatorRoleBinding, k8sClientProvider, kubeconfigProvider) - } - - var deprovisioningQueue queue.OperationQueue - - if cfg.RuntimeDeregistrationEnabled { - deprovisioningQueue = queue.CreateDeprovisioningQueue(cfg.DeprovisioningTimeout, dbsFactory, directorClient, shootClient) - } else { - deprovisioningQueue = queue.CreateDeprovisioningQueue(cfg.DeprovisioningTimeout, dbsFactory, nil, shootClient) - } + provisioningQueue := queue.CreateProvisioningQueue(cfg.ProvisioningTimeout, dbsFactory, shootClient, cfg.OperatorRoleBinding, k8sClientProvider, kubeconfigProvider) + shootUpgradeQueue := queue.CreateShootUpgradeQueue(cfg.ProvisioningTimeout, dbsFactory, shootClient, cfg.OperatorRoleBinding, k8sClientProvider, kubeconfigProvider) + deprovisioningQueue := queue.CreateDeprovisioningQueue(cfg.DeprovisioningTimeout, dbsFactory, shootClient) provisioner := gardener.NewProvisioner(gardenerNamespace, shootClient, dbsFactory, cfg.Gardener.AuditLogsPolicyConfigMap, cfg.Gardener.MaintenanceWindowConfigPath) shootController, err := newShootController(gardenerNamespace, gardenerClusterConfig, dbsFactory, cfg.Gardener.AuditLogsTenantConfigPath) @@ -232,7 +194,6 @@ func main() { shootUpgradeQueue, cfg.Gardener.DefaultEnableKubernetesVersionAutoUpdate, cfg.Gardener.DefaultEnableMachineImageVersionAutoUpdate, - cfg.RuntimeRegistrationEnabled, kubeconfigProvider, ) diff --git a/components/provisioner/internal/api/resolver_integration_with_gardener_test.go b/components/provisioner/internal/api/resolver_integration_with_gardener_test.go index 9e26b7a8ef..38ebd38131 100644 --- a/components/provisioner/internal/api/resolver_integration_with_gardener_test.go +++ b/components/provisioner/internal/api/resolver_integration_with_gardener_test.go @@ -208,8 +208,6 @@ func TestProvisioning_ProvisionRuntimeWithDatabase(t *testing.T) { inputConverter := provisioning.NewInputConverter(uuidGenerator, "Project", defaultEnableKubernetesVersionAutoUpdate, defaultEnableMachineImageVersionAutoUpdate) graphQLConverter := provisioning.NewGraphQLConverter() - runtimeRegistrationEnabled := true - provisioningService := provisioning.NewProvisioningService( inputConverter, graphQLConverter, @@ -221,8 +219,7 @@ func TestProvisioning_ProvisionRuntimeWithDatabase(t *testing.T) { provisioningQueue, deprovisioningQueue, shootUpgradeQueue, - kubeconfigProviderMock, - runtimeRegistrationEnabled) + kubeconfigProviderMock) validator := api.NewValidator() diff --git a/components/provisioner/internal/operations/queue/queues_constructor.go b/components/provisioner/internal/operations/queue/queues_constructor.go index 0150507605..55a56291ac 100644 --- a/components/provisioner/internal/operations/queue/queues_constructor.go +++ b/components/provisioner/internal/operations/queue/queues_constructor.go @@ -4,7 +4,6 @@ import ( "time" gardener_apis "github.com/gardener/gardener/pkg/client/core/clientset/versioned/typed/core/v1beta1" - "github.com/kyma-project/control-plane/components/provisioner/internal/director" "github.com/kyma-project/control-plane/components/provisioner/internal/model" "github.com/kyma-project/control-plane/components/provisioner/internal/operations" "github.com/kyma-project/control-plane/components/provisioner/internal/operations/failure" @@ -12,7 +11,6 @@ import ( "github.com/kyma-project/control-plane/components/provisioner/internal/operations/stages/provisioning" "github.com/kyma-project/control-plane/components/provisioner/internal/operations/stages/shootupgrade" "github.com/kyma-project/control-plane/components/provisioner/internal/provisioning/persistence/dbsession" - "github.com/kyma-project/control-plane/components/provisioner/internal/runtime" "github.com/kyma-project/control-plane/components/provisioner/internal/util/k8s" ) @@ -45,39 +43,6 @@ type KubeconfigProvider interface { } func CreateProvisioningQueue( - timeouts ProvisioningTimeouts, - factory dbsession.Factory, - directorClient director.DirectorClient, - shootClient gardener_apis.ShootInterface, - operatorRoleBindingConfig provisioning.OperatorRoleBinding, - k8sClientProvider k8s.K8sClientProvider, - configurator runtime.Configurator, - kubeconfigProvider KubeconfigProvider) OperationQueue { - - configureAgentStep := provisioning.NewConnectAgentStep(configurator, kubeconfigProvider, model.FinishedStage, timeouts.AgentConfiguration) - createBindingsForOperatorsStep := provisioning.NewCreateBindingsForOperatorsStep(k8sClientProvider, operatorRoleBindingConfig, kubeconfigProvider, configureAgentStep.Name(), timeouts.BindingsCreation) - waitForClusterCreationStep := provisioning.NewWaitForClusterCreationStep(shootClient, factory.NewReadWriteSession(), createBindingsForOperatorsStep.Name(), timeouts.ClusterCreation) - waitForClusterDomainStep := provisioning.NewWaitForClusterDomainStep(shootClient, directorClient, waitForClusterCreationStep.Name(), timeouts.ClusterDomains) - - provisionSteps := map[model.OperationStage]operations.Step{ - model.ConnectRuntimeAgent: configureAgentStep, - model.CreatingBindingsForOperators: createBindingsForOperatorsStep, - model.WaitingForClusterDomain: waitForClusterDomainStep, - model.WaitingForClusterCreation: waitForClusterCreationStep, - } - - provisioningExecutor := operations.NewExecutor( - factory.NewReadWriteSession(), - model.Provision, - provisionSteps, - failure.NewNoopFailureHandler(), - directorClient, - ) - - return NewQueue(provisioningExecutor) -} - -func CreateProvisioningQueueWithoutRegistration( timeouts ProvisioningTimeouts, factory dbsession.Factory, shootClient gardener_apis.ShootInterface, @@ -87,7 +52,7 @@ func CreateProvisioningQueueWithoutRegistration( createBindingsForOperatorsStep := provisioning.NewCreateBindingsForOperatorsStep(k8sClientProvider, operatorRoleBindingConfig, kubeconfigProvider, model.FinishedStage, timeouts.BindingsCreation) waitForClusterCreationStep := provisioning.NewWaitForClusterCreationStep(shootClient, factory.NewReadWriteSession(), createBindingsForOperatorsStep.Name(), timeouts.ClusterCreation) - waitForClusterDomainStep := provisioning.NewWaitForClusterDomainStep(shootClient, nil, waitForClusterCreationStep.Name(), timeouts.ClusterDomains) + waitForClusterDomainStep := provisioning.NewWaitForClusterDomainStep(shootClient, waitForClusterCreationStep.Name(), timeouts.ClusterDomains) provisionSteps := map[model.OperationStage]operations.Step{ model.CreatingBindingsForOperators: createBindingsForOperatorsStep, @@ -109,11 +74,10 @@ func CreateProvisioningQueueWithoutRegistration( func CreateDeprovisioningQueue( timeouts DeprovisioningTimeouts, factory dbsession.Factory, - directorClient director.DirectorClient, shootClient gardener_apis.ShootInterface, ) OperationQueue { - waitForClusterDeletion := deprovisioning.NewWaitForClusterDeletionStep(shootClient, factory, directorClient, model.FinishedStage, timeouts.WaitingForClusterDeletion) + waitForClusterDeletion := deprovisioning.NewWaitForClusterDeletionStep(shootClient, factory, model.FinishedStage, timeouts.WaitingForClusterDeletion) deleteCluster := deprovisioning.NewDeleteClusterStep(shootClient, waitForClusterDeletion.Name(), timeouts.ClusterDeletion) deprovisioningSteps := map[model.OperationStage]operations.Step{ @@ -126,7 +90,7 @@ func CreateDeprovisioningQueue( model.DeprovisionNoInstall, deprovisioningSteps, failure.NewNoopFailureHandler(), - directorClient, + nil, ) return NewQueue(deprovisioningExecutor) @@ -135,7 +99,6 @@ func CreateDeprovisioningQueue( func CreateShootUpgradeQueue( timeouts ProvisioningTimeouts, factory dbsession.Factory, - directorClient director.DirectorClient, shootClient gardener_apis.ShootInterface, operatorRoleBindingConfig provisioning.OperatorRoleBinding, k8sClientProvider k8s.K8sClientProvider, @@ -157,7 +120,7 @@ func CreateShootUpgradeQueue( model.UpgradeShoot, upgradeSteps, failure.NewNoopFailureHandler(), - directorClient, + nil, ) return NewQueue(upgradeClusterExecutor) diff --git a/components/provisioner/internal/operations/stages/deprovisioning/wait_for_cluster_deletion.go b/components/provisioner/internal/operations/stages/deprovisioning/wait_for_cluster_deletion.go index 5214eb4f4a..99fe397ca6 100644 --- a/components/provisioner/internal/operations/stages/deprovisioning/wait_for_cluster_deletion.go +++ b/components/provisioner/internal/operations/stages/deprovisioning/wait_for_cluster_deletion.go @@ -7,7 +7,6 @@ import ( "github.com/kyma-project/control-plane/components/provisioner/internal/apperrors" "github.com/kyma-project/control-plane/components/provisioner/internal/util" - "github.com/kyma-project/control-plane/components/provisioner/internal/director" "github.com/kyma-project/control-plane/components/provisioner/internal/provisioning/persistence/dbsession" "github.com/kyma-project/control-plane/components/provisioner/internal/model" @@ -21,16 +20,14 @@ import ( type WaitForClusterDeletionStep struct { gardenerClient GardenerClient dbsFactory dbsession.Factory - directorClient director.DirectorClient nextStep model.OperationStage timeLimit time.Duration } -func NewWaitForClusterDeletionStep(gardenerClient GardenerClient, dbsFactory dbsession.Factory, directorClient director.DirectorClient, nextStep model.OperationStage, timeLimit time.Duration) *WaitForClusterDeletionStep { +func NewWaitForClusterDeletionStep(gardenerClient GardenerClient, dbsFactory dbsession.Factory, nextStep model.OperationStage, timeLimit time.Duration) *WaitForClusterDeletionStep { return &WaitForClusterDeletionStep{ gardenerClient: gardenerClient, dbsFactory: dbsFactory, - directorClient: directorClient, nextStep: nextStep, timeLimit: timeLimit, } @@ -87,13 +84,6 @@ func (s *WaitForClusterDeletionStep) setDeprovisioningFinished(cluster model.Clu return errors.Wrap(dberr, "error marking cluster for deletion") } - if s.directorClient != nil { - err := s.deleteRuntime(cluster) - if err != nil { - return err - } - } - dberr = session.Commit() if dberr != nil { return errors.Wrap(dberr, "error commiting transaction") @@ -101,30 +91,3 @@ func (s *WaitForClusterDeletionStep) setDeprovisioningFinished(cluster model.Clu return nil } - -func (s *WaitForClusterDeletionStep) deleteRuntime(cluster model.Cluster) error { - var exists bool - err := util.RetryOnError(5*time.Second, 3, "Error while checking if runtime exists in Director: %s", func() (err apperrors.AppError) { - exists, err = s.directorClient.RuntimeExists(cluster.ID, cluster.Tenant) - return - }) - - if err != nil { - return errors.Wrap(err, "error checking Runtime exists in Director") - } - - if !exists { - return nil - } - - err = util.RetryOnError(5*time.Second, 3, "Error while unregistering runtime in Director: %s", func() (err apperrors.AppError) { - err = s.directorClient.DeleteRuntime(cluster.ID, cluster.Tenant) - return - }) - - if err != nil { - return errors.Wrap(err, "error deleting Runtime form Director") - } - - return nil -} diff --git a/components/provisioner/internal/operations/stages/provisioning/wait_for_cluster_domain.go b/components/provisioner/internal/operations/stages/provisioning/wait_for_cluster_domain.go index 5369855144..ecd33c97a9 100644 --- a/components/provisioner/internal/operations/stages/provisioning/wait_for_cluster_domain.go +++ b/components/provisioner/internal/operations/stages/provisioning/wait_for_cluster_domain.go @@ -2,17 +2,13 @@ package provisioning import ( "context" - "fmt" "time" gardener_types "github.com/gardener/gardener/pkg/apis/core/v1beta1" - "github.com/kyma-incubator/compass/components/director/pkg/graphql" - "github.com/pkg/errors" "github.com/sirupsen/logrus" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" "github.com/kyma-project/control-plane/components/provisioner/internal/apperrors" - "github.com/kyma-project/control-plane/components/provisioner/internal/director" "github.com/kyma-project/control-plane/components/provisioner/internal/model" "github.com/kyma-project/control-plane/components/provisioner/internal/operations" "github.com/kyma-project/control-plane/components/provisioner/internal/util" @@ -20,7 +16,6 @@ import ( type WaitForClusterDomainStep struct { gardenerClient GardenerClient - directorClient director.DirectorClient nextStep model.OperationStage timeLimit time.Duration } @@ -30,10 +25,9 @@ type GardenerClient interface { Get(ctx context.Context, name string, options v1.GetOptions) (*gardener_types.Shoot, error) } -func NewWaitForClusterDomainStep(gardenerClient GardenerClient, directorClient director.DirectorClient, nextStep model.OperationStage, timeLimit time.Duration) *WaitForClusterDomainStep { +func NewWaitForClusterDomainStep(gardenerClient GardenerClient, nextStep model.OperationStage, timeLimit time.Duration) *WaitForClusterDomainStep { return &WaitForClusterDomainStep{ gardenerClient: gardenerClient, - directorClient: directorClient, nextStep: nextStep, timeLimit: timeLimit, } @@ -58,54 +52,5 @@ func (s *WaitForClusterDomainStep) Run(cluster model.Cluster, _ model.Operation, return operations.StageResult{Stage: s.Name(), Delay: 5 * time.Second}, nil } - if s.directorClient == nil { - return operations.StageResult{Stage: s.nextStep, Delay: 0}, nil - } - - // TODO: Consider updating Labels and StatusCondition separately without getting the Runtime - // It'll be possible after this issue implementation: - // - https://github.com/kyma-project/control-plane/issues/1186 - runtimeInput, err := s.prepareProvisioningUpdateRuntimeInput(cluster.ID, cluster.Tenant, shoot) - if err != nil { - return operations.StageResult{}, err - } - - err = util.RetryOnError(5*time.Second, 3, "Error while updating runtime in Director: %s", func() (err apperrors.AppError) { - err = s.directorClient.UpdateRuntime(cluster.ID, runtimeInput, cluster.Tenant) - return - }) - - if err != nil { - return operations.StageResult{}, err - } - return operations.StageResult{Stage: s.nextStep, Delay: 0}, nil } - -func (s *WaitForClusterDomainStep) prepareProvisioningUpdateRuntimeInput(runtimeId, tenant string, shoot *gardener_types.Shoot) (*graphql.RuntimeUpdateInput, error) { - - var runtime graphql.RuntimeExt - - err := util.RetryOnError(5*time.Second, 3, "Error while getting runtime from Director: %s", func() (err apperrors.AppError) { - runtime, err = s.directorClient.GetRuntime(runtimeId, tenant) - return - }) - if err != nil { - return &graphql.RuntimeUpdateInput{}, errors.Wrap(err, fmt.Sprintf("failed to get Runtime by ID: %s", runtimeId)) - } - - if runtime.Labels == nil { - runtime.Labels = graphql.Labels{} - } - runtime.Labels["gardenerClusterName"] = shoot.Name - runtime.Labels["gardenerClusterDomain"] = *shoot.Spec.DNS.Domain - statusCondition := graphql.RuntimeStatusConditionProvisioning - - runtimeUpdateInput := &graphql.RuntimeUpdateInput{ - Name: runtime.Name, - Description: runtime.Description, - Labels: runtime.Labels, - StatusCondition: &statusCondition, - } - return runtimeUpdateInput, nil -} diff --git a/components/provisioner/internal/provisioning/graphql_converter.go b/components/provisioner/internal/provisioning/graphql_converter.go index ecd6d07671..dcbdc54ab2 100644 --- a/components/provisioner/internal/provisioning/graphql_converter.go +++ b/components/provisioner/internal/provisioning/graphql_converter.go @@ -6,8 +6,8 @@ import ( ) type GraphQLConverter interface { - RuntimeStatusToGraphQLStatus(status model.RuntimeStatus, includeCompassID bool) *gqlschema.RuntimeStatus - OperationStatusToGQLOperationStatus(operation model.Operation, includeCompassID bool) *gqlschema.OperationStatus + RuntimeStatusToGraphQLStatus(status model.RuntimeStatus) *gqlschema.RuntimeStatus + OperationStatusToGQLOperationStatus(operation model.Operation) *gqlschema.OperationStatus } func NewGraphQLConverter() GraphQLConverter { @@ -16,43 +16,27 @@ func NewGraphQLConverter() GraphQLConverter { type graphQLConverter struct{} -func (c graphQLConverter) RuntimeStatusToGraphQLStatus(status model.RuntimeStatus, includeCompassID bool) *gqlschema.RuntimeStatus { +func (c graphQLConverter) RuntimeStatusToGraphQLStatus(status model.RuntimeStatus) *gqlschema.RuntimeStatus { return &gqlschema.RuntimeStatus{ - LastOperationStatus: c.OperationStatusToGQLOperationStatus(status.LastOperationStatus, includeCompassID), + LastOperationStatus: c.OperationStatusToGQLOperationStatus(status.LastOperationStatus), RuntimeConnectionStatus: c.runtimeConnectionStatusToGraphQLStatus(status.RuntimeConnectionStatus), RuntimeConfiguration: c.clusterToToGraphQLRuntimeConfiguration(status.RuntimeConfiguration), } } -func (c graphQLConverter) OperationStatusToGQLOperationStatus(operation model.Operation, includeCompassID bool) *gqlschema.OperationStatus { - - if includeCompassID { - return &gqlschema.OperationStatus{ - ID: &operation.ID, - Operation: c.operationTypeToGraphQLType(operation.Type), - State: c.operationStateToGraphQLState(operation.State), - Message: &operation.Message, - RuntimeID: &operation.ClusterID, - CompassRuntimeID: &operation.ClusterID, - LastError: &gqlschema.LastError{ - ErrMessage: operation.ErrMessage, - Reason: operation.Reason, - Component: operation.Component, - }, - } - } else { - return &gqlschema.OperationStatus{ - ID: &operation.ID, - Operation: c.operationTypeToGraphQLType(operation.Type), - State: c.operationStateToGraphQLState(operation.State), - Message: &operation.Message, - RuntimeID: &operation.ClusterID, - LastError: &gqlschema.LastError{ - ErrMessage: operation.ErrMessage, - Reason: operation.Reason, - Component: operation.Component, - }, - } +func (c graphQLConverter) OperationStatusToGQLOperationStatus(operation model.Operation) *gqlschema.OperationStatus { + + return &gqlschema.OperationStatus{ + ID: &operation.ID, + Operation: c.operationTypeToGraphQLType(operation.Type), + State: c.operationStateToGraphQLState(operation.State), + Message: &operation.Message, + RuntimeID: &operation.ClusterID, + LastError: &gqlschema.LastError{ + ErrMessage: operation.ErrMessage, + Reason: operation.Reason, + Component: operation.Component, + }, } } diff --git a/components/provisioner/internal/provisioning/graphql_converter_test.go b/components/provisioner/internal/provisioning/graphql_converter_test.go index 47d90166e4..02014df732 100644 --- a/components/provisioner/internal/provisioning/graphql_converter_test.go +++ b/components/provisioner/internal/provisioning/graphql_converter_test.go @@ -53,7 +53,7 @@ func TestOperationStatusToGQLOperationStatus(t *testing.T) { } //when - status := graphQLConverter.OperationStatusToGQLOperationStatus(operation, true) + status := graphQLConverter.OperationStatusToGQLOperationStatus(operation) //then assert.Equal(t, expectedOperationStatus, status) @@ -93,7 +93,7 @@ func TestOperationStatusToGQLOperationStatus(t *testing.T) { } //when - status := graphQLConverter.OperationStatusToGQLOperationStatus(operation, false) + status := graphQLConverter.OperationStatusToGQLOperationStatus(operation) //then assert.Equal(t, expectedOperationStatus, status) @@ -261,7 +261,7 @@ func TestRuntimeStatusToGraphQLStatus(t *testing.T) { } //when - gqlStatus := graphQLConverter.RuntimeStatusToGraphQLStatus(runtimeStatus, true) + gqlStatus := graphQLConverter.RuntimeStatusToGraphQLStatus(runtimeStatus) //then assert.Equal(t, expectedRuntimeStatus, gqlStatus) @@ -410,7 +410,7 @@ func TestRuntimeStatusToGraphQLStatus(t *testing.T) { } //when - gqlStatus := graphQLConverter.RuntimeStatusToGraphQLStatus(runtimeStatus, true) + gqlStatus := graphQLConverter.RuntimeStatusToGraphQLStatus(runtimeStatus) //then assert.Equal(t, expectedRuntimeStatus, gqlStatus) @@ -552,7 +552,7 @@ func TestRuntimeStatusToGraphQLStatus(t *testing.T) { } //when - gqlStatus := graphQLConverter.RuntimeStatusToGraphQLStatus(runtimeStatus, true) + gqlStatus := graphQLConverter.RuntimeStatusToGraphQLStatus(runtimeStatus) //then assert.Equal(t, expectedRuntimeStatus, gqlStatus) diff --git a/components/provisioner/internal/provisioning/service.go b/components/provisioner/internal/provisioning/service.go index 958ab94968..d48bcb3885 100644 --- a/components/provisioner/internal/provisioning/service.go +++ b/components/provisioner/internal/provisioning/service.go @@ -50,8 +50,6 @@ type service struct { shootProvider ShootProvider dynamicKubeconfigProvider DynamicKubeconfigProvider - runtimeRegistrationEnabled bool - dbSessionFactory dbsession.Factory provisioner Provisioner uuidGenerator uuid.UUIDGenerator @@ -75,47 +73,32 @@ func NewProvisioningService( deprovisioningQueue queue.OperationQueue, shootUpgradeQueue queue.OperationQueue, dynamicKubeconfigProvider DynamicKubeconfigProvider, - runtimeRegistrationEnabled bool, ) Service { return &service{ - inputConverter: inputConverter, - graphQLConverter: graphQLConverter, - directorService: directorService, - dbSessionFactory: factory, - provisioner: provisioner, - uuidGenerator: generator, - provisioningQueue: provisioningQueue, - deprovisioningQueue: deprovisioningQueue, - shootUpgradeQueue: shootUpgradeQueue, - shootProvider: shootProvider, - dynamicKubeconfigProvider: dynamicKubeconfigProvider, - runtimeRegistrationEnabled: runtimeRegistrationEnabled, + inputConverter: inputConverter, + graphQLConverter: graphQLConverter, + directorService: directorService, + dbSessionFactory: factory, + provisioner: provisioner, + uuidGenerator: generator, + provisioningQueue: provisioningQueue, + deprovisioningQueue: deprovisioningQueue, + shootUpgradeQueue: shootUpgradeQueue, + shootProvider: shootProvider, + dynamicKubeconfigProvider: dynamicKubeconfigProvider, } } func (r *service) ProvisionRuntime(config gqlschema.ProvisionRuntimeInput, tenant, subAccount string) (*gqlschema.OperationStatus, apperrors.AppError) { - runtimeInput := config.RuntimeInput var runtimeID string - if r.runtimeRegistrationEnabled { - - err := util.RetryOnError(5*time.Second, 3, "Error while registering runtime in Director: %s", func() (err apperrors.AppError) { - runtimeID, err = r.directorService.CreateRuntime(runtimeInput, tenant) - return - }) - - if err != nil { - return nil, err.Append("Failed to register Runtime") - } - } else { - runtimeID = r.uuidGenerator.New() - } + runtimeID = r.uuidGenerator.New() + log.Infof("Assigned new ID for provisioned Runtime: %s ", runtimeID) cluster, err := r.inputConverter.ProvisioningInputToCluster(runtimeID, config, tenant, subAccount) if err != nil { - r.unregisterFailedRuntime(runtimeID, tenant) return nil, err } @@ -128,42 +111,23 @@ func (r *service) ProvisionRuntime(config gqlschema.ProvisionRuntimeInput, tenan // Try to set provisioning started before triggering it (which is hard to interrupt) to verify all unique constraints operation, dberr := r.setProvisioningStarted(dbSession, runtimeID, cluster) if dberr != nil { - r.unregisterFailedRuntime(runtimeID, tenant) return nil, dberr } err = r.provisioner.ProvisionCluster(cluster, operation.ID) if err != nil { - r.unregisterFailedRuntime(runtimeID, tenant) return nil, err.Append("Failed to start provisioning") } dberr = dbSession.Commit() if dberr != nil { - r.unregisterFailedRuntime(runtimeID, tenant) return nil, dberr } log.Infof("KymaConfig not provided. Starting provisioning steps for runtime %s without installation", cluster.ID) r.provisioningQueue.Add(operation.ID) - return r.graphQLConverter.OperationStatusToGQLOperationStatus(operation, r.runtimeRegistrationEnabled), nil -} - -func (r *service) unregisterFailedRuntime(id, tenant string) { - - if !r.runtimeRegistrationEnabled { - return - } - - log.Infof("Starting provisioning failed. Unregistering Runtime %s...", id) - err := util.RetryOnError(10*time.Second, 3, "Error while unregistering runtime in Director: %s", func() (err apperrors.AppError) { - err = r.directorService.DeleteRuntime(id, tenant) - return - }) - if err != nil { - log.Warnf("Failed to unregister failed Runtime '%s': %s", id, err.Error()) - } + return r.graphQLConverter.OperationStatusToGQLOperationStatus(operation), nil } func (r *service) DeprovisionRuntime(id string) (string, apperrors.AppError) { @@ -269,7 +233,7 @@ func (r *service) UpgradeGardenerShoot(runtimeID string, input gqlschema.Upgrade r.shootUpgradeQueue.Add(operation.ID) - return r.graphQLConverter.OperationStatusToGQLOperationStatus(operation, r.runtimeRegistrationEnabled), nil + return r.graphQLConverter.OperationStatusToGQLOperationStatus(operation), nil } func (r *service) verifyLastOperationFinished(session dbsession.ReadSession, runtimeId string) apperrors.AppError { @@ -295,7 +259,7 @@ func (r *service) RuntimeStatus(runtimeID string) (*gqlschema.RuntimeStatus, app return nil, dberr.Append("failed to get Runtime Status") } - return r.graphQLConverter.RuntimeStatusToGraphQLStatus(runtimeStatus, r.runtimeRegistrationEnabled), nil + return r.graphQLConverter.RuntimeStatusToGraphQLStatus(runtimeStatus), nil } func (r *service) RuntimeOperationStatus(operationID string) (*gqlschema.OperationStatus, apperrors.AppError) { @@ -306,7 +270,7 @@ func (r *service) RuntimeOperationStatus(operationID string) (*gqlschema.Operati return nil, dberr.Append("failed to get Runtime Operation Status") } - return r.graphQLConverter.OperationStatusToGQLOperationStatus(operation, r.runtimeRegistrationEnabled), nil + return r.graphQLConverter.OperationStatusToGQLOperationStatus(operation), nil } func (r *service) getRuntimeStatus(runtimeID string) (model.RuntimeStatus, apperrors.AppError) { diff --git a/components/provisioner/internal/provisioning/service_test.go b/components/provisioner/internal/provisioning/service_test.go index 168a298e79..70e891d78d 100644 --- a/components/provisioner/internal/provisioning/service_test.go +++ b/components/provisioner/internal/provisioning/service_test.go @@ -108,43 +108,7 @@ func TestService_ProvisionRuntime(t *testing.T) { operationMatcher := getOperationMatcher(expectedOperation) kubeconfigProviderMock := &queue_mock.KubeconfigProvider{} - t.Run("Should start runtime provisioning of Gardener cluster and return operation ID ", func(t *testing.T) { - // given - sessionFactoryMock := &sessionMocks.Factory{} - writeSessionWithinTransactionMock := &sessionMocks.WriteSessionWithinTransaction{} - directorServiceMock := &directormock.DirectorClient{} - provisioner := &mocks2.Provisioner{} - - provisioningQueue := &mocks.OperationQueue{} - - directorServiceMock.On("CreateRuntime", mock.Anything, tenant).Return(runtimeID, nil) - sessionFactoryMock.On("NewSessionWithinTransaction").Return(writeSessionWithinTransactionMock, nil) - writeSessionWithinTransactionMock.On("InsertCluster", mock.MatchedBy(clusterMatcher)).Return(nil) - writeSessionWithinTransactionMock.On("InsertGardenerConfig", mock.AnythingOfType("model.GardenerConfig")).Return(nil) - writeSessionWithinTransactionMock.On("InsertOperation", mock.MatchedBy(operationMatcher)).Return(nil) - writeSessionWithinTransactionMock.On("Commit").Return(nil) - writeSessionWithinTransactionMock.On("RollbackUnlessCommitted").Return() - provisioner.On("ProvisionCluster", mock.MatchedBy(clusterMatcher), mock.MatchedBy(notEmptyUUIDMatcher)).Return(nil) - - provisioningQueue.On("Add", mock.AnythingOfType("string")).Return(nil) - - service := NewProvisioningService(inputConverter, graphQLConverter, directorServiceMock, sessionFactoryMock, provisioner, uuidGenerator, nil, provisioningQueue, nil, nil, kubeconfigProviderMock, true) - - // when - operationStatus, err := service.ProvisionRuntime(provisionRuntimeInputNoKymaConfig, tenant, subAccountId) - require.NoError(t, err) - - // then - assert.Equal(t, runtimeID, *operationStatus.RuntimeID) - assert.Equal(t, gqlschema.OperationTypeProvision, operationStatus.Operation) - assert.NotEmpty(t, operationStatus.ID) - sessionFactoryMock.AssertExpectations(t) - writeSessionWithinTransactionMock.AssertExpectations(t) - directorServiceMock.AssertExpectations(t) - provisioner.AssertExpectations(t) - }) - - t.Run("Should start runtime provisioning of Gardener cluster and return operation ID without registration of the runtime in Director when registration is disabled", func(t *testing.T) { + t.Run("Should start runtime provisioning of Gardener cluster and return operation ID", func(t *testing.T) { // given sessionFactoryMock := &sessionMocks.Factory{} writeSessionWithinTransactionMock := &sessionMocks.WriteSessionWithinTransaction{} @@ -165,7 +129,7 @@ func TestService_ProvisionRuntime(t *testing.T) { provisioningQueue.On("Add", mock.AnythingOfType("string")).Return(nil) - service := NewProvisioningService(inputConverter, graphQLConverter, directorServiceMock, sessionFactoryMock, provisioner, uuidGeneratorMock, nil, provisioningQueue, nil, nil, kubeconfigProviderMock, false) + service := NewProvisioningService(inputConverter, graphQLConverter, directorServiceMock, sessionFactoryMock, provisioner, uuidGeneratorMock, nil, provisioningQueue, nil, nil, kubeconfigProviderMock) // when operationStatus, err := service.ProvisionRuntime(provisionRuntimeInputNoKymaConfig, tenant, subAccountId) diff --git a/components/provisioner/internal/runtime/configuration_test.go b/components/provisioner/internal/runtime/configuration_test.go deleted file mode 100644 index dd6641a6f6..0000000000 --- a/components/provisioner/internal/runtime/configuration_test.go +++ /dev/null @@ -1,207 +0,0 @@ -package runtime - -import ( - "context" - - core "k8s.io/api/core/v1" - meta "k8s.io/apimachinery/pkg/apis/meta/v1" - - "testing" - - "github.com/kyma-project/control-plane/components/provisioner/internal/apperrors" - "github.com/kyma-project/control-plane/components/provisioner/internal/util" - - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/client-go/kubernetes" - - "github.com/kyma-incubator/compass/components/director/pkg/graphql" - mocks2 "github.com/kyma-project/control-plane/components/provisioner/internal/director/mocks" - "github.com/kyma-project/control-plane/components/provisioner/internal/model" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/client-go/kubernetes/fake" -) - -const ( - kubeconfig = "some Kubeconfig" -) - -func TestProvider_CreateConfigMapForRuntime(t *testing.T) { - connectorURL := "https://kyma.cx/connector/graphql" - runtimeID := "123-123-456" - tenant := "tenant" - token := "shdfv7123ygfbw832b" - - namespace := "kyma-system" - - cluster := model.Cluster{ - ID: runtimeID, - Tenant: tenant, - } - - oneTimeToken := graphql.OneTimeTokenForRuntimeExt{ - OneTimeTokenForRuntime: graphql.OneTimeTokenForRuntime{ - TokenWithURL: graphql.TokenWithURL{Token: token, ConnectorURL: connectorURL}, - }, - } - - t.Run("Should configure Runtime Agent", func(t *testing.T) { - //given - k8sClientProvider := newMockClientProvider(t) - directorClient := &mocks2.DirectorClient{} - - directorClient.On("GetConnectionToken", runtimeID, tenant).Return(oneTimeToken, nil) - - configProvider := NewRuntimeConfigurator(k8sClientProvider, directorClient) - - //when - err := configProvider.ConfigureRuntime(cluster, kubeconfig) - - //then - require.NoError(t, err) - secret, k8serr := k8sClientProvider.fakeClient.CoreV1().Secrets(namespace).Get(context.Background(), AgentConfigurationSecretName, v1.GetOptions{}) - require.NoError(t, k8serr) - - assertData := func(data map[string]string) { - assert.Equal(t, connectorURL, data["CONNECTOR_URL"]) - assert.Equal(t, runtimeID, data["RUNTIME_ID"]) - assert.Equal(t, tenant, data["TENANT"]) - assert.Equal(t, token, data["TOKEN"]) - } - - assertData(secret.StringData) - }) - - t.Run("Should reconfigure Runtime Agent", func(t *testing.T) { - //given - k8sClientProvider := newMockClientProvider(t) - oldSecret := &core.Secret{ - ObjectMeta: meta.ObjectMeta{ - Name: AgentConfigurationSecretName, - Namespace: namespace, - }, - StringData: map[string]string{ - "key": "value", - }, - } - - secret, k8serr := k8sClientProvider.fakeClient.CoreV1().Secrets(namespace).Create(context.Background(), oldSecret, v1.CreateOptions{}) - require.NoError(t, k8serr) - - directorClient := &mocks2.DirectorClient{} - directorClient.On("GetConnectionToken", runtimeID, tenant).Return(oneTimeToken, nil) - - configProvider := NewRuntimeConfigurator(k8sClientProvider, directorClient) - - //when - err := configProvider.ConfigureRuntime(cluster, kubeconfig) - - //then - require.NoError(t, err) - secret, k8serr = k8sClientProvider.fakeClient.CoreV1().Secrets(namespace).Get(context.Background(), AgentConfigurationSecretName, v1.GetOptions{}) - require.NoError(t, k8serr) - - assertData := func(data map[string]string) { - assert.Equal(t, connectorURL, data["CONNECTOR_URL"]) - assert.Equal(t, runtimeID, data["RUNTIME_ID"]) - assert.Equal(t, tenant, data["TENANT"]) - assert.Equal(t, token, data["TOKEN"]) - } - - assertData(secret.StringData) - }) - - t.Run("Should retry on GetConnectionToken and configure Runtime Agent", func(t *testing.T) { - //given - k8sClientProvider := newMockClientProvider(t) - directorClient := &mocks2.DirectorClient{} - - directorClient.On("GetConnectionToken", runtimeID, tenant).Once().Return(graphql.OneTimeTokenForRuntimeExt{}, apperrors.Internal("token error")) - directorClient.On("GetConnectionToken", runtimeID, tenant).Once().Return(oneTimeToken, nil) - - configProvider := NewRuntimeConfigurator(k8sClientProvider, directorClient) - - //when - err := configProvider.ConfigureRuntime(cluster, kubeconfig) - - //then - require.NoError(t, err) - secret, k8serr := k8sClientProvider.fakeClient.CoreV1().Secrets(namespace).Get(context.Background(), AgentConfigurationSecretName, v1.GetOptions{}) - require.NoError(t, k8serr) - - assertData := func(data map[string]string) { - assert.Equal(t, connectorURL, data["CONNECTOR_URL"]) - assert.Equal(t, runtimeID, data["RUNTIME_ID"]) - assert.Equal(t, tenant, data["TENANT"]) - assert.Equal(t, token, data["TOKEN"]) - } - - assertData(secret.StringData) - }) - - t.Run("Should return error when failed to create client", func(t *testing.T) { - //given - - k8sClientProvider := newErrorClientProvider(t, apperrors.Internal("error")) - directorClient := &mocks2.DirectorClient{} - - directorClient.On("GetConnectionToken", runtimeID, tenant).Return(oneTimeToken, nil) - - configProvider := NewRuntimeConfigurator(k8sClientProvider, directorClient) - - //when - err := configProvider.ConfigureRuntime(cluster, kubeconfig) - - //then - require.Error(t, err) - util.CheckErrorType(t, err, apperrors.CodeInternal) - }) - - t.Run("Should return error when failed to fetch token", func(t *testing.T) { - //given - directorClient := &mocks2.DirectorClient{} - - directorClient.On("GetConnectionToken", runtimeID, tenant).Return(graphql.OneTimeTokenForRuntimeExt{}, apperrors.Internal("error")) - - configProvider := NewRuntimeConfigurator(nil, directorClient) - - //when - err := configProvider.ConfigureRuntime(cluster, kubeconfig) - - //then - require.Error(t, err) - util.CheckErrorType(t, err, apperrors.CodeInternal) - }) -} - -type mockClientProvider struct { - t *testing.T - fakeClient *fake.Clientset - err apperrors.AppError -} - -func newMockClientProvider(t *testing.T, objects ...runtime.Object) *mockClientProvider { - return &mockClientProvider{ - t: t, - fakeClient: fake.NewSimpleClientset(objects...), - } -} - -func newErrorClientProvider(t *testing.T, err apperrors.AppError) *mockClientProvider { - return &mockClientProvider{ - t: t, - err: err, - } -} - -func (m *mockClientProvider) CreateK8SClient(kubeconfigRaw string) (kubernetes.Interface, apperrors.AppError) { - assert.Equal(m.t, kubeconfig, kubeconfigRaw) - - if m.err != nil { - return nil, m.err - } - - return m.fakeClient, nil -} diff --git a/components/provisioner/internal/runtime/configurator.go b/components/provisioner/internal/runtime/configurator.go deleted file mode 100644 index dede6578fd..0000000000 --- a/components/provisioner/internal/runtime/configurator.go +++ /dev/null @@ -1,143 +0,0 @@ -package runtime - -import ( - "context" - "time" - - "github.com/pkg/errors" - k8serrors "k8s.io/apimachinery/pkg/api/errors" - v1 "k8s.io/client-go/kubernetes/typed/core/v1" - - "github.com/kyma-incubator/compass/components/director/pkg/graphql" - - "github.com/kyma-project/control-plane/components/provisioner/internal/apperrors" - "github.com/kyma-project/control-plane/components/provisioner/internal/util" - - "github.com/kyma-project/control-plane/components/provisioner/internal/util/k8s" - - "github.com/kyma-project/control-plane/components/provisioner/internal/director" - "github.com/kyma-project/control-plane/components/provisioner/internal/model" - - core "k8s.io/api/core/v1" - meta "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -const ( - AgentConfigurationSecretName = "compass-agent-configuration" - runtimeAgentComponentNameSpace = "kyma-system" -) - -//go:generate mockery --name=Configurator -type Configurator interface { - ConfigureRuntime(cluster model.Cluster, kubeconfigRaw string) apperrors.AppError -} - -type configurator struct { - builder k8s.K8sClientProvider - directorClient director.DirectorClient -} - -func NewRuntimeConfigurator(builder k8s.K8sClientProvider, directorClient director.DirectorClient) Configurator { - return &configurator{ - builder: builder, - directorClient: directorClient, - } -} - -func (c *configurator) ConfigureRuntime(cluster model.Cluster, kubeconfigRaw string) apperrors.AppError { - - token, err := c.getConnectionToken(cluster) - if err != nil { - return err.Append("error getting one time token from Director") - } - - err = c.configureAgent(cluster, token, runtimeAgentComponentNameSpace, kubeconfigRaw) - if err != nil { - return err.Append("error configuring Runtime Agent") - } - - return nil -} - -func (c *configurator) configureAgent(cluster model.Cluster, token graphql.OneTimeTokenForRuntimeExt, namespace, kubeconfigRaw string) apperrors.AppError { - var err apperrors.AppError - - k8sClient, err := c.builder.CreateK8SClient(kubeconfigRaw) - if err != nil { - return err.Append("error creating Config Map client") - } - - configurationData := map[string]string{ - "CONNECTOR_URL": token.ConnectorURL, - "RUNTIME_ID": cluster.ID, - "TENANT": cluster.Tenant, - "TOKEN": token.Token, - } - - err = util.RetryOnError(3*time.Second, 2, "Error while creating istio-system namespace for Runtime Agent configuration: %s", func() (err apperrors.AppError) { - err = c.createNamespace(k8sClient.CoreV1().Namespaces(), "istio-system") - return - }) - - err = util.RetryOnError(3*time.Second, 2, "Error while creating namespace for Runtime Agent configuration: %s", func() (err apperrors.AppError) { - err = c.createNamespace(k8sClient.CoreV1().Namespaces(), namespace) - return - }) - - if err != nil { - return err.Append("error getting or creating namespace") - } - - secret := &core.Secret{ - ObjectMeta: meta.ObjectMeta{ - Name: AgentConfigurationSecretName, - Namespace: namespace, - }, - StringData: configurationData, - } - return c.upsertSecret(k8sClient.CoreV1().Secrets(namespace), secret) -} - -func (c *configurator) getConnectionToken(cluster model.Cluster) (graphql.OneTimeTokenForRuntimeExt, apperrors.AppError) { - var err apperrors.AppError - var token graphql.OneTimeTokenForRuntimeExt - - err = util.RetryOnError(10*time.Second, 3, "Error while getting one time token from Director: %s", func() (err apperrors.AppError) { - token, err = c.directorClient.GetConnectionToken(cluster.ID, cluster.Tenant) - return - }) - - if err != nil { - return graphql.OneTimeTokenForRuntimeExt{}, err - } - - return token, nil -} - -func (c *configurator) createNamespace(namespaceInterface v1.NamespaceInterface, namespace string) apperrors.AppError { - ns := &core.Namespace{ - ObjectMeta: meta.ObjectMeta{Name: namespace}, - } - _, err := namespaceInterface.Create(context.Background(), ns, meta.CreateOptions{}) - - if err != nil && !k8serrors.IsAlreadyExists(err) { - return util.K8SErrorToAppError(errors.Wrap(err, "Failed to create namespace")) - } - return nil -} - -func (c *configurator) upsertSecret(secretInterface v1.SecretInterface, secret *core.Secret) apperrors.AppError { - _, err := secretInterface.Create(context.Background(), secret, meta.CreateOptions{}) - if err == nil { - return nil - } - if !k8serrors.IsAlreadyExists(err) { - return util.K8SErrorToAppError(err).Append("error creating Secret on Runtime") - } - - _, err = secretInterface.Update(context.Background(), secret, meta.UpdateOptions{}) - if err != nil { - return util.K8SErrorToAppError(err).Append("error updating Secret on Runtime") - } - return nil -} diff --git a/components/provisioner/internal/runtime/mocks/Configurator.go b/components/provisioner/internal/runtime/mocks/Configurator.go deleted file mode 100644 index 578fc223d5..0000000000 --- a/components/provisioner/internal/runtime/mocks/Configurator.go +++ /dev/null @@ -1,45 +0,0 @@ -// Code generated by mockery v2.35.2. DO NOT EDIT. - -package mocks - -import ( - apperrors "github.com/kyma-project/control-plane/components/provisioner/internal/apperrors" - mock "github.com/stretchr/testify/mock" - - model "github.com/kyma-project/control-plane/components/provisioner/internal/model" -) - -// Configurator is an autogenerated mock type for the Configurator type -type Configurator struct { - mock.Mock -} - -// ConfigureRuntime provides a mock function with given fields: cluster, kubeconfigRaw -func (_m *Configurator) ConfigureRuntime(cluster model.Cluster, kubeconfigRaw string) apperrors.AppError { - ret := _m.Called(cluster, kubeconfigRaw) - - var r0 apperrors.AppError - if rf, ok := ret.Get(0).(func(model.Cluster, string) apperrors.AppError); ok { - r0 = rf(cluster, kubeconfigRaw) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(apperrors.AppError) - } - } - - return r0 -} - -// NewConfigurator creates a new instance of Configurator. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewConfigurator(t interface { - mock.TestingT - Cleanup(func()) -}) *Configurator { - mock := &Configurator{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} From 4a40e9727f9d534cc15596f87c3d8e6e4915556d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Przemys=C5=82aw=20Golicz?= Date: Fri, 15 Mar 2024 12:54:59 +0100 Subject: [PATCH 02/19] working on unit tests --- .../wait_for_cluster_deletion_test.go | 232 +----------------- .../stages/provisioning/connect_agent.go | 56 ----- .../stages/provisioning/connect_agent_test.go | 84 ------- .../wait_for_cluster_domain_test.go | 30 +-- 4 files changed, 13 insertions(+), 389 deletions(-) delete mode 100644 components/provisioner/internal/operations/stages/provisioning/connect_agent.go delete mode 100644 components/provisioner/internal/operations/stages/provisioning/connect_agent_test.go diff --git a/components/provisioner/internal/operations/stages/deprovisioning/wait_for_cluster_deletion_test.go b/components/provisioner/internal/operations/stages/deprovisioning/wait_for_cluster_deletion_test.go index 58700983e2..fc629b93d4 100644 --- a/components/provisioner/internal/operations/stages/deprovisioning/wait_for_cluster_deletion_test.go +++ b/components/provisioner/internal/operations/stages/deprovisioning/wait_for_cluster_deletion_test.go @@ -11,7 +11,6 @@ import ( "k8s.io/apimachinery/pkg/runtime/schema" gardener_types "github.com/gardener/gardener/pkg/apis/core/v1beta1" - directorMocks "github.com/kyma-project/control-plane/components/provisioner/internal/director/mocks" "github.com/kyma-project/control-plane/components/provisioner/internal/model" "github.com/kyma-project/control-plane/components/provisioner/internal/operations" gardener_mocks "github.com/kyma-project/control-plane/components/provisioner/internal/operations/stages/deprovisioning/mocks" @@ -26,7 +25,6 @@ import ( func TestWaitForClusterDeletion_Run(t *testing.T) { - type mockFunc func(gardenerClient *gardener_mocks.GardenerClient, dbSessionFactory *dbMocks.Factory, directorClient *directorMocks.DirectorClient) type mockFuncNoDirector func(gardenerClient *gardener_mocks.GardenerClient, dbSessionFactory *dbMocks.Factory) cluster := model.Cluster{ @@ -37,105 +35,6 @@ func TestWaitForClusterDeletion_Run(t *testing.T) { Tenant: "tenant", } - for _, testCase := range []struct { - description string - mockFunc mockFunc - expectedStage model.OperationStage - expectedDelay time.Duration - }{ - { - description: "should go to the next step when Shoot was deleted successfully and Runtime exists", - mockFunc: func(gardenerClient *gardener_mocks.GardenerClient, dbSessionFactory *dbMocks.Factory, directorClient *directorMocks.DirectorClient) { - gardenerClient.On("Get", context.Background(), clusterName, mock.Anything).Return(nil, k8serrors.NewNotFound(schema.GroupResource{}, "")) - dbSession := &dbMocks.WriteSessionWithinTransaction{} - dbSession.On("MarkClusterAsDeleted", runtimeID).Return(nil) - dbSessionFactory.On("NewSessionWithinTransaction").Return(dbSession, nil) - directorClient.On("RuntimeExists", runtimeID, tenant).Return(true, nil) - directorClient.On("DeleteRuntime", runtimeID, tenant).Return(nil) - dbSession.On("Commit").Return(nil) - dbSession.On("RollbackUnlessCommitted").Return() - }, - expectedStage: nextStageName, - expectedDelay: 0, - }, - { - description: "should go to the next step when Shoot was deleted successfully and Runtime not exists", - mockFunc: func(gardenerClient *gardener_mocks.GardenerClient, dbSessionFactory *dbMocks.Factory, directorClient *directorMocks.DirectorClient) { - gardenerClient.On("Get", context.Background(), clusterName, mock.Anything).Return(nil, k8serrors.NewNotFound(schema.GroupResource{}, "")) - dbSession := &dbMocks.WriteSessionWithinTransaction{} - dbSession.On("MarkClusterAsDeleted", runtimeID).Return(nil) - dbSessionFactory.On("NewSessionWithinTransaction").Return(dbSession, nil) - directorClient.On("RuntimeExists", runtimeID, tenant).Return(false, nil) - dbSession.On("Commit").Return(nil) - dbSession.On("RollbackUnlessCommitted").Return() - }, - expectedStage: nextStageName, - expectedDelay: 0, - }, - { - description: "should retry on error on RuntimeExists call and go to the next step when Shoot was deleted successfully", - mockFunc: func(gardenerClient *gardener_mocks.GardenerClient, dbSessionFactory *dbMocks.Factory, directorClient *directorMocks.DirectorClient) { - gardenerClient.On("Get", context.Background(), clusterName, mock.Anything).Return(nil, k8serrors.NewNotFound(schema.GroupResource{}, "")) - dbSession := &dbMocks.WriteSessionWithinTransaction{} - dbSession.On("MarkClusterAsDeleted", runtimeID).Return(nil) - dbSessionFactory.On("NewSessionWithinTransaction").Return(dbSession, nil) - directorClient.On("RuntimeExists", runtimeID, tenant).Once().Return(false, apperrors.Internal("exists err")) - directorClient.On("RuntimeExists", runtimeID, tenant).Once().Return(true, nil) - directorClient.On("DeleteRuntime", runtimeID, tenant).Return(nil) - dbSession.On("Commit").Return(nil) - dbSession.On("RollbackUnlessCommitted").Return() - }, - expectedStage: nextStageName, - expectedDelay: 0, - }, - { - description: "should retry on error on DeleteRuntime call and go to the next step when Shoot was deleted successfully", - mockFunc: func(gardenerClient *gardener_mocks.GardenerClient, dbSessionFactory *dbMocks.Factory, directorClient *directorMocks.DirectorClient) { - gardenerClient.On("Get", context.Background(), clusterName, mock.Anything).Return(nil, k8serrors.NewNotFound(schema.GroupResource{}, "")) - dbSession := &dbMocks.WriteSessionWithinTransaction{} - dbSession.On("MarkClusterAsDeleted", runtimeID).Return(nil) - dbSessionFactory.On("NewSessionWithinTransaction").Return(dbSession, nil) - directorClient.On("RuntimeExists", runtimeID, tenant).Return(true, nil) - directorClient.On("DeleteRuntime", runtimeID, tenant).Once().Return(apperrors.Internal("delete error")) - directorClient.On("DeleteRuntime", runtimeID, tenant).Once().Return(nil) - dbSession.On("Commit").Return(nil) - dbSession.On("RollbackUnlessCommitted").Return() - }, - expectedStage: nextStageName, - expectedDelay: 0, - }, - { - description: "should continue waiting if shoot not deleted", - mockFunc: func(gardenerClient *gardener_mocks.GardenerClient, dbSessionFactory *dbMocks.Factory, directorClient *directorMocks.DirectorClient) { - gardenerClient.On("Get", context.Background(), clusterName, mock.Anything).Return(&gardener_types.Shoot{}, nil) - }, - expectedStage: model.WaitForClusterDeletion, - expectedDelay: 20 * time.Second, - }, - } { - t.Run(testCase.description, func(t *testing.T) { - // given - gardenerClient := &gardener_mocks.GardenerClient{} - dbSessionFactory := &dbMocks.Factory{} - directorClient := &directorMocks.DirectorClient{} - - testCase.mockFunc(gardenerClient, dbSessionFactory, directorClient) - - waitForClusterDeletionStep := NewWaitForClusterDeletionStep(gardenerClient, dbSessionFactory, directorClient, nextStageName, 10*time.Minute) - - // when - result, err := waitForClusterDeletionStep.Run(cluster, model.Operation{}, logrus.New()) - - // then - require.NoError(t, err) - assert.Equal(t, testCase.expectedStage, result.Stage) - assert.Equal(t, testCase.expectedDelay, result.Delay) - gardenerClient.AssertExpectations(t) - directorClient.AssertExpectations(t) - }) - } - - // tests for disabled Director integration for _, testCase := range []struct { description string mockFunc mockFuncNoDirector @@ -172,7 +71,7 @@ func TestWaitForClusterDeletion_Run(t *testing.T) { testCase.mockFunc(gardenerClient, dbSessionFactory) - waitForClusterDeletionStep := NewWaitForClusterDeletionStep(gardenerClient, dbSessionFactory, nil, nextStageName, 10*time.Minute) + waitForClusterDeletionStep := NewWaitForClusterDeletionStep(gardenerClient, dbSessionFactory, nextStageName, 10*time.Minute) // when result, err := waitForClusterDeletionStep.Run(cluster, model.Operation{}, logrus.New()) @@ -184,133 +83,6 @@ func TestWaitForClusterDeletion_Run(t *testing.T) { }) } - for _, testCase := range []struct { - description string - mockFunc mockFunc - cluster model.Cluster - unrecoverableError bool - errComponent apperrors.ErrComponent - errReason apperrors.ErrReason - errMsg string - }{ - { - description: "should return error when failed to get shoot", - mockFunc: func(gardenerClient *gardener_mocks.GardenerClient, dbSessionFactory *dbMocks.Factory, directorClient *directorMocks.DirectorClient) { - gardenerClient.On("Get", context.Background(), clusterName, mock.Anything).Return(nil, errors.New("some error")) - }, - cluster: cluster, - unrecoverableError: false, - errComponent: apperrors.ErrGardenerClient, - errReason: "", - errMsg: "some error", - }, - { - description: "should return error when failed to start database transaction", - mockFunc: func(gardenerClient *gardener_mocks.GardenerClient, dbSessionFactory *dbMocks.Factory, directorClient *directorMocks.DirectorClient) { - gardenerClient.On("Get", context.Background(), clusterName, mock.Anything).Return(nil, k8serrors.NewNotFound(schema.GroupResource{}, "")) - dbSessionFactory.On("NewSessionWithinTransaction").Return(nil, dberrors.Internal("some error")) - }, - cluster: cluster, - unrecoverableError: false, - errComponent: apperrors.ErrDB, - errReason: dberrors.ErrDBInternal, - errMsg: "error starting db session with transaction: some error", - }, - { - description: "should return error when failed to mark cluster as deleted", - mockFunc: func(gardenerClient *gardener_mocks.GardenerClient, dbSessionFactory *dbMocks.Factory, directorClient *directorMocks.DirectorClient) { - gardenerClient.On("Get", context.Background(), clusterName, mock.Anything).Return(nil, k8serrors.NewNotFound(schema.GroupResource{}, "")) - dbSession := &dbMocks.WriteSessionWithinTransaction{} - dbSession.On("MarkClusterAsDeleted", runtimeID).Return(dberrors.NotFound("some error")) - dbSessionFactory.On("NewSessionWithinTransaction").Return(dbSession, nil) - dbSession.On("RollbackUnlessCommitted").Return() - }, - cluster: cluster, - unrecoverableError: false, - errComponent: apperrors.ErrDB, - errReason: dberrors.ErrDBNotFound, - errMsg: "error marking cluster for deletion: some error", - }, - { - description: "should return error when failed to check if Runtime exists", - mockFunc: func(gardenerClient *gardener_mocks.GardenerClient, dbSessionFactory *dbMocks.Factory, directorClient *directorMocks.DirectorClient) { - gardenerClient.On("Get", context.Background(), clusterName, mock.Anything).Return(nil, k8serrors.NewNotFound(schema.GroupResource{}, "")) - dbSession := &dbMocks.WriteSessionWithinTransaction{} - dbSession.On("MarkClusterAsDeleted", runtimeID).Return(nil) - dbSessionFactory.On("NewSessionWithinTransaction").Return(dbSession, nil) - dbSession.On("RollbackUnlessCommitted").Return() - directorClient.On("RuntimeExists", runtimeID, tenant).Return(false, apperrors.External("some error").SetComponent(apperrors.ErrMpsOAuth2)) - }, - cluster: cluster, - unrecoverableError: false, - errComponent: apperrors.ErrMpsOAuth2, - errReason: "", - errMsg: "error checking Runtime exists in Director: some error", - }, - { - description: "should return error when failed to delete Runtime", - mockFunc: func(gardenerClient *gardener_mocks.GardenerClient, dbSessionFactory *dbMocks.Factory, directorClient *directorMocks.DirectorClient) { - gardenerClient.On("Get", context.Background(), clusterName, mock.Anything).Return(nil, k8serrors.NewNotFound(schema.GroupResource{}, "")) - dbSession := &dbMocks.WriteSessionWithinTransaction{} - dbSession.On("MarkClusterAsDeleted", runtimeID).Return(nil) - dbSessionFactory.On("NewSessionWithinTransaction").Return(dbSession, nil) - dbSession.On("RollbackUnlessCommitted").Return() - directorClient.On("RuntimeExists", runtimeID, tenant).Return(true, nil) - directorClient.On("DeleteRuntime", runtimeID, tenant).Return(apperrors.BadGateway("some error").SetComponent(apperrors.ErrCompassDirector).SetReason(apperrors.ErrReason("Invalid data")).Append("Failed to request")) - }, - cluster: cluster, - unrecoverableError: false, - errComponent: apperrors.ErrCompassDirector, - errReason: apperrors.ErrReason("Invalid data"), - errMsg: "error deleting Runtime form Director: Failed to request, some error", - }, - { - description: "should return error when failed to commit database transaction", - mockFunc: func(gardenerClient *gardener_mocks.GardenerClient, dbSessionFactory *dbMocks.Factory, directorClient *directorMocks.DirectorClient) { - gardenerClient.On("Get", context.Background(), clusterName, mock.Anything).Return(nil, k8serrors.NewNotFound(schema.GroupResource{}, "")) - dbSession := &dbMocks.WriteSessionWithinTransaction{} - dbSession.On("MarkClusterAsDeleted", mock.AnythingOfType("string")).Return(nil) - dbSessionFactory.On("NewSessionWithinTransaction").Return(dbSession, nil) - directorClient.On("RuntimeExists", runtimeID, tenant).Return(true, nil) - directorClient.On("DeleteRuntime", runtimeID, tenant).Return(nil) - dbSession.On("Commit").Return(dberrors.Internal("some error")) - dbSession.On("RollbackUnlessCommitted").Return() - }, - cluster: cluster, - unrecoverableError: false, - errComponent: apperrors.ErrDB, - errReason: dberrors.ErrDBInternal, - errMsg: "error commiting transaction: some error", - }, - } { - t.Run(testCase.description, func(t *testing.T) { - // given - gardenerClient := &gardener_mocks.GardenerClient{} - dbSessionFactory := &dbMocks.Factory{} - directorClient := &directorMocks.DirectorClient{} - - testCase.mockFunc(gardenerClient, dbSessionFactory, directorClient) - - waitForClusterDeletionStep := NewWaitForClusterDeletionStep(gardenerClient, dbSessionFactory, directorClient, nextStageName, 10*time.Minute) - - // when - _, err := waitForClusterDeletionStep.Run(testCase.cluster, model.Operation{}, logrus.New()) - appErr := operations.ConvertToAppError(err) - - // then - require.Error(t, err) - nonRecoverable := operations.NonRecoverableError{} - require.Equal(t, testCase.unrecoverableError, errors.As(err, &nonRecoverable)) - assert.Equal(t, testCase.errComponent, appErr.Component()) - assert.Equal(t, testCase.errReason, appErr.Reason()) - assert.Equal(t, testCase.errMsg, err.Error()) - gardenerClient.AssertExpectations(t) - dbSessionFactory.AssertExpectations(t) - directorClient.AssertExpectations(t) - }) - } - - // tests for disabled Director integration for _, testCase := range []struct { description string mockFunc mockFuncNoDirector @@ -383,7 +155,7 @@ func TestWaitForClusterDeletion_Run(t *testing.T) { testCase.mockFunc(gardenerClient, dbSessionFactory) - waitForClusterDeletionStep := NewWaitForClusterDeletionStep(gardenerClient, dbSessionFactory, nil, nextStageName, 10*time.Minute) + waitForClusterDeletionStep := NewWaitForClusterDeletionStep(gardenerClient, dbSessionFactory, nextStageName, 10*time.Minute) // when _, err := waitForClusterDeletionStep.Run(testCase.cluster, model.Operation{}, logrus.New()) diff --git a/components/provisioner/internal/operations/stages/provisioning/connect_agent.go b/components/provisioner/internal/operations/stages/provisioning/connect_agent.go deleted file mode 100644 index 6e2be59550..0000000000 --- a/components/provisioner/internal/operations/stages/provisioning/connect_agent.go +++ /dev/null @@ -1,56 +0,0 @@ -package provisioning - -import ( - "time" - - "github.com/kyma-project/control-plane/components/provisioner/internal/model" - "github.com/kyma-project/control-plane/components/provisioner/internal/operations" - "github.com/kyma-project/control-plane/components/provisioner/internal/runtime" - "github.com/sirupsen/logrus" -) - -type ConnectAgentStep struct { - runtimeConfigurator runtime.Configurator - dynamicKubeconfigProvider DynamicKubeconfigProvider - nextStage model.OperationStage - timeLimit time.Duration -} - -func NewConnectAgentStep( - configurator runtime.Configurator, - dynamicKubeconfigProvider DynamicKubeconfigProvider, - nextStage model.OperationStage, - timeLimit time.Duration) *ConnectAgentStep { - return &ConnectAgentStep{ - runtimeConfigurator: configurator, - dynamicKubeconfigProvider: dynamicKubeconfigProvider, - nextStage: nextStage, - timeLimit: timeLimit, - } -} - -func (s *ConnectAgentStep) Name() model.OperationStage { - return model.ConnectRuntimeAgent -} - -func (s *ConnectAgentStep) TimeLimit() time.Duration { - return s.timeLimit -} - -func (s *ConnectAgentStep) Run(cluster model.Cluster, _ model.Operation, _ logrus.FieldLogger) (operations.StageResult, error) { - - var kubeconfig []byte - { - var err error - kubeconfig, err = s.dynamicKubeconfigProvider.FetchFromRequest(cluster.ClusterConfig.Name) - if err != nil { - return operations.StageResult{Stage: s.Name(), Delay: 20 * time.Second}, nil - } - } - err := s.runtimeConfigurator.ConfigureRuntime(cluster, string(kubeconfig)) - if err != nil { - return operations.StageResult{}, err.Append("failed to configure Runtime Agent") - } - - return operations.StageResult{Stage: s.nextStage, Delay: 0}, nil -} diff --git a/components/provisioner/internal/operations/stages/provisioning/connect_agent_test.go b/components/provisioner/internal/operations/stages/provisioning/connect_agent_test.go deleted file mode 100644 index 151ae1cb89..0000000000 --- a/components/provisioner/internal/operations/stages/provisioning/connect_agent_test.go +++ /dev/null @@ -1,84 +0,0 @@ -package provisioning - -import ( - "testing" - "time" - - "github.com/pkg/errors" - - provisioning_mocks "github.com/kyma-project/control-plane/components/provisioner/internal/operations/stages/provisioning/mocks" - - "github.com/kyma-project/control-plane/components/provisioner/internal/apperrors" - - "github.com/kyma-project/control-plane/components/provisioner/internal/model" - "github.com/kyma-project/control-plane/components/provisioner/internal/runtime/mocks" - "github.com/kyma-project/control-plane/components/provisioner/internal/util" - "github.com/sirupsen/logrus" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -const ( - nextStageName model.OperationStage = "NextStage" -) - -func TestConnectAgentStep_Run(t *testing.T) { - - cluster := model.Cluster{ - Kubeconfig: util.PtrTo("kubeconfig"), - ClusterConfig: model.GardenerConfig{ - Name: "shoot", - }, - } - dynamicKubeconfigProvider := &provisioning_mocks.DynamicKubeconfigProvider{} - dynamicKubeconfigProvider.On("FetchFromRequest", "shoot").Return([]byte("dynamic_kubeconfig"), nil) - - t.Run("should return next step when finished", func(t *testing.T) { - // given - configurator := &mocks.Configurator{} - configurator.On("ConfigureRuntime", cluster, dynamicKubeconfig).Return(nil) - - stage := NewConnectAgentStep(configurator, dynamicKubeconfigProvider, nextStageName, time.Minute) - - // when - result, err := stage.Run(cluster, model.Operation{}, &logrus.Entry{}) - - // then - require.NoError(t, err) - assert.Equal(t, nextStageName, result.Stage) - assert.Equal(t, time.Duration(0), result.Delay) - }) - - t.Run("should attempt retry when failed to get dynamic kubeconfig", func(t *testing.T) { - // given - dynamicKubeconfigProvider := &provisioning_mocks.DynamicKubeconfigProvider{} - dynamicKubeconfigProvider.On("FetchFromRequest", "shoot").Return(nil, errors.New("some error")) - - configurator := &mocks.Configurator{} - - stage := NewConnectAgentStep(configurator, dynamicKubeconfigProvider, nextStageName, time.Minute) - - // when - result, err := stage.Run(cluster, model.Operation{}, &logrus.Entry{}) - - // then - require.NoError(t, err) - assert.Equal(t, model.ConnectRuntimeAgent, result.Stage) - assert.Equal(t, 20*time.Second, result.Delay) - }) - - t.Run("should return error when failed to configure cluster", func(t *testing.T) { - // given - configurator := &mocks.Configurator{} - configurator.On("ConfigureRuntime", cluster, dynamicKubeconfig).Return(apperrors.Internal("error")) - - stage := NewConnectAgentStep(configurator, dynamicKubeconfigProvider, nextStageName, time.Minute) - - // when - _, err := stage.Run(cluster, model.Operation{}, &logrus.Entry{}) - - // then - require.Error(t, err) - }) - -} diff --git a/components/provisioner/internal/operations/stages/provisioning/wait_for_cluster_domain_test.go b/components/provisioner/internal/operations/stages/provisioning/wait_for_cluster_domain_test.go index 62f06ae2fc..045cdec492 100644 --- a/components/provisioner/internal/operations/stages/provisioning/wait_for_cluster_domain_test.go +++ b/components/provisioner/internal/operations/stages/provisioning/wait_for_cluster_domain_test.go @@ -3,6 +3,7 @@ package provisioning import ( "context" "errors" + directormock "github.com/kyma-project/control-plane/components/provisioner/internal/director/mocks" "testing" "time" @@ -13,7 +14,6 @@ import ( gardener_types "github.com/gardener/gardener/pkg/apis/core/v1beta1" "github.com/kyma-incubator/compass/components/director/pkg/graphql" - directormock "github.com/kyma-project/control-plane/components/provisioner/internal/director/mocks" "github.com/kyma-project/control-plane/components/provisioner/internal/model" gardenerMocks "github.com/kyma-project/control-plane/components/provisioner/internal/operations/stages/provisioning/mocks" "github.com/kyma-project/control-plane/components/provisioner/internal/util" @@ -63,13 +63,13 @@ func TestWaitForClusterDomain_Run(t *testing.T) { for _, testCase := range []struct { description string - mockFunc func(gardenerClient *gardenerMocks.GardenerClient, directorClient *directormock.DirectorClient) + mockFunc func(gardenerClient *gardenerMocks.GardenerClient) expectedStage model.OperationStage expectedDelay time.Duration }{ { description: "should continue waiting if domain name is not set", - mockFunc: func(gardenerClient *gardenerMocks.GardenerClient, _ *directormock.DirectorClient) { + mockFunc: func(gardenerClient *gardenerMocks.GardenerClient) { gardenerClient.On("Get", context.Background(), clusterName, mock.Anything).Return(&gardener_types.Shoot{}, nil) }, expectedStage: model.WaitingForClusterDomain, @@ -77,44 +77,36 @@ func TestWaitForClusterDomain_Run(t *testing.T) { }, { description: "should go to the next stage if domain name is available", - mockFunc: func(gardenerClient *gardenerMocks.GardenerClient, directorClient *directormock.DirectorClient) { + mockFunc: func(gardenerClient *gardenerMocks.GardenerClient) { gardenerClient.On("Get", context.Background(), clusterName, mock.Anything).Return(fixShootWithDomainSet(clusterName, domain), nil) runtime := fixRuntime(runtimeID, clusterName, map[string]interface{}{ "label": "value", }) - directorClient.On("GetRuntime", runtimeID, tenant).Return(runtime, nil) - directorClient.On("UpdateRuntime", runtimeID, mock.Anything, tenant).Return(nil) }, expectedStage: nextStageName, expectedDelay: 0, }, { description: "should retry on failed GetRuntime call and go to the next stage if domain name is available", - mockFunc: func(gardenerClient *gardenerMocks.GardenerClient, directorClient *directormock.DirectorClient) { + mockFunc: func(gardenerClient *gardenerMocks.GardenerClient) { gardenerClient.On("Get", context.Background(), clusterName, mock.Anything).Return(fixShootWithDomainSet(clusterName, domain), nil) runtime := fixRuntime(runtimeID, clusterName, map[string]interface{}{ "label": "value", }) - directorClient.On("GetRuntime", runtimeID, tenant).Once().Return(graphql.RuntimeExt{}, apperrors.Internal("get runtime error")) - directorClient.On("GetRuntime", runtimeID, tenant).Once().Return(runtime, nil) - directorClient.On("UpdateRuntime", runtimeID, mock.Anything, tenant).Return(nil) }, expectedStage: nextStageName, expectedDelay: 0, }, { description: "should retry on failed UpdateRuntime call and go to the next stage if domain name is available", - mockFunc: func(gardenerClient *gardenerMocks.GardenerClient, directorClient *directormock.DirectorClient) { + mockFunc: func(gardenerClient *gardenerMocks.GardenerClient) { gardenerClient.On("Get", context.Background(), clusterName, mock.Anything).Return(fixShootWithDomainSet(clusterName, domain), nil) runtime := fixRuntime(runtimeID, clusterName, map[string]interface{}{ "label": "value", }) - directorClient.On("GetRuntime", runtimeID, tenant).Return(runtime, nil) - directorClient.On("UpdateRuntime", runtimeID, mock.Anything, tenant).Once().Return(apperrors.Internal("update runtime error")) - directorClient.On("UpdateRuntime", runtimeID, mock.Anything, tenant).Once().Return(nil) }, expectedStage: nextStageName, expectedDelay: 0, @@ -125,9 +117,9 @@ func TestWaitForClusterDomain_Run(t *testing.T) { gardenerClient := &gardenerMocks.GardenerClient{} directorClient := &directormock.DirectorClient{} - testCase.mockFunc(gardenerClient, directorClient) + testCase.mockFunc(gardenerClient) - waitForClusterDomainStep := NewWaitForClusterDomainStep(gardenerClient, directorClient, nextStageName, 10*time.Minute) + waitForClusterDomainStep := NewWaitForClusterDomainStep(gardenerClient, nextStageName, 10*time.Minute) // when result, err := waitForClusterDomainStep.Run(cluster, model.Operation{}, logrus.New()) @@ -171,7 +163,7 @@ func TestWaitForClusterDomain_Run(t *testing.T) { testCase.mockFunc(gardenerClient) - waitForClusterDomainStep := NewWaitForClusterDomainStep(gardenerClient, nil, nextStageName, 10*time.Minute) + waitForClusterDomainStep := NewWaitForClusterDomainStep(gardenerClient, nextStageName, 10*time.Minute) // when result, err := waitForClusterDomainStep.Run(cluster, model.Operation{}, logrus.New()) @@ -230,7 +222,7 @@ func TestWaitForClusterDomain_Run(t *testing.T) { testCase.mockFunc(gardenerClient, directorClient) - waitForClusterDomainStep := NewWaitForClusterDomainStep(gardenerClient, directorClient, nextStageName, 10*time.Minute) + waitForClusterDomainStep := NewWaitForClusterDomainStep(gardenerClient, nextStageName, 10*time.Minute) // when _, err := waitForClusterDomainStep.Run(testCase.cluster, model.Operation{}, logrus.New()) @@ -267,7 +259,7 @@ func TestWaitForClusterDomain_Run(t *testing.T) { testCase.mockFunc(gardenerClient) - waitForClusterDomainStep := NewWaitForClusterDomainStep(gardenerClient, nil, nextStageName, 10*time.Minute) + waitForClusterDomainStep := NewWaitForClusterDomainStep(gardenerClient, nextStageName, 10*time.Minute) // when _, err := waitForClusterDomainStep.Run(testCase.cluster, model.Operation{}, logrus.New()) From 0242f5c469f3ee258f6e6c35b67a8bd681787994 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Przemys=C5=82aw=20Golicz?= Date: Fri, 15 Mar 2024 13:07:17 +0100 Subject: [PATCH 03/19] Update unit test for wait for cluster domain step --- .../wait_for_cluster_domain_test.go | 152 +----------------- 1 file changed, 3 insertions(+), 149 deletions(-) diff --git a/components/provisioner/internal/operations/stages/provisioning/wait_for_cluster_domain_test.go b/components/provisioner/internal/operations/stages/provisioning/wait_for_cluster_domain_test.go index 045cdec492..c2c8b27bd7 100644 --- a/components/provisioner/internal/operations/stages/provisioning/wait_for_cluster_domain_test.go +++ b/components/provisioner/internal/operations/stages/provisioning/wait_for_cluster_domain_test.go @@ -3,7 +3,6 @@ package provisioning import ( "context" "errors" - directormock "github.com/kyma-project/control-plane/components/provisioner/internal/director/mocks" "testing" "time" @@ -13,7 +12,6 @@ import ( "github.com/stretchr/testify/mock" gardener_types "github.com/gardener/gardener/pkg/apis/core/v1beta1" - "github.com/kyma-incubator/compass/components/director/pkg/graphql" "github.com/kyma-project/control-plane/components/provisioner/internal/model" gardenerMocks "github.com/kyma-project/control-plane/components/provisioner/internal/operations/stages/provisioning/mocks" "github.com/kyma-project/control-plane/components/provisioner/internal/util" @@ -24,7 +22,8 @@ import ( ) const ( - kubeconfig = `apiVersion: v1 + nextStageName model.OperationStage = "NextStage" + kubeconfig = `apiVersion: v1 clusters: - cluster: server: https://192.168.64.4:8443 @@ -68,7 +67,7 @@ func TestWaitForClusterDomain_Run(t *testing.T) { expectedDelay time.Duration }{ { - description: "should continue waiting if domain name is not set", + description: "should continue waiting if domain name is not set yet", mockFunc: func(gardenerClient *gardenerMocks.GardenerClient) { gardenerClient.On("Get", context.Background(), clusterName, mock.Anything).Return(&gardener_types.Shoot{}, nil) }, @@ -77,79 +76,6 @@ func TestWaitForClusterDomain_Run(t *testing.T) { }, { description: "should go to the next stage if domain name is available", - mockFunc: func(gardenerClient *gardenerMocks.GardenerClient) { - gardenerClient.On("Get", context.Background(), clusterName, mock.Anything).Return(fixShootWithDomainSet(clusterName, domain), nil) - - runtime := fixRuntime(runtimeID, clusterName, map[string]interface{}{ - "label": "value", - }) - }, - expectedStage: nextStageName, - expectedDelay: 0, - }, - { - description: "should retry on failed GetRuntime call and go to the next stage if domain name is available", - mockFunc: func(gardenerClient *gardenerMocks.GardenerClient) { - gardenerClient.On("Get", context.Background(), clusterName, mock.Anything).Return(fixShootWithDomainSet(clusterName, domain), nil) - - runtime := fixRuntime(runtimeID, clusterName, map[string]interface{}{ - "label": "value", - }) - }, - expectedStage: nextStageName, - expectedDelay: 0, - }, - { - description: "should retry on failed UpdateRuntime call and go to the next stage if domain name is available", - mockFunc: func(gardenerClient *gardenerMocks.GardenerClient) { - gardenerClient.On("Get", context.Background(), clusterName, mock.Anything).Return(fixShootWithDomainSet(clusterName, domain), nil) - - runtime := fixRuntime(runtimeID, clusterName, map[string]interface{}{ - "label": "value", - }) - }, - expectedStage: nextStageName, - expectedDelay: 0, - }, - } { - t.Run(testCase.description, func(t *testing.T) { - // given - gardenerClient := &gardenerMocks.GardenerClient{} - directorClient := &directormock.DirectorClient{} - - testCase.mockFunc(gardenerClient) - - waitForClusterDomainStep := NewWaitForClusterDomainStep(gardenerClient, nextStageName, 10*time.Minute) - - // when - result, err := waitForClusterDomainStep.Run(cluster, model.Operation{}, logrus.New()) - - // then - require.NoError(t, err) - assert.Equal(t, testCase.expectedStage, result.Stage) - assert.Equal(t, testCase.expectedDelay, result.Delay) - gardenerClient.AssertExpectations(t) - directorClient.AssertExpectations(t) - }) - } - - // tests for disabled Director integration - for _, testCase := range []struct { - description string - mockFunc func(gardenerClient *gardenerMocks.GardenerClient) - expectedStage model.OperationStage - expectedDelay time.Duration - }{ - { - description: "should continue waiting if domain name is not set when Director integration is disabled", - mockFunc: func(gardenerClient *gardenerMocks.GardenerClient) { - gardenerClient.On("Get", context.Background(), clusterName, mock.Anything).Return(&gardener_types.Shoot{}, nil) - }, - expectedStage: model.WaitingForClusterDomain, - expectedDelay: 5 * time.Second, - }, - { - description: "should go to the next stage if domain name is available and Director integration is disabled", mockFunc: func(gardenerClient *gardenerMocks.GardenerClient) { gardenerClient.On("Get", context.Background(), clusterName, mock.Anything).Return(fixShootWithDomainSet(clusterName, domain), nil) }, @@ -176,68 +102,6 @@ func TestWaitForClusterDomain_Run(t *testing.T) { }) } - for _, testCase := range []struct { - description string - mockFunc func(gardenerClient *gardenerMocks.GardenerClient, directorClient *directormock.DirectorClient) - cluster model.Cluster - unrecoverableError bool - }{ - { - description: "should return error if failed to read Shoot", - mockFunc: func(gardenerClient *gardenerMocks.GardenerClient, _ *directormock.DirectorClient) { - gardenerClient.On("Get", context.Background(), clusterName, mock.Anything).Return(nil, apperrors.Internal("some error")) - }, - unrecoverableError: false, - cluster: cluster, - }, - { - description: "should return error if failed to get Runtime from Director", - mockFunc: func(gardenerClient *gardenerMocks.GardenerClient, directorClient *directormock.DirectorClient) { - gardenerClient.On("Get", context.Background(), clusterName, mock.Anything).Return(fixShootWithDomainSet(clusterName, domain), nil) - directorClient.On("GetRuntime", runtimeID, tenant).Return(graphql.RuntimeExt{}, apperrors.Internal("some error")) - - }, - unrecoverableError: false, - cluster: cluster, - }, - { - description: "should return error if failed to update Runtime in Director", - mockFunc: func(gardenerClient *gardenerMocks.GardenerClient, directorClient *directormock.DirectorClient) { - gardenerClient.On("Get", context.Background(), clusterName, mock.Anything).Return(fixShootWithDomainSet(clusterName, domain), nil) - - runtime := fixRuntime(runtimeID, clusterName, map[string]interface{}{ - "label": "value", - }) - directorClient.On("GetRuntime", runtimeID, tenant).Return(runtime, nil) - directorClient.On("UpdateRuntime", runtimeID, mock.Anything, tenant).Return(apperrors.Internal("some error")) - }, - unrecoverableError: false, - cluster: cluster, - }, - } { - t.Run(testCase.description, func(t *testing.T) { - // given - gardenerClient := &gardenerMocks.GardenerClient{} - directorClient := &directormock.DirectorClient{} - - testCase.mockFunc(gardenerClient, directorClient) - - waitForClusterDomainStep := NewWaitForClusterDomainStep(gardenerClient, nextStageName, 10*time.Minute) - - // when - _, err := waitForClusterDomainStep.Run(testCase.cluster, model.Operation{}, logrus.New()) - - // then - require.Error(t, err) - nonRecoverable := operations.NonRecoverableError{} - require.Equal(t, testCase.unrecoverableError, errors.As(err, &nonRecoverable)) - - gardenerClient.AssertExpectations(t) - directorClient.AssertExpectations(t) - }) - } - - // tests for disabled Director integration for _, testCase := range []struct { description string mockFunc func(gardenerClient *gardenerMocks.GardenerClient) @@ -286,13 +150,3 @@ func fixShootWithDomainSet(name, domain string) *gardener_types.Shoot { }, } } - -func fixRuntime(runtimeId, name string, labels map[string]interface{}) graphql.RuntimeExt { - return graphql.RuntimeExt{ - Runtime: graphql.Runtime{ - ID: runtimeId, - Name: name, - }, - Labels: labels, - } -} From 45024d8fb21d5da4e6353bcbba353a9d999d13db Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Przemys=C5=82aw=20Golicz?= Date: Fri, 15 Mar 2024 13:38:02 +0100 Subject: [PATCH 04/19] working on unit tests for delete cluster step --- .../operations/stages/deprovisioning/delete_cluster_test.go | 3 --- 1 file changed, 3 deletions(-) diff --git a/components/provisioner/internal/operations/stages/deprovisioning/delete_cluster_test.go b/components/provisioner/internal/operations/stages/deprovisioning/delete_cluster_test.go index 5ba893725e..5fbe04f3fc 100644 --- a/components/provisioner/internal/operations/stages/deprovisioning/delete_cluster_test.go +++ b/components/provisioner/internal/operations/stages/deprovisioning/delete_cluster_test.go @@ -9,7 +9,6 @@ import ( "k8s.io/apimachinery/pkg/runtime/schema" "github.com/kyma-project/control-plane/components/provisioner/internal/apperrors" - directorMocks "github.com/kyma-project/control-plane/components/provisioner/internal/director/mocks" "github.com/kyma-project/control-plane/components/provisioner/internal/model" "github.com/kyma-project/control-plane/components/provisioner/internal/operations" gardener_mocks "github.com/kyma-project/control-plane/components/provisioner/internal/operations/stages/deprovisioning/mocks" @@ -105,7 +104,6 @@ func TestDeprovisionCluster_Run(t *testing.T) { // given gardenerClient := &gardener_mocks.GardenerClient{} dbSessionFactory := &dbMocks.Factory{} - directorClient := &directorMocks.DirectorClient{} testCase.mockFunc(gardenerClient) @@ -124,7 +122,6 @@ func TestDeprovisionCluster_Run(t *testing.T) { assert.Error(t, err, testCase.errMsg) gardenerClient.AssertExpectations(t) dbSessionFactory.AssertExpectations(t) - directorClient.AssertExpectations(t) }) } } From df17d12bec1fd5f8ad60d0238c69253f544d102b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Przemys=C5=82aw=20Golicz?= Date: Mon, 18 Mar 2024 15:34:53 +0100 Subject: [PATCH 05/19] continue working on full removing compass integration --- components/provisioner/cmd/init.go | 34 ---- components/provisioner/cmd/main.go | 19 +- .../internal/gardener/provisioner.go | 2 - .../internal/operations/executor.go | 20 +-- .../internal/operations/executor_test.go | 165 +----------------- .../internal/provisioning/service.go | 4 - .../internal/provisioning/service_test.go | 93 ++-------- 7 files changed, 24 insertions(+), 313 deletions(-) diff --git a/components/provisioner/cmd/init.go b/components/provisioner/cmd/init.go index d201aabba1..355b777b97 100644 --- a/components/provisioner/cmd/init.go +++ b/components/provisioner/cmd/init.go @@ -7,19 +7,13 @@ import ( "os" "time" - "k8s.io/apimachinery/pkg/util/yaml" - "github.com/kyma-project/control-plane/components/provisioner/internal/operations/queue" "github.com/kyma-project/control-plane/components/provisioner/internal/provisioning/persistence/dbsession" - "github.com/kyma-project/control-plane/components/provisioner/internal/director" "github.com/kyma-project/control-plane/components/provisioner/internal/gardener" - "github.com/kyma-project/control-plane/components/provisioner/internal/graphql" - "github.com/kyma-project/control-plane/components/provisioner/internal/oauth" "github.com/kyma-project/control-plane/components/provisioner/internal/provisioning" "github.com/kyma-project/control-plane/components/provisioner/internal/uuid" - "github.com/pkg/errors" ctrl "sigs.k8s.io/controller-runtime" restclient "k8s.io/client-go/rest" @@ -38,7 +32,6 @@ func newProvisioningService( gardenerProject string, provisioner provisioning.Provisioner, dbsFactory dbsession.Factory, - directorService director.DirectorClient, shootProvider gardener.ShootProvider, provisioningQueue queue.OperationQueue, deprovisioningQueue queue.OperationQueue, @@ -54,7 +47,6 @@ func newProvisioningService( return provisioning.NewProvisioningService( inputConverter, graphQLConverter, - directorService, dbsFactory, provisioner, uuidGenerator, @@ -65,32 +57,6 @@ func newProvisioningService( dynamicKubeconfigProvider) } -func newDirectorClient(config config) (director.DirectorClient, error) { - file, err := os.ReadFile(config.DirectorOAuthPath) - if err != nil { - return nil, errors.Wrap(err, "Failed to open director config") - } - - cfg := DirectorOAuth{} - err = yaml.Unmarshal(file, &cfg) - if err != nil { - return nil, errors.Wrap(err, "Failed to unmarshal director config") - } - - gqlClient := graphql.NewGraphQLClient(config.DirectorURL, true, config.SkipDirectorCertVerification) - oauthClient := oauth.NewOauthClient(newHTTPClient(config.SkipDirectorCertVerification), cfg.Data.ClientID, cfg.Data.ClientSecret, cfg.Data.TokensEndpoint) - - return director.NewDirectorClient(gqlClient, oauthClient), nil -} - -type DirectorOAuth struct { - Data struct { - ClientID string `json:"client_id"` - ClientSecret string `json:"client_secret"` - TokensEndpoint string `json:"tokens_endpoint"` - } `json:"data"` -} - func newShootController(gardenerNamespace string, gardenerClusterCfg *restclient.Config, dbsFactory dbsession.Factory, auditLogTenantConfigPath string) (*gardener.ShootController, error) { syncPeriod := defaultSyncPeriod diff --git a/components/provisioner/cmd/main.go b/components/provisioner/cmd/main.go index 86997bf927..ee5a06c5f6 100644 --- a/components/provisioner/cmd/main.go +++ b/components/provisioner/cmd/main.go @@ -39,12 +39,9 @@ import ( const connStringFormat string = "host=%s port=%s user=%s password=%s dbname=%s sslmode=%s sslrootcert=%s" type config struct { - Address string `envconfig:"default=127.0.0.1:3000"` - APIEndpoint string `envconfig:"default=/graphql"` - PlaygroundAPIEndpoint string `envconfig:"default=/graphql"` - DirectorURL string `envconfig:"default=http://compass-director.compass-system.svc.cluster.local:3000/graphql"` - SkipDirectorCertVerification bool `envconfig:"default=false"` - DirectorOAuthPath string `envconfig:"APP_DIRECTOR_OAUTH_PATH,default=./dev/director.yaml"` + Address string `envconfig:"default=127.0.0.1:3000"` + APIEndpoint string `envconfig:"default=/graphql"` + PlaygroundAPIEndpoint string `envconfig:"default=/graphql"` Database struct { User string `envconfig:"default=postgres"` @@ -85,8 +82,7 @@ type config struct { } func (c *config) String() string { - return fmt.Sprintf("Address: %s, APIEndpoint: %s, DirectorURL: %s, "+ - "SkipDirectorCertVerification: %v, DirectorOAuthPath: %s, "+ + return fmt.Sprintf("Address: %s, APIEndpoint: %s, "+ "DatabaseUser: %s, DatabaseHost: %s, DatabasePort: %s, "+ "DatabaseName: %s, DatabaseSSLMode: %s, "+ "ProvisioningTimeoutClusterCreation: %s "+ @@ -99,8 +95,7 @@ func (c *config) String() string { "LatestDownloadedReleases: %d, DownloadPreReleases: %v, "+ "EnqueueInProgressOperations: %v"+ "LogLevel: %s", - c.Address, c.APIEndpoint, c.DirectorURL, - c.SkipDirectorCertVerification, c.DirectorOAuthPath, + c.Address, c.APIEndpoint, c.Database.User, c.Database.Host, c.Database.Port, c.Database.Name, c.Database.SSLMode, c.ProvisioningTimeout.ClusterCreation.String(), @@ -163,9 +158,6 @@ func main() { shootClient := gardenerClientSet.Shoots(gardenerNamespace) - directorClient, err := newDirectorClient(cfg) - exitOnError(err, "Failed to initialize Director client") - k8sClientProvider := k8s.NewK8sClientProvider() adminKubeconfigRequest := gardenerClient.SubResource("adminkubeconfig") @@ -187,7 +179,6 @@ func main() { cfg.Gardener.Project, provisioner, dbsFactory, - directorClient, gardener.NewShootProvider(shootClient), provisioningQueue, deprovisioningQueue, diff --git a/components/provisioner/internal/gardener/provisioner.go b/components/provisioner/internal/gardener/provisioner.go index d4e5d6bb45..793a28dc91 100644 --- a/components/provisioner/internal/gardener/provisioner.go +++ b/components/provisioner/internal/gardener/provisioner.go @@ -20,7 +20,6 @@ import ( v1 "k8s.io/apimachinery/pkg/apis/meta/v1" "github.com/gardener/gardener/pkg/apis/core/v1beta1" - "github.com/kyma-project/control-plane/components/provisioner/internal/director" "github.com/kyma-project/control-plane/components/provisioner/internal/model" "github.com/kyma-project/control-plane/components/provisioner/internal/provisioning/persistence/dbsession" ) @@ -50,7 +49,6 @@ type GardenerProvisioner struct { namespace string shootClient Client dbSessionFactory dbsession.Factory - directorService director.DirectorClient policyConfigMapName string maintenanceWindowConfigPath string } diff --git a/components/provisioner/internal/operations/executor.go b/components/provisioner/internal/operations/executor.go index 9b0e826a60..5e96fef42a 100644 --- a/components/provisioner/internal/operations/executor.go +++ b/components/provisioner/internal/operations/executor.go @@ -5,11 +5,8 @@ import ( "fmt" "time" - "github.com/kyma-incubator/compass/components/director/pkg/graphql" - retry "github.com/avast/retry-go" "github.com/kyma-project/control-plane/components/provisioner/internal/apperrors" - "github.com/kyma-project/control-plane/components/provisioner/internal/director" "github.com/kyma-project/control-plane/components/provisioner/internal/model" "github.com/kyma-project/control-plane/components/provisioner/internal/provisioning/persistence/dbsession" "github.com/sirupsen/logrus" @@ -26,8 +23,7 @@ func NewExecutor( session dbsession.ReadWriteSession, operation model.OperationType, stages map[model.OperationStage]Step, - failureHandler FailureHandler, - directorClient director.DirectorClient) *Executor { + failureHandler FailureHandler) *Executor { return &Executor{ dbSession: session, @@ -35,7 +31,6 @@ func NewExecutor( operation: operation, failureHandler: failureHandler, log: logrus.WithFields(logrus.Fields{"Component": "Executor", "OperationType": operation}), - directorClient: directorClient, } } @@ -44,7 +39,6 @@ type Executor struct { stages map[model.OperationStage]Step operation model.OperationType failureHandler FailureHandler - directorClient director.DirectorClient log logrus.FieldLogger } @@ -84,7 +78,6 @@ func (e *Executor) Execute(operationID string) ProcessingResult { log.Errorf("unrecoverable error occurred while processing operation: %s", err.Error()) e.handleOperationFailure(operation, cluster, log) e.updateOperationStatus(log, operation.ID, nonRecoverable.Error(), model.Failed, time.Now()) - e.setRuntimeStatusCondition(log, cluster.ID, cluster.Tenant) return ProcessingResult{Requeue: false} } @@ -205,17 +198,6 @@ func (e *Executor) updateOperationLastError(log logrus.FieldLogger, id string, r } } -func (e *Executor) setRuntimeStatusCondition(log logrus.FieldLogger, id, tenant string) { - if e.directorClient != nil { - err := retry.Do(func() error { - return e.directorClient.SetRuntimeStatusCondition(id, graphql.RuntimeStatusConditionFailed, tenant) - }, retry.Attempts(5), retry.Delay(backOffDirectorDelay), retry.DelayType(retry.BackOffDelay)) - if err != nil { - log.Infof("Cannot set runtime %s status condition: %s", graphql.RuntimeStatusConditionFailed.String(), err.Error()) - } - } -} - func (e *Executor) updateOperationStage(log logrus.FieldLogger, id, message string, stage model.OperationStage, t time.Time) { err := retry.Do(func() error { return e.dbSession.TransitionOperation(id, message, stage, t) diff --git a/components/provisioner/internal/operations/executor_test.go b/components/provisioner/internal/operations/executor_test.go index 8089e234ea..036192eda1 100644 --- a/components/provisioner/internal/operations/executor_test.go +++ b/components/provisioner/internal/operations/executor_test.go @@ -7,9 +7,6 @@ import ( "github.com/kyma-project/control-plane/components/provisioner/internal/apperrors" - "github.com/kyma-incubator/compass/components/director/pkg/graphql" - - directorMocks "github.com/kyma-project/control-plane/components/provisioner/internal/director/mocks" "github.com/kyma-project/control-plane/components/provisioner/internal/model" "github.com/kyma-project/control-plane/components/provisioner/internal/operations/failure" "github.com/kyma-project/control-plane/components/provisioner/internal/persistence/dberrors" @@ -60,36 +57,7 @@ func TestStagesExecutor_Execute(t *testing.T) { model.WaitingForInstallation: mockStage, } - directorClient := &directorMocks.DirectorClient{} - - executor := NewExecutor(dbSession, model.Provision, installationStages, failure.NewNoopFailureHandler(), directorClient) - - // when - result := executor.Execute(operationId) - - // then - assert.Equal(t, false, result.Requeue) - assert.True(t, mockStage.called) - }) - - t.Run("should not requeue operation when stage is Finished and Director integration is disabled", func(t *testing.T) { - // given - dbSession := &mocks.ReadWriteSession{} - dbSession.On("GetOperation", operationId).Return(operation, nil) - dbSession.On("GetCluster", clusterId).Return(cluster, nil) - dbSession.On("TransitionOperation", operationId, "Provisioning steps finished", model.FinishedStage, mock.AnythingOfType("time.Time")). - Return(nil) - dbSession.On("UpdateOperationState", operationId, "Operation succeeded", model.Succeeded, mock.AnythingOfType("time.Time")). - Return(nil) - dbSession.On("UpdateOperationLastError", operationId, "", "", "").Return(nil) - - mockStage := NewMockStep(model.WaitingForInstallation, model.FinishedStage, 10*time.Second, 10*time.Second) - - installationStages := map[model.OperationStage]Step{ - model.WaitingForInstallation: mockStage, - } - - executor := NewExecutor(dbSession, model.Provision, installationStages, failure.NewNoopFailureHandler(), nil) + executor := NewExecutor(dbSession, model.Provision, installationStages, failure.NewNoopFailureHandler()) // when result := executor.Execute(operationId) @@ -113,33 +81,7 @@ func TestStagesExecutor_Execute(t *testing.T) { model.WaitingForInstallation: mockStage, } - directorClient := &directorMocks.DirectorClient{} - - executor := NewExecutor(dbSession, model.Provision, installationStages, failure.NewNoopFailureHandler(), directorClient) - - // when - result := executor.Execute(operationId) - - // then - assert.Equal(t, true, result.Requeue) - assert.True(t, mockStage.called) - }) - - t.Run("should requeue operation if error occurred and Director integration is disabled", func(t *testing.T) { - // given - runErr := fmt.Errorf("error") - dbSession := &mocks.ReadWriteSession{} - dbSession.On("GetOperation", operationId).Return(operation, nil) - dbSession.On("GetCluster", clusterId).Return(cluster, nil) - dbSession.On("UpdateOperationLastError", operationId, runErr.Error(), string(apperrors.ErrProvisionerInternal), string(apperrors.ErrProvisioner)).Return(nil) - - mockStage := NewErrorStep(model.WaitingForClusterCreation, runErr, time.Second*10) - - installationStages := map[model.OperationStage]Step{ - model.WaitingForInstallation: mockStage, - } - - executor := NewExecutor(dbSession, model.Provision, installationStages, failure.NewNoopFailureHandler(), nil) + executor := NewExecutor(dbSession, model.Provision, installationStages, failure.NewNoopFailureHandler()) // when result := executor.Execute(operationId) @@ -165,12 +107,9 @@ func TestStagesExecutor_Execute(t *testing.T) { model.WaitingForInstallation: mockStage, } - directorClient := &directorMocks.DirectorClient{} - directorClient.On("SetRuntimeStatusCondition", clusterId, graphql.RuntimeStatusConditionFailed, mock.AnythingOfType("string")).Return(nil) - failureHandler := MockFailureHandler{} - executor := NewExecutor(dbSession, model.Provision, installationStages, &failureHandler, directorClient) + executor := NewExecutor(dbSession, model.Provision, installationStages, &failureHandler) // when result := executor.Execute(operationId) @@ -181,67 +120,6 @@ func TestStagesExecutor_Execute(t *testing.T) { assert.True(t, failureHandler.called) }) - t.Run("should not requeue operation and run failure handler if NonRecoverable error occurred and Director integration is disabled", func(t *testing.T) { - // given - runErr := NewNonRecoverableError(apperrors.External("gardener error").SetComponent(apperrors.ErrGardener).SetReason("ERR_INFRA_QUOTA_EXCEEDED").Append("something")) - dbSession := &mocks.ReadWriteSession{} - dbSession.On("GetOperation", operationId).Return(operation, nil) - dbSession.On("GetCluster", clusterId).Return(cluster, nil) - dbSession.On("UpdateOperationState", operationId, "something, gardener error", model.Failed, mock.AnythingOfType("time.Time")). - Return(nil) - dbSession.On("UpdateOperationLastError", operationId, "something, gardener error", "ERR_INFRA_QUOTA_EXCEEDED", string(apperrors.ErrGardener)).Return(nil) - - mockStage := NewErrorStep(model.WaitingForClusterCreation, runErr, 10*time.Second) - - installationStages := map[model.OperationStage]Step{ - model.WaitingForInstallation: mockStage, - } - - failureHandler := MockFailureHandler{} - - executor := NewExecutor(dbSession, model.Provision, installationStages, &failureHandler, nil) - - // when - result := executor.Execute(operationId) - - // then - assert.Equal(t, false, result.Requeue) - assert.True(t, mockStage.called) - assert.True(t, failureHandler.called) - }) - - t.Run("should not requeue operation and run failure handler if NonRecoverable error occurred but failed to update Director", func(t *testing.T) { - // given - runErr := NewNonRecoverableError(apperrors.External(errors.Wrap(fmt.Errorf("error"), "kyma installation").Error()).SetComponent(apperrors.ErrKymaInstaller).SetReason("istio")) - dbSession := &mocks.ReadWriteSession{} - dbSession.On("GetOperation", operationId).Return(operation, nil) - dbSession.On("GetCluster", clusterId).Return(cluster, nil) - dbSession.On("UpdateOperationState", operationId, "kyma installation: error", model.Failed, mock.AnythingOfType("time.Time")). - Return(nil) - dbSession.On("UpdateOperationLastError", operationId, "kyma installation: error", "istio", string(apperrors.ErrKymaInstaller)).Return(nil) - - mockStage := NewErrorStep(model.StartingInstallation, runErr, 10*time.Second) - - installationStages := map[model.OperationStage]Step{ - model.WaitingForInstallation: mockStage, - } - - directorClient := &directorMocks.DirectorClient{} - directorClient.On("SetRuntimeStatusCondition", clusterId, graphql.RuntimeStatusConditionFailed, mock.AnythingOfType("string")).Return(apperrors.Internal("error")) - - failureHandler := MockFailureHandler{} - - executor := NewExecutor(dbSession, model.Provision, installationStages, &failureHandler, directorClient) - - // when - result := executor.Execute(operationId) - - // then - assert.False(t, result.Requeue) - assert.True(t, mockStage.called) - assert.True(t, failureHandler.called) - }) - t.Run("should not requeue operation and run failure handler if timeout reached", func(t *testing.T) { // given dbSession := &mocks.ReadWriteSession{} @@ -259,42 +137,9 @@ func TestStagesExecutor_Execute(t *testing.T) { model.WaitingForInstallation: mockStage, } - directorClient := &directorMocks.DirectorClient{} - directorClient.On("SetRuntimeStatusCondition", clusterId, graphql.RuntimeStatusConditionFailed, mock.AnythingOfType("string")).Return(nil) - - failureHandler := MockFailureHandler{} - - executor := NewExecutor(dbSession, model.Provision, installationStages, &failureHandler, directorClient) - - // when - result := executor.Execute(operationId) - - // then - assert.Equal(t, false, result.Requeue) - assert.False(t, mockStage.called) - assert.True(t, failureHandler.called) - }) - - t.Run("should not requeue operation and run failure handler if timeout reached and Director integration is disabled", func(t *testing.T) { - // given - dbSession := &mocks.ReadWriteSession{} - dbSession.On("GetOperation", operationId).Return(operation, nil) - dbSession.On("GetCluster", clusterId).Return(cluster, nil) - dbSession.On("TransitionOperation", operationId, "Operation in progress", model.ConnectRuntimeAgent, mock.AnythingOfType("time.Time")). - Return(nil) - dbSession.On("UpdateOperationState", operationId, "error: timeout while processing operation", model.Failed, mock.AnythingOfType("time.Time")). - Return(nil) - dbSession.On("UpdateOperationLastError", operationId, "error: timeout while processing operation", string(apperrors.ErrProvisionerTimeout), string(apperrors.ErrProvisioner)).Return(nil) - - mockStage := NewMockStep(model.WaitingForInstallation, model.ConnectRuntimeAgent, 0, 0*time.Second) - - installationStages := map[model.OperationStage]Step{ - model.WaitingForInstallation: mockStage, - } - failureHandler := MockFailureHandler{} - executor := NewExecutor(dbSession, model.Provision, installationStages, &failureHandler, nil) + executor := NewExecutor(dbSession, model.Provision, installationStages, &failureHandler) // when result := executor.Execute(operationId) @@ -305,8 +150,6 @@ func TestStagesExecutor_Execute(t *testing.T) { assert.True(t, failureHandler.called) }) - // tests for disabled Director integration - } type mockStep struct { diff --git a/components/provisioner/internal/provisioning/service.go b/components/provisioner/internal/provisioning/service.go index d48bcb3885..9265721392 100644 --- a/components/provisioner/internal/provisioning/service.go +++ b/components/provisioner/internal/provisioning/service.go @@ -6,7 +6,6 @@ import ( gardener_Types "github.com/gardener/gardener/pkg/apis/core/v1beta1" "github.com/hashicorp/go-version" "github.com/kyma-project/control-plane/components/provisioner/internal/apperrors" - "github.com/kyma-project/control-plane/components/provisioner/internal/director" "github.com/kyma-project/control-plane/components/provisioner/internal/model" "github.com/kyma-project/control-plane/components/provisioner/internal/operations/queue" "github.com/kyma-project/control-plane/components/provisioner/internal/persistence/dberrors" @@ -46,7 +45,6 @@ type ShootProvider interface { type service struct { inputConverter InputConverter graphQLConverter GraphQLConverter - directorService director.DirectorClient shootProvider ShootProvider dynamicKubeconfigProvider DynamicKubeconfigProvider @@ -64,7 +62,6 @@ type service struct { func NewProvisioningService( inputConverter InputConverter, graphQLConverter GraphQLConverter, - directorService director.DirectorClient, factory dbsession.Factory, provisioner Provisioner, generator uuid.UUIDGenerator, @@ -78,7 +75,6 @@ func NewProvisioningService( return &service{ inputConverter: inputConverter, graphQLConverter: graphQLConverter, - directorService: directorService, dbSessionFactory: factory, provisioner: provisioner, uuidGenerator: generator, diff --git a/components/provisioner/internal/provisioning/service_test.go b/components/provisioner/internal/provisioning/service_test.go index 70e891d78d..c25bc8660f 100644 --- a/components/provisioner/internal/provisioning/service_test.go +++ b/components/provisioner/internal/provisioning/service_test.go @@ -11,7 +11,6 @@ import ( "github.com/stretchr/testify/require" "github.com/kyma-project/control-plane/components/provisioner/internal/apperrors" - directormock "github.com/kyma-project/control-plane/components/provisioner/internal/director/mocks" "github.com/kyma-project/control-plane/components/provisioner/internal/model" "github.com/kyma-project/control-plane/components/provisioner/internal/operations/mocks" queue_mock "github.com/kyma-project/control-plane/components/provisioner/internal/operations/queue/mocks" @@ -112,7 +111,6 @@ func TestService_ProvisionRuntime(t *testing.T) { // given sessionFactoryMock := &sessionMocks.Factory{} writeSessionWithinTransactionMock := &sessionMocks.WriteSessionWithinTransaction{} - directorServiceMock := &directormock.DirectorClient{} provisioner := &mocks2.Provisioner{} uuidGeneratorMock := &uuidMocks.UUIDGenerator{} @@ -129,7 +127,7 @@ func TestService_ProvisionRuntime(t *testing.T) { provisioningQueue.On("Add", mock.AnythingOfType("string")).Return(nil) - service := NewProvisioningService(inputConverter, graphQLConverter, directorServiceMock, sessionFactoryMock, provisioner, uuidGeneratorMock, nil, provisioningQueue, nil, nil, kubeconfigProviderMock) + service := NewProvisioningService(inputConverter, graphQLConverter, sessionFactoryMock, provisioner, uuidGeneratorMock, nil, provisioningQueue, nil, nil, kubeconfigProviderMock) // when operationStatus, err := service.ProvisionRuntime(provisionRuntimeInputNoKymaConfig, tenant, subAccountId) @@ -141,19 +139,16 @@ func TestService_ProvisionRuntime(t *testing.T) { assert.NotEmpty(t, operationStatus.ID) sessionFactoryMock.AssertExpectations(t) writeSessionWithinTransactionMock.AssertExpectations(t) - directorServiceMock.AssertExpectations(t) provisioner.AssertExpectations(t) }) - t.Run("Should return error and unregister Runtime when failed to commit transaction", func(t *testing.T) { + t.Run("Should return error when failed to commit transaction", func(t *testing.T) { // given sessionFactoryMock := &sessionMocks.Factory{} writeSessionWithinTransactionMock := &sessionMocks.WriteSessionWithinTransaction{} - directorServiceMock := &directormock.DirectorClient{} provisioner := &mocks2.Provisioner{} expectErr := dberrors.Internal("Failed to commit transaction: error") - directorServiceMock.On("CreateRuntime", mock.Anything, tenant).Return(runtimeID, nil) sessionFactoryMock.On("NewSessionWithinTransaction").Return(writeSessionWithinTransactionMock, nil) writeSessionWithinTransactionMock.On("InsertCluster", mock.MatchedBy(clusterMatcher)).Return(nil) writeSessionWithinTransactionMock.On("InsertGardenerConfig", mock.AnythingOfType("model.GardenerConfig")).Return(nil) @@ -161,9 +156,8 @@ func TestService_ProvisionRuntime(t *testing.T) { writeSessionWithinTransactionMock.On("Commit").Return(expectErr) writeSessionWithinTransactionMock.On("RollbackUnlessCommitted").Return() provisioner.On("ProvisionCluster", mock.MatchedBy(clusterMatcher), mock.MatchedBy(notEmptyUUIDMatcher)).Return(nil) - directorServiceMock.On("DeleteRuntime", runtimeID, tenant).Return(nil) - service := NewProvisioningService(inputConverter, graphQLConverter, directorServiceMock, sessionFactoryMock, provisioner, uuidGenerator, nil, nil, nil, nil, kubeconfigProviderMock, true) + service := NewProvisioningService(inputConverter, graphQLConverter, sessionFactoryMock, provisioner, uuidGenerator, nil, nil, nil, nil, kubeconfigProviderMock) // when _, err := service.ProvisionRuntime(provisionRuntimeInput, tenant, subAccountId) @@ -174,27 +168,23 @@ func TestService_ProvisionRuntime(t *testing.T) { assert.Contains(t, err.Error(), "Failed to commit transaction") sessionFactoryMock.AssertExpectations(t) writeSessionWithinTransactionMock.AssertExpectations(t) - directorServiceMock.AssertExpectations(t) provisioner.AssertExpectations(t) }) - t.Run("Should return error and unregister Runtime when failed to start provisioning", func(t *testing.T) { + t.Run("Should return error when failed to start provisioning", func(t *testing.T) { // given sessionFactoryMock := &sessionMocks.Factory{} writeSessionWithinTransactionMock := &sessionMocks.WriteSessionWithinTransaction{} - directorServiceMock := &directormock.DirectorClient{} provisioner := &mocks2.Provisioner{} - directorServiceMock.On("CreateRuntime", mock.Anything, tenant).Return(runtimeID, nil) sessionFactoryMock.On("NewSessionWithinTransaction").Return(writeSessionWithinTransactionMock, nil) writeSessionWithinTransactionMock.On("InsertCluster", mock.MatchedBy(clusterMatcher)).Return(nil) writeSessionWithinTransactionMock.On("InsertGardenerConfig", mock.AnythingOfType("model.GardenerConfig")).Return(nil) writeSessionWithinTransactionMock.On("InsertOperation", mock.MatchedBy(operationMatcher)).Return(nil) writeSessionWithinTransactionMock.On("RollbackUnlessCommitted").Return() provisioner.On("ProvisionCluster", mock.MatchedBy(clusterMatcher), mock.MatchedBy(notEmptyUUIDMatcher)).Return(apperrors.Internal("error")) - directorServiceMock.On("DeleteRuntime", runtimeID, tenant).Return(nil) - service := NewProvisioningService(inputConverter, graphQLConverter, directorServiceMock, sessionFactoryMock, provisioner, uuidGenerator, nil, nil, nil, nil, kubeconfigProviderMock, true) + service := NewProvisioningService(inputConverter, graphQLConverter, sessionFactoryMock, provisioner, uuidGenerator, nil, nil, nil, nil, kubeconfigProviderMock) // when _, err := service.ProvisionRuntime(provisionRuntimeInput, tenant, subAccountId) @@ -205,64 +195,9 @@ func TestService_ProvisionRuntime(t *testing.T) { assert.Contains(t, err.Error(), "Failed to start provisioning") sessionFactoryMock.AssertExpectations(t) writeSessionWithinTransactionMock.AssertExpectations(t) - directorServiceMock.AssertExpectations(t) provisioner.AssertExpectations(t) }) - t.Run("Should return error when failed to register Runtime", func(t *testing.T) { - // given - directorServiceMock := &directormock.DirectorClient{} - - directorServiceMock.On("CreateRuntime", mock.Anything, tenant).Return("", apperrors.Internal("registering error")) - - service := NewProvisioningService(inputConverter, graphQLConverter, directorServiceMock, nil, nil, uuidGenerator, nil, nil, nil, nil, kubeconfigProviderMock, true) - - // when - _, err := service.ProvisionRuntime(provisionRuntimeInput, tenant, subAccountId) - require.Error(t, err) - util.CheckErrorType(t, err, apperrors.CodeInternal) - - //then - assert.Equal(t, err, apperrors.Internal("Failed to register Runtime, registering error")) - assert.Contains(t, err.Error(), "Failed to register Runtime") - directorServiceMock.AssertExpectations(t) - }) - - t.Run("Should retry when failed to register Runtime and start runtime provisioning of Gardener cluster", func(t *testing.T) { - // given - sessionFactoryMock := &sessionMocks.Factory{} - writeSessionWithinTransactionMock := &sessionMocks.WriteSessionWithinTransaction{} - directorServiceMock := &directormock.DirectorClient{} - provisioner := &mocks2.Provisioner{} - - provisioningQueue := &mocks.OperationQueue{} - - directorServiceMock.On("CreateRuntime", mock.Anything, tenant).Once().Return("", apperrors.Internal("registering error")) - directorServiceMock.On("CreateRuntime", mock.Anything, tenant).Once().Return(runtimeID, nil) - sessionFactoryMock.On("NewSessionWithinTransaction").Return(writeSessionWithinTransactionMock, nil) - writeSessionWithinTransactionMock.On("InsertCluster", mock.MatchedBy(clusterMatcher)).Return(nil) - writeSessionWithinTransactionMock.On("InsertGardenerConfig", mock.AnythingOfType("model.GardenerConfig")).Return(nil) - writeSessionWithinTransactionMock.On("InsertOperation", mock.MatchedBy(operationMatcher)).Return(nil) - writeSessionWithinTransactionMock.On("Commit").Return(nil) - writeSessionWithinTransactionMock.On("RollbackUnlessCommitted").Return() - provisioner.On("ProvisionCluster", mock.MatchedBy(clusterMatcher), mock.MatchedBy(notEmptyUUIDMatcher)).Return(nil) - - provisioningQueue.On("Add", mock.AnythingOfType("string")).Return(nil) - - service := NewProvisioningService(inputConverter, graphQLConverter, directorServiceMock, sessionFactoryMock, provisioner, uuidGenerator, nil, provisioningQueue, nil, nil, kubeconfigProviderMock, true) - - // when - operationStatus, err := service.ProvisionRuntime(provisionRuntimeInput, tenant, subAccountId) - require.NoError(t, err) - - // then - assert.Equal(t, runtimeID, *operationStatus.RuntimeID) - assert.NotEmpty(t, operationStatus.ID) - sessionFactoryMock.AssertExpectations(t) - writeSessionWithinTransactionMock.AssertExpectations(t) - directorServiceMock.AssertExpectations(t) - provisioner.AssertExpectations(t) - }) } func TestService_DeprovisionRuntime(t *testing.T) { @@ -308,7 +243,7 @@ func TestService_DeprovisionRuntime(t *testing.T) { provisioner.On("DeprovisionCluster", mock.MatchedBy(clusterMatcher), mock.MatchedBy(notEmptyUUIDMatcher)).Return(operation, nil) readWriteSession.On("InsertOperation", mock.MatchedBy(operationMatcher)).Return(nil) - resolver := NewProvisioningService(inputConverter, graphQLConverter, nil, sessionFactoryMock, provisioner, uuid.NewUUIDGenerator(), nil, nil, deprovisioningQueue, nil, nil, true) + resolver := NewProvisioningService(inputConverter, graphQLConverter, sessionFactoryMock, provisioner, uuid.NewUUIDGenerator(), nil, nil, deprovisioningQueue, nil, nil) // when opID, err := resolver.DeprovisionRuntime(runtimeID) @@ -354,7 +289,7 @@ func TestService_DeprovisionRuntime(t *testing.T) { provisioner.On("DeprovisionCluster", mock.MatchedBy(clusterMatcher), mock.MatchedBy(notEmptyUUIDMatcher)).Return(operation, nil) readWriteSession.On("InsertOperation", mock.MatchedBy(operationMatcher)).Return(nil) - resolver := NewProvisioningService(inputConverter, graphQLConverter, nil, sessionFactoryMock, provisioner, uuid.NewUUIDGenerator(), nil, nil, deprovisioningQueue, nil, nil, true) + resolver := NewProvisioningService(inputConverter, graphQLConverter, sessionFactoryMock, provisioner, uuid.NewUUIDGenerator(), nil, nil, deprovisioningQueue, nil, nil) // when opID, err := resolver.DeprovisionRuntime(runtimeID) @@ -379,7 +314,7 @@ func TestService_DeprovisionRuntime(t *testing.T) { readWriteSession.On("GetCluster", runtimeID).Return(cluster, nil) provisioner.On("DeprovisionCluster", mock.MatchedBy(clusterMatcher), mock.MatchedBy(notEmptyUUIDMatcher)).Return(model.Operation{}, apperrors.Internal("some error")) - resolver := NewProvisioningService(inputConverter, graphQLConverter, nil, sessionFactoryMock, provisioner, uuid.NewUUIDGenerator(), nil, nil, nil, nil, nil, true) + resolver := NewProvisioningService(inputConverter, graphQLConverter, sessionFactoryMock, provisioner, uuid.NewUUIDGenerator(), nil, nil, nil, nil, nil) // when _, err := resolver.DeprovisionRuntime(runtimeID) @@ -404,7 +339,7 @@ func TestService_DeprovisionRuntime(t *testing.T) { readWriteSession.On("GetLastOperation", runtimeID).Return(lastOperation, nil) readWriteSession.On("GetCluster", runtimeID).Return(model.Cluster{}, dberrors.Internal("some error")) - resolver := NewProvisioningService(inputConverter, graphQLConverter, nil, sessionFactoryMock, nil, uuid.NewUUIDGenerator(), nil, nil, nil, nil, nil, true) + resolver := NewProvisioningService(inputConverter, graphQLConverter, sessionFactoryMock, nil, uuid.NewUUIDGenerator(), nil, nil, nil, nil, nil) // when _, err := resolver.DeprovisionRuntime(runtimeID) @@ -428,7 +363,7 @@ func TestService_DeprovisionRuntime(t *testing.T) { sessionFactoryMock.On("NewReadWriteSession").Return(readWriteSession) readWriteSession.On("GetLastOperation", runtimeID).Return(operation, nil) - resolver := NewProvisioningService(inputConverter, graphQLConverter, nil, sessionFactoryMock, nil, uuid.NewUUIDGenerator(), nil, nil, nil, nil, nil, true) + resolver := NewProvisioningService(inputConverter, graphQLConverter, sessionFactoryMock, nil, uuid.NewUUIDGenerator(), nil, nil, nil, nil, nil) // when _, err := resolver.DeprovisionRuntime(runtimeID) @@ -451,7 +386,7 @@ func TestService_DeprovisionRuntime(t *testing.T) { sessionFactoryMock.On("NewReadWriteSession").Return(readWriteSession) readWriteSession.On("GetLastOperation", runtimeID).Return(model.Operation{}, dberrors.Internal("some error")) - resolver := NewProvisioningService(inputConverter, graphQLConverter, nil, sessionFactoryMock, nil, uuid.NewUUIDGenerator(), nil, nil, nil, nil, nil, true) + resolver := NewProvisioningService(inputConverter, graphQLConverter, sessionFactoryMock, nil, uuid.NewUUIDGenerator(), nil, nil, nil, nil, nil) // when _, err := resolver.DeprovisionRuntime(runtimeID) @@ -487,7 +422,7 @@ func TestService_RuntimeOperationStatus(t *testing.T) { sessionFactoryMock.On("NewReadSession").Return(readSession) readSession.On("GetOperation", operationID).Return(operation, nil) - resolver := NewProvisioningService(inputConverter, graphQLConverter, nil, sessionFactoryMock, nil, uuidGenerator, nil, nil, nil, nil, nil, true) + resolver := NewProvisioningService(inputConverter, graphQLConverter, sessionFactoryMock, nil, uuidGenerator, nil, nil, nil, nil, nil) // when status, err := resolver.RuntimeOperationStatus(operationID) @@ -510,7 +445,7 @@ func TestService_RuntimeOperationStatus(t *testing.T) { sessionFactoryMock.On("NewReadSession").Return(readSession) readSession.On("GetOperation", operationID).Return(model.Operation{}, dberrors.Internal("error")) - resolver := NewProvisioningService(inputConverter, graphQLConverter, nil, sessionFactoryMock, nil, uuidGenerator, nil, nil, nil, nil, nil, true) + resolver := NewProvisioningService(inputConverter, graphQLConverter, sessionFactoryMock, nil, uuidGenerator, nil, nil, nil, nil, nil) // when _, err := resolver.RuntimeOperationStatus(operationID) @@ -551,7 +486,7 @@ func TestService_RuntimeStatus(t *testing.T) { provisioner := &mocks2.Provisioner{} - resolver := NewProvisioningService(inputConverter, graphQLConverter, nil, sessionFactoryMock, provisioner, uuidGenerator, nil, nil, nil, nil, kubeconfigProviderMock(), true) + resolver := NewProvisioningService(inputConverter, graphQLConverter, sessionFactoryMock, provisioner, uuidGenerator, nil, nil, nil, nil, kubeconfigProviderMock()) // when status, err := resolver.RuntimeStatus(operationID) From 910cab8f7f13d204bca9118baad7bd6ccfc28511 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Przemys=C5=82aw=20Golicz?= Date: Tue, 19 Mar 2024 11:17:04 +0100 Subject: [PATCH 06/19] remove director mock usage --- ...resolver_integration_with_gardener_test.go | 36 ++----------------- .../operations/queue/queues_constructor.go | 3 -- 2 files changed, 2 insertions(+), 37 deletions(-) diff --git a/components/provisioner/internal/api/resolver_integration_with_gardener_test.go b/components/provisioner/internal/api/resolver_integration_with_gardener_test.go index 38ebd38131..8f0d5880ed 100644 --- a/components/provisioner/internal/api/resolver_integration_with_gardener_test.go +++ b/components/provisioner/internal/api/resolver_integration_with_gardener_test.go @@ -28,15 +28,12 @@ import ( gardener_types "github.com/gardener/gardener/pkg/apis/core/v1beta1" gardener_apis "github.com/gardener/gardener/pkg/client/core/clientset/versioned/typed/core/v1beta1" - "github.com/kyma-incubator/compass/components/director/pkg/graphql" - directormock "github.com/kyma-project/control-plane/components/provisioner/internal/director/mocks" "github.com/kyma-project/control-plane/components/provisioner/internal/gardener" kubeconfigprovidermock "github.com/kyma-project/control-plane/components/provisioner/internal/operations/queue/mocks" "github.com/kyma-project/control-plane/components/provisioner/internal/persistence/database" "github.com/kyma-project/control-plane/components/provisioner/internal/persistence/testutils" "github.com/kyma-project/control-plane/components/provisioner/internal/provisioning" "github.com/kyma-project/control-plane/components/provisioner/internal/provisioning/persistence/dbsession" - runtimeConfig "github.com/kyma-project/control-plane/components/provisioner/internal/runtime" "github.com/kyma-project/control-plane/components/provisioner/internal/util" "github.com/kyma-project/control-plane/components/provisioner/pkg/gqlschema" "github.com/stretchr/testify/assert" @@ -120,14 +117,10 @@ func TestProvisioning_ProvisionRuntimeWithDatabase(t *testing.T) { err = database.SetupSchema(connection, testutils.SchemaFilePath) require.NoError(t, err) - directorServiceMock := &directormock.DirectorClient{} - mockK8sClientProvider := &mocks.K8sClientProvider{} fakeK8sClient := fake.NewSimpleClientset() mockK8sClientProvider.On("CreateK8SClient", mockedKubeconfig).Return(fakeK8sClient, nil) - runtimeConfigurator := runtimeConfig.NewRuntimeConfigurator(mockK8sClientProvider, directorServiceMock) - auditLogsConfigPath := filepath.Join("testdata", "config.json") maintenanceWindowConfigPath := filepath.Join("testdata", "maintwindow.json") @@ -146,18 +139,16 @@ func TestProvisioning_ProvisionRuntimeWithDatabase(t *testing.T) { provisioningQueue := queue.CreateProvisioningQueue( testProvisioningTimeouts(), dbsFactory, - directorServiceMock, shootInterface, testOperatorRoleBinding(), mockK8sClientProvider, - runtimeConfigurator, kubeconfigProviderMock) provisioningQueue.Run(queueCtx.Done()) - deprovisioningQueue := queue.CreateDeprovisioningQueue(testDeprovisioningTimeouts(), dbsFactory, directorServiceMock, shootInterface) + deprovisioningQueue := queue.CreateDeprovisioningQueue(testDeprovisioningTimeouts(), dbsFactory, shootInterface) deprovisioningQueue.Run(queueCtx.Done()) - shootUpgradeQueue := queue.CreateShootUpgradeQueue(testProvisioningTimeouts(), dbsFactory, directorServiceMock, shootInterface, testOperatorRoleBinding(), mockK8sClientProvider, kubeconfigProviderMock) + shootUpgradeQueue := queue.CreateShootUpgradeQueue(testProvisioningTimeouts(), dbsFactory, shootInterface, testOperatorRoleBinding(), mockK8sClientProvider, kubeconfigProviderMock) shootUpgradeQueue.Run(queueCtx.Done()) controler, err := gardener.NewShootController(mgr, dbsFactory, auditLogsConfigPath) @@ -180,28 +171,6 @@ func TestProvisioning_ProvisionRuntimeWithDatabase(t *testing.T) { clusterConfig := config.provisioningInput.config runtimeInput := config.provisioningInput.runtimeInput - _ = fakeK8sClient.CoreV1().Secrets(compassSystemNamespace).Delete(context.Background(), runtimeConfig.AgentConfigurationSecretName, metav1.DeleteOptions{}) - _ = fakeK8sClient.CoreV1().ConfigMaps(compassSystemNamespace).Delete(context.Background(), runtimeConfig.AgentConfigurationSecretName, metav1.DeleteOptions{}) - - directorServiceMock.Calls = nil - directorServiceMock.ExpectedCalls = nil - - directorServiceMock.On("CreateRuntime", mock.Anything, mock.Anything).Return(config.runtimeID, nil) - directorServiceMock.On("RuntimeExists", mock.Anything, mock.Anything).Return(true, nil) - directorServiceMock.On("DeleteRuntime", mock.Anything, mock.Anything).Return(nil) - directorServiceMock.On("GetConnectionToken", mock.Anything, mock.Anything).Return(graphql.OneTimeTokenForRuntimeExt{}, nil) - - directorServiceMock.On("GetRuntime", mock.Anything, mock.Anything).Return(graphql.RuntimeExt{ - Runtime: graphql.Runtime{ - ID: config.runtimeID, - Name: runtimeInput.Name, - Description: runtimeInput.Description, - }, - }, nil) - - directorServiceMock.On("UpdateRuntime", mock.Anything, mock.Anything, mock.Anything).Return(nil) - directorServiceMock.On("SetRuntimeStatusCondition", mock.Anything, mock.Anything, mock.Anything).Return(nil) - uuidGenerator := uuid.NewUUIDGenerator() provisioner := gardener.NewProvisioner(namespace, shootInterface, dbsFactory, auditLogPolicyCMName, maintenanceWindowConfigPath) @@ -211,7 +180,6 @@ func TestProvisioning_ProvisionRuntimeWithDatabase(t *testing.T) { provisioningService := provisioning.NewProvisioningService( inputConverter, graphQLConverter, - directorServiceMock, dbsFactory, provisioner, uuidGenerator, diff --git a/components/provisioner/internal/operations/queue/queues_constructor.go b/components/provisioner/internal/operations/queue/queues_constructor.go index 55a56291ac..971ddfe614 100644 --- a/components/provisioner/internal/operations/queue/queues_constructor.go +++ b/components/provisioner/internal/operations/queue/queues_constructor.go @@ -65,7 +65,6 @@ func CreateProvisioningQueue( model.Provision, provisionSteps, failure.NewNoopFailureHandler(), - nil, ) return NewQueue(provisioningExecutor) @@ -90,7 +89,6 @@ func CreateDeprovisioningQueue( model.DeprovisionNoInstall, deprovisioningSteps, failure.NewNoopFailureHandler(), - nil, ) return NewQueue(deprovisioningExecutor) @@ -120,7 +118,6 @@ func CreateShootUpgradeQueue( model.UpgradeShoot, upgradeSteps, failure.NewNoopFailureHandler(), - nil, ) return NewQueue(upgradeClusterExecutor) From a0ca6de40196582b4915dad763778aa76a8b433d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Przemys=C5=82aw=20Golicz?= Date: Tue, 19 Mar 2024 11:29:08 +0100 Subject: [PATCH 07/19] remove director client --- .../internal/director/directorclient.go | 292 ---- .../internal/director/directorclient_test.go | 1174 ----------------- .../internal/director/mocks/DirectorClient.go | 184 --- .../provisioner/internal/director/model.go | 35 - .../provisioner/internal/director/query.go | 38 - 5 files changed, 1723 deletions(-) delete mode 100644 components/provisioner/internal/director/directorclient.go delete mode 100644 components/provisioner/internal/director/directorclient_test.go delete mode 100644 components/provisioner/internal/director/mocks/DirectorClient.go delete mode 100644 components/provisioner/internal/director/model.go delete mode 100644 components/provisioner/internal/director/query.go diff --git a/components/provisioner/internal/director/directorclient.go b/components/provisioner/internal/director/directorclient.go deleted file mode 100644 index 6e074305ac..0000000000 --- a/components/provisioner/internal/director/directorclient.go +++ /dev/null @@ -1,292 +0,0 @@ -package director - -import ( - "fmt" - - directorApperrors "github.com/kyma-incubator/compass/components/director/pkg/apperrors" - "github.com/kyma-incubator/compass/components/director/pkg/graphql" - "github.com/kyma-incubator/compass/components/director/pkg/graphql/graphqlizer" - log "github.com/sirupsen/logrus" - - "github.com/kyma-project/control-plane/components/provisioner/internal/apperrors" - gql "github.com/kyma-project/control-plane/components/provisioner/internal/graphql" - "github.com/kyma-project/control-plane/components/provisioner/internal/oauth" - "github.com/kyma-project/control-plane/components/provisioner/pkg/gqlschema" - gcli "github.com/kyma-project/control-plane/components/provisioner/third_party/machinebox/graphql" -) - -const ( - AuthorizationHeader = "Authorization" - TenantHeader = "Tenant" -) - -//go:generate mockery --name=DirectorClient -type DirectorClient interface { - CreateRuntime(config *gqlschema.RuntimeInput, tenant string) (string, apperrors.AppError) - GetRuntime(id, tenant string) (graphql.RuntimeExt, apperrors.AppError) - UpdateRuntime(id string, config *graphql.RuntimeUpdateInput, tenant string) apperrors.AppError - DeleteRuntime(id, tenant string) apperrors.AppError - SetRuntimeStatusCondition(id string, statusCondition graphql.RuntimeStatusCondition, tenant string) apperrors.AppError - GetConnectionToken(id, tenant string) (graphql.OneTimeTokenForRuntimeExt, apperrors.AppError) - RuntimeExists(gardenerClusterName, tenant string) (bool, apperrors.AppError) -} - -type directorClient struct { - gqlClient gql.Client - queryProvider queryProvider - graphqlizer graphqlizer.Graphqlizer - token oauth.Token - oauthClient oauth.Client -} - -func NewDirectorClient(gqlClient gql.Client, oauthClient oauth.Client) DirectorClient { - return &directorClient{ - gqlClient: gqlClient, - oauthClient: oauthClient, - queryProvider: queryProvider{}, - graphqlizer: graphqlizer.Graphqlizer{}, - token: oauth.Token{}, - } -} - -func (cc *directorClient) CreateRuntime(config *gqlschema.RuntimeInput, tenant string) (string, apperrors.AppError) { - log.Infof("Registering Runtime on Director service") - - if config == nil { - return "", apperrors.BadRequest("Cannot register runtime in Director: missing Runtime config") - } - - var labels graphql.Labels - if config.Labels != nil { - l := graphql.Labels(config.Labels) - labels = l - } - - directorInput := graphql.RuntimeRegisterInput{ - Name: config.Name, - Description: config.Description, - Labels: labels, - } - - runtimeInput, err := cc.graphqlizer.RuntimeRegisterInputToGQL(directorInput) - if err != nil { - log.Infof("Failed to create graphQLized Runtime input") - return "", apperrors.Internal("Failed to create graphQLized Runtime input: %s", err.Error()).SetComponent(apperrors.ErrCompassDirectorClient).SetReason(apperrors.ErrDirectorClientGraphqlizer) - } - - runtimeQuery := cc.queryProvider.createRuntimeMutation(runtimeInput) - - var response CreateRuntimeResponse - appErr := cc.executeDirectorGraphQLCall(runtimeQuery, tenant, &response) - if appErr != nil { - return "", appErr.Append("Failed to register runtime in Director. Request failed") - } - - // Nil check is necessary due to GraphQL client not checking response code - if response.Result == nil { - return "", apperrors.Internal("Failed to register runtime in Director: Received nil response.").SetComponent(apperrors.ErrCompassDirector).SetReason(apperrors.ErrDirectorNilResponse) - } - - log.Infof("Successfully registered Runtime %s in Director for tenant %s", config.Name, tenant) - - return response.Result.ID, nil -} - -func (cc *directorClient) GetRuntime(id, tenant string) (graphql.RuntimeExt, apperrors.AppError) { - log.Infof("Getting Runtime from Director service") - - runtimeQuery := cc.queryProvider.getRuntimeQuery(id) - - var response GetRuntimeResponse - err := cc.executeDirectorGraphQLCall(runtimeQuery, tenant, &response) - if err != nil { - return graphql.RuntimeExt{}, err.Append("Failed to get runtime %s from Director", id) - } - if response.Result == nil { - return graphql.RuntimeExt{}, apperrors.Internal("Failed to get runtime %s from Director: received nil response.", id).SetComponent(apperrors.ErrCompassDirector).SetReason(apperrors.ErrDirectorNilResponse) - } - if response.Result.ID != id { - return graphql.RuntimeExt{}, apperrors.Internal("Failed to get runtime %s from Director: received unexpected RuntimeID", id).SetComponent(apperrors.ErrCompassDirector).SetReason(apperrors.ErrDirectorRuntimeIDMismatch) - } - - log.Infof("Successfully got Runtime %s from Director for tenant %s", id, tenant) - return *response.Result, nil -} - -func (cc *directorClient) UpdateRuntime(id string, directorInput *graphql.RuntimeUpdateInput, tenant string) apperrors.AppError { - log.Infof("Updating Runtime in Director service") - - if directorInput == nil { - return apperrors.BadRequest("Cannot update runtime in Director: missing Runtime config") - } - - runtimeInput, err := cc.graphqlizer.RuntimeUpdateInputToGQL(*directorInput) - if err != nil { - log.Infof("Failed to create graphQLized Runtime input") - return apperrors.Internal("Failed to create graphQLized Runtime input: %s", err.Error()).SetComponent(apperrors.ErrCompassDirectorClient).SetReason(apperrors.ErrDirectorClientGraphqlizer) - } - runtimeQuery := cc.queryProvider.updateRuntimeMutation(id, runtimeInput) - - var response UpdateRuntimeResponse - appErr := cc.executeDirectorGraphQLCall(runtimeQuery, tenant, &response) - if appErr != nil { - return appErr.Append("Failed to update runtime %s in Director", id) - } - if response.Result == nil { - return apperrors.Internal("Failed to update runtime %s in Director: received nil response.", id).SetComponent(apperrors.ErrCompassDirector).SetReason(apperrors.ErrDirectorNilResponse) - } - if response.Result.ID != id { - return apperrors.Internal("Failed to update runtime %s in Director: received unexpected RuntimeID", id).SetComponent(apperrors.ErrCompassDirector).SetReason(apperrors.ErrDirectorRuntimeIDMismatch) - } - - log.Infof("Successfully updated Runtime %s in Director for tenant %s", id, tenant) - return nil -} - -func (cc *directorClient) DeleteRuntime(id, tenant string) apperrors.AppError { - runtimeQuery := cc.queryProvider.deleteRuntimeMutation(id) - - var response DeleteRuntimeResponse - err := cc.executeDirectorGraphQLCall(runtimeQuery, tenant, &response) - if err != nil { - return err.Append("Failed to unregister runtime %s in Director", id) - } - // Nil check is necessary due to GraphQL client not checking response code - if response.Result == nil { - return apperrors.Internal("Failed to unregister runtime %s in Director: received nil response.", id).SetComponent(apperrors.ErrCompassDirector).SetReason(apperrors.ErrDirectorNilResponse) - } - - if response.Result.ID != id { - return apperrors.Internal("Failed to unregister runtime %s in Director: received unexpected RuntimeID.", id).SetComponent(apperrors.ErrCompassDirector).SetReason(apperrors.ErrDirectorRuntimeIDMismatch) - } - - log.Infof("Successfully unregistered Runtime %s in Director for tenant %s", id, tenant) - - return nil -} - -func (cc *directorClient) RuntimeExists(id, tenant string) (bool, apperrors.AppError) { - runtimeQuery := cc.queryProvider.getRuntimeQuery(id) - - var response GetRuntimeResponse - err := cc.executeDirectorGraphQLCall(runtimeQuery, tenant, &response) - if err != nil { - if err.Code() == apperrors.CodeBadRequest && err.Cause() == apperrors.TenantNotFound { - return false, nil - } - return false, err.Append("Failed to get runtime %s from Director", id) - } - - if response.Result == nil { - return false, nil - } - - return true, nil -} - -func (cc *directorClient) SetRuntimeStatusCondition(id string, statusCondition graphql.RuntimeStatusCondition, tenant string) apperrors.AppError { - // TODO: Set StatusCondition without getting the Runtime - // It'll be possible after this issue implementation: - // - https://github.com/kyma-incubator/compass/issues/1186 - runtime, err := cc.GetRuntime(id, tenant) - if err != nil { - log.Errorf("Failed to get Runtime by ID: %s", err.Error()) - return err.Append("failed to get runtime by ID") - } - runtimeInput := &graphql.RuntimeUpdateInput{ - Name: runtime.Name, - Description: runtime.Description, - StatusCondition: &statusCondition, - Labels: runtime.Labels, - } - err = cc.UpdateRuntime(id, runtimeInput, tenant) - if err != nil { - log.Errorf("Failed to update Runtime in Director: %s", err.Error()) - return err.Append("failed to update runtime in Director") - } - return nil -} - -func (cc *directorClient) GetConnectionToken(id, tenant string) (graphql.OneTimeTokenForRuntimeExt, apperrors.AppError) { - runtimeQuery := cc.queryProvider.requestOneTimeTokenMutation(id) - - var response OneTimeTokenResponse - err := cc.executeDirectorGraphQLCall(runtimeQuery, tenant, &response) - if err != nil { - return graphql.OneTimeTokenForRuntimeExt{}, err.Append("Failed to get OneTimeToken for Runtime %s in Director", id) - } - - if response.Result == nil { - return graphql.OneTimeTokenForRuntimeExt{}, apperrors.Internal("Failed to get OneTimeToken for Runtime %s in Director: received nil response.", id).SetComponent(apperrors.ErrCompassDirector).SetReason(apperrors.ErrDirectorNilResponse) - } - - log.Infof("Received OneTimeToken for Runtime %s in Director for tenant %s", id, tenant) - - return *response.Result, nil -} - -func (cc *directorClient) getToken() apperrors.AppError { - token, err := cc.oauthClient.GetAuthorizationToken() - if err != nil { - return err.Append("Error while obtaining token") - } - - if token.EmptyOrExpired() { - return apperrors.Internal("Obtained empty or expired token") - } - - cc.token = token - return nil -} - -func (cc *directorClient) executeDirectorGraphQLCall(directorQuery string, tenant string, response interface{}) apperrors.AppError { - if cc.token.EmptyOrExpired() { - log.Infof("Refreshing token to access Director Service") - if err := cc.getToken(); err != nil { - return err - } - } - - req := gcli.NewRequest(directorQuery) - req.Header.Set(AuthorizationHeader, fmt.Sprintf("Bearer %s", cc.token.AccessToken)) - req.Header.Set(TenantHeader, tenant) - - if err := cc.gqlClient.Do(req, response); err != nil { - if egErr, ok := err.(gcli.ExtendedError); ok { - return mapDirectorErrorToProvisionerError(egErr).Append("Failed to execute GraphQL request to Director") - } - return apperrors.Internal("Failed to execute GraphQL request to Director: %v", err) - } - - return nil -} - -func mapDirectorErrorToProvisionerError(egErr gcli.ExtendedError) apperrors.AppError { - errorCodeValue, present := egErr.Extensions()["error_code"] - if !present { - return apperrors.Internal("Failed to read the error code from the error response. Original error: %v", egErr) - } - errorCode, ok := errorCodeValue.(float64) - if !ok { - return apperrors.Internal("Failed to cast the error code from the error response. Original error: %v", egErr) - } - - var err apperrors.AppError - reason := apperrors.ErrReason(directorApperrors.ErrorType(errorCode).String()) - - switch directorApperrors.ErrorType(errorCode) { - case directorApperrors.InternalError, directorApperrors.UnknownError: - err = apperrors.Internal(egErr.Error()) - case directorApperrors.InsufficientScopes, directorApperrors.Unauthorized: - err = apperrors.BadGateway(egErr.Error()) - case directorApperrors.NotFound, directorApperrors.NotUnique, directorApperrors.InvalidData, - directorApperrors.InvalidOperation: - err = apperrors.BadRequest(egErr.Error()) - case directorApperrors.TenantRequired, directorApperrors.TenantNotFound: - err = apperrors.InvalidTenant(egErr.Error()) - default: - err = apperrors.Internal("Did not recognize the error code from the error response. Original error: %v", egErr) - } - - return err.SetComponent(apperrors.ErrCompassDirector).SetReason(reason) -} diff --git a/components/provisioner/internal/director/directorclient_test.go b/components/provisioner/internal/director/directorclient_test.go deleted file mode 100644 index 957f76cff1..0000000000 --- a/components/provisioner/internal/director/directorclient_test.go +++ /dev/null @@ -1,1174 +0,0 @@ -package director - -import ( - "errors" - "fmt" - "testing" - "time" - - directorApperrors "github.com/kyma-incubator/compass/components/director/pkg/apperrors" - "github.com/kyma-incubator/compass/components/director/pkg/graphql" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/kyma-project/control-plane/components/provisioner/internal/apperrors" - gql "github.com/kyma-project/control-plane/components/provisioner/internal/graphql" - "github.com/kyma-project/control-plane/components/provisioner/internal/oauth" - oauthmocks "github.com/kyma-project/control-plane/components/provisioner/internal/oauth/mocks" - "github.com/kyma-project/control-plane/components/provisioner/internal/util" - "github.com/kyma-project/control-plane/components/provisioner/pkg/gqlschema" - gcli "github.com/kyma-project/control-plane/components/provisioner/third_party/machinebox/graphql" -) - -const ( - runtimeTestingID = "test-runtime-ID-12345" - runtimeTestingName = "Runtime Test name" - validTokenValue = "12345" - tenantValue = "3e64ebae-38b5-46a0-b1ed-9ccee153a0ae" - oneTimeToken = "54321" - connectorURL = "https://kyma.cx/connector/graphql" - - expectedRegisterRuntimeQuery = `mutation { - result: registerRuntime(in: { - name: "Runtime Test name", - description: "runtime description", - }) { id } }` - - expectedDeleteRuntimeQuery = `mutation { - result: unregisterRuntime(id: "test-runtime-ID-12345") { - id -}}` - - expectedOneTimeTokenQuery = `mutation { - result: requestOneTimeTokenForRuntime(id: "test-runtime-ID-12345") { - token connectorURL -}}` - - expectedGetRuntimeQuery = `query { - result: runtime(id: "test-runtime-ID-12345") { - id name description labels -}}` - - expectedUpdateMutation = `mutation { - result: updateRuntime(id: "test-runtime-ID-12345" in: { - name: "Runtime Test name", - labels: {label1:"something",label2:"something2",}, - statusCondition: CONNECTED, - }) { - id -}}` -) - -var ( - futureExpirationTime = time.Now().Add(time.Duration(60) * time.Minute).Unix() - passedExpirationTime = time.Now().Add(time.Duration(60) * time.Minute * -1).Unix() -) - -func TestDirectorClient_RuntimeRegistering(t *testing.T) { - expectedRequest := gcli.NewRequest(expectedRegisterRuntimeQuery) - expectedRequest.Header.Set(AuthorizationHeader, fmt.Sprintf("Bearer %s", validTokenValue)) - expectedRequest.Header.Set(TenantHeader, tenantValue) - - inputDescription := "runtime description" - - runtimeInput := &gqlschema.RuntimeInput{ - Name: runtimeTestingName, - Description: &inputDescription, - } - - t.Run("Should register runtime and return new runtime ID when the Director access token is valid", func(t *testing.T) { - // given - responseDescription := "runtime description" - expectedResponse := &graphql.Runtime{ - ID: runtimeTestingID, - Name: runtimeTestingName, - Description: &responseDescription, - } - - expectedID := runtimeTestingID - - gqlClient := gql.NewQueryAssertClient(t, nil, []*gcli.Request{expectedRequest}, func(t *testing.T, r interface{}) { - cfg, ok := r.(*CreateRuntimeResponse) - require.True(t, ok) - assert.Empty(t, cfg.Result) - cfg.Result = expectedResponse - }) - - token := oauth.Token{ - AccessToken: validTokenValue, - Expiration: futureExpirationTime, - } - - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(token, nil) - - configClient := NewDirectorClient(gqlClient, mockedOAuthClient) - - // when - receivedRuntimeID, err := configClient.CreateRuntime(runtimeInput, tenantValue) - - // then - assert.NoError(t, err) - assert.Equal(t, expectedID, receivedRuntimeID) - }) - - t.Run("Should not register runtime and return an error when the Director access token is empty", func(t *testing.T) { - // given - token := oauth.Token{ - AccessToken: "", - Expiration: futureExpirationTime, - } - - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(token, nil) - - configClient := NewDirectorClient(nil, mockedOAuthClient) - - // when - receivedRuntimeID, err := configClient.CreateRuntime(runtimeInput, tenantValue) - - // then - assert.Error(t, err) - assert.Empty(t, receivedRuntimeID) - }) - - t.Run("Should not register runtime and return an error when the Director access token is expired", func(t *testing.T) { - // given - expiredToken := oauth.Token{ - AccessToken: validTokenValue, - Expiration: passedExpirationTime, - } - - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(expiredToken, nil) - - configClient := NewDirectorClient(nil, mockedOAuthClient) - - // when - receivedRuntimeID, err := configClient.CreateRuntime(runtimeInput, tenantValue) - - // then - assert.Error(t, err) - assert.Empty(t, receivedRuntimeID) - }) - - t.Run("Should not register Runtime and return error when the client fails to get an access token for Director", func(t *testing.T) { - // given - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(oauth.Token{}, apperrors.Internal("Failed token error")) - - configClient := NewDirectorClient(nil, mockedOAuthClient) - - // when - receivedRuntimeID, err := configClient.CreateRuntime(runtimeInput, tenantValue) - - // then - assert.Error(t, err) - util.CheckErrorType(t, err, apperrors.CodeInternal) - assert.Empty(t, receivedRuntimeID) - }) - - t.Run("Should return error when the result of the call to Director service is nil", func(t *testing.T) { - // given - validToken := oauth.Token{ - AccessToken: validTokenValue, - Expiration: futureExpirationTime, - } - - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(validToken, nil) - - gqlClient := gql.NewQueryAssertClient(t, nil, []*gcli.Request{expectedRequest}, func(t *testing.T, r interface{}) { - cfg, ok := r.(*CreateRuntimeResponse) - require.True(t, ok) - assert.Empty(t, cfg.Result) - cfg.Result = nil - }) - - configClient := NewDirectorClient(gqlClient, mockedOAuthClient) - - // when - receivedRuntimeID, err := configClient.CreateRuntime(runtimeInput, tenantValue) - - // then - assert.Error(t, err) - assert.Empty(t, receivedRuntimeID) - }) - - t.Run("Should return error when Director fails to register Runtime ", func(t *testing.T) { - // given - validToken := oauth.Token{ - AccessToken: validTokenValue, - Expiration: futureExpirationTime, - } - - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(validToken, nil) - - gqlClient := gql.NewQueryAssertClient(t, errors.New("error"), []*gcli.Request{expectedRequest}, func(t *testing.T, r interface{}) { - cfg, ok := r.(*CreateRuntimeResponse) - require.True(t, ok) - assert.Empty(t, cfg.Result) - cfg.Result = nil - }) - - configClient := NewDirectorClient(gqlClient, mockedOAuthClient) - - // when - receivedRuntimeID, err := configClient.CreateRuntime(runtimeInput, tenantValue) - - // then - assert.Error(t, err) - assert.Empty(t, receivedRuntimeID) - }) -} - -func TestDirectorClient_RuntimeUnregistering(t *testing.T) { - expectedRequest := gcli.NewRequest(expectedDeleteRuntimeQuery) - expectedRequest.Header.Set(AuthorizationHeader, fmt.Sprintf("Bearer %s", validTokenValue)) - expectedRequest.Header.Set(TenantHeader, tenantValue) - - t.Run("Should unregister runtime of given ID and return no error when the Director access token is valid", func(t *testing.T) { - // given - responseDescription := "runtime description" - expectedResponse := &graphql.Runtime{ - ID: runtimeTestingID, - Name: runtimeTestingName, - Description: &responseDescription, - } - - gqlClient := gql.NewQueryAssertClient(t, nil, []*gcli.Request{expectedRequest}, func(t *testing.T, r interface{}) { - cfg, ok := r.(*DeleteRuntimeResponse) - require.True(t, ok) - assert.Empty(t, cfg.Result) - cfg.Result = expectedResponse - }) - - validToken := oauth.Token{ - AccessToken: validTokenValue, - Expiration: futureExpirationTime, - } - - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(validToken, nil) - - configClient := NewDirectorClient(gqlClient, mockedOAuthClient) - - // when - err := configClient.DeleteRuntime(runtimeTestingID, tenantValue) - - // then - assert.NoError(t, err) - }) - - t.Run("Should not unregister runtime and return an error when the Director access token is empty", func(t *testing.T) { - // given - emptyToken := oauth.Token{ - AccessToken: "", - Expiration: futureExpirationTime, - } - - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(emptyToken, nil) - - configClient := NewDirectorClient(nil, mockedOAuthClient) - - // when - err := configClient.DeleteRuntime(runtimeTestingID, tenantValue) - - // then - assert.Error(t, err) - }) - - t.Run("Should not unregister register runtime and return an error when the Director access token is expired", func(t *testing.T) { - // given - expiredToken := oauth.Token{ - AccessToken: validTokenValue, - Expiration: passedExpirationTime, - } - - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(expiredToken, nil) - - configClient := NewDirectorClient(nil, mockedOAuthClient) - - // when - err := configClient.DeleteRuntime(runtimeTestingID, tenantValue) - - // then - assert.Error(t, err) - }) - - t.Run("Should not unregister Runtime and return error when the client fails to get an access token for Director", func(t *testing.T) { - // given - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(oauth.Token{}, apperrors.Internal("Failed token error")) - - configClient := NewDirectorClient(nil, mockedOAuthClient) - - // when - err := configClient.DeleteRuntime(runtimeTestingID, tenantValue) - - // then - assert.Error(t, err) - util.CheckErrorType(t, err, apperrors.CodeInternal) - }) - - t.Run("Should return error when the result of the call to Director service is nil", func(t *testing.T) { - // given - validToken := oauth.Token{ - AccessToken: validTokenValue, - Expiration: futureExpirationTime, - } - - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(validToken, nil) - - // given - gqlClient := gql.NewQueryAssertClient(t, nil, []*gcli.Request{expectedRequest}, func(t *testing.T, r interface{}) { - cfg, ok := r.(*DeleteRuntimeResponse) - require.True(t, ok) - assert.Empty(t, cfg.Result) - cfg.Result = nil - }) - - configClient := NewDirectorClient(gqlClient, mockedOAuthClient) - - // when - err := configClient.DeleteRuntime(runtimeTestingID, tenantValue) - - // then - assert.Error(t, err) - }) - - t.Run("Should return error when Director fails to delete Runtime", func(t *testing.T) { - // given - gqlClient := gql.NewQueryAssertClient(t, errors.New("error"), []*gcli.Request{expectedRequest}, func(t *testing.T, r interface{}) { - cfg, ok := r.(*DeleteRuntimeResponse) - require.True(t, ok) - assert.Empty(t, cfg.Result) - cfg.Result = nil - }) - - validToken := oauth.Token{ - AccessToken: validTokenValue, - Expiration: futureExpirationTime, - } - - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(validToken, nil) - - configClient := NewDirectorClient(gqlClient, mockedOAuthClient) - - // when - err := configClient.DeleteRuntime(runtimeTestingID, tenantValue) - - // then - assert.Error(t, err) - }) - - // unusual and strange case - t.Run("Should return error when Director returns bad ID after Deleting", func(t *testing.T) { - // given - responseDescription := "runtime description" - expectedResponse := &graphql.Runtime{ - ID: "BadId", - Name: runtimeTestingName, - Description: &responseDescription, - } - - gqlClient := gql.NewQueryAssertClient(t, nil, []*gcli.Request{expectedRequest}, func(t *testing.T, r interface{}) { - cfg, ok := r.(*DeleteRuntimeResponse) - require.True(t, ok) - assert.Empty(t, cfg.Result) - cfg.Result = expectedResponse - }) - - validToken := oauth.Token{ - AccessToken: validTokenValue, - Expiration: futureExpirationTime, - } - - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(validToken, nil) - - configClient := NewDirectorClient(gqlClient, mockedOAuthClient) - - // when - err := configClient.DeleteRuntime(runtimeTestingID, tenantValue) - - // then - assert.Error(t, err) - }) -} - -func TestDirectorClient_GetConnectionToken(t *testing.T) { - expectedRequest := gcli.NewRequest(expectedOneTimeTokenQuery) - expectedRequest.Header.Set(AuthorizationHeader, fmt.Sprintf("Bearer %s", validTokenValue)) - expectedRequest.Header.Set(TenantHeader, tenantValue) - - t.Run("Should return OneTimeToken when Oauth Token is valid", func(t *testing.T) { - // given - expectedResponse := &graphql.OneTimeTokenForRuntimeExt{ - OneTimeTokenForRuntime: graphql.OneTimeTokenForRuntime{ - TokenWithURL: graphql.TokenWithURL{ - Token: oneTimeToken, - ConnectorURL: connectorURL, - }, - }, - } - - gqlClient := gql.NewQueryAssertClient(t, nil, []*gcli.Request{expectedRequest}, func(t *testing.T, r interface{}) { - cfg, ok := r.(*OneTimeTokenResponse) - require.True(t, ok) - assert.Empty(t, cfg.Result) - cfg.Result = expectedResponse - }) - - token := oauth.Token{ - AccessToken: validTokenValue, - Expiration: futureExpirationTime, - } - - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(token, nil) - - configClient := NewDirectorClient(gqlClient, mockedOAuthClient) - - // when - receivedOneTimeToken, err := configClient.GetConnectionToken(runtimeTestingID, tenantValue) - - // then - require.NoError(t, err) - require.NotEmpty(t, receivedOneTimeToken) - assert.Equal(t, oneTimeToken, receivedOneTimeToken.Token) - assert.Equal(t, connectorURL, receivedOneTimeToken.ConnectorURL) - }) - - t.Run("Should return error when Oauth Token is empty", func(t *testing.T) { - // given - token := oauth.Token{ - AccessToken: "", - Expiration: futureExpirationTime, - } - - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(token, nil) - - configClient := NewDirectorClient(nil, mockedOAuthClient) - - // when - receivedOneTimeToken, err := configClient.GetConnectionToken(runtimeTestingID, tenantValue) - - // then - require.Error(t, err) - require.Empty(t, receivedOneTimeToken) - }) - - t.Run("Should return error when Oauth Token is expired", func(t *testing.T) { - // given - token := oauth.Token{ - AccessToken: validTokenValue, - Expiration: passedExpirationTime, - } - - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(token, nil) - - configClient := NewDirectorClient(nil, mockedOAuthClient) - - // when - receivedOneTimeToken, err := configClient.GetConnectionToken(runtimeTestingID, tenantValue) - - // then - require.Error(t, err) - require.Empty(t, receivedOneTimeToken) - }) - - t.Run("Should return error when Director call returns nil reponse", func(t *testing.T) { - // given - gqlClient := gql.NewQueryAssertClient(t, nil, []*gcli.Request{expectedRequest}, func(t *testing.T, r interface{}) { - cfg, ok := r.(*OneTimeTokenResponse) - require.True(t, ok) - assert.Empty(t, cfg.Result) - }) - - token := oauth.Token{ - AccessToken: validTokenValue, - Expiration: futureExpirationTime, - } - - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(token, nil) - - configClient := NewDirectorClient(gqlClient, mockedOAuthClient) - - // when - receivedOneTimeToken, err := configClient.GetConnectionToken(runtimeTestingID, tenantValue) - - // then - require.Error(t, err) - require.Empty(t, receivedOneTimeToken) - }) -} - -func TestDirectorClient_GetRuntime(t *testing.T) { - expectedRequest := gcli.NewRequest(expectedGetRuntimeQuery) - expectedRequest.Header.Set(AuthorizationHeader, fmt.Sprintf("Bearer %s", validTokenValue)) - expectedRequest.Header.Set(TenantHeader, tenantValue) - - t.Run("should return Runtime", func(t *testing.T) { - // given - expectedResponse := &graphql.RuntimeExt{ - Runtime: graphql.Runtime{ - ID: runtimeTestingID, - Name: runtimeTestingName, - }, - } - - gqlClient := gql.NewQueryAssertClient(t, nil, []*gcli.Request{expectedRequest}, func(t *testing.T, r interface{}) { - cfg, ok := r.(*GetRuntimeResponse) - require.True(t, ok) - assert.Empty(t, cfg.Result) - cfg.Result = expectedResponse - }) - - token := oauth.Token{ - AccessToken: validTokenValue, - Expiration: futureExpirationTime, - } - - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(token, nil) - - configClient := NewDirectorClient(gqlClient, mockedOAuthClient) - - // when - runtime, err := configClient.GetRuntime(runtimeTestingID, tenantValue) - - // then - require.NoError(t, err) - assert.Equal(t, expectedResponse.Name, runtime.Name) - assert.Equal(t, expectedResponse.ID, runtime.ID) - }) - - t.Run("should return error when access token is empty", func(t *testing.T) { - // given - emptyToken := oauth.Token{ - AccessToken: "", - Expiration: futureExpirationTime, - } - - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(emptyToken, nil) - - configClient := NewDirectorClient(nil, mockedOAuthClient) - - // when - runtime, err := configClient.GetRuntime(runtimeTestingID, tenantValue) - - // then - assert.Error(t, err) - assert.Empty(t, runtime) - }) - - t.Run("should return error when Director returns nil response", func(t *testing.T) { - // given - gqlClient := gql.NewQueryAssertClient(t, nil, []*gcli.Request{expectedRequest}, func(t *testing.T, r interface{}) { - cfg, ok := r.(*GetRuntimeResponse) - require.True(t, ok) - assert.Empty(t, cfg.Result) - cfg.Result = nil - }) - - token := oauth.Token{ - AccessToken: validTokenValue, - Expiration: futureExpirationTime, - } - - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(token, nil) - - configClient := NewDirectorClient(gqlClient, mockedOAuthClient) - - // when - runtime, err := configClient.GetRuntime(runtimeTestingID, tenantValue) - - // then - require.Error(t, err) - assert.Empty(t, runtime) - }) - - t.Run("should return error when Director fails to get Runtime", func(t *testing.T) { - // given - gqlClient := gql.NewQueryAssertClient(t, errors.New("error"), []*gcli.Request{expectedRequest}, func(t *testing.T, r interface{}) { - cfg, ok := r.(*GetRuntimeResponse) - require.True(t, ok) - assert.Empty(t, cfg.Result) - cfg.Result = nil - }) - - token := oauth.Token{ - AccessToken: validTokenValue, - Expiration: futureExpirationTime, - } - - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(token, nil) - - configClient := NewDirectorClient(gqlClient, mockedOAuthClient) - - // when - runtime, err := configClient.GetRuntime(runtimeTestingID, tenantValue) - - // then - require.Error(t, err) - assert.Empty(t, runtime) - }) -} - -func TestDirectorClient_UpdateRuntime(t *testing.T) { - expectedRequest := gcli.NewRequest(expectedUpdateMutation) - expectedRequest.Header.Set(AuthorizationHeader, fmt.Sprintf("Bearer %s", validTokenValue)) - expectedRequest.Header.Set(TenantHeader, tenantValue) - - t.Run("should update Runtime", func(t *testing.T) { - // given - conditionConnected := graphql.RuntimeStatusConditionConnected - runtimeInput := &graphql.RuntimeUpdateInput{ - Name: runtimeTestingName, - Labels: graphql.Labels{ - "label1": "something", - "label2": "something2", - }, - StatusCondition: &conditionConnected, - } - - expectedResponse := &graphql.Runtime{ - ID: runtimeTestingID, - Name: runtimeTestingName, - } - - gqlClient := gql.NewQueryAssertClient(t, nil, []*gcli.Request{expectedRequest}, func(t *testing.T, r interface{}) { - cfg, ok := r.(*UpdateRuntimeResponse) - require.True(t, ok) - assert.Empty(t, cfg.Result) - cfg.Result = expectedResponse - }) - - token := oauth.Token{ - AccessToken: validTokenValue, - Expiration: futureExpirationTime, - } - - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(token, nil) - - configClient := NewDirectorClient(gqlClient, mockedOAuthClient) - - // when - err := configClient.UpdateRuntime(runtimeTestingID, runtimeInput, tenantValue) - - // then - require.NoError(t, err) - }) - - t.Run("should return error when access token is empty", func(t *testing.T) { - // given - emptyToken := oauth.Token{ - AccessToken: "", - Expiration: futureExpirationTime, - } - - conditionConnected := graphql.RuntimeStatusConditionConnected - runtimeInput := &graphql.RuntimeUpdateInput{ - Name: runtimeTestingName, - Labels: graphql.Labels{ - "label1": "something", - "label2": "something2", - }, - StatusCondition: &conditionConnected, - } - - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(emptyToken, nil) - - configClient := NewDirectorClient(nil, mockedOAuthClient) - - // when - err := configClient.UpdateRuntime(runtimeTestingID, runtimeInput, tenantValue) - - // then - assert.Error(t, err) - }) - - t.Run("should return error when Director returns nil response", func(t *testing.T) { - // given - conditionConnected := graphql.RuntimeStatusConditionConnected - runtimeInput := &graphql.RuntimeUpdateInput{ - Name: runtimeTestingName, - Labels: graphql.Labels{ - "label1": "something", - "label2": "something2", - }, - StatusCondition: &conditionConnected, - } - - gqlClient := gql.NewQueryAssertClient(t, nil, []*gcli.Request{expectedRequest}, func(t *testing.T, r interface{}) { - cfg, ok := r.(*UpdateRuntimeResponse) - require.True(t, ok) - assert.Empty(t, cfg.Result) - cfg.Result = nil - }) - - token := oauth.Token{ - AccessToken: validTokenValue, - Expiration: futureExpirationTime, - } - - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(token, nil) - - configClient := NewDirectorClient(gqlClient, mockedOAuthClient) - - // when - err := configClient.UpdateRuntime(runtimeTestingID, runtimeInput, tenantValue) - - // then - require.Error(t, err) - }) -} - -func TestDirectorClient_SetRuntimeStatusCondition(t *testing.T) { - expectedFirstRequest := gcli.NewRequest(expectedGetRuntimeQuery) - expectedFirstRequest.Header.Set(AuthorizationHeader, fmt.Sprintf("Bearer %s", validTokenValue)) - expectedFirstRequest.Header.Set(TenantHeader, tenantValue) - - statusCondition := graphql.RuntimeStatusConditionConnected - - expectedSecondRequest := gcli.NewRequest(expectedUpdateMutation) - expectedSecondRequest.Header.Set(AuthorizationHeader, fmt.Sprintf("Bearer %s", validTokenValue)) - expectedSecondRequest.Header.Set(TenantHeader, tenantValue) - - t.Run("should set runtime status condition", func(t *testing.T) { - expectedGetResponse := &graphql.RuntimeExt{ - Runtime: graphql.Runtime{ - ID: runtimeTestingID, - Name: runtimeTestingName, - }, - Labels: graphql.Labels{ - "label1": "something", - "label2": "something2", - }, - } - - getFunction := func(t *testing.T, r interface{}) { - cfg, ok := r.(*GetRuntimeResponse) - require.True(t, ok) - assert.Empty(t, cfg.Result) - cfg.Result = expectedGetResponse - } - - expectedUpdateResponse := &graphql.Runtime{ - ID: runtimeTestingID, - Name: runtimeTestingName, - } - - updateFunction := func(t *testing.T, r interface{}) { - cfg, ok := r.(*UpdateRuntimeResponse) - require.True(t, ok) - assert.Empty(t, cfg.Result) - cfg.Result = expectedUpdateResponse - } - - gqlClient := gql.NewQueryAssertClient(t, nil, []*gcli.Request{expectedFirstRequest, expectedSecondRequest}, getFunction, updateFunction) - - token := oauth.Token{ - AccessToken: validTokenValue, - Expiration: futureExpirationTime, - } - - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(token, nil) - - configClient := NewDirectorClient(gqlClient, mockedOAuthClient) - - // when - err := configClient.SetRuntimeStatusCondition(runtimeTestingID, statusCondition, tenantValue) - - // then - require.NoError(t, err) - }) - - t.Run("should return error when GetRuntime returns error", func(t *testing.T) { - getFunction := func(t *testing.T, r interface{}) { - cfg, ok := r.(*GetRuntimeResponse) - require.True(t, ok) - assert.Empty(t, cfg.Result) - cfg.Result = nil - } - - expectedUpdateResponse := &graphql.Runtime{ - ID: runtimeTestingID, - Name: runtimeTestingName, - } - - updateFunction := func(t *testing.T, r interface{}) { - cfg, ok := r.(*UpdateRuntimeResponse) - require.True(t, ok) - assert.Empty(t, cfg.Result) - cfg.Result = expectedUpdateResponse - } - - gqlClient := gql.NewQueryAssertClient(t, nil, []*gcli.Request{expectedFirstRequest, expectedSecondRequest}, getFunction, updateFunction) - - token := oauth.Token{ - AccessToken: validTokenValue, - Expiration: futureExpirationTime, - } - - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(token, nil) - - configClient := NewDirectorClient(gqlClient, mockedOAuthClient) - - // when - err := configClient.SetRuntimeStatusCondition(runtimeTestingID, statusCondition, tenantValue) - - // then - require.Error(t, err) - }) - - t.Run("should return error when UpdateRuntime returns error", func(t *testing.T) { - expectedGetResponse := &graphql.RuntimeExt{ - Runtime: graphql.Runtime{ - ID: runtimeTestingID, - Name: runtimeTestingName, - }, - Labels: graphql.Labels{ - "label1": "something", - "label2": "something2", - }, - } - - getFunction := func(t *testing.T, r interface{}) { - cfg, ok := r.(*GetRuntimeResponse) - require.True(t, ok) - assert.Empty(t, cfg.Result) - cfg.Result = expectedGetResponse - } - - updateFunction := func(t *testing.T, r interface{}) { - cfg, ok := r.(*UpdateRuntimeResponse) - require.True(t, ok) - assert.Empty(t, cfg.Result) - cfg.Result = nil - } - - gqlClient := gql.NewQueryAssertClient(t, nil, []*gcli.Request{expectedFirstRequest, expectedSecondRequest}, getFunction, updateFunction) - - token := oauth.Token{ - AccessToken: validTokenValue, - Expiration: futureExpirationTime, - } - - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(token, nil) - - configClient := NewDirectorClient(gqlClient, mockedOAuthClient) - - // when - err := configClient.SetRuntimeStatusCondition(runtimeTestingID, statusCondition, tenantValue) - - // then - require.Error(t, err) - }) -} - -func TestDirectorClient_RuntimeExists(t *testing.T) { - expectedRequest := gcli.NewRequest(expectedGetRuntimeQuery) - expectedRequest.Header.Set(AuthorizationHeader, fmt.Sprintf("Bearer %s", validTokenValue)) - expectedRequest.Header.Set(TenantHeader, tenantValue) - - t.Run("should return true when Runtime exists", func(t *testing.T) { - // given - expectedResponse := &graphql.RuntimeExt{ - Runtime: graphql.Runtime{ - ID: runtimeTestingID, - Name: runtimeTestingName, - }, - } - - gqlClient := gql.NewQueryAssertClient(t, nil, []*gcli.Request{expectedRequest}, func(t *testing.T, r interface{}) { - cfg, ok := r.(*GetRuntimeResponse) - require.True(t, ok) - assert.Empty(t, cfg.Result) - cfg.Result = expectedResponse - }) - - token := oauth.Token{ - AccessToken: validTokenValue, - Expiration: futureExpirationTime, - } - - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(token, nil) - - configClient := NewDirectorClient(gqlClient, mockedOAuthClient) - - // when - exists, err := configClient.RuntimeExists(runtimeTestingID, tenantValue) - - // then - require.NoError(t, err) - assert.True(t, exists) - }) - - t.Run("should return false when Runtime does not exist", func(t *testing.T) { - // given - gqlClient := gql.NewQueryAssertClient(t, nil, []*gcli.Request{expectedRequest}, func(t *testing.T, r interface{}) { - cfg, ok := r.(*GetRuntimeResponse) - require.True(t, ok) - assert.Empty(t, cfg.Result) - cfg.Result = nil - }) - - token := oauth.Token{ - AccessToken: validTokenValue, - Expiration: futureExpirationTime, - } - - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(token, nil) - - configClient := NewDirectorClient(gqlClient, mockedOAuthClient) - - // when - exists, err := configClient.RuntimeExists(runtimeTestingID, tenantValue) - - // then - require.NoError(t, err) - assert.False(t, exists) - }) - - t.Run("should return error when director returns error", func(t *testing.T) { - // given - directorError := &testGraphQLError{ - Message: "some error", - ErrorExtensions: map[string]interface{}{"error_code": float64(directorApperrors.InternalError)}, - } - - gqlClient := gql.NewQueryAssertClient(t, directorError, []*gcli.Request{expectedRequest}, func(t *testing.T, r interface{}) { - cfg, ok := r.(*GetRuntimeResponse) - require.True(t, ok) - assert.Empty(t, cfg.Result) - cfg.Result = nil - }) - - token := oauth.Token{ - AccessToken: validTokenValue, - Expiration: futureExpirationTime, - } - - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(token, nil) - - configClient := NewDirectorClient(gqlClient, mockedOAuthClient) - - // when - exists, err := configClient.RuntimeExists(runtimeTestingID, tenantValue) - - // then - require.Error(t, err) - assert.False(t, exists) - }) - - t.Run("should return false when director returns TenantNotFound error", func(t *testing.T) { - // given - directorError := &testGraphQLError{ - Message: "some error", - ErrorExtensions: map[string]interface{}{"error_code": float64(directorApperrors.TenantNotFound)}, - } - - gqlClient := gql.NewQueryAssertClient(t, directorError, []*gcli.Request{expectedRequest}, func(t *testing.T, r interface{}) { - cfg, ok := r.(*GetRuntimeResponse) - require.True(t, ok) - assert.Empty(t, cfg.Result) - cfg.Result = nil - }) - - token := oauth.Token{ - AccessToken: validTokenValue, - Expiration: futureExpirationTime, - } - - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(token, nil) - - configClient := NewDirectorClient(gqlClient, mockedOAuthClient) - - // when - exists, err := configClient.RuntimeExists(runtimeTestingID, tenantValue) - - // then - require.NoError(t, err) - assert.False(t, exists) - }) -} - -type testGraphQLError struct { - Message string - ErrorExtensions map[string]interface{} -} - -func (e testGraphQLError) Error() string { - return "graphql: " + e.Message -} - -func (e testGraphQLError) Extensions() map[string]interface{} { - return e.ErrorExtensions -} - -func TestDirectorClient_MapDirectorErrors(t *testing.T) { - // given - expectedRequest := gcli.NewRequest(expectedRegisterRuntimeQuery) - expectedRequest.Header.Set(AuthorizationHeader, fmt.Sprintf("Bearer %s", validTokenValue)) - expectedRequest.Header.Set(TenantHeader, tenantValue) - - inputDescription := "runtime description" - runtimeInput := &gqlschema.RuntimeInput{ - Name: runtimeTestingName, - Description: &inputDescription, - } - - token := oauth.Token{ - AccessToken: validTokenValue, - Expiration: futureExpirationTime, - } - - testcases := []struct { - description string - directorErrorExtensions map[string]interface{} - provisionerErrorCode apperrors.ErrCode - internalErrorCode apperrors.CauseCode - provisionerErrorMessage string - }{ - { - "Should map Director Internal Error to Provisioner Internal Error", - map[string]interface{}{"error_code": float64(directorApperrors.InternalError)}, - apperrors.CodeInternal, - apperrors.Unknown, - "Failed to register runtime in Director. Request failed, Failed to execute GraphQL request to Director, graphql: some error", - }, - { - "Should map Director Unknown Error to Provisioner Internal Error", - map[string]interface{}{"error_code": float64(directorApperrors.UnknownError)}, - apperrors.CodeInternal, - apperrors.Unknown, - "Failed to register runtime in Director. Request failed, Failed to execute GraphQL request to Director, graphql: some error", - }, - { - "Should map Director Insufficient Scopes Error to Provisioner Bad Gateway Error", - map[string]interface{}{"error_code": float64(directorApperrors.InsufficientScopes)}, - apperrors.CodeBadGateway, - apperrors.Unknown, - "Failed to register runtime in Director. Request failed, Failed to execute GraphQL request to Director, graphql: some error", - }, - { - "Should map Director Unauthorized Error to Provisioner Bad Gateway Error", - map[string]interface{}{"error_code": float64(directorApperrors.Unauthorized)}, - apperrors.CodeBadGateway, - apperrors.Unknown, - "Failed to register runtime in Director. Request failed, Failed to execute GraphQL request to Director, graphql: some error", - }, - { - "Should map Director Not Found Error to Provisioner Bad Request Error", - map[string]interface{}{"error_code": float64(directorApperrors.NotFound)}, - apperrors.CodeBadRequest, - apperrors.Unknown, - "Failed to register runtime in Director. Request failed, Failed to execute GraphQL request to Director, graphql: some error", - }, - { - "Should map Director Not Unique Error to Provisioner Bad Request Error", - map[string]interface{}{"error_code": float64(directorApperrors.NotUnique)}, - apperrors.CodeBadRequest, - apperrors.Unknown, - "Failed to register runtime in Director. Request failed, Failed to execute GraphQL request to Director, graphql: some error", - }, - { - "Should map Director Invalid Data Error to Provisioner Bad Request Error", - map[string]interface{}{"error_code": float64(directorApperrors.InvalidData)}, - apperrors.CodeBadRequest, - apperrors.Unknown, - "Failed to register runtime in Director. Request failed, Failed to execute GraphQL request to Director, graphql: some error", - }, - { - "Should map Director Tenant Required Error to Provisioner Bad Request Error", - map[string]interface{}{"error_code": float64(directorApperrors.TenantRequired)}, - apperrors.CodeBadRequest, - apperrors.TenantNotFound, - "Failed to register runtime in Director. Request failed, Failed to execute GraphQL request to Director, graphql: some error", - }, - { - "Should map Director Tenant Not Found Error to Provisioner Bad Request Error", - map[string]interface{}{"error_code": float64(directorApperrors.TenantNotFound)}, - apperrors.CodeBadRequest, - apperrors.TenantNotFound, - "Failed to register runtime in Director. Request failed, Failed to execute GraphQL request to Director, graphql: some error", - }, - { - "Should map Director Invalid Operation Error to Provisioner Bad Request Error", - map[string]interface{}{"error_code": float64(directorApperrors.InvalidOperation)}, - apperrors.CodeBadRequest, - apperrors.Unknown, - "Failed to register runtime in Director. Request failed, Failed to execute GraphQL request to Director, graphql: some error", - }, - { - "Should return Internal Error if failed to find error code in the Director Error", - map[string]interface{}{"something_else": float64(directorApperrors.InvalidOperation)}, - apperrors.CodeInternal, - apperrors.Unknown, - "Failed to register runtime in Director. Request failed, Failed to execute GraphQL request to Director, Failed to read the error code from the error response. Original error: graphql: some error", - }, - { - "Should return Internal Error if failed to cast error code from the Director Error", - map[string]interface{}{"error_code": "not a float64"}, - apperrors.CodeInternal, - apperrors.Unknown, - "Failed to register runtime in Director. Request failed, Failed to execute GraphQL request to Director, Failed to cast the error code from the error response. Original error: graphql: some error", - }, - { - "Should return Internal Error if failed to recognize the Director Error code", - map[string]interface{}{"error_code": float64(123)}, - apperrors.CodeInternal, - apperrors.Unknown, - "Failed to register runtime in Director. Request failed, Failed to execute GraphQL request to Director, Did not recognize the error code from the error response. Original error: graphql: some error", - }, - } - - for _, testcase := range testcases { - t.Run(testcase.description, func(t *testing.T) { - // given - directorError := &testGraphQLError{ - Message: "some error", - ErrorExtensions: testcase.directorErrorExtensions, - } - - gqlClient := gql.NewQueryAssertClient(t, directorError, []*gcli.Request{expectedRequest}) - - mockedOAuthClient := &oauthmocks.Client{} - mockedOAuthClient.On("GetAuthorizationToken").Return(token, nil) - - directorClient := NewDirectorClient(gqlClient, mockedOAuthClient) - - // when - _, err := directorClient.CreateRuntime(runtimeInput, tenantValue) - - // then - require.Error(t, err) - assert.Equal(t, testcase.provisionerErrorCode, err.Code()) - assert.Equal(t, testcase.internalErrorCode, err.Cause()) - assert.Equal(t, testcase.provisionerErrorMessage, err.Error()) - }) - } -} diff --git a/components/provisioner/internal/director/mocks/DirectorClient.go b/components/provisioner/internal/director/mocks/DirectorClient.go deleted file mode 100644 index 558837ca04..0000000000 --- a/components/provisioner/internal/director/mocks/DirectorClient.go +++ /dev/null @@ -1,184 +0,0 @@ -// Code generated by mockery v2.35.2. DO NOT EDIT. - -package mocks - -import ( - apperrors "github.com/kyma-project/control-plane/components/provisioner/internal/apperrors" - - gqlschema "github.com/kyma-project/control-plane/components/provisioner/pkg/gqlschema" - - graphql "github.com/kyma-incubator/compass/components/director/pkg/graphql" - - mock "github.com/stretchr/testify/mock" -) - -// DirectorClient is an autogenerated mock type for the DirectorClient type -type DirectorClient struct { - mock.Mock -} - -// CreateRuntime provides a mock function with given fields: config, tenant -func (_m *DirectorClient) CreateRuntime(config *gqlschema.RuntimeInput, tenant string) (string, apperrors.AppError) { - ret := _m.Called(config, tenant) - - var r0 string - var r1 apperrors.AppError - if rf, ok := ret.Get(0).(func(*gqlschema.RuntimeInput, string) (string, apperrors.AppError)); ok { - return rf(config, tenant) - } - if rf, ok := ret.Get(0).(func(*gqlschema.RuntimeInput, string) string); ok { - r0 = rf(config, tenant) - } else { - r0 = ret.Get(0).(string) - } - - if rf, ok := ret.Get(1).(func(*gqlschema.RuntimeInput, string) apperrors.AppError); ok { - r1 = rf(config, tenant) - } else { - if ret.Get(1) != nil { - r1 = ret.Get(1).(apperrors.AppError) - } - } - - return r0, r1 -} - -// DeleteRuntime provides a mock function with given fields: id, tenant -func (_m *DirectorClient) DeleteRuntime(id string, tenant string) apperrors.AppError { - ret := _m.Called(id, tenant) - - var r0 apperrors.AppError - if rf, ok := ret.Get(0).(func(string, string) apperrors.AppError); ok { - r0 = rf(id, tenant) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(apperrors.AppError) - } - } - - return r0 -} - -// GetConnectionToken provides a mock function with given fields: id, tenant -func (_m *DirectorClient) GetConnectionToken(id string, tenant string) (graphql.OneTimeTokenForRuntimeExt, apperrors.AppError) { - ret := _m.Called(id, tenant) - - var r0 graphql.OneTimeTokenForRuntimeExt - var r1 apperrors.AppError - if rf, ok := ret.Get(0).(func(string, string) (graphql.OneTimeTokenForRuntimeExt, apperrors.AppError)); ok { - return rf(id, tenant) - } - if rf, ok := ret.Get(0).(func(string, string) graphql.OneTimeTokenForRuntimeExt); ok { - r0 = rf(id, tenant) - } else { - r0 = ret.Get(0).(graphql.OneTimeTokenForRuntimeExt) - } - - if rf, ok := ret.Get(1).(func(string, string) apperrors.AppError); ok { - r1 = rf(id, tenant) - } else { - if ret.Get(1) != nil { - r1 = ret.Get(1).(apperrors.AppError) - } - } - - return r0, r1 -} - -// GetRuntime provides a mock function with given fields: id, tenant -func (_m *DirectorClient) GetRuntime(id string, tenant string) (graphql.RuntimeExt, apperrors.AppError) { - ret := _m.Called(id, tenant) - - var r0 graphql.RuntimeExt - var r1 apperrors.AppError - if rf, ok := ret.Get(0).(func(string, string) (graphql.RuntimeExt, apperrors.AppError)); ok { - return rf(id, tenant) - } - if rf, ok := ret.Get(0).(func(string, string) graphql.RuntimeExt); ok { - r0 = rf(id, tenant) - } else { - r0 = ret.Get(0).(graphql.RuntimeExt) - } - - if rf, ok := ret.Get(1).(func(string, string) apperrors.AppError); ok { - r1 = rf(id, tenant) - } else { - if ret.Get(1) != nil { - r1 = ret.Get(1).(apperrors.AppError) - } - } - - return r0, r1 -} - -// RuntimeExists provides a mock function with given fields: gardenerClusterName, tenant -func (_m *DirectorClient) RuntimeExists(gardenerClusterName string, tenant string) (bool, apperrors.AppError) { - ret := _m.Called(gardenerClusterName, tenant) - - var r0 bool - var r1 apperrors.AppError - if rf, ok := ret.Get(0).(func(string, string) (bool, apperrors.AppError)); ok { - return rf(gardenerClusterName, tenant) - } - if rf, ok := ret.Get(0).(func(string, string) bool); ok { - r0 = rf(gardenerClusterName, tenant) - } else { - r0 = ret.Get(0).(bool) - } - - if rf, ok := ret.Get(1).(func(string, string) apperrors.AppError); ok { - r1 = rf(gardenerClusterName, tenant) - } else { - if ret.Get(1) != nil { - r1 = ret.Get(1).(apperrors.AppError) - } - } - - return r0, r1 -} - -// SetRuntimeStatusCondition provides a mock function with given fields: id, statusCondition, tenant -func (_m *DirectorClient) SetRuntimeStatusCondition(id string, statusCondition graphql.RuntimeStatusCondition, tenant string) apperrors.AppError { - ret := _m.Called(id, statusCondition, tenant) - - var r0 apperrors.AppError - if rf, ok := ret.Get(0).(func(string, graphql.RuntimeStatusCondition, string) apperrors.AppError); ok { - r0 = rf(id, statusCondition, tenant) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(apperrors.AppError) - } - } - - return r0 -} - -// UpdateRuntime provides a mock function with given fields: id, config, tenant -func (_m *DirectorClient) UpdateRuntime(id string, config *graphql.RuntimeUpdateInput, tenant string) apperrors.AppError { - ret := _m.Called(id, config, tenant) - - var r0 apperrors.AppError - if rf, ok := ret.Get(0).(func(string, *graphql.RuntimeUpdateInput, string) apperrors.AppError); ok { - r0 = rf(id, config, tenant) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(apperrors.AppError) - } - } - - return r0 -} - -// NewDirectorClient creates a new instance of DirectorClient. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewDirectorClient(t interface { - mock.TestingT - Cleanup(func()) -}) *DirectorClient { - mock := &DirectorClient{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/components/provisioner/internal/director/model.go b/components/provisioner/internal/director/model.go deleted file mode 100644 index 8fabfa2f63..0000000000 --- a/components/provisioner/internal/director/model.go +++ /dev/null @@ -1,35 +0,0 @@ -package director - -import ( - "github.com/kyma-incubator/compass/components/director/pkg/graphql" -) - -type CreateRuntimeResponse struct { - Result *graphql.Runtime `json:"result"` -} - -type GetRuntimeResponse struct { - Result *graphql.RuntimeExt `json:"result"` -} - -type GetRuntimesResponse struct { - Result *graphql.RuntimePage `json:"result"` -} - -type DeleteRuntimeResponse struct { - Result *graphql.Runtime `json:"result"` -} - -type UpdateRuntimeResponse struct { - Result *graphql.Runtime `json:"result"` -} - -type OneTimeTokenResponse struct { - Result *graphql.OneTimeTokenForRuntimeExt `json:"result"` -} - -type RuntimeInput struct { - Name string `json:"name"` - Description *string `json:"description"` - Labels *graphql.Labels `json:"labels"` -} diff --git a/components/provisioner/internal/director/query.go b/components/provisioner/internal/director/query.go deleted file mode 100644 index 276ff2e41e..0000000000 --- a/components/provisioner/internal/director/query.go +++ /dev/null @@ -1,38 +0,0 @@ -package director - -import "fmt" - -type queryProvider struct{} - -func (qp queryProvider) createRuntimeMutation(runtimeInput string) string { - return fmt.Sprintf(`mutation { - result: registerRuntime(in: %s) { id } }`, runtimeInput) -} - -func (qp queryProvider) getRuntimeQuery(runtimeID string) string { - return fmt.Sprintf(`query { - result: runtime(id: "%s") { - id name description labels -}}`, runtimeID) -} - -func (qp queryProvider) updateRuntimeMutation(runtimeID, runtimeInput string) string { - return fmt.Sprintf(`mutation { - result: updateRuntime(id: "%s" in: %s) { - id -}}`, runtimeID, runtimeInput) -} - -func (qp queryProvider) deleteRuntimeMutation(runtimeID string) string { - return fmt.Sprintf(`mutation { - result: unregisterRuntime(id: "%s") { - id -}}`, runtimeID) -} - -func (qp queryProvider) requestOneTimeTokenMutation(runtimeID string) string { - return fmt.Sprintf(`mutation { - result: requestOneTimeTokenForRuntime(id: "%s") { - token connectorURL -}}`, runtimeID) -} From 48a300956a733d123d3827c4d54f67c8f7ff37db Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Przemys=C5=82aw=20Golicz?= Date: Tue, 19 Mar 2024 11:45:02 +0100 Subject: [PATCH 08/19] go mod fixes --- components/provisioner/go.mod | 14 ------- components/provisioner/go.sum | 38 ------------------- .../internal/operations/executor.go | 3 +- 3 files changed, 1 insertion(+), 54 deletions(-) diff --git a/components/provisioner/go.mod b/components/provisioner/go.mod index a266f059c9..0672de5411 100644 --- a/components/provisioner/go.mod +++ b/components/provisioner/go.mod @@ -32,14 +32,10 @@ require ( require ( github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 // indirect - github.com/Masterminds/goutils v1.1.1 // indirect github.com/Masterminds/semver v1.5.0 // indirect - github.com/Masterminds/semver/v3 v3.1.1 // indirect - github.com/Masterminds/sprig/v3 v3.2.2 // indirect github.com/Microsoft/go-winio v0.5.2 // indirect github.com/Microsoft/hcsshim v0.9.6 // indirect github.com/agnivade/levenshtein v1.1.0 // indirect - github.com/asaskevich/govalidator v0.0.0-20210307081110-f21760c49a8d // indirect github.com/beorn7/perks v1.0.1 // indirect github.com/cenkalti/backoff/v4 v4.1.3 // indirect github.com/cespare/xxhash/v2 v2.2.0 // indirect @@ -59,7 +55,6 @@ require ( github.com/go-openapi/jsonpointer v0.19.5 // indirect github.com/go-openapi/jsonreference v0.20.0 // indirect github.com/go-openapi/swag v0.21.1 // indirect - github.com/go-ozzo/ozzo-validation/v4 v4.3.0 // indirect github.com/gogo/protobuf v1.3.2 // indirect github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect github.com/golang/protobuf v1.5.3 // indirect @@ -70,7 +65,6 @@ require ( github.com/hashicorp/errwrap v1.1.0 // indirect github.com/hashicorp/go-multierror v1.1.1 // indirect github.com/hashicorp/golang-lru v0.5.4 // indirect - github.com/huandu/xstrings v1.3.2 // indirect github.com/imdario/mergo v0.3.12 // indirect github.com/josharian/intern v1.0.0 // indirect github.com/json-iterator/go v1.1.12 // indirect @@ -78,8 +72,6 @@ require ( github.com/magiconair/properties v1.8.6 // indirect github.com/mailru/easyjson v0.7.7 // indirect github.com/matttproud/golang_protobuf_extensions v1.0.4 // indirect - github.com/mitchellh/copystructure v1.2.0 // indirect - github.com/mitchellh/reflectwalk v1.0.2 // indirect github.com/moby/sys/mount v0.3.3 // indirect github.com/moby/sys/mountinfo v0.7.1 // indirect github.com/moby/term v0.0.0-20220808134915-39b0c02b01ae // indirect @@ -95,16 +87,10 @@ require ( github.com/prometheus/common v0.37.0 // indirect github.com/prometheus/procfs v0.8.0 // indirect github.com/russross/blackfriday/v2 v2.1.0 // indirect - github.com/shopspring/decimal v1.2.0 // indirect - github.com/spf13/cast v1.4.1 // indirect github.com/spf13/pflag v1.0.5 // indirect github.com/stretchr/objx v0.5.0 // indirect github.com/urfave/cli/v2 v2.1.1 // indirect - github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect - github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect - github.com/xeipuuv/gojsonschema v1.2.0 // indirect go.opencensus.io v0.23.0 // indirect - golang.org/x/crypto v0.16.0 // indirect golang.org/x/mod v0.14.0 // indirect golang.org/x/net v0.19.0 // indirect golang.org/x/oauth2 v0.13.0 // indirect diff --git a/components/provisioner/go.sum b/components/provisioner/go.sum index 0bfa9efb34..91faa8685b 100644 --- a/components/provisioner/go.sum +++ b/components/provisioner/go.sum @@ -44,14 +44,8 @@ github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym github.com/DATA-DOG/go-sqlmock v1.3.3/go.mod h1:f/Ixk793poVmq4qj/V1dPUg2JEAKC73Q5eFN3EC/SaM= github.com/DATA-DOG/go-sqlmock v1.5.0 h1:Shsta01QNfFxHCfpW6YH2STWB0MudeXXEWMr20OEh60= github.com/DATA-DOG/go-sqlmock v1.5.0/go.mod h1:f/Ixk793poVmq4qj/V1dPUg2JEAKC73Q5eFN3EC/SaM= -github.com/Masterminds/goutils v1.1.1 h1:5nUrii3FMTL5diU80unEVvNevw1nH4+ZV4DSLVJLSYI= -github.com/Masterminds/goutils v1.1.1/go.mod h1:8cTjp+g8YejhMuvIA5y2vz3BpJxksy863GQaJW2MFNU= github.com/Masterminds/semver v1.5.0 h1:H65muMkzWKEuNDnfl9d70GUjFniHKHRbFPGBuZ3QEww= github.com/Masterminds/semver v1.5.0/go.mod h1:MB6lktGJrhw8PrUyiEoblNEGEQ+RzHPF078ddwwvV3Y= -github.com/Masterminds/semver/v3 v3.1.1 h1:hLg3sBzpNErnxhQtUy/mmLR2I9foDujNK030IGemrRc= -github.com/Masterminds/semver/v3 v3.1.1/go.mod h1:VPu/7SZ7ePZ3QOrcuXROw5FAcLl4a0cBrbBpGY/8hQs= -github.com/Masterminds/sprig/v3 v3.2.2 h1:17jRggJu518dr3QaafizSXOjKYp94wKfABxUmyxvxX8= -github.com/Masterminds/sprig/v3 v3.2.2/go.mod h1:UoaO7Yp8KlPnJIYWTFkMaqPUYKTfGFPhxNuwnnxkKlk= github.com/Microsoft/go-winio v0.4.16-0.20201130162521-d1ffc52c7331/go.mod h1:XB6nPKklQyQ7GC9LdcBEcBl8PF76WugXOPRXwdLnMv0= github.com/Microsoft/go-winio v0.4.17/go.mod h1:JPGBdM1cNvN/6ISo+n8V5iA4v8pBzdOpzfwIujj1a84= github.com/Microsoft/go-winio v0.5.1/go.mod h1:JPGBdM1cNvN/6ISo+n8V5iA4v8pBzdOpzfwIujj1a84= @@ -84,9 +78,6 @@ github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmV github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5/go.mod h1:wHh0iHkYZB8zMSxRWpUBQtwG5a7fFgvEO+odwuTv2gs= github.com/asaskevich/govalidator v0.0.0-20190424111038-f61b66f89f4a/go.mod h1:lB+ZfQJz7igIIfQNfa7Ml4HSf2uFQQRzpGGRXenZAgY= -github.com/asaskevich/govalidator v0.0.0-20200108200545-475eaeb16496/go.mod h1:oGkLhpf+kjZl6xBf758TQhh5XrAeiJv/7FRz/2spLIg= -github.com/asaskevich/govalidator v0.0.0-20210307081110-f21760c49a8d h1:Byv0BzEl3/e6D5CLfI0j/7hiIEtvGVFPCZ7Ei2oq8iQ= -github.com/asaskevich/govalidator v0.0.0-20210307081110-f21760c49a8d/go.mod h1:WaHUgvxTVq04UNunO+XhnAqY/wQc+bxr74GqbsZ/Jqw= github.com/avast/retry-go v3.0.0+incompatible h1:4SOWQ7Qs+oroOTQOYnAHqelpCO0biHSxpiH9JdtuBj0= github.com/avast/retry-go v3.0.0+incompatible/go.mod h1:XtSnn+n/sHqQIpZ10K1qAevBhOOCWBLXXy3hyiqqBrY= github.com/benbjohnson/clock v1.0.3/go.mod h1:bGMdMPoPVvcYyt1gHDf4J2KE153Yf9BuiUKYMaxlTDM= @@ -279,8 +270,6 @@ github.com/go-openapi/swag v0.19.5/go.mod h1:POnQmlKehdgb5mhVOsnJFsivZCEZ/vjK9gh github.com/go-openapi/swag v0.19.14/go.mod h1:QYRuS/SOXUCsnplDa677K7+DxSOj6IPNl/eQntq43wQ= github.com/go-openapi/swag v0.21.1 h1:wm0rhTb5z7qpJRHBdPOMuY4QjVUMbF6/kwoYeRAOrKU= github.com/go-openapi/swag v0.21.1/go.mod h1:QYRuS/SOXUCsnplDa677K7+DxSOj6IPNl/eQntq43wQ= -github.com/go-ozzo/ozzo-validation/v4 v4.3.0 h1:byhDUpfEwjsVQb1vBunvIjh2BHQ9ead57VkAEY4V+Es= -github.com/go-ozzo/ozzo-validation/v4 v4.3.0/go.mod h1:2NKgrcHl3z6cJs+3Oo940FPRiTzuqKbvfrL2RxCj6Ew= github.com/go-redis/redis/v8 v8.11.5 h1:AcZZR7igkdvfVmQTPnu9WE37LRrO/YrBH5zWyjDC0oI= github.com/go-redis/redis/v8 v8.11.5/go.mod h1:gREzHqY1hg6oD9ngVRbLStwAWKhA0FEgq8Jd4h5lpwo= github.com/go-sql-driver/mysql v1.4.0/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w= @@ -429,13 +418,9 @@ github.com/hashicorp/mdns v1.0.0/go.mod h1:tL+uN++7HEJ6SQLQ2/p+z2pH24WQKWjBPkE0m github.com/hashicorp/memberlist v0.1.3/go.mod h1:ajVTdAv/9Im8oMAAj5G31PhhMCZJV2pPBoIllUwCN7I= github.com/hashicorp/serf v0.8.2/go.mod h1:6hOLApaqBFA1NXqRQAsxw9QxuDEvNxSQRwA/JwenrHc= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= -github.com/huandu/xstrings v1.3.1/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE= -github.com/huandu/xstrings v1.3.2 h1:L18LIDzqlW6xN2rEkpdV8+oL/IXWJ1APd+vsdYy4Wdw= -github.com/huandu/xstrings v1.3.2/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE= github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= github.com/imdario/mergo v0.3.6/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA= -github.com/imdario/mergo v0.3.11/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH0dnCYA= github.com/imdario/mergo v0.3.12 h1:b6R2BslTbIEToALKP7LxUvijTsNI9TAe80pLWN2g/HU= github.com/imdario/mergo v0.3.12/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH0dnCYA= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= @@ -519,24 +504,16 @@ github.com/miekg/dns v1.0.14/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3N github.com/miekg/pkcs11 v1.1.1/go.mod h1:XsNlhZGX73bx86s2hdc/FuaLm2CPZJemRLMA+WTFxgs= github.com/mistifyio/go-zfs v2.1.2-0.20190413222219-f784269be439+incompatible/go.mod h1:8AuVvqP/mXw1px98n46wfvcGfQ4ci2FwoAjKYxuo3Z4= github.com/mitchellh/cli v1.0.0/go.mod h1:hNIlj7HEI86fIcpObd7a0FcrxTWetlwJDGcceTlRvqc= -github.com/mitchellh/copystructure v1.0.0/go.mod h1:SNtv71yrdKgLRyLFxmLdkAbkKEFWgYaq1OVrnRcwhnw= -github.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw= -github.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s= github.com/mitchellh/go-homedir v1.0.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= github.com/mitchellh/go-testing-interface v1.0.0/go.mod h1:kRemZodwjscx+RGhAo8eIhFbs2+BFgRtFPeD/KE+zxI= github.com/mitchellh/gox v0.4.0/go.mod h1:Sd9lOJ0+aimLBi73mGofS1ycjY8lL3uZM3JPS42BGNg= -github.com/mitchellh/hashstructure/v2 v2.0.2 h1:vGKWl0YJqUNxE8d+h8f6NJLcCJrgbhC4NcD46KavDd4= -github.com/mitchellh/hashstructure/v2 v2.0.2/go.mod h1:MG3aRVU/N29oo/V/IhBX8GR/zz4kQkprJgF2EVszyDE= github.com/mitchellh/iochan v1.0.0/go.mod h1:JwYml1nuB7xOzsp52dPpHFffvOCDupsG0QubkSMEySY= github.com/mitchellh/mapstructure v0.0.0-20160808181253-ca63d7c062ee/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= github.com/mitchellh/mapstructure v0.0.0-20180203102830-a4e142e9c047/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= github.com/mitchellh/mapstructure v1.4.3 h1:OVowDSCllw/YjdLkam3/sm7wEtOy59d8ndGgCcyj8cs= github.com/mitchellh/mapstructure v1.4.3/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= -github.com/mitchellh/reflectwalk v1.0.0/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= -github.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ= -github.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= github.com/moby/locker v1.0.1/go.mod h1:S7SDdo5zpBK84bzzVlKr2V0hz+7x9hWbYC/kq7oQppc= github.com/moby/spdystream v0.2.0/go.mod h1:f7i0iNDQJ059oMTcWxx8MA/zKFIuD/lY+0GqbN2Wy8c= github.com/moby/sys/mount v0.3.3 h1:fX1SVkXFJ47XWDoeFW4Sq7PdQJnV2QIDZAqjNqgEjUs= @@ -689,8 +666,6 @@ github.com/seccomp/libseccomp-golang v0.9.2-0.20220502022130-f33da4d89646/go.mod github.com/sergi/go-diff v1.1.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM= github.com/sergi/go-diff v1.2.0 h1:XU+rvMAioB0UC3q1MFrIQy4Vo5/4VsRDQQXHsEya6xQ= github.com/sergi/go-diff v1.2.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM= -github.com/shopspring/decimal v1.2.0 h1:abSATXmQEYyShuxI4/vyW3tV1MrKAJzCZ/0zLUXYbsQ= -github.com/shopspring/decimal v1.2.0/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o= github.com/shurcooL/httpfs v0.0.0-20171119174359-809beceb2371/go.mod h1:ZY1cvUeJuFPAdZ/B6v7RHavJWZn2YPVFQ1OSXhCGOkg= github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= github.com/shurcooL/vfsgen v0.0.0-20180121065927-ffb13db8def0/go.mod h1:TrYk7fJVaAttu97ZZKrO9UbRa8izdowaMIZcxYMbVaw= @@ -711,9 +686,6 @@ github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasO github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= github.com/spf13/afero v1.2.2/go.mod h1:9ZxEEn6pIJ8Rxe320qSDBk6AsU0r9pR7Q4OcevTdifk= github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= -github.com/spf13/cast v1.3.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= -github.com/spf13/cast v1.4.1 h1:s0hze+J0196ZfEMTs80N7UlFt0BDuQ7Q+JDnHiMWKdA= -github.com/spf13/cast v1.4.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= github.com/spf13/cobra v0.0.2-0.20171109065643-2da4a54c5cee/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ= github.com/spf13/cobra v1.1.3/go.mod h1:pGADOWyqRD/YMrPZigI/zbliZ2wVD/23d+is3pSWzOo= github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo= @@ -752,8 +724,6 @@ github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA= github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM= github.com/tidwall/pretty v1.2.0 h1:RWIZEg2iJ8/g6fDDYzMpobmaoGh5OLl4AXtGUGPcqCs= github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU= -github.com/tidwall/sjson v1.2.4 h1:cuiLzLnaMeBhRmEv00Lpk3tkYrcxpmbU81tAY4Dw0tc= -github.com/tidwall/sjson v1.2.4/go.mod h1:098SZ494YoMWPmMO6ct4dcFnqxwj9r/gF0Etp19pSNM= github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= github.com/tmc/grpc-websocket-proxy v0.0.0-20201229170055-e5319fda7802/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= github.com/urfave/cli v1.22.1/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0= @@ -771,13 +741,6 @@ github.com/vishvananda/netns v0.0.0-20200728191858-db3c7e526aae/go.mod h1:DD4vA1 github.com/vishvananda/netns v0.0.0-20210104183010-2eb08e3e575f/go.mod h1:DD4vA1DwXk04H54A1oHXtwZmA0grkVMdPxx/VGLCah0= github.com/vrischmann/envconfig v1.3.0 h1:4XIvQTXznxmWMnjouj0ST5lFo/WAYf5Exgl3x82crEk= github.com/vrischmann/envconfig v1.3.0/go.mod h1:bbvxFYJdRSpXrhS63mBFtKJzkDiNkyArOLXtY6q0kuI= -github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= -github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb h1:zGWFAtiMcyryUHoUjUJX0/lt1H2+i2Ka2n+D3DImSNo= -github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= -github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 h1:EzJWgHovont7NscjpAxXsDA8S8BMYve8Y5+7cuRE7R0= -github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1:GwrjFmJcFw6At/Gs6z4yjiIwzuJ1/+UwLxMQDVQXShQ= -github.com/xeipuuv/gojsonschema v1.2.0 h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17UxZ74= -github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y= github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU= github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= go.etcd.io/bbolt v1.3.2/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU= @@ -834,7 +797,6 @@ go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= go.uber.org/zap v1.17.0/go.mod h1:MXVU+bhUf/A7Xi2HNOnopQOrmycQ5Ih87HtOu4q5SSo= go.uber.org/zap v1.24.0 h1:FiJd5l1UOLj0wCgbSE0rwwXHzEdAZS6hiiSnxJN/D60= go.uber.org/zap v1.24.0/go.mod h1:2kMP+WWQ8aoFoedH3T2sq6iJ2yDWpHbP0f6MQbS9Gkg= -golang.org/x/crypto v0.16.0 h1:mMMrFzRSCF0GvB7Ne27XVtVAaXLrPmgPC7/v0tkwHaY= golang.org/x/crypto v0.16.0/go.mod h1:gCAAfMLgwOJRpTjQ2zCCt2OcSfYMTeZVSRtQlPC7Nq4= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= diff --git a/components/provisioner/internal/operations/executor.go b/components/provisioner/internal/operations/executor.go index 5e96fef42a..0678c6a8c0 100644 --- a/components/provisioner/internal/operations/executor.go +++ b/components/provisioner/internal/operations/executor.go @@ -13,8 +13,7 @@ import ( ) const ( - defaultDelay = 2 * time.Second - backOffDirectorDelay = 1 * time.Second + defaultDelay = 2 * time.Second ) var ErrKubeconfigNil = errors.New("cluster kubeconfig is nil") From 96f11ee5fe4e1625126a8b4771c688a1ec7dc085 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Przemys=C5=82aw=20Golicz?= Date: Mon, 29 Apr 2024 16:15:34 +0200 Subject: [PATCH 09/19] update dependencies in go.mod --- components/provisioner/go.mod | 43 ++++------------ components/provisioner/go.sum | 97 ++++++----------------------------- 2 files changed, 26 insertions(+), 114 deletions(-) diff --git a/components/provisioner/go.mod b/components/provisioner/go.mod index 9629fbe9fc..af5e84721d 100644 --- a/components/provisioner/go.mod +++ b/components/provisioner/go.mod @@ -32,14 +32,10 @@ require ( require ( github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 // indirect - github.com/Masterminds/goutils v1.1.1 // indirect github.com/Masterminds/semver v1.5.0 // indirect - github.com/Masterminds/semver/v3 v3.2.0 // indirect - github.com/Masterminds/sprig/v3 v3.2.3 // indirect github.com/Microsoft/go-winio v0.5.2 // indirect github.com/Microsoft/hcsshim v0.9.6 // indirect github.com/agnivade/levenshtein v1.1.1 // indirect - github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 // indirect github.com/beorn7/perks v1.0.1 // indirect github.com/cenkalti/backoff/v4 v4.1.3 // indirect github.com/cespare/xxhash/v2 v2.2.0 // indirect @@ -47,7 +43,6 @@ require ( github.com/containerd/containerd v1.6.8 // indirect github.com/cpuguy83/go-md2man/v2 v2.0.3 // indirect github.com/davecgh/go-spew v1.1.1 // indirect - github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0 // indirect github.com/docker/distribution v2.8.2+incompatible // indirect github.com/docker/docker v20.10.24+incompatible // indirect github.com/docker/go-connections v0.4.0 // indirect @@ -55,14 +50,11 @@ require ( github.com/emicklei/go-restful/v3 v3.9.0 // indirect github.com/evanphx/json-patch v4.12.0+incompatible // indirect github.com/evanphx/json-patch/v5 v5.6.0 // indirect - github.com/form3tech-oss/jwt-go v3.2.5+incompatible // indirect github.com/fsnotify/fsnotify v1.6.0 // indirect github.com/go-logr/logr v1.2.4 // indirect github.com/go-openapi/jsonpointer v0.19.5 // indirect github.com/go-openapi/jsonreference v0.20.0 // indirect github.com/go-openapi/swag v0.22.3 // indirect - github.com/go-ozzo/ozzo-validation/v4 v4.3.0 // indirect - github.com/goccy/go-json v0.10.2 // indirect github.com/gogo/protobuf v1.3.2 // indirect github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect github.com/golang/protobuf v1.5.3 // indirect @@ -73,17 +65,9 @@ require ( github.com/hashicorp/errwrap v1.1.0 // indirect github.com/hashicorp/go-multierror v1.1.1 // indirect github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect - github.com/huandu/xstrings v1.4.0 // indirect github.com/imdario/mergo v0.3.14 // indirect github.com/josharian/intern v1.0.0 // indirect github.com/json-iterator/go v1.1.12 // indirect - github.com/kyma-incubator/compass/components/hydrator v0.0.0-20240311150451-fb47652e9f70 // indirect - github.com/lestrrat-go/backoff/v2 v2.0.8 // indirect - github.com/lestrrat-go/blackmagic v1.0.2 // indirect - github.com/lestrrat-go/httpcc v1.0.1 // indirect - github.com/lestrrat-go/iter v1.0.2 // indirect - github.com/lestrrat-go/jwx v1.2.29 // indirect - github.com/lestrrat-go/option v1.0.1 // indirect github.com/magiconair/properties v1.8.6 // indirect github.com/mailru/easyjson v0.7.7 // indirect github.com/matttproud/golang_protobuf_extensions v1.0.4 // indirect @@ -102,27 +86,18 @@ require ( github.com/prometheus/common v0.44.0 // indirect github.com/prometheus/procfs v0.11.1 // indirect github.com/russross/blackfriday/v2 v2.1.0 // indirect - github.com/shopspring/decimal v1.2.0 // indirect github.com/sosodev/duration v1.2.0 // indirect - github.com/spf13/cast v1.5.0 // indirect github.com/spf13/pflag v1.0.5 // indirect github.com/stretchr/objx v0.5.2 // indirect - github.com/tidwall/gjson v1.17.0 // indirect - github.com/tidwall/match v1.1.1 // indirect - github.com/tidwall/pretty v1.2.0 // indirect - github.com/tidwall/sjson v1.2.5 // indirect github.com/urfave/cli/v2 v2.27.1 // indirect - github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect - github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect - github.com/xeipuuv/gojsonschema v1.2.0 // indirect github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 // indirect go.opencensus.io v0.23.0 // indirect - golang.org/x/crypto v0.21.0 // indirect - golang.org/x/mod v0.16.0 // indirect - golang.org/x/net v0.22.0 // indirect + golang.org/x/mod v0.17.0 // indirect + golang.org/x/net v0.24.0 // indirect golang.org/x/oauth2 v0.13.0 // indirect - golang.org/x/sys v0.18.0 // indirect - golang.org/x/term v0.18.0 // indirect + golang.org/x/sync v0.7.0 // indirect + golang.org/x/sys v0.19.0 // indirect + golang.org/x/term v0.19.0 // indirect golang.org/x/text v0.14.0 // indirect golang.org/x/time v0.3.0 // indirect golang.org/x/tools v0.19.0 // indirect @@ -147,11 +122,11 @@ require ( replace ( github.com/Microsoft/hcsshim => github.com/Microsoft/hcsshim v0.8.14 github.com/containerd/containerd => github.com/containerd/containerd v1.6.18 - golang.org/x/crypto => golang.org/x/crypto v0.16.0 - golang.org/x/net => golang.org/x/net v0.19.0 - golang.org/x/sys => golang.org/x/sys v0.15.0 + golang.org/x/crypto => golang.org/x/crypto v0.22.0 + golang.org/x/net => golang.org/x/net v0.24.0 + golang.org/x/sys => golang.org/x/sys v0.19.0 golang.org/x/text => golang.org/x/text v0.14.0 - golang.org/x/tools => golang.org/x/tools v0.16.0 + golang.org/x/tools => golang.org/x/tools v0.20.0 k8s.io/client-go => k8s.io/client-go v0.26.1 sourcegraph.com/sourcegraph/appdash-data => github.com/sourcegraph/appdash-data v0.0.0-20151005221446-73f23eafcf67 ) diff --git a/components/provisioner/go.sum b/components/provisioner/go.sum index 6dfce22378..61d0c28a36 100644 --- a/components/provisioner/go.sum +++ b/components/provisioner/go.sum @@ -44,14 +44,8 @@ github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym github.com/DATA-DOG/go-sqlmock v1.3.3/go.mod h1:f/Ixk793poVmq4qj/V1dPUg2JEAKC73Q5eFN3EC/SaM= github.com/DATA-DOG/go-sqlmock v1.5.0 h1:Shsta01QNfFxHCfpW6YH2STWB0MudeXXEWMr20OEh60= github.com/DATA-DOG/go-sqlmock v1.5.0/go.mod h1:f/Ixk793poVmq4qj/V1dPUg2JEAKC73Q5eFN3EC/SaM= -github.com/Masterminds/goutils v1.1.1 h1:5nUrii3FMTL5diU80unEVvNevw1nH4+ZV4DSLVJLSYI= -github.com/Masterminds/goutils v1.1.1/go.mod h1:8cTjp+g8YejhMuvIA5y2vz3BpJxksy863GQaJW2MFNU= github.com/Masterminds/semver v1.5.0 h1:H65muMkzWKEuNDnfl9d70GUjFniHKHRbFPGBuZ3QEww= github.com/Masterminds/semver v1.5.0/go.mod h1:MB6lktGJrhw8PrUyiEoblNEGEQ+RzHPF078ddwwvV3Y= -github.com/Masterminds/semver/v3 v3.2.0 h1:3MEsd0SM6jqZojhjLWWeBY+Kcjy9i6MQAeY7YgDP83g= -github.com/Masterminds/semver/v3 v3.2.0/go.mod h1:qvl/7zhW3nngYb5+80sSMF+FG2BjYrf8m9wsX0PNOMQ= -github.com/Masterminds/sprig/v3 v3.2.3 h1:eL2fZNezLomi0uOLqjQoN6BfsDD+fyLtgbJMAj9n6YA= -github.com/Masterminds/sprig/v3 v3.2.3/go.mod h1:rXcFaZ2zZbLRJv/xSysmlgIM1u11eBaRMhvYXJNkGuM= github.com/Microsoft/go-winio v0.4.16-0.20201130162521-d1ffc52c7331/go.mod h1:XB6nPKklQyQ7GC9LdcBEcBl8PF76WugXOPRXwdLnMv0= github.com/Microsoft/go-winio v0.4.17/go.mod h1:JPGBdM1cNvN/6ISo+n8V5iA4v8pBzdOpzfwIujj1a84= github.com/Microsoft/go-winio v0.5.1/go.mod h1:JPGBdM1cNvN/6ISo+n8V5iA4v8pBzdOpzfwIujj1a84= @@ -86,9 +80,6 @@ github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmV github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5/go.mod h1:wHh0iHkYZB8zMSxRWpUBQtwG5a7fFgvEO+odwuTv2gs= github.com/asaskevich/govalidator v0.0.0-20190424111038-f61b66f89f4a/go.mod h1:lB+ZfQJz7igIIfQNfa7Ml4HSf2uFQQRzpGGRXenZAgY= -github.com/asaskevich/govalidator v0.0.0-20200108200545-475eaeb16496/go.mod h1:oGkLhpf+kjZl6xBf758TQhh5XrAeiJv/7FRz/2spLIg= -github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 h1:DklsrG3dyBCFEj5IhUbnKptjxatkF07cF2ak3yi77so= -github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2/go.mod h1:WaHUgvxTVq04UNunO+XhnAqY/wQc+bxr74GqbsZ/Jqw= github.com/avast/retry-go v3.0.0+incompatible h1:4SOWQ7Qs+oroOTQOYnAHqelpCO0biHSxpiH9JdtuBj0= github.com/avast/retry-go v3.0.0+incompatible/go.mod h1:XtSnn+n/sHqQIpZ10K1qAevBhOOCWBLXXy3hyiqqBrY= github.com/benbjohnson/clock v1.0.3/go.mod h1:bGMdMPoPVvcYyt1gHDf4J2KE153Yf9BuiUKYMaxlTDM= @@ -176,8 +167,8 @@ github.com/coreos/go-systemd/v22 v22.3.2/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSV github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA= github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= github.com/cpuguy83/go-md2man/v2 v2.0.0/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= -github.com/cpuguy83/go-md2man/v2 v2.0.2 h1:p1EgwI/C7NhT0JmVkwCD2ZBK8j4aeHQX2pMHHBfMQ6w= -github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= +github.com/cpuguy83/go-md2man/v2 v2.0.3 h1:qMCsGGgs+MAzDFyp9LpAe1Lqy/fY/qCovCm0qnXZOBM= +github.com/cpuguy83/go-md2man/v2 v2.0.3/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/creack/pty v1.1.11 h1:07n33Z8lZxZ2qwegKbObQohDhXDQxiMMz1NOUGYlesw= github.com/creack/pty v1.1.11/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= @@ -188,9 +179,6 @@ github.com/d2g/dhcp4server v0.0.0-20181031114812-7d4a0a7f59a5/go.mod h1:Eo87+Kg/ github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/decred/dcrd/crypto/blake256 v1.0.1/go.mod h1:2OfgNZ5wDpcsFmHmCK5gZTPcCXqlm2ArzUIkw9czNJo= -github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0 h1:8UrgZ3GkP4i/CLijOJx79Yu+etlyjdBU4sfcs2WYQMs= -github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0/go.mod h1:v57UDF4pDQJcEfFUCRop3lJL149eHGSe9Jvczhzjo/0= github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78= github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc= @@ -237,11 +225,7 @@ github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5Kwzbycv github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYFFOfk= github.com/felixge/httpsnoop v1.0.1/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= github.com/form3tech-oss/jwt-go v3.2.3+incompatible/go.mod h1:pbq4aXjuKjdthFRnoDwaVPLA+WlJuPGy+QneDUgJi2k= -github.com/form3tech-oss/jwt-go v3.2.5+incompatible h1:/l4kBbb4/vGSsdtB5nUe8L7B9mImVMaBPw9L/0TBHU8= -github.com/form3tech-oss/jwt-go v3.2.5+incompatible/go.mod h1:pbq4aXjuKjdthFRnoDwaVPLA+WlJuPGy+QneDUgJi2k= github.com/frankban/quicktest v1.11.3/go.mod h1:wRf/ReqHper53s+kmmSZizM8NamnL3IM0I9ntUbOk+k= -github.com/frankban/quicktest v1.14.4 h1:g2rn0vABPOOXmZUj+vbmUp0lPoXEMuhTpIluN0XL9UY= -github.com/frankban/quicktest v1.14.4/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= github.com/fsnotify/fsnotify v1.5.4/go.mod h1:OVB6XrOHzAwXMpEM7uPOzcehqUV2UqJxmVXmkdnm1bU= @@ -284,8 +268,6 @@ github.com/go-openapi/swag v0.19.5/go.mod h1:POnQmlKehdgb5mhVOsnJFsivZCEZ/vjK9gh github.com/go-openapi/swag v0.19.14/go.mod h1:QYRuS/SOXUCsnplDa677K7+DxSOj6IPNl/eQntq43wQ= github.com/go-openapi/swag v0.22.3 h1:yMBqmnQ0gyZvEb/+KzuWZOXgllrXT4SADYbvDaXHv/g= github.com/go-openapi/swag v0.22.3/go.mod h1:UzaqsxGiab7freDnrUUra0MwWfN/q7tE4j+VcZ0yl14= -github.com/go-ozzo/ozzo-validation/v4 v4.3.0 h1:byhDUpfEwjsVQb1vBunvIjh2BHQ9ead57VkAEY4V+Es= -github.com/go-ozzo/ozzo-validation/v4 v4.3.0/go.mod h1:2NKgrcHl3z6cJs+3Oo940FPRiTzuqKbvfrL2RxCj6Ew= github.com/go-redis/redis/v8 v8.11.5 h1:AcZZR7igkdvfVmQTPnu9WE37LRrO/YrBH5zWyjDC0oI= github.com/go-redis/redis/v8 v8.11.5/go.mod h1:gREzHqY1hg6oD9ngVRbLStwAWKhA0FEgq8Jd4h5lpwo= github.com/go-sql-driver/mysql v1.4.0/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w= @@ -296,8 +278,6 @@ github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/me github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE= github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572 h1:tfuBGBXKqDEevZMzYi5KSi8KkcZtzBcTgAUUtapy0OI= github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572/go.mod h1:9Pwr4B2jHnOSGXyyzV8ROjYa2ojvAY6HCGYYfMoC3Ls= -github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU= -github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= github.com/gocraft/dbr/v2 v2.6.3 h1:T5djSa17dYgx/7tKFyGZcnfjFfEdDF6i9pI27vfopSU= github.com/gocraft/dbr/v2 v2.6.3/go.mod h1:gKhNOSeil013r91WnpefkahGiB5W/vjBoSYzPlMBoOE= github.com/godbus/dbus/v5 v5.0.3/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= @@ -433,13 +413,9 @@ github.com/hashicorp/mdns v1.0.0/go.mod h1:tL+uN++7HEJ6SQLQ2/p+z2pH24WQKWjBPkE0m github.com/hashicorp/memberlist v0.1.3/go.mod h1:ajVTdAv/9Im8oMAAj5G31PhhMCZJV2pPBoIllUwCN7I= github.com/hashicorp/serf v0.8.2/go.mod h1:6hOLApaqBFA1NXqRQAsxw9QxuDEvNxSQRwA/JwenrHc= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= -github.com/huandu/xstrings v1.3.3/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE= -github.com/huandu/xstrings v1.4.0 h1:D17IlohoQq4UcpqD7fDk80P7l+lwAmlFaBHgOipl2FU= -github.com/huandu/xstrings v1.4.0/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE= github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= github.com/imdario/mergo v0.3.6/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA= -github.com/imdario/mergo v0.3.11/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH0dnCYA= github.com/imdario/mergo v0.3.12/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH0dnCYA= github.com/imdario/mergo v0.3.14 h1:fOqeC1+nCuuk6PKQdg9YmosXX7Y7mHX6R/0ZldI9iHo= github.com/imdario/mergo v0.3.14/go.mod h1:WBLT9ZmE3lPoWsEzCh9LPo3TiwVN+ZKEjmz+hD27ysY= @@ -485,21 +461,6 @@ github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/kyma-incubator/compass/components/director v0.0.0-20240329103248-7710e72be80a h1:X8l9ubRI+az6WMbfvYBvSx6URKxIE69RgdxSZALn+14= github.com/kyma-incubator/compass/components/director v0.0.0-20240329103248-7710e72be80a/go.mod h1:2Ix9woiwr/5t76zzMF4PJAxcDj/wNgdK+wGvm9zVzGI= -github.com/kyma-incubator/compass/components/hydrator v0.0.0-20240311150451-fb47652e9f70 h1:DI1IghTUkzYwrMxbThTdT9yAVnr9wLbuq21RyymwPVo= -github.com/kyma-incubator/compass/components/hydrator v0.0.0-20240311150451-fb47652e9f70/go.mod h1:4xn8Yd3YNcWxzSlqsRzOwdy6KOwr+561/cXjECLJK0c= -github.com/lestrrat-go/backoff/v2 v2.0.8 h1:oNb5E5isby2kiro9AgdHLv5N5tint1AnDVVf2E2un5A= -github.com/lestrrat-go/backoff/v2 v2.0.8/go.mod h1:rHP/q/r9aT27n24JQLa7JhSQZCKBBOiM/uP402WwN8Y= -github.com/lestrrat-go/blackmagic v1.0.2 h1:Cg2gVSc9h7sz9NOByczrbUvLopQmXrfFx//N+AkAr5k= -github.com/lestrrat-go/blackmagic v1.0.2/go.mod h1:UrEqBzIR2U6CnzVyUtfM6oZNMt/7O7Vohk2J0OGSAtU= -github.com/lestrrat-go/httpcc v1.0.1 h1:ydWCStUeJLkpYyjLDHihupbn2tYmZ7m22BGkcvZZrIE= -github.com/lestrrat-go/httpcc v1.0.1/go.mod h1:qiltp3Mt56+55GPVCbTdM9MlqhvzyuL6W/NMDA8vA5E= -github.com/lestrrat-go/iter v1.0.2 h1:gMXo1q4c2pHmC3dn8LzRhJfP1ceCbgSiT9lUydIzltI= -github.com/lestrrat-go/iter v1.0.2/go.mod h1:Momfcq3AnRlRjI5b5O8/G5/BvpzrhoFTZcn06fEOPt4= -github.com/lestrrat-go/jwx v1.2.29 h1:QT0utmUJ4/12rmsVQrJ3u55bycPkKqGYuGT4tyRhxSQ= -github.com/lestrrat-go/jwx v1.2.29/go.mod h1:hU8k2l6WF0ncx20uQdOmik/Gjg6E3/wIRtXSNFeZuB8= -github.com/lestrrat-go/option v1.0.0/go.mod h1:5ZHFbivi4xwXxhxY9XHDe2FHo6/Z7WWmtT7T5nBBp3I= -github.com/lestrrat-go/option v1.0.1 h1:oAzP2fvZGQKWkvHa1/SAcFolBEca1oN+mQ7eooNBEYU= -github.com/lestrrat-go/option v1.0.1/go.mod h1:5ZHFbivi4xwXxhxY9XHDe2FHo6/Z7WWmtT7T5nBBp3I= github.com/lib/pq v1.0.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= github.com/lib/pq v1.2.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw= @@ -535,9 +496,6 @@ github.com/miekg/dns v1.0.14/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3N github.com/miekg/pkcs11 v1.1.1/go.mod h1:XsNlhZGX73bx86s2hdc/FuaLm2CPZJemRLMA+WTFxgs= github.com/mistifyio/go-zfs v2.1.2-0.20190413222219-f784269be439+incompatible/go.mod h1:8AuVvqP/mXw1px98n46wfvcGfQ4ci2FwoAjKYxuo3Z4= github.com/mitchellh/cli v1.0.0/go.mod h1:hNIlj7HEI86fIcpObd7a0FcrxTWetlwJDGcceTlRvqc= -github.com/mitchellh/copystructure v1.0.0/go.mod h1:SNtv71yrdKgLRyLFxmLdkAbkKEFWgYaq1OVrnRcwhnw= -github.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw= -github.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s= github.com/mitchellh/go-homedir v1.0.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= github.com/mitchellh/go-testing-interface v1.0.0/go.mod h1:kRemZodwjscx+RGhAo8eIhFbs2+BFgRtFPeD/KE+zxI= @@ -547,9 +505,6 @@ github.com/mitchellh/mapstructure v0.0.0-20160808181253-ca63d7c062ee/go.mod h1:F github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= -github.com/mitchellh/reflectwalk v1.0.0/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= -github.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ= -github.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= github.com/moby/locker v1.0.1/go.mod h1:S7SDdo5zpBK84bzzVlKr2V0hz+7x9hWbYC/kq7oQppc= github.com/moby/spdystream v0.2.0/go.mod h1:f7i0iNDQJ059oMTcWxx8MA/zKFIuD/lY+0GqbN2Wy8c= github.com/moby/sys/mount v0.3.3 h1:fX1SVkXFJ47XWDoeFW4Sq7PdQJnV2QIDZAqjNqgEjUs= @@ -695,8 +650,6 @@ github.com/seccomp/libseccomp-golang v0.9.2-0.20210429002308-3879420cc921/go.mod github.com/seccomp/libseccomp-golang v0.9.2-0.20220502022130-f33da4d89646/go.mod h1:JA8cRccbGaA1s33RQf7Y1+q9gHmZX1yB/z9WDN1C6fg= github.com/sergi/go-diff v1.3.1 h1:xkr+Oxo4BOQKmkn/B9eMK0g5Kg/983T9DqqPHwYqD+8= github.com/sergi/go-diff v1.3.1/go.mod h1:aMJSSKb2lpPvRNec0+w3fl7LP9IOFzdc9Pa4NFbPK1I= -github.com/shopspring/decimal v1.2.0 h1:abSATXmQEYyShuxI4/vyW3tV1MrKAJzCZ/0zLUXYbsQ= -github.com/shopspring/decimal v1.2.0/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o= github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= github.com/sirupsen/logrus v1.4.1/go.mod h1:ni0Sbl8bgC9z8RoU9G6nDWqqs/fq4eDPysMBDgk/93Q= @@ -716,9 +669,6 @@ github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasO github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= github.com/spf13/afero v1.2.2/go.mod h1:9ZxEEn6pIJ8Rxe320qSDBk6AsU0r9pR7Q4OcevTdifk= github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= -github.com/spf13/cast v1.3.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= -github.com/spf13/cast v1.5.0 h1:rj3WzYc11XZaIZMPKmwP96zkFEnnAmV8s6XbB2aY32w= -github.com/spf13/cast v1.5.0/go.mod h1:SpXXQ5YoyJw6s3/6cMTQuxvgRl3PCJiyaX9p6b155UU= github.com/spf13/cobra v0.0.2-0.20171109065643-2da4a54c5cee/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ= github.com/spf13/cobra v1.1.3/go.mod h1:pGADOWyqRD/YMrPZigI/zbliZ2wVD/23d+is3pSWzOo= github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo= @@ -733,7 +683,6 @@ github.com/stoewer/go-strcase v1.2.0/go.mod h1:IBiWB2sKIp3wVVQ3Y035++gc+knqhUQag github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= -github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY= github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= @@ -744,7 +693,6 @@ github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/ github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= -github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw= @@ -752,15 +700,12 @@ github.com/syndtr/gocapability v0.0.0-20200815063812-42c35b437635/go.mod h1:hkRG github.com/tchap/go-patricia v2.2.6+incompatible/go.mod h1:bmLyhP68RS6kStMGxByiQ23RP/odRBOTVjwp2cDyi6I= github.com/testcontainers/testcontainers-go v0.14.0 h1:h0D5GaYG9mhOWr2qHdEKDXpkce/VlvaYOCzTRi6UBi8= github.com/testcontainers/testcontainers-go v0.14.0/go.mod h1:hSRGJ1G8Q5Bw2gXgPulJOLlEBaYJHeBSOkQM5JLG+JQ= -github.com/tidwall/gjson v1.14.2/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= github.com/tidwall/gjson v1.17.0 h1:/Jocvlh98kcTfpN2+JzGQWQcqrPQwDrVEMApx/M5ZwM= github.com/tidwall/gjson v1.17.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA= github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM= github.com/tidwall/pretty v1.2.0 h1:RWIZEg2iJ8/g6fDDYzMpobmaoGh5OLl4AXtGUGPcqCs= github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU= -github.com/tidwall/sjson v1.2.5 h1:kLy8mja+1c9jlljvWTlSazM7cKDRfJuR/bOJhcY5NcY= -github.com/tidwall/sjson v1.2.5/go.mod h1:Fvgq9kS/6ociJEDnK0Fk1cpYF4FIW6ZF7LAe+6jwd28= github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= github.com/tmc/grpc-websocket-proxy v0.0.0-20201229170055-e5319fda7802/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= github.com/urfave/cli v1.22.1/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0= @@ -776,13 +721,6 @@ github.com/vishvananda/netns v0.0.0-20200728191858-db3c7e526aae/go.mod h1:DD4vA1 github.com/vishvananda/netns v0.0.0-20210104183010-2eb08e3e575f/go.mod h1:DD4vA1DwXk04H54A1oHXtwZmA0grkVMdPxx/VGLCah0= github.com/vrischmann/envconfig v1.3.0 h1:4XIvQTXznxmWMnjouj0ST5lFo/WAYf5Exgl3x82crEk= github.com/vrischmann/envconfig v1.3.0/go.mod h1:bbvxFYJdRSpXrhS63mBFtKJzkDiNkyArOLXtY6q0kuI= -github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= -github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb h1:zGWFAtiMcyryUHoUjUJX0/lt1H2+i2Ka2n+D3DImSNo= -github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= -github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 h1:EzJWgHovont7NscjpAxXsDA8S8BMYve8Y5+7cuRE7R0= -github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1:GwrjFmJcFw6At/Gs6z4yjiIwzuJ1/+UwLxMQDVQXShQ= -github.com/xeipuuv/gojsonschema v1.2.0 h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17UxZ74= -github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y= github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU= github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 h1:bAn7/zixMGCfxrRTfdpNzjtPYqr8smhKouy9mxVdGPU= github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673/go.mod h1:N3UwUGtsrSj3ccvlPHLoLsHnpR27oXr4ZE984MbSER8= @@ -841,8 +779,7 @@ go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= go.uber.org/zap v1.17.0/go.mod h1:MXVU+bhUf/A7Xi2HNOnopQOrmycQ5Ih87HtOu4q5SSo= go.uber.org/zap v1.24.0 h1:FiJd5l1UOLj0wCgbSE0rwwXHzEdAZS6hiiSnxJN/D60= go.uber.org/zap v1.24.0/go.mod h1:2kMP+WWQ8aoFoedH3T2sq6iJ2yDWpHbP0f6MQbS9Gkg= -golang.org/x/crypto v0.16.0 h1:mMMrFzRSCF0GvB7Ne27XVtVAaXLrPmgPC7/v0tkwHaY= -golang.org/x/crypto v0.16.0/go.mod h1:gCAAfMLgwOJRpTjQ2zCCt2OcSfYMTeZVSRtQlPC7Nq4= +golang.org/x/crypto v0.22.0/go.mod h1:vr6Su+7cTlO45qkww3VDJlzDn0ctJvRgYbC2NvXHt+M= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= @@ -876,11 +813,11 @@ golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.6.0-dev.0.20220106191415-9b9b3d81d5e3/go.mod h1:3p9vT2HGsQu2K1YbXdKPJLVgG5VJdoTa1poYQBtP1AY= golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= -golang.org/x/mod v0.14.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= -golang.org/x/mod v0.16.0 h1:QX4fJ0Rr5cPQCF7O9lh9Se4pmwfwskqZfq5moyldzic= -golang.org/x/mod v0.16.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= -golang.org/x/net v0.19.0 h1:zTwKpTd2XuCqf8huc7Fo2iSy+4RHPd10s4KzeTnVr1c= -golang.org/x/net v0.19.0/go.mod h1:CfAk/cbD4CthTvqiEl8NpboMuiuOYsAr/7NOjZJtv1U= +golang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= +golang.org/x/mod v0.17.0 h1:zY54UmvipHiNd+pm+m0x9KhZ9hl1/7QNMyxXbc6ICqA= +golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= +golang.org/x/net v0.24.0 h1:1PcaxkF854Fu3+lvBIx5SYn9wRlBzzcnHZSiaFFAb0w= +golang.org/x/net v0.24.0/go.mod h1:2Q7sJY5mzlzWjKtYUEXSlBWCdyaioyXzRB2RtU8KVE8= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= @@ -902,18 +839,18 @@ golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220601150217-0de741cfad7f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.5.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= -golang.org/x/sync v0.6.0 h1:5BMeUDZ7vkXGfEr1x9B4bRcTH4lpkTkpdh0T/J+qjbQ= golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= -golang.org/x/sys v0.15.0 h1:h48lPFYpsTvQJZF4EKyI4aLHaev3CxivZmv7yZig9pc= -golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sync v0.7.0 h1:YsImfSBoP9QPYL0xyKJPq0gcaJdG3rInoqxTWbfQu9M= +golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/sys v0.19.0 h1:q5f1RH2jigJ1MoAWp2KTp3gm5zAGFUTarQZ5U386+4o= +golang.org/x/sys v0.19.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.0.0-20220526004731-065cf7ba2467/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.3.0/go.mod h1:q750SLmJuPmVoN1blW3UFBPREJfb1KmY3vwxfr+nFDA= -golang.org/x/term v0.15.0/go.mod h1:BDl952bC7+uMoWR75FIrCDx79TPU9oHkTZ9yRbYOrX0= -golang.org/x/term v0.18.0 h1:FcHjZXDMxI8mM3nwhX9HlKop4C0YQvCVCdwYl2wOtE8= -golang.org/x/term v0.18.0/go.mod h1:ILwASektA3OnRv7amZ1xhE/KTR+u50pbXfZ03+6Nx58= +golang.org/x/term v0.19.0 h1:+ThwsDv+tYfnJFhF4L8jITxu1tdTWRTZpdsWgEgjL6Q= +golang.org/x/term v0.19.0/go.mod h1:2CuTdWZ7KHSQwUzKva0cbMg6q2DMI3Mmxp+gKJbskEk= golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= @@ -924,8 +861,8 @@ golang.org/x/time v0.0.0-20210723032227-1f47c861a9ac/go.mod h1:tRJNPiyCQ0inRvYxb golang.org/x/time v0.0.0-20220210224613-90d013bbcef8/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.3.0 h1:rg5rLMjNzMS1RkNLzCG38eapWhnYLFYXDXj2gOlr8j4= golang.org/x/time v0.3.0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= -golang.org/x/tools v0.16.0 h1:GO788SKMRunPIBCXiQyo2AaexLstOrVhuAL5YwsckQM= -golang.org/x/tools v0.16.0/go.mod h1:kYVVN6I1mBNoB1OX+noeBjbRk4IUEPa7JJ+TJMEooJ0= +golang.org/x/tools v0.20.0 h1:hz/CVckiOxybQvFw6h7b/q80NTr9IUQb4s1IIzW7KNY= +golang.org/x/tools v0.20.0/go.mod h1:WvitBU7JJf6A4jOdg4S1tviW9bhUxkgeCui/0JHctQg= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= From 8f1ffe934317796d064cfcc2043d6afa2133d439 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Przemys=C5=82aw=20Golicz?= Date: Mon, 29 Apr 2024 17:20:17 +0200 Subject: [PATCH 10/19] fixing unit tests for mocked uuids --- .../internal/provisioning/service_test.go | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/components/provisioner/internal/provisioning/service_test.go b/components/provisioner/internal/provisioning/service_test.go index 1a5843e652..f0752fa18a 100644 --- a/components/provisioner/internal/provisioning/service_test.go +++ b/components/provisioner/internal/provisioning/service_test.go @@ -62,7 +62,6 @@ func kubeconfigProviderMock() *queue_mock.KubeconfigProvider { func TestService_ProvisionRuntime(t *testing.T) { inputConverter := NewInputConverter(uuid.NewUUIDGenerator(), gardenerProject, defaultEnableKubernetesVersionAutoUpdate, defaultEnableMachineImageVersionAutoUpdate, defaultEnableIMDSv2) graphQLConverter := NewGraphQLConverter() - uuidGenerator := uuid.NewUUIDGenerator() clusterConfig := &gqlschema.ClusterConfigInput{ GardenerConfig: &gqlschema.GardenerConfigInput{ @@ -148,6 +147,9 @@ func TestService_ProvisionRuntime(t *testing.T) { writeSessionWithinTransactionMock := &sessionMocks.WriteSessionWithinTransaction{} provisioner := &mocks2.Provisioner{} + uuidGeneratorMock := &uuidMocks.UUIDGenerator{} + uuidGeneratorMock.On("New").Return(runtimeID) + expectErr := dberrors.Internal("Failed to commit transaction: error") sessionFactoryMock.On("NewSessionWithinTransaction").Return(writeSessionWithinTransactionMock, nil) writeSessionWithinTransactionMock.On("InsertCluster", mock.MatchedBy(clusterMatcher)).Return(nil) @@ -157,7 +159,7 @@ func TestService_ProvisionRuntime(t *testing.T) { writeSessionWithinTransactionMock.On("RollbackUnlessCommitted").Return() provisioner.On("ProvisionCluster", mock.MatchedBy(clusterMatcher), mock.MatchedBy(notEmptyUUIDMatcher)).Return(nil) - service := NewProvisioningService(inputConverter, graphQLConverter, sessionFactoryMock, provisioner, uuidGenerator, nil, nil, nil, nil, kubeconfigProviderMock) + service := NewProvisioningService(inputConverter, graphQLConverter, sessionFactoryMock, provisioner, uuidGeneratorMock, nil, nil, nil, nil, kubeconfigProviderMock) // when _, err := service.ProvisionRuntime(provisionRuntimeInput, tenant, subAccountId) @@ -177,6 +179,9 @@ func TestService_ProvisionRuntime(t *testing.T) { writeSessionWithinTransactionMock := &sessionMocks.WriteSessionWithinTransaction{} provisioner := &mocks2.Provisioner{} + uuidGeneratorMock := &uuidMocks.UUIDGenerator{} + uuidGeneratorMock.On("New").Return(runtimeID) + sessionFactoryMock.On("NewSessionWithinTransaction").Return(writeSessionWithinTransactionMock, nil) writeSessionWithinTransactionMock.On("InsertCluster", mock.MatchedBy(clusterMatcher)).Return(nil) writeSessionWithinTransactionMock.On("InsertGardenerConfig", mock.AnythingOfType("model.GardenerConfig")).Return(nil) @@ -184,7 +189,7 @@ func TestService_ProvisionRuntime(t *testing.T) { writeSessionWithinTransactionMock.On("RollbackUnlessCommitted").Return() provisioner.On("ProvisionCluster", mock.MatchedBy(clusterMatcher), mock.MatchedBy(notEmptyUUIDMatcher)).Return(apperrors.Internal("error")) - service := NewProvisioningService(inputConverter, graphQLConverter, sessionFactoryMock, provisioner, uuidGenerator, nil, nil, nil, nil, kubeconfigProviderMock) + service := NewProvisioningService(inputConverter, graphQLConverter, sessionFactoryMock, provisioner, uuidGeneratorMock, nil, nil, nil, nil, kubeconfigProviderMock) // when _, err := service.ProvisionRuntime(provisionRuntimeInput, tenant, subAccountId) @@ -508,7 +513,7 @@ func TestService_RuntimeStatus(t *testing.T) { readSession.On("GetLastOperation", operationID).Return(operation, nil) readSession.On("GetCluster", operationID).Return(model.Cluster{}, dberrors.Internal("error")) - resolver := NewProvisioningService(inputConverter, graphQLConverter, nil, sessionFactoryMock, nil, uuidGenerator, nil, nil, nil, nil, nil, true) + resolver := NewProvisioningService(inputConverter, graphQLConverter, sessionFactoryMock, nil, uuidGenerator, nil, nil, nil, nil, nil) // when _, err := resolver.RuntimeStatus(operationID) @@ -527,7 +532,7 @@ func TestService_RuntimeStatus(t *testing.T) { sessionFactoryMock.On("NewReadSession").Return(readSession) readSession.On("GetLastOperation", operationID).Return(model.Operation{}, dberrors.Internal("error")) - resolver := NewProvisioningService(inputConverter, graphQLConverter, nil, sessionFactoryMock, nil, uuidGenerator, nil, nil, nil, nil, nil, true) + resolver := NewProvisioningService(inputConverter, graphQLConverter, sessionFactoryMock, nil, uuidGenerator, nil, nil, nil, nil, nil) // when _, err := resolver.RuntimeStatus(operationID) @@ -638,7 +643,7 @@ func TestService_UpgradeGardenerShoot(t *testing.T) { testCase.mockFunc(sessionFactory, readSession, writeSessionWithinTransaction, provisioner, shootProvider, upgradeShootQueue) - service := NewProvisioningService(inputConverter, graphQLConverter, nil, sessionFactory, provisioner, uuidGenerator, shootProvider, nil, nil, upgradeShootQueue, nil, true) + service := NewProvisioningService(inputConverter, graphQLConverter, sessionFactory, provisioner, uuidGenerator, shootProvider, nil, nil, upgradeShootQueue, nil) // when operationStatus, err := service.UpgradeGardenerShoot(runtimeID, upgradeShootInput) @@ -758,7 +763,7 @@ func TestService_UpgradeGardenerShoot(t *testing.T) { testCase.mockFunc(sessionFactory, readSession, writeSessionWithinTransaction, provisioner, shootProvider) - service := NewProvisioningService(inputConverter, graphQLConverter, nil, sessionFactory, provisioner, uuidGenerator, shootProvider, nil, nil, upgradeShootQueue, nil, true) + service := NewProvisioningService(inputConverter, graphQLConverter, sessionFactory, provisioner, uuidGenerator, shootProvider, nil, nil, upgradeShootQueue, nil) // when _, err := service.UpgradeGardenerShoot(runtimeID, upgradeShootInput) From f12ed9e304118ebdcf25bc17d9c702e2f57494d0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Przemys=C5=82aw=20Golicz?= Date: Mon, 29 Apr 2024 17:41:21 +0200 Subject: [PATCH 11/19] fixing unit tests and removing not used compassID --- .../provisioning/graphql_converter_test.go | 79 +++++-------------- 1 file changed, 18 insertions(+), 61 deletions(-) diff --git a/components/provisioner/internal/provisioning/graphql_converter_test.go b/components/provisioner/internal/provisioning/graphql_converter_test.go index 02014df732..3fe4f667c6 100644 --- a/components/provisioner/internal/provisioning/graphql_converter_test.go +++ b/components/provisioner/internal/provisioning/graphql_converter_test.go @@ -19,46 +19,6 @@ func TestOperationStatusToGQLOperationStatus(t *testing.T) { graphQLConverter := NewGraphQLConverter() - t.Run("Should create proper operation status struct", func(t *testing.T) { - //given - operation := model.Operation{ - ID: "5f6e3ab6-d803-430a-8fac-29c9c9b4485a", - Type: model.Upgrade, - State: model.InProgress, - Message: "Some message", - ClusterID: "6af76034-272a-42be-ac39-30e075f515a3", - LastError: model.LastError{ - ErrMessage: "error msg", - Reason: "ERR_INFRA_QUOTA_EXCEEDED", - Component: "gardener", - }, - } - - operationID := "5f6e3ab6-d803-430a-8fac-29c9c9b4485a" - message := "Some message" - runtimeID := "6af76034-272a-42be-ac39-30e075f515a3" - - expectedOperationStatus := &gqlschema.OperationStatus{ - ID: &operationID, - Operation: gqlschema.OperationTypeUpgrade, - State: gqlschema.OperationStateInProgress, - Message: &message, - RuntimeID: &runtimeID, - CompassRuntimeID: &runtimeID, - LastError: &gqlschema.LastError{ - ErrMessage: "error msg", - Reason: "ERR_INFRA_QUOTA_EXCEEDED", - Component: "gardener", - }, - } - - //when - status := graphQLConverter.OperationStatusToGQLOperationStatus(operation) - - //then - assert.Equal(t, expectedOperationStatus, status) - }) - t.Run("Should create proper operation status struct without compassID", func(t *testing.T) { //given operation := model.Operation{ @@ -193,13 +153,12 @@ func TestRuntimeStatusToGraphQLStatus(t *testing.T) { expectedRuntimeStatus := &gqlschema.RuntimeStatus{ LastOperationStatus: &gqlschema.OperationStatus{ - ID: &operationID, - Operation: gqlschema.OperationTypeDeprovision, - State: gqlschema.OperationStateFailed, - Message: &message, - RuntimeID: &runtimeID, - CompassRuntimeID: &runtimeID, - LastError: &gqlschema.LastError{}, + ID: &operationID, + Operation: gqlschema.OperationTypeDeprovision, + State: gqlschema.OperationStateFailed, + Message: &message, + RuntimeID: &runtimeID, + LastError: &gqlschema.LastError{}, }, RuntimeConnectionStatus: &gqlschema.RuntimeConnectionStatus{ Status: gqlschema.RuntimeAgentConnectionStatusDisconnected, @@ -354,13 +313,12 @@ func TestRuntimeStatusToGraphQLStatus(t *testing.T) { expectedRuntimeStatus := &gqlschema.RuntimeStatus{ LastOperationStatus: &gqlschema.OperationStatus{ - ID: &operationID, - Operation: gqlschema.OperationTypeDeprovisionNoInstall, - State: gqlschema.OperationStateFailed, - Message: &message, - RuntimeID: &runtimeID, - CompassRuntimeID: &runtimeID, - LastError: &gqlschema.LastError{}, + ID: &operationID, + Operation: gqlschema.OperationTypeDeprovisionNoInstall, + State: gqlschema.OperationStateFailed, + Message: &message, + RuntimeID: &runtimeID, + LastError: &gqlschema.LastError{}, }, RuntimeConnectionStatus: &gqlschema.RuntimeConnectionStatus{ Status: gqlschema.RuntimeAgentConnectionStatusDisconnected, @@ -503,13 +461,12 @@ func TestRuntimeStatusToGraphQLStatus(t *testing.T) { expectedRuntimeStatus := &gqlschema.RuntimeStatus{ LastOperationStatus: &gqlschema.OperationStatus{ - ID: &operationID, - Operation: gqlschema.OperationTypeDeprovision, - State: gqlschema.OperationStateFailed, - Message: &message, - RuntimeID: &runtimeID, - CompassRuntimeID: &runtimeID, - LastError: &gqlschema.LastError{}, + ID: &operationID, + Operation: gqlschema.OperationTypeDeprovision, + State: gqlschema.OperationStateFailed, + Message: &message, + RuntimeID: &runtimeID, + LastError: &gqlschema.LastError{}, }, RuntimeConnectionStatus: &gqlschema.RuntimeConnectionStatus{ Status: gqlschema.RuntimeAgentConnectionStatusDisconnected, From 56c5ad86c583f4ac598b98709c184552bf6b1161 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Przemys=C5=82aw=20Golicz?= Date: Mon, 29 Apr 2024 18:38:57 +0200 Subject: [PATCH 12/19] fixing db tests - remove compassID --- ...resolver_integration_with_gardener_test.go | 24 +++++++++---------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/components/provisioner/internal/api/resolver_integration_with_gardener_test.go b/components/provisioner/internal/api/resolver_integration_with_gardener_test.go index 001d88d9de..78b01f4140 100644 --- a/components/provisioner/internal/api/resolver_integration_with_gardener_test.go +++ b/components/provisioner/internal/api/resolver_integration_with_gardener_test.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "fmt" + uuidMocks "github.com/kyma-project/control-plane/components/provisioner/internal/uuid/mocks" "path/filepath" "strings" "testing" @@ -11,8 +12,6 @@ import ( "github.com/kyma-project/control-plane/components/provisioner/internal/api/fake/seeds" "github.com/kyma-project/control-plane/components/provisioner/internal/api/fake/shoots" - "github.com/kyma-project/control-plane/components/provisioner/internal/uuid" - provisioning2 "github.com/kyma-project/control-plane/components/provisioner/internal/operations/stages/provisioning" "github.com/kyma-project/control-plane/components/provisioner/internal/api" @@ -170,10 +169,12 @@ func TestProvisioning_ProvisionRuntimeWithDatabase(t *testing.T) { clusterConfig := config.provisioningInput.config runtimeInput := config.provisioningInput.runtimeInput - uuidGenerator := uuid.NewUUIDGenerator() + uuidGeneratorMock := &uuidMocks.UUIDGenerator{} + uuidGeneratorMock.On("New").Return(config.runtimeID) + provisioner := gardener.NewProvisioner(namespace, shootInterface, dbsFactory, auditLogPolicyCMName, maintenanceWindowConfigPath) - inputConverter := provisioning.NewInputConverter(uuidGenerator, "Project", defaultEnableKubernetesVersionAutoUpdate, defaultEnableMachineImageVersionAutoUpdate, defaultEnableIMDSv2) + inputConverter := provisioning.NewInputConverter(uuidGeneratorMock, "Project", defaultEnableKubernetesVersionAutoUpdate, defaultEnableMachineImageVersionAutoUpdate, defaultEnableIMDSv2) graphQLConverter := provisioning.NewGraphQLConverter() provisioningService := provisioning.NewProvisioningService( @@ -181,7 +182,7 @@ func TestProvisioning_ProvisionRuntimeWithDatabase(t *testing.T) { graphQLConverter, dbsFactory, provisioner, - uuidGenerator, + uuidGeneratorMock, gardener.NewShootProvider(shootInterface), provisioningQueue, deprovisioningQueue, @@ -363,13 +364,12 @@ func testDeprovisionRuntime(t *testing.T, ctx context.Context, resolver *api.Res func fixOperationStatusProvisioned(runtimeId, operationId *string) *gqlschema.OperationStatus { return &gqlschema.OperationStatus{ - ID: operationId, - Operation: gqlschema.OperationTypeProvision, - State: gqlschema.OperationStateSucceeded, - RuntimeID: runtimeId, - CompassRuntimeID: runtimeId, - Message: util.PtrTo("Operation succeeded"), - LastError: &gqlschema.LastError{}, + ID: operationId, + Operation: gqlschema.OperationTypeProvision, + State: gqlschema.OperationStateSucceeded, + RuntimeID: runtimeId, + Message: util.PtrTo("Operation succeeded"), + LastError: &gqlschema.LastError{}, } } From f3b759307de09267f7f50650da7b1ad2072a9e92 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Przemys=C5=82aw=20Golicz?= Date: Tue, 30 Apr 2024 17:21:15 +0200 Subject: [PATCH 13/19] fix of unit test to use mocked uuids for db testing --- .../internal/api/resolver_integration_test.go | 30 ++++++++++++++----- ...resolver_integration_with_gardener_test.go | 9 +++++- 2 files changed, 31 insertions(+), 8 deletions(-) diff --git a/components/provisioner/internal/api/resolver_integration_test.go b/components/provisioner/internal/api/resolver_integration_test.go index 4f0399c72d..612cb7bedc 100644 --- a/components/provisioner/internal/api/resolver_integration_test.go +++ b/components/provisioner/internal/api/resolver_integration_test.go @@ -63,6 +63,10 @@ type testCase struct { name string description string runtimeID string + provisioningID string + gardenerConfigID string + deprovisioningID string + upgradeID string auditLogConfig *gardener.AuditLogConfig provisioningInput provisioningInput upgradeShootInput gqlschema.UpgradeShootInput @@ -82,8 +86,12 @@ Everything else should be tested in appropriate package func newTestProvisioningConfigs() []testCase { return []testCase{ {name: "Azure on Gardener", - description: "Should provision, deprovision a runtime and upgrade shoot on happy path, using correct Azure configuration for Gardener, when zones passed", - runtimeID: "1100bb59-9c40-4ebb-b846-7477c4dc5bb4", + description: "Should provision, deprovision a runtime and upgrade shoot on happy path, using correct Azure configuration for Gardener, when zones passed", + runtimeID: "1100bb59-9c40-4ebb-b846-7477c4dc5bb4", + provisioningID: "2100bb59-9c40-4ebb-b846-7477c4dc5bb5", + gardenerConfigID: "3100bb59-9c40-4ebb-b846-7477c4dc5bb6", + deprovisioningID: "4100bb59-9c40-4ebb-b846-7477c4dc5bb7", + upgradeID: "5100bb59-9c40-4ebb-b846-7477c4dc5bb8", auditLogConfig: &gardener.AuditLogConfig{ TenantID: "12d68c35-556b-4966-a061-235d4a060929", ServiceURL: "https://auditlog.example.com:3001", @@ -99,9 +107,13 @@ func newTestProvisioningConfigs() []testCase { seed: seedConfig("az-eu2", "eu-west-1", "azure"), }, {name: "Azure on Gardener seed is empty", - description: "Should provision, deprovision a runtime and upgrade shoot on happy path, using correct Azure configuration for Gardener, when seed is empty", - runtimeID: "1100bb59-9c40-4ebb-b846-7477c4dc5bb2", - auditLogConfig: nil, + description: "Should provision, deprovision a runtime and upgrade shoot on happy path, using correct Azure configuration for Gardener, when seed is empty", + runtimeID: "5100bb59-9c40-4ebb-b846-7477c4dc5b11", + provisioningID: "6100bb59-9c40-4ebb-b846-7477c4dc5b22", + gardenerConfigID: "7100bb59-9c40-4ebb-b846-7477c4dc5b33", + deprovisioningID: "8100bb59-9c40-4ebb-b846-7477c4dc5b44", + upgradeID: "9100bb59-9c40-4ebb-b846-7477c4dc5b55", + auditLogConfig: nil, provisioningInput: provisioningInput{ config: azureGardenerClusterConfigInputNoSeed(), runtimeInput: gqlschema.RuntimeInput{ @@ -111,8 +123,12 @@ func newTestProvisioningConfigs() []testCase { upgradeShootInput: NewUpgradeShootInput(), }, {name: "OpenStack on Gardener", - description: "Should provision, deprovision a runtime and upgrade shoot on happy path, using correct OpenStack configuration for Gardener", - runtimeID: "1100bb59-9c40-4ebb-b846-7477c4dc5bb8", + description: "Should provision, deprovision a runtime and upgrade shoot on happy path, using correct OpenStack configuration for Gardener", + runtimeID: "9100bb59-9c40-4ebb-b846-7477c4dc5bb8", + provisioningID: "a100bb59-9c40-4ebb-b846-7477c4dc5bb9", + gardenerConfigID: "b100bb59-9c40-4ebb-b846-7477c4dc5bba", + deprovisioningID: "c100bb59-9c40-4ebb-b846-7477c4dc5bbb", + upgradeID: "d100bb59-9c40-4ebb-b846-7477c4dc5bbc", auditLogConfig: &gardener.AuditLogConfig{ TenantID: "e7382275-e835-4549-94e1-3b1101e3a1fa", ServiceURL: "https://auditlog.example.com:3000", diff --git a/components/provisioner/internal/api/resolver_integration_with_gardener_test.go b/components/provisioner/internal/api/resolver_integration_with_gardener_test.go index 78b01f4140..db00aad413 100644 --- a/components/provisioner/internal/api/resolver_integration_with_gardener_test.go +++ b/components/provisioner/internal/api/resolver_integration_with_gardener_test.go @@ -170,7 +170,14 @@ func TestProvisioning_ProvisionRuntimeWithDatabase(t *testing.T) { runtimeInput := config.provisioningInput.runtimeInput uuidGeneratorMock := &uuidMocks.UUIDGenerator{} - uuidGeneratorMock.On("New").Return(config.runtimeID) + uuidGeneratorMock.On("New").Return(config.runtimeID).Once() + uuidGeneratorMock.On("New").Return(config.provisioningID).Once() + uuidGeneratorMock.On("New").Return(config.gardenerConfigID).Once() + uuidGeneratorMock.On("New").Return(config.upgradeID).Once() + uuidGeneratorMock.On("New").Return(config.deprovisioningID).Once() + + //uuidGeneratorMock.On("New").Return(config.upgradeID).Once() + //uuidGeneratorMock.On("New").Return(config.deprovisioningID).Once() provisioner := gardener.NewProvisioner(namespace, shootInterface, dbsFactory, auditLogPolicyCMName, maintenanceWindowConfigPath) From ff6a54d097918ad34e4bf69f93374e42f5f1da3c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Przemys=C5=82aw=20Golicz?= Date: Mon, 6 May 2024 13:03:41 +0200 Subject: [PATCH 14/19] removing unused deployment configuration options --- components/provisioner/cmd/main.go | 7 ------ ...resolver_integration_with_gardener_test.go | 2 -- .../operations/queue/queues_constructor.go | 2 -- .../provisioner/templates/deployment.yaml | 22 +------------------ resources/kcp/charts/provisioner/values.yaml | 8 ------- 5 files changed, 1 insertion(+), 40 deletions(-) diff --git a/components/provisioner/cmd/main.go b/components/provisioner/cmd/main.go index c7121948d5..9dd851d544 100644 --- a/components/provisioner/cmd/main.go +++ b/components/provisioner/cmd/main.go @@ -72,9 +72,6 @@ type config struct { DefaultEnableIMDSv2 bool `envconfig:"default=false"` } - LatestDownloadedReleases int `envconfig:"default=5"` - DownloadPreReleases bool `envconfig:"default=true"` - EnqueueInProgressOperations bool `envconfig:"default=true"` MetricsAddress string `envconfig:"default=127.0.0.1:9000"` @@ -88,12 +85,10 @@ func (c *config) String() string { "DatabaseName: %s, DatabaseSSLMode: %s, "+ "ProvisioningTimeoutClusterCreation: %s "+ "ProvisioningTimeoutInstallation: %s, ProvisioningTimeoutUpgrade: %s, "+ - "ProvisioningTimeoutAgentConfiguration: %s, ProvisioningTimeoutAgentConnection: %s, "+ "DeprovisioningNoInstallTimeoutClusterDeletion: %s, DeprovisioningNoInstallTimeoutWaitingForClusterDeletion: %s "+ "ShootUpgradeTimeout: %s, "+ "OperatorRoleBindingL2SubjectName: %s, OperatorRoleBindingL3SubjectName: %s, OperatorRoleBindingCreatingForAdmin: %t "+ "GardenerProject: %s, GardenerKubeconfigPath: %s, GardenerAuditLogsPolicyConfigMap: %s, AuditLogsTenantConfigPath: %s, DefaultEnableIMDSv2: %v"+ - "LatestDownloadedReleases: %d, DownloadPreReleases: %v, "+ "EnqueueInProgressOperations: %v"+ "LogLevel: %s", c.Address, c.APIEndpoint, @@ -101,12 +96,10 @@ func (c *config) String() string { c.Database.Name, c.Database.SSLMode, c.ProvisioningTimeout.ClusterCreation.String(), c.ProvisioningTimeout.Installation.String(), c.ProvisioningTimeout.Upgrade.String(), - c.ProvisioningTimeout.AgentConfiguration.String(), c.ProvisioningTimeout.AgentConnection.String(), c.DeprovisioningTimeout.ClusterDeletion.String(), c.DeprovisioningTimeout.WaitingForClusterDeletion.String(), c.ProvisioningTimeout.ShootUpgrade.String(), c.OperatorRoleBinding.L2SubjectName, c.OperatorRoleBinding.L3SubjectName, c.OperatorRoleBinding.CreatingForAdmin, c.Gardener.Project, c.Gardener.KubeconfigPath, c.Gardener.AuditLogsPolicyConfigMap, c.Gardener.AuditLogsTenantConfigPath, c.Gardener.DefaultEnableIMDSv2, - c.LatestDownloadedReleases, c.DownloadPreReleases, c.EnqueueInProgressOperations, c.LogLevel) } diff --git a/components/provisioner/internal/api/resolver_integration_with_gardener_test.go b/components/provisioner/internal/api/resolver_integration_with_gardener_test.go index db00aad413..83d79a9842 100644 --- a/components/provisioner/internal/api/resolver_integration_with_gardener_test.go +++ b/components/provisioner/internal/api/resolver_integration_with_gardener_test.go @@ -391,8 +391,6 @@ func testProvisioningTimeouts() queue.ProvisioningTimeouts { UpgradeTriggering: 5 * time.Minute, ShootUpgrade: 5 * time.Minute, ShootRefresh: 5 * time.Minute, - AgentConfiguration: 5 * time.Minute, - AgentConnection: 5 * time.Minute, } } diff --git a/components/provisioner/internal/operations/queue/queues_constructor.go b/components/provisioner/internal/operations/queue/queues_constructor.go index 971ddfe614..c11c929626 100644 --- a/components/provisioner/internal/operations/queue/queues_constructor.go +++ b/components/provisioner/internal/operations/queue/queues_constructor.go @@ -24,8 +24,6 @@ type ProvisioningTimeouts struct { UpgradeTriggering time.Duration `envconfig:"default=20m"` ShootUpgrade time.Duration `envconfig:"default=30m"` ShootRefresh time.Duration `envconfig:"default=5m"` - AgentConfiguration time.Duration `envconfig:"default=15m"` - AgentConnection time.Duration `envconfig:"default=15m"` } type DeprovisioningTimeouts struct { diff --git a/resources/kcp/charts/provisioner/templates/deployment.yaml b/resources/kcp/charts/provisioner/templates/deployment.yaml index 5499e0efd9..fbf912f5f4 100644 --- a/resources/kcp/charts/provisioner/templates/deployment.yaml +++ b/resources/kcp/charts/provisioner/templates/deployment.yaml @@ -98,24 +98,10 @@ spec: name: {{ .Values.deployment.databaseEncryptionSecret | quote }} key: secretKey optional: false - - name: APP_DIRECTOR_OAUTH_PATH - value: /director-secret/director.yaml - - name: APP_DIRECTOR_URL - value: "https://{{ .Values.global.compass.tls.secure.oauth.host }}.{{ .Values.global.compass.domain | default .Values.global.ingress.domainName }}/director/graphql" - - name: APP_SKIP_DIRECTOR_CERT_VERIFICATION - value: {{ or .Values.global.isLocalEnv .Values.security.skipTLSCertificateVeryfication | quote }} - - name: APP_RUNTIME_REGISTRATION_ENABLED - value: {{ or .Values.compassIntegration.registratonEnabled | quote }} - - name: APP_RUNTIME_DEREGISTRATION_ENABLED - value: {{ or .Values.compassIntegration.deregistrationEnabled | quote }} - name: APP_PROVISIONING_TIMEOUT_INSTALLATION value: {{ .Values.installation.timeout | quote }} - name: APP_PROVISIONING_TIMEOUT_UPGRADE value: {{ .Values.installation.timeout | quote }} - - name: APP_PROVISIONING_TIMEOUT_AGENT_CONFIGURATION - value: {{ .Values.runtimeAgent.configurationTimeout | quote }} - - name: APP_PROVISIONING_TIMEOUT_AGENT_CONNECTION - value: {{ .Values.runtimeAgent.connectionTimeout | quote }} - name: APP_PROVISIONING_TIMEOUT_CLUSTER_CREATION value: {{ .Values.gardener.clusterCreationTimeout | quote }} - name: APP_PROVISIONING_TIMEOUT_UPGRADE_TRIGGERING @@ -163,9 +149,6 @@ spec: - name: APP_ENQUEUE_IN_PROGRESS_OPERATIONS value: "true" volumeMounts: - - name: director-oauth - mountPath: /director-secret/ - readOnly: true {{if .Values.gardener.auditLogExtensionConfigMapName }} - mountPath: /gardener/tenant name: gardener-audit-log-tenant-config @@ -252,7 +235,4 @@ spec: name: {{ .Values.gardener.maintenanceWindowConfigMapName }} optional: true {{end}} - - name: director-oauth - secret: - secretName: {{ .Values.directorFileSecret }} - optional: false + diff --git a/resources/kcp/charts/provisioner/values.yaml b/resources/kcp/charts/provisioner/values.yaml index 953f74da14..10d2c665e4 100644 --- a/resources/kcp/charts/provisioner/values.yaml +++ b/resources/kcp/charts/provisioner/values.yaml @@ -72,17 +72,9 @@ kymaRelease: installation: timeout: 22h -compassIntegration: - registratonEnabled: true - deregistrationEnabled: true - upgrade: triggeringTimeout: 20m -runtimeAgent: - configurationTimeout: 1h - connectionTimeout: 1h - metrics: port: 9000 From a9c956d338879c79265fd196c4fc33fee2f3af44 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Przemys=C5=82aw=20Golicz?= Date: Mon, 6 May 2024 18:45:45 +0200 Subject: [PATCH 15/19] removing unused env variables from e2e tests --- components/provisioner/e2e_test/test.sh | 15 --------------- 1 file changed, 15 deletions(-) diff --git a/components/provisioner/e2e_test/test.sh b/components/provisioner/e2e_test/test.sh index 61eed35eb3..d3df13eed7 100755 --- a/components/provisioner/e2e_test/test.sh +++ b/components/provisioner/e2e_test/test.sh @@ -70,15 +70,6 @@ has_to_succeed wait_for postgres 5432 -export APP_DIRECTOR_URL=https://compass-gateway-auth-oauth.cmp-main.dev.kyma.cloud.sap/director/graphql -if [[ -z "$APP_DIRECTOR_OAUTH_PATH" ]]; then - export APP_DIRECTOR_OAUTH_PATH=/compass-director-secret/secret.yaml -fi - -if ! [[ -f "$APP_DIRECTOR_OAUTH_PATH" ]]; then - echo "APP_DIRECTOR_OAUTH_PATH is not set or file doesn't exist $APP_DIRECTOR_OAUTH_PATH" - exit 1 -fi export APP_GARDENER_KUBECONFIG_PATH=${APP_GARDENER_KUBECONFIG_PATH:-$GARDENER_KYMA_PROW_KUBECONFIG} export APP_GARDENER_PROJECT=${GARDENER_KYMA_PROW_PROJECT_NAME:-$APP_GARDENER_PROJECT} @@ -102,18 +93,12 @@ export APP_DATABASE_USER=postgres export APP_PROVISIONING_TIMEOUT_INSTALLATION=90m export APP_PROVISIONING_TIMEOUT_UPGRADE=90m -export APP_PROVISIONING_TIMEOUT_AGENT_CONFIGURATION=90m export APP_PROVISIONING_NO_INSTALL_TIMEOUT_AGENT_CONFIGURATION=90m -export APP_PROVISIONING_TIMEOUT_AGENT_CONNECTION=90m export APP_PROVISIONING_TIMEOUT_CLUSTER_CREATION=90m export APP_PROVISIONING_TIMEOUT_CLUSTER_DOMAINS=20m export APP_PROVISIONING_NO_INSTALL_TIMEOUT_CLUSTER_CREATION=90m export APP_PROVISIONING_TIMEOUT_UPGRADE_TRIGGERING=90m -# for testing disabled Compass registration/deregistration -export APP_RUNTIME_REGISTRATION_ENABLED="false" -export APP_RUNTIME_DEREGISTRATION_ENABLED="false" - printf '\n########## SETTING UP THE DB ##########\n\n' go run ./pgsetup.go From 56f488e4fa1d3a896531ed7cd7d841986a5a3552 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Przemys=C5=82aw=20Golicz?= Date: Tue, 7 May 2024 08:59:36 +0200 Subject: [PATCH 16/19] remove unused method after removal of director oauth client --- components/provisioner/cmd/init.go | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/components/provisioner/cmd/init.go b/components/provisioner/cmd/init.go index 0c711ad42c..3f3254a08d 100644 --- a/components/provisioner/cmd/init.go +++ b/components/provisioner/cmd/init.go @@ -1,9 +1,7 @@ package main import ( - "crypto/tls" "fmt" - "net/http" "os" "time" @@ -83,12 +81,3 @@ func newGardenerClusterConfig(cfg config) (*restclient.Config, error) { return gardenerClusterConfig, nil } - -func newHTTPClient(skipCertVerification bool) *http.Client { - return &http.Client{ - Transport: &http.Transport{ - TLSClientConfig: &tls.Config{InsecureSkipVerify: skipCertVerification}, - }, - Timeout: 30 * time.Second, - } -} From 79267890338280c485835ed01e4beea34128c20a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Przemys=C5=82aw=20Golicz?= Date: Tue, 7 May 2024 09:19:07 +0200 Subject: [PATCH 17/19] remove graphql client used for director integration --- .../internal/apperrors/apperrors.go | 27 ++----- .../provisioner/internal/graphql/client.go | 76 ------------------- .../internal/graphql/gql_client_testkit.go | 47 ------------ .../internal/graphql/mocks/Client.go | 42 ---------- 4 files changed, 7 insertions(+), 185 deletions(-) delete mode 100644 components/provisioner/internal/graphql/client.go delete mode 100644 components/provisioner/internal/graphql/gql_client_testkit.go delete mode 100644 components/provisioner/internal/graphql/mocks/Client.go diff --git a/components/provisioner/internal/apperrors/apperrors.go b/components/provisioner/internal/apperrors/apperrors.go index d2d021e53a..a9bd0db3d2 100644 --- a/components/provisioner/internal/apperrors/apperrors.go +++ b/components/provisioner/internal/apperrors/apperrors.go @@ -8,32 +8,19 @@ type ErrReason string type ErrComponent string const ( - ErrDB ErrComponent = "db - provisioner" - ErrProvisionerK8SClient ErrComponent = "k8s client - provisioner" - ErrProvisioner ErrComponent = "provisioner" - ErrCompassDirectorClient ErrComponent = "compass director client" - ErrCompassDirector ErrComponent = "compass director" - ErrMpsOAuth2 ErrComponent = "mps oauth2" - ErrCompassConnectionClient ErrComponent = "compass connection client" - ErrCompassConnection ErrComponent = "compass connection" - ErrGardenerClient ErrComponent = "k8s client - gardener" - ErrGardener ErrComponent = "gardener" - ErrClusterK8SClient ErrComponent = "k8s client - cluster" - ErrKymaInstaller ErrComponent = "kyma installer" + ErrDB ErrComponent = "db - provisioner" + ErrProvisionerK8SClient ErrComponent = "k8s client - provisioner" + ErrProvisioner ErrComponent = "provisioner" + ErrMpsOAuth2 ErrComponent = "mps oauth2" + ErrGardenerClient ErrComponent = "k8s client - gardener" + ErrGardener ErrComponent = "gardener" + ErrClusterK8SClient ErrComponent = "k8s client - cluster" ) const ( ErrProvisionerInternal ErrReason = "err_provisioner_internal" ErrProvisionerTimeout ErrReason = "err_provisioner_timeout" ErrProvisionerStepNotFound ErrReason = "err_provisioner_step_not_found" - - ErrDirectorNilResponse ErrReason = "err_director_nil_response" - ErrDirectorRuntimeIDMismatch ErrReason = "err_director_runtime_id_mismatch" - ErrDirectorClientGraphqlizer ErrReason = "err_director_client_graphqlizer" - - ErrCheckKymaInstallationState ErrReason = "err_check_kyma_installation_state" - ErrTriggerKymaInstall ErrReason = "err_trigger_kyma_install" - ErrTriggerKymaUninstall ErrReason = "err_trigger_kyma_uninstall" ) type ErrCode int diff --git a/components/provisioner/internal/graphql/client.go b/components/provisioner/internal/graphql/client.go deleted file mode 100644 index 9ab943eeed..0000000000 --- a/components/provisioner/internal/graphql/client.go +++ /dev/null @@ -1,76 +0,0 @@ -package graphql - -import ( - "context" - "crypto/tls" - "net/http" - "time" - - "github.com/kyma-project/control-plane/components/provisioner/third_party/machinebox/graphql" - "github.com/sirupsen/logrus" -) - -const ( - timeout = 30 * time.Second -) - -type ClientConstructor func(certificate *tls.Certificate, graphqlEndpoint string, enableLogging bool, insecureConfigFetch bool) (Client, error) - -//go:generate mockery --name=Client -type Client interface { - Do(req *graphql.Request, res interface{}) error -} - -type client struct { - gqlClient *graphql.Client - logs []string - logging bool -} - -func NewGraphQLClient(graphqlEndpoint string, enableLogging bool, insecureSkipVerify bool) Client { - httpClient := &http.Client{ - Transport: &http.Transport{ - TLSClientConfig: &tls.Config{InsecureSkipVerify: insecureSkipVerify}, - }, - } - - gqlClient := graphql.NewClient(graphqlEndpoint, graphql.WithHTTPClient(httpClient)) - - client := &client{ - gqlClient: gqlClient, - logging: enableLogging, - logs: []string{}, - } - - client.gqlClient.Log = client.addLog - - return client -} - -func (c *client) Do(req *graphql.Request, res interface{}) error { - ctx, cancel := context.WithTimeout(context.Background(), timeout) - defer cancel() - - c.clearLogs() - err := c.gqlClient.Run(ctx, req, res) - if err != nil { - for _, l := range c.logs { - if l != "" { - logrus.Info(l) - } - } - } - return err -} - -func (c *client) addLog(log string) { - if !c.logging { - return - } - - c.logs = append(c.logs, log) -} - -func (c *client) clearLogs() { - c.logs = []string{} -} diff --git a/components/provisioner/internal/graphql/gql_client_testkit.go b/components/provisioner/internal/graphql/gql_client_testkit.go deleted file mode 100644 index 6c3ed7a628..0000000000 --- a/components/provisioner/internal/graphql/gql_client_testkit.go +++ /dev/null @@ -1,47 +0,0 @@ -package graphql - -import ( - "errors" - "testing" - - "github.com/kyma-project/control-plane/components/provisioner/third_party/machinebox/graphql" - "github.com/stretchr/testify/assert" -) - -type QueryAssertClient struct { - t *testing.T - expectedRequests []*graphql.Request - err error - modifyResponseFunc ModifyResponseFunc -} - -type ModifyResponseFunc []func(t *testing.T, r interface{}) - -func (c *QueryAssertClient) Do(req *graphql.Request, res interface{}) error { - if len(c.expectedRequests) == 0 { - return errors.New("no more requests were expected") - } - - assert.Equal(c.t, c.expectedRequests[0], req) - if len(c.expectedRequests) > 1 { - c.expectedRequests = c.expectedRequests[1:] - } - - if len(c.modifyResponseFunc) > 0 { - c.modifyResponseFunc[0](c.t, res) - if len(c.modifyResponseFunc) > 1 { - c.modifyResponseFunc = c.modifyResponseFunc[1:] - } - } - - return c.err -} - -func NewQueryAssertClient(t *testing.T, err error, expectedReq []*graphql.Request, modifyResponseFunc ...func(t *testing.T, r interface{})) Client { - return &QueryAssertClient{ - t: t, - expectedRequests: expectedReq, - err: err, - modifyResponseFunc: modifyResponseFunc, - } -} diff --git a/components/provisioner/internal/graphql/mocks/Client.go b/components/provisioner/internal/graphql/mocks/Client.go deleted file mode 100644 index a8bf913ac7..0000000000 --- a/components/provisioner/internal/graphql/mocks/Client.go +++ /dev/null @@ -1,42 +0,0 @@ -// Code generated by mockery v2.36.1. DO NOT EDIT. - -package mocks - -import ( - graphql "github.com/kyma-project/control-plane/components/provisioner/third_party/machinebox/graphql" - - mock "github.com/stretchr/testify/mock" -) - -// Client is an autogenerated mock type for the Client type -type Client struct { - mock.Mock -} - -// Do provides a mock function with given fields: req, res -func (_m *Client) Do(req *graphql.Request, res interface{}) error { - ret := _m.Called(req, res) - - var r0 error - if rf, ok := ret.Get(0).(func(*graphql.Request, interface{}) error); ok { - r0 = rf(req, res) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// NewClient creates a new instance of Client. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewClient(t interface { - mock.TestingT - Cleanup(func()) -}) *Client { - mock := &Client{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} From a0c1d1b207adcecbc52a086ebe47786206b07f0d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Przemys=C5=82aw=20Golicz?= Date: Tue, 7 May 2024 09:25:56 +0200 Subject: [PATCH 18/19] remove oauth client used for director integration --- .../provisioner/internal/oauth/client.go | 92 --------------- .../provisioner/internal/oauth/client_test.go | 108 ------------------ .../internal/oauth/mocks/Client.go | 55 --------- .../provisioner/internal/oauth/types.go | 38 ------ .../provisioner/internal/oauth/types_test.go | 53 --------- 5 files changed, 346 deletions(-) delete mode 100644 components/provisioner/internal/oauth/client.go delete mode 100644 components/provisioner/internal/oauth/client_test.go delete mode 100644 components/provisioner/internal/oauth/mocks/Client.go delete mode 100644 components/provisioner/internal/oauth/types.go delete mode 100644 components/provisioner/internal/oauth/types_test.go diff --git a/components/provisioner/internal/oauth/client.go b/components/provisioner/internal/oauth/client.go deleted file mode 100644 index b49ffd0094..0000000000 --- a/components/provisioner/internal/oauth/client.go +++ /dev/null @@ -1,92 +0,0 @@ -package oauth - -import ( - "encoding/json" - "io" - "net/http" - "net/http/httputil" - "net/url" - "strings" - "time" - - "github.com/kyma-project/control-plane/components/provisioner/internal/apperrors" - - "github.com/kyma-project/control-plane/components/provisioner/internal/util" - log "github.com/sirupsen/logrus" -) - -//go:generate mockery --name=Client -type Client interface { - GetAuthorizationToken() (Token, apperrors.AppError) -} - -type oauthClient struct { - httpClient *http.Client - creds credentials -} - -func NewOauthClient(client *http.Client, clientID, clientSecret, tokensEndpoint string) Client { - return &oauthClient{ - httpClient: client, - creds: credentials{ - clientID: clientID, - clientSecret: clientSecret, - tokensEndpoint: tokensEndpoint, - }, - } -} - -func (c *oauthClient) GetAuthorizationToken() (Token, apperrors.AppError) { - return c.getAuthorizationToken(c.creds) -} - -func (c *oauthClient) getAuthorizationToken(credentials credentials) (Token, apperrors.AppError) { - log.Infof("Getting authorisation token for credentials to access Director from endpoint: %s", credentials.tokensEndpoint) - - form := url.Values{} - form.Add(grantTypeFieldName, credentialsGrantType) - form.Add(scopeFieldName, scopes) - - request, err := http.NewRequest(http.MethodPost, credentials.tokensEndpoint, strings.NewReader(form.Encode())) - if err != nil { - log.Errorf("Failed to create authorisation token request") - return Token{}, apperrors.Internal("Failed to create authorisation token request: %s", err.Error()) - } - - now := time.Now().Unix() - - request.SetBasicAuth(credentials.clientID, credentials.clientSecret) - request.Header.Set(contentTypeHeader, contentTypeApplicationURLEncoded) - - response, err := c.httpClient.Do(request) - if err != nil { - return Token{}, apperrors.Internal("Failed to execute http call: %s", err.Error()) - } - defer util.Close(response.Body) - - if response.StatusCode != http.StatusOK { - dump, err := httputil.DumpResponse(response, true) - if err != nil { - dump = []byte("failed to dump response body") - } - return Token{}, apperrors.External("Get token call returned unexpected status: %s. Response dump: %s", response.Status, string(dump)).SetComponent(apperrors.ErrMpsOAuth2) - } - - body, err := io.ReadAll(response.Body) - if err != nil { - return Token{}, apperrors.Internal("Failed to read token response body from '%s': %s", credentials.tokensEndpoint, err.Error()) - } - - tokenResponse := Token{} - - err = json.Unmarshal(body, &tokenResponse) - if err != nil { - return Token{}, apperrors.Internal("failed to unmarshal token response body: %s", err.Error()) - } - - log.Infof("Successfully unmarshal response oauth token for accessing Director") - - tokenResponse.Expiration += now - - return tokenResponse, nil -} diff --git a/components/provisioner/internal/oauth/client_test.go b/components/provisioner/internal/oauth/client_test.go deleted file mode 100644 index aecdf58cdd..0000000000 --- a/components/provisioner/internal/oauth/client_test.go +++ /dev/null @@ -1,108 +0,0 @@ -package oauth - -import ( - "bytes" - "context" - "encoding/json" - "io/ioutil" - "net/http" - "testing" - "time" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - v1 "k8s.io/api/core/v1" - meta "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/client-go/kubernetes/fake" - core "k8s.io/client-go/kubernetes/typed/core/v1" -) - -const ( - namespace = "kcp-system" - secretName = "kcp-provisioner-registration" -) - -func TestOauthClient_GetAuthorizationToken(t *testing.T) { - t.Run("Should return oauth token", func(t *testing.T) { - //given - credentials := credentials{ - clientID: "12345", - clientSecret: "some dark and scary secret", - tokensEndpoint: "http://hydra:4445", - } - - token := Token{ - AccessToken: "12345", - Expiration: 1234, - } - - client := NewTestClient(func(req *http.Request) *http.Response { - username, secret, ok := req.BasicAuth() - - if ok && username == credentials.clientID && secret == credentials.clientSecret { - jsonToken, err := json.Marshal(&token) - - require.NoError(t, err) - - return &http.Response{ - StatusCode: http.StatusOK, - Body: ioutil.NopCloser(bytes.NewReader(jsonToken)), - } - } - return &http.Response{ - StatusCode: http.StatusForbidden, - } - }) - - coreV1 := fake.NewSimpleClientset() - secrets := coreV1.CoreV1().Secrets(namespace) - - createFakeCredentialsSecret(t, secrets, credentials) - - oauthClient := NewOauthClient(client, credentials.clientID, credentials.clientSecret, credentials.tokensEndpoint) - - //when - responseToken, err := oauthClient.GetAuthorizationToken() - require.NoError(t, err) - token.Expiration += time.Now().Unix() - - //then - assert.Equal(t, token.AccessToken, responseToken.AccessToken) - assert.Equal(t, token.Expiration, responseToken.Expiration) - }) -} - -func NewTestClient(fn RoundTripFunc) *http.Client { - return &http.Client{ - Transport: fn, - } -} - -type RoundTripFunc func(req *http.Request) *http.Response - -func (f RoundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) { - return f(req), nil -} - -func createFakeCredentialsSecret(t *testing.T, secrets core.SecretInterface, credentials credentials) { - - secret := &v1.Secret{ - ObjectMeta: meta.ObjectMeta{ - Name: secretName, - Namespace: namespace, - }, - TypeMeta: meta.TypeMeta{ - Kind: "Secret", - APIVersion: "v1", - }, - Data: map[string][]byte{ - clientIDKey: []byte(credentials.clientID), - clientSecretKey: []byte(credentials.clientSecret), - tokensEndpointKey: []byte(credentials.tokensEndpoint), - }, - } - - _, err := secrets.Create(context.Background(), secret, meta.CreateOptions{}) - - require.NoError(t, err) -} diff --git a/components/provisioner/internal/oauth/mocks/Client.go b/components/provisioner/internal/oauth/mocks/Client.go deleted file mode 100644 index 8d66e11fae..0000000000 --- a/components/provisioner/internal/oauth/mocks/Client.go +++ /dev/null @@ -1,55 +0,0 @@ -// Code generated by mockery v2.36.1. DO NOT EDIT. - -package mocks - -import ( - apperrors "github.com/kyma-project/control-plane/components/provisioner/internal/apperrors" - mock "github.com/stretchr/testify/mock" - - oauth "github.com/kyma-project/control-plane/components/provisioner/internal/oauth" -) - -// Client is an autogenerated mock type for the Client type -type Client struct { - mock.Mock -} - -// GetAuthorizationToken provides a mock function with given fields: -func (_m *Client) GetAuthorizationToken() (oauth.Token, apperrors.AppError) { - ret := _m.Called() - - var r0 oauth.Token - var r1 apperrors.AppError - if rf, ok := ret.Get(0).(func() (oauth.Token, apperrors.AppError)); ok { - return rf() - } - if rf, ok := ret.Get(0).(func() oauth.Token); ok { - r0 = rf() - } else { - r0 = ret.Get(0).(oauth.Token) - } - - if rf, ok := ret.Get(1).(func() apperrors.AppError); ok { - r1 = rf() - } else { - if ret.Get(1) != nil { - r1 = ret.Get(1).(apperrors.AppError) - } - } - - return r0, r1 -} - -// NewClient creates a new instance of Client. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewClient(t interface { - mock.TestingT - Cleanup(func()) -}) *Client { - mock := &Client{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/components/provisioner/internal/oauth/types.go b/components/provisioner/internal/oauth/types.go deleted file mode 100644 index aa4c9d3666..0000000000 --- a/components/provisioner/internal/oauth/types.go +++ /dev/null @@ -1,38 +0,0 @@ -package oauth - -import "time" - -const ( - contentTypeHeader = "Content-Type" - contentTypeApplicationURLEncoded = "application/x-www-form-urlencoded" - - grantTypeFieldName = "grant_type" - credentialsGrantType = "client_credentials" - - scopeFieldName = "scope" - scopes = "runtime:read runtime:write" - - clientIDKey = "client_id" - clientSecretKey = "client_secret" - tokensEndpointKey = "tokens_endpoint" -) - -type Token struct { - AccessToken string `json:"access_token"` - Expiration int64 `json:"expires_in"` -} - -type credentials struct { - clientID string - clientSecret string - tokensEndpoint string -} - -func (token Token) EmptyOrExpired() bool { - if token.AccessToken == "" { - return true - } - - expiration := time.Unix(token.Expiration, 0) - return time.Now().After(expiration) -} diff --git a/components/provisioner/internal/oauth/types_test.go b/components/provisioner/internal/oauth/types_test.go deleted file mode 100644 index e1f8b0f76a..0000000000 --- a/components/provisioner/internal/oauth/types_test.go +++ /dev/null @@ -1,53 +0,0 @@ -package oauth - -import ( - "testing" - "time" - - "github.com/stretchr/testify/assert" -) - -func TestToken_EmptyOrExpired(t *testing.T) { - t.Run("Should return true when token is empty", func(t *testing.T) { - //given - token := Token{} - - //when - empty := token.EmptyOrExpired() - - //then - assert.True(t, empty) - }) - - t.Run("Should return true when expired", func(t *testing.T) { - //given - time2000 := time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC).Unix() - - token := Token{ - AccessToken: "token", - Expiration: time2000, - } - - //when - expired := token.EmptyOrExpired() - - //then - assert.True(t, expired) - }) - - t.Run("Should return false when not empty or expired", func(t *testing.T) { - //given - time3000 := time.Date(3000, 1, 1, 0, 0, 0, 0, time.UTC).Unix() - - token := Token{ - AccessToken: "token", - Expiration: time3000, - } - - //when - notExpired := token.EmptyOrExpired() - - //then - assert.False(t, notExpired) - }) -} From c75b814c41a08ec4c5816e142f9f548edc551c63 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Przemys=C5=82aw=20Golicz?= Date: Tue, 7 May 2024 10:04:17 +0200 Subject: [PATCH 19/19] remove unused file closer.go used for oauth client --- components/provisioner/internal/util/closer.go | 14 -------------- 1 file changed, 14 deletions(-) delete mode 100644 components/provisioner/internal/util/closer.go diff --git a/components/provisioner/internal/util/closer.go b/components/provisioner/internal/util/closer.go deleted file mode 100644 index 370e1e691d..0000000000 --- a/components/provisioner/internal/util/closer.go +++ /dev/null @@ -1,14 +0,0 @@ -package util - -import ( - "io" - - "github.com/sirupsen/logrus" -) - -func Close(closer io.ReadCloser) { - err := closer.Close() - if err != nil { - logrus.Warnf("Failed to close read closer: %s", err.Error()) - } -}