Diffinery

homeflare/celldpublic

celld/crates/celld/container.rs
1882 lines · 72.1 KBRaw History
1// Copyright 2026 Deno Land Inc. Apache-2.0 license.
2
3//! Containers attached to Durable Objects: the engine side of
4//! `ctx.container`.
5//!
6//! A cell of a class named in the deployment's `containers` config owns at
7//! most one container, named after the cell, on the node that owns the
8//! cell. The Durable Object supervises it through the ops in
9//! `js/container.rs`; this module performs the effects against the
10//! container engine, which is the Docker Engine API on a unix socket
11//! (Podman serves the same API).
12//!
13//! The container is bound to the cell's ownership on this node, not to its
14//! residency: an idle eviction leaves it running under an inactivity timer
15//! and the next activation of the same cell reconnects to it by name, which
16//! is what Cloudflare does and what the `@cloudflare/containers` class's
17//! `sleepAfter` alarm relies on. Every other stop destroys it. The
18//! container's disk is ephemeral on Cloudflare too, so a takeover that
19//! starts fresh is conformant.
20//!
21//! Images travel through the bucket. `celld deploy` saves the image the
22//! config names as a tar at `deploy/images/<id>.tar`, and a node loads it
23//! into its engine the first time a cell of that class starts, so a node
24//! never talks to a registry.
25
26use crate::asyncrt;
27use crate::docker::{frame_header, Docker, Stream};
28use anyhow::{anyhow, Context};
29use bytes::Bytes;
30use serde_json::{json, Value};
31use std::collections::HashMap;
32use std::path::PathBuf;
33use std::sync::atomic::{AtomicU64, Ordering};
34use std::sync::{Arc, Mutex, OnceLock, RwLock};
35use std::time::Duration;
36use tokio::io::{AsyncReadExt, AsyncWriteExt};
37use tokio::sync::{mpsc, watch};
38
39/// One `containers[]` entry of a deployment, as the node sees it.
40#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
41pub struct ContainerSpec {
42 pub class_name: String,
43 /// The image reference the engine starts, `celld-image:<content key>`,
44 /// so two deployments of one image share one tar and one load.
45 pub image: String,
46 #[serde(default, skip_serializing_if = "Option::is_none")]
47 pub instance_type: Option<String>,
48 #[serde(default, skip_serializing_if = "Option::is_none")]
49 pub max_instances: Option<u64>,
50 /// The OCI runtime this class runs under, such as `runsc` (gVisor) for
51 /// untrusted code. Overrides the node's `CELLD_CONTAINER_RUNTIME` for
52 /// this class; `None` takes the node default. A node whose daemon does
53 /// not have the runtime fails every start of the class, so the class
54 /// runs only where its isolation is available. celld extends the
55 /// Cloudflare config here, which has no per-class runtime.
56 #[serde(default, skip_serializing_if = "Option::is_none")]
57 pub runtime: Option<String>,
58}
59
60/// The reference every engine holds an image under, from its content key.
61/// The key hashes the layer digests and the image config, so an engine
62/// that rebuilds identical content under a new id still resolves it.
63pub fn image_reference(key: &str) -> String {
64 format!("celld-image:{key}")
65}
66
67/// The bucket key of one saved image, from its reference.
68pub fn image_key(image: &str) -> String {
69 format!(
70 "deploy/images/{}.tar",
71 image.trim_start_matches("celld-image:")
72 )
73}
74
75/// The resources an instance type reserves. Cloudflare's published table;
76/// a name outside it is refused at deploy.
77pub fn instance_resources(instance_type: &str) -> Option<(f64, u64)> {
78 let gib = 1024 * 1024 * 1024;
79 Some(match instance_type {
80 "lite" | "dev" => (1.0 / 16.0, 256 * 1024 * 1024),
81 "basic" => (0.25, gib),
82 "standard-1" | "standard" => (0.5, 4 * gib),
83 "standard-2" => (1.0, 6 * gib),
84 "standard-3" => (2.0, 8 * gib),
85 "standard-4" => (4.0, 12 * gib),
86 _ => return None,
87 })
88}
89
90/// The instance type of a class that declares none, as on Cloudflare.
91const DEFAULT_INSTANCE_TYPE: &str = "dev";
92
93/// The resolvers a container gets when it runs under a non-default runtime
94/// and the operator set none. gVisor's network stack does not reach
95/// Docker's embedded resolver at `127.0.0.11`, so a container under it
96/// cannot resolve a hostname though it reaches the Internet by address; a
97/// public resolver, which the fence permits, restores name resolution.
98/// `CELLD_CONTAINER_DNS` overrides this.
99const DEFAULT_CONTAINER_DNS: &[&str] = &["1.1.1.1", "1.0.0.1"];
100
101/// The memory a container of this instance type reserves on the node. A
102/// class that declares none gets the default type, as `create_and_start`
103/// does. An unknown name is refused at deploy, so a running container
104/// always maps; this returns 0 for a name that somehow does not, which
105/// undercounts rather than blocks a sample.
106pub fn instance_memory_bytes(instance_type: Option<&str>) -> u64 {
107 instance_resources(instance_type.unwrap_or(DEFAULT_INSTANCE_TYPE))
108 .map(|(_, memory)| memory)
109 .unwrap_or(0)
110}
111
112/// The memory this node commits to its running containers, for the node's
113/// capacity accounting. Zero when no engine has connected. See
114/// `celld_logic::pressure::Load::container_reserved_bytes` for why the node
115/// counts the cap rather than the container's live usage.
116pub fn reserved_memory_bytes() -> u64 {
117 engine_if_ready().map_or(0, |engine| engine.reserved_memory_bytes())
118}
119
120/// This node's running containers per class, published in the node lease so
121/// peers can sum a class's instances across the fleet for `max_instances`.
122/// Empty when no engine has connected.
123pub fn running_instances_by_class() -> std::collections::BTreeMap<String, u64> {
124 engine_if_ready().map_or_else(Default::default, |engine| {
125 engine.running_instances_by_class()
126 })
127}
128/// Processes one container can hold. Cloudflare publishes no number; this
129/// is room for a build tool's process tree and far short of a fork bomb.
130const PIDS_LIMIT: u64 = 1024;
131/// The host interfaces of the two bridges, named so the fence can address
132/// them; Docker's default `br-<id>` changes with every recreation.
133const OPEN_BRIDGE: &str = "celld0";
134const INTERNAL_BRIDGE: &str = "celld1";
135const BRIDGE_NAME_OPTION: &str = "com.docker.network.bridge.name";
136/// The fence, installed on the node from a one-shot privileged container of
137/// the `celld-fence` image: a container may reach the Internet and nothing
138/// of the node's own. Hooks before Docker's own chains (priority filter -
139/// 10) so a verdict here is final. Input: no new connection from a bridge
140/// to the node itself, which is where the internal listener and the public
141/// listener bind; replies to connections the node opened still pass.
142/// Forward: nothing to the private ranges, where the fleet, the VPC, and
143/// the metadata service live. Rules on the host side of the bridge cover
144/// every runtime, gVisor included, and no process inside a container can
145/// see them, let alone remove them.
146const FENCE_RULES: &str = r#"table inet celld
147delete table inet celld
148table inet celld {
149 chain input {
150 type filter hook input priority -10; policy accept;
151 iifname { "celld0", "celld1" } ct state established,related accept
152 #ALLOW
153 iifname { "celld0", "celld1" } reject
154 }
155 chain forward {
156 type filter hook forward priority -10; policy accept;
157 #ALLOW
158 iifname { "celld0", "celld1" } ip daddr { 169.254.0.0/16, 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, 100.64.0.0/10 } reject
159 iifname { "celld0", "celld1" } ip6 daddr { fe80::/10, fc00::/7 } reject
160 }
161#CHAINS
162}
163"#;
164
165/// homeflare: the fence for a rootless Podman engine, installed in the
166/// engine's rootless network namespace (`CELLD_FENCE_NETNS`), where the
167/// bridges live and the engine's user holds `CAP_NET_ADMIN`. Two changes from
168/// [`FENCE_RULES`], because the node is not that namespace's host but
169/// another container on another bridge in it. Its traffic to a container is
170/// forwarded, not input, so the replies are forwarded too and pass on
171/// `ct state`; the node sits in a private range the forward chain otherwise
172/// rejects. And Podman's resolver (aardvark-dns) answers on each bridge's
173/// gateway, an input to the namespace, so port 53 there stays open; the
174/// containers have no other resolver. Everything else is the same: no new
175/// connection into the namespace, nothing to the private ranges (the node,
176/// Homeflare, the LAN through pasta's 169.254 gateway).
177const FENCE_RULES_NETNS: &str = r#"table inet celld
178delete table inet celld
179table inet celld {
180 chain input {
181 type filter hook input priority -10; policy accept;
182 iifname { "celld0", "celld1" } ct state established,related accept
183 iifname { "celld0", "celld1" } meta l4proto { udp, tcp } th dport 53 accept
184 #ALLOW
185 iifname { "celld0", "celld1" } reject
186 }
187 chain forward {
188 type filter hook forward priority -10; policy accept;
189 iifname { "celld0", "celld1" } ct state established,related accept
190 #ALLOW
191 iifname { "celld0", "celld1" } ip daddr { 169.254.0.0/16, 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, 100.64.0.0/10 } reject
192 iifname { "celld0", "celld1" } ip6 daddr { fe80::/10, fc00::/7 } reject
193 }
194#CHAINS
195}
196"#;
197
198/// homeflare: the connection mark a `CELLD_FENCE_DNAT` rewrite sets. Podman
199/// (netavark) isolates its networks from one another, and the redirected
200/// connection crosses from celld's bridge to the edge's network; netavark
201/// accepts connections carrying this mark ahead of its isolation rules, as
202/// it does for its own port forwarding (its "hostport" mark). The mark stays
203/// with the connection, so the replies pass too. Another engine ignores it.
204const FENCE_DNAT_MARK: u32 = 0x1000;
205
206/// homeflare: an IPv4 address and TCP port from a fence setting. The host
207/// may be a name (Homeflare's edge container, whose address can change when
208/// it restarts), resolved to IPv4 each time the rules are rendered; either
209/// way only an address and a number reach the nftables rules.
210async fn fence_endpoint(text: &str) -> anyhow::Result<(std::net::Ipv4Addr, u16)> {
211 let (host, port) = text
212 .trim()
213 .rsplit_once(':')
214 .ok_or_else(|| anyhow!("{text:?} is not HOST:PORT"))?;
215 let port: u16 = port.parse().with_context(|| format!("{text:?}: port"))?;
216 anyhow::ensure!(port != 0, "{text:?}: port 0");
217 if let Ok(ip) = host.parse::<std::net::Ipv4Addr>() {
218 return Ok((ip, port));
219 }
220 anyhow::ensure!(
221 !host.is_empty()
222 && host.len() <= 253
223 && host
224 .chars()
225 .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '.'),
226 "{text:?}: not an IPv4 address or a hostname"
227 );
228 let ip = tokio::net::lookup_host((host, port))
229 .await
230 .with_context(|| format!("{text:?}: resolve {host}"))?
231 .find_map(|addr| match addr.ip() {
232 std::net::IpAddr::V4(ip) => Some(ip),
233 std::net::IpAddr::V6(_) => None,
234 })
235 .ok_or_else(|| anyhow!("{text:?}: {host} has no IPv4 address"))?;
236 Ok((ip, port))
237}
238
239/// homeflare: exceptions to the fence, for a node that serves its own
240/// Workers on a private address (Homeflare's edge on the LAN). On Cloudflare
241/// a container reaches a Worker over the Internet; here the Worker's
242/// hostname resolves to the LAN, which the fence refuses. Homeflare runs a
243/// listener that serves Worker hostnames only and asks the fence to send the
244/// containers there:
245///
246/// - `CELLD_FENCE_DNAT=IP:PORT=IP:PORT[,...]` rewrites new TCP connections
247/// from the bridges to the first endpoint into the second (prerouting,
248/// before the engine's own port forwarding);
249/// - `CELLD_FENCE_ALLOW=IP:PORT[,...]` lets new TCP connections from the
250/// bridges reach those endpoints, ahead of the rejects.
251///
252/// Everything else stays fenced. Returns the rules to add to the table.
253async fn fence_rules(base: &str) -> anyhow::Result<String> {
254 let list = |name: &str| -> Vec<String> {
255 std::env::var(name)
256 .unwrap_or_default()
257 .split(',')
258 .map(str::trim)
259 .filter(|s| !s.is_empty())
260 .map(str::to_string)
261 .collect()
262 };
263 let bridges = format!("{{ \"{OPEN_BRIDGE}\", \"{INTERNAL_BRIDGE}\" }}");
264 // An accept ends only its own chain, so the exceptions go inside the
265 // fence's chains, ahead of the rejects (a reject anywhere is final).
266 let mut allow = String::new();
267 for entry in list("CELLD_FENCE_ALLOW") {
268 let (ip, port) = fence_endpoint(&entry).await.context("CELLD_FENCE_ALLOW")?;
269 allow.push_str(&format!(
270 "iifname {bridges} ip daddr {ip} tcp dport {port} accept\n "
271 ));
272 }
273 let mut dnat = String::new();
274 for entry in list("CELLD_FENCE_DNAT") {
275 let (from, to) = entry
276 .split_once('=')
277 .ok_or_else(|| anyhow!("CELLD_FENCE_DNAT: {entry:?} is not IP:PORT=IP:PORT"))?;
278 let (from_ip, from_port) = fence_endpoint(from).await.context("CELLD_FENCE_DNAT")?;
279 let (to_ip, to_port) = fence_endpoint(to).await.context("CELLD_FENCE_DNAT")?;
280 dnat.push_str(&format!(
281 " iifname {bridges} ip daddr {from_ip} tcp dport {from_port} ct mark set ct mark | {FENCE_DNAT_MARK:#010x} dnat ip to {to_ip}:{to_port}\n"
282 ));
283 }
284 let chains = if dnat.is_empty() {
285 String::new()
286 } else {
287 format!(" chain prerouting {{\n type nat hook prerouting priority -110; policy accept;\n{dnat} }}\n")
288 };
289 let mut rules = base
290 .replace("#ALLOW\n ", &allow)
291 .replace("#CHAINS\n", &chains);
292 // homeflare: `CELLD_FENCE_NODE=HOST` is this node's own address on the
293 // engine's network. Podman isolates its networks from one another, so
294 // the node's connections into a container (a port it publishes, such as
295 // a sandbox's server) are dropped on the way to the bridge. They get the
296 // mark netavark accepts ahead of its isolation (as `CELLD_FENCE_DNAT`
297 // connections do); it stays with the connection, so replies pass too.
298 // The rule is in a table of this node's own, named after the host: the
299 // main table is shared by every node on the engine and each replaces it,
300 // while each node replaces only its own (its address changes when it
301 // restarts).
302 if let Some(node) = std::env::var("CELLD_FENCE_NODE")
303 .ok()
304 .map(|s| s.trim().to_string())
305 .filter(|s| !s.is_empty())
306 {
307 let (ip, _) = fence_endpoint(&format!("{node}:1"))
308 .await
309 .context("CELLD_FENCE_NODE")?;
310 let table: String = node
311 .chars()
312 .map(|c| {
313 if c.is_ascii_alphanumeric() {
314 c.to_ascii_lowercase()
315 } else {
316 '_'
317 }
318 })
319 .collect();
320 rules.push_str(&format!(
321 "table inet celld_node_{table}\n\
322 delete table inet celld_node_{table}\n\
323 table inet celld_node_{table} {{\n\
324 \x20 chain forward {{\n\
325 \x20 type filter hook forward priority -11; policy accept;\n\
326 \x20 ip saddr {ip} oifname {bridges} ct state new ct mark set ct mark | {FENCE_DNAT_MARK:#010x}\n\
327 \x20 }}\n\
328 }}\n"
329 ));
330 }
331 Ok(rules)
332}
333
334/// homeflare: the network namespace the fence joins instead of the host's,
335/// as the engine names it (`ns:<path>`): a rootless Podman's rootless-netns,
336/// `$XDG_RUNTIME_DIR/containers/networks/rootless-netns/rootless-netns`.
337fn fence_netns() -> Option<String> {
338 std::env::var("CELLD_FENCE_NETNS")
339 .ok()
340 .filter(|path| !path.trim().is_empty())
341}
342
343/// Docker's bridge option that forbids traffic between two containers on
344/// the same bridge. The node still reaches every container, because it
345/// speaks from the host side of the bridge.
346const ICC_OPTION: &str = "com.docker.network.bridge.enable_icc";
347
348/// How a cell stop treats its container.
349#[derive(Clone, Copy, Debug, PartialEq, Eq)]
350pub enum Release {
351 /// An idle eviction: keep the container under its inactivity timer.
352 Keep,
353 /// Ownership leaves this node, or the cell is reset: destroy it.
354 Destroy,
355}
356
357/// The default inactivity window after an idle eviction when the object
358/// never set one. The `@cloudflare/containers` alarm wakes the object well
359/// inside this to enforce `sleepAfter`, so this is the backstop for an
360/// object that never wakes, not the policy.
361const DEFAULT_INACTIVITY: Duration = Duration::from_secs(10 * 60);
362
363/// Environment every container sees. The values mirror workerd's local
364/// engine: applications read the names, never the values.
365const DEFAULT_ENV: &[&str] = &[
366 "CLOUDFLARE_COUNTRY_A2=XX",
367 "CLOUDFLARE_DEPLOYMENT_ID=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
368 "CLOUDFLARE_LOCATION=loc01",
369 "CLOUDFLARE_REGION=REGN",
370 "CLOUDFLARE_APPLICATION_ID=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
371];
372
373pub struct StartParams {
374 pub entrypoint: Option<Vec<String>>,
375 pub env: Vec<(String, String)>,
376 pub enable_internet: bool,
377 pub labels: Vec<(String, String)>,
378}
379
380#[derive(Default)]
381struct CellState {
382 running: bool,
383 /// Where the node dials the container: the bridge address on Linux,
384 /// the published loopback ports elsewhere.
385 address: Address,
386 inactivity: Option<Duration>,
387 /// The pending destroy after an idle eviction. Dropping it cancels.
388 sweeper: Option<asyncrt::TaskHandle<()>>,
389 /// Bumped per start so a wait from a previous run cannot report for
390 /// this one.
391 run: u64,
392}
393
394#[derive(Clone, Debug, Default)]
395enum Address {
396 #[default]
397 None,
398 Ip(String),
399 Published(HashMap<u16, u16>),
400}
401
402pub struct CellContainer {
403 scope: String,
404 name: String,
405 spec: Arc<ContainerSpec>,
406 state: Mutex<CellState>,
407 /// Processes `exec()` started in this container. An object drops one
408 /// after `output()`; the rest go with the container.
409 processes: Mutex<Vec<u64>>,
410 /// The exit of the current run, `None` while it runs. `Some(Err)` is
411 /// an engine failure the wait could not attribute to the process.
412 /// Written with `send_replace`: a plain `send` discards the value
413 /// while nobody subscribes, and `monitor()` usually subscribes late.
414 exit: watch::Sender<Option<(u64, Result<i64, String>)>>,
415}
416
417impl CellContainer {
418 pub fn running(&self) -> bool {
419 self.state.lock().unwrap().running
420 }
421
422 /// `host:port` for `getTcpPort(port)`.
423 pub fn address(&self, port: u16) -> Result<String, String> {
424 let state = self.state.lock().unwrap();
425 if !state.running {
426 return Err("the container is not running".to_string());
427 }
428 match &state.address {
429 Address::Ip(ip) => Ok(format!("{ip}:{port}")),
430 Address::Published(ports) => ports
431 .get(&port)
432 .map(|host| format!("127.0.0.1:{host}"))
433 .ok_or_else(|| {
434 format!(
435 "The container is not listening on port {port}: on this platform a port \
436 must be declared with EXPOSE in the image"
437 )
438 }),
439 Address::None => Err(format!("The container is not listening on port {port}")),
440 }
441 }
442
443 pub fn set_inactivity(&self, duration: Duration) {
444 self.state.lock().unwrap().inactivity = Some(duration);
445 }
446
447 /// Open the next run, synchronously, before the start is even queued.
448 /// The object's `start()` returns at once and its `monitor()` follows
449 /// immediately, so the run they both mean must exist before either
450 /// effect runs, or the monitor would find the previous run's exit and
451 /// report the new container dead on arrival.
452 pub fn begin_run(&self) -> u64 {
453 let mut state = self.state.lock().unwrap();
454 state.run += 1;
455 state.running = true;
456 state.address = Address::None;
457 let run = state.run;
458 drop(state);
459 self.exit.send_replace(None);
460 run
461 }
462
463 /// The run `monitor()` waits on: the newest one.
464 pub fn current_run(&self) -> u64 {
465 self.state.lock().unwrap().run
466 }
467}
468
469pub struct ContainerEngine {
470 /// See `Config::runtime`.
471 runtime: Option<String>,
472 /// See `Config::dns`.
473 dns: Vec<String>,
474 /// The absolute path of the container resolv.conf this engine wrote and
475 /// bind-mounts; `None` when it could not be written.
476 resolv_conf: Option<PathBuf>,
477 docker: Docker,
478 node: String,
479 bucket: Option<crate::bucket::Bucket>,
480 /// Per-image load lock, so two cells of one class starting together
481 /// load the tar once.
482 images: Mutex<HashMap<String, Arc<tokio::sync::Mutex<bool>>>>,
483 cells: Mutex<HashMap<String, Arc<CellContainer>>>,
484 networks: tokio::sync::Mutex<Option<(String, String)>>,
485 /// Whether this process has installed the fence on the node's bridges.
486 /// The rules this process installed on the node's bridges, if any. A
487 /// change (homeflare: a fence exception's host resolving elsewhere)
488 /// installs them again.
489 fenced: tokio::sync::Mutex<Option<String>>,
490}
491
492/// What the runtime told this module about the node: set once at start.
493struct Config {
494 node: String,
495 bucket: Option<crate::bucket::Bucket>,
496 /// `CELLD_CONTAINER_RUNTIME`: the OCI runtime every container starts
497 /// under, such as `runsc` (gVisor) or `kata` (a VM). `None` is the
498 /// daemon's default, which is `runc` unless the operator changed it. A
499 /// class can override it, see `ContainerSpec::runtime`.
500 runtime: Option<String>,
501 /// `CELLD_CONTAINER_DNS`: the resolvers a container gets, overriding
502 /// `DEFAULT_CONTAINER_DNS`. Empty takes the default when a runtime is in
503 /// use and the daemon's otherwise.
504 dns: Vec<String>,
505 /// The node's state directory. celld writes the container resolv.conf
506 /// here and bind-mounts it, so the path must be the same on the host as
507 /// celld sees it; a self-hosted node runs celld as a host process, and
508 /// the lab mounts the directory one-to-one.
509 data_dir: PathBuf,
510}
511
512static CONFIG: RwLock<Option<Config>> = RwLock::new(None);
513/// The deployment's container classes. Replaced on every generation swap;
514/// a running container keeps the spec it started with.
515static SPECS: RwLock<Vec<Arc<ContainerSpec>>> = RwLock::new(Vec::new());
516/// The deployment's `celld-fence` image; see `Manifest::fence_image`.
517static FENCE_IMAGE: RwLock<Option<String>> = RwLock::new(None);
518/// The engine, connected on first use. A node whose deployment declares no
519/// container class never opens the socket.
520static ENGINE: tokio::sync::OnceCell<Arc<ContainerEngine>> = tokio::sync::OnceCell::const_new();
521
522pub fn configure(node: String, bucket: Option<crate::bucket::Bucket>, data_dir: PathBuf) {
523 let runtime = std::env::var("CELLD_CONTAINER_RUNTIME")
524 .ok()
525 .filter(|runtime| !runtime.is_empty());
526 let dns = std::env::var("CELLD_CONTAINER_DNS")
527 .unwrap_or_default()
528 .split(',')
529 .map(|resolver| resolver.trim().to_string())
530 .filter(|resolver| !resolver.is_empty())
531 .collect();
532 *CONFIG.write().unwrap() = Some(Config {
533 node,
534 bucket,
535 runtime,
536 dns,
537 data_dir,
538 });
539}
540
541pub fn install_specs(specs: Vec<ContainerSpec>, fence_image: Option<String>) {
542 *SPECS.write().unwrap() = specs.into_iter().map(Arc::new).collect();
543 *FENCE_IMAGE.write().unwrap() = fence_image;
544}
545
546pub fn spec(class: &str) -> Option<Arc<ContainerSpec>> {
547 SPECS
548 .read()
549 .unwrap()
550 .iter()
551 .find(|spec| spec.class_name == class)
552 .cloned()
553}
554
555/// The engine, connecting on the first call. A failure is returned rather
556/// than cached, so a daemon that comes up later is found by the next call.
557pub async fn engine() -> anyhow::Result<Arc<ContainerEngine>> {
558 ENGINE
559 .get_or_try_init(|| async {
560 let (node, bucket, runtime, dns, data_dir) = {
561 let config = CONFIG.read().unwrap();
562 let config = config.as_ref().ok_or_else(|| {
563 anyhow!("the container engine is not configured on this node")
564 })?;
565 (
566 config.node.clone(),
567 config.bucket.clone(),
568 config.runtime.clone(),
569 config.dns.clone(),
570 config.data_dir.clone(),
571 )
572 };
573 let docker = Docker::discover().ok_or_else(|| {
574 anyhow!(
575 "no container engine: set DOCKER_HOST to a unix socket, or run a Docker or \
576 Podman daemon on this node"
577 )
578 })?;
579 Ok(Arc::new(
580 ContainerEngine::connect(docker, node, bucket, runtime, dns, data_dir).await?,
581 ))
582 })
583 .await
584 .cloned()
585}
586
587/// The engine only if a previous call connected it.
588pub fn engine_if_ready() -> Option<Arc<ContainerEngine>> {
589 ENGINE.get().cloned()
590}
591
592/// Destroy every container of this node at process exit. A preserve
593/// shutdown (`celld dev` on Ctrl-C) keeps its cells resident and stops
594/// none of them, and a handoff cut by the deadline leaves cells behind
595/// too; without this their containers ran on until the next start of the
596/// same node reaped them, invisible to the object that owned them.
597pub async fn shutdown() {
598 let Some(engine) = engine_if_ready() else {
599 return;
600 };
601 if let Err(error) = engine.reap().await {
602 tracing::warn!(
603 event = "container_shutdown_reap_failed",
604 error = %format!("{error:#}"),
605 "containers of this node may still be running"
606 );
607 }
608}
609
610/// Connect and load every image of the installed specs, ahead of the
611/// first cell that needs one. Failures are logged: a node without an
612/// engine still serves every other class, and the container class fails
613/// at its first `start()` with the same message.
614pub async fn prewarm() {
615 let engine = match engine().await {
616 Ok(engine) => engine,
617 Err(error) => {
618 tracing::warn!(error = %format!("{error:#}"), "containers are unavailable on this node");
619 return;
620 }
621 };
622 if let Err(error) = engine.ensure_fence().await {
623 tracing::warn!(
624 error = %format!("{error:#}"),
625 "the container bridges are not fenced; no container starts on this node"
626 );
627 }
628 let specs = SPECS.read().unwrap().clone();
629 for spec in specs {
630 if let Err(error) = engine.ensure_image(&spec.image).await {
631 tracing::warn!(
632 class = %spec.class_name,
633 image = %spec.image,
634 error = %format!("{error:#}"),
635 "container image is unavailable"
636 );
637 }
638 }
639}
640
641impl ContainerEngine {
642 /// Connect to the engine and reap every container a previous process
643 /// of this node left behind. A restarted node cannot know which of its
644 /// containers still belong to cells it will own again, and a container
645 /// whose object has lost track of it is a leak, so a restart starts
646 /// clean. The next `start()` of each object creates a fresh one.
647 pub async fn connect(
648 docker: Docker,
649 node: String,
650 bucket: Option<crate::bucket::Bucket>,
651 runtime: Option<String>,
652 dns: Vec<String>,
653 data_dir: PathBuf,
654 ) -> anyhow::Result<Self> {
655 // Write the resolv.conf once, to bind into every container that runs
656 // under a non-default runtime. gVisor cannot reach Docker's embedded
657 // resolver, so a bind-mounted file with a public resolver, which the
658 // fence permits, is the only resolv.conf the container can use.
659 let resolvers: Vec<String> = if dns.is_empty() {
660 DEFAULT_CONTAINER_DNS
661 .iter()
662 .map(|r| r.to_string())
663 .collect()
664 } else {
665 dns.clone()
666 };
667 let resolv_conf = {
668 let path = data_dir.join("container-resolv.conf");
669 let body: String = resolvers
670 .iter()
671 .map(|resolver| format!("nameserver {resolver}\n"))
672 .collect();
673 let fs = asyncrt::fs();
674 match fs
675 .create_dir_all(&data_dir)
676 .and_then(|()| fs.write(&path, body.as_bytes()))
677 {
678 Ok(()) => Some(path),
679 Err(error) => {
680 tracing::warn!(event = "container_resolv_write_failed", %error);
681 None
682 }
683 }
684 };
685 let engine = Self {
686 docker,
687 node,
688 bucket,
689 runtime,
690 dns,
691 resolv_conf,
692 images: Mutex::new(HashMap::new()),
693 cells: Mutex::new(HashMap::new()),
694 networks: tokio::sync::Mutex::new(None),
695 fenced: tokio::sync::Mutex::new(None),
696 };
697 engine.reap().await?;
698 Ok(engine)
699 }
700
701 pub fn socket(&self) -> &std::path::Path {
702 self.docker.socket()
703 }
704
705 async fn reap(&self) -> anyhow::Result<()> {
706 let filters = json!({ "label": [format!("celld.node={}", self.node)] }).to_string();
707 let reply = self
708 .docker
709 .expect(
710 "GET",
711 &format!(
712 "/containers/json?all=true&filters={}",
713 percent_encoding::utf8_percent_encode(
714 &filters,
715 percent_encoding::NON_ALPHANUMERIC
716 )
717 ),
718 None,
719 "list containers",
720 )
721 .await?;
722 let list = reply.json()?;
723 for entry in list.as_array().into_iter().flatten() {
724 if let Some(id) = entry.get("Id").and_then(Value::as_str) {
725 let _ = self
726 .docker
727 .call("DELETE", &format!("/containers/{id}?force=true"), None)
728 .await;
729 }
730 }
731 Ok(())
732 }
733
734 /// Make the class's image present in the engine, loading it from the
735 /// bucket when it is not. Idempotent and serialized per image.
736 pub async fn ensure_image(&self, image: &str) -> anyhow::Result<()> {
737 let lock = self
738 .images
739 .lock()
740 .unwrap()
741 .entry(image.to_string())
742 .or_insert_with(|| Arc::new(tokio::sync::Mutex::new(false)))
743 .clone();
744 let mut loaded = lock.lock().await;
745 if *loaded {
746 return Ok(());
747 }
748 let reply = self
749 .docker
750 .call("GET", &format!("/images/{image}/json"), None)
751 .await?;
752 if reply.status.is_success() {
753 tracing::info!(image, "container image present in the engine");
754 *loaded = true;
755 return Ok(());
756 }
757 let bucket = self
758 .bucket
759 .as_ref()
760 .ok_or_else(|| anyhow!("image {image} is not present in the container engine"))?;
761 let key = image_key(image);
762 // homeflare: download in ranges to a temporary file and stream it to
763 // the engine. An image tar is often gigabytes: one `get` would hold
764 // it all in memory and has to finish within the bucket client's
765 // per-request timeout.
766 let temp = tempfile::NamedTempFile::new().context("temporary file for the image")?;
767 let mut file = tokio::fs::File::from_std(temp.reopen().context("open the image file")?);
768 let bytes = bucket.get_large(&key, &mut file).await?.ok_or_else(|| {
769 anyhow!("image {image} is not in the bucket at {key}; run `celld deploy`")
770 })?;
771 drop(file);
772 let file = tokio::fs::File::from_std(temp.reopen().context("open the image file")?);
773 let reply = self
774 .docker
775 .post_file(
776 "/images/load?quiet=true",
777 file,
778 "application/x-tar",
779 "load image",
780 )
781 .await?;
782 drop(temp);
783 tracing::info!(
784 image,
785 bytes,
786 answer = %String::from_utf8_lossy(&reply.body).trim_end(),
787 "container image loaded from the bucket"
788 );
789 *loaded = true;
790 Ok(())
791 }
792
793 /// The two bridges every container joins: one with egress, one
794 /// without. Docker implements an internal network by omitting the
795 /// masquerade rule and the default route; the node still reaches the
796 /// bridge address, which is all ingress needs.
797 async fn networks(&self) -> anyhow::Result<(String, String)> {
798 let mut guard = self.networks.lock().await;
799 if let Some(names) = guard.as_ref() {
800 return Ok(names.clone());
801 }
802 for (name, internal) in [("celld", false), ("celld-internal", true)] {
803 // A bridge keeps the options it was created with, so one from
804 // before containers were isolated from each other is replaced.
805 // The replacement fails while a container is attached, which a
806 // node start after its reap never has; a failure keeps the old
807 // bridge and says so rather than refusing every container.
808 let current = self
809 .docker
810 .call("GET", &format!("/networks/{name}"), None)
811 .await?;
812 if current.status.is_success() {
813 let bridge = if internal {
814 INTERNAL_BRIDGE
815 } else {
816 OPEN_BRIDGE
817 };
818 let current_options = current
819 .json()
820 .ok()
821 .and_then(|network| network.get("Options").cloned())
822 .unwrap_or(Value::Null);
823 let option = |key: &str| current_options.get(key).and_then(Value::as_str);
824 if option(ICC_OPTION) == Some("false") && option(BRIDGE_NAME_OPTION) == Some(bridge)
825 {
826 continue;
827 }
828 let removed = self
829 .docker
830 .call("DELETE", &format!("/networks/{name}"), None)
831 .await?;
832 if !removed.status.is_success() {
833 tracing::warn!(
834 network = name,
835 error = %removed.message(),
836 "the container bridge predates container isolation and is in use; \
837 containers on it can reach each other until the node restarts idle"
838 );
839 continue;
840 }
841 }
842 let reply = self
843 .docker
844 .call(
845 "POST",
846 "/networks/create",
847 Some(json!({
848 "Name": name,
849 "Driver": "bridge",
850 "Internal": internal,
851 "Options": {
852 ICC_OPTION: "false",
853 BRIDGE_NAME_OPTION: if internal { INTERNAL_BRIDGE } else { OPEN_BRIDGE },
854 },
855 })),
856 )
857 .await?;
858 // 409: it exists, which is the steady state.
859 if !reply.status.is_success() && reply.status.as_u16() != 409 {
860 return Err(anyhow!(
861 "create network {name} failed with [{}] {}",
862 reply.status.as_u16(),
863 reply.message()
864 ));
865 }
866 }
867 let names = ("celld".to_string(), "celld-internal".to_string());
868 *guard = Some(names.clone());
869 Ok(names)
870 }
871
872 /// Install the fence on the node's bridges, once per process, and again
873 /// when its rules change (homeflare: a fence exception's host resolving
874 /// to a new address). Every container start waits on this and fails
875 /// when it fails: a node that
876 /// cannot fence its bridges runs no container, because an unfenced
877 /// container can reach the node's internal listener and the cloud's
878 /// metadata service. The rules live in the kernel and outlive this
879 /// process; a restart re-applies them, which is idempotent.
880 pub async fn ensure_fence(&self) -> anyhow::Result<()> {
881 let mut fenced = self.fenced.lock().await;
882 let netns = fence_netns();
883 let (rules, network_mode) = match &netns {
884 Some(path) => (FENCE_RULES_NETNS, format!("ns:{path}")),
885 None => (FENCE_RULES, "host".to_string()),
886 };
887 let rules = fence_rules(rules).await?;
888 if fenced.as_deref() == Some(rules.as_str()) {
889 return Ok(());
890 }
891 let image = FENCE_IMAGE.read().unwrap().clone().ok_or_else(|| {
892 anyhow!(
893 "this deployment has no fence image; deploy it again with this celld, which \
894 saves the celld-fence image beside the container images"
895 )
896 })?;
897 self.ensure_image(&image).await?;
898 self.networks().await?;
899 let body = json!({
900 "Image": image,
901 "Env": [format!("CELLD_NFT={rules}")],
902 "Cmd": ["sh", "-c", "printf '%s' \"$CELLD_NFT\" | nft -f -"],
903 "Labels": { "celld.node": self.node, "celld.fence": "1" },
904 "HostConfig": { "NetworkMode": network_mode, "CapAdd": ["NET_ADMIN"] },
905 });
906 let created = self
907 .docker
908 .expect(
909 "POST",
910 "/containers/create",
911 Some(body),
912 "create fence container",
913 )
914 .await?
915 .json()?;
916 let id = created
917 .get("Id")
918 .and_then(Value::as_str)
919 .ok_or_else(|| anyhow!("create fence container answered without an id"))?
920 .to_string();
921 let outcome = async {
922 self.docker
923 .expect(
924 "POST",
925 &format!("/containers/{id}/start"),
926 None,
927 "start fence container",
928 )
929 .await?;
930 let waited = self
931 .docker
932 .expect(
933 "POST",
934 &format!("/containers/{id}/wait"),
935 None,
936 "wait fence container",
937 )
938 .await?
939 .json()?;
940 let code = waited
941 .get("StatusCode")
942 .and_then(Value::as_i64)
943 .unwrap_or(-1);
944 if code != 0 {
945 let logs = self.logs(&id).await.unwrap_or_default();
946 return Err(anyhow!(
947 "the fence container exited with {code}: {}",
948 logs.trim()
949 ));
950 }
951 Ok(())
952 }
953 .await;
954 let _ = self
955 .docker
956 .call("DELETE", &format!("/containers/{id}?force=true"), None)
957 .await;
958 outcome.context("fence the container bridges")?;
959 tracing::info!(
960 event = "container_bridges_fenced",
961 bridges = format!("{OPEN_BRIDGE},{INTERNAL_BRIDGE}"),
962 netns = netns.as_deref().unwrap_or("host"),
963 "containers can reach the Internet and nothing of the node's own"
964 );
965 *fenced = Some(rules);
966 Ok(())
967 }
968
969 /// Both output streams of a stopped container, for an error message.
970 async fn logs(&self, id: &str) -> anyhow::Result<String> {
971 let reply = self
972 .docker
973 .expect(
974 "GET",
975 &format!("/containers/{id}/logs?stdout=true&stderr=true"),
976 None,
977 "container logs",
978 )
979 .await?;
980 let mut text = Vec::new();
981 let mut rest: &[u8] = &reply.body;
982 while rest.len() >= 8 {
983 let (_, length) = frame_header(rest[..8].try_into().unwrap());
984 let end = (8 + length).min(rest.len());
985 text.extend_from_slice(&rest[8..end]);
986 rest = &rest[end..];
987 }
988 Ok(String::from_utf8_lossy(&text).into_owned())
989 }
990
991 /// The cell's container handle, adopting a container a previous
992 /// activation on this node left running. Called at cell start for a
993 /// class with a spec; the object's `running` reads the answer.
994 pub async fn attach(&self, scope: &str, class: &str) -> anyhow::Result<Arc<CellContainer>> {
995 let spec = spec(class).ok_or_else(|| anyhow!("class {class} has no container"))?;
996 let cell = {
997 let mut cells = self.cells.lock().unwrap();
998 let cell = cells.entry(scope.to_string()).or_insert_with(|| {
999 Arc::new(CellContainer {
1000 scope: scope.to_string(),
1001 name: container_name(&self.node, scope),
1002 spec,
1003 state: Mutex::new(CellState::default()),
1004 processes: Mutex::new(Vec::new()),
1005 exit: watch::channel(None).0,
1006 })
1007 });
1008 // A returning cell cancels the destroy its eviction armed.
1009 cell.state.lock().unwrap().sweeper = None;
1010 cell.clone()
1011 };
1012 let running = self.inspect_running(&cell).await?;
1013 // A container this handle did not start, left running by an
1014 // earlier owner of the name: give it a run so `monitor()` has an
1015 // exit to wait for. The run opens before the address lands, because
1016 // opening one clears it.
1017 let adopted = running.is_some() && !cell.running();
1018 if adopted {
1019 let run = cell.begin_run();
1020 self.watch_exit(&cell, run);
1021 }
1022 let mut state = cell.state.lock().unwrap();
1023 state.running = running.is_some();
1024 state.address = running.unwrap_or_default();
1025 drop(state);
1026 Ok(cell)
1027 }
1028
1029 /// The cell's handle, if the cell started on this node.
1030 pub fn cell(&self, scope: &str) -> Option<Arc<CellContainer>> {
1031 self.cells.lock().unwrap().get(scope).cloned()
1032 }
1033
1034 /// The memory the node's running containers reserve, summed over their
1035 /// instance-type caps. A cell whose container is not running reserves
1036 /// nothing: a stopped container holds no memory, and an idle eviction
1037 /// stops it before the sample would count it.
1038 pub fn reserved_memory_bytes(&self) -> u64 {
1039 self.cells
1040 .lock()
1041 .unwrap()
1042 .values()
1043 .filter(|cell| cell.running())
1044 .map(|cell| instance_memory_bytes(cell.spec.instance_type.as_deref()))
1045 .sum()
1046 }
1047
1048 /// This node's running containers per class.
1049 fn running_instances_by_class(&self) -> std::collections::BTreeMap<String, u64> {
1050 let mut counts = std::collections::BTreeMap::new();
1051 for cell in self.cells.lock().unwrap().values() {
1052 if cell.running() {
1053 *counts.entry(cell.spec.class_name.clone()).or_insert(0) += 1;
1054 }
1055 }
1056 counts
1057 }
1058
1059 /// Refuse a start that would put the class over its fleet-wide
1060 /// `max_instances`. The fleet count is this node's own running
1061 /// containers of the class, read live, plus every peer's count from the
1062 /// shared capacity sample; `begin_run` already marked the starting cell
1063 /// running, so the live count includes it. A class with no
1064 /// `max_instances`, or a node with no bucket to read the sample from as
1065 /// under `celld dev`, has no fleet ceiling. See
1066 /// [`crate::ownership_store::fleet_class_instances`] for the staleness
1067 /// the sample admits.
1068 async fn enforce_instance_ceiling(&self, cell: &CellContainer) -> anyhow::Result<()> {
1069 let Some(max) = cell.spec.max_instances else {
1070 return Ok(());
1071 };
1072 let class = &cell.spec.class_name;
1073 let here = self
1074 .cells
1075 .lock()
1076 .unwrap()
1077 .values()
1078 .filter(|other| other.running() && other.spec.class_name == *class)
1079 .count() as u64;
1080 let elsewhere = match &self.bucket {
1081 Some(bucket) => {
1082 crate::ownership_store::fleet_class_instances(bucket, class, &self.node).await
1083 }
1084 None => 0,
1085 };
1086 anyhow::ensure!(
1087 here + elsewhere <= max,
1088 "container class {class} is at its max_instances limit of {max}: \
1089 {here} on this node and {elsewhere} on other nodes",
1090 );
1091 Ok(())
1092 }
1093
1094 async fn inspect_running(&self, cell: &CellContainer) -> anyhow::Result<Option<Address>> {
1095 let reply = self
1096 .docker
1097 .call("GET", &format!("/containers/{}/json", cell.name), None)
1098 .await?;
1099 if reply.status.as_u16() == 404 {
1100 return Ok(None);
1101 }
1102 if !reply.status.is_success() {
1103 return Err(anyhow!(
1104 "inspect container failed with [{}] {}",
1105 reply.status.as_u16(),
1106 reply.message()
1107 ));
1108 }
1109 let info = reply.json()?;
1110 let running = info
1111 .pointer("/State/Running")
1112 .and_then(Value::as_bool)
1113 .unwrap_or(false);
1114 Ok(running.then(|| address_of(&info)))
1115 }
1116
1117 /// Start the cell's container. The object's `start()` returns before
1118 /// this completes, as on Cloudflare; a failure surfaces through
1119 /// `monitor()`.
1120 /// Start the cell's container for the run `begin_run` opened. The
1121 /// object's `start()` returns before this completes, as on Cloudflare;
1122 /// a failure surfaces through `monitor()`.
1123 pub async fn start(
1124 &self,
1125 cell: &Arc<CellContainer>,
1126 run: u64,
1127 params: StartParams,
1128 ) -> anyhow::Result<()> {
1129 let started = self.create_and_start(cell, params).await;
1130 let address = match started {
1131 Ok(address) => address,
1132 Err(error) => {
1133 // `start()` is fire-and-forget for the object, and its
1134 // `monitor()` sees this error only if it was already
1135 // waiting; say it here too, or a start that fails fast
1136 // leaves no trace anywhere.
1137 tracing::warn!(
1138 event = "container_start_failed",
1139 cell = %cell.scope,
1140 error = %format!("{error:#}"),
1141 "the container did not start"
1142 );
1143 let mut state = cell.state.lock().unwrap();
1144 state.running = false;
1145 drop(state);
1146 cell.exit
1147 .send_replace(Some((run, Err(format!("{error:#}")))));
1148 return Err(error);
1149 }
1150 };
1151 {
1152 let mut state = cell.state.lock().unwrap();
1153 state.running = true;
1154 state.address = address;
1155 }
1156 self.watch_exit(cell, run);
1157 Ok(())
1158 }
1159
1160 /// Wait for the container's root process to end and publish the exit
1161 /// for `run`; a later run's start has already replaced the state.
1162 fn watch_exit(&self, cell: &Arc<CellContainer>, run: u64) {
1163 let docker = self.docker.clone();
1164 let cell_ = cell.clone();
1165 asyncrt::spawn(async move {
1166 let result = docker
1167 .call("POST", &format!("/containers/{}/wait", cell_.name), None)
1168 .await
1169 .and_then(|reply| {
1170 if !reply.status.is_success() {
1171 return Err(anyhow!(
1172 "wait failed with [{}] {}",
1173 reply.status.as_u16(),
1174 reply.message()
1175 ));
1176 }
1177 reply
1178 .json()?
1179 .get("StatusCode")
1180 .and_then(Value::as_i64)
1181 .ok_or_else(|| anyhow!("wait answered without a status code"))
1182 })
1183 .map_err(|error| format!("{error:#}"));
1184 let mut state = cell_.state.lock().unwrap();
1185 if state.run == run {
1186 state.running = false;
1187 state.address = Address::None;
1188 }
1189 drop(state);
1190 cell_.exit.send_replace(Some((run, result)));
1191 })
1192 .detach();
1193 }
1194
1195 async fn create_and_start(
1196 &self,
1197 cell: &CellContainer,
1198 params: StartParams,
1199 ) -> anyhow::Result<Address> {
1200 self.ensure_fence().await?;
1201 self.enforce_instance_ceiling(cell).await?;
1202 self.ensure_image(&cell.spec.image).await?;
1203 let (open, internal) = self.networks().await?;
1204 // A previous run's container may still be named: the wait task
1205 // observed its exit but nothing removed it, or a restart adopted a
1206 // stopped one. The name is the cell's, so it is ours to remove.
1207 let _ = self
1208 .docker
1209 .call(
1210 "DELETE",
1211 &format!("/containers/{}?force=true", cell.name),
1212 None,
1213 )
1214 .await;
1215 let mut env: Vec<String> = DEFAULT_ENV.iter().map(|entry| entry.to_string()).collect();
1216 env.push(format!("CLOUDFLARE_DURABLE_OBJECT_ID={}", cell.scope));
1217 env.extend(
1218 params
1219 .env
1220 .iter()
1221 .map(|(name, value)| format!("{name}={value}")),
1222 );
1223 let mut labels = serde_json::Map::new();
1224 labels.insert("celld.node".into(), json!(self.node));
1225 labels.insert("celld.cell".into(), json!(cell.scope));
1226 labels.insert("celld.class".into(), json!(cell.spec.class_name));
1227 for (name, value) in &params.labels {
1228 labels.insert(format!("celld.user.{name}"), json!(value));
1229 }
1230 // Off Linux the node reaches a container only through published
1231 // ports, and Docker publishes nothing on an internal network, so
1232 // `enableInternet: false` would make the container unreachable.
1233 // Development there keeps egress; the compat page says so.
1234 let offline = !params.enable_internet && cfg!(target_os = "linux");
1235 if !params.enable_internet && !offline {
1236 tracing::warn!(
1237 cell = %cell.scope,
1238 "enableInternet: false is not enforced on this platform; the container keeps egress"
1239 );
1240 }
1241 // A container is a tenant's process tree, not the operator's: no
1242 // capability, no privilege gain through setuid binaries, the
1243 // daemon's seccomp profile, and a process ceiling. What a class
1244 // legitimately needs beyond this is a config question for later,
1245 // not a default. The kernel boundary itself is the runtime's.
1246 let mut host_config = json!({
1247 "NetworkMode": if offline { &internal } else { &open },
1248 "PublishAllPorts": !cfg!(target_os = "linux"),
1249 "CapDrop": ["ALL"],
1250 "SecurityOpt": ["no-new-privileges"],
1251 "PidsLimit": PIDS_LIMIT,
1252 // An init as PID 1 reaps orphaned children. Without it a process
1253 // whose parent exits becomes a zombie the container holds until
1254 // it stops, and enough of them exhaust the PID ceiling; a fleet
1255 // fork bomb left exactly these behind.
1256 "Init": true,
1257 });
1258 // A class can name its own runtime, else the node default. A class
1259 // that needs isolation names `runsc`, and the node's daemon must
1260 // have it or the start fails, so the class runs only where its
1261 // isolation is real.
1262 let runtime = cell
1263 .spec
1264 .runtime
1265 .as_deref()
1266 .or(self.runtime.as_deref())
1267 .filter(|runtime| !runtime.is_empty());
1268 if let Some(runtime) = runtime {
1269 host_config["Runtime"] = json!(runtime);
1270 }
1271 // A container under a non-default runtime gets an explicit resolver
1272 // through a bind-mounted resolv.conf: gVisor cannot reach Docker's
1273 // embedded resolver at `127.0.0.11`, and on a user bridge Docker
1274 // keeps that address in resolv.conf whatever `--dns` says, so the
1275 // file itself must name a reachable resolver. An operator who set
1276 // `CELLD_CONTAINER_DNS` gets it for every container.
1277 let wants_resolver = runtime.is_some() || !self.dns.is_empty();
1278 if wants_resolver {
1279 if let Some(resolv) = &self.resolv_conf {
1280 let bind = format!("{}:/etc/resolv.conf:ro", resolv.display());
1281 host_config["Binds"] = json!([bind]);
1282 }
1283 }
1284 // Every container has a limit: a class without an instance type
1285 // gets Cloudflare's default type rather than the node.
1286 let instance_type = cell
1287 .spec
1288 .instance_type
1289 .as_deref()
1290 .unwrap_or(DEFAULT_INSTANCE_TYPE);
1291 let (vcpu, memory) =
1292 instance_resources(instance_type).expect("the deploy refused this instance type");
1293 host_config["NanoCpus"] = json!((vcpu * 1e9) as u64);
1294 host_config["Memory"] = json!(memory);
1295 host_config["MemorySwap"] = json!(memory);
1296 let mut body = json!({
1297 "Image": cell.spec.image,
1298 "Env": env,
1299 "Labels": labels,
1300 "HostConfig": host_config,
1301 });
1302 if let Some(entrypoint) = params.entrypoint {
1303 body["Cmd"] = json!(entrypoint);
1304 }
1305 // The daemon can answer 409 for a name whose previous container is
1306 // still being removed, so a fresh start after `destroy()` retries
1307 // briefly, as workerd's engine does.
1308 let mut reply = self
1309 .docker
1310 .call(
1311 "POST",
1312 &format!("/containers/create?name={}", cell.name),
1313 Some(body.clone()),
1314 )
1315 .await?;
1316 for _ in 0..20 {
1317 if reply.status.as_u16() != 409 {
1318 break;
1319 }
1320 asyncrt::sleep(Duration::from_millis(100)).await;
1321 let _ = self
1322 .docker
1323 .call(
1324 "DELETE",
1325 &format!("/containers/{}?force=true", cell.name),
1326 None,
1327 )
1328 .await;
1329 reply = self
1330 .docker
1331 .call(
1332 "POST",
1333 &format!("/containers/create?name={}", cell.name),
1334 Some(body.clone()),
1335 )
1336 .await?;
1337 }
1338 if reply.status.as_u16() == 404 {
1339 return Err(anyhow!("No such image available named {}", cell.spec.image));
1340 }
1341 if !reply.status.is_success() {
1342 return Err(anyhow!(
1343 "Create container failed with [{}] {}",
1344 reply.status.as_u16(),
1345 reply.message()
1346 ));
1347 }
1348 self.docker
1349 .expect(
1350 "POST",
1351 &format!("/containers/{}/start", cell.name),
1352 None,
1353 "start container",
1354 )
1355 .await?;
1356 let info = self
1357 .docker
1358 .expect(
1359 "GET",
1360 &format!("/containers/{}/json", cell.name),
1361 None,
1362 "inspect container",
1363 )
1364 .await?
1365 .json()?;
1366 Ok(address_of(&info))
1367 }
1368
1369 /// Wait for the current run to end. `Ok(code)` is the root process's
1370 /// exit code; a destroyed container reports 137.
1371 pub async fn monitor(&self, cell: &Arc<CellContainer>, run: u64) -> Result<i64, String> {
1372 let mut receiver = cell.exit.subscribe();
1373 loop {
1374 if let Some((ended, result)) = receiver.borrow_and_update().clone() {
1375 if ended >= run {
1376 return result;
1377 }
1378 }
1379 if receiver.changed().await.is_err() {
1380 return Err("the container engine went away".to_string());
1381 }
1382 }
1383 }
1384
1385 pub async fn destroy(&self, cell: &Arc<CellContainer>) -> anyhow::Result<()> {
1386 // Kill first so the wait task reports 137 before the removal makes
1387 // the name disappear under it.
1388 let _ = self
1389 .docker
1390 .call(
1391 "POST",
1392 &format!("/containers/{}/kill?signal=SIGKILL", cell.name),
1393 None,
1394 )
1395 .await;
1396 let _ = self
1397 .docker
1398 .call(
1399 "DELETE",
1400 &format!("/containers/{}?force=true", cell.name),
1401 None,
1402 )
1403 .await;
1404 let mut state = cell.state.lock().unwrap();
1405 state.running = false;
1406 state.address = Address::None;
1407 Ok(())
1408 }
1409
1410 pub async fn signal(&self, cell: &Arc<CellContainer>, signal: u32) -> anyhow::Result<()> {
1411 self.docker
1412 .expect(
1413 "POST",
1414 &format!("/containers/{}/kill?signal={signal}", cell.name),
1415 None,
1416 "signal container",
1417 )
1418 .await?;
1419 Ok(())
1420 }
1421
1422 /// The cell left this node's runtime. An idle eviction keeps the
1423 /// container for its inactivity window; anything else destroys it, and
1424 /// the stop waits for that: a drain ends the process right after its
1425 /// last stop, and a destroy left to a detached task did not always get
1426 /// its two daemon calls in before the exit.
1427 pub async fn release(self: &Arc<Self>, scope: &str, release: Release) {
1428 let Some(cell) = self.cell(scope) else {
1429 return;
1430 };
1431 match release {
1432 Release::Keep => {
1433 let window = cell
1434 .state
1435 .lock()
1436 .unwrap()
1437 .inactivity
1438 .unwrap_or(DEFAULT_INACTIVITY);
1439 let engine = self.clone();
1440 let cell_ = cell.clone();
1441 let sweeper = asyncrt::spawn(async move {
1442 asyncrt::sleep(window).await;
1443 engine.forget(&cell_).await;
1444 });
1445 cell.state.lock().unwrap().sweeper = Some(sweeper);
1446 }
1447 Release::Destroy => self.forget(&cell).await,
1448 }
1449 }
1450
1451 async fn forget(&self, cell: &Arc<CellContainer>) {
1452 let _ = self.destroy(cell).await;
1453 for id in cell.processes.lock().unwrap().drain(..) {
1454 drop_process(id);
1455 }
1456 let mut cells = self.cells.lock().unwrap();
1457 if cells
1458 .get(&cell.scope)
1459 .is_some_and(|current| Arc::ptr_eq(current, cell))
1460 {
1461 cells.remove(&cell.scope);
1462 }
1463 }
1464
1465 pub async fn exec(
1466 &self,
1467 cell: &Arc<CellContainer>,
1468 params: ExecParams,
1469 ) -> anyhow::Result<Arc<ExecProcess>> {
1470 if !cell.running() {
1471 return Err(anyhow!("exec() requires a running container."));
1472 }
1473 let mut body = json!({
1474 "AttachStdin": true,
1475 "AttachStdout": true,
1476 "AttachStderr": true,
1477 "Tty": false,
1478 "Cmd": params.cmd,
1479 });
1480 if !params.env.is_empty() {
1481 body["Env"] = json!(params
1482 .env
1483 .iter()
1484 .map(|(name, value)| format!("{name}={value}"))
1485 .collect::<Vec<_>>());
1486 }
1487 if let Some(cwd) = &params.cwd {
1488 body["WorkingDir"] = json!(cwd);
1489 }
1490 if let Some(user) = &params.user {
1491 body["User"] = json!(user);
1492 }
1493 let created = self
1494 .docker
1495 .expect(
1496 "POST",
1497 &format!("/containers/{}/exec", cell.name),
1498 Some(body),
1499 "create exec",
1500 )
1501 .await?
1502 .json()?;
1503 let exec_id = created
1504 .get("Id")
1505 .and_then(Value::as_str)
1506 .ok_or_else(|| anyhow!("exec create answered without an id"))?
1507 .to_string();
1508 let stream = self
1509 .docker
1510 .hijack(
1511 &format!("/exec/{exec_id}/start"),
1512 json!({ "Detach": false, "Tty": false }),
1513 )
1514 .await?;
1515 // Docker reports `Running: false` with no pid before it has spawned
1516 // the process, and a finished exec keeps its pid, so a pid of zero
1517 // is the one answer that means "not yet": retry it briefly, as
1518 // workerd does. Breaking on `Running: false` here lost the pid of a
1519 // short command whenever the inspect landed in that window.
1520 let mut pid = 0;
1521 for _ in 0..20 {
1522 let info = self
1523 .docker
1524 .expect(
1525 "GET",
1526 &format!("/exec/{exec_id}/json"),
1527 None,
1528 "inspect exec",
1529 )
1530 .await?
1531 .json()?;
1532 pid = info.get("Pid").and_then(Value::as_i64).unwrap_or(0);
1533 if pid != 0 {
1534 break;
1535 }
1536 asyncrt::sleep(Duration::from_millis(50)).await;
1537 }
1538 let (read, write) = tokio::io::split(stream);
1539 let (stdout_tx, stdout_rx) = mpsc::channel(16);
1540 let (stderr_tx, stderr_rx) = mpsc::channel(16);
1541 let combined = params.combined;
1542 let ended = watch::channel(false).0;
1543 let ended_ = ended.clone();
1544 asyncrt::spawn(async move {
1545 demux(read, stdout_tx, stderr_tx, combined).await;
1546 ended_.send_replace(true);
1547 })
1548 .detach();
1549 let process = Arc::new(ExecProcess {
1550 id: next_exec_id(),
1551 exec_id,
1552 container: cell.name.clone(),
1553 pid,
1554 docker: self.docker.clone(),
1555 stdin: tokio::sync::Mutex::new(Some(write)),
1556 stdout: tokio::sync::Mutex::new(stdout_rx),
1557 stderr: tokio::sync::Mutex::new(stderr_rx),
1558 ended,
1559 exit_code: tokio::sync::Mutex::new(None),
1560 });
1561 processes()
1562 .lock()
1563 .unwrap()
1564 .insert(process.id, process.clone());
1565 cell.processes.lock().unwrap().push(process.id);
1566 Ok(process)
1567 }
1568}
1569
1570pub struct ExecParams {
1571 pub cmd: Vec<String>,
1572 pub env: Vec<(String, String)>,
1573 pub cwd: Option<String>,
1574 pub user: Option<String>,
1575 /// stderr folded into stdout.
1576 pub combined: bool,
1577}
1578
1579type WriteHalf = tokio::io::WriteHalf<Box<dyn Stream>>;
1580
1581pub struct ExecProcess {
1582 pub id: u64,
1583 exec_id: String,
1584 container: String,
1585 pub pid: i64,
1586 docker: Docker,
1587 stdin: tokio::sync::Mutex<Option<WriteHalf>>,
1588 stdout: tokio::sync::Mutex<mpsc::Receiver<Bytes>>,
1589 stderr: tokio::sync::Mutex<mpsc::Receiver<Bytes>>,
1590 /// True once the hijacked stream reached EOF, which the daemon sends
1591 /// when the process exits.
1592 ended: watch::Sender<bool>,
1593 exit_code: tokio::sync::Mutex<Option<i64>>,
1594}
1595
1596fn processes() -> &'static Mutex<HashMap<u64, Arc<ExecProcess>>> {
1597 static PROCESSES: OnceLock<Mutex<HashMap<u64, Arc<ExecProcess>>>> = OnceLock::new();
1598 PROCESSES.get_or_init(Default::default)
1599}
1600
1601fn next_exec_id() -> u64 {
1602 static NEXT: AtomicU64 = AtomicU64::new(1);
1603 NEXT.fetch_add(1, Ordering::Relaxed)
1604}
1605
1606pub fn process(id: u64) -> Option<Arc<ExecProcess>> {
1607 processes().lock().unwrap().get(&id).cloned()
1608}
1609
1610pub fn drop_process(id: u64) {
1611 processes().lock().unwrap().remove(&id);
1612}
1613
1614impl ExecProcess {
1615 /// One chunk of stdout (`1`) or stderr (`2`); empty at end of stream.
1616 pub async fn read(&self, which: u8) -> Bytes {
1617 let mut receiver = match which {
1618 1 => self.stdout.lock().await,
1619 _ => self.stderr.lock().await,
1620 };
1621 receiver.recv().await.unwrap_or_default()
1622 }
1623
1624 pub async fn write(&self, bytes: &[u8]) -> Result<(), String> {
1625 let mut guard = self.stdin.lock().await;
1626 let stdin = guard.as_mut().ok_or("stdin is closed")?;
1627 stdin
1628 .write_all(bytes)
1629 .await
1630 .map_err(|error| format!("stdin write failed: {error}"))?;
1631 stdin
1632 .flush()
1633 .await
1634 .map_err(|error| format!("stdin flush failed: {error}"))
1635 }
1636
1637 /// End stdin. Half-closing the hijacked connection is how the daemon
1638 /// learns the process's stdin reached EOF.
1639 pub async fn close_stdin(&self) {
1640 if let Some(mut stdin) = self.stdin.lock().await.take() {
1641 let _ = stdin.shutdown().await;
1642 }
1643 }
1644
1645 pub async fn wait(&self) -> anyhow::Result<i64> {
1646 let mut exit = self.exit_code.lock().await;
1647 if let Some(code) = *exit {
1648 return Ok(code);
1649 }
1650 let mut ended = self.ended.subscribe();
1651 while !*ended.borrow_and_update() {
1652 if ended.changed().await.is_err() {
1653 break;
1654 }
1655 }
1656 // The stream closes when the process exits, but the daemon records
1657 // the exit code a moment later.
1658 let mut code = None;
1659 for _ in 0..40 {
1660 let info = self
1661 .docker
1662 .expect(
1663 "GET",
1664 &format!("/exec/{}/json", self.exec_id),
1665 None,
1666 "inspect exec",
1667 )
1668 .await?
1669 .json()?;
1670 if !info
1671 .get("Running")
1672 .and_then(Value::as_bool)
1673 .unwrap_or(false)
1674 {
1675 code = info.get("ExitCode").and_then(Value::as_i64);
1676 break;
1677 }
1678 asyncrt::sleep(Duration::from_millis(50)).await;
1679 }
1680 let code = code.ok_or_else(|| anyhow!("the process did not report an exit code"))?;
1681 *exit = Some(code);
1682 Ok(code)
1683 }
1684
1685 /// The Engine API has no exec kill, so the signal is delivered by a
1686 /// second exec of `kill`, as workerd does.
1687 pub async fn kill(&self, signal: u32) -> anyhow::Result<()> {
1688 let body = json!({
1689 "AttachStdin": false, "AttachStdout": false, "AttachStderr": false,
1690 "Cmd": ["kill", format!("-{signal}"), self.pid.to_string()],
1691 });
1692 let created = self
1693 .docker
1694 .expect(
1695 "POST",
1696 &format!("/containers/{}/exec", self.container),
1697 Some(body),
1698 "create exec",
1699 )
1700 .await?
1701 .json()?;
1702 let id = created
1703 .get("Id")
1704 .and_then(Value::as_str)
1705 .ok_or_else(|| anyhow!("exec create answered without an id"))?;
1706 self.docker
1707 .expect(
1708 "POST",
1709 &format!("/exec/{id}/start"),
1710 Some(json!({ "Detach": true })),
1711 "start exec",
1712 )
1713 .await?;
1714 Ok(())
1715 }
1716}
1717
1718/// Split Docker's multiplexed stream into stdout and stderr chunks until
1719/// the daemon closes it.
1720async fn demux(
1721 mut read: tokio::io::ReadHalf<Box<dyn Stream>>,
1722 stdout: mpsc::Sender<Bytes>,
1723 stderr: mpsc::Sender<Bytes>,
1724 combined: bool,
1725) {
1726 let mut header = [0u8; 8];
1727 loop {
1728 if read.read_exact(&mut header).await.is_err() {
1729 return;
1730 }
1731 let (stream, length) = frame_header(&header);
1732 let mut payload = vec![0u8; length];
1733 if read.read_exact(&mut payload).await.is_err() {
1734 return;
1735 }
1736 let target = if stream == 2 && !combined {
1737 &stderr
1738 } else {
1739 &stdout
1740 };
1741 if target.send(Bytes::from(payload)).await.is_err() {
1742 // The reader went away; keep draining so the process is not
1743 // blocked on a full pipe.
1744 continue;
1745 }
1746 }
1747}
1748
1749fn address_of(info: &Value) -> Address {
1750 if cfg!(target_os = "linux") {
1751 let ip = info
1752 .pointer("/NetworkSettings/Networks")
1753 .and_then(Value::as_object)
1754 .and_then(|networks| networks.values().next())
1755 .and_then(|network| network.get("IPAddress"))
1756 .and_then(Value::as_str)
1757 .filter(|ip| !ip.is_empty());
1758 return ip.map_or(Address::None, |ip| Address::Ip(ip.to_string()));
1759 }
1760 let mut ports = HashMap::new();
1761 if let Some(map) = info
1762 .pointer("/NetworkSettings/Ports")
1763 .and_then(Value::as_object)
1764 {
1765 for (key, bindings) in map {
1766 let Some(port) = key
1767 .strip_suffix("/tcp")
1768 .and_then(|port| port.parse::<u16>().ok())
1769 else {
1770 continue;
1771 };
1772 let host = bindings
1773 .as_array()
1774 .into_iter()
1775 .flatten()
1776 .find_map(|binding| binding.get("HostPort")?.as_str()?.parse::<u16>().ok());
1777 if let Some(host) = host {
1778 ports.insert(port, host);
1779 }
1780 }
1781 }
1782 Address::Published(ports)
1783}
1784
1785/// A Docker name from a node and a cell scope: the scope's characters are
1786/// not all legal, so the name is a hash and the scope rides in a label.
1787/// The node is part of it because two nodes can share one engine in a
1788/// development or test setup, and a name from the scope alone let one
1789/// node adopt, or reap, the other's container for the same object.
1790fn container_name(node: &str, scope: &str) -> String {
1791 use sha2::Digest;
1792 let digest = sha2::Sha256::digest(format!("{node}\n{scope}").as_bytes());
1793 format!("celld-{:x}", digest)[..30].to_string()
1794}
1795
1796#[cfg(test)]
1797mod fence_rule_tests {
1798 use super::*;
1799
1800 #[test]
1801 #[allow(clippy::disallowed_methods)]
1802 fn exceptions_go_inside_the_fence_chains() {
1803 // SAFETY: tests in this module run in one thread; nothing else reads these.
1804 unsafe {
1805 std::env::remove_var("CELLD_FENCE_ALLOW");
1806 std::env::remove_var("CELLD_FENCE_DNAT");
1807 }
1808 let rt = tokio::runtime::Builder::new_current_thread()
1809 .enable_all()
1810 .build()
1811 .unwrap();
1812 let render = |base| rt.block_on(fence_rules(base));
1813 let plain = render(FENCE_RULES_NETNS).unwrap();
1814 assert!(
1815 !plain.contains("#ALLOW")
1816 && !plain.contains("#CHAINS")
1817 && !plain.contains("prerouting")
1818 );
1819 assert_eq!(
1820 plain.matches("reject").count(),
1821 FENCE_RULES_NETNS.matches("reject").count()
1822 );
1823 let upstream = render(FENCE_RULES).unwrap();
1824 assert!(!upstream.contains('#'));
1825
1826 unsafe {
1827 std::env::set_var("CELLD_FENCE_ALLOW", "192.168.50.189:8444");
1828 std::env::set_var("CELLD_FENCE_DNAT", "192.168.50.189:443=192.168.50.189:8444");
1829 }
1830 let rules = render(FENCE_RULES_NETNS).unwrap();
1831 let accept =
1832 r#"iifname { "celld0", "celld1" } ip daddr 192.168.50.189 tcp dport 8444 accept"#;
1833 assert_eq!(rules.matches(accept).count(), 2, "{rules}");
1834 // Each accept comes before its chain's first reject.
1835 for chain in ["chain input", "chain forward"] {
1836 let body = &rules[rules.find(chain).unwrap()..];
1837 let body = &body[..body.find(" }").unwrap()];
1838 assert!(
1839 body.find(accept).unwrap() < body.find("reject").unwrap(),
1840 "{body}"
1841 );
1842 }
1843 assert!(rules.contains("type nat hook prerouting priority -110"));
1844 assert!(
1845 rules.contains("ip daddr 192.168.50.189 tcp dport 443 ct mark set ct mark | 0x00001000 dnat ip to 192.168.50.189:8444")
1846 );
1847
1848 unsafe {
1849 std::env::set_var(
1850 "CELLD_FENCE_ALLOW",
1851 "192.168.50.189:8444; nft flush ruleset",
1852 )
1853 };
1854 assert!(render(FENCE_RULES_NETNS).is_err());
1855 // The node's own connections into the bridges get the mark, in a
1856 // table of the node's own.
1857 unsafe {
1858 std::env::remove_var("CELLD_FENCE_ALLOW");
1859 std::env::remove_var("CELLD_FENCE_DNAT");
1860 std::env::set_var("CELLD_FENCE_NODE", "localhost");
1861 }
1862 let node = render(FENCE_RULES_NETNS).unwrap();
1863 assert!(node.contains("table inet celld_node_localhost {"), "{node}");
1864 assert!(
1865 node.contains("delete table inet celld_node_localhost\n"),
1866 "{node}"
1867 );
1868 assert!(node.contains(r#"ip saddr 127.0.0.1 oifname { "celld0", "celld1" } ct state new ct mark set ct mark | 0x00001000"#), "{node}");
1869 unsafe { std::env::set_var("CELLD_FENCE_NODE", "bad host; flush ruleset") };
1870 assert!(render(FENCE_RULES_NETNS).is_err());
1871 unsafe { std::env::remove_var("CELLD_FENCE_NODE") };
1872 // A hostname target resolves to its IPv4 address.
1873 unsafe { std::env::set_var("CELLD_FENCE_ALLOW", "localhost:8444") };
1874 assert!(render(FENCE_RULES_NETNS)
1875 .unwrap()
1876 .contains("ip daddr 127.0.0.1 tcp dport 8444 accept"));
1877 unsafe {
1878 std::env::remove_var("CELLD_FENCE_ALLOW");
1879 std::env::remove_var("CELLD_FENCE_DNAT");
1880 }
1881 }
1882}