Skip to main content

Workers, agents and the link

The control plane does not speak Kubernetes. Workspaces run on workers: a cluster, or a namespace of one, with one or more agents installed in it. An agent dials the control plane, keeps a WebSocket open to it, and carries out what the control plane asks of its cluster. Because the agent dials, a worker may sit behind a firewall or NAT; it only needs to reach the control plane's URL.

The chart of the control plane installs one worker in its own cluster, named local. Others are enrolled on the Workers page and installed with the idekube-worker chart; see Workers.

The contract​

The control plane builds messages defined in proto/idekube/worker/v1/ (the link's frames in link.proto, each resource in a file of its own) and an agent hands them to its driver:

message WorkspaceSpec {
string id = 1;
bool running = 2;
string image = 3;
uint32 port = 4;
repeated string command = 5;
repeated string args = 6;
map<string, string> env = 7;
map<string, string> secret_env = 8; // applies at the next start, without a restart
uint32 cpu_m = 9;
uint32 memory_mb = 10;
uint32 shm_mb = 11; // 0 keeps the runtime's /dev/shm
Accelerator accelerator = 12; // class, count; absent without devices
string runtime = 13; // a runtime the worker offers
repeated Mount mounts = 14; // volume_id, path
string health_path = 15; // empty probes the port
string host = 16; // empty disables exposure
map<string, string> labels = 17;
repeated string public_paths = 19; // served without authentication
repeated string networks = 20; // Multus networks the worker offers
string access_token = 21; // drawn at every start; see Workspace access
string sidecar_image = 22; // chosen at start, so upgrades restart nothing
}

message VolumeSpec {
string id = 1;
uint64 size_mb = 2;
string class = 3; // a volume class the worker offers
}

message Observation {
Phase phase = 1; // PENDING, READY, STOPPED, FAILED, ABSENT
string message = 2;
}

Workspaces and volumes are resources of a kind, workspace and volume, named by an Object {kind, id}. A driver implements two idempotent methods (worker.Driver):

MethodReturns
apply(Apply)What it observes after acting; the spec, a WorkspaceSpec or a VolumeSpec, tells the kind. Never ABSENT.
delete(Object)ABSENT once nothing is left.

The caller converges by calling again until the observation is the one it wants. This is exactly what the reconciler does: on the control plane, the driver of a worker is the link to one of its agents that applies resources of the kind, and the agent runs the Kubernetes driver.

The module that owns a kind's rows tells the worker module about them (Workers.Resource): it makes rows due when their objects change, names the ids it has no row for, forgets a removed worker's rows, and says what each worker holds, which placement weighs. The worker module reads no table of theirs.

worker/link carries one protobuf Frame per WebSocket binary message, in both directions. A request carries an id; its reply carries reply_to with either a body or an error. A notice carries neither and is not answered. A body a peer does not know is answered with an error at once, so that the caller does not wait for its deadline; so is a command holding a field the agent does not know, which it does not half apply. An error carries a code besides its message: UNSUPPORTED (an agent of a release that does not know the request) and INVALID (a request that cannot be served as it stands) will not pass by asking again, TIMEOUT, BUSY (the peer serves as many requests as it may at once) and anything else may. The control plane logs the message, which is the peer's, and shows the code: worker_outdated, worker_error or worker_unreachable.

FrameFromMeaning
Hello → ConfigureagentFirst request: the agent's version and protocol, which instance it is (its pod's UID) and when its process started, the kinds of resources it applies, and the domain and scheme its workspaces are served on. The answer is the worker's settings and its id, which the objects the agent makes carry.
Configurecontrol planeThe worker's settings, the installation's id and epoch, or whether the worker is in maintenance, changed; sent at most every 30 seconds.
MaintenanceagentWhy the agent holds its cluster as it is, or that it does not; sent on every link and whenever it changes.
HealthagentWhy the agent does not serve workspaces, if it does not, and when it last sent a snapshot; once on every link and whenever that changes. Whether the agent is alive is told by the link's pings.
LogsagentWhat the agent logged at INFO and above since it last said, every ten seconds; it keeps 500 lines at most while the link is down.
Resume → emptycontrol planeAn administrator resumed the worker: the agent leaves maintenance and takes the epoch given as the one it saw last.
Command → Observationcontrol planeOne driver call. An apply carries the generation of the row it is of, which the objects carry too.
Sidecar → SidecarConfigagentWhat a workspace's sidecar serves, asked on its behalf.
Revisionscontrol planeThe revision of what each running workspace's sidecar serves, sent when it changes.
Authorize → AuthorizedagentWhether a request to a workspace may pass, for the gateway.
ActivityagentBytes the gateway passed to and from each workspace in the last half a minute.
InventoryagentWhat the ready, schedulable nodes that workspaces may run on can allocate, those the worker's node selector picks and whose taints workspaces or a device class tolerate: CPU and memory in all and on the largest such node, devices per accelerator class, storage and runtime classes, and those storage classes that do not let a claim grow. A workspace larger than the largest node is not placed on the worker. Looked at every minute, sent on connect and whenever it changes, and every ten minutes besides, which tells it is still so.
ChangedagentResources whose objects changed in the cluster. Their rows are made due, so that the reconciler looks at them now rather than at its next visit.
Statuses → OrphansagentA snapshot of all the cluster holds, in pages of 2,000 resources: for each, the generation its objects were applied from and how they fare, with, on the last page, how many objects agents of other workers made. Sent right after Hello, and every ten minutes when the brief one finds a change; see catching up.
Digest → DigestedagentA snapshot in brief, every ten minutes: how many resources and a hash of each one's kind, id, generation and phase (worker.Digest).
  • Authentication. The agent sends its worker's token as a bearer token on the upgrade request to GET /v1/workers/connect. Tokens start with idkw_; the control plane keeps their SHA-256 digest.
  • Liveness. Each end pings every 20 seconds and closes a link whose pong does not come within 10 seconds. The agent reconnects with a jittered backoff from one to 30 seconds. Reading never waits: a request beyond the 64 a peer serves at once is answered BUSY, and notices are queued and served one at a time, in the order they were sent.
  • Versions. A control plane speaks every protocol from that of the previous release to its own (link.Oldest to link.Protocol), and refuses others with UNSUPPORTED, saying which it speaks. Upgrade the control plane first, then the agents, within a release of each other: an agent of the previous release keeps working meanwhile. The protocol is the link itself, how frames are framed and answered, and rarely changes.
  • Features. What an agent does besides applying its kinds it lists when it connects, each at a version: gang.v1, mount.read_only.v1, volume.shared.v1, volume.existing.v1, volume.clone.v1, sidecar.mtls.v1. A resource that needs one goes to an agent of its worker that lists it, and fails as worker_outdated where none does; a new workspace or cluster that needs one is not placed on a worker whose connected agents lack it. A feature that changes past what the other end can ignore takes its next version, which an agent lists beside the earlier ones for as long as it still does those, so features change one at a time and the protocol not at all. Besides, a command holding a field an agent does not know is refused rather than half applied, and a resource of a kind no connected agent applies fails as worker_outdated too. An agent's features are in GET /v1/workers/{id}.

