From 5d8015b5da8cd4534785319d52c18898cef69518 Mon Sep 17 00:00:00 2001 From: Marcus Kimpenhaus <575109+kimpenhaus@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:19:39 +0100 Subject: [PATCH] feat(client)!: write the status with server-side apply UpdateStatusAsync replaced the status with a PUT that carried the resourceVersion and failed with 409 Conflict whenever the resource had changed, e.g. its spec. It now sends apiVersion, kind, name, namespace and the status as a server-side apply to the /status subresource, without the resourceVersion and with force, as recommended for controllers. It uses the field manager of the client; an operator sets it. BREAKING CHANGE: UpdateStatusAsync no longer fails with 409 Conflict on an outdated entity, and it needs a field manager. A KubernetesClient outside an operator that writes the status has to be created with one, e.g. new KubernetesClient(config, "my-tool"). --- .../operator/configuration/field-manager.mdx | 7 +- docs/docs/operator/migration.mdx | 24 +++- docs/docs/operator/troubleshooting.mdx | 7 +- .../IKubernetesClient.cs | 7 ++ .../KubernetesClient.cs | 29 ++++- src/KubeOps.KubernetesClient/README.md | 5 + .../KubernetesClient.FieldManager.Test.cs | 2 +- .../KubernetesClient.UpdateStatus.Test.cs | 105 ++++++++++++++++++ .../EntityController.Integration.Test.cs | 4 +- .../ReplaceEntityRequeue.Integration.Test.cs | 5 +- ...tesClient.UpdateStatus.Integration.Test.cs | 65 +++++++++++ 11 files changed, 248 insertions(+), 12 deletions(-) create mode 100644 test/KubeOps.KubernetesClient.Test/KubernetesClient.UpdateStatus.Test.cs create mode 100644 test/KubeOps.Operator.Test/KubernetesClient.UpdateStatus.Integration.Test.cs diff --git a/docs/docs/operator/configuration/field-manager.mdx b/docs/docs/operator/configuration/field-manager.mdx index 59d22723..6da32b16 100644 --- a/docs/docs/operator/configuration/field-manager.mdx +++ b/docs/docs/operator/configuration/field-manager.mdx @@ -55,8 +55,11 @@ leader elector and all internal services write through that instance, so the fie Requests to the connect subresources `proxy`, `exec`, `attach` and `portforward` stay unchanged: they do not write an object, and the API server forwards the query of a proxy request to the backend. -A request that already carries a `fieldManager` keeps it. A server-side apply, which requires an explicit -field manager, still writes under the name you pass to `PatchAsync`: +`UpdateStatusAsync` writes the status with server-side apply, which requires a field manager; it uses the +field manager of the client. + +A request that already carries a `fieldManager` keeps it. A server-side apply through `PatchAsync` still +writes under the name you pass to it: ```csharp await client.PatchAsync( diff --git a/docs/docs/operator/migration.mdx b/docs/docs/operator/migration.mdx index 122fab91..8db7eb93 100644 --- a/docs/docs/operator/migration.mdx +++ b/docs/docs/operator/migration.mdx @@ -368,7 +368,8 @@ thread on the API call. Use the `...Async` variants, which also accept a `Cancel v15 moves `KubeOps.Aspire.Hosting` to Aspire 17. Aspire 17 deprecates `AddProject` and the `Aspire.AppHost.Sdk` in favour of path-based projects, so `AddKubeOps` now takes the path of the operator project. `KubeOps.KubernetesClient` drops the `force` parameter of the JSON patch overloads of `PatchAsync`, -where the API server never accepted it. The other packages have no breaking changes. +where the API server never accepted it, and `UpdateStatusAsync` writes the status with server-side apply. The +other packages have no breaking changes. ### `KubeOps.Aspire.Hosting` requires Aspire 17 @@ -417,3 +418,24 @@ builder.AddKubeOps("operator", "../MyOperator") **Migration:** remove `force` from these calls. To take over fields of other field managers, send a server-side apply patch with `PatchAsync(new V1Patch(..., V1Patch.PatchType.ApplyPatch), name, namespace, fieldManager, force: true)`. + +### `UpdateStatusAsync` writes the status with server-side apply + +`UpdateStatusAsync` replaced the status with a `PUT` that carried the `resourceVersion` and failed with +`409 Conflict` whenever the resource had changed, e.g. its spec. It now sends the status as a server-side apply +to the `/status` subresource, without the `resourceVersion` and with `force`, as recommended for controllers: + +- It no longer fails with `409 Conflict` on an outdated entity, and it keeps the spec and the status fields it + does not send. +- The status fields belong to the field manager in `managedFields` (operation `Apply`). A field that an earlier + `UpdateStatusAsync` sent and the entity no longer carries is removed. Fields written before the upgrade stay + with the `Update` entry of the `PUT` and are only taken over when they are sent again; leaving one out does not + remove it from existing resources. +- Server-side apply needs a field manager. An operator sets it (see [Field Manager](./configuration/field-manager)). + +**Migration:** nothing within an operator that uses the default `IKubernetes`. An own registered `IKubernetes` +needs the `FieldManagerHandler` (see [Field Manager](./configuration/field-manager)). A `KubernetesClient` +outside an operator that writes the status needs a field manager: `new KubernetesClient(config, "my-tool")`. Without one, the API server rejects the write with +`fieldManager: Required value`. If you relied on `UpdateStatusAsync` failing on an outdated entity, replace the +status through `client.ApiClient.CustomObjects.ReplaceNamespacedCustomObjectStatusAsync`, which still checks the +`resourceVersion`. diff --git a/docs/docs/operator/troubleshooting.mdx b/docs/docs/operator/troubleshooting.mdx index 74d53ed6..1d141fdf 100644 --- a/docs/docs/operator/troubleshooting.mdx +++ b/docs/docs/operator/troubleshooting.mdx @@ -68,16 +68,19 @@ The most common causes, in order of likelihood: ## HTTP 409 Conflict on updates -**Symptom:** `UpdateAsync`/`UpdateStatusAsync` fails with `Conflict`. +**Symptom:** `UpdateAsync` fails with `Conflict`. Every mutating call returns the entity with a **new `resourceVersion`**. Reusing a stale reference for a subsequent call fails with 409. Always continue working with the entity instance returned by the client: ```csharp -entity = await client.UpdateStatusAsync(entity, cancellationToken); // use the returned entity +entity = await client.UpdateAsync(entity, cancellationToken); // use the returned entity ``` +`UpdateStatusAsync` does not conflict: it applies the status with server-side apply and without the +`resourceVersion`. + 409s can also come from another actor (or a second operator instance without [leader election](./configuration/leader-election)) writing the same object concurrently. Treat them as retryable: re-fetch, re-apply, or simply let the failed reconciliation retry. diff --git a/src/KubeOps.KubernetesClient/IKubernetesClient.cs b/src/KubeOps.KubernetesClient/IKubernetesClient.cs index 856d36b2..25e80b18 100644 --- a/src/KubeOps.KubernetesClient/IKubernetesClient.cs +++ b/src/KubeOps.KubernetesClient/IKubernetesClient.cs @@ -251,6 +251,13 @@ Task> UpdateAsync(params TEntity[] entities) /// /// Update the status object of a given entity on the Kubernetes API. /// + /// + /// The status is sent as a server-side apply to the /status subresource, without the + /// resourceVersion and with force. It does not fail with 409 Conflict if the entity changed + /// in the meantime, and status fields that an earlier update set but no longer + /// carries are removed. The client needs a field manager, which an operator sets; outside an operator, create + /// the client with one. + /// /// The type of the Kubernetes entity. /// The entity that contains a status object. /// The token to monitor for cancellation requests. diff --git a/src/KubeOps.KubernetesClient/KubernetesClient.cs b/src/KubeOps.KubernetesClient/KubernetesClient.cs index 01e8c991..b6b7b5c0 100644 --- a/src/KubeOps.KubernetesClient/KubernetesClient.cs +++ b/src/KubeOps.KubernetesClient/KubernetesClient.cs @@ -6,6 +6,7 @@ using System.Diagnostics; using System.Net; using System.Runtime.CompilerServices; +using System.Text.Json.Nodes; using k8s; using k8s.Autorest; @@ -228,22 +229,42 @@ public Task UpdateStatusAsync(TEntity entity, CancellationToke ThrowIfDisposed(); var metadata = GetMetadata(); + + // A server-side apply of the status only: without resourceVersion it does not conflict with other writes, + // and force takes over the status fields from other managers, as recommended for controllers. + var objectMeta = new JsonObject { ["name"] = entity.Name() }; + if (entity.Namespace() is { } @namespace) + { + objectMeta["namespace"] = @namespace; + } + + var status = new JsonObject + { + ["apiVersion"] = metadata.GroupWithVersion, + ["kind"] = metadata.Kind, + ["metadata"] = objectMeta, + ["status"] = entity.ToNode()?["status"]?.DeepClone(), + }; + var patch = new V1Patch(status.ToJsonString(), V1Patch.PatchType.ApplyPatch); + return entity.Namespace() switch { - { } ns => ApiClient.CustomObjects.ReplaceNamespacedCustomObjectStatusAsync( - entity, + { } ns => ApiClient.CustomObjects.PatchNamespacedCustomObjectStatusAsync( + patch, metadata.Group ?? string.Empty, metadata.Version, ns, metadata.PluralName, entity.Name(), + force: true, cancellationToken: cancellationToken), - _ => ApiClient.CustomObjects.ReplaceClusterCustomObjectStatusAsync( - entity, + _ => ApiClient.CustomObjects.PatchClusterCustomObjectStatusAsync( + patch, metadata.Group ?? string.Empty, metadata.Version, metadata.PluralName, entity.Name(), + force: true, cancellationToken: cancellationToken), }; } diff --git a/src/KubeOps.KubernetesClient/README.md b/src/KubeOps.KubernetesClient/README.md index 68c42584..218e5daa 100644 --- a/src/KubeOps.KubernetesClient/README.md +++ b/src/KubeOps.KubernetesClient/README.md @@ -161,6 +161,11 @@ if (existingCrd != null) } ``` +`UpdateStatusAsync` applies the status with server-side apply to the `/status` subresource, without the +`resourceVersion`, so it does not fail with `409 Conflict` when the resource changed in the meantime. Server-side +apply needs a field manager: create the client with one (see [Field Manager](#field-manager)); within an +operator it is set automatically. + ### Watch Resources ```csharp diff --git a/test/KubeOps.KubernetesClient.Test/KubernetesClient.FieldManager.Test.cs b/test/KubeOps.KubernetesClient.Test/KubernetesClient.FieldManager.Test.cs index abc4a677..1b830107 100644 --- a/test/KubeOps.KubernetesClient.Test/KubernetesClient.FieldManager.Test.cs +++ b/test/KubeOps.KubernetesClient.Test/KubernetesClient.FieldManager.Test.cs @@ -47,7 +47,7 @@ await _client.PatchAsync( _apiServer.Requests.Should().Equal( ("POST", "my-operator"), ("PUT", "my-operator"), - ("PUT", "my-operator"), + ("PATCH", "my-operator"), ("PATCH", "my-operator")); } diff --git a/test/KubeOps.KubernetesClient.Test/KubernetesClient.UpdateStatus.Test.cs b/test/KubeOps.KubernetesClient.Test/KubernetesClient.UpdateStatus.Test.cs new file mode 100644 index 00000000..9858f555 --- /dev/null +++ b/test/KubeOps.KubernetesClient.Test/KubernetesClient.UpdateStatus.Test.cs @@ -0,0 +1,105 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. + +using System.Text.Json.Nodes; + +using FluentAssertions; + +using k8s; +using k8s.Models; + +using KubeOps.Abstractions.Entities; +using KubeOps.TestHelpers; + +namespace KubeOps.KubernetesClient.Test; + +[Trait(TestTrait.Category, TestCategory.UnitTest)] +[Trait(TestTrait.Area, TestArea.KubernetesClient)] +public sealed class KubernetesClientUpdateStatusTest : IDisposable +{ + private static readonly KubernetesClientConfiguration Config = new() { Host = "https://kubernetes.test" }; + + private readonly StubApiServer _apiServer = new() { Response = new V1StatusTestEntity() }; + private readonly IKubernetesClient _client; + + public KubernetesClientUpdateStatusTest() + { + _client = new KubernetesClient(Config, new Kubernetes(Config, _apiServer)); + } + + [Fact] + public async Task UpdateStatus_Applies_Only_The_Status_With_Force_To_The_Status_Subresource() + { + var entity = new V1StatusTestEntity + { + Metadata = new() { Name = "my-entity", NamespaceProperty = "default", ResourceVersion = "1" }, + Spec = new() { Replicas = 3 }, + Status = new() { Phase = "Ready" }, + }; + + await _client.UpdateStatusAsync(entity, TestContext.Current.CancellationToken); + + var request = _apiServer.Requests.Should().ContainSingle().Subject; + request.Method.Should().Be("PATCH"); + request.Uri.PathAndQuery.Should() + .Be("/apis/client.test/v1/namespaces/default/statustests/my-entity/status?force=true"); + request.ContentType.Should().Be("application/apply-patch+yaml"); + JsonNode.DeepEquals(JsonNode.Parse(request.Body!), JsonNode.Parse(""" + { + "apiVersion": "client.test/v1", + "kind": "StatusTest", + "metadata": { "name": "my-entity", "namespace": "default" }, + "status": { "phase": "Ready" } + } + """)).Should().BeTrue(request.Body); + } + + [Fact] + public async Task UpdateStatus_Of_A_Cluster_Scoped_Entity_Sends_No_Namespace() + { + var entity = new V1ClusterStatusTestEntity + { + Metadata = new() { Name = "my-entity" }, + Status = new() { Phase = "Ready" }, + }; + + await _client.UpdateStatusAsync(entity, TestContext.Current.CancellationToken); + + var request = _apiServer.Requests.Should().ContainSingle().Subject; + request.Uri.PathAndQuery.Should().Be("/apis/client.test/v1/clusterstatustests/my-entity/status?force=true"); + JsonNode.DeepEquals(JsonNode.Parse(request.Body!), JsonNode.Parse(""" + { + "apiVersion": "client.test/v1", + "kind": "ClusterStatusTest", + "metadata": { "name": "my-entity" }, + "status": { "phase": "Ready" } + } + """)).Should().BeTrue(request.Body); + } + + public void Dispose() => _client.Dispose(); + + [KubernetesEntity(Group = "client.test", ApiVersion = "v1", Kind = "StatusTest", PluralName = "statustests")] + private sealed class V1StatusTestEntity + : CustomKubernetesEntity + { + public sealed class EntitySpec + { + public int Replicas { get; set; } + } + + public sealed class EntityStatus + { + public string? Phase { get; set; } + } + } + + [KubernetesEntity( + Group = "client.test", + ApiVersion = "v1", + Kind = "ClusterStatusTest", + PluralName = "clusterstatustests")] + private sealed class V1ClusterStatusTestEntity + : CustomKubernetesEntity; +} diff --git a/test/KubeOps.Operator.Test/Controller/EntityController.Integration.Test.cs b/test/KubeOps.Operator.Test/Controller/EntityController.Integration.Test.cs index fa3e6722..34729d0e 100644 --- a/test/KubeOps.Operator.Test/Controller/EntityController.Integration.Test.cs +++ b/test/KubeOps.Operator.Test/Controller/EntityController.Integration.Test.cs @@ -4,6 +4,7 @@ using FluentAssertions; +using k8s; using k8s.Models; using KubeOps.Abstractions.Reconciliation; @@ -20,7 +21,8 @@ namespace KubeOps.Operator.Test.Controller; public sealed class EntityControllerIntegrationTest : IntegrationTestBase { private readonly InvocationCounter _mock = new(); - private readonly IKubernetesClient _client = new KubernetesClient.KubernetesClient(); + private readonly IKubernetesClient _client = + new KubernetesClient.KubernetesClient(KubernetesClientConfiguration.BuildDefaultConfig(), "kubeops-test"); private readonly TestNamespaceProvider _ns = new(); [Fact] diff --git a/test/KubeOps.Operator.Test/Controller/ReplaceEntityRequeue.Integration.Test.cs b/test/KubeOps.Operator.Test/Controller/ReplaceEntityRequeue.Integration.Test.cs index ae450ac3..df107cea 100644 --- a/test/KubeOps.Operator.Test/Controller/ReplaceEntityRequeue.Integration.Test.cs +++ b/test/KubeOps.Operator.Test/Controller/ReplaceEntityRequeue.Integration.Test.cs @@ -4,6 +4,8 @@ using FluentAssertions; +using k8s; + using KubeOps.Abstractions.Reconciliation; using KubeOps.Abstractions.Reconciliation.Controller; using KubeOps.Abstractions.Reconciliation.Queue; @@ -21,7 +23,8 @@ namespace KubeOps.Operator.Test.Controller; public sealed class ReplaceEntityRequeueIntegrationTest : IntegrationTestBase { private readonly InvocationCounter _mock = new(); - private readonly IKubernetesClient _client = new KubernetesClient.KubernetesClient(); + private readonly IKubernetesClient _client = + new KubernetesClient.KubernetesClient(KubernetesClientConfiguration.BuildDefaultConfig(), "kubeops-test"); private readonly TestNamespaceProvider _ns = new(); [Fact] diff --git a/test/KubeOps.Operator.Test/KubernetesClient.UpdateStatus.Integration.Test.cs b/test/KubeOps.Operator.Test/KubernetesClient.UpdateStatus.Integration.Test.cs new file mode 100644 index 00000000..aa853dd7 --- /dev/null +++ b/test/KubeOps.Operator.Test/KubernetesClient.UpdateStatus.Integration.Test.cs @@ -0,0 +1,65 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. + +using FluentAssertions; + +using k8s; +using k8s.Models; + +using KubeOps.KubernetesClient; +using KubeOps.Operator.Test.TestEntities; + +using Microsoft.Extensions.Hosting; + +namespace KubeOps.Operator.Test; + +[Trait(TestTrait.Area, TestArea.KubernetesClient)] +public sealed class KubernetesClientUpdateStatusIntegrationTest : IntegrationTestBase +{ + private readonly IKubernetesClient _client = + new KubernetesClient.KubernetesClient(KubernetesClientConfiguration.BuildDefaultConfig(), "kubeops-test"); + + private readonly TestNamespaceProvider _ns = new(); + + [Fact] + public async Task UpdateStatus_Of_An_Outdated_Entity_Applies_The_Status_And_Keeps_The_Spec() + { + var cancellationToken = TestContext.Current.CancellationToken; + var entity = await _client.CreateAsync( + new V1OperatorIntegrationTestEntity("test-entity", "username", _ns.Namespace), + cancellationToken); + var outdated = await _client.GetAsync( + entity.Name(), + entity.Namespace(), + cancellationToken); + + entity.Spec.Username = "changed"; + await _client.UpdateAsync(entity, cancellationToken); + + outdated!.Status.Status = "applied"; + var updated = await _client.UpdateStatusAsync(outdated, cancellationToken); + + updated.Status.Status.Should().Be("applied"); + updated.Spec.Username.Should().Be("changed"); + updated.Metadata.ManagedFields.Should().Contain(f => + f.Manager == "kubeops-test" && f.Operation == "Apply" && f.Subresource == "status"); + } + + public override async ValueTask InitializeAsync() + { + await base.InitializeAsync(); + await _ns.InitializeAsync(); + } + + public override async ValueTask DisposeAsync() + { + await base.DisposeAsync(); + await _ns.DisposeAsync(); + _client.Dispose(); + } + + protected override void ConfigureHost(HostApplicationBuilder builder) + { + } +}