Diffinery

homeflare/celldpublic

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