Skip to content
Closed
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
20 changes: 18 additions & 2 deletions docs/docs/operator/building-blocks/controllers.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -126,13 +126,29 @@ public async Task<ReconciliationResult<V1DemoEntity>> ReconcileAsync(
}

// Update status to reflect current state
entity.Status.LastReconciled = DateTime.UtcNow;
await client.UpdateStatusAsync(entity, cancellationToken);
entity = await client.PatchStatusAsync(
entity,
e => e.Status.LastReconciled = DateTime.UtcNow,
cancellationToken);

return ReconciliationResult<V1DemoEntity>.Success(entity);
}
```

### Writing the Status

`PatchStatusAsync(entity, change)` applies `change` to the entity and writes only the status fields it changed,
as a JSON merge patch to the `/status` subresource. The patch carries no `resourceVersion`, so it does not fail
with `409 Conflict` when the entity changed in the meantime, and status fields you did not change stay as
others wrote them. `PatchStatusAsync(from, to)` does the same for the changes between two entities.

Removed fields are sent as `null`. A changed array, e.g. a list of conditions, is sent as a whole and replaces
the conditions that others added in the meantime; use a server-side apply patch with
`PatchStatusAsync<TEntity>(patch, name, namespace, fieldManager, force)` when several writers share a list.

`UpdateStatusAsync(entity)` replaces the whole status. Use it when the write must fail with `409 Conflict` if
the entity changed since you read it.

### DeletedAsync

:::warning[Important]
Expand Down
6 changes: 6 additions & 0 deletions docs/docs/operator/migration.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -405,3 +405,9 @@ builder.AddKubeOps("operator", "../MyOperator")
.RunWithKubernetes(k8s)
.PublishAsKubernetesOperator(k8s);
```

### New in v15 (non-breaking)

