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
5 changes: 5 additions & 0 deletions docs/docs/operator/building-blocks/controllers.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,11 @@ This method is called when a resource is deleted, but should only be used for:
- Triggering non-critical cleanup tasks
- Updating external systems about the deletion

If an object is deleted and recreated under the same name, `DeletedAsync` for the old object and
`ReconcileAsync` for the new one are independent reconciliations and may run in any order or in
parallel. Do not clean up resources in `DeletedAsync` by a name derived from the entity alone — the
recreated object may already own them. Use owner references or [finalizers](./finalizer) instead.

```csharp
public async Task<ReconciliationResult<V1DemoEntity>> DeletedAsync(
V1DemoEntity entity,
Expand Down
16 changes: 11 additions & 5 deletions docs/docs/operator/configuration/queue-strategy.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,15 @@ queue-consumer hosted service. Which consumer is started depends on the configur
All scheduling state lives in the operator pod's heap.

When the same entity is scheduled multiple times before it becomes ready, the in-memory queue keeps
one entry per namespace/name key. The entry scheduled to run earliest is kept, and later enqueue calls
can update the reconciliation metadata for that scheduled entry. Scheduled entries are not removed by
the reconciler while processing an API-server event.
one entry per object, keyed by the object's UID (entities without a UID fall back to namespace/name).
The entry scheduled to run earliest is kept, and later enqueue calls can update the reconciliation
metadata for that scheduled entry. Scheduled entries are not removed by the reconciler while processing
an API-server event.

Because the key is the UID, an object that is deleted and recreated under the same name yields two
separate entries: `DeletedAsync` receives the deleted object and `ReconcileAsync` receives the new one.
An entry for a non-deleted object whose name now resolves to a different (recreated) object is skipped
when it is processed, since the new object is reconciled through its own entry.

- **Advantages**: Zero configuration. Minimal latency between watch event and reconciliation call.
- **Disadvantages**: Pending requeue timers are lost when the pod restarts. In practice this is
Expand Down Expand Up @@ -77,7 +83,7 @@ in-memory queue (see [Multiple Controllers per Entity](../building-blocks/contro
:::

Custom queues should follow the same de-duplication contract as the built-in implementation: keep at
most one pending entry per namespace/name key and preserve the earliest scheduled execution time.
most one pending entry per object UID (falling back to namespace/name when no UID is set) and preserve the earliest scheduled execution time.

`Enqueue` returns `Task<bool>`: return `true` when the entry was scheduled and `false` when it was
dropped (for example because the `cancellationToken` was already cancelled, or — for a queue that
Expand All @@ -99,7 +105,7 @@ public Task<bool> Enqueue(
return Task.FromResult(false); // dropped
}

// ... schedule the entry (de-duplicated by namespace/name) ...
// ... schedule the entry (de-duplicated by UID) ...
return Task.FromResult(true); // scheduled
}
```
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,21 @@ protected virtual async Task<ReconciliationResult<TEntity>> ReconcileSingleAsync
? entry.Entity
: await client.GetAsync<TEntity>(entry.Entity.Name(), entry.Entity.Namespace(), cancellationToken);

// The object loaded by name may be a different object than the one the entry was scheduled for, when
// the original was deleted and recreated under the same name (e.g. a pending requeue whose Deleted
// event was never observed). That object has its own queue entry, so the stale one is skipped.
if (entity is not null
&& !string.IsNullOrEmpty(entry.Entity.Uid())
&& entity.Uid() != entry.Entity.Uid())
{
logger
.LogDebug(
"""Queued entry for "{Identifier}" is stale; the object was recreated as "{Current}". Skipping.""",
entry.Entity.ToIdentifierString(),
entity.ToIdentifierString());
return ReconciliationResult<TEntity>.Success(entity);
}

if (entity is not null)
{
// The gate runs on the entity that will actually be reconciled — the freshly loaded object for
Expand Down
3 changes: 2 additions & 1 deletion src/KubeOps.Operator/Queue/TimedEntityQueue.cs
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,8 @@ public Task<bool> Enqueue(TEntity entity, ReconciliationType type, Reconciliatio
newQueueIn.TotalSeconds);
}

