on df08e45 help sign in
vibebox/src/instance.rs
647 lines 22 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 VM_ROOT_LOG_NAME: &str = "vm_root.log";
30pub(crate) const 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>,
49impl InstanceConfig {
50 pub(crate) fn ssh_user_display(&self) -> String {
51 if self.ssh_user.trim().is_empty() {
52 DEFAULT_SSH_USER.to_string()
53 } else {
54 self.ssh_user.clone()
55 }
56 }
59fn default_ssh_user() -> String {
60 DEFAULT_SSH_USER.to_string()
63pub fn run_with_ssh(manager_conn: UnixStream) -> Result<(), Box<dyn std::error::Error>> {
64 let project_root = env::current_dir()?;
65 tracing::info!(root = %project_root.display(), "starting ssh session");
66 let instance_dir = ensure_instance_dir(&project_root)?;
67 tracing::debug!(instance_dir = %instance_dir.display(), "instance dir ready");
68 let (ssh_key, _ssh_pub) = ensure_ssh_keypair(&instance_dir)?;
70 let config = load_or_create_instance_config(&instance_dir)?;
71 let ssh_user = config.ssh_user.clone();
72 tracing::debug!(ssh_user = %ssh_user, "loaded instance config");
74 let _manager_conn = manager_conn;
75 tracing::debug!("waiting for vm ipv4");
76 wait_for_vm_ipv4(&instance_dir, Duration::from_secs(120))?;
78 let ip = load_or_create_instance_config(&instance_dir)?
79 .vm_ipv4
80 .ok_or("VM IPv4 not available")?;
81 tracing::info!(ip = %ip, "vm ipv4 ready");
83 run_ssh_session(ssh_key, ssh_user, ip)
86pub fn ensure_instance_dir(project_root: &Path) -> Result<PathBuf, io::Error> {
87 let instance_dir = project_root.join(INSTANCE_DIR_NAME);
88 fs::create_dir_all(&instance_dir)?;
89 Ok(instance_dir)
92pub(crate) fn ensure_ssh_keypair(
93 instance_dir: &Path,
94) -> Result<(PathBuf, PathBuf), Box<dyn std::error::Error>> {
95 let private_key = instance_dir.join(SSH_KEY_NAME);
96 let public_key = instance_dir.join(format!("{SSH_KEY_NAME}.pub"));
98 if private_key.exists() && public_key.exists() {
99 return Ok((private_key, public_key));
100 }
102 if private_key.exists() {
103 let _ = fs::remove_file(&private_key);
104 }
105 if public_key.exists() {
106 let _ = fs::remove_file(&public_key);
107 }
109 let status = Command::new("ssh-keygen")
110 .args([
111 "-t",
112 "ed25519",
113 "-N",
114 "",
115 "-f",
116 private_key.to_str().ok_or("ssh key path not utf-8")?,
117 "-C",
118 "vibebox",
119 ])
120 .stdin(Stdio::null())
121 .stdout(Stdio::inherit())
122 .stderr(Stdio::inherit())
123 .status()?;
125 if !status.success() {
126 return Err("ssh-keygen failed".into());
127 }
129 fs::set_permissions(&private_key, fs::Permissions::from_mode(0o600))?;
130 fs::set_permissions(&public_key, fs::Permissions::from_mode(0o644))?;
132 Ok((private_key, public_key))
135pub(crate) fn load_or_create_instance_config(
136 instance_dir: &Path,
137) -> Result<InstanceConfig, Box<dyn std::error::Error>> {
138 let config_path = instance_dir.join(INSTANCE_FILENAME);
139 let mut config = if config_path.exists() {
140 let raw = fs::read_to_string(&config_path)?;
141 toml::from_str::<InstanceConfig>(&raw)?
142 } else {
143 InstanceConfig {
144 id: String::new(),
145 ssh_user: default_ssh_user(),
146 sudo_password: String::new(),
147 last_active: None,
148 vm_ipv4: None,
149 }
150 };
152 let mut changed = false;
153 if config.ssh_user.trim().is_empty() {
154 config.ssh_user = default_ssh_user();
155 changed = true;
156 }
158 if config.id.trim().is_empty() {
159 config.id = Uuid::now_v7().to_string();
160 changed = true;
161 }
163 if config.sudo_password.trim().is_empty() {
164 config.sudo_password = generate_password();
165 changed = true;
166 }
168 if !config_path.exists() || changed {
169 write_instance_config(&config_path, &config)?;
170 }
172 Ok(config)
175fn read_instance_config(
176 instance_dir: &Path,
177) -> Result<Option<InstanceConfig>, Box<dyn std::error::Error>> {
178 let config_path = instance_dir.join(INSTANCE_FILENAME);
179 if !config_path.exists() {
180 return Ok(None);
181 }
182 let raw = fs::read_to_string(&config_path)?;
183 let config = toml::from_str::<InstanceConfig>(&raw)?;
184 Ok(Some(config))
187pub fn read_instance_vm_ip(
188 instance_dir: &Path,
189) -> Result<Option<String>, Box<dyn std::error::Error>> {
190 let config = read_instance_config(instance_dir)?;
191 Ok(config.and_then(|cfg| cfg.vm_ipv4))
194pub fn read_instance_ssh_user(
195 instance_dir: &Path,
196) -> Result<Option<String>, Box<dyn std::error::Error>> {
197 let config = read_instance_config(instance_dir)?;
198 Ok(config
199 .map(|cfg| cfg.ssh_user)
200 .filter(|user| !user.trim().is_empty()))
203pub fn touch_last_active(instance_dir: &Path) -> Result<(), Box<dyn std::error::Error>> {
204 let mut config = load_or_create_instance_config(instance_dir)?;
205 let now = OffsetDateTime::now_utc().format(&Rfc3339)?;
206 config.last_active = Some(now);
207 write_instance_config(&instance_dir.join(INSTANCE_FILENAME), &config)?;
208 Ok(())
211pub(crate) fn write_instance_config(
212 path: &Path,
213 config: &InstanceConfig,
214) -> Result<(), Box<dyn std::error::Error>> {
215 let data = toml::to_string_pretty(config)?;
216 fs::write(path, data)?;
217 fs::set_permissions(path, fs::Permissions::from_mode(0o600))?;
218 Ok(())
221fn generate_password() -> String {
222 Uuid::now_v7().simple().to_string()
225pub(crate) fn extract_ipv4(line: &str) -> Option<String> {
226 let mut current = String::new();
227 let mut best: Option<String> = None;
229 for ch in line.chars().chain(std::iter::once(' ')) {
230 if ch.is_ascii_digit() || ch == '.' {
231 current.push(ch);
232 } else if !current.is_empty() {
233 if is_ipv4_candidate(&current) {
234 best = Some(current.clone());
235 break;
236 }
237 current.clear();
238 }
239 }
241 best
244fn wait_for_vm_ipv4(
245 instance_dir: &Path,
246 timeout: Duration,
247) -> Result<(), Box<dyn std::error::Error>> {
248 let start = Instant::now();
249 let mut next_log_at = start + Duration::from_secs(10);
250 tracing::debug!("waiting for vm ipv4");
251 loop {
252 let config = load_or_create_instance_config(instance_dir)?;
253 if config.vm_ipv4.is_some() {
254 return Ok(());
255 }
256 if start.elapsed() > timeout {
257 return Err("Timed out waiting for VM IPv4".into());
258 }
259 if Instant::now() >= next_log_at {
260 let waited = start.elapsed();
261 tracing::debug!("still waiting for vm ipv4, {}s elapsed", waited.as_secs(),);
262 next_log_at += Duration::from_secs(10);
263 }
264 thread::sleep(Duration::from_millis(200));
265 }
268fn run_ssh_session(
269 ssh_key: PathBuf,
270 ssh_user: String,
271 ip: String,
272) -> Result<(), Box<dyn std::error::Error>> {
273 let mut attempts = 0usize;
274 loop {
275 attempts += 1;
276 if !ssh_port_open(&ip) {
277 tracing::debug!(attempts, "ssh port doesn't open yet");
278 tracing::info!(
279 attempts,
280 ip = %ip,
281 "waiting for ssh port ({}/{})",
282 attempts,
283 SSH_CONNECT_RETRIES
284 );
285 if attempts >= SSH_CONNECT_RETRIES {
286 return Err(
287 format!("ssh port not ready after {SSH_CONNECT_RETRIES} attempts").into(),
288 );
289 }
290 thread::sleep(Duration::from_millis(SSH_CONNECT_DELAY_MS));
291 continue;
292 }
294 tracing::info!(
295 attempts,
296 user = %ssh_user,
297 ip = %ip,
298 "starting ssh ({}/{})",
299 attempts,
300 SSH_CONNECT_RETRIES
301 );
302 let status = Command::new("ssh")
303 .args([
304 "-i",
305 ssh_key.to_str().unwrap_or(".vibebox/ssh_key"),
306 "-o",
307 "IdentitiesOnly=yes",
308 "-o",
309 "StrictHostKeyChecking=no",
310 "-o",
311 "UserKnownHostsFile=/dev/null",
312 "-o",
313 "GlobalKnownHostsFile=/dev/null",
314 "-o",
315 "PasswordAuthentication=no",
316 "-o",
317 "BatchMode=yes",
318 "-o",
319 "LogLevel=ERROR",
320 "-o",
321 "ConnectTimeout=5",
322 ])
323 .env_remove("LC_CTYPE")
324 .env_remove("LC_ALL")
325 .env_remove("LANG")
326 .arg(format!("{ssh_user}@{ip}"))
327 .stdin(Stdio::inherit())
328 .stdout(Stdio::inherit())
329 .stderr(Stdio::inherit())
330 .status();
332 match status {
333 Ok(status) if status.success() => {
334 tracing::info!(status = %status, "ssh exited");
335 break;
336 }
337 Ok(status) if status.code() == Some(255) => {
338 tracing::warn!(status = %status, "ssh connection failed");
339 if attempts >= SSH_CONNECT_RETRIES {
340 return Err(format!("ssh failed after {SSH_CONNECT_RETRIES} attempts").into());
341 }
342 thread::sleep(Duration::from_millis(500));
343 }
344 Ok(status) => {
345 tracing::info!(status = %status, "ssh exited");
346 break;
347 }
348 Err(err) => {
349 tracing::error!(error = %err, "failed to start ssh");
350 return Err(format!("failed to start ssh: {err}").into());
351 }
352 }
353 }
355 Ok(())
358fn is_ipv4_candidate(candidate: &str) -> bool {
359 let parts: Vec<&str> = candidate.split('.').collect();
360 if parts.len() != 4 {
361 return false;
362 }
363 for part in parts {
364 if part.is_empty() || part.len() > 3 {
365 return false;
366 }
367 if part.parse::<u8>().is_err() {
368 return false;
369 }
370 }
371 true
374fn ssh_port_open(ip: &str) -> bool {
375 let addr: SocketAddr = match format!("{ip}:22").parse() {
376 Ok(addr) => addr,
377 Err(_) => return false,
378 };
379 TcpStream::connect_timeout(&addr, std::time::Duration::from_millis(500)).is_ok()
382pub(crate) fn build_ssh_login_actions(
383 config: &Arc<Mutex<InstanceConfig>>,
384 project_name: &str,
385 guest_dir: &str,
386 key_name: &str,
387 home_links_script: &str,
388) -> Vec<LoginAction> {
389 let config_guard = config.lock().expect("config mutex poisoned");
390 let ssh_user = config_guard.ssh_user.clone();
391 let sudo_password = config_guard.sudo_password.clone();
392 drop(config_guard);
394 let key_path = format!("{guest_dir}/{key_name}.pub");
396 let setup_script = SSH_SETUP_SCRIPT
397 .replace("__SSH_USER__", &ssh_user)
398 .replace("__SUDO_PASSWORD__", &sudo_password)
399 .replace("__PROJECT_NAME__", project_name)
400 .replace("__KEY_PATH__", &key_path)
401 .replace("__VIBEBOX_SHELL_SCRIPT__", &commands::render_shell_script())
402 .replace("__VIBEBOX_HOME_LINKS__", home_links_script);
403 let setup = vm::script_command_from_content("ssh_setup", &setup_script)
404 .expect("ssh setup script contained invalid marker");
406 vec![LoginAction::Send(setup)]
409fn spawn_ssh_io(
410 app: Arc<Mutex<AppState>>,
411 config: Arc<Mutex<InstanceConfig>>,
412 instance_dir: PathBuf,
413 ssh_key: PathBuf,
414 output_monitor: Arc<vm::OutputMonitor>,
415 vm_output_fd: OwnedFd,
416 vm_input_fd: OwnedFd,
417) -> vm::IoContext {
418 let io_control = vm::IoControl::new();
420 let log_path = instance_dir.join(VM_ROOT_LOG_NAME);
421 let log_file = fs::OpenOptions::new()
422 .create(true)
423 .write(true)
424 .truncate(true)
425 .open(&log_path)
426 .ok()
427 .map(|file| Arc::new(Mutex::new(file)));
429 let ssh_connected = Arc::new(AtomicBool::new(false));
430 let ssh_started = Arc::new(AtomicBool::new(false));
431 let ssh_ready = Arc::new(AtomicBool::new(false));
432 let input_tx_holder: Arc<Mutex<Option<Sender<VmInput>>>> = Arc::new(Mutex::new(None));
434 let instance_path = instance_dir.join(INSTANCE_FILENAME);
435 let config_for_output = config.clone();
436 let log_for_output = log_file.clone();
437 let ssh_connected_for_output = ssh_connected.clone();
438 let ssh_ready_for_output = ssh_ready.clone();
440 let mut line_buf = String::new();
442 let handlers = commands::build_handlers(app.clone(), io_control.clone());
443 let on_line = move |line: &str| handlers.handle(line);
445 let on_output = move |bytes: &[u8]| {
446 if ssh_connected_for_output.load(Ordering::SeqCst) {
447 if let Some(log) = &log_for_output {
448 if let Ok(mut file) = log.lock() {
449 let _ = file.write_all(bytes);
450 }
451 }
452 }
454 let text = String::from_utf8_lossy(bytes);
455 line_buf.push_str(&text);
457 while let Some(pos) = line_buf.find('\n') {
458 let mut line = line_buf[..pos].to_string();
459 if line.ends_with('\r') {
460 line.pop();
461 }
462 line_buf.drain(..=pos);
464 let cleaned = line.trim_start_matches(|c: char| c == '\r' || c == ' ');
466 if let Some(pos) = cleaned.find("VIBEBOX_IPV4=") {
467 let ip_raw = &cleaned[(pos + "VIBEBOX_IPV4=".len())..];
468 let ip = extract_ipv4(ip_raw).unwrap_or_default();
469 if !ip.is_empty() {
470 if let Ok(mut cfg) = config_for_output.lock() {
471 if cfg.vm_ipv4.as_deref() != Some(ip.as_str()) {
472 cfg.vm_ipv4 = Some(ip.clone());
473 let _ = write_instance_config(&instance_path, &cfg);
474 tracing::info!(ip = %ip, "detected vm ipv4");
475 }
476 }
477 }
478 }
480 if cleaned.contains("VIBEBOX_SSH_READY") {
481 ssh_ready_for_output.store(true, Ordering::SeqCst);
482 tracing::info!("sshd ready");
483 }
484 }
485 };
487 let io_ctx = vm::spawn_vm_io_with_hooks(
488 output_monitor,
489 vm_output_fd,
490 vm_input_fd,
491 io_control.clone(),
492 on_line,
493 on_output,
494 );
496 *input_tx_holder.lock().unwrap() = Some(io_ctx.input_tx.clone());
498 let ssh_ready_for_thread = ssh_ready.clone();
499 let ssh_started_for_thread = ssh_started.clone();
500 let ssh_connected_for_thread = ssh_connected.clone();
501 let io_control_for_thread = io_control.clone();
502 let ssh_key_for_thread = ssh_key.clone();
503 let config_for_thread = config.clone();
504 let input_tx_holder_for_thread = input_tx_holder.clone();
506 thread::spawn(move || {
507 loop {
508 if ssh_started_for_thread.load(Ordering::SeqCst) {
509 break;
510 }
511 if !ssh_ready_for_thread.load(Ordering::SeqCst) {
512 thread::sleep(std::time::Duration::from_millis(200));
513 continue;
514 }
516 let ip = config_for_thread
517 .lock()
518 .ok()
519 .and_then(|cfg| cfg.vm_ipv4.clone());
520 let ssh_user = config_for_thread
521 .lock()
522 .map(|cfg| cfg.ssh_user.clone())
523 .unwrap_or_else(|_| DEFAULT_SSH_USER.to_string());
525 if let Some(ip) = ip {
526 if ssh_started_for_thread
527 .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
528 .is_err()
529 {
530 break;
531 }
533 tracing::info!(user = %ssh_user, ip = %ip, "starting ssh");
534 io_control_for_thread.request_terminal_restore();
535 io_control_for_thread.set_forward_output(false);
536 io_control_for_thread.set_forward_input(false);
537 ssh_connected_for_thread.store(true, Ordering::SeqCst);
539 let mut attempts = 0usize;
540 loop {
541 attempts += 1;
542 if !ssh_port_open(&ip) {
543 tracing::info!(
544 attempts,
545 ip = %ip,
546 "waiting for ssh port ({}/{})",
547 attempts,
548 SSH_CONNECT_RETRIES
549 );
550 if attempts >= SSH_CONNECT_RETRIES {
551 ssh_connected_for_thread.store(false, Ordering::SeqCst);
552 tracing::warn!(
553 attempts,
554 "ssh port not ready after {} attempts",
555 SSH_CONNECT_RETRIES
556 );
557 break;
558 }
559 thread::sleep(std::time::Duration::from_millis(SSH_CONNECT_DELAY_MS));
560 continue;
561 }
563 tracing::info!(
564 attempts,
565 user = %ssh_user,
566 ip = %ip,
567 "starting ssh ({}/{})",
568 attempts,
569 SSH_CONNECT_RETRIES
570 );
571 let status = Command::new("ssh")
572 .args([
573 "-i",
574 ssh_key_for_thread.to_str().unwrap_or(".vibebox/ssh_key"),
575 "-o",
576 "IdentitiesOnly=yes",
577 "-o",
578 "StrictHostKeyChecking=no",
579 "-o",
580 "UserKnownHostsFile=/dev/null",
581 "-o",
582 "GlobalKnownHostsFile=/dev/null",
583 "-o",
584 "PasswordAuthentication=no",
585 "-o",
586 "BatchMode=yes",
587 "-o",
588 "LogLevel=ERROR",
589 "-o",
590 "ConnectTimeout=5",
591 ])
592 .env_remove("LC_CTYPE")
593 .env_remove("LC_ALL")
594 // .env_remove("LANG")
595 .arg(format!("{ssh_user}@{ip}"))
596 .stdin(Stdio::inherit())
597 .stdout(Stdio::inherit())
598 .stderr(Stdio::inherit())
599 .status();
601 match status {
602 Ok(status) if status.success() => {
603 ssh_connected_for_thread.store(false, Ordering::SeqCst);
604 tracing::info!(status = %status, "ssh exited");
605 if let Some(tx) = input_tx_holder_for_thread.lock().unwrap().clone() {
606 let _ = tx.send(VmInput::Bytes(b"systemctl poweroff\n".to_vec()));
607 }
608 break;
609 }
610 Ok(status) if status.code() == Some(255) => {
611 tracing::warn!(status = %status, "ssh connection failed");
612 if attempts >= SSH_CONNECT_RETRIES {
613 ssh_connected_for_thread.store(false, Ordering::SeqCst);
614 tracing::warn!(
615 attempts,
616 "ssh failed after {} attempts",
617 SSH_CONNECT_RETRIES
618 );
619 break;
620 }
621 thread::sleep(std::time::Duration::from_millis(500));
622 continue;
623 }
624 Ok(status) => {
625 ssh_connected_for_thread.store(false, Ordering::SeqCst);
626 tracing::info!(status = %status, "ssh exited");
627 if let Some(tx) = input_tx_holder_for_thread.lock().unwrap().clone() {
628 let _ = tx.send(VmInput::Bytes(b"systemctl poweroff\n".to_vec()));
629 }
630 break;
631 }
632 Err(err) => {
633 ssh_connected_for_thread.store(false, Ordering::SeqCst);
634 tracing::error!(error = %err, "failed to start ssh");
635 break;
636 }
637 }
638 }
639 break;
640 }
642 thread::sleep(std::time::Duration::from_millis(200));
643 }
644 });
646 io_ctx