Skip to content

The control service

This page is for a contributor who must change internal/join or the module control/. It tells you how the control service and the join of a daemon work. After you read it, you know how a request gets to the correct daemon, what the SQLite file records, and what a failure does.

The control service puts many daemons behind one address, so a client uses one URL and one API key for all of them. A daemon that joins opens the connections itself and does not listen for the control service. The page clusters.md tells a user how to set it up. The page decisions.md gives the reasons in decisions 17 and 18.

  • A daemon keeps 4 idle connections open to the control service. Each connection carries exactly one request and its answer, and then it closes.
  • The join token makes a connection trusted. The control service keeps the SHA-256 of the token with each connection and checks it before each use.
  • The SQLite file records the clusters and the cluster of each sandbox, snapshot and pool. The first cluster that has an id in the file keeps it.
  • The router places a create with place and sends each other request to the cluster of its object. A list goes to each cluster at the same time.
  • If a cluster has no idle connection, a request waits for a maximum of --wait, 30 seconds by default, and then gets cluster_unavailable.
Part Source Function
Join, the half of the daemon internal/join/dial.go Serve keeps idle connections open to the control service and serves one request on each.
Join, the half of the control service internal/join/hub.go Hub takes the connections of the daemons. Hub.Transport gives an http.RoundTripper that sends each request on one of them.
The protocol internal/join/join.go Hello, GPU, the name rules and the label rules.
The join flags internal/join/flags.go AddFlags and Flags.Config for boxfork serve and boxfork-testserver.
The SQLite file control/internal/store/store.go Store: the clusters and the cluster of each object.
The selection of a cluster control/internal/router/place.go place: the clusters that can take a new object, in sequence.
The HTTP API of the control service control/internal/router/router.go, tools.go Server.Handler: each route of the API.
The binary control/cmd/boxfork-control/main.go serve, token, forget, version.

The package internal/join uses only the standard library, so the daemon stays without dependencies. The module control/ uses modernc.org/sqlite, a SQLite driver in pure Go, so the build needs no C compiler. It also imports packages of boxfork/internal. Go permits this, because boxfork/control is below boxfork.

A daemon that joins opens connections to the control service. It does not listen for the control service. Each connection carries exactly one request and its answer. Then the two ends close it.

Open the diagram at full size

The daemon writes an HTTP/1.1 request on a new TCP or TLS connection:

Item Value
Request line GET /v1/join below the path of --join
Connection Upgrade
Upgrade boxfork-join/1
Authorization Bearer and the join token
X-Boxfork-Hello The Hello as JSON, in base64url without padding

The Hello has these fields:

Field Meaning
cluster The name of the cluster. 1 to 63 lower-case letters, digits and -.
labels The labels of the cluster. A key has 1 to 63 of A-Z a-z 0-9 . / - _. A value has 0 to 63 of A-Z a-z 0-9 . - _.
version The version of the daemon.
gpus Each GPU: name, memory_mb, and free. A GPU is free if no sandbox holds it and the GPU allocator does not mark it busy or missing.

The daemon reads the GPUs again only if its last read is older than 5 seconds. Each new connection thus does not ask the GPU allocator.

The control service answers in one of these ways:

Answer Cause
101 Switching Protocols with Upgrade: boxfork-join/1 The token is the token of the cluster. The connection is now idle at the control service.
400 with the code invalid_request The request is not a join request, or the Hello is wrong.
401 with the code unauthorized The cluster is not known, or the token is not its token, or the labels of the Hello are not the labels that boxfork-control token --label gave.

The daemon logs a refusal and tries again. The wait between two tries starts at 250 ms and doubles to a maximum of 5 seconds. The daemon logs the same error only one time, to keep its log short. It logs again when the error changes or when the join works. It also logs the first join that works, so that the log tells a person that the daemon joined.

After the 101, the daemon gives the connection to an http.Server through a net.Listener of its own. That server has keep-alives off. Thus it serves exactly one request on the connection and then closes it. The handler is api.Server.TrustedHandler: the normal routes without the check of the API key. The join token made the connection trusted.

The daemon keeps 4 idle connections (DefaultIdle). When the control service uses one, the daemon opens a new one.

