Skip to content

Commit 960ef8f

Browse files
authored
Merge pull request #149 from erikgb/resolve-ns-conflict
fix: should resolve SubNamespace conflict when sub-namespace deleted
2 parents e688318 + a9377a8 commit 960ef8f

File tree

7 files changed

+108
-21
lines changed

7 files changed

+108
-21
lines changed

cmd/accurate-controller/sub/run.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,9 @@ func subMain(ns, addr string, port int) error {
133133
hooks.SetupNamespaceWebhook(mgr, dec)
134134

135135
// SubNamespace reconciler & webhook
136+
if err := indexing.SetupIndexForSubNamespace(ctx, mgr); err != nil {
137+
return fmt.Errorf("failed to setup indexer for subnamespaces: %w", err)
138+
}
136139
if err = (&controllers.SubNamespaceReconciler{
137140
Client: mgr.GetClient(),
138141
}).SetupWithManager(mgr); err != nil {

controllers/subnamespace_controller.go

Lines changed: 30 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -16,14 +16,15 @@ import (
1616
"k8s.io/apimachinery/pkg/types"
1717
metav1ac "k8s.io/client-go/applyconfigurations/meta/v1"
1818
"k8s.io/client-go/util/csaupgrade"
19-
"k8s.io/client-go/util/workqueue"
2019
kstatus "sigs.k8s.io/cli-utils/pkg/kstatus/status"
2120
ctrl "sigs.k8s.io/controller-runtime"
21+
"sigs.k8s.io/controller-runtime/pkg/builder"
2222
"sigs.k8s.io/controller-runtime/pkg/client"
2323
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
2424
"sigs.k8s.io/controller-runtime/pkg/event"
2525
"sigs.k8s.io/controller-runtime/pkg/handler"
2626
"sigs.k8s.io/controller-runtime/pkg/log"
27+
"sigs.k8s.io/controller-runtime/pkg/predicate"
2728
"sigs.k8s.io/controller-runtime/pkg/reconcile"
2829
)
2930

@@ -154,30 +155,42 @@ func (r *SubNamespaceReconciler) reconcileNS(ctx context.Context, sn *accuratev2
154155

155156
// SetupWithManager sets up the controller with the Manager.
156157
func (r *SubNamespaceReconciler) SetupWithManager(mgr ctrl.Manager) error {
157-
nsHandler := func(o client.Object, q workqueue.RateLimitingInterface) {
158+
nsHandler := func(ctx context.Context, o client.Object) (requests []reconcile.Request) {
158159
parent := o.GetLabels()[constants.LabelParent]
159-
if parent == "" {
160+
if parent != "" {
161+
requests = append(requests, reconcile.Request{NamespacedName: types.NamespacedName{
162+
Namespace: parent,
163+
Name: o.GetName(),
164+
}})
160165
return
161166
}
162-
q.Add(reconcile.Request{NamespacedName: types.NamespacedName{
163-
Namespace: parent,
164-
Name: o.GetName(),
165-
}})
167+
if o.GetDeletionTimestamp() != nil {
168+
// The namespace has no parent and is in terminating state.
169+
// Let's find all (conflicting) subnamespaces that might want to recreate it.
170+
snList := &accuratev2.SubNamespaceList{}
171+
err := r.List(ctx, snList, client.MatchingFields{constants.SubNamespaceNameKey: o.GetName()})
172+
if err != nil {
173+
logger := log.FromContext(ctx)
174+
logger.Error(err, "failed to list subnamespaces")
175+
return
176+
}
177+
for _, sn := range snList.Items {
178+
requests = append(requests, reconcile.Request{NamespacedName: types.NamespacedName{
179+
Namespace: sn.Namespace,
180+
Name: sn.Name,
181+
}})
182+
}
183+
}
184+
return
166185
}
167186

168187
return ctrl.NewControllerManagedBy(mgr).
169188
For(&accuratev2.SubNamespace{}).
170-
Watches(&corev1.Namespace{}, handler.Funcs{
171-
UpdateFunc: func(ctx context.Context, ev event.UpdateEvent, q workqueue.RateLimitingInterface) {
172-
if ev.ObjectNew.GetDeletionTimestamp() != nil {
173-
return
174-
}
175-
nsHandler(ev.ObjectOld, q)
176-
},
177-
DeleteFunc: func(ctx context.Context, ev event.DeleteEvent, q workqueue.RateLimitingInterface) {
178-
nsHandler(ev.Object, q)
189+
Watches(&corev1.Namespace{}, handler.EnqueueRequestsFromMapFunc(nsHandler), builder.WithPredicates(predicate.Funcs{
190+
CreateFunc: func(e event.TypedCreateEvent[client.Object]) bool {
191+
return false
179192
},
180-
}).
193+
})).
181194
Complete(r)
182195
}
183196

controllers/subnamespace_controller_test.go

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import (
66

77
accuratev2 "github.com/cybozu-go/accurate/api/accurate/v2"
88
"github.com/cybozu-go/accurate/pkg/constants"
9+
"github.com/cybozu-go/accurate/pkg/indexing"
910
. "github.com/onsi/ginkgo/v2"
1011
. "github.com/onsi/gomega"
1112
corev1 "k8s.io/api/core/v1"
@@ -34,6 +35,9 @@ var _ = Describe("SubNamespace controller", func() {
3435
err = snr.SetupWithManager(mgr)
3536
Expect(err).ToNot(HaveOccurred())
3637

38+
err = indexing.SetupIndexForSubNamespace(ctx, mgr)
39+
Expect(err).NotTo(HaveOccurred())
40+
3741
ctx, cancel := context.WithCancel(ctx)
3842
stopFunc = cancel
3943
go func() {
@@ -50,7 +54,7 @@ var _ = Describe("SubNamespace controller", func() {
5054
time.Sleep(100 * time.Millisecond)
5155
})
5256

53-
It("should create and delete sub namespaces", func() {
57+
It("should create and delete sub-namespaces", func() {
5458
ns := &corev1.Namespace{}
5559
ns.Name = "test1"
5660
Expect(k8sClient.Create(ctx, ns)).To(Succeed())
@@ -92,9 +96,14 @@ var _ = Describe("SubNamespace controller", func() {
9296
Eventually(komega.Object(sn)).Should(HaveField("Status.ObservedGeneration", BeNumerically(">", 0)))
9397
Expect(sn.Status.Conditions).To(HaveLen(1))
9498
Expect(sn.Status.Conditions[0].Reason).To(Equal(accuratev2.SubNamespaceConflict))
99+
100+
// It's tempting to test if a conflict can be resolved by deleting the conflicting namespace,
101+
// but this is currently not possible because EnvTest does not support namespace deletion.
102+
// See https://github.com/kubernetes-sigs/controller-runtime/issues/880 for details.
103+
// This feature should be tested in e2e-tests.
95104
})
96105

97-
It("should not delete a conflicting sub namespace", func() {
106+
It("should not delete a conflicting sub-namespace", func() {
98107
ns := &corev1.Namespace{}
99108
ns.Name = "test3"
100109
Expect(k8sClient.Create(ctx, ns)).To(Succeed())
@@ -121,7 +130,7 @@ var _ = Describe("SubNamespace controller", func() {
121130
Consistently(komega.Object(sub1)).Should(HaveField("DeletionTimestamp", BeNil()))
122131
})
123132

124-
It("should re-create a subnamespace if it is deleted", func() {
133+
It("should re-create a sub-namespace if it is deleted", func() {
125134
ns := &corev1.Namespace{}
126135
ns.Name = "test4"
127136
Expect(k8sClient.Create(ctx, ns)).To(Succeed())

e2e/e2e_test.go

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,9 @@ var resourceQuota []byte
2323
//go:embed testdata/serviceaccountWithDummySecrets.yaml
2424
var serviceAccountWithDummySecretsYAML []byte
2525

26+
//go:embed testdata/conflicting-subnamespace.yaml
27+
var conflictingSubnamespaceYAML []byte
28+
2629
var (
2730
sealedJSON []byte
2831
k8sMinorVersion int
@@ -292,6 +295,51 @@ var _ = Describe("kubectl accurate", func() {
292295
Expect(err).To(HaveOccurred())
293296
})
294297

298+
It("should (re)create sub-namespace when conflicting namespace deleted", func() {
299+
By("preparing namespaces")
300+
kubectlSafe(nil, "create", "ns", "conflict-root1")
301+
kubectlSafe(nil, "accurate", "ns", "set-type", "conflict-root1", "root")
302+
kubectlSafe(nil, "create", "ns", "conflict-sub1")
303+
304+
By("creating conflicting subnamespace")
305+
// Cannot use "kubectl accurate" here, since conflict is validated client-side.
306+
kubectlSafe(conflictingSubnamespaceYAML, "apply", "-f", "-")
307+
var conditions []metav1.Condition
308+
Eventually(func() ([]metav1.Condition, error) {
309+
out, err := kubectl(nil, "get", "-n", "conflict-root1", "subnamespaces", "conflict-sub1", "-o", "json")
310+
if err != nil {
311+
return nil, err
312+
}
313+
sn := &accuratev2.SubNamespace{}
314+
if err := json.Unmarshal(out, sn); err != nil {
315+
return nil, err
316+
}
317+
conditions = sn.Status.Conditions
318+
return conditions, nil
319+
}).Should(HaveLen(1))
320+
Expect(conditions[0].Reason).To(Equal("Conflict"))
321+
322+
By("deleting conflicting namespace")
323+
kubectlSafe(nil, "delete", "ns", "conflict-sub1")
324+
Eventually(func() ([]metav1.Condition, error) {
325+
out, err := kubectl(nil, "get", "-n", "conflict-root1", "subnamespaces", "conflict-sub1", "-o", "json")
326+
if err != nil {
327+
return nil, err
328+
}
329+
sn := &accuratev2.SubNamespace{}
330+
if err := json.Unmarshal(out, sn); err != nil {
331+
return nil, err
332+
}
333+
return sn.Status.Conditions, nil
334+
}).Should(BeEmpty())
335+
out, err := kubectl(nil, "get", "ns", "conflict-sub1", "-o", "json")
336+
Expect(err).NotTo(HaveOccurred())
337+
sn := &corev1.Namespace{}
338+
err = json.Unmarshal(out, sn)
339+
Expect(err).NotTo(HaveOccurred())
340+
Expect(sn.Labels).To(HaveKeyWithValue(constants.LabelParent, "conflict-root1"))
341+
})
342+
295343
It("should propagate ServiceAccount w/o secrets field", func() {
296344
// From Kubernetes 1.24, the auto-generation of secret-based service account tokens has been disabled by default.
297345
// So the secrets field in the ServiceAccount is not updated. But when upgrading Kubernetes from 1.23 or lower,
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
apiVersion: accurate.cybozu.com/v2
2+
kind: SubNamespace
3+
metadata:
4+
name: conflict-sub1
5+
namespace: conflict-root1

pkg/constants/indexer.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,4 +5,5 @@ const (
55
NamespaceParentKey = "namespace.parent"
66
NamespaceTemplateKey = "namespace.template"
77
PropagateKey = "resource.propagate"
8+
SubNamespaceNameKey = "subnamespace.name"
89
)

pkg/indexing/indexing.go

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package indexing
33
import (
44
"context"
55

6+
accuratev2 "github.com/cybozu-go/accurate/api/accurate/v2"
67
"github.com/cybozu-go/accurate/pkg/constants"
78
corev1 "k8s.io/api/core/v1"
89
"sigs.k8s.io/controller-runtime/pkg/client"
@@ -23,7 +24,7 @@ func SetupIndexForResource(ctx context.Context, mgr manager.Manager, res client.
2324
// SetupIndexForNamespace sets up indexers for namespaces.
2425
func SetupIndexForNamespace(ctx context.Context, mgr manager.Manager) error {
2526
ns := &corev1.Namespace{}
26-
err := mgr.GetFieldIndexer().IndexField(context.Background(), ns, constants.NamespaceParentKey, func(rawObj client.Object) []string {
27+
err := mgr.GetFieldIndexer().IndexField(ctx, ns, constants.NamespaceParentKey, func(rawObj client.Object) []string {
2728
parent := rawObj.GetLabels()[constants.LabelParent]
2829
if parent == "" {
2930
return nil
@@ -42,3 +43,10 @@ func SetupIndexForNamespace(ctx context.Context, mgr manager.Manager) error {
4243
return []string{tmpl}
4344
})
4445
}
46+
47+
// SetupIndexForSubNamespace sets up indexers for subnamespaces.
48+
func SetupIndexForSubNamespace(ctx context.Context, mgr manager.Manager) error {
49+
return mgr.GetFieldIndexer().IndexField(ctx, &accuratev2.SubNamespace{}, constants.SubNamespaceNameKey, func(rawObj client.Object) []string {
50+
return []string{rawObj.GetName()}
51+
})
52+
}

0 commit comments

Comments
 (0)