use std::io::{Read, Write};
use std::net::Shutdown;
use std::path::PathBuf;
use std::process::{Child, ExitStatus, Stdio};
use std::sync::Mutex;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;
use super::lent::{self, Files, Peer, Reach};
use crate::commands::exec::{SHELL_FALLBACK_CMD, exec_argv_with, exec_context, session_attach_command, session_new_command};
use crate::devsbd::control::valid_run_id;
use crate::devsbd::rpc::{self, Exit, Json, Obj, Record};
use crate::serve::attaches::{Attaches, Origin};
use crate::serve::endpoint::Stream;
use crate::serve::helper::{Call, CallError, Cancel, HelperClient, Input};
use crate::serve::machines::cli::{DETACHED_EXIT, NO_SESSION_EXIT, VERSION_EXIT};
use crate::state::{Instance, State};
pub const METHOD: &str = "session.attach";
pub mod code {
pub use crate::devsbd::rpc::code::{BAD_REQUEST, FAILED};
pub const DENIED: &str = "denied";
pub const NOT_FOUND: &str = "not-found";
pub const NOT_RUNNING: &str = "not-running";
pub const UNSUPPORTED: &str = "unsupported";
pub const LOST: &str = "lost";
}
const HEADER_WAIT: Duration = Duration::from_secs(30);
const PIPE_TICK: Duration = Duration::from_millis(100);
const PIPE_CHUNK: usize = 64 * 1024;
#[derive(Debug, Clone, PartialEq)]
pub struct Header {
pub root: PathBuf,
pub instance: String,
pub mode: Mode,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Mode {
Session { id: String, create: Option<Vec<String>> },
Pipe { argv: Vec<String>, interactive: bool },
Service { name: String, argv: Vec<String> },
}
fn bad(message: impl Into<String>) -> Record {
Record::error(code::BAD_REQUEST, message)
}
fn kind(rec: &Record) -> &'static str {
match rec {
Record::Call(_) => "call",
Record::Stdin(_) => "stdin",
Record::StdinEof => "stdin-eof",
Record::Resize { .. } => "resize",
Record::Signal(_) => "signal",
Record::Stdout(_) => "stdout",
Record::Stderr(_) => "stderr",
Record::Event(_) => "event",
Record::Result(_) => "result",
Record::Error { .. } => "error",
Record::Exit(_) => "exit",
}
}
pub fn parse_header(rec: Record) -> Result<Header, Record> {
let call = match rec {
Record::Call(call) => call,
other => return Err(bad(format!("a PTY stream starts with a `{METHOD}` call, not a `{}` record", kind(&other)))),
};
if call.method != METHOD {
return Err(bad(format!("a PTY stream's call is `{METHOD}`, not `{}`", call.method)));
}
let p = &call.params;
let text = |key: &str| p.str(key).filter(|s| !s.is_empty()).ok_or_else(|| bad(format!("the PTY header needs `{key}`")));
let root = PathBuf::from(text("root")?);
let instance = text("instance")?.to_string();
let present = |key: &str| !matches!(p.get(key), None | Some(Json::Null));
let create_argv = |c: &Obj| match c.get("argv") {
None | Some(Json::Null) => Ok(Vec::new()),
Some(Json::Strs(argv)) => Ok(argv.clone()),
Some(_) => Err(bad("`create.argv` must be an array of strings")),
};
if present("service") {
if present("session") || present("pipe") {
return Err(bad("the PTY header takes one of `session`, `pipe` and `service`"));
}
let name = text("service")?.to_string();
let argv = match p.get("create") {
Some(Json::Obj(c)) => create_argv(c)?,
None | Some(Json::Null) => return Err(bad("a service terminal needs `create` (there are no service sessions)")),
Some(_) => return Err(bad("`create` must be an object")),
};
return Ok(Header { root, instance, mode: Mode::Service { name, argv } });
}
if present("pipe") {
if present("session") || present("create") {
return Err(bad("the PTY header takes `pipe` or `session`, not both"));
}
let Some(Json::Obj(pipe)) = p.get("pipe") else { return Err(bad("`pipe` must be an object")) };
let argv = match pipe.get("argv") {
Some(Json::Strs(argv)) if !argv.is_empty() => argv.clone(),
Some(Json::Strs(_)) | None | Some(Json::Null) => return Err(bad("`pipe.argv` needs a command")),
Some(_) => return Err(bad("`pipe.argv` must be an array of strings")),
};
let interactive = match pipe.get("interactive") {
None | Some(Json::Null) => false,
Some(Json::Bool(b)) => *b,
Some(_) => return Err(bad("`pipe.interactive` must be a boolean")),
};
return Ok(Header { root, instance, mode: Mode::Pipe { argv, interactive } });
}
let id = text("session")?.to_string();
if !valid_run_id(&id) {
return Err(bad(format!("bad session id `{id}`")));
}
let create = match p.get("create") {
None | Some(Json::Null) => None,
Some(Json::Obj(c)) => Some(create_argv(c)?),
Some(_) => return Err(bad("`create` must be an object")),
};
Ok(Header { root, instance, mode: Mode::Session { id, create } })
}
pub fn gate<'a>(h: &Header, state: &'a State, reach: &Reach) -> Result<(&'a str, &'a Instance), Record> {
let root = lent::confine_path(reach, &h.root, true).map_err(|e| match e.code {
"invalid" => bad(e.message),
code => Record::error(code, e.message),
})?;
let lent = lent::lent_instances(state, reach);
let by_name = state.instances.get_key_value(&h.instance);
let found = by_name
.or_else(|| state.instances.iter().find(|(_, i)| i.instance_id == h.instance))
.filter(|(name, i)| lent.names.contains(*name) && i.config_dir.as_deref().is_some_and(|d| lent::root_under(d, &root)));
let Some((name, instance)) = found else {
return Err(Record::error(code::NOT_FOUND, format!("no instance `{}` in {}", h.instance, root.display())));
};
Ok((name.as_str(), instance))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Terminal {
Attach,
Client,
Tty,
}
pub const TTY_NOTE: &str = "this terminal isn't resumable (no helper): a dropped link ends it\r\n";
pub fn decide(create: bool, offers: Option<Result<bool, CallError>>, name: &str) -> Result<Terminal, Record> {
match offers {
Some(Ok(true)) => Ok(Terminal::Attach),
Some(Ok(false) | Err(CallError::Unsupported(_))) => Ok(Terminal::Client),
Some(Err(e)) => Err(refusal(e, name)),
None if create => Ok(Terminal::Tty),
None => Err(Record::error(
rpc::code::NO_SESSION,
format!("`{name}`'s terminals over the fleet link aren't resumable (no helper): no session to attach to"),
)),
}
}
pub fn client_command(id: &str, create: Option<&[String]>) -> Vec<String> {
match create {
Some(argv) => session_new_command(id, &or_shell(argv)),
None => session_attach_command(id),
}
}
fn refusal(e: CallError, name: &str) -> Record {
match e {
CallError::NoBridge(_) => {
Record::error(code::NOT_RUNNING, format!("`{name}` isn't running (or its helper's bridge isn't up yet)"))
}
CallError::Unsupported(_) => Record::error(code::UNSUPPORTED, format!("`{name}`'s helper no longer offers `{METHOD}`")),
e => Record::error(code::FAILED, format!("cannot ask `{name}`'s helper: {e}")),
}
}
pub fn service_container(instance: &Instance, name: &str, state: &State, service: &str) -> Result<String, Record> {
let failed = |e: anyhow::Error| Record::error(code::FAILED, format!("{e:#}"));
let dir = instance
.config_dir
.as_deref()
.ok_or_else(|| Record::error(code::NOT_FOUND, format!("`{name}` has no config root recorded")))?;
let config = crate::config::Config::load(dir).map_err(failed)?;
let project = crate::commands::services::project_id(dir).map_err(failed)?;
crate::commands::port::service_container_for(&config, state, &project, name, service)
.map_err(|e| Record::error(code::NOT_FOUND, e))
}
pub fn attach_params(id: &str, create: Option<&[String]>, instance: &Instance, host_agent: bool) -> Obj {
let params = Obj::new().with("id", id);
let Some(argv) = create else { return params };
let argv = if argv.is_empty() { SHELL_FALLBACK_CMD.iter().map(|s| s.to_string()).collect() } else { argv.to_vec() };
let ctx = exec_context(instance, host_agent);
let env = ctx.env.iter().fold(Obj::new(), |env, (k, v)| env.with(k, v.as_str()));
let mut create = Obj::new().with("argv", argv).with("cwd", ctx.cwd).with("env", env);
if let Some(user) = ctx.user {
create = create.with("user", user);
}
params.with("create", create)
}
pub enum Target<'a> {
Instance { instance: &'a Instance, interactive: bool, tty: bool, argv: &'a [String], host_agent: bool },
Service { container: &'a str, argv: &'a [String] },
}
pub type ExecCommand = fn(&Target) -> Vec<String>;
pub fn runtime_exec(t: &Target) -> Vec<String> {
let mut argv = vec![crate::runtime::backend().bin().to_string()];
match t {
Target::Instance { instance, interactive, tty, argv: command, host_agent } => {
argv.extend(exec_argv_with(instance, *interactive, *tty, command, *host_agent));
}
Target::Service { container, argv: command } => {
argv.extend(["exec", "-i", "-t", container].map(String::from));
argv.extend(command.iter().cloned());
}
}
argv
}
fn or_shell(argv: &[String]) -> Vec<String> {
if argv.is_empty() { SHELL_FALLBACK_CMD.iter().map(|s| s.to_string()).collect() } else { argv.to_vec() }
}
pub fn exit_record(status: ExitStatus) -> Record {
use std::os::unix::process::ExitStatusExt;
Record::Exit(match (status.code(), status.signal()) {
(Some(code), _) => Exit::Code(code),
(None, Some(signal)) => Exit::Signal(signal),
(None, None) => Exit::Code(1),
})
}
pub fn tty_exit_record(status: &portable_pty::ExitStatus) -> Record {
Record::Exit(match status.signal() {
Some(name) => signal_number(name).map(Exit::Signal).unwrap_or(Exit::Code(i32::try_from(status.exit_code()).unwrap_or(1))),
None => Exit::Code(i32::try_from(status.exit_code()).unwrap_or(i32::MAX)),
})
}
pub fn client_exit_record(status: &portable_pty::ExitStatus) -> Record {
let code = match i32::try_from(status.exit_code()) {
_ if status.signal().is_some() => None,
Ok(NO_SESSION_EXIT) => Some(rpc::code::NO_SESSION),
Ok(DETACHED_EXIT) => Some(rpc::code::DETACHED),
Ok(VERSION_EXIT) => Some(rpc::code::VERSION),
_ => None,
};
match code {
Some(code) => Record::error(code, ""),
None => tty_exit_record(status),
}
}
fn signal_number(name: &str) -> Option<i32> {
if let Some(n) = name.strip_prefix("Signal ") {
return n.parse().ok();
}
(1..65).find(|&n| {
let s = unsafe { libc::strsignal(n) };
!s.is_null() && unsafe { std::ffi::CStr::from_ptr(s) }.to_string_lossy() == name
})
}
pub struct Tty {
master: Box<dyn portable_pty::MasterPty + Send>,
child: Box<dyn portable_pty::Child + Send + Sync>,
reader: Box<dyn Read + Send>,
writer: Box<dyn Write + Send>,
}
pub fn spawn_tty(argv: Vec<String>) -> anyhow::Result<Tty> {
use portable_pty::{CommandBuilder, PtySize, native_pty_system};
let pair = native_pty_system().openpty(PtySize { rows: 24, cols: 80, pixel_width: 0, pixel_height: 0 })?;
let mut cmd = CommandBuilder::from_argv(argv.into_iter().map(Into::into).collect());
cmd.env("TERM", "xterm-256color");
let child = pair.slave.spawn_command(cmd)?;
drop(pair.slave);
let reader = pair.master.try_clone_reader()?;
let writer = pair.master.take_writer()?;
Ok(Tty { master: pair.master, child, reader, writer })
}
enum Started {
Attach(Call, Input),
Pipe(Child),
Tty(Tty, Option<String>, EndOf),
}
#[allow(clippy::too_many_arguments)]
pub fn serve(
link: Stream,
helper: &HelperClient,
files: &Files,
peer: &Peer,
attaches: &Attaches,
host_agent: fn() -> bool,
exec: ExecCommand,
log: fn(&str),
) {
let caller = format!("fleet control plane {}", peer.name);
let _ = link.set_read_timeout(Some(HEADER_WAIT));
let first = rpc::read_record(&mut &link);
let _ = link.set_read_timeout(None);
let started = match first {
Ok(Some(rec)) => start(rec, &link, helper, files, peer, host_agent, exec, &caller, log),
Ok(None) => return,
Err(e) => Err(bad(format!("no PTY header: {e}"))),
};
match started {
Ok((started, instance_id)) => {
let _attach = (!matches!(started, Started::Pipe(_)))
.then(|| attaches.begin_in(&instance_id, Origin::Member(peer.name.clone())));
match started {
Started::Attach(call, input) => pump(&link, call, input),
Started::Pipe(child) => run_pipe(&link, child),
Started::Tty(tty, note, end) => run_tty(&link, tty, note.as_deref(), end),
}
}
Err(rec) => {
if let Record::Error { code: c, message } = &rec
&& c == code::DENIED
{
log(&format!("fleet: refused a PTY stream from {}: {message}", peer.name));
}
let _ = rpc::write_record(&mut &link, &rec);
}
}
let _ = link.shutdown(Shutdown::Both);
}
#[allow(clippy::too_many_arguments)]
fn start(
first: Record,
link: &Stream,
helper: &HelperClient,
files: &Files,
peer: &Peer,
host_agent: fn() -> bool,
exec: ExecCommand,
caller: &str,
log: fn(&str),
) -> Result<(Started, String), Record> {
let h = parse_header(first)?;
let state = State::load_at(&files.state).map_err(|e| Record::error(code::FAILED, format!("{e:#}")))?;
let (reach, warning) = Reach::load(files, peer.fleet_root.as_deref());
if let Some(w) = warning {
log(&format!("fleet: a PTY stream from {}: {w}", peer.name));
}
let (name, instance) = gate(&h, &state, &reach)?;
let id = instance.instance_id.clone();
start_in(&h, &state, name, instance, link, helper, host_agent, exec, caller).map(|s| (s, id))
}
#[allow(clippy::too_many_arguments)]
fn start_in(
h: &Header,
state: &State,
name: &str,
instance: &Instance,
link: &Stream,
helper: &HelperClient,
host_agent: fn() -> bool,
exec: ExecCommand,
caller: &str,
) -> Result<Started, Record> {
let tty = |argv: Vec<String>, note: Option<String>, end: EndOf| {
spawn_tty(argv)
.map(|t| Started::Tty(t, note, end))
.map_err(|e| Record::error(code::FAILED, format!("cannot run a terminal in `{name}`: {e:#}")))
};
let (id, create) = match &h.mode {
Mode::Pipe { argv, interactive } => {
let target = Target::Instance { instance, interactive: *interactive, tty: false, argv, host_agent: host_agent() };
let argv = exec(&target);
let (program, args) = argv.split_first().ok_or_else(|| Record::error(code::FAILED, "an empty exec"))?;
let mut command = std::process::Command::new(program);
command
.args(args)
.stdin(if *interactive { Stdio::piped() } else { Stdio::null() })
.stdout(Stdio::piped())
.stderr(Stdio::piped());
return command
.spawn()
.map(Started::Pipe)
.map_err(|e| Record::error(code::FAILED, format!("cannot run an exec in `{name}`: {e}")));
}
Mode::Service { name: service, argv } => {
let container = service_container(instance, name, state, service)?;
return tty(exec(&Target::Service { container: &container, argv: &or_shell(argv) }), None, tty_exit_record);
}
Mode::Session { id, create } => (id, create),
};
let offers = instance.devsbd_arch.is_some().then(|| helper.offers(&instance.container, METHOD, caller));
let (argv, note, end): (_, _, EndOf) = match decide(create.is_some(), offers, name)? {
Terminal::Attach => (None, None, tty_exit_record),
Terminal::Client => (Some(client_command(id, create.as_deref())), None, client_exit_record),
Terminal::Tty => (Some(or_shell(create.as_deref().unwrap_or_default())), Some(TTY_NOTE.to_string()), tty_exit_record),
};
if let Some(argv) = argv {
let target = Target::Instance { instance, interactive: true, tty: true, argv: &argv, host_agent: host_agent() };
return tty(exec(&target), note, end);
}
let params = attach_params(id, create.as_deref(), instance, host_agent());
let abandoned = || crate::serve::daemon::hung_up(link, Duration::ZERO);
let (call, input) = helper.call_with_input(&instance.container, METHOD, params, Obj::new(), caller, &abandoned).map_err(|e| match e {
CallError::NoBridge(_) | CallError::Unsupported(_) => refusal(e, name),
CallError::Abandoned => Record::error(code::FAILED, "the caller hung up while the attach queued"),
CallError::Io(e) => Record::error(code::LOST, format!("cannot reach `{name}`'s helper: {e}")),
})?;
Ok(Started::Attach(call, input))
}
fn run_pipe(link: &Stream, mut child: Child) {
let (stdin, stdout, stderr) = (child.stdin.take(), child.stdout.take(), child.stderr.take());
let writer = Mutex::new(());
let send = |rec: &Record| {
let _turn = writer.lock().unwrap_or_else(|e| e.into_inner());
rpc::write_record(&mut &*link, rec).is_ok()
};
let done = AtomicBool::new(false);
let gone = AtomicBool::new(false);
std::thread::scope(|s| {
let send = &send;
let out = stdout.map(|r| s.spawn(move || drain(r, Record::Stdout, send)));
let err = stderr.map(|r| s.spawn(move || drain(r, Record::Stderr, send)));
if let Ok(reader) = link.try_clone() {
let (done, gone) = (&done, &gone);
s.spawn(move || feed_pipe(reader, stdin, done, gone));
}
let ended = loop {
match child.try_wait() {
Ok(Some(status)) => break Ok(status),
Ok(None) => {}
Err(e) => break Err(e),
}
if gone.load(Ordering::SeqCst) || crate::serve::daemon::hung_up(link, PIPE_TICK) {
gone.store(true, Ordering::SeqCst);
let _ = child.kill();
let _ = child.wait();
break Err(std::io::Error::other("the caller hung up"));
}
};
for drained in [out, err].into_iter().flatten() {
let _ = drained.join();
}
if !gone.load(Ordering::SeqCst) {
let last = match ended {
Ok(status) => exit_record(status),
Err(e) => {
let _ = child.kill();
let _ = child.wait();
Record::error(code::FAILED, format!("cannot wait for the exec: {e}"))
}
};
send(&last);
}
done.store(true, Ordering::SeqCst);
let _ = link.shutdown(Shutdown::Both);
});
}
type EndOf = fn(&portable_pty::ExitStatus) -> Record;
fn run_tty(link: &Stream, tty: Tty, note: Option<&str>, end: EndOf) {
let Tty { master, mut child, reader, writer } = tty;
let master = Mutex::new(master);
let turn = Mutex::new(());
let send = |rec: &Record| {
let _turn = turn.lock().unwrap_or_else(|e| e.into_inner());
rpc::write_record(&mut &*link, rec).is_ok()
};
if let Some(note) = note {
send(&Record::Stderr(note.as_bytes().to_vec()));
}
let done = AtomicBool::new(false);
let gone = AtomicBool::new(false);
std::thread::scope(|s| {
let send = &send;
let out = s.spawn(move || drain(reader, Record::Stdout, send));
let (m, d, g) = (&master, &done, &gone);
let feeder = link.try_clone().ok().map(|r| s.spawn(move || feed_tty(r, writer, m, d, g)));
let ended = loop {
match child.try_wait() {
Ok(Some(status)) => break Ok(status),
Ok(None) => {}
Err(e) => break Err(e),
}
if gone.load(Ordering::SeqCst) || crate::serve::daemon::hung_up(link, PIPE_TICK) {
gone.store(true, Ordering::SeqCst);
let _ = child.kill();
let _ = child.wait();
break Err(std::io::Error::other("the caller hung up"));
}
};
let _ = out.join();
if !gone.load(Ordering::SeqCst) {
let last = match ended {
Ok(status) => end(&status),
Err(e) => {
let _ = child.kill();
let _ = child.wait();
Record::error(code::FAILED, format!("cannot wait for the terminal: {e}"))
}
};
send(&last);
}
done.store(true, Ordering::SeqCst);
let _ = link.shutdown(Shutdown::Both);
if let Some(feeder) = feeder {
drop(feeder.join());
}
});
}
fn feed_tty(
mut reader: Stream,
mut writer: Box<dyn Write + Send>,
master: &Mutex<Box<dyn portable_pty::MasterPty + Send>>,
done: &AtomicBool,
gone: &AtomicBool,
) -> Box<dyn Write + Send> {
loop {
match rpc::read_record(&mut reader) {
Ok(Some(Record::Stdin(bytes))) => {
let _ = writer.write_all(&bytes).and_then(|()| writer.flush());
}
Ok(Some(Record::Resize { cols, rows })) => {
let size = portable_pty::PtySize { rows, cols, pixel_width: 0, pixel_height: 0 };
let _ = master.lock().unwrap_or_else(|e| e.into_inner()).resize(size);
}
Ok(Some(_)) => {}
Ok(None) | Err(_) => {
if !done.load(Ordering::SeqCst) {
gone.store(true, Ordering::SeqCst);
}
return writer;
}
}
}
}
fn drain(mut r: impl Read, wrap: fn(Vec<u8>) -> Record, send: &(dyn Fn(&Record) -> bool + Sync)) {
let mut buf = vec![0u8; PIPE_CHUNK];
loop {
match r.read(&mut buf) {
Ok(0) => return,
Ok(n) => {
if !send(&wrap(buf[..n].to_vec())) {
return;
}
}
Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
Err(_) => return,
}
}
}
fn feed_pipe(mut reader: Stream, mut stdin: Option<std::process::ChildStdin>, done: &AtomicBool, gone: &AtomicBool) {
loop {
match rpc::read_record(&mut reader) {
Ok(Some(Record::Stdin(bytes))) => {
if let Some(w) = &mut stdin
&& w.write_all(&bytes).is_err()
{
stdin = None;
}
}
Ok(Some(Record::StdinEof)) => stdin = None,
Ok(Some(_)) => {}
Ok(None) | Err(_) => {
if !done.load(Ordering::SeqCst) {
gone.store(true, Ordering::SeqCst);
}
return;
}
}
}
}
fn is_end(rec: &Record) -> bool {
matches!(rec, Record::Exit(_) | Record::Error { .. } | Record::Result(_))
}
fn pump(link: &Stream, mut call: Call, input: Input) {
let done = AtomicBool::new(false);
let gone = AtomicBool::new(false);
let cancel = call.canceller();
std::thread::scope(|s| {
if let Ok(reader) = link.try_clone() {
let (done, gone, cancel) = (&done, &gone, &cancel);
s.spawn(move || feed(reader, input, done, gone, cancel));
}
let last = loop {
match call.next() {
Ok(Some(rec)) => {
let end = is_end(&rec);
if rpc::write_record(&mut &*link, &rec).is_err() || end {
break None;
}
}
Ok(None) => break Some(Record::error(code::LOST, "the attach ended without an end record")),
Err(_) if gone.load(Ordering::SeqCst) => break None,
Err(e) => break Some(Record::error(code::LOST, format!("the bridge to the instance was lost: {e}"))),
}
};
if let Some(rec) = last {
let _ = rpc::write_record(&mut &*link, &rec);
}
done.store(true, Ordering::SeqCst);
let _ = link.shutdown(Shutdown::Both);
});
}
fn feed(mut reader: Stream, mut input: Input, done: &AtomicBool, gone: &AtomicBool, cancel: &Cancel) {
loop {
let sent = match rpc::read_record(&mut reader) {
Ok(Some(Record::Stdin(bytes))) => input.stdin(&bytes),
Ok(Some(Record::Resize { cols, rows })) => input.resize(cols, rows),
Ok(Some(Record::StdinEof)) => input.stdin_eof(),
Ok(Some(_)) => Ok(()),
Ok(None) | Err(_) => {
if !done.load(Ordering::SeqCst) {
gone.store(true, Ordering::SeqCst);
cancel.cancel();
}
return;
}
};
if sent.is_err() {
return;
}
}
}
#[cfg(test)]
mod tests {
use std::collections::BTreeMap;
use std::os::unix::net::UnixStream;
use std::path::Path;
use super::*;
use crate::devsbd::proto::caps;
use crate::devsbd::rpc::{Call as RpcCall, Exit};
use crate::serve::helper::tests::{Fake, log, logged};
fn scratch(tag: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("dsv-pty-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
std::fs::canonicalize(&dir).unwrap()
}
const SESSION: &str = "1700000000-ab12";
fn header(params: Obj) -> Record {
Record::Call(RpcCall { method: METHOD.into(), params, meta: Obj::new() })
}
fn base(root: &str) -> Obj {
Obj::new().with("root", root).with("instance", "web-1").with("session", SESSION)
}
#[test]
fn the_header_parses_and_is_checked() {
let h = parse_header(header(base("/f/cfg"))).unwrap();
assert_eq!(h, Header { root: "/f/cfg".into(), instance: "web-1".into(), mode: session(None) });
let shell = parse_header(header(base("/f").with("create", Obj::new()))).unwrap();
assert_eq!(shell.mode, session(Some(Vec::new())), "no argv: the login shell");
let argv = parse_header(header(base("/f").with("create", Obj::new().with("argv", vec!["htop".to_string()])))).unwrap();
assert_eq!(argv.mode, session(Some(vec!["htop".to_string()])));
assert_eq!(parse_header(header(base("/f").with("create", Json::Null))).unwrap().mode, session(None));
let refused = |rec: Record| match parse_header(rec) {
Err(Record::Error { code, message }) => (code, message),
other => panic!("{other:?}"),
};
let (c, m) = refused(Record::Stdin(b"x".to_vec()));
assert_eq!((c.as_str(), m.contains("not a `stdin` record")), (code::BAD_REQUEST, true));
let wrong = Record::Call(RpcCall { method: "run.start".into(), params: base("/f"), meta: Obj::new() });
assert!(refused(wrong).1.contains("not `run.start`"));
assert!(refused(header(base("/f").with("session", "nope"))).1.contains("bad session id"));
assert!(refused(header(base("/f").with("instance", ""))).1.contains("needs `instance`"));
assert!(refused(header(Obj::new().with("instance", "a").with("session", SESSION))).1.contains("needs `root`"));
assert!(refused(header(base("/f").with("create", "sh"))).1.contains("`create` must be"));
assert!(refused(header(base("/f").with("create", Obj::new().with("argv", "sh")))).1.contains("`create.argv`"));
}
fn session(create: Option<Vec<String>>) -> Mode {
Mode::Session { id: SESSION.into(), create }
}
fn pipe_base(root: &str) -> Obj {
Obj::new().with("root", root).with("instance", "web-1")
}
#[test]
fn a_pipe_header_parses_and_excludes_a_session() {
let ls = || Obj::new().with("argv", vec!["ls".to_string(), "-l".into()]);
let h = parse_header(header(pipe_base("/f").with("pipe", ls()))).unwrap();
assert_eq!(h.mode, Mode::Pipe { argv: vec!["ls".into(), "-l".into()], interactive: false }, "no session needed");
let i = parse_header(header(pipe_base("/f").with("pipe", ls().with("interactive", true)))).unwrap();
assert_eq!(i.mode, Mode::Pipe { argv: vec!["ls".into(), "-l".into()], interactive: true });
let refused = |params: Obj| match parse_header(header(params)) {
Err(Record::Error { code, message }) => {
assert_eq!(code, code::BAD_REQUEST);
message
}
other => panic!("{other:?}"),
};
assert!(refused(base("/f").with("pipe", ls())).contains("not both"), "with a session");
assert!(refused(pipe_base("/f").with("pipe", ls()).with("create", Obj::new())).contains("not both"));
assert!(refused(pipe_base("/f").with("pipe", Obj::new())).contains("needs a command"));
assert!(refused(pipe_base("/f").with("pipe", Obj::new().with("argv", Vec::<String>::new()))).contains("needs a command"));
assert!(refused(pipe_base("/f").with("pipe", Obj::new().with("argv", "ls"))).contains("array of strings"));
assert!(refused(pipe_base("/f").with("pipe", ls().with("interactive", "yes"))).contains("boolean"));
assert!(refused(pipe_base("/f").with("pipe", "ls")).contains("must be an object"));
assert!(refused(pipe_base("/f")).contains("needs `session`"), "neither");
}
#[test]
fn a_service_header_parses_creates_and_excludes_the_others() {
let svc = || pipe_base("/f").with("service", "db");
let h = parse_header(header(svc().with("create", Obj::new()))).unwrap();
assert_eq!(h, Header { root: "/f".into(), instance: "web-1".into(), mode: Mode::Service { name: "db".into(), argv: vec![] } });
let psql = parse_header(header(svc().with("create", Obj::new().with("argv", vec!["psql".to_string()])))).unwrap();
assert_eq!(psql.mode, Mode::Service { name: "db".into(), argv: vec!["psql".into()] });
let refused = |params: Obj| match parse_header(header(params)) {
Err(Record::Error { code, message }) => {
assert_eq!(code, code::BAD_REQUEST);
message
}
other => panic!("{other:?}"),
};
assert!(refused(svc()).contains("needs `create`"), "no attach-only service terminal");
assert!(refused(svc().with("create", "sh")).contains("`create` must be"));
assert!(refused(svc().with("create", Obj::new()).with("session", SESSION)).contains("one of"));
let ls = Obj::new().with("argv", vec!["ls".to_string()]);
assert!(refused(svc().with("create", Obj::new()).with("pipe", ls)).contains("one of"));
assert!(refused(pipe_base("/f").with("service", "").with("create", Obj::new())).contains("needs `service`"));
assert!(refused(svc().with("create", Obj::new().with("argv", "sh"))).contains("`create.argv`"));
}
#[test]
fn exits_encode_a_code_or_a_signal() {
use std::os::unix::process::ExitStatusExt;
assert_eq!(exit_record(ExitStatus::from_raw(3 << 8)), Record::Exit(Exit::Code(3)));
assert_eq!(exit_record(ExitStatus::from_raw(0)), Record::Exit(Exit::Code(0)));
assert_eq!(exit_record(ExitStatus::from_raw(9)), Record::Exit(Exit::Signal(9)));
let rec = exit_record(ExitStatus::from_raw(15));
assert_eq!(rpc::read_record(&mut &rec.encode()[..]).unwrap(), Some(rec), "as rpc carries it");
}
fn state_with(base: &Path, root: &Path) -> State {
let inst = |name: &str, dir: &Path, helper: bool| {
format!(
"[instance.{name}]\ninstance_id = \"id-{name}\"\nsandbox = \"web\"\ncontainer = \"devsandbox-{name}\"\n\
folder = \"/w\"\nworkspace = \"/workspaces/{name}\"\ncreated_unix = 1\nconfig_dir = {:?}\n{}",
dir.to_str().unwrap(),
if helper { "devsbd_arch = \"x86_64\"\n" } else { "" }
)
};
let text = inst("web-1", &root.join("cfg"), true) + &inst("bare", &root.join("cfg"), false) + &inst("own", &base.join("mine"), true);
let path = base.join("state.toml");
std::fs::write(&path, text).unwrap();
State::load_at(&path).unwrap()
}
fn code_of(r: Result<impl std::fmt::Debug, Record>) -> String {
match r {
Err(Record::Error { code, .. }) => code,
other => panic!("{other:?}"),
}
}
#[test]
fn the_gate_takes_lent_instances_with_a_helper() {
let b = scratch("gate");
let root = b.join("fleet/control_plane");
std::fs::create_dir_all(root.join("cfg")).unwrap();
std::fs::create_dir_all(root.join("other")).unwrap();
std::fs::create_dir_all(b.join("mine")).unwrap();
let state = state_with(&b, &root);
let cfg = root.join("cfg");
let h = |root: &Path, instance: &str| Header { root: root.to_path_buf(), instance: instance.into(), mode: session(None) };
let reach = |own: &[PathBuf]| Reach { trust: crate::worker_policy::Trust::Worker, fleet_root: Some(root.clone()), own: own.iter().cloned().collect() };
let mine = b.join("mine");
std::fs::create_dir_all(mine.join("nested")).unwrap();
let with_own = reach(&[mine.clone()]);
assert_eq!(gate(&h(&mine, "own"), &state, &with_own).unwrap().0, "own", "an own root's");
assert_eq!(gate(&h(&mine, "id-own"), &state, &with_own).unwrap().0, "own", "by id");
assert_eq!(code_of(gate(&h(&mine.join("nested"), "own"), &state, &with_own)), code::DENIED, "not what's nested in it");
assert_eq!(code_of(gate(&h(&cfg, "own"), &state, &with_own)), code::NOT_FOUND, "not another root's");
let full = Reach { trust: crate::worker_policy::Trust::Full, ..reach(&[]) };
assert_eq!(gate(&h(&mine, "own"), &state, &full).unwrap().0, "own", "`full`: any root");
let r = reach(&[]);
let (name, i) = gate(&h(&cfg, "web-1"), &state, &r).unwrap();
assert_eq!((name, i.container.as_str()), ("web-1", "devsandbox-web-1"));
assert_eq!(gate(&h(&cfg, "id-web-1"), &state, &r).unwrap().0, "web-1", "by id");
assert_eq!(gate(&h(&root, "web-1"), &state, &r).unwrap().0, "web-1", "the fleet root holds it too");
assert_eq!(code_of(gate(&h(&cfg, "web"), &state, &r)), code::NOT_FOUND, "exact names only");
assert_eq!(code_of(gate(&h(&cfg, "own"), &state, &r)), code::NOT_FOUND, "not lent");
assert_eq!(code_of(gate(&h(&root.join("other"), "web-1"), &state, &r)), code::NOT_FOUND, "another root's");
assert_eq!(code_of(gate(&h(&b.join("mine"), "own"), &state, &r)), code::DENIED, "outside the fleet root");
assert_eq!(code_of(gate(&h(&root.join("gone"), "web-1"), &state, &r)), code::NOT_FOUND);
assert_eq!(code_of(gate(&h(Path::new("rel"), "web-1"), &state, &r)), code::BAD_REQUEST);
assert_eq!(gate(&h(&cfg, "bare"), &state, &r).unwrap().0, "bare", "no helper: `decide`'s to say");
let pipe = |instance: &str| Header { mode: Mode::Pipe { argv: vec!["ls".into()], interactive: false }, ..h(&cfg, instance) };
assert_eq!(gate(&pipe("bare"), &state, &r).unwrap().0, "bare", "a pipe needs no helper");
assert_eq!(code_of(gate(&pipe("own"), &state, &r)), code::NOT_FOUND, "but the same reach");
let _ = std::fs::remove_dir_all(&b);
}
#[test]
fn a_helper_that_cant_attach_runs_its_session_client() {
assert_eq!(decide(true, Some(Ok(true)), "w"), Ok(Terminal::Attach));
assert_eq!(decide(false, Some(Ok(true)), "w"), Ok(Terminal::Attach), "an attach is the helper's");
for create in [true, false] {
assert_eq!(decide(create, Some(Ok(false)), "w"), Ok(Terminal::Client));
assert_eq!(decide(create, Some(Err(CallError::Unsupported("c".into()))), "w"), Ok(Terminal::Client), "an older helper");
}
assert_eq!(decide(true, None, "w"), Ok(Terminal::Tty));
let Err(Record::Error { code, message }) = decide(false, None, "w") else { panic!() };
assert_eq!(code, rpc::code::NO_SESSION);
assert!(message.contains("aren't resumable (no helper)"), "{message}");
assert_eq!(code_of(decide(true, Some(Err(CallError::NoBridge("c".into()))), "w")), code::NOT_RUNNING);
assert_eq!(code_of(decide(true, Some(Err(CallError::Io(std::io::Error::other("x")))), "w")), code::FAILED);
}
#[test]
fn session_client_ends_read_as_an_attachs() {
use std::os::unix::process::ExitStatusExt;
let of = |raw| client_exit_record(&portable_pty::ExitStatus::from(ExitStatus::from_raw(raw)));
assert_eq!(of(250 << 8), Record::error(rpc::code::NO_SESSION, ""));
assert_eq!(of(251 << 8), Record::error(rpc::code::DETACHED, ""));
assert_eq!(of(252 << 8), Record::error(rpc::code::VERSION, ""));
assert_eq!(of(0), Record::Exit(Exit::Code(0)));
assert_eq!(of(3 << 8), Record::Exit(Exit::Code(3)));
assert_eq!(of(253 << 8), Record::Exit(Exit::Code(253)));
assert_eq!(of(9), Record::Exit(Exit::Signal(9)), "a signal stays one");
}
#[test]
fn tty_exits_keep_the_signal_number() {
use std::os::unix::process::ExitStatusExt;
let of = |raw| tty_exit_record(&portable_pty::ExitStatus::from(ExitStatus::from_raw(raw)));
assert_eq!(of(3 << 8), Record::Exit(Exit::Code(3)));
assert_eq!(of(9), Record::Exit(Exit::Signal(9)));
assert_eq!(of(1), Record::Exit(Exit::Signal(1)));
assert_eq!(tty_exit_record(&portable_pty::ExitStatus::with_signal("Signal 50")), Record::Exit(Exit::Signal(50)));
}
#[test]
fn the_exec_argv_is_a_local_execs() {
let b = scratch("argv");
let root = b.join("fleet/control_plane");
std::fs::create_dir_all(root.join("cfg")).unwrap();
let state = state_with(&b, &root);
let bin = crate::runtime::backend().bin().to_string();
let argv = vec!["ls".to_string()];
let inst = &state.instances["web-1"];
let tty = runtime_exec(&Target::Instance { instance: inst, interactive: true, tty: true, argv: &argv, host_agent: false });
assert_eq!(tty[0], bin);
assert_eq!(tty[1..], exec_argv_with(inst, true, true, &argv, false));
let svc = runtime_exec(&Target::Service { container: "devsandbox-svc-p-db", argv: &argv });
assert_eq!(svc, [bin.as_str(), "exec", "-i", "-t", "devsandbox-svc-p-db", "ls"]);
assert_eq!(or_shell(&[]), SHELL_FALLBACK_CMD);
let client = |create: Option<&[String]>| {
runtime_exec(&Target::Instance { instance: inst, interactive: true, tty: true, argv: &client_command(SESSION, create), host_agent: false })
};
let shell: Vec<String> = SHELL_FALLBACK_CMD.iter().map(|s| s.to_string()).collect();
assert_eq!(client(Some(&[]))[1..], exec_argv_with(inst, true, true, &session_new_command(SESSION, &shell), false), "the login shell");
assert_eq!(client(Some(&argv))[1..], exec_argv_with(inst, true, true, &session_new_command(SESSION, &argv), false));
assert_eq!(client(None)[1..], exec_argv_with(inst, true, true, &session_attach_command(SESSION), false), "attach only");
let _ = std::fs::remove_dir_all(&b);
}
#[test]
fn create_runs_as_an_exec_would() {
let b = scratch("params");
let root = b.join("fleet/control_plane");
std::fs::create_dir_all(root.join("cfg")).unwrap();
let state = state_with(&b, &root);
let mut inst = state.instances["web-1"].clone();
assert_eq!(attach_params(SESSION, None, &inst, false), Obj::new().with("id", SESSION), "attach only");
inst.remote_user = Some("vscode".into());
inst.remote_env = BTreeMap::from([("A".into(), "1".into()), ("SSH_AUTH_SOCK".into(), "/mine".into())]);
inst.ssh_auth_sock = Some("/ssh-agent".into());
let p = attach_params(SESSION, Some(&[]), &inst, false);
let c = p.obj("create").unwrap();
let shell: Vec<String> = SHELL_FALLBACK_CMD.iter().map(|s| s.to_string()).collect();
assert_eq!(c.strs("argv"), Some(shell.as_slice()), "empty argv: the login shell");
assert_eq!(c.str("cwd"), Some("/workspaces/web-1"));
assert_eq!(c.str("user"), Some("vscode"));
assert_eq!(c.map("env").unwrap(), [("A".to_string(), "1".to_string()), ("SSH_AUTH_SOCK".into(), "/ssh-agent".into())], "one each, the agent's last");
let rec = Record::Call(RpcCall { method: METHOD.into(), params: p, meta: Obj::new() });
assert_eq!(rpc::read_record(&mut &rec.encode()[..]).unwrap(), Some(rec));
inst.remote_user = None;
let c = attach_params(SESSION, Some(&["htop".to_string()]), &inst, false).obj("create").unwrap().clone();
assert_eq!((c.strs("argv"), c.str("user")), (Some(&["htop".to_string()][..]), None), "no user: the container's");
let _ = std::fs::remove_dir_all(&b);
}
fn sessions(s: UnixStream) {
let mut r = &s;
let Ok(Some(Record::Call(call))) = rpc::read_record(&mut r) else { return };
let mut w = &s;
let mut send = |rec: Record| rpc::write_record(&mut w, &rec);
match call.method.as_str() {
"rpc.methods" => {
let _ = send(Record::Result(Obj::new().with("methods", vec!["session.attach@1".to_string()])));
}
"session.attach" => {
let id = call.params.str("id").unwrap_or_default().to_string();
let cwd = call.params.obj("create").and_then(|c| c.str("cwd")).unwrap_or("-").to_string();
let _ = send(Record::Stdout(format!("{id} {cwd}\n").into_bytes()));
if id == "1700000000-0105" {
let _ = s.shutdown(Shutdown::Both);
return;
}
loop {
let rec = match rpc::read_record(&mut r) {
Ok(Some(Record::Stdin(b))) => Record::Stdout(b),
Ok(Some(Record::Resize { cols, rows })) => Record::Stdout(format!("{cols}x{rows}").into_bytes()),
Ok(Some(Record::StdinEof)) => Record::Exit(Exit::Code(7)),
Ok(Some(_)) => continue,
_ => return,
};
let last = matches!(rec, Record::Exit(_));
let _ = send(rec);
if last {
break;
}
}
}
m => {
let _ = send(Record::error(rpc::code::UNKNOWN_METHOD, format!("no method `{m}`")));
}
}
let _ = s.shutdown(Shutdown::Write);
let _ = std::io::copy(&mut r, &mut std::io::sink());
}
fn not_root(s: UnixStream) {
let mut r = &s;
let Ok(Some(Record::Call(_))) = rpc::read_record(&mut r) else { return };
let _ = rpc::write_record(&mut &s, &Record::Result(Obj::new().with("methods", vec!["rpc.methods@1".to_string()])));
}
struct World {
base: PathBuf,
root: PathBuf,
state: PathBuf,
helper: HelperClient,
attaches: Attaches,
}
impl Drop for World {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.base);
}
}
const CONFIG: &str = "[services.db]\nimage = \"postgres\"\nscope = \"isolated\"\n\n\
[services.cache]\nimage = \"redis\"\nscope = \"global\"\n\n\
[sandbox.web]\nimage = \"node\"\nservices = [\"db\"]\n";
fn world(tag: &str) -> World {
let base = scratch(tag);
let root = base.join("fleet/control_plane");
std::fs::create_dir_all(root.join("cfg")).unwrap();
std::fs::write(root.join("cfg").join(crate::config::CONFIG_FILE), CONFIG).unwrap();
state_with(&base, &root);
let fake = Fake::default();
fake.add("devsandbox-web-1", caps::RPC, 1, sessions);
let helper = HelperClient::new(fake.clone(), log);
World { state: base.join("state.toml"), base, root, helper, attaches: Attaches::default() }
}
fn open(w: &World, header: Record, helper: HelperClient) -> (UnixStream, std::thread::JoinHandle<()>) {
let (control_plane, ours) = UnixStream::pair().unwrap();
let peer = Peer { name: "me@control_plane".into(), fleet_root: Some(w.root.clone()), env: None, agent: None, key: None, introduced_by: None };
let files = Files { state: w.state.clone(), member: None, home: None };
let attaches = w.attaches.clone();
let t = std::thread::spawn(move || serve(ours, &helper, &files, &peer, &attaches, || false, sh, log));
rpc::write_record(&mut &control_plane, &header).unwrap();
control_plane.set_read_timeout(Some(Duration::from_secs(10))).unwrap();
(control_plane, t)
}
fn rest(mut control_plane: &UnixStream) -> Vec<Record> {
let mut recs = Vec::new();
while let Ok(Some(rec)) = rpc::read_record(&mut control_plane) {
recs.push(rec);
}
recs
}
fn create_header(w: &World, session: &str) -> Record {
let cfg = w.root.join("cfg");
header(base(cfg.to_str().unwrap()).with("session", session).with("create", Obj::new()))
}
#[test]
fn a_stream_relays_input_and_output_to_the_end_record() {
let w = world("relay");
let (control_plane, t) = open(&w, create_header(&w, SESSION), w.helper.clone());
let mut out = &control_plane;
rpc::write_record(&mut out, &Record::Stdin(b"ls\n".to_vec())).unwrap();
rpc::write_record(&mut out, &Record::Resize { cols: 120, rows: 40 }).unwrap();
rpc::write_record(&mut out, &Record::Signal(2)).unwrap();
rpc::write_record(&mut out, &Record::StdinEof).unwrap();
let recs = rest(&control_plane);
t.join().unwrap();
let stdout = |s: &str| Record::Stdout(s.as_bytes().to_vec());
assert_eq!(
recs,
[stdout(&format!("{SESSION} /workspaces/web-1\n")), stdout("ls\n"), stdout("120x40"), Record::Exit(Exit::Code(7))],
"the helper's records, unchanged, then nothing"
);
}
fn attached(w: &World, id: &str) -> Option<Origin> {
w.attaches.latest(id, std::time::Instant::now())
}
#[test]
fn a_stream_is_its_instances_latest_attach_from_its_origin() {
let w = world("attach");
assert_eq!(attached(&w, "id-web-1"), None);
let (control_plane, t) = open(&w, create_header(&w, SESSION), w.helper.clone());
assert!(matches!(rpc::read_record(&mut &control_plane), Ok(Some(Record::Stdout(_)))), "attached");
assert_eq!(attached(&w, "id-web-1"), Some(Origin::Member("me@control_plane".into())), "during the stream");
assert!(w.attaches.live_in("id-web-1"));
let here = w.attaches.begin_in("id-web-1", Origin::Here);
rpc::write_record(&mut &control_plane, &Record::StdinEof).unwrap();
rest(&control_plane);
t.join().unwrap();
assert_eq!(attached(&w, "id-web-1"), Some(Origin::Here));
drop(here);
let (control_plane, t) = open(&w, pipe_header(&w, "bare", "exit 0", false), w.helper.clone());
rest(&control_plane);
t.join().unwrap();
assert_eq!(attached(&w, "id-bare"), None, "a pipe: no attach");
let cfg = w.root.join("cfg");
let create = Obj::new().with("argv", vec!["exit 0".to_string()]);
let h = header(pipe_base(cfg.to_str().unwrap()).with("service", "db").with("create", create));
let _ = w.attaches.begin_in("id-web-1", Origin::Here);
let (control_plane, t) = open(&w, h, w.helper.clone());
rest(&control_plane);
t.join().unwrap();
assert_eq!(attached(&w, "id-web-1"), Some(Origin::Member("me@control_plane".into())), "a service terminal: its instance's");
let (control_plane, t) = open(&w, header(base(cfg.to_str().unwrap()).with("instance", "own")), w.helper.clone());
rest(&control_plane);
t.join().unwrap();
assert_eq!(attached(&w, "id-own"), None, "refused: no attach");
}
#[test]
fn a_lost_bridge_ends_with_lost_and_a_hang_up_cancels() {
let w = world("lost");
let (control_plane, t) = open(&w, create_header(&w, "1700000000-0105"), w.helper.clone());
let recs = rest(&control_plane);
t.join().unwrap();
assert_eq!(recs.len(), 2, "{recs:?}");
assert!(matches!(&recs[1], Record::Error { code, .. } if code == code::LOST), "{recs:?}");
let (control_plane, t) = open(&w, create_header(&w, "1700000000-0106"), w.helper.clone());
assert!(matches!(rpc::read_record(&mut &control_plane), Ok(Some(Record::Stdout(_)))));
drop(control_plane);
t.join().unwrap();
assert!(logged("helper devsandbox-web-1: session.attach from fleet control plane me@control_plane: cancelled ("));
}
fn sh(t: &Target) -> Vec<String> {
let script = match t {
Target::Instance { argv, .. } if argv[0] == crate::devsbd::BIN => match &argv[1..] {
[_, new, _, id, _, command, ..] if new == "new" => format!("echo new {id}; {command}"),
[_, attach, id] if attach == "attach" => format!("echo attach {id}; exit {DETACHED_EXIT}"),
other => panic!("{other:?}"),
},
Target::Instance { argv, .. } => argv[0].clone(),
Target::Service { container, argv } => format!("echo {container}; {}", argv[0]),
};
vec!["sh".into(), "-c".into(), script]
}
fn pipe_header(w: &World, instance: &str, script: &str, interactive: bool) -> Record {
let cfg = w.root.join("cfg");
let pipe = Obj::new().with("argv", vec![script.to_string()]).with("interactive", interactive);
header(Obj::new().with("root", cfg.to_str().unwrap()).with("instance", instance).with("pipe", pipe))
}
fn split(recs: &[Record]) -> (String, String, Option<Record>) {
let (mut out, mut err) = (Vec::new(), Vec::new());
for rec in recs {
match rec {
Record::Stdout(b) => out.extend_from_slice(b),
Record::Stderr(b) => err.extend_from_slice(b),
_ => {}
}
}
(String::from_utf8(out).unwrap(), String::from_utf8(err).unwrap(), recs.last().cloned())
}
#[test]
fn a_pipe_splits_its_outputs_and_ends_with_its_exit() {
let w = world("pipe-out");
let (control_plane, t) = open(&w, pipe_header(&w, "bare", "echo out; echo err >&2; cat; exit 5", false), w.helper.clone());
let _ = rpc::write_record(&mut &control_plane, &Record::Stdin(b"ignored\n".to_vec()));
let recs = rest(&control_plane);
t.join().unwrap();
assert_eq!(split(&recs), ("out\n".into(), "err\n".into(), Some(Record::Exit(Exit::Code(5)))), "not interactive: empty stdin");
assert_eq!(recs.iter().filter(|r| matches!(r, Record::Exit(_))).count(), 1);
let (control_plane, t) = open(&w, pipe_header(&w, "web-1", "kill -9 $$", false), w.helper.clone());
let recs = rest(&control_plane);
t.join().unwrap();
assert_eq!(recs, [Record::Exit(Exit::Signal(9))]);
}
#[test]
fn a_pipe_forwards_stdin_to_its_eof() {
let w = world("pipe-in");
let (control_plane, t) = open(&w, pipe_header(&w, "web-1", "cat; echo done", true), w.helper.clone());
rpc::write_record(&mut &control_plane, &Record::Stdin(b"abc".to_vec())).unwrap();
rpc::write_record(&mut &control_plane, &Record::Resize { cols: 80, rows: 24 }).unwrap();
rpc::write_record(&mut &control_plane, &Record::Stdin(b"def\n".to_vec())).unwrap();
rpc::write_record(&mut &control_plane, &Record::StdinEof).unwrap();
let recs = rest(&control_plane);
t.join().unwrap();
assert_eq!(split(&recs), ("abcdef\ndone\n".into(), String::new(), Some(Record::Exit(Exit::Code(0)))));
}
#[test]
fn a_hang_up_kills_the_pipe() {
let w = world("pipe-hup");
let (control_plane, t) = open(&w, pipe_header(&w, "web-1", "echo $$; exec sleep 30", true), w.helper.clone());
let Ok(Some(Record::Stdout(pid))) = rpc::read_record(&mut &control_plane) else { panic!("no pid") };
let pid = String::from_utf8(pid).unwrap();
let pid: libc::pid_t = pid.trim().parse().unwrap_or_else(|_| panic!("{pid:?}"));
let started = std::time::Instant::now();
drop(control_plane);
t.join().unwrap();
assert!(started.elapsed() < Duration::from_secs(10), "killed, not waited out");
assert_eq!(unsafe { libc::kill(pid, 0) }, -1, "killed and reaped");
}
#[test]
fn refusals_are_one_error_record() {
let w = world("refuse");
let refusal = |header: Record, helper: HelperClient| {
let (control_plane, t) = open(&w, header, helper);
let recs = rest(&control_plane);
t.join().unwrap();
match recs.as_slice() {
[Record::Error { code, .. }] => code.clone(),
other => panic!("{other:?}"),
}
};
let cfg = w.root.join("cfg");
let cfg = cfg.to_str().unwrap();
assert_eq!(refusal(Record::StdinEof, w.helper.clone()), code::BAD_REQUEST);
assert_eq!(refusal(header(base(cfg).with("instance", "own")), w.helper.clone()), code::NOT_FOUND);
let other = w.base.join("other");
std::fs::create_dir_all(&other).unwrap();
assert_eq!(refusal(header(base(other.to_str().unwrap()).with("instance", "own")), w.helper.clone()), code::DENIED);
assert!(logged("fleet: refused a PTY stream from me@control_plane"));
let mine = w.base.join("mine");
std::fs::create_dir_all(&mine).unwrap();
assert_eq!(refusal(header(base(mine.to_str().unwrap()).with("instance", "own")), w.helper.clone()), code::NOT_RUNNING);
assert_eq!(refusal(header(base(cfg).with("instance", "bare")), w.helper.clone()), rpc::code::NO_SESSION);
let none = HelperClient::new(Fake::default(), log);
assert_eq!(refusal(header(base(cfg)), none), code::NOT_RUNNING);
let svc = |service: &str| header(pipe_base(cfg).with("service", service).with("create", Obj::new()));
assert_eq!(refusal(svc("cache"), w.helper.clone()), code::NOT_FOUND, "not one `web-1` uses");
assert_eq!(refusal(svc("nope"), w.helper.clone()), code::NOT_FOUND);
let own = header(base(cfg).with("instance", "own").with("session", Json::Null).with("service", "db").with("create", Obj::new()));
assert_eq!(refusal(own, w.helper.clone()), code::NOT_FOUND, "the instance gates the service");
}
fn tty_header(w: &World, instance: &str, script: &str) -> Record {
let cfg = w.root.join("cfg");
let create = Obj::new().with("argv", vec![script.to_string()]);
header(base(cfg.to_str().unwrap()).with("instance", instance).with("create", create))
}
#[test]
fn a_helperless_instance_gets_a_tty_that_says_it_isnt_resumable() {
let w = world("tty");
let (control_plane, t) = open(&w, tty_header(&w, "bare", "read x; stty size; echo got $x; exit 3"), w.helper.clone());
rpc::write_record(&mut &control_plane, &Record::Resize { cols: 100, rows: 30 }).unwrap();
rpc::write_record(&mut &control_plane, &Record::Stdin(b"hi\n".to_vec())).unwrap();
let recs = rest(&control_plane);
t.join().unwrap();
assert_eq!(recs[0], Record::Stderr(TTY_NOTE.as_bytes().to_vec()), "the note first: {recs:?}");
let (out, err, last) = split(&recs);
assert_eq!(err, TTY_NOTE, "only the note");
assert!(out.contains("30 100"), "the resize reached the pty: {out:?}");
assert!(out.contains("got hi"), "{out:?}");
assert_eq!(last, Some(Record::Exit(Exit::Code(3))));
let (control_plane, t) = open(&w, tty_header(&w, "bare", "kill -9 $$"), w.helper.clone());
let recs = rest(&control_plane);
t.join().unwrap();
assert_eq!(recs.last(), Some(&Record::Exit(Exit::Signal(9))));
}
#[test]
fn a_non_root_helper_runs_its_session_client() {
let w = world("tty-root");
let not_root = || {
let fake = Fake::default();
fake.add("devsandbox-web-1", caps::RPC, 1, not_root);
HelperClient::new(fake, log)
};
let run = |header: Record| {
let (control_plane, t) = open(&w, header, not_root());
let recs = rest(&control_plane);
t.join().unwrap();
split(&recs)
};
let (out, err, last) = run(tty_header(&w, "web-1", "echo ok"));
assert!(out.contains(&format!("new {SESSION}")) && out.contains("ok"), "{out:?}");
assert_eq!((err.as_str(), last), ("", Some(Record::Exit(Exit::Code(0)))), "no note: it is a session");
let (_, _, last) = run(tty_header(&w, "web-1", &format!("exit {VERSION_EXIT}")));
assert_eq!(last, Some(Record::error(rpc::code::VERSION, "")));
let (out, _, last) = run(header(base(w.root.join("cfg").to_str().unwrap())));
assert!(out.contains(&format!("attach {SESSION}")), "{out:?}");
assert_eq!(last, Some(Record::error(rpc::code::DETACHED, "")));
}
#[test]
fn a_hang_up_kills_the_tty() {
let w = world("tty-hup");
let typed = w.base.join("typed");
let script = format!("trap '' HUP; echo $$; read x; touch {}; exec sleep 30", typed.display());
let (control_plane, t) = open(&w, tty_header(&w, "bare", &script), w.helper.clone());
let mut out = String::new();
let pid: libc::pid_t = loop {
match rpc::read_record(&mut &control_plane) {
Ok(Some(Record::Stdout(b))) => out.push_str(&String::from_utf8_lossy(&b)),
Ok(Some(Record::Stderr(_))) => {}
other => panic!("{other:?} after {out:?}"),
}
if let Some(line) = out.lines().next().filter(|_| out.contains('\n')) {
break line.trim().parse().unwrap_or_else(|_| panic!("{out:?}"));
}
};
let started = std::time::Instant::now();
drop(control_plane);
t.join().unwrap();
assert!(started.elapsed() < Duration::from_secs(10), "killed, not waited out");
assert_eq!(unsafe { libc::kill(pid, 0) }, -1, "killed and reaped");
assert!(!typed.exists(), "nothing typed into the pty on the hang-up");
}
#[test]
fn a_service_terminal_runs_in_the_container_the_worker_names() {
let w = world("svc");
let cfg = w.root.join("cfg");
let create = Obj::new().with("argv", vec!["exit 4".to_string()]);
let h = header(pipe_base(cfg.to_str().unwrap()).with("service", "db").with("create", create));
let (control_plane, t) = open(&w, h, w.helper.clone());
let recs = rest(&control_plane);
t.join().unwrap();
let (out, err, last) = split(&recs);
let project = crate::commands::services::project_id(&cfg).unwrap();
let container = crate::commands::services::isolated_service_container(&project, "id-web-1", "db");
assert!(out.contains(&container), "{out:?}");
assert_eq!(err, "", "no note: a service terminal was never a session");
assert_eq!(last, Some(Record::Exit(Exit::Code(4))));
}
#[test_utils::docker_test(helper)]
fn a_session_client_outlives_its_callers_hang_up_with_docker() -> Result<(), &'static str> {
let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
let name = format!("devsandbox-pty-client-test-{stamp}");
let up = crate::test_support::runtime_cmd()
.args(["run", "-d", "--rm", "--name", &name, "alpine:3.20", "sleep", "300"])
.output()
.unwrap();
assert!(up.status.success(), "{}", String::from_utf8_lossy(&up.stderr));
let cleanup = || {
let _ = crate::test_support::runtime_cmd().args(["rm", "-f", &name]).output();
};
crate::test_support::with_cleanup(cleanup, || {
crate::devsbd::install(&name, None).unwrap();
let base = scratch("client-docker");
let text = format!(
"[instance.c]\ninstance_id = \"id-c\"\nsandbox = \"c\"\ncontainer = {name:?}\nfolder = \"/w\"\n\
workspace = \"/\"\ncreated_unix = 1\nremote_user = \"nobody\"\ndevsbd_arch = \"x86_64\"\n"
);
std::fs::write(base.join("state.toml"), text).unwrap();
let state = State::load_at(&base.join("state.toml")).unwrap();
let inst = state.instances["c"].clone();
const ID: &str = "1700000000-c11e";
let open = |create: Option<&[String]>| {
let argv = client_command(ID, create);
let argv = runtime_exec(&Target::Instance { instance: &inst, interactive: true, tty: true, argv: &argv, host_agent: false });
let tty = spawn_tty(argv).unwrap();
let (control_plane, ours) = UnixStream::pair().unwrap();
let t = std::thread::spawn(move || run_tty(&ours, tty, None, client_exit_record));
control_plane.set_read_timeout(Some(Duration::from_secs(30))).unwrap();
(control_plane, t)
};
let until = |mut s: &UnixStream, needle: &str| {
let mut out = String::new();
while !out.contains(needle) {
match rpc::read_record(&mut s) {
Ok(Some(Record::Stdout(b))) => out.push_str(&String::from_utf8_lossy(&b)),
other => panic!("{other:?} before {needle:?}, after {out:?}"),
}
}
out
};
let say = |s: &UnixStream, text: &str| rpc::write_record(&mut &*s, &Record::Stdin(text.as_bytes().to_vec())).unwrap();
let program = vec!["sh".to_string(), "-c".into(), "while read l; do echo \"got $l $$.\"; done".into()];
let (first, t) = open(Some(&program));
say(&first, "zero\n");
let out = until(&first, ".\r\n");
let pid = out.split("got zero ").nth(1).and_then(|r| r.split('.').next()).unwrap_or_else(|| panic!("{out:?}")).to_string();
let started = std::time::Instant::now();
drop(first);
t.join().unwrap();
assert!(started.elapsed() < Duration::from_secs(10), "the runtime's exec client killed, not waited out");
let (a, ta) = open(None);
say(&a, "one\n");
until(&a, &format!("got one {pid}."));
let (b, tb) = open(None);
let rest_a = rest(&a);
ta.join().unwrap();
let (out, _, last) = split(&rest_a);
assert_eq!(last, Some(Record::error(rpc::code::DETACHED, "")), "{rest_a:?}");
assert!(out.contains("attached elsewhere"), "the client's own note, as output: {out:?}");
say(&b, "two\n");
until(&b, &format!("got two {pid}."));
say(&b, "\x04");
let rest_b = rest(&b);
tb.join().unwrap();
assert_eq!(rest_b.last(), Some(&Record::Exit(Exit::Code(0))), "{rest_b:?}");
let _ = std::fs::remove_dir_all(&base);
});
Ok(())
}
}