use std::collections::BTreeMap;
use std::path::PathBuf;
use isoloom_manifest::contract::CONSOLES;
use isoloom_manifest::{ConsoleSource, Machine, Protocol};
use serde::{Deserialize, Serialize};
use crate::Result;
use crate::error::Error;
use crate::executor::Cx;
use crate::secrets::SecretValue;
const FILE: &str = "consoles.json";
const PASSWORD_LEN: usize = 8;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
struct Chosen {
port: u16,
password: String,
}
fn path(cx: &Cx<'_>) -> PathBuf {
cx.state_dir().join(FILE)
}
fn read(cx: &Cx<'_>) -> Result<BTreeMap<String, Chosen>> {
Ok(crate::store::read_json(&path(cx))?.unwrap_or_default())
}
fn wanted<'m>(cx: &'m Cx<'_>) -> impl Iterator<Item = &'m Machine> {
let provider = cx.scope.provider;
cx.run
.manifest()
.machines
.iter()
.filter(move |m| m.console(provider).is_some_and(|c| matches!(c.source, Some(ConsoleSource::Runner {}))))
}
pub(crate) fn ensure(cx: &Cx<'_>) -> Result<()> {
let mut table = read(cx)?;
let missing: Vec<String> = wanted(cx).map(|m| m.name.to_string()).filter(|m| !table.contains_key(m)).collect();
if missing.is_empty() {
return Ok(());
}
let taken: Vec<u16> = table.values().map(|c| c.port).collect();
let mut held = Vec::new();
for machine in missing {
let port = loop {
let free = cx
.run
.runner
.pick_reserved(cx.run.name(), Protocol::Tcp)
.map_err(Error::io("a tcp port on 127.0.0.1", "bound"))?
.ok_or_else(|| Error::NoConsole {
machine: machine.clone(),
why: "no free port on this computer's loopback for its console".into(),
})?;
let port = free.port;
held.push(free);
if !taken.contains(&port) {
break port;
}
};
table.insert(machine, Chosen { port, password: password()? });
}
let path = path(cx);
let text = serde_json::to_vec(&table).map_err(|e| Error::io(&path, "written")(e.into()))?;
crate::store::write(&path, &text)
}
fn password() -> Result<String> {
const ALPHABET: &[u8] = b"ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789";
let mut bytes = [0u8; PASSWORD_LEN];
getrandom::fill(&mut bytes).map_err(|e| Error::io("the OS's random source", "read")(std::io::Error::other(e.to_string())))?;
Ok(bytes
.iter()
.filter_map(|b| ALPHABET.get(usize::from(*b) % ALPHABET.len()).copied().map(char::from))
.collect())
}
pub(crate) fn var(cx: &Cx<'_>) -> Result<Option<(String, String)>> {
let table = read(cx)?;
if table.is_empty() {
return Ok(None);
}
let text = serde_json::to_string(&table).map_err(|e| Error::io(CONSOLES, "written")(e.into()))?;
Ok(Some((CONSOLES.to_owned(), text)))
}
pub(crate) fn of(cx: &Cx<'_>, machine: &Machine) -> Result<(u16, SecretValue)> {
match read(cx)?.remove(machine.name.as_str()) {
Some(c) => Ok((c.port, SecretValue::new(c.password))),
None => Err(super::none(machine, "the runner chose none for it: it boots with one at the run's next start")),
}
}
pub(crate) fn forget(cx: &Cx<'_>) -> Result<()> {
crate::store::remove(&path(cx))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_password_is_eight_unambiguous_letters_and_digits() {
let a = password().unwrap();
assert_eq!(a.len(), PASSWORD_LEN);
assert!(a.chars().all(|c| c.is_ascii_alphanumeric() && !"0O1lI".contains(c)), "{a}");
assert_ne!(a, password().unwrap());
}
}