This design has these properties:

  • A streamed command, a large file and an upgraded connection go through as on a direct connection. Each request has a TCP connection of its own.
  • A slow request does not stop other requests. No two requests share a connection.
  • The cost is one TCP connection, and one TLS handshake with https, for each request. The daemon opens the replacement after the request starts. A burst of more than 4 requests at one time waits for new connections.

Hub.Accept takes the connection from the http.Server of the control service (http.Hijacker) and writes the 101. Hub.add puts it in the idle list of its cluster.

While a connection is idle, a goroutine (watch) reads one byte from it. A daemon sends nothing on an idle connection. Thus the read ends only when the daemon closes the connection. Then watch removes the connection from the list.

To use a connection, take sets a read deadline in the past. The read of watch stops with a timeout and no byte. watch then gives the connection to take. A timeout on a tls.Conn does not break the connection, so this also works with TLS.

Hub.Transport returns an http.RoundTripper around an http.Transport whose DialContext calls take. The host of the URL is the name of the cluster, for example http://gpu-eu/v1/sandboxes. The transport has keep-alives off and does not ask for compression. Thus it does not keep a used connection.

The hub keeps the SHA-256 of the join token with each connection. Before take uses a connection, it calls Hub.Valid. The router sets Valid to compare the hash with the hash in the file (Store.IsToken).

After boxfork-control token makes a new token, or after forget, the hashes are different. Then take closes the connection and uses a different one. Sweep calls Hub.Prune every 5 minutes. Prune closes each idle connection that Valid refuses.

If a cluster has no idle connection, take waits until a connection comes or until the end of the wait. The wait is --wait of boxfork-control serve, 30 seconds by default. A list waits 3 seconds for each cluster.

The wait starts at the earlier of two times: the start of the request, and the time when the cluster lost its last connection. Thus a request for a cluster that is away for a long time fails at once with cluster_unavailable. After a restart of the control service, the second time is the start of the process. Thus a request just after a restart waits for the daemons to connect again.

The wait stops when the client of the request closes its connection. http.Transport dials with a context that the end of the request does not cancel, because a later request can use the connection. Thus the RoundTripper puts the context of the request into the context of the dial as a value, and take obeys it. Without this, a request that ended can take the next connection. The transport then closes that connection without a request, and the daemon waits before it opens a new one.

The file is control.db in the data directory. The store opens it with WAL, a busy timeout of 10 seconds and foreign keys on. The store uses one connection. Thus the writes of one process wait in a queue in Go, not in SQLite.

CREATE TABLE clusters (
name TEXT PRIMARY KEY,
token_hash BLOB NOT NULL, -- SHA-256 of the join token
permitted TEXT, -- JSON, from token --label; NULL: all labels
labels TEXT NOT NULL DEFAULT '{}', -- JSON, from the last Hello
gpus TEXT NOT NULL DEFAULT '[]', -- JSON, from the last Hello
version TEXT NOT NULL DEFAULT '',
last_seen INTEGER NOT NULL DEFAULT 0 -- milliseconds; 0: never joined
);
CREATE TABLE objects (
kind TEXT NOT NULL, -- sandbox, snapshot, pool or volume
id TEXT NOT NULL, -- the id; the name for a volume
cluster TEXT NOT NULL REFERENCES clusters(name) ON DELETE CASCADE,
seen_at INTEGER NOT NULL,
PRIMARY KEY (kind, id, cluster)
);

Each write gives the same rows if it occurs two times. Thus a retry after a crash is safe.

Method Function
SetToken Add a cluster, or replace its token and its permitted labels. The labels and the GPUs of the last Hello stay.
CheckToken Compare the hash of a token with the hash in the file, in constant time. An unknown name takes the same time.
IsToken Compare a hash with the hash in the file. Hub.Valid calls it before each request.
Seen Write the Hello of a cluster and the time. The control service calls it for each new connection. If the token permits only some labels, and the Hello has different labels, Seen gives ErrLabels and writes nothing.
Put Record that an object is in a cluster. A sandbox, a snapshot or a pool is in one cluster only: the first cluster that has the id keeps it. Put for a different cluster gives ErrClaimed. A volume name can be in more than one cluster, because each daemon can have a default volume with the same name.
Owners The clusters of an object. The cluster that showed it last comes first.
Drop Forget that an object is in a cluster.
Reconcile Make the file agree with a full list from one cluster. See below.
Forget Remove a cluster. The foreign key removes its objects.

