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
3 changes: 3 additions & 0 deletions docs/docs/operator/cli.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,9 @@ This command:
- Generates the necessary CRDs
- Installs them into your current Kubernetes context

The CLI writes with the field manager `kubeops-cli`, so the CRDs it creates or replaces are recorded under that
name in `metadata.managedFields`.

:::tip[Solution files]
Instead of a `.csproj` file, you can pass a `.sln` or `.slnx` solution file. The CLI will compile all projects in the solution and search them for custom resources.
:::
Expand Down
111 changes: 111 additions & 0 deletions docs/docs/operator/configuration/field-manager.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
---
title: Field Manager
description: The name under which the operator's writes are recorded in managedFields
sidebar_position: 12
---

# Field Manager

The Kubernetes API server records, for every object, which client last wrote which fields. These entries
are kept in `metadata.managedFields`, and each entry names a _field manager_. A client sets the field
manager with the `fieldManager` query parameter of a write request. Without the parameter, the API server
derives the manager from the user agent, so every client built on the official C# client shows up as
`kubernetes-csharp`.

KubeOps sends every write (`POST`, `PUT` and `PATCH`) with an explicit field manager. It defaults to the
operator name and is configured with `WithFieldManager`:

```csharp
builder.Services
.AddKubernetesOperator(settings => settings
.WithName("my-operator")
.WithFieldManager("my-operator")); // optional, defaults to the operator name
```

The writes of the operator then appear under that name:

```yaml
metadata:
managedFields:
- manager: my-operator
operation: Update
apiVersion: demo.kubeops.dev/v1
fieldsType: FieldsV1
fieldsV1:
f:metadata:
f:finalizers: {}
```

This tells the writes of the operator apart from those of other clients, for example when tooling looks
for clients that still write through a deprecated API version of a CRD.

## Covered Writes

The operator registers the default `IKubernetes` with a `FieldManagerHandler`. `IKubernetesClient`, the
leader elector and all internal services write through that instance, so the field manager covers:

