Skip to content

Commit f45a2f8

Browse files
EmilienMFrostGod
andauthored
fix(server): scope the SSH identity lock per sandbox and bound data-pool lock holders (#4696)
* fix(server): bound data-pool lock holders The SSH identity and provider-refresh locks each hold their PostgreSQL advisory lock on a data-pool connection, and their holders then query the same pool. At a small database_max_connections, a few holders could take every data connection and wait for one more until sqlx's 30-second acquire timeout, stalling every database request on the replica. Each PostgresStore now has max(1, max_connections / 2) data-pool lock slots. A holder takes a slot before its connection and keeps it until that connection has closed, so every holder can still get a second connection for its queries. A slot that stays busy for the 10-second mutation lock timeout fails with a lock timeout and a warning. The floor rationale in the config docs, man page and startup error now names both holders, and mutation_lock.rs documents the slot-sharing cycle the timeouts break at small pools. Part of #4307. Signed-off-by: Emilien Macchi <emacchi@redhat.com> * fix(server): scope the SSH identity lock per sandbox SSH host identity provisioning and cleanup took one fleet-wide advisory key and a process-wide mutex, so create, start, restart and delete ran that step for one sandbox at a time across the fleet, with each waiting create holding a lock-pool connection. The SSH identity guard now takes the legacy key in shared mode and then an exclusive key derived from the sandbox id, on one data-pool connection and one data-pool lock slot. The local mutex is keyed by sandbox id too. Steps for different sandboxes run at once, steps for the same sandbox still exclude each other on every replica, and gateways from earlier releases, which hold the legacy key exclusively, keep excluding new ones during a rolling upgrade. One 10-second deadline now covers a data-pool lock holder's slot, its connection and every lock statement, as it already did for mutation locks, so the second lock statement doesn't extend the wait under create's mutation guard. A lock that times out returns a lock timeout. Part of #4307. Closes #4686 Signed-off-by: Emilien Macchi <emacchi@redhat.com> * fix(server): release the create guard before the SSH identity step Sandbox creation held its PostgreSQL mutation guard while it waited for the SSH identity keys, so each replica admitted at most one in-flight create per lock-pool connection. The per-sandbox SSH identity lock already fences a concurrent delete, so release the guard before that step. Data-pool lock connections were closed on every release, which opened a new PostgreSQL session per create. Unlock and reset an idle session and return it to the pool; close it only when a lock statement may still be waiting. Signed-off-by: divesh <dgude@nvidia.com> --------- Signed-off-by: Emilien Macchi <emacchi@redhat.com> Signed-off-by: divesh <dgude@nvidia.com> Co-authored-by: divesh <dgude@nvidia.com>
1 parent f882962 commit f45a2f8

14 files changed

Lines changed: 1100 additions & 95 deletions

File tree

‎crates/openshell-server/src/cli.rs‎

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -163,11 +163,14 @@ struct RunArgs {
163163
///
164164
/// When unset, the gateway uses its backend default: 10 with Postgres,
165165
/// 5 with an on-disk `SQLite` database. An in-memory `SQLite` database is
166-
/// always a single connection. Postgres needs at least 2, because the SSH
167-
/// identity lock keeps one connection while it queries the pool, so the
168-
/// gateway rejects 1 there at startup. Each replica opens its own pool,
169-
/// plus a mutation lock pool on Postgres (`--db-lock-max-connections`), so
170-
/// keep the total below what the database server itself admits.
166+
/// always a single connection. Postgres needs at least 2, so the gateway
167+
/// rejects 1 there at startup: an SSH identity or provider-refresh lock
168+
/// holder keeps one data connection for its lock and queries the pool on
169+
/// another, and the gateway caps those holders at half of
170+
/// `database_max_connections` per replica. Each replica opens its own
171+
/// pool, plus a mutation lock pool on Postgres
172+
/// (`--db-lock-max-connections`), so keep the total below what the
173+
/// database server itself admits.
171174
#[arg(
172175
long,
173176
env = "OPENSHELL_DB_MAX_CONNECTIONS",

‎crates/openshell-server/src/compute/mod.rs‎

Lines changed: 47 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1743,8 +1743,10 @@ impl ComputeRuntime {
17431743
metadata.resource_version = result.resource_version;
17441744
}
17451745
// The parent now owns any staged key, including if this request is
1746-
// cancelled. Keep the creation guard until its public identity and
1747-
// protected launch bundle have been committed.
1746+
// cancelled. Release the creation guard before the SSH identity step:
1747+
// its per-sandbox lock fences a concurrent delete on its own, and a
1748+
// guard held across it would cap concurrent creates at the lock pool.
1749+
drop(mutation_guard);
17481750
let prepared = async {
17491751
if let Some(encoded) = runtime_inputs.launch_authentication {
17501752
let authentication = serde_json::from_slice(&encoded)
@@ -1764,7 +1766,6 @@ impl ComputeRuntime {
17641766
}
17651767
}
17661768
.await;
1767-
drop(mutation_guard);
17681769
let launch_authentication = match prepared {
17691770
Ok(authentication) => authentication,
17701771
Err(status) => {
@@ -10369,6 +10370,49 @@ mod tests {
1036910370
assert_eq!(driver.create_calls.load(Ordering::SeqCst), 1);
1037010371
}
1037110372

10373+
#[tokio::test]
10374+
async fn create_releases_its_mutation_guard_before_the_ssh_identity_step() {
10375+
let driver = ControlledDriver::new();
10376+
driver.set_runtime_identity("test-runtime");
10377+
let mut runtime = test_runtime(driver.clone()).await;
10378+
let credentials = configure_test_ssh_credentials(&mut runtime);
10379+
let sandbox = sandbox_record(
10380+
"sb-guard-release",
10381+
"guard-release",
10382+
SandboxPhase::Provisioning,
10383+
);
10384+
let (entered, release) = credentials.gate_next_store();
10385+
let creating = {
10386+
let runtime = runtime.clone();
10387+
let sandbox = sandbox.clone();
10388+
tokio::spawn(async move {
10389+
runtime
10390+
.create_sandbox_authenticated(
10391+
sandbox.clone(),
10392+
None,
10393+
Some(test_launch_authentication(&sandbox)),
10394+
false,
10395+
)
10396+
.await
10397+
})
10398+
};
10399+
entered.await.unwrap();
10400+
10401+
let guard = tokio::time::timeout(
10402+
Duration::from_secs(5),
10403+
runtime.mutation_guard(MutationScope::sandbox("default", sandbox.object_id())),
10404+
)
10405+
.await
10406+
.expect("the SSH identity step must not hold the sandbox mutation guard")
10407+
.unwrap();
10408+
drop(guard);
10409+
10410+
release.send(()).unwrap();
10411+
let created = creating.await.unwrap().unwrap();
10412+
assert!(!created.host_key_fingerprint.is_empty());
10413+
assert_eq!(driver.create_calls.load(Ordering::SeqCst), 1);
10414+
}
10415+
1037210416
#[tokio::test]
1037310417
async fn ssh_credential_delete_failure_keeps_failed_create_deleting_until_reconciliation() {
1037410418
for code in [

‎crates/openshell-server/src/compute/mutation_guard.rs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1373,7 +1373,7 @@ mod tests {
13731373
async move {
13741374
let _ssh = runtime
13751375
.store
1376-
.acquire_ssh_identity_mutation_guard()
1376+
.acquire_ssh_identity_mutation_guard("f")
13771377
.await
13781378
.unwrap();
13791379
drop(
@@ -1397,7 +1397,7 @@ mod tests {
13971397
drop(
13981398
runtime
13991399
.store
1400-
.acquire_ssh_identity_mutation_guard()
1400+
.acquire_ssh_identity_mutation_guard("g")
14011401
.await
14021402
.unwrap(),
14031403
);

‎crates/openshell-server/src/config_file.rs‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -123,8 +123,10 @@ pub struct GatewayFileSection {
123123
/// which must stay under the server's own `max_connections`. Omit to keep
124124
/// the backend default (10 for Postgres, 5 for on-disk `SQLite`); an
125125
/// in-memory `SQLite` database is always a single connection. Postgres
126-
/// needs at least 2, because the SSH identity lock keeps one connection
127-
/// while it queries the pool.
126+
/// needs at least 2: an SSH identity or provider-refresh lock holder keeps
127+
/// one data connection for its lock and queries the pool on another, and
128+
/// the gateway caps those holders at half of `database_max_connections`
129+
/// per replica.
128130
#[serde(default)]
129131
pub database_max_connections: Option<u32>,
130132

‎crates/openshell-server/src/persistence/mod.rs‎

Lines changed: 23 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -425,15 +425,29 @@ impl Store {
425425

426426
/// Independent of the mutation locks: creation already holds its sandbox
427427
/// mutation guard when it provisions a supervisor's durable SSH identity.
428+
///
429+
/// On `PostgreSQL` it takes the legacy
430+
/// [`mutation_lock::SSH_IDENTITY_LOCK_KEY`] shared and then the sandbox's
431+
/// [`mutation_lock::sandbox_ssh_identity_lock_key`] exclusively, in that
432+
/// order on one data-pool connection. Steps for different sandboxes run at
433+
/// once, and gateways from earlier releases, which hold the legacy key
434+
/// exclusively, still exclude every one of them.
428435
pub(crate) async fn acquire_ssh_identity_mutation_guard(
429436
&self,
437+
sandbox_id: &str,
430438
) -> PersistenceResult<SshIdentityMutationGuard> {
431439
lock_order::check(lock_order::Lock::SshIdentity);
432440
match self {
433441
Self::Postgres(store) => Ok(SshIdentityMutationGuard {
434442
_postgres: Some(
435443
store
436-
.acquire_data_pool_lock(mutation_lock::SSH_IDENTITY_LOCK_KEY)
444+
.acquire_data_pool_locks(&[
445+
(mutation_lock::SSH_IDENTITY_LOCK_KEY, LockMode::Shared),
446+
(
447+
mutation_lock::sandbox_ssh_identity_lock_key(sandbox_id),
448+
LockMode::Exclusive,
449+
),
450+
])
437451
.await?,
438452
),
439453
_order: lock_order::hold(lock_order::Lock::SshIdentity),
@@ -462,7 +476,11 @@ impl Store {
462476
let key = i64::from_be_bytes(hash[..8].try_into().expect("eight digest bytes"));
463477
match self {
464478
Self::Postgres(store) => Ok(RefreshMutationGuard {
465-
_postgres: Some(store.acquire_data_pool_lock(key).await?),
479+
_postgres: Some(
480+
store
481+
.acquire_data_pool_locks(&[(key, LockMode::Exclusive)])
482+
.await?,
483+
),
466484
}),
467485
Self::Sqlite(_) => Ok(RefreshMutationGuard { _postgres: None }),
468486
}
@@ -532,8 +550,9 @@ impl Store {
532550
{
533551
return Err(CoreError::config(format!(
534552
"database_max_connections (--db-max-connections, OPENSHELL_DB_MAX_CONNECTIONS) \
535-
is {configured}, but PostgreSQL needs at least {}: the SSH identity lock \
536-
keeps one data connection while it queries the pool",
553+
is {configured}, but PostgreSQL needs at least {}: an SSH identity or \
554+
provider-refresh lock holder keeps one data connection for its lock and \
555+
queries the pool on another",
537556
postgres::MIN_MAX_CONNECTIONS
538557
)));
539558
}

‎crates/openshell-server/src/persistence/mutation_lock.rs‎

Lines changed: 62 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -23,14 +23,28 @@
2323
//! ascending order, all on one lock-pool connection.
2424
//! 4. A task never acquires a mutation guard or a local lifecycle lock while
2525
//! it holds one: no nesting and no upgrade.
26-
//! 5. The SSH identity key, held on a data-pool connection, is a leaf: its
27-
//! holders take no mutation guard, local key, or lifecycle gate, so sandbox
28-
//! creation may wait for it while holding its guard.
26+
//! 5. The SSH identity keys, S([`SSH_IDENTITY_LOCK_KEY`]) and then
27+
//! X([`sandbox_ssh_identity_lock_key`]) on one data-pool connection and one
28+
//! data-pool lock slot, together form a leaf: their holders take no
29+
//! mutation guard, local key, or lifecycle gate. Their data-pool lock slot
30+
//! is shared with provider-refresh holders, which are not leaves: a
31+
//! refresh executor takes S(global) X(workspace) while it holds a slot.
32+
//! Sandbox creation therefore takes the SSH identity keys only after it
33+
//! releases its mutation guard, so it never waits for a slot while
34+
//! executors wait for its keys.
35+
//! 6. A data-pool lock holder never waits for another data-pool lock. At the
36+
//! floor there is one slot, so nesting would wait on itself until the slot
37+
//! deadline. Debug builds don't check this rule, because both holders
38+
//! acquire inside spawned tasks.
2939
//!
3040
//! Within each layer every waiter on a key holds only smaller keys, and the
3141
//! local phase ends before the `PostgreSQL` phase starts, so no wait-for cycle
32-
//! can form. Debug builds check rules 1, 4, and 5 before every acquisition
33-
//! that can wait; see [`super::lock_order`].
42+
//! can form, except through data-pool lock slots (rule 5). The SSH identity
43+
//! keys break key order: a waiter on a sandbox's key holds the legacy key,
44+
//! which can be larger. They are always taken in one fixed order, legacy key
45+
//! first (rule 5), which keeps that layer free of cycles. Debug builds check
46+
//! rules 1, 4, and 5 before every acquisition that can wait; see
47+
//! [`super::lock_order`].
3448
//!
3549
//! The global key is the legacy cross-object key. Gateways from earlier
3650
//! releases hold it exclusively for every mutation, which conflicts with every
@@ -49,13 +63,17 @@ use std::time::Duration;
4963
/// "OPENSHLL" and stay within `PostgreSQL`'s signed 64-bit key space.
5064
pub const GLOBAL_MUTATION_LOCK_KEY: i64 = 0x4f50_454e_5348_4c4c;
5165

52-
/// Advisory-lock key that serializes sandbox SSH host identity provisioning
53-
/// and cleanup across replicas.
66+
/// Legacy compatibility key of sandbox SSH host identity provisioning and
67+
/// cleanup.
5468
///
55-
/// Never change this value: every gateway in a fleet must take the same key.
56-
/// It is held on a data-pool connection, not the lock pool, because sandbox
57-
/// creation takes it while holding its mutation guard. The bytes spell
58-
/// "OSSHHOST".
69+
/// Never change this value: gateways from earlier releases hold it
70+
/// exclusively for every SSH identity step, and this release holds it shared
71+
/// next to [`sandbox_ssh_identity_lock_key`], so old and new replicas keep
72+
/// excluding each other during a rolling upgrade. The shared lock exists only
73+
/// to exclude earlier releases and can be dropped once no supported release
74+
/// takes the key exclusively. It is held on a data-pool connection, not the
75+
/// lock pool, so SSH identity steps never compete with mutation guards for
76+
/// lock connections. The bytes spell "OSSHHOST".
5977
pub const SSH_IDENTITY_LOCK_KEY: i64 = 0x4f53_5348_484f_5354;
6078

6179
/// Upper bound on acquiring one mutation lock set.
@@ -144,6 +162,15 @@ impl MutationLockKey<'_> {
144162
}
145163
}
146164

165+
/// Advisory-lock key of one sandbox's SSH host identity, held exclusively
166+
/// after a shared [`SSH_IDENTITY_LOCK_KEY`].
167+
///
168+
/// Derived like [`MutationLockKey::advisory_key`] but with its own kind, so it
169+
/// never equals the sandbox's mutation lock key.
170+
pub fn sandbox_ssh_identity_lock_key(sandbox_id: &str) -> i64 {
171+
derived_key(b"ssh-identity", sandbox_id)
172+
}
173+
147174
fn derived_key(kind: &[u8], value: &str) -> i64 {
148175
let digest = Sha256::new()
149176
.chain_update(KEY_DOMAIN)
@@ -264,6 +291,30 @@ mod tests {
264291
);
265292
}
266293

294+
#[test]
295+
fn sandbox_ssh_identity_keys_match_golden_values() {
296+
// Computed independently from the documented byte layout with the
297+
// "ssh-identity" kind. Changing either breaks mutual exclusion with
298+
// running replicas.
299+
assert_eq!(
300+
sandbox_ssh_identity_lock_key("00000000-0000-0000-0000-000000000001"),
301+
1_276_723_582_497_569_200
302+
);
303+
assert_eq!(
304+
sandbox_ssh_identity_lock_key("sb-1"),
305+
-7_153_211_921_910_715_692
306+
);
307+
}
308+
309+
#[test]
310+
fn sandbox_ssh_identity_keys_separate_from_other_keys() {
311+
assert_ne!(
312+
sandbox_ssh_identity_lock_key("sb-1"),
313+
MutationLockKey::Sandbox("sb-1").advisory_key()
314+
);
315+
assert_ne!(sandbox_ssh_identity_lock_key("sb-1"), SSH_IDENTITY_LOCK_KEY);
316+
}
317+
267318
#[test]
268319
fn reserved_keys_are_remapped() {
269320
assert_ne!(

0 commit comments

Comments
 (0)