// schedule deleted reconciliations must not be cancelled
// schedule deleted reconciliations must not be cancelled; entries are keyed by UID, so
// this only merges events of the same object, never those of a recreated namesake
var newReconciliationType = oldEntry.ReconciliationType == ReconciliationType.Deleted
? oldEntry.ReconciliationType
: type;
Expand Down
12 changes: 9 additions & 3 deletions src/KubeOps.Operator/Queue/TimedEntityQueueExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,10 @@ namespace KubeOps.Operator.Queue;
public static class TimedEntityQueueExtensions
{
/// <summary>
/// Retrieves a unique key for the specified Kubernetes entity. The key is constructed
/// using the entity's namespace and name, if available. If the entity does not have
/// a valid name, the method returns null.
/// Retrieves a unique key for the specified Kubernetes entity. The key is the entity's UID, so that
/// a deleted object and a newly created object with the same namespace and name are never merged into
/// one queue entry. Entities without a UID (e.g. objects constructed locally) fall back to namespace
/// and name. If the entity does not have a valid name, the method returns null.
/// </summary>
/// <typeparam name="TEntity">
/// The type of the Kubernetes entity. Must implement <see cref="IKubernetesObject{V1ObjectMeta}"/>.
Expand All @@ -38,6 +39,11 @@ public static class TimedEntityQueueExtensions
return null;
}

if (!string.IsNullOrWhiteSpace(entity.Uid()))
{
return entity.Uid();
}

return string.IsNullOrWhiteSpace(entity.Namespace())
? entity.Name()
: $"{entity.Namespace()}/{entity.Name()}";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -527,6 +527,33 @@ public async Task Deleted_Entry_Uses_Entity_From_Queue_Without_Client_Lookup()
Times.Once);
}

[Trait("Area", "EntityIdentity")]
[Fact]
public async Task Stale_Entry_Is_Skipped_When_Object_Was_Recreated_With_Same_Name()
{
var queue = new ControllableQueue<V1ConfigMap>();
var reconcilerMock = new Mock<IReconciler<V1ConfigMap>>();
var clientMock = new Mock<IKubernetesClient>();
var stale = CreateEntity("uid-old");
var recreated = CreateEntity("uid-new");

await using var service = CreateService(queue, reconcilerMock, clientMock, recreated);
await service.StartAsync(TestContext.Current.CancellationToken);

queue.Push(stale, ReconciliationType.Modified, ReconciliationTriggerSource.Operator);
queue.Complete();

await Task.Delay(300, TestContext.Current.CancellationToken);
await service.StopAsync(TestContext.Current.CancellationToken);

reconcilerMock.Verify(
r => r.Reconcile(
It.IsAny<ReconciliationContext<V1ConfigMap>>(),
It.IsAny<CancellationToken>()),
Times.Never);
queue.EnqueueCallCount.Should().Be(0);
}

