fix(api): preserve Application update concurrency constraints (#5234)

<!-- Thank you for making a contribution! Here are some tips for you:
- Use Conventional Commits for the PR title: `type(scope): description`
- Types: feat, fix, docs, style, refactor, perf, test, build, ci, chore
- Scopes are not an exhaustive list — pick the most specific scope for
the change and extend the list when a genuinely new area appears.
Examples:
- System components: dashboard, platform, operator, cilium, kube-ovn,
linstor, fluxcd, cluster-api
- Managed apps: postgres, mariadb, redis, kafka, clickhouse,
virtual-machine, kubernetes
- Development and maintenance: api, hack, tests, ci, docs, maintenance
- Breaking changes: append `!` after type/scope (`feat(api)!: ...`) or
add a `BREAKING CHANGE:` footer
- If it's a work in progress, consider creating this PR as a draft.
- Don't hesistate to ask for opinion and review in the community chats,
even if it's still a draft.
- Add the label `kind/backport` if it's a bugfix that needs to be
backported to a previous version.
-->

## What this PR does

A stale application update could succeed after a backend conflict.
Retries now rebuild and validate the update against a fresh HelmRelease
snapshot. Caller UID and resourceVersion constraints are checked again.

Updates without a resource version remain supported. A resource version
that parses to zero is unconditional too, as in the Kubernetes generic
registry. A nonzero version older than the live release conflicts. A
retry is judged like a fresh unconditional PUT, including for garbage
collector finalizers. HTTP PUT, PATCH and apply tests cover it. Durable
SSA ownership is not fixed here: Application conversions still omit
managedFields.

Build and vet pass. Race tests for the Application registry and API
server pass. Scoped lint reports one unchanged errcheck that is also
present on main.

Updated the head to the current fix on top of main, including the
workload memory validation from #5348. Please review this head.

### Screenshots

Not applicable; no UI changes.

<!-- REQUIRED for UI changes: attach screenshots or screen recordings
demonstrating
the visual impact of your changes. PRs with UI changes without
screenshots will not be merged. -->

### Downstream repositories

<!--
Cozystack is upstream for repositories that are NOT kept in sync with it
automatically, and nothing in CI compares the two sides, so a change
here can break them silently.

Which change forces what, and which file to touch, is the trigger map in
docs/agents/contributing.md under "Downstream Repositories". Walk it
before you tick anything.

IF YOU ARE AN AI AGENT OR AN LLM, THIS IS PART OF THE TASK, NOT A FORM
TO FILL IN:

1. Walk the trigger map against the actual diff of this PR, file by
file. Do not decide from the PR title or from your memory of what you
changed.
2. For every repository you tick, open the follow-up PR there and link
it on the same line. A ticked box with no link claims work that does not
exist, which is worse than an empty box. Search that repository for an
open PR or issue covering it first, and link that instead of filing a
duplicate.
3. When the follow-up is out of scope, or needs a decision that is not
yours to make, open an issue in that repository instead, link that, and
say so in the PR body. Do not push a speculative PR into another
repository just to fill a line here.
4. Do not tick "No downstream repository is affected" to make the
checklist go away. If you are unsure, leave every box empty and say so
in the PR body, so a human decides.
-->

- [x] No downstream repository is affected by this change
- [ ] [cozystack/website](https://github.com/cozystack/website) -
follow-up:
- [ ]
[cozystack/terraform-provider-cozystack](https://github.com/cozystack/terraform-provider-cozystack)
- follow-up:
- [ ]
[cozystack/ansible-cozystack](https://github.com/cozystack/ansible-cozystack)
- follow-up:
- [ ] [cozystack/ccp](https://github.com/cozystack/ccp) - follow-up:
- [ ] [cozystack/talm](https://github.com/cozystack/talm) - follow-up:
- [ ] [cozystack/cozyhr](https://github.com/cozystack/cozyhr) -
follow-up:
- [ ] [cozystack/cozy-proxy](https://github.com/cozystack/cozy-proxy) -
follow-up:
- [ ]
[cozystack/cozystack-telemetry-server](https://github.com/cozystack/cozystack-telemetry-server)
- follow-up:
- [ ]
[cozystack/external-apps-example](https://github.com/cozystack/external-apps-example)
- follow-up:
- [ ] [cozystack/examples](https://github.com/cozystack/examples) -
follow-up:
- [ ] [cozystack/community](https://github.com/cozystack/community) -
follow-up:

### Release note

<!--  Write a release note:
- Explain what has changed internally and for users.
- Start with the same `type(scope):` prefix as in the PR title
- Follow the guidelines at
https://github.com/kubernetes/community/blob/master/contributors/guide/release-notes.md.
-->

```release-note
fix(api): honor Application update preconditions and recompute patches after conflicts instead of retrying an outdated admitted object.
```


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

* **Bug Fixes**
* Application updates now enforce object identity and resource-version
preconditions. Requests with stale versions or mismatched identities
return a conflict rather than modifying a newer or different object.
* Concurrent updates preserve unrelated HelmRelease fields and lifecycle
metadata when the update can safely be retried. When the request is
based on stale state or the conflict cannot be safely resolved, it
returns a conflict instead of overwriting newer changes.
* Updates from watch events now reject stale resource versions while
allowing updates based on current events.
* Retries no longer restore a removed finalizer on a release being
deleted; the request returns a validation error instead.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
This commit is contained in:
Aleksei Sviridkin authored and GitHub committed 2026-12-03 18:05:36 +03:00
commit 0cc3948180
15 files changed
+1255 -125

No files matched your search

@@ -0,0 +1,500 @@
package server_test
import (
"bytes"
"context"
"encoding/json"
"fmt"
cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1"
"io"
"k8s.io/apimachinery/pkg/watch"
"net/http"
"slices"
"sync"
"testing"
"time"
appsv1alpha1 "github.com/cozystack/cozystack/pkg/apis/apps/v1alpha1"
helmv2 "github.com/fluxcd/helm-controller/api/v2"
apiextv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
apiequality "k8s.io/apimachinery/pkg/api/equality"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apiserver/pkg/admission"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/client/interceptor"
fluxshard "github.com/cozystack/cozystack/internal/fluxshardoperator"
"github.com/cozystack/cozystack/pkg/config"
)
func TestApplicationApplyCreate(t *testing.T) {
for _, uid := range []string{"", "nonexistent"} {
for _, dryRun := range []bool{false, true} {
for _, force := range []bool{false, true} {
t.Run(fmt.Sprintf("uid=%s/dryRun=%v/force=%v", uid, dryRun, force), func(t *testing.T) {
ts, backing := startAppsServer(t, &config.ResourceConfig{Resources: []config.Resource{redisConfig}})
payload := fmt.Sprintf(`{"apiVersion":"apps.cozystack.io/v1alpha1","kind":"Redis","metadata":{"name":"new-app","namespace":"tenant-a","uid":%q},"spec":{"replicas":1}}`, uid)
url := ts.URL + fmt.Sprintf("/apis/apps.cozystack.io/v1alpha1/namespaces/tenant-a/redises/new-app?fieldManager=create-test&force=%v", force)
if dryRun {
url += "&dryRun=All"
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodPatch, url, bytes.NewBufferString(payload))
if err != nil {
t.Fatal(err)
}
req.Header.Set("Content-Type", "application/apply-patch+yaml")
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
response, err := io.ReadAll(resp.Body)
if closeErr := resp.Body.Close(); closeErr != nil {
t.Fatal(closeErr)
}
if err != nil {
t.Fatal(err)
}
want := http.StatusCreated
if uid != "" {
want = http.StatusConflict
}
if resp.StatusCode != want {
t.Fatalf("HTTP %d, want %d: %s", resp.StatusCode, want, response)
}
live := &helmv2.HelmRelease{}
err = backing.Get(ctx, client.ObjectKey{Namespace: "tenant-a", Name: "redis-new-app"}, live)
if dryRun || uid != "" {
if !apierrors.IsNotFound(err) {
t.Fatalf("unexpected persisted object: err=%v live=%#v", err, live)
}
return
}
if err != nil {
t.Fatal(err)
}
if !bytes.Contains(live.Spec.Values.Raw, []byte(`"replicas":1`)) {
t.Fatalf("lost apply spec: %s", live.Spec.Values.Raw)
}
})
}
}
}
}
type updateAdmissionProbe struct {
*admission.Handler
mu sync.Mutex
mutated []string
validated []string
rejectFresh bool
dryRun bool
}
func (p *updateAdmissionProbe) Admit(_ context.Context, attrs admission.Attributes, _ admission.ObjectInterfaces) error {
if attrs.IsDryRun() != p.dryRun {
return fmt.Errorf("mutating admission lost dry-run option")
}
old := attrs.GetOldObject().(*appsv1alpha1.Application)
p.mu.Lock()
p.mutated = append(p.mutated, old.ResourceVersion)
p.mu.Unlock()
app := attrs.GetObject().(*appsv1alpha1.Application)
if app.Annotations == nil {
app.Annotations = map[string]string{}
}
app.Annotations["admitted-version"] = old.ResourceVersion
return nil
}
func (p *updateAdmissionProbe) Validate(_ context.Context, attrs admission.Attributes, _ admission.ObjectInterfaces) error {
if attrs.IsDryRun() != p.dryRun {
return fmt.Errorf("validating admission lost dry-run option")
}
old := attrs.GetOldObject().(*appsv1alpha1.Application)
p.mu.Lock()
p.validated = append(p.validated, old.ResourceVersion)
reject := p.rejectFresh && len(p.mutated) > 0 && old.ResourceVersion != p.mutated[0]
p.mu.Unlock()
if reject {
return apierrors.NewForbidden(attrs.GetResource().GroupResource(), attrs.GetName(), fmt.Errorf("fresh admission snapshot rejected"))
}
return nil
}
func (p *updateAdmissionProbe) versions() ([]string, []string) {
p.mu.Lock()
defer p.mu.Unlock()
return append([]string(nil), p.mutated...), append([]string(nil), p.validated...)
}
func TestApplicationUpdateHTTPConcurrency(t *testing.T) {
for _, method := range []string{"put", "json", "merge", "strategic", "apply"} {
for _, version := range []string{"omitted", "current", "stale", "newer", "zero", "test", "matchingUID", "emptyUID", "wrongUID", "uncontended", "admissionReject"} {
if version == "test" && method != "json" {
continue
}
for _, dryRun := range []bool{false, true} {
for _, force := range []bool{false, true} {
if force && method != "apply" {
continue
}
t.Run(fmt.Sprintf("%s/%s/dryRun=%v/force=%v", method, version, dryRun, force), func(t *testing.T) {
var mu sync.Mutex
writes := 0
var baselineManagedFields []metav1.ManagedFieldsEntry
funcs := interceptor.Funcs{Update: func(ctx context.Context, c client.WithWatch, obj client.Object, opts ...client.UpdateOption) error {
mu.Lock()
defer mu.Unlock()
writes++
writeOptions := (&client.UpdateOptions{}).ApplyOptions(opts).AsUpdateOptions()
if writeOptions.FieldManager != "concurrency-test" || writeOptions.FieldValidation != metav1.FieldValidationStrict || slices.Contains(writeOptions.DryRun, metav1.DryRunAll) != dryRun {
return fmt.Errorf("write options changed: %#v", writeOptions)
}
if writes == 1 && version != "uncontended" {
live := &helmv2.HelmRelease{}
if err := c.Get(ctx, client.ObjectKeyFromObject(obj), live); err != nil {
return err
}
live.Spec.Values = &apiextv1.JSON{Raw: []byte(`{"retained":2,"numeric":1e1,"_internal":true}`)}
live.Spec.Suspend = true
live.Labels["apps.cozystack.io-concurrent"] = "kept"
live.Labels["foreign.example/controller"] = "kept"
live.Labels[fluxshard.ShardKeyLabel] = "concurrent-shard"
live.Annotations = map[string]string{"foreign.example/controller": "kept", "apps.cozystack.io-concurrent": "kept"}
live.OwnerReferences = []metav1.OwnerReference{{APIVersion: "v1", Kind: "ConfigMap", Name: "owner", UID: "owner"}}
live.Finalizers = []string{"finalizers.fluxcd.io", metav1.FinalizerDeleteDependents}
if err := c.Update(ctx, live); err != nil {
return err
}
if err := c.Delete(ctx, live); err != nil {
return err
}
if err := c.Get(ctx, client.ObjectKeyFromObject(obj), live); err != nil {
return err
}
baselineManagedFields = slices.Clone(live.ManagedFields)
}
// The fake client skips resourceVersion validation for dry-run writes.
live := &helmv2.HelmRelease{}
if err := c.Get(ctx, client.ObjectKeyFromObject(obj), live); err != nil {
return err
}
if obj.GetResourceVersion() != live.ResourceVersion || obj.GetUID() != live.UID {
return apierrors.NewConflict(helmv2.GroupVersion.WithResource("helmreleases").GroupResource(), obj.GetName(), fmt.Errorf("object changed"))
}
return c.Update(ctx, obj, opts...)
}}
probe := &updateAdmissionProbe{Handler: admission.NewHandler(admission.Update), dryRun: dryRun, rejectFresh: version == "admissionReject"}
ts, backing := startAppsServerWithInterceptors(t, &config.ResourceConfig{Resources: []config.Resource{redisConfig}}, funcs, probe)
ctx := context.Background()
hr := &helmv2.HelmRelease{ObjectMeta: metav1.ObjectMeta{Name: "redis-app", Namespace: "tenant-a", UID: "original", Labels: map[string]string{
"apps.cozystack.io/application.kind": "Redis", "apps.cozystack.io/application.group": "apps.cozystack.io", "apps.cozystack.io/application.name": "app",
}}, Spec: helmv2.HelmReleaseSpec{Values: &apiextv1.JSON{Raw: []byte(`{"retained":1,"numeric":10.0}`)}}}
if err := backing.Create(ctx, hr); err != nil {
t.Fatal(err)
}
if err := backing.Status().Update(ctx, hr); err != nil {
t.Fatal(err)
}
fixture := &helmv2.HelmRelease{}
if err := backing.Get(ctx, client.ObjectKeyFromObject(hr), fixture); err != nil {
t.Fatal(err)
}
baselineManagedFields = fixture.ManagedFields
url := ts.URL + "/apis/apps.cozystack.io/v1alpha1/namespaces/tenant-a/redises/app"
metadata := map[string]any{"name": "app", "namespace": "tenant-a"}
switch version {
case "current", "test", "uncontended":
metadata["resourceVersion"] = hr.ResourceVersion
case "stale":
metadata["resourceVersion"] = "1"
case "newer":
metadata["resourceVersion"] = "999"
case "zero":
metadata["resourceVersion"] = "0"
case "matchingUID":
metadata["uid"] = "original"
case "emptyUID":
metadata["uid"] = ""
case "wrongUID":
metadata["uid"] = "different"
}
payload := map[string]any{"apiVersion": "apps.cozystack.io/v1alpha1", "kind": "Redis", "metadata": metadata, "spec": map[string]any{"requested": true}}
verb, contentType := http.MethodPatch, "application/merge-patch+json"
var body []byte
switch method {
case "put":
verb, contentType = http.MethodPut, "application/json"
case "strategic":
contentType = "application/strategic-merge-patch+json"
case "apply":
contentType = "application/apply-patch+yaml"
case "json":
contentType = "application/json-patch+json"
ops := []map[string]any{{"op": "add", "path": "/spec/requested", "value": true}}
if rv, ok := metadata["resourceVersion"]; ok {
op := "add"
if version == "test" {
op = "test"
}
ops = append(ops, map[string]any{"op": op, "path": "/metadata/resourceVersion", "value": rv})
}
if uid, ok := metadata["uid"]; ok {
ops = append(ops, map[string]any{"op": "add", "path": "/metadata/uid", "value": uid})
}
body, _ = json.Marshal(ops)
}
if body == nil {
body, _ = json.Marshal(payload)
}
url += "?fieldManager=concurrency-test&fieldValidation=Strict"
if dryRun {
url += "&dryRun=All"
}
if method == "apply" {
url += fmt.Sprintf("&force=%v", force)
}
req, err := http.NewRequestWithContext(ctx, verb, url, bytes.NewReader(body))
if err != nil {
t.Fatal(err)
}
req.Header.Set("Content-Type", contentType)
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
response, err := io.ReadAll(resp.Body)
if closeErr := resp.Body.Close(); closeErr != nil {
t.Fatal(closeErr)
}
if err != nil {
t.Fatal(err)
}
want := http.StatusOK
if version == "current" || version == "stale" {
want = http.StatusConflict
}
if version == "test" {
want = http.StatusUnprocessableEntity
}
if version == "wrongUID" {
want = http.StatusUnprocessableEntity
if method == "put" {
want = http.StatusConflict
}
}
if version == "admissionReject" {
want = http.StatusForbidden
}
if resp.StatusCode != want {
t.Fatalf("HTTP %d, want %d: %s", resp.StatusCode, want, response)
}
mutatedVersions, validatedVersions := probe.versions()
if want == http.StatusOK || want == http.StatusForbidden {
wantCalls := 2
if version == "uncontended" {
wantCalls = 1
}
if len(mutatedVersions) != wantCalls || len(validatedVersions) != wantCalls {
t.Fatalf("admission mutations=%v validations=%v, want %d calls", mutatedVersions, validatedVersions, wantCalls)
}
for i := range mutatedVersions {
if mutatedVersions[i] != validatedVersions[i] {
t.Fatalf("admission snapshot mismatch: mutations=%v validations=%v", mutatedVersions, validatedVersions)
}
}
if wantCalls == 2 && mutatedVersions[0] == mutatedVersions[1] {
t.Fatalf("admission used stale snapshot: %v", mutatedVersions)
}
}
if want == http.StatusOK {
var typed struct {
Metadata metav1.ObjectMeta `json:"metadata"`
Spec struct {
Numeric int64 `json:"numeric"`
Requested bool `json:"requested"`
} `json:"spec"`
}
if err := json.Unmarshal(response, &typed); err != nil {
t.Fatalf("typed readback: %v; response=%s", err, response)
}
if !typed.Spec.Requested || typed.Metadata.Annotations["admitted-version"] != mutatedVersions[len(mutatedVersions)-1] {
t.Fatalf("proposed update missing from response: %s", response)
}
if method != "put" && (typed.Spec.Numeric != 10 || bytes.Contains(response, []byte("_internal"))) {
t.Fatalf("public projection changed: %s", response)
}
}
live := &helmv2.HelmRelease{}
if err := backing.Get(ctx, client.ObjectKeyFromObject(hr), live); err != nil {
t.Fatal(err)
}
if dryRun && (live.Annotations["apps.cozystack.io-admitted-version"] != "" || !apiequality.Semantic.DeepEqual(live.ManagedFields, baselineManagedFields)) {
t.Fatalf("dry-run admission or field management persisted: %#v", live.ObjectMeta)
}
if want == http.StatusOK && !dryRun && live.Annotations["apps.cozystack.io-admitted-version"] != mutatedVersions[len(mutatedVersions)-1] {
t.Fatalf("persisted stale admission output: annotations=%v versions=%v", live.Annotations, mutatedVersions)
}
mu.Lock()
attempts := writes
mu.Unlock()
if want == http.StatusForbidden && attempts != 1 {
t.Fatalf("denied fresh admission reached backend: attempts=%d", attempts)
}
if version == "stale" || version == "wrongUID" {
if attempts != 0 {
t.Fatalf("failed identity constraint reached backend: %d", attempts)
}
return
}
if version == "uncontended" {
if attempts != 1 {
t.Fatalf("uncontended write attempts=%d", attempts)
}
if bytes.Contains(live.Spec.Values.Raw, []byte("requested")) == dryRun {
t.Fatalf("dryRun=%v persisted=%s", dryRun, live.Spec.Values.Raw)
}
return
}
if live.Labels["foreign.example/controller"] != "kept" || live.Annotations["foreign.example/controller"] != "kept" || live.Labels[fluxshard.ShardKeyLabel] != "concurrent-shard" {
t.Fatalf("concurrent controller metadata lost: %#v", live.ObjectMeta)
}
if len(live.OwnerReferences) != 1 || live.OwnerReferences[0].UID != "owner" || live.DeletionTimestamp == nil {
t.Fatalf("concurrent lifecycle metadata lost: %#v", live.ObjectMeta)
}
wantFinalizers := 2
if method == "put" && want == http.StatusOK && !dryRun {
wantFinalizers = 1
}
if !live.Spec.Suspend || len(live.Finalizers) != wantFinalizers || !slices.Contains(live.Finalizers, "finalizers.fluxcd.io") || slices.Contains(live.Finalizers, metav1.FinalizerDeleteDependents) != (wantFinalizers == 2) {
t.Fatalf("concurrent suspension/finalizers lost: %#v", live)
}
if want != http.StatusOK || dryRun {
if bytes.Contains(live.Spec.Values.Raw, []byte("requested")) {
t.Fatalf("failed/dry-run request persisted: %s", live.Spec.Values.Raw)
}
return
}
if attempts != 2 {
t.Fatalf("write attempts=%d, want 2", attempts)
}
if !bytes.Contains(live.Spec.Values.Raw, []byte(`"requested":true`)) {
t.Fatalf("request lost: %s", live.Spec.Values.Raw)
}
if method != "put" && (!bytes.Contains(live.Spec.Values.Raw, []byte(`"retained":2`)) || live.Labels["apps.cozystack.io-concurrent"] != "kept" || live.Annotations["apps.cozystack.io-concurrent"] != "kept") {
t.Fatalf("patch lost concurrent fields: values=%s labels=%v", live.Spec.Values.Raw, live.Labels)
}
})
}
}
}
}
}
func TestApplicationPutFromMonitorWatchEvent(t *testing.T) {
for _, stale := range []bool{false, true} {
t.Run(fmt.Sprintf("stale=%v", stale), func(t *testing.T) {
hrWatch, wmWatch := watch.NewRaceFreeFake(), watch.NewRaceFreeFake()
ts, backing := startAppsServerWithInterceptors(t, &config.ResourceConfig{Resources: []config.Resource{redisConfig}}, interceptor.Funcs{
Watch: func(_ context.Context, _ client.WithWatch, list client.ObjectList, _ ...client.ListOption) (watch.Interface, error) {
if _, ok := list.(*cozyv1alpha1.WorkloadMonitorList); ok {
return wmWatch, nil
}
return hrWatch, nil
},
}, nil)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
hr := &helmv2.HelmRelease{ObjectMeta: metav1.ObjectMeta{Name: "redis-app", Namespace: "tenant-a", UID: "original", Labels: map[string]string{
"apps.cozystack.io/application.kind": "Redis", "apps.cozystack.io/application.group": "apps.cozystack.io", "apps.cozystack.io/application.name": "app",
}}, Spec: helmv2.HelmReleaseSpec{Values: &apiextv1.JSON{Raw: []byte(`{"retained":1}`)}}}
if err := backing.Create(ctx, hr); err != nil {
t.Fatal(err)
}
url := ts.URL + "/apis/apps.cozystack.io/v1alpha1/namespaces/tenant-a/redises"
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url+"?watch=true", nil)
if err != nil {
t.Fatal(err)
}
response, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
defer func() {
if err := response.Body.Close(); err != nil {
t.Errorf("close watch response: %v", err)
}
}()
if response.StatusCode != http.StatusOK {
t.Fatalf("watch HTTP %d", response.StatusCode)
}
monitorRV := "5000"
if stale {
monitorRV = hr.ResourceVersion
}
wmWatch.Modify(&cozyv1alpha1.WorkloadMonitor{ObjectMeta: metav1.ObjectMeta{Name: "monitor", Namespace: "tenant-a", ResourceVersion: monitorRV, Labels: map[string]string{
"apps.cozystack.io/application.kind": "Redis", "apps.cozystack.io/application.group": "apps.cozystack.io", "apps.cozystack.io/application.name": "app",
}}})
var event struct {
Type string `json:"type"`
Object appsv1alpha1.Application `json:"object"`
}
if err := json.NewDecoder(response.Body).Decode(&event); err != nil {
t.Fatal(err)
}
if event.Object.ResourceVersion != monitorRV || !bytes.Contains(event.Object.Spec.Raw, []byte(`"retained":1`)) {
t.Fatalf("watch event: %#v", event)
}
if stale {
hr.Spec.Values = &apiextv1.JSON{Raw: []byte(`{"concurrent":true}`)}
if err := backing.Update(ctx, hr); err != nil {
t.Fatal(err)
}
}
event.Object.Spec = &apiextv1.JSON{Raw: []byte(`{"requested":true}`)}
data, err := json.Marshal(&event.Object)
if err != nil {
t.Fatal(err)
}
put, err := http.NewRequestWithContext(ctx, http.MethodPut, url+"/app", bytes.NewReader(data))
if err != nil {
t.Fatal(err)
}
put.Header.Set("Content-Type", "application/json")
result, err := http.DefaultClient.Do(put)
if err != nil {
t.Fatal(err)
}
defer func() {
if err := result.Body.Close(); err != nil {
t.Errorf("close PUT response: %v", err)
}
}()
body, err := io.ReadAll(result.Body)
if err != nil {
t.Fatal(err)
}
want := http.StatusOK
if stale {
want = http.StatusConflict
}
if result.StatusCode != want {
t.Fatalf("PUT HTTP %d want %d: %s", result.StatusCode, want, body)
}
live := &helmv2.HelmRelease{}
if err := backing.Get(ctx, client.ObjectKeyFromObject(hr), live); err != nil {
t.Fatal(err)
}
expected := `{"requested":true}`
if stale {
expected = `{"concurrent":true}`
}
if string(live.Spec.Values.Raw) != expected {
t.Fatalf("live spec: %s want %s", live.Spec.Values.Raw, expected)
}
})
}
}
+27 -10
View File
@@ -27,11 +27,13 @@ import (
"testing"
"time"
cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1"
helmv2 "github.com/fluxcd/helm-controller/api/v2"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apiserver/pkg/admission"
"k8s.io/apiserver/pkg/authentication/authenticator"
"k8s.io/apiserver/pkg/authentication/user"
"k8s.io/apiserver/pkg/authorization/authorizerfactory"
@@ -75,37 +77,52 @@ func startAppsServerWithUIDs(t *testing.T, rc *config.ResourceConfig, objects ..
}
func serveApps(t *testing.T, rc *config.ResourceConfig, assignUIDs bool, objects ...client.Object) (*httptest.Server, client.Client) {
t.Helper()
return serveAppsWith(t, rc, assignUIDs, interceptor.Funcs{}, nil, objects...)
}
func startAppsServerWithInterceptors(t *testing.T, rc *config.ResourceConfig, funcs interceptor.Funcs, admissionControl admission.Interface) (*httptest.Server, client.Client) {
t.Helper()
return serveAppsWith(t, rc, false, funcs, admissionControl)
}
func serveAppsWith(t *testing.T, rc *config.ResourceConfig, assignUIDs bool, funcs interceptor.Funcs, admissionControl admission.Interface, objects ...client.Object) (*httptest.Server, client.Client) {
t.Helper()
if err := appsv1alpha1.RegisterDynamicTypes(apiserver.Scheme, rc); err != nil {
t.Fatal(err)
}
backing := runtime.NewScheme()
if err := cozyv1alpha1.AddToScheme(backing); err != nil {
t.Fatal(err)
}
if err := helmv2.AddToScheme(backing); err != nil {
t.Fatal(err)
}
if err := corev1.AddToScheme(backing); err != nil {
t.Fatal(err)
}
builder := fake.NewClientBuilder().WithScheme(backing).WithObjects(objects...)
if assignUIDs {
var uids atomic.Int64
builder = builder.WithInterceptorFuncs(interceptor.Funcs{
Create: func(ctx context.Context, c client.WithWatch, obj client.Object, opts ...client.CreateOption) error {
if obj.GetUID() == "" {
obj.SetUID(types.UID(fmt.Sprintf("00000000-0000-0000-0000-%012d", uids.Add(1))))
}
return c.Create(ctx, obj, opts...)
},
})
next := funcs.Create
funcs.Create = func(ctx context.Context, c client.WithWatch, obj client.Object, opts ...client.CreateOption) error {
if obj.GetUID() == "" {
obj.SetUID(types.UID(fmt.Sprintf("00000000-0000-0000-0000-%012d", uids.Add(1))))
}
if next != nil {
return next(ctx, c, obj, opts...)
}
return c.Create(ctx, obj, opts...)
}
}
cli := builder.Build()
cli := fake.NewClientBuilder().WithScheme(backing).WithObjects(objects...).WithStatusSubresource(&helmv2.HelmRelease{}).WithInterceptorFuncs(funcs).WithReturnManagedFields().Build()
cfg := genericapiserver.NewConfig(apiserver.Codecs)
cfg.Authorization.Authorizer = authorizerfactory.NewAlwaysAllowAuthorizer()
cfg.Authentication.Authenticator = authenticator.RequestFunc(func(*http.Request) (*authenticator.Response, bool, error) {
return &authenticator.Response{User: &user.DefaultInfo{Name: "test-user"}}, true, nil
})
cfg.AdmissionControl = admissionControl
cfg.ExternalAddress = "localhost:443"
cfg.LoopbackClientConfig = &restclient.Config{}
cfg.FeatureGate = utilfeature.DefaultMutableFeatureGate
@@ -158,14 +158,17 @@ func TestWorkloadMemoryRecheckedAgainstLiveRelease(t *testing.T) {
}}, Spec: helmv2.HelmReleaseSpec{Values: &apiextv1.JSON{Raw: []byte(stale)}}}
r := newKubernetesWarnREST(t, stored)
r.specSchema = chartSpecSchema(t, "tcp-balancer")
r.c = interceptor.NewClient(r.w, tc.funcs())
base := r.w
intercepted := interceptor.NewClient(base, tc.funcs())
r.c = intercepted
r.w = intercepted
ctx := request.WithNamespace(context.Background(), app.Namespace)
_, _, err := r.Update(ctx, app.Name, newDefaultUpdatedObjectInfo(app), nil, nil, false, &metav1.UpdateOptions{})
if tc.reject && !apierrors.IsInvalid(err) || !tc.reject && err != nil {
t.Fatalf("reject=%v, got %v", tc.reject, err)
}
got := &helmv2.HelmRelease{}
if err := r.w.Get(ctx, client.ObjectKeyFromObject(stored), got); err != nil {
if err := base.Get(ctx, client.ObjectKeyFromObject(stored), got); err != nil {
t.Fatal(err)
}
if string(got.Spec.Values.Raw) != tc.want {
+87 -84
View File
@@ -45,6 +45,7 @@ import (
"k8s.io/apimachinery/pkg/watch"
"k8s.io/apiserver/pkg/endpoints/request"
"k8s.io/apiserver/pkg/registry/rest"
"k8s.io/apiserver/pkg/storage"
"k8s.io/apiserver/pkg/warning"
"k8s.io/client-go/util/retry"
"k8s.io/klog/v2"
@@ -296,47 +297,34 @@ func (r *REST) Create(ctx context.Context, obj runtime.Object, createValidation
// Get retrieves an Application by converting the corresponding HelmRelease
func (r *REST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error) {
app, _, err := r.applicationSnapshot(ctx, name, options, r.c)
if err != nil {
return nil, err
}
return app, nil
}
func (r *REST) applicationSnapshot(ctx context.Context, name string, options *metav1.GetOptions, reader client.Reader) (*appsv1alpha1.Application, *helmv2.HelmRelease, error) {
namespace, err := r.getNamespace(ctx)
if err != nil {
klog.Errorf("Failed to get namespace: %v", err)
return nil, err
return nil, nil, err
}
klog.V(6).Infof("Attempting to retrieve resource %s of type %s in namespace %s", name, r.gvr.Resource, namespace)
// Get the corresponding HelmRelease using the new prefix
helmReleaseName := r.releaseConfig.Prefix + name
helmRelease := &helmv2.HelmRelease{}
err = r.c.Get(ctx, client.ObjectKey{Namespace: namespace, Name: helmReleaseName}, helmRelease, &client.GetOptions{Raw: options})
if err != nil {
klog.Errorf("Error retrieving HelmRelease for resource %s: %v", name, err)
// Check if the error is a NotFound error
if err := reader.Get(ctx, client.ObjectKey{Namespace: namespace, Name: r.releaseConfig.Prefix + name}, helmRelease, &client.GetOptions{Raw: options}); err != nil {
if apierrors.IsNotFound(err) {
// Return a NotFound error for the Application resource instead of HelmRelease
return nil, apierrors.NewNotFound(r.gvr.GroupResource(), name)
return nil, nil, apierrors.NewNotFound(r.gvr.GroupResource(), name)
}
// For other errors, return them as-is
return nil, err
return nil, nil, err
}
// Check if HelmRelease has required labels
if !r.hasRequiredApplicationLabels(helmRelease) {
klog.Errorf("HelmRelease %s does not match the required application labels", helmReleaseName)
// Return a NotFound error for the Application resource
return nil, apierrors.NewNotFound(r.gvr.GroupResource(), name)
return nil, nil, apierrors.NewNotFound(r.gvr.GroupResource(), name)
}
// Convert HelmRelease to Application
snapshot := helmRelease.DeepCopy()
convertedApp, err := r.ConvertHelmReleaseToApplication(ctx, helmRelease)
if err != nil {
klog.Errorf("Conversion error from HelmRelease to Application for resource %s: %v", name, err)
return nil, fmt.Errorf("conversion error: %v", err)
return nil, nil, fmt.Errorf("conversion error: %v", err)
}
klog.V(6).Infof("Successfully retrieved and converted resource %s of kind %s", name, r.gvr.Resource)
return &convertedApp, nil
return &convertedApp, snapshot, nil
}
// List retrieves a list of Applications by converting HelmReleases
@@ -519,13 +507,51 @@ func (r *REST) List(ctx context.Context, options *metainternalversion.ListOption
// Update updates an existing Application by converting it to a HelmRelease
func (r *REST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error) {
// Retrieve the existing Application
oldObj, err := r.Get(ctx, name, &metav1.GetOptions{})
var result runtime.Object
var created, retryable bool
preconditions := objInfo.Preconditions()
if preconditions != nil {
preconditions = preconditions.DeepCopy()
}
// A conflict invalidates the admission snapshot, not just the write's version.
err := retry.OnError(retry.DefaultBackoff, func(err error) bool {
return retryable && apierrors.IsConflict(err)
}, func() error {
var err error
result, retryable, err = r.updateAttempt(ctx, name, objInfo, preconditions, createValidation, updateValidation, forceAllowCreate, options, &created)
return err
})
return result, created, err
}
func (r *REST) checkUpdatePreconditions(name string, preconditions *metav1.Preconditions, app *appsv1alpha1.Application) error {
if preconditions == nil {
return nil
}
check := storage.Preconditions{UID: preconditions.UID}
if app.ResourceVersion == "" {
check.ResourceVersion = preconditions.ResourceVersion
} else if preconditions.ResourceVersion != nil {
if err := r.checkResourceVersion(name, *preconditions.ResourceVersion, app.ResourceVersion); err != nil {
return err
}
}
if err := check.Check(name, app); err != nil {
return apierrors.NewConflict(r.gvr.GroupResource(), name, err)
}
return nil
}
func (r *REST) updateAttempt(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, preconditions *metav1.Preconditions, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions, created *bool) (runtime.Object, bool, error) {
oldObj, snapshot, err := r.applicationSnapshot(ctx, name, &metav1.GetOptions{}, r.w)
if err != nil {
if apierrors.IsNotFound(err) {
if !forceAllowCreate {
return nil, false, err
}
if preconditionErr := r.checkUpdatePreconditions(name, preconditions, &appsv1alpha1.Application{}); preconditionErr != nil {
return nil, false, preconditionErr
}
// If not found and force allow create, create a new one
obj, err := objInfo.UpdatedObject(ctx, nil)
if err != nil {
@@ -537,17 +563,20 @@ func (r *REST) Update(ctx context.Context, name string, objInfo rest.UpdatedObje
klog.Errorf("Failed to create new Application: %v", err)
return nil, false, err
}
return createdObj, true, nil
*created = true
return createdObj, false, nil
}
klog.Errorf("Failed to get existing Application %s: %v", name, err)
return nil, false, err
}
previousValues := oldObj.(*appsv1alpha1.Application).Spec.DeepCopy()
previousFinalizers := slices.Clone(oldObj.(*appsv1alpha1.Application).Finalizers)
if err := r.checkUpdatePreconditions(name, preconditions, oldObj); err != nil {
return nil, false, err
}
previousValues := oldObj.Spec.DeepCopy()
previousFinalizers := slices.Clone(oldObj.Finalizers)
// Update the Application object
newObj, err := objInfo.UpdatedObject(ctx, oldObj)
newObj, err := objInfo.UpdatedObject(ctx, oldObj.DeepCopy())
if err != nil {
klog.Errorf("Failed to get updated object: %v", err)
return nil, false, err
@@ -561,6 +590,22 @@ func (r *REST) Update(ctx context.Context, name string, objInfo rest.UpdatedObje
}
app = app.DeepCopy()
// As in the generic registry, a resourceVersion that parses to zero is an
// unconditional update. Unlike it, a version newer than the release is
// accepted, because watch events can carry a WorkloadMonitor version; see
// checkResourceVersion.
if rv, err := strconv.ParseUint(app.ResourceVersion, 10, 64); app.ResourceVersion != "" && (err != nil || rv != 0) {
if err := r.checkResourceVersion(name, app.ResourceVersion, snapshot.ResourceVersion); err != nil {
return nil, false, err
}
}
// Application updates have historically allowed an omitted resourceVersion.
app.ResourceVersion = snapshot.ResourceVersion
if app.UID == "" {
app.UID = snapshot.UID
} else if app.UID != snapshot.UID {
return nil, false, apierrors.NewInvalid(r.gvk.GroupKind(), name, field.ErrorList{field.Invalid(field.NewPath("metadata", "uid"), app.UID, "field is immutable")})
}
// Note: name validation (DNS-1035 format + length) is intentionally skipped on
// Update because Kubernetes names are immutable. Validating here would block
@@ -586,7 +631,7 @@ func (r *REST) Update(ctx context.Context, name string, objInfo rest.UpdatedObje
// Validate the update if a validation function is provided
if updateValidation != nil {
if err := updateValidation(ctx, app, oldObj); err != nil {
if err := updateValidation(ctx, app.DeepCopy(), oldObj.DeepCopy()); err != nil {
klog.Errorf("Update validation failed for Application %s: %v", name, err)
return nil, false, err
}
@@ -613,17 +658,12 @@ func (r *REST) Update(ctx context.Context, name string, objInfo rest.UpdatedObje
return nil, false, fmt.Errorf("conversion error: %v", err)
}
// Keep the conversion output pristine: the metadata assembly below reads the
// live object, so a conflict retry has to redo it from this copy rather than
// re-apply it on top of its own previous result.
converted := helmRelease.DeepCopy()
cur := &helmv2.HelmRelease{}
if err := r.c.Get(ctx, client.ObjectKey{Namespace: helmRelease.Namespace, Name: helmRelease.Name}, cur, &client.GetOptions{Raw: &metav1.GetOptions{}}); err != nil {
if err := r.w.Get(ctx, client.ObjectKeyFromObject(snapshot), cur, &client.GetOptions{Raw: &metav1.GetOptions{}}); err != nil {
return nil, false, registry.WrapPreservingStatus("failed to fetch current HelmRelease", err, r.gvr.GroupResource(), name)
}
if helmRelease.ResourceVersion == "" {
helmRelease.SetResourceVersion(cur.GetResourceVersion())
if cur.UID != snapshot.UID || cur.ResourceVersion != snapshot.ResourceVersion {
return nil, true, apierrors.NewConflict(r.gvr.GroupResource(), name, fmt.Errorf("the object changed during the update"))
}
// The memory check above compared against the read at the start of Update.
// Compare again against the live release, so a stale value below 1Mi cannot
@@ -647,45 +687,8 @@ func (r *REST) Update(ctx context.Context, name string, objInfo rest.UpdatedObje
klog.V(6).Infof("Updating HelmRelease %s in namespace %s", helmRelease.Name, helmRelease.Namespace)
// Update the HelmRelease in Kubernetes.
//
// Flux's helm-controller (and other controllers) continuously write the
// HelmRelease's status, which shares the object's resourceVersion. When a
// caller updates an app CR while a prior reconcile is still in flight, the
// resourceVersion read above goes stale and the Update is rejected with a
// 409 Conflict. Apart from suspend, the HelmRelease spec is derived from the
// Application the caller just applied, so a stale-resourceVersion conflict
// is never a real spec conflict here: refresh the resourceVersion from the
// live object and retry. Suspend is refreshed with it, because the write
// that caused the conflict may be the one that suspended the release.
//
// The carried-over metadata is not derived from the Application, though, and
// the writer that caused the conflict is usually the controller that owns it
// — helm-controller re-adding finalizers.fluxcd.io is the case this whole
// carry-over exists for. Keeping the copy read before the conflict would put
// the stale metadata back and undo that write, so rebuild from the
// conversion output against the object just read.
err = retry.RetryOnConflict(retry.DefaultBackoff, func() error {
updateErr := r.c.Update(ctx, helmRelease, registry.ClientUpdateOptions(options))
if apierrors.IsConflict(updateErr) {
cur := &helmv2.HelmRelease{}
if getErr := r.c.Get(ctx, client.ObjectKey{Namespace: helmRelease.Namespace, Name: helmRelease.Name}, cur, &client.GetOptions{Raw: &metav1.GetOptions{}}); getErr != nil {
return getErr
}
if memErr := r.validateWorkloadMemory(app, cur.Spec.Values); memErr != nil {
return memErr
}
helmRelease = converted.DeepCopy()
r.applyLiveMetadata(helmRelease, cur, app, previousFinalizers)
keepAccountValuesFrom(helmRelease, cur)
helmRelease.SetResourceVersion(cur.GetResourceVersion())
helmRelease.Spec.Suspend = cur.Spec.Suspend
}
return updateErr
})
if err != nil {
klog.Errorf("Failed to update HelmRelease %s: %v", helmRelease.Name, err)
return nil, false, registry.WrapPreservingStatus("failed to update HelmRelease", err, r.gvr.GroupResource(), name)
if err := r.c.Update(ctx, helmRelease, registry.ClientUpdateOptions(options)); err != nil {
return nil, apierrors.IsConflict(err), registry.WrapPreservingStatus("failed to update HelmRelease", err, r.gvr.GroupResource(), name)
}
// Convert the updated HelmRelease back to Application
@@ -63,6 +63,7 @@ func TestCreate_AdmissionChain_RejectsViaCreateValidation(t *testing.T) {
fakeClient := fake.NewClientBuilder().WithScheme(scheme).Build()
r := &REST{
c: fakeClient,
w: fakeClient,
gvr: schema.GroupVersionResource{
Group: appsv1alpha1.GroupName,
Version: "v1alpha1",
@@ -143,6 +144,7 @@ func TestUpdate_AdmissionChain_RejectsViaUpdateValidation(t *testing.T) {
fakeClient := fake.NewClientBuilder().WithScheme(scheme).WithObjects(existing).Build()
r := &REST{
c: fakeClient,
w: fakeClient,
gvr: schema.GroupVersionResource{
Group: appsv1alpha1.GroupName,
Version: "v1alpha1",
@@ -247,6 +249,7 @@ func TestDelete_AdmissionChain_RejectsViaDeleteValidation(t *testing.T) {
r := &REST{
c: fakeClient,
w: fakeClient,
gvr: schema.GroupVersionResource{
Group: appsv1alpha1.GroupName,
Version: "v1alpha1",
@@ -35,21 +35,6 @@ import (
"github.com/cozystack/cozystack/pkg/config"
)
// TestUpdate_RetriesOnResourceVersionConflict pins the retry.RetryOnConflict
// wrapper around the HelmRelease write in REST.Update.
//
// Flux's helm-controller continuously rewrites a HelmRelease's status, which
// shares the object's resourceVersion. When a caller updates an Application CR
// while a prior reconcile is still in flight, the resourceVersion read by
// Update goes stale and the write is rejected with a 409 Conflict. Apart from
// suspend, which TestUpdate_RefreshesSuspendOnConflictRetry covers, the
// HelmRelease spec is derived from the Application the caller just applied, so
// a stale-resourceVersion conflict is never a real spec conflict: Update must
// refresh the resourceVersion and retry rather than surface the 409.
//
// The fake client returns one Conflict on the first HelmRelease Update, then
// lets the second through. A regression that drops the retry makes the first
// 409 fatal and this test fails.
func TestUpdate_RetriesOnResourceVersionConflict(t *testing.T) {
scheme := runtime.NewScheme()
if err := helmv2.AddToScheme(scheme); err != nil {
@@ -104,6 +89,7 @@ func TestUpdate_RetriesOnResourceVersionConflict(t *testing.T) {
r := &REST{
c: fakeClient,
w: fakeClient,
gvr: schema.GroupVersionResource{
Group: appsv1alpha1.GroupName,
Version: "v1alpha1",
@@ -37,6 +37,7 @@ func newCredentialsTestREST(t *testing.T, objs ...client.Object) (*REST, client.
c := fake.NewClientBuilder().WithScheme(scheme).WithObjects(objs...).Build()
return &REST{
c: c,
w: c,
gvr: schema.GroupVersionResource{Group: appsv1alpha1.GroupName, Version: "v1alpha1", Resource: "postgreses"},
gvk: schema.GroupVersionKind{Group: appsv1alpha1.GroupName, Version: "v1alpha1", Kind: "Postgres"},
kindName: "Postgres",
@@ -1,15 +1,19 @@
package application
import (
"bytes"
"context"
"errors"
"slices"
"testing"
helmv2 "github.com/fluxcd/helm-controller/api/v2"
apiextv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
apivalidation "k8s.io/apimachinery/pkg/api/validation"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/util/validation/field"
"k8s.io/apiserver/pkg/endpoints/request"
"k8s.io/apiserver/pkg/registry/rest"
"sigs.k8s.io/controller-runtime/pkg/client"
@@ -77,18 +81,17 @@ func TestApplicationGarbageCollection(t *testing.T) {
}
}
func TestApplicationGarbageCollectionConflict(t *testing.T) {
func TestApplicationGarbageCollectionExplicitVersionConflict(t *testing.T) {
for _, concurrent := range []struct {
name string
initial []string
requested []string
updated []string
expected []string
}{
{"helm-completes", []string{metav1.FinalizerDeleteDependents, "finalizers.fluxcd.io", "test.example/hold"}, nil, []string{metav1.FinalizerDeleteDependents, "test.example/hold"}, []string{"test.example/hold"}},
{"controller-adds-finalizer", []string{metav1.FinalizerDeleteDependents}, nil, []string{metav1.FinalizerDeleteDependents, "finalizers.fluxcd.io"}, []string{"finalizers.fluxcd.io"}},
{"gc-starts-during-update", []string{"finalizers.fluxcd.io"}, nil, []string{"finalizers.fluxcd.io", metav1.FinalizerDeleteDependents}, []string{"finalizers.fluxcd.io", metav1.FinalizerDeleteDependents}},
{"gc-finishes-during-update", []string{"finalizers.fluxcd.io", metav1.FinalizerDeleteDependents}, []string{metav1.FinalizerDeleteDependents}, []string{"finalizers.fluxcd.io"}, []string{"finalizers.fluxcd.io"}},
{"helm-completes", []string{metav1.FinalizerDeleteDependents, "finalizers.fluxcd.io", "test.example/hold"}, nil, []string{metav1.FinalizerDeleteDependents, "test.example/hold"}},
{"controller-adds-finalizer", []string{metav1.FinalizerDeleteDependents}, nil, []string{metav1.FinalizerDeleteDependents, "finalizers.fluxcd.io"}},
{"gc-starts-during-update", []string{"finalizers.fluxcd.io"}, nil, []string{"finalizers.fluxcd.io", metav1.FinalizerDeleteDependents}},
{"gc-finishes-during-update", []string{"finalizers.fluxcd.io", metav1.FinalizerDeleteDependents}, []string{metav1.FinalizerDeleteDependents}, []string{"finalizers.fluxcd.io"}},
} {
t.Run(concurrent.name, func(t *testing.T) {
hr := optionsTestHelmRelease()
@@ -105,6 +108,7 @@ func TestApplicationGarbageCollectionConflict(t *testing.T) {
return err
}
live.Finalizers = slices.Clone(concurrent.updated)
live.Spec.Values = &apiextv1.JSON{Raw: []byte(`{"concurrent":true}`)}
if err := c.Update(ctx, live); err != nil {
return err
}
@@ -118,18 +122,22 @@ func TestApplicationGarbageCollectionConflict(t *testing.T) {
}
app := obj.(*appsv1alpha1.Application)
app.Finalizers = concurrent.requested
if _, _, err := r.Update(ctx, app.Name, rest.DefaultUpdatedObjectInfo(app), nil, nil, false, &metav1.UpdateOptions{}); err != nil {
t.Fatal(err)
app.Spec = &apiextv1.JSON{Raw: []byte(`{"requested":true}`)}
if _, _, err := r.Update(ctx, app.Name, rest.DefaultUpdatedObjectInfo(app), nil, nil, false, &metav1.UpdateOptions{}); !apierrors.IsConflict(err) {
t.Fatalf("expected explicit resourceVersion conflict, got %v", err)
}
live := &helmv2.HelmRelease{}
if err := r.c.Get(ctx, client.ObjectKeyFromObject(hr), live); err != nil {
t.Fatal(err)
}
if updates != 2 {
t.Fatalf("update calls = %d, want 2", updates)
if updates != 1 {
t.Fatalf("update calls = %d, want 1", updates)
}
if !slices.Equal(live.Finalizers, concurrent.expected) {
t.Fatalf("finalizers = %v, want %v", live.Finalizers, concurrent.expected)
if !slices.Equal(live.Finalizers, concurrent.updated) {
t.Fatalf("finalizers = %v, want %v", live.Finalizers, concurrent.updated)
}
if live.Spec.Values == nil || !bytes.Equal(live.Spec.Values.Raw, []byte(`{"concurrent":true}`)) {
t.Fatalf("stale desired spec persisted: %v", live.Spec.Values)
}
})
}
@@ -194,3 +202,59 @@ func TestApplicationGarbageCollectionWithInPlaceUpdate(t *testing.T) {
t.Fatalf("release still exists after in-place finalizer removal: %v", err)
}
}
// A retry is rebuilt like a fresh unconditional PUT, so a finalizer the caller
// still carries after the garbage collector removed it is a new finalizer on a
// deleting object, which the API server forbids.
func TestApplicationGarbageCollectionRetryCannotRestoreFinalizer(t *testing.T) {
hr := optionsTestHelmRelease()
now := metav1.Now()
hr.DeletionTimestamp = &now
hr.Finalizers = []string{"finalizers.fluxcd.io", metav1.FinalizerDeleteDependents}
updates := 0
r := newOptionsTestREST(t, interceptor.Funcs{
Update: func(ctx context.Context, c client.WithWatch, obj client.Object, opts ...client.UpdateOption) error {
updates++
live := &helmv2.HelmRelease{}
if err := c.Get(ctx, client.ObjectKeyFromObject(obj), live); err != nil {
return err
}
if updates == 1 {
live.Finalizers = []string{"finalizers.fluxcd.io"}
if err := c.Update(ctx, live); err != nil {
return err
}
return apierrors.NewConflict(helmv2.GroupVersion.WithResource("helmreleases").GroupResource(), obj.GetName(), errors.New("garbage collector finished"))
}
if errs := apivalidation.ValidateObjectMetaAccessorUpdate(obj, live, field.NewPath("metadata")); len(errs) > 0 {
return apierrors.NewInvalid(helmv2.GroupVersion.WithKind("HelmRelease").GroupKind(), obj.GetName(), errs)
}
return c.Update(ctx, obj, opts...)
},
}, hr)
ctx := request.WithNamespace(context.Background(), optionsTestNamespace)
obj, err := r.Get(ctx, "example", &metav1.GetOptions{})
if err != nil {
t.Fatal(err)
}
app := obj.(*appsv1alpha1.Application)
if !slices.Contains(app.Finalizers, metav1.FinalizerDeleteDependents) {
t.Fatalf("caller cannot see %q: %v", metav1.FinalizerDeleteDependents, app.Finalizers)
}
app.ResourceVersion = ""
_, _, err = r.Update(ctx, app.Name, rest.DefaultUpdatedObjectInfo(app), nil, nil, false, &metav1.UpdateOptions{})
var status apierrors.APIStatus
if !apierrors.IsInvalid(err) || !errors.As(err, &status) || status.Status().Details == nil {
t.Fatalf("expected Invalid for a finalizer restored on a deleting release, got %v", err)
}
if causes := status.Status().Details.Causes; len(causes) != 1 || causes[0].Field != "metadata.finalizers" {
t.Fatalf("rejected for %v, want only metadata.finalizers", causes)
}
live := &helmv2.HelmRelease{}
if err := r.c.Get(ctx, client.ObjectKeyFromObject(hr), live); err != nil {
t.Fatal(err)
}
if updates != 2 || !slices.Equal(live.Finalizers, []string{"finalizers.fluxcd.io"}) {
t.Fatalf("updates=%d finalizers=%v", updates, live.Finalizers)
}
}
@@ -69,6 +69,7 @@ func TestUpdate_PreservesShardKeyLabel(t *testing.T) {
fakeClient := fake.NewClientBuilder().WithScheme(scheme).WithObjects(existing).Build()
r := &REST{
c: fakeClient,
w: fakeClient,
gvr: schema.GroupVersionResource{
Group: appsv1alpha1.GroupName,
Version: "v1alpha1",
@@ -57,6 +57,7 @@ func newSuspendTestREST(t *testing.T, existing *helmv2.HelmRelease, funcs *inter
c := builder.Build()
return &REST{
c: c,
w: c,
gvr: schema.GroupVersionResource{
Group: appsv1alpha1.GroupName,
Version: "v1alpha1",
@@ -0,0 +1,548 @@
package application
import (
"bytes"
"context"
"encoding/json"
"fmt"
"testing"
helmv2 "github.com/fluxcd/helm-controller/api/v2"
apiextv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apiserver/pkg/endpoints/request"
"k8s.io/apiserver/pkg/registry/rest"
"k8s.io/client-go/util/retry"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/client/interceptor"
appsv1alpha1 "github.com/cozystack/cozystack/pkg/apis/apps/v1alpha1"
)
type concurrencyObjectInfo struct {
preconditions *metav1.Preconditions
transform func(context.Context, runtime.Object) (runtime.Object, error)
}
func (i concurrencyObjectInfo) Preconditions() *metav1.Preconditions { return i.preconditions }
func (i concurrencyObjectInfo) UpdatedObject(ctx context.Context, old runtime.Object) (runtime.Object, error) {
return i.transform(ctx, old)
}
func TestUpdatePreconditions(t *testing.T) {
uid, emptyUID := types.UID("original"), types.UID("")
rv, emptyRV, differentRV := "7", "", "07"
differentUID := types.UID("different")
for _, tc := range []struct {
name string
preconditions *metav1.Preconditions
missing bool
conflict bool
badRequest bool
retry bool
}{
{name: "none"},
{name: "matching", preconditions: &metav1.Preconditions{UID: &uid, ResourceVersion: &rv}},
{name: "RV changed after conflict", preconditions: &metav1.Preconditions{ResourceVersion: &rv}, retry: true, conflict: true},
{name: "empty UID", preconditions: &metav1.Preconditions{UID: &emptyUID}, conflict: true},
{name: "empty RV", preconditions: &metav1.Preconditions{ResourceVersion: &emptyRV}, badRequest: true},
{name: "missing with UID", preconditions: &metav1.Preconditions{UID: &uid}, missing: true, conflict: true},
{name: "missing empty UID", preconditions: &metav1.Preconditions{UID: &emptyUID}, missing: true},
{name: "different UID", preconditions: &metav1.Preconditions{UID: &differentUID}, conflict: true},
{name: "numeric RV alias", preconditions: &metav1.Preconditions{ResourceVersion: &differentRV}},
{name: "missing with RV", preconditions: &metav1.Preconditions{ResourceVersion: &rv}, missing: true, conflict: true},
{name: "missing empty RV", preconditions: &metav1.Preconditions{ResourceVersion: &emptyRV}, missing: true},
} {
t.Run(tc.name, func(t *testing.T) {
existing := optionsTestHelmRelease()
existing.UID, existing.ResourceVersion = uid, rv
objects := []client.Object{existing}
if tc.missing {
objects = nil
}
writes, callbacks := 0, 0
r := newOptionsTestREST(t, interceptor.Funcs{
Update: func(ctx context.Context, c client.WithWatch, obj client.Object, opts ...client.UpdateOption) error {
writes++
if tc.retry && writes == 1 {
live := &helmv2.HelmRelease{}
if err := c.Get(ctx, client.ObjectKeyFromObject(obj), live); err != nil {
return err
}
live.Spec.Suspend = true
if err := c.Update(ctx, live); err != nil {
return err
}
}
return c.Update(ctx, obj, opts...)
},
}, objects...)
info := concurrencyObjectInfo{preconditions: tc.preconditions, transform: func(context.Context, runtime.Object) (runtime.Object, error) {
callbacks++
return optionsTestApplication(), nil
}}
ctx := request.WithNamespace(context.Background(), optionsTestNamespace)
_, _, err := r.Update(ctx, "example", info, nil, nil, tc.missing, &metav1.UpdateOptions{})
if tc.badRequest {
if !apierrors.IsBadRequest(err) || writes != 0 {
t.Fatalf("err=%v writes=%d", err, writes)
}
return
}
if tc.conflict {
wantCalls := 0
if tc.retry {
wantCalls = 1
}
if !apierrors.IsConflict(err) || writes != wantCalls || callbacks != wantCalls {
t.Fatalf("err=%v writes=%d callbacks=%d, want %d", err, writes, callbacks, wantCalls)
}
} else if err != nil {
t.Fatal(err)
}
if tc.retry {
live := &helmv2.HelmRelease{}
if err := r.c.Get(ctx, client.ObjectKeyFromObject(existing), live); err != nil {
t.Fatal(err)
}
if live.ResourceVersion != "8" || !live.Spec.Suspend {
t.Fatalf("concurrent write changed: %#v", live)
}
}
})
}
}
func TestUpdateOutputIdentity(t *testing.T) {
for _, tc := range []struct {
name, rv string
uid types.UID
conflict, invalid bool
}{
{name: "omitted"},
{name: "numeric zero", rv: "0"},
{name: "numeric zero alias", rv: "00"},
{name: "current", rv: "7", uid: "original"},
{name: "monitor revision", rv: "5000", uid: "original"},
{name: "stale", rv: "6", conflict: true},
{name: "changed UID", uid: "different", invalid: true},
} {
t.Run(tc.name, func(t *testing.T) {
existing := optionsTestHelmRelease()
existing.UID, existing.ResourceVersion = "original", "7"
r := newOptionsTestREST(t, interceptor.Funcs{}, existing)
app := optionsTestApplication()
app.UID, app.ResourceVersion = tc.uid, tc.rv
ctx := request.WithNamespace(context.Background(), optionsTestNamespace)
got, _, err := r.Update(ctx, "example", concurrencyObjectInfo{transform: func(context.Context, runtime.Object) (runtime.Object, error) { return app, nil }}, nil, nil, false, &metav1.UpdateOptions{})
if tc.conflict {
if !apierrors.IsConflict(err) {
t.Fatalf("expected conflict: %v", err)
}
return
}
if tc.invalid {
if !apierrors.IsInvalid(err) {
t.Fatalf("expected invalid UID: %v", err)
}
return
}
if err != nil {
t.Fatal(err)
}
if got.(*appsv1alpha1.Application).UID != "original" {
t.Fatalf("identity lost: %#v", got)
}
})
}
}
func TestUpdateRebuildsAttempt(t *testing.T) {
for _, beforeSecondRead := range []bool{false, true} {
for _, explicitRV := range []bool{false, true} {
t.Run(fmt.Sprintf("secondRead=%v/explicitRV=%v", beforeSecondRead, explicitRV), func(t *testing.T) {
existing := optionsTestHelmRelease()
existing.UID, existing.ResourceVersion = "original", "7"
existing.Spec.Values = &apiextv1.JSON{Raw: []byte(`{"counter":1}`)}
reads, writes, callbacks, admissions := 0, 0, 0, 0
mutate := func(ctx context.Context, c client.WithWatch) error {
live := &helmv2.HelmRelease{}
if err := c.Get(ctx, client.ObjectKeyFromObject(existing), live); err != nil {
return err
}
live.Spec.Values = &apiextv1.JSON{Raw: []byte(`{"counter":2}`)}
live.Spec.Suspend = true
live.Labels[LabelPrefix+"concurrent"] = "kept"
live.Labels["foreign"] = "kept"
return c.Update(ctx, live)
}
r := newOptionsTestREST(t, interceptor.Funcs{
Get: func(ctx context.Context, c client.WithWatch, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error {
reads++
if beforeSecondRead && reads == 2 {
if err := mutate(ctx, c); err != nil {
return err
}
}
return c.Get(ctx, key, obj, opts...)
},
Update: func(ctx context.Context, c client.WithWatch, obj client.Object, opts ...client.UpdateOption) error {
writes++
if !beforeSecondRead && writes == 1 {
if err := mutate(ctx, c); err != nil {
return err
}
}
return c.Update(ctx, obj, opts...)
},
}, existing)
info := concurrencyObjectInfo{transform: func(_ context.Context, old runtime.Object) (runtime.Object, error) {
callbacks++
app := old.(*appsv1alpha1.Application).DeepCopy()
if explicitRV {
app.ResourceVersion = "7"
}
var values map[string]any
if err := json.Unmarshal(app.Spec.Raw, &values); err != nil {
return nil, err
}
values["requested"] = true
app.Spec.Raw, _ = json.Marshal(values)
old.(*appsv1alpha1.Application).Spec.Raw = []byte(`{"counter":999}`)
return app, nil
}}
ctx := request.WithNamespace(context.Background(), optionsTestNamespace)
_, _, err := r.Update(ctx, "example", info, nil, func(_ context.Context, _, old runtime.Object) error {
admissions++
if bytes.Contains(old.(*appsv1alpha1.Application).Spec.Raw, []byte("999")) {
t.Fatal("callback mutated admission snapshot")
}
return nil
}, false, &metav1.UpdateOptions{})
wantWrites := 2
if beforeSecondRead {
wantWrites = 1
}
if explicitRV {
wantWrites--
if !apierrors.IsConflict(err) || writes != wantWrites {
t.Fatalf("stale RV: err=%v writes=%d, want %d", err, writes, wantWrites)
}
return
}
if err != nil {
t.Fatal(err)
}
if writes != wantWrites {
t.Fatalf("writes=%d, want %d", writes, wantWrites)
}
live := &helmv2.HelmRelease{}
if err := r.c.Get(ctx, client.ObjectKeyFromObject(existing), live); err != nil {
t.Fatal(err)
}
if callbacks < 2 || admissions < 2 || !live.Spec.Suspend || live.Labels[LabelPrefix+"concurrent"] != "kept" || live.Labels["foreign"] != "kept" {
t.Fatalf("callbacks=%d admissions=%d live=%#v", callbacks, admissions, live)
}
app, err := r.ConvertHelmReleaseToApplication(ctx, live)
if err != nil {
t.Fatal(err)
}
if !bytes.Contains(app.Spec.Raw, []byte(`"counter":2`)) || !bytes.Contains(app.Spec.Raw, []byte(`"requested":true`)) {
t.Fatalf("lost concurrent spec: %v", app.Spec)
}
})
}
}
}
func TestUpdateStatusConflict(t *testing.T) {
for _, explicit := range []bool{false, true} {
t.Run(fmt.Sprint(explicit), func(t *testing.T) {
existing := optionsTestHelmRelease()
existing.UID, existing.ResourceVersion = "original", "7"
writes, callbacks, admissions := 0, 0, 0
r := newOptionsTestREST(t, interceptor.Funcs{Update: func(ctx context.Context, c client.WithWatch, obj client.Object, opts ...client.UpdateOption) error {
writes++
if writes == 1 {
live := &helmv2.HelmRelease{}
if err := c.Get(ctx, client.ObjectKeyFromObject(existing), live); err != nil {
return err
}
live.Status.LastAttemptedRevision = "new-status"
if err := c.Status().Update(ctx, live); err != nil {
return err
}
}
return c.Update(ctx, obj, opts...)
}}, existing)
info := concurrencyObjectInfo{transform: func(_ context.Context, old runtime.Object) (runtime.Object, error) {
callbacks++
app := old.(*appsv1alpha1.Application).DeepCopy()
if explicit {
app.ResourceVersion = "7"
}
return app, nil
}}
ctx := request.WithNamespace(context.Background(), optionsTestNamespace)
got, _, err := r.Update(ctx, "example", info, nil, func(_ context.Context, _, old runtime.Object) error {
admissions++
if admissions == 2 && old.(*appsv1alpha1.Application).Status.Version != "new-status" {
t.Fatal("stale admission status")
}
return nil
}, false, &metav1.UpdateOptions{})
if explicit {
if !apierrors.IsConflict(err) || writes != 1 {
t.Fatalf("err=%v writes=%d", err, writes)
}
return
}
if err != nil {
t.Fatal(err)
}
if callbacks != 2 || admissions != 2 || got.(*appsv1alpha1.Application).Status.Version != "new-status" {
t.Fatalf("callbacks=%d admissions=%d result=%#v", callbacks, admissions, got)
}
})
}
}
func TestUpdateConflictExhaustionAndCallbackErrors(t *testing.T) {
for _, failure := range []string{"backend", "callback", "admission"} {
t.Run(failure, func(t *testing.T) {
conflict := apierrors.NewConflict(helmv2.GroupVersion.WithResource("helmreleases").GroupResource(), "postgresql-example", fmt.Errorf("conflict"))
writes, callbacks, admissions := 0, 0, 0
r := newOptionsTestREST(t, interceptor.Funcs{Update: func(context.Context, client.WithWatch, client.Object, ...client.UpdateOption) error {
writes++
return conflict
}}, optionsTestHelmRelease())
info := concurrencyObjectInfo{transform: func(context.Context, runtime.Object) (runtime.Object, error) {
callbacks++
if failure == "callback" {
return nil, conflict
}
return optionsTestApplication(), nil
}}
ctx := request.WithNamespace(context.Background(), optionsTestNamespace)
_, _, err := r.Update(ctx, "example", info, nil, func(context.Context, runtime.Object, runtime.Object) error {
admissions++
if failure == "admission" {
return conflict
}
return nil
}, false, &metav1.UpdateOptions{})
if !apierrors.IsConflict(err) {
t.Fatalf("expected conflict: %v", err)
}
if failure == "backend" {
if writes != retry.DefaultBackoff.Steps || callbacks != writes || admissions != writes {
t.Fatalf("writes=%d callbacks=%d admissions=%d", writes, callbacks, admissions)
}
} else if writes != 0 || callbacks != 1 {
t.Fatalf("non-backend conflict retried: writes=%d callbacks=%d", writes, callbacks)
}
})
}
}
func TestUpdateUsesDirectReader(t *testing.T) {
existing := optionsTestHelmRelease()
existing.UID, existing.ResourceVersion = "original", "7"
r := newOptionsTestREST(t, interceptor.Funcs{}, existing)
direct := r.w
cached := interceptor.NewClient(direct, interceptor.Funcs{Get: func(context.Context, client.WithWatch, client.ObjectKey, client.Object, ...client.GetOption) error {
t.Fatal("update consulted cached reader")
return nil
}})
r.c = cached
app := optionsTestApplication()
app.ResourceVersion = "7"
ctx := request.WithNamespace(context.Background(), optionsTestNamespace)
if _, _, err := r.Update(ctx, "example", rest.DefaultUpdatedObjectInfo(app), nil, nil, false, &metav1.UpdateOptions{}); err != nil {
t.Fatal(err)
}
}
func TestUpdateRecreation(t *testing.T) {
for _, betweenReads := range []bool{false, true} {
for _, constrained := range []bool{false, true} {
t.Run(fmt.Sprintf("betweenReads=%v/constrained=%v", betweenReads, constrained), func(t *testing.T) {
existing := optionsTestHelmRelease()
existing.UID, existing.ResourceVersion = "original", "7"
existing.Spec.Values = &apiextv1.JSON{Raw: []byte(`{"incarnation":"original"}`)}
reads, writes, callbacks := 0, 0, 0
recreate := func(ctx context.Context, c client.WithWatch) error {
if err := c.Delete(ctx, existing); err != nil {
return err
}
replacement := existing.DeepCopy()
replacement.UID, replacement.ResourceVersion = "replacement", ""
replacement.Spec.Values = &apiextv1.JSON{Raw: []byte(`{"incarnation":"replacement"}`)}
return c.Create(ctx, replacement)
}
r := newOptionsTestREST(t, interceptor.Funcs{
Get: func(ctx context.Context, c client.WithWatch, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error {
reads++
if betweenReads && reads == 2 {
if err := recreate(ctx, c); err != nil {
return err
}
}
return c.Get(ctx, key, obj, opts...)
},
Update: func(ctx context.Context, c client.WithWatch, obj client.Object, opts ...client.UpdateOption) error {
writes++
if !betweenReads && writes == 1 {
if err := recreate(ctx, c); err != nil {
return err
}
}
return c.Update(ctx, obj, opts...)
},
}, existing)
info := concurrencyObjectInfo{transform: func(_ context.Context, old runtime.Object) (runtime.Object, error) {
callbacks++
return old.DeepCopyObject(), nil
}}
if constrained {
uid := existing.UID
info.preconditions = &metav1.Preconditions{UID: &uid}
}
ctx := request.WithNamespace(context.Background(), optionsTestNamespace)
got, _, err := r.Update(ctx, "example", info, nil, nil, false, &metav1.UpdateOptions{})
if constrained {
if !apierrors.IsConflict(err) || callbacks != 1 {
t.Fatalf("err=%v callbacks=%d", err, callbacks)
}
return
}
if err != nil {
t.Fatal(err)
}
if callbacks != 2 || got.(*appsv1alpha1.Application).UID != "replacement" || !bytes.Contains(got.(*appsv1alpha1.Application).Spec.Raw, []byte("replacement")) {
t.Fatalf("callbacks=%d result=%#v", callbacks, got)
}
})
}
}
}
func TestUpdateValidationCannotChangeWriteIdentity(t *testing.T) {
existing := optionsTestHelmRelease()
existing.UID, existing.ResourceVersion = "original", "7"
r := newOptionsTestREST(t, interceptor.Funcs{}, existing)
ctx := request.WithNamespace(context.Background(), optionsTestNamespace)
got, _, err := r.Update(ctx, "example", rest.DefaultUpdatedObjectInfo(optionsTestApplication()), nil, func(_ context.Context, obj, old runtime.Object) error {
obj.(*appsv1alpha1.Application).UID = "validator-mutation"
old.(*appsv1alpha1.Application).UID = "validator-mutation"
return nil
}, false, &metav1.UpdateOptions{})
if err != nil {
t.Fatal(err)
}
if got.(*appsv1alpha1.Application).UID != "original" {
t.Fatalf("validator changed persisted identity: %#v", got)
}
}
func TestUpdateMissingWithoutCreateRemainsNotFound(t *testing.T) {
r := newOptionsTestREST(t, interceptor.Funcs{})
app := optionsTestApplication()
app.UID = "missing"
ctx := request.WithNamespace(context.Background(), optionsTestNamespace)
if _, _, err := r.Update(ctx, "example", rest.DefaultUpdatedObjectInfo(app), nil, nil, false, &metav1.UpdateOptions{}); !apierrors.IsNotFound(err) {
t.Fatalf("expected NotFound without create-on-update, got %v", err)
}
}
func TestUpdateDiscardsEqualPublicSnapshots(t *testing.T) {
existing := optionsTestHelmRelease()
existing.UID, existing.ResourceVersion = "original", "7"
existing.Spec.Values = &apiextv1.JSON{Raw: []byte(`{"counter":10.0}`)}
reads, writes := 0, 0
var publicSnapshots [][]byte
r := newOptionsTestREST(t, interceptor.Funcs{
Get: func(ctx context.Context, c client.WithWatch, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error {
reads++
if reads == 2 {
live := &helmv2.HelmRelease{}
if err := c.Get(ctx, key, live); err != nil {
return err
}
live.Spec.Values = &apiextv1.JSON{Raw: []byte(`{"counter":1e1}`)}
if err := c.Update(ctx, live); err != nil {
return err
}
}
return c.Get(ctx, key, obj, opts...)
},
Update: func(ctx context.Context, c client.WithWatch, obj client.Object, opts ...client.UpdateOption) error {
writes++
return c.Update(ctx, obj, opts...)
},
}, existing)
info := concurrencyObjectInfo{transform: func(_ context.Context, old runtime.Object) (runtime.Object, error) {
app := old.(*appsv1alpha1.Application)
publicSnapshots = append(publicSnapshots, bytes.Clone(app.Spec.Raw))
return app.DeepCopy(), nil
}}
ctx := request.WithNamespace(context.Background(), optionsTestNamespace)
if _, _, err := r.Update(ctx, "example", info, nil, nil, false, &metav1.UpdateOptions{}); err != nil {
t.Fatal(err)
}
if len(publicSnapshots) != 2 || !bytes.Equal(publicSnapshots[0], publicSnapshots[1]) || writes != 1 {
t.Fatalf("public snapshots=%q writes=%d", publicSnapshots, writes)
}
}
var _ rest.UpdatedObjectInfo = concurrencyObjectInfo{}
func TestUpdateFromMonitorWatchEvent(t *testing.T) {
for _, stale := range []bool{false, true} {
t.Run(fmt.Sprintf("stale=%v", stale), func(t *testing.T) {
f := newRVWatchFixture(t)
ctx, w := startRVWatch(t, f)
f.advanceLive(t, "watched")
live := f.liveRelease(t)
monitorRV := live.ResourceVersion
if !stale {
monitorRV = "5000"
}
f.monitorEvent(monitorRV)
app := nextApplication(t, w)
if app.ResourceVersion != monitorRV || specMarker(t, app) != "watched" {
t.Fatalf("watch snapshot: %#v", app)
}
if stale {
f.advanceLive(t, "concurrent")
}
writes := 0
f.rest.c = interceptor.NewClient(f.cacheStore, interceptor.Funcs{
Update: func(ctx context.Context, _ client.WithWatch, obj client.Object, opts ...client.UpdateOption) error {
writes++
return f.live.Update(ctx, obj, opts...)
},
})
app.Spec = &apiextv1.JSON{Raw: []byte(`{"marker":"requested"}`)}
_, _, err := f.rest.Update(ctx, "mydb", rest.DefaultUpdatedObjectInfo(app), nil, nil, false, &metav1.UpdateOptions{})
if stale {
if !apierrors.IsConflict(err) || writes != 0 {
t.Fatalf("stale update: err=%v writes=%d", err, writes)
}
if got := string(f.liveRelease(t).Spec.Values.Raw); got != `{"marker":"concurrent"}` {
t.Fatalf("overwrote concurrent spec: %s", got)
}
} else {
if err != nil {
t.Fatal(err)
}
if got := string(f.liveRelease(t).Spec.Values.Raw); got != `{"marker":"requested"}` {
t.Fatalf("write not stored: %s", got)
}
}
})
}
}
@@ -110,6 +110,7 @@ func TestUpdate_ForceAllowCreate_RejectsTenantDashName(t *testing.T) {
r := &REST{
c: fakeClient,
w: fakeClient,
gvr: schema.GroupVersionResource{
Group: appsv1alpha1.GroupName,
Version: "v1alpha1",
@@ -209,7 +209,8 @@ func TestWatchIntegration_WMWatcherCloseProducesNilChannel(t *testing.T) {
}
func newTestRESTWithSchemesFromClient(c client.Client) *REST {
return NewREST(c, nil, nil, &config.Resource{
w, _ := c.(client.WithWatch)
return NewREST(c, w, nil, &config.Resource{
Application: config.ApplicationConfig{
Kind: "PostgreSQL",
Plural: "postgresqls",
@@ -25,7 +25,7 @@ func newTestRESTWithSchemes(objs ...runtime.Object) *REST {
}
c := builder.Build()
return NewREST(c, nil, nil, &config.Resource{
return NewREST(c, c, nil, &config.Resource{
Application: config.ApplicationConfig{
Kind: "PostgreSQL",
Plural: "postgresqls",
@@ -55,6 +55,7 @@ func newOptionsTestREST(t *testing.T, funcs interceptor.Funcs, objects ...client
}
c := fake.NewClientBuilder().
WithScheme(scheme).
WithStatusSubresource(&helmv2.HelmRelease{}).
WithObjects(objects...).
WithInterceptorFuncs(funcs).
Build()