aev-vm 0.1.0

Manage QEMU virtual machines in Rust and open their consoles in Aen
Documentation
//! Ephemeral state for a running virtual machine.

use std::fs::{self, OpenOptions};
use std::io::Write;
use std::os::unix::fs::OpenOptionsExt;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};

use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};

/// Process and socket metadata for one running VM.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct VmState {
    /// Definition name.
    pub name: String,
    /// QEMU daemon process ID.
    pub pid: u32,
    /// UNIX timestamp at launch.
    pub started_at_unix: u64,
    /// QMP control endpoint.
    pub qmp_socket: PathBuf,
    /// RFB display endpoint.
    pub display_socket: PathBuf,
    /// Optional QEMU Guest Agent proxy endpoint.
    #[serde(default)]
    pub agent_socket: Option<PathBuf>,
}

impl VmState {
    /// Construct state for a newly launched process.
    #[must_use]
    pub fn new(
        name: String,
        pid: u32,
        qmp_socket: PathBuf,
        display_socket: PathBuf,
        agent_socket: Option<PathBuf>,
    ) -> Self {
        let started_at_unix = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs();
        Self {
            name,
            pid,
            started_at_unix,
            qmp_socket,
            display_socket,
            agent_socket,
        }
    }

    /// Read JSON state from disk.
    pub fn load(path: &Path) -> Result<Self> {
        let source = fs::read(path)
            .with_context(|| format!("failed to read VM state {}", path.display()))?;
        serde_json::from_slice(&source)
            .with_context(|| format!("failed to parse VM state {}", path.display()))
    }

    /// Atomically replace JSON state on disk.
    pub fn save(&self, path: &Path) -> Result<()> {
        let nonce = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_nanos();
        let temporary = path.with_extension(format!("json.tmp-{}-{nonce}", std::process::id()));
        let mut created = false;
        let result = (|| -> Result<()> {
            let mut file = OpenOptions::new()
                .write(true)
                .create_new(true)
                .mode(0o600)
                .custom_flags(libc::O_NOFOLLOW)
                .open(&temporary)
                .with_context(|| format!("failed to create VM state {}", temporary.display()))?;
            created = true;
            serde_json::to_writer_pretty(&mut file, self)?;
            file.write_all(b"\n")?;
            file.sync_all()?;
            drop(file);
            fs::rename(&temporary, path).with_context(|| {
                format!(
                    "failed to replace VM state {} with {}",
                    path.display(),
                    temporary.display()
                )
            })
        })();
        if result.is_err() && created {
            let _ = fs::remove_file(&temporary);
        }
        result
    }
}

/// Check whether a process is still live, excluding terminated zombies.
#[must_use]
pub fn process_exists(pid: u32) -> bool {
    if pid == 0 || process_is_defunct(pid) {
        return false;
    }
    let Ok(pid) = i32::try_from(pid) else {
        return false;
    };
    // SAFETY: signal zero performs an existence check and the integer PID is validated above.
    let result = unsafe { libc::kill(pid, 0) };
    result == 0 || std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)
}

fn process_is_defunct(pid: u32) -> bool {
    let Ok(stat) = fs::read_to_string(format!("/proc/{pid}/stat")) else {
        return false;
    };
    let Some((_, fields)) = stat.rsplit_once(") ") else {
        return false;
    };
    matches!(fields.split_whitespace().next(), Some("Z" | "X"))
}

#[cfg(test)]
mod tests {
    use super::{VmState, process_exists};
    use std::{
        fs,
        os::unix::fs::{PermissionsExt, symlink},
        path::PathBuf,
        process::Command,
        thread,
        time::{Duration, Instant},
    };
    use tempfile::tempdir;

    #[test]
    fn save_uses_private_unique_temp_and_does_not_follow_stale_symlink() {
        let root = tempdir().unwrap();
        let path = root.path().join("state.json");
        let temporary = path.with_extension("json.tmp");
        let sentinel = root.path().join("sentinel");
        fs::write(&sentinel, b"preserve this file").unwrap();
        symlink(&sentinel, &temporary).unwrap();
        let state = VmState::new(
            "test".to_owned(),
            123,
            PathBuf::from("/run/knottvm/test/qmp.sock"),
            PathBuf::from("/run/knottvm/test/display.sock"),
            None,
        );

        state.save(&path).unwrap();

        assert_eq!(fs::read(&sentinel).unwrap(), b"preserve this file");
        assert!(
            fs::symlink_metadata(&temporary)
                .unwrap()
                .file_type()
                .is_symlink()
        );
        assert_eq!(VmState::load(&path).unwrap(), state);
        assert_eq!(
            fs::metadata(&path).unwrap().permissions().mode() & 0o777,
            0o600
        );
    }

    #[test]
    fn exited_but_unreaped_child_is_not_reported_as_live() {
        let mut child = Command::new("/bin/sh")
            .args(["-c", "exit 0"])
            .spawn()
            .unwrap();
        let pid = child.id();
        let deadline = Instant::now() + Duration::from_secs(2);
        loop {
            let state = std::fs::read_to_string(format!("/proc/{pid}/stat")).unwrap();
            if state.rsplit_once(") ").unwrap().1.starts_with('Z') {
                break;
            }
            assert!(Instant::now() < deadline, "child did not become a zombie");
            thread::sleep(Duration::from_millis(5));
        }

        assert!(!process_exists(pid));
        assert!(child.wait().unwrap().success());
    }

    #[test]
    fn nonexistent_pid_is_not_reported_as_live() {
        assert!(!process_exists(u32::MAX));
    }
}