Reconcile gets the time when the control service asked for the list. It records each object of the list. It forgets each other object of that cluster that it recorded before that time. Thus an object that a create recorded while the list was on its way stays in the file. It does not record an id that a different cluster has in the file. It returns these ids, and the router writes them to the log.

A cluster can be wrong, or an attacker can control it. Such a cluster can say that it has the object of a different cluster. If the control service believes it, that cluster can get the commands, the files and the kill of the object. Thus the control service obeys these rules for a sandbox, a snapshot and a pool:

  • The first cluster that has an id in the file keeps it. A list, a fork, a snapshot or a create of a different cluster does not change that record.
  • owner records an object that the file does not have only if all clusters answered and exactly one cluster has the object.
  • If two or more clusters say that they have the object, the answer is 409 with the code cluster_conflict. The request goes to no cluster.
  • If two clusters list an id that the file does not have, the file does not record it.

The router writes each refused claim to the log as a warning.

The router is router.Server. It speaks the HTTP API of the daemon, with the API key of the control service. It removes the headers Authorization and X-API-Key before it sends a request to a daemon.

  1. readBody reads the JSON body as a map of fields. Thus a field that the control service does not know goes to the daemon unchanged. The daemon finds the name of a field in all cases of letters, for example Placement. readBody does the same for the fields that the control service reads. A body with two names for one field, for example placement and Placement, gets invalid_request.
  2. takePlacement removes placement from the body. Thus a daemon of an earlier version, which refuses unknown fields, also takes the request.
  3. need finds the cluster of the snapshot, if the body has one. volumeOwners finds the clusters of the volumes.
  4. place gives the clusters that can take the object, in sequence. ../clusters.md gives the rules.
  5. tryEach sends the request to the first cluster. If that cluster does not connect in the wait, or answers gpu_unavailable, it tries the next one.
  6. When a daemon answers 201, put records the new object in the file. Then the router sends the answer to the client.

If the client closed its connection before step 6, unheard kills the new sandbox. No client knows its id. A daemon does the same for a direct client.

A fork and a snapshot go to the cluster of the sandbox (onSandbox). The router records the new sandboxes and the snapshot in that cluster.

A daemon changes the size of a pool that exists for the same start and shape, and makes no second pool. Thus createPool asks each cluster for its pools first. poolFirst puts first the cluster that has a pool with each field of the shape that the request gives. A field that the request does not give is the default of the daemon. The control service does not know that default, so all values agree with it.

owner reads the cluster of the object from the file. If the file does not have the object, owner asks each cluster for it and records the cluster that has it. See “One cluster for each id”. That is the case for a sandbox that a client made directly on a daemon, or for a record that the file lost.

forward then sends the request with httputil.ReverseProxy through Hub.Transport. FlushInterval is -1: each piece of a streamed answer goes to the client at once. If the daemon answers that the object does not exist, forgetGone removes the record.

gather sends the same request to each cluster that joined, all at the same time, with the list wait of 3 seconds. It calls Reconcile for each answer. The router sorts the merged list by created_at, as a daemon sorts its own list. A cluster that did not answer is in the field unreachable.

Sweep calls gather for each kind of object every 5 minutes. Thus the file forgets a sandbox whose timeout ended, also if no client asks for it.

The router does not do a tool call itself. It sends the call to a daemon, which does it as for a direct client:

  • sandbox_list and gpu_list go to each cluster. The router joins the texts and the data.
  • sandbox_create goes to a cluster by place, with the GPUs and the snapshot of the arguments.
  • Each other tool goes to the cluster of its sandbox_id. A call without a sandbox_id, or with an unknown one, goes to a connected cluster, which answers with the error text for the model.

The router records the created and removed sandboxes of each result, and the snapshot_id of sandbox_snapshot.

Case What occurs
The control service stops Each connection closes. The daemons try again, from 250 ms to each 5 seconds. A request that ran on a connection stops, as when a client closes its connection.
The control service starts again It reads the file. Requests wait for the clusters, for a maximum of the wait from the start of the process.
A daemon stops Its connections close. Requests for its objects wait, then get cluster_unavailable. Lists name it in unreachable.
A connection breaks during a request The client gets cluster_unavailable with status 502, or a stream that ends early.
The file lost a record owner asks each cluster and records the answer.
A sandbox ended on its daemon The next request for it, or the next list, removes the record.
A wrong join token The daemon gets 401, logs it and tries again. The control service logs the name and the address.
A new join token, or forget, while a daemon is connected The connections of the old token get no request. Sweep closes them. The daemon then gets 401 until it has the new token.
Two daemons with the same name and token The control service treats them as one cluster and sends requests to the two. Do not do this.
A cluster says that it has the object of a different cluster The cluster in the file keeps the object. If the file has no cluster for the object, the request gets cluster_conflict with status 409.
A cluster did not answer when owner looks for an object that the file does not have The request gets cluster_unavailable with status 503, also if a different cluster has the object. Send the request again later.

