1use std::fs::{self, OpenOptions};
4use std::io::Write;
5use std::os::unix::fs::OpenOptionsExt;
6use std::path::{Path, PathBuf};
7use std::time::{SystemTime, UNIX_EPOCH};
8
9use anyhow::{Context, Result};
10use serde::{Deserialize, Serialize};
11
12#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
14pub struct VmState {
15 pub name: String,
17 pub pid: u32,
19 pub started_at_unix: u64,
21 pub qmp_socket: PathBuf,
23 pub display_socket: PathBuf,
25 #[serde(default)]
27 pub agent_socket: Option<PathBuf>,
28}
29
30impl VmState {
31 #[must_use]
33 pub fn new(
34 name: String,
35 pid: u32,
36 qmp_socket: PathBuf,
37 display_socket: PathBuf,
38 agent_socket: Option<PathBuf>,
39 ) -> Self {
40 let started_at_unix = SystemTime::now()
41 .duration_since(UNIX_EPOCH)
42 .unwrap_or_default()
43 .as_secs();
44 Self {
45 name,
46 pid,
47 started_at_unix,
48 qmp_socket,
49 display_socket,
50 agent_socket,
51 }
52 }
53
54 pub fn load(path: &Path) -> Result<Self> {
56 let source = fs::read(path)
57 .with_context(|| format!("failed to read VM state {}", path.display()))?;
58 serde_json::from_slice(&source)
59 .with_context(|| format!("failed to parse VM state {}", path.display()))
60 }
61
62 pub fn save(&self, path: &Path) -> Result<()> {
64 let nonce = SystemTime::now()
65 .duration_since(UNIX_EPOCH)
66 .unwrap_or_default()
67 .as_nanos();
68 let temporary = path.with_extension(format!("json.tmp-{}-{nonce}", std::process::id()));
69 let mut created = false;
70 let result = (|| -> Result<()> {
71 let mut file = OpenOptions::new()
72 .write(true)
73 .create_new(true)
74 .mode(0o600)
75 .custom_flags(libc::O_NOFOLLOW)
76 .open(&temporary)
77 .with_context(|| format!("failed to create VM state {}", temporary.display()))?;
78 created = true;
79 serde_json::to_writer_pretty(&mut file, self)?;
80 file.write_all(b"\n")?;
81 file.sync_all()?;
82 drop(file);
83 fs::rename(&temporary, path).with_context(|| {
84 format!(
85 "failed to replace VM state {} with {}",
86 path.display(),
87 temporary.display()
88 )
89 })
90 })();
91 if result.is_err() && created {
92 let _ = fs::remove_file(&temporary);
93 }
94 result
95 }
96}
97
98#[must_use]
100pub fn process_exists(pid: u32) -> bool {
101 if pid == 0 || process_is_defunct(pid) {
102 return false;
103 }
104 let Ok(pid) = i32::try_from(pid) else {
105 return false;
106 };
107 let result = unsafe { libc::kill(pid, 0) };
109 result == 0 || std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)
110}
111
112fn process_is_defunct(pid: u32) -> bool {
113 let Ok(stat) = fs::read_to_string(format!("/proc/{pid}/stat")) else {
114 return false;
115 };
116 let Some((_, fields)) = stat.rsplit_once(") ") else {
117 return false;
118 };
119 matches!(fields.split_whitespace().next(), Some("Z" | "X"))
120}
121
122#[cfg(test)]
123mod tests {
124 use super::{VmState, process_exists};
125 use std::{
126 fs,
127 os::unix::fs::{PermissionsExt, symlink},
128 path::PathBuf,
129 process::Command,
130 thread,
131 time::{Duration, Instant},
132 };
133 use tempfile::tempdir;
134
135 #[test]
136 fn save_uses_private_unique_temp_and_does_not_follow_stale_symlink() {
137 let root = tempdir().unwrap();
138 let path = root.path().join("state.json");
139 let temporary = path.with_extension("json.tmp");
140 let sentinel = root.path().join("sentinel");
141 fs::write(&sentinel, b"preserve this file").unwrap();
142 symlink(&sentinel, &temporary).unwrap();
143 let state = VmState::new(
144 "test".to_owned(),
145 123,
146 PathBuf::from("/run/knottvm/test/qmp.sock"),
147 PathBuf::from("/run/knottvm/test/display.sock"),
148 None,
149 );
150
151 state.save(&path).unwrap();
152
153 assert_eq!(fs::read(&sentinel).unwrap(), b"preserve this file");
154 assert!(
155 fs::symlink_metadata(&temporary)
156 .unwrap()
157 .file_type()
158 .is_symlink()
159 );
160 assert_eq!(VmState::load(&path).unwrap(), state);
161 assert_eq!(
162 fs::metadata(&path).unwrap().permissions().mode() & 0o777,
163 0o600
164 );
165 }
166
167 #[test]
168 fn exited_but_unreaped_child_is_not_reported_as_live() {
169 let mut child = Command::new("/bin/sh")
170 .args(["-c", "exit 0"])
171 .spawn()
172 .unwrap();
173 let pid = child.id();
174 let deadline = Instant::now() + Duration::from_secs(2);
175 loop {
176 let state = std::fs::read_to_string(format!("/proc/{pid}/stat")).unwrap();
177 if state.rsplit_once(") ").unwrap().1.starts_with('Z') {
178 break;
179 }
180 assert!(Instant::now() < deadline, "child did not become a zombie");
181 thread::sleep(Duration::from_millis(5));
182 }
183
184 assert!(!process_exists(pid));
185 assert!(child.wait().unwrap().success());
186 }
187
188 #[test]
189 fn nonexistent_pid_is_not_reported_as_live() {
190 assert!(!process_exists(u32::MAX));
191 }
192}