Diffinery

homeflare/celldpublic

celld/crates/celld/container.rs
1588 lines · 59.2 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 iifname { "celld0", "celld1" } reject
153 }
154 chain forward {
155 type filter hook forward priority -10; policy accept;
156 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
157 iifname { "celld0", "celld1" } ip6 daddr { fe80::/10, fc00::/7 } reject
158 }
159}
160"#;
161
162/// Docker's bridge option that forbids traffic between two containers on
163/// the same bridge. The node still reaches every container, because it
164/// speaks from the host side of the bridge.
165const ICC_OPTION: &str = "com.docker.network.bridge.enable_icc";
166
167/// How a cell stop treats its container.
168#[derive(Clone, Copy, Debug, PartialEq, Eq)]
169pub enum Release {
170 /// An idle eviction: keep the container under its inactivity timer.
171 Keep,
172 /// Ownership leaves this node, or the cell is reset: destroy it.
173 Destroy,
174}
175
176/// The default inactivity window after an idle eviction when the object
177/// never set one. The `@cloudflare/containers` alarm wakes the object well
178/// inside this to enforce `sleepAfter`, so this is the backstop for an
179/// object that never wakes, not the policy.
180const DEFAULT_INACTIVITY: Duration = Duration::from_secs(10 * 60);
181
182/// Environment every container sees. The values mirror workerd's local
183/// engine: applications read the names, never the values.
184const DEFAULT_ENV: &[&str] = &[
185 "CLOUDFLARE_COUNTRY_A2=XX",
186 "CLOUDFLARE_DEPLOYMENT_ID=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
187 "CLOUDFLARE_LOCATION=loc01",
188 "CLOUDFLARE_REGION=REGN",
189 "CLOUDFLARE_APPLICATION_ID=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
190];
191
192pub struct StartParams {
193 pub entrypoint: Option<Vec<String>>,
194 pub env: Vec<(String, String)>,
195 pub enable_internet: bool,
196 pub labels: Vec<(String, String)>,
197}
198
199#[derive(Default)]
200struct CellState {
201 running: bool,
202 /// Where the node dials the container: the bridge address on Linux,
203 /// the published loopback ports elsewhere.
204 address: Address,
205 inactivity: Option<Duration>,
206 /// The pending destroy after an idle eviction. Dropping it cancels.
207 sweeper: Option<asyncrt::TaskHandle<()>>,
208 /// Bumped per start so a wait from a previous run cannot report for
209 /// this one.
210 run: u64,
211}
212
213#[derive(Clone, Debug, Default)]
214enum Address {
215 #[default]
216 None,
217 Ip(String),
218 Published(HashMap<u16, u16>),
219}
220
221pub struct CellContainer {
222 scope: String,
223 name: String,
224 spec: Arc<ContainerSpec>,
225 state: Mutex<CellState>,
226 /// Processes `exec()` started in this container. An object drops one
227 /// after `output()`; the rest go with the container.
228 processes: Mutex<Vec<u64>>,
229 /// The exit of the current run, `None` while it runs. `Some(Err)` is
230 /// an engine failure the wait could not attribute to the process.
231 /// Written with `send_replace`: a plain `send` discards the value
232 /// while nobody subscribes, and `monitor()` usually subscribes late.
233 exit: watch::Sender<Option<(u64, Result<i64, String>)>>,
234}
235
236impl CellContainer {
237 pub fn running(&self) -> bool {
238 self.state.lock().unwrap().running
239 }
240
241 /// `host:port` for `getTcpPort(port)`.
242 pub fn address(&self, port: u16) -> Result<String, String> {
243 let state = self.state.lock().unwrap();
244 if !state.running {
245 return Err("the container is not running".to_string());
246 }
247 match &state.address {
248 Address::Ip(ip) => Ok(format!("{ip}:{port}")),
249 Address::Published(ports) => ports
250 .get(&port)
251 .map(|host| format!("127.0.0.1:{host}"))
252 .ok_or_else(|| {
253 format!(
254 "The container is not listening on port {port}: on this platform a port \
255 must be declared with EXPOSE in the image"
256 )
257 }),
258 Address::None => Err(format!("The container is not listening on port {port}")),
259 }
260 }
261
262 pub fn set_inactivity(&self, duration: Duration) {
263 self.state.lock().unwrap().inactivity = Some(duration);
264 }
265
266 /// Open the next run, synchronously, before the start is even queued.
267 /// The object's `start()` returns at once and its `monitor()` follows
268 /// immediately, so the run they both mean must exist before either
269 /// effect runs, or the monitor would find the previous run's exit and
270 /// report the new container dead on arrival.
271 pub fn begin_run(&self) -> u64 {
272 let mut state = self.state.lock().unwrap();
273 state.run += 1;
274 state.running = true;
275 state.address = Address::None;
276 let run = state.run;
277 drop(state);
278 self.exit.send_replace(None);
279 run
280 }
281
282 /// The run `monitor()` waits on: the newest one.
283 pub fn current_run(&self) -> u64 {
284 self.state.lock().unwrap().run
285 }
286}
287
288pub struct ContainerEngine {
289 /// See `Config::runtime`.
290 runtime: Option<String>,
291 /// See `Config::dns`.
292 dns: Vec<String>,
293 /// The absolute path of the container resolv.conf this engine wrote and
294 /// bind-mounts; `None` when it could not be written.
295 resolv_conf: Option<PathBuf>,
296 docker: Docker,
297 node: String,
298 bucket: Option<crate::bucket::Bucket>,
299 /// Per-image load lock, so two cells of one class starting together
300 /// load the tar once.
301 images: Mutex<HashMap<String, Arc<tokio::sync::Mutex<bool>>>>,
302 cells: Mutex<HashMap<String, Arc<CellContainer>>>,
303 networks: tokio::sync::Mutex<Option<(String, String)>>,
304 /// Whether this process has installed the fence on the node's bridges.
305 fenced: tokio::sync::Mutex<bool>,
306}
307
308/// What the runtime told this module about the node: set once at start.
309struct Config {
310 node: String,
311 bucket: Option<crate::bucket::Bucket>,
312 /// `CELLD_CONTAINER_RUNTIME`: the OCI runtime every container starts
313 /// under, such as `runsc` (gVisor) or `kata` (a VM). `None` is the
314 /// daemon's default, which is `runc` unless the operator changed it. A
315 /// class can override it, see `ContainerSpec::runtime`.
316 runtime: Option<String>,
317 /// `CELLD_CONTAINER_DNS`: the resolvers a container gets, overriding
318 /// `DEFAULT_CONTAINER_DNS`. Empty takes the default when a runtime is in
319 /// use and the daemon's otherwise.
320 dns: Vec<String>,
321 /// The node's state directory. celld writes the container resolv.conf
322 /// here and bind-mounts it, so the path must be the same on the host as
323 /// celld sees it; a self-hosted node runs celld as a host process, and
324 /// the lab mounts the directory one-to-one.
325 data_dir: PathBuf,
326}
327
328static CONFIG: RwLock<Option<Config>> = RwLock::new(None);
329/// The deployment's container classes. Replaced on every generation swap;
330/// a running container keeps the spec it started with.
331static SPECS: RwLock<Vec<Arc<ContainerSpec>>> = RwLock::new(Vec::new());
332/// The deployment's `celld-fence` image; see `Manifest::fence_image`.
333static FENCE_IMAGE: RwLock<Option<String>> = RwLock::new(None);
334/// The engine, connected on first use. A node whose deployment declares no
335/// container class never opens the socket.
336static ENGINE: tokio::sync::OnceCell<Arc<ContainerEngine>> = tokio::sync::OnceCell::const_new();
337
338pub fn configure(node: String, bucket: Option<crate::bucket::Bucket>, data_dir: PathBuf) {
339 let runtime = std::env::var("CELLD_CONTAINER_RUNTIME")
340 .ok()
341 .filter(|runtime| !runtime.is_empty());
342 let dns = std::env::var("CELLD_CONTAINER_DNS")
343 .unwrap_or_default()
344 .split(',')
345 .map(|resolver| resolver.trim().to_string())
346 .filter(|resolver| !resolver.is_empty())
347 .collect();
348 *CONFIG.write().unwrap() = Some(Config {
349 node,
350 bucket,
351 runtime,
352 dns,
353 data_dir,
354 });
355}
356
357pub fn install_specs(specs: Vec<ContainerSpec>, fence_image: Option<String>) {
358 *SPECS.write().unwrap() = specs.into_iter().map(Arc::new).collect();
359 *FENCE_IMAGE.write().unwrap() = fence_image;
360}
361
362pub fn spec(class: &str) -> Option<Arc<ContainerSpec>> {
363 SPECS
364 .read()
365 .unwrap()
366 .iter()
367 .find(|spec| spec.class_name == class)
368 .cloned()
369}
370
371/// The engine, connecting on the first call. A failure is returned rather
372/// than cached, so a daemon that comes up later is found by the next call.
373pub async fn engine() -> anyhow::Result<Arc<ContainerEngine>> {
374 ENGINE
375 .get_or_try_init(|| async {
376 let (node, bucket, runtime, dns, data_dir) = {
377 let config = CONFIG.read().unwrap();
378 let config = config.as_ref().ok_or_else(|| {
379 anyhow!("the container engine is not configured on this node")
380 })?;
381 (
382 config.node.clone(),
383 config.bucket.clone(),
384 config.runtime.clone(),
385 config.dns.clone(),
386 config.data_dir.clone(),
387 )
388 };
389 let docker = Docker::discover().ok_or_else(|| {
390 anyhow!(
391 "no container engine: set DOCKER_HOST to a unix socket, or run a Docker or \
392 Podman daemon on this node"
393 )
394 })?;
395 Ok(Arc::new(
396 ContainerEngine::connect(docker, node, bucket, runtime, dns, data_dir).await?,
397 ))
398 })
399 .await
400 .cloned()
401}
402
403/// The engine only if a previous call connected it.
404pub fn engine_if_ready() -> Option<Arc<ContainerEngine>> {
405 ENGINE.get().cloned()
406}
407
408/// Destroy every container of this node at process exit. A preserve
409/// shutdown (`celld dev` on Ctrl-C) keeps its cells resident and stops
410/// none of them, and a handoff cut by the deadline leaves cells behind
411/// too; without this their containers ran on until the next start of the
412/// same node reaped them, invisible to the object that owned them.
413pub async fn shutdown() {
414 let Some(engine) = engine_if_ready() else {
415 return;
416 };
417 if let Err(error) = engine.reap().await {
418 tracing::warn!(
419 event = "container_shutdown_reap_failed",
420 error = %format!("{error:#}"),
421 "containers of this node may still be running"
422 );
423 }
424}
425
426/// Connect and load every image of the installed specs, ahead of the
427/// first cell that needs one. Failures are logged: a node without an
428/// engine still serves every other class, and the container class fails
429/// at its first `start()` with the same message.
430pub async fn prewarm() {
431 let engine = match engine().await {
432 Ok(engine) => engine,
433 Err(error) => {
434 tracing::warn!(error = %format!("{error:#}"), "containers are unavailable on this node");
435 return;
436 }
437 };
438 if let Err(error) = engine.ensure_fence().await {
439 tracing::warn!(
440 error = %format!("{error:#}"),
441 "the container bridges are not fenced; no container starts on this node"
442 );
443 }
444 let specs = SPECS.read().unwrap().clone();
445 for spec in specs {
446 if let Err(error) = engine.ensure_image(&spec.image).await {
447 tracing::warn!(
448 class = %spec.class_name,
449 image = %spec.image,
450 error = %format!("{error:#}"),
451 "container image is unavailable"
452 );
453 }
454 }
455}
456
457impl ContainerEngine {
458 /// Connect to the engine and reap every container a previous process
459 /// of this node left behind. A restarted node cannot know which of its
460 /// containers still belong to cells it will own again, and a container
461 /// whose object has lost track of it is a leak, so a restart starts
462 /// clean. The next `start()` of each object creates a fresh one.
463 pub async fn connect(
464 docker: Docker,
465 node: String,
466 bucket: Option<crate::bucket::Bucket>,
467 runtime: Option<String>,
468 dns: Vec<String>,
469 data_dir: PathBuf,
470 ) -> anyhow::Result<Self> {
471 // Write the resolv.conf once, to bind into every container that runs
472 // under a non-default runtime. gVisor cannot reach Docker's embedded
473 // resolver, so a bind-mounted file with a public resolver, which the
474 // fence permits, is the only resolv.conf the container can use.
475 let resolvers: Vec<String> = if dns.is_empty() {
476 DEFAULT_CONTAINER_DNS
477 .iter()
478 .map(|r| r.to_string())
479 .collect()
480 } else {
481 dns.clone()
482 };
483 let resolv_conf = {
484 let path = data_dir.join("container-resolv.conf");
485 let body: String = resolvers
486 .iter()
487 .map(|resolver| format!("nameserver {resolver}\n"))
488 .collect();
489 let fs = asyncrt::fs();
490 match fs
491 .create_dir_all(&data_dir)
492 .and_then(|()| fs.write(&path, body.as_bytes()))
493 {
494 Ok(()) => Some(path),
495 Err(error) => {
496 tracing::warn!(event = "container_resolv_write_failed", %error);
497 None
498 }
499 }
500 };
501 let engine = Self {
502 docker,
503 node,
504 bucket,
505 runtime,
506 dns,
507 resolv_conf,
508 images: Mutex::new(HashMap::new()),
509 cells: Mutex::new(HashMap::new()),
510 networks: tokio::sync::Mutex::new(None),
511 fenced: tokio::sync::Mutex::new(false),
512 };
513 engine.reap().await?;
514 Ok(engine)
515 }
516
517 pub fn socket(&self) -> &std::path::Path {
518 self.docker.socket()
519 }
520
521 async fn reap(&self) -> anyhow::Result<()> {
522 let filters = json!({ "label": [format!("celld.node={}", self.node)] }).to_string();
523 let reply = self
524 .docker
525 .expect(
526 "GET",
527 &format!(
528 "/containers/json?all=true&filters={}",
529 percent_encoding::utf8_percent_encode(
530 &filters,
531 percent_encoding::NON_ALPHANUMERIC
532 )
533 ),
534 None,
535 "list containers",
536 )
537 .await?;
538 let list = reply.json()?;
539 for entry in list.as_array().into_iter().flatten() {
540 if let Some(id) = entry.get("Id").and_then(Value::as_str) {
541 let _ = self
542 .docker
543 .call("DELETE", &format!("/containers/{id}?force=true"), None)
544 .await;
545 }
546 }
547 Ok(())
548 }
549
550 /// Make the class's image present in the engine, loading it from the
551 /// bucket when it is not. Idempotent and serialized per image.
552 pub async fn ensure_image(&self, image: &str) -> anyhow::Result<()> {
553 let lock = self
554 .images
555 .lock()
556 .unwrap()
557 .entry(image.to_string())
558 .or_insert_with(|| Arc::new(tokio::sync::Mutex::new(false)))
559 .clone();
560 let mut loaded = lock.lock().await;
561 if *loaded {
562 return Ok(());
563 }
564 let reply = self
565 .docker
566 .call("GET", &format!("/images/{image}/json"), None)
567 .await?;
568 if reply.status.is_success() {
569 tracing::info!(image, "container image present in the engine");
570 *loaded = true;
571 return Ok(());
572 }
573 let bucket = self
574 .bucket
575 .as_ref()
576 .ok_or_else(|| anyhow!("image {image} is not present in the container engine"))?;
577 let key = image_key(image);
578 let (tar, _) = bucket.get(&key).await?.ok_or_else(|| {
579 anyhow!("image {image} is not in the bucket at {key}; run `celld deploy`")
580 })?;
581 let bytes = tar.len();
582 let reply = self
583 .docker
584 .post_octets("/images/load?quiet=true", tar, "load image")
585 .await?;
586 tracing::info!(
587 image,
588 bytes,
589 answer = %String::from_utf8_lossy(&reply.body).trim_end(),
590 "container image loaded from the bucket"
591 );
592 *loaded = true;
593 Ok(())
594 }
595
596 /// The two bridges every container joins: one with egress, one
597 /// without. Docker implements an internal network by omitting the
598 /// masquerade rule and the default route; the node still reaches the
599 /// bridge address, which is all ingress needs.
600 async fn networks(&self) -> anyhow::Result<(String, String)> {
601 let mut guard = self.networks.lock().await;
602 if let Some(names) = guard.as_ref() {
603 return Ok(names.clone());
604 }
605 for (name, internal) in [("celld", false), ("celld-internal", true)] {
606 // A bridge keeps the options it was created with, so one from
607 // before containers were isolated from each other is replaced.
608 // The replacement fails while a container is attached, which a
609 // node start after its reap never has; a failure keeps the old
610 // bridge and says so rather than refusing every container.
611 let current = self
612 .docker
613 .call("GET", &format!("/networks/{name}"), None)
614 .await?;
615 if current.status.is_success() {
616 let bridge = if internal {
617 INTERNAL_BRIDGE
618 } else {
619 OPEN_BRIDGE
620 };
621 let current_options = current
622 .json()
623 .ok()
624 .and_then(|network| network.get("Options").cloned())
625 .unwrap_or(Value::Null);
626 let option = |key: &str| current_options.get(key).and_then(Value::as_str);
627 if option(ICC_OPTION) == Some("false") && option(BRIDGE_NAME_OPTION) == Some(bridge)
628 {
629 continue;
630 }
631 let removed = self
632 .docker
633 .call("DELETE", &format!("/networks/{name}"), None)
634 .await?;
635 if !removed.status.is_success() {
636 tracing::warn!(
637 network = name,
638 error = %removed.message(),
639 "the container bridge predates container isolation and is in use; \
640 containers on it can reach each other until the node restarts idle"
641 );
642 continue;
643 }
644 }
645 let reply = self
646 .docker
647 .call(
648 "POST",
649 "/networks/create",
650 Some(json!({
651 "Name": name,
652 "Driver": "bridge",
653 "Internal": internal,
654 "Options": {
655 ICC_OPTION: "false",
656 BRIDGE_NAME_OPTION: if internal { INTERNAL_BRIDGE } else { OPEN_BRIDGE },
657 },
658 })),
659 )
660 .await?;
661 // 409: it exists, which is the steady state.
662 if !reply.status.is_success() && reply.status.as_u16() != 409 {
663 return Err(anyhow!(
664 "create network {name} failed with [{}] {}",
665 reply.status.as_u16(),
666 reply.message()
667 ));
668 }
669 }
670 let names = ("celld".to_string(), "celld-internal".to_string());
671 *guard = Some(names.clone());
672 Ok(names)
673 }
674
675 /// Install the fence on the node's bridges, once per process. Every
676 /// container start waits on this and fails when it fails: a node that
677 /// cannot fence its bridges runs no container, because an unfenced
678 /// container can reach the node's internal listener and the cloud's
679 /// metadata service. The rules live in the kernel and outlive this
680 /// process; a restart re-applies them, which is idempotent.
681 pub async fn ensure_fence(&self) -> anyhow::Result<()> {
682 let mut fenced = self.fenced.lock().await;
683 if *fenced {
684 return Ok(());
685 }
686 let image = FENCE_IMAGE.read().unwrap().clone().ok_or_else(|| {
687 anyhow!(
688 "this deployment has no fence image; deploy it again with this celld, which \
689 saves the celld-fence image beside the container images"
690 )
691 })?;
692 self.ensure_image(&image).await?;
693 self.networks().await?;
694 let body = json!({
695 "Image": image,
696 "Env": [format!("CELLD_NFT={FENCE_RULES}")],
697 "Cmd": ["sh", "-c", "printf '%s' \"$CELLD_NFT\" | nft -f -"],
698 "Labels": { "celld.node": self.node, "celld.fence": "1" },
699 "HostConfig": { "NetworkMode": "host", "CapAdd": ["NET_ADMIN"] },
700 });
701 let created = self
702 .docker
703 .expect(
704 "POST",
705 "/containers/create",
706 Some(body),
707 "create fence container",
708 )
709 .await?
710 .json()?;
711 let id = created
712 .get("Id")
713 .and_then(Value::as_str)
714 .ok_or_else(|| anyhow!("create fence container answered without an id"))?
715 .to_string();
716 let outcome = async {
717 self.docker
718 .expect(
719 "POST",
720 &format!("/containers/{id}/start"),
721 None,
722 "start fence container",
723 )
724 .await?;
725 let waited = self
726 .docker
727 .expect(
728 "POST",
729 &format!("/containers/{id}/wait"),
730 None,
731 "wait fence container",
732 )
733 .await?
734 .json()?;
735 let code = waited
736 .get("StatusCode")
737 .and_then(Value::as_i64)
738 .unwrap_or(-1);
739 if code != 0 {
740 let logs = self.logs(&id).await.unwrap_or_default();
741 return Err(anyhow!(
742 "the fence container exited with {code}: {}",
743 logs.trim()
744 ));
745 }
746 Ok(())
747 }
748 .await;
749 let _ = self
750 .docker
751 .call("DELETE", &format!("/containers/{id}?force=true"), None)
752 .await;
753 outcome.context("fence the container bridges")?;
754 tracing::info!(
755 event = "container_bridges_fenced",
756 bridges = format!("{OPEN_BRIDGE},{INTERNAL_BRIDGE}"),
757 "containers can reach the Internet and nothing of the node's own"
758 );
759 *fenced = true;
760 Ok(())
761 }
762
763 /// Both output streams of a stopped container, for an error message.
764 async fn logs(&self, id: &str) -> anyhow::Result<String> {
765 let reply = self
766 .docker
767 .expect(
768 "GET",
769 &format!("/containers/{id}/logs?stdout=true&stderr=true"),
770 None,
771 "container logs",
772 )
773 .await?;
774 let mut text = Vec::new();
775 let mut rest: &[u8] = &reply.body;
776 while rest.len() >= 8 {
777 let (_, length) = frame_header(rest[..8].try_into().unwrap());
778 let end = (8 + length).min(rest.len());
779 text.extend_from_slice(&rest[8..end]);
780 rest = &rest[end..];
781 }
782 Ok(String::from_utf8_lossy(&text).into_owned())
783 }
784
785 /// The cell's container handle, adopting a container a previous
786 /// activation on this node left running. Called at cell start for a
787 /// class with a spec; the object's `running` reads the answer.
788 pub async fn attach(&self, scope: &str, class: &str) -> anyhow::Result<Arc<CellContainer>> {
789 let spec = spec(class).ok_or_else(|| anyhow!("class {class} has no container"))?;
790 let cell = {
791 let mut cells = self.cells.lock().unwrap();
792 let cell = cells.entry(scope.to_string()).or_insert_with(|| {
793 Arc::new(CellContainer {
794 scope: scope.to_string(),
795 name: container_name(&self.node, scope),
796 spec,
797 state: Mutex::new(CellState::default()),
798 processes: Mutex::new(Vec::new()),
799 exit: watch::channel(None).0,
800 })
801 });
802 // A returning cell cancels the destroy its eviction armed.
803 cell.state.lock().unwrap().sweeper = None;
804 cell.clone()
805 };
806 let running = self.inspect_running(&cell).await?;
807 // A container this handle did not start, left running by an
808 // earlier owner of the name: give it a run so `monitor()` has an
809 // exit to wait for. The run opens before the address lands, because
810 // opening one clears it.
811 let adopted = running.is_some() && !cell.running();
812 if adopted {
813 let run = cell.begin_run();
814 self.watch_exit(&cell, run);
815 }
816 let mut state = cell.state.lock().unwrap();
817 state.running = running.is_some();
818 state.address = running.unwrap_or_default();
819 drop(state);
820 Ok(cell)
821 }
822
823 /// The cell's handle, if the cell started on this node.
824 pub fn cell(&self, scope: &str) -> Option<Arc<CellContainer>> {
825 self.cells.lock().unwrap().get(scope).cloned()
826 }
827
828 /// The memory the node's running containers reserve, summed over their
829 /// instance-type caps. A cell whose container is not running reserves
830 /// nothing: a stopped container holds no memory, and an idle eviction
831 /// stops it before the sample would count it.
832 pub fn reserved_memory_bytes(&self) -> u64 {
833 self.cells
834 .lock()
835 .unwrap()
836 .values()
837 .filter(|cell| cell.running())
838 .map(|cell| instance_memory_bytes(cell.spec.instance_type.as_deref()))
839 .sum()
840 }
841
842 /// This node's running containers per class.
843 fn running_instances_by_class(&self) -> std::collections::BTreeMap<String, u64> {
844 let mut counts = std::collections::BTreeMap::new();
845 for cell in self.cells.lock().unwrap().values() {
846 if cell.running() {
847 *counts.entry(cell.spec.class_name.clone()).or_insert(0) += 1;
848 }
849 }
850 counts
851 }
852
853 /// Refuse a start that would put the class over its fleet-wide
854 /// `max_instances`. The fleet count is this node's own running
855 /// containers of the class, read live, plus every peer's count from the
856 /// shared capacity sample; `begin_run` already marked the starting cell
857 /// running, so the live count includes it. A class with no
858 /// `max_instances`, or a node with no bucket to read the sample from as
859 /// under `celld dev`, has no fleet ceiling. See
860 /// [`crate::ownership_store::fleet_class_instances`] for the staleness
861 /// the sample admits.
862 async fn enforce_instance_ceiling(&self, cell: &CellContainer) -> anyhow::Result<()> {
863 let Some(max) = cell.spec.max_instances else {
864 return Ok(());
865 };
866 let class = &cell.spec.class_name;
867 let here = self
868 .cells
869 .lock()
870 .unwrap()
871 .values()
872 .filter(|other| other.running() && other.spec.class_name == *class)
873 .count() as u64;
874 let elsewhere = match &self.bucket {
875 Some(bucket) => {
876 crate::ownership_store::fleet_class_instances(bucket, class, &self.node).await
877 }
878 None => 0,
879 };
880 anyhow::ensure!(
881 here + elsewhere <= max,
882 "container class {class} is at its max_instances limit of {max}: \
883 {here} on this node and {elsewhere} on other nodes",
884 );
885 Ok(())
886 }
887
888 async fn inspect_running(&self, cell: &CellContainer) -> anyhow::Result<Option<Address>> {
889 let reply = self
890 .docker
891 .call("GET", &format!("/containers/{}/json", cell.name), None)
892 .await?;
893 if reply.status.as_u16() == 404 {
894 return Ok(None);
895 }
896 if !reply.status.is_success() {
897 return Err(anyhow!(
898 "inspect container failed with [{}] {}",
899 reply.status.as_u16(),
900 reply.message()
901 ));
902 }
903 let info = reply.json()?;
904 let running = info
905 .pointer("/State/Running")
906 .and_then(Value::as_bool)
907 .unwrap_or(false);
908 Ok(running.then(|| address_of(&info)))
909 }
910
911 /// Start the cell's container. The object's `start()` returns before
912 /// this completes, as on Cloudflare; a failure surfaces through
913 /// `monitor()`.
914 /// Start the cell's container for the run `begin_run` opened. The
915 /// object's `start()` returns before this completes, as on Cloudflare;
916 /// a failure surfaces through `monitor()`.
917 pub async fn start(
918 &self,
919 cell: &Arc<CellContainer>,
920 run: u64,
921 params: StartParams,
922 ) -> anyhow::Result<()> {
923 let started = self.create_and_start(cell, params).await;
924 let address = match started {
925 Ok(address) => address,
926 Err(error) => {
927 // `start()` is fire-and-forget for the object, and its
928 // `monitor()` sees this error only if it was already
929 // waiting; say it here too, or a start that fails fast
930 // leaves no trace anywhere.
931 tracing::warn!(
932 event = "container_start_failed",
933 cell = %cell.scope,
934 error = %format!("{error:#}"),
935 "the container did not start"
936 );
937 let mut state = cell.state.lock().unwrap();
938 state.running = false;
939 drop(state);
940 cell.exit
941 .send_replace(Some((run, Err(format!("{error:#}")))));
942 return Err(error);
943 }
944 };
945 {
946 let mut state = cell.state.lock().unwrap();
947 state.running = true;
948 state.address = address;
949 }
950 self.watch_exit(cell, run);
951 Ok(())
952 }
953
954 /// Wait for the container's root process to end and publish the exit
955 /// for `run`; a later run's start has already replaced the state.
956 fn watch_exit(&self, cell: &Arc<CellContainer>, run: u64) {
957 let docker = self.docker.clone();
958 let cell_ = cell.clone();
959 asyncrt::spawn(async move {
960 let result = docker
961 .call("POST", &format!("/containers/{}/wait", cell_.name), None)
962 .await
963 .and_then(|reply| {
964 if !reply.status.is_success() {
965 return Err(anyhow!(
966 "wait failed with [{}] {}",
967 reply.status.as_u16(),
968 reply.message()
969 ));
970 }
971 reply
972 .json()?
973 .get("StatusCode")
974 .and_then(Value::as_i64)
975 .ok_or_else(|| anyhow!("wait answered without a status code"))
976 })
977 .map_err(|error| format!("{error:#}"));
978 let mut state = cell_.state.lock().unwrap();
979 if state.run == run {
980 state.running = false;
981 state.address = Address::None;
982 }
983 drop(state);
984 cell_.exit.send_replace(Some((run, result)));
985 })
986 .detach();
987 }
988
989 async fn create_and_start(
990 &self,
991 cell: &CellContainer,
992 params: StartParams,
993 ) -> anyhow::Result<Address> {
994 self.ensure_fence().await?;
995 self.enforce_instance_ceiling(cell).await?;
996 self.ensure_image(&cell.spec.image).await?;
997 let (open, internal) = self.networks().await?;
998 // A previous run's container may still be named: the wait task
999 // observed its exit but nothing removed it, or a restart adopted a
1000 // stopped one. The name is the cell's, so it is ours to remove.
1001 let _ = self
1002 .docker
1003 .call(
1004 "DELETE",
1005 &format!("/containers/{}?force=true", cell.name),
1006 None,
1007 )
1008 .await;
1009 let mut env: Vec<String> = DEFAULT_ENV.iter().map(|entry| entry.to_string()).collect();
1010 env.push(format!("CLOUDFLARE_DURABLE_OBJECT_ID={}", cell.scope));
1011 env.extend(
1012 params
1013 .env
1014 .iter()
1015 .map(|(name, value)| format!("{name}={value}")),
1016 );
1017 let mut labels = serde_json::Map::new();
1018 labels.insert("celld.node".into(), json!(self.node));
1019 labels.insert("celld.cell".into(), json!(cell.scope));
1020 labels.insert("celld.class".into(), json!(cell.spec.class_name));
1021 for (name, value) in &params.labels {
1022 labels.insert(format!("celld.user.{name}"), json!(value));
1023 }
1024 // Off Linux the node reaches a container only through published
1025 // ports, and Docker publishes nothing on an internal network, so
1026 // `enableInternet: false` would make the container unreachable.
1027 // Development there keeps egress; the compat page says so.
1028 let offline = !params.enable_internet && cfg!(target_os = "linux");
1029 if !params.enable_internet && !offline {
1030 tracing::warn!(
1031 cell = %cell.scope,
1032 "enableInternet: false is not enforced on this platform; the container keeps egress"
1033 );
1034 }
1035 // A container is a tenant's process tree, not the operator's: no
1036 // capability, no privilege gain through setuid binaries, the
1037 // daemon's seccomp profile, and a process ceiling. What a class
1038 // legitimately needs beyond this is a config question for later,
1039 // not a default. The kernel boundary itself is the runtime's.
1040 let mut host_config = json!({
1041 "NetworkMode": if offline { &internal } else { &open },
1042 "PublishAllPorts": !cfg!(target_os = "linux"),
1043 "CapDrop": ["ALL"],
1044 "SecurityOpt": ["no-new-privileges"],
1045 "PidsLimit": PIDS_LIMIT,
1046 // An init as PID 1 reaps orphaned children. Without it a process
1047 // whose parent exits becomes a zombie the container holds until
1048 // it stops, and enough of them exhaust the PID ceiling; a fleet
1049 // fork bomb left exactly these behind.
1050 "Init": true,
1051 });
1052 // A class can name its own runtime, else the node default. A class
1053 // that needs isolation names `runsc`, and the node's daemon must
1054 // have it or the start fails, so the class runs only where its
1055 // isolation is real.
1056 let runtime = cell
1057 .spec
1058 .runtime
1059 .as_deref()
1060 .or(self.runtime.as_deref())
1061 .filter(|runtime| !runtime.is_empty());
1062 if let Some(runtime) = runtime {
1063 host_config["Runtime"] = json!(runtime);
1064 }
1065 // A container under a non-default runtime gets an explicit resolver
1066 // through a bind-mounted resolv.conf: gVisor cannot reach Docker's
1067 // embedded resolver at `127.0.0.11`, and on a user bridge Docker
1068 // keeps that address in resolv.conf whatever `--dns` says, so the
1069 // file itself must name a reachable resolver. An operator who set
1070 // `CELLD_CONTAINER_DNS` gets it for every container.
1071 let wants_resolver = runtime.is_some() || !self.dns.is_empty();
1072 if wants_resolver {
1073 if let Some(resolv) = &self.resolv_conf {
1074 let bind = format!("{}:/etc/resolv.conf:ro", resolv.display());
1075 host_config["Binds"] = json!([bind]);
1076 }
1077 }
1078 // Every container has a limit: a class without an instance type
1079 // gets Cloudflare's default type rather than the node.
1080 let instance_type = cell
1081 .spec
1082 .instance_type
1083 .as_deref()
1084 .unwrap_or(DEFAULT_INSTANCE_TYPE);
1085 let (vcpu, memory) =
1086 instance_resources(instance_type).expect("the deploy refused this instance type");
1087 host_config["NanoCpus"] = json!((vcpu * 1e9) as u64);
1088 host_config["Memory"] = json!(memory);
1089 host_config["MemorySwap"] = json!(memory);
1090 let mut body = json!({
1091 "Image": cell.spec.image,
1092 "Env": env,
1093 "Labels": labels,
1094 "HostConfig": host_config,
1095 });
1096 if let Some(entrypoint) = params.entrypoint {
1097 body["Cmd"] = json!(entrypoint);
1098 }
1099 // The daemon can answer 409 for a name whose previous container is
1100 // still being removed, so a fresh start after `destroy()` retries
1101 // briefly, as workerd's engine does.
1102 let mut reply = self
1103 .docker
1104 .call(
1105 "POST",
1106 &format!("/containers/create?name={}", cell.name),
1107 Some(body.clone()),
1108 )
1109 .await?;
1110 for _ in 0..20 {
1111 if reply.status.as_u16() != 409 {
1112 break;
1113 }
1114 asyncrt::sleep(Duration::from_millis(100)).await;
1115 let _ = self
1116 .docker
1117 .call(
1118 "DELETE",
1119 &format!("/containers/{}?force=true", cell.name),
1120 None,
1121 )
1122 .await;
1123 reply = self
1124 .docker
1125 .call(
1126 "POST",
1127 &format!("/containers/create?name={}", cell.name),
1128 Some(body.clone()),
1129 )
1130 .await?;
1131 }
1132 if reply.status.as_u16() == 404 {
1133 return Err(anyhow!("No such image available named {}", cell.spec.image));
1134 }
1135 if !reply.status.is_success() {
1136 return Err(anyhow!(
1137 "Create container failed with [{}] {}",
1138 reply.status.as_u16(),
1139 reply.message()
1140 ));
1141 }
1142 self.docker
1143 .expect(
1144 "POST",
1145 &format!("/containers/{}/start", cell.name),
1146 None,
1147 "start container",
1148 )
1149 .await?;
1150 let info = self
1151 .docker
1152 .expect(
1153 "GET",
1154 &format!("/containers/{}/json", cell.name),
1155 None,
1156 "inspect container",
1157 )
1158 .await?
1159 .json()?;
1160 Ok(address_of(&info))
1161 }
1162
1163 /// Wait for the current run to end. `Ok(code)` is the root process's
1164 /// exit code; a destroyed container reports 137.
1165 pub async fn monitor(&self, cell: &Arc<CellContainer>, run: u64) -> Result<i64, String> {
1166 let mut receiver = cell.exit.subscribe();
1167 loop {
1168 if let Some((ended, result)) = receiver.borrow_and_update().clone() {
1169 if ended >= run {
1170 return result;
1171 }
1172 }
1173 if receiver.changed().await.is_err() {
1174 return Err("the container engine went away".to_string());
1175 }
1176 }
1177 }
1178
1179 pub async fn destroy(&self, cell: &Arc<CellContainer>) -> anyhow::Result<()> {
1180 // Kill first so the wait task reports 137 before the removal makes
1181 // the name disappear under it.
1182 let _ = self
1183 .docker
1184 .call(
1185 "POST",
1186 &format!("/containers/{}/kill?signal=SIGKILL", cell.name),
1187 None,
1188 )
1189 .await;
1190 let _ = self
1191 .docker
1192 .call(
1193 "DELETE",
1194 &format!("/containers/{}?force=true", cell.name),
1195 None,
1196 )
1197 .await;
1198 let mut state = cell.state.lock().unwrap();
1199 state.running = false;
1200 state.address = Address::None;
1201 Ok(())
1202 }
1203
1204 pub async fn signal(&self, cell: &Arc<CellContainer>, signal: u32) -> anyhow::Result<()> {
1205 self.docker
1206 .expect(
1207 "POST",
1208 &format!("/containers/{}/kill?signal={signal}", cell.name),
1209 None,
1210 "signal container",
1211 )
1212 .await?;
1213 Ok(())
1214 }
1215
1216 /// The cell left this node's runtime. An idle eviction keeps the
1217 /// container for its inactivity window; anything else destroys it, and
1218 /// the stop waits for that: a drain ends the process right after its
1219 /// last stop, and a destroy left to a detached task did not always get
1220 /// its two daemon calls in before the exit.
1221 pub async fn release(self: &Arc<Self>, scope: &str, release: Release) {
1222 let Some(cell) = self.cell(scope) else {
1223 return;
1224 };
1225 match release {
1226 Release::Keep => {
1227 let window = cell
1228 .state
1229 .lock()
1230 .unwrap()
1231 .inactivity
1232 .unwrap_or(DEFAULT_INACTIVITY);
1233 let engine = self.clone();
1234 let cell_ = cell.clone();
1235 let sweeper = asyncrt::spawn(async move {
1236 asyncrt::sleep(window).await;
1237 engine.forget(&cell_).await;
1238 });
1239 cell.state.lock().unwrap().sweeper = Some(sweeper);
1240 }
1241 Release::Destroy => self.forget(&cell).await,
1242 }
1243 }
1244
1245 async fn forget(&self, cell: &Arc<CellContainer>) {
1246 let _ = self.destroy(cell).await;
1247 for id in cell.processes.lock().unwrap().drain(..) {
1248 drop_process(id);
1249 }
1250 let mut cells = self.cells.lock().unwrap();
1251 if cells
1252 .get(&cell.scope)
1253 .is_some_and(|current| Arc::ptr_eq(current, cell))
1254 {
1255 cells.remove(&cell.scope);
1256 }
1257 }
1258
1259 pub async fn exec(
1260 &self,
1261 cell: &Arc<CellContainer>,
1262 params: ExecParams,
1263 ) -> anyhow::Result<Arc<ExecProcess>> {
1264 if !cell.running() {
1265 return Err(anyhow!("exec() requires a running container."));
1266 }
1267 let mut body = json!({
1268 "AttachStdin": true,
1269 "AttachStdout": true,
1270 "AttachStderr": true,
1271 "Tty": false,
1272 "Cmd": params.cmd,
1273 });
1274 if !params.env.is_empty() {
1275 body["Env"] = json!(params
1276 .env
1277 .iter()
1278 .map(|(name, value)| format!("{name}={value}"))
1279 .collect::<Vec<_>>());
1280 }
1281 if let Some(cwd) = &params.cwd {
1282 body["WorkingDir"] = json!(cwd);
1283 }
1284 if let Some(user) = &params.user {
1285 body["User"] = json!(user);
1286 }
1287 let created = self
1288 .docker
1289 .expect(
1290 "POST",
1291 &format!("/containers/{}/exec", cell.name),
1292 Some(body),
1293 "create exec",
1294 )
1295 .await?
1296 .json()?;
1297 let exec_id = created
1298 .get("Id")
1299 .and_then(Value::as_str)
1300 .ok_or_else(|| anyhow!("exec create answered without an id"))?
1301 .to_string();
1302 let stream = self
1303 .docker
1304 .hijack(
1305 &format!("/exec/{exec_id}/start"),
1306 json!({ "Detach": false, "Tty": false }),
1307 )
1308 .await?;
1309 // Docker reports `Running: false` with no pid before it has spawned
1310 // the process, and a finished exec keeps its pid, so a pid of zero
1311 // is the one answer that means "not yet": retry it briefly, as
1312 // workerd does. Breaking on `Running: false` here lost the pid of a
1313 // short command whenever the inspect landed in that window.
1314 let mut pid = 0;
1315 for _ in 0..20 {
1316 let info = self
1317 .docker
1318 .expect(
1319 "GET",
1320 &format!("/exec/{exec_id}/json"),
1321 None,
1322 "inspect exec",
1323 )
1324 .await?
1325 .json()?;
1326 pid = info.get("Pid").and_then(Value::as_i64).unwrap_or(0);
1327 if pid != 0 {
1328 break;
1329 }
1330 asyncrt::sleep(Duration::from_millis(50)).await;
1331 }
1332 let (read, write) = tokio::io::split(stream);
1333 let (stdout_tx, stdout_rx) = mpsc::channel(16);
1334 let (stderr_tx, stderr_rx) = mpsc::channel(16);
1335 let combined = params.combined;
1336 let ended = watch::channel(false).0;
1337 let ended_ = ended.clone();
1338 asyncrt::spawn(async move {
1339 demux(read, stdout_tx, stderr_tx, combined).await;
1340 ended_.send_replace(true);
1341 })
1342 .detach();
1343 let process = Arc::new(ExecProcess {
1344 id: next_exec_id(),
1345 exec_id,
1346 container: cell.name.clone(),
1347 pid,
1348 docker: self.docker.clone(),
1349 stdin: tokio::sync::Mutex::new(Some(write)),
1350 stdout: tokio::sync::Mutex::new(stdout_rx),
1351 stderr: tokio::sync::Mutex::new(stderr_rx),
1352 ended,
1353 exit_code: tokio::sync::Mutex::new(None),
1354 });
1355 processes()
1356 .lock()
1357 .unwrap()
1358 .insert(process.id, process.clone());
1359 cell.processes.lock().unwrap().push(process.id);
1360 Ok(process)
1361 }
1362}
1363
1364pub struct ExecParams {
1365 pub cmd: Vec<String>,
1366 pub env: Vec<(String, String)>,
1367 pub cwd: Option<String>,
1368 pub user: Option<String>,
1369 /// stderr folded into stdout.
1370 pub combined: bool,
1371}
1372
1373type WriteHalf = tokio::io::WriteHalf<Box<dyn Stream>>;
1374
1375pub struct ExecProcess {
1376 pub id: u64,
1377 exec_id: String,
1378 container: String,
1379 pub pid: i64,
1380 docker: Docker,
1381 stdin: tokio::sync::Mutex<Option<WriteHalf>>,
1382 stdout: tokio::sync::Mutex<mpsc::Receiver<Bytes>>,
1383 stderr: tokio::sync::Mutex<mpsc::Receiver<Bytes>>,
1384 /// True once the hijacked stream reached EOF, which the daemon sends
1385 /// when the process exits.
1386 ended: watch::Sender<bool>,
1387 exit_code: tokio::sync::Mutex<Option<i64>>,
1388}
1389
1390fn processes() -> &'static Mutex<HashMap<u64, Arc<ExecProcess>>> {
1391 static PROCESSES: OnceLock<Mutex<HashMap<u64, Arc<ExecProcess>>>> = OnceLock::new();
1392 PROCESSES.get_or_init(Default::default)
1393}
1394
1395fn next_exec_id() -> u64 {
1396 static NEXT: AtomicU64 = AtomicU64::new(1);
1397 NEXT.fetch_add(1, Ordering::Relaxed)
1398}
1399
1400pub fn process(id: u64) -> Option<Arc<ExecProcess>> {
1401 processes().lock().unwrap().get(&id).cloned()
1402}
1403
1404pub fn drop_process(id: u64) {
1405 processes().lock().unwrap().remove(&id);
1406}
1407
1408impl ExecProcess {
1409 /// One chunk of stdout (`1`) or stderr (`2`); empty at end of stream.
1410 pub async fn read(&self, which: u8) -> Bytes {
1411 let mut receiver = match which {
1412 1 => self.stdout.lock().await,
1413 _ => self.stderr.lock().await,
1414 };
1415 receiver.recv().await.unwrap_or_default()
1416 }
1417
1418 pub async fn write(&self, bytes: &[u8]) -> Result<(), String> {
1419 let mut guard = self.stdin.lock().await;
1420 let stdin = guard.as_mut().ok_or("stdin is closed")?;
1421 stdin
1422 .write_all(bytes)
1423 .await
1424 .map_err(|error| format!("stdin write failed: {error}"))?;
1425 stdin
1426 .flush()
1427 .await
1428 .map_err(|error| format!("stdin flush failed: {error}"))
1429 }
1430
1431 /// End stdin. Half-closing the hijacked connection is how the daemon
1432 /// learns the process's stdin reached EOF.
1433 pub async fn close_stdin(&self) {
1434 if let Some(mut stdin) = self.stdin.lock().await.take() {
1435 let _ = stdin.shutdown().await;
1436 }
1437 }
1438
1439 pub async fn wait(&self) -> anyhow::Result<i64> {
1440 let mut exit = self.exit_code.lock().await;
1441 if let Some(code) = *exit {
1442 return Ok(code);
1443 }
1444 let mut ended = self.ended.subscribe();
1445 while !*ended.borrow_and_update() {
1446 if ended.changed().await.is_err() {
1447 break;
1448 }
1449 }
1450 // The stream closes when the process exits, but the daemon records
1451 // the exit code a moment later.
1452 let mut code = None;
1453 for _ in 0..40 {
1454 let info = self
1455 .docker
1456 .expect(
1457 "GET",
1458 &format!("/exec/{}/json", self.exec_id),
1459 None,
1460 "inspect exec",
1461 )
1462 .await?
1463 .json()?;
1464 if !info
1465 .get("Running")
1466 .and_then(Value::as_bool)
1467 .unwrap_or(false)
1468 {
1469 code = info.get("ExitCode").and_then(Value::as_i64);
1470 break;
1471 }
1472 asyncrt::sleep(Duration::from_millis(50)).await;
1473 }
1474 let code = code.ok_or_else(|| anyhow!("the process did not report an exit code"))?;
1475 *exit = Some(code);
1476 Ok(code)
1477 }
1478
1479 /// The Engine API has no exec kill, so the signal is delivered by a
1480 /// second exec of `kill`, as workerd does.
1481 pub async fn kill(&self, signal: u32) -> anyhow::Result<()> {
1482 let body = json!({
1483 "AttachStdin": false, "AttachStdout": false, "AttachStderr": false,
1484 "Cmd": ["kill", format!("-{signal}"), self.pid.to_string()],
1485 });
1486 let created = self
1487 .docker
1488 .expect(
1489 "POST",
1490 &format!("/containers/{}/exec", self.container),
1491 Some(body),
1492 "create exec",
1493 )
1494 .await?
1495 .json()?;
1496 let id = created
1497 .get("Id")
1498 .and_then(Value::as_str)
1499 .ok_or_else(|| anyhow!("exec create answered without an id"))?;
1500 self.docker
1501 .expect(
1502 "POST",
1503 &format!("/exec/{id}/start"),
1504 Some(json!({ "Detach": true })),
1505 "start exec",
1506 )
1507 .await?;
1508 Ok(())
1509 }
1510}
1511
1512/// Split Docker's multiplexed stream into stdout and stderr chunks until
1513/// the daemon closes it.
1514async fn demux(
1515 mut read: tokio::io::ReadHalf<Box<dyn Stream>>,
1516 stdout: mpsc::Sender<Bytes>,
1517 stderr: mpsc::Sender<Bytes>,
1518 combined: bool,
1519) {
1520 let mut header = [0u8; 8];
1521 loop {
1522 if read.read_exact(&mut header).await.is_err() {
1523 return;
1524 }
1525 let (stream, length) = frame_header(&header);
1526 let mut payload = vec![0u8; length];
1527 if read.read_exact(&mut payload).await.is_err() {
1528 return;
1529 }
1530 let target = if stream == 2 && !combined {
1531 &stderr
1532 } else {
1533 &stdout
1534 };
1535 if target.send(Bytes::from(payload)).await.is_err() {
1536 // The reader went away; keep draining so the process is not
1537 // blocked on a full pipe.
1538 continue;
1539 }
1540 }
1541}
1542
1543fn address_of(info: &Value) -> Address {
1544 if cfg!(target_os = "linux") {
1545 let ip = info
1546 .pointer("/NetworkSettings/Networks")
1547 .and_then(Value::as_object)
1548 .and_then(|networks| networks.values().next())
1549 .and_then(|network| network.get("IPAddress"))
1550 .and_then(Value::as_str)
1551 .filter(|ip| !ip.is_empty());
1552 return ip.map_or(Address::None, |ip| Address::Ip(ip.to_string()));
1553 }
1554 let mut ports = HashMap::new();
1555 if let Some(map) = info
1556 .pointer("/NetworkSettings/Ports")
1557 .and_then(Value::as_object)
1558 {
1559 for (key, bindings) in map {
1560 let Some(port) = key
1561 .strip_suffix("/tcp")
1562 .and_then(|port| port.parse::<u16>().ok())
1563 else {
1564 continue;
1565 };
1566 let host = bindings
1567 .as_array()
1568 .into_iter()
1569 .flatten()
1570 .find_map(|binding| binding.get("HostPort")?.as_str()?.parse::<u16>().ok());
1571 if let Some(host) = host {
1572 ports.insert(port, host);
1573 }
1574 }
1575 }
1576 Address::Published(ports)
1577}
1578
1579/// A Docker name from a node and a cell scope: the scope's characters are
1580/// not all legal, so the name is a hash and the scope rides in a label.
1581/// The node is part of it because two nodes can share one engine in a
1582/// development or test setup, and a name from the scope alone let one
1583/// node adopt, or reap, the other's container for the same object.
1584fn container_name(node: &str, scope: &str) -> String {
1585 use sha2::Digest;
1586 let digest = sha2::Sha256::digest(format!("{node}\n{scope}").as_bytes());
1587 format!("celld-{:x}", digest)[..30].to_string()
1588}