Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- `GET /deployments` and `GET /deployments/{id}` returned the registry `config.password` to any token allowed to read deployments. The API no longer returns it; it reads back as `null`

### Fixed
- An instance whose image was still being pulled kept the memory admitted for it reserved: the next pass refused that very instance on its own reservation, and any other deployment needing the memory, until the pull ended or the reservation expired. A start that does not get its instance running now gives its reservation back
- A config update whose request was cut short after the config was stored (a client that hung up, a server stopped) left the deployments mounting it on the old content: `live` files were not rewritten and `rollout` deployments not redeployed, and nothing caught up. The change is now recorded with the update and the scheduler finishes it
- After the disk filled up during a database write, Ring failed every later write with `database is locked` until it was restarted, and lost writes it had already confirmed. Writes now resume once there is room again
- Replicas started one after the other could all be admitted on the same free memory, before the first had allocated its own, and the OOM killer settled it later. Each admitted instance now reserves its memory for 60 seconds, and later admissions count those reservations
Expand Down
2 changes: 1 addition & 1 deletion documentation/reference/manifest.md
Original file line number Diff line number Diff line change
Expand Up @@ -374,7 +374,7 @@ resources:

Both `limits` and `requests` are optional. Within each, `cpu` and `memory` are also optional.

> **Memory admission control.** Before creating a container or booting a VM, Ring checks the deployment's requested memory against the host's currently-available memory. The figure it admits against is `requests.memory` if set, otherwise `limits.memory` (and, on Cloud Hypervisor, the 256 MiB default when neither is set). If the host can't hold it, the deployment goes to `backing_off` with the reason `insufficient_resources` and an event naming the gap (`needs X MiB but only Y MiB is available`), and is checked again every few seconds since memory gets freed (a refusal is not a restart: it does not raise `restart_count` or use up `max_attempts`), instead of starting and getting OOM-killed (Docker) or failing the VM spawn opaquely (CH). Each admitted instance reserves its memory for 60 seconds, the time to actually allocate it, and later admissions subtract those reservations, so replicas started one after the other cannot all be admitted on the same free memory (`… 300 MiB reserved by instances started in the last 60s`). A deployment never holds more reservations than its `replicas`, so a crash loop does not stack them. The check is still best-effort (workloads Ring did not start are only seen once they allocate), and it is *not* applied to CPU, since CPU overcommit is non-fatal. A deployment that declares no memory request or limit is not gated.
> **Memory admission control.** Before creating a container or booting a VM, Ring checks the deployment's requested memory against the host's currently-available memory. The figure it admits against is `requests.memory` if set, otherwise `limits.memory` (and, on Cloud Hypervisor, the 256 MiB default when neither is set). If the host can't hold it, the deployment goes to `backing_off` with the reason `insufficient_resources` and an event naming the gap (`needs X MiB but only Y MiB is available`), and is checked again every few seconds since memory gets freed (a refusal is not a restart: it does not raise `restart_count` or use up `max_attempts`), instead of starting and getting OOM-killed (Docker) or failing the VM spawn opaquely (CH). Each admitted instance reserves its memory for 60 seconds, the time to actually allocate it, and later admissions subtract those reservations, so replicas started one after the other cannot all be admitted on the same free memory (`… 300 MiB reserved by instances started in the last 60s`). A deployment never holds more reservations than its `replicas`, so a crash loop does not stack them, and a start that does not get its instance running (an image still being pulled, a failed create) gives its reservation back. The check is still best-effort (workloads Ring did not start are only seen once they allocate), and it is *not* applied to CPU, since CPU overcommit is non-fatal. A deployment that declares no memory request or limit is not gated.

> **Cloud Hypervisor sizing.** When `resources` is not set on a CH deployment, the VM defaults to 1 vCPU and 256 MiB of RAM. Resizing is at-boot only; Ring does not use Cloud Hypervisor's `vm.resize` API to live-resize a running VM, so changing `resources` requires a redeploy.

Expand Down
114 changes: 103 additions & 11 deletions src/hypervisor/resources.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,9 @@ pub(crate) struct Reservations {
}

