isothrum_runner/lib.rs
1//! The Isothrum runner: runs a project folder (a Compose project, a Vagrantfile, a Terraform
2//! module) through its own tool, with that tool's own lifecycle, and reads nothing else of it.
3//!
4//! The format comes from the folder's files ([`Format::detect`]), and each format has one driver
5//! that knows its tool: Compose's `up --wait` and `down`, Vagrant's `up`, `suspend`, `halt` and
6//! `destroy`, Terraform's `init`, `apply` and `destroy`. The runner adds what only it can know: the
7//! run's name, key and private state, one operation per run at a time, journaled in the home's
8//! store, the values and secrets the tools get in their environment, the resources each tool
9//! reports, and the event stream an embedder (an app, the `isothrum` command line) shows. It
10//! depends on no UI and on no generator: any project of a format it runs is a project.
11//!
12//! # Example
13//!
14//! Opening a folder detects its format, and nothing runs yet:
15//!
16//! ```
17//! use isothrum_runner::{Format, RunName, Runner, RunnerConfig};
18//!
19//! let home = tempfile::tempdir()?;
20//! let dir = tempfile::tempdir()?;
21//! std::fs::write(dir.path().join("compose.yaml"), "services:\n web:\n image: nginx\n")?;
22//!
23//! let runner = Runner::new(RunnerConfig::new(home.path()))?;
24//! let run = runner.open(dir.path(), Some(RunName::new("demo")?))?;
25//! assert_eq!(run.project().format, Format::Compose);
26//! assert_eq!(run.name().as_str(), "demo");
27//! assert!(runner.runs()?.is_empty(), "no operation has run");
28//! # Ok::<(), Box<dyn std::error::Error>>(())
29//! ```
30//!
31//! Running it takes its tool (here Docker), and an event sink ([`Events`], implemented for
32//! closures):
33//!
34//! ```no_run
35//! # async fn demo(run: &isothrum_runner::Running<'_>) -> isothrum_runner::Result<()> {
36//! use isothrum_runner::{Event, Park, RunOptions};
37//!
38//! let events = |event: &Event| println!("{}", serde_json::to_string(event).unwrap_or_default());
39//! let opts = RunOptions::new().with_env("GREETING", "hello");
40//! let started = run.up(&opts, &events).await?;
41//! let report = run.exec("web", &["true".to_owned()], &opts, &events).await?;
42//! run.park(Park::Shutdown, &opts, &events).await?;
43//! run.resume(&opts, &events).await?;
44//! run.down(&opts, &events).await?;
45//! # let _ = (started, report);
46//! # Ok(())
47//! # }
48//! ```
49//!
50//! # Ports
51//!
52//! Every outside effect goes through a port: [`ProcessRunner`] (the tools), [`HostPorts`] (the
53//! host's ports) and [`Events`] (where events go). [`ProcessRunner`] and [`Events`] are open traits,
54//! since embedders implement them. [`HostPorts`] is sealed: [`RunnerConfig::new`] binds the
55//! loopback itself, and the `fake` feature's `FakePorts` stands in for it in tests, as its
56//! `FakeProcesses` does for the tools. A few programs run outside [`ProcessRunner`], each for a
57//! reason of its own: on Windows `whoami` and `icacls`, which make the home owner-only when the
58//! runner is built ([`Runner::new`]), before any operation, and, only for a tool a killed
59//! operation left running, `ps` (Windows: PowerShell) to tell it is still that tool, and on
60//! Windows `taskkill` to end it. Whether the process holding a lease of the home's store still runs
61//! is the system's answer (Unix: signal 0; Windows: `OpenProcess`). The runner's one network
62//! client is its own: Proxmox VE's API, for a VM's console and its state on the server, the
63//! server's certificate checked by the system's trust store or by the SHA-256 the run pins
64//! ([`tls`]).
65//!
66//! # Inputs
67//!
68//! Values ([`RunOptions::env`]) and secrets ([`RunOptions::secrets`]) reach the tools only in
69//! their environment, never on a command line and never in a file: Compose interpolates `${NAME}`
70//! from it, a Vagrantfile reads `ENV`, and Terraform also gets each as `TF_VAR_<NAME>`. Every
71//! tool of a run also gets the run's key ([`RUN_KEY_VAR`]). A secret is masked in every event.
72//!
73//! # Concurrency
74//!
75//! The runner is **async**, on Tokio, chosen once for the whole crate: every tool runs as an async
76//! process with a time limit, and dropping an operation's future stops the process trees it
77//! started: on Unix each gets SIGINT (so Terraform saves its state) and SIGKILL once it exited or
78//! 30 seconds later; on Windows Ctrl-C on its own console, then its job ended the same way
79//! ([`SystemProcesses`]). Operations on one run in one [`Runner`] wait for each other; an operation
80//! on it from another process (or another runner) fails with `locked` once it has waited a second
81//! for the run's lock. Operations on different runs run side by side. One exception to "no
82//! blocking call in async code": the home's store ([`store::Store`], SQLite) and the run's lock are
83//! a few KB on the local disk, each transaction a few rows, so they are read and written inline
84//! rather than through `spawn_blocking`.
85//!
86//! # Errors and tracing
87//!
88//! Every fallible call returns [`Result`], whose [`Error`] has a stable [`ErrorCode`]; an
89//! operation also reports its failure as its last event. The runner logs through `tracing` (spans
90//! `run` and `driver`, events for each process), never by printing.
91
92#![cfg_attr(docsrs, feature(doc_cfg))]
93#![cfg_attr(
94 test,
95 expect(
96 clippy::disallowed_methods,
97 reason = "the unit tests start real processes to stand in for a tool or to read what one did; each spawn of the product code says why"
98 )
99)]
100
101mod address_blocks;
102mod adopt;
103mod cli;
104mod clock;
105mod console;
106mod downloads;
107mod encoding;
108mod error;
109mod events;
110#[cfg(any(test, feature = "fake"))]
111#[cfg_attr(docsrs, doc(cfg(feature = "fake")))]
112pub mod fake_https;
113mod formats;
114mod future;
115mod graphical;
116mod host_env;
117mod name;
118mod net;
119mod network_env;
120mod options;
121mod port;
122mod process;
123mod project;
124mod proxmox;
125mod reap;
126mod run;
127mod runner;
128mod secrets;
129mod ssh;
130mod state;
131mod status;
132mod steps;
133pub mod store;
134#[cfg(test)]
135mod testing;
136pub mod tls;
137mod tool_output;
138
139pub use adopt::Adoption;
140pub use cli::listener::port_holder;
141pub use clock::{rfc3339, rfc3339_seconds};
142pub use console::ShellCommand;
143pub use downloads::{Download, DownloadId, DownloadItem, DownloadRemoval, DownloadToAdopt, DownloadsToRemove, RemovalOutcome};
144pub use encoding::{every_name, from_wire_name, percent_encoded, wire_name};
145pub use error::{DETAIL_VERSION, Detail, DownloadKind, Error, ErrorCode, ErrorDetail, ErrorReport, PortHolder, ProviderNeed, Result, TimedOut};
146pub use events::{Event, EventKind, EventLog, Events, OperationPhase, ResultData, ShownOutput, StepState, Stream, SweepFailure, WarningCode, events_schema};
147pub use future::BoxFuture;
148pub use graphical::{Console, ConsoleOffer, ConsoleProtocol, Endpoint, NativeApp, NativeConsole, NativeNeed, NativeOpen, ProxmoxVnc, Tunnel};
149pub use name::RunName;
150#[cfg(any(test, feature = "fake"))]
151#[cfg_attr(docsrs, doc(cfg(feature = "fake")))]
152pub use net::FakePorts;
153pub use net::HostPorts;
154pub use options::RunOptions;
155pub use port::{GuestPort, HostPort};
156#[cfg(any(test, feature = "fake"))]
157#[cfg_attr(docsrs, doc(cfg(feature = "fake")))]
158pub use process::fake;
159pub use process::ledger;
160pub use process::process_started_at;
161pub use process::{Captured, Exit, HyperVRights, OnLine, ProcessError, ProcessFailed, ProcessRunner, ProcessSpec, SystemProcesses, capture, may_manage_hyperv};
162pub use project::platform::{Arch, Cloud, HostOs, Protocol, Provider, Version};
163pub use project::variables::{InputVariable, variables_of};
164pub use project::{Format, Project};
165pub use run::{ExecReport, Running, ServiceEndpoint};
166pub use runner::{RUN_KEY_VAR, Runner, RunnerConfig, copy_key, this_arch, this_host};
167pub use secrets::{SecretValue, Secrets};
168pub use state::{Cause, Desired, IllegalTransition, Op, Park, RunState, Transition};
169pub use status::{MachineState, MachineStatus, MachineUsage, OutputValue, PublishedPort, Started, Status, park_modes, status_schema};
170pub use steps::{Phase, StepCount};
171pub use store::{LastOp, RunRecord};
172pub use tool_output::{azure_cli_version, sign_in_expired, vagrant_plugins, version_found, virtualbox_vms};