Guide
Events
Every manifest method call and every generated resource is an event - intercept methods, react to generated resources, and write rules that hold for the whole build.
Templating has no moment at which "every pod spec of the build" exists for a program to address: text goes in, text comes out. Klass8s renders by running a program, so that moment exists, and the event system is how you reach it. It is where a platform keeps the rules that apply to everything: a ServiceAccount for every pod, checksums on every workload, limits on every production container.
It is also how Klass8s itself works. Environment methods, #[AfterMethod], the default labels, the checksums and the klass8s.dev/* annotations are subscribers to the same events you can subscribe to.
Two kinds of events
Method events fire around every public method call on every manifest and container, because each one enters the build wrapped in a proxy. They can intercept: read the arguments, see the result, replace it, or skip the method entirely.
Generated events fire as resources come together: for each container, each pod spec, each finished resource, each manifest, and once for the whole build. You receive the generated klass8s/k8schema object and change it.
Where they fall in the render lifecycle:
a manifest method is called ─▶ klass8s.manifest.before_method (may skip the method)
the method returns ─▶ klass8s.manifest.method_called (may replace the result)
a container is built ─▶ klass8s.container.generated
a pod spec is built ─▶ klass8s.pod_spec.generated
a pod template is built ─▶ klass8s.pod_template_spec.generated
a resource of a kind ─▶ klass8s.manifest_generated.deployment (and one per kind)
every manifest ─▶ klass8s.manifest_generated (may drop the resource)
every App is built ─▶ klass8s.manifests.processed (checksums happen here)
files are written ─▶ klass8s.manifests.dumpedContainer classes have their own pair, klass8s.container.before_method and klass8s.container.method_called. The events reference lists every event with its payload.
Intercepting methods
The base classes are AbstractMethodSubscriber (before the method) and AbstractMethodResultSubscriber (after it), with variants bound to manifest or container events. You write what the subscriber supports and what it does:
namespace App\EventSubscriber;
use App\K8S\Platform\Manifest\WorkloadServiceAccount;
use App\K8S\Platform\PlatformApp;
use Klass8s\Bundle\EventListener\AbstractManifestMethodResultSubscriber;
use Klass8s\Core\Pod\PodSpecInterface;
use Klass8s\Event\ProxyableMethodCalledEventInterface;
use Klass8s\Manifest\Reference\ManifestClassReference;
/** Every pod runs under the platform's workload ServiceAccount, unless its manifest names one. */
final class DefaultServiceAccountSubscriber extends AbstractManifestMethodResultSubscriber
{
protected supports(ProxyableMethodCalledEventInterface $event): bool
=> 'serviceAccount' === $event->methodName() && $event->proxyable() instanceof PodSpecInterface;
protected afterMethod(ProxyableMethodCalledEventInterface $event): void {
if (null !== $event->returnedValue()) {
return; // the manifest chose its own
}
$event->setReturnValue(new ManifestClassReference(PlatformApp::NAME, WorkloadServiceAccount::class));
}
}<?php
declare(strict_types=1);
namespace App\EventSubscriber;
use App\K8S\Platform\Manifest\WorkloadServiceAccount;
use App\K8S\Platform\PlatformApp;
use Klass8s\Bundle\EventListener\AbstractManifestMethodResultSubscriber;
use Klass8s\Core\Pod\PodSpecInterface;
use Klass8s\Event\ProxyableMethodCalledEventInterface;
use Klass8s\Manifest\Reference\ManifestClassReference;
/** Every pod runs under the platform's workload ServiceAccount, unless its manifest names one. */
final class DefaultServiceAccountSubscriber extends AbstractManifestMethodResultSubscriber
{
protected function supports(ProxyableMethodCalledEventInterface $event): bool
{
return 'serviceAccount' === $event->methodName() && $event->proxyable() instanceof PodSpecInterface;
}
protected function afterMethod(ProxyableMethodCalledEventInterface $event): void
{
if (null !== $event->returnedValue()) {
return; // the manifest chose its own
}
$event->setReturnValue(new ManifestClassReference(PlatformApp::NAME, WorkloadServiceAccount::class));
}
}The rule reads: every pod runs under the platform's ServiceAccount, unless its manifest chose another. The last clause is the hard part for a post-processing step, and here it is a null check: the subscriber sees what the manifest's own method returned before deciding whether to answer for it. A manifest that names its own keeps it:
# File: /shop/api.deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
annotations:
klass8s.dev/app: shop
klass8s.dev/deploy-priority: '0'
labels:
app.kubernetes.io/name: shop
app.kubernetes.io/component: api
name: shop-api
spec:
replicas: 1
revisionHistoryLimit: 1
selector:
matchLabels:
app.kubernetes.io/name: shop
app.kubernetes.io/component: api
template:
metadata:
annotations:
klass8s.dev/env-sources-checksum: d41d8cd98f00b204e9800998ecf8427e
klass8s.dev/volume-sources-checksum: d41d8cd98f00b204e9800998ecf8427e
labels:
app.kubernetes.io/name: shop
app.kubernetes.io/component: api
spec:
containers:
-
image: 'acme/shop-api:1.0.0'
imagePullPolicy: IfNotPresent
name: app
resources:
limits: { memory: 512Mi }
serviceAccountName: platform-workload
---
# File: /shop/indexer.deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
annotations:
klass8s.dev/app: shop
klass8s.dev/deploy-priority: '0'
labels:
app.kubernetes.io/name: shop
app.kubernetes.io/component: indexer
name: shop-indexer
spec:
replicas: 1
revisionHistoryLimit: 1
selector:
matchLabels:
app.kubernetes.io/name: shop
app.kubernetes.io/component: indexer
template:
metadata:
annotations:
klass8s.dev/env-sources-checksum: d41d8cd98f00b204e9800998ecf8427e
klass8s.dev/volume-sources-checksum: d41d8cd98f00b204e9800998ecf8427e
labels:
app.kubernetes.io/name: shop
app.kubernetes.io/component: indexer
spec:
containers:
-
image: 'acme/shop-indexer:1.0.0'
imagePullPolicy: IfNotPresent
name: app
resources:
limits: { memory: 1Gi }
serviceAccountName: shop-indexerWhat an event offers:
returnedValue(): what the method returned (after the call only).setReturnValue($value): after the call, replaces what the caller receives; before it, skips the method and supplies the result.auto_set_replicasis this: a before-subscriber that answersreplicas()from configuration.methodParams(),methodParam($name),typedMethodParam($name, $class): the arguments; to add to avoidconfigurator method, take its configurator argument and call it.proxyable(): the manifest or container, for aninstanceoftest insupports().
Interception is not limited to methods Klass8s declares: every public method of a manifest fires the events, your own methods included. That is why the subscriber above filters on the method's name and an interface.
Reacting to generated resources
For rules about the result rather than the process, subscribe to the generated events. These are plain Symfony subscribers, with no base class:
namespace App\EventSubscriber;
use Klass8s\Bundle\EnvManagement\Env;
use Klass8s\Event\ContainerGeneratedEvent;
use LogicException;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/** A production container without a memory limit fails the render. */
final class RequireMemoryLimitsInProd implements EventSubscriberInterface
{
__construct(#[Autowire('%kernel.environment%')] private string $environment) {}
static getSubscribedEvents(): map<string, string> => [ContainerGeneratedEvent::NAME => 'onContainer'];
onContainer(ContainerGeneratedEvent $event): void throws LogicException {
if (Env::PRODUCTION !== $this->environment) {
return;
}
$limits = $event->container->getResources()?->limits();
if (null === $limits || !$limits->has('memory')) {
throw new LogicException(sprintf('Container "%s" has no memory limit, which production requires.', $event->container->getName()));
}
}
}<?php
declare(strict_types=1);
namespace App\EventSubscriber;
use Klass8s\Bundle\EnvManagement\Env;
use Klass8s\Event\ContainerGeneratedEvent;
use LogicException;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/** A production container without a memory limit fails the render. */
final class RequireMemoryLimitsInProd implements EventSubscriberInterface
{
public function __construct(#[Autowire('%kernel.environment%')] private string $environment) {}
/**
* @return array<string, string>
*/
public static function getSubscribedEvents(): array
{
return [ContainerGeneratedEvent::NAME => 'onContainer'];
}
/**
* @throws LogicException
*/
public function onContainer(ContainerGeneratedEvent $event): void
{
if (Env::PRODUCTION !== $this->environment) {
return;
}
$limits = $event->container->getResources()?->limits();
if (null === $limits || !$limits->has('memory')) {
throw new LogicException(sprintf('Container "%s" has no memory limit, which production requires.', $event->container->getName()));
}
}
}The render fails, on a laptop or in CI, instead of the rule failing quietly in the cluster. Subscribe with the event's NAME constant: events are dispatched under those names, not under their class names.
From fine to coarse:
ContainerGeneratedEvent,PodSpecGeneratedEvent,PodTemplateSpecGeneratedEvent: every container and pod of the build, whatever the workload's kind. The level for sidecars, security defaults and scheduling defaults.- One event per kind (
DeploymentGeneratedEvent,ServiceGeneratedEvent,HTTPRouteGeneratedEventand the others): the finished resource with its manifest and App. Some kinds have none (RBAC, autoscalers, claims, monitors, self-making manifests) and fire only the generic event; the reference has the list. ManifestGeneratedEvent: every manifest of every kind, with a writablepreventProcessing: set it totrueand the resource is left out of the output.ManifestsProcessedEvent: once, after every App is built and before anything is written; the only point that sees the whole build. The checksums are computed here, from what earlier subscribers recorded, and policy-spawned manifests are added here.
Two smaller mechanisms complete it. The environment-source events (klass8s.env_source.config_map and .secret) can be stopped: stopPropagation() keeps that ConfigMap or Secret out of the container's environment. Image middleware (ContainerImageMiddlewareInterface) rewrites every container's Image (a registry mirror, a pinned tag), ordered by a static priority().
Order
Subscribers run at priority 0 unless they say otherwise (override protected static function priority(): int on the base classes, or use Symfony's syntax). The framework's own subscribers run at 0, with three at -1024: the environment methods (so that replicasProd() has the last word), the tracking of generated resources, and the checksums. To see final values, subscribe below -1024; to contribute values that environment methods may still override, stay at 0 or above.
What is on by default
| Behaviour | Mechanism | Switch |
|---|---|---|
app.kubernetes.io/* labels on resources and selectors | method subscribers on metadata() and selector() | set_default_metadata_labels, set_default_selector_labels; per class #[NoDefaultMetadataLabels], #[NoDefaultSelectorLabels] |
| a Service's selector from the workload with its short name | subscriber on ServiceGeneratedEvent | set_default_service_selector; per class #[NoDefaultServiceSelector] |
klass8s.dev/app and klass8s.dev/deploy-priority | subscriber on ManifestGeneratedEvent and its Helm counterpart | always on: tools that read the output depend on them |
| checksums of configuration in pod templates | ManifestsProcessedEvent, at -1024 | auto_generate_checksums |
| replicas and resources from configuration | before-method subscribers | auto_set_replicas, auto_set_resources, off by default |
| environment methods and decorators | method subscribers | env_management.env_suffixed_methods |
metadata.namespace removed from the output | subscribers on the generated events | strip_namespace, off by default |
The switches are in the configuration reference.
Choosing where a rule lives
- A base class or a trait, when the rule applies to a family you control ("all our workers look like this"). Inheritance is simpler than interception; try it first.
- A subscriber, when the rule applies to everything of a shape, including manifests not written yet, or must be enforced.
- Configuration with
auto_set_*, when it is not a rule but a dial someone else sets. configure<Kind>()in one manifest, when it concerns one manifest. The third copy of the same change is the sign to make it a subscriber.
Next
- Events reference
- Environments: the attributes built on these events.
- Testing: proving that a subscriber does what it should.