Diffinery

homeflare/celldpublic

fix(containers): admit containers against a memory budget, not the node's pressure

Running containers' caps no longer shed and evict cells; a start past CELLD_CONTAINER_MEMORY_MB fails with "too many containers".
Jason Schwarzenberger authored 1 parent fccdc3ecommit 08fe855ae9843acef3252e0bd7c1d5370e00fb07Browse files
6 files changed+59−31
Files (6)
modifiedHOMEFLARE.md+1−0View file
@@ -31,6 +31,7 @@
3131 | Fence in another network namespace (`CELLD_FENCE_NETNS`) | Under rootless Podman the fence's `--network host` container can't load nftables rules (`netlink: Operation not permitted`), and the container bridges aren't in the host's namespace anyway: they're in Podman's rootless-netns, which the user owns. With `CELLD_FENCE_NETNS=<path>` the fence joins that namespace (`ns:<path>`) and loads `FENCE_RULES_NETNS`: as `FENCE_RULES`, plus `ct state established,related accept` in forward (the node is another container there, so its replies are forwarded) and port 53 to the bridge gateways (aardvark-dns). Unset keeps upstream's behaviour. |
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. |
34+| 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. |
3435 | `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. |
3536
3637 ## Building
modifiedcrates/celld/actor.rs+0−3View file
@@ -2665,9 +2665,6 @@
26652665 in_use_bytes: metrics.in_use_bytes,
26662666 cgroup_working_set_bytes: metrics.cgroup_working_set_bytes,
26672667 cgroup_current_bytes: metrics.cgroup_current_bytes,
2668- // Containers run in sibling cgroups, so the sample above
2669- // omits their memory; add what they reserve on this node.
2670- container_reserved_bytes: crate::container::reserved_memory_bytes(),
26712668 };
26722669 let now_mono_ms = crate::asyncrt::mono_ms();
26732670 self.drive(Event::LoadSampled { load, now_mono_ms }, out);
modifiedcrates/celld/container.rs+49−12View file
@@ -87,6 +87,25 @@
8787 })
8888 }
8989
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.
99+fn 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+
90109 /// The instance type of a class that declares none, as on Cloudflare.
91110 const DEFAULT_INSTANCE_TYPE: &str = "dev";
92111
@@ -109,14 +128,6 @@
109128 .unwrap_or(0)
110129 }
111130
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.
116-pub fn reserved_memory_bytes() -> u64 {
117- engine_if_ready().map_or(0, |engine| engine.reserved_memory_bytes())
118-}
119-
120131 /// This node's running containers per class, published in the node lease so
121132 /// peers can sum a class's instances across the fleet for `max_instances`.
122133 /// Empty when no engine has connected.
@@ -487,6 +498,9 @@
487498 /// change (homeflare: a fence exception's host resolving elsewhere)
488499 /// installs them again.
489500 fenced: tokio::sync::Mutex<Option<String>>,
501+ /// homeflare: what running containers may reserve together; see
502+ /// `container_memory_budget`. `None`: no budget.
503+ memory_budget: Option<u64>,
490504 }
491505
492506 /// What the runtime told this module about the node: set once at start.
@@ -693,6 +707,7 @@
693707 cells: Mutex::new(HashMap::new()),
694708 networks: tokio::sync::Mutex::new(None),
695709 fenced: tokio::sync::Mutex::new(None),
710+ memory_budget: container_memory_budget()?,
696711 };
697712 engine.reap().await?;
698713 Ok(engine)
@@ -1032,10 +1047,10 @@
10321047 }
10331048
10341049 /// The memory the node's running containers reserve, summed over their
1035- /// instance-type caps. A cell whose container is not running reserves
1036- /// nothing: a stopped container holds no memory, and an idle eviction
1037- /// stops it before the sample would count it.
1038- pub fn reserved_memory_bytes(&self) -> u64 {
1050+ /// instance-type caps: a container can grow to its cap at any moment.
1051+ /// A cell whose container is not running reserves nothing: a stopped
1052+ /// container holds no memory.
1053+ fn reserved_memory_bytes(&self) -> u64 {
10391054 self.cells
10401055 .lock()
10411056 .unwrap()
@@ -1091,6 +1106,27 @@
10911106 Ok(())
10921107 }
10931108
1109+ /// homeflare: refuse a start that would put the node's running
1110+ /// containers over their memory budget. `begin_run` already marked the
1111+ /// starting cell running, so the sum includes it. The refusal fails this
1112+ /// start only, as `max_instances` does, and says "too many containers"
1113+ /// so a caller that retries on capacity (Diffinery) tries again later.
1114+ fn enforce_memory_budget(&self) -> anyhow::Result<()> {
1115+ let Some(budget) = self.memory_budget else {
1116+ return Ok(());
1117+ };
1118+ let reserved = self.reserved_memory_bytes();
1119+ let mib = 1024 * 1024;
1120+ anyhow::ensure!(
1121+ reserved <= budget,
1122+ "too many containers: they would reserve {} MiB of this node's {} MiB \
1123+ of container memory (CELLD_CONTAINER_MEMORY_MB)",
1124+ reserved / mib,
1125+ budget / mib,
1126+ );
1127+ Ok(())
1128+ }
1129+
10941130 async fn inspect_running(&self, cell: &CellContainer) -> anyhow::Result<Option<Address>> {
10951131 let reply = self
10961132 .docker
@@ -1199,6 +1235,7 @@
11991235 ) -> anyhow::Result<Address> {
12001236 self.ensure_fence().await?;
12011237 self.enforce_instance_ceiling(cell).await?;
1238+ self.enforce_memory_budget()?;
12021239 self.ensure_image(&cell.spec.image).await?;
12031240 let (open, internal) = self.networks().await?;
12041241 // A previous run's container may still be named: the wait task
modifiedcrates/celld/env_vars.rs+1−0View file
@@ -272,6 +272,7 @@
272272 "CELLD_ADMISSION_WAIT_MS",
273273 "CELLD_ALARM_RESIDENT_MS",
274274 "CELLD_ASSET_CACHE_BYTES",
275+ "CELLD_CONTAINER_MEMORY_MB",
275276 "CELLD_DEPLOY_MAX_AGE_S",
276277 "CELLD_LOCAL_CACHE_MAX_BYTES",
277278 "CELLD_LTX_TRUNCATE_PAGES",
modifiedcrates/celld/lib.rs+1−0View file
@@ -325,4 +325,5 @@
325325 "version-metadata",
326326 "ratelimits",
327327 "send-email",
328+ "container-memory-budget",
328329 ];
modifiedcrates/logic/pressure.rs+7−16View file
@@ -90,16 +90,11 @@
9090 /// limit constrains, including charges that process RSS does not contain.
9191 /// `None` outside a readable Linux memory cgroup.
9292 pub cgroup_current_bytes: Option<u64>,
93- /// Memory the node commits to its containers, outside this process.
94- ///
95- /// A container runs in its own cgroup, a sibling of the node's, so its
96- /// memory is in neither the process RSS nor the node's cgroup charge. It
97- /// is real memory on the machine all the same, and a container can grow
98- /// to its instance-type cap at any moment, so the node counts each
99- /// running container's cap as committed. Both measurements add it: the
100- /// ordinary ceiling so the node stops taking cells before the machine
101- /// fills, and the hard cap so the absolute limit sees the whole charge.
102- pub container_reserved_bytes: u64,
93+ // homeflare: no container memory. A container runs in its own cgroup, a
94+ // sibling of the node's, and shedding cells gives none of it back, so
95+ // counting it here refused and evicted every cell while CI ran. The
96+ // container engine admits containers against their own budget instead
97+ // (CELLD_CONTAINER_MEMORY_MB).
10398 }
10499
105100 impl Load {
@@ -114,17 +109,13 @@
114109 .cgroup_working_set_bytes
115110 .unwrap_or_default()
116111 .saturating_sub(allocator_slack);
117- self.in_use_bytes
118- .max(cgroup_in_use)
119- .saturating_add(self.container_reserved_bytes)
112+ self.in_use_bytes.max(cgroup_in_use)
120113 }
121114
122115 /// The hard pressure measurement. `memory.current` is authoritative when
123116 /// present because the cgroup limit constrains it, not process RSS.
124117 pub fn hard_bytes(self) -> u64 {
125- self.cgroup_current_bytes
126- .unwrap_or(self.rss_bytes)
127- .saturating_add(self.container_reserved_bytes)
118+ self.cgroup_current_bytes.unwrap_or(self.rss_bytes)
128119 }
129120
130121 pub fn metric_bytes(self, metric: Metric) -> u64 {