diff --git a/pkg/registry/apps/application/rest.go b/pkg/registry/apps/application/rest.go index 6cd544994..50700d4dd 100644 --- a/pkg/registry/apps/application/rest.go +++ b/pkg/registry/apps/application/rest.go @@ -19,6 +19,7 @@ package application import ( "context" "encoding/json" + "errors" "fmt" "maps" "net/http" @@ -673,9 +674,20 @@ func (r *REST) Delete(ctx context.Context, name string, deleteValidation rest.Va // Construct HelmRelease name with the configured prefix helmReleaseName := r.releaseConfig.Prefix + name + // A resourceVersion precondition is judged against the live release, so + // read it uncached. + var callerRV *string + if options != nil && options.Preconditions != nil { + callerRV = options.Preconditions.ResourceVersion + } + reader := client.Reader(r.c) + if callerRV != nil { + reader = r.w + } + // Retrieve the HelmRelease before attempting to delete helmRelease := &helmv2.HelmRelease{} - err = r.c.Get(ctx, client.ObjectKey{Namespace: namespace, Name: helmReleaseName}, helmRelease, &client.GetOptions{Raw: &metav1.GetOptions{}}) + err = reader.Get(ctx, client.ObjectKey{Namespace: namespace, Name: helmReleaseName}, helmRelease, &client.GetOptions{Raw: &metav1.GetOptions{}}) if err != nil { if apierrors.IsNotFound(err) { // If HelmRelease does not exist, return NotFound error for Application @@ -694,6 +706,15 @@ func (r *REST) Delete(ctx context.Context, name string, deleteValidation rest.Va return nil, false, apierrors.NewNotFound(r.gvr.GroupResource(), name) } + if callerRV != nil { + if err := r.checkResourceVersion(name, *callerRV, helmRelease.ResourceVersion); err != nil { + return nil, false, err + } + options = options.DeepCopy() + liveRV := helmRelease.ResourceVersion + options.Preconditions.ResourceVersion = &liveRV + } + // Run the genericapiserver-supplied admission chain (validating webhooks // and ValidatingAdmissionPolicies) on the resolved Application before // removing the underlying HelmRelease. Custom REST handlers must invoke @@ -723,6 +744,46 @@ func (r *REST) Delete(ctx context.Context, name string, deleteValidation rest.Va return nil, true, nil } +// checkResourceVersion applies a caller's resourceVersion precondition to the +// live HelmRelease. Every resourceVersion is a revision of the same etcd. An +// Application carries the version of the release its spec came from or, on a +// WorkloadMonitor-triggered watch event, a monitor revision, which is newer +// than that release only when the release was read at or after it. A value +// newer than the live release therefore names the current spec, and only an +// older one is a conflict. +func (r *REST) checkResourceVersion(name, callerRV, liveRV string) error { + caller, err := strconv.ParseUint(callerRV, 10, 64) + if err != nil { + return apierrors.NewBadRequest(fmt.Sprintf("invalid resourceVersion %q: %v", callerRV, err)) + } + live, err := strconv.ParseUint(liveRV, 10, 64) + if err != nil { + return fmt.Errorf("HelmRelease for %s has an invalid resourceVersion %q: %w", name, liveRV, err) + } + if caller < live { + return apierrors.NewConflict(r.gvr.GroupResource(), name, errors.New("the object has been modified; please apply your changes to the latest version and try again")) + } + return nil +} + +// newerResourceVersion returns whichever of two numeric resourceVersions is +// higher, preferring b when either does not parse. +func newerResourceVersion(a, b string) string { + av, aErr := strconv.ParseUint(a, 10, 64) + bv, bErr := strconv.ParseUint(b, 10, 64) + if aErr != nil || bErr != nil || bv >= av { + return b + } + return a +} + +// Watches bypass the API server's default one-minute request timeout. +const ( + liveReleaseReadAttempts = 3 + liveReleaseReadRetryDelay = 100 * time.Millisecond + liveReleaseReadTimeout = time.Minute +) + // Watch sets up a watch on HelmReleases, filters them based on application labels, and converts events to Applications func (r *REST) Watch(ctx context.Context, options *metainternalversion.ListOptions) (watch.Interface, error) { namespace, err := r.getNamespace(ctx) @@ -862,6 +923,17 @@ func (r *REST) Watch(ctx context.Context, options *metainternalversion.ListOptio if wmWatcherForCleanup != nil { defer wmWatcherForCleanup.Stop() } + // Live reads use a context that Stop cancels, so a stopped watch + // never waits on the API server. + readCtx, cancelReads := context.WithCancel(ctx) + defer cancelReads() + go func() { + select { + case <-customW.stopChan: + cancelReads() + case <-readCtx.Done(): + } + }() // Buffer of WorkloadMonitor events that arrived before the initial // snapshot finished. The watch-list contract requires the stream to @@ -871,7 +943,12 @@ func (r *REST) Watch(ctx context.Context, options *metainternalversion.ListOptio // workload whose status flips during the snapshot window (after the // Application ADDED but before the bookmark) and then stops changing // would leave the client with a stale WorkloadsReady forever. - var pendingWMEvents []watch.Event + type monitorEvent struct { + event watch.Event + monitorRV string + releaseRV string + } + var pendingWMEvents []monitorEvent // Get the starting resourceVersion from options // If client provides resourceVersion (e.g., from a previous List), we should skip @@ -895,9 +972,38 @@ func (r *REST) Watch(ctx context.Context, options *metainternalversion.ListOptio } } + // lastSent holds, per Application, the resourceVersion of the last + // event this watch sent. + lastSent := map[client.ObjectKey]string{} + remember := func(app *appsv1alpha1.Application, eventType watch.EventType) { + key := client.ObjectKey{Namespace: app.Namespace, Name: app.Name} + if eventType == watch.Deleted { + delete(lastSent, key) + return + } + lastSent[key] = app.ResourceVersion + } + + // sendMonitorEvent falls back to the monitor's own resourceVersion + // when the event might repeat the one the client already holds, which + // a shared informer hides from its handlers. Without an entry for the + // object, a client resuming this watch may hold any release version, + // so the release's own version counts as held. The object the client + // caches from a fallback event gets a conflict on a precondition-checked + // delete until its next event. + sendMonitorEvent := func(me monitorEvent) bool { + app := me.event.Object.(*appsv1alpha1.Application) + last, known := lastSent[client.ObjectKey{Namespace: app.Namespace, Name: app.Name}] + if (known && app.ResourceVersion == last) || (!known && app.ResourceVersion == me.releaseRV) { + app.SetResourceVersion(me.monitorRV) + } + remember(app, me.event.Type) + return send(me.event) + } + drainPendingWMEvents := func() bool { for _, ev := range pendingWMEvents { - if !send(ev) { + if !sendMonitorEvent(ev) { return false } } @@ -1012,6 +1118,7 @@ func (r *REST) Watch(ctx context.Context, options *metainternalversion.ListOptio // When startingRV == 0, always send ADDED events (client wants full state) // Send event to custom watcher + remember(&app, event.Type) if !send(watch.Event{Type: event.Type, Object: &app}) { return } @@ -1070,10 +1177,39 @@ func (r *REST) Watch(ctx context.Context, options *metainternalversion.ListOptio } else if !fieldFilter.MatchesNamespace(hrNS) { continue } + // The event's resourceVersion may be the monitor's, which a + // Delete precondition accepts as current while the release has + // not moved past it. A cached release older than the monitor + // revision could pair a stale spec with that version, so only + // then is the release read live. + hrKey := client.ObjectKey{Namespace: hrNS, Name: hrName} hr := &helmv2.HelmRelease{} - if err := r.c.Get(ctx, client.ObjectKey{Namespace: hrNS, Name: hrName}, hr); err != nil { - klog.V(4).Infof("Cannot find HelmRelease %s/%s for WorkloadMonitor event: %v", hrNS, hrName, err) - continue + if err := r.c.Get(ctx, hrKey, hr); err != nil || newerResourceVersion(wm.GetResourceVersion(), hr.GetResourceVersion()) != hr.GetResourceVersion() { + hr = &helmv2.HelmRelease{} + // Nothing replays a monitor event this watch drops, so a + // transient failure of the live read is retried briefly. + // A missing release is final. + liveCtx, cancelLiveRead := context.WithTimeout(readCtx, liveReleaseReadTimeout) + liveErr := r.w.Get(liveCtx, hrKey, hr) + for attempt := 1; liveErr != nil && !apierrors.IsNotFound(liveErr) && attempt < liveReleaseReadAttempts; attempt++ { + select { + case <-liveCtx.Done(): + case <-time.After(liveReleaseReadRetryDelay): + } + if liveCtx.Err() != nil { + break + } + liveErr = r.w.Get(liveCtx, hrKey, hr) + } + readEnded := liveCtx.Err() != nil + cancelLiveRead() + if readEnded { + return + } + if liveErr != nil { + klog.V(4).Infof("Cannot find HelmRelease %s/%s for WorkloadMonitor event: %v", hrNS, hrName, liveErr) + continue + } } // Pass the fresh WorkloadMonitor so conversion uses the latest // operational status even if the cache (r.c) has not yet @@ -1094,10 +1230,8 @@ func (r *REST) Watch(ctx context.Context, options *metainternalversion.ListOptio continue } } - // Use the WorkloadMonitor's ResourceVersion for the emitted event - // so clients see a monotonically increasing RV and don't skip this update. - app.SetResourceVersion(wm.GetResourceVersion()) - outEvent := watch.Event{Type: watch.Modified, Object: &app} + app.SetResourceVersion(newerResourceVersion(wm.GetResourceVersion(), hr.GetResourceVersion())) + outEvent := monitorEvent{event: watch.Event{Type: watch.Modified, Object: &app}, monitorRV: wm.GetResourceVersion(), releaseRV: hr.GetResourceVersion()} // Buffer WM-triggered events that arrive before the // initial-events-end bookmark. They will be replayed in order // immediately after the bookmark is emitted. @@ -1106,7 +1240,7 @@ func (r *REST) Watch(ctx context.Context, options *metainternalversion.ListOptio continue } bookmarker.Observe(wm.GetResourceVersion()) - if !send(outEvent) { + if !sendMonitorEvent(outEvent) { return } diff --git a/pkg/registry/apps/application/rest_watch_deadline_test.go b/pkg/registry/apps/application/rest_watch_deadline_test.go new file mode 100644 index 000000000..3d4bc68f5 --- /dev/null +++ b/pkg/registry/apps/application/rest_watch_deadline_test.go @@ -0,0 +1,149 @@ +package application + +import ( + "context" + "errors" + "testing" + "testing/synctest" + "time" + + metainternalversion "k8s.io/apimachinery/pkg/apis/meta/internalversion" + "k8s.io/apimachinery/pkg/watch" + "k8s.io/apiserver/pkg/endpoints/request" +) + +func expectLiveReadWatchClosed(t *testing.T, w watch.Interface) { + t.Helper() + select { + case event, open := <-w.ResultChan(): + if open { + t.Fatalf("unexpected %s event instead of watch closure", event.Type) + } + default: + t.Fatal("watch remains open after the live-read deadline") + } +} + +func TestWatchHungLiveReadDeadlineClosesAndReconnects(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + f := newRVWatchFixture(t) + parent, w := startRVWatch(t, f) + cached := f.liveRelease(t) + f.hrW.Modify(cached.DeepCopy()) + resume := nextApplication(t, w).ResourceVersion + live := f.advanceLive(t, "before-timeout") + readsBefore := f.liveReleaseGets + entered := make(chan context.Context, 1) + f.liveReleaseErrs = []error{errors.New("live read failed")} + f.onLiveReleaseError = func(ctx context.Context) { + entered <- ctx + <-ctx.Done() + } + + readStarted := time.Now() + f.monitorEvent(live.ResourceVersion) + synctest.Wait() + var liveCtx context.Context + select { + case liveCtx = <-entered: + default: + t.Fatal("live read did not start") + } + time.Sleep(time.Minute) + synctest.Wait() + expectLiveReadWatchClosed(t, w) + if !errors.Is(liveCtx.Err(), context.DeadlineExceeded) { + t.Fatalf("live read ended with %v, want its own deadline", liveCtx.Err()) + } + deadline, bounded := liveCtx.Deadline() + if !bounded || deadline.Sub(readStarted) != time.Minute { + t.Fatalf("live read budget %v, bounded=%t, want exactly one minute", deadline.Sub(readStarted), bounded) + } + if parent.Err() != nil { + t.Fatalf("watch parent unexpectedly ended: %v", parent.Err()) + } + if got := f.liveReleaseGets - readsBefore; got != 1 { + t.Fatalf("live release reads %d, want one bounded hung read", got) + } + + f.hrW, f.wmW = watch.NewFake(), watch.NewFake() + fresh := f.advanceLive(t, "after-reconnect") + reconnected := startRVWatchFrom(t, f, resume) + f.monitorEvent(fresh.ResourceVersion) + app := nextApplication(t, reconnected) + if got := specMarker(t, app); got != "after-reconnect" { + t.Fatalf("reconnected spec marker %q, want fresh live state", got) + } + if app.ResourceVersion != fresh.ResourceVersion { + t.Fatalf("reconnected version %q, want %q", app.ResourceVersion, fresh.ResourceVersion) + } + }) +} + +func TestWatchLiveReadDeadlineIncludesRetries(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + f := newRVWatchFixture(t) + _, w := startRVWatch(t, f) + live := f.advanceLive(t, "live") + readsBefore := f.liveReleaseGets + f.liveReleaseErrs = []error{errors.New("temporary live read failure")} + f.onLiveReleaseError = func(context.Context) { + time.Sleep(45 * time.Second) + f.liveReleaseHang = true + } + + f.monitorEvent(live.ResourceVersion) + synctest.Wait() + time.Sleep(time.Minute) + synctest.Wait() + expectLiveReadWatchClosed(t, w) + if got := f.liveReleaseGets - readsBefore; got != 2 { + t.Fatalf("live release reads %d, want one slow failure and one hung retry", got) + } + }) +} + +func TestWatchCancellationEndsHungLiveReadBeforeDeadline(t *testing.T) { + for _, mode := range []string{"stop", "context"} { + t.Run(mode, func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + f := newRVWatchFixture(t) + parent, cancel := context.WithCancel(request.WithNamespace(context.Background(), "default")) + t.Cleanup(cancel) + w, err := f.rest.Watch(parent, &metainternalversion.ListOptions{}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(w.Stop) + live := f.advanceLive(t, "live") + readsBefore := f.liveReleaseGets + entered := make(chan context.Context, 1) + f.liveReleaseErrs = []error{errors.New("live read failed")} + f.onLiveReleaseError = func(ctx context.Context) { + entered <- ctx + <-ctx.Done() + } + f.monitorEvent(live.ResourceVersion) + synctest.Wait() + liveCtx := <-entered + before := time.Now() + if mode == "stop" { + w.Stop() + } else { + cancel() + } + synctest.Wait() + expectLiveReadWatchClosed(t, w) + if !errors.Is(liveCtx.Err(), context.Canceled) { + t.Fatalf("live read ended with %v, want cancellation", liveCtx.Err()) + } + if time.Since(before) != 0 { + t.Fatal("cancellation waited for a timer") + } + if got := f.liveReleaseGets - readsBefore; got != 1 { + t.Fatalf("live release reads %d, want exactly one", got) + } + }) + }) + } +} diff --git a/pkg/registry/apps/application/rest_watch_rv_test.go b/pkg/registry/apps/application/rest_watch_rv_test.go new file mode 100644 index 000000000..06640d72e --- /dev/null +++ b/pkg/registry/apps/application/rest_watch_rv_test.go @@ -0,0 +1,633 @@ +package application + +import ( + "context" + "encoding/json" + "errors" + "strconv" + "testing" + "time" + + cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1" + appsv1alpha1 "github.com/cozystack/cozystack/pkg/apis/apps/v1alpha1" + "github.com/cozystack/cozystack/pkg/config" + helmv2 "github.com/fluxcd/helm-controller/api/v2" + apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metainternalversion "k8s.io/apimachinery/pkg/apis/meta/internalversion" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/watch" + "k8s.io/apiserver/pkg/endpoints/request" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + "sigs.k8s.io/controller-runtime/pkg/client/interceptor" +) + +// rvWatchFixture models the two clients REST uses: c reads from an informer +// cache and writes to the API server, w talks to the API server directly. +// The cache can be left behind the live release, and the HelmRelease and +// WorkloadMonitor watches are fake watchers the test drives. +type rvWatchFixture struct { + rest *REST + cache client.Client + live client.WithWatch + hrW *watch.FakeWatcher + wmW *watch.FakeWatcher + // liveReleaseGets counts HelmRelease reads that bypass the cache. The + // watch goroutine and the test both update it; receiving an event from + // the watch orders the watch's updates before the test's next access. + liveReleaseGets int + // liveReleaseErrs are returned by the next live HelmRelease reads, one + // per read, before reads reach the store again. + liveReleaseErrs []error + onLiveReleaseError func(context.Context) + // liveReleaseHang makes live HelmRelease reads block until their context + // ends, like a request to an API server that never answers. + liveReleaseHang bool + // cacheStore is the store behind cache, for tests that leave the cache + // without the release. + cacheStore client.WithWatch +} + +var rvReleaseKey = client.ObjectKey{Namespace: "default", Name: "postgresql-mydb"} + +func newRVWatchFixture(t *testing.T) *rvWatchFixture { + t.Helper() + scheme := runtime.NewScheme() + if err := cozyv1alpha1.AddToScheme(scheme); err != nil { + t.Fatal(err) + } + if err := helmv2.AddToScheme(scheme); err != nil { + t.Fatal(err) + } + release := func() *helmv2.HelmRelease { + return &helmv2.HelmRelease{ + ObjectMeta: metav1.ObjectMeta{ + Name: rvReleaseKey.Name, + Namespace: rvReleaseKey.Namespace, + Labels: map[string]string{ + ApplicationKindLabel: "PostgreSQL", + ApplicationGroupLabel: appsv1alpha1.GroupName, + ApplicationNameLabel: "mydb", + }, + }, + Spec: helmv2.HelmReleaseSpec{Values: &apiextensionsv1.JSON{Raw: []byte(`{"marker":"cached"}`)}}, + } + } + + f := &rvWatchFixture{hrW: watch.NewFake(), wmW: watch.NewFake()} + liveStore := fake.NewClientBuilder().WithScheme(scheme).WithObjects(release()).Build() + f.live = interceptor.NewClient(liveStore, interceptor.Funcs{ + Get: func(ctx context.Context, c client.WithWatch, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error { + if _, ok := obj.(*helmv2.HelmRelease); ok { + f.liveReleaseGets++ + if f.liveReleaseHang { + <-ctx.Done() + return ctx.Err() + } + if len(f.liveReleaseErrs) > 0 { + err := f.liveReleaseErrs[0] + f.liveReleaseErrs = f.liveReleaseErrs[1:] + if hook := f.onLiveReleaseError; hook != nil { + f.onLiveReleaseError = nil + hook(ctx) + } + return err + } + } + return c.Get(ctx, key, obj, opts...) + }, + Watch: func(_ context.Context, _ client.WithWatch, list client.ObjectList, _ ...client.ListOption) (watch.Interface, error) { + if _, ok := list.(*cozyv1alpha1.WorkloadMonitorList); ok { + return f.wmW, nil + } + return f.hrW, nil + }, + }) + f.cacheStore = fake.NewClientBuilder().WithScheme(scheme).WithObjects(release()).Build() + f.cache = interceptor.NewClient(f.cacheStore, interceptor.Funcs{ + Delete: func(ctx context.Context, _ client.WithWatch, obj client.Object, opts ...client.DeleteOption) error { + return liveStore.Delete(ctx, obj, opts...) + }, + }) + f.rest = NewREST(f.cache, f.live, &config.Resource{ + Application: config.ApplicationConfig{Kind: "PostgreSQL", Plural: "postgresqls", Singular: "postgresql"}, + Release: config.ReleaseConfig{Prefix: "postgresql-"}, + }) + return f +} + +func (f *rvWatchFixture) liveRelease(t *testing.T) *helmv2.HelmRelease { + t.Helper() + hr := &helmv2.HelmRelease{} + if err := f.live.Get(context.Background(), rvReleaseKey, hr); err != nil { + t.Fatal(err) + } + return hr +} + +// advanceLive writes a new spec to the live release only, leaving the cache +// one version behind, and returns the new live release. +func (f *rvWatchFixture) advanceLive(t *testing.T, marker string) *helmv2.HelmRelease { + t.Helper() + hr := f.liveRelease(t) + before := hr.ResourceVersion + hr.Spec.Values = &apiextensionsv1.JSON{Raw: []byte(`{"marker":"` + marker + `"}`)} + if err := f.live.Update(context.Background(), hr); err != nil { + t.Fatal(err) + } + if hr.ResourceVersion == before { + t.Fatal("fake client did not advance the release version") + } + return hr +} + +func (f *rvWatchFixture) monitorEvent(rv string) { + f.wmW.Modify(&cozyv1alpha1.WorkloadMonitor{ + ObjectMeta: metav1.ObjectMeta{ + Name: "mon-1", + Namespace: "default", + ResourceVersion: rv, + Labels: map[string]string{ + appsv1alpha1.ApplicationKindLabel: "PostgreSQL", + appsv1alpha1.ApplicationGroupLabel: appsv1alpha1.GroupName, + appsv1alpha1.ApplicationNameLabel: "mydb", + }, + }, + Status: cozyv1alpha1.WorkloadMonitorStatus{Operational: new(true)}, + }) +} + +func startRVWatch(t *testing.T, f *rvWatchFixture) (context.Context, watch.Interface) { + t.Helper() + ctx, cancel := context.WithCancel(request.WithNamespace(context.Background(), "default")) + t.Cleanup(cancel) + w, err := f.rest.Watch(ctx, &metainternalversion.ListOptions{}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(w.Stop) + return ctx, w +} + +func nextApplication(t *testing.T, w watch.Interface) *appsv1alpha1.Application { + t.Helper() + select { + case ev, ok := <-w.ResultChan(): + if !ok { + t.Fatal("watch closed") + } + app, ok := ev.Object.(*appsv1alpha1.Application) + if !ok { + t.Fatalf("got %s %T, want an Application", ev.Type, ev.Object) + } + return app + case <-time.After(5 * time.Second): + t.Fatal("no event") + } + return nil +} + +func specMarker(t *testing.T, app *appsv1alpha1.Application) string { + t.Helper() + var v struct { + Marker string `json:"marker"` + } + if app.Spec == nil { + t.Fatal("application has no spec") + } + if err := json.Unmarshal(app.Spec.Raw, &v); err != nil { + t.Fatal(err) + } + return v.Marker +} + +func rvNumber(t *testing.T, rv string) uint64 { + t.Helper() + n, err := strconv.ParseUint(rv, 10, 64) + if err != nil { + t.Fatalf("resourceVersion %q: %v", rv, err) + } + return n +} + +// The spec in a monitor-triggered event must come from a release read no +// earlier than the monitor revision the event carries, or a precondition on +// that version would accept a write built on a stale spec. +func TestWatchMonitorEventReadsReleaseLive(t *testing.T) { + f := newRVWatchFixture(t) + _, w := startRVWatch(t, f) + f.advanceLive(t, "live") + + f.monitorEvent("5000") + app := nextApplication(t, w) + if got := specMarker(t, app); got != "live" { + t.Fatalf("spec marker %q, want the live release's", got) + } + if app.ResourceVersion != "5000" { + t.Fatalf("resourceVersion %q, want the monitor's 5000", app.ResourceVersion) + } + if f.liveReleaseGets != 2 { + t.Fatalf("%d live release reads, want the test's own plus one for the event", f.liveReleaseGets) + } +} + +// A release cached at or past the monitor revision already pairs its spec +// with its own version, so the event uses it without a live read: a watch +// replays every existing monitor as ADDED when it starts. With nothing sent +// for the object yet, the client may hold that release version, so the event +// carries the monitor's. +func TestWatchMonitorEventUsesCacheNotOlderThanMonitor(t *testing.T) { + f := newRVWatchFixture(t) + _, w := startRVWatch(t, f) + cached := &helmv2.HelmRelease{} + if err := f.cache.Get(context.Background(), rvReleaseKey, cached); err != nil { + t.Fatal(err) + } + f.advanceLive(t, "live") + gets := f.liveReleaseGets + + f.monitorEvent("1") + app := nextApplication(t, w) + if got := specMarker(t, app); got != "cached" { + t.Fatalf("spec marker %q, want the cached release's", got) + } + if app.ResourceVersion != "1" { + t.Fatalf("resourceVersion %q, want the monitor's 1 rather than the cached release's %q", app.ResourceVersion, cached.ResourceVersion) + } + if f.liveReleaseGets != gets { + t.Fatalf("%d live release reads for a monitor older than the cached release, want none", f.liveReleaseGets-gets) + } +} + +// Shared informers deliver an update whose resourceVersion equals the stored +// one only to handlers due for a resync, so each monitor-only change must +// arrive with a resourceVersion different from the previous event's. +func TestWatchMonitorOnlyChangeAdvancesVersion(t *testing.T) { + f := newRVWatchFixture(t) + _, w := startRVWatch(t, f) + live := f.advanceLive(t, "live") + + f.hrW.Modify(live.DeepCopy()) + prev := rvNumber(t, nextApplication(t, w).ResourceVersion) + for _, rv := range []string{"5000", "5001"} { + f.monitorEvent(rv) + got := rvNumber(t, nextApplication(t, w).ResourceVersion) + if got <= prev { + t.Fatalf("monitor event resourceVersion %d, want above the previous event's %d", got, prev) + } + prev = got + } +} + +// A monitor event processed after the release event it predates must not +// repeat the resourceVersion the client already holds, or a shared informer +// hides it from its handlers. It falls back to the monitor's older version, +// and a delete with that version gets a conflict instead of acting on a spec +// the client may not have. +func TestWatchLateMonitorEventDoesNotRepeatVersion(t *testing.T) { + f := newRVWatchFixture(t) + ctx, w := startRVWatch(t, f) + live := f.liveRelease(t) + + f.hrW.Modify(live.DeepCopy()) + if got := nextApplication(t, w).ResourceVersion; got != live.ResourceVersion { + t.Fatalf("release event resourceVersion %q, want %q", got, live.ResourceVersion) + } + f.monitorEvent("1") + rv := nextApplication(t, w).ResourceVersion + if rv != "1" { + t.Fatalf("late monitor event resourceVersion %q, want the monitor's 1 rather than the held %q", rv, live.ResourceVersion) + } + _, _, err := f.rest.Delete(ctx, "mydb", nil, &metav1.DeleteOptions{Preconditions: &metav1.Preconditions{ResourceVersion: &rv}}) + if !apierrors.IsConflict(err) { + t.Fatalf("delete with the monitor's older version: got %v, want Conflict", err) + } +} + +// A release the client already holds is skipped on a resumed watch, so the +// next monitor event must not repeat its version either. +func TestWatchLateMonitorEventAfterSkippedReplay(t *testing.T) { + f := newRVWatchFixture(t) + live := f.liveRelease(t) + w := startRVWatchFrom(t, f, live.ResourceVersion) + + f.hrW.Add(live.DeepCopy()) + f.monitorEvent("1") + if rv := nextApplication(t, w).ResourceVersion; rv != "1" { + t.Fatalf("monitor event after the skipped replay has resourceVersion %q, want the monitor's 1 rather than the held %q", rv, live.ResourceVersion) + } +} + +// Once this watch has sent the object a monitor version, the release version +// is no longer what the client holds, and the event can carry it. +func TestWatchMonitorEventCarriesReleaseAfterFallback(t *testing.T) { + f := newRVWatchFixture(t) + _, w := startRVWatch(t, f) + live := f.liveRelease(t) + + f.monitorEvent("1") + if rv := nextApplication(t, w).ResourceVersion; rv != "1" { + t.Fatalf("first monitor event resourceVersion %q, want the monitor's 1", rv) + } + f.monitorEvent("2") + if rv := nextApplication(t, w).ResourceVersion; rv != live.ResourceVersion { + t.Fatalf("second monitor event resourceVersion %q, want the release's %q", rv, live.ResourceVersion) + } +} + +// expectNoApplication fails if the watch delivers anything within the wait, +// then sends a release event and receives it so that the watch goroutine's +// earlier bookkeeping is ordered before the caller's next read of it. +func expectNoApplication(t *testing.T, f *rvWatchFixture, w watch.Interface, release *helmv2.HelmRelease) { + t.Helper() + select { + case ev := <-w.ResultChan(): + t.Fatalf("unexpected %s event", ev.Type) + case <-time.After((liveReleaseReadAttempts + 2) * liveReleaseReadRetryDelay): + } + f.hrW.Modify(release) + nextApplication(t, w) +} + +// A transient failure of the live read must not cost the client the monitor +// change: nothing replays it, so the read is retried. +func TestWatchMonitorEventRetriesLiveRead(t *testing.T) { + f := newRVWatchFixture(t) + _, w := startRVWatch(t, f) + live := f.advanceLive(t, "live") + readsBefore := f.liveReleaseGets + timeout := errors.New("etcdserver: request timed out") + f.liveReleaseErrs = []error{timeout, timeout} + + f.monitorEvent(live.ResourceVersion) + app := nextApplication(t, w) + if got := f.liveReleaseGets - readsBefore; got != 3 { + t.Fatalf("live release reads %d, want two failed attempts and one success", got) + } + if got := specMarker(t, app); got != "live" { + t.Fatalf("spec marker %q, want the live spec", got) + } + if app.ResourceVersion != live.ResourceVersion { + t.Fatalf("resourceVersion %q, want the live release's %q", app.ResourceVersion, live.ResourceVersion) + } +} + +// A read that keeps failing is given up after the last attempt, so a broken +// apiserver cannot hold the watch goroutine. +func TestWatchMonitorEventGivesUpAfterRetries(t *testing.T) { + f := newRVWatchFixture(t) + _, w := startRVWatch(t, f) + live := f.advanceLive(t, "live") + readsBefore := f.liveReleaseGets + timeout := errors.New("etcdserver: request timed out") + for range liveReleaseReadAttempts { + f.liveReleaseErrs = append(f.liveReleaseErrs, timeout) + } + + f.monitorEvent(live.ResourceVersion) + expectNoApplication(t, f, w, live) + if got := f.liveReleaseGets - readsBefore; got != liveReleaseReadAttempts { + t.Fatalf("live release reads %d, want %d attempts and no more", got, liveReleaseReadAttempts) + } +} + +// Cancel before the first failed Get returns: a send to FakeWatcher only +// orders event receipt, so cancelling after the send can lose the retry window. +func stopAtFailedLiveRead(t *testing.T, f *rvWatchFixture, w watch.Interface, stop func()) { + t.Helper() + live := f.advanceLive(t, "live") + readsBefore := f.liveReleaseGets + timeout := errors.New("etcdserver: request timed out") + for range liveReleaseReadAttempts { + f.liveReleaseErrs = append(f.liveReleaseErrs, timeout) + } + + f.onLiveReleaseError = func(ctx context.Context) { + stop() + select { + case <-ctx.Done(): + case <-time.After(5 * time.Second): + t.Error("live read context still open after cancellation") + } + } + f.monitorEvent(live.ResourceVersion) + select { + case ev, ok := <-w.ResultChan(): + if ok { + t.Fatalf("unexpected %s event", ev.Type) + } + case <-time.After(5 * time.Second): + t.Fatal("watch still open") + } + if got := f.liveReleaseGets - readsBefore; got != 1 { + t.Fatalf("live release reads %d, want the one before the stop", got) + } +} + +func TestWatchStopAtFailedLiveReadPreventsRetry(t *testing.T) { + f := newRVWatchFixture(t) + _, w := startRVWatch(t, f) + stopAtFailedLiveRead(t, f, w, w.Stop) +} + +func TestWatchContextCancelAtFailedLiveReadPreventsRetry(t *testing.T) { + f := newRVWatchFixture(t) + ctx, cancel := context.WithCancel(request.WithNamespace(context.Background(), "default")) + t.Cleanup(cancel) + w, err := f.rest.Watch(ctx, &metainternalversion.ListOptions{}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(w.Stop) + stopAtFailedLiveRead(t, f, w, cancel) +} + +// A live read that never answers must not outlive the watch: Stop cancels +// the read's context, and the watch closes. +func TestWatchStopCancelsHungLiveRead(t *testing.T) { + f := newRVWatchFixture(t) + _, w := startRVWatch(t, f) + live := f.advanceLive(t, "live") + f.liveReleaseHang = true + + f.monitorEvent(live.ResourceVersion) + w.Stop() + select { + case ev, ok := <-w.ResultChan(): + if ok { + t.Fatalf("unexpected %s event", ev.Type) + } + case <-time.After(5 * time.Second): + t.Fatal("watch still open while a live read hangs") + } +} + +// A release that is gone is final: the event is dropped after one read, +// without retries that would delay the next event. +func TestWatchMonitorEventDroppedWhenReleaseIsGone(t *testing.T) { + f := newRVWatchFixture(t) + _, w := startRVWatch(t, f) + release := f.liveRelease(t) + for _, c := range []client.Client{f.cacheStore, f.live} { + if err := c.Delete(context.Background(), release.DeepCopy()); err != nil { + t.Fatal(err) + } + } + readsBefore := f.liveReleaseGets + + f.monitorEvent(strconv.FormatUint(rvNumber(t, release.ResourceVersion)+1, 10)) + expectNoApplication(t, f, w, release) + if got := f.liveReleaseGets - readsBefore; got != 1 { + t.Fatalf("live release reads %d, want a single read", got) + } +} + +// A release the cache has not seen yet is read live and delivered. +func TestWatchMonitorEventReadsReleaseMissingFromCache(t *testing.T) { + f := newRVWatchFixture(t) + _, w := startRVWatch(t, f) + live := f.advanceLive(t, "live") + if err := f.cacheStore.Delete(context.Background(), live.DeepCopy()); err != nil { + t.Fatal(err) + } + readsBefore := f.liveReleaseGets + + f.monitorEvent(live.ResourceVersion) + app := nextApplication(t, w) + if got := f.liveReleaseGets - readsBefore; got != 1 { + t.Fatalf("live release reads %d, want one", got) + } + if got := specMarker(t, app); got != "live" { + t.Fatalf("spec marker %q, want the live spec", got) + } +} + +// A release event in between makes the release version the held one again. +func TestWatchReleaseEventResetsHeldVersion(t *testing.T) { + f := newRVWatchFixture(t) + _, w := startRVWatch(t, f) + live := f.liveRelease(t) + + f.monitorEvent("1") + nextApplication(t, w) + f.hrW.Modify(live.DeepCopy()) + if rv := nextApplication(t, w).ResourceVersion; rv != live.ResourceVersion { + t.Fatalf("release event resourceVersion %q, want %q", rv, live.ResourceVersion) + } + f.monitorEvent("2") + if rv := nextApplication(t, w).ResourceVersion; rv != "2" { + t.Fatalf("monitor event after the release event has resourceVersion %q, want the monitor's 2 rather than the held %q", rv, live.ResourceVersion) + } +} + +func startRVWatchFrom(t *testing.T, f *rvWatchFixture, resourceVersion string) watch.Interface { + t.Helper() + ctx, cancel := context.WithCancel(request.WithNamespace(context.Background(), "default")) + t.Cleanup(cancel) + w, err := f.rest.Watch(ctx, &metainternalversion.ListOptions{ResourceVersion: resourceVersion}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(w.Stop) + return w +} + +// On a resumed watch the replayed monitor can arrive before the replayed +// release, so nothing is known yet about the version the client holds. +func TestWatchResumedMonitorReplayBeforeRelease(t *testing.T) { + f := newRVWatchFixture(t) + live := f.liveRelease(t) + w := startRVWatchFrom(t, f, live.ResourceVersion) + + f.monitorEvent("1") + if rv := nextApplication(t, w).ResourceVersion; rv != "1" { + t.Fatalf("replayed monitor event has resourceVersion %q, want the monitor's 1 rather than the possibly held %q", rv, live.ResourceVersion) + } +} + +// A fallback event steps the client's resume point below versions it holds, +// so a resumed client can hold a release version above the one it resumes +// from. +func TestWatchResumedBelowHeldReleaseVersion(t *testing.T) { + f := newRVWatchFixture(t) + live := f.liveRelease(t) + if rvNumber(t, live.ResourceVersion) <= 500 { + t.Fatalf("fixture release version %q must be above the resume point", live.ResourceVersion) + } + w := startRVWatchFrom(t, f, "500") + + f.monitorEvent("1") + if rv := nextApplication(t, w).ResourceVersion; rv != "1" { + t.Fatalf("replayed monitor event has resourceVersion %q, want the monitor's 1 rather than the possibly held %q", rv, live.ResourceVersion) + } +} + +func TestDeleteWithVersionFromMonitorEvent(t *testing.T) { + f := newRVWatchFixture(t) + ctx, w := startRVWatch(t, f) + f.advanceLive(t, "live") + + f.monitorEvent("5000") + rv := nextApplication(t, w).ResourceVersion + _, _, err := f.rest.Delete(ctx, "mydb", nil, &metav1.DeleteOptions{Preconditions: &metav1.Preconditions{ResourceVersion: &rv}}) + if err != nil { + t.Fatalf("delete with resourceVersion %q from the watch event: %v", rv, err) + } + if err := f.live.Get(context.Background(), rvReleaseKey, &helmv2.HelmRelease{}); !apierrors.IsNotFound(err) { + t.Fatalf("release still present after delete: %v", err) + } +} + +func TestDeleteRejectsVersionOlderThanLive(t *testing.T) { + f := newRVWatchFixture(t) + cached := &helmv2.HelmRelease{} + if err := f.cache.Get(context.Background(), rvReleaseKey, cached); err != nil { + t.Fatal(err) + } + f.advanceLive(t, "live") + + ctx := request.WithNamespace(context.Background(), "default") + rv := cached.ResourceVersion + _, _, err := f.rest.Delete(ctx, "mydb", nil, &metav1.DeleteOptions{Preconditions: &metav1.Preconditions{ResourceVersion: &rv}}) + if !apierrors.IsConflict(err) { + t.Fatalf("delete with stale resourceVersion %q: got %v, want Conflict", rv, err) + } + if err := f.live.Get(context.Background(), rvReleaseKey, &helmv2.HelmRelease{}); err != nil { + t.Fatalf("release gone after a rejected delete: %v", err) + } +} + +func TestCheckResourceVersion(t *testing.T) { + r := newTestRESTWithSchemesFromClient(nil) + for _, tc := range []struct { + caller string + check func(error) bool + }{ + {"100", func(err error) bool { return err == nil }}, + {"101", func(err error) bool { return err == nil }}, + {"99", apierrors.IsConflict}, + {"0", apierrors.IsConflict}, + {"", apierrors.IsBadRequest}, + {"abc", apierrors.IsBadRequest}, + } { + if err := r.checkResourceVersion("mydb", tc.caller, "100"); !tc.check(err) { + t.Errorf("caller resourceVersion %q against live 100: unexpected result %v", tc.caller, err) + } + } +} + +func TestNewerResourceVersion(t *testing.T) { + for _, tc := range []struct{ a, b, want string }{ + {"7", "5", "7"}, + {"5", "7", "7"}, + {"7", "7", "7"}, + {"x", "5", "5"}, + {"7", "y", "y"}, + } { + if got := newerResourceVersion(tc.a, tc.b); got != tc.want { + t.Errorf("newerResourceVersion(%q, %q) = %q, want %q", tc.a, tc.b, got, tc.want) + } + } +} diff --git a/pkg/registry/apps/application/rest_write_options_test.go b/pkg/registry/apps/application/rest_write_options_test.go index 823a7327c..fd6417c3f 100644 --- a/pkg/registry/apps/application/rest_write_options_test.go +++ b/pkg/registry/apps/application/rest_write_options_test.go @@ -58,7 +58,7 @@ func newOptionsTestREST(t *testing.T, funcs interceptor.Funcs, objects ...client WithObjects(objects...). WithInterceptorFuncs(funcs). Build() - return NewREST(c, nil, &config.Resource{ + return NewREST(c, c, &config.Resource{ Application: config.ApplicationConfig{ Kind: "PostgreSQL", Plural: "postgresqls", @@ -185,7 +185,9 @@ func TestDeletePropagatesWriteOptions(t *testing.T) { grace := int64(3) propagation := metav1.DeletePropagationForeground uid := types.UID("expected-uid") - rv := "17" + // The version the fake client stamps on seeded objects: a resourceVersion + // precondition is checked against the live release. + rv := "999" want := &metav1.DeleteOptions{ GracePeriodSeconds: &grace, Preconditions: &metav1.Preconditions{UID: &uid, ResourceVersion: &rv},