summaryrefslogtreecommitdiffstats
path: root/src/sandbox/remote.rs
blob: 96b1ee6f003f3cd5554b1192affea71f83f85c37 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
//! The hub side of the agent protocol: a [`SandboxBackend`] that leases
//! sandboxes which dial in from outside.
//!
//! The rendezvous is outbound-only: `acquire` waits for an agent to connect
//! and present the shared token, and every command since then is a frame on
//! the connection *the agent initiated*. A sandbox that vanishes mid-run is
//! not an error this code invents — a closed connection reads as a failed
//! step, which reads as an expired lease, which the reaper already turns into
//! a requeue (I5). The remote backend adds no new failure vocabulary.
//!
//! One connection is one lease: after `destroy` (or a drop of the hub side),
//! the agent dies and the next `acquire` waits for a fresh one. That matches
//! the disposable-sandbox model — warm pooling across steps of one build is
//! a backend optimization, not an interface requirement.
//!
//! Workspace note: `Run` frames carry a hub-side `cwd`, which is honest for
//! loopback-shaped deployments and the test tier where hub and sandbox share
//! a filesystem. A remote-over-the-network deployment needs the workspace
//! manifest/tar sync from the design sketch; that is deliberately not here
//! yet, and nothing should pretend otherwise.

use std::collections::HashMap;
use std::io::BufReader;
use std::net::TcpListener;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, OnceLock};

use crossbeam_channel::Receiver;

use crate::config::Config;
use crate::error::{Error, Result};
use crate::sandbox::wire::{self, Frame};
use crate::sandbox::{Exit, Sandbox, SandboxBackend, SandboxInfo, SandboxSpec};

pub struct RemoteBackend {
    cfg: Config,
    token: String,
    addr: String,
    /// Connections the accept thread has taken off the listener but not yet
    /// rendezvoused. `acquire` waits on this up to the spec's TTL.
    queue: Receiver<std::net::TcpStream>,
}

/// A listener shared by every backend built from the same `(addr, token)`.
struct Bound {
    local: String,
    rx: Receiver<std::net::TcpStream>,
}

/// One bound listener per `(address, token)` per process.
///
/// The listener is a property of the *process*, not of a build. Binding it per
/// build — which is what happened while `Ctx::new` constructed a backend for
/// every build — meant a second concurrent build hit `EADDRINUSE` on a fixed
/// `listen` and failed for a reason that had nothing to do with its package.
/// Sharing the queue is also exactly the semantics `remote` already has: an
/// agent dials in when the operator boots one, and whichever build is waiting
/// takes it.
///
/// The token is part of the key on purpose. Two different tokens cannot share a
/// listener, and reusing the first one's listener for a second, different token
/// would be a fail-open surprise; forcing a real bind makes the mistake loud.
fn registry() -> &'static Mutex<HashMap<(String, String), Bound>> {
    static REGISTRY: OnceLock<Mutex<HashMap<(String, String), Bound>>> = OnceLock::new();
    REGISTRY.get_or_init(|| Mutex::new(HashMap::new()))
}

fn bound_listener(addr: &str, token: &str) -> Result<Bound> {
    let key = (addr.to_string(), token.to_string());
    // A poisoned registry means a panic in some other thread's bind; the map
    // itself is still sound, so recover rather than wedge every later build —
    // the same posture as the publish lock.
    let mut reg = registry().lock().unwrap_or_else(|p| p.into_inner());
    if let Some(b) = reg.get(&key) {
        return Ok(Bound { local: b.local.clone(), rx: b.rx.clone() });
    }
    let listener = TcpListener::bind(addr)?;
    let local = listener.local_addr()?.to_string();
    let (tx, rx) = crossbeam_channel::unbounded();
    std::thread::spawn(move || {
        for stream in listener.incoming() {
            match stream {
                Ok(s) => {
                    let _ = tx.send(s);
                }
                Err(_) => break,
            }
        }
    });
    let bound = Bound { local, rx };
    reg.insert(key, Bound { local: bound.local.clone(), rx: bound.rx.clone() });
    Ok(bound)
}

