Operator
The operator is a single controller-manager binary
(operator/cmd/controllers/kornercode). It runs two controllers, the
Workspace and Team controllers, and serves the admission webhooks for all
four custom resources. It is built with
controller-runtime and
genop-runtime, a small
framework that structures reconciliation as an ordered chain of steps
(ADR 0001).
| Path | Contents |
|---|---|
operator/api/v1alpha1 | CRD types, labels and annotations shared with the gateway |
operator/cmd/controllers/kornercode | Entry point: manager, controllers, webhooks, metrics, events |
operator/internal/controllers/v1alpha1/workspace | Workspace reconciler, watches, apply/delete steps, helpers |
operator/internal/controllers/v1alpha1/team | Team reconciler: namespace and NetworkPolicy propagation |
operator/internal/webhook/v1alpha1 | Validating and mutating admission webhooks |
config/helm | Helm chart (operator and gateway), generated CRDs and RBAC |
operator/api/v1alpha1/validation | Validation rules shared with the gateway (owner IDs, test ports, namespaces, mounts, profiles, TTL, …) |
The step-chain model
A genop operator defines an ordered list of apply steps and deletion steps. Each step manages one concern and reports its result as a status condition on the resource:
Succeed(): the step’s condition becomesTrueand the chain moves on.Requeue(after, message): the condition isFalse; the chain stops and resumes at this step after the delay.Fail(...): the resource goes toFailedand is retried with backoff.
A step whose condition is already True is skipped. When every step is
True, a reconcile is a drift check: all steps run again to confirm the
state still holds, and the resource keeps its Ready condition unless a step
reports a problem. The framework also manages the finalizer
(code.kornercloud.dev/<kind>-deletion), the Ready condition,
observedGeneration, backoff and Kubernetes events.
This gives one rule that every step must follow: a step must be able to
return Succeed(). A step that always requeues keeps the chain from ever
being fully True, so watch events never trigger a drift check and nothing
heals (ADR 0009).
Annotations offer manual control: reconcile.code.kornercloud.dev/pause=true
pauses a resource, and code.kornercloud.dev/<ConditionType>=retry re-runs a
single step.
Workspace controller
Apply chain
| # | Step | Condition | Responsibility |
|---|---|---|---|
| 1 | ReconcilePVC | PVCReconciled | Resolve the owner’s single home volume (adopt a restored one, reuse or create home-<owner>) and record it in status.homePVCName (see below) |
| 2 | ReconcileServiceAccount | ServiceAccountReconciled | Ensure the namespace’s workspace service account exists |
| 3 | ReconcileCertificate | CertificateReconciled | With mTLS: request the workspace certificate and render the Envoy configuration; otherwise a no-op |
| 4 | ReconcilePod | PodReconciled | Create the pod with status.homePVCName at /home/coder, replace it when it is lost or finished, detect configuration drift (see below) |
| 5 | ReconcileService | ServiceReconciled | Expose code-server and the test port |
| 6 | ReconcileNetworkPolicy | NetworkPolicyReconciled | Keep the pod’s NetworkPolicy labels in line with the security profile |
| 7 | ReconcileLifecycle | LifecycleReconciled | Maintain status.expiresAt |
The deletion chain removes the certificate, the pod, the service and any legacy per-workspace NetworkPolicy. The home volume is deliberately kept (ADR 0003).
Home volume
Each user has exactly one home volume per namespace, a PersistentVolumeClaim
mounted at /home/coder. It holds everything that belongs to the user,
code-server’s own settings and extensions included. A home is identified by
labels, not by name:
| Label | Value | Set by |
|---|---|---|
code.kornercloud.dev/owner | owner ID (lowercased Keycloak sub) | operator |
code.kornercloud.dev/managed-by | kornercode-operator | operator |
code.kornercloud.dev/volume | home, or replaced-home for a home that an adopted volume superseded | operator |
code.kornercloud.dev/home-for | owner ID | administrator, to hand a restored volume to a user |
ReconcilePVC resolves the home of the workspace owner in this order and
stops at the first match:
- Adoption. A PVC in the namespace labeled
home-for=<owner>(the label value is compared in lowercase). The operator adds whichever ofowner,managed-byandvolume=homeit lacks, relabels every other home of the ownervolume=replaced-home, and emits a Normal eventHomeVolumeAdoptedon the Workspace naming the adopted volume and any home it replaced. This holds even when the volume already carriesvolume=home, as one restored from another kornercode install may; once nothing is left to change, the step changes nothing and emits no event. The step fails with a Warning event when several PVCs carry the label for the same owner, or when the labeled PVC already has anownerlabel for someone else; it never relabels such a volume. The admin guide therefore has administrators remove a staleownerlabel before labeling a volume. Size and storage class stay as restored; the profile’sstorageSizedoes not apply. Thehome-forlabel stays on the PVC. - Managed home. The PVC labeled
owner=<owner>,managed-byandvolume=home. More than one is a failure with a Warning event. - Legacy home. A
home-<owner>PVC without avolumelabel, created before homes were labeled: the operator adds the labels and uses it, unless itsownerorhome-forlabel names another user, which fails the step. Ifhome-<owner>is labeledvolume=replaced-home, the step fails until an administrator or the user deletes it, because a replaced home is never mounted again and its name blocks a fresh one. Any other labeledhome-<owner>that is not this owner’s managed home, such as one labeledvolume=homefor another user, fails the step with a message naming the mismatched label. - New home. Create
home-<owner>with the profile’sstorageSize(default10Gi) andstorageClassName.
The result is written to status.homePVCName, which ReconcilePod mounts and
the gateway reads for the dashboard, usage and storage views. A replaced home
keeps its owner and managed-by labels, so it stays listed (as orphaned) and
deletable on the storage pages. Adopting a volume for a user whose workspace is
running does not recreate the pod: the pod spec changes, status.restartRequired
becomes true, and the adopted volume is mounted at the next restart. The
administrator procedure is in the
admin guide.
Code-server container
The operator keeps the image’s ENTRYPOINT and sets args to
--bind-addr <host>:8080 --auth none, where <host> is 0.0.0.0, or
127.0.0.1 with mTLS so that only the Envoy sidecar reaches code-server
(mTLS). It injects no environment
variables of its own beyond spec.extraEnv of the profile.
The restrictions in effect for the workspace’s Team, its own
spec.restrictions OR’d with the platform’s PLATFORM_RESTRICTIONS, add
code-server flags: --disable-file-downloads, --disable-file-uploads,
--disable-proxy, --disable-workspace-trust and
--disable-getting-started-override (TeamRestrictions.CodeServerFlags in
operator/api/v1alpha1/restrictions.go). A change to them counts as
configuration drift: running pods are not replaced, and the workspace shows
“restart required”. The other two restrictions, blockAdminIDEAccess and
disableTestEndpoint, are enforced by the gateway (see
Restrictions).
What triggers a reconcile
Each watch has its own filter, so the operator reacts to what matters without reconciling on every status change:
| Source | Filter | Effect |
|---|---|---|
Workspace | spec (generation) or annotation change | Reconcile that workspace |
WorkspaceProfile | spec change | Reconcile every workspace using the profile |
Team | spec change | Reconcile every workspace in the team’s namespace |
SecurityProfile | spec change | Reconcile every workspace of the teams using it |
Pod | deleted, or reached Failed/Succeeded | Reconcile the owning workspace |
A healthy workspace is also reconciled again every 12 hours as a safety net
(DefaultSuccessCheckInterval in operator/cmd/controllers/kornercode/main.go).
PVCs are not watched, so this re-check is the latest point at which a newly
labeled home volume is picked up for a running workspace.
Self-healing and configuration drift
The pod step keeps a workspace running for as long as the Workspace exists:
- Lost pod (deleted by hand, node lost): recreated on the next reconcile, which the pod watch triggers immediately.
- Finished pod (
Failedafter an eviction, orSucceededwhen code-server exits cleanly under theOnFailurerestart policy): deleted and recreated. - Terminating pod: the step waits for it to go before creating the new one.
Every pod carries the annotation code.kornercloud.dev/pod-spec-hash, a
hash of the pod spec the operator built. When the current profile, team,
security profile or operator settings would produce a different spec, the
operator does not recreate the running pod. It sets
status.restartRequired=true instead, and the dashboard shows the user a
banner with a Restart button
(ADR 0008).
A restart is requested by stamping the annotation
code.kornercloud.dev/restart-pod with the UID of the pod to replace. The
gateway sets it; the operator deletes exactly that pod and creates a fresh one
from the current configuration. Because the request names one pod instance, it
is idempotent and cannot restart the replacement.
Lifecycle
A workspace is deleted automatically when it reaches either limit:
- TTL:
creationTimestamp + spec.ttl(or the profile’sdefaultTTL). Users can extend it from the dashboard, up to the profile’s optionalmaxTTL. - Inactivity: no proxied request for
spec.inactivityTimeout(or the profile’sdefaultInactivityTimeout). The gateway records activity instatus.lastActivityTime, at most once a minute per user and replica.
An unset or zero duration means no limit; a value on the Workspace, zero included, replaces the profile’s default. A workspace with neither limit is never deleted automatically nor requeued for it, which is how profiles for long-running work are built (ADR 0013).
Enforcement lives in WorkspaceReconciler.Reconcile, around the step chain:
an expired workspace is deleted before the chain runs, even if a step is
failing, and every other reconcile is requeued no later than the next
deadline (ADR 0009).
Security context
The effective security context is resolved with this priority, highest first: SecurityProfile, then WorkspaceProfile, then operator defaults.
| Level | Operator default |
|---|---|
| Pod | runAsNonRoot: true, user, group and fsGroup 1000, seccomp RuntimeDefault |
| Container | allowPrivilegeEscalation: false, all capabilities dropped |
When the effective pod context sets fsGroup without fsGroupChangePolicy,
the operator adds fsGroupChangePolicy: OnRootMismatch so a large home is not
re-chowned on every start. The defaults run any image built from
codercom/code-server as its coder user; the uid must match the image user.
disableDefaultSecurityContext: true (on either profile) removes every
security context, an escape hatch for images that must start as root. See
pod security.
Team controller
| # | Step | Responsibility |
|---|---|---|
| 1 | ReconcileNamespace | Create the team namespace if needed and merge spec.namespaceLabels / spec.namespaceAnnotations onto it (keys it did not set are never removed) |
| 2 | ReconcileNetworkPolicies | Copy every NetworkPolicy labeled code.kornercloud.dev/managed=true from the operator namespace into the team namespace, keep the copies in sync and remove orphans |
The operator namespace is read from OPERATOR_NAMESPACE (default kornercode).
A Team may not target a system namespace such as kube-system or default.
Admission webhooks
Webhooks are registered automatically when cert-manager is installed (the
operator checks that the cert-manager.io/v1 API is served; any discovery
error other than “not found” is retried and then stops the operator, so a
transient API failure never silently disables them).
| Resource | Validation |
|---|---|
Workspace | Name at most 53 characters (the pod and Service are named workspace-<name>), owner format, profile and team exist, namespace matches the team, test port from 1024 to 65535 and not 8080, owner, team, profile and deletion policy fixed after creation, spec.ttl positive and within the profile’s maxTTL when it sets one. On create, the Secrets, ConfigMaps and PVCs the team mounts must exist. Defaulting sets the deletion policy and the owner label |
Team | Group claim, namespace (valid, not reserved), namespace labels (no reserved prefixes), mount names (valid pod volume names, unique per list), allowed profiles and security profile exist |
WorkspaceProfile | Image and storage size present, test port not 8080, maxTTL positive and at least defaultTTL, which must then be positive, no explicit security context together with disableDefaultSecurityContext |
SecurityProfile | Policy references are valid label values, no explicit security context together with disableDefaultSecurityContext |
Webhooks skip updates that only change metadata (finalizers, annotations) and
updates of objects being deleted, so a resource that predates a rule can
always be cleaned up. The rules live in operator/api/v1alpha1/validation. The gateway
applies the ones that concern what it writes (owner IDs, test ports and TTLs
for workspaces; namespaces, namespace labels and mount names for Teams;
security contexts and policy references for profiles), so admins get the
reason in the API response, also on clusters without the webhooks. Existence
checks, immutability and the mount-target check run only in the webhooks
(ADR 0007).
Observability
- Metrics: controller-runtime metrics and per-resource gauges such as
code_kornercloud_dev_workspace_phaseandcode_kornercloud_dev_workspace_ready, served on--metrics-bind-address. The Helm chart can create a ServiceMonitor. - Events: each step emits
events.k8s.io/v1events on the resource (ReconcilePodSucceeded, …), visible in the dashboard’s Events tab. - Status:
phase, theReadycondition, one condition per step,expiresAt,restartRequired, and theNetworkPolicyDisabledcondition.
Flags and Helm values are listed in the configuration reference.