Files
leleka/control-plane/src/service_switch.rs
T

228 lines
8.2 KiB
Rust

//! Explicit transaction between installed native user services. Never replay an
//! interrupted lifecycle operation; retained phases require reconciliation.
use serde::Deserialize;
use serde_json::{Value, json};
use sha2::{Digest, Sha256};
use std::{
collections::BTreeMap,
path::{Path, PathBuf},
time::Duration,
};
const USAGE: &str =
"usage: strata-next service-switch --catalog FILE [--from ID] --to ID --state-dir ABSOLUTE_DIR";
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Catalog {
schema_version: u32,
profiles: BTreeMap<String, Profile>,
#[serde(default = "provision_budget")]
provision_timeout_s: u64,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Profile {
unit: String,
config: PathBuf,
working_dir: PathBuf,
url: String,
model: String,
key_file: Option<PathBuf>,
#[serde(default = "ready_budget")]
timeout_s: u64,
}
#[cfg(unix)]
mod storage {
use super::*;
use std::{
fs::{self, File, OpenOptions},
io::{Read, Write},
os::unix::fs::{DirBuilderExt, MetadataExt, OpenOptionsExt},
};
pub(super) fn read(path: &Path, private: bool, max: u64) -> Result<Vec<u8>, String> {
if !path.is_absolute() {
return Err("profile paths must be absolute".into());
}
let file = OpenOptions::new()
.read(true)
.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK)
.open(path)
.map_err(|_| "cannot open profile file")?;
let meta = file.metadata().map_err(|_| "cannot inspect profile file")?;
if !meta.is_file()
|| meta.uid() != unsafe { libc::geteuid() }
|| meta.mode() & if private { 0o077 } else { 0o022 } != 0
|| meta.len() > max
{
return Err(
"profile file must be owned, regular, bounded and have safe permissions".into(),
);
}
let mut bytes = Vec::new();
file.take(max + 1)
.read_to_end(&mut bytes)
.map_err(|_| "cannot read profile file")?;
if bytes.len() as u64 > max {
return Err("profile file exceeds limit".into());
}
Ok(bytes)
}
pub(super) fn digest(path: &Path) -> Result<String, String> {
Ok(hex::encode(Sha256::digest(read(path, false, 1024 * 1024)?)))
}
pub(super) struct Journal {
dir: PathBuf,
directory: File,
_lock: File,
pub(super) value: Value,
}
impl Journal {
pub(super) fn open(path: &Path, value: Value) -> Result<Self, String> {
Self::open_inner(path, value, false)
}
pub(super) fn reconciliation(path: &Path) -> Result<Self, String> {
read(&path.join("transaction.json"), true, 65536)?;
Self::open_inner(path, json!({}), true)
}
fn open_inner(path: &Path, value: Value, reconciliation: bool) -> Result<Self, String> {
create_state_directory(path)?;
let dir = path
.canonicalize()
.map_err(|_| "cannot resolve state directory")?;
let lock = open_lock(&dir)?;
check_prior_transaction(&dir, reconciliation)?;
let directory = File::open(&dir).map_err(|_| "cannot open state directory")?;
Ok(Self {
dir,
directory,
_lock: lock,
value,
})
}
pub(super) fn phase(&mut self, phase: &str) -> Result<(), String> {
self.value["phase"] = json!(phase);
let bytes =
serde_json::to_vec(&self.value).map_err(|_| "cannot encode switch journal")?;
let temp = self.dir.join(format!(
".transaction-{}-{}.tmp",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_err(|_| "invalid clock")?
.as_nanos()
));
if self.write_atomically(&temp, &bytes).is_err() {
let _ = fs::remove_file(&temp);
return Err(
"cannot durably record switch phase; no further action performed".into(),
);
}
Ok(())
}
/// Write `bytes` to `temp`, rename it over `transaction.json` and sync the directory.
fn write_atomically(&self, temp: &Path, bytes: &[u8]) -> std::io::Result<()> {
let mut file = OpenOptions::new()
.write(true)
.create_new(true)
.mode(0o600)
.open(temp)?;
file.write_all(bytes)?;
file.sync_all()?;
fs::rename(temp, self.dir.join("transaction.json"))?;
self.directory.sync_all()
}
}
/// The state directory exists (created private when absent), is owned, mode 0700 and not a symlink.
fn create_state_directory(path: &Path) -> Result<(), String> {
if !path.is_absolute() || path.file_name().is_none() {
return Err("state directory must be absolute and non-root".into());
}
match fs::DirBuilder::new().mode(0o700).create(path) {
Ok(()) => (),
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => (),
Err(_) => {
return Err("cannot create private state directory; parent must exist".into());
}
}
let m = fs::symlink_metadata(path).map_err(|_| "cannot inspect state directory")?;
if !m.is_dir()
|| m.file_type().is_symlink()
|| m.uid() != unsafe { libc::geteuid() }
|| m.mode() & 0o777 != 0o700
{
return Err("state directory must be owned, private mode0700 and not a symlink".into());
}
Ok(())
}
/// Take the exclusive switch lock of the state directory.
fn open_lock(dir: &Path) -> Result<File, String> {
let lock = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.mode(0o600)
.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK)
.open(dir.join("switch.lock"))
.map_err(|_| "cannot open switch lock")?;
let m = lock.metadata().map_err(|_| "cannot inspect switch lock")?;
if !m.is_file() || m.uid() != unsafe { libc::geteuid() } || m.mode() & 0o077 != 0 {
return Err("unsafe switch lock".into());
}
lock.try_lock()
.map_err(|_| "another switch is running or lock is unavailable")?;
Ok(lock)
}
/// A prior transaction must be finished (any phase when reconciling).
fn check_prior_transaction(dir: &Path, reconciliation: bool) -> Result<(), String> {
let previous = dir.join("transaction.json");
match fs::symlink_metadata(&previous) {
Err(e) if e.kind() == std::io::ErrorKind::NotFound => (),
Err(_) => return Err("cannot inspect prior transaction".into()),
Ok(_) => {
let prior: Value = serde_json::from_slice(&read(&previous, true, 65536)?)
.map_err(|_| "invalid prior transaction; reconcile explicitly")?;
if !reconciliation && !finished(&prior) {
return Err(concat!(
"unfinished or unknown switch transaction; inspect services and archive ",
"journal only after explicit reconciliation"
)
.into());
}
}
}
Ok(())
}
fn finished(prior: &Value) -> bool {
prior["schema_version"] == 1
&& matches!(
prior["phase"].as_str(),
Some(
"committed"
| "rolled_back"
| "preflight_failed"
| "cold_failed"
| "reused"
| "reconciled"
)
)
}
}
#[cfg(test)]
mod tests;
mod provision_budget;
#[allow(unused_imports)]
pub use provision_budget::*;
mod run;
#[allow(unused_imports)]
pub use run::*;
mod reconcile;
#[cfg(unix)]
mod transaction;
#[allow(unused_imports)]
pub use reconcile::*;