- **Status patch**: `PatchStatusAsync(entity, change)` and `PatchStatusAsync(from, to)` write only the changed
status fields as a JSON merge patch, without a `409 Conflict` on an outdated `resourceVersion`. See
[Writing the Status](./building-blocks/controllers#writing-the-status).
3 changes: 3 additions & 0 deletions docs/docs/operator/troubleshooting.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,9 @@ entity = await client.UpdateStatusAsync(entity, cancellationToken); // use the r
[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.

For the status, `PatchStatusAsync` avoids the conflict: it patches only the changed status fields and
carries no `resourceVersion`. See [Writing the Status](./building-blocks/controllers#writing-the-status).

## Entity is stuck in "Terminating"

**Symptom:** A resource has a `DeletionTimestamp` but is never deleted.
Expand Down
107 changes: 106 additions & 1 deletion src/KubeOps.KubernetesClient/IKubernetesClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

using KubeOps.Abstractions.Entities;
using KubeOps.KubernetesClient.Selectors;
using KubeOps.Transpiler;

namespace KubeOps.KubernetesClient;

Expand Down Expand Up @@ -249,15 +250,106 @@ Task<IEnumerable<TEntity>> UpdateAsync<TEntity>(params TEntity[] entities)
}

/// <summary>
/// Update the status object of a given entity on the Kubernetes API.
/// Update (replace) the status object of a given entity on the Kubernetes API.
/// </summary>
/// <remarks>
/// The replace carries the <c>resourceVersion</c> of <paramref name="entity"/> and fails with
/// <c>409 Conflict</c> if the entity changed in the meantime. To write only the changed status fields
/// without that check, use <see cref="PatchStatusAsync{TEntity}(TEntity,Action{TEntity},CancellationToken)"/>.
/// </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>
/// <returns>The entity with the updated status.</returns>
Task<TEntity> UpdateStatusAsync<TEntity>(TEntity entity, CancellationToken cancellationToken = default)
where TEntity : IKubernetesObject<V1ObjectMeta>;

/// <summary>
/// Apply <paramref name="change"/> to <paramref name="entity"/> and patch the status fields it changed on the
/// Kubernetes API.
/// </summary>
/// <remarks>
/// The changes are sent as a JSON merge patch to the <c>/status</c> subresource. It carries only the changed
/// fields (removed fields as <c>null</c>, changed arrays as a whole) and no <c>resourceVersion</c>, so it does
/// not fail with <c>409 Conflict</c> if the entity changed in the meantime. A changed array replaces the
/// array on the API, including entries that others added.
/// </remarks>
/// <typeparam name="TEntity">The type of the Kubernetes entity.</typeparam>
/// <param name="entity">The entity, e.g. as it was passed to the reconciler. It is changed in place.</param>
/// <param name="change">The change of the status, e.g. <c>e =&gt; e.Status.Phase = "Ready"</c>.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <returns>The patched entity, or <paramref name="entity"/> if the status did not change.</returns>
Task<TEntity> PatchStatusAsync<TEntity>(
TEntity entity,
Action<TEntity> change,
CancellationToken cancellationToken = default)
where TEntity : IKubernetesObject<V1ObjectMeta>
{
var original = entity.ToNode();
change(entity);
var patch = StatusPatch.CreateMergePatch(original, entity.ToNode());
return PatchStatusIfChangedAsync(patch, entity, cancellationToken);
}

/// <summary>
/// Patch the status of a given entity on the Kubernetes API with the changes between the status of
/// <paramref name="from"/> and the status of <paramref name="to"/>.
/// </summary>
/// <remarks>
/// Sent like <see cref="PatchStatusAsync{TEntity}(TEntity,Action{TEntity},CancellationToken)"/>.
/// </remarks>
/// <typeparam name="TEntity">The type of the Kubernetes entity.</typeparam>
/// <param name="from">The entity with the original status.</param>
/// <param name="to">The entity with the desired status.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <returns>The patched entity, or <paramref name="from"/> if the status did not change.</returns>
Task<TEntity> PatchStatusAsync<TEntity>(
TEntity from,
TEntity to,
CancellationToken cancellationToken = default)
where TEntity : IKubernetesObject<V1ObjectMeta> =>
PatchStatusIfChangedAsync(StatusPatch.CreateMergePatch(from.ToNode(), to.ToNode()), from, cancellationToken);

/// <summary>
/// Patch the status of a given entity on the Kubernetes API by name and namespace using a
/// <see cref="V1Patch"/> object, sent to the <c>/status</c> subresource.
/// </summary>
/// <typeparam name="TEntity">The type of the Kubernetes entity.</typeparam>
/// <param name="patch">
/// The <see cref="V1Patch"/> representing the changes to apply, e.g. a JSON merge patch or a server-side apply
/// patch. Only changes to the status are applied.
/// </param>
/// <param name="name">The name of the entity to patch.</param>
/// <param name="namespace">The namespace of the entity to patch (if applicable).</param>
/// <param name="fieldManager">
/// The field manager to write with. Required for a server-side apply patch outside an operator.
/// </param>
/// <param name="force">
/// Force a server-side apply patch, taking ownership of conflicting fields. Only valid for server-side apply.
/// </param>
/// <param name="dryRun">When set (e.g., "All"), the patch is validated but not persisted to storage.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <returns>The patched entity.</returns>
Task<TEntity> PatchStatusAsync<TEntity>(
V1Patch patch,
string name,
string? @namespace = null,
string? fieldManager = null,
bool? force = null,
string? dryRun = null,
CancellationToken cancellationToken = default)
where TEntity : IKubernetesObject<V1ObjectMeta> =>
StatusPatch.SendAsync<TEntity>(
ApiClient,
Entities.ToEntityMetadata<TEntity>().Metadata,
patch,
name,
@namespace,
fieldManager,
force,
dryRun,
cancellationToken);

/// <summary>
/// Patch a given entity on the Kubernetes API by calculating the diff between the current entity and the provided entity.
/// This method fetches the current entity from the API, computes the patch, and applies it.
Expand Down Expand Up @@ -559,4 +651,17 @@ Watcher<TEntity> Watch<TEntity>(
bool? allowWatchBookmarks = null,
CancellationToken cancellationToken = default)
where TEntity : IKubernetesObject<V1ObjectMeta>;

private Task<TEntity> PatchStatusIfChangedAsync<TEntity>(
V1Patch? patch,
TEntity unchanged,
CancellationToken cancellationToken)
where TEntity : IKubernetesObject<V1ObjectMeta> =>
patch is null
? Task.FromResult(unchanged)
: PatchStatusAsync<TEntity>(
patch,
unchanged.Name(),
unchanged.Namespace(),
cancellationToken: cancellationToken);
}
25 changes: 25 additions & 0 deletions src/KubeOps.KubernetesClient/KubernetesClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,31 @@ public Task<TEntity> UpdateStatusAsync<TEntity>(TEntity entity, CancellationToke
};
}

/// <inheritdoc />
public async Task<TEntity> PatchStatusAsync<TEntity>(
V1Patch patch,
string name,
string? @namespace = null,
string? fieldManager = null,
bool? force = null,
string? dryRun = null,
CancellationToken cancellationToken = default)
where TEntity : IKubernetesObject<V1ObjectMeta>
{
ThrowIfDisposed();

return await StatusPatch.SendAsync<TEntity>(
ApiClient,
GetMetadata<TEntity>(),
patch,
name,
@namespace,
fieldManager,
force,
dryRun,
cancellationToken);
}

