leleka-deploy: one env_settings reader, no dyn, supervisor and flows read time through the Clock port, explicit imports

glob-super-import 15 -> 0, env-read 41 -> 0 outside crates/deploy/src/env_settings.rs (typed accessors: home, PATH, tokens presence, route, distro; the LELEKA_* lookup is a fn pointer EnvLookup), dyn-trait 17 -> 0 (impl Fn / impl FnMut), instant-now 28 -> 0 (ServiceSupervisor holds an AnyClock, command flows use SystemClock of leleka-obs). Doc headers of the generated files are real sentences.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Pavlo Ratushnyi
2026-11-14 19:40:18 +01:00
co-authored by Claude Sonnet 5.5
parent af77c63fa3
commit e2e8b78abf
70 changed files with 368 additions and 211 deletions
+1 -1
View File
@@ -36,7 +36,7 @@ mod settings_change;
mod status_report;
mod stop_flow;
mod verify_flow;
pub use entry::{env_var, main_native, main_with, version_text};
pub use entry::{main_native, main_with, version_text};
pub use install_flow::{powershell_try, run_up, summary, summary_json, up};
pub use machine_view::render_machine;
#[cfg(unix)]
+6 -19
View File
@@ -1,10 +1,9 @@
//! The process entry: environment, version text, root check and the command dispatch of `main`.
use super::*;
pub fn env_var(name: &str) -> Option<String> {
std::env::var(name).ok().filter(|v| !v.is_empty())
}
use super::{
BUILTIN, Command, Environment, Profile, USAGE, down, parse, preflight, reconfigure, seal_probe, status, supervisor,
up, verify,
};
/// What `leleka version` prints: the first line stays `leleka VERSION` (scripts parse it); the rest is the build
/// identity embedded by `build.rs` (docs/release/5090-v0.1-checklist.md, section 3).
@@ -43,17 +42,6 @@ pub async fn main_with(args: Vec<String>) -> i32 {
main_native(args).await
}
pub(super) fn home_dir() -> Option<PathBuf> {
#[cfg(windows)]
{
std::env::var_os("USERPROFILE").map(PathBuf::from)
}
#[cfg(not(windows))]
{
std::env::var_os("HOME").map(PathBuf::from)
}
}
/// The commands on this host itself: systemd or foreground on Linux, foreground on Windows (`--native`).
pub async fn main_native(mut args: Vec<String>) -> i32 {
// `--hidden` (the logon task): hide the console window (the console itself stays, children stop through it).
@@ -63,11 +51,10 @@ pub async fn main_native(mut args: Vec<String>) -> i32 {
#[cfg(windows)]
crate::winsys::hide_console();
}
let var = env_var;
let environment = Environment {
root: is_root(),
home: home_dir(),
var: &var,
home: crate::env_settings::home_dir(),
var: crate::env_settings::lookup,
};
match parse(&args, &environment) {
Ok(command) => run_command(command).await,
+2 -2
View File
@@ -1,12 +1,12 @@
//! `leleka up`: run the plan, then print or serialize the summary of the installed service.
use super::{
Context, Mode, Step, StepState, UnitScopeTag, UpOptions, Value, env_var, gather, gather_fs, json, json_plan,
Context, Mode, Step, StepState, UnitScopeTag, UpOptions, Value, gather, gather_fs, json, json_plan,
plan_steps, print_report, render_plan, say, steps, supervisor,
};
pub async fn up(opts: UpOptions) -> i32 {
let ctx = gather(&opts, &env_var);
let ctx = gather(&opts, crate::env_settings::lookup);
if let Err(message) = &ctx.profile {
eprintln!("leleka: {message}");
return 1;
+3 -2
View File
@@ -1,5 +1,6 @@
//! Functions: `operator_figures`, `the_machine_view_names_every_figure_the_operator_asked_for`, `the_settings_block_...
//! Split out of `app` to keep its files under the line limit.
//! Unit tests of the machine view of `leleka status`: it names every figure the operator asked for (GPU, CPU, RAM,
//! throughput, cache, context), lists every settings member and the prefix cache on one line, and leaves out a block
//! that is missing instead of inventing it.
use super::render_machine;
use serde_json::json;
+4 -3
View File
@@ -1,12 +1,13 @@
//! `leleka preflight` and the sealed-archive probe: the host checks and the JSON plan.
use super::*;
use leleka_obs::time::{Clock as _, SystemClock};
use super::{Context, Report, Step, UpOptions, Value, gather, json};
/// `leleka seal-probe FILE`: the archive copy of `leleka run` on any file, and the proof that the memfd equals the
/// file.
#[cfg(unix)]
pub(super) fn seal_probe(file: &std::path::Path) -> i32 {
let started = std::time::Instant::now();
let started = SystemClock.now();
let (memfd, _identity, report) =
match crate::sealed::seal_file_report(file, None, &mut sealing_progress) {
Ok(done) => done,
@@ -120,7 +121,7 @@ pub(super) fn json_plan(ctx: &Context, steps: &[Step]) -> Value {
}
pub(super) async fn preflight(opts: UpOptions) -> i32 {
let ctx = gather(&opts, &env_var);
let ctx = gather(&opts, crate::env_settings::lookup);
match (&ctx.profile, &ctx.report) {
(Err(message), _) => {
eprintln!("leleka: {message}");
+2 -1
View File
@@ -1,5 +1,6 @@
//! `leleka reconfigure`: ask the supervisor, persist the settings or restart, and render the effective values.
use leleka_obs::time::{Clock as _, SystemClock};
use super::{PersistTarget, ReconfigureArgs, UpOptions, Value, json};
/// `leleka reconfigure`.
@@ -164,7 +165,7 @@ pub(super) async fn ask_supervisor(
) -> Result<crate::reconfigure::Outcome, String> {
use crate::reconfigure::{State, read_outcome, write_request};
write_request(paths, request)?;
let started = std::time::Instant::now();
let started = SystemClock.now();
let mut last = String::new();
loop {
tokio::time::sleep(std::time::Duration::from_millis(500)).await;
+2 -2
View File
@@ -1,10 +1,10 @@
//! `leleka status`: the installed scope, the supervisor document and its human rendering.
use super::{PathBuf, UnitScopeTag, UpOptions, Value, json, render_machine, steps, supervisor};
use super::{UnitScopeTag, UpOptions, Value, json, render_machine, steps, supervisor};
/// Which systemd unit of this deployment exists (system first), judged by the unit file.
pub(super) fn installed_scope(paths: &crate::layout::Paths) -> Option<UnitScopeTag> {
let home = std::env::var_os("HOME").map(PathBuf::from);
let home = crate::env_settings::home();
[UnitScopeTag::System, UnitScopeTag::User]
.into_iter()
.find(|scope| {
+2 -2
View File
@@ -1,5 +1,5 @@
//! Functions: `the_supervisor_part_of_status_shows_age_restarts_and_a_dead_supervisor`.
//! Split out of `app` to keep its files under the line limit.
//! Unit tests of the supervisor part of `leleka status`: it shows the phase, the age, the restarts and the health, and
//! warns when the status file is stale (a dead supervisor) but not when the supervisor stopped cleanly.
use super::*;
use serde_json::json;
+4 -2
View File
@@ -1,6 +1,8 @@
//! `leleka down`: stop the service (or the foreground supervisor) and wait for the drain.
use super::*;
#[cfg(windows)]
use leleka_obs::time::{Clock as _, SystemClock};
use super::{UnitScopeTag, UpOptions, installed_scope};
pub(super) async fn down(opts: UpOptions) -> i32 {
let paths = opts.dirs.paths();
@@ -64,7 +66,7 @@ pub async fn stop_foreground(paths: &crate::layout::Paths) -> i32 {
return 1;
}
eprintln!("leleka: stop requested: the API drains first, then the gateway and the engine");
let started = std::time::Instant::now();
let started = SystemClock.now();
while started.elapsed() < std::time::Duration::from_secs(120) {
tokio::time::sleep(std::time::Duration::from_secs(2)).await;
if !crate::plan::service_running(paths) {
+3 -2
View File
@@ -1,5 +1,6 @@
//! `leleka verify`: the quick offline check and the full verification against a running engine.
use leleka_obs::time::{Clock as _, SystemClock};
use super::quick_health::{Health, report_logs_and_requests, report_model_files, report_service};
use super::{PathBuf, UpOptions, say};
use crate::{config::RunConfig, layout::Paths};
@@ -43,7 +44,7 @@ pub(super) async fn verify(opts: UpOptions) -> i32 {
Err(code) => return code,
};
let tier_failed = tier_has_failed(&config, &paths);
let started = std::time::Instant::now();
let started = SystemClock.now();
say(concat!(
"hashing both shards (and the archive, when it is a file) in full, in parallel; ",
"this renews the stamps"
@@ -167,7 +168,7 @@ fn hash_and_stamp_archive(
if !memfd {
return Ok(None);
}
let begun = std::time::Instant::now();
let begun = SystemClock.now();
let file =
std::fs::File::open(kar).map_err(|e| format!("cannot open {}: {e}", kar.display()))?;
let before = file.metadata().ok().and_then(|m| FileIdentity::of(&m));
+2 -2
View File
@@ -1,5 +1,5 @@
//! Functions: `the_version_names_the_commit_and_the_strata_pin_and_keeps_the_first_line`.
//! Split out of `app` to keep its files under the line limit.
//! Unit test of the `leleka --version` text: it names the commit and the Strata pin and keeps the package version on
//! its first line.
use super::version_text;
@@ -1,6 +1,6 @@
//! The `leleka-cli` double: typed load, verify and shard fetch answers.
use super::*;
use super::{Duration, Path, alive, flag, fs};
pub(super) fn cli(fake: &Path, args: &[String]) {
let config: serde_json::Value = flag(args, "--config")
@@ -1,6 +1,6 @@
//! The `leleka-inference` double: its port, its pid file and its one-shot crash and failure switches.
use super::*;
use super::{Duration, Path, TcpListener, TcpStream, flag, fs};
pub(super) fn alive(address: &str) -> bool {
address
@@ -55,12 +55,12 @@ fn verify_only(fake: &Path) {
/// The token must be there, the Hugging Face token must not, and a refused budget stops the start.
fn check_environment(fake: &Path, args: &[String]) {
let token = std::env::var("LELEKA_RUNTIME_TOKEN").unwrap_or_default();
let token = leleka_deploy::env_settings::runtime_token();
if token.len() < 32 {
eprintln!("fake engine: LELEKA_RUNTIME_TOKEN missing");
std::process::exit(2);
}
if std::env::var_os("HF_TOKEN").is_some() {
if leleka_deploy::env_settings::hf_token_present() {
eprintln!("fake engine: HF_TOKEN leaked into the engine environment");
std::process::exit(3);
}
@@ -1,6 +1,7 @@
//! The gateway and API doubles: the strata process and its HTTP readiness answers.
use super::*;
use super::{Duration, Path, TcpListener, TcpStream, alive, fetch_shards, fs};
use std::io::{Read, Write};
pub(super) fn strata(fake: &Path, args: &[String]) {
let args: Vec<&str> = args.iter().map(String::as_str).collect();
@@ -95,11 +96,7 @@ pub(super) fn api(fake: &Path, config: &str) {
}
fn require_runtime_token() {
if std::env::var("LELEKA_RUNTIME_TOKEN")
.unwrap_or_default()
.len()
< 32
{
if leleka_deploy::env_settings::runtime_token().len() < 32 {
eprintln!("fake api: LELEKA_RUNTIME_TOKEN missing");
std::process::exit(2);
}
+2 -6
View File
@@ -7,7 +7,7 @@
//! `loaded`, `calls.log`, and the one-shot switches `crash-engine-once` / `fail-engine`.
use std::{
fs,
io::{Read, Write},
io::Write,
net::{TcpListener, TcpStream},
path::{Path, PathBuf},
time::Duration,
@@ -77,11 +77,7 @@ fn daemon(args: &[String]) {
.as_str()
.unwrap_or("127.0.0.1:0")
.to_owned();
if std::env::var("LELEKA_GATEWAY_TOKEN")
.unwrap_or_default()
.len()
< 32
{
if leleka_deploy::env_settings::gateway_token().len() < 32 {
eprintln!("fake daemon: LELEKA_GATEWAY_TOKEN missing");
std::process::exit(2);
}
+2 -2
View File
@@ -284,10 +284,10 @@ const UP_FLAGS: &[(&str, bool)] = &[
];
/// Environment access is injected so that parsing is testable.
pub struct Environment<'a> {
pub struct Environment {
pub root: bool,
pub home: Option<PathBuf>,
pub var: &'a dyn Fn(&str) -> Option<String>,
pub var: crate::env_settings::EnvLookup,
}
/// The settings flags of `leleka reconfigure` (member of the settings document, takes a value).
+4 -3
View File
@@ -1,7 +1,9 @@
//! The `logs`, `report` and `reconfigure` commands and the splitting of their flags.
use super::flag_parsing::{next_value, split_inline};
use super::*;
use super::{Command, Environment, Flags, RECONFIGURE_FLAGS, ReconfigureArgs, number, ranged, text, up_options};
#[cfg(test)]
use super::{Dirs, UpOptions};
/// The settings flags of a `reconfigure` command line: returns the other arguments (they locate the service) and the
/// JSON document the engine validates. Numbers stay numbers; the two cache members stay text.
@@ -185,13 +187,12 @@ pub(crate) fn tests_options(dirs: Dirs) -> UpOptions {
.iter()
.map(|s| (*s).to_owned())
.collect();
let var = |_: &str| None;
up_options(
&args,
&Environment {
root: false,
home: Some(dirs.state.clone()),
var: &var,
var: crate::env_settings::nothing,
},
)
.expect("test options")
+3 -3
View File
@@ -1,4 +1,5 @@
//! Unit tests of this module (split out of its file; the test ids are unchanged).
//! Unit tests of the `leleka` command-line parser: flag syntax and per-command flag tables, and the arguments of
//! `reconfigure`, parsed against a fake environment (root or not, home directory).
use super::*;
@@ -7,13 +8,12 @@ fn strings(items: &[&str]) -> Vec<String> {
}
fn parse_as(root: bool, args: &[&str]) -> Result<Command, String> {
let var = |_: &str| None;
parse(
&strings(args),
&Environment {
root,
home: Some("/home/para".into()),
var: &var,
var: crate::env_settings::nothing,
},
)
}
+2 -1
View File
@@ -1,4 +1,5 @@
//! Unit tests of this module (split out of its file; the test ids are unchanged).
//! Unit tests of the run configuration: the engine and verify command lines per profile, which profile switches reach
//! the engine environment (5090 profiles only), validation, JSON round trip, environment merge and token rules.
use super::*;
+137
View File
@@ -0,0 +1,137 @@
//! The one place of `leleka-deploy` that reads the process environment.
//!
//! Every variable the deploy tool looks at is named here with the type it is parsed into (a path, a flag, a token
//! presence, a text), so the operator's surface is one list and no other module reaches for `std::env`. The reads are
//! live (not a snapshot taken at start): the commands that spawn children set the child's environment themselves with
//! `Command::env`, and the tests that need other values pass a lookup function (`EnvLookup`) to the code that takes
//! one.
//!
//! The variables:
//!
//! * `HOME`, `USERPROFILE`, `LOCALAPPDATA`, `SystemRoot`, `USERNAME`, `USERDOMAIN`: the default directories, the
//! `.wslconfig` and `wsl.exe` lookups and the account of the Windows task;
//! * `PATH`, `LD_LIBRARY_PATH`: tool and CUDA library discovery and the child environment of the engine;
//! * `HF_TOKEN`: the preflight (presence only; the value is never read) and the fake engine's leak check;
//! * `LELEKA_ROUTE`, `LELEKA_WSL_DISTRO`: the Windows front end's route and WSL distribution;
//! * `LELEKA_RUNTIME_TOKEN`, `LELEKA_GATEWAY_TOKEN`: the test doubles' check that the supervisor passed the credential;
//! * any name: [`lookup`] (the `LELEKA_*` overrides of `leleka up`) and [`operator_var`] (the extents pin).
use std::{ffi::OsString, path::PathBuf};
/// A lookup of one variable by name: the process environment in `main`, a fixed table in the tests.
pub type EnvLookup = fn(&str) -> Option<String>;
/// The value of `name`, `None` when it is unset, not Unicode or empty (the `LELEKA_*` overrides of `leleka up`).
pub fn lookup(name: &str) -> Option<String> {
std::env::var(name).ok().filter(|v| !v.is_empty())
}
/// The value of `name` as the operator set it (an empty value is a value), `None` when unset or not Unicode.
pub fn operator_var(name: &str) -> Option<String> {
std::env::var(name).ok()
}
/// The home directory of this platform: `USERPROFILE` on Windows, `HOME` elsewhere.
pub fn home_dir() -> Option<PathBuf> {
#[cfg(windows)]
{
user_profile()
}
#[cfg(not(windows))]
{
home()
}
}
/// `HOME` (the Unix home directory, the systemd user unit directory).
pub fn home() -> Option<PathBuf> {
std::env::var_os("HOME").map(PathBuf::from)
}
/// `USERPROFILE` (the Windows profile folder, where `.wslconfig` lives).
pub fn user_profile() -> Option<PathBuf> {
std::env::var_os("USERPROFILE").map(PathBuf::from)
}
/// The home directory as text, `HOME` first and `USERPROFILE` second (the report replaces it by `~`).
pub fn home_text() -> Option<String> {
std::env::var("HOME")
.or_else(|_| std::env::var("USERPROFILE"))
.ok()
}
/// `LOCALAPPDATA` (the Windows per-user data folder), `None` in a session that does not set it.
pub fn local_app_data() -> Option<PathBuf> {
std::env::var_os("LOCALAPPDATA").map(PathBuf::from)
}
/// `SystemRoot` (`C:\Windows`).
pub fn system_root() -> Option<PathBuf> {
std::env::var_os("SystemRoot").map(PathBuf::from)
}
/// `PATH` as the OS string, `None` when unset.
pub fn search_path() -> Option<OsString> {
std::env::var_os("PATH")
}
/// `PATH` as text, empty when unset or not Unicode (the prefix of a child's `PATH`).
pub fn search_path_text() -> String {
std::env::var("PATH").unwrap_or_default()
}
/// `LD_LIBRARY_PATH` as the OS string, `None` when unset.
pub fn library_path() -> Option<OsString> {
std::env::var_os("LD_LIBRARY_PATH")
}
/// `LD_LIBRARY_PATH` as text, empty when unset or not Unicode (the suffix of a child's loader path).
pub fn library_path_text() -> String {
std::env::var("LD_LIBRARY_PATH").unwrap_or_default()
}
/// Is `HF_TOKEN` set to something? Only the presence is ever read: the token itself is the model downloader's.
pub fn hf_token_set() -> bool {
std::env::var_os("HF_TOKEN").is_some_and(|v| !v.is_empty())
}
/// Is `HF_TOKEN` set at all (empty counts)? The fake engine uses it to prove the supervisor did not forward it.
pub fn hf_token_present() -> bool {
std::env::var_os("HF_TOKEN").is_some()
}
/// `LELEKA_ROUTE` (`wsl` or `native`), `None` when unset or not Unicode.
pub fn route() -> Option<String> {
std::env::var("LELEKA_ROUTE").ok()
}
/// `LELEKA_WSL_DISTRO` as set (an empty value is kept: the caller decides what empty means).
pub fn wsl_distro() -> Option<String> {
std::env::var("LELEKA_WSL_DISTRO").ok()
}
/// `USERNAME`, `"user"` when unset.
pub fn user_name() -> String {
std::env::var("USERNAME").unwrap_or_else(|_| "user".into())
}
/// `USERDOMAIN`, `None` when unset or not Unicode.
pub fn user_domain() -> Option<String> {
std::env::var("USERDOMAIN").ok()
}
/// The runtime credential the supervisor hands the engine and the API (`LELEKA_RUNTIME_TOKEN`), empty when unset.
pub fn runtime_token() -> String {
std::env::var("LELEKA_RUNTIME_TOKEN").unwrap_or_default()
}
/// The gateway credential (`LELEKA_GATEWAY_TOKEN`), empty when unset.
pub fn gateway_token() -> String {
std::env::var("LELEKA_GATEWAY_TOKEN").unwrap_or_default()
}
/// An environment with no variables: parsing that must not depend on the process (`leleka reconfigure` flag
/// reading, the unit tests).
pub fn nothing(_name: &str) -> Option<String> {
None
}
@@ -94,7 +94,7 @@ pub(super) fn commit(part: &Path, dest: &Path, expected: &str) -> Result<Option<
/// (`--expert-profile-file PATH`, `--no-expert-tier`). Nothing unverified is ever left at `dest`.
pub fn provision(
request: &Request,
fetch: &mut dyn FnMut(&str, &Path) -> Result<(), String>,
fetch: &mut impl FnMut(&str, &Path) -> Result<(), String>,
) -> Result<Outcome, String> {
if file_state(request.dest, request.expected) == FileState::Valid {
return Ok(Outcome::AlreadyPresent);
+2 -1
View File
@@ -1,4 +1,5 @@
//! Unit tests of this module (split out of its file; the test ids are unchanged).
//! Unit tests of the expert-usage table handling: the embedded table, the "expert tier ON/OFF" report and the sources
//! the table is taken from, over a small fixture table whose digest stands in for the pinned one.
use super::*;
use std::cell::RefCell;
+3 -3
View File
@@ -13,7 +13,7 @@ fn read(path: &str) -> String {
}
fn which(name: &str, extra: &[&str]) -> Option<PathBuf> {
let path = std::env::var_os("PATH").unwrap_or_default();
let path = crate::env_settings::search_path().unwrap_or_default();
std::env::split_paths(&path)
.chain(extra.iter().map(PathBuf::from))
.map(|dir| dir.join(name))
@@ -51,7 +51,7 @@ pub fn probe(request: &ProbeRequest) -> Facts {
os: std::env::consts::OS.to_owned(),
arch: std::env::consts::ARCH.to_owned(),
root: rustix::process::geteuid().is_root(),
hf_token_set: std::env::var_os("HF_TOKEN").is_some_and(|v| !v.is_empty()),
hf_token_set: crate::env_settings::hf_token_set(),
lab_holder: lab_holder_running(),
..Facts::default()
};
@@ -137,7 +137,7 @@ fn probe_libraries(facts: &mut Facts, request: &ProbeRequest) {
.map(|o| String::from_utf8_lossy(&o.stdout).into_owned())
.unwrap_or_default();
let mut library_dirs: Vec<PathBuf> = request.extra_library_dirs.clone();
if let Some(paths) = std::env::var_os("LD_LIBRARY_PATH") {
if let Some(paths) = crate::env_settings::library_path() {
library_dirs.extend(std::env::split_paths(&paths).filter(|p| !p.as_os_str().is_empty()));
}
for fixed in [
+5 -1
View File
@@ -1,6 +1,10 @@
//! Parsers of what the host tools print (nvidia-smi, meminfo, mounts, loader) and the Gpu and Facts accessors.
use super::*;
use super::{BTreeMap, Facts, Gpu, Memory, Path, PathBuf, ProbeRequest};
#[cfg(target_os = "linux")]
use super::linux;
#[cfg(windows)]
use super::windows;
impl Gpu {
pub fn driver_major(&self) -> Option<u32> {
+2 -1
View File
@@ -1,4 +1,5 @@
//! Unit tests of this module (split out of its file; the test ids are unchanged).
//! Unit tests of the host fact parsers: `nvidia-smi` CSV, `/proc/meminfo`, WSL and cgroup detection, filesystem type by
//! mount prefix, CUDA library lookup, the env-file format and the physical core count.
use super::*;
+12 -12
View File
@@ -1,12 +1,15 @@
//! Windows probe of the host facts: nvidia-smi, memory, ports and the CUDA libraries on PATH.
use super::*;
use super::{
DirFact, Facts, Path, PathBuf, ProbeRequest, WINDOWS_LIBRARIES, WINDOWS_NVIDIA_SMI_DIRS, find_in_dirs,
parse_meminfo, parse_nvidia_smi,
};
use leleka_memory::ProcSource;
use leleka_memory_os::HostProc;
use std::{net::TcpListener, process::Command};
fn nvidia_smi() -> Option<PathBuf> {
let path = std::env::var_os("PATH").unwrap_or_default();
let path = crate::env_settings::search_path().unwrap_or_default();
let mut dirs: Vec<PathBuf> = std::env::split_paths(&path).collect();
dirs.extend(WINDOWS_NVIDIA_SMI_DIRS.iter().map(PathBuf::from));
find_in_dirs("nvidia-smi.exe", &dirs)
@@ -25,7 +28,7 @@ pub fn probe(request: &ProbeRequest) -> Facts {
let mut facts = Facts {
os: "windows".to_owned(),
arch: std::env::consts::ARCH.to_owned(),
hf_token_set: std::env::var_os("HF_TOKEN").is_some_and(|v| !v.is_empty()),
hf_token_set: crate::env_settings::hf_token_set(),
..Facts::default()
};
// The memory governor's Win32 view, rendered as /proc/meminfo: available = available physical memory,
@@ -93,20 +96,17 @@ fn probe_libraries(facts: &mut Facts, request: &ProbeRequest) {
}
// Where `scripts/windows/fetch-cublas.ps1` puts the two cuBLAS DLLs.
// LOCALAPPDATA is not set in every kind of terminal or service session: fall back to the profile folder.
let local = std::env::var_os("LOCALAPPDATA")
.map(PathBuf::from)
.or_else(|| {
std::env::var_os("USERPROFILE")
.map(|home| PathBuf::from(home).join("AppData").join("Local"))
});
let local = crate::env_settings::local_app_data().or_else(|| {
crate::env_settings::user_profile().map(|home| home.join("AppData").join("Local"))
});
if let Some(local) = local {
library_dirs.push(local.join("leleka").join("cublas").join("bin"));
}
if let Some(paths) = std::env::var_os("PATH") {
if let Some(paths) = crate::env_settings::search_path() {
library_dirs.extend(std::env::split_paths(&paths).filter(|p| !p.as_os_str().is_empty()));
}
if let Some(root) = std::env::var_os("SystemRoot") {
library_dirs.push(PathBuf::from(root).join("System32"));
if let Some(root) = crate::env_settings::system_root() {
library_dirs.push(root.join("System32"));
}
for (soname, dll) in WINDOWS_LIBRARIES {
facts
+7 -9
View File
@@ -65,7 +65,7 @@ pub struct Dirs {
impl Dirs {
/// Defaults: root gets `/opt/leleka`, `/var/lib/leleka`; a user gets XDG-style directories under `$HOME`.
/// Environment overrides: `LELEKA_PREFIX`, `LELEKA_STATE`, `LELEKA_ASSETS`.
pub fn defaults(root: bool, home: Option<&Path>, env: &dyn Fn(&str) -> Option<String>) -> Dirs {
pub fn defaults(root: bool, home: Option<&Path>, env: impl Fn(&str) -> Option<String>) -> Dirs {
#[cfg(windows)]
{
let _ = root;
@@ -93,7 +93,7 @@ impl Dirs {
fn unix_defaults(
root: bool,
home: Option<&Path>,
env: &dyn Fn(&str) -> Option<String>,
env: impl Fn(&str) -> Option<String>,
) -> Dirs {
let pick = |name: &str, fallback: PathBuf| env(name).map(PathBuf::from).unwrap_or(fallback);
if root {
@@ -243,8 +243,7 @@ mod tests {
#[cfg(windows)]
#[test]
fn windows_defaults_live_under_the_profile() {
let none = |_: &str| None;
let dirs = Dirs::defaults(false, Some(Path::new("C:\\Users\\para")), &none);
let dirs = Dirs::defaults(false, Some(Path::new("C:\\Users\\para")), crate::env_settings::nothing);
assert_eq!(
dirs.state,
PathBuf::from("C:\\Users\\para\\AppData\\Local\\leleka\\state")
@@ -253,7 +252,7 @@ mod tests {
dirs.prefix,
PathBuf::from("C:\\Users\\para\\AppData\\Local\\leleka")
);
let overridden = Dirs::defaults(false, None, &|name| match name {
let overridden = Dirs::defaults(false, None, |name| match name {
"LOCALAPPDATA" => Some("D:\\Local".to_owned()),
"LELEKA_ASSETS" => Some("E:\\models".to_owned()),
_ => None,
@@ -267,12 +266,11 @@ mod tests {
#[cfg(unix)]
#[test]
fn defaults_follow_the_user() {
let none = |_: &str| None;
let root = Dirs::defaults(true, None, &none);
let root = Dirs::defaults(true, None, crate::env_settings::nothing);
assert_eq!(root.prefix, PathBuf::from("/opt/leleka"));
let user = Dirs::defaults(false, Some(Path::new("/home/para")), &none);
let user = Dirs::defaults(false, Some(Path::new("/home/para")), crate::env_settings::nothing);
assert_eq!(user.state, PathBuf::from("/home/para/.local/state/leleka"));
let overridden = Dirs::defaults(false, Some(Path::new("/home/para")), &|name| {
let overridden = Dirs::defaults(false, Some(Path::new("/home/para")), |name| {
(name == "LELEKA_ASSETS").then(|| "/data/leleka".to_owned())
});
assert_eq!(overridden.assets, PathBuf::from("/data/leleka"));
+1
View File
@@ -7,6 +7,7 @@ pub mod app;
pub mod cli;
pub mod config;
pub mod doctor;
pub mod env_settings;
pub mod expert_profile;
pub mod facts;
pub mod http;
+5 -4
View File
@@ -1,6 +1,9 @@
//! `leleka report`: host facts, install and service summaries and the report file.
use super::*;
use super::{
Entry, Filter, Level, Path, PathBuf, ReportArgs, ReportInputs, UpOptions, Value, Write, build_report, collect,
format_utc_ms, json, now_ms, recent_requests, redact,
};
pub(super) fn host_facts() -> Value {
let facts = crate::facts::probe(&crate::facts::ProbeRequest::default());
@@ -97,9 +100,7 @@ fn expert_tier_value(c: &crate::config::RunConfig) -> Value {
/// The home directory, which the report replaces by `~`.
fn home_directory() -> Option<String> {
std::env::var("HOME")
.or_else(|_| std::env::var("USERPROFILE"))
.ok()
crate::env_settings::home_text()
}
/// The newest 50 warning and error entries of the logs.
+3 -1
View File
@@ -1,4 +1,6 @@
//! Unit tests of this module (split out of its file; the test ids are unchanged).
//! Unit tests of `leleka logs` and `leleka report`: parsing of old and new log lines, reading rotated generations,
//! the filters, joining the API record and the engine line of a request, the summary, scrubbing of credentials, and
//! the opt-in report that holds no secret, no text and no home directory.
use super::*;
+8 -4
View File
@@ -1,6 +1,10 @@
//! Read the host state (installed files, service, expert profile) into the planning context.
use super::*;
use super::{
BINARIES, BTreeMap, CUBLAS_BYTES, Context, ExpertProfileState, Facts, KarSource, Manifest, Mode, ModeChoice, Needs,
Path, PathBuf, Paths, ProbeRequest, Profile, Report, RunConfig, UnitScopeTag, UpOptions, evaluate,
missing_asset_bytes, probe, resolve, resolve_mode,
};
pub(super) fn current_bin_dir() -> PathBuf {
std::env::current_exe()
@@ -49,11 +53,11 @@ pub(super) fn process_alive(pid: u64) -> bool {
u32::try_from(pid).is_ok_and(crate::winsys::process_alive)
}
pub(super) fn user_session_available(var: &dyn Fn(&str) -> Option<String>) -> bool {
pub(super) fn user_session_available(var: crate::env_settings::EnvLookup) -> bool {
var("XDG_RUNTIME_DIR").is_some_and(|dir| Path::new(&dir).join("systemd").exists())
}
pub fn gather(opts: &UpOptions, var: &dyn Fn(&str) -> Option<String>) -> Context {
pub fn gather(opts: &UpOptions, var: crate::env_settings::EnvLookup) -> Context {
let paths = opts.dirs.paths();
let bin_src = opts.bin_src.clone().unwrap_or_else(current_bin_dir);
let installed = paths.bin_dir();
@@ -167,7 +171,7 @@ fn chosen_mode(opts: &UpOptions) -> ModeChoice {
}
}
fn service_user_of(opts: &UpOptions, mode: &Mode, var: impl Fn(&str) -> Option<String>) -> String {
fn service_user_of(opts: &UpOptions, mode: &Mode, var: crate::env_settings::EnvLookup) -> String {
if matches!(mode, Mode::Systemd(UnitScopeTag::System)) {
opts.service_user
.clone()
+3 -3
View File
@@ -1,4 +1,5 @@
//! Unit tests of this module (split out of its file; the test ids are unchanged).
//! Unit tests of the deployment plan: which steps `up` plans for the expert profile, for an install, and how the
//! mode is resolved, over a finished host by default.
use super::*;
use crate::{
@@ -8,7 +9,6 @@ use crate::{
};
fn options(extra: &[&str]) -> UpOptions {
let var = |_: &str| None;
let mut args: Vec<String> = vec![
"up".into(),
"--assets".into(),
@@ -24,7 +24,7 @@ fn options(extra: &[&str]) -> UpOptions {
&Environment {
root: true,
home: None,
var: &var,
var: crate::env_settings::nothing,
},
)
.unwrap()
@@ -141,7 +141,7 @@ fn the_gathered_environment_names_the_table_unless_the_tier_is_opted_out() {
args.extend_from_slice(extra);
let mut opts = options(&args);
opts.dirs.assets = dir.clone();
gather(&opts, &|_| None)
gather(&opts, crate::env_settings::nothing)
};
// The table is absent: the configuration still names it (the step provisions it before the configuration is
// written).
+2 -1
View File
@@ -1,4 +1,5 @@
//! Unit tests of this module (split out of its file; the test ids are unchanged).
//! Unit tests of the preflight checks: GPU and driver, host resources (RAM, disk, libraries, tools) and the Windows
//! host, each judged as pass, warn or fail with a fix, over server facts.
use super::*;
use crate::facts::{DirFact, Memory};
+1 -1
View File
@@ -114,7 +114,7 @@ pub const SPARSE_MEMFD_BYTES_ESTIMATE: u64 = 16_000_348_672;
/// --hash-extents` on an archive that matched its full pinned SHA-256). The second form is explicitly experimental and
/// is logged as such.
pub fn extents_sha256(
env: &dyn Fn(&str) -> Option<String>,
env: impl Fn(&str) -> Option<String>,
) -> Result<([u8; 32], PinSource), String> {
let compiled = leleka_model_format::kar::PLE_EXTENTS_SHA256;
if compiled != [0u8; 32] {
+2 -1
View File
@@ -1,4 +1,5 @@
//! Unit tests of this module (split out of its file; the test ids are unchanged).
//! Unit tests of the memory profiles: the built-in profiles, profile selection by GPU, the budget arguments and the
//! sparse memfd form of the KAR source.
use super::*;
@@ -122,7 +122,7 @@ fn pin_environment(value: &str) -> impl Fn(&str) -> Option<String> {
fn check_an_unmeasured_pin_needs_an_explicit_value() {
// not measured yet: the sparse form refuses to start without an explicit value, and says how to get one
let with = pin_environment;
let error = extents_sha256(&|_: &str| None).unwrap_err();
let error = extents_sha256(crate::env_settings::nothing).unwrap_err();
assert!(
error.contains("kar_census") && error.contains("--hash-extents"),
"{error}"
@@ -142,7 +142,7 @@ fn check_an_unmeasured_pin_needs_an_explicit_value() {
fn check_a_measured_pin_wins_over_the_environment(compiled: [u8; 32]) {
// measured: the binary's value wins and an environment value cannot override it
assert_eq!(
extents_sha256(&|_: &str| None).unwrap(),
extents_sha256(crate::env_settings::nothing).unwrap(),
(compiled, PinSource::Compiled)
);
assert_eq!(
+2 -1
View File
@@ -1,4 +1,5 @@
//! Unit tests of this module (split out of its file; the test ids are unchanged).
//! Unit tests of `leleka reconfigure`: the plan for a changed setting on a big host, the recording of the change, and
//! the ranges each setting accepts.
use super::*;
use crate::{config::Ports, facts::Memory, layout::Dirs, profile::KarSource};
+2 -1
View File
@@ -1,4 +1,5 @@
//! Unit tests of this module (split out of its file; the test ids are unchanged).
//! Unit tests of the resource presets: the plan per preset and worker count, how it fits the host RAM, and the Windows
//! presets, on the 5090 server and the 3080 laptop profiles.
use super::*;
use crate::facts::Memory;
+8 -7
View File
@@ -1,5 +1,6 @@
//! The Linux sealing of the KAR archive: a sealed memfd, the sparse extent copy and the exec of the engine.
use leleka_obs::time::{Clock as _, SystemClock};
use super::substitute;
use leleka_model_format::{kar::Extent, verify_stamp::FileIdentity};
use rustix::fs::{MemfdFlags, SealFlags, fcntl_add_seals, fcntl_get_seals, memfd_create};
@@ -33,7 +34,7 @@ const COPY_CHUNK: usize = 32 << 20;
pub fn seal_file(
path: &Path,
expect_bytes: Option<u64>,
progress: &mut dyn FnMut(u64, u64),
progress: &mut impl FnMut(u64, u64),
) -> Result<File, String> {
seal_file_with_identity(path, expect_bytes, progress).map(|(file, _)| file)
}
@@ -44,7 +45,7 @@ pub fn seal_file(
pub fn seal_file_with_identity(
path: &Path,
expect_bytes: Option<u64>,
progress: &mut dyn FnMut(u64, u64),
progress: &mut impl FnMut(u64, u64),
) -> Result<(File, Option<FileIdentity>), String> {
seal_file_report(path, expect_bytes, progress).map(|(file, identity, _)| (file, identity))
}
@@ -53,7 +54,7 @@ pub fn seal_file_with_identity(
pub fn seal_file_report(
path: &Path,
expect_bytes: Option<u64>,
progress: &mut dyn FnMut(u64, u64),
progress: &mut impl FnMut(u64, u64),
) -> Result<
(
File,
@@ -75,7 +76,7 @@ pub fn seal_extents(
path: &Path,
expect_bytes: Option<u64>,
extents: &[Extent],
progress: &mut dyn FnMut(u64, u64),
progress: &mut impl FnMut(u64, u64),
) -> Result<(File, Option<FileIdentity>), String> {
seal_extents_report(path, expect_bytes, extents, progress)
.map(|(file, identity, _)| (file, identity))
@@ -86,7 +87,7 @@ pub fn seal_extents_report(
path: &Path,
expect_bytes: Option<u64>,
extents: &[Extent],
progress: &mut dyn FnMut(u64, u64),
progress: &mut impl FnMut(u64, u64),
) -> Result<
(
File,
@@ -130,7 +131,7 @@ fn seal_ranges(
path: &Path,
expect_bytes: Option<u64>,
extents: Option<&[Extent]>,
progress: &mut dyn FnMut(u64, u64),
progress: &mut impl FnMut(u64, u64),
) -> SealedArchive {
let (source, metadata) = open_archive(path, expect_bytes)?;
let identity_before = FileIdentity::of(&metadata);
@@ -283,7 +284,7 @@ pub fn exec_inherit(args: &[String]) -> Result<Infallible, String> {
/// pinned digest of the extents).
pub fn seal_exec(args: &[String]) -> Result<Infallible, String> {
let plan = super::parse_seal_exec(args)?;
let started = std::time::Instant::now();
let started = SystemClock.now();
let progress = |done: u64, total: u64| {
eprintln!(
"leleka seal-exec: {:.1} of {:.1} GiB",
+2 -1
View File
@@ -1,4 +1,5 @@
//! Unit tests of this module (split out of its file; the test ids are unchanged).
//! Unit tests of the Linux sealing: a memfd that is exactly sealed, unlinked and close-on-exec, the byte-exact
//! parallel fill, the sparse copy of extents (and the extents it refuses), and the exec inheritance.
use super::*;
use std::io::Write;
+2 -1
View File
@@ -1,4 +1,5 @@
//! Unit tests of this module (split out of its file; the test ids are unchanged).
//! Unit tests of the sealed KAR archive: strict parsing of the seal-exec arguments, the extents of the pinned archive,
//! placeholder substitution, and which memfd a sparse or full profile accepts.
use super::*;
+4 -4
View File
@@ -4,7 +4,7 @@
pub fn seal_file(
_path: &std::path::Path,
_expect_bytes: Option<u64>,
_progress: &mut dyn FnMut(u64, u64),
_progress: &mut impl FnMut(u64, u64),
) -> Result<std::fs::File, String> {
Err("sealed memfd archives require Linux".into())
}
@@ -13,7 +13,7 @@ pub fn seal_file(
pub fn seal_file_with_identity(
_path: &std::path::Path,
_expect_bytes: Option<u64>,
_progress: &mut dyn FnMut(u64, u64),
_progress: &mut impl FnMut(u64, u64),
) -> Result<
(
std::fs::File,
@@ -28,7 +28,7 @@ pub fn seal_file_with_identity(
pub fn seal_file_report(
_path: &std::path::Path,
_expect_bytes: Option<u64>,
_progress: &mut dyn FnMut(u64, u64),
_progress: &mut impl FnMut(u64, u64),
) -> Result<
(
std::fs::File,
@@ -45,7 +45,7 @@ pub fn seal_extents_report(
_path: &std::path::Path,
_expect_bytes: Option<u64>,
_extents: &[leleka_model_format::kar::Extent],
_progress: &mut dyn FnMut(u64, u64),
_progress: &mut impl FnMut(u64, u64),
) -> Result<
(
std::fs::File,
+4 -1
View File
@@ -1,6 +1,9 @@
//! The model assets: shards, KAR archive, MTP pack, tokenizer and configs.
use super::*;
use super::{
ARCHIVE_BYTES, Context, MANIFEST, MTP_FILES, Path, PathBuf, mtp_complete, render_configs, run_tool, say,
stamp_path, write_private, write_secrets_and_env, write_stamp,
};
pub async fn fetch_and_verify_model(ctx: &Context) -> Result<(), String> {
let strata = ctx.paths.bin("strata-next");
+3 -2
View File
@@ -1,7 +1,8 @@
//! Preparing and re-planning the steps of `up`.
use leleka_obs::time::{Clock as _, SystemClock};
use super::{
Changes, Context, Instant, RunConfig, Step, StepState, ensure_kar, extract_tokenizer, fetch_and_verify_model,
Changes, Context, RunConfig, Step, StepState, ensure_kar, extract_tokenizer, fetch_and_verify_model,
gather_fs, import_mtp_pack, init_api_key, install_binaries, install_cublas, kar_runs_tool, make_dirs, plan_steps,
provision_expert_profile, say, write_configs, write_secrets_and_env,
};
@@ -14,7 +15,7 @@ pub async fn prepare(ctx: &Context, steps: &[Step]) -> Result<Changes, String> {
continue;
}
say(&format!("[{}/{}] {}", index + 1, total, step.title));
let started = Instant::now();
let started = SystemClock.now();
let result: Result<(), String> = if step.id == "secrets" {
prepare_secrets(ctx).await?
} else {
+1 -1
View File
@@ -45,7 +45,7 @@ pub async fn fetch_status_with_key(key: &str, api: &str) -> Option<serde_json::V
}
pub fn unit_text(ctx: &Context, scope: UnitScopeTag) -> Result<(PathBuf, String), String> {
let home = std::env::var_os("HOME").map(PathBuf::from);
let home = crate::env_settings::home();
let text = units::render(
scope.scope(),
&ctx.opts.dirs.prefix,
+4 -3
View File
@@ -1,5 +1,6 @@
//! The service user, the systemd unit, the start and the readiness wait.
use leleka_obs::time::{Clock as _, SystemClock};
use super::{
ARCHIVE_BYTES, Changes, Command, Context, Duration, Instant, Mode, Path, Stdio, Step, StepState, UnitScopeTag,
probe_ready, run_tool, say, unit_text,
@@ -141,10 +142,10 @@ pub async fn start_unit(
/// Poll `/ready`, printing the supervisor's phase every 15 s. Fails fast when the unit or supervisor failed.
pub async fn wait_ready(ctx: &Context, scope: Option<UnitScopeTag>) -> Result<(), String> {
let started = Instant::now();
let started = SystemClock.now();
let limit = Duration::from_secs(ctx.opts.timeout_s);
let mut last_phase = String::new();
let mut last_print = Instant::now() - Duration::from_secs(60);
let mut last_print = SystemClock.now() - Duration::from_secs(60);
loop {
if probe_ready(ctx).await {
return Ok(());
@@ -157,7 +158,7 @@ pub async fn wait_ready(ctx: &Context, scope: Option<UnitScopeTag>) -> Result<()
if phase != last_phase || last_print.elapsed() >= Duration::from_secs(30) {
say_waiting(&phase, started);
last_phase = phase;
last_print = Instant::now();
last_print = SystemClock.now();
}
if started.elapsed() > limit {
return Err(format!(
+2 -1
View File
@@ -1,4 +1,5 @@
//! Unit tests of this module (split out of its file; the test ids are unchanged).
//! Unit tests of the plan steps: verification stamps (size and mtime), finding the MTP pack root, provisioning the
//! pinned table from upstream and failing closed when a source answers something else, and SHA-256 of a file.
use super::*;
+3
View File
@@ -15,6 +15,7 @@ use crate::{
reconfigure, sealed, watchdog,
};
use leleka_model_format::verify_stamp::{FileIdentity, VerifyStamps};
use leleka_obs::time::{AnyClock, Clock};
use serde::Serialize;
use std::{
collections::BTreeMap,
@@ -149,6 +150,8 @@ struct ServiceSupervisor {
restarts_total: u32,
last_restart: Option<(u64, String)>,
health_note: String,
/// The monotonic clock of the supervision loop and the waits; tests pass a manual one.
clock: AnyClock,
}
/// The file `leleka down` creates on Windows (there is no signal to send to a supervisor in another console).
+2 -2
View File
@@ -1,10 +1,10 @@
//! The public API process: readiness wait, answers to the operator and restart.
use super::{Child, ChildSpec, Duration, Flow, Instant, ServiceSupervisor, fail, http, reconfigure};
use super::{Child, ChildSpec, Clock, Duration, Flow, ServiceSupervisor, fail, http, reconfigure};
impl ServiceSupervisor {
pub(super) async fn wait_api_ready(&mut self, api: &mut Child) -> Result<(), Flow> {
let started = Instant::now();
let started = self.clock.now();
loop {
if self.stopping() {
return Err(Flow::Stopped);
+4 -4
View File
@@ -1,7 +1,7 @@
//! The sealed archive the engine inherits: opened from a descriptor, copied into a memfd, or absent.
use super::{
ARCHIVE_BYTES, Child, Failure, File, FileIdentity, Flow, Instant, KarSource, MemfdExtents, Path, Phase,
Clock, ARCHIVE_BYTES, Child, Failure, File, FileIdentity, Flow, Instant, KarSource, MemfdExtents, Path, Phase,
ServiceSupervisor, archive_sha256, fail, sealed,
};
@@ -61,7 +61,7 @@ impl ServiceSupervisor {
let allocated = sealed::inherited_archive_allocated_bytes(fd)
.map_err(|message| Flow::Fatal(Failure { code: 2, message }))?;
let allow_full_copy =
Self::operator_env(sealed::ALLOW_FULL_MEMFD_ENV).as_deref() == Some("1");
crate::env_settings::operator_var(sealed::ALLOW_FULL_MEMFD_ENV).as_deref() == Some("1");
let form = self.config.profile.memfd_extents;
sealed::single_copy_verdict(form, allocated, allow_full_copy)
.or_else(|message| fail(2, message))?;
@@ -84,7 +84,7 @@ impl ServiceSupervisor {
None => None,
};
self.announce_sealing(&kar, extents.as_deref());
let started = Instant::now();
let started = self.clock.now();
let mut preverify = self.spawn_shard_preverify();
let source = self.source_state(&kar);
let sealed = self.copy_archive(&kar, extents.as_deref());
@@ -164,7 +164,7 @@ impl ServiceSupervisor {
let Some(child) = preverify else {
return Ok(());
};
let waited = Instant::now();
let waited = self.clock.now();
match child.wait().await {
Ok(status) if status.success() => {
self.log.line(&format!(
+6 -3
View File
@@ -1,6 +1,9 @@
//! Spawning, pausing and killing the child processes (gateway, engine, API).
use super::*;
use super::{
BTreeMap, Child, Command, Duration, File, Flow, GATEWAY_TOKEN_ENV, Path, RUNTIME_TOKEN_ENV, ServiceSupervisor,
Stdio, fail, interrupt, private_append, sleep, timeout,
};
/// Windows: the long-lived children (engine, gateway, API) get their own process group, so that Ctrl-C typed in the
/// supervisor's terminal reaches only the supervisor, which then stops them in order with Ctrl-Break (`interrupt`).
@@ -74,7 +77,7 @@ impl ServiceSupervisor {
// The loader flags of the engine search the application directory and System32 plus the directories named
// here (`leleka-libc-shim` registers them), so the cuBLAS DLLs can stay where the operator keeps them.
command.env(leleka_libc_shim_dll_dirs_env(), extra_path);
let existing = std::env::var("PATH").unwrap_or_default();
let existing = crate::env_settings::search_path_text();
command.env("PATH", format!("{extra_path};{existing}"));
}
}
@@ -82,7 +85,7 @@ impl ServiceSupervisor {
#[cfg(not(windows))]
fn library_path_env(&self, command: &mut Command) {
if let Some(extra_path) = self.env.get("LD_LIBRARY_PATH") {
let existing = std::env::var("LD_LIBRARY_PATH").unwrap_or_default();
let existing = crate::env_settings::library_path_text();
let joined = if existing.is_empty() {
extra_path.clone()
} else {
+3 -3
View File
@@ -1,7 +1,7 @@
//! Starting the engine, waiting for its port, the `leleka-cli` calls and recovering a dead engine.
use super::{
BTreeMap, Child, ChildSpec, Command, Duration, Failure, File, FileIdentity, Flow, Instant, KarArg, KarSource,
Clock, BTreeMap, Child, ChildSpec, Command, Duration, Failure, File, FileIdentity, Flow, Instant, KarArg, KarSource,
Phase, ServiceSupervisor, SocketAddr, Stdio, archive_sha256, fail, timeout, unix_now,
};
@@ -128,7 +128,7 @@ impl ServiceSupervisor {
what: &str,
limit: Duration,
) -> Result<(), Flow> {
let started = Instant::now();
let started = self.clock.now();
loop {
if self.stopping() {
return Err(Flow::Stopped);
@@ -214,7 +214,7 @@ impl ServiceSupervisor {
if let Some(child) = self.try_start_engine(gateway).await? {
*engine = child;
self.set_phase(Phase::Ready, "ready (engine restarted)");
*ready_since = Instant::now();
*ready_since = self.clock.now();
return Ok(());
}
}
+5 -5
View File
@@ -1,7 +1,7 @@
//! Loading the model into a started engine through `leleka-cli` and waiting until it is ready.
use super::{
Child, Duration, Flow, Instant, OPERATION_FAILED, OPERATION_INDETERMINATE, Phase, ServiceSupervisor, fail,
Child, Clock, Duration, Flow, Instant, OPERATION_FAILED, OPERATION_INDETERMINATE, Phase, ServiceSupervisor, fail,
parse_operation, parse_operation_state, parse_runtime_status, tail_of,
};
@@ -28,7 +28,7 @@ impl ServiceSupervisor {
/// The gateway connects to the engine lazily; wait until it reports the runtime connected.
async fn wait_gateway_connected(&mut self, engine: &mut Child, id: &str) -> Result<(), Flow> {
let started = Instant::now();
let started = self.clock.now();
loop {
if self.stopping() {
return Err(Flow::Stopped);
@@ -83,8 +83,8 @@ impl ServiceSupervisor {
id: &str,
operation: Option<&Operation>,
) -> Result<(), Flow> {
let started = Instant::now();
let mut last_report = Instant::now();
let started = self.clock.now();
let mut last_report = self.clock.now();
loop {
if self.stopping() {
return Err(Flow::Stopped);
@@ -99,7 +99,7 @@ impl ServiceSupervisor {
}
self.check_load_progress(id, operation, started).await?;
if last_report.elapsed() >= Duration::from_secs(30) {
last_report = Instant::now();
last_report = self.clock.now();
self.say_still_loading(started);
}
if !self.pause(Duration::from_secs(3)).await {
+7
View File
@@ -80,6 +80,13 @@ pub fn write_private(path: &Path, contents: &str) -> std::io::Result<()> {
std::fs::rename(tmp, path)
}
impl Log {
/// The log of a supervisor that writes to `file`.
pub(super) fn new(file: File) -> Self {
Log {
file: std::sync::Mutex::new(file),
}
}
/// A free-text note of the supervisor (the text is the message of a `msg` event).
pub(super) fn line(&self, message: &str) {
self.event(leleka_obs::Level::Info, "msg", &[("msg", message.into())]);
+1 -1
View File
@@ -1,6 +1,6 @@
//! Stop requests (SIGTERM/SIGINT, Ctrl-C, a stop file) and the interrupt sent to a child.
use super::*;
use super::{Child, PathBuf, watch};
pub(super) fn spawn_signal_task(stop: watch::Sender<bool>, run_dir: PathBuf) {
#[cfg(windows)]
+1 -7
View File
@@ -45,19 +45,13 @@ impl ServiceSupervisor {
}
}
/// The operator's environment as the supervisor sees it: the one place that reads it (the extents pin and the
/// single-copy override).
pub(super) fn operator_env(key: &str) -> Option<String> {
std::env::var(key).ok()
}
/// The pin of the extents when the profile asks for a sparse memfd (`None` for the full copy); refuses to start
/// without one.
pub(super) fn sparse_pin(&self) -> Result<Option<[u8; 32]>, Flow> {
if self.config.profile.memfd_extents != MemfdExtents::PleOnly {
return Ok(None);
}
match extents_sha256(&Self::operator_env) {
match extents_sha256(crate::env_settings::operator_var) {
Ok((pin, source)) => {
self.log.line(&format!(
"memfd_extents=ple_only: only the byte ranges the serve path reads are in the sealed memfd; the \
+7 -4
View File
@@ -1,6 +1,10 @@
//! Entry of `leleka run`: build the supervisor, seal the archive and run until a stop request.
use super::*;
use super::{
AnyClock, BTreeMap, Failure, File, Flow, GATEWAY_TOKEN_ENV, Log, Options, Paths, Phase, RUNTIME_TOKEN_ENV,
RunConfig, ServiceSupervisor, SocketAddr, VerifyStamps, open_log, parse_env_file, spawn_signal_task, unix_now,
valid_token, watch,
};
pub async fn run(options: Options) -> i32 {
match run_inner(options).await {
@@ -151,15 +155,14 @@ struct Assembly {
impl ServiceSupervisor {
fn assemble(parts: Assembly, addresses: (SocketAddr, SocketAddr, SocketAddr)) -> Self {
ServiceSupervisor {
clock: AnyClock::default(),
status_path: parts.paths.status_file(),
stamps: VerifyStamps::new(parts.paths.engine_stamps(), false),
config: parts.config,
paths: parts.paths,
env: parts.env,
api_key: parts.api_key,
log: Log {
file: std::sync::Mutex::new(parts.log_file),
},
log: Log::new(parts.log_file),
shutdown: parts.shutdown,
archive: None,
source_identity: None,
+13 -12
View File
@@ -1,8 +1,8 @@
//! The supervision loop of a running service and its health sampling.
use super::{
Child, ChildSpec, Duration, Flow, Instant, Phase, RunConfig, ServiceSupervisor, fail, http, logs, reconfigure,
unix_now, watchdog,
Child, ChildSpec, Clock, Duration, Flow, Instant, Phase, RunConfig, ServiceSupervisor, fail, http, logs,
reconfigure, unix_now, watchdog,
};
use std::process::ExitStatus;
@@ -52,17 +52,18 @@ fn skipping_interval(period: Duration) -> tokio::time::Interval {
}
impl Running {
fn new(config: &RunConfig, engine: Child, gateway: Child, api: Child) -> Self {
fn new(config: &RunConfig, now: Instant, children: [Child; 3]) -> Self {
let health = config.health.clone();
let [engine, gateway, api] = children;
Self {
engine,
gateway,
api,
ready_since: Instant::now(),
ready_since: now,
gateway_restarts: 0,
api_restarts: 0,
gateway_since: Instant::now(),
api_since: Instant::now(),
gateway_since: now,
api_since: now,
stable: Duration::from_secs(config.restart.stable_after_s),
requests: skipping_interval(Duration::from_secs(1)),
logs_tick: skipping_interval(Duration::from_secs(10)),
@@ -155,7 +156,7 @@ impl ServiceSupervisor {
self.config.profile.name,
self.paths.logs().display()
));
Ok(Running::new(&self.config, engine, gateway, api))
Ok(Running::new(&self.config, self.clock.now(), [engine, gateway, api]))
}
/// The public API; the engine and the gateway are stopped when it does not come up.
@@ -215,7 +216,7 @@ impl ServiceSupervisor {
.await
{
Ok(()) => {
r.ready_since = Instant::now();
r.ready_since = self.clock.now();
r.watchdog.reset();
Step::Go
}
@@ -254,7 +255,7 @@ impl ServiceSupervisor {
async fn on_health_tick(&mut self, r: &mut Running) -> Step {
let sample = self.sample_health().await;
match r.watchdog.observe(Instant::now(), &sample) {
match r.watchdog.observe(self.clock.now(), &sample) {
watchdog::Verdict::Healthy => {
self.note_health("healthy");
Step::Go
@@ -280,7 +281,7 @@ impl ServiceSupervisor {
self.log.event(leleka_obs::Level::Warn, "restart", &fields);
self.restarts_total += 1;
self.last_restart = Some((unix_now(), why));
r.api_since = Instant::now();
r.api_since = self.clock.now();
let result = self.restart_api(&mut r.api).await;
r.recovered(result)
}
@@ -317,7 +318,7 @@ impl ServiceSupervisor {
}
r.gateway = self.spawn_gateway()?;
self.pids[1] = r.gateway.id();
r.gateway_since = Instant::now();
r.gateway_since = self.clock.now();
Ok(Step::Go)
}
@@ -340,7 +341,7 @@ impl ServiceSupervisor {
}
r.api = self.spawn_api()?;
self.pids[2] = r.api.id();
r.api_since = Instant::now();
r.api_since = self.clock.now();
Ok(Step::Go)
}
+2 -1
View File
@@ -1,4 +1,5 @@
//! Unit tests of this module (split out of its file; the test ids are unchanged).
//! Unit tests of the foreground supervisor: UTC formatting, parsing of the gateway status document and of operation
//! records from CLI output, log tail and rotation, the token rule, and atomic private (mode 0600) file writes.
use super::*;
+2 -1
View File
@@ -1,5 +1,6 @@
//! The Windows front's `status`, `reconfigure` and `down`.
use leleka_obs::time::{Clock as _, SystemClock};
use super::{
Bridge, Duration, PathBuf, Session, StatusReport, Value, fetch_status_with_key, forward, linux_to_unc, note,
open_session, print_status, probe_ready_with_key, send_reconfigure, split_reconfigure,
@@ -221,7 +222,7 @@ fn running_supervisor(bridge: &Bridge, state_dir: &str) -> Option<u64> {
/// Wait up to two minutes for the supervisor to exit after the SIGINT.
async fn wait_until_gone(bridge: &Bridge, pid_text: &str) -> i32 {
let started = std::time::Instant::now();
let started = SystemClock.now();
while started.elapsed() < Duration::from_secs(120) {
tokio::time::sleep(Duration::from_secs(2)).await;
if bridge.capture("kill", &["-0", pid_text]).is_err() {
+3 -4
View File
@@ -14,7 +14,7 @@ fn gib(bytes: u64) -> String {
/// `leleka doctor [--assets DIR]`: everything this machine tells about the two routes, then what is missing and the one
/// command that fixes the first missing thing.
pub(super) async fn doctor(args: &[String]) -> i32 {
let home = std::env::var_os("USERPROFILE").map(PathBuf::from);
let home = crate::env_settings::user_profile();
let paths = doctor_dirs(home.as_deref(), args).paths();
let exe_dir = std::env::current_exe()
.ok()
@@ -45,8 +45,7 @@ pub(super) async fn doctor(args: &[String]) -> i32 {
/// The default directories with the `--assets` of the command line.
fn doctor_dirs(home: Option<&Path>, args: &[String]) -> crate::layout::Dirs {
let var = |name: &str| std::env::var(name).ok().filter(|v| !v.is_empty());
let mut dirs = crate::layout::Dirs::defaults(false, home, &var);
let mut dirs = crate::layout::Dirs::defaults(false, home, crate::env_settings::lookup);
apply_assets_flag(&mut dirs, args);
dirs
}
@@ -159,7 +158,7 @@ fn print_distros(wsl: &Path) -> Option<bool> {
Ok(list) => list,
};
print_distro_list(&list);
match pick_distro(&list, std::env::var("LELEKA_WSL_DISTRO").ok().as_deref()) {
match pick_distro(&list, crate::env_settings::wsl_distro().as_deref()) {
Err(message) => {
println!(" chosen {message}");
None
+8 -14
View File
@@ -27,11 +27,9 @@ pub fn split_route(
}
pub(super) fn local_app_data() -> PathBuf {
std::env::var_os("LOCALAPPDATA")
.map(PathBuf::from)
crate::env_settings::local_app_data()
.or_else(|| {
std::env::var_os("USERPROFILE")
.map(|home| PathBuf::from(home).join("AppData").join("Local"))
crate::env_settings::user_profile().map(|home| home.join("AppData").join("Local"))
})
.unwrap_or_else(|| PathBuf::from("."))
}
@@ -43,14 +41,13 @@ pub(super) fn note(message: &str) {
/// Is a native (Windows) supervisor of the default state directory alive? Decides the route of `status`/`down` when no
/// flag is given.
pub(super) fn native_service_alive() -> bool {
let var = |name: &str| std::env::var(name).ok().filter(|v| !v.is_empty());
let home = std::env::var_os("USERPROFILE").map(PathBuf::from);
let dirs = crate::layout::Dirs::defaults(false, home.as_deref(), &var);
let home = crate::env_settings::user_profile();
let dirs = crate::layout::Dirs::defaults(false, home.as_deref(), crate::env_settings::lookup);
crate::plan::service_running(&dirs.paths())
}
pub async fn dispatch(args: &[String]) -> Option<i32> {
let env_route = std::env::var("LELEKA_ROUTE").ok();
let env_route = crate::env_settings::route();
let (explicit, args) = match split_route(args, env_route.as_deref()) {
Ok(pair) => pair,
Err(message) => {
@@ -129,9 +126,8 @@ fn default_route(command: &str, have_wsl: bool) -> Route {
/// Has `leleka up --native` written a run configuration in the default state directory?
pub(super) fn native_prepared() -> bool {
let var = |name: &str| std::env::var(name).ok().filter(|v| !v.is_empty());
let home = std::env::var_os("USERPROFILE").map(PathBuf::from);
crate::layout::Dirs::defaults(false, home.as_deref(), &var)
let home = crate::env_settings::user_profile();
crate::layout::Dirs::defaults(false, home.as_deref(), crate::env_settings::lookup)
.paths()
.run_config()
.is_file()
@@ -218,9 +214,7 @@ fn service_without_session(action: crate::cli::ServiceAction, message: &str) ->
/// The distribution named by the flags or the environment, else the one of the last `up`.
fn requested_distro(args: &[String], saved: Option<&BridgeState>) -> Option<String> {
// The distribution can be named before the other flags are translated (UNC paths name it too).
let mut requested = std::env::var("LELEKA_WSL_DISTRO")
.ok()
.filter(|v| !v.is_empty());
let mut requested = crate::env_settings::wsl_distro().filter(|v| !v.is_empty());
let mut iter = args.iter();
while let Some(arg) = iter.next() {
if let Some(value) = arg
+5 -5
View File
@@ -1,7 +1,7 @@
//! A session with the WSL bridge: routing a command, forwarding it and announcing readiness.
use super::{
Bridge, BridgeState, Duration, PathBuf, ProbeRequest, Session, Value, down, effective_wsl_memory, is_drvfs,
Bridge, BridgeState, Duration, ProbeRequest, Session, Value, down, effective_wsl_memory, is_drvfs,
linux_to_unc, local_app_data, note, open_session, parse_wslconfig, probe, probe_ready_with_key, reconfigure,
status, wslconfig_advice,
};
@@ -46,8 +46,8 @@ pub(super) fn wslconfig_note(wanted_gib: u32) -> Option<String> {
if host_total == 0 {
return None;
}
let text = std::env::var_os("USERPROFILE")
.map(|home| PathBuf::from(home).join(".wslconfig"))
let text = crate::env_settings::user_profile()
.map(|home| home.join(".wslconfig"))
.and_then(|path| std::fs::read_to_string(path).ok())
.unwrap_or_default();
wslconfig_advice(&parse_wslconfig(&text), host_total, wanted_gib)
@@ -104,8 +104,8 @@ fn note_wsl_memory() {
note(&format!("note: {advice}"));
return;
}
let have = std::env::var_os("USERPROFILE")
.map(|home| PathBuf::from(home).join(".wslconfig"))
let have = crate::env_settings::user_profile()
.map(|home| home.join(".wslconfig"))
.and_then(|path| std::fs::read_to_string(path).ok())
.map(|text| {
effective_wsl_memory(
+2 -1
View File
@@ -1,4 +1,5 @@
//! Unit tests of this module (split out of its file; the test ids are unchanged).
//! Unit test of the route choice of `leleka.exe`: the route flag wins over the environment and is removed from the
//! arguments forwarded to the engine side.
use super::*;
+3 -3
View File
@@ -16,9 +16,9 @@ fn note(message: &str) {
/// `DOMAIN\user` of the account that runs the command.
pub fn current_user() -> String {
let user = std::env::var("USERNAME").unwrap_or_else(|_| "user".into());
match std::env::var("USERDOMAIN") {
Ok(domain) if !domain.is_empty() => format!("{domain}\\{user}"),
let user = crate::env_settings::user_name();
match crate::env_settings::user_domain() {
Some(domain) if !domain.is_empty() => format!("{domain}\\{user}"),
_ => user,
}
}
+2 -2
View File
@@ -35,8 +35,8 @@ fn note_missing_unit(distro: &str) {
/// Where the task definition is written before `schtasks` reads it.
fn task_xml_dir() -> std::path::PathBuf {
std::env::var_os("LOCALAPPDATA")
.map(|d| std::path::PathBuf::from(d).join("leleka"))
crate::env_settings::local_app_data()
.map(|d| d.join("leleka"))
.unwrap_or_else(|| std::path::PathBuf::from("."))
}
+3 -3
View File
@@ -99,14 +99,14 @@ impl BridgeState {
/// Locations of `wsl.exe` to try after `PATH`.
pub fn wsl_exe() -> Option<PathBuf> {
let from_path = std::env::var_os("PATH").and_then(|paths| {
let from_path = crate::env_settings::search_path().and_then(|paths| {
std::env::split_paths(&paths)
.map(|dir| dir.join("wsl.exe"))
.find(|candidate| candidate.is_file())
});
from_path.or_else(|| {
let root = std::env::var_os("SystemRoot")?;
let candidate = PathBuf::from(root).join("System32").join("wsl.exe");
let root = crate::env_settings::system_root()?;
let candidate = root.join("System32").join("wsl.exe");
candidate.is_file().then_some(candidate)
})
}
+2 -1
View File
@@ -1,4 +1,5 @@
//! Unit tests of this module (split out of its file; the test ids are unchanged).
//! Unit tests of the WSL2 front end: decoding of UTF-16 `wsl.exe` output, picking the distribution, translation of
//! Windows, Linux and DrvFs paths and of forwarded arguments, `.wslconfig` advice, and the bridge state file.
use super::*;
+2 -3
View File
@@ -42,7 +42,6 @@ pub(crate) fn up_options_with(
profile: &str,
extra: &[&str],
) -> UpOptions {
let var = |_: &str| None;
let mut args = up_arguments(fixture, sources, profile);
args.extend(extra.iter().map(|s| s.to_string()));
match parse(
@@ -50,7 +49,7 @@ pub(crate) fn up_options_with(
&Environment {
root: false,
home: Some(fixture.root.clone()),
var: &var,
var: leleka_deploy::env_settings::nothing,
},
)
.unwrap()
@@ -93,7 +92,7 @@ fn up_arguments(fixture: &Fixture, sources: UpSources<'_>, profile: &str) -> Vec
/// A host that passes the preflight, whatever machine runs the test.
pub(crate) fn healthy_context(opts: &UpOptions) -> Context {
let mut ctx = gather(opts, &|_| None);
let mut ctx = gather(opts, leleka_deploy::env_settings::nothing);
let gpu = Gpu {
index: 0,
name: "NVIDIA GeForce RTX 3080 Laptop GPU".into(),