| 1 | |
|
| 2 | |
|
| 3 | |
|
| 4 | |
|
| 5 | |
|
| 6 | |
|
| 7 | |
|
| 8 | |
|
| 9 | |
|
| 10 | |
|
| 11 | |
|
| 12 | |
|
| 13 | |
|
| 14 | |
|
| 15 | |
|
| 16 | |
|
| 17 | |
|
| 18 | |
|
| 19 | |
|
| 20 | |
|
| 21 | | use anyhow::{bail, Context, Result}; |
| 22 | | use serde::Deserialize; |
| 23 | | use std::collections::HashMap; |
| 24 | | use std::path::{Path, PathBuf}; |
| 25 | | use std::sync::Mutex; |
| 26 | |
|
| 27 | | #[derive(Clone, Debug, Deserialize)] |
| 28 | | pub struct Pinned { |
| 29 | | pub path: PathBuf, |
| 30 | | pub blake3: String, |
| 31 | | } |
| 32 | |
|
| 33 | | #[derive(Clone, Debug, Deserialize)] |
| 34 | | pub struct MicrovmConfig { |
| 35 | | pub firecracker: Pinned, |
| 36 | | pub kernel: Pinned, |
| 37 | | pub init: Pinned, |
| 38 | | } |
| 39 | |
|
| 40 | |
|
| 41 | | pub const RUNNER_TOML: &str = "runner.toml"; |
| 42 | |
|
| 43 | |
|
| 44 | | pub const CA_PEM: &str = "hub-ca.pem"; |
| 45 | |
|
| 46 | | #[derive(Clone, Debug, Deserialize)] |
| 47 | | pub struct RunnerConfig { |
| 48 | | pub hub: String, |
| 49 | | pub token: String, |
| 50 | | pub ca: Option<PathBuf>, |
| 51 | | pub name: Option<String>, |
| 52 | | |
| 53 | | #[serde(default)] |
| 54 | | pub max_jobs: Option<usize>, |
| 55 | | |
| 56 | | #[serde(default)] |
| 57 | | pub labels: Vec<String>, |
| 58 | | |
| 59 | | #[serde(default)] |
| 60 | | pub memory_mib: Option<u32>, |
| 61 | | #[serde(default)] |
| 62 | | pub cpus: Option<u32>, |
| 63 | | |
| 64 | | |
| 65 | | #[serde(default)] |
| 66 | | pub swarm: Option<SwarmConfig>, |
| 67 | | |
| 68 | | #[serde(default)] |
| 69 | | pub cache_gb: Option<u64>, |
| 70 | | |
| 71 | | |
| 72 | | |
| 73 | | #[serde(default)] |
| 74 | | pub cache_prune_percent: Option<u8>, |
| 75 | | |
| 76 | | |
| 77 | | |
| 78 | | #[serde(default)] |
| 79 | | pub egress: bool, |
| 80 | | |
| 81 | | |
| 82 | | |
| 83 | | |
| 84 | | #[serde(default)] |
| 85 | | pub keyless: bool, |
| 86 | | |
| 87 | | |
| 88 | | #[serde(default)] |
| 89 | | pub metrics: Option<String>, |
| 90 | | |
| 91 | | #[serde(default)] |
| 92 | | pub metrics_token: Option<String>, |
| 93 | | |
| 94 | | #[serde(default)] |
| 95 | | pub update: Option<UpdateConfig>, |
| 96 | | } |
| 97 | |
|
| 98 | |
|
| 99 | |
|
| 100 | | #[derive(Clone, Debug, Deserialize)] |
| 101 | | pub struct UpdateConfig { |
| 102 | | |
| 103 | | #[serde(default = "yes")] |
| 104 | | pub allow: bool, |
| 105 | | } |
| 106 | |
|
| 107 | 0× | fn yes() -> bool { |
| 108 | 0× | true |
| 109 | 0× | } |
| 110 | |
|
| 111 | | impl RunnerConfig { |
| 112 | | |
| 113 | | |
| 114 | 0× | pub fn offered_labels(&self) -> Vec<String> { |
| 115 | 0× | let mut l = self.labels.clone(); |
| 116 | 0× | if self.egress && !l.iter().any(|x| x == flow_core::EGRESS_LABEL) { |
| 117 | 0× | l.push(flow_core::EGRESS_LABEL.to_string()); |
| 118 | 0× | } |
| 119 | 0× | l |
| 120 | 0× | } |
| 121 | | } |
| 122 | |
|
| 123 | |
|
| 124 | | #[derive(Clone, Debug, Deserialize)] |
| 125 | | pub struct SwarmConfig { |
| 126 | | |
| 127 | | pub listen: String, |
| 128 | | |
| 129 | | #[serde(default)] |
| 130 | | pub advertise: Option<String>, |
| 131 | | |
| 132 | | #[serde(default)] |
| 133 | | pub site: String, |
| 134 | | |
| 135 | | #[serde(default)] |
| 136 | | pub upload_mib_s: Option<u32>, |
| 137 | | } |
| 138 | |
|
| 139 | | #[derive(Clone, Debug, Default, Deserialize)] |
| 140 | | pub struct Config { |
| 141 | | pub microvm: Option<MicrovmConfig>, |
| 142 | | pub runner: Option<RunnerConfig>, |
| 143 | | } |
| 144 | |
|
| 145 | | pub struct Home { |
| 146 | | pub root: PathBuf, |
| 147 | | pub config: Config, |
| 148 | | |
| 149 | | verified: Mutex<HashMap<PathBuf, (u64, std::time::SystemTime)>>, |
| 150 | | } |
| 151 | |
|
| 152 | | impl Home { |
| 153 | 23× | pub fn locate(explicit: Option<&Path>) -> Result<Home> { |
| 154 | 23× | let root = match explicit { |
| 155 | 23× | Some(p) => p.to_path_buf(), |
| 156 | 0× | None => match std::env::var_os("FLOW_HOME") { |
| 157 | 0× | Some(p) => PathBuf::from(p), |
| 158 | 0× | None => PathBuf::from(std::env::var_os("HOME").context("HOME is not set")?).join(".local/share/flow"), |
| 159 | | }, |
| 160 | | }; |
| 161 | 23× | let file = root.join("flow.toml"); |
| 162 | 23× | let mut config: Config = if file.is_file() { |
| 163 | 0× | let text = std::fs::read_to_string(&file).with_context(|| format!("read {}", file.display()))?; |
| 164 | 0× | toml::from_str(&text).with_context(|| format!("parse {}", file.display()))? |
| 165 | | } else { |
| 166 | 23× | Config::default() |
| 167 | | }; |
| 168 | | |
| 169 | | |
| 170 | 23× | let registered = root.join(RUNNER_TOML); |
| 171 | 23× | if config.runner.is_none() && registered.is_file() { |
| 172 | 14× | let text = std::fs::read_to_string(®istered).with_context(|| format!("read {}", registered.display()))?; |
| 173 | 14× | let mut runner: RunnerConfig = toml::from_str(&text).with_context(|| format!("parse {}", registered.display()))?; |
| 174 | | |
| 175 | | |
| 176 | 14× | runner.ca = runner.ca.map(|ca| if ca.is_absolute() { ca } else { root.join(ca) }); |
| 177 | 14× | config.runner = Some(runner); |
| 178 | 9× | } |
| 179 | 69× | for d in ["cas", "work", "repos"] { |
| 180 | 69× | std::fs::create_dir_all(root.join(d)).with_context(|| format!("create {}", root.join(d).display()))?; |
| 181 | | } |
| 182 | 23× | Ok(Home { root, config, verified: Mutex::new(HashMap::new()) }) |
| 183 | 23× | } |
| 184 | |
|
| 185 | 0× | pub fn resolve(&self, p: &Path) -> PathBuf { |
| 186 | 0× | if p.is_absolute() { |
| 187 | 0× | p.to_path_buf() |
| 188 | | } else { |
| 189 | 0× | self.root.join(p) |
| 190 | | } |
| 191 | 0× | } |
| 192 | |
|
| 193 | | |
| 194 | 40× | pub fn rootfs(&self, hash: &str) -> PathBuf { |
| 195 | 40× | self.root.join("cas").join(format!("{hash}.ext4")) |
| 196 | 40× | } |
| 197 | |
|
| 198 | | |
| 199 | | |
| 200 | 16× | pub fn image_manifest(&self, hash: &str) -> PathBuf { |
| 201 | 16× | self.root.join("cas").join(format!("{hash}.json")) |
| 202 | 16× | } |
| 203 | |
|
| 204 | | |
| 205 | | |
| 206 | | |
| 207 | | |
| 208 | | |
| 209 | 10× | pub fn image_arch(&self, hash: &str) -> Option<String> { |
| 210 | 10× | let path = self.image_manifest(hash); |
| 211 | 10× | let mut v: serde_json::Value = |
| 212 | 10× | std::fs::read_to_string(&path).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or_else(|| serde_json::json!({})); |
| 213 | 10× | if let Some(a) = v["arch"].as_str() { |
| 214 | 3× | return Some(a.to_string()); |
| 215 | 7× | } |
| 216 | 7× | let image = self.rootfs(hash); |
| 217 | 7× | if v.get("arch_read_ms").is_some() || !image.is_file() { |
| 218 | 1× | return None; |
| 219 | 6× | } |
| 220 | 6× | let arch = jet::rootfs::arch_of_file(&image); |
| 221 | 6× | let o = v.as_object_mut()?; |
| 222 | 6× | if let Some(a) = arch { |
| 223 | 1× | o.insert("arch".into(), a.into()); |
| 224 | 5× | } |
| 225 | 6× | let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0); |
| 226 | 6× | o.insert("arch_read_ms".into(), now.into()); |
| 227 | 6× | let tmp = path.with_extension("json.part"); |
| 228 | 6× | if std::fs::write(&tmp, v.to_string()).is_ok() { |
| 229 | 6× | let _ = std::fs::rename(&tmp, &path); |
| 230 | 6× | } |
| 231 | 6× | arch.map(String::from) |
| 232 | 10× | } |
| 233 | |
|
| 234 | | |
| 235 | 1× | pub fn image_archs(&self) -> std::collections::BTreeMap<String, String> { |
| 236 | 1× | self.images().into_iter().filter_map(|h| self.image_arch(&h).map(|a| (h, a))).collect() |
| 237 | 1× | } |
| 238 | |
|
| 239 | | |
| 240 | 13× | pub fn images(&self) -> Vec<String> { |
| 241 | 13× | let Ok(dir) = std::fs::read_dir(self.root.join("cas")) else { |
| 242 | 0× | return Vec::new(); |
| 243 | | }; |
| 244 | 13× | let mut out: Vec<String> = dir |
| 245 | 13× | .filter_map(|e| { |
| 246 | 6× | let name = e.ok()?.file_name().into_string().ok()?; |
| 247 | 6× | let hash = name.strip_suffix(".ext4")?; |
| 248 | 320× | (hash.len() == 64 && hash.chars().all(|c| c.is_ascii_hexdigit())).then(|| hash.to_string()) |
| 249 | 6× | }) |
| 250 | 13× | .collect(); |
| 251 | 13× | out.sort(); |
| 252 | 13× | out |
| 253 | 13× | } |
| 254 | |
|
| 255 | | |
| 256 | | |
| 257 | 4× | pub fn verified(&self, path: &Path, blake3_hex: &str) -> Result<PathBuf> { |
| 258 | 4× | let meta = std::fs::metadata(path).with_context(|| format!("{} is missing", path.display()))?; |
| 259 | 4× | let stamp = (meta.len(), meta.modified()?); |
| 260 | 4× | if self.verified.lock().unwrap().get(path) == Some(&stamp) { |
| 261 | 1× | return Ok(path.to_path_buf()); |
| 262 | 3× | } |
| 263 | 3× | let mut got = hash_file(path)?; |
| 264 | 3× | if got != blake3_hex { |
| 265 | | |
| 266 | | |
| 267 | | |
| 268 | | |
| 269 | 1× | drop_cached(path); |
| 270 | 1× | let again = hash_file(path)?; |
| 271 | 1× | if again == blake3_hex { |
| 272 | 0× | eprintln!( |
| 273 | 0× | "warning: {} hashed {got} from the page cache but {again} from the disk: the cached copy was bad (check this machine's memory)", |
| 274 | 0× | path.display() |
| 275 | 0× | ); |
| 276 | 1× | } |
| 277 | 1× | got = again; |
| 278 | 2× | } |
| 279 | 3× | if got != blake3_hex { |
| 280 | 1× | bail!("{} has BLAKE3 {got}, but {blake3_hex} is pinned", path.display()); |
| 281 | 2× | } |
| 282 | 2× | self.verified.lock().unwrap().insert(path.to_path_buf(), stamp); |
| 283 | 2× | Ok(path.to_path_buf()) |
| 284 | 4× | } |
| 285 | | } |
| 286 | |
|
| 287 | |
|
| 288 | |
|
| 289 | 1× | fn drop_cached(path: &Path) { |
| 290 | | #[cfg(target_os = "linux")] |
| 291 | 1× | if let Ok(f) = std::fs::File::open(path) { |
| 292 | | use std::os::fd::AsRawFd; |
| 293 | | |
| 294 | 1× | unsafe { |
| 295 | 1× | libc::posix_fadvise(f.as_raw_fd(), 0, 0, libc::POSIX_FADV_DONTNEED); |
| 296 | 1× | } |
| 297 | 0× | } |
| 298 | | #[cfg(not(target_os = "linux"))] |
| 299 | | let _ = path; |
| 300 | 1× | } |
| 301 | |
|
| 302 | 21× | pub fn hash_file(path: &Path) -> Result<String> { |
| 303 | 21× | let mut h = blake3::Hasher::new(); |
| 304 | 21× | h.update_reader(std::fs::File::open(path).with_context(|| format!("open {}", path.display()))?)?; |
| 305 | 21× | Ok(h.finalize().to_hex().to_string()) |
| 306 | 21× | } |
| 307 | |
|
| 308 | |
|
| 309 | | pub struct RunnerKey { |
| 310 | | pub identity: oxy_core::identity::Identity, |
| 311 | | pub secret: oxy_core::identity::SecretKey, |
| 312 | | } |
| 313 | |
|
| 314 | | impl Home { |
| 315 | | |
| 316 | | |
| 317 | 4× | pub fn runner_key(&self, name: &str) -> Result<RunnerKey> { |
| 318 | | use oxy_core::identity::{Identity, SecretKey}; |
| 319 | 4× | let key_path = self.root.join("runner.key"); |
| 320 | 4× | let id_path = self.root.join("runner.identity"); |
| 321 | 4× | if key_path.exists() { |
| 322 | 2× | let (key, secret) = SecretKey::decode(&std::fs::read(&key_path)?).context("runner.key")?; |
| 323 | 2× | let identity = Identity::decode(&std::fs::read(&id_path)?).context("runner.identity")?; |
| 324 | 2× | if identity.hash() != key { |
| 325 | 0× | bail!("runner.identity does not belong to runner.key"); |
| 326 | 2× | } |
| 327 | 2× | return Ok(RunnerKey { identity, secret }); |
| 328 | 2× | } |
| 329 | 2× | let secret = SecretKey::generate(); |
| 330 | 2× | let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0); |
| 331 | 2× | let identity = secret.identity(&format!("{name} (OxygenFlow runner)"), "", now); |
| 332 | 2× | std::fs::write(&id_path, identity.encode())?; |
| 333 | 2× | let tmp = self.root.join("runner.key.tmp"); |
| 334 | | { |
| 335 | | use std::io::Write; |
| 336 | 2× | let mut f = crate::portable::private(std::fs::OpenOptions::new().write(true).create(true).truncate(true)).open(&tmp)?; |
| 337 | 2× | f.write_all(&secret.encode(&identity.hash()))?; |
| 338 | 2× | f.sync_all()?; |
| 339 | | } |
| 340 | 2× | std::fs::rename(&tmp, &key_path)?; |
| 341 | 2× | Ok(RunnerKey { identity, secret }) |
| 342 | 4× | } |
| 343 | | } |
| 344 | |
|
| 345 | | #[cfg(test)] |
| 346 | | mod tests { |
| 347 | | use super::*; |
| 348 | |
|
| 349 | | #[test] |
| 350 | 1× | fn the_runner_key_is_made_once_and_kept_private() { |
| 351 | | use std::os::unix::fs::PermissionsExt; |
| 352 | 1× | let dir = tempfile::tempdir().unwrap(); |
| 353 | 1× | let home = Home::locate(Some(dir.path())).unwrap(); |
| 354 | 1× | let a = home.runner_key("earth-1").unwrap(); |
| 355 | 1× | assert_eq!(a.identity.name, "earth-1 (OxygenFlow runner)"); |
| 356 | 1× | let mode = std::fs::metadata(dir.path().join("runner.key")).unwrap().permissions().mode(); |
| 357 | 1× | assert_eq!(mode & 0o777, 0o600); |
| 358 | 1× | let b = home.runner_key("renamed").unwrap(); |
| 359 | 1× | assert_eq!(a.identity, b.identity, "the same key after a restart"); |
| 360 | 1× | let sig = b.secret.sign(oxy_core::identity::Domain::Attest, &b.identity.hash(), &oxy_core::hash::ObjectRef([1; 32])); |
| 361 | 1× | oxy_core::identity::verify(&a.identity, &sig, oxy_core::identity::Domain::Attest, &oxy_core::hash::ObjectRef([1; 32])).unwrap(); |
| 362 | 1× | } |
| 363 | |
|
| 364 | | |
| 365 | | #[test] |
| 366 | 1× | fn a_registered_runners_relative_ca_is_in_its_home() { |
| 367 | 1× | let dir = tempfile::tempdir().unwrap(); |
| 368 | 1× | std::fs::write(dir.path().join(RUNNER_TOML), "hub = \"https://hub\"\ntoken = \"t\"\nca = \"hub-ca.pem\"\n").unwrap(); |
| 369 | 1× | let home = Home::locate(Some(dir.path())).unwrap(); |
| 370 | 1× | assert_eq!(home.config.runner.unwrap().ca, Some(dir.path().join("hub-ca.pem"))); |
| 371 | 1× | std::fs::write(dir.path().join(RUNNER_TOML), "hub = \"https://hub\"\ntoken = \"t\"\nca = \"/etc/ssl/hub.pem\"\n").unwrap(); |
| 372 | 1× | let home = Home::locate(Some(dir.path())).unwrap(); |
| 373 | 1× | assert_eq!(home.config.runner.unwrap().ca, Some(PathBuf::from("/etc/ssl/hub.pem"))); |
| 374 | 1× | } |
| 375 | | } |