Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: display managed namespaces in ui (#11196) #11350

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions controller/state.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"fmt"
v1 "k8s.io/api/core/v1"
"reflect"
"strings"
"time"
Expand Down Expand Up @@ -503,6 +504,32 @@ func (m *appStateManager) CompareAppState(app *v1alpha1.Application, project *ap
LastTransitionTime: &now,
})
}

// Live namespaces which are managed namespaces (i.e. application namespaces which are managed with
// CreateNamespace=true and has non-nil managedNamespaceMetadata) will (usually) not have a corresponding
// entry in source control. In order for the namespace not to risk being pruned, we'll need to generate a
// namespace which we can compare the live namespace with. For that, we'll do the same as is done in
// gitops-engine, the difference here being that we create a managed namespace which is only used for comparison.
if liveObj.GetKind() == kubeutil.NamespaceKind && liveObj.GetName() == app.Spec.Destination.Namespace && app.Spec.SyncPolicy != nil && app.Spec.SyncPolicy.ManagedNamespaceMetadata != nil {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think that this part will also need to verify that a targetObj matching the namespace doesn't already exist

nsSpec := &v1.Namespace{TypeMeta: metav1.TypeMeta{APIVersion: "v1", Kind: kubeutil.NamespaceKind}, ObjectMeta: metav1.ObjectMeta{Name: liveObj.GetName()}}
managedNs, err := kubeutil.ToUnstructured(nsSpec)

// TODO: Check the error handling to confirm that this is indeed the way to do it
if err != nil {
conditions = append(conditions, v1alpha1.ApplicationCondition{Type: v1alpha1.ApplicationConditionComparisonError, Message: err.Error(), LastTransitionTime: &now})
failedToLoadObjs = true
continue
}

// No need to care about the return value here, we just want the modified managedNs
_, err = syncNamespace(m.resourceTracking, appLabelKey, trackingMethod, app, m.namespace)(managedNs, liveObj)
if err != nil {
conditions = append(conditions, v1alpha1.ApplicationCondition{Type: v1alpha1.ApplicationConditionComparisonError, Message: err.Error(), LastTransitionTime: &now})
failedToLoadObjs = true
} else {
targetObjs = append(targetObjs, managedNs)
}
}
}
}

Expand Down
39 changes: 39 additions & 0 deletions controller/state_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -365,6 +365,45 @@ func TestCompareAppStateDuplicatedNamespacedResources(t *testing.T) {
assert.Equal(t, 4, len(compRes.resources))
}

func TestCompareAppStateManagedNamespaceMetadataWithLiveNs(t *testing.T) {
app := newFakeApp()
app.Spec.SyncPolicy = &argoappv1.SyncPolicy{
ManagedNamespaceMetadata: &argoappv1.ManagedNamespaceMetadata{
Labels: nil,
Annotations: nil,
},
}

ns := NewNamespace()
ns.SetName(test.FakeDestNamespace)
ns.SetNamespace(test.FakeDestNamespace)
ns.SetAnnotations(map[string]string{"argocd.argoproj.io/sync-options": "ServerSideApply=true"})
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.


_ = argo.NewResourceTracking().SetAppInstance(ns, common.LabelKeyAppInstance, app.Name, "", argo.TrackingMethodLabel)

data := fakeData{
manifestResponse: &apiclient.ManifestResponse{
Manifests: []string{},
Namespace: test.FakeDestNamespace,
Server: test.FakeClusterURL,
Revision: "abc123",
},
managedLiveObjs: map[kube.ResourceKey]*unstructured.Unstructured{
kube.GetResourceKey(ns): ns,
},
}
ctrl := newFakeController(&data)
compRes := ctrl.appStateManager.CompareAppState(app, &defaultProj, []string{}, app.Spec.Sources, false, false, nil, false)

assert.NotNil(t, compRes)
assert.Equal(t, 0, len(app.Status.Conditions))
assert.NotNil(t, compRes)
assert.NotNil(t, compRes.syncStatus)
assert.Len(t, compRes.resources, 1)
assert.Len(t, compRes.managedResources, 1)
assert.Equal(t, argoappv1.SyncStatusCodeSynced, compRes.syncStatus.Status)
}