[Fact]
public async Task Discard_Strategy_Drops_Concurrent_Entry_For_Same_Uid()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -146,10 +146,17 @@ private void SetupResponsibility(V1OperatorIntegrationTestEntity entity, bool re
.Setup(s => s.IsResponsibleForAsync(entity, It.IsAny<CancellationToken>()))
.ReturnsAsync(responsible);

private static V1OperatorIntegrationTestEntity CreateEntity(string uid) =>
// Snapshot and current are two states of the same object, so they share the UID and differ in version.
private static V1OperatorIntegrationTestEntity CreateEntity(string resourceVersion) =>
new()
{
Metadata = new V1ObjectMeta { Name = "test-entity", NamespaceProperty = "test-namespace", Uid = uid },
Metadata = new V1ObjectMeta
{
Name = "test-entity",
NamespaceProperty = "test-namespace",
Uid = "test-uid",
ResourceVersion = resourceVersion,
},
};

private static QueueEntry<V1OperatorIntegrationTestEntity> CreateEntry(
Expand Down
110 changes: 110 additions & 0 deletions test/KubeOps.Operator.Test/Queue/TimedEntityQueue.Test.cs
Original file line number Diff line number Diff line change
Expand Up @@ -328,6 +328,109 @@ public void Dispose_Should_Complete_Without_Exception()
act.Should().NotThrow();
}

[Trait("Area", "EntityIdentity")]
[Fact]
public async Task Enqueue_Should_Not_Merge_Added_Of_Recreated_Object_Into_Pending_Deleted()
{
using var queue = new TimedEntityQueue<V1Secret>(Mock.Of<ILogger<TimedEntityQueue<V1Secret>>>());
var deleted = CreateSecret("ns", "secret", "uid-old");
var recreated = CreateSecret("ns", "secret", "uid-new");

await queue.Enqueue(
deleted,
ReconciliationType.Deleted,
ReconciliationTriggerSource.ApiServer,
TimeSpan.Zero,
retryCount: 0,
TestContext.Current.CancellationToken);
await queue.Enqueue(
recreated,
ReconciliationType.Added,
ReconciliationTriggerSource.ApiServer,
TimeSpan.Zero,
retryCount: 0,
TestContext.Current.CancellationToken);

var items = await DrainQueue(queue, TimeSpan.FromMilliseconds(500));

items.Should().HaveCount(2);
items.Should().ContainSingle(e => e.ReconciliationType == ReconciliationType.Deleted)
.Which.Entity.Uid().Should().Be("uid-old");
items.Should().ContainSingle(e => e.ReconciliationType == ReconciliationType.Added)
.Which.Entity.Uid().Should().Be("uid-new");
}

[Trait("Area", "EntityIdentity")]
[Fact]
public async Task Enqueue_Should_Not_Merge_Deleted_Retry_Of_Previous_Object_Into_Pending_Added()
{
using var queue = new TimedEntityQueue<V1Secret>(Mock.Of<ILogger<TimedEntityQueue<V1Secret>>>());
var recreated = CreateSecret("ns", "secret", "uid-new");
var deleted = CreateSecret("ns", "secret", "uid-old");

await queue.Enqueue(
recreated,
ReconciliationType.Added,
ReconciliationTriggerSource.ApiServer,
TimeSpan.Zero,
retryCount: 0,
TestContext.Current.CancellationToken);
await queue.Enqueue(
deleted,
ReconciliationType.Deleted,
ReconciliationTriggerSource.ApiServer,
TimeSpan.FromMilliseconds(100),
retryCount: 1,
TestContext.Current.CancellationToken);

var items = await DrainQueue(queue, TimeSpan.FromMilliseconds(500));

items.Should().HaveCount(2);
items.Should().ContainSingle(e => e.ReconciliationType == ReconciliationType.Added)
.Which.Entity.Uid().Should().Be("uid-new");
items.Should().ContainSingle(e => e.ReconciliationType == ReconciliationType.Deleted)
.Which.Entity.Uid().Should().Be("uid-old");
}

[Trait("Area", "EntityIdentity")]
[Fact]
public async Task Enqueue_Should_Merge_Entries_Of_Same_Uid()
{
using var queue = new TimedEntityQueue<V1Secret>(Mock.Of<ILogger<TimedEntityQueue<V1Secret>>>());

await queue.Enqueue(
CreateSecret("ns", "secret", "uid"),
ReconciliationType.Deleted,
ReconciliationTriggerSource.ApiServer,
TimeSpan.FromMilliseconds(100),
retryCount: 0,
TestContext.Current.CancellationToken);
await queue.Enqueue(
CreateSecret("ns", "secret", "uid"),
ReconciliationType.Modified,
ReconciliationTriggerSource.Operator,
TimeSpan.FromMilliseconds(100),
retryCount: 0,
TestContext.Current.CancellationToken);

queue.Count.Should().Be(1);

var items = await DrainQueue(queue, TimeSpan.FromMilliseconds(500));

items.Should().ContainSingle()
.Which.ReconciliationType.Should().Be(ReconciliationType.Deleted);
}

[Trait("Area", "EntityIdentity")]
[Fact]
public void GetKey_Should_Use_Uid_And_Fall_Back_To_Namespace_And_Name()
{
using var queue = new TimedEntityQueue<V1Secret>(Mock.Of<ILogger<TimedEntityQueue<V1Secret>>>());

queue.GetKey(CreateSecret("ns", "secret", "uid")).Should().Be("uid");
queue.GetKey(CreateSecret("ns", "secret")).Should().Be("ns/secret");
}

private static V1Secret CreateSecret(string secretNamespace, string secretName)
{
var secret = new V1Secret();
Expand All @@ -339,6 +442,13 @@ private static V1Secret CreateSecret(string secretNamespace, string secretName)
return secret;
}

private static V1Secret CreateSecret(string secretNamespace, string secretName, string uid)
{
var secret = CreateSecret(secretNamespace, secretName);
secret.Metadata.Uid = uid;
return secret;
}

private static async Task WaitUntil(Func<bool> condition, TimeSpan timeout)
{
var deadline = DateTimeOffset.UtcNow + timeout;
Expand Down
Loading