The API service of a Kubernetes cluster, boxfork-operator api, joins as one daemon does. It takes the same join flags. join.AddFlags and Flags.Config read them, and serve in operator/cmd/boxfork-operator/main.go calls join.Serve:

err := join.Serve(ctx, join.Config{
Control: controlURL, // --join
Insecure: false, // --join-insecure: true permits http:// to a different machine
Token: joinToken, // BOXFORK_JOIN_TOKEN, from a Secret
Cluster: "k8s-eu", // --cluster-name: the name of the token
Labels: map[string]string{"cloud": "gcp", "region": "europe-west4"}, // --cluster-label
Version: version,
GPUs: nil, // no GPUs: see below
TLS: caConfig, // --join-ca, from a Secret; nil: the authorities of the system
Log: logger,
}, srv.TrustedHandler()) // the HTTP API of boxfork, without a check of the API key
  • The handler serves the routes of ../reference/http-api.md. The join token is the authentication. Thus the handler does not ask for an API key.
  • The API service reports no GPUs, because it has no GPU allocator and makes no GPU sandbox. Thus the control service sends it no sandbox with a GPU. kubernetes.md gives the reason.
  • Serve returns when ctx ends. It returns an error only for a wrong Config. serve writes that error to the log with the message “the join to the control service stopped”. Flags.Config does the same checks before the API service starts. Thus a wrong value stops the start, and the log line is for a Config that the flags did not make.

The values of the Helm chart and the network policies are in kubernetes.md.

Test What it proves
internal/join/join_test.go Requests, a 1 MiB file, a streamed command, an upgraded connection and TLS go through the connections. A client that closes its connection stops its command. A wrong token or a wrong certificate does not join. A request waits for a daemon after a restart, and fails at once for a cluster that is away for a long time.
control/internal/store/store_test.go Tokens, the Hello, writes that occur two times, Reconcile, Forget, and a second process that reads the file of the first.
control/internal/router/place_test.go The rules and the sequence of place.
control/internal/router/router_test.go Two daemons from apitest that join through real connections: placement, requests on objects, lists, forks, an object made directly on a daemon, a restart from the same file, a lost cluster, keys and tokens, volumes, pools and tool calls.
scripts/proof/control-phase3.sh Two boxfork-testserver processes join one boxfork-control process. The Python SDK does each check. The control service stops with SIGKILL and starts again from its file. The script reads the log to make sure that the restarted service did not ask the clusters for the objects.
operator/cmd/boxfork-operator/main_test.go The API service of Kubernetes serves its API through the connections without a key, and on its port only with the key. Its Hello has the labels and no GPUs. Its start refuses http:// to a different machine before it calls the Kubernetes API. If the join cannot start, the log gives the reason. serve returns only after the join stopped, when its context ends and also when its HTTP server fails. Thus a request through the control service ends before serve returns.
scripts/proof/control-k8s.sh The API services of two kind clusters and one test server join one boxfork-control over HTTPS. The SDK puts sandboxes by labels, and kubectl finds each on its cluster. Commands, files, a snapshot and a fork go through the control service to a cluster. The control service stops with SIGKILL, and the sandboxes continue.

A break-it check: a store that finds no record still routes each request, because owner asks each cluster. Only the check of the log in the proof script failed. Thus that check is necessary.

  • All runs were on one computer. No run used two machines or a real network.
  • The Kubernetes clusters were kind clusters in the virtual machine of Podman. Their pods reached the control service through the network of Podman. No run used a cloud cluster.
  • No run used a real GPU. The GPUs of the test servers are stand-ins.
  • No test stopped the control service while a command ran through it. A test closed the client side of a streamed command.
  • Each new connection writes the Hello to the file: one small write for each request. Nobody measured the control service under load.
  • The control service has one instance. The code does not support two instances on the same file.