#[cfg(any(windows, test))]
mod acl;
mod db;
mod fs;
mod lock;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use serde::{Deserialize, Serialize};
#[cfg(test)]
pub(crate) use db::dead_pid;
pub use db::{
CopyName, Ended, EventCursor, EventPage, Lease, LeaseOutcome, Lifetime, MIRROR_FILE, NewResource, NotPerCopy, OperationId, OperationRow, Outcome, Owner,
PortReservation, Recovered, Reserver, ResourceId, ResourceKind, ResourceRow, ResourceState, RunRow, Scope, Store, Tx,
};
pub(crate) use fs::{create_private, if_there, private_dir, remove_path, write_private};
pub(crate) fn create_dir(dir: &Path) -> Result<()> {
private_dir(dir).map_err(Error::io(dir, "created"))
}
pub(crate) fn write(path: &Path, contents: &[u8]) -> Result<()> {
write_private(path, contents).map_err(Error::io(path, "written"))
}
pub(crate) fn remove(path: &Path) -> Result<()> {
remove_path(path).map_err(Error::io(path, "removed"))
}
pub(crate) fn read_json<T: serde::de::DeserializeOwned + Default>(path: &Path) -> Result<T> {
match if_there(std::fs::read_to_string(path)).map_err(Error::io(path, "read"))? {
Some(text) => serde_json::from_str(&text).map_err(|e| Error::io(path, "read")(std::io::Error::new(std::io::ErrorKind::InvalidData, e))),
None => Ok(T::default()),
}
}
pub(crate) fn write_json<T: Serialize>(path: &Path, value: &T) -> Result<()> {
if let Some(dir) = path.parent() {
create_dir(dir)?;
}
let json = serde_json::to_string(value).map_err(|e| Error::io(path, "written")(std::io::Error::other(e)))?;
write(path, json.as_bytes())
}
pub(crate) use lock::{RunLocks, hold};
use crate::Result;
use crate::error::{Error, ErrorCode};
use crate::events::EventLog;
use crate::name::RunName;
use crate::project::Format;
use crate::project::platform::{Cloud, Provider};
use crate::state::{Desired, Op, Park, RunState};
use crate::status::MachineStatus;
const RECORD_VERSION: u32 = 0;
const LOCK_FILE: &str = "lock";
pub(crate) const EVENTS_KEPT: usize = 4000;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct LastOp {
pub op: Op,
pub ok: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub code: Option<ErrorCode>,
pub at: String,
}
impl LastOp {
pub(crate) fn ended(op: Op, code: Option<ErrorCode>, at: String) -> LastOp {
LastOp {
op,
ok: code.is_none(),
code,
at,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct RunRecord {
pub version: u32,
pub name: RunName,
#[serde(alias = "manifest")]
pub project: PathBuf,
#[serde(alias = "driver")]
pub format: Format,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cloud: Option<Cloud>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub provider: Option<Provider>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub docker_context: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub host_label: Option<String>,
pub state: RunState,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub parked: Option<Park>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub started_at: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub expires_at: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub last: Option<LastOp>,
#[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
pub env: std::collections::BTreeMap<String, String>,
}
impl RunRecord {
#[must_use]
pub fn expired(&self, now: std::time::SystemTime) -> bool {
let now = crate::clock::unix_seconds(now);
self.state != RunState::Absent && self.expires_at.is_some_and(|at| at <= now)
}
pub(crate) fn fresh(name: RunName, project: PathBuf, format: Format) -> RunRecord {
RunRecord {
version: RECORD_VERSION,
name,
project,
format,
cloud: None,
provider: None,
docker_context: None,
host_label: None,
state: RunState::Absent,
parked: None,
started_at: None,
expires_at: None,
last: None,
env: std::collections::BTreeMap::new(),
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct LastObserved {
pub machines: Vec<MachineStatus>,
}
#[derive(Debug, Clone)]
pub(crate) struct Home {
runs: PathBuf,
db: Arc<Store>,
}
impl Home {
pub(crate) fn open(home: &Path, profile: Option<&Path>) -> Result<Home> {
fs::private_home(home, profile).map_err(Error::io(home, "made owner-only"))?;
let runs = home.join("runs");
create_dir(&runs)?;
let db = Arc::new(Store::open(home)?);
Ok(Home { runs, db })
}
pub(crate) fn run_dir(&self, name: &RunName) -> Result<PathBuf> {
let dir = self.run_dir_path(name);
create_dir(&dir)?;
Ok(dir)
}
pub(crate) fn run_dir_path(&self, name: &RunName) -> PathBuf {
self.runs.join(name.as_str())
}
pub(crate) fn lock_path(&self, name: &RunName) -> PathBuf {
self.run_dir_path(name).join(LOCK_FILE)
}
pub(crate) fn db(&self) -> &Arc<Store> {
&self.db
}
pub(crate) fn record(&self, name: &RunName) -> Result<Option<RunRecord>> {
Ok(self.db.read(|tx| tx.run(name))?.map(|r| r.record))
}
pub(crate) fn save(&self, record: &RunRecord) -> Result<()> {
self.run_dir(&record.name)?;
self.db.write(|tx| tx.save_record(record, Desired::Running))
}
pub(crate) fn save_adopted(&self, record: &RunRecord) -> Result<()> {
self.run_dir(&record.name)?;
self.db.write(|tx| {
tx.save_record(record, Desired::Running)?;
if let Some(row) = tx.run(&record.name)?
&& row.state != RunState::Ready
{
tx.apply(&record.name, crate::state::Transition::adopted(row.state)?)?;
}
Ok(())
})
}
pub(crate) fn records(&self) -> Result<Vec<RunRecord>> {
self.db.read(|tx| tx.runs().map(|rows| rows.into_iter().map(|r| r.record).collect()))
}
pub(crate) fn trim_event_log(&self, name: &RunName) -> Result<()> {
self.db.write(|tx| {
let (events, unreadable) = tx.events_after(EventCursor::default(), Some(name), EVENTS_KEPT + 1)?;
if events.len() + unreadable > EVENTS_KEPT {
tx.trim_events(name, EVENTS_KEPT / 2)?;
}
Ok(())
})
}
pub(crate) fn events(&self, name: &RunName) -> Result<EventLog> {
let (events, unreadable) = self.db.read(|tx| tx.events_after(EventCursor::default(), Some(name), usize::MAX))?;
Ok(EventLog {
events: events.into_iter().map(|(_, e)| e).collect(),
unreadable,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
fn record(name: &str) -> RunRecord {
RunRecord::fresh(RunName::new(name).unwrap(), "/work/x".into(), Format::Compose)
}
#[test]
fn records_are_kept_per_run_and_listed_by_name() {
let home = tempfile::tempdir().unwrap();
let store = Home::open(home.path(), None).unwrap();
assert_eq!(store.record(&RunName::new("b").unwrap()).unwrap(), None);
let mut b = record("b");
b.host_label = Some("server".into());
store.save(&b).unwrap();
store.save(&record("a")).unwrap();
let names: Vec<String> = store.records().unwrap().iter().map(|r| r.name.to_string()).collect();
assert_eq!(names, ["a", "b"]);
assert_eq!(store.record(&b.name).unwrap(), Some(b));
}
}