Skip to content

Commit c50f673

Browse files
committed
fix: event recorder aggregation, long names and cluster scoped events (#3665)
Correctness fixes of the event recorder, found while reviewing the virtual thread support (#3664). - Aggregating onto a named event now updates its type, reason and action along with the count, last timestamp and message, so a Warning repeated under the name of a Normal event is no longer reported as the Normal one. An occurrence without an action clears the earlier action, except on an event that carries an eventTime, where the reason stands in for it, as the API server requires an action for such events. The API server only makes these fields immutable for events.k8s.io/v1, not for the core API the sink writes to. - Supplied event names longer than the Kubernetes limit are shortened with a hash of the full name instead of being plainly truncated, so distinct names sharing a long prefix no longer merge into one event. Trailing '-' and '.' are stripped before the hash is appended, for supplied and generated names alike, so a name is never cut into an invalid "...-.<hash>". - Events about cluster scoped resources in the kube-system namespace carry an eventTime and an action (defaulting to the reason), which is what the API server requires to accept them there. Events in the default namespace are unchanged. The API server rejects such events in any other namespace, so the javadocs and docs no longer suggest the namespace the operator runs in. Tests: regression and unit tests, a kube-api-test based DefaultEventRecorderIntegrationTest recording events against a real API server, and ITs for cluster scoped resources in default and kube-system.
1 parent 1ce0ecc commit c50f673

12 files changed

Lines changed: 853 additions & 28 deletions

File tree

‎docs/content/en/docs/documentation/operations/configuration.md‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -379,7 +379,7 @@ All operator-level keys are prefixed with `josdk.`.
379379

380380
| Key | Type | Description |
381381
|---|---|---|
382-
| `josdk.events.cluster-scoped-namespace` | `String` | Namespace to record events about cluster scoped resources in (defaults to `default`) |
382+
| `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` |
383383

384384
Recording events requires the operator's service account to be allowed `get`, `create` and `patch` on
385385
`events` in the core (`""`) API group. All three are used: an event that does not exist yet is
@@ -395,6 +395,11 @@ therefore has to grant the permission in every namespace events are recorded in
395395
`default`, or whatever `josdk.events.cluster-scoped-namespace` is set to, if the operator reconciles
396396
cluster scoped resources. A `ClusterRole` covers all of them at once.
397397

398+
The API server only accepts events about cluster scoped objects in the `default` and `kube-system`
399+
namespaces, so those are the only values `josdk.events.cluster-scoped-namespace` can usefully be set
400+
to. In particular, the namespace the operator itself runs in is rejected, and the event dropped with
401+
a warning in the operator log.
402+
398403
#### Leader Election
399404

400405
Leader election is activated when at least one `josdk.leader-election.*` key is present.

‎operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ConfigurationService.java‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -389,9 +389,11 @@ default Optional<LeaderElectionConfiguration> getLeaderElectionConfiguration() {
389389
* <p>Defaults to the {@code default} namespace, following the Kubernetes convention, which is
390390
* also what the Go client does, so that events recorded by an operator end up alongside the ones
391391
* recorded by the built-in controllers. Operators whose RBAC does not allow creating events in
392-
* the {@code default} namespace should override this, typically with the namespace the operator
393-
* itself runs in. Note that recording an event is best effort, so a missing permission results in
394-
* the event being dropped with a warning in the log rather than in an error.
392+
* the {@code default} namespace can override this with {@code kube-system}. The API server
393+
* rejects events about cluster scoped resources in any other namespace, such as the namespace the
394+
* operator itself runs in. Note that recording an event is best effort, so a missing permission
395+
* or a rejected namespace results in the event being dropped with a warning in the log rather
396+
* than in an error.
395397
*
396398
* @return the namespace to record events about cluster scoped resources in
397399
*/

‎operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ConfigurationServiceOverrider.java‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -201,8 +201,8 @@ public ConfigurationServiceOverrider withLeaderElectionConfiguration(
201201

202202
/**
203203
* Sets the namespace in which Kubernetes events about cluster scoped resources are recorded. Use
204-
* this when the operator is not allowed to create events in the {@code default} namespace,
205-
* passing for example the namespace the operator itself runs in.
204+
* this when the operator is not allowed to create events in the {@code default} namespace. The
205+
* API server only accepts {@code default} and {@code kube-system} for such events.
206206
*
207207
* @param namespace the namespace to record events about cluster scoped resources in
208208
* @return this {@link ConfigurationServiceOverrider} for chained customization

‎operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/DefaultEventRecorder.java‎

Lines changed: 46 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,8 @@
2121
import java.security.MessageDigest;
2222
import java.security.NoSuchAlgorithmException;
2323
import java.time.Instant;
24+
import java.time.ZoneOffset;
25+
import java.time.format.DateTimeFormatter;
2426
import java.time.temporal.ChronoUnit;
2527
import java.util.HexFormat;
2628
import java.util.Objects;
@@ -32,6 +34,7 @@
3234
import io.fabric8.kubernetes.api.model.Event;
3335
import io.fabric8.kubernetes.api.model.EventBuilder;
3436
import io.fabric8.kubernetes.api.model.HasMetadata;
37+
import io.fabric8.kubernetes.api.model.MicroTime;
3538
import io.fabric8.kubernetes.api.model.ObjectReference;
3639
import io.fabric8.kubernetes.api.model.ObjectReferenceBuilder;
3740
import io.javaoperatorsdk.operator.api.config.LeaderElectionConfiguration;
@@ -47,7 +50,8 @@
4750
* <p>Events for cluster scoped objects have to live in some namespace: by default the {@value
4851
* #CLUSTER_SCOPED_EVENT_NAMESPACE} namespace is used, following the Kubernetes convention, but it
4952
* can be overridden, see {@link
50-
* io.javaoperatorsdk.operator.api.config.ConfigurationService#clusterScopedEventNamespace()}.
53+
* io.javaoperatorsdk.operator.api.config.ConfigurationService#clusterScopedEventNamespace()}. The
54+
* API server only accepts such events in the {@code default} and {@code kube-system} namespaces.
5155
*
5256
* <p>By default, events are named deterministically, after the object they are about plus a hash of
5357
* everything that identifies the event, so that recording the same event again resolves to the
@@ -61,6 +65,8 @@ public class DefaultEventRecorder implements EventRecorder {
6165

6266
public static final String CLUSTER_SCOPED_EVENT_NAMESPACE = "default";
6367

68+
private static final String KUBE_SYSTEM_NAMESPACE = "kube-system";
69+
6470
/**
6571
* Kubernetes limits object names to 253 characters, as they have to be valid RFC 1123 DNS
6672
* subdomains.
@@ -75,6 +81,12 @@ public class DefaultEventRecorder implements EventRecorder {
7581

7682
private static final int IDENTITY_HASH_LENGTH = 32;
7783

84+
/**
85+
* The fixed width format of {@code MicroTime}, which the API server refuses to read otherwise.
86+
*/
87+
private static final DateTimeFormatter EVENT_TIME_FORMAT =
88+
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSS'Z'").withZone(ZoneOffset.UTC);
89+
7890
/** What the API server accepts as an object name, see RFC 1123 on DNS subdomains. */
7991
private static final Pattern RFC_1123_SUBDOMAIN =
8092
Pattern.compile("[a-z0-9]([-a-z0-9]*[a-z0-9])?(\\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*");
@@ -211,11 +223,12 @@ protected Event toEvent(Context<?> context, EventRecord record) {
211223
var regarding = context.getPrimaryResource();
212224
var now = Instant.now().truncatedTo(ChronoUnit.SECONDS).toString();
213225
var involvedObject = objectReferenceFor(regarding);
226+
var namespace = eventNamespace(regarding, context);
214227
var builder =
215228
new EventBuilder()
216229
.withNewMetadata()
217230
.withName(eventName(regarding, record, controllerName))
218-
.withNamespace(eventNamespace(regarding, context))
231+
.withNamespace(namespace)
219232
.withLabels(record.labels())
220233
.withAnnotations(record.annotations())
221234
.endMetadata()
@@ -255,10 +268,28 @@ protected Event toEvent(Context<?> context, EventRecord record) {
255268
.endOwnerReference()
256269
.endMetadata();
257270
}
258-
record.action().ifPresent(builder::withAction);
271+
var action = record.action().filter(a -> !a.isBlank());
272+
action.ifPresent(builder::withAction);
273+
if (requiresEventTime(regarding, namespace)) {
274+
builder.withEventTime(new MicroTime(EVENT_TIME_FORMAT.format(Instant.now())));
275+
if (action.isEmpty()) {
276+
builder.withAction(record.reason());
277+
}
278+
}
259279
return builder.build();
260280
}
261281

282+
/**
283+
* The API server only accepts an event without {@code eventTime} for a cluster scoped object if
284+
* the event lives in the {@code default} namespace. An event that carries an {@code eventTime}
285+
* (and with it an {@code action}) is also accepted in the {@code kube-system} namespace. No other
286+
* namespace is accepted for such an event, whether it has an {@code eventTime} or not.
287+
*/
288+
private static boolean requiresEventTime(HasMetadata regarding, String eventNamespace) {
289+
return regarding.getMetadata().getNamespace() == null
290+
&& KUBE_SYSTEM_NAMESPACE.equals(eventNamespace);
291+
}
292+
262293
private String eventNamespace(HasMetadata regarding, Context<?> context) {
263294
var namespace = regarding.getMetadata().getNamespace();
264295
if (namespace != null) {
@@ -295,14 +326,20 @@ private static String truncateToMaxNameLength(String name) {
295326
if (name.length() <= MAX_NAME_LENGTH) {
296327
return name;
297328
}
298-
var truncated = name.substring(0, MAX_NAME_LENGTH);
329+
var suffix = "." + identityDigest(name);
330+
var shortened = truncate(name, MAX_NAME_LENGTH - suffix.length()) + suffix;
331+
log.warn(
332+
"Shortened the name of event {} to {} to stay within the Kubernetes name limit",
333+
name,
334+
shortened);
335+
return shortened;
336+
}
337+
338+
private static String truncate(String name, int maxLength) {
339+
var truncated = name.substring(0, Math.min(name.length(), maxLength));
299340
while (truncated.endsWith("-") || truncated.endsWith(".")) {
300341
truncated = truncated.substring(0, truncated.length() - 1);
301342
}
302-
log.warn(
303-
"Truncated the name of event {} to {} to stay within the Kubernetes name limit",
304-
name,
305-
truncated);
306343
return truncated;
307344
}
308345

@@ -337,12 +374,7 @@ private String identityHashName(
337374
.orElseGet(() -> requireNonNullElse(record.message(), "")));
338375

339376
var suffix = "." + identityDigest(identity);
340-
var prefix = metadata.getName();
341-
var maxPrefixLength = MAX_NAME_LENGTH - suffix.length();
342-
if (prefix.length() > maxPrefixLength) {
343-
prefix = prefix.substring(0, maxPrefixLength);
344-
}
345-
return prefix + suffix;
377+
return truncate(metadata.getName(), MAX_NAME_LENGTH - suffix.length()) + suffix;
346378
}
347379

348380
/**

‎operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/DefaultEventSink.java‎

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,8 +30,13 @@
3030
* <p>An event that does not exist yet is created. An event that does is a repeat of one already
3131
* recorded, since the name of an event is derived from everything that identifies it (see {@link
3232
* DefaultEventRecorder}), and is aggregated onto the recorded one by patching its {@code count} and
33-
* {@code lastTimestamp}. That is what makes {@code kubectl describe} report a repeating event once,
34-
* as {@code (x12 over 3m)}, rather than filling the event list with copies of it.
33+
* {@code lastTimestamp}, along with its {@code message}, {@code type}, {@code reason} and {@code
34+
* action}, which events sharing a name explicitly may differ in: they describe the latest
35+
* occurrence. The API server only makes them immutable for {@code events.k8s.io/v1} requests, not
36+
* for the core group this sink writes to. An event that carries an {@code eventTime} needs an
37+
* {@code action}, so the reason stands in for it when the occurrence has none. That is what makes
38+
* {@code kubectl describe} report a repeating event once, as {@code (x12 over 3m)}, rather than
39+
* filling the event list with copies of it.
3540
*
3641
* <p>Recording therefore needs {@code get}, {@code create} and {@code patch} on {@code events} in
3742
* the core API group. The patch is made on the resource version the event was read at, so two
@@ -55,11 +60,18 @@ public void emit(Event event, Context<?> context) {
5560
if (existing == null) {
5661
events.resource(event).create();
5762
} else {
63+
var action = event.getAction();
64+
if (action == null && existing.getEventTime() != null) {
65+
action = event.getReason();
66+
}
5867
var aggregated =
5968
new EventBuilder(existing)
6069
.withCount(requireNonNullElse(existing.getCount(), 1) + 1)
6170
.withLastTimestamp(event.getLastTimestamp())
6271
.withMessage(event.getMessage())
72+
.withType(event.getType())
73+
.withReason(event.getReason())
74+
.withAction(action)
6375
.build();
6476
events.resource(existing).patch(aggregated);
6577
}

‎operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/EventNamingStrategy.java‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,8 +30,9 @@
3030
*
3131
* <p>A name must be a valid RFC 1123 DNS subdomain: at most 253 lowercase alphanumeric characters,
3232
* {@code -} or {@code .}, starting and ending with an alphanumeric character. Names longer than the
33-
* limit are truncated. A name derived from the object and a fixed lowercase suffix (such as {@code
34-
* <object>-status-report}) satisfies all of this by construction.
33+
* limit are shortened, keeping a hash of the full name so distinct names stay distinct. A name
34+
* derived from the object and a fixed lowercase suffix (such as {@code <object>-status-report})
35+
* satisfies all of this by construction.
3536
*
3637
* <p>An empty result or an invalid name falls back to the default {@code <object>.<identity hash>}
3738
* name, rather than the event being lost to the API server rejecting the name.

0 commit comments

Comments
 (0)