Skip to content

Commit dd3febc

Browse files
authored
fix(server): find a finished sandbox's supervisor on any replica (#5667)
After a retained sandbox's main process exits, CreateSshSession and ForwardTcp allow access only while the supervisor is connected. The check looked only at the receiving replica's session map, so on a multi-replica gateway a request that landed on another replica was refused with "sandbox is not ready". This broke `sandbox create -- <cmd>` when the command finished before the CLI attached. Check the supervisor owner record too, the same way relay opening already routes to the owning replica. Run the host-gateway client as the sandbox's main process again, so the k3s-ha row covers the attach. Signed-off-by: Piotr Mlocek <pmlocek@nvidia.com>
1 parent d08935e commit dd3febc

3 files changed

Lines changed: 111 additions & 26 deletions

File tree

‎crates/openshell-server/src/grpc/sandbox.rs‎

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2882,7 +2882,7 @@ pub(super) async fn handle_forward_tcp(
28822882
// The main process may finish between minting the SSH token and opening
28832883
// its transport. Keep the relay reachable until terminal delivery is
28842884
// finalized so fast commands can attach without a readiness race.
2885-
if !sandbox_relay_reachable(state, &sandbox) {
2885+
if !sandbox_relay_reachable(state, &sandbox).await? {
28862886
return Err(Status::failed_precondition("sandbox is not ready"));
28872887
}
28882888

@@ -3430,11 +3430,19 @@ pub(super) async fn handle_exec_sandbox_interactive_start(
34303430
// SSH session handlers
34313431
// ---------------------------------------------------------------------------
34323432

3433-
fn sandbox_relay_reachable(state: &ServerState, sandbox: &Sandbox) -> bool {
3434-
let phase = SandboxPhase::try_from(sandbox.phase()).ok();
3435-
matches!(phase, Some(SandboxPhase::Ready))
3436-
|| (matches!(phase, Some(SandboxPhase::Completed | SandboxPhase::Error))
3437-
&& state.supervisor_sessions.has_session(sandbox.object_id()))
3433+
/// Whether a relay into the sandbox can open: always when `Ready`, and after
3434+
/// the main process exits while its supervisor is connected to any replica.
3435+
async fn sandbox_relay_reachable(
3436+
state: &Arc<ServerState>,
3437+
sandbox: &Sandbox,
3438+
) -> Result<bool, Status> {
3439+
match SandboxPhase::try_from(sandbox.phase()).ok() {
3440+
Some(SandboxPhase::Ready) => Ok(true),
3441+
Some(SandboxPhase::Completed | SandboxPhase::Error) => {
3442+
crate::supervisor_session::supervisor_connected(state, sandbox.object_id()).await
3443+
}
3444+
_ => Ok(false),
3445+
}
34383446
}
34393447

34403448
pub(super) async fn handle_create_ssh_session(
@@ -3453,7 +3461,7 @@ pub(super) async fn handle_create_ssh_session(
34533461
.await?;
34543462
let sandbox_id = sandbox.object_id().to_string();
34553463

3456-
if !sandbox_relay_reachable(state, &sandbox) {
3464+
if !sandbox_relay_reachable(state, &sandbox).await? {
34573465
return Err(Status::failed_precondition("sandbox is not ready"));
34583466
}
34593467

@@ -9660,10 +9668,10 @@ mod tests {
96609668
.supervisor_sessions
96619669
.finalize_main_process_exit("sandbox-work")
96629670
);
9663-
assert!(sandbox_relay_reachable(&state, &sandbox));
9671+
assert!(sandbox_relay_reachable(&state, &sandbox).await.unwrap());
96649672

96659673
assert!(state.supervisor_sessions.disconnect("sandbox-work"));
9666-
assert!(!sandbox_relay_reachable(&state, &sandbox));
9674+
assert!(!sandbox_relay_reachable(&state, &sandbox).await.unwrap());
96679675
}
96689676

96699677
#[tokio::test]

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

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1825,6 +1825,33 @@ fn owner_is_fresh(owner: &crate::supervisor_owner::OwnerRecord) -> bool {
18251825
owner.is_fresh(OWNER_TTL)
18261826
}
18271827

1828+
/// Whether this sandbox's supervisor is connected to any replica.
1829+
///
1830+
/// A peer replica counts only through a fresh owner record. An owner record
1831+
/// naming this replica without a local session is a leftover from a lost
1832+
/// session.
1833+
pub async fn supervisor_connected(
1834+
state: &Arc<ServerState>,
1835+
sandbox_id: &str,
1836+
) -> Result<bool, Status> {
1837+
if state.supervisor_sessions.has_session(sandbox_id) {
1838+
return Ok(true);
1839+
}
1840+
if state.store.is_single_replica() {
1841+
return Ok(false);
1842+
}
1843+
let owner_index = SupervisorOwnerIndex::new(state.store.clone(), OWNER_TTL);
1844+
let owner = resolve_owner(state, &owner_index, sandbox_id).await?;
1845+
Ok(peer_holds_session(&state.replica_id, owner.as_ref()))
1846+
}
1847+
1848+
fn peer_holds_session(
1849+
self_replica_id: &str,
1850+
owner: Option<&crate::supervisor_owner::OwnerRecord>,
1851+
) -> bool {
1852+
owner.is_some_and(|owner| owner_is_fresh(owner) && owner.owner_replica_id != self_replica_id)
1853+
}
1854+
18281855
/// The replica currently holding this sandbox's supervisor session, if known.
18291856
pub async fn owner_replica_id(state: &Arc<ServerState>, sandbox_id: &str) -> Option<String> {
18301857
if state.store.is_single_replica() {
@@ -3719,6 +3746,59 @@ mod tests {
37193746
.expect("complete chart peer TLS materials should configure tonic");
37203747
}
37213748

3749+
#[tokio::test]
3750+
async fn supervisor_connected_follows_the_local_session() {
3751+
let state = crate::grpc::test_support::test_server_state().await;
3752+
let connected = |sandbox_id: &'static str| {
3753+
let state = state.clone();
3754+
async move { supervisor_connected(&state, sandbox_id).await.unwrap() }
3755+
};
3756+
3757+
assert!(!connected("relay-none").await);
3758+
3759+
let (tx, _rx) = mpsc::channel(1);
3760+
let (shutdown_tx, _shutdown_rx) = oneshot::channel();
3761+
state.supervisor_sessions.register(
3762+
"relay-local".to_string(),
3763+
"session".to_string(),
3764+
tx,
3765+
shutdown_tx,
3766+
);
3767+
assert!(connected("relay-local").await);
3768+
assert!(state.supervisor_sessions.disconnect("relay-local"));
3769+
assert!(!connected("relay-local").await);
3770+
3771+
// A single replica holds every session itself, so an owner record
3772+
// naming a peer is a leftover and is not read.
3773+
assert!(state.store.is_single_replica());
3774+
SupervisorOwnerIndex::new(state.store.clone(), OWNER_TTL)
3775+
.publish(
3776+
"relay-peer",
3777+
"session",
3778+
"supervisor",
3779+
1,
3780+
"peer-replica",
3781+
"https://peer",
3782+
)
3783+
.await
3784+
.unwrap();
3785+
assert!(!connected("relay-peer").await);
3786+
}
3787+
3788+
#[test]
3789+
fn peer_holds_session_only_through_a_fresh_peer_owner_record() {
3790+
assert!(peer_holds_session("gw-0", Some(&owner_record("gw-1"))));
3791+
assert!(!peer_holds_session("gw-0", None));
3792+
3793+
let mut stale = owner_record("gw-1");
3794+
stale.updated_at_ms = 0;
3795+
assert!(!peer_holds_session("gw-0", Some(&stale)));
3796+
3797+
// An owner record naming this replica without a local session is a
3798+
// leftover from a lost session, not a live supervisor.
3799+
assert!(!peer_holds_session("gw-0", Some(&owner_record("gw-0"))));
3800+
}
3801+
37223802
fn sandbox_record(id: &str, name: &str) -> Sandbox {
37233803
Sandbox {
37243804
metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta {

‎tests/suites/features/host-gateway/tests/host_gateway.rs‎

Lines changed: 14 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,8 @@ const PYTHON: &str = "python3";
2222

2323
/// Requests `/` from `host.openshell.internal` on the port in `argv[1]` and
2424
/// prints the response. The server listens before the sandbox is created,
25-
/// and a Ready sandbox's network is up, so the client doesn't retry.
25+
/// and the network is up before the main process starts, so the client
26+
/// doesn't retry.
2627
const CLIENT: &str = r#"
2728
import socket, sys
2829
@@ -45,25 +46,21 @@ async fn python_sandbox_reaches_host_server(cx: &mut Context) -> testkit::Result
4546
let server = HttpRecorder::start(marker.clone()).await?;
4647
let image = testkit::python_image();
4748

48-
// The client runs through `sandbox exec` in a Ready sandbox, not as the
49-
// main process. A gateway with several replicas (k3s-ha) can refuse to
50-
// attach to a main process that already finished with "sandbox is not
51-
// ready" when the request reaches a replica that doesn't hold the
52-
// sandbox's session.
53-
let sandbox = cx
54-
.sandbox("hg")
49+
// The client runs as the main process. It usually finishes before the CLI
50+
// attaches, so on a gateway with several replicas (k3s-ha) this also
51+
// covers attaching to a finished main process through a replica that
52+
// doesn't hold the sandbox's supervisor session.
53+
let client = cx
54+
.cli_sandbox("hg")
5555
.image(image.clone())
56-
.policy(policy(server.port))
57-
.command(["sh", "-c", "exec sleep infinity"])
58-
.create_ready()
59-
.await
60-
.context(format!("create a sandbox from {image}"))?;
61-
62-
let client = sandbox
63-
.exec([PYTHON, "-c", CLIENT, &server.port.to_string()])
56+
.policy_yaml(policy::to_yaml(&policy(server.port))?)
57+
.command([PYTHON, "-c", CLIENT, &server.port.to_string()])
58+
.run()
6459
.await?
6560
.success()
66-
.context("run the client in the sandbox")?;
61+
.context(format!(
62+
"run the client as the main process of a sandbox from {image}"
63+
))?;
6764
testkit::ensure!(
6865
client.stdout.contains(&marker),
6966
"the client did not get the host server's response:\n{}{}",

0 commit comments

Comments
 (0)