var defaultProj = argoappv1.AppProject{
ObjectMeta: metav1.ObjectMeta{
Name: "default",
Expand Down
2 changes: 1 addition & 1 deletion controller/sync.go
Original file line number Diff line number Diff line change
Expand Up @@ -290,7 +290,7 @@ func (m *appStateManager) SyncAppState(app *v1alpha1.Application, state *v1alpha
}

if syncOp.SyncOptions.HasOption("CreateNamespace=true") {
opts = append(opts, sync.WithNamespaceModifier(syncNamespace(m.resourceTracking, appLabelKey, trackingMethod, app.Name, app.Spec.SyncPolicy)))
opts = append(opts, sync.WithNamespaceModifier(syncNamespace(m.resourceTracking, appLabelKey, trackingMethod, app, m.namespace)))
}

syncCtx, cleanup, err := sync.NewSyncContext(
Expand Down
29 changes: 21 additions & 8 deletions controller/sync_namespace.go
Original file line number Diff line number Diff line change
@@ -1,21 +1,24 @@
package controller

import (
"fmt"
"github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
"github.com/argoproj/argo-cd/v2/util/argo"
gitopscommon "github.com/argoproj/gitops-engine/pkg/sync/common"
log "github.com/sirupsen/logrus"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
)

// syncNamespace determine if Argo CD should create and/or manage the namespace
// syncNamespace determines whether Argo CD should create and/or manage the namespace
// where the application will be deployed.
func syncNamespace(resourceTracking argo.ResourceTracking, appLabelKey string, trackingMethod v1alpha1.TrackingMethod, appName string, syncPolicy *v1alpha1.SyncPolicy) func(m, l *unstructured.Unstructured) (bool, error) {
func syncNamespace(resourceTracking argo.ResourceTracking, appLabelKey string, trackingMethod v1alpha1.TrackingMethod, app *v1alpha1.Application, appNamespace string) func(m *unstructured.Unstructured, l *unstructured.Unstructured) (bool, error) {
// This function must return true for the managed namespace to be synced.
return func(managedNs, liveNs *unstructured.Unstructured) (bool, error) {
if managedNs == nil {
return false, nil
}

syncPolicy := app.Spec.SyncPolicy
isNewNamespace := liveNs == nil
isManagedNamespace := syncPolicy != nil && syncPolicy.ManagedNamespaceMetadata != nil

Expand All @@ -26,18 +29,28 @@ func syncNamespace(resourceTracking argo.ResourceTracking, appLabelKey string, t
}

if isManagedNamespace {
appInstanceName := app.InstanceName(appNamespace)
if liveNs != nil {
// first check if another application owns the live namespace
liveAppName := resourceTracking.GetAppName(liveNs, appLabelKey, trackingMethod)
if liveAppName != "" && liveAppName != appInstanceName {
log.Errorf("expected namespace %s to be managed by application %s, but it's managed by application %s", liveNs.GetName(), app.Name, liveAppName)
return false, fmt.Errorf("namespace %s is managed by another application than %s", liveNs.GetName(), app.Name)
}
}

managedNamespaceMetadata := syncPolicy.ManagedNamespaceMetadata
managedNs.SetLabels(managedNamespaceMetadata.Labels)
// managedNamespaceMetadata relies on SSA in order to avoid overriding
// existing labels and annotations in namespaces
managedNs.SetAnnotations(appendSSAAnnotation(managedNamespaceMetadata.Annotations))
}

// TODO: https://github.com/argoproj/argo-cd/issues/11196
// err := resourceTracking.SetAppInstance(managedNs, appLabelKey, appName, "", trackingMethod)
// if err != nil {
// return false, fmt.Errorf("failed to set app instance tracking on the namespace %s: %s", managedNs.GetName(), err)
// }
// set ownership of the namespace to the current application
err := resourceTracking.SetAppInstance(managedNs, appLabelKey, appInstanceName, "", trackingMethod)
if err != nil {
return false, fmt.Errorf("failed to set app instance tracking on the namespace %s: %s", managedNs.GetName(), err)
}
}

return true, nil
}
Expand Down
Loading