Diffinery

homeflare/celldpublic

feat(containers): privileged classes run on a second engine, another user's Podman

Jason Schwarzenberger authored 1 parent 08fe855commit 6f2fbc5aee0d7451c6ed27e6cc5b559ca079cacaBrowse files
5 files changed+195−38
Files (5)
modifiedHOMEFLARE.md+1−0View file
@@ -32,6 +32,7 @@
3232 | Fence exceptions (`CELLD_FENCE_DNAT`, `CELLD_FENCE_ALLOW`) | A container reaching one of the node's own Workers on Cloudflare goes over the Internet. On Homeflare the Worker's hostname resolves to the LAN, which the fence refuses (Diffinery's import agent couldn't report back). `CELLD_FENCE_DNAT=HOST:PORT=HOST:PORT[,...]` rewrites the bridges' new TCP connections to the first endpoint into the second (a nat prerouting chain at -110, ahead of the engine's port forwarding, since a connection is translated once). The rewrite also sets connection mark `0x1000`: Podman (netavark) isolates its networks from one another and drops forwarding from celld's bridge to the edge's network, but accepts connections with that mark ahead of its isolation, as it does for its own port forwarding; the mark stays with the connection, so replies pass. `CELLD_FENCE_ALLOW=HOST:PORT[,...]` accepts the bridges' connections to those endpoints inside the fence's input and forward chains, ahead of the rejects (an accept in a chain of its own wouldn't stop them). A host may be a name; it's resolved to IPv4 each time a container starts, and the fence is installed again when its rules change. Only addresses and numbers reach the rules. Test: `cargo test -p celld --lib fence_rule_tests`. |
3333 | The node's own connections into its containers (`CELLD_FENCE_NODE`) | Podman isolates its networks from one another, so the node (on the engine's network) couldn't reach a port a container serves: Diffinery's sandbox server never answered `startAndWaitForPorts`. `CELLD_FENCE_NODE=HOST` (resolved each container start) marks the node's new connections into `celld0`/`celld1` with netavark's `0x1000`, which it accepts ahead of its isolation; replies keep the mark. The rule is in a table of the node's own (`inet celld_node_<host>`), since the main table is shared by every node on the engine and each replaces it. |
3434 | Container memory budget (`CELLD_CONTAINER_MEMORY_MB`) | A node counted each running container's instance-type cap towards its memory pressure, so four of Diffinery's `standard-4` runners (12 GiB each) on a 60 GiB machine put it over its ceiling: it refused every new cell (`CapacityExhausted`, the forge's own `RepoDO`s too) and evicted live ones, which frees none of a container's memory and stops a container cell's runner. Containers no longer count towards pressure. Instead a start that would take the running containers' caps past the budget fails with `too many containers: ...`, as one over `max_instances` does, and Diffinery queues the job again. The budget is `CELLD_CONTAINER_MEMORY_MB` (`0` for none); unset, it's the node's memory ceiling, where containers used to stop the node. Caps are rarely all used, so a machine with headroom can set it past its memory. |
35+| Privileged containers (`CELLD_PRIVILEGED_CONTAINER_CLASSES`) | A Cloudflare Container runs with root's capabilities, so Diffinery's runner starts its own Docker daemon for a job's `docker` steps, service containers and builds. celld drops every capability, so the daemon couldn't start. The classes named in `CELLD_PRIVILEGED_CONTAINER_CLASSES=Class[,...]` run privileged instead, on a second engine, `CELLD_PRIVILEGED_CONTAINER_HOST=unix:///path`: another user's rootless Podman, so a container that escapes lands as that user, not as the node's. The daemon's storage (`/var/lib/docker`) is an anonymous volume, removed with the container (every delete passes `v=true`), and the process ceiling is 8192, since it holds the daemon's own containers. The engine's bridges get their own fence, in `CELLD_PRIVILEGED_FENCE_NETNS` (that user's rootless-netns), without the default engine's exceptions. Both engines' containers share the memory budget. |
3536 | `homeflare:` line in `celld --version` | Lists what this build adds (`HOMEFLARE_FEATURES` in `lib.rs`), so Homeflare sends a config key only to a celld that accepts it. Add a feature there with each patch. |
3637
3738 ## Building
modifiedcrates/celld/container.rs+186−31View file
@@ -132,13 +132,20 @@
132132 /// peers can sum a class's instances across the fleet for `max_instances`.
133133 /// Empty when no engine has connected.
134134 pub fn running_instances_by_class() -> std::collections::BTreeMap<String, u64> {
135- engine_if_ready().map_or_else(Default::default, |engine| {
136- engine.running_instances_by_class()
137- })
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
138142 }
139143 /// Processes one container can hold. Cloudflare publishes no number; this
140144 /// is room for a build tool's process tree and far short of a fork bomb.
141145 const 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).
148+const PRIVILEGED_PIDS_LIMIT: u64 = 8192;
142149 /// The host interfaces of the two bridges, named so the fence can address
143150 /// them; Docker's default `br-<id>` changes with every recreation.
144151 const OPEN_BRIDGE: &str = "celld0";
@@ -261,8 +268,14 @@
261268 /// bridges reach those endpoints, ahead of the rejects.
262269 ///
263270 /// Everything else stays fenced. Returns the rules to add to the table.
264-async fn fence_rules(base: &str) -> anyhow::Result<String> {
271+///
272+/// homeflare: the privileged engine's fence has no exceptions (`privileged`):
273+/// they name addresses on the default engine's network.
274+async fn fence_rules(base: &str, privileged: bool) -> anyhow::Result<String> {
265275 let list = |name: &str| -> Vec<String> {
276+ if privileged {
277+ return Vec::new();
278+ }
266279 std::env::var(name)
267280 .unwrap_or_default()
268281 .split(',')
@@ -312,6 +325,7 @@
312325 // restarts).
313326 if let Some(node) = std::env::var("CELLD_FENCE_NODE")
314327 .ok()
328+ .filter(|_| !privileged)
315329 .map(|s| s.trim().to_string())
316330 .filter(|s| !s.is_empty())
317331 {
@@ -345,8 +359,13 @@
345359 /// homeflare: the network namespace the fence joins instead of the host's,
346360 /// as the engine names it (`ns:<path>`): a rootless Podman's rootless-netns,
347361 /// `$XDG_RUNTIME_DIR/containers/networks/rootless-netns/rootless-netns`.
348-fn fence_netns() -> Option<String> {
349- std::env::var("CELLD_FENCE_NETNS")
362+fn 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)
350369 .ok()
351370 .filter(|path| !path.trim().is_empty())
352371 }
@@ -501,6 +520,8 @@
501520 /// homeflare: what running containers may reserve together; see
502521 /// `container_memory_budget`. `None`: no budget.
503522 memory_budget: Option<u64>,
523+ /// homeflare: the engine of privileged classes; see `PRIVILEGED_ENGINE`.
524+ privileged: bool,
504525 }
505526
506527 /// What the runtime told this module about the node: set once at start.
@@ -603,21 +624,100 @@
603624 ENGINE.get().cloned()
604625 }
605626
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.
634+static PRIVILEGED_ENGINE: tokio::sync::OnceCell<Arc<ContainerEngine>> =
635+ tokio::sync::OnceCell::const_new();
636+
637+/// Whether `class` runs on the privileged engine.
638+pub 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`).
646+fn 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.
651+pub 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.
687+pub 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.
692+pub 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.
701+fn ready_engines() -> impl Iterator<Item = Arc<ContainerEngine>> {
702+ [ENGINE.get().cloned(), PRIVILEGED_ENGINE.get().cloned()]
703+ .into_iter()
704+ .flatten()
705+}
706+
606707 /// Destroy every container of this node at process exit. A preserve
607708 /// shutdown (`celld dev` on Ctrl-C) keeps its cells resident and stops
608709 /// none of them, and a handoff cut by the deadline leaves cells behind
609710 /// too; without this their containers ran on until the next start of the
610711 /// same node reaped them, invisible to the object that owned them.
611712 pub async fn shutdown() {
612- let Some(engine) = engine_if_ready() else {
613- return;
614- };
615- if let Err(error) = engine.reap().await {
616- tracing::warn!(
617- event = "container_shutdown_reap_failed",
618- error = %format!("{error:#}"),
619- "containers of this node may still be running"
620- );
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+ }
621721 }
622722 }
623723
@@ -626,20 +726,41 @@
626726 /// engine still serves every other class, and the container class fails
627727 /// at its first `start()` with the same message.
628728 pub async fn prewarm() {
629- let engine = match engine().await {
630- Ok(engine) => engine,
631- Err(error) => {
632- tracing::warn!(error = %format!("{error:#}"), "containers are unavailable on this node");
633- return;
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+ }
634749 }
635- };
750+ }
751+}
752+
753+async fn prewarm_engine(engine: &ContainerEngine, specs: &[Arc<ContainerSpec>]) {
636754 if let Err(error) = engine.ensure_fence().await {
637755 tracing::warn!(
638756 error = %format!("{error:#}"),
757+ privileged = engine.privileged,
639758 "the container bridges are not fenced; no container starts on this node"
640759 );
641760 }
642- let specs = SPECS.read().unwrap().clone();
761+ let specs = specs
762+ .iter()
763+ .filter(|spec| privileged_class(&spec.class_name) == engine.privileged);
643764 for spec in specs {
644765 if let Err(error) = engine.ensure_image(&spec.image).await {
645766 tracing::warn!(
@@ -708,6 +829,7 @@
708829 networks: tokio::sync::Mutex::new(None),
709830 fenced: tokio::sync::Mutex::new(None),
710831 memory_budget: container_memory_budget()?,
832+ privileged: false,
711833 };
712834 engine.reap().await?;
713835 Ok(engine)
@@ -739,7 +861,11 @@
739861 if let Some(id) = entry.get("Id").and_then(Value::as_str) {
740862 let _ = self
741863 .docker
742- .call("DELETE", &format!("/containers/{id}?force=true"), None)
864+ .call(
865+ "DELETE",
866+ &format!("/containers/{id}?force=true&v=true"),
867+ None,
868+ )
743869 .await;
744870 }
745871 }
@@ -894,12 +1020,12 @@
8941020 /// process; a restart re-applies them, which is idempotent.
8951021 pub async fn ensure_fence(&self) -> anyhow::Result<()> {
8961022 let mut fenced = self.fenced.lock().await;
897- let netns = fence_netns();
1023+ let netns = fence_netns(self.privileged);
8981024 let (rules, network_mode) = match &netns {
8991025 Some(path) => (FENCE_RULES_NETNS, format!("ns:{path}")),
9001026 None => (FENCE_RULES, "host".to_string()),
9011027 };
902- let rules = fence_rules(rules).await?;
1028+ let rules = fence_rules(rules, self.privileged).await?;
9031029 if fenced.as_deref() == Some(rules.as_str()) {
9041030 return Ok(());
9051031 }
@@ -968,7 +1094,11 @@
9681094 .await;
9691095 let _ = self
9701096 .docker
971- .call("DELETE", &format!("/containers/{id}?force=true"), None)
1097+ .call(
1098+ "DELETE",
1099+ &format!("/containers/{id}?force=true&v=true"),
1100+ None,
1101+ )
9721102 .await;
9731103 outcome.context("fence the container bridges")?;
9741104 tracing::info!(
@@ -1115,7 +1245,13 @@
11151245 let Some(budget) = self.memory_budget else {
11161246 return Ok(());
11171247 };
1118- let reserved = self.reserved_memory_bytes();
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+ }
11191255 let mib = 1024 * 1024;
11201256 anyhow::ensure!(
11211257 reserved <= budget,
@@ -1245,7 +1381,7 @@
12451381 .docker
12461382 .call(
12471383 "DELETE",
1248- &format!("/containers/{}?force=true", cell.name),
1384+ &format!("/containers/{}?force=true&v=true", cell.name),
12491385 None,
12501386 )
12511387 .await;
@@ -1305,6 +1441,20 @@
13051441 if let Some(runtime) = runtime {
13061442 host_config["Runtime"] = json!(runtime);
13071443 }
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+ }
13081458 // A container under a non-default runtime gets an explicit resolver
13091459 // through a bind-mounted resolv.conf: gVisor cannot reach Docker's
13101460 // embedded resolver at `127.0.0.11`, and on a user bridge Docker
@@ -1335,6 +1485,7 @@
13351485 "Env": env,
13361486 "Labels": labels,
13371487 "HostConfig": host_config,
1488+ "Volumes": volumes,
13381489 });
13391490 if let Some(entrypoint) = params.entrypoint {
13401491 body["Cmd"] = json!(entrypoint);
@@ -1359,7 +1510,7 @@
13591510 .docker
13601511 .call(
13611512 "DELETE",
1362- &format!("/containers/{}?force=true", cell.name),
1513+ &format!("/containers/{}?force=true&v=true", cell.name),
13631514 None,
13641515 )
13651516 .await;
@@ -1434,7 +1585,7 @@
14341585 .docker
14351586 .call(
14361587 "DELETE",
1437- &format!("/containers/{}?force=true", cell.name),
1588+ &format!("/containers/{}?force=true&v=true", cell.name),
14381589 None,
14391590 )
14401591 .await;
@@ -1846,7 +1997,7 @@
18461997 .enable_all()
18471998 .build()
18481999 .unwrap();
1849- let render = |base| rt.block_on(fence_rules(base));
2000+ let render = |base| rt.block_on(fence_rules(base, false));
18502001 let plain = render(FENCE_RULES_NETNS).unwrap();
18512002 assert!(
18522003 !plain.contains("#ALLOW")
@@ -1881,6 +2032,10 @@
18812032 assert!(
18822033 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")
18832034 );
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);
18842039
18852040 unsafe {
18862041 std::env::set_var(
modifiedcrates/celld/js/container.rs+5−5View file
@@ -11,7 +11,7 @@
1111 use std::time::Duration;
1212
1313 async fn cell_for(scope: &str) -> Result<(Arc<ContainerEngine>, Arc<CellContainer>), String> {
14- let engine = container::engine()
14+ let engine = container::engine_for_scope(scope)
1515 .await
1616 .map_err(|error| format!("{error:#}"))?;
1717 let cell = engine
@@ -38,7 +38,7 @@
3838 mut rv: v8::ReturnValue<v8::Value>,
3939 ) {
4040 let cell = string_arg(scope, &args, 0);
41- let running = container::engine_if_ready()
41+ let running = container::engine_if_ready_for_scope(&cell)
4242 .and_then(|engine| engine.cell(&cell))
4343 .is_some_and(|cell| cell.running());
4444 rv.set(v8::Boolean::new(scope, running).into());
@@ -52,7 +52,7 @@
5252 ) {
5353 let cell = string_arg(scope, &args, 0);
5454 let port = number_arg(scope, &args, 1) as u16;
55- let address = container::engine_if_ready()
55+ let address = container::engine_if_ready_for_scope(&cell)
5656 .and_then(|engine| engine.cell(&cell))
5757 .ok_or_else(|| "this Durable Object has no container".to_string())
5858 .and_then(|cell| cell.address(port));
@@ -87,7 +87,7 @@
8787 };
8888 // The run opens here, on the calling thread, so the monitor() that
8989 // follows this call in the same turn waits for this start's exit.
90- let run = container::engine_if_ready()
90+ let run = container::engine_if_ready_for_scope(&cell)
9191 .and_then(|engine| engine.cell(&cell))
9292 .map(|cell| cell.begin_run());
9393 let async_id = asyncrt::enqueue_io_context(async move {
@@ -122,7 +122,7 @@
122122 mut rv: v8::ReturnValue<v8::Value>,
123123 ) {
124124 let cell = string_arg(scope, &args, 0);
125- let run = container::engine_if_ready()
125+ let run = container::engine_if_ready_for_scope(&cell)
126126 .and_then(|engine| engine.cell(&cell))
127127 .map_or(0, |cell| cell.current_run());
128128 let async_id = asyncrt::enqueue_unrefed(async move {
modifiedcrates/celld/lib.rs+1−0View file
@@ -326,4 +326,5 @@
326326 "ratelimits",
327327 "send-email",
328328 "container-memory-budget",
329+ "privileged-containers",
329330 ];
modifiedcrates/celld/runtime.rs+2−2View file
@@ -1259,7 +1259,7 @@
12591259 // answers it here, before the object exists. A container a previous
12601260 // activation on this node left running is adopted by name.
12611261 if config.container_class(class) {
1262- let engine = crate::container::engine().await?;
1262+ let engine = crate::container::engine_for(class).await?;
12631263 engine.attach(&cell, class).await?;
12641264 }
12651265 let startup_timing = CellIsolateStartupTiming {
@@ -1403,7 +1403,7 @@
14031403 // No facet opens once the stop begins; the facet loop below stops
14041404 // the streams this answers again, with any that opened before.
14051405 self.facets.stopping(cell, epoch);
1406- if let Some(engine) = crate::container::engine_if_ready() {
1406+ if let Some(engine) = crate::container::engine_if_ready_for_scope(cell) {
14071407 // Only an idle eviction keeps the cell on this node, so only it
14081408 // keeps the container: the next activation here reconnects.
14091409 let release = match &mode {