Repository: kubesphere/ks-devops
Pull request #541 (2022-04-12 03:30:05)

The AppProject CR should be in the argocd namespace
<!-- Thanks for sending a pull request! Here are some tips for you:

1. If you want **faster** PR reviews, read how: https://github.com/kubesphere/community/blob/master/developer-guide/development/the-pr-author-guide-to-getting-through-code-review.md
2. In case you want to know how your PR got reviewed, read: https://github.com/kubesphere/community/blob/master/developer-guide/development/code-review-guide.md
3. Here are some coding conventions followed by the KubeSphere community: https://github.com/kubesphere/community/blob/master/developer-guide/development/coding-conventions.md
4. Additional open-source best practice: https://github.com/LinuxSuRen/open-source-best-practice
-->

### What type of PR is this?
<!-- 
Add one of the following kinds:
/kind bug
/kind cleanup
/kind documentation
/kind feature
/kind design
/kind chore

Optionally add one or more of the following kinds if applicable:
/kind api-change
/kind deprecation
/kind failing-test
/kind flake
/kind regression
-->
/kind bug

### What this PR does / why we need it:

### Which issue(s) this PR fixes:
<!--
Usage: `Fixes #<issue number>`, or `Fixes (paste link of issue)`.
_If PR is about `failing-tests or flakes`, please post the related issues/tests in a comment and do not use `Fixes`_*
Please leave it or change # to be None if there is no corresponding issue that exists
-->
Fixes #

### Special notes for reviewers:
<!--
You can use the following command to let the DevOps SIG members help you to review your PR.
/cc @kubesphere/sig-devops 
And please avoid cc any individual.
-->
Please check the following list before waiting reviewers:

- [ ] Already committed the CRD files to [the Helm Chart](https://github.com/kubesphere-sigs/ks-devops-helm-chart/) if you created some new CRDs
- [ ] Already [added the permission](https://github.com/kubesphere/ks-installer/blob/9e063b085a0e43fdb3d0d9e3e7f4149146f14b9c/roles/ks-core/prepare/files/ks-init/role-templates.yaml) for the new API
- [ ] Already added the RBAC markers for the new controllers

### Does this PR introduce a user-facing change??
<!--
If no, just write "None" in the release-note block below.
If yes, a release note is required:
Enter your extended-release note in the block below. If the PR requires additional action from users switching to the new release, include the string "action required".

Please keep the note be same as your PR title if you believe it should be in the release notes.
-->
```release-note
None
```


ks-ci-bot: [APPROVALNOTIFIER] This PR is **APPROVED**

This pull-request has been approved by: *<a href="https://github.com/kubesphere/ks-devops/pull/541#" title="Author self-approved">LinuxSuRen</a>*

The full list of commands accepted by this bot can be found [here](https://go.k8s.io/bot-commands?repo=kubesphere%2Fks-devops).

The pull request process is described [here](https://git.k8s.io/community/contributors/guide/owners.md#the-code-review-process)

<details >
Needs approval from an approver in each of these files:

- ~~[OWNERS](https://github.com/kubesphere/ks-devops/blob/master/OWNERS)~~ [LinuxSuRen]

Approvers can indicate their approval by writing `/approve` in a comment
Approvers can cancel approval by writing `/approve cancel` in a comment
</details>
<!-- META={"approvers":[]} -->
codecov[bot]: # [Codecov](https://codecov.io/gh/kubesphere/ks-devops/pull/541?src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=kubesphere) Report
> Merging [#541](https://codecov.io/gh/kubesphere/ks-devops/pull/541?src=pr&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=kubesphere) (eda1a30) into [master](https://codecov.io/gh/kubesphere/ks-devops/commit/3f37fccef5bddad6c3f11bd4424018f9d5f5a50f?el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=kubesphere) (3f37fcc) will **not change** coverage.
> The diff coverage is `100.00%`.

```diff
@@           Coverage Diff           @@
##           master     #541   +/-   ##
=======================================
  Coverage   77.41%   77.41%           
=======================================
  Files         143      143           
  Lines       23202    23202           
=======================================
  Hits        17961    17961           
+ Misses       5030     5029    -1     
- Partials      211      212    +1     
```

| Flag | Coverage Δ | |
|---|---|---|
| unittests | `77.41% <100.00%> (ø)` | |

Flags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=kubesphere#carryforward-flags-in-the-pull-request-comment) to find out more.

| [Impacted Files](https://codecov.io/gh/kubesphere/ks-devops/pull/541?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=kubesphere) | Coverage Δ | |
|---|---|---|
| [controllers/argocd/project\_controller.go](https://codecov.io/gh/kubesphere/ks-devops/pull/541/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=kubesphere#diff-Y29udHJvbGxlcnMvYXJnb2NkL3Byb2plY3RfY29udHJvbGxlci5nbw==) | `61.53% <100.00%> (ø)` | |
| [...ontrollers/jenkins/pipeline/pipeline\_controller.go](https://codecov.io/gh/kubesphere/ks-devops/pull/541/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=kubesphere#diff-Y29udHJvbGxlcnMvamVua2lucy9waXBlbGluZS9waXBlbGluZV9jb250cm9sbGVyLmdv) | `39.39% <0.00%> (-3.79%)` | :arrow_down: |
| [...ns/devopscredential/devopscredential\_controller.go](https://codecov.io/gh/kubesphere/ks-devops/pull/541/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=kubesphere#diff-Y29udHJvbGxlcnMvamVua2lucy9kZXZvcHNjcmVkZW50aWFsL2Rldm9wc2NyZWRlbnRpYWxfY29udHJvbGxlci5nbw==) | `36.73% <0.00%> (+3.40%)` | :arrow_up: |

------

[Continue to review full report at Codecov](https://codecov.io/gh/kubesphere/ks-devops/pull/541?src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=kubesphere).
> **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=kubesphere)
> `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
> Powered by [Codecov](https://codecov.io/gh/kubesphere/ks-devops/pull/541?src=pr&el=footer&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=kubesphere). Last update [3f37fcc...eda1a30](https://codecov.io/gh/kubesphere/ks-devops/pull/541?src=pr&el=lastupdated&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=kubesphere). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=kubesphere).


Patch:
diff --git a/cmd/controller/app/controllers.go b/cmd/controller/app/controllers.go
index 1281460..51ced88 100644
--- a/cmd/controller/app/controllers.go
+++ b/cmd/controller/app/controllers.go
@@ -97,7 +97,8 @@ func getAllControllers(mgr manager.Manager, client k8s.Client, informerFactory i
 	s *options.DevOpsControllerManagerOptions) map[string]func(mgr manager.Manager) error {
 
 	argocdReconciler := &argocd.Reconciler{
-		Client: mgr.GetClient(),
+		Client:        mgr.GetClient(),
+		ArgoNamespace: s.ArgoCDOption.Namespace,
 	}
 	argocdAppReconciler := &argocd.ApplicationReconciler{
 		Client: mgr.GetClient(),
diff --git a/controllers/argocd/project_controller.go b/controllers/argocd/project_controller.go
index 0a0ad02..346fad3 100644
--- a/controllers/argocd/project_controller.go
+++ b/controllers/argocd/project_controller.go
@@ -42,6 +42,8 @@ type Reconciler struct {
 	client.Client
 	log      logr.Logger
 	recorder record.EventRecorder
+
+	ArgoNamespace string
 }
 
 // Reconcile makes sure the ArgoAppProject can be maintained which comes from the DevOpsProject
@@ -85,21 +87,21 @@ func (r *Reconciler) reconcileArgoProject(project *v1alpha3.DevOpsProject) (err
 	argoAppProject.SetAPIVersion("argoproj.io/v1alpha1")
 
 	if err = r.Client.Get(ctx, types.NamespacedName{
-		Namespace: project.Name,
+		Namespace: r.ArgoNamespace,
 		Name:      project.Name,
 	}, argoAppProject); err != nil {
 		if !apierrors.IsNotFound(err) {
 			return
 		}
 
-		if argoAppProject, err = createUnstructuredObject(project); err != nil {
+		if argoAppProject, err = createUnstructuredObject(project, r.ArgoNamespace); err != nil {
 			return
 		}
 
 		err = r.Client.Create(ctx, argoAppProject)
 	} else {
 		var newProject *unstructured.Unstructured
-		if newProject, err = createUnstructuredObject(project); err == nil {
+		if newProject, err = createUnstructuredObject(project, r.ArgoNamespace); err == nil {
 			argoAppProject.Object["spec"] = newProject.Object["spec"]
 			k8sutil.AddOwnerReference(argoAppProject, project.TypeMeta, project.ObjectMeta)
 			err = r.Client.Update(ctx, argoAppProject)
@@ -108,7 +110,7 @@ func (r *Reconciler) reconcileArgoProject(project *v1alpha3.DevOpsProject) (err
 	return
 }
 
-func createUnstructuredObject(project *v1alpha3.DevOpsProject) (result *unstructured.Unstructured, err error) {
+func createUnstructuredObject(project *v1alpha3.DevOpsProject, argocdNamespace string) (result *unstructured.Unstructured, err error) {
 	project = project.DeepCopy()
 	if project.Spec.Argo == nil {
 		err = fmt.Errorf("no argo found from the spec")
@@ -142,7 +144,7 @@ func createUnstructuredObject(project *v1alpha3.DevOpsProject) (result *unstruct
 	if err = tpl.Execute(buffer, argo); err == nil {
 		if result, err = GetObjectFromYaml(buffer.String()); err == nil {
 			result.SetName(project.GetName())
-			result.SetNamespace(project.GetName())
+			result.SetNamespace(argocdNamespace)
 			k8sutil.AddOwnerReference(result, project.TypeMeta, project.ObjectMeta)
 		}
 	}


Test patch:
diff --git a/controllers/argocd/project_controller_test.go b/controllers/argocd/project_controller_test.go
index e774f02..aa0a0d8 100644
--- a/controllers/argocd/project_controller_test.go
+++ b/controllers/argocd/project_controller_test.go
@@ -32,9 +32,10 @@ func TestCreateUnstructuredObject(t *testing.T) {
 	project := &v1alpha3.DevOpsProject{}
 	project.SetName("name")
 	project.SetNamespace("namespace")
+	argocdNs := "argocd"
 
 	// test against the nil situation
-	_, err := createUnstructuredObject(project)
+	_, err := createUnstructuredObject(project, argocdNs)
 	assert.NotNil(t, err, "should not do anything if there is no spec.argo")
 
 	var obj *unstructured.Unstructured
@@ -42,7 +43,7 @@ func TestCreateUnstructuredObject(t *testing.T) {
 	// test against the default value situation
 	p1 := project.DeepCopy()
 	p1.Spec.Argo = &v1alpha3.Argo{}
-	obj, err = createUnstructuredObject(p1)
+	obj, err = createUnstructuredObject(p1, argocdNs)
 	assert.Nil(t, err)
 	result, _, _ := unstructured.NestedStringSlice(obj.Object, "spec", "sourceRepos")
 	assert.Equal(t, []string{"*"}, result)
@@ -71,7 +72,7 @@ func TestCreateUnstructuredObject(t *testing.T) {
 			Kind:  "kind2",
 		}},
 	}
-	obj, err = createUnstructuredObject(p2)
+	obj, err = createUnstructuredObject(p2, argocdNs)
 	assert.Nil(t, err)
 	p2Repos, _, _ := unstructured.NestedStringSlice(obj.Object, "spec", "sourceRepos")
 	assert.Equal(t, []string{"repo1", "repo2"}, p2Repos)
@@ -104,7 +105,7 @@ func TestReconcileArgoProject(t *testing.T) {
 	appProject.SetAPIVersion("argoproj.io/v1alpha1")
 	appProject.SetKind("AppProject")
 	appProject.SetName("fake")
-	appProject.SetNamespace("fake")
+	appProject.SetNamespace("argocd")
 
 	tests := []struct {
 		name    string
@@ -135,7 +136,7 @@ func TestReconcileArgoProject(t *testing.T) {
 			appProject := appProject.DeepCopy()
 
 			err = c.Get(context.Background(), types.NamespacedName{
-				Namespace: "fake",
+				Namespace: "argocd",
 				Name:      "fake",
 			}, appProject)
 			assert.Nil(t, err)
@@ -157,7 +158,7 @@ func TestReconcileArgoProject(t *testing.T) {
 			appProject := appProject.DeepCopy()
 
 			err = c.Get(context.Background(), types.NamespacedName{
-				Namespace: "fake",
+				Namespace: "argocd",
 				Name:      "fake",
 			}, appProject)
 			assert.Nil(t, err)
@@ -168,7 +169,8 @@ func TestReconcileArgoProject(t *testing.T) {
 	for _, tt := range tests {
 		t.Run(tt.name, func(t *testing.T) {
 			r := &Reconciler{
-				Client: tt.c,
+				Client:        tt.c,
+				ArgoNamespace: "argocd",
 			}
 			err := r.reconcileArgoProject(tt.project())
 			tt.verify(t, err, tt.c)