Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
702 lines
29 KiB
Rust
702 lines
29 KiB
Rust
//! `leleka.exe` on Windows: the commands of the WSL2 route (`up`, `preflight`, `verify`, `status`, `reconfigure`, `down`,
|
|
//! `doctor`). `dispatch` returns `None` for everything that the ordinary (native) command code handles.
|
|
//!
|
|
//! The Linux `leleka` inside the distribution does the deployment work, exactly as it does on a Linux host; this file only
|
|
//! starts it through `wsl.exe`, translates paths, and reads state and talks to the engine from the Windows side.
|
|
use crate::{
|
|
app::{print_status, send_reconfigure},
|
|
cli::split_reconfigure,
|
|
facts::{ProbeRequest, probe},
|
|
steps::{fetch_status_with_key, probe_ready_with_key},
|
|
wsl::{
|
|
Bridge, BridgeState, Forwarded, effective_wsl_memory, is_drvfs, linux_to_unc, list_distros, parse_wslconfig, pick_distro,
|
|
translate_args, wsl_exe, wslconfig_advice,
|
|
},
|
|
};
|
|
use serde_json::Value;
|
|
use std::{path::PathBuf, time::Duration};
|
|
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
pub enum Route {
|
|
Wsl,
|
|
Native,
|
|
}
|
|
|
|
/// Remove `--wsl` / `--native` from `args`; the flag wins over `LELEKA_ROUTE`.
|
|
pub fn split_route(args: &[String], env_route: Option<&str>) -> Result<(Option<Route>, Vec<String>), String> {
|
|
let mut route = match env_route {
|
|
Some("wsl") => Some(Route::Wsl),
|
|
Some("native") => Some(Route::Native),
|
|
Some("") | None => None,
|
|
Some(other) => return Err(format!("LELEKA_ROUTE must be wsl or native, not {other:?}")),
|
|
};
|
|
let mut rest = Vec::new();
|
|
for arg in args {
|
|
match arg.as_str() {
|
|
"--wsl" => route = Some(Route::Wsl),
|
|
"--native" => route = Some(Route::Native),
|
|
_ => rest.push(arg.clone()),
|
|
}
|
|
}
|
|
Ok((route, rest))
|
|
}
|
|
|
|
fn local_app_data() -> PathBuf {
|
|
std::env::var_os("LOCALAPPDATA")
|
|
.map(PathBuf::from)
|
|
.or_else(|| std::env::var_os("USERPROFILE").map(|home| PathBuf::from(home).join("AppData").join("Local")))
|
|
.unwrap_or_else(|| PathBuf::from("."))
|
|
}
|
|
|
|
fn note(message: &str) {
|
|
eprintln!("leleka: {message}");
|
|
}
|
|
|
|
/// Is a native (Windows) supervisor of the default state directory alive? Decides the route of `status`/`down` when no flag is given.
|
|
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);
|
|
crate::plan::service_running(&dirs.paths())
|
|
}
|
|
|
|
pub async fn dispatch(args: &[String]) -> Option<i32> {
|
|
let env_route = std::env::var("LELEKA_ROUTE").ok();
|
|
let (explicit, args) = match split_route(args, env_route.as_deref()) {
|
|
Ok(pair) => pair,
|
|
Err(message) => {
|
|
note(&message);
|
|
return Some(2);
|
|
}
|
|
};
|
|
let command = args.first()?.clone();
|
|
match command.as_str() {
|
|
"doctor" => return Some(doctor(&args[1..]).await),
|
|
"up" | "preflight" | "verify" | "status" | "reconfigure" | "down" | "service" => {}
|
|
_ => return None,
|
|
}
|
|
let have_wsl = wsl_exe().is_some();
|
|
let route = match explicit {
|
|
Some(route) => route,
|
|
None if !have_wsl => Route::Native,
|
|
// A service is installed for the route that was prepared: the WSL bridge state, unless a native configuration exists.
|
|
None if command == "service" => {
|
|
if BridgeState::read(&local_app_data()).is_some() && !native_prepared() {
|
|
Route::Wsl
|
|
} else {
|
|
Route::Native
|
|
}
|
|
}
|
|
None if matches!(command.as_str(), "status" | "reconfigure" | "down") && native_service_alive() => Route::Native,
|
|
None => Route::Wsl,
|
|
};
|
|
if route == Route::Native {
|
|
// The ordinary command code, with the route flags removed.
|
|
let rest: Vec<String> = args.clone();
|
|
return Some(crate::app::main_native(rest).await);
|
|
}
|
|
if !have_wsl {
|
|
note("wsl.exe was not found; install WSL2 (`wsl --install -d Ubuntu`) or use --native");
|
|
return Some(1);
|
|
}
|
|
if command == "service" {
|
|
return Some(service_wsl(&args[1..]).await);
|
|
}
|
|
Some(wsl_route(&command, &args[1..]).await)
|
|
}
|
|
|
|
/// Has `leleka up --native` written a run configuration in the default state directory?
|
|
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).paths().run_config().is_file()
|
|
}
|
|
|
|
async fn service_wsl(args: &[String]) -> i32 {
|
|
use crate::cli::ServiceAction;
|
|
let action = match args.first().map(String::as_str) {
|
|
Some("install") => ServiceAction::Install,
|
|
Some("uninstall") => ServiceAction::Uninstall,
|
|
Some("status") => ServiceAction::Status,
|
|
Some("start") => ServiceAction::Start,
|
|
Some("stop") => ServiceAction::Stop,
|
|
Some("hold") => ServiceAction::Hold,
|
|
_ => {
|
|
note("usage: leleka service install|uninstall|status|start|stop [--wsl-distro NAME]");
|
|
return 2;
|
|
}
|
|
};
|
|
let hidden = args.iter().any(|a| a == "--hidden");
|
|
let rest: Vec<String> = args[1..].iter().filter(|a| *a != "--hidden").cloned().collect();
|
|
if action == ServiceAction::Install && args.iter().any(|a| a == "--dry-run") {
|
|
let exe = std::env::current_exe().map(|p| p.display().to_string()).unwrap_or_else(|_| "leleka.exe".into());
|
|
let spec = crate::service::wsl_task(&exe, "<distribution>", &crate::winservice::current_user());
|
|
println!(
|
|
"--dry-run: nothing is changed. In the distribution: `systemctl --user enable {}`; on Windows: `schtasks /Create /TN {} /XML <file> /F` with this task definition:
|
|
{}",
|
|
crate::service::WSL_UNIT,
|
|
spec.name,
|
|
crate::service::task_xml(&spec)
|
|
);
|
|
return 0;
|
|
}
|
|
let begin = matches!(action, ServiceAction::Install | ServiceAction::Start | ServiceAction::Hold);
|
|
match open_session(&rest, begin) {
|
|
Ok(session) => crate::winservice::run_wsl(action, &session.bridge, hidden).await,
|
|
Err(message) => match action {
|
|
ServiceAction::Status => {
|
|
println!("unit {}: {message}", crate::service::WSL_UNIT);
|
|
crate::winservice::print_task_state(crate::service::WSL_TASK);
|
|
1
|
|
}
|
|
ServiceAction::Uninstall => {
|
|
match crate::winservice::schtasks(&["/Delete", "/TN", crate::service::WSL_TASK, "/F"]) {
|
|
Ok(_) => println!("removed the task {}", crate::service::WSL_TASK),
|
|
Err(why) => note(&format!("task not removed: {why}")),
|
|
}
|
|
0
|
|
}
|
|
_ => {
|
|
note(&message);
|
|
1
|
|
}
|
|
},
|
|
}
|
|
}
|
|
|
|
struct Session {
|
|
bridge: Bridge,
|
|
home: String,
|
|
forwarded: Forwarded,
|
|
saved: Option<BridgeState>,
|
|
}
|
|
|
|
/// Choose the distribution, translate the arguments. `start` is false for read-only commands: they must not boot a stopped VM.
|
|
fn open_session(args: &[String], start: bool) -> Result<Session, String> {
|
|
let wsl = wsl_exe().ok_or("wsl.exe was not found")?;
|
|
let saved = BridgeState::read(&local_app_data());
|
|
// 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 iter = args.iter();
|
|
while let Some(arg) = iter.next() {
|
|
if let Some(value) = arg.strip_prefix("--wsl-distro=").or_else(|| arg.strip_prefix("--distro=")) {
|
|
requested = Some(value.to_owned());
|
|
} else if arg == "--wsl-distro" || arg == "--distro" {
|
|
requested = iter.next().cloned();
|
|
}
|
|
}
|
|
if requested.is_none() {
|
|
requested = saved.as_ref().map(|s| s.distro.clone());
|
|
}
|
|
let list = list_distros(&wsl)?;
|
|
let distro = pick_distro(&list, requested.as_deref())?;
|
|
let running = list.iter().any(|d| d.name == distro && d.state.eq_ignore_ascii_case("running"));
|
|
if !start && !running {
|
|
return Err(format!(
|
|
"the WSL distribution {distro} is not running, so neither is the engine (start it with `leleka up`)"
|
|
));
|
|
}
|
|
let bridge = Bridge { wsl, distro: distro.clone() };
|
|
let home = bridge.home()?;
|
|
let forwarded = translate_args(args, &distro, Some(&home))?;
|
|
Ok(Session { bridge, home, forwarded, saved })
|
|
}
|
|
|
|
impl Session {
|
|
fn state_dir(&self) -> String {
|
|
self.forwarded
|
|
.state_dir
|
|
.clone()
|
|
.or_else(|| self.saved.as_ref().map(|s| s.state_dir.clone()))
|
|
.unwrap_or_else(|| format!("{}/.local/state/leleka", self.home))
|
|
}
|
|
|
|
/// The API address: the engine's own `leleka.json` when readable, else the saved one, else the flag or the default.
|
|
fn api(&self, state_dir: &str) -> String {
|
|
self.bridge
|
|
.read_file(&format!("{state_dir}/leleka.json"))
|
|
.and_then(|text| serde_json::from_str::<Value>(&text).ok())
|
|
.and_then(|doc| doc["ports"]["api"].as_str().map(str::to_owned))
|
|
.or_else(|| self.saved.as_ref().map(|s| s.api.clone()))
|
|
.unwrap_or_else(|| format!("127.0.0.1:{}", self.forwarded.api_port.unwrap_or(8081)))
|
|
}
|
|
|
|
fn key_unc(&self, state_dir: &str) -> String {
|
|
linux_to_unc(&self.bridge.distro, &format!("{state_dir}/api-key"))
|
|
}
|
|
}
|
|
|
|
async fn wsl_route(command: &str, args: &[String]) -> i32 {
|
|
match command {
|
|
"up" | "preflight" | "verify" => forward(command, args).await,
|
|
"status" => status(args).await,
|
|
"reconfigure" => reconfigure(args).await,
|
|
"down" => down(args).await,
|
|
_ => unreachable!("dispatch filters the commands"),
|
|
}
|
|
}
|
|
|
|
/// Windows view of the memory the WSL2 VM gets, from `%UserProfile%\.wslconfig`.
|
|
fn wslconfig_note(wanted_gib: u32) -> Option<String> {
|
|
let host_total = probe(&ProbeRequest::default()).memory.total;
|
|
if host_total == 0 {
|
|
return None;
|
|
}
|
|
let text = std::env::var_os("USERPROFILE")
|
|
.map(|home| PathBuf::from(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)
|
|
}
|
|
|
|
async fn forward(command: &str, args: &[String]) -> i32 {
|
|
let session = match open_session(args, true) {
|
|
Ok(session) => session,
|
|
Err(message) => {
|
|
note(&message);
|
|
return 1;
|
|
}
|
|
};
|
|
let json = session.forwarded.args.iter().any(|a| a == "--json");
|
|
if let Some(assets) = &session.forwarded.assets
|
|
&& is_drvfs(assets)
|
|
{
|
|
note(&format!(
|
|
"--assets {assets} is a Windows drive seen from WSL (9p): mapped and direct reads of the 140 GB model are far too slow there. Put the model volume on the WSL disk, e.g. --assets {}/leleka-assets (copy the files with `wsl -d {} cp` or from \\\\wsl.localhost\\{}\\...)",
|
|
session.home, session.bridge.distro, session.bridge.distro
|
|
));
|
|
return 2;
|
|
}
|
|
if !json && matches!(command, "up" | "preflight") {
|
|
match wslconfig_note(32) {
|
|
Some(advice) => note(&format!("note: {advice}")),
|
|
None => {
|
|
let have = std::env::var_os("USERPROFILE")
|
|
.map(|home| PathBuf::from(home).join(".wslconfig"))
|
|
.and_then(|path| std::fs::read_to_string(path).ok())
|
|
.map(|text| effective_wsl_memory(&parse_wslconfig(&text), probe(&ProbeRequest::default()).memory.total));
|
|
if let Some(have) = have {
|
|
note(&format!("WSL2 memory is {:.0} GiB (.wslconfig); fine for the laptop profile", have as f64 / (1u64 << 30) as f64));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
let binary = match session.bridge.find_leleka(session.forwarded.wsl_bin.as_deref().or(session.saved.as_ref().map(|s| s.leleka_bin.as_str()))) {
|
|
Ok(binary) => binary,
|
|
Err(message) => {
|
|
note(&message);
|
|
return 1;
|
|
}
|
|
};
|
|
let state_dir = session.state_dir();
|
|
let api = format!("127.0.0.1:{}", session.forwarded.api_port.unwrap_or(8081));
|
|
if command == "up" && !args.iter().any(|a| a == "--dry-run") {
|
|
let state = BridgeState {
|
|
distro: session.bridge.distro.clone(),
|
|
leleka_bin: binary.clone(),
|
|
state_dir: state_dir.clone(),
|
|
api: api.clone(),
|
|
};
|
|
if let Err(message) = state.write(&local_app_data()) {
|
|
note(&format!("cannot remember the WSL settings: {message}"));
|
|
}
|
|
}
|
|
if !json {
|
|
note(&format!(
|
|
"running `{binary} {command}` in WSL2 ({}); the engine's output follows",
|
|
session.bridge.distro
|
|
));
|
|
if command == "up" {
|
|
note(&format!("API endpoint will be http://{api} (WSL2 forwards loopback to Windows)"));
|
|
note(&format!("API key will be in {} (WSL path {state_dir}/api-key)", session.key_unc(&state_dir)));
|
|
}
|
|
}
|
|
let mut linux_args = vec![command.to_owned()];
|
|
linux_args.extend(session.forwarded.args.clone());
|
|
let mut child = match tokio::process::Command::from(session.bridge.command(&binary, &linux_args)).spawn() {
|
|
Ok(child) => child,
|
|
Err(error) => {
|
|
note(&format!("cannot start wsl.exe: {error}"));
|
|
return 1;
|
|
}
|
|
};
|
|
let announce = (command == "up" && !json && !args.iter().any(|a| a == "--dry-run")).then(|| {
|
|
let bridge = session.bridge.clone();
|
|
let (state_dir, api) = (state_dir.clone(), api.clone());
|
|
tokio::spawn(async move { announce_when_ready(bridge, state_dir, api).await })
|
|
});
|
|
let mut interrupts = 0;
|
|
let status = loop {
|
|
tokio::select! {
|
|
status = child.wait() => break status,
|
|
_ = tokio::signal::ctrl_c() => {
|
|
interrupts += 1;
|
|
if interrupts == 1 {
|
|
note("Ctrl-C: the service in WSL drains and stops; press Ctrl-C again to kill it");
|
|
} else {
|
|
let _ = child.start_kill();
|
|
}
|
|
}
|
|
}
|
|
};
|
|
if let Some(task) = announce {
|
|
task.abort();
|
|
}
|
|
match status {
|
|
Ok(status) => {
|
|
let prepare_only = args.windows(2).any(|w| w[0] == "--mode" && w[1] == "none") || args.iter().any(|a| a == "--mode=none");
|
|
if command == "up" && status.success() && !json && !prepare_only && !args.iter().any(|a| a == "--dry-run") {
|
|
// A service started under systemd keeps running after `up` returns: say how to reach it.
|
|
print_windows_summary(&session.bridge.distro, &state_dir, &api);
|
|
}
|
|
status.code().unwrap_or(1)
|
|
}
|
|
Err(error) => {
|
|
note(&format!("wsl.exe failed: {error}"));
|
|
1
|
|
}
|
|
}
|
|
}
|
|
|
|
fn print_windows_summary(distro: &str, state_dir: &str, api: &str) {
|
|
eprintln!(
|
|
"\nLeleka (WSL2 route) is reachable from Windows:\n endpoint http://{api}\n api key {} (WSL: {state_dir}/api-key)\n try {}\n status leleka status telemetry: GPU, CPU, RAM, tokens/s, cache, context\n settings leleka reconfigure --context-tokens N ... | stop: leleka down (or Ctrl-C in the `up` window)",
|
|
linux_to_unc(distro, &format!("{state_dir}/api-key")),
|
|
crate::app::powershell_try(&linux_to_unc(distro, &format!("{state_dir}/api-key")), api, crate::layout::MODEL_ID)
|
|
);
|
|
}
|
|
|
|
/// While `up` runs in the foreground, watch from Windows for readiness and print the Windows view once.
|
|
async fn announce_when_ready(bridge: Bridge, state_dir: String, api: String) {
|
|
loop {
|
|
tokio::time::sleep(Duration::from_secs(10)).await;
|
|
let (b, path) = (bridge.clone(), format!("{state_dir}/api-key"));
|
|
let key = tokio::task::spawn_blocking(move || b.read_file(&path)).await.ok().flatten();
|
|
if let Some(key) = key
|
|
&& probe_ready_with_key(&key, &api).await
|
|
{
|
|
print_windows_summary(&bridge.distro, &state_dir, &api);
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
|
|
async fn status(args: &[String]) -> i32 {
|
|
let session = match open_session(args, false) {
|
|
Ok(session) => session,
|
|
Err(message) => {
|
|
// Not an error of the tool: nothing is running. Same shape as a native "not ready".
|
|
let json = args.iter().any(|a| a == "--json");
|
|
if json {
|
|
println!("{{\"ready\": false, \"reason\": {}}}", Value::String(message));
|
|
} else {
|
|
println!("ready: false\n{message}");
|
|
}
|
|
return 1;
|
|
}
|
|
};
|
|
let json = session.forwarded.args.iter().any(|a| a == "--json");
|
|
let state_dir = session.state_dir();
|
|
let api = session.api(&state_dir);
|
|
let supervisor: Option<Value> = session
|
|
.bridge
|
|
.read_file(&format!("{state_dir}/run/status.json"))
|
|
.and_then(|text| serde_json::from_str(&text).ok());
|
|
let key = session.bridge.read_file(&format!("{state_dir}/api-key"));
|
|
let ready = match &key {
|
|
Some(key) => probe_ready_with_key(key, &api).await,
|
|
None => false,
|
|
};
|
|
let gateway = match (&key, ready) {
|
|
(Some(key), true) => fetch_status_with_key(key, &api).await,
|
|
_ => None,
|
|
};
|
|
if !json && key.is_none() {
|
|
note(&format!("no API key in {state_dir}/api-key of {} (has `leleka up` run? other state? pass --state-dir)", session.bridge.distro));
|
|
}
|
|
print_status(json, ready, None, supervisor, gateway.as_ref(), &linux_to_unc(&session.bridge.distro, &format!("{state_dir}/run")))
|
|
}
|
|
|
|
async fn reconfigure(args: &[String]) -> i32 {
|
|
let (rest, extra) = match split_reconfigure(args) {
|
|
Ok(pair) => pair,
|
|
Err(message) => {
|
|
note(&message);
|
|
return 2;
|
|
}
|
|
};
|
|
// A restart of the engine process or a persisted change needs the supervisor and the files inside the distribution: run the Linux command there.
|
|
if extra.needs_restart() || extra.persist {
|
|
return forward("reconfigure", args).await;
|
|
}
|
|
let document = serde_json::Value::Object(extra.settings.clone()).to_string();
|
|
let session = match open_session(&rest, false) {
|
|
Ok(session) => session,
|
|
Err(message) => {
|
|
note(&message);
|
|
return 1;
|
|
}
|
|
};
|
|
let state_dir = session.state_dir();
|
|
let api = session.api(&state_dir);
|
|
let Some(key) = session.bridge.read_file(&format!("{state_dir}/api-key")) else {
|
|
note(&format!("no API key in {state_dir}/api-key of {} (is the service prepared?)", session.bridge.distro));
|
|
return 1;
|
|
};
|
|
let Some(address) = crate::config::probe_address(&api) else {
|
|
note(&format!("cannot reach the API address {api}"));
|
|
return 1;
|
|
};
|
|
let json = session.forwarded.args.iter().any(|a| a == "--json");
|
|
send_reconfigure(address, key.trim_end(), &document, json, None).await
|
|
}
|
|
|
|
async fn down(args: &[String]) -> i32 {
|
|
let session = match open_session(args, false) {
|
|
Ok(session) => session,
|
|
Err(message) => {
|
|
note(&format!("nothing to stop: {message}"));
|
|
return 0;
|
|
}
|
|
};
|
|
let state_dir = session.state_dir();
|
|
let bridge = &session.bridge;
|
|
// A systemd user unit inside the distribution?
|
|
let unit = bridge.capture("systemctl", &["--user", "is-active", "leleka.service"]).unwrap_or_default();
|
|
if unit.trim() == "active" || unit.trim() == "activating" {
|
|
return match bridge.capture("systemctl", &["--user", "stop", "leleka.service"]) {
|
|
Ok(_) => {
|
|
note("stopped leleka.service (user unit in WSL)");
|
|
0
|
|
}
|
|
Err(message) => {
|
|
note(&message);
|
|
1
|
|
}
|
|
};
|
|
}
|
|
let supervisor: Option<Value> = bridge
|
|
.read_file(&format!("{state_dir}/run/status.json"))
|
|
.and_then(|text| serde_json::from_str(&text).ok());
|
|
let pid = supervisor.as_ref().and_then(|s| s["supervisor_pid"].as_u64());
|
|
let phase = supervisor.as_ref().and_then(|s| s["phase"].as_str()).unwrap_or("").to_owned();
|
|
let Some(pid) = pid.filter(|_| !matches!(phase.as_str(), "stopped" | "failed")) else {
|
|
note("no running supervisor was found in this state directory");
|
|
return 0;
|
|
};
|
|
let pid_text = pid.to_string();
|
|
if bridge.capture("kill", &["-0", &pid_text]).is_err() {
|
|
note(&format!("the supervisor (pid {pid}) is not running any more"));
|
|
return 0;
|
|
}
|
|
note(&format!("stopping the supervisor (pid {pid}) with SIGINT: the API drains first, then the gateway and the engine"));
|
|
if let Err(message) = bridge.capture("kill", &["-INT", &pid_text]) {
|
|
note(&message);
|
|
return 1;
|
|
}
|
|
let started = std::time::Instant::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() {
|
|
note("stopped");
|
|
return 0;
|
|
}
|
|
}
|
|
note("the supervisor is still draining after 120 s; check `leleka status` (it escalates to SIGKILL itself after its grace period)");
|
|
1
|
|
}
|
|
|
|
/// The repository checkout that holds `scripts\windows`, found by walking up from the executable (`target\release\leleka.exe`,
|
|
/// `dist\bin\leleka.exe`) or from the current directory.
|
|
fn find_repo() -> Option<PathBuf> {
|
|
let starts = [std::env::current_exe().ok(), std::env::current_dir().ok()];
|
|
for start in starts.into_iter().flatten() {
|
|
for dir in start.ancestors() {
|
|
if dir.join("scripts").join("windows").join("fetch-cublas.ps1").is_file() {
|
|
return Some(dir.to_path_buf());
|
|
}
|
|
}
|
|
}
|
|
None
|
|
}
|
|
|
|
/// `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.
|
|
async fn doctor(args: &[String]) -> i32 {
|
|
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 mut dirs = crate::layout::Dirs::defaults(false, home.as_deref(), &var);
|
|
let mut iter = args.iter();
|
|
while let Some(arg) = iter.next() {
|
|
if let Some(value) = arg.strip_prefix("--assets=") {
|
|
dirs.assets = PathBuf::from(value);
|
|
} else if arg == "--assets"
|
|
&& let Some(value) = iter.next()
|
|
{
|
|
dirs.assets = PathBuf::from(value);
|
|
}
|
|
}
|
|
let paths = dirs.paths();
|
|
let exe_dir = std::env::current_exe().ok().and_then(|exe| exe.parent().map(PathBuf::from));
|
|
let facts = probe(&ProbeRequest {
|
|
binary_dir: exe_dir.clone(),
|
|
..ProbeRequest::default()
|
|
});
|
|
let gib = |bytes: u64| format!("{:.1} GiB", bytes as f64 / (1u64 << 30) as f64);
|
|
println!("windows facts:");
|
|
println!(" os/arch {}/{}", facts.os, facts.arch);
|
|
println!(" cpu {} logical cores", facts.cpu_cores);
|
|
println!(" ram {} total, {} available", gib(facts.memory.total), gib(facts.memory.available));
|
|
if facts.gpus.is_empty() {
|
|
println!(" gpu none ({})", facts.nvidia_smi_error.as_deref().unwrap_or("nvidia-smi listed nothing"));
|
|
}
|
|
for gpu in &facts.gpus {
|
|
println!(
|
|
" gpu {} {} sm_{} {} MiB ({} free), driver {}",
|
|
gpu.index,
|
|
gpu.name,
|
|
gpu.sm.map_or("?".into(), |s| s.to_string()),
|
|
gpu.vram_total_mib,
|
|
gpu.vram_free_mib,
|
|
gpu.driver
|
|
);
|
|
}
|
|
let wslconfig = home.as_ref().map(|home| home.join(".wslconfig"));
|
|
let text = wslconfig.as_ref().and_then(|path| std::fs::read_to_string(path).ok());
|
|
println!("wsl2 (route A):");
|
|
match &text {
|
|
Some(text) => {
|
|
let config = parse_wslconfig(text);
|
|
println!(
|
|
" .wslconfig memory={} swap={}",
|
|
config.memory_bytes.map_or("(default: half of RAM)".into(), gib),
|
|
config.swap_bytes.map_or("(default)".into(), gib)
|
|
);
|
|
}
|
|
None => println!(" .wslconfig none (WSL2 gets half of the RAM and a small swap)"),
|
|
}
|
|
match wslconfig_advice(&parse_wslconfig(text.as_deref().unwrap_or("")), facts.memory.total, 32) {
|
|
Some(advice) => println!(" advice {advice}"),
|
|
None => println!(" advice none: memory and swap are enough for the laptop profile"),
|
|
}
|
|
let mut linux_leleka_found = None;
|
|
let wsl = wsl_exe();
|
|
match &wsl {
|
|
None => println!(" wsl.exe not found (WSL is not installed: use --native, or `wsl --install -d Ubuntu`)"),
|
|
Some(wsl) => {
|
|
println!(" wsl.exe {}", wsl.display());
|
|
match list_distros(wsl) {
|
|
Err(message) => println!(" distros {message}"),
|
|
Ok(list) => {
|
|
for d in &list {
|
|
println!(" distro {}{} {} (WSL{})", if d.default { "* " } else { "" }, d.name, d.state, d.version);
|
|
}
|
|
match pick_distro(&list, std::env::var("LELEKA_WSL_DISTRO").ok().as_deref()) {
|
|
Err(message) => println!(" chosen {message}"),
|
|
Ok(distro) => {
|
|
println!(" chosen {distro}");
|
|
let bridge = Bridge { wsl: wsl.clone(), distro };
|
|
if list.iter().any(|d| d.name == bridge.distro && d.state.eq_ignore_ascii_case("running")) {
|
|
match bridge.find_leleka(None) {
|
|
Ok(path) => {
|
|
println!(" linux leleka {path}");
|
|
linux_leleka_found = Some(true);
|
|
}
|
|
Err(message) => {
|
|
println!(" linux leleka {message}");
|
|
linux_leleka_found = Some(false);
|
|
}
|
|
}
|
|
} else {
|
|
println!(" linux leleka (the distribution is stopped; not started just to look)");
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
if let Some(saved) = BridgeState::read(&local_app_data()) {
|
|
println!(" last up distro {} state {} api {}", saved.distro, saved.state_dir, saved.api);
|
|
}
|
|
println!("native route:");
|
|
let native_missing: Vec<String> = exe_dir
|
|
.as_ref()
|
|
.map(|dir| crate::layout::BINARIES.iter().filter(|b| !dir.join(b).is_file()).map(|b| (*b).to_owned()).collect())
|
|
.unwrap_or_else(|| crate::layout::BINARIES.iter().map(|b| (*b).to_owned()).collect());
|
|
println!(
|
|
" programs {}",
|
|
if native_missing.is_empty() { "all five .exe files are next to leleka.exe".to_owned() } else { format!("missing next to leleka.exe: {}", native_missing.join(", ")) }
|
|
);
|
|
let mut cublas_missing = Vec::new();
|
|
for (soname, dll) in crate::facts::WINDOWS_LIBRARIES {
|
|
let found = facts.lib(soname);
|
|
println!(" {dll:<18} {}", found.map_or("not found".to_owned(), |p| p.display().to_string()));
|
|
if found.is_none() && soname != "libcuda.so.1" {
|
|
cublas_missing.push(dll);
|
|
}
|
|
}
|
|
let volume_missing = crate::doctor::volume_missing(&paths);
|
|
println!(" volume {}", paths.dirs.assets.display());
|
|
for line in &volume_missing {
|
|
println!(" {line}");
|
|
}
|
|
if volume_missing.is_empty() {
|
|
println!(
|
|
" complete{}",
|
|
if crate::doctor::expert_profile_present(&paths) { "" } else { " (data\\expert-profile.bin is absent: optional, but it is the ranked VRAM expert tier)" }
|
|
);
|
|
}
|
|
let inputs = crate::doctor::Inputs {
|
|
repo: find_repo(),
|
|
gpu_found: !facts.gpus.is_empty(),
|
|
native_binaries_missing: native_missing,
|
|
cublas_missing,
|
|
volume_missing,
|
|
assets: paths.dirs.assets.clone(),
|
|
wsl_found: wsl.is_some(),
|
|
linux_leleka_found,
|
|
};
|
|
println!("verdict:");
|
|
for finding in &crate::doctor::advise(&inputs) {
|
|
if finding.ok() {
|
|
println!(" ok {}", finding.what);
|
|
} else {
|
|
println!(" MISSING {}", finding.what);
|
|
if let Some(fix) = &finding.fix {
|
|
println!(" fix: {fix}");
|
|
}
|
|
}
|
|
}
|
|
match crate::doctor::next_command(&inputs) {
|
|
Some(command) => {
|
|
println!("next (native route): {command}");
|
|
1
|
|
}
|
|
None => {
|
|
println!("next (native route): leleka up --native --foreground --assets {}", paths.dirs.assets.display());
|
|
0
|
|
}
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
fn strings(items: &[&str]) -> Vec<String> {
|
|
items.iter().map(|s| s.to_string()).collect()
|
|
}
|
|
|
|
#[test]
|
|
fn the_route_flag_wins_over_the_environment_and_is_removed() {
|
|
let (route, rest) = split_route(&strings(&["up", "--native", "--gpu", "0"]), Some("wsl")).unwrap();
|
|
assert_eq!((route, rest), (Some(Route::Native), strings(&["up", "--gpu", "0"])));
|
|
let (route, _) = split_route(&strings(&["up"]), Some("wsl")).unwrap();
|
|
assert_eq!(route, Some(Route::Wsl));
|
|
let (route, _) = split_route(&strings(&["up"]), None).unwrap();
|
|
assert_eq!(route, None);
|
|
assert!(split_route(&strings(&["up"]), Some("docker")).is_err());
|
|
}
|
|
}
|