impl RemoteBackend {
    /// Bind the agent listener — or share the one this process already bound for
    /// the same `(addr, token)`. `addr` may name port 0; [`Self::local_addr`]
    /// reports what actually got bound, which is how a test (or a supervisor)
    /// hands the address to the agent without a port negotiation dance.
    pub fn bind(cfg: &Config, addr: &str, token: &str) -> Result<Self> {
        let bound = bound_listener(addr, token)?;
        Ok(Self { cfg: cfg.clone(), token: token.to_string(), addr: bound.local, queue: bound.rx })
    }

    pub fn local_addr(&self) -> &str {
        &self.addr
    }
}

impl SandboxBackend for RemoteBackend {
    fn acquire(&self, spec: &SandboxSpec) -> Result<Arc<dyn Sandbox>> {
        let stream = self.queue.recv_timeout(spec.ttl).map_err(|_| {
            Error::other(format!(
                "no sandbox connected to {} within the lease window",
                self.addr
            ))
        })?;
        // The rendezvous itself is bounded; the run loop is not (pings keep
        // the agent's watchdog fed, and a dead agent fails the step anyway).
        let _ = stream.set_read_timeout(Some(spec.ttl));
        let mut reader = BufReader::new(stream.try_clone()?);
        let agent_id = match wire::read_frame(&mut reader)? {
            Some(Frame::Hello { token, agent_id, profiles }) => {
                if token != self.token {
                    return Err(Error::fail_closed(format!(
                        "sandbox {agent_id} presented the wrong token"
                    )));
                }
                if !profiles.is_empty() && !profiles.contains(&spec.profile) {
                    return Err(Error::fail_closed(format!(
                        "sandbox {agent_id} serves {profiles:?}, not profile {}",
                        spec.profile
                    )));
                }
                agent_id
            }
            Some(other) => return Err(Error::invalid(format!("expected hello, got {other:?}"))),
            None => return Err(Error::other("sandbox disconnected at rendezvous")),
        };
        wire::write_frame(&mut stream.try_clone()?, &Frame::HelloAck { ttl_secs: spec.ttl.as_secs().max(1) })?;
        let _ = stream.set_read_timeout(None);
        Ok(Arc::new(RemoteSandbox::after_hello(
            &self.cfg, stream, agent_id, spec.ttl,
        )))
    }

    fn status(&self) -> Result<Vec<SandboxInfo>> {
        Ok(vec![SandboxInfo {
            id: format!("remote@{}", self.addr),
            profile: self.cfg.build_profile.clone(),
            warm: !self.queue.is_empty(),
        }])
    }
}

pub struct RemoteSandbox {
    cfg: Config,
    id: String,
    ttl: std::time::Duration,
    reader: Mutex<BufReader<std::net::TcpStream>>,
    writer: Mutex<std::net::TcpStream>,
    req: AtomicU64,
}

impl RemoteSandbox {
    /// Wrap a stream whose `Hello` has been verified and answered. Split out
    /// so the kata backend can lease a rendezvoused connection with its own
    /// accept loop without duplicating the sandbox half.
    pub(crate) fn after_hello(cfg: &Config, stream: std::net::TcpStream, agent_id: String, ttl: std::time::Duration) -> Self {
        let reader = BufReader::new(
            stream.try_clone().expect("cloning a connected tcp stream cannot fail"),
        );
        Self {
            cfg: cfg.clone(),
            id: agent_id,
            ttl,
            reader: Mutex::new(reader),
            writer: Mutex::new(stream),
            req: AtomicU64::new(1),
        }
    }

    fn send(&self, frame: &Frame) -> Result<()> {
        wire::write_frame(&mut *self.writer.lock().unwrap(), frame).map_err(Into::into)
    }

    /// Read frames until a reply for `req` arrives. `Log` frames for that
    /// request are handed to `sink` (stream name + bytes) as they arrive, so
    /// the caller gets live streaming *and* can accumulate what it needs.
    fn pump(&self, req: u64, sink: &mut dyn FnMut(&str, &[u8])) -> Result<Frame> {
        loop {
            let frame = match wire::read_frame(&mut *self.reader.lock().unwrap())? {
                Some(f) => f,
                None => return Err(Error::other(format!("sandbox {} vanished", self.id))),
            };
            match frame {
                Frame::Log { req: r, ref stream, ref data } if r == req => {
                    sink(stream, &wire::unhex(data)?);
                }
                Frame::Exit { req: r, .. }
                | Frame::Blob { req: r, .. }
                | Frame::Ok { req: r }
                | Frame::Err { req: r, .. }
                    if r == req =>
                {
                    return Ok(frame)
                }
                _ => {} // Ping echoes and foreign requests are not ours
            }
        }
    }
}

