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