summaryrefslogtreecommitdiffstats
path: root/src/sandbox/remote.rs
blob: ba701550daf65f967e071e0aea0217feaf264892 (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
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};

pub struct RemoteBackend {
    cfg: Config,
    token: String,
    addr: String,
    queue: Receiver<std::net::TcpStream>,
}

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 })
    }

    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 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(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| {
            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(())
    }
}