/// <inheritdoc />
public async Task<TEntity> PatchAsync<TEntity>(
V1Patch patch,
Expand Down
8 changes: 5 additions & 3 deletions src/KubeOps.KubernetesClient/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -152,15 +152,17 @@ if (existingPod != null)
### Update Resource Status

```csharp
// Update the status of a custom resource
// Patch only the changed status fields, without a 409 Conflict on an outdated resourceVersion
var existingCrd = await client.GetAsync<V1MyCrd>("my-instance", "default");
if (existingCrd != null)
{
existingCrd.Status.Message = "Processing completed";
var updatedCrd = await client.UpdateStatusAsync(existingCrd);
var patchedCrd = await client.PatchStatusAsync(existingCrd, crd => crd.Status.Message = "Processing completed");
}
```

`UpdateStatusAsync` replaces the whole status instead and fails with `409 Conflict` on an outdated
`resourceVersion`. See [Writing the Status](https://dotnet.github.io/dotnet-operator-sdk/docs/operator/building-blocks/controllers#writing-the-status).

### Watch Resources

```csharp
Expand Down
109 changes: 109 additions & 0 deletions src/KubeOps.KubernetesClient/StatusPatch.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
// 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 k8s;
using k8s.Models;

using KubeOps.Abstractions.Entities;

namespace KubeOps.KubernetesClient;

/// <summary>
/// Builds and sends patches of the <c>/status</c> subresource of an entity.
/// </summary>
internal static class StatusPatch
{
private const string Status = "status";

/// <summary>
/// Creates a merge patch that turns the status of <paramref name="from"/> into the status of
/// <paramref name="to"/>. It carries only the changed fields: removed fields are set to <c>null</c>,
/// and changed arrays are sent as a whole.
/// </summary>
/// <param name="from">The JSON of the entity with the original status.</param>
/// <param name="to">The JSON of the entity with the desired status.</param>
/// <returns>The merge patch, or <see langword="null"/> if the status did not change.</returns>
public static V1Patch? CreateMergePatch(JsonNode? from, JsonNode? to) =>
TryCreateDiff(from?[Status], to?[Status], out var status)
? new V1Patch(new JsonObject { [Status] = status }.ToJsonString(), V1Patch.PatchType.MergePatch)
: null;

/// <summary>
/// Sends <paramref name="patch"/> to the <c>/status</c> subresource of the entity.
/// </summary>
/// <typeparam name="TEntity">The type of the entity.</typeparam>
/// <param name="apiClient">The client to send the patch with.</param>
/// <param name="metadata">The metadata of <typeparamref name="TEntity"/>.</param>
/// <param name="patch">The patch.</param>
/// <param name="name">The name of the entity.</param>
/// <param name="namespace">The namespace of the entity, or <see langword="null"/> if cluster scoped.</param>
/// <param name="fieldManager">The field manager to write with.</param>
/// <param name="force">Whether to force a server-side apply patch.</param>
/// <param name="dryRun">The dry run mode.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <returns>The patched entity.</returns>
public static Task<TEntity> SendAsync<TEntity>(
IKubernetes apiClient,
EntityMetadata metadata,
V1Patch patch,
string name,
string? @namespace,
string? fieldManager,
bool? force,
string? dryRun,
CancellationToken cancellationToken) =>
@namespace switch
{
not null => apiClient.CustomObjects.PatchNamespacedCustomObjectStatusAsync<TEntity>(
patch,
metadata.Group ?? string.Empty,
metadata.Version,
@namespace,
metadata.PluralName,
name,
dryRun: dryRun,
fieldManager: fieldManager,
force: force,
cancellationToken: cancellationToken),
_ => apiClient.CustomObjects.PatchClusterCustomObjectStatusAsync<TEntity>(
patch,
metadata.Group ?? string.Empty,
metadata.Version,
metadata.PluralName,
name,
dryRun: dryRun,
fieldManager: fieldManager,
force: force,
cancellationToken: cancellationToken),
};

private static bool TryCreateDiff(JsonNode? from, JsonNode? to, out JsonNode? diff)
{
if (from is not JsonObject fromObject || to is not JsonObject toObject)
{
var changed = !JsonNode.DeepEquals(from, to);
diff = changed ? to?.DeepClone() : null;
return changed;
}

var diffObject = new JsonObject();
foreach (var (key, _) in fromObject.Where(property => !toObject.ContainsKey(property.Key)))
{
diffObject[key] = null;
}

foreach (var (key, toValue) in toObject)
{
if (TryCreateDiff(fromObject[key], toValue, out var valueDiff))
{
diffObject[key] = valueDiff;
}
}

diff = diffObject;
return diffObject.Count > 0;
}
}
Loading