use std::io::IsTerminal;
use anyhow::Result;
use super::resolve_instance;
use crate::runtime::backend;
use crate::state::{Instance, State};
pub const SHELL_FALLBACK_CMD: [&str; 3] = [
"sh",
"-lc",
"command -v zsh >/dev/null 2>&1 && exec zsh -l; command -v bash >/dev/null 2>&1 && exec bash -l; exec sh -l",
];
pub fn exec(name: &str, interactive: bool, tty: bool, command: &[String]) -> Result<()> {
std::process::exit(exec_status(name, interactive, tty, command)?);
}
pub fn exec_status(name: &str, interactive: bool, tty: bool, command: &[String]) -> Result<i32> {
let state = State::load()?;
let key = resolve_instance(&state, name)?;
let instance = state.instances.get(&key).expect("key came from state");
let shell: Vec<String>;
let (command, interactive, tty) = if command.is_empty() {
shell = SHELL_FALLBACK_CMD.iter().map(|s| s.to_string()).collect();
let (i, t) = shell_flags(interactive, tty, std::io::stdin().is_terminal());
(shell.as_slice(), i, t)
} else {
(command, interactive, tty)
};
let host_agent = crate::devsbd::relay_mode(instance) && has_host_agent();
#[cfg(unix)]
let relay = host_agent.then(|| AgentRelay::start(&key));
let args = exec_argv_with(instance, interactive, tty, command, host_agent);
let arg_refs: Vec<&str> = args.iter().map(String::as_str).collect();
let code = backend().run_inherit(&arg_refs)?;
#[cfg(unix)]
if let Some(relay) = relay {
relay.finish(&instance.container);
}
Ok(code)
}
#[cfg(unix)]
pub(crate) struct AgentRelay(std::thread::JoinHandle<Result<crate::serve::client::Conn>>);
#[cfg(unix)]
const LIFECYCLE_RELAY_WAIT: std::time::Duration = std::time::Duration::from_secs(12);
#[cfg(unix)]
fn relay_note(ready: Option<crate::devsbd::bridge::Readiness>) -> Option<String> {
match ready {
None => None,
Some(r) if r.ready => None,
Some(r) => Some(r.error.unwrap_or_else(|| "the bridge isn't ready".into())),
}
}
#[cfg(unix)]
impl AgentRelay {
pub(crate) fn start(key: &str) -> AgentRelay {
let key = key.to_string();
AgentRelay(std::thread::spawn(move || {
let agent = crate::devsbd::bridge::own_agent();
crate::serve::client::ensure_bridge(&key, agent.as_deref(), None).map(|(conn, _)| conn)
}))
}
pub(crate) fn ready(key: &str, container: &str) -> Option<crate::serve::client::Conn> {
let agent = crate::devsbd::bridge::own_agent();
let (conn, note) = Self::wait(key, agent.as_deref());
if let Some(why) = note {
eprintln!("note: ssh-agent relay unavailable in `{container}`: {why}");
}
conn
}
pub(crate) fn wait(
key: &str,
agent: Option<&std::path::Path>,
) -> (Option<crate::serve::client::Conn>, Option<String>) {
match crate::serve::client::ensure_bridge(key, agent, Some(LIFECYCLE_RELAY_WAIT)) {
Ok((conn, ready)) => (Some(conn), relay_note(ready)),
Err(e) => (None, Some(format!("{e:#}"))),
}
}
pub(crate) fn finish(self, container: &str) {
let result = self.0.join().unwrap_or_else(|_| Err(anyhow::anyhow!("the request panicked")));
if let Err(e) = result {
eprintln!("note: ssh-agent relay unavailable in `{container}`: {e:#}");
}
}
}
fn shell_flags(interactive: bool, tty: bool, stdin_tty: bool) -> (bool, bool) {
if interactive || tty {
(interactive, tty)
} else {
(true, stdin_tty)
}
}
pub fn exec_argv(
instance: &Instance,
interactive: bool,
tty: bool,
command: &[String],
) -> Vec<String> {
let host_agent = crate::devsbd::relay_mode(instance) && has_host_agent();
exec_argv_with(instance, interactive, tty, command, host_agent)
}
#[cfg(unix)]
pub(crate) fn has_host_agent() -> bool {
crate::devsbd::bridge::has_host_agent()
}
#[cfg(not(unix))]
pub(crate) fn has_host_agent() -> bool {
false
}
pub(crate) fn ssh_auth_sock_env(instance: &Instance, host_agent: bool) -> Option<&str> {
match &instance.ssh_auth_sock {
Some(sock) => Some(sock.as_str()),
None if crate::devsbd::relay_mode(instance) && host_agent => {
Some(crate::commands::run::SSH_AGENT_TARGET)
}
None => None,
}
}
pub(crate) fn exec_argv_with(
instance: &Instance,
interactive: bool,
tty: bool,
command: &[String],
host_agent: bool,
) -> Vec<String> {
let mut args: Vec<String> = vec!["exec".into()];
if interactive {
args.push("-i".into());
}
if tty {
args.push("-t".into());
}
args.extend(["-w".into(), instance.workspace.clone()]);
if let Some(user) = &instance.remote_user {
args.push("-u".into());
args.push(user.clone());
}
for (key, value) in &instance.exec_env() {
args.push("-e".into());
args.push(format!("{key}={value}"));
}
if let Some(sock) = ssh_auth_sock_env(instance, host_agent) {
args.push("-e".into());
args.push(format!("SSH_AUTH_SOCK={sock}"));
}
args.push(instance.container.clone());
args.extend(command.iter().cloned());
args
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::BTreeMap;
use std::path::PathBuf;
fn instance() -> Instance {
Instance {
sandbox: "repository-1".into(),
instance_id: "repo-abc1".into(),
project: "abc12345".into(),
container: "devsandbox-repo-abc1".into(),
folder: PathBuf::from("/home/u/repository-1"),
base_folder: PathBuf::from("/home/u/repository-1"),
worktree: None,
branch: None,
branch_created: true,
folders: Vec::new(),
shell_history: None,
workspace: "/workspaces/repository-1".into(),
workspace_file: None,
remote_env: BTreeMap::new(),
remote_user: None,
ssh_auth_sock: None,
devsbd_arch: None,
volumes: Vec::new(),
dispatcher: None,
config_dir: None,
extra_env: Default::default(),
forwarded_ports: Default::default(),
done: None,
created_unix: 0,
}
}
#[test]
fn argv_minimal() {
let inst = instance();
assert_eq!(
exec_argv_with(&inst, false, false, &["ls".into()], false),
vec![
"exec",
"-w",
"/workspaces/repository-1",
"devsandbox-repo-abc1",
"ls",
]
);
}
#[test]
fn argv_flag_ordering() {
let mut inst = instance();
inst.remote_user = Some("vscode".into());
inst.remote_env.insert("FOO".into(), "bar".into());
inst.remote_env.insert("BAZ".into(), "qux".into());
assert_eq!(
exec_argv_with(&inst, true, true, &["bash".into(), "-l".into()], false),
vec![
"exec",
"-i",
"-t",
"-w",
"/workspaces/repository-1",
"-u",
"vscode",
"-e",
"BAZ=qux",
"-e",
"FOO=bar",
"devsandbox-repo-abc1",
"bash",
"-l",
]
);
}
#[test]
fn argv_includes_extra_env_over_remote_env() {
let mut inst = instance();
inst.remote_env.insert("FOO".into(), "remote".into());
inst.remote_env.insert("BAZ".into(), "qux".into());
inst.extra_env.insert("FOO".into(), "extra".into());
inst.extra_env.insert("PR".into(), "42".into());
assert_eq!(
exec_argv_with(&inst, false, false, &["ls".into()], false),
vec![
"exec",
"-w",
"/workspaces/repository-1",
"-e",
"BAZ=qux",
"-e",
"FOO=extra",
"-e",
"PR=42",
"devsandbox-repo-abc1",
"ls",
]
);
}
#[test]
fn argv_ssh_auth_sock() {
let mut inst = instance();
inst.remote_env.insert("FOO".into(), "bar".into());
inst.ssh_auth_sock = Some("/run/devsandbox/ssh-agent.sock".into());
assert_eq!(
exec_argv_with(&inst, false, false, &["ls".into()], false),
vec![
"exec",
"-w",
"/workspaces/repository-1",
"-e",
"FOO=bar",
"-e",
"SSH_AUTH_SOCK=/run/devsandbox/ssh-agent.sock",
"devsandbox-repo-abc1",
"ls",
]
);
}
#[cfg(unix)]
#[test]
fn argv_relay_injects_only_with_host_agent() {
let mut inst = instance();
inst.devsbd_arch = Some(crate::devsbd::Arch::X86_64);
assert_eq!(
exec_argv_with(&inst, false, false, &["ls".into()], true),
vec![
"exec",
"-w",
"/workspaces/repository-1",
"-e",
"SSH_AUTH_SOCK=/run/devsandbox/ssh-agent.sock",
"devsandbox-repo-abc1",
"ls",
]
);
assert_eq!(
exec_argv_with(&inst, false, false, &["ls".into()], false),
vec!["exec", "-w", "/workspaces/repository-1", "devsandbox-repo-abc1", "ls"]
);
}
#[cfg(unix)]
#[test]
fn relay_note_only_for_a_relay_known_not_ready() {
use crate::devsbd::bridge::Readiness;
assert_eq!(relay_note(None), None, "older daemon: no verdict");
assert_eq!(relay_note(Some(Readiness { ready: true, error: None })), None);
let outdated = Readiness { ready: false, error: Some("helper in c is outdated".into()) };
assert_eq!(relay_note(Some(outdated)).as_deref(), Some("helper in c is outdated"));
assert_eq!(relay_note(Some(Readiness { ready: false, error: None })).as_deref(), Some("the bridge isn't ready"));
}
#[test]
fn shell_flags_default_only_without_explicit_flags() {
assert_eq!(shell_flags(false, false, true), (true, true));
assert_eq!(shell_flags(false, false, false), (true, false));
assert_eq!(shell_flags(true, false, true), (true, false));
assert_eq!(shell_flags(false, true, false), (false, true));
assert_eq!(shell_flags(true, true, false), (true, true));
}
#[test]
fn shell_fallback_cmd_probes_zsh_bash_sh() {
assert_eq!(SHELL_FALLBACK_CMD[0], "sh");
assert_eq!(SHELL_FALLBACK_CMD[1], "-lc");
let at = |s: &str| SHELL_FALLBACK_CMD[2].find(s).unwrap();
assert!(at("exec zsh -l") < at("exec bash -l"));
assert!(at("exec bash -l") < at("exec sh -l"));
}
#[test]
fn ssh_auth_sock_env_rule() {
let mut mount = instance();
mount.ssh_auth_sock = Some("/run/devsandbox/ssh-agent.sock".into());
assert_eq!(ssh_auth_sock_env(&mount, false), Some("/run/devsandbox/ssh-agent.sock"));
assert_eq!(ssh_auth_sock_env(&mount, true), Some("/run/devsandbox/ssh-agent.sock"));
let mut relay = instance();
relay.devsbd_arch = Some(crate::devsbd::Arch::X86_64);
#[cfg(unix)]
{
assert_eq!(
ssh_auth_sock_env(&relay, true),
Some(crate::commands::run::SSH_AGENT_TARGET)
);
assert_eq!(ssh_auth_sock_env(&relay, false), None);
}
#[cfg(not(unix))]
{
assert_eq!(ssh_auth_sock_env(&relay, true), None);
}
let bare = instance();
assert_eq!(ssh_auth_sock_env(&bare, true), None);
assert_eq!(ssh_auth_sock_env(&bare, false), None);
}
}