diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index 6441364993..26c3322fbd 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -23,7 +23,7 @@ jobs:
httpclient-tests:
strategy:
matrix:
- httpclient: [ 'vertx', 'jdk', 'jetty' ]
+ httpclient: [ 'vertx-5', 'jdk', 'jetty' ]
uses: ./.github/workflows/integration-tests.yml
with:
java-version: 25
diff --git a/.github/workflows/integration-tests.yml b/.github/workflows/integration-tests.yml
index 3f1353efea..d29d1f1d21 100644
--- a/.github/workflows/integration-tests.yml
+++ b/.github/workflows/integration-tests.yml
@@ -12,7 +12,7 @@ on:
http-client:
type: string
required: false
- default: 'vertx'
+ default: 'vertx-5'
experimental:
type: boolean
required: false
diff --git a/bootstrapper-maven-plugin/pom.xml b/bootstrapper-maven-plugin/pom.xml
index 90407d169b..b0d36eaf70 100644
--- a/bootstrapper-maven-plugin/pom.xml
+++ b/bootstrapper-maven-plugin/pom.xml
@@ -22,7 +22,7 @@
io.javaoperatorsdkjava-operator-sdk
- 5.6.5-SNAPSHOT
+ 999-SNAPSHOTbootstrapper
diff --git a/caffeine-bounded-cache-support/pom.xml b/caffeine-bounded-cache-support/pom.xml
index 0ccc983162..be70ab9a2e 100644
--- a/caffeine-bounded-cache-support/pom.xml
+++ b/caffeine-bounded-cache-support/pom.xml
@@ -21,7 +21,7 @@
io.javaoperatorsdkjava-operator-sdk
- 5.6.5-SNAPSHOT
+ 999-SNAPSHOTcaffeine-bounded-cache-support
diff --git a/docs/content/en/blog/releases/v5-7-release.md b/docs/content/en/blog/releases/v5-7-release.md
new file mode 100644
index 0000000000..5b92e8bacb
--- /dev/null
+++ b/docs/content/en/blog/releases/v5-7-release.md
@@ -0,0 +1,270 @@
+---
+title: Version 5.7 Released!
+date: 2026-11-19
+author: >-
+ [Attila Mészáros](https://github.com/csviri)
+---
+
+We're pleased to announce the release of Java Operator SDK v5.7.0! The headline features of this
+minor version are **virtual thread support**, an upgrade to the **Fabric8 Kubernetes Client 8.0**
+(with the **Vert.x 5 HTTP client** as the new default), **desired state aspects** for adding common
+metadata to all managed resources, and a much more capable **event recorder**. Because of the client
+upgrade, which moves to Jackson 3, this release contains **breaking changes** for operators that use
+Jackson types directly — see the migration notes.
+
+## Key Features
+
+### Virtual threads
+
+Reconciliation is mostly about blocking: talking to the Kubernetes API server or to external systems.
+Virtual threads make such blocking calls much cheaper than platform threads, and the framework can now
+be switched over to them with a single flag:
+
+```java
+Operator operator = new Operator(override -> override.withUseVirtualThreads(true));
+```
+
+The same can be set with the `josdk.use-virtual-threads` configuration property. When enabled,
+reconciliations, dependent resource workflows and the framework's internal housekeeping (starting the
+informers, for example) all run on virtual threads. So do the polls of the polling event sources and
+the retried and rescheduled reconciliations; the Kubernetes client the framework creates also
+dispatches informer and watch events on virtual threads.
+
+Enabling virtual threads does **not** remove the concurrency limits. `withConcurrentReconciliationThreads`
+and `withConcurrentWorkflowExecutorThreads` still cap the parallelism exactly as before, only the
+threads backing those limits change. Since virtual threads are cheap, these limits can usually be
+raised significantly compared to what is reasonable with platform threads.
+
+A few things to keep in mind:
+
+- Virtual threads are only supported on **Java 25 or later**, the first LTS release where a virtual
+ thread no longer pins its carrier thread while inside a `synchronized` block
+ ([JEP 491](https://openjdk.org/jeps/491), delivered in Java 24). Without that, pinning can starve
+ the carrier pool and even deadlock an operator on startup. This is checked at runtime: on an older
+ JVM a warning is logged and platform threads are used, so the same configuration works on any Java
+ version the operator runs on.
+- Virtual threads are daemon threads, so they don't keep the JVM running. If nothing else does, call
+ the new `Operator.keepAlive()` after starting the operator (see below).
+- An executor you provide yourself is always used as is, the flag has no effect on it. There is one
+ catch: overriding `useVirtualThreads`, or `withConcurrentRetryAndRescheduleThreads`, of a
+ configuration that provides its own retry and reschedule executor replaces that executor with the
+ default one, so provide it again with `withRetryAndRescheduleExecutorService(...)` in that case.
+
+#### Keeping the JVM alive
+
+Until now the JVM was kept running as a side effect of the non-daemon threads of the operator's thread
+pools. With virtual threads that is no longer the case, so `Operator.keepAlive()` starts a non-daemon
+thread that keeps the JVM running until the operator is stopped:
+
+```java
+public static void main(String[] args) {
+ Operator operator = new Operator(override -> override.withUseVirtualThreads(true));
+ operator.register(new MyReconciler());
+ operator.installShutdownHook();
+ operator.start();
+ operator.keepAlive();
+}
+```
+
+#### Polling event sources have their own executors
+
+To make this work, the polling event sources and the internal `TimerEventSource` no longer use a
+`java.util.Timer`. Each polling event source now polls on a scheduled executor of its own, so a slow
+poll of one event source never delays the polls of the others, and retried and rescheduled
+reconciliations run on a separate executor that a slow poll can never delay. A
+`PerResourcePollingEventSource` with many registered resources can be given an executor with more
+threads:
+
+```java
+var config =
+ new PerResourcePollingConfigurationBuilder<>(this::fetchResources, Duration.ofSeconds(5))
+ .withExecutorService(Executors.newScheduledThreadPool(4))
+ .build();
+```
+
+An executor provided that way is yours to shut down. See the
+[configuration](/docs/documentation/operations/configuration/#virtual-threads) and
+[eventing](/docs/documentation/eventing/#threading-of-the-polling-event-sources) documentation for
+details, and the migration guide for the (small) behavioral differences.
+
+### Fabric8 Kubernetes Client 8.0 and the Vert.x 5 HTTP client
+
+JOSDK 5.7 is built on version 8.0.0 of the
+[Fabric8 Kubernetes Client](https://github.com/fabric8io/kubernetes-client). The most visible change
+of the client is the move from Jackson 2 to **Jackson 3**: the packages changed from
+`com.fasterxml.jackson` to `tools.jackson` (the annotations being the exception). If your operator
+uses Jackson types directly, you will need to update your imports and dependencies.
+
+In line with the client's own default, the `operator-framework` artifact now brings the **Vert.x 5**
+based HTTP client instead of the JDK one. If you don't declare an HTTP client of your own there is
+nothing to do. To keep the JDK client, or to use another implementation, exclude the default and add the
+one you want:
+
+```xml
+
+ io.javaoperatorsdk
+ operator-framework
+
+
+ io.fabric8
+ kubernetes-httpclient-vertx-5
+
+
+
+
+ io.fabric8
+ kubernetes-httpclient-jdk
+ 8.0.0
+
+```
+
+### Desired state aspects
+
+Operators often need to mark every resource they manage in a uniform way, for example with an
+`app.kubernetes.io/managed-by` label, so that these resources can be easily identified, selected or
+garbage-collected later on. Instead of repeating that logic in every `desired()` implementation, a
+`DesiredStateAspect` can now be registered once, at the operator level, and is applied to the desired
+state of every Kubernetes dependent resource the operator manages:
+
+```java
+Operator operator = new Operator(overrider -> overrider
+ .withDesiredStateAspects(List.of(
+ (desired, dependentResource, context) -> desired.getMetadata().getLabels()
+ .put("app.kubernetes.io/managed-by", "my-operator"))));
+```
+
+Aspects are applied in registration order, right after the desired state is computed and before it is
+matched against the actual resource. The metadata an aspect adds is therefore part of the desired
+state proper: if it is removed from the actual resource, or the aspect itself changes, the secondary
+resources are updated accordingly on the next reconciliation. Aspects are called at most once per
+dependent resource and reconciliation, are not called for external (non-Kubernetes) dependent
+resources, and need to be thread-safe.
+
+Thanks to [Martin Stefanko](https://github.com/xstefank) for this contribution!
+
+### A more capable event recorder
+
+The [event recorder](/docs/documentation/kubernetes-events) introduced in 5.6 got several additions,
+and has a documentation page of its own now.
+
+**Events about any object.** An event does not have to be about the primary resource. A controller
+reconciling a child resource can, for example, record on the parent, so that `kubectl describe parent`
+shows what happened to its children. Bind the recorder to the other object:
+
+```java
+var parent = context.getSecondaryResource(Parent.class).orElseThrow();
+context.eventRecorder(parent).warn("ChildFailed", "could not reconcile child " + name);
+```
+
+Aggregation works per object: two children recording the same reason and message on one parent count
+as repeats of a single event on the parent, while different messages stay separate events.
+
+**Fail on error.** Recording an event is best effort by default: a failure to write it is logged and
+swallowed. Where an event that is not recorded must not go unnoticed, the default recorder can be
+configured to propagate the failure, so that the reconciliation fails and is retried like any other:
+
+```java
+KubernetesClient client = new KubernetesClientBuilder().build();
+Operator operator = new Operator(override -> override
+ .withKubernetesClient(client)
+ .withEventRecorder(DefaultEventRecorder.builder(new DefaultEventSink(client))
+ .failOnError(true)
+ .build()));
+```
+
+**Configurable aggregation, owner references and naming.** `DefaultEventRecorder` can now be built with
+an `EventKeyStrategy`, controlling what counts as the same event, an `EventNamingStrategy`,
+controlling how events are named, and optionally sets an `ownerReference` to the object an event is
+about. `EventRecord.Builder#key(...)` and `ownedByRegarding(...)` override these per event.
+
+**Correctness fixes.** Aggregating onto an existing event now also updates its type, reason and
+action, so a `Warning` repeated under the name of a `Normal` event is no longer reported as the
+`Normal` one. Event names longer than the Kubernetes limit are shortened with a hash instead of being
+plainly truncated, so distinct names sharing a long prefix no longer merge into one event. Events
+about cluster scoped resources now carry what the API server requires to accept them in `kube-system`
+(the API server only accepts such events in `default` and `kube-system`, so the documentation no
+longer suggests the namespace the operator runs in).
+
+Thanks to [Antonio Fernandez Alhambra](https://github.com/afalhambra-hivemq) for the event recorder
+contributions!
+
+### Removing the namespace index of informers
+
+Informers keep an index from namespace to the cached resources. JOSDK never reads that index, so for
+informers caching a large number of resources it can be removed to save an entry per cached resource,
+which matters most together with a custom item store that caches only a reduced form of each resource:
+
+```java
+@ControllerConfiguration(informer = @Informer(withoutNamespaceIndex = true))
+public class MyReconciler implements Reconciler { }
+```
+
+The option is also available on `InformerEventSourceConfiguration.Builder` and `InformerConfiguration.Builder`,
+and as the `josdk.controller..informer.without-namespace-index` property. Note that it takes
+part in the informer pool identity: event sources watching the same resource type, where only one
+removes the index, don't share an informer.
+
+Thanks to [Antonio Fernandez Alhambra](https://github.com/afalhambra-hivemq) for this contribution too!
+
+## Bug Fixes
+
+- **`comparableResourceVersions` is kept when a dependent resource's informer configuration is
+ copied**, it used to be lost.
+- **The `version.properties` resource was renamed to `operator-sdk-version.properties`** to avoid
+ collisions with resources of the same name on the classpath.
+
+## Migration Notes
+
+### Fabric8 Kubernetes Client 8.0 / Jackson 3
+
+This is the only source-incompatible change for most operators. Besides the package change
+(`com.fasterxml.jackson` to `tools.jackson`), `JsonProcessingException` was replaced by the unchecked
+`JacksonException`, some `JsonNode` methods were renamed (`fields()` to `properties()`, `asText()` to
+`asString()`), and `ObjectMapper` instances are created using builders. Also, calls to
+`withShardSelector(null)` no longer compile because of an additional overload, cast the argument:
+`withShardSelector((String) null)`.
+
+### Default HTTP client is now Vert.x 5
+
+If your operator already replaced the default HTTP client by excluding `kubernetes-httpclient-jdk`,
+update the exclusion to `kubernetes-httpclient-vertx-5`, otherwise it ends up on the classpath next to
+your implementation. This is especially important with the Vert.x 4 based client, since Vert.x 4 and
+Vert.x 5 cannot be used together.
+
+### Polling and timer event sources
+
+An executor provided to a `PerResourcePollingConfigurationBuilder` is no longer shut down by the event
+source, and `PerResourcePollingConfiguration.executorService()` returns `null` when none was provided.
+`PollingEventSource(Class, PollingConfiguration)` and `TimerEventSource(String, boolean)` are
+deprecated; use the constructors that take an `EventSourceContext` and an executor supplier respectively.
+
+### Low level event recorder API
+
+The low level event recorder API changed to support events about any object: a custom
+`EventRecorder` now implements `record(HasMetadata regarding, EventRecord event, Context> context)`
+and a subclass of `DefaultEventRecorder` overrides `toEvent(HasMetadata, EventRecord, Context>)`.
+Reconcilers that only use `context.eventRecorder()` are not affected.
+
+See the [migration guide](/docs/migration/v5-7-migration) for all the details.
+
+## Getting Started
+
+```xml
+
+ io.javaoperatorsdk
+ operator-framework
+ 5.7.0
+
+```
+
+## All Changes
+
+See the [comparison view](https://github.com/operator-framework/java-operator-sdk/compare/v5.6.4...v5.7.0)
+for the full list of changes.
+
+## Feedback
+
+Please report issues or suggest improvements on our
+[GitHub repository](https://github.com/operator-framework/java-operator-sdk/issues).
+
+Happy operator building! 🚀
diff --git a/docs/content/en/docs/documentation/_index.md b/docs/content/en/docs/documentation/_index.md
index d639b8b9f9..a5368978da 100644
--- a/docs/content/en/docs/documentation/_index.md
+++ b/docs/content/en/docs/documentation/_index.md
@@ -25,6 +25,7 @@ This section contains detailed documentation for all Java Operator SDK features
- **[Eventing](eventing/)** - Understanding the event-driven model
- **[Event filters](event-filters/)** - Filtering events and the default filter behavior
- **[Accessing Resources in Caches](working-with-es-caches/)** - How to access resources in caches
+- **[Recording Kubernetes Events](kubernetes-events/)** - Surfacing controller actions in `kubectl describe`
- **[Operations](operations/)** - Helm chart, metrics, logging, configurations, leader election
- **[Other Features](features/)** - Additional capabilities and integrations
diff --git a/docs/content/en/docs/documentation/dependent-resource-and-workflows/dependent-resources.md b/docs/content/en/docs/documentation/dependent-resource-and-workflows/dependent-resources.md
index 538c52c00c..3ac1e88e71 100644
--- a/docs/content/en/docs/documentation/dependent-resource-and-workflows/dependent-resources.md
+++ b/docs/content/en/docs/documentation/dependent-resource-and-workflows/dependent-resources.md
@@ -531,6 +531,34 @@ samples [here](https://github.com/java-operator-sdk/java-operator-sdk/tree/main/
in [related integration test](https://github.com/operator-framework/java-operator-sdk/blob/main/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/orderedmanageddependent/ConfigMapDependentResource2.java)
.
+### Adding Common Metadata to All Managed Resources (Desired State Aspects)
+
+Operators often need to mark every resource they manage in a uniform way, for example with a
+`app.kubernetes.io/managed-by` label, so that these resources can easily be identified, selected or
+garbage-collected later on. Instead of repeating that logic in every `desired()` implementation, a
+`DesiredStateAspect` can be registered once, at the operator level, and is then applied to the
+desired state of every Kubernetes dependent resource managed by the operator:
+
+```java
+Operator operator = new Operator(overrider -> overrider
+ .withDesiredStateAspects(List.of(
+ (desired, dependentResource, context) -> desired.getMetadata().getLabels()
+ .put("app.kubernetes.io/managed-by", "my-operator"))));
+```
+
+Aspects are applied, in registration order, right after the desired state has been computed and
+before the desired state is matched against the actual resource, created or updated. As a
+consequence, the metadata added by an aspect is part of the desired state proper: if it is removed
+from the actual resource, or if the aspect itself changes, the associated secondary resources are
+updated accordingly on the next reconciliation.
+
+Since the desired state is computed at most once per reconciliation and cached in the `Context`,
+aspects are called at most once per dependent resource and reconciliation. They are only called for
+dependent resources whose desired state is a `HasMetadata`, meaning that external (non-Kubernetes)
+dependent resources are left untouched. Implementations are expected to modify the provided desired
+state in place and need to be thread-safe as they can be called concurrently for different primary
+resources.
+
## "Read-only" Dependent Resources vs. Event Source
See Integration test for a read-only
diff --git a/docs/content/en/docs/documentation/eventing.md b/docs/content/en/docs/documentation/eventing.md
index e7aea6b065..03d4dcab86 100644
--- a/docs/content/en/docs/documentation/eventing.md
+++ b/docs/content/en/docs/documentation/eventing.md
@@ -222,6 +222,37 @@ is similar to `PerResourcePollingEventSource` except that, contrary to that even
doesn't poll a specific API separately per resource, but periodically and independently of
actually observed primary resources.
+#### Threading of the polling event sources
+
+Each polling event source polls on a scheduled executor of its own, so a slow poll of one event
+source never delays the polls of the others. Unless you provide one, the event source creates a
+single daemon thread executor when it is started and shuts it down when it is stopped. With a single
+thread the polls of a source run one after the other. A `PollingEventSource` runs a single periodic
+task, so more threads would not help it. A `PerResourcePollingEventSource` however polls each
+registered resource on its own, so if it has many registered resources or fetches slowly, it can be
+given an executor with more threads using the `withExecutorService` method of its configuration
+builder:
+
+```java
+var config =
+ new PerResourcePollingConfigurationBuilder<>(this::fetchResources, Duration.ofSeconds(5))
+ .withExecutorService(Executors.newScheduledThreadPool(4))
+ .build();
+```
+
+An executor provided that way is not managed by the operator: it is your responsibility to shut it
+down. It is only ever used as is, the virtual threads flag has no effect on it. You can also share
+it between multiple event sources deliberately.
+
+With virtual threads enabled, see [virtual threads](../operations/configuration/#virtual-threads),
+the executor the event source creates runs the polls on virtual threads, only keeping one platform
+thread to do the timing. The number of polls running at the same time is then not limited.
+
+Retried and rescheduled reconciliations are triggered on a separate executor, so a slow poll can
+never delay them. It is sized with `withConcurrentRetryAndRescheduleThreads` (2 threads by
+default); few threads are needed there since triggering a reconciliation only enqueues an event
+for one of the reconciliation threads to pick up.
+
#### Inbound event sources
[SimpleInboundEventSource](https://github.com/operator-framework/java-operator-sdk/blob/main/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/inbound/SimpleInboundEventSource.java)
@@ -348,6 +379,30 @@ See
also [CaffeineBoundedItemStores](https://github.com/operator-framework/java-operator-sdk/blob/main/caffeine-bounded-cache-support/src/main/java/io/javaoperatorsdk/operator/processing/event/source/cache/CaffeineBoundedItemStores.java)
for more details.
+### Removing the Namespace Index
+
+Informers keep an index from namespace to the resources cached for it. JOSDK never reads that index,
+only the ones registered explicitly through `IndexerResourceCache.addIndexers(..)`, so it can be
+removed to save an entry per cached resource:
+
+```java
+@ControllerConfiguration(informer = @Informer(withoutNamespaceIndex = true))
+public class MyReconciler implements Reconciler { }
+```
+
+The same option is available on `InformerEventSourceConfiguration.Builder` for event sources, and on
+`InformerConfiguration.Builder`.
+
+This matters most for informers that cache a large number of resources, and in particular together
+with a custom [item store](#bounded-caches-for-informers) that keeps only a reduced form of each
+resource: the index is keyed independently of what the store does with the resource itself, so
+shrinking what is cached does not shrink the index.
+
+Note that this takes part in the informer pool identity described below: an event source that
+removes the index does not share an informer with one that keeps it. If two event sources watch the
+same resource type and only one of them sets the option, they end up with two informers, and two
+caches of that resource type, which can cost far more memory than the index ever did.
+
### Sharing Informers Between Controllers (Informer Pool)
{{% alert title="Experimental" color="warning" %}}
@@ -374,7 +429,10 @@ Two event sources share an informer when their effective informer configuration
- the resource type (or the group/version/kind for generic resources),
- the watched namespace,
- the label, field and shard selectors,
-- the configured [item store](#bounded-caches-for-informers).
+- the configured [item store](#bounded-caches-for-informers),
+- whether the [namespace index is removed](#removing-the-namespace-index): it cannot be present for
+ one event source and absent for another on one shared informer, so event sources that disagree on
+ it are backed by separate informers.
The `informerListLimit` is intentionally *not* part of this identity: if two otherwise-equivalent
event sources request a different list limit, the existing informer is reused (a warning is logged
diff --git a/docs/content/en/docs/documentation/kubernetes-events.md b/docs/content/en/docs/documentation/kubernetes-events.md
new file mode 100644
index 0000000000..23010a588f
--- /dev/null
+++ b/docs/content/en/docs/documentation/kubernetes-events.md
@@ -0,0 +1,93 @@
+---
+title: Recording Kubernetes Events
+weight: 51
+---
+
+A controller can record Kubernetes events, so that what it does shows up where users already look
+for it: `kubectl describe` on the resource the event is about. Events are informational and best
+effort by design, Kubernetes keeps them for a limited time and treats them as supplemental data, so
+they complement the status of a resource rather than replace it.
+
+## Recording from a reconciliation
+
+Inside a reconciliation the recorder is available from the `Context`, bound to the primary resource:
+
+```java
+@Override
+public UpdateControl reconcile(MyResource resource, Context context) {
+ context.eventRecorder().normal("Reconciled", "resource reconciled");
+ context.eventRecorder().warn("SomethingIsOff", "this is a warning about the resource");
+ return UpdateControl.noUpdate();
+}
+```
+
+For more control, build an `EventRecord`, which also carries an optional action, reporting
+component, labels and annotations:
+
+```java
+context.eventRecorder().record(EventRecord.builder()
+ .type(EventType.WARNING)
+ .reason("DeploymentFailed")
+ .message("could not scale the deployment")
+ .action("Scaling")
+ .build());
+```
+
+## Recording about another object
+
+An event does not have to be about the primary resource. A controller reconciling a child resource
+can, for example, record on the parent, so that `kubectl describe parent` shows what happened to its
+children. Bind the recorder to the other object instead:
+
+```java
+var parent = context.getSecondaryResource(Parent.class).orElseThrow();
+context.eventRecorder(parent).warn("ChildFailed", "could not reconcile child " + name);
+```
+
+The event references the given object as its involved object and lives in that object's namespace,
+or, for a cluster scoped object, in the namespace configured for such events (see below). It is
+still attributed to the controller recording it. Aggregation works per object: two children
+recording the same reason and message on one parent count as repeats of a single event on the
+parent, while different messages stay separate events.
+
+## What an event carries
+
+The recorder fills in everything derivable from the controller and the object: the involved object
+reference, the reporting controller (the controller name, or the reporting component set on the
+record), the reporting instance (the leader election identity when configured, otherwise the host
+name, which in a pod is the pod name), the timestamps and the count.
+
+Repeats are aggregated, not duplicated. Events are named deterministically, after the object they
+are about plus a hash of everything that identifies the event, so recording the same event again
+resolves to the event already recorded and counts the occurrence on it. That is what makes `kubectl
+describe` report a repeating event once, as `(x12 over 3m)`, instead of listing copies. Use
+`EventRecord.Builder#key(...)` to control what counts as the same event, or configure the default
+through `DefaultEventRecorder.builder(sink).keyStrategy(...)`, see the javadoc of
+`EventKeyStrategy` and `EventNamingStrategy`.
+
+Events about cluster scoped objects live in the namespace configured through
+`withClusterScopedEventNamespace(...)` or the `josdk.events.cluster-scoped-namespace` property,
+`default` unless configured otherwise. The API server only accepts `default` and `kube-system`.
+
+## Failure handling
+
+Recording is best effort by default: a failure to write the event is logged as a warning and
+swallowed, and never fails the reconciliation. To make such a failure fail the reconciliation
+instead, so that it goes through the usual error handling and retries, configure the default
+recorder with `failOnError(true)`, see the
+[Events section of the configuration page](operations/configuration.md#events) for the snippet.
+
+## Custom recorders
+
+To assemble events differently or send them somewhere else entirely, plug in an `EventRecorder` of
+your own for the whole operator with `withEventRecorder(...)`. A custom recorder is shared by all
+controllers, so it must be stateless and thread safe; it implements a single method,
+`record(HasMetadata regarding, EventRecord event, Context> context)`, and gets the bound views for
+free. Extend `DefaultEventRecorder` and override `toEvent(...)` to change how events are assembled,
+or implement an `EventSink` to change where the assembled events go.
+
+## Permissions
+
+Recording needs `get`, `create` and `patch` on `events` in the core API group in every namespace
+events are recorded in, see the
+[Events section of the configuration page](operations/configuration.md#events).
diff --git a/docs/content/en/docs/documentation/operations/configuration.md b/docs/content/en/docs/documentation/operations/configuration.md
index cee9f65efa..6c78efc4d7 100644
--- a/docs/content/en/docs/documentation/operations/configuration.md
+++ b/docs/content/en/docs/documentation/operations/configuration.md
@@ -23,6 +23,60 @@ Operator operator = new Operator( override -> override
.withLeaderElectionConfiguration(new LeaderElectionConfiguration("bar", "barNS")));
```
+### Virtual Threads
+
+Reconciliation is mostly about blocking: talking to the Kubernetes API server or to external
+systems. Virtual threads make such blocking calls much cheaper than platform threads, and the
+framework can be switched over to them with a single flag:
+
+```java
+Operator operator = new Operator(override -> override.withUseVirtualThreads(true));
+```
+
+When enabled, reconciliations, dependent resource workflows and the framework's internal
+housekeeping (starting the informers, for example) all run on virtual threads.
+
+Enabling virtual threads does **not** remove the concurrency limits, parallelism is configured
+exactly as before: `withConcurrentReconciliationThreads(int)` still caps how many reconciliations
+run at the same time and `withConcurrentWorkflowExecutorThreads(int)` how many dependent resources
+of a workflow are processed concurrently. Only the threads backing those limits change. Since
+virtual threads are cheap, these limits can usually be raised significantly compared to what is
+reasonable with platform threads.
+
+Things to keep in mind:
+
+- Virtual threads are only supported on **Java 25 or later**. Before Java 25 a virtual thread pins
+ its carrier thread while it is inside a `synchronized` block, which can starve the carrier pool
+ and even deadlock the operator on startup. [JEP 491](https://openjdk.org/jeps/491), delivered in
+ Java 25, removed that pinning. This is checked at runtime: on an older JVM, including the ones
+ where virtual threads exist (Java 21 to 24), a warning is logged and platform threads are used
+ instead, so the same configuration works on any Java version the operator runs on.
+- The scheduled tasks (the polls of the polling event sources, which each create an executor of
+ their own unless one is provided, and the retried and rescheduled reconciliations) run on virtual
+ threads too. The JDK has no scheduled executor backed by virtual threads, so the default ones keep
+ a single platform thread for the timing only and run each task they fire on a virtual thread. The
+ number of those tasks running at the same time is not limited, so
+ `withConcurrentRetryAndRescheduleThreads(int)` only applies to platform threads.
+- Virtual threads are always daemon threads, so unlike the threads of the platform thread pools they
+ don't keep the JVM running: if the `main` method of your application returns after starting the
+ operator and nothing else keeps the JVM alive, call `Operator.keepAlive()`, see
+ [Keeping the JVM Alive](#keeping-the-jvm-alive).
+- A custom `ExecutorService` provided through `withExecutorService(...)` or
+ `withWorkflowExecutorService(...)` is always used as is, the flag has no effect on it. The same
+ goes for `withRetryAndRescheduleExecutorService(...)`. Note however that overriding the flag, or
+ `withConcurrentRetryAndRescheduleThreads(int)`, of a configuration that provides its own retry and
+ reschedule executor replaces that executor with the default one, so provide it again with
+ `withRetryAndRescheduleExecutorService(...)` in that case.
+- The Kubernetes client the framework creates when none is provided also switches its internal
+ task executor (used to dispatch informer events to their handlers and to deliver watch events)
+ to virtual threads. A client you provide through `withKubernetesClient(...)` is used as is: to
+ get the same behavior, configure it yourself, e.g. with
+ `new KubernetesClientBuilder().withTaskExecutor(Executors.newVirtualThreadPerTaskExecutor())`
+ (the client doesn't shut down an executor passed that way, use `withTaskExecutorSupplier(...)`
+ if it should be shut down when the client is closed).
+ Either way, the blocking calls your reconciler makes through the client work well on virtual
+ threads without any client-side change.
+
## Reconciler-Level Configuration
While reconcilers are typically configured using the `@ControllerConfiguration` annotation, you can also override configuration at runtime when registering the reconciler with the operator. You can either:
@@ -101,6 +155,24 @@ See also
the [integration test](https://github.com/operator-framework/java-operator-sdk/tree/main/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/changenamespace)
for this feature.
+## Keeping the JVM Alive
+
+The operator normally keeps the JVM running through the non-daemon threads of its thread pools. If
+nothing else does, for example because all the threads of the operator are daemon threads as it is
+the case with virtual threads, the JVM exits as soon as the `main` method returns after starting
+the operator. Call `Operator.keepAlive()` to have a non-daemon thread keep the JVM running until the
+operator is stopped:
+
+```java
+public static void main(String[] args) {
+ Operator operator = new Operator();
+ operator.register(new MyReconciler());
+ operator.installShutdownHook();
+ operator.start();
+ operator.keepAlive();
+}
+```
+
## DependentResource-level configuration
It is possible to define custom annotations to configure custom `DependentResource` implementations. In order to provide
@@ -267,6 +339,7 @@ All operator-level keys are prefixed with `josdk.`.
|---|---|---|
| `josdk.check-crd` | `Boolean` | Validate CRDs against local model on startup |
| `josdk.close-client-on-stop` | `Boolean` | Close the Kubernetes client when the operator stops |
+| `josdk.use-virtual-threads` | `Boolean` | Run the framework's concurrent work on virtual threads (only supported on Java 25+, platform threads are used on older versions) |
| `josdk.use-ssa-to-patch-primary-resource` | `Boolean` | Use Server-Side Apply to patch the primary resource |
| `josdk.clone-secondary-resources-when-getting-from-cache` | `Boolean` | Clone secondary resources on cache reads |
@@ -283,6 +356,12 @@ All operator-level keys are prefixed with `josdk.`.
|---|---|---|
| `josdk.workflow.executor-threads` | `Integer` | Thread pool size for workflow execution |
+#### Retry and Reschedule
+
+| Key | Type | Description |
+|---|---|---|
+| `josdk.retry-and-reschedule.concurrent-threads` | `Integer` | Thread pool size for triggering retried and rescheduled reconciliations |
+
#### Informer
| Key | Type | Description |
@@ -298,17 +377,36 @@ All operator-level keys are prefixed with `josdk.`.
#### Events
+See [Recording Kubernetes Events](../kubernetes-events.md) for how events are recorded. The key
+below configures where events about cluster scoped resources go.
+
| Key | Type | Description |
|---|---|---|
-| `josdk.events.cluster-scoped-namespace` | `String` | Namespace to record events about cluster scoped resources in (defaults to `default`) |
+| `josdk.events.cluster-scoped-namespace` | `String` | Namespace to record events about cluster scoped resources in (defaults to `default`); the API server only accepts `default` and `kube-system` |
Recording events requires the operator's service account to be allowed `get`, `create` and `patch` on
`events` in the core (`""`) API group. All three are used: an event that does not exist yet is
created, and an event that does is a repeat of one already recorded, which is patched to count the
new occurrence instead of being recorded a second time. The
[generic Helm chart](helm-chart.md) grants all three. If you write your own RBAC and a permission is
-missing, recording fails silently as far as reconciliation is concerned: the failure is swallowed so
-that it cannot break a reconciliation, and only shows up as a warning in the operator log.
+missing, recording fails silently as far as reconciliation is concerned by default: the failure is
+swallowed so that it cannot break a reconciliation, and only shows up as a warning in the operator
+log. Kubernetes treats events as best effort, supplemental data, so this is usually what you want.
+Where an event that is not recorded must not go unnoticed, configure a recorder that propagates the
+failure to the reconciler instead, so that the reconciliation fails and is retried like any other
+failed one:
+
+```java
+KubernetesClient client = new KubernetesClientBuilder().build();
+Operator operator = new Operator(override -> override
+ .withKubernetesClient(client)
+ .withEventRecorder(DefaultEventRecorder.builder(new DefaultEventSink(client))
+ .failOnError(true)
+ .build()));
+```
+
+Every failure propagates then, transient ones included, such as the conflict two replicas run into
+when they count the same occurrence of an event at the same time.
Note that events live in a namespace of their own choosing, which is the namespace of the object
they are about, and for cluster scoped objects the namespace configured above. A namespaced `Role`
@@ -316,6 +414,11 @@ therefore has to grant the permission in every namespace events are recorded in
`default`, or whatever `josdk.events.cluster-scoped-namespace` is set to, if the operator reconciles
cluster scoped resources. A `ClusterRole` covers all of them at once.
+The API server only accepts events about cluster scoped objects in the `default` and `kube-system`
+namespaces, so those are the only values `josdk.events.cluster-scoped-namespace` can usefully be set
+to. In particular, the namespace the operator itself runs in is rejected, and the event dropped with
+a warning in the operator log (or, with `failOnError(true)`, the reconciliation failed).
+
#### Leader Election
Leader election is activated when at least one `josdk.leader-election.*` key is present.
@@ -385,6 +488,7 @@ josdk.controller.mycontroller.namespaces=team-a,team-b
| `josdk.controller..informer.shard-selector` | `String` | Shard selector for the primary resource informer (alias for `shard-selector`) |
| `josdk.controller..informer.list-limit` | `Long` | Page size for paginated informer list requests; omit for no pagination |
| `josdk.controller..informer.comparable-resource-versions` | `Boolean` | Whether the resource versions of the primary resource can be treated as integers and thus compared |
+| `josdk.controller..informer.without-namespace-index` | `Boolean` | Removes the namespace index the informer maintains; defaults to `false`. See [Removing the Namespace Index](../eventing#removing-the-namespace-index) |
#### Retry
diff --git a/docs/content/en/docs/migration/v5-7-migration.md b/docs/content/en/docs/migration/v5-7-migration.md
new file mode 100644
index 0000000000..faaa8af841
--- /dev/null
+++ b/docs/content/en/docs/migration/v5-7-migration.md
@@ -0,0 +1,129 @@
+---
+title: Migrating from v5.6 to v5.7
+description: Migrating from v5.6 to v5.7
+---
+
+## Fabric8 Kubernetes Client upgraded to v8.0.0
+
+v5.7 uses version 8.0.0 of the
+[Fabric8 Kubernetes Client](https://github.com/fabric8io/kubernetes-client). Please consult the
+client's own release notes and migration guide for the complete list of changes. The ones that are
+most likely to affect operators built with JOSDK are described below.
+
+### Jackson 3
+
+The client moved from Jackson 2 to Jackson 3. The packages changed from `com.fasterxml.jackson` to
+`tools.jackson` (the annotations from `jackson-annotations` are the exception and remain in
+`com.fasterxml.jackson.annotation`). If your operator uses Jackson types directly, for example
+`JsonNode` obtained from the client's `KubernetesSerialization`, update the imports and the
+dependencies accordingly:
+
+```java
+// before
+import com.fasterxml.jackson.databind.JsonNode;
+
+// after
+import tools.jackson.databind.JsonNode;
+```
+
+Other notable Jackson 3 differences:
+
+- `JsonProcessingException` was replaced by `JacksonException`, which is unchecked.
+- `JsonNode.fields()` was replaced by `properties()`, `fieldNames()` by `propertyNames()` and
+ `asText()` by `asString()`.
+- `ObjectMapper` instances are created using builders, for example `YAMLMapper.builder().build()`.
+
+### Ambiguous `withShardSelector(null)`
+
+`Filterable` now has an additional `withShardSelector(ShardSelector)` overload next to
+`withShardSelector(String)`. Calls passing a bare `null` no longer compile, cast the argument:
+
+```java
+client.pods().withShardSelector((String) null);
+```
+
+## Default HTTP client is now Vert.x 5
+
+The `operator-framework` artifact now brings the Vert.x 5 based HTTP client of the Fabric8 client
+(`kubernetes-httpclient-vertx-5`), which is also the default of the Fabric8 client itself, instead of
+the JDK one (`kubernetes-httpclient-jdk`). If your operator doesn't declare an HTTP client
+implementation of its own there is nothing to do, it gets the new default. To keep using the JDK
+client, or to use another implementation, exclude the default from the `operator-framework`
+dependency and add the one you want:
+
+```xml
+
+ io.javaoperatorsdk
+ operator-framework
+
+
+ io.fabric8
+ kubernetes-httpclient-vertx-5
+
+
+
+
+ io.fabric8
+ kubernetes-httpclient-jdk
+ 8.0.0
+
+```
+
+The implementations provided as part of the Fabric8 client all follow the
+`kubernetes-httpclient-` pattern for their artifact identifier.
+
+If your operator already replaced the default HTTP client, update the exclusion: excluding
+`kubernetes-httpclient-jdk` no longer has any effect and `kubernetes-httpclient-vertx-5` would end up
+on the classpath next to your implementation. This is especially important if you use the Vert.x 4
+based client (`kubernetes-httpclient-vertx`), since Vert.x 4 and Vert.x 5 cannot be used together.
+If you want to keep the Vert.x 4 based client, use it in place of `kubernetes-httpclient-jdk` in the
+snippet above.
+
+## Executors of the polling and timer event sources
+
+The polling event sources and the internal `TimerEventSource` no longer use a `java.util.Timer`, and
+`PerResourcePollingEventSource` no longer creates its executor when its configuration is built. They
+run on scheduled executors, see [virtual threads](../documentation/operations/configuration/#virtual-threads)
+and [Threading of the polling event sources](../documentation/eventing/#threading-of-the-polling-event-sources).
+This is transparent unless your operator provides an executor to a polling event source, or relies
+on one of the following:
+
+- A `ScheduledExecutorService` provided with `withExecutorService(...)` to a
+ `PerResourcePollingConfigurationBuilder` was shut down with `shutdownNow()` when the event source
+ was stopped. It is not anymore: **an executor you provide is yours to shut down**, like it is for
+ `PollingConfigurationBuilder`. If you relied on the event source for this, shut it down yourself
+ after stopping the operator, otherwise its threads can keep the JVM from exiting if they are not
+ daemon threads.
+- `PerResourcePollingConfiguration.executorService()` returns `null` when no executor was provided,
+ it used to be a `ScheduledThreadPoolExecutor` with a single non-daemon thread created by the
+ configuration. The event source now creates a single daemon thread executor, or one running on
+ virtual threads if `useVirtualThreads` is enabled, when it starts, shuts it down when it stops, and
+ creates a new one if it is started again. `PerResourcePollingConfiguration.DEFAULT_EXECUTOR_THREAD_NUMBER`
+ is deprecated, it isn't used anymore.
+- Each polling event source has an executor of its own: they don't share threads, and the number of
+ threads of a source is not configurable other than by providing an executor.
+- `new PollingEventSource<>(Class, PollingConfiguration)` is deprecated. Use the constructor that
+ takes the `EventSourceContext` as well, `new PollingEventSource<>(Class, EventSourceContext,
+ PollingConfiguration)`, otherwise the event source cannot know about the `useVirtualThreads`
+ setting and polls on a platform thread.
+- `TimerEventSource(String, boolean)` is deprecated, use the constructor that also takes an
+ executor supplier, `null` to have the event source create an executor of its own.
+- `ExecutorServiceManager.scheduledExecutorService()` is deprecated. The framework doesn't use it
+ anymore, it creates the executor on first use, and shuts it down when the manager is stopped.
+
+## Event recorder: events about any object
+
+The event recorder can now record events about objects other than the primary resource, with
+`context.eventRecorder(otherObject)`, see
+[Recording Kubernetes Events](../documentation/kubernetes-events.md). Reconcilers that only use
+`context.eventRecorder()` are not affected. The low level API, which is experimental, changed to
+make this possible:
+
+- A custom `EventRecorder` implements
+ `record(HasMetadata regarding, EventRecord event, Context> context)` instead of
+ `record(EventRecord, Context>)` and `forContext(Context>)`. Those two are now default methods
+ that delegate to the new one, as is the new `forResource(HasMetadata, Context>)`.
+- A subclass of `DefaultEventRecorder` overrides or calls
+ `toEvent(HasMetadata regarding, EventRecord record, Context> context)` instead of
+ `toEvent(Context>, EventRecord)`. An override of the old signature without `@Override` still
+ compiles but is no longer called.
diff --git a/micrometer-support/pom.xml b/micrometer-support/pom.xml
index 650a24074c..29dcf1f9f5 100644
--- a/micrometer-support/pom.xml
+++ b/micrometer-support/pom.xml
@@ -21,7 +21,7 @@
io.javaoperatorsdkjava-operator-sdk
- 5.6.5-SNAPSHOT
+ 999-SNAPSHOTmicrometer-support
@@ -64,7 +64,7 @@
io.fabric8
- kubernetes-httpclient-vertx
+ kubernetes-httpclient-${fabric8-httpclient-impl.name}test
diff --git a/migration/pom.xml b/migration/pom.xml
index 785f489728..cf5143c925 100644
--- a/migration/pom.xml
+++ b/migration/pom.xml
@@ -21,7 +21,7 @@
io.javaoperatorsdkjava-operator-sdk
- 5.6.5-SNAPSHOT
+ 999-SNAPSHOTmigration
diff --git a/operator-framework-bom/pom.xml b/operator-framework-bom/pom.xml
index 712cfa769a..7ce5b2530b 100644
--- a/operator-framework-bom/pom.xml
+++ b/operator-framework-bom/pom.xml
@@ -21,7 +21,7 @@
io.javaoperatorsdkoperator-framework-bom
- 5.6.5-SNAPSHOT
+ 999-SNAPSHOTpomOperator SDK - Bill of MaterialsJava SDK for implementing Kubernetes operators
diff --git a/operator-framework-core/pom.xml b/operator-framework-core/pom.xml
index 7cf71de625..755536add7 100644
--- a/operator-framework-core/pom.xml
+++ b/operator-framework-core/pom.xml
@@ -21,7 +21,7 @@
io.javaoperatorsdkjava-operator-sdk
- 5.6.5-SNAPSHOT
+ 999-SNAPSHOT../pom.xml
@@ -46,7 +46,7 @@
io.fabric8
- kubernetes-httpclient-okhttp
+ kubernetes-httpclient-vertx-5
@@ -54,6 +54,11 @@
org.slf4jslf4j-api
+
+ io.fabric8
+ kubernetes-httpclient-${fabric8-httpclient-impl.name}
+ test
+ org.apache.logging.log4jlog4j-slf4j2-impl
@@ -128,7 +133,7 @@
${git-commit-id-maven-plugin.version}true
- ${project.build.outputDirectory}/version.properties
+ ${project.build.outputDirectory}/operator-sdk-version.properties^git.build.time$^git.commit.id.(abbrev|full)$
@@ -149,7 +154,7 @@
org.codehaus.mojotemplating-maven-plugin
- 3.2.0
+ 3.1.1filtering-java-templates
diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/ExecutorUtilsInternal.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/ExecutorUtilsInternal.java
new file mode 100644
index 0000000000..e9ebdb6673
--- /dev/null
+++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/ExecutorUtilsInternal.java
@@ -0,0 +1,77 @@
+/*
+ * Copyright Java Operator SDK Authors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.javaoperatorsdk.operator;
+
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ScheduledThreadPoolExecutor;
+import java.util.concurrent.ThreadFactory;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicLong;
+
+public class ExecutorUtilsInternal {
+
+ private static final long SCHEDULED_THREAD_KEEP_ALIVE_SECONDS = 60;
+
+ // prevent instantiation of util class
+ private ExecutorUtilsInternal() {}
+
+ /**
+ * Creates a {@link ThreadFactory} producing daemon threads named after the specified prefix.
+ * Daemon threads don't keep the JVM alive if the {@link Operator} is never stopped, and naming
+ * them makes the pool they belong to identifiable in thread dumps.
+ *
+ * @param namePrefix the prefix the created threads are named after
+ * @return a {@link ThreadFactory} creating named daemon threads
+ */
+ public static ThreadFactory daemonThreadFactory(String namePrefix) {
+ final var defaultThreadFactory = Executors.defaultThreadFactory();
+ final var counter = new AtomicLong();
+ return runnable -> {
+ final var thread = defaultThreadFactory.newThread(runnable);
+ thread.setName(namePrefix + "-" + counter.incrementAndGet());
+ thread.setDaemon(true);
+ return thread;
+ };
+ }
+
+ /**
+ * Creates the kind of {@link ScheduledExecutorService} the operator runs its scheduled (i.e.
+ * periodic or delayed) tasks on: one whose threads are daemon threads named after the specified
+ * prefix, and which doesn't let the tasks that were scheduled for later delay its shutdown.
+ *
+ * @param corePoolSize the maximal number of threads of the pool, which are created on demand and
+ * let go if idle for a while
+ * @param threadNamePrefix the prefix the threads of the pool are named after
+ * @return a {@link ScheduledExecutorService} to run scheduled tasks on
+ */
+ public static ScheduledExecutorService daemonScheduledThreadPool(
+ int corePoolSize, String threadNamePrefix) {
+ final var executor =
+ new ScheduledThreadPoolExecutor(corePoolSize, daemonThreadFactory(threadNamePrefix));
+ // tasks that are scheduled far out (a reconciliation rescheduled in an hour, say) would
+ // otherwise keep the pool from terminating until the graceful shutdown timeout expires
+ executor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
+ // cancelled tasks are frequent (every retry that is superseded by a new event cancels one) and
+ // would otherwise be retained until their delay elapses
+ executor.setRemoveOnCancelPolicy(true);
+ // the threads are created as tasks get scheduled, not as the load requires, so without this
+ // they would all stay around idle for good; the pool always keeps a thread for delayed tasks
+ executor.setKeepAliveTime(SCHEDULED_THREAD_KEEP_ALIVE_SECONDS, TimeUnit.SECONDS);
+ executor.allowCoreThreadTimeOut(true);
+ return executor;
+ }
+}
diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/Operator.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/Operator.java
index 1e9f927f79..780cd52813 100644
--- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/Operator.java
+++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/Operator.java
@@ -20,6 +20,8 @@
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.concurrent.locks.LockSupport;
import java.util.function.Consumer;
import org.slf4j.Logger;
@@ -45,6 +47,7 @@ public class Operator implements LifecycleAware {
private ConfigurationService configurationService;
private volatile boolean started = false;
private final AtomicBoolean shutdownHookInstalled = new AtomicBoolean(false);
+ private final AtomicReference keepAliveThread = new AtomicReference<>();
public Operator() {
init(initConfigurationService(null, null), true);
@@ -175,6 +178,38 @@ public void installShutdownHook(Duration gracefulShutdownTimeout) {
installShutdownHook();
}
+ /**
+ * Keeps the JVM running until this operator is stopped, by starting a non-daemon thread that does
+ * nothing but wait. This is useful when the {@code main} method of the application returns after
+ * starting the operator and nothing else keeps the JVM alive, for example when the threads of the
+ * operator are all daemon threads, as is the case with virtual threads.
+ *
+ *
It can be called before or after {@link #start()}, and calling it again while the thread is
+ * already running has no effect. The thread ends when {@link #stop()} is called, so the operator
+ * can be stopped from a shutdown hook, see {@link #installShutdownHook()}.
+ */
+ public void keepAlive() {
+ var thread =
+ new Thread(
+ () -> {
+ while (!Thread.currentThread().isInterrupted()) {
+ LockSupport.park();
+ }
+ },
+ "josdk-keep-alive");
+ thread.setDaemon(false);
+ if (keepAliveThread.compareAndSet(null, thread)) {
+ thread.start();
+ }
+ }
+
+ private void stopKeepAlive() {
+ var thread = keepAliveThread.getAndSet(null);
+ if (thread != null) {
+ thread.interrupt();
+ }
+ }
+
public KubernetesClient getKubernetesClient() {
return configurationService.getKubernetesClient();
}
@@ -240,6 +275,7 @@ public synchronized void start() {
*/
@Override
public void stop() throws OperatorException {
+ stopKeepAlive();
Duration reconciliationTerminationTimeout =
configurationService.reconciliationTerminationTimeout();
diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ConfigurationService.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ConfigurationService.java
index db1b9a5fa5..3e34946c73 100644
--- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ConfigurationService.java
+++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ConfigurationService.java
@@ -16,10 +16,11 @@
package io.javaoperatorsdk.operator.api.config;
import java.time.Duration;
+import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
import java.util.function.Consumer;
import org.slf4j.Logger;
@@ -41,6 +42,7 @@
import io.javaoperatorsdk.operator.api.reconciler.Experimental;
import io.javaoperatorsdk.operator.api.reconciler.Reconciler;
import io.javaoperatorsdk.operator.api.reconciler.dependent.DependentResourceFactory;
+import io.javaoperatorsdk.operator.api.reconciler.dependent.DesiredStateAspect;
import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependent;
import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependentResource;
import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependentResourceConfig;
@@ -62,6 +64,12 @@ public interface ConfigurationService {
/** The default number of threads used to process dependent workflows */
int DEFAULT_WORKFLOW_EXECUTOR_THREAD_NUMBER = DEFAULT_RECONCILIATION_THREADS_NUMBER;
+ /**
+ * The default number of threads used to trigger the operator's retried and rescheduled
+ * reconciliations
+ */
+ int DEFAULT_RETRY_AND_RESCHEDULE_THREADS_NUMBER = 2;
+
/**
* Creates a new {@link ConfigurationService} instance used to configure an {@link
* io.javaoperatorsdk.operator.Operator} instance, starting from the specified base configuration
@@ -145,14 +153,20 @@ public R clone(R object) {
* you do not need to worry about setting the namespace information in most cases).
*
*
Previous versions of this class provided direct access to the serialization mechanism (via
- * {@link com.fasterxml.jackson.databind.ObjectMapper}) or the client's configuration. This was
- * somewhat confusing, in particular with respect to changes made in the Fabric8 client
- * serialization architecture made in 6.7. The proper way to configure these aspects is now to
- * configure the Kubernetes client accordingly and the SDK will extract the information it needs
- * from this instance. The recommended way to do so is to create your operator with {@link
+ * {@link tools.jackson.databind.ObjectMapper}) or the client's configuration. This was somewhat
+ * confusing, in particular with respect to changes made in the Fabric8 client serialization
+ * architecture made in 6.7. The proper way to configure these aspects is now to configure the
+ * Kubernetes client accordingly and the SDK will extract the information it needs from this
+ * instance. The recommended way to do so is to create your operator with {@link
* io.javaoperatorsdk.operator.Operator#Operator(Consumer)}, passing your custom instance with
* {@link ConfigurationServiceOverrider#withKubernetesClient(KubernetesClient)}.
*
+ *
When {@link #useVirtualThreads()} is enabled (and supported by the JVM), the default client
+ * runs its internal asynchronous tasks, such as dispatching informer events to their handlers and
+ * delivering watch events, on virtual threads instead of its default cached platform thread pool.
+ * A client provided by overriding this method or through {@link
+ * ConfigurationServiceOverrider#withKubernetesClient(KubernetesClient)} is used as is.
+ *
*
NOTE: It is strongly suggested that implementors override this method since the
* default implementation creates a new {@link KubernetesClient} instance each time this method is
* called.
@@ -161,13 +175,17 @@ public R clone(R object) {
* @since 4.4.0
*/
default KubernetesClient getKubernetesClient() {
- return new KubernetesClientBuilder()
- .withConfig(
- new ConfigBuilder(Config.autoConfigure(null))
- .withMaxConcurrentRequests(DEFAULT_MAX_CONCURRENT_REQUEST)
- .build())
- .withKubernetesSerialization(new KubernetesSerialization())
- .build();
+ final var builder =
+ new KubernetesClientBuilder()
+ .withConfig(
+ new ConfigBuilder(Config.autoConfigure(null))
+ .withMaxConcurrentRequests(DEFAULT_MAX_CONCURRENT_REQUEST)
+ .build())
+ .withKubernetesSerialization(new KubernetesSerialization());
+ if (VirtualThreads.shouldUse(useVirtualThreads())) {
+ builder.withTaskExecutorSupplier(VirtualThreads.newKubernetesClientTaskExecutorSupplier());
+ }
+ return builder.build();
}
/**
@@ -201,6 +219,11 @@ default boolean checkCRDAndValidateLocalModel() {
* The number of threads the operator can spin out to dispatch reconciliation requests to
* reconcilers with the default executors
*
+ *
This is a concurrency limit and applies regardless of whether the default executor is backed
+ * by platform or by virtual threads, see {@link #useVirtualThreads()}: with virtual threads it
+ * caps how many reconciliations run at the same time rather than the size of a thread pool. Since
+ * virtual threads are cheap, the limit can be set considerably higher when they are enabled.
+ *
* @return the number of concurrent reconciliation threads
*/
default int concurrentReconciliationThreads() {
@@ -211,12 +234,32 @@ default int concurrentReconciliationThreads() {
* Number of threads the operator can spin out to be used in the workflows with the default
* executor.
*
+ *
This is a concurrency limit and applies regardless of whether the default executor is backed
+ * by platform or by virtual threads, see {@link #useVirtualThreads()}: with virtual threads it
+ * caps how many dependent resources are processed at the same time rather than the size of a
+ * thread pool. Since virtual threads are cheap, the limit can be set considerably higher when
+ * they are enabled.
+ *
* @return the maximum number of concurrent workflow threads
*/
default int concurrentWorkflowExecutorThreads() {
return DEFAULT_WORKFLOW_EXECUTOR_THREAD_NUMBER;
}
+ /**
+ * Number of threads the operator can spin out to trigger its retried and rescheduled
+ * reconciliations with the default executor. These threads are shared by all the controllers of
+ * the operator, but the tasks they run only enqueue an event for the reconciliation to happen on
+ * a reconciliation thread, so few of them are needed. Not used when virtual threads are enabled,
+ * see {@link #useVirtualThreads()}.
+ *
+ * @return the maximum number of concurrent retry and reschedule threads
+ * @since 5.7.0
+ */
+ default int concurrentRetryAndRescheduleThreads() {
+ return DEFAULT_RETRY_AND_RESCHEDULE_THREADS_NUMBER;
+ }
+
/**
* Override to provide a custom {@link Metrics} implementation
*
@@ -226,6 +269,46 @@ default Metrics getMetrics() {
return Metrics.NOOP;
}
+ /**
+ * Whether the framework should run the tasks it executes concurrently — reconciliations,
+ * dependent workflows and internal housekeeping such as starting the informers — on virtual
+ * threads instead of platform threads.
+ *
+ *
Virtual threads make blocking operations, which is essentially all a reconciler does while
+ * talking to the Kubernetes API server or to external systems, much cheaper. Enabling them does
+ * not lift the configured concurrency limits: {@link #concurrentReconciliationThreads()}
+ * and {@link #concurrentWorkflowExecutorThreads()} still cap how many reconciliations,
+ * respectively dependent resources, are processed at the same time, they just aren't backed by a
+ * pool of platform threads anymore. Since virtual threads are cheap, those limits can be set
+ * considerably higher than what would be reasonable for platform threads.
+ *
+ *
Virtual threads are only supported on Java 25 or later, where JEP 491 removed the pinning of the carrier thread by
+ * {@code synchronized} blocks. This is checked at runtime: on an older JVM, a warning is logged
+ * and platform threads are used, so that the same configuration works regardless of the Java
+ * version the operator runs on.
+ *
+ *
Note that this only affects the executors created by the framework: a custom {@link
+ * ExecutorService} provided through {@link #getExecutorService()} or {@link
+ * #getWorkflowExecutorService()}, or a custom {@link ScheduledExecutorService} provided through
+ * {@link #getRetryAndRescheduleExecutorService()} or the polling configuration, is used as is.
+ * The default scheduled executors, including the ones the polling event sources create for
+ * themselves, keep a single platform thread for the timing and run each task they fire on a
+ * virtual thread. The same goes for the {@link KubernetesClient}: the default client created by
+ * {@link #getKubernetesClient()} then also runs its internal asynchronous tasks (informer event
+ * dispatching, watch event delivery) on virtual threads, while a custom client, e.g. provided
+ * through {@link ConfigurationServiceOverrider#withKubernetesClient(KubernetesClient)}, keeps
+ * whatever task executor it was built with. The blocking calls a reconciler performs through the
+ * client don't need any of this: they already park the calling virtual thread rather than its
+ * carrier.
+ *
+ * @return {@code true} to use virtual threads, {@code false} (default) to use platform threads
+ * @since 5.7.0
+ */
+ default boolean useVirtualThreads() {
+ return false;
+ }
+
/**
* Override to provide a custom {@link ExecutorService} implementation to change how threads
* handle concurrent reconciliations
@@ -234,7 +317,8 @@ default Metrics getMetrics() {
* processing
*/
default ExecutorService getExecutorService() {
- return Executors.newFixedThreadPool(concurrentReconciliationThreads());
+ return ExecutorServiceManager.newBoundedExecutorService(
+ concurrentReconciliationThreads(), useVirtualThreads());
}
/**
@@ -244,7 +328,26 @@ default ExecutorService getExecutorService() {
* @return the {@link ExecutorService} implementation to use for dependent workflow processing
*/
default ExecutorService getWorkflowExecutorService() {
- return Executors.newFixedThreadPool(concurrentWorkflowExecutorThreads());
+ return ExecutorServiceManager.newBoundedExecutorService(
+ concurrentWorkflowExecutorThreads(), useVirtualThreads());
+ }
+
+ /**
+ * Override to provide a custom {@link ScheduledExecutorService} implementation to change how the
+ * operator's retried and rescheduled reconciliations are triggered.
+ *
+ *
Note that the default implementation lets the executor discard the tasks that were scheduled
+ * for later when it is shut down, so that they don't delay the termination of the operator, and
+ * that it creates daemon threads so that a never stopped operator doesn't keep the JVM alive.
+ * Custom implementations are advised to do the same.
+ *
+ * @return the {@link ScheduledExecutorService} implementation to use to trigger retried and
+ * rescheduled reconciliations
+ * @since 5.7.0
+ */
+ default ScheduledExecutorService getRetryAndRescheduleExecutorService() {
+ return ExecutorServiceManager.newScheduledExecutorService(
+ concurrentRetryAndRescheduleThreads(), useVirtualThreads(), "josdk-retry-reschedule");
}
/**
@@ -286,9 +389,11 @@ default Optional getLeaderElectionConfiguration() {
*
Defaults to the {@code default} namespace, following the Kubernetes convention, which is
* also what the Go client does, so that events recorded by an operator end up alongside the ones
* recorded by the built-in controllers. Operators whose RBAC does not allow creating events in
- * the {@code default} namespace should override this, typically with the namespace the operator
- * itself runs in. Note that recording an event is best effort, so a missing permission results in
- * the event being dropped with a warning in the log rather than in an error.
+ * the {@code default} namespace can override this with {@code kube-system}. The API server
+ * rejects events about cluster scoped resources in any other namespace, such as the namespace the
+ * operator itself runs in. Note that recording an event is best effort by default, so a missing
+ * permission or a rejected namespace results in the event being dropped with a warning in the log
+ * rather than in an error.
*
* @return the namespace to record events about cluster scoped resources in
*/
@@ -303,8 +408,8 @@ default String clusterScopedEventNamespace() {
*
*
When empty, which is the default, every controller gets a {@link DefaultEventRecorder} of
* its own. A recorder configured here is shared by all controllers of the operator instead, which
- * is why the reconciliation an event is recorded from is passed to it per call rather than
- * configured on it: implementations have to be stateless and thread safe.
+ * is why the object an event is about and the reconciliation it is recorded from are passed to it
+ * per call rather than configured on it: implementations have to be stateless and thread safe.
*
* @return the event recorder to use for the whole operator, or an empty optional to let each
* controller use its own default one
@@ -539,4 +644,18 @@ default InformerPool informerPool() {
pool.setConfigurationService(this);
return pool;
}
+
+ /**
+ * Retrieves the {@link DesiredStateAspect}s applied to the desired state of all the Kubernetes
+ * dependent resources managed by the operator. Aspects are applied in the order in which they are
+ * returned, right after the desired state has been computed, and are typically used to add common
+ * metadata (such as a label identifying the operator managing the resource) to all the resources
+ * the operator creates or updates.
+ *
+ * @return the list of aspects to apply to computed desired states, empty by default
+ * @since 5.7.0
+ */
+ default List desiredStateAspects() {
+ return List.of();
+ }
}
diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ConfigurationServiceOverrider.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ConfigurationServiceOverrider.java
index 18a2e3fc38..2330a83ee4 100644
--- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ConfigurationServiceOverrider.java
+++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ConfigurationServiceOverrider.java
@@ -16,9 +16,12 @@
package io.javaoperatorsdk.operator.api.config;
import java.time.Duration;
+import java.util.ArrayList;
+import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ExecutorService;
+import java.util.concurrent.ScheduledExecutorService;
import java.util.function.Function;
import org.slf4j.Logger;
@@ -31,6 +34,7 @@
import io.javaoperatorsdk.operator.api.monitoring.Metrics;
import io.javaoperatorsdk.operator.api.reconciler.Experimental;
import io.javaoperatorsdk.operator.api.reconciler.dependent.DependentResourceFactory;
+import io.javaoperatorsdk.operator.api.reconciler.dependent.DesiredStateAspect;
import io.javaoperatorsdk.operator.processing.event.source.informer.pool.InformerPool;
@SuppressWarnings({"unused", "UnusedReturnValue"})
@@ -42,11 +46,14 @@ public class ConfigurationServiceOverrider {
private Boolean checkCR;
private Integer concurrentReconciliationThreads;
private Integer concurrentWorkflowExecutorThreads;
+ private Integer concurrentRetryAndRescheduleThreads;
private Cloner cloner;
private Boolean closeClientOnStop;
private KubernetesClient client;
private ExecutorService executorService;
private ExecutorService workflowExecutorService;
+ private Boolean useVirtualThreads;
+ private ScheduledExecutorService retryAndRescheduleExecutorService;
private LeaderElectionConfiguration leaderElectionConfiguration;
private String clusterScopedEventNamespace;
private EventRecorder eventRecorder;
@@ -59,6 +66,7 @@ public class ConfigurationServiceOverrider {
private Boolean useSSAToPatchPrimaryResource;
private Boolean cloneSecondaryResourcesWhenGettingFromCache;
private InformerPool informerPool;
+ private List desiredStateAspects;
@SuppressWarnings("rawtypes")
private DependentResourceFactory dependentResourceFactory;
@@ -82,6 +90,25 @@ public ConfigurationServiceOverrider withConcurrentWorkflowExecutorThreads(int t
return this;
}
+ /**
+ * Sets the number of threads used to trigger the operator's retried and rescheduled
+ * reconciliations, which are shared by all its controllers.
+ *
+ *
Note that changing the number of threads makes the overridden configuration build the
+ * default retry and reschedule executor itself, so a custom one provided by the configuration
+ * being overridden is not used anymore. Use {@link #withRetryAndRescheduleExecutorService} to
+ * provide one.
+ *
+ * @param threadNumber the maximum number of concurrent retry and reschedule threads
+ * @return this {@link ConfigurationServiceOverrider} for chained customization
+ * @see ConfigurationService#concurrentRetryAndRescheduleThreads()
+ * @since 5.7.0
+ */
+ public ConfigurationServiceOverrider withConcurrentRetryAndRescheduleThreads(int threadNumber) {
+ this.concurrentRetryAndRescheduleThreads = threadNumber;
+ return this;
+ }
+
@SuppressWarnings("rawtypes")
public ConfigurationServiceOverrider withDependentResourceFactory(
DependentResourceFactory dependentResourceFactory) {
@@ -115,6 +142,41 @@ public ConfigurationServiceOverrider withWorkflowExecutorService(
return this;
}
+ /**
+ * Replaces the executor used to trigger the operator's retried and rescheduled reconciliations,
+ * which is shared by all its controllers.
+ *
+ * @param retryAndRescheduleExecutorService the executor to trigger retried and rescheduled
+ * reconciliations on
+ * @return this {@link ConfigurationServiceOverrider} for chained customization
+ * @see ConfigurationService#getRetryAndRescheduleExecutorService()
+ * @since 5.7.0
+ */
+ public ConfigurationServiceOverrider withRetryAndRescheduleExecutorService(
+ ScheduledExecutorService retryAndRescheduleExecutorService) {
+ this.retryAndRescheduleExecutorService = retryAndRescheduleExecutorService;
+ return this;
+ }
+
+ /**
+ * Makes the framework run the tasks it executes concurrently on virtual threads instead of
+ * platform threads. Only supported on Java 25 or later, see {@link
+ * ConfigurationService#useVirtualThreads()} for the details.
+ *
+ *
Note that if this changes the value of the configuration being overridden, the overridden
+ * configuration builds the default retry and reschedule executor itself, so a custom one provided
+ * by the configuration being overridden is replaced and not used as is. Use {@link
+ * #withRetryAndRescheduleExecutorService} to provide one along with this setting.
+ *
+ * @param useVirtualThreads {@code true} to use virtual threads
+ * @return this {@link ConfigurationServiceOverrider} for chained customization
+ * @since 5.7.0
+ */
+ public ConfigurationServiceOverrider withUseVirtualThreads(boolean useVirtualThreads) {
+ this.useVirtualThreads = useVirtualThreads;
+ return this;
+ }
+
/**
* Replaces the default {@link KubernetesClient} instance by the specified one. This is the
* preferred mechanism to configure which client will be used to access the cluster.
@@ -139,8 +201,8 @@ public ConfigurationServiceOverrider withLeaderElectionConfiguration(
/**
* Sets the namespace in which Kubernetes events about cluster scoped resources are recorded. Use
- * this when the operator is not allowed to create events in the {@code default} namespace,
- * passing for example the namespace the operator itself runs in.
+ * this when the operator is not allowed to create events in the {@code default} namespace. The
+ * API server only accepts {@code default} and {@code kube-system} for such events.
*
* @param namespace the namespace to record events about cluster scoped resources in
* @return this {@link ConfigurationServiceOverrider} for chained customization
@@ -229,6 +291,38 @@ public ConfigurationServiceOverrider withInformerPool(InformerPool informerPool)
return this;
}
+ /**
+ * Replaces the {@link DesiredStateAspect}s applied to the desired state of all the Kubernetes
+ * dependent resources managed by the operator by the specified ones.
+ *
+ * @param desiredStateAspects the aspects to apply, in the order in which they should be applied
+ * @return this {@link ConfigurationServiceOverrider} for chained customization
+ * @since 5.7.0
+ */
+ public ConfigurationServiceOverrider withDesiredStateAspects(
+ List desiredStateAspects) {
+ this.desiredStateAspects = new ArrayList<>(desiredStateAspects);
+ return this;
+ }
+
+ /**
+ * Appends the specified {@link DesiredStateAspect}s to the already configured ones, which are the
+ * ones configured on the overridden {@link ConfigurationService} unless {@link
+ * #withDesiredStateAspects(List)} was called on this overrider first.
+ *
+ * @param desiredStateAspects the aspects to append, in the order in which they should be applied
+ * @return this {@link ConfigurationServiceOverrider} for chained customization
+ * @since 5.7.0
+ */
+ public ConfigurationServiceOverrider addDesiredStateAspects(
+ DesiredStateAspect... desiredStateAspects) {
+ if (this.desiredStateAspects == null) {
+ this.desiredStateAspects = new ArrayList<>(original.desiredStateAspects());
+ }
+ this.desiredStateAspects.addAll(List.of(desiredStateAspects));
+ return this;
+ }
+
public ConfigurationService build() {
return new BaseConfigurationService(original.getVersion(), cloner, client) {
@Override
@@ -276,6 +370,17 @@ public int concurrentWorkflowExecutorThreads() {
original.concurrentWorkflowExecutorThreads());
}
+ @Override
+ public int concurrentRetryAndRescheduleThreads() {
+ return Utils.ensureValid(
+ overriddenValueOrDefault(
+ concurrentRetryAndRescheduleThreads,
+ ConfigurationService::concurrentRetryAndRescheduleThreads),
+ "maximum retry and reschedule threads",
+ 1,
+ original.concurrentRetryAndRescheduleThreads());
+ }
+
@Override
public Metrics getMetrics() {
return overriddenValueOrDefault(metrics, ConfigurationService::getMetrics);
@@ -286,6 +391,11 @@ public boolean closeClientOnStop() {
return overriddenValueOrDefault(closeClientOnStop, ConfigurationService::closeClientOnStop);
}
+ @Override
+ public boolean useVirtualThreads() {
+ return overriddenValueOrDefault(useVirtualThreads, ConfigurationService::useVirtualThreads);
+ }
+
@Override
public ExecutorService getExecutorService() {
if (executorService != null) {
@@ -304,6 +414,26 @@ public ExecutorService getWorkflowExecutorService() {
}
}
+ @Override
+ public ScheduledExecutorService getRetryAndRescheduleExecutorService() {
+ if (retryAndRescheduleExecutorService != null) {
+ return retryAndRescheduleExecutorService;
+ } else if (!changes(
+ concurrentRetryAndRescheduleThreads, original.concurrentRetryAndRescheduleThreads())) {
+ return original.getRetryAndRescheduleExecutorService();
+ } else {
+ return super.getRetryAndRescheduleExecutorService();
+ }
+ }
+
+ // the default scheduled executors are only built anew when an override actually changes the
+ // way they are built, otherwise the ones of the original configuration are kept, which also
+ // preserves a custom executor the original provides
+ private boolean changes(Integer overriddenThreads, int originalThreads) {
+ return (overriddenThreads != null && overriddenThreads != originalThreads)
+ || (useVirtualThreads != null && useVirtualThreads != original.useVirtualThreads());
+ }
+
@Override
public Optional getLeaderElectionConfiguration() {
return leaderElectionConfiguration != null
@@ -383,6 +513,12 @@ public synchronized InformerPool informerPool() {
informerPool.setConfigurationService(this);
return informerPool;
}
+
+ @Override
+ public List desiredStateAspects() {
+ return overriddenValueOrDefault(
+ desiredStateAspects, ConfigurationService::desiredStateAspects);
+ }
};
}
}
diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ControllerConfigurationOverrider.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ControllerConfigurationOverrider.java
index bf0f54e41a..816e5659fa 100644
--- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ControllerConfigurationOverrider.java
+++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ControllerConfigurationOverrider.java
@@ -222,6 +222,18 @@ public ControllerConfigurationOverrider withInformerListLimit(Long informerLi
return this;
}
+ /**
+ * Whether to remove the namespace index the underlying informer maintains by default. Note that
+ * event sources that disagree on this setting do not share an informer.
+ *
+ * @param withoutNamespaceIndex true to remove the namespace index, false (the default) to keep it
+ * @see io.javaoperatorsdk.operator.api.config.informer.Informer#withoutNamespaceIndex()
+ */
+ public ControllerConfigurationOverrider withoutNamespaceIndex(boolean withoutNamespaceIndex) {
+ config.withoutNamespaceIndex(withoutNamespaceIndex);
+ return this;
+ }
+
public ControllerConfigurationOverrider replacingNamedDependentResourceConfig(
String name, Object dependentResourceConfig) {
diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ExecutorServiceManager.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ExecutorServiceManager.java
index cdcafcaa46..7f90b1b60d 100644
--- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ExecutorServiceManager.java
+++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ExecutorServiceManager.java
@@ -33,6 +33,7 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import io.javaoperatorsdk.operator.ExecutorUtilsInternal;
import io.javaoperatorsdk.operator.OperatorException;
public class ExecutorServiceManager {
@@ -42,6 +43,7 @@ public class ExecutorServiceManager {
private ExecutorService workflowExecutor;
private ExecutorService cachingExecutorService;
private ScheduledExecutorService scheduledExecutorService;
+ private ScheduledExecutorService retryAndRescheduleExecutorService;
private boolean started;
private ConfigurationService configurationService;
@@ -49,6 +51,59 @@ public class ExecutorServiceManager {
start(configurationService);
}
+ /**
+ * Creates the executor service used to run a bounded number of tasks concurrently, either backed
+ * by virtual threads or by a fixed size pool of platform threads. The concurrency limit is
+ * enforced in both cases.
+ *
+ * @param maxConcurrency the maximal number of tasks executed at the same time
+ * @param useVirtualThreads whether virtual threads should be used, see {@link
+ * ConfigurationService#useVirtualThreads()}
+ * @return the created {@link ExecutorService}
+ */
+ public static ExecutorService newBoundedExecutorService(
+ int maxConcurrency, boolean useVirtualThreads) {
+ return VirtualThreads.shouldUse(useVirtualThreads)
+ ? VirtualThreads.newBoundedVirtualThreadExecutor(maxConcurrency)
+ : Executors.newFixedThreadPool(maxConcurrency);
+ }
+
+ /**
+ * Creates the executor service used to run scheduled (i.e. periodic or delayed) tasks, either
+ * firing them on virtual threads or on a pool of platform threads. The platform thread variant is
+ * the one of {@link ExecutorUtilsInternal#daemonScheduledThreadPool(int, String)}. In both cases
+ * the threads are daemon threads. Virtual threads are cheap and the tasks scheduled are typically
+ * blocking calls, so their number is not limited.
+ *
+ * @param maxConcurrency the number of threads of the platform thread pool, not used with virtual
+ * threads
+ * @param useVirtualThreads whether virtual threads should be used, see {@link
+ * ConfigurationService#useVirtualThreads()}
+ * @param threadNamePrefix the prefix the threads of the executor are named after
+ * @return the {@link ScheduledExecutorService} to run scheduled tasks on
+ * @since 5.7.0
+ */
+ public static ScheduledExecutorService newScheduledExecutorService(
+ int maxConcurrency, boolean useVirtualThreads, String threadNamePrefix) {
+ return VirtualThreads.shouldUse(useVirtualThreads)
+ ? VirtualThreads.newScheduledExecutor(threadNamePrefix)
+ : ExecutorUtilsInternal.daemonScheduledThreadPool(maxConcurrency, threadNamePrefix);
+ }
+
+ /**
+ * Creates the executor service used to run an unbounded number of tasks concurrently, either
+ * backed by virtual threads or by a cached pool of platform threads.
+ *
+ * @param useVirtualThreads whether virtual threads should be used, see {@link
+ * ConfigurationService#useVirtualThreads()}
+ * @return the created {@link ExecutorService}
+ */
+ public static ExecutorService newUnboundedExecutorService(boolean useVirtualThreads) {
+ return VirtualThreads.shouldUse(useVirtualThreads)
+ ? VirtualThreads.newVirtualThreadPerTaskExecutor()
+ : Executors.newCachedThreadPool();
+ }
+
/**
* Uses cachingExecutorService from this manager. Use this only for tasks, that don't have dynamic
* nature, in sense that won't grow with the number of inputs (thus kubernetes resources)
@@ -128,30 +183,63 @@ public ExecutorService cachingExecutorService() {
return cachingExecutorService;
}
- public ScheduledExecutorService scheduledExecutorService() {
+ /**
+ * A general purpose scheduled executor, created on first use, which is shut down by {@link
+ * #stop(Duration)} and replaced by a fresh one on the next use after a {@link
+ * #start(ConfigurationService)}. The framework itself doesn't use it: the polling event sources
+ * poll on executors of their own, and retries are triggered on {@link
+ * #retryAndRescheduleExecutorService()}.
+ *
+ * @return the executor to run scheduled tasks on
+ * @deprecated the framework doesn't use this executor anymore, create and manage the executor you
+ * need yourself, e.g. with {@link #newScheduledExecutorService(int, boolean, String)}
+ */
+ @Deprecated(since = "5.7.0")
+ public synchronized ScheduledExecutorService scheduledExecutorService() {
+ if (scheduledExecutorService == null) {
+ scheduledExecutorService =
+ newScheduledExecutorService(
+ 1, configurationService.useVirtualThreads(), "josdk-scheduled-task");
+ }
return scheduledExecutorService;
}
+ /**
+ * The executor the operator triggers its retried and rescheduled reconciliations on. Note that it
+ * is only valid while the manager is started: it is shut down by {@link #stop(Duration)} and
+ * replaced by a fresh one on the next {@link #start(ConfigurationService)}, so callers should
+ * retrieve it when they start rather than hold on to it.
+ *
+ * @return the executor to trigger retried and rescheduled reconciliations on
+ */
+ public ScheduledExecutorService retryAndRescheduleExecutorService() {
+ return retryAndRescheduleExecutorService;
+ }
+
public synchronized void start(ConfigurationService configurationService) {
if (!started) {
this.configurationService = configurationService; // used to lazy init workflow executor
- this.cachingExecutorService = Executors.newCachedThreadPool();
- this.scheduledExecutorService = Executors.newScheduledThreadPool(0);
+ this.cachingExecutorService =
+ newUnboundedExecutorService(configurationService.useVirtualThreads());
+ this.retryAndRescheduleExecutorService =
+ configurationService.getRetryAndRescheduleExecutorService();
this.executor = new InstrumentedExecutorService(configurationService.getExecutorService());
started = true;
}
}
public synchronized void stop(Duration gracefulShutdownTimeout) {
- var parallelExec = Executors.newFixedThreadPool(4);
+ var shutdowns =
+ List.of(
+ shutdown(executor, gracefulShutdownTimeout),
+ shutdown(workflowExecutor, gracefulShutdownTimeout),
+ shutdown(cachingExecutorService, gracefulShutdownTimeout),
+ shutdown(scheduledExecutorService, gracefulShutdownTimeout),
+ shutdown(retryAndRescheduleExecutorService, gracefulShutdownTimeout));
+ var parallelExec = Executors.newFixedThreadPool(shutdowns.size());
try {
log.debug("Closing executor");
- parallelExec.invokeAll(
- List.of(
- shutdown(executor, gracefulShutdownTimeout),
- shutdown(workflowExecutor, gracefulShutdownTimeout),
- shutdown(cachingExecutorService, gracefulShutdownTimeout),
- shutdown(scheduledExecutorService, gracefulShutdownTimeout)));
+ parallelExec.invokeAll(shutdowns);
} catch (InterruptedException e) {
log.debug("Exception closing executor: {}", e.getLocalizedMessage());
Thread.currentThread().interrupt();
@@ -161,6 +249,7 @@ public synchronized void stop(Duration gracefulShutdownTimeout) {
// silently leaving the manager with already terminated executors
parallelExec.shutdownNow();
workflowExecutor = null;
+ scheduledExecutorService = null;
started = false;
}
}
diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/Utils.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/Utils.java
index 6ad4928c86..4613d9645d 100644
--- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/Utils.java
+++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/Utils.java
@@ -42,6 +42,8 @@ public class Utils {
public static final String GENERIC_PARAMETER_TYPE_ERROR_PREFIX =
"Couldn't retrieve generic parameter type from ";
+ public static final String VERSION_PROPERTIES_FILE_NAME = "operator-sdk-version.properties";
+
public static final Version VERSION = loadFromProperties();
/**
@@ -52,7 +54,9 @@ public class Utils {
*/
private static Version loadFromProperties() {
final var is =
- Thread.currentThread().getContextClassLoader().getResourceAsStream("version.properties");
+ Thread.currentThread()
+ .getContextClassLoader()
+ .getResourceAsStream(VERSION_PROPERTIES_FILE_NAME);
final var properties = new Properties();
if (is != null) {
@@ -62,7 +66,9 @@ private static Version loadFromProperties() {
log.warn("Couldn't load version information: {}", e.getMessage());
}
} else {
- log.warn("Couldn't find version.properties file. Default version information will be used.");
+ log.warn(
+ "Couldn't find {} file. Default version information will be used.",
+ VERSION_PROPERTIES_FILE_NAME);
}
Date builtTime;
diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/VirtualThreadScheduledExecutor.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/VirtualThreadScheduledExecutor.java
new file mode 100644
index 0000000000..3e3935e5ad
--- /dev/null
+++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/VirtualThreadScheduledExecutor.java
@@ -0,0 +1,312 @@
+/*
+ * Copyright Java Operator SDK Authors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.javaoperatorsdk.operator.api.config;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.AbstractExecutorService;
+import java.util.concurrent.Callable;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.Delayed;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.RejectedExecutionException;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+
+import io.javaoperatorsdk.operator.ExecutorUtilsInternal;
+
+/**
+ * A {@link ScheduledExecutorService} running the tasks it fires on the threads of another executor,
+ * which is how scheduled tasks end up on virtual threads: the JDK has no virtual thread backed
+ * {@link ScheduledExecutorService}, so a single daemon platform thread does the timing and only
+ * hands each fired task off.
+ *
+ *
The semantics follow the ones of the default scheduled executor of the SDK, see {@link
+ * ExecutorUtilsInternal#daemonScheduledThreadPool(int, String)}: tasks that were scheduled for
+ * later, and periodic tasks, are discarded when the executor is shut down, while tasks that already
+ * started are let finish.
+ */
+final class VirtualThreadScheduledExecutor extends AbstractExecutorService
+ implements ScheduledExecutorService {
+
+ private final ExecutorService worker;
+ private final ScheduledExecutorService timer;
+ private final Set> waiting = ConcurrentHashMap.newKeySet();
+ private final Object lifecycleLock = new Object();
+
+ VirtualThreadScheduledExecutor(ExecutorService worker, String threadNamePrefix) {
+ this.worker = worker;
+ this.timer = ExecutorUtilsInternal.daemonScheduledThreadPool(1, threadNamePrefix + "-timer");
+ }
+
+ @Override
+ public ScheduledFuture> schedule(Runnable command, long delay, TimeUnit unit) {
+ Objects.requireNonNull(command);
+ return start(new Handle(Executors.callable(command, null), 0), delay, unit);
+ }
+
+ @Override
+ public ScheduledFuture schedule(Callable callable, long delay, TimeUnit unit) {
+ Objects.requireNonNull(callable);
+ return start(new Handle<>(callable, 0), delay, unit);
+ }
+
+ @Override
+ public ScheduledFuture> scheduleAtFixedRate(
+ Runnable command, long initialDelay, long period, TimeUnit unit) {
+ Objects.requireNonNull(command);
+ if (period <= 0) {
+ throw new IllegalArgumentException("period must be positive");
+ }
+ return start(
+ new Handle(Executors.callable(command, null), unit.toNanos(period)),
+ initialDelay,
+ unit);
+ }
+
+ @Override
+ public ScheduledFuture> scheduleWithFixedDelay(
+ Runnable command, long initialDelay, long delay, TimeUnit unit) {
+ Objects.requireNonNull(command);
+ if (delay <= 0) {
+ throw new IllegalArgumentException("delay must be positive");
+ }
+ return start(
+ new Handle(Executors.callable(command, null), -unit.toNanos(delay)),
+ initialDelay,
+ unit);
+ }
+
+ private Handle start(Handle handle, long initialDelay, TimeUnit unit) {
+ handle.arm(System.nanoTime() + Math.max(0, unit.toNanos(initialDelay)));
+ return handle;
+ }
+
+ @Override
+ public void execute(Runnable command) {
+ worker.execute(Objects.requireNonNull(command));
+ }
+
+ @Override
+ public void shutdown() {
+ synchronized (lifecycleLock) {
+ cancelWaiting(false);
+ timer.shutdown();
+ worker.shutdown();
+ }
+ }
+
+ @Override
+ public List shutdownNow() {
+ final var notStarted = new ArrayList();
+ synchronized (lifecycleLock) {
+ cancelWaiting(true);
+ timer.shutdownNow();
+ for (var task : worker.shutdownNow()) {
+ if (task instanceof Dispatched dispatched) {
+ dispatched.handle.cancel(false);
+ } else {
+ notStarted.add(task);
+ }
+ }
+ }
+ return Collections.unmodifiableList(notStarted);
+ }
+
+ private void cancelWaiting(boolean mayInterruptIfRunning) {
+ for (var handle : waiting) {
+ handle.cancel(mayInterruptIfRunning);
+ }
+ }
+
+ @Override
+ public boolean isShutdown() {
+ return timer.isShutdown() && worker.isShutdown();
+ }
+
+ @Override
+ public boolean isTerminated() {
+ return timer.isTerminated() && worker.isTerminated();
+ }
+
+ @Override
+ public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
+ final var deadline = System.nanoTime() + unit.toNanos(timeout);
+ return timer.awaitTermination(timeout, unit)
+ && worker.awaitTermination(deadline - System.nanoTime(), TimeUnit.NANOSECONDS);
+ }
+
+ /**
+ * What is handed to the worker once a task fires, so that it can be traced back to its handle.
+ */
+ private record Dispatched(Handle> handle) implements Runnable {
+ @Override
+ public void run() {
+ handle.runOnWorker();
+ }
+ }
+
+ /**
+ * The future of a scheduled task. A positive {@code period} makes it a task at a fixed rate, a
+ * negative one a task with a fixed delay, whose absolute value is the delay.
+ */
+ private final class Handle implements ScheduledFuture {
+
+ private final Callable callable;
+ private final long period;
+ private final CompletableFuture result = new CompletableFuture<>();
+
+ private volatile ScheduledFuture> timerFuture;
+ private volatile Thread runner;
+ private volatile long triggerTime;
+
+ private Handle(Callable callable, long period) {
+ this.callable = callable;
+ this.period = period;
+ }
+
+ private void arm(long triggerNanos) {
+ triggerTime = triggerNanos;
+ final var delayNanos = Math.max(0, triggerNanos - System.nanoTime());
+ synchronized (lifecycleLock) {
+ waiting.add(this);
+ try {
+ timerFuture = timer.schedule(this::dispatch, delayNanos, TimeUnit.NANOSECONDS);
+ } catch (RejectedExecutionException e) {
+ waiting.remove(this);
+ throw e;
+ }
+ }
+ if (result.isDone()) {
+ waiting.remove(this);
+ timerFuture.cancel(false);
+ }
+ }
+
+ private void dispatch() {
+ waiting.remove(this);
+ if (result.isDone()) {
+ return;
+ }
+ try {
+ worker.execute(new Dispatched(this));
+ } catch (RejectedExecutionException e) {
+ result.cancel(false);
+ }
+ }
+
+ private void runOnWorker() {
+ runner = Thread.currentThread();
+ try {
+ if (result.isDone()) {
+ return;
+ }
+ if (period == 0) {
+ result.complete(callable.call());
+ return;
+ }
+ callable.call();
+ } catch (Throwable t) {
+ result.completeExceptionally(t);
+ return;
+ } finally {
+ runner = null;
+ }
+ rearm();
+ }
+
+ private void rearm() {
+ if (result.isDone()) {
+ return;
+ }
+ final long nextTrigger;
+ if (period > 0) {
+ nextTrigger = triggerTime + period;
+ } else {
+ nextTrigger = System.nanoTime() - period;
+ }
+ try {
+ arm(nextTrigger);
+ } catch (RejectedExecutionException e) {
+ result.cancel(false);
+ }
+ }
+
+ @Override
+ public boolean cancel(boolean mayInterruptIfRunning) {
+ final var cancelled = result.cancel(mayInterruptIfRunning);
+ if (cancelled) {
+ waiting.remove(this);
+ final var future = timerFuture;
+ if (future != null) {
+ future.cancel(false);
+ }
+ final var thread = runner;
+ if (mayInterruptIfRunning && thread != null) {
+ thread.interrupt();
+ }
+ }
+ return cancelled;
+ }
+
+ @Override
+ public boolean isCancelled() {
+ return result.isCancelled();
+ }
+
+ @Override
+ public boolean isDone() {
+ return result.isDone();
+ }
+
+ @Override
+ public V get() throws InterruptedException, ExecutionException {
+ return result.get();
+ }
+
+ @Override
+ public V get(long timeout, TimeUnit unit)
+ throws InterruptedException, ExecutionException, TimeoutException {
+ return result.get(timeout, unit);
+ }
+
+ @Override
+ public long getDelay(TimeUnit unit) {
+ return unit.convert(triggerTime - System.nanoTime(), TimeUnit.NANOSECONDS);
+ }
+
+ @Override
+ public int compareTo(Delayed other) {
+ if (other == this) {
+ return 0;
+ }
+ if (other instanceof Handle> otherHandle) {
+ // the deadlines are compared as they are, sampling the remaining delay of each handle
+ // separately would make a.compareTo(b) and b.compareTo(a) disagree for close deadlines
+ return Long.compare(triggerTime - otherHandle.triggerTime, 0);
+ }
+ return Long.compare(getDelay(TimeUnit.NANOSECONDS), other.getDelay(TimeUnit.NANOSECONDS));
+ }
+ }
+}
diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/VirtualThreads.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/VirtualThreads.java
new file mode 100644
index 0000000000..a47f09b320
--- /dev/null
+++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/VirtualThreads.java
@@ -0,0 +1,280 @@
+/*
+ * Copyright Java Operator SDK Authors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.javaoperatorsdk.operator.api.config;
+
+import java.lang.invoke.MethodHandle;
+import java.lang.invoke.MethodHandles;
+import java.lang.invoke.MethodType;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.AbstractExecutorService;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.Executor;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.Semaphore;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import io.fabric8.kubernetes.client.KubernetesClientBuilder.ExecutorSupplier;
+import io.javaoperatorsdk.operator.OperatorException;
+
+/**
+ * Creates the virtual thread based executors used when {@link
+ * ConfigurationService#useVirtualThreads()} is enabled.
+ *
+ *
Virtual threads are only supported on Java 25 or later, where JEP 491 removed the pinning of the carrier thread by
+ * {@code synchronized} blocks. On older JVMs, including the ones where virtual threads already
+ * exist, the request is ignored with a warning and platform threads are used, see {@link
+ * #shouldUse(boolean)}.
+ *
+ *
The SDK is compiled for Java 17, in which virtual threads don't exist yet, so {@code
+ * Executors.newVirtualThreadPerTaskExecutor()} is looked up reflectively.
+ *
+ *
The JDK provides no virtual thread backed {@link
+ * java.util.concurrent.ScheduledExecutorService} (the Loom runtime itself uses a platform thread
+ * scheduler to unpark timed out virtual threads), so the scheduled variant, see {@link
+ * #newScheduledExecutor(String)}, keeps a single platform thread for the timing only and hands each
+ * fired task off to a virtual thread.
+ */
+final class VirtualThreads {
+
+ private static final Logger log = LoggerFactory.getLogger(VirtualThreads.class);
+
+ /** The first Java version virtual threads are supported on. */
+ static final int MINIMUM_SUPPORTED_JAVA_VERSION = 25;
+
+ private static final MethodHandle NEW_VIRTUAL_THREAD_PER_TASK_EXECUTOR = lookupFactoryMethod();
+ private static final AtomicBoolean UNSUPPORTED_WARNING_LOGGED = new AtomicBoolean();
+
+ private VirtualThreads() {}
+
+ private static MethodHandle lookupFactoryMethod() {
+ try {
+ return MethodHandles.publicLookup()
+ .findStatic(
+ Executors.class,
+ "newVirtualThreadPerTaskExecutor",
+ MethodType.methodType(ExecutorService.class));
+ } catch (NoSuchMethodException | IllegalAccessException e) {
+ log.debug("Virtual threads are not available on this JVM", e);
+ return null;
+ }
+ }
+
+ /**
+ * Whether the JVM the operator runs on supports virtual threads, i.e. is Java {@value
+ * #MINIMUM_SUPPORTED_JAVA_VERSION} or later.
+ */
+ static boolean isSupported() {
+ return isSupported(Runtime.version().feature());
+ }
+
+ static boolean isSupported(int javaFeatureVersion) {
+ return NEW_VIRTUAL_THREAD_PER_TASK_EXECUTOR != null
+ && javaFeatureVersion >= MINIMUM_SUPPORTED_JAVA_VERSION;
+ }
+
+ /**
+ * Whether virtual threads should effectively be used, i.e. they were requested through {@link
+ * ConfigurationService#useVirtualThreads()} and the JVM supports them. Requesting them
+ * on a JVM that doesn't support them is only warned about, so that the same configuration can be
+ * used regardless of the Java version the operator ends up running on, the only consequence being
+ * that platform threads are used instead. Concurrency limits are enforced either way.
+ */
+ static boolean shouldUse(boolean requested) {
+ if (!requested || isSupported()) {
+ return requested;
+ }
+ if (UNSUPPORTED_WARNING_LOGGED.compareAndSet(false, true)) {
+ log.warn(
+ "Virtual threads were requested but are only supported on Java {} or later, and the JVM"
+ + " in use is Java {}. Falling back to platform threads.",
+ MINIMUM_SUPPORTED_JAVA_VERSION,
+ Runtime.version().feature());
+ }
+ return false;
+ }
+
+ /** An unbounded executor starting a new virtual thread for each submitted task. */
+ static ExecutorService newVirtualThreadPerTaskExecutor() {
+ if (!isSupported()) {
+ throw new OperatorException(
+ "Virtual threads are only supported on Java "
+ + MINIMUM_SUPPORTED_JAVA_VERSION
+ + " or later");
+ }
+ try {
+ return (ExecutorService) NEW_VIRTUAL_THREAD_PER_TASK_EXECUTOR.invokeExact();
+ } catch (Throwable e) {
+ throw new OperatorException("Couldn't create a virtual thread per task executor", e);
+ }
+ }
+
+ /**
+ * Supplies the task executor of the default {@link io.fabric8.kubernetes.client.KubernetesClient}
+ * created by {@link ConfigurationService#getKubernetesClient()}: an unbounded virtual thread
+ * executor, replacing the client's default cached platform thread pool, that is shut down when
+ * the client is closed.
+ */
+ static ExecutorSupplier newKubernetesClientTaskExecutorSupplier() {
+ return new ExecutorSupplier() {
+ @Override
+ public Executor get() {
+ return newVirtualThreadPerTaskExecutor();
+ }
+
+ @Override
+ public void onClose(Executor executor) {
+ ((ExecutorService) executor).shutdownNow();
+ }
+ };
+ }
+
+ /**
+ * A {@link ScheduledExecutorService} running the tasks it fires on virtual threads, without
+ * limiting how many of them run at the same time. The timing is done by a single daemon platform
+ * thread named after {@code threadNamePrefix}, which only hands the tasks off.
+ */
+ static ScheduledExecutorService newScheduledExecutor(String threadNamePrefix) {
+ return new VirtualThreadScheduledExecutor(newVirtualThreadPerTaskExecutor(), threadNamePrefix);
+ }
+
+ /**
+ * A virtual thread based executor executing at most {@code maxConcurrency} tasks at the same
+ * time, the equivalent of a fixed size platform thread pool.
+ */
+ static ExecutorService newBoundedVirtualThreadExecutor(int maxConcurrency) {
+ if (maxConcurrency <= 0) {
+ throw new IllegalArgumentException("maxConcurrency must be positive: " + maxConcurrency);
+ }
+ return new BoundedExecutorService(newVirtualThreadPerTaskExecutor(), maxConcurrency);
+ }
+
+ /**
+ * Limits how many of the tasks submitted to the wrapped executor run at the same time.
+ *
+ *
A thread is started for each task as soon as it is submitted, the task then waits for a
+ * permit before it actually runs. This only makes sense with virtual threads, which are cheap
+ * enough to be parked in large numbers, and has the property that submitting a task never blocks
+ * the submitting thread, just like queuing it on a fixed size platform thread pool wouldn't.
+ */
+ private static final class BoundedExecutorService extends AbstractExecutorService {
+
+ private final ExecutorService delegate;
+ private final Semaphore permits;
+ private final Set pending = ConcurrentHashMap.newKeySet();
+ private final Object lifecycleLock = new Object();
+
+ private BoundedExecutorService(ExecutorService delegate, int maxConcurrency) {
+ this.delegate = delegate;
+ this.permits = new Semaphore(maxConcurrency, true);
+ }
+
+ @Override
+ public void execute(Runnable command) {
+ Objects.requireNonNull(command);
+ var task = new PendingTask(command);
+ // admission is closed under the same lock that shutdownNow drains pending tasks with, so a
+ // task is either rejected or seen by the drain, and never interrupted while unaccounted for
+ synchronized (lifecycleLock) {
+ pending.add(task);
+ try {
+ delegate.execute(task);
+ } catch (RuntimeException e) {
+ pending.remove(task);
+ throw e;
+ }
+ }
+ }
+
+ private final class PendingTask implements Runnable {
+
+ private final Runnable command;
+ private final AtomicBoolean claimed = new AtomicBoolean();
+
+ private PendingTask(Runnable command) {
+ this.command = command;
+ }
+
+ private boolean claim() {
+ return claimed.compareAndSet(false, true);
+ }
+
+ @Override
+ public void run() {
+ try {
+ permits.acquire();
+ } catch (InterruptedException e) {
+ // shutdownNow interrupted us and already handed the task back to its caller
+ Thread.currentThread().interrupt();
+ return;
+ }
+ try {
+ if (!claim()) {
+ return;
+ }
+ pending.remove(this);
+ command.run();
+ } finally {
+ permits.release();
+ }
+ }
+ }
+
+ @Override
+ public void shutdown() {
+ delegate.shutdown();
+ }
+
+ @Override
+ public List shutdownNow() {
+ var notStarted = new ArrayList();
+ synchronized (lifecycleLock) {
+ for (var task : pending) {
+ if (task.claim()) {
+ pending.remove(task);
+ notStarted.add(task.command);
+ }
+ }
+ delegate.shutdownNow();
+ }
+ return notStarted;
+ }
+
+ @Override
+ public boolean isShutdown() {
+ return delegate.isShutdown();
+ }
+
+ @Override
+ public boolean isTerminated() {
+ return delegate.isTerminated();
+ }
+
+ @Override
+ public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
+ return delegate.awaitTermination(timeout, unit);
+ }
+ }
+}
diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/informer/Informer.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/informer/Informer.java
index 04f97902d3..69999ef04f 100644
--- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/informer/Informer.java
+++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/informer/Informer.java
@@ -31,6 +31,7 @@
import static io.javaoperatorsdk.operator.api.reconciler.Constants.DEFAULT_COMPARABLE_RESOURCE_VERSION;
import static io.javaoperatorsdk.operator.api.reconciler.Constants.DEFAULT_FOLLOW_CONTROLLER_NAMESPACE_CHANGES;
import static io.javaoperatorsdk.operator.api.reconciler.Constants.DEFAULT_GHOST_RESOURCE_CHECK_INTERVAL_MILLIS;
+import static io.javaoperatorsdk.operator.api.reconciler.Constants.DEFAULT_WITHOUT_NAMESPACE_INDEX;
import static io.javaoperatorsdk.operator.api.reconciler.Constants.NO_LONG_VALUE_SET;
import static io.javaoperatorsdk.operator.api.reconciler.Constants.NO_VALUE_SET;
@@ -153,6 +154,23 @@
*/
boolean comparableResourceVersions() default DEFAULT_COMPARABLE_RESOURCE_VERSION;
+ /**
+ * Whether to remove the namespace index that the underlying informer maintains by default.
+ *
+ *
The framework never reads that index, it only reads the indexes registered through {@link
+ * io.javaoperatorsdk.operator.processing.event.source.IndexerResourceCache#addIndexers}, so
+ * dropping it saves an entry per cached resource. It is worth setting when the informer caches a
+ * large number of resources and nothing looks them up by namespace, in particular together with a
+ * custom {@link #itemStore()} that keeps only a reduced form of each resource.
+ *
+ *
Note that this makes the informer a distinct one for pooling purposes: event sources that
+ * disagree on this setting do not share an informer, because the index cannot be present for one
+ * of them and absent for the other.
+ *
+ * @since 5.7.0
+ */
+ boolean withoutNamespaceIndex() default DEFAULT_WITHOUT_NAMESPACE_INDEX;
+
/**
* @deprecated Ghost resource checking is now triggered by the informer's onList callback. This
* setting is no longer used.
diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/informer/InformerConfiguration.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/informer/InformerConfiguration.java
index 9fe25c999d..106f5898c5 100644
--- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/informer/InformerConfiguration.java
+++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/informer/InformerConfiguration.java
@@ -58,6 +58,7 @@ public class InformerConfiguration {
private Long informerListLimit;
private FieldSelector fieldSelector;
private Boolean comparableResourceVersions;
+ private Boolean withoutNamespaceIndex;
protected InformerConfiguration(
Class resourceClass,
@@ -75,6 +76,7 @@ protected InformerConfiguration(
Long informerListLimit,
FieldSelector fieldSelector,
Boolean comparableResourceVersions,
+ Boolean withoutNamespaceIndex,
// TODO for removal in major release
Duration ghostResourceCacheCheckInterval) {
this(resourceClass, resourceGroupVersionKind);
@@ -91,6 +93,7 @@ protected InformerConfiguration(
this.informerListLimit = informerListLimit;
this.fieldSelector = fieldSelector;
this.comparableResourceVersions = comparableResourceVersions;
+ this.withoutNamespaceIndex = withoutNamespaceIndex;
}
private InformerConfiguration(Class resourceClass, GroupVersionKind resourceGroupVersionKind) {
@@ -140,6 +143,7 @@ public static InformerConfiguration.Builder builder(
original.informerListLimit,
original.fieldSelector,
original.comparableResourceVersions,
+ original.withoutNamespaceIndex,
null)
.builder;
}
@@ -332,6 +336,15 @@ public boolean isComparableResourceVersions() {
return comparableResourceVersions;
}
+ /**
+ * Whether the namespace index the underlying informer maintains by default is removed.
+ *
+ * @see Informer#withoutNamespaceIndex()
+ */
+ public boolean isWithoutNamespaceIndex() {
+ return withoutNamespaceIndex;
+ }
+
@SuppressWarnings("UnusedReturnValue")
public class Builder {
@@ -349,6 +362,9 @@ public InformerConfiguration buildForController() {
if (comparableResourceVersions == null) {
comparableResourceVersions = DEFAULT_COMPARABLE_RESOURCE_VERSION;
}
+ if (withoutNamespaceIndex == null) {
+ withoutNamespaceIndex = DEFAULT_WITHOUT_NAMESPACE_INDEX;
+ }
return InformerConfiguration.this;
}
@@ -364,6 +380,9 @@ public InformerConfiguration build() {
if (comparableResourceVersions == null) {
comparableResourceVersions = DEFAULT_COMPARABLE_RESOURCE_VERSION;
}
+ if (withoutNamespaceIndex == null) {
+ withoutNamespaceIndex = DEFAULT_WITHOUT_NAMESPACE_INDEX;
+ }
return InformerConfiguration.this;
}
@@ -417,6 +436,7 @@ public InformerConfiguration.Builder initFromAnnotation(
.map(f -> new FieldSelector.Field(f.path(), f.value(), f.negated()))
.toList()));
withComparableResourceVersions(informerConfig.comparableResourceVersions());
+ withoutNamespaceIndex(informerConfig.withoutNamespaceIndex());
}
return this;
}
@@ -533,6 +553,16 @@ private static boolean isEmpty(FieldSelector fieldSelector) {
|| fieldSelector.getFields().isEmpty();
}
+ /**
+ * Whether to remove the namespace index the underlying informer maintains by default.
+ *
+ * @see Informer#withoutNamespaceIndex()
+ */
+ public Builder withoutNamespaceIndex(boolean withoutNamespaceIndex) {
+ InformerConfiguration.this.withoutNamespaceIndex = withoutNamespaceIndex;
+ return this;
+ }
+
public Builder withComparableResourceVersions(boolean comparableResourceVersions) {
InformerConfiguration.this.comparableResourceVersions = comparableResourceVersions;
return this;
diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/informer/InformerEventSourceConfiguration.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/informer/InformerEventSourceConfiguration.java
index 9bd6f84d06..d40469de4c 100644
--- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/informer/InformerEventSourceConfiguration.java
+++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/informer/InformerEventSourceConfiguration.java
@@ -292,6 +292,11 @@ public Builder withComparableResourceVersion(boolean comparableResourceVersio
return this;
}
+ public Builder withoutNamespaceIndex(boolean withoutNamespaceIndex) {
+ config.withoutNamespaceIndex(withoutNamespaceIndex);
+ return this;
+ }
+
@Deprecated(forRemoval = true)
public Builder withGhostResourceCacheCheckInterval(
Duration ghostResourceCacheCheckInterval) {
@@ -316,6 +321,8 @@ public void updateFrom(InformerConfiguration informerConfig) {
.withOnDeleteFilter(informerConfig.getOnDeleteFilter())
.withGenericFilter(informerConfig.getGenericFilter())
.withInformerListLimit(informerConfig.getInformerListLimit())
+ .withComparableResourceVersions(informerConfig.isComparableResourceVersions())
+ .withoutNamespaceIndex(informerConfig.isWithoutNamespaceIndex())
.withFieldSelector(informerConfig.getFieldSelector());
}
}
diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/BoundResourceEventRecorder.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/BoundResourceEventRecorder.java
new file mode 100644
index 0000000000..13a711ac48
--- /dev/null
+++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/BoundResourceEventRecorder.java
@@ -0,0 +1,46 @@
+/*
+ * Copyright Java Operator SDK Authors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.javaoperatorsdk.operator.api.event;
+
+import java.util.Objects;
+import java.util.function.Consumer;
+
+/**
+ * A {@link ResourceEventRecorder} that hands every event to a fixed recording, through which an
+ * {@link EventRecorder} binds it to an object and a reconciliation.
+ */
+record BoundResourceEventRecorder(Consumer recording)
+ implements ResourceEventRecorder {
+
+ BoundResourceEventRecorder {
+ Objects.requireNonNull(recording, "the recording to hand events to must not be null");
+ }
+
+ @Override
+ public void normal(String reason, String message) {
+ record(EventRecord.normal(reason, message));
+ }
+
+ @Override
+ public void warn(String reason, String message) {
+ record(EventRecord.warning(reason, message));
+ }
+
+ @Override
+ public void record(EventRecord event) {
+ recording.accept(event);
+ }
+}
diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/DefaultEventRecorder.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/DefaultEventRecorder.java
index 2e7023623d..8fd3f1fc7a 100644
--- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/DefaultEventRecorder.java
+++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/DefaultEventRecorder.java
@@ -21,9 +21,12 @@
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Instant;
+import java.time.ZoneOffset;
+import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.HexFormat;
import java.util.Objects;
+import java.util.regex.Pattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -31,6 +34,7 @@
import io.fabric8.kubernetes.api.model.Event;
import io.fabric8.kubernetes.api.model.EventBuilder;
import io.fabric8.kubernetes.api.model.HasMetadata;
+import io.fabric8.kubernetes.api.model.MicroTime;
import io.fabric8.kubernetes.api.model.ObjectReference;
import io.fabric8.kubernetes.api.model.ObjectReferenceBuilder;
import io.javaoperatorsdk.operator.api.config.LeaderElectionConfiguration;
@@ -39,19 +43,29 @@
import static java.util.Objects.requireNonNullElse;
/**
- * Default {@link EventRecorder}. Assembles events from an {@link EventRecord} plus the context the
- * controller already knows about (the involved object reference, the reporting controller and
- * instance), then hands them to an {@link EventSink}.
+ * Default {@link EventRecorder}. Assembles events from an {@link EventRecord} plus what is known
+ * about the object the event is about (the involved object reference) and the controller recording
+ * it (the reporting controller and instance), then hands them to an {@link EventSink}.
*
*
Events for cluster scoped objects have to live in some namespace: by default the {@value
* #CLUSTER_SCOPED_EVENT_NAMESPACE} namespace is used, following the Kubernetes convention, but it
* can be overridden, see {@link
- * io.javaoperatorsdk.operator.api.config.ConfigurationService#clusterScopedEventNamespace()}.
+ * io.javaoperatorsdk.operator.api.config.ConfigurationService#clusterScopedEventNamespace()}. The
+ * API server only accepts such events in the {@code default} and {@code kube-system} namespaces.
*
- *
Events are named deterministically, after the object they are about plus a hash of everything
- * that identifies the event, so that recording the same event again resolves to the event already
- * recorded for it. Repeat occurrences are then counted on that event rather than recorded as copies
- * of it, see {@link DefaultEventSink}.
+ *
By default, events are named deterministically, after the object they are about plus a hash of
+ * everything that identifies the event, so that recording the same event again resolves to the
+ * event already recorded for it. Repeat occurrences are then counted on that event rather than
+ * recorded as copies of it, see {@link DefaultEventSink}. How events aggregate, how they are named
+ * and whether they carry an owner reference can be configured, see {@link #builder(EventSink)}.
+ *
+ *
Recording is best effort by default: an event that cannot be written is logged and dropped,
+ * and the caller carries on. A recorder built with {@link Builder#failOnError(boolean)} propagates
+ * the failure to the caller instead, so that a reconciliation that cannot record its events fails
+ * and is retried.
+ *
+ *
An event can be about any object, not only the primary resource of the reconciliation
+ * recording it: the object is passed per call, see {@link EventRecorder}.
*/
public class DefaultEventRecorder implements EventRecorder {
@@ -59,6 +73,8 @@ public class DefaultEventRecorder implements EventRecorder {
public static final String CLUSTER_SCOPED_EVENT_NAMESPACE = "default";
+ private static final String KUBE_SYSTEM_NAMESPACE = "kube-system";
+
/**
* Kubernetes limits object names to 253 characters, as they have to be valid RFC 1123 DNS
* subdomains.
@@ -73,10 +89,107 @@ public class DefaultEventRecorder implements EventRecorder {
private static final int IDENTITY_HASH_LENGTH = 32;
+ /**
+ * The fixed width format of {@code MicroTime}, which the API server refuses to read otherwise.
+ */
+ private static final DateTimeFormatter EVENT_TIME_FORMAT =
+ DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSS'Z'").withZone(ZoneOffset.UTC);
+
+ /** What the API server accepts as an object name, see RFC 1123 on DNS subdomains. */
+ private static final Pattern RFC_1123_SUBDOMAIN =
+ Pattern.compile("[a-z0-9]([-a-z0-9]*[a-z0-9])?(\\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*");
+
private final EventSink sink;
+ private final EventNamingStrategy namingStrategy;
+ private final EventKeyStrategy keyStrategy;
+ private final boolean ownerReference;
+ private final boolean failOnError;
public DefaultEventRecorder(EventSink sink) {
+ this(sink, EventNamingStrategy.none(), EventKeyStrategy.none(), false, false);
+ }
+
+ private DefaultEventRecorder(
+ EventSink sink,
+ EventNamingStrategy namingStrategy,
+ EventKeyStrategy keyStrategy,
+ boolean ownerReference,
+ boolean failOnError) {
this.sink = sink;
+ this.namingStrategy = namingStrategy;
+ this.keyStrategy = keyStrategy;
+ this.ownerReference = ownerReference;
+ this.failOnError = failOnError;
+ }
+
+ public static Builder builder(EventSink sink) {
+ return new Builder(sink);
+ }
+
+ /** Builder for {@link DefaultEventRecorder}. */
+ public static final class Builder {
+
+ private final EventSink sink;
+ private EventNamingStrategy namingStrategy = EventNamingStrategy.none();
+ private EventKeyStrategy keyStrategy = EventKeyStrategy.none();
+ private boolean ownerReference = false;
+ private boolean failOnError = false;
+
+ private Builder(EventSink sink) {
+ this.sink = Objects.requireNonNull(sink, "sink must not be null");
+ }
+
+ /** The strategy naming recorded events, see {@link EventNamingStrategy}. */
+ public Builder namingStrategy(EventNamingStrategy namingStrategy) {
+ this.namingStrategy =
+ Objects.requireNonNull(namingStrategy, "namingStrategy must not be null");
+ return this;
+ }
+
+ /**
+ * The strategy deriving the default aggregation key of records that do not set one, see {@link
+ * EventKeyStrategy}. The key is ignored for events whose name is set by the record or resolved
+ * by the naming strategy, see {@link EventNamingStrategy}.
+ */
+ public Builder keyStrategy(EventKeyStrategy keyStrategy) {
+ this.keyStrategy = Objects.requireNonNull(keyStrategy, "keyStrategy must not be null");
+ return this;
+ }
+
+ /**
+ * When set, recorded events carry an {@code ownerReference} to the object they are about. The
+ * reference expresses ownership for tooling that reads it; note that the Kubernetes garbage
+ * collector ignores events, so it does not cause cascade deletion, events expire through the
+ * event TTL either way. Records can override this per event via {@link
+ * EventRecord.Builder#ownedByRegarding(boolean)}. The reference is only set when the object
+ * already has a uid.
+ */
+ public Builder ownerReference(boolean ownerReference) {
+ this.ownerReference = ownerReference;
+ return this;
+ }
+
+ /**
+ * When set, a failure to record an event is propagated to the caller rather than logged and
+ * swallowed, so that the reconciliation recording the event fails and goes through the usual
+ * error handling and retries. Off by default: Kubernetes treats events as best effort,
+ * supplemental data, and a controller that cannot reconcile because it cannot write an event is
+ * usually worse off than one that records nothing. Enable it only where an event that is not
+ * recorded must not go unnoticed.
+ *
+ *
Every failure propagates, transient ones included, such as a conflicting write when two
+ * replicas aggregate the same event at the same time; the reconciliation is then retried like
+ * any other failed one.
+ */
+ public Builder failOnError(boolean failOnError) {
+ this.failOnError = failOnError;
+ return this;
+ }
+
+ public DefaultEventRecorder build() {
+ return new DefaultEventRecorder(
+ sink, namingStrategy, keyStrategy, ownerReference, failOnError);
+ }
}
/**
@@ -108,40 +221,45 @@ private static String resolve() {
}
@Override
- public void record(EventRecord event, Context> context) {
- Objects.requireNonNull(context, "the context of the reconciliation must not be null");
+ public void record(HasMetadata regarding, EventRecord event, Context> context) {
+ Objects.requireNonNull(regarding, "the object the event is about must not be null");
+ Objects.requireNonNull(
+ regarding.getMetadata(), "the object the event is about must have metadata");
Objects.requireNonNull(event, "event must not be null");
+ Objects.requireNonNull(context, "the context of the reconciliation must not be null");
+ Event assembled = null;
try {
- sink.emit(toEvent(context, event), context);
+ assembled = toEvent(regarding, event, context);
+ sink.emit(assembled, context);
} catch (Exception e) {
- // recording an event must never break the caller: a controller that fails to reconcile
- // because it could not write an event is strictly worse than one that records nothing
+ if (failOnError) {
+ throw e;
+ }
+ // by default recording an event must not break the caller: a controller that fails to
+ // reconcile because it could not write an event is usually worse off than one that records
+ // nothing
log.warn(
- "Could not record {} event with reason {} for resource {} in namespace {}",
+ "Could not record {} event named {} with reason {} about {} {} in namespace {}",
event.type(),
+ assembled != null ? assembled.getMetadata().getName() : "unknown",
event.reason(),
- context.getPrimaryResource().getMetadata().getName(),
- context.getPrimaryResource().getMetadata().getNamespace(),
+ regarding.getKind(),
+ regarding.getMetadata().getName(),
+ regarding.getMetadata().getNamespace(),
e);
}
}
- @Override
- public ResourceEventRecorder forContext(Context> context) {
- Objects.requireNonNull(context, "the context events will be recorded from must not be null");
- return new BoundEventRecorder(this, context);
- }
-
- protected Event toEvent(Context> context, EventRecord record) {
+ protected Event toEvent(HasMetadata regarding, EventRecord record, Context> context) {
var controllerName = context.getControllerConfiguration().getName();
- var regarding = context.getPrimaryResource();
var now = Instant.now().truncatedTo(ChronoUnit.SECONDS).toString();
var involvedObject = objectReferenceFor(regarding);
+ var namespace = eventNamespace(regarding, context);
var builder =
new EventBuilder()
.withNewMetadata()
.withName(eventName(regarding, record, controllerName))
- .withNamespace(eventNamespace(regarding, context))
+ .withNamespace(namespace)
.withLabels(record.labels())
.withAnnotations(record.annotations())
.endMetadata()
@@ -164,10 +282,45 @@ protected Event toEvent(Context> context, EventRecord record) {
.withNewSource()
.withComponent(record.reportingComponent().orElse(controllerName))
.endSource();
- record.action().ifPresent(builder::withAction);
+ boolean ownedByRegarding = record.ownedByRegarding().orElse(ownerReference);
+ if (ownedByRegarding && regarding.getMetadata().getUid() == null) {
+ log.debug(
+ "Not setting the owner reference on the event about {}: the object has no uid yet",
+ regarding.getMetadata().getName());
+ }
+ if (ownedByRegarding && regarding.getMetadata().getUid() != null) {
+ builder
+ .editMetadata()
+ .addNewOwnerReference()
+ .withApiVersion(regarding.getApiVersion())
+ .withKind(regarding.getKind())
+ .withName(regarding.getMetadata().getName())
+ .withUid(regarding.getMetadata().getUid())
+ .endOwnerReference()
+ .endMetadata();
+ }
+ var action = record.action().filter(a -> !a.isBlank());
+ action.ifPresent(builder::withAction);
+ if (requiresEventTime(regarding, namespace)) {
+ builder.withEventTime(new MicroTime(EVENT_TIME_FORMAT.format(Instant.now())));
+ if (action.isEmpty()) {
+ builder.withAction(record.reason());
+ }
+ }
return builder.build();
}
+ /**
+ * The API server only accepts an event without {@code eventTime} for a cluster scoped object if
+ * the event lives in the {@code default} namespace. An event that carries an {@code eventTime}
+ * (and with it an {@code action}) is also accepted in the {@code kube-system} namespace. No other
+ * namespace is accepted for such an event, whether it has an {@code eventTime} or not.
+ */
+ private static boolean requiresEventTime(HasMetadata regarding, String eventNamespace) {
+ return regarding.getMetadata().getNamespace() == null
+ && KUBE_SYSTEM_NAMESPACE.equals(eventNamespace);
+ }
+
private String eventNamespace(HasMetadata regarding, Context> context) {
var namespace = regarding.getMetadata().getNamespace();
if (namespace != null) {
@@ -181,17 +334,62 @@ private String eventNamespace(HasMetadata regarding, Context> context) {
CLUSTER_SCOPED_EVENT_NAMESPACE);
}
+ private String eventName(HasMetadata regarding, EventRecord record, String reportingController) {
+ return record
+ .name()
+ .filter(name -> !name.isBlank())
+ .or(() -> namingStrategy.nameFor(regarding, record).filter(name -> !name.isBlank()))
+ .map(DefaultEventRecorder::truncateToMaxNameLength)
+ .filter(DefaultEventRecorder::isValidEventName)
+ .orElseGet(() -> identityHashName(regarding, record, reportingController));
+ }
+
+ private static boolean isValidEventName(String name) {
+ if (RFC_1123_SUBDOMAIN.matcher(name).matches()) {
+ return true;
+ }
+ log.warn(
+ "Falling back to the default event name: {} is not a valid RFC 1123 DNS subdomain", name);
+ return false;
+ }
+
+ private static String truncateToMaxNameLength(String name) {
+ if (name.length() <= MAX_NAME_LENGTH) {
+ return name;
+ }
+ var suffix = "." + identityDigest(name);
+ var shortened = truncate(name, MAX_NAME_LENGTH - suffix.length()) + suffix;
+ log.warn(
+ "Shortened the name of event {} to {} to stay within the Kubernetes name limit",
+ name,
+ shortened);
+ return shortened;
+ }
+
+ private static String truncate(String name, int maxLength) {
+ var truncated = name.substring(0, Math.min(name.length(), maxLength));
+ while (truncated.endsWith("-") || truncated.endsWith(".")) {
+ truncated = truncated.substring(0, truncated.length() - 1);
+ }
+ return truncated;
+ }
+
/**
* Names events {@code