Skip to content

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).

PathContents
operator/api/v1alpha1CRD types, labels and annotations shared with the gateway
operator/cmd/controllers/kornercodeEntry point: manager, controllers, webhooks, metrics, events
operator/internal/controllers/v1alpha1/workspaceWorkspace reconciler, watches, apply/delete steps, helpers
operator/internal/controllers/v1alpha1/teamTeam reconciler: namespace and NetworkPolicy propagation
operator/internal/webhook/v1alpha1Validating and mutating admission webhooks
config/helmHelm chart (operator and gateway), generated CRDs and RBAC
operator/api/v1alpha1/validationValidation 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 becomes True and the chain moves on.
  • Requeue(after, message): the condition is False; the chain stops and resumes at this step after the delay.
  • Fail(...): the resource goes to Failed and 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

#StepConditionResponsibility
1ReconcilePVCPVCReconciledResolve the owner’s single home volume (adopt a restored one, reuse or create home-<owner>) and record it in status.homePVCName (see below)
2ReconcileServiceAccountServiceAccountReconciledEnsure the namespace’s workspace service account exists
3ReconcileCertificateCertificateReconciledWith mTLS: request the workspace certificate and render the Envoy configuration; otherwise a no-op
4ReconcilePodPodReconciledCreate the pod with status.homePVCName at /home/coder, replace it when it is lost or finished, detect configuration drift (see below)
5ReconcileServiceServiceReconciledExpose code-server and the test port
6ReconcileNetworkPolicyNetworkPolicyReconciledKeep the pod’s NetworkPolicy labels in line with the security profile
7ReconcileLifecycleLifecycleReconciledMaintain 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:

LabelValueSet by
code.kornercloud.dev/ownerowner ID (lowercased Keycloak sub)operator
code.kornercloud.dev/managed-bykornercode-operatoroperator
code.kornercloud.dev/volumehome, or replaced-home for a home that an adopted volume supersededoperator
code.kornercloud.dev/home-forowner IDadministrator, 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:

  1. Adoption. A PVC in the namespace labeled home-for=<owner> (the label value is compared in lowercase). The operator adds whichever of owner, managed-by and volume=home it lacks, relabels every other home of the owner volume=replaced-home, and emits a Normal event HomeVolumeAdopted on the Workspace naming the adopted volume and any home it replaced. This holds even when the volume already carries volume=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 an owner label for someone else; it never relabels such a volume. The admin guide therefore has administrators remove a stale owner label before labeling a volume. Size and storage class stay as restored; the profile’s storageSize does not apply. The home-for label stays on the PVC.
  2. Managed home. The PVC labeled owner=<owner>, managed-by and volume=home. More than one is a failure with a Warning event.
  3. Legacy home. A home-<owner> PVC without a volume label, created before homes were labeled: the operator adds the labels and uses it, unless its owner or home-for label names another user, which fails the step. If home-<owner> is labeled volume=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 labeled home-<owner> that is not this owner’s managed home, such as one labeled volume=home for another user, fails the step with a message naming the mismatched label.
  4. New home. Create home-<owner> with the profile’s storageSize (default 10Gi) and storageClassName.

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:

SourceFilterEffect
Workspacespec (generation) or annotation changeReconcile that workspace
WorkspaceProfilespec changeReconcile every workspace using the profile
Teamspec changeReconcile every workspace in the team’s namespace
SecurityProfilespec changeReconcile every workspace of the teams using it
Poddeleted, or reached Failed/SucceededReconcile 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 (Failed after an eviction, or Succeeded when code-server exits cleanly under the OnFailure restart 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’s defaultTTL). Users can extend it from the dashboard, up to the profile’s optional maxTTL.
  • Inactivity: no proxied request for spec.inactivityTimeout (or the profile’s defaultInactivityTimeout). The gateway records activity in status.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.

LevelOperator default
PodrunAsNonRoot: true, user, group and fsGroup 1000, seccomp RuntimeDefault
ContainerallowPrivilegeEscalation: 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

#StepResponsibility
1ReconcileNamespaceCreate the team namespace if needed and merge spec.namespaceLabels / spec.namespaceAnnotations onto it (keys it did not set are never removed)
2ReconcileNetworkPoliciesCopy 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).

ResourceValidation
WorkspaceName 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
TeamGroup 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
WorkspaceProfileImage 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
SecurityProfilePolicy 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_phase and code_kornercloud_dev_workspace_ready, served on --metrics-bind-address. The Helm chart can create a ServiceMonitor.
  • Events: each step emits events.k8s.io/v1 events on the resource (ReconcilePodSucceeded, …), visible in the dashboard’s Events tab.
  • Status: phase, the Ready condition, one condition per step, expiresAt, restartRequired, and the NetworkPolicyDisabled condition.

Flags and Helm values are listed in the configuration reference.