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

Ensure object are finalized under impersonation #552

Merged
merged 1 commit into from
Jan 31, 2022
Merged
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
18 changes: 11 additions & 7 deletions controllers/kustomization_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -922,13 +922,12 @@ func (r *KustomizationReconciler) finalize(ctx context.Context, kustomization ku
objects, _ := ListObjectsInInventory(kustomization.Status.Inventory)

impersonation := NewKustomizeImpersonation(kustomization, r.Client, r.StatusPoller, r.DefaultServiceAccount)
kubeClient, _, err := impersonation.GetClient(ctx)
if err != nil {
// when impersonation fails, log the stale objects and continue with the finalization
msg := fmt.Sprintf("unable to prune objects: \n%s", ssa.FmtUnstructuredList(objects))
log.Error(fmt.Errorf("failed to build kube client: %w", err), msg)
r.event(ctx, kustomization, kustomization.Status.LastAppliedRevision, events.EventSeverityError, msg, nil)
} else {
if impersonation.CanFinalize(ctx) {
kubeClient, _, err := impersonation.GetClient(ctx)
if err != nil {
return ctrl.Result{}, err
}

resourceManager := ssa.NewResourceManager(kubeClient, nil, ssa.Owner{
Field: r.ControllerName,
Group: kustomizev1.GroupVersion.Group,
Expand All @@ -953,6 +952,11 @@ func (r *KustomizationReconciler) finalize(ctx context.Context, kustomization ku
if changeSet != nil && len(changeSet.Entries) > 0 {
r.event(ctx, kustomization, kustomization.Status.LastAppliedRevision, events.EventSeverityInfo, changeSet.String(), nil)
}
} else {
// when the account to impersonate is gone, log the stale objects and continue with the finalization
msg := fmt.Sprintf("unable to prune objects: \n%s", ssa.FmtUnstructuredList(objects))
Copy link
Member

Choose a reason for hiding this comment

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

Do we want the logged message to contain a newline and/or full list of objects?

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 haven't changed to log format in this PR. Each object is logged a new line like before, this makes it pretty in Slack and others.

Copy link
Member

Choose a reason for hiding this comment

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

Yes, I get this is pretty for Slack. Was more wondering how useful it is in controller log output.

Copy link
Member Author

Choose a reason for hiding this comment

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

All objects lists/actions are logged like this in KC. If you think we should use a different formatting for logs, please open an issue.

log.Error(fmt.Errorf("skiping pruning, failed to find account to impersonate"), msg)
r.event(ctx, kustomization, kustomization.Status.LastAppliedRevision, events.EventSeverityError, msg, nil)
}
}

Expand Down
29 changes: 29 additions & 0 deletions controllers/kustomization_impersonation.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,9 @@ package controllers
import (
"context"
"fmt"

corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
Expand Down Expand Up @@ -69,6 +71,33 @@ func (ki *KustomizeImpersonation) GetClient(ctx context.Context) (client.Client,
}
}

// CanFinalize asserts if the given Kustomization can be finalized using impersonation.
func (ki *KustomizeImpersonation) CanFinalize(ctx context.Context) bool {
name := ki.defaultServiceAccount
if sa := ki.kustomization.Spec.ServiceAccountName; sa != "" {
name = sa
}
if name == "" {
return true
}

sa := &corev1.ServiceAccount{
TypeMeta: metav1.TypeMeta{
Kind: "ServiceAccount",
APIVersion: "v1",
},
ObjectMeta: metav1.ObjectMeta{
Name: name,
Namespace: ki.kustomization.Namespace,
},
}
if err := ki.Client.Get(ctx, client.ObjectKeyFromObject(sa), sa); err != nil {
return false
}

return true
}

func (ki *KustomizeImpersonation) setImpersonationConfig(restConfig *rest.Config) {
name := ki.defaultServiceAccount
if sa := ki.kustomization.Spec.ServiceAccountName; sa != "" {
Expand Down
20 changes: 20 additions & 0 deletions controllers/kustomization_impersonation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import (
. "github.com/onsi/gomega"
corev1 "k8s.io/api/core/v1"
rbacv1 "k8s.io/api/rbac/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
apimeta "k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
Expand Down Expand Up @@ -101,6 +102,7 @@ data:
Kind: sourcev1.GitRepositoryKind,
},
TargetNamespace: id,
Prune: true,
},
}

Expand Down Expand Up @@ -187,4 +189,22 @@ data:

g.Expect(readyCondition.Reason).To(Equal(meta.ReconciliationSucceededReason))
})

t.Run("can finalize impersonating service account", func(t *testing.T) {
saK := &kustomizev1.Kustomization{}
err = k8sClient.Get(context.Background(), client.ObjectKeyFromObject(kustomization), saK)
g.Expect(err).NotTo(HaveOccurred())

err = k8sClient.Delete(context.Background(), saK)
g.Expect(err).NotTo(HaveOccurred())

g.Eventually(func() bool {
err := k8sClient.Get(context.Background(), client.ObjectKeyFromObject(kustomization), resultK)
return apierrors.IsNotFound(err)
}, timeout, time.Second).Should(BeTrue())

resultConfig := &corev1.ConfigMap{}
err := k8sClient.Get(context.Background(), types.NamespacedName{Name: id, Namespace: id}, resultConfig)
g.Expect(apierrors.IsNotFound(err)).To(BeTrue())
})
}