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
|
use std::io::BufReader;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
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};
/// The real definition. The module is private, so this `pub`
/// is not a nameable path from outside; the alias below is the
/// only way to reach it, and the alias is what carries the
/// feature-conditional visibility.
mod remote_backend {
use super::*;
// `pub` fields inside a private module are not nameable from
// outside; they stay readable by the impls below.
pub struct RemoteBackend {
pub cfg: Config,
pub token: String,
pub addr: String,
pub queue: Receiver<std::net::TcpStream>,
}
}
/// The remote backend, built by `backend_for`. A fixture test builds one to drive the agent protocol.
///
/// `pub` only under `test-support`. Production reaches the type
/// through its own module and never names it from outside; the
/// outside reader that needs the name is a test.
#[cfg(feature = "test-support")]
pub use remote_backend::RemoteBackend;
#[cfg(not(feature = "test-support"))]
pub(crate) use remote_backend::RemoteBackend;
impl RemoteBackend {
pub fn bind(cfg: &Config, addr: &str, token: &str) -> Result<Self> {
let bound = super::bound_listener(addr, token)?;
Ok(Self { cfg: cfg.clone(), token: token.to_string(), addr: bound.local, queue: bound.rx })
}
/// The address the rendezvous listener actually bound to.
///
/// Test-tier only. Production binds through `bound_listener` and hands the
/// address to the agent itself, so nothing in the crate asks for it back;
/// `tests/remote_agent.rs` needs it to point a real agent at the socket.
/// It is gated rather than left public because the census believed it had
/// production callers at two `listener.local_addr()` calls — std's method
/// on a `TcpListener`, in sibling files, which a name match cannot tell
/// apart from this one. That confusion is what `dotted_only` confirmation
/// in `tools/test-surface.py` now forces a human to resolve.
#[cfg(feature = "test-support")]
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
))
})?;
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(crate) 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 {
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)
}
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)
}
_ => {}
}
}
}
}
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(),
})?;
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(crate::time::inherit(move || {
while !stop.load(Ordering::SeqCst) {
crate::time::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| {
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<()> {
let _ = self.send(&Frame::Destroy {});
Ok(())
}
}
|