struct Reservation {
/// Tells this reservation apart, so the start it was made for can give it
/// back without touching the others of its deployment.
id: u64,
deployment_id: String,
at: Instant,
bytes: i64,
Expand All @@ -62,7 +65,13 @@ impl Reservations {
/// has more than `replicas` instances alive, so it never holds more than
/// `replicas` reservations: the oldest goes, which is what keeps a crash
/// loop restarting the same instance from stacking reservations.
pub(crate) fn reserve(&mut self, now: Instant, deployment_id: &str, replicas: u32, bytes: i64) {
pub(crate) fn reserve(
&mut self,
now: Instant,
deployment_id: &str,
replicas: u32,
bytes: i64,
) -> u64 {
let held = self
.entries
.iter()
Expand All @@ -76,11 +85,19 @@ impl Reservations {
{
self.entries.remove(oldest);
}
let id = NEXT_RESERVATION.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
self.entries.push(Reservation {
id,
deployment_id: deployment_id.to_string(),
at: now,
bytes,
});
id
}

/// Give back reservation `id`: the start it was made for did not happen.
pub(crate) fn release(&mut self, id: u64) {
self.entries.retain(|r| r.id != id);
}

/// Admit `required_bytes` against `available_bytes` minus what is still
Expand All @@ -91,14 +108,13 @@ impl Reservations {
deployment: &Deployment,
required_bytes: i64,
available_bytes: i64,
) -> Result<(), RuntimeError> {
) -> Result<u64, RuntimeError> {
let replicas = deployment.replicas;
// The oldest reservation of this deployment is about to make room for
// this one when it already holds all its slots: do not count it.
let reserved = self.reserved(now) - self.displaced(deployment, replicas);
check_against(&deployment.name, required_bytes, available_bytes, reserved)?;
self.reserve(now, &deployment.id, replicas, required_bytes);
Ok(())
Ok(self.reserve(now, &deployment.id, replicas, required_bytes))
}

fn displaced(&self, deployment: &Deployment, replicas: u32) -> i64 {
Expand All @@ -118,6 +134,40 @@ static RESERVATIONS: Mutex<Reservations> = Mutex::new(Reservations {
entries: Vec::new(),
});

static NEXT_RESERVATION: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);

fn ledger() -> std::sync::MutexGuard<'static, Reservations> {
// A poisoned lock only means another admission panicked mid-way; the
// ledger is still a plain list of reservations.
RESERVATIONS.lock().unwrap_or_else(|e| e.into_inner())
}

/// The memory an admitted start reserved. Dropped without [`keep`], the start
/// did not happen (it failed, or returned while its image is pulled), and the
/// memory goes back: held for the whole reservation window, it refused the
/// next attempt of the very instance it was reserved for.
///
/// [`keep`]: Admission::keep
#[must_use = "dropping an admission gives its memory back: call keep() once the instance started"]
pub(crate) struct Admission {
reservation: Option<u64>,
}

impl Admission {
/// The instance started: its memory stays reserved for the window.
pub(crate) fn keep(mut self) {
self.reservation = None;
}
}

impl Drop for Admission {
fn drop(&mut self) {
if let Some(id) = self.reservation.take() {
ledger().release(id);
}
}
}

/// The memory figure we admit against, in bytes. `requests.memory` is the
/// scheduling intent ("how much this workload needs to run"), so it wins;
/// `limits.memory` is the cap and is used as a fallback when no request is
Expand Down Expand Up @@ -179,9 +229,9 @@ pub(crate) fn check_against(
/// not start, but it catches the common, gross case ("asked for 8 GiB on a
/// 2 GiB host") and replicas outrunning each other before any expensive image
/// pull or VM boot.
pub(crate) fn check_host_memory(deployment: &Deployment) -> Result<(), RuntimeError> {
pub(crate) fn check_host_memory(deployment: &Deployment) -> Result<Admission, RuntimeError> {
let Some(required) = required_memory_bytes(deployment) else {
return Ok(());
return Ok(Admission { reservation: None });
};

let mut sys = match System::new() {
Expand All @@ -191,18 +241,18 @@ pub(crate) fn check_host_memory(deployment: &Deployment) -> Result<(), RuntimeEr
"skipping the host memory check for '{}': {}",
deployment.name, e
);
return Ok(());
return Ok(Admission { reservation: None });
}
};
sys.refresh_memory();
// sysinfo reports bytes; `available_memory` accounts for reclaimable cache,
// matching what the kernel would actually hand out.
let available = sys.available_memory() as i64;

// A poisoned lock only means another admission panicked mid-way; the
// ledger is still a plain list of reservations.
let mut reservations = RESERVATIONS.lock().unwrap_or_else(|e| e.into_inner());
reservations.admit(Instant::now(), deployment, required, available)
let reservation = ledger().admit(Instant::now(), deployment, required, available)?;
Ok(Admission {
reservation: Some(reservation),
})
}

#[cfg(test)]
Expand Down Expand Up @@ -411,4 +461,46 @@ mod tests {
.is_ok()
);
}

#[test]
fn a_released_reservation_leaves_the_others_of_its_deployment() {
let mut ledger = Reservations::default();
let now = Instant::now();
let first = ledger.reserve(now, "dep", 2, 100);
let second = ledger.reserve(now, "dep", 2, 50);
ledger.release(second);
assert_eq!(ledger.reserved(now), 100);
ledger.release(first);
assert_eq!(ledger.reserved(now), 0);
}

fn held_by(deployment_id: &str) -> usize {
ledger()
.entries
.iter()
.filter(|r| r.deployment_id == deployment_id)
.count()
}

/// A start that returns before its instance exists (an image still being
/// pulled, a failed create) gives its memory back, so the next attempt of
/// the same instance is not refused on it.
#[test]
fn an_admission_given_up_returns_its_memory_and_a_kept_one_holds_it() {
let dropped = format!("dropped-{}", uuid::Uuid::new_v4());
let id = ledger().reserve(Instant::now(), &dropped, 1, 100);
drop(Admission {
reservation: Some(id),
});
assert_eq!(held_by(&dropped), 0);

let kept = format!("kept-{}", uuid::Uuid::new_v4());
let id = ledger().reserve(Instant::now(), &kept, 1, 100);
Admission {
reservation: Some(id),
}
.keep();
assert_eq!(held_by(&kept), 1);
ledger().entries.retain(|r| r.deployment_id != kept);
}
}
3 changes: 2 additions & 1 deletion src/runtime/cloud_hypervisor/lifecycle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -450,7 +450,7 @@ impl CloudHypervisorLifecycle {
// reserves its whole memory at boot, so an over-ask fails the spawn with
// an opaque "Cannot allocate memory". Catch it here with a clear
// need/have message instead.
crate::hypervisor::resources::check_host_memory(deployment)?;
let admission = crate::hypervisor::resources::check_host_memory(deployment)?;

let instance_image = self.instance_image_path(instance_id);
if !instance_image.exists() {
Expand Down Expand Up @@ -811,6 +811,7 @@ impl CloudHypervisorLifecycle {
instance_id, deployment.id
);

admission.keep();
Ok(())
}

Expand Down
3 changes: 2 additions & 1 deletion src/runtime/containerd/lifecycle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -477,7 +477,7 @@ impl ContainerdLifecycle {
client: &containerd_client::Client,
resolved_mounts: &[ResolvedMount],
) -> Result<(), RuntimeError> {
crate::hypervisor::resources::check_host_memory(deployment)?;
let admission = crate::hypervisor::resources::check_host_memory(deployment)?;

let ns = &self.config.namespace;

Expand Down Expand Up @@ -566,6 +566,7 @@ impl ContainerdLifecycle {

deployment.instances.push(instance_id.clone());
info!("containerd instance {} created and started", instance_id);
admission.keep();
Ok(())
}

Expand Down
3 changes: 2 additions & 1 deletion src/runtime/docker/container.rs
Original file line number Diff line number Diff line change
Expand Up @@ -544,7 +544,7 @@ pub(crate) async fn create_container(
// if the host can't hold the requested memory, the container would only get
// OOM-killed at runtime (or, with no limit, take the host down with it).
// Fail here with an actionable message instead.
crate::hypervisor::resources::check_host_memory(deployment)?;
let admission = crate::hypervisor::resources::check_host_memory(deployment)?;

let (name, reference) = parse_image_reference(&deployment.image);

Expand Down Expand Up @@ -758,6 +758,7 @@ pub(crate) async fn create_container(
"Docker container {} created and started successfully",
container_name
);
admission.keep();
Ok(())
}
Err(e) => {
Expand Down
3 changes: 2 additions & 1 deletion src/runtime/firecracker/lifecycle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -471,7 +471,7 @@ impl FirecrackerLifecycle {
// allocation failure — and here it would do so only *after* copying a
// full rootfs image. Same check Cloud Hypervisor already ran; without it
// Firecracker had no memory gate at all.
crate::hypervisor::resources::check_host_memory(deployment)?;
let admission = crate::hypervisor::resources::check_host_memory(deployment)?;

// Private to Ring's user: it stages the decrypted config files and the
// environment handed to the guest.
Expand Down Expand Up @@ -732,6 +732,7 @@ impl FirecrackerLifecycle {
self.taps.lock().unwrap().insert(instance_id.clone(), t);
}
info!("Firecracker microVM {} booted (pid {})", instance_id, pid);
admission.keep();
Ok(instance_id)
}

Expand Down
98 changes: 98 additions & 0 deletions tests/e2e/docker/t59_pulling_instance_reserves_no_memory.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
#!/usr/bin/env bash
# T59: an instance whose image is still being pulled holds no memory.
#
# Memory admission reserves what it admits, so that replicas started one after
# the other cannot all fit in the same free memory. The reservation was made
# before the image pull, and kept when the start returned to wait for the
# pull in the background: the next pass then refused that very instance on its
# own reservation, and any other deployment needing the memory with it.
#
# A deployment requesting 60% of the host's memory pulls from a registry that
# never answers. Another one requesting the same 60% must still start.

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=../lib.sh
source "$SCRIPT_DIR/../lib.sh"

log "== T59: an instance waiting on its pull reserves no memory =="

command -v python3 > /dev/null || fail "python3 is needed for the fake registry"

REGISTRY_PORT=""
for candidate in $(seq 16100 16200); do
if ! (exec 3<>"/dev/tcp/127.0.0.1/$candidate") 2>/dev/null; then
REGISTRY_PORT=$candidate
break
fi
done
[ -n "$REGISTRY_PORT" ] || fail "no free port for the fake registry"

python3 - "$REGISTRY_PORT" <<'PY' &
import socket, sys
s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(("127.0.0.1", int(sys.argv[1])))
s.listen(64)
held = []
while True:
conn, _ = s.accept()
held.append(conn) # accept, never answer
PY
REGISTRY_PID=$!

cleanup_registry() {
local ec=$?
kill "$REGISTRY_PID" 2>/dev/null || true
cleanup_ring
return $ec
}
trap cleanup_registry EXIT

start_ring
ring_login

available_mib=$(awk '/^MemAvailable:/ { print int($2 / 1024) }' /proc/meminfo)
request_mib=$(( available_mib * 60 / 100 ))
log "host has ${available_mib} MiB available, each deployment requests ${request_mib} MiB"

cat > "$RING_TEST_DIR/hang.yaml" <<YAML
deployments:
hang:
name: hang
namespace: ring-e2e
runtime: docker
image: 127.0.0.1:${REGISTRY_PORT}/app:1
replicas: 1
resources:
requests:
memory: "${request_mib}Mi"
YAML
cat > "$RING_TEST_DIR/web.yaml" <<YAML
deployments:
web:
name: web
namespace: ring-e2e
runtime: docker
image: alpine:3.19
command: ["sleep", "600"]
replicas: 1
config:
image_pull_policy: IfNotPresent
resources:
requests:
memory: "${request_mib}Mi"
YAML

docker pull -q alpine:3.19 > /dev/null
"$RING_BIN" apply --file "$RING_TEST_DIR/hang.yaml" > /dev/null
# A few passes: each one admits 'hang' and finds its pull still running.
sleep 5
log "'hang' is waiting on a registry that never answers"

"$RING_BIN" apply --file "$RING_TEST_DIR/web.yaml" > /dev/null
wait_deployment_state "ring-e2e" "web" "running" 30
log "'web' was admitted beside the pulling instance"

log "PASS"
Loading