on 64e2cdb help sign in
vibebox/src/instance.rs
600 lines 21 kB history raw
1use std::{
2 env, fs,
3 io::{self, Write},
4 net::{SocketAddr, TcpStream},
5 os::unix::{fs::PermissionsExt, io::OwnedFd, net::UnixStream},
6 path::{Path, PathBuf},
7 process::{Command, Stdio},
8 sync::{
9 Arc, Mutex,
10 atomic::{AtomicBool, Ordering},
11 },
12 thread,
13 time::{Duration, Instant},
14};
16use serde::{Deserialize, Serialize};
17use std::sync::mpsc::Sender;
18use time::{OffsetDateTime, format_description::well_known::Rfc3339};
19use uuid::Uuid;
21use crate::{
22 commands,
23 session_manager::{INSTANCE_DIR_NAME, INSTANCE_FILENAME},
24 tui::AppState,
25 vm::{self, LoginAction, VmInput},
26};
28const SSH_KEY_NAME: &str = "ssh_key";
29pub(crate) const SERIAL_LOG_NAME: &str = "serial.log";
30const DEFAULT_SSH_USER: &str = "vibecoder";
31const SSH_CONNECT_RETRIES: usize = 30;
32const SSH_CONNECT_DELAY_MS: u64 = 500;
33const SSH_SETUP_SCRIPT: &str = include_str!("ssh.sh");
35#[derive(Debug, Clone, Serialize, Deserialize)]
36pub(crate) struct InstanceConfig {
37 #[serde(default)]
38 id: String,
39 #[serde(default = "default_ssh_user")]
40 ssh_user: String,
41 #[serde(default)]
42 sudo_password: String,
43 #[serde(default)]
44 last_active: Option<String>,
45 #[serde(default)]
46 pub(crate) vm_ipv4: Option<String>,
49fn default_ssh_user() -> String {
50 DEFAULT_SSH_USER.to_string()
53pub fn run_with_ssh(manager_conn: UnixStream) -> Result<(), Box<dyn std::error::Error>> {
54 let project_root = env::current_dir()?;
55 tracing::info!(root = %project_root.display(), "starting ssh session");
56 let instance_dir = ensure_instance_dir(&project_root)?;
57 tracing::debug!(instance_dir = %instance_dir.display(), "instance dir ready");
58 let (ssh_key, _ssh_pub) = ensure_ssh_keypair(&instance_dir)?;
60 let config = load_or_create_instance_config(&instance_dir)?;
61 let ssh_user = config.ssh_user.clone();
62 tracing::debug!(ssh_user = %ssh_user, "loaded instance config");
64 let _manager_conn = manager_conn;
65 tracing::debug!("waiting for vm ipv4");
66 wait_for_vm_ipv4(&instance_dir, Duration::from_secs(120))?;
68 let ip = load_or_create_instance_config(&instance_dir)?
69 .vm_ipv4
70 .ok_or("VM IPv4 not available")?;
71 tracing::info!(ip = %ip, "vm ipv4 ready");
73 run_ssh_session(ssh_key, ssh_user, ip)
76pub fn ensure_instance_dir(project_root: &Path) -> Result<PathBuf, io::Error> {
77 let instance_dir = project_root.join(INSTANCE_DIR_NAME);
78 fs::create_dir_all(&instance_dir)?;
79 Ok(instance_dir)
82pub(crate) fn ensure_ssh_keypair(
83 instance_dir: &Path,
84) -> Result<(PathBuf, PathBuf), Box<dyn std::error::Error>> {
85 let private_key = instance_dir.join(SSH_KEY_NAME);
86 let public_key = instance_dir.join(format!("{SSH_KEY_NAME}.pub"));
88 if private_key.exists() && public_key.exists() {
89 return Ok((private_key, public_key));
90 }
92 if private_key.exists() {
93 let _ = fs::remove_file(&private_key);
94 }
95 if public_key.exists() {
96 let _ = fs::remove_file(&public_key);
97 }
99 let status = Command::new("ssh-keygen")
100 .args([
101 "-t",
102 "ed25519",
103 "-N",
104 "",
105 "-f",
106 private_key.to_str().ok_or("ssh key path not utf-8")?,
107 "-C",
108 "vibebox",
109 ])
110 .stdin(Stdio::null())
111 .stdout(Stdio::null())
112 .stderr(Stdio::inherit())
113 .status()?;
115 if !status.success() {
116 return Err("ssh-keygen failed".into());
117 }
119 fs::set_permissions(&private_key, fs::Permissions::from_mode(0o600))?;
120 fs::set_permissions(&public_key, fs::Permissions::from_mode(0o644))?;
122 Ok((private_key, public_key))
125pub(crate) fn load_or_create_instance_config(
126 instance_dir: &Path,
127) -> Result<InstanceConfig, Box<dyn std::error::Error>> {
128 let config_path = instance_dir.join(INSTANCE_FILENAME);
129 let mut config = if config_path.exists() {
130 let raw = fs::read_to_string(&config_path)?;
131 toml::from_str::<InstanceConfig>(&raw)?
132 } else {
133 InstanceConfig {
134 id: String::new(),
135 ssh_user: default_ssh_user(),
136 sudo_password: String::new(),
137 last_active: None,
138 vm_ipv4: None,
139 }
140 };
142 let mut changed = false;
143 if config.ssh_user.trim().is_empty() {
144 config.ssh_user = default_ssh_user();
145 changed = true;
146 }
148 if config.id.trim().is_empty() {
149 config.id = Uuid::now_v7().to_string();
150 changed = true;
151 }
153 if config.sudo_password.trim().is_empty() {
154 config.sudo_password = generate_password();
155 changed = true;
156 }
158 if !config_path.exists() || changed {
159 write_instance_config(&config_path, &config)?;
160 }
162 Ok(config)
165fn read_instance_config(
166 instance_dir: &Path,
167) -> Result<Option<InstanceConfig>, Box<dyn std::error::Error>> {
168 let config_path = instance_dir.join(INSTANCE_FILENAME);
169 if !config_path.exists() {
170 return Ok(None);
171 }
172 let raw = fs::read_to_string(&config_path)?;
173 let config = toml::from_str::<InstanceConfig>(&raw)?;
174 Ok(Some(config))
177pub fn read_instance_vm_ip(
178 instance_dir: &Path,
179) -> Result<Option<String>, Box<dyn std::error::Error>> {
180 let config = read_instance_config(instance_dir)?;
181 Ok(config.and_then(|cfg| cfg.vm_ipv4))
184pub fn touch_last_active(instance_dir: &Path) -> Result<(), Box<dyn std::error::Error>> {
185 let mut config = load_or_create_instance_config(instance_dir)?;
186 let now = OffsetDateTime::now_utc().format(&Rfc3339)?;
187 config.last_active = Some(now);
188 write_instance_config(&instance_dir.join(INSTANCE_FILENAME), &config)?;
189 Ok(())
192pub(crate) fn write_instance_config(
193 path: &Path,
194 config: &InstanceConfig,
195) -> Result<(), Box<dyn std::error::Error>> {
196 let data = toml::to_string_pretty(config)?;
197 fs::write(path, data)?;
198 fs::set_permissions(path, fs::Permissions::from_mode(0o600))?;
199 Ok(())
202fn generate_password() -> String {
203 Uuid::now_v7().simple().to_string()
206pub(crate) fn extract_ipv4(line: &str) -> Option<String> {
207 let mut current = String::new();
208 let mut best: Option<String> = None;
210 for ch in line.chars().chain(std::iter::once(' ')) {
211 if ch.is_ascii_digit() || ch == '.' {
212 current.push(ch);
213 } else if !current.is_empty() {
214 if is_ipv4_candidate(&current) {
215 best = Some(current.clone());
216 break;
217 }
218 current.clear();
219 }
220 }
222 best
225fn wait_for_vm_ipv4(
226 instance_dir: &Path,
227 timeout: Duration,
228) -> Result<(), Box<dyn std::error::Error>> {
229 let start = Instant::now();
230 loop {
231 let config = load_or_create_instance_config(instance_dir)?;
232 if config.vm_ipv4.is_some() {
233 return Ok(());
234 }
235 if start.elapsed() > timeout {
236 return Err("Timed out waiting for VM IPv4".into());
237 }
238 if start.elapsed().as_secs() % 5 == 0 {
239 tracing::debug!("still waiting for vm ipv4");
240 }
241 thread::sleep(Duration::from_millis(200));
242 }
245fn run_ssh_session(
246 ssh_key: PathBuf,
247 ssh_user: String,
248 ip: String,
249) -> Result<(), Box<dyn std::error::Error>> {
250 let mut attempts = 0usize;
251 loop {
252 attempts += 1;
253 if !ssh_port_open(&ip) {
254 tracing::debug!(attempts, "ssh port not open yet");
255 eprintln!(
256 "[vibebox] waiting for ssh port on {ip} (attempt {attempts}/{SSH_CONNECT_RETRIES})"
257 );
258 if attempts >= SSH_CONNECT_RETRIES {
259 return Err(
260 format!("ssh port not ready after {SSH_CONNECT_RETRIES} attempts").into(),
261 );
262 }
263 thread::sleep(Duration::from_millis(SSH_CONNECT_DELAY_MS));
264 continue;
265 }
267 eprintln!(
268 "[vibebox] starting ssh to {ssh_user}@{ip} (attempt {attempts}/{SSH_CONNECT_RETRIES})"
269 );
270 tracing::info!(attempts, user = %ssh_user, ip = %ip, "starting ssh");
271 let status = Command::new("ssh")
272 .args([
273 "-i",
274 ssh_key.to_str().unwrap_or(".vibebox/ssh_key"),
275 "-o",
276 "IdentitiesOnly=yes",
277 "-o",
278 "StrictHostKeyChecking=no",
279 "-o",
280 "UserKnownHostsFile=/dev/null",
281 "-o",
282 "GlobalKnownHostsFile=/dev/null",
283 "-o",
284 "PasswordAuthentication=no",
285 "-o",
286 "BatchMode=yes",
287 "-o",
288 "LogLevel=ERROR",
289 "-o",
290 "ConnectTimeout=5",
291 ])
292 .env_remove("LC_CTYPE")
293 .env_remove("LC_ALL")
294 .env_remove("LANG")
295 .arg(format!("{ssh_user}@{ip}"))
296 .stdin(Stdio::inherit())
297 .stdout(Stdio::inherit())
298 .stderr(Stdio::inherit())
299 .status();
301 match status {
302 Ok(status) if status.success() => {
303 eprintln!("[vibebox] ssh exited with status: {status}");
304 break;
305 }
306 Ok(status) if status.code() == Some(255) => {
307 eprintln!("[vibebox] ssh connection failed: {status}");
308 if attempts >= SSH_CONNECT_RETRIES {
309 return Err(format!("ssh failed after {SSH_CONNECT_RETRIES} attempts").into());
310 }
311 thread::sleep(Duration::from_millis(500));
312 }
313 Ok(status) => {
314 eprintln!("[vibebox] ssh exited with status: {status}");
315 break;
316 }
317 Err(err) => {
318 return Err(format!("failed to start ssh: {err}").into());
319 }
320 }
321 }
323 Ok(())
326fn is_ipv4_candidate(candidate: &str) -> bool {
327 let parts: Vec<&str> = candidate.split('.').collect();
328 if parts.len() != 4 {
329 return false;
330 }
331 for part in parts {
332 if part.is_empty() || part.len() > 3 {
333 return false;
334 }
335 if part.parse::<u8>().is_err() {
336 return false;
337 }
338 }
339 true
342fn ssh_port_open(ip: &str) -> bool {
343 let addr: SocketAddr = match format!("{ip}:22").parse() {
344 Ok(addr) => addr,
345 Err(_) => return false,
346 };
347 TcpStream::connect_timeout(&addr, std::time::Duration::from_millis(500)).is_ok()
350pub(crate) fn build_ssh_login_actions(
351 config: &Arc<Mutex<InstanceConfig>>,
352 project_name: &str,
353 guest_dir: &str,
354 key_name: &str,
355) -> Vec<LoginAction> {
356 let config_guard = config.lock().expect("config mutex poisoned");
357 let ssh_user = config_guard.ssh_user.clone();
358 let sudo_password = config_guard.sudo_password.clone();
359 drop(config_guard);
361 let key_path = format!("{guest_dir}/{key_name}.pub");
363 let setup_script = SSH_SETUP_SCRIPT
364 .replace("__SSH_USER__", &ssh_user)
365 .replace("__SUDO_PASSWORD__", &sudo_password)
366 .replace("__PROJECT_NAME__", project_name)
367 .replace("__KEY_PATH__", &key_path)
368 .replace("__VIBEBOX_SHELL_SCRIPT__", &commands::render_shell_script());
369 let setup = vm::script_command_from_content("ssh_setup", &setup_script)
370 .expect("ssh setup script contained invalid marker");
372 vec![LoginAction::Send(setup)]
375fn spawn_ssh_io(
376 app: Arc<Mutex<AppState>>,
377 config: Arc<Mutex<InstanceConfig>>,
378 instance_dir: PathBuf,
379 ssh_key: PathBuf,
380 output_monitor: Arc<vm::OutputMonitor>,
381 vm_output_fd: OwnedFd,
382 vm_input_fd: OwnedFd,
383) -> vm::IoContext {
384 let io_control = vm::IoControl::new();
386 let log_path = instance_dir.join(SERIAL_LOG_NAME);
387 let log_file = fs::OpenOptions::new()
388 .create(true)
389 .write(true)
390 .truncate(true)
391 .open(&log_path)
392 .ok()
393 .map(|file| Arc::new(Mutex::new(file)));
395 let ssh_connected = Arc::new(AtomicBool::new(false));
396 let ssh_started = Arc::new(AtomicBool::new(false));
397 let ssh_ready = Arc::new(AtomicBool::new(false));
398 let input_tx_holder: Arc<Mutex<Option<Sender<VmInput>>>> = Arc::new(Mutex::new(None));
400 let instance_path = instance_dir.join(INSTANCE_FILENAME);
401 let config_for_output = config.clone();
402 let log_for_output = log_file.clone();
403 let ssh_connected_for_output = ssh_connected.clone();
404 let ssh_ready_for_output = ssh_ready.clone();
406 let mut line_buf = String::new();
408 let handlers = commands::build_handlers(app.clone(), io_control.clone());
409 let on_line = move |line: &str| handlers.handle(line);
411 let on_output = move |bytes: &[u8]| {
412 if ssh_connected_for_output.load(Ordering::SeqCst) {
413 if let Some(log) = &log_for_output {
414 if let Ok(mut file) = log.lock() {
415 let _ = file.write_all(bytes);
416 }
417 }
418 }
420 let text = String::from_utf8_lossy(bytes);
421 line_buf.push_str(&text);
423 while let Some(pos) = line_buf.find('\n') {
424 let mut line = line_buf[..pos].to_string();
425 if line.ends_with('\r') {
426 line.pop();
427 }
428 line_buf.drain(..=pos);
430 let cleaned = line.trim_start_matches(|c: char| c == '\r' || c == ' ');
432 if let Some(pos) = cleaned.find("VIBEBOX_IPV4=") {
433 let ip_raw = &cleaned[(pos + "VIBEBOX_IPV4=".len())..];
434 let ip = extract_ipv4(ip_raw).unwrap_or_default();
435 if !ip.is_empty() {
436 if let Ok(mut cfg) = config_for_output.lock() {
437 if cfg.vm_ipv4.as_deref() != Some(ip.as_str()) {
438 cfg.vm_ipv4 = Some(ip.clone());
439 let _ = write_instance_config(&instance_path, &cfg);
440 eprintln!("[vibebox] detected vm IPv4: {ip}");
441 }
442 }
443 }
444 }
446 if cleaned.contains("VIBEBOX_SSH_READY") {
447 ssh_ready_for_output.store(true, Ordering::SeqCst);
448 eprintln!("[vibebox] sshd ready");
449 }
450 }
451 };
453 let io_ctx = vm::spawn_vm_io_with_hooks(
454 output_monitor,
455 vm_output_fd,
456 vm_input_fd,
457 io_control.clone(),
458 on_line,
459 on_output,
460 );
462 *input_tx_holder.lock().unwrap() = Some(io_ctx.input_tx.clone());
464 let ssh_ready_for_thread = ssh_ready.clone();
465 let ssh_started_for_thread = ssh_started.clone();
466 let ssh_connected_for_thread = ssh_connected.clone();
467 let io_control_for_thread = io_control.clone();
468 let ssh_key_for_thread = ssh_key.clone();
469 let config_for_thread = config.clone();
470 let input_tx_holder_for_thread = input_tx_holder.clone();
472 thread::spawn(move || {
473 loop {
474 if ssh_started_for_thread.load(Ordering::SeqCst) {
475 break;
476 }
477 if !ssh_ready_for_thread.load(Ordering::SeqCst) {
478 thread::sleep(std::time::Duration::from_millis(200));
479 continue;
480 }
482 let ip = config_for_thread
483 .lock()
484 .ok()
485 .and_then(|cfg| cfg.vm_ipv4.clone());
486 let ssh_user = config_for_thread
487 .lock()
488 .map(|cfg| cfg.ssh_user.clone())
489 .unwrap_or_else(|_| DEFAULT_SSH_USER.to_string());
491 if let Some(ip) = ip {
492 if ssh_started_for_thread
493 .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
494 .is_err()
495 {
496 break;
497 }
499 eprintln!("[vibebox] starting ssh to {ssh_user}@{ip}");
500 io_control_for_thread.request_terminal_restore();
501 io_control_for_thread.set_forward_output(false);
502 io_control_for_thread.set_forward_input(false);
503 ssh_connected_for_thread.store(true, Ordering::SeqCst);
505 let mut attempts = 0usize;
506 loop {
507 attempts += 1;
508 if !ssh_port_open(&ip) {
509 eprintln!(
510 "[vibebox] waiting for ssh port on {ip} (attempt {attempts}/{SSH_CONNECT_RETRIES})"
511 );
512 if attempts >= SSH_CONNECT_RETRIES {
513 ssh_connected_for_thread.store(false, Ordering::SeqCst);
514 eprintln!(
515 "[vibebox] ssh port not ready after {SSH_CONNECT_RETRIES} attempts"
516 );
517 break;
518 }
519 thread::sleep(std::time::Duration::from_millis(SSH_CONNECT_DELAY_MS));
520 continue;
521 }
523 eprintln!(
524 "[vibebox] starting ssh to {ssh_user}@{ip} (attempt {attempts}/{SSH_CONNECT_RETRIES})"
525 );
526 let status = Command::new("ssh")
527 .args([
528 "-i",
529 ssh_key_for_thread.to_str().unwrap_or(".vibebox/ssh_key"),
530 "-o",
531 "IdentitiesOnly=yes",
532 "-o",
533 "StrictHostKeyChecking=no",
534 "-o",
535 "UserKnownHostsFile=/dev/null",
536 "-o",
537 "GlobalKnownHostsFile=/dev/null",
538 "-o",
539 "PasswordAuthentication=no",
540 "-o",
541 "BatchMode=yes",
542 "-o",
543 "LogLevel=ERROR",
544 "-o",
545 "ConnectTimeout=5",
546 ])
547 .env_remove("LC_CTYPE")
548 .env_remove("LC_ALL")
549 // .env_remove("LANG")
550 .arg(format!("{ssh_user}@{ip}"))
551 .stdin(Stdio::inherit())
552 .stdout(Stdio::inherit())
553 .stderr(Stdio::inherit())
554 .status();
556 match status {
557 Ok(status) if status.success() => {
558 ssh_connected_for_thread.store(false, Ordering::SeqCst);
559 eprintln!("[vibebox] ssh exited with status: {status}");
560 if let Some(tx) = input_tx_holder_for_thread.lock().unwrap().clone() {
561 let _ = tx.send(VmInput::Bytes(b"systemctl poweroff\n".to_vec()));
562 }
563 break;
564 }
565 Ok(status) if status.code() == Some(255) => {
566 eprintln!("[vibebox] ssh connection failed: {status}");
567 if attempts >= SSH_CONNECT_RETRIES {
568 ssh_connected_for_thread.store(false, Ordering::SeqCst);
569 eprintln!(
570 "[vibebox] ssh failed after {SSH_CONNECT_RETRIES} attempts"
571 );
572 break;
573 }
574 thread::sleep(std::time::Duration::from_millis(500));
575 continue;
576 }
577 Ok(status) => {
578 ssh_connected_for_thread.store(false, Ordering::SeqCst);
579 eprintln!("[vibebox] ssh exited with status: {status}");
580 if let Some(tx) = input_tx_holder_for_thread.lock().unwrap().clone() {
581 let _ = tx.send(VmInput::Bytes(b"systemctl poweroff\n".to_vec()));
582 }
583 break;
584 }
585 Err(err) => {
586 ssh_connected_for_thread.store(false, Ordering::SeqCst);
587 eprintln!("[vibebox] failed to start ssh: {err}");
588 break;
589 }
590 }
591 }
592 break;
593 }
595 thread::sleep(std::time::Duration::from_millis(200));
596 }
597 });
599 io_ctx