|
| 1 | +/* |
| 2 | +
|
| 3 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +you may not use this file except in compliance with the License. |
| 5 | +You may obtain a copy of the License at |
| 6 | +
|
| 7 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +
|
| 9 | +Unless required by applicable law or agreed to in writing, software |
| 10 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +See the License for the specific language governing permissions and |
| 13 | +limitations under the License. |
| 14 | +*/ |
| 15 | + |
| 16 | +package constrainttemplate |
| 17 | + |
| 18 | +import ( |
| 19 | + "context" |
| 20 | + "testing" |
| 21 | + |
| 22 | + "github.com/open-policy-agent/frameworks/constraint/pkg/apis/templates/v1beta1" |
| 23 | + statusv1beta1 "github.com/open-policy-agent/gatekeeper/v3/apis/status/v1beta1" |
| 24 | + "github.com/stretchr/testify/require" |
| 25 | + apierrors "k8s.io/apimachinery/pkg/api/errors" |
| 26 | + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" |
| 27 | + "k8s.io/apimachinery/pkg/runtime" |
| 28 | + "k8s.io/apimachinery/pkg/types" |
| 29 | + "sigs.k8s.io/controller-runtime/pkg/client" |
| 30 | + "sigs.k8s.io/controller-runtime/pkg/client/fake" |
| 31 | +) |
| 32 | + |
| 33 | +// staleClient wraps a controller-runtime client and serves Get requests from a snapshot taken at construction time, |
| 34 | +// while forwarding Update/Create/Delete/List to the real (live) client. This simulates a controller-runtime informer |
| 35 | +// cache that has not yet observed the latest write to the backing store, which is the underlying cause of the spurious |
| 36 | +// "the object has been modified" conflicts we hit in the ConstraintTemplate reconciler. |
| 37 | +type staleClient struct { |
| 38 | + client.Client |
| 39 | + stale map[client.ObjectKey]*statusv1beta1.ConstraintTemplatePodStatus |
| 40 | +} |
| 41 | + |
| 42 | +func (s *staleClient) Get(ctx context.Context, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error { |
| 43 | + if cts, ok := obj.(*statusv1beta1.ConstraintTemplatePodStatus); ok { |
| 44 | + if cached, ok := s.stale[key]; ok { |
| 45 | + cached.DeepCopyInto(cts) |
| 46 | + return nil |
| 47 | + } |
| 48 | + } |
| 49 | + return s.Client.Get(ctx, key, obj, opts...) |
| 50 | +} |
| 51 | + |
| 52 | +func newPodStatusForTest(name string) *statusv1beta1.ConstraintTemplatePodStatus { |
| 53 | + return &statusv1beta1.ConstraintTemplatePodStatus{ |
| 54 | + TypeMeta: metav1.TypeMeta{ |
| 55 | + APIVersion: statusv1beta1.GroupVersion.String(), |
| 56 | + Kind: "ConstraintTemplatePodStatus", |
| 57 | + }, |
| 58 | + ObjectMeta: metav1.ObjectMeta{ |
| 59 | + Name: name, |
| 60 | + Namespace: "gatekeeper-system", |
| 61 | + }, |
| 62 | + } |
| 63 | +} |
| 64 | + |
| 65 | +func newSchemeForTest(t *testing.T) *runtime.Scheme { |
| 66 | + t.Helper() |
| 67 | + scheme := runtime.NewScheme() |
| 68 | + require.NoError(t, statusv1beta1.AddToScheme(scheme)) |
| 69 | + require.NoError(t, v1beta1.AddToScheme(scheme)) |
| 70 | + return scheme |
| 71 | +} |
| 72 | + |
| 73 | +// TestUpdatePodStatusWithRetry_StaleCacheRecovers reproduces the race that produced "update ct pod status error" in |
| 74 | +// production: the reconciler's cached client returns a stale resourceVersion for the PodStatus, so the first Update |
| 75 | +// returns a 409 Conflict; the helper must refetch via the uncached APIReader and successfully retry. |
| 76 | +func TestUpdatePodStatusWithRetry_StaleCacheRecovers(t *testing.T) { |
| 77 | + ctx := context.Background() |
| 78 | + scheme := newSchemeForTest(t) |
| 79 | + |
| 80 | + initial := newPodStatusForTest("pod-template-status") |
| 81 | + initial.Status.ID = "initial" |
| 82 | + |
| 83 | + // Live store: the API-server-equivalent that holds the latest resourceVersion. |
| 84 | + live := fake.NewClientBuilder(). |
| 85 | + WithScheme(scheme). |
| 86 | + WithObjects(initial.DeepCopy()). |
| 87 | + Build() |
| 88 | + |
| 89 | + // Capture the resourceVersion the fake client assigned to the initial object on Build(). We can't read it off |
| 90 | + // `initial` because WithObjects deep-copies its input before stamping a resourceVersion on the stored copy. |
| 91 | + storedBefore := &statusv1beta1.ConstraintTemplatePodStatus{} |
| 92 | + require.NoError(t, live.Get(ctx, client.ObjectKeyFromObject(initial), storedBefore)) |
| 93 | + staleResourceVersion := storedBefore.ResourceVersion |
| 94 | + require.NotEmpty(t, staleResourceVersion, "test sanity: fake client must stamp a resourceVersion on stored objects") |
| 95 | + |
| 96 | + // Simulate an out-of-band update advancing the resourceVersion on the API server while the controller's informer |
| 97 | + // cache still serves the old version. |
| 98 | + latestOnAPIServer := storedBefore.DeepCopy() |
| 99 | + latestOnAPIServer.Status.ID = "out-of-band" |
| 100 | + require.NoError(t, live.Update(ctx, latestOnAPIServer)) |
| 101 | + require.NotEqual(t, staleResourceVersion, latestOnAPIServer.ResourceVersion, "test sanity: Update must bump resourceVersion") |
| 102 | + |
| 103 | + // The stale informer view: same spec the cache observed at storedBefore, pinned to the older resourceVersion. |
| 104 | + cachedView := storedBefore.DeepCopy() |
| 105 | + cachedView.ResourceVersion = staleResourceVersion |
| 106 | + |
| 107 | + cached := &staleClient{ |
| 108 | + Client: live, |
| 109 | + stale: map[client.ObjectKey]*statusv1beta1.ConstraintTemplatePodStatus{ |
| 110 | + client.ObjectKeyFromObject(initial): cachedView, |
| 111 | + }, |
| 112 | + } |
| 113 | + |
| 114 | + r := &ReconcileConstraintTemplate{ |
| 115 | + Client: cached, |
| 116 | + apiReader: live, |
| 117 | + scheme: scheme, |
| 118 | + } |
| 119 | + |
| 120 | + // The reconciler reads the PodStatus through the cached client and gets the stale version, then mutates and tries |
| 121 | + // to write. The first Update must fail with Conflict (server side rejects the old resourceVersion); the helper must |
| 122 | + // recover via the uncached apiReader. |
| 123 | + status := &statusv1beta1.ConstraintTemplatePodStatus{} |
| 124 | + require.NoError(t, cached.Get(ctx, client.ObjectKeyFromObject(initial), status)) |
| 125 | + require.Equal(t, staleResourceVersion, status.ResourceVersion, "test sanity: cached view is pinned to the older resourceVersion") |
| 126 | + require.Equal(t, "initial", status.Status.ID, "test sanity: cached view still reflects the pre-out-of-band spec") |
| 127 | + status.Status.ID = "desired-by-reconciler" |
| 128 | + |
| 129 | + require.NoError(t, r.updatePodStatusWithRetry(ctx, status)) |
| 130 | + |
| 131 | + final := &statusv1beta1.ConstraintTemplatePodStatus{} |
| 132 | + require.NoError(t, live.Get(ctx, client.ObjectKeyFromObject(initial), final)) |
| 133 | + require.Equal(t, "desired-by-reconciler", final.Status.ID, "desired status must be applied on top of the latest resourceVersion") |
| 134 | +} |
| 135 | + |
| 136 | +// TestUpdatePodStatusWithRetry_NonConflictErrorReturned ensures that errors other than 409 Conflict are returned to the |
| 137 | +// caller unchanged and not silently swallowed by the retry loop. |
| 138 | +func TestUpdatePodStatusWithRetry_NonConflictErrorReturned(t *testing.T) { |
| 139 | + ctx := context.Background() |
| 140 | + scheme := newSchemeForTest(t) |
| 141 | + |
| 142 | + live := fake.NewClientBuilder().WithScheme(scheme).Build() |
| 143 | + |
| 144 | + r := &ReconcileConstraintTemplate{ |
| 145 | + Client: live, |
| 146 | + apiReader: live, |
| 147 | + scheme: scheme, |
| 148 | + } |
| 149 | + |
| 150 | + // PodStatus does not exist in the live store, so Update must fail with NotFound. The helper must surface that error |
| 151 | + // without retrying. |
| 152 | + missing := newPodStatusForTest("missing-status") |
| 153 | + missing.Status.ID = "anything" |
| 154 | + |
| 155 | + err := r.updatePodStatusWithRetry(ctx, missing) |
| 156 | + require.Error(t, err) |
| 157 | + require.True(t, apierrors.IsNotFound(err), "expected NotFound, got %v", err) |
| 158 | +} |
| 159 | + |
| 160 | +// TestUpdatePodStatusWithRetry_HappyPath ensures that a normal update with the latest resourceVersion succeeds without |
| 161 | +// any retry overhead. |
| 162 | +func TestUpdatePodStatusWithRetry_HappyPath(t *testing.T) { |
| 163 | + ctx := context.Background() |
| 164 | + scheme := newSchemeForTest(t) |
| 165 | + |
| 166 | + initial := newPodStatusForTest("happy-status") |
| 167 | + initial.Status.ID = "before" |
| 168 | + |
| 169 | + live := fake.NewClientBuilder(). |
| 170 | + WithScheme(scheme). |
| 171 | + WithObjects(initial.DeepCopy()). |
| 172 | + Build() |
| 173 | + |
| 174 | + r := &ReconcileConstraintTemplate{ |
| 175 | + Client: live, |
| 176 | + apiReader: live, |
| 177 | + scheme: scheme, |
| 178 | + } |
| 179 | + |
| 180 | + current := &statusv1beta1.ConstraintTemplatePodStatus{} |
| 181 | + require.NoError(t, live.Get(ctx, client.ObjectKeyFromObject(initial), current)) |
| 182 | + current.Status.ID = "after" |
| 183 | + |
| 184 | + require.NoError(t, r.updatePodStatusWithRetry(ctx, current)) |
| 185 | + |
| 186 | + final := &statusv1beta1.ConstraintTemplatePodStatus{} |
| 187 | + require.NoError(t, live.Get(ctx, types.NamespacedName{Name: initial.Name, Namespace: initial.Namespace}, final)) |
| 188 | + require.Equal(t, "after", final.Status.ID) |
| 189 | +} |
0 commit comments