| | @@ -132,13 +132,20 @@ |
| 132 | 132 | /// peers can sum a class's instances across the fleet for `max_instances`. |
| 133 | 133 | /// Empty when no engine has connected. |
| 134 | 134 | 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 |
| 138 | 142 | } |
| 139 | 143 | /// Processes one container can hold. Cloudflare publishes no number; this |
| 140 | 144 | /// is room for a build tool's process tree and far short of a fork bomb. |
| 141 | 145 | 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; |
| 142 | 149 | /// The host interfaces of the two bridges, named so the fence can address |
| 143 | 150 | /// them; Docker's default `br-<id>` changes with every recreation. |
| 144 | 151 | const OPEN_BRIDGE: &str = "celld0"; |
| | @@ -261,8 +268,14 @@ |
| 261 | 268 | /// bridges reach those endpoints, ahead of the rejects. |
| 262 | 269 | /// |
| 263 | 270 | /// 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> { |
| 265 | 275 | let list = |name: &str| -> Vec<String> { |
| 276 | + if privileged { |
| 277 | + return Vec::new(); |
| 278 | + } |
| 266 | 279 | std::env::var(name) |
| 267 | 280 | .unwrap_or_default() |
| 268 | 281 | .split(',') |
| | @@ -312,6 +325,7 @@ |
| 312 | 325 | // restarts). |
| 313 | 326 | if let Some(node) = std::env::var("CELLD_FENCE_NODE") |
| 314 | 327 | .ok() |
| 328 | + .filter(|_| !privileged) |
| 315 | 329 | .map(|s| s.trim().to_string()) |
| 316 | 330 | .filter(|s| !s.is_empty()) |
| 317 | 331 | { |
| | @@ -345,8 +359,13 @@ |
| 345 | 359 | /// homeflare: the network namespace the fence joins instead of the host's, |
| 346 | 360 | /// as the engine names it (`ns:<path>`): a rootless Podman's rootless-netns, |
| 347 | 361 | /// `$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) |
| 350 | 369 | .ok() |
| 351 | 370 | .filter(|path| !path.trim().is_empty()) |
| 352 | 371 | } |
| | @@ -501,6 +520,8 @@ |
| 501 | 520 | /// homeflare: what running containers may reserve together; see |
| 502 | 521 | /// `container_memory_budget`. `None`: no budget. |
| 503 | 522 | memory_budget: Option<u64>, |
| 523 | + /// homeflare: the engine of privileged classes; see `PRIVILEGED_ENGINE`. |
| 524 | + privileged: bool, |
| 504 | 525 | } |
| 505 | 526 | |
| 506 | 527 | /// What the runtime told this module about the node: set once at start. |
| | @@ -603,21 +624,100 @@ |
| 603 | 624 | ENGINE.get().cloned() |
| 604 | 625 | } |
| 605 | 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. |
| 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 | + |
| 606 | 707 | /// Destroy every container of this node at process exit. A preserve |
| 607 | 708 | /// shutdown (`celld dev` on Ctrl-C) keeps its cells resident and stops |
| 608 | 709 | /// none of them, and a handoff cut by the deadline leaves cells behind |
| 609 | 710 | /// too; without this their containers ran on until the next start of the |
| 610 | 711 | /// same node reaped them, invisible to the object that owned them. |
| 611 | 712 | 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 | + } |
| 621 | 721 | } |
| 622 | 722 | } |
| 623 | 723 | |
| | @@ -626,20 +726,41 @@ |
| 626 | 726 | /// engine still serves every other class, and the container class fails |
| 627 | 727 | /// at its first `start()` with the same message. |
| 628 | 728 | 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 | + } |
| 634 | 749 | } |
| 635 | | - }; |
| 750 | + } |
| 751 | +} |
| 752 | + |
| 753 | +async fn prewarm_engine(engine: &ContainerEngine, specs: &[Arc<ContainerSpec>]) { |
| 636 | 754 | if let Err(error) = engine.ensure_fence().await { |
| 637 | 755 | tracing::warn!( |
| 638 | 756 | error = %format!("{error:#}"), |
| 757 | + privileged = engine.privileged, |
| 639 | 758 | "the container bridges are not fenced; no container starts on this node" |
| 640 | 759 | ); |
| 641 | 760 | } |
| 642 | | - let specs = SPECS.read().unwrap().clone(); |
| 761 | + let specs = specs |
| 762 | + .iter() |
| 763 | + .filter(|spec| privileged_class(&spec.class_name) == engine.privileged); |
| 643 | 764 | for spec in specs { |
| 644 | 765 | if let Err(error) = engine.ensure_image(&spec.image).await { |
| 645 | 766 | tracing::warn!( |
| | @@ -708,6 +829,7 @@ |
| 708 | 829 | networks: tokio::sync::Mutex::new(None), |
| 709 | 830 | fenced: tokio::sync::Mutex::new(None), |
| 710 | 831 | memory_budget: container_memory_budget()?, |
| 832 | + privileged: false, |
| 711 | 833 | }; |
| 712 | 834 | engine.reap().await?; |
| 713 | 835 | Ok(engine) |
| | @@ -739,7 +861,11 @@ |
| 739 | 861 | if let Some(id) = entry.get("Id").and_then(Value::as_str) { |
| 740 | 862 | let _ = self |
| 741 | 863 | .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 | + ) |
| 743 | 869 | .await; |
| 744 | 870 | } |
| 745 | 871 | } |
| | @@ -894,12 +1020,12 @@ |
| 894 | 1020 | /// process; a restart re-applies them, which is idempotent. |
| 895 | 1021 | pub async fn ensure_fence(&self) -> anyhow::Result<()> { |
| 896 | 1022 | let mut fenced = self.fenced.lock().await; |
| 897 | | - let netns = fence_netns(); |
| 1023 | + let netns = fence_netns(self.privileged); |
| 898 | 1024 | let (rules, network_mode) = match &netns { |
| 899 | 1025 | Some(path) => (FENCE_RULES_NETNS, format!("ns:{path}")), |
| 900 | 1026 | None => (FENCE_RULES, "host".to_string()), |
| 901 | 1027 | }; |
| 902 | | - let rules = fence_rules(rules).await?; |
| 1028 | + let rules = fence_rules(rules, self.privileged).await?; |
| 903 | 1029 | if fenced.as_deref() == Some(rules.as_str()) { |
| 904 | 1030 | return Ok(()); |
| 905 | 1031 | } |
| | @@ -968,7 +1094,11 @@ |
| 968 | 1094 | .await; |
| 969 | 1095 | let _ = self |
| 970 | 1096 | .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 | + ) |
| 972 | 1102 | .await; |
| 973 | 1103 | outcome.context("fence the container bridges")?; |
| 974 | 1104 | tracing::info!( |
| | @@ -1115,7 +1245,13 @@ |
| 1115 | 1245 | let Some(budget) = self.memory_budget else { |
| 1116 | 1246 | return Ok(()); |
| 1117 | 1247 | }; |
| 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 | + } |
| 1119 | 1255 | let mib = 1024 * 1024; |
| 1120 | 1256 | anyhow::ensure!( |
| 1121 | 1257 | reserved <= budget, |
| | @@ -1245,7 +1381,7 @@ |
| 1245 | 1381 | .docker |
| 1246 | 1382 | .call( |
| 1247 | 1383 | "DELETE", |
| 1248 | | - &format!("/containers/{}?force=true", cell.name), |
| 1384 | + &format!("/containers/{}?force=true&v=true", cell.name), |
| 1249 | 1385 | None, |
| 1250 | 1386 | ) |
| 1251 | 1387 | .await; |
| | @@ -1305,6 +1441,20 @@ |
| 1305 | 1441 | if let Some(runtime) = runtime { |
| 1306 | 1442 | host_config["Runtime"] = json!(runtime); |
| 1307 | 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 | + } |
| 1308 | 1458 | // A container under a non-default runtime gets an explicit resolver |
| 1309 | 1459 | // through a bind-mounted resolv.conf: gVisor cannot reach Docker's |
| 1310 | 1460 | // embedded resolver at `127.0.0.11`, and on a user bridge Docker |
| | @@ -1335,6 +1485,7 @@ |
| 1335 | 1485 | "Env": env, |
| 1336 | 1486 | "Labels": labels, |
| 1337 | 1487 | "HostConfig": host_config, |
| 1488 | + "Volumes": volumes, |
| 1338 | 1489 | }); |
| 1339 | 1490 | if let Some(entrypoint) = params.entrypoint { |
| 1340 | 1491 | body["Cmd"] = json!(entrypoint); |
| | @@ -1359,7 +1510,7 @@ |
| 1359 | 1510 | .docker |
| 1360 | 1511 | .call( |
| 1361 | 1512 | "DELETE", |
| 1362 | | - &format!("/containers/{}?force=true", cell.name), |
| 1513 | + &format!("/containers/{}?force=true&v=true", cell.name), |
| 1363 | 1514 | None, |
| 1364 | 1515 | ) |
| 1365 | 1516 | .await; |
| | @@ -1434,7 +1585,7 @@ |
| 1434 | 1585 | .docker |
| 1435 | 1586 | .call( |
| 1436 | 1587 | "DELETE", |
| 1437 | | - &format!("/containers/{}?force=true", cell.name), |
| 1588 | + &format!("/containers/{}?force=true&v=true", cell.name), |
| 1438 | 1589 | None, |
| 1439 | 1590 | ) |
| 1440 | 1591 | .await; |
| | @@ -1846,7 +1997,7 @@ |
| 1846 | 1997 | .enable_all() |
| 1847 | 1998 | .build() |
| 1848 | 1999 | .unwrap(); |
| 1849 | | - let render = |base| rt.block_on(fence_rules(base)); |
| 2000 | + let render = |base| rt.block_on(fence_rules(base, false)); |
| 1850 | 2001 | let plain = render(FENCE_RULES_NETNS).unwrap(); |
| 1851 | 2002 | assert!( |
| 1852 | 2003 | !plain.contains("#ALLOW") |
| | @@ -1881,6 +2032,10 @@ |
| 1881 | 2032 | assert!( |
| 1882 | 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") |
| 1883 | 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); |
| 1884 | 2039 | |
| 1885 | 2040 | unsafe { |
| 1886 | 2041 | std::env::set_var( |