- attaching and detaching finalizers
- Kubernetes events
- CRD installation by the [CRD Installer](./crd-installer)
- webhook configurations and the CRD `caBundle`
- the leader election lease
- every create, update, status update and patch your controllers send through `IKubernetesClient` or
its `ApiClient`

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`:

```csharp
await client.PatchAsync(
entity,
new V1Patch(applyConfiguration, V1Patch.PatchType.ApplyPatch),
fieldManager: "my-operator-apply",
force: true);
```

## Valid Field Managers

The API server accepts field managers of at most 128 bytes (UTF-8) that contain only printable characters.
`WithFieldManager`, the `OperatorSettingsBuilder.FieldManager` property and `OperatorSettings.FieldManager`
reject other values with an `ArgumentException`.

Without an explicit field manager, the operator name is used as it is. If the name is not a valid field
manager, `OperatorSettingsBuilder.Build()` throws an `InvalidOperationException`; set a field manager with
`WithFieldManager` in that case.

## Registering an Own `IKubernetes`

An `IKubernetes` that you register yourself replaces the default one, including its handler. Add the handler
yourself to keep the field manager:

```csharp
builder.Services.AddSingleton<IKubernetes>(services => new Kubernetes(
services.GetRequiredService<KubernetesClientConfiguration>(),
new FieldManagerHandler(services.GetRequiredService<OperatorSettings>().FieldManager)));
```

Pass a new `FieldManagerHandler` to every `Kubernetes` instance; like every `DelegatingHandler`, it must not
be shared between clients.

## Outside the Operator

CLIs, migration jobs and other tools that use `KubernetesClient` directly pass the field manager to the
constructor:

```csharp
using var client = new KubernetesClient(KubernetesClientConfiguration.BuildDefaultConfig(), "my-migration");
```

The KubeOps CLI writes as `kubeops-cli`, e.g. when `kubeops install` creates or replaces CRDs.

## Upgrading

Only the name in `managedFields` changes. Writes after the upgrade are recorded under the operator name
instead of `kubernetes-csharp`. Existing entries keep their old manager until the fields they own are
written again.

Update operations never conflict on field ownership, and server-side apply already requires an explicit
field manager, so the new name does not change which write wins a conflict.
1 change: 1 addition & 0 deletions docs/docs/operator/configuration/index.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,4 @@ Each `With*` method corresponds to one of the options described on the pages of
| [Registration Validation](./registration-validation) | Startup validation of the operator's DI registrations |
| [Customizing Resource Generation](./generation-customization) | Replacing or extending the CRD, webhook, and event factories |
| [CRD Installer](./crd-installer) | Installing CRDs from the operator during development |
| [Field Manager](./field-manager) | The name under which the operator's writes are recorded in `managedFields` |
10 changes: 10 additions & 0 deletions docs/docs/operator/migration.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -352,3 +352,13 @@ JSON Patch API is now part of `KubeOps.Abstractions` and no longer requires prev
`Get`, `List`, `Save`, `Create`, `Update`, `UpdateStatus`, `Patch` and `Delete` are gone. They blocked a
thread on the API call. Use the `...Async` variants, which also accept a `CancellationToken`.
`GetCurrentNamespace` stays, because it does not call the API, and so does `Watch`.

### New in v14 (non-breaking)

- **Explicit field manager**: every write of the operator carries a `fieldManager`, which defaults to the
operator name and is set with `WithFieldManager(...)`. Writes are recorded in `metadata.managedFields` under
that name instead of `kubernetes-csharp`; existing entries keep their old manager until their fields are
written again. If you register an own `IKubernetes`, add the `FieldManagerHandler` yourself. An operator
name that is not a valid field manager (over 128 bytes or with non-printable characters) needs an explicit
`WithFieldManager(...)`. The KubeOps CLI writes as `kubeops-cli`. See
[Field Manager](./configuration/field-manager).
91 changes: 91 additions & 0 deletions src/KubeOps.Abstractions/Builder/FieldManagerName.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
// 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.Buffers;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Text;

namespace KubeOps.Abstractions.Builder;

/// <summary>
/// The rules the Kubernetes API server applies to the <c>fieldManager</c> of a write request.
/// </summary>
public static class FieldManagerName
{
/// <summary>
/// The maximum length of a field manager, in bytes of its UTF-8 representation.
/// </summary>
public const int MaxLength = 128;

/// <summary>
/// Throws if <paramref name="fieldManager"/> is not accepted by the Kubernetes API server:
/// it must not be empty, must not exceed <see cref="MaxLength"/> bytes and
/// may only contain printable characters.
/// </summary>
/// <param name="fieldManager">The field manager to validate.</param>
/// <param name="paramName">The name of the validated parameter.</param>
/// <exception cref="ArgumentNullException"><paramref name="fieldManager"/> is <c>null</c>.</exception>
/// <exception cref="ArgumentException"><paramref name="fieldManager"/> is not a valid field manager.</exception>
public static void ThrowIfInvalid(
string fieldManager,
[CallerArgumentExpression(nameof(fieldManager))] string? paramName = null)
{
ArgumentNullException.ThrowIfNull(fieldManager, paramName);

if (GetError(fieldManager) is { } error)
{
throw new ArgumentException(error, paramName);
}
}

/// <summary>
/// Determines why the API server would reject <paramref name="fieldManager"/>.
/// </summary>
/// <param name="fieldManager">The field manager to validate.</param>
/// <returns>The reason, or <c>null</c> if <paramref name="fieldManager"/> is valid.</returns>
internal static string? GetError(string? fieldManager)
{
if (string.IsNullOrEmpty(fieldManager))
{
return "The field manager must not be empty.";
}

if (Encoding.UTF8.GetByteCount(fieldManager) > MaxLength)
{
return $"The field manager must not be longer than {MaxLength} bytes.";
}

return IsPrintable(fieldManager) ? null : "The field manager may only contain printable characters.";
}

// Mirrors Go's unicode.IsPrint, which the API server uses: letters, marks, numbers, punctuation,
// symbols and the ASCII space. Invalid UTF-16 (a lone surrogate) is rejected as well.
private static bool IsPrintable(ReadOnlySpan<char> value)
{
while (!value.IsEmpty)
{
if (Rune.DecodeFromUtf16(value, out var rune, out var consumed) != OperationStatus.Done ||
!IsPrintable(rune))
{
return false;
}

value = value[consumed..];
}

return true;
}

private static bool IsPrintable(Rune rune) =>
rune.Value == ' ' ||
Rune.GetUnicodeCategory(rune) is not (UnicodeCategory.Control
or UnicodeCategory.Format
or UnicodeCategory.Surrogate
or UnicodeCategory.PrivateUse
or UnicodeCategory.OtherNotAssigned
or UnicodeCategory.SpaceSeparator
or UnicodeCategory.LineSeparator
or UnicodeCategory.ParagraphSeparator);
}
30 changes: 30 additions & 0 deletions src/KubeOps.Abstractions/Builder/OperatorSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
// 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.Diagnostics.CodeAnalysis;

using ZiggyCreatures.Caching.Fusion;

namespace KubeOps.Abstractions.Builder;
Expand All @@ -18,6 +20,34 @@ public sealed record OperatorSettings
/// </summary>
public required string Name { get; init; }

/// <summary>
/// The field manager the operator sends with every write (<c>POST</c>, <c>PUT</c> and <c>PATCH</c>) to the
/// Kubernetes API server. The API server records the written fields under this name in
/// <c>metadata.managedFields</c>, so the operator's writes can be told apart from those of other clients.
/// A request that already carries a <c>fieldManager</c> (e.g. a server-side apply) keeps it.
/// </summary>
/// <value>
/// The configured field manager, or <see cref="Name"/> if none is set (<c>null</c>).
/// </value>
/// <exception cref="ArgumentException">
/// The value is empty, longer than <see cref="FieldManagerName.MaxLength"/> bytes or contains
/// non-printable characters.
/// </exception>
[AllowNull]
public string FieldManager
{
get => field ?? Name;
init
{
if (value is not null)
{
FieldManagerName.ThrowIfInvalid(value);
}

field = value;
}
}

/// <summary>
/// <para>
/// Controls the namespace which is watched by the operator.
Expand Down
70 changes: 53 additions & 17 deletions src/KubeOps.Abstractions/Builder/OperatorSettingsBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,28 @@ public sealed partial class OperatorSettingsBuilder
.Replace(DefaultOperatorName, NonCharReplacement)
.ToLowerInvariant();

/// <summary>
/// The field manager under which the operator's writes are recorded in <c>metadata.managedFields</c>.
/// Defaults to <c>null</c>, which uses <see cref="Name"/>.
/// </summary>
/// <exception cref="ArgumentException">
/// The value is empty, longer than <see cref="FieldManagerName.MaxLength"/> bytes or contains
/// non-printable characters.
/// </exception>
public string? FieldManager
{
get;
set
{
if (value is not null)
{
FieldManagerName.ThrowIfInvalid(value);
}

field = value;
}
}

/// <summary>
/// Controls the namespace which is watched by the operator.
/// If this field is <c>null</c>, all namespaces are watched for CRD instances.
Expand Down Expand Up @@ -132,24 +154,38 @@ public sealed partial class OperatorSettingsBuilder
/// Produces an immutable <see cref="OperatorSettings"/> record from the current configuration.
/// </summary>
/// <returns>A fully initialised <see cref="OperatorSettings"/> record.</returns>
public OperatorSettings Build() => new()
/// <exception cref="InvalidOperationException">
/// No <see cref="FieldManager"/> is set and <see cref="Name"/> is not a valid field manager.
/// </exception>
public OperatorSettings Build()
{
Name = Name,
Namespace = Namespace,
LeaderElectionType = LeaderElectionType,
QueueStrategy = QueueStrategy,
WatchStrategy = WatchStrategy,
LeaderElectionLeaseDuration = LeaderElectionLeaseDuration,
LeaderElectionRenewDeadline = LeaderElectionRenewDeadline,
LeaderElectionRetryPeriod = LeaderElectionRetryPeriod,
ConfigureResourceWatcherEntityCache = ConfigureResourceWatcherEntityCache,
AutoAttachFinalizers = AutoAttachFinalizers,
AutoDetachFinalizers = AutoDetachFinalizers,
ReconcileStrategy = ReconcileStrategy,
ParallelReconciliation = ParallelReconciliation.Build(),
EnableMetrics = EnableMetrics,
ValidateRegistrations = ValidateRegistrations,
};
if (FieldManager is null && FieldManagerName.GetError(Name) is { } error)
{
throw new InvalidOperationException(
$"The operator name '{Name}' is used as field manager, but is not a valid one: {error} " +
"Set a valid field manager with WithFieldManager.");
}

return new()
{
Name = Name,
FieldManager = FieldManager,
Namespace = Namespace,
LeaderElectionType = LeaderElectionType,
QueueStrategy = QueueStrategy,
WatchStrategy = WatchStrategy,
LeaderElectionLeaseDuration = LeaderElectionLeaseDuration,
LeaderElectionRenewDeadline = LeaderElectionRenewDeadline,
LeaderElectionRetryPeriod = LeaderElectionRetryPeriod,
ConfigureResourceWatcherEntityCache = ConfigureResourceWatcherEntityCache,
AutoAttachFinalizers = AutoAttachFinalizers,
AutoDetachFinalizers = AutoDetachFinalizers,
ReconcileStrategy = ReconcileStrategy,
ParallelReconciliation = ParallelReconciliation.Build(),
EnableMetrics = EnableMetrics,
ValidateRegistrations = ValidateRegistrations,
};
}

[GeneratedRegex(@"(\W|_)", RegexOptions.CultureInvariant)]
private static partial Regex OperatorNameRegex();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,23 @@ public static OperatorSettingsBuilder WithName(this OperatorSettingsBuilder buil
return builder;
}

/// <summary>
/// Sets the field manager under which the operator's writes are recorded in <c>metadata.managedFields</c>.
/// Defaults to the operator name.
/// </summary>
/// <param name="builder">The builder to configure.</param>
/// <param name="fieldManager">
/// The field manager: not empty, at most <see cref="FieldManagerName.MaxLength"/> bytes and only
/// printable characters.
/// </param>
/// <returns>The same <paramref name="builder"/> instance for chaining.</returns>
/// <exception cref="ArgumentException"><paramref name="fieldManager"/> is not a valid field manager.</exception>
public static OperatorSettingsBuilder WithFieldManager(this OperatorSettingsBuilder builder, string fieldManager)
{
builder.FieldManager = fieldManager;
return builder;
}

/// <summary>Sets the namespace to watch. Pass <c>null</c> to watch all namespaces (the default).</summary>
/// <param name="builder">The builder to configure.</param>
/// <param name="ns">The namespace, or <c>null</c> for all namespaces.</param>
Expand Down
Loading
Loading