Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions docs/docs/operator/configuration/field-manager.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
24 changes: 23 additions & 1 deletion docs/docs/operator/migration.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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<TProject>` 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

Expand Down Expand Up @@ -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<TEntity>(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`.
7 changes: 5 additions & 2 deletions docs/docs/operator/troubleshooting.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
7 changes: 7 additions & 0 deletions src/KubeOps.KubernetesClient/IKubernetesClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,13 @@ Task<IEnumerable<TEntity>> UpdateAsync<TEntity>(params TEntity[] entities)
/// <summary>
/// Update the status object of a given entity on the Kubernetes API.
/// </summary>
/// <remarks>
/// The status is sent as a server-side apply to the <c>/status</c> subresource, without the
/// <c>resourceVersion</c> and with <c>force</c>. It does not fail with <c>409 Conflict</c> if the entity changed
/// in the meantime, and status fields that an earlier update set but <paramref name="entity"/> no longer
/// carries are removed. The client needs a field manager, which an operator sets; outside an operator, create
/// the client with one.
/// </remarks>
/// <typeparam name="TEntity">The type of the Kubernetes entity.</typeparam>
/// <param name="entity">The entity that contains a status object.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
Expand Down
29 changes: 25 additions & 4 deletions src/KubeOps.KubernetesClient/KubernetesClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using System.Diagnostics;
using System.Net;
using System.Runtime.CompilerServices;
using System.Text.Json.Nodes;

using k8s;
using k8s.Autorest;
Expand Down Expand Up @@ -228,22 +229,42 @@ public Task<TEntity> UpdateStatusAsync<TEntity>(TEntity entity, CancellationToke
ThrowIfDisposed();

var metadata = GetMetadata<TEntity>();

// 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<TEntity>(
entity,
{ } ns => ApiClient.CustomObjects.PatchNamespacedCustomObjectStatusAsync<TEntity>(
patch,
metadata.Group ?? string.Empty,
metadata.Version,
ns,
metadata.PluralName,
entity.Name(),
force: true,
cancellationToken: cancellationToken),
_ => ApiClient.CustomObjects.ReplaceClusterCustomObjectStatusAsync<TEntity>(
entity,
_ => ApiClient.CustomObjects.PatchClusterCustomObjectStatusAsync<TEntity>(
patch,
metadata.Group ?? string.Empty,
metadata.Version,
metadata.PluralName,
entity.Name(),
force: true,
cancellationToken: cancellationToken),
};
}
Expand Down
5 changes: 5 additions & 0 deletions src/KubeOps.KubernetesClient/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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"));
}

Expand Down
Original file line number Diff line number Diff line change
@@ -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<V1StatusTestEntity.EntitySpec, V1StatusTestEntity.EntityStatus>
{
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<V1StatusTestEntity.EntitySpec, V1StatusTestEntity.EntityStatus>;
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

using FluentAssertions;

using k8s;
using k8s.Models;

using KubeOps.Abstractions.Reconciliation;
Expand All @@ -20,7 +21,8 @@ namespace KubeOps.Operator.Test.Controller;
public sealed class EntityControllerIntegrationTest : IntegrationTestBase
{
private readonly InvocationCounter<V1OperatorIntegrationTestEntity> _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]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

using FluentAssertions;

using k8s;

using KubeOps.Abstractions.Reconciliation;
using KubeOps.Abstractions.Reconciliation.Controller;
using KubeOps.Abstractions.Reconciliation.Queue;
Expand All @@ -21,7 +23,8 @@ namespace KubeOps.Operator.Test.Controller;
public sealed class ReplaceEntityRequeueIntegrationTest : IntegrationTestBase
{
private readonly InvocationCounter<V1OperatorIntegrationTestEntity> _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]
Expand Down
Original file line number Diff line number Diff line change
@@ -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<V1OperatorIntegrationTestEntity>(
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)
{
}
}