impl Sandbox for RemoteSandbox {
    fn id(&self) -> &str {
        &self.id
    }

    fn run(&self, cmd: &crate::sandbox::Cmd, on_log: &mut dyn FnMut(&[u8])) -> Result<Exit> {
        let req = self.req.fetch_add(1, Ordering::SeqCst);
        self.send(&Frame::Run {
            req,
            argv: cmd.argv.clone(),
            cwd: cmd.cwd.as_ref().map(|p| p.display().to_string()),
            env: self.cfg.child_env_pairs(),
        })?;
        // Keepalive: the agent's watchdog expects a frame at least every TTL;
        // a long build produces none of its own on the control connection.
        let stop = Arc::new(std::sync::atomic::AtomicBool::new(false));
        let mut writer = self.writer.lock().unwrap().try_clone()?;
        {
            let (stop, interval) = (stop.clone(), self.ttl / 3);
            std::thread::spawn(move || {
                while !stop.load(Ordering::SeqCst) {
                    std::thread::sleep(interval.max(std::time::Duration::from_millis(50)));
                    if stop.load(Ordering::SeqCst) {
                        break;
                    }
                    if wire::write_frame(&mut writer, &Frame::Ping {}).is_err() {
                        break;
                    }
                }
            });
        }
        let mut stdout = Vec::new();
        let mut stderr = Vec::new();
        let result = self.pump(req, &mut |stream, bytes| {
            // The build log gets bytes in arrival order; the captured halves
            // keep stdout and stderr apart so error tails name the right one,
            // exactly like the loopback sandbox's Exit.
            on_log(bytes);
            if stream == "stderr" {
                stderr.extend_from_slice(bytes);
            } else {
                stdout.extend_from_slice(bytes);
            }
        });
        stop.store(true, Ordering::SeqCst);
        match result? {
            Frame::Exit { code, .. } => Ok(Exit { code, stdout, stderr }),
            Frame::Err { msg, .. } => Err(Error::other(format!("sandbox {}: {msg}", self.id))),
            other => Err(Error::invalid(format!("sandbox {}: unexpected {other:?}", self.id))),
        }
    }

    fn put(&self, digest: &str, r: &mut dyn std::io::Read) -> Result<()> {
        let req = self.req.fetch_add(1, Ordering::SeqCst);
        let mut buf = Vec::new();
        r.read_to_end(&mut buf)?;
        self.send(&Frame::Put { req, digest: digest.to_string(), data: wire::hex_bytes(&buf) })?;
        match self.pump(req, &mut |_, _| {})? {
            Frame::Ok { .. } => Ok(()),
            Frame::Err { msg, .. } => Err(Error::fail_closed(format!("sandbox {}: {msg}", self.id))),
            other => Err(Error::invalid(format!("sandbox {}: unexpected {other:?}", self.id))),
        }
    }

    fn get(&self, digest: &str) -> Result<Box<dyn std::io::Read>> {
        let req = self.req.fetch_add(1, Ordering::SeqCst);
        self.send(&Frame::Get { req, digest: digest.to_string() })?;
        match self.pump(req, &mut |_, _| {})? {
            Frame::Blob { data, .. } => Ok(Box::new(std::io::Cursor::new(wire::unhex(&data)?))),
            Frame::Err { msg, .. } => Err(Error::other(format!("sandbox {}: {msg}", self.id))),
            other => Err(Error::invalid(format!("sandbox {}: unexpected {other:?}", self.id))),
        }
    }

    fn destroy(&self) -> Result<()> {
        // Best effort: a sandbox that is already gone has nothing to destroy.
        let _ = self.send(&Frame::Destroy {});
        Ok(())
    }
}