A volume cloned from another (VolumeSpec.clone_of) is filled by a Job, clone-<id>, owned by its claim, that mounts the source claim read-only and the new one and runs idekube-sidecar copy from the sidecar's image as the sidecar's user. The volume is pending while the Job runs and failed when it gives up; once it succeeds the claim is annotated idekube.io/cloned and the Job is deleted. A source claim of a class that is not ReadWriteMany and that a workspace on another node mounts holds the Job back until that workspace stops.

  • Ahead of its features. The contract already holds what two features to come need of it, so that the releases that bring them change no frame the others send: Usage, which the leading agent will send every minute with what each running workspace, mounted volume and node used (feature usage.v1), and a volume's transfer, which moves all it holds to the object store or back, with TransferTarget for a worker to ask where (feature volume.transfer.v1). No agent lists either yet, so nothing sends the first, and a volume applied with the second fails as worker_outdated.
  • Commands time out after 30 seconds. A request carries how long its caller waits, which bounds how long it is served, and a caller that gives up sends a frame that stops it; the agent does not start a command whose caller already gave up, which may have been overtaken. Commands are also cancelled when the link ends, so that none outlives the link it came on.

Catching up​

Changes are pushed as they happen, but a link that is down misses them, and a notice queued when a link ends is lost. Rather than replaying them, the agent sends a snapshot on every link and every ten minutes, built from its informers' caches, and the control plane compares it with the rows of the worker. Only the rows that differ are made due: those whose objects are missing, were applied from another generation, or fare otherwise than the row says, e.g. a pod that crashed while the link was down. A running workspace is therefore not applied again on a timer; after a control plane restart, the commands sent are as many as the resources that differ, not as many as the worker holds.

Every ten minutes the agent first sends the snapshot in brief. The control plane keeps, for each link, the brief of its last whole snapshot and a hash of the rows it was compared with, as the comparison left them; when both are the same, comparing again would find the same, and it answers so, with the orphans that snapshot found. Otherwise, or when a control plane of an earlier release does not know the frame, the agent sends the whole. Both ends compress frames of 512 bytes or more (permessage-deflate, each on its own); idekube_link_frames_total and idekube_link_frame_bytes_total count, on either end, what each kind of frame costs.

The answer to the last page names the resources the control plane has no row for. The agent removes what a workspace without a row left behind once it was an orphan for ten minutes, over two snapshots at least, so that a row still being created, or lost to a mistake soon undone, is spared; it only counts a volume's claim and never removes one. Objects carry the id of the worker whose agent made them: another worker's objects, in a namespace two workers share, are neither reported nor removed.

Several replicas, several agents​

An agent's link ends on one API server replica. That replica holds the worker in its registry, and only it reconciles the worker's rows: each replica claims the due rows of the workers it holds and leaves the others to the replicas that hold them (see Reconciliation). A worker may run several agents, each connected to whichever replica the load balancer picked; commands are idempotent, so the replicas holding the same worker need no coordination.

The worker chart runs two agents, on different nodes when it can, behind a disruption budget that keeps one, and rolls a new release out before it stops an old one: the worker's gateway never pauses for a restart, an upgrade or a drain. Both serve the gateway and take commands; one of them, elected with a Lease, alone removes orphans, checks the network, reports the inventory and configures sidecars, which the other would only repeat.

Every replica checks its links every 30 seconds: it marks their workers as seen, sends settings that changed, and closes the link of an agent whose token was rotated or whose worker was removed. A worker none of whose agents was seen for 90 seconds is offline. When a replica shuts down, it closes its links with going away and the agents reconnect to another one.

Settings​

A worker's settings are the worker settings section, with the worker's own overrides replacing top-level fields. The control plane sends them to the agent, which builds the cluster objects from them. What a worker serves on (its domain, scheme and namespace) is set where the worker is installed, and its agents report it in Hello.

What a workspace becomes​

worker/kubernetes/manifests.go is a pure function from a spec and the worker's settings to Kubernetes objects. Only a running workspace has any: a stopped one keeps nothing in the cluster but its volumes, so the number of objects grows with what runs, not with how many workspaces exist. For a running workspace with id abc:

ObjectNameNotes
StatefulSetws-abc1 replica, whose pod ws-abc-0 keeps its name: the controller never starts a new pod while the old one exists, even one being evicted or on a lost node, so that no two pods ever mount a ReadWriteOnce volume. Its update strategy is OnDelete; the driver changes it only through zero (see below). Its annotations tell the gateway how to serve it: idekube.io/host, idekube.io/port, idekube.io/public-paths and idekube.io/access-token. They are on the StatefulSet rather than its pod template, so that changing them restarts nothing. idekube.io/spec is the digest of the spec it was applied from: while it matches, the agent leaves the pod as it is, so that the worker's settings and the agent's own release apply from the next start. idekube.io/generation and the label idekube.io/worker say which generation of the row and which worker it was applied for.
Servicews-abcOnly for a member of a gang (spec.gang): headless, publishing addresses of pods that are not ready yet, and owned by the StatefulSet, which takes it along. The other members reach the pod as ws-abc-0.ws-abc (worker.MemberHost).
Secretws-abc-tlsPer-workspace mTLS material (ca.crt, tls.crt, tls.key) owned by the StatefulSet and mounted read-only at /etc/idekube/tls into the idekube sidecar container alone — never into the workspace container. Excluded from idekube.io/spec so certificate rotation updates the Secret in place without restarting the pod.
NetworkPolicyws-abcAlways applied whenever the agent knows its own namespace and pod labels: restricts sidecar ports 7070 and 7071 exclusively to the worker's agent pods, even when workspace network isolation is off, and carves 7070 and 7071 out of every non-agent ingress rule when isolation is on.

Otherwise there is no Service or Ingress per workspace: the worker's gateway routes each workspace's host to its pod's address, and what may change while it runs comes from its sidecar.

A volume with id xyz becomes a PersistentVolumeClaim vol-xyz, in the StorageClass its volume class names.

The pod has a container named workspace, and the sidecar idekube next to it. The workspace container has:

  • the image, rewritten through worker.registry_mirrors;
  • CPU and memory limits from the workspace, and requests that are the limits divided by worker.cpu_overcommit and worker.memory_overcommit;
  • devices as a limit on the extended resource of their class in worker.accelerators, with the class's node selector, tolerations and RuntimeClass;
  • the template's runtime as the RuntimeClass, when it names one;
  • the template's networks in the k8s.v1.cni.cncf.io/networks annotation of the pod, for Multus (reserved, not yet tested);
  • an HTTP readiness probe on the template's health path, or a TCP probe on the port when it has none;
  • the template's environment, and IDEKUBE_ACCESS_TOKEN, which a template cannot set;
  • the sidecar's directory /run/idekube, read-only, and the startup hook mounted from it at /etc/idekube/startup.bash/50-idekube.sh; /run/idekube-tasks, where its tasks write;
  • one mount per mounted volume, read-only when the mount is, in the sidecar as well; and a memory-backed /dev/shm of the template's size when it sets one;
  • no service account token and no service links.

Objects are labelled app.kubernetes.io/managed-by: idekube, plus idekube.io/workspace: <id> and idekube.io/team: <team id> for workspace objects and idekube.io/volume: <id> for claims. A claim is ReadWriteMany for a shared volume (VolumeSpec.shared) and ReadWriteOnce otherwise.

Gangs​

Workspaces that are scheduled all at once or not at all, such as the nodes of a cluster, share a gang (WorkspaceSpec.gang: its name, size and the member's rank). A member's pod carries the label idekube.io/gang, the annotation idekube.io/gang-size and the scheduling gate idekube.io/gang, which keeps the scheduler from placing it. The leading agent lets the pods of a gang go once all of them exist, whenever pods change and every minute besides, never in maintenance, as a routine of the driver's gang feature (worker.Routine: what a feature has the leading agent do on its own, which the agent runs without knowing what it is); a member made again later, after its node failed, finds the others there and goes at once. A gang grows and shrinks without its members restarting: its size is left out of the digest that decides whether a pod is made anew, as the network rules are, and the gated pods, the latest, say how many members it has now, so that those added go together while those that run predate the change. A gated pod reports that it waits for the rest of its group.

The control plane admits a gang whole, against the room its worker reports, and stops it whole when its members do not all run in time: Kubernetes' own gang scheduling is still alpha. Gangs, read-only mounts and shared volumes are features: an agent that lists none of them is sent none, and the rows that ask for them fail as worker_outdated until it is upgraded.

The sidecar​

Every workspace pod runs the sidecar idekube as a native sidecar container: an init container with restartPolicy: Always, which needs Kubernetes 1.29 or later. It starts before the workspace and lives as long as the pod. It runs as the workspace's user (worker.sidecar.run_as_user), without privileges. It makes no request of its own: its worker's agent configures it, and what it may do reaches no further than its workspace.

  1. What it is sent. The control plane answers with the workspace's variables, the SSH keys of its creator (when the template serves SSH and the creator's account is active and may still open the workspace), git credentials, the template's tasks, the steps that put files in place, and the SSH client's key and peers (the other nodes of its cluster), with a revision. A revision is a database sequence value, raised by triggers whenever variables, SSH keys, team membership or the creator's account change, so that no code path can forget it. Each control-plane replica reads a digest of the revisions of its workers' running workspaces every three seconds, their count and sum, which a partial index answers; it reads them all only when the digest changed, or five minutes passed, and sends them to the agents when they changed.
  2. Who configures it. The agent, as soon as its informers see the sidecar's container run, and whenever a revision changes: it asks the sidecar which revision it holds and sends the configuration only when that is older. Each worker has its own control-plane-managed ECDSA P-256 CA (whose private key is sealed in PostgreSQL); the control plane delivers a short-lived client certificate and CA bundle to agents in Configure, and a per-workspace server certificate (ws-<id>.idekube.internal) in WorkspaceSpec.sidecar_tls. The sidecar serves /agent/v1/ exclusively on port 7071 over TLS 1.2+ with RequireAndVerifyClientCert (hot-reloading certificates from /etc/idekube/tls on disk) and additionally checks the workspace's sidecar token (Bearer), drawn at every start like the access token and given to the sidecar container alone. Pre-upgrade running pods without mTLS fall back to port 7070 until restarted. The sidecar keeps a newer revision over an older one, and its directory outlives its own restarts. A restarted agent asks every sidecar and sends only what changed. In maintenance a sidecar that holds a configuration keeps it.
  3. What it writes. In /run/idekube: env.sh for shells, environment for PAM, two supervisord sections, ssh/authorized_keys, ssh/id_idekube, ssh/config and ssh/hosts for reaching its peers, git/credentials, tasks.sh and, last, revision. Each file is replaced whole. The startup probe passes once the first configuration is written, or after 20 seconds, so that a workspace starts even when the control plane is out of reach; its tasks then wait for the configuration.
  4. What it serves. On port 7070 the sidecar serves GET /healthz for kubelet's startup probe and /.idekube/ (the files of the workspace's volumes, which it mounts at the same paths, and the state of its tasks and their output) to the platform's pages, idk and the MCP server through the gateway; see Workspace access. Its API is described in backend/sidecar.openapi.json. /agent/v1/ is served exclusively on port 7071 over mTLS (never on port 7070 once mTLS is active).
  5. The hook. The image's startup.sh runs 50-idekube.sh as root before it starts supervisord. It gives services the variables through a [supervisord] environment section (in the escaping of the installed release: up to 4.3 the setting is expanded twice and split without escapes), makes login and interactive shells source env.sh, adds the environment file to the PAM session of sshd, has sshd ask idekube-keys for the user's keys at every login (AuthorizedKeysCommand, which answers only for the workspace's user), and adds a supervisord program that runs the tasks as the user once the configuration is written. Tasks append to their logs, which the sidecar rotates past 4 MiB, keeping one older part, so that a chatty task cannot fill its directory and have the pod evicted. /run/idekube is read-only in the workspace.

The gateway​

An agent's pod also runs Envoy, configured by the agent through xDS (worker/gateway). Listener, TLS and filters are static, in the bootstrap the worker chart renders; the agent serves the routes and the upstream clusters, and answers Envoy's authorization checks. Both talk over 127.0.0.1 inside the pod, and Envoy's admin interface listens there too, so that nothing outside the pod can read the routes and the access tokens in them.

From its informers, the agent knows each workspace's StatefulSet and ready pod. Every running workspace with a ready pod becomes a virtual host for its host name, routing to the pod's address; public paths are routes of their own without authorization. Any other host falls through to a route that only the authorization filter answers. The configuration's version is a hash of the routes, so that every agent of a worker serves the same one, and Envoy keeps serving the last one while its agent restarts. Envoy takes it incrementally (delta xDS): a workspace that starts or stops sends it that change alone. It keeps only the statistics the agent reads, each workspace's traffic, and its own, as a worker may run thousands of workspaces of two clusters each.

The Kubernetes driver​

worker/kubernetes applies those objects with server-side apply under the field manager idekube, forcing conflicts. A workspace's pod is never replaced in place: when its spec changes, the driver scales its StatefulSet to zero, waits until the cluster holds no pod of the workspace, read from the API server rather than the informers, and only then applies the new spec at one replica. A stopped workspace goes to zero the same way, then its StatefulSet is deleted; its claims stay. A Deployment an earlier release ran a workspace as is removed like a previous pod.

Whenever the agent knows its own namespace and pod labels (IDEKUBE_AGENT_NAMESPACE and IDEKUBE_AGENT_LABELS, which the chart sets), every workspace gets a NetworkPolicy ws-<id>, applied before the StatefulSet so that no pod runs without it, and deleted once the workspace's pods are gone. Without workspace network rules, the policy restricts only ingress so TCP ports 7070 and 7071 (the sidecar listeners) are reachable solely from the agent's pods while all other TCP/UDP ports (1-7069 and 7072-65535) remain open. With a network spec, ingress always admits the agent's pods and carves 7070 and 7071 out of every non-agent ingress rule; egress always lets the workspace reach the agent's pods and the cluster's DNS servers on port 53, the pods and addresses worker.dns names, and no other host on that port, which would carry whatever a workspace tunnels through it; the spec's rules come on top. Without IDEKUBE_AGENT_NAMESPACE and IDEKUBE_AGENT_LABELS, a spec with a network is FAILED.

At start and every hour, or five minutes after a check that could not tell, the agent checks whether the cluster enforces network policies: it runs a Deployment idekube-netcheck-<agent> of the sidecar's image in probe mode, connects to its pod, gives it a NetworkPolicy that admits nothing and sees whether its connections stop. It reports enforced, unenforced or unknown with a reason in its inventory, and removes the objects; those an agent left behind when it died are removed by the next check after a quarter of an hour. Inventory reports carry the time the agent took them, and a report older than the one kept is dropped, since the control plane serves frames concurrently. A spec asking for a device class, runtime, network or volume class the worker's settings do not offer is FAILED without touching the cluster.

It reports:

ObservationWhen
READYThe StatefulSet runs the current spec and has a ready replica.
STOPPEDThe workspace should not run, and its StatefulSet and pods are gone.
PENDINGAnything still converging. The message carries the scheduler's reason when the pod cannot be scheduled.
FAILEDA container, the sidecar among them, waits with ImagePullBackOff, ErrImagePull, InvalidImageName, CrashLoopBackOff, CreateContainerConfigError or RunContainerError; the cluster rejected the object itself (HTTP 400, 403 or 422); or a claim is Lost.
ABSENTAfter a delete, once the StatefulSet and its pods, or the claim, are gone.

Other cluster errors are raised, shown as the status message and retried by the reconciler. The driver watches StatefulSets, pods, claims and network policies labelled app.kubernetes.io/managed-by: idekube with informers and reports every change as Changed.

Credentials. The agent uses its pod's service account inside a cluster and falls back to the local kubeconfig otherwise (make agent.run). Workspaces run in <release>-workspaces unless the chart names another namespace.

Permissions. The idekube-worker chart binds the agent's service account to a Role in the workspaces namespace that covers exactly these objects: StatefulSets, Deployments (for the network check), PersistentVolumeClaims and NetworkPolicies (get, list, watch, create, patch, delete), Secrets (get, list, watch, create, update, patch, delete — for per-workspace sidecar mTLS certificates), Pods (get, list, watch, and patch to let a gang's go), Services (get, create, patch, for the names the members of a gang reach each other by) and Jobs (get, create, patch, delete, for volume clones). A ClusterRole lets it list nodes, StorageClasses and RuntimeClasses for its inventory; without it, the agent reports an empty inventory and works all the same. The API server has no Kubernetes permission at all.