diff --git a/cmd/gitops/add/app/cmd.go b/cmd/gitops/add/app/cmd.go index 70ef7423cf2..e6cc43a9ed8 100644 --- a/cmd/gitops/add/app/cmd.go +++ b/cmd/gitops/add/app/cmd.go @@ -118,9 +118,14 @@ func runCmd(cmd *cobra.Command, args []string) error { return fmt.Errorf("failed to create app service: %w", err) } + wegoConfig, err := kubeClient.GetWegoConfig(ctx, params.Namespace) + if err != nil { + return fmt.Errorf("failed getting wego config") + } + gitClient, gitProvider, err := factory.GetGitClients(ctx, kubeClient, providerClient, services.GitConfigParams{ URL: params.Url, - ConfigRepo: params.ConfigRepo, + ConfigRepo: wegoConfig.ConfigRepo, Namespace: params.Namespace, IsHelmRepository: params.IsHelmRepository(), DryRun: params.DryRun, diff --git a/cmd/gitops/install/cmd.go b/cmd/gitops/install/cmd.go index 708550b7855..46e330e0da8 100644 --- a/cmd/gitops/install/cmd.go +++ b/cmd/gitops/install/cmd.go @@ -11,8 +11,6 @@ import ( "strings" "github.com/spf13/cobra" - corev1 "k8s.io/api/core/v1" - wego "github.com/weaveworks/weave-gitops/api/v1alpha1" "github.com/weaveworks/weave-gitops/cmd/gitops/version" "github.com/weaveworks/weave-gitops/cmd/internal" @@ -26,6 +24,7 @@ import ( "github.com/weaveworks/weave-gitops/pkg/services/auth" "github.com/weaveworks/weave-gitops/pkg/services/gitopswriter" "github.com/weaveworks/weave-gitops/pkg/services/install" + corev1 "k8s.io/api/core/v1" ) type params struct { @@ -84,7 +83,11 @@ func installRunCmd(cmd *cobra.Command, args []string) error { } if installParams.DryRun { - manifests, err := models.BootstrapManifests(fluxClient, clusterName, namespace, configURL) + manifests, err := models.BootstrapManifests(fluxClient, kubeClient, models.BootstrapManifestsParams{ + ClusterName: clusterName, + WegoNamespace: namespace, + ConfigRepo: configURL, + }) if err != nil { return fmt.Errorf("failed getting gitops manifests: %w", err) } diff --git a/cmd/gitops/upgrade/cmd.go b/cmd/gitops/upgrade/cmd.go index a1cc489283d..ed82d849aaa 100644 --- a/cmd/gitops/upgrade/cmd.go +++ b/cmd/gitops/upgrade/cmd.go @@ -37,7 +37,6 @@ var Cmd = &cobra.Command{ } func init() { - Cmd.PersistentFlags().StringVar(&upgradeCmdFlags.ConfigRepo, "config-repo", "", "URL of external repository that will hold automation manifests") Cmd.PersistentFlags().StringVar(&upgradeCmdFlags.Version, "version", "", "Version of Weave GitOps Enterprise to be installed") Cmd.PersistentFlags().StringVar(&upgradeCmdFlags.BaseBranch, "base", "", "The base branch to open the pull request against") Cmd.PersistentFlags().StringVar(&upgradeCmdFlags.HeadBranch, "branch", "tier-upgrade-enterprise", "The branch to create the pull request from") @@ -45,7 +44,6 @@ func init() { Cmd.PersistentFlags().StringArrayVar(&upgradeCmdFlags.Values, "set", []string{}, "set profile values on the command line (can specify multiple or separate values with commas: key1=val1,key2=val2)") Cmd.PersistentFlags().BoolVar(&upgradeCmdFlags.DryRun, "dry-run", false, "Output the generated profile without creating a pull request") - cobra.CheckErr(Cmd.MarkPersistentFlagRequired("config-repo")) cobra.CheckErr(Cmd.MarkPersistentFlagRequired("version")) } @@ -70,6 +68,13 @@ func upgradeCmdRunE() func(*cobra.Command, []string) error { fluxClient := flux.New(osys.New(), &runner.CLIRunner{}) factory := services.NewFactory(fluxClient, log) + wegoConfig, err := kubeClient.GetWegoConfig(ctx, namespace) + if err != nil { + return fmt.Errorf("failed getting wego config") + } + + upgradeCmdFlags.ConfigRepo = wegoConfig.ConfigRepo + providerClient := internal.NewGitProviderClient(os.Stdout, os.LookupEnv, auth.NewAuthCLIHandler, log) gitClient, gitProvider, err := factory.GetGitClients(ctx, kubeClient, providerClient, services.GitConfigParams{ diff --git a/pkg/kube/kube.go b/pkg/kube/kube.go index baea97d7d8d..f54e9203894 100644 --- a/pkg/kube/kube.go +++ b/pkg/kube/kube.go @@ -44,6 +44,7 @@ var toStatusString = map[ClusterStatus]string{ type WegoConfig struct { FluxNamespace string WegoNamespace string + ConfigRepo string } //counterfeiter:generate . Kube diff --git a/pkg/models/manifest.go b/pkg/models/manifest.go index 81cb6f12139..ac8e1fbc0ee 100644 --- a/pkg/models/manifest.go +++ b/pkg/models/manifest.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "crypto/md5" + "errors" "fmt" "os" "path/filepath" @@ -47,9 +48,15 @@ const ( WegoConfigMapName = "weave-gitops-config" ) +type BootstrapManifestsParams struct { + ClusterName string + WegoNamespace string + ConfigRepo gitproviders.RepoURL +} + // BootstrapManifests creates all yaml files that are going to be applied to the cluster -func BootstrapManifests(fluxClient flux.Flux, clusterName string, namespace string, configURL gitproviders.RepoURL) ([]Manifest, error) { - runtimeManifests, err := fluxClient.Install(namespace, true) +func BootstrapManifests(fluxClient flux.Flux, kubeClient kube.Kube, params BootstrapManifestsParams) ([]Manifest, error) { + runtimeManifests, err := fluxClient.Install(params.WegoNamespace, true) if err != nil { return nil, fmt.Errorf("failed getting runtime manifests: %w", err) } @@ -59,31 +66,44 @@ func BootstrapManifests(fluxClient flux.Flux, clusterName string, namespace stri version = "latest" } - wegoAppManifests, err := manifests.GenerateWegoAppManifests(manifests.Params{AppVersion: version, Namespace: namespace}) + wegoAppManifests, err := manifests.GenerateWegoAppManifests(manifests.Params{AppVersion: version, Namespace: params.WegoNamespace}) if err != nil { return nil, fmt.Errorf("error generating wego-app manifest: %w", err) } wegoAppManifest := bytes.Join(wegoAppManifests, []byte("---\n")) - sourceName := CreateClusterSourceName(configURL) - systemResourceName := ConstrainResourceName(fmt.Sprintf("%s-system", clusterName)) + sourceName := CreateClusterSourceName(params.ConfigRepo) + systemResourceName := ConstrainResourceName(fmt.Sprintf("%s-system", params.ClusterName)) systemKustResourceManifest, err := fluxClient.CreateKustomization(systemResourceName, sourceName, - workAroundFluxDroppingDot(git.GetSystemPath(clusterName)), namespace) + workAroundFluxDroppingDot(git.GetSystemPath(params.ClusterName)), params.WegoNamespace) if err != nil { return nil, err } - userResourceName := ConstrainResourceName(fmt.Sprintf("%s-user", clusterName)) + userResourceName := ConstrainResourceName(fmt.Sprintf("%s-user", params.ClusterName)) userKustResourceManifest, err := fluxClient.CreateKustomization(userResourceName, sourceName, - workAroundFluxDroppingDot(git.GetUserPath(clusterName)), namespace) + workAroundFluxDroppingDot(git.GetUserPath(params.ClusterName)), params.WegoNamespace) if err != nil { return nil, err } - gitopsConfigMap, err := CreateGitopsConfigMap(namespace, namespace) + fluxNs := params.WegoNamespace + + fluxNamespace, err := kubeClient.FetchNamespaceWithLabel(context.Background(), flux.PartOfLabelKey, flux.PartOfLabelValue) + if err != nil { + if !errors.Is(err, kube.ErrNamespaceNotFound) { + return nil, fmt.Errorf("failed fetching flux namespace: %w", err) + } + } + + if fluxNamespace != nil { + fluxNs = fluxNamespace.Name + } + + gitopsConfigMap, err := CreateGitopsConfigMap(fluxNs, params.WegoNamespace, params.ConfigRepo.String()) if err != nil { return nil, err } @@ -95,63 +115,66 @@ func BootstrapManifests(fluxClient flux.Flux, clusterName string, namespace stri return []Manifest{ { - Path: git.GetSystemQualifiedPath(clusterName, AppCRDPath), + Path: git.GetSystemQualifiedPath(params.ClusterName, AppCRDPath), Content: manifests.AppCRD, }, { - Path: git.GetSystemQualifiedPath(clusterName, RuntimePath), + Path: git.GetSystemQualifiedPath(params.ClusterName, RuntimePath), Content: runtimeManifests, }, { - Path: git.GetSystemQualifiedPath(clusterName, SystemKustResourcePath), + Path: git.GetSystemQualifiedPath(params.ClusterName, SystemKustResourcePath), Content: systemKustResourceManifest, }, { - Path: git.GetSystemQualifiedPath(clusterName, UserKustResourcePath), + Path: git.GetSystemQualifiedPath(params.ClusterName, UserKustResourcePath), Content: userKustResourceManifest, }, { - Path: git.GetSystemQualifiedPath(clusterName, WegoAppPath), + Path: git.GetSystemQualifiedPath(params.ClusterName, WegoAppPath), Content: wegoAppManifest, }, { - Path: git.GetSystemQualifiedPath(clusterName, WegoConfigPath), + Path: git.GetSystemQualifiedPath(params.ClusterName, WegoConfigPath), Content: wegoConfigManifest, }, }, nil } -// GitopsManifests generates all yaml files that are going to be written in the config repo -func GitopsManifests(ctx context.Context, fluxClient flux.Flux, gitProvider gitproviders.GitProvider, clusterName string, namespace string, configURL gitproviders.RepoURL) ([]Manifest, error) { - bootstrapManifest, err := BootstrapManifests(fluxClient, clusterName, namespace, configURL) - if err != nil { - return nil, err - } +type GitopsManifestsParams struct { + FluxClient flux.Flux + GitProvider gitproviders.GitProvider + ClusterName string + WegoNamespace string + ConfigRepo gitproviders.RepoURL +} - systemKustomization := CreateKustomization(clusterName, namespace, RuntimePath, SourcePath, SystemKustResourcePath, UserKustResourcePath, WegoAppPath) +// GitopsManifests generates all yaml files that are going to be written in the config repo +func GitopsManifests(ctx context.Context, bootstrapManifests []Manifest, params GitopsManifestsParams) ([]Manifest, error) { + systemKustomization := CreateKustomization(params.ClusterName, params.WegoNamespace, RuntimePath, SourcePath, SystemKustResourcePath, UserKustResourcePath, WegoAppPath) systemKustomizationManifest, err := yaml.Marshal(systemKustomization) if err != nil { return nil, err } - configBranch, err := gitProvider.GetDefaultBranch(ctx, configURL) + configBranch, err := params.GitProvider.GetDefaultBranch(ctx, params.ConfigRepo) if err != nil { return nil, err } - sourceManifest, err := GetSourceManifest(ctx, fluxClient, gitProvider, clusterName, namespace, configURL, configBranch) + sourceManifest, err := GetSourceManifest(ctx, params.FluxClient, params.GitProvider, params.ClusterName, params.WegoNamespace, params.ConfigRepo, configBranch) if err != nil { return nil, err } - return append(bootstrapManifest, sourceManifest, // TODO: Move this to boostrap manifests until getGitClients is refactored + return append(bootstrapManifests, sourceManifest, // TODO: Move this to boostrap manifests until getGitClients is refactored Manifest{ - Path: git.GetSystemQualifiedPath(clusterName, SystemKustomizationPath), + Path: git.GetSystemQualifiedPath(params.ClusterName, SystemKustomizationPath), Content: systemKustomizationManifest, }, Manifest{ - Path: filepath.Join(git.GetUserPath(clusterName), ".keep"), + Path: filepath.Join(git.GetUserPath(params.ClusterName), ".keep"), Content: strconv.AppendQuote(nil, "# keep"), }), nil } @@ -251,9 +274,11 @@ func workAroundFluxDroppingDot(str string) string { return "." + str } -func CreateGitopsConfigMap(fluxNamespace string, wegoNamespace string) (corev1.ConfigMap, error) { +func CreateGitopsConfigMap(fluxNamespace string, wegoNamespace string, configRepo string) (corev1.ConfigMap, error) { config := kube.WegoConfig{ FluxNamespace: fluxNamespace, + WegoNamespace: wegoNamespace, + ConfigRepo: configRepo, } configBytes, err := yaml.Marshal(config) diff --git a/pkg/models/manifest_test.go b/pkg/models/manifest_test.go index e7840d9360c..247268a3c46 100644 --- a/pkg/models/manifest_test.go +++ b/pkg/models/manifest_test.go @@ -10,6 +10,9 @@ import ( "github.com/fluxcd/go-git-providers/gitprovider" "github.com/weaveworks/weave-gitops/pkg/gitproviders/gitprovidersfakes" + "github.com/weaveworks/weave-gitops/pkg/kube/kubefakes" + v1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" @@ -24,223 +27,238 @@ var _ = Describe("Installer", func() { var fakeFluxClient *fluxfakes.FakeFlux var fakeGitProvider *gitprovidersfakes.FakeGitProvider - const clusterName = "test-cluster" - const testNamespace = "test-namespace" - var configRepo gitproviders.RepoURL + var fakeKubeClient *kubefakes.FakeKube + var params = BootstrapManifestsParams{ + ClusterName: "test-cluster", + WegoNamespace: "test-namespace", + } var err error var _ = BeforeEach(func() { - fakeFluxClient = &fluxfakes.FakeFlux{} - configRepo, err = gitproviders.NewRepoURL("ssh://git@github.com/test-user/test-repo", true) - Expect(err).ShouldNot(HaveOccurred()) - }) + params.ConfigRepo, err = gitproviders.NewRepoURL("ssh://git@github.com/test-user/test-repo", true) - Context("BootstrapManifests", func() { + fakeFluxClient = &fluxfakes.FakeFlux{} + fakeKubeClient = &kubefakes.FakeKube{} + fakeKubeClient.FetchNamespaceWithLabelReturns(&v1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: params.WegoNamespace}}, nil) - Context("error paths", func() { - someError := errors.New("some error") - It("should fail getting runtime manifests", func() { + Context("BootstrapManifests", func() { + Context("error paths", func() { + someError := errors.New("some error") - fakeFluxClient.InstallReturns(nil, someError) + It("should fail getting runtime manifests", func() { + fakeFluxClient.InstallReturns(nil, someError) - _, err = BootstrapManifests(fakeFluxClient, clusterName, testNamespace, configRepo) - Expect(err.Error()).Should(ContainSubstring(someError.Error())) - }) + _, err = BootstrapManifests(fakeFluxClient, fakeKubeClient, params) + Expect(err.Error()).Should(ContainSubstring(someError.Error())) + }) - It("should fail creating system resource kustomization", func() { + It("should fail creating system resource kustomization", func() { - fakeFluxClient.InstallReturns(nil, nil) + fakeFluxClient.InstallReturns(nil, nil) - fakeFluxClient.CreateKustomizationReturns(nil, someError) + fakeFluxClient.CreateKustomizationReturns(nil, someError) - _, err = BootstrapManifests(fakeFluxClient, clusterName, testNamespace, configRepo) - Expect(err.Error()).Should(ContainSubstring(someError.Error())) - }) + _, err = BootstrapManifests(fakeFluxClient, fakeKubeClient, params) + Expect(err.Error()).Should(ContainSubstring(someError.Error())) + }) - It("should fail creating user resource kustomization", func() { + It("should fail creating user resource kustomization", func() { - fakeFluxClient.InstallReturns(nil, nil) + fakeFluxClient.InstallReturns(nil, nil) - fakeFluxClient.CreateKustomizationReturnsOnCall(0, nil, nil) - fakeFluxClient.CreateKustomizationReturnsOnCall(1, nil, someError) + fakeFluxClient.CreateKustomizationReturnsOnCall(0, nil, nil) + fakeFluxClient.CreateKustomizationReturnsOnCall(1, nil, someError) - _, err = BootstrapManifests(fakeFluxClient, clusterName, testNamespace, configRepo) - Expect(err.Error()).Should(ContainSubstring(someError.Error())) + _, err = BootstrapManifests(fakeFluxClient, fakeKubeClient, params) + Expect(err.Error()).Should(ContainSubstring(someError.Error())) + }) + }) + Context("success case", func() { + It("should pass successfully", func() { + + runtimeManifests := []byte("flux runtime content") + fakeFluxClient.InstallReturns(runtimeManifests, nil) + + systemKustomizationResourceManifest := []byte("system kustomization resource") + fakeFluxClient.CreateKustomizationReturnsOnCall(0, systemKustomizationResourceManifest, nil) + + userKustomizationResourceManifest := []byte("user kustomization resource") + fakeFluxClient.CreateKustomizationReturnsOnCall(1, userKustomizationResourceManifest, nil) + + wegoAppManifests, err := manifests.GenerateWegoAppManifests(manifests.Params{AppVersion: "v0.0.0", Namespace: params.WegoNamespace}) + Expect(err).ShouldNot(HaveOccurred()) + + wegoAppManifest := bytes.Join(wegoAppManifests, []byte("---\n")) + + gitopsConfigMap, err := CreateGitopsConfigMap(params.WegoNamespace, params.WegoNamespace, params.ConfigRepo.String()) + Expect(err).ShouldNot(HaveOccurred()) + + wegoConfigManifest, err := yaml.Marshal(gitopsConfigMap) + Expect(err).ShouldNot(HaveOccurred()) + + manifestsFiles, err := BootstrapManifests(fakeFluxClient, fakeKubeClient, params) + Expect(err).ShouldNot(HaveOccurred()) + expectedManifests := []Manifest{ + { + Path: git.GetSystemQualifiedPath(params.ClusterName, AppCRDPath), + Content: manifests.AppCRD, + }, + { + Path: git.GetSystemQualifiedPath(params.ClusterName, RuntimePath), + Content: runtimeManifests, + }, + { + Path: git.GetSystemQualifiedPath(params.ClusterName, SystemKustResourcePath), + Content: systemKustomizationResourceManifest, + }, + { + Path: git.GetSystemQualifiedPath(params.ClusterName, UserKustResourcePath), + Content: userKustomizationResourceManifest, + }, + { + Path: git.GetSystemQualifiedPath(params.ClusterName, WegoAppPath), + Content: wegoAppManifest, + }, + { + Path: git.GetSystemQualifiedPath(params.ClusterName, WegoConfigPath), + Content: wegoConfigManifest, + }, + } + + for ind, manifest := range manifestsFiles { + Expect(manifest.Path).Should(Equal(expectedManifests[ind].Path)) + Expect(string(manifest.Content)).Should(Equal(string(expectedManifests[ind].Content))) + } + + }) }) }) - Context("success case", func() { - It("should pass successfully", func() { - - runtimeManifests := []byte("flux runtime content") - fakeFluxClient.InstallReturns(runtimeManifests, nil) - - systemKustomizationResourceManifest := []byte("system kustomization resource") - fakeFluxClient.CreateKustomizationReturnsOnCall(0, systemKustomizationResourceManifest, nil) - userKustomizationResourceManifest := []byte("user kustomization resource") - fakeFluxClient.CreateKustomizationReturnsOnCall(1, userKustomizationResourceManifest, nil) + Context("GitopsManifests", func() { + var ctx context.Context + var boostrapManifests []Manifest + var params GitopsManifestsParams + BeforeEach(func() { + ctx = context.Background() + fakeFluxClient = &fluxfakes.FakeFlux{} + fakeGitProvider = &gitprovidersfakes.FakeGitProvider{} + fakeGitProvider.GetRepoVisibilityReturns(gitprovider.RepositoryVisibilityVar(gitprovider.RepositoryVisibilityPublic), nil) - wegoAppManifests, err := manifests.GenerateWegoAppManifests(manifests.Params{AppVersion: "v0.0.0", Namespace: testNamespace}) - Expect(err).ShouldNot(HaveOccurred()) - - wegoAppManifest := bytes.Join(wegoAppManifests, []byte("---\n")) + boostrapManifests = []Manifest{} - gitopsConfigMap, err := CreateGitopsConfigMap(testNamespace, testNamespace) + configRepo, err := gitproviders.NewRepoURL("ssh://git@github.com/test-user/test-repo", true) Expect(err).ShouldNot(HaveOccurred()) - wegoConfigManifest, err := yaml.Marshal(gitopsConfigMap) - Expect(err).ShouldNot(HaveOccurred()) - - manifestsFiles, err := BootstrapManifests(fakeFluxClient, clusterName, testNamespace, configRepo) - Expect(err).ShouldNot(HaveOccurred()) - - Expect(len(manifestsFiles)).Should(Equal(6)) - - expectedManifests := []Manifest{ - { - Path: git.GetSystemQualifiedPath(clusterName, AppCRDPath), - Content: manifests.AppCRD, - }, - { - Path: git.GetSystemQualifiedPath(clusterName, RuntimePath), - Content: runtimeManifests, - }, - { - Path: git.GetSystemQualifiedPath(clusterName, SystemKustResourcePath), - Content: systemKustomizationResourceManifest, - }, - { - Path: git.GetSystemQualifiedPath(clusterName, UserKustResourcePath), - Content: userKustomizationResourceManifest, - }, - { - Path: git.GetSystemQualifiedPath(clusterName, WegoAppPath), - Content: wegoAppManifest, - }, - { - Path: git.GetSystemQualifiedPath(clusterName, WegoConfigPath), - Content: wegoConfigManifest, - }, + params = GitopsManifestsParams{ + FluxClient: fakeFluxClient, + GitProvider: fakeGitProvider, + ClusterName: "test-cluster", + WegoNamespace: "test-namespace", + ConfigRepo: configRepo, } - - for ind, manifest := range manifestsFiles { - Expect(manifest.Path).Should(Equal(expectedManifests[ind].Path)) - Expect(string(manifest.Content)).Should(Equal(string(expectedManifests[ind].Content))) - } - }) - }) - }) - - Context("GitopsManifests", func() { - var ctx context.Context - BeforeEach(func() { - ctx = context.Background() - fakeGitProvider = &gitprovidersfakes.FakeGitProvider{} - }) - Context("error paths", func() { - someError := errors.New("some error") - It("should fail getting runtime manifests", func() { - - fakeFluxClient.InstallReturns(nil, someError) + Context("error paths", func() { + someError := errors.New("some error") + It("should fail getting runtime manifests", func() { + fakeGitProvider.GetDefaultBranchReturns("", someError) - _, err = GitopsManifests(ctx, fakeFluxClient, fakeGitProvider, clusterName, testNamespace, configRepo) - Expect(err.Error()).Should(ContainSubstring(someError.Error())) - }) + _, err = GitopsManifests(ctx, boostrapManifests, params) + Expect(err.Error()).Should(ContainSubstring(someError.Error())) + }) - It("should fail getting secret name for private git source", func() { - fakeFluxClient.InstallReturns(nil, nil) + It("should fail getting secret name for private git source", func() { + fakeFluxClient.InstallReturns(nil, nil) - fakeGitProvider.GetRepoVisibilityReturns(nil, someError) + fakeGitProvider.GetRepoVisibilityReturns(nil, someError) - _, err = GitopsManifests(ctx, fakeFluxClient, fakeGitProvider, clusterName, testNamespace, configRepo) - Expect(err.Error()).Should(ContainSubstring(someError.Error())) - }) + _, err = GitopsManifests(ctx, boostrapManifests, params) + Expect(err.Error()).Should(ContainSubstring(someError.Error())) + }) - It("should fail getting secret name for private git source", func() { - fakeFluxClient.InstallReturns(nil, nil) + It("should fail getting secret name for private git source", func() { + fakeFluxClient.InstallReturns(nil, nil) - privateVisibility := gitprovider.RepositoryVisibilityPrivate - fakeGitProvider.GetRepoVisibilityReturns(&privateVisibility, nil) + privateVisibility := gitprovider.RepositoryVisibilityPrivate + fakeGitProvider.GetRepoVisibilityReturns(&privateVisibility, nil) - fakeGitProvider.GetDefaultBranchReturns("", someError) + fakeGitProvider.GetDefaultBranchReturns("", someError) - _, err = GitopsManifests(ctx, fakeFluxClient, fakeGitProvider, clusterName, testNamespace, configRepo) - Expect(err.Error()).Should(ContainSubstring(someError.Error())) - }) + _, err = GitopsManifests(ctx, boostrapManifests, params) + Expect(err.Error()).Should(ContainSubstring(someError.Error())) + }) - It("should fail creating flux source", func() { - fakeFluxClient.InstallReturns(nil, nil) + It("should fail creating flux source", func() { + fakeFluxClient.InstallReturns(nil, nil) - privateVisibility := gitprovider.RepositoryVisibilityPrivate - fakeGitProvider.GetRepoVisibilityReturns(&privateVisibility, nil) + privateVisibility := gitprovider.RepositoryVisibilityPrivate + fakeGitProvider.GetRepoVisibilityReturns(&privateVisibility, nil) - fakeGitProvider.GetDefaultBranchReturns("main", nil) + fakeGitProvider.GetDefaultBranchReturns("main", nil) - fakeFluxClient.CreateSourceGitReturns(nil, someError) + fakeFluxClient.CreateSourceGitReturns(nil, someError) - _, err = GitopsManifests(ctx, fakeFluxClient, fakeGitProvider, clusterName, testNamespace, configRepo) - Expect(err.Error()).Should(ContainSubstring(someError.Error())) + _, err = GitopsManifests(ctx, boostrapManifests, params) + Expect(err.Error()).Should(ContainSubstring(someError.Error())) + }) + }) + Context("success case", func() { + It("should pass successfully", func() { + runtimeManifests := []byte("flux runtime content") + fakeFluxClient.InstallReturns(runtimeManifests, nil) + + privateVisibility := gitprovider.RepositoryVisibilityPrivate + fakeGitProvider.GetRepoVisibilityReturns(&privateVisibility, nil) + + fakeGitProvider.GetDefaultBranchReturns("main", nil) + + systemKustomization := CreateKustomization(params.ClusterName, params.WegoNamespace, RuntimePath, SourcePath, SystemKustResourcePath, UserKustResourcePath, WegoAppPath) + + systemKustomizationManifest, err := yaml.Marshal(systemKustomization) + Expect(err).ShouldNot(HaveOccurred()) + + gitSource := []byte("git source") + fakeFluxClient.CreateSourceGitReturns(gitSource, nil) + + manifestsFiles, err := GitopsManifests(ctx, boostrapManifests, params) + Expect(err).ShouldNot(HaveOccurred()) + + Expect(len(manifestsFiles)).Should(Equal(len(boostrapManifests) + 3)) + + expectedManifests := []Manifest{ + { + Path: git.GetSystemQualifiedPath(params.ClusterName, SourcePath), + Content: gitSource, + }, + { + Path: git.GetSystemQualifiedPath(params.ClusterName, SystemKustomizationPath), + Content: systemKustomizationManifest, + }, + { + Path: filepath.Join(git.GetUserPath(params.ClusterName), ".keep"), + Content: strconv.AppendQuote(nil, "# keep"), + }, + } + + for ind, manifest := range manifestsFiles { + Expect(manifest.Path).Should(Equal(expectedManifests[ind].Path)) + Expect(string(manifest.Content)).Should(Equal(string(expectedManifests[ind].Content))) + } + }) }) }) - Context("success case", func() { - It("should pass successfully", func() { - runtimeManifests := []byte("flux runtime content") - fakeFluxClient.InstallReturns(runtimeManifests, nil) - - privateVisibility := gitprovider.RepositoryVisibilityPrivate - fakeGitProvider.GetRepoVisibilityReturns(&privateVisibility, nil) - fakeGitProvider.GetDefaultBranchReturns("main", nil) - - systemKustomization := CreateKustomization(clusterName, testNamespace, RuntimePath, SourcePath, SystemKustResourcePath, UserKustResourcePath, WegoAppPath) - - systemKustomizationManifest, err := yaml.Marshal(systemKustomization) - Expect(err).ShouldNot(HaveOccurred()) - - gitSource := []byte("git source") - fakeFluxClient.CreateSourceGitReturns(gitSource, nil) - - manifestsFiles, err := GitopsManifests(ctx, fakeFluxClient, fakeGitProvider, clusterName, testNamespace, configRepo) - Expect(err).ShouldNot(HaveOccurred()) - - Expect(len(manifestsFiles)).Should(Equal(9)) - - expectedManifests := []Manifest{ - { - Path: git.GetSystemQualifiedPath(clusterName, SourcePath), - Content: gitSource, - }, - { - Path: git.GetSystemQualifiedPath(clusterName, SystemKustomizationPath), - Content: systemKustomizationManifest, - }, - { - Path: filepath.Join(git.GetUserPath(clusterName), ".keep"), - Content: strconv.AppendQuote(nil, "# keep"), - }, - } - - for ind, manifest := range manifestsFiles[6:] { - Expect(manifest.Path).Should(Equal(expectedManifests[ind].Path)) - Expect(string(manifest.Content)).Should(Equal(string(expectedManifests[ind].Content))) - } + Context("Validate name", func() { + It("should pass successfully", func() { + Expect(ValidateApplicationName("foobar")).ShouldNot(HaveOccurred()) + Expect(ValidateApplicationName("foobar-1234-test-bar-0123456")).ShouldNot(HaveOccurred()) + Expect(ValidateApplicationName("f")).ShouldNot(HaveOccurred()) + Expect(ValidateApplicationName("6")).ShouldNot(HaveOccurred()) + Expect(ValidateApplicationName(strings.Repeat("1", 63))).ShouldNot(HaveOccurred()) + }) + It("should fail", func() { + Expect(ValidateApplicationName("Special")).Should(HaveOccurred()) + Expect(ValidateApplicationName("foobar.baz")).Should(HaveOccurred()) + Expect(ValidateApplicationName(strings.Repeat("1", 64))).Should(HaveOccurred()) }) - - }) - }) - Context("Validate name", func() { - It("should pass successfully", func() { - Expect(ValidateApplicationName("foobar")).ShouldNot(HaveOccurred()) - Expect(ValidateApplicationName("foobar-1234-test-bar-0123456")).ShouldNot(HaveOccurred()) - Expect(ValidateApplicationName("f")).ShouldNot(HaveOccurred()) - Expect(ValidateApplicationName("6")).ShouldNot(HaveOccurred()) - Expect(ValidateApplicationName(strings.Repeat("1", 63))).ShouldNot(HaveOccurred()) - }) - It("should fail", func() { - Expect(ValidateApplicationName("Special")).Should(HaveOccurred()) - Expect(ValidateApplicationName("foobar.baz")).Should(HaveOccurred()) - Expect(ValidateApplicationName(strings.Repeat("1", 64))).Should(HaveOccurred()) }) }) - }) diff --git a/pkg/server/server.go b/pkg/server/server.go index 58bd464f38d..e4f5159b995 100644 --- a/pkg/server/server.go +++ b/pkg/server/server.go @@ -309,12 +309,14 @@ func (s *applicationServer) AddApplication(ctx context.Context, msg *pb.AddAppli return nil, grpcStatus.Errorf(codes.InvalidArgument, "unable to parse app url %q: %s", msg.Url, err) } - var configRepo gitproviders.RepoURL - if msg.ConfigRepo != "" { - configRepo, err = gitproviders.NewRepoURL(msg.ConfigRepo, true) - if err != nil { - return nil, grpcStatus.Errorf(codes.InvalidArgument, "unable to parse config url %q: %s", msg.ConfigRepo, err) - } + wegoConfig, err := kubeClient.GetWegoConfig(ctx, msg.Namespace) + if err != nil { + return nil, fmt.Errorf("failed getting wego config") + } + + configRepo, err := gitproviders.NewRepoURL(wegoConfig.ConfigRepo, true) + if err != nil { + return nil, grpcStatus.Errorf(codes.InvalidArgument, "unable to parse config url %q: %s", wegoConfig.ConfigRepo, err) } appSrv, err := s.factory.GetAppService(ctx, kubeClient) @@ -337,7 +339,7 @@ func (s *applicationServer) AddApplication(ctx context.Context, msg *pb.AddAppli gitClient, gitProvider, err := s.factory.GetGitClients(ctx, kubeClient, client, services.GitConfigParams{ URL: msg.Url, - ConfigRepo: msg.ConfigRepo, + ConfigRepo: wegoConfig.ConfigRepo, Namespace: msg.Namespace, }) if err != nil { diff --git a/pkg/server/server_test.go b/pkg/server/server_test.go index a5b1fc24761..6bf54bd46f4 100644 --- a/pkg/server/server_test.go +++ b/pkg/server/server_test.go @@ -538,6 +538,26 @@ var _ = Describe("ApplicationsServer", func() { }) Describe("AddApplication", func() { + BeforeEach(func() { + cm := &corev1.ConfigMap{ + TypeMeta: metav1.TypeMeta{ + Kind: "ConfigMap", + APIVersion: corev1.SchemeGroupVersion.String(), + }, + ObjectMeta: metav1.ObjectMeta{ + Name: "weave-gitops-config", + Namespace: namespace.Name, + }, + Data: map[string]string{ + "config": fmt.Sprintf(`--- +WegoNamespace: %s +FluxNamespace: %s +ConfigRepo: %s`, namespace.Name, namespace.Name, "ssh://git@github.com/some-org/my-config-url.git"), + }, + } + Expect(k8sClient.Create(context.Background(), cm)).To(Succeed()) + }) + It("adds an app with an unspecified config repo", func() { ctx := context.Background() name := "my-app" diff --git a/pkg/services/app/add.go b/pkg/services/app/add.go index a67c13e3683..a4825beb24e 100644 --- a/pkg/services/app/add.go +++ b/pkg/services/app/add.go @@ -2,7 +2,6 @@ package app import ( "context" - "errors" "fmt" "strings" @@ -142,9 +141,6 @@ func (a *AppSvc) updateParametersIfNecessary(ctx context.Context, gitProvider gi return params, fmt.Errorf("--url must be specified for helm repositories") } - if params.ConfigRepo == "" { - return params, errors.New("--config-repo should be provided") - } default: var err error diff --git a/pkg/services/app/add_test.go b/pkg/services/app/add_test.go index ce57ab6ee39..ed7681db84b 100644 --- a/pkg/services/app/add_test.go +++ b/pkg/services/app/add_test.go @@ -67,15 +67,6 @@ var _ = Describe("Add", func() { Expect(kubeClient.GetClusterNameCallCount()).To(Equal(1)) }) - It("validates config-repo is set when source is helm", func() { - addParams.Chart = "my-chart" - addParams.Url = "https://my-chart.com" - addParams.ConfigRepo = "" - - err := appSrv.Add(gitClient, gitProviders, addParams) - Expect(err.Error()).Should(HaveSuffix("--config-repo should be provided")) - }) - It("validates invalid chartname is handled", func() { addParams.Chart = "invalid_Chartname.bar" addParams.Url = "https://my-chart.com" diff --git a/pkg/services/install/install.go b/pkg/services/install/install.go index 36647c2b820..f134103ff5e 100644 --- a/pkg/services/install/install.go +++ b/pkg/services/install/install.go @@ -57,7 +57,11 @@ func (i *install) Install(namespace string, configURL gitproviders.RepoURL, auto return fmt.Errorf("failed installing flux: %w", err) } - manifests, err := models.BootstrapManifests(i.fluxClient, clusterName, namespace, configURL) + bootstrapManifests, err := models.BootstrapManifests(i.fluxClient, i.kubeClient, models.BootstrapManifestsParams{ + ClusterName: clusterName, + WegoNamespace: namespace, + ConfigRepo: configURL, + }) if err != nil { return fmt.Errorf("failed getting bootstrap manifests: %w", err) } @@ -73,7 +77,7 @@ func (i *install) Install(namespace string, configURL gitproviders.RepoURL, auto return fmt.Errorf("failed getting git source: %w", err) } - manifests = append(manifests, source) + manifests := append(bootstrapManifests, source) for _, manifest := range manifests { ms := bytes.Split(manifest.Content, []byte("---\n")) @@ -89,7 +93,13 @@ func (i *install) Install(namespace string, configURL gitproviders.RepoURL, auto } } - gitopsManifests, err := models.GitopsManifests(ctx, i.fluxClient, i.gitProviderClient, clusterName, namespace, configURL) + gitopsManifests, err := models.GitopsManifests(ctx, bootstrapManifests, models.GitopsManifestsParams{ + FluxClient: i.fluxClient, + GitProvider: i.gitProviderClient, + ClusterName: clusterName, + WegoNamespace: namespace, + ConfigRepo: configURL, + }) if err != nil { return fmt.Errorf("failed generating gitops manifests: %w", err) } diff --git a/pkg/services/install/install_test.go b/pkg/services/install/install_test.go index 69475bb8fc7..2f1e3d8c6d7 100644 --- a/pkg/services/install/install_test.go +++ b/pkg/services/install/install_test.go @@ -9,6 +9,7 @@ import ( "strconv" "github.com/fluxcd/go-git-providers/gitprovider" + v1 "k8s.io/api/core/v1" "sigs.k8s.io/yaml" "github.com/weaveworks/weave-gitops/manifests" @@ -23,6 +24,7 @@ import ( "github.com/weaveworks/weave-gitops/pkg/logger/loggerfakes" "github.com/weaveworks/weave-gitops/pkg/models" "github.com/weaveworks/weave-gitops/pkg/services/gitopswriter" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" @@ -47,6 +49,7 @@ var _ = Describe("Installer", func() { Expect(err).ShouldNot(HaveOccurred()) fakeFluxClient = &fluxfakes.FakeFlux{} fakeKubeClient = &kubefakes.FakeKube{} + fakeKubeClient.FetchNamespaceWithLabelReturns(&v1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: testNamespace}}, nil) fakeGitClient = &gitfakes.FakeGit{} fakeGitProvider = &gitprovidersfakes.FakeGitProvider{} log = &loggerfakes.FakeLogger{} @@ -60,6 +63,7 @@ var _ = Describe("Installer", func() { BeforeEach(func() { fakeKubeClient.GetClusterStatusReturns(kube.Unmodified) fakeKubeClient.GetWegoConfigReturns(&kube.WegoConfig{ + ConfigRepo: configRepo.String(), FluxNamespace: testNamespace, WegoNamespace: testNamespace, }, nil) @@ -115,7 +119,6 @@ var _ = Describe("Installer", func() { }) It("should fail getting config repo git source", func() { - fakeGitProvider.GetRepoVisibilityReturns(nil, someError) err := installer.Install(testNamespace, configRepo, true) @@ -130,10 +133,10 @@ var _ = Describe("Installer", func() { }) It("should fail getting gitops manifests", func() { - fakeFluxClient.InstallReturnsOnCall(2, nil, someError) + fakeFluxClient.InstallReturnsOnCall(1, nil, someError) err := installer.Install(testNamespace, configRepo, true) - Expect(err).Should(MatchError(fmt.Sprintf("failed generating gitops manifests: failed getting runtime manifests: %s", someError))) + Expect(err.Error()).Should(ContainSubstring(fmt.Sprintf("failed getting runtime manifests: %s", someError))) }) It("should fail writing directly to branch", func() { @@ -163,6 +166,7 @@ var _ = Describe("Installer", func() { BeforeEach(func() { fakeKubeClient.GetClusterStatusReturns(kube.Unmodified) fakeKubeClient.GetWegoConfigReturns(&kube.WegoConfig{ + ConfigRepo: configRepo.String(), FluxNamespace: testNamespace, WegoNamespace: testNamespace, }, nil) @@ -193,7 +197,7 @@ var _ = Describe("Installer", func() { fakeFluxClient.CreateKustomizationReturnsOnCall(2, systemKustomizationResource, nil) fakeFluxClient.CreateKustomizationReturnsOnCall(3, userKustomizationResource, nil) - gitopsConfigMap, err := models.CreateGitopsConfigMap(testNamespace, testNamespace) + gitopsConfigMap, err := models.CreateGitopsConfigMap(testNamespace, testNamespace, configRepo.String()) Expect(err).ShouldNot(HaveOccurred()) wegoConfigManifest, err = yaml.Marshal(gitopsConfigMap) @@ -209,50 +213,6 @@ var _ = Describe("Installer", func() { }) It("should succeed with auto-merge=true", func() { - //fakeKubeClient.GetClusterStatusReturns(kube.Unmodified) - //fakeKubeClient.GetWegoConfigReturns(&kube.WegoConfig{ - // FluxNamespace: testNamespace, - // WegoNamespace: testNamespace, - //}, nil) - //fakeKubeClient.GetClusterNameReturns(clusterName, nil) - // - //fakeGitProvider.GetDefaultBranchReturnsOnCall(0, "main", nil) - // - //privateVisibility := gitprovider.RepositoryVisibilityPrivate - //fakeGitProvider.GetRepoVisibilityReturns(&privateVisibility, nil) - // - //fakeKubeClient.ApplyReturns(nil) - // - //runtimeManifests := []byte("runtime-manifests") - //fakeFluxClient.InstallReturns(runtimeManifests, nil) - // - //wegoAppManifests, err := manifests.GenerateWegoAppManifests(manifests.Params{AppVersion: "v0.0.0", Namespace: testNamespace}) - //Expect(err).ShouldNot(HaveOccurred()) - // - //wegoAppManifest := bytes.Join(wegoAppManifests, []byte("---\n")) - // - //systemKustomizationResource := []byte("system kustomization resource") - //fakeFluxClient.CreateKustomizationReturnsOnCall(0, systemKustomizationResource, nil) - //userKustomizationResource := []byte("user kustomization resource") - //fakeFluxClient.CreateKustomizationReturnsOnCall(1, userKustomizationResource, nil) - // - //fakeFluxClient.CreateKustomizationReturnsOnCall(2, systemKustomizationResource, nil) - //fakeFluxClient.CreateKustomizationReturnsOnCall(3, userKustomizationResource, nil) - // - //gitopsConfigMap, err := models.CreateGitopsConfigMap(testNamespace, testNamespace) - //Expect(err).ShouldNot(HaveOccurred()) - // - //wegoConfigManifest, err := yaml.Marshal(gitopsConfigMap) - //Expect(err).ShouldNot(HaveOccurred()) - // - //systemKustomization := models.CreateKustomization(clusterName, testNamespace, models.RuntimePath, models.SourcePath, models.SystemKustResourcePath, models.UserKustResourcePath, models.WegoAppPath) - // - //systemKustomizationManifest, err := yaml.Marshal(systemKustomization) - //Expect(err).ShouldNot(HaveOccurred()) - // - //source, err := models.GetSourceManifest(context.Background(), fakeFluxClient, fakeGitProvider, clusterName, testNamespace, configRepo, "main") - //Expect(err).ShouldNot(HaveOccurred()) - expectedManifests := []models.Manifest{ { Path: git.GetSystemQualifiedPath(clusterName, models.AppCRDPath), diff --git a/test/acceptance/test/add_tests.go b/test/acceptance/test/add_tests.go index 64e80c5c4e5..c631981b5ba 100644 --- a/test/acceptance/test/add_tests.go +++ b/test/acceptance/test/add_tests.go @@ -151,11 +151,11 @@ var _ = Describe("Weave GitOps Add App Tests", func() { }) By("Then I should see error message", func() { - Eventually(errOutput).Should(ContainSubstring("required flag(s) \"config-repo\", \"version\" not set")) + Eventually(errOutput).Should(ContainSubstring("required flag(s) \"version\" not set")) }) - By("When I try to upgrade gitops core to enterprise with config-repo & version provided", func() { - _, errOutput = runCommandAndReturnStringOutput(gitopsBinaryPath + " upgrade --config-repo=" + appRepoRemoteURL + " --version=0.0.1") + By("When I try to upgrade gitops core to enterprise and version provided", func() { + _, errOutput = runCommandAndReturnStringOutput(gitopsBinaryPath + " upgrade --version=0.0.1") }) By("Then I should see error message", func() { @@ -1304,8 +1304,6 @@ var _ = Describe("Weave GitOps Add App Tests", func() { appRepoRemoteURL := "ssh://git@" + gitProviderName + ".com/" + gitOrg + "/" + appRepoName + ".git" helmRepoURL := "https://charts.kube-ops.io" - invalidAddCommand := "add app --url=" + helmRepoURL + " --chart=" + appName1 + " --auto-merge=true" - addCommand1 := "add app --url=" + helmRepoURL + " --chart=" + appName1 + " --config-repo=" + appRepoRemoteURL + " --auto-merge=true --helm-release-target-namespace=" + workloadNamespace addCommand2 := "add app --url=" + helmRepoURL + " --chart=" + appName2 + " --config-repo=" + appRepoRemoteURL + " --auto-merge=true --helm-release-target-namespace=" + workloadNamespace @@ -1337,11 +1335,6 @@ var _ = Describe("Weave GitOps Add App Tests", func() { Eventually(out).Should(ContainSubstring("namespace/" + workloadNamespace + " created")) }) - By("And I add an invalid entry without --config-repo set", func() { - _, err := runWegoAddCommandWithOutput(repoAbsolutePath, invalidAddCommand, WEGO_DEFAULT_NAMESPACE) - Eventually(err).Should(ContainSubstring("--config-repo should be provided")) - }) - By("And I run gitops add app command for 1st app", func() { runWegoAddCommand(repoAbsolutePath, addCommand1, WEGO_DEFAULT_NAMESPACE) }) diff --git a/test/acceptance/test/help_tests.go b/test/acceptance/test/help_tests.go index 7d128fbd008..ab8cd551719 100644 --- a/test/acceptance/test/help_tests.go +++ b/test/acceptance/test/help_tests.go @@ -82,7 +82,6 @@ var _ = XDescribe("WEGO Help Tests", func() { Eventually(stringOutput).Should(MatchRegexp(`Associates an additional application in a git repository with a gitops cluster so that its contents may be managed via GitOps\n*Usage:`)) Eventually(stringOutput).Should(MatchRegexp(`gitops add app \[--name ] \[--url ] \[--branch ] \[--path ] \ \[flags]`)) Eventually(stringOutput).Should(MatchRegexp(`Examples:\ngitops add app .\n*Flags:`)) - Eventually(stringOutput).Should(MatchRegexp(`--config-repo string\s*URL of external repository \(if any\) which will hold automation manifests`)) Eventually(stringOutput).Should(MatchRegexp(`--auto-merge\s*If set, 'gitops add app' will merge automatically into the set`)) Eventually(stringOutput).Should(MatchRegexp(`--branch\n\s*--branch string\s*Branch to watch within git repository \(default "main"\)`)) Eventually(stringOutput).Should(MatchRegexp(`--chart string\s*Specify chart for helm source`)) diff --git a/test/integration/server/add_test.go b/test/integration/server/add_test.go index ab38f8f86a9..52056340384 100644 --- a/test/integration/server/add_test.go +++ b/test/integration/server/add_test.go @@ -79,6 +79,8 @@ var _ = XDescribe("AddApplication", func() { sourceRepo, sourceRef, err = helpers.CreatePopulatedSourceRepo(ctx, gp, sourceRepoURL) Expect(err).NotTo(HaveOccurred()) + Expect(helpers.SetWegoConfig(env.Client, namespace.Name, sourceRepoURL)).To(Succeed()) + appName = "my-app" addAppRequest = &pb.AddApplicationRequest{ @@ -163,11 +165,12 @@ var _ = XDescribe("AddApplication", func() { } }) It("adds an app with an external config repo", func() { - defer func() { Expect(sourceRepo.Delete(ctx)).To(Succeed()) }() configRepoURL := fmt.Sprintf("https://github.com/%s/%s", githubOrg, configRepoName) + Expect(helpers.SetWegoConfig(env.Client, namespace.Name, configRepoURL)).To(Succeed()) + configRepo, configRef, err := helpers.CreateRepo(ctx, gp, configRepoURL) Expect(err).NotTo(HaveOccurred()) @@ -381,6 +384,7 @@ var _ = XDescribe("AddApplication", func() { defer func() { Expect(sourceRepo.Delete(ctx)).To(Succeed()) }() configRepoURL := fmt.Sprintf("https://github.com/%s/%s", githubOrg, configRepoName) + Expect(helpers.SetWegoConfig(env.Client, namespace.Name, configRepoURL)).To(Succeed()) configRepo, configRef, err := helpers.CreateRepo(ctx, gp, configRepoURL) Expect(err).NotTo(HaveOccurred()) @@ -493,6 +497,8 @@ var _ = XDescribe("AddApplication", func() { Expect(err).NotTo(HaveOccurred()) sourceRepoURL = fmt.Sprintf("https://gitlab.com/%s/%s", gitlabOrg, sourceRepoName) + Expect(helpers.SetWegoConfig(env.Client, namespace.Name, sourceRepoURL)).To(Succeed()) + sourceRepo, sourceRef, err = helpers.CreatePopulatedSourceRepo(ctx, gitlabProviderClient, sourceRepoURL) Expect(err).NotTo(HaveOccurred()) @@ -585,6 +591,8 @@ var _ = XDescribe("AddApplication", func() { configRepoURL := fmt.Sprintf("https://gitlab.com/%s/%s", gitlabOrg, configRepoName) + Expect(helpers.SetWegoConfig(env.Client, namespace.Name, configRepoURL)).To(Succeed()) + configRepo, configRef, err := helpers.CreateRepo(ctx, gitlabProviderClient, configRepoURL) Expect(err).NotTo(HaveOccurred()) diff --git a/test/integration/server/helpers/helpers.go b/test/integration/server/helpers/helpers.go index a9b484e4a01..aa1c1b6eb11 100644 --- a/test/integration/server/helpers/helpers.go +++ b/test/integration/server/helpers/helpers.go @@ -15,6 +15,7 @@ import ( "time" glAPI "github.com/xanzy/go-gitlab" + "sigs.k8s.io/controller-runtime/pkg/client" "github.com/fluxcd/go-git-providers/gitprovider" kustomizev2 "github.com/fluxcd/kustomize-controller/api/v1beta2" @@ -22,10 +23,13 @@ import ( "github.com/google/go-cmp/cmp" "github.com/google/go-cmp/cmp/cmpopts" ghAPI "github.com/google/go-github/v32/github" + corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" "github.com/fluxcd/source-controller/pkg/sourceignore" wego "github.com/weaveworks/weave-gitops/api/v1alpha1" pb "github.com/weaveworks/weave-gitops/pkg/api/applications" + "github.com/weaveworks/weave-gitops/pkg/models" "github.com/weaveworks/weave-gitops/pkg/utils" "golang.org/x/oauth2" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -82,6 +86,41 @@ func CreateRepo(ctx context.Context, gp gitprovider.Client, url string) (gitprov return repo, ref, err } +func SetWegoConfig(k8sClient client.Client, namespace string, configRepo string) error { + ctx := context.Background() + + cm := &corev1.ConfigMap{ + TypeMeta: metav1.TypeMeta{ + Kind: "ConfigMap", + APIVersion: corev1.SchemeGroupVersion.String(), + }, + ObjectMeta: metav1.ObjectMeta{ + Name: models.WegoConfigMapName, + Namespace: namespace, + }, + } + + key := client.ObjectKeyFromObject(cm) + if err := k8sClient.Get(ctx, key, cm); err != nil { + if !apierrors.IsNotFound(err) { + return err + } + + if err := k8sClient.Create(ctx, cm); err != nil { + return err + } + } + + cm.Data = map[string]string{ + "config": fmt.Sprintf(` +WegoNamespace: %s +FluxNamespace: %s +ConfigRepo: %s`, namespace, namespace, configRepo), + } + + return k8sClient.Update(ctx, cm) +} + func addFiles(ctx context.Context, message string, repo gitprovider.OrgRepository, files []gitprovider.CommitFile) error { _, err := repo.Commits().Create(ctx, "main", "Initial commit", []gitprovider.CommitFile{ { diff --git a/test/integration/server/remove_test.go b/test/integration/server/remove_test.go index 0679a5ccc70..c6053ddbc75 100644 --- a/test/integration/server/remove_test.go +++ b/test/integration/server/remove_test.go @@ -65,6 +65,7 @@ var _ = XDescribe("RemoveApplication", func() { ) Expect(err).NotTo(HaveOccurred()) sourceRepoURL = fmt.Sprintf("https://github.com/%s/%s", githubOrg, sourceRepoName) + Expect(helpers.SetWegoConfig(env.Client, namespace.Name, sourceRepoURL)).To(Succeed()) sourceRepo, sourceRef, err = helpers.CreatePopulatedSourceRepo(ctx, gp, sourceRepoURL) Expect(err).NotTo(HaveOccurred()) @@ -232,7 +233,7 @@ var _ = XDescribe("RemoveApplication", func() { gitlabAPIClient, err = glAPI.NewClient(gitlabToken) Expect(err).NotTo(HaveOccurred()) sourceRepoURL = fmt.Sprintf("https://gitlab.com/%s/%s", gitlabGroup, sourceRepoName) - + Expect(helpers.SetWegoConfig(env.Client, namespace.Name, sourceRepoURL)).To(Succeed()) sourceRepo, sourceRef, err = helpers.CreatePopulatedSourceRepo(ctx, gitlabProviderClient, sourceRepoURL) Expect(err).NotTo(HaveOccurred())