Skip to main content

isothrum_runner/
lib.rs

1//! The Isothrum runner: executes the run manifest Isoloom writes next to a target's generated
2//! files (`.isoloom/<target>/run.json`), and reads nothing else of them.
3//!
4//! The manifest holds the native commands in order, the documented driver actions, readiness,
5//! outputs, check runners, and the slots inputs and secrets travel through. The runner adds what
6//! only it can know: the run's name and private state, one operation per run at a time, the
7//! values of params and secrets, and the event stream an embedder (an app, the `isothrum` command
8//! line) shows. It sits between Isoloom (whose
9//! `isoloom-manifest` crate is the contract) and those embedders, and depends on no UI.
10//!
11//! # Example
12//!
13//! Opening a manifest reads and checks it, and nothing runs yet:
14//!
15//! ```
16//! use isothrum_runner::{RunName, Runner, RunnerConfig};
17//!
18//! let home = tempfile::tempdir()?;
19//! let dir = tempfile::tempdir()?;
20//! let manifest = dir.path().join("run.json");
21//! std::fs::write(&manifest, include_str!("../tests/fixtures/web-portal.run.json"))?;
22//!
23//! let runner = Runner::new(RunnerConfig::new(home.path()))?;
24//! let run = runner.open(&manifest, Some(RunName::new("demo")?))?;
25//! assert_eq!(run.manifest().environment.name.as_str(), "web-portal");
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 the tools it names (here Docker), and an event sink ([`Events`], implemented
32//! for 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_param("ISOLOOM_PUBLISH_FIXED", "1");
40//! let started = run.up(&opts, &events).await?;
41//! let report = run.check(&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: Apple's `nc`, the macOS relays' byte pipe for as long as a connection lasts
58//! (not a tool run to its end), a graphical console's SSH tunnel (`ssh -N -L`), for as long as its
59//! [`Console`] lives, on Windows `whoami` and `icacls`, which make the home
60//! owner-only when the runner is built ([`Runner::new`]), before any operation, and, only for a
61//! tool a killed operation left running, `ps` (Windows: PowerShell) to tell it is still that tool,
62//! and on Windows `taskkill` to end it.
63//!
64//! # Deliveries
65//!
66//! Params and slot values reach the tools only through the manifest's deliveries, never on a
67//! command line: `env` (a step's variables), `tf_var` (`TF_VAR_<var>`, a `map_entry` making one
68//! JSON object), `state_file` (an owner-only Terraform variable file in the run's state folder,
69//! written at `up`, kept for the destroy, removed by a successful `down`), and `guest` over SSH, Isoloom's delivery into a machine for a cloud with no secret
70//! store (DigitalOcean, Linode): once the step it names (else every `up` step) succeeded, one
71//! SSH session per machine, to the outputs `address_<machine>` and `ssh_user_<machine>` (else
72//! `ssh_user`; the machine's name with `-` and `.` as `_`, in lower case), runs a fixed script as root that keeps each value
73//! owner-only under `/var/lib/isoloom/secrets/<slot name>` and then touches
74//! `/var/lib/isoloom/secrets/.delivered`, which the machine's set-up waits for; the values travel
75//! base64-encoded on its standard input, retried while SSH can't connect (up to 15 minutes),
76//! from an owner-only `guest-<machine>.in` in the run's state folder that is removed once
77//! delivered (a removal that fails, fails the delivery) or once the operation is cut short.
78//!
79//! # Concurrency
80//!
81//! The runner is **async**, on Tokio, chosen once for the whole crate: every tool runs as an async
82//! process with a time limit (a step's `provider_timeout_s` for the run's provider, else its
83//! `timeout_s`, else an hour; 25 s for a probe; two minutes for an action's own Docker calls),
84//! and dropping an operation's future stops the process trees it started: on Unix each gets
85//! SIGINT (so Terraform saves its state) and SIGKILL once it exited or 30 seconds later; on
86//! Windows each is ended at once ([`SystemProcesses`]). The limit counts the time
87//! a tool shows no progress: it is stopped once it printed no new line for that long (a line, on
88//! either stream, that isn't blank and isn't one of its last distinct lines; from its start when
89//! it prints nothing), and at the latest six hours after its start, or at its limit when that is
90//! longer ([`TimedOut`] says which). The images a Compose `up` starts are pulled before it, and
91//! the boxes a `vagrant up` boots downloaded before it (those the manifest lists that Vagrant
92//! hasn't), each in a step of their own (`pull-<step>`, `boxes-<step>`) with no such ceiling: a
93//! download still moving runs as long as it moves, and one that shows no progress for 15 minutes
94//! fails with `download_stalled` (a download that fails, with `download_failed`). A step the
95//! manifest marks `download` runs the same way, its own limit the time it may show no progress. Operations on one run in one [`Runner`] wait for each other;
96//! an operation on it from another process (or another runner) fails with `locked` once it has
97//! waited a second for the run's lock. Operations on different runs run side by side. One
98//! exception to "no blocking call in async code": the run's state files (a record, a lock, the
99//! pinned ports, the event log) are a few KB on the local disk, so they are read and written
100//! inline rather than through `spawn_blocking`.
101//!
102//! # Errors and tracing
103//!
104//! Every fallible call returns [`Result`], whose [`Error`] has a stable [`ErrorCode`]; an
105//! operation also reports its failure as its last event. The runner logs through `tracing` (spans
106//! `run`, `step` and `driver`, events for each process), never by printing.
107
108#![cfg_attr(docsrs, feature(doc_cfg))]
109
110mod adopt;
111mod archive;
112mod checks;
113mod clock;
114mod console;
115mod container;
116mod driver;
117mod encoding;
118mod error;
119mod events;
120mod executor;
121mod future;
122#[cfg(feature = "fuzzing")]
123#[doc(hidden)]
124pub mod fuzzing;
125mod graphical;
126mod guest;
127mod host_env;
128mod in_vm;
129mod manifest;
130mod name;
131mod net;
132mod network_env;
133mod options;
134mod outputs;
135mod params;
136mod process;
137mod ready;
138mod reap;
139mod relay;
140mod run;
141mod runner;
142mod scope;
143mod secrets;
144mod server_auth;
145mod slot;
146mod ssh;
147mod state;
148mod status;
149mod store;
150#[cfg(test)]
151mod testing;
152mod tool_output;
153mod tools;
154mod vars;
155
156pub use adopt::Adoption;
157pub use checks::{CheckReport, CheckResult};
158pub use clock::rfc3339;
159pub use console::ShellCommand;
160pub use encoding::{every_name, from_wire_name, wire_name};
161pub use error::{Error, ErrorCode, Result, TimedOut};
162#[cfg(test)]
163pub(crate) use events::Recorder;
164pub use events::{Event, EventKind, EventLog, Events, ReadyState, StepState, Stream, WarningCode, events_schema};
165pub use future::BoxFuture;
166pub use graphical::{Console, ConsoleOffer, Endpoint, NativeApp, NativeConsole, NativeNeed, NativeOpen, ProxmoxVnc};
167pub use isoloom_manifest;
168pub use manifest::{LoadedManifest, MANIFEST_FILE, is_outputs_folder, load_manifest};
169pub use name::RunName;
170#[cfg(any(test, feature = "fake"))]
171#[cfg_attr(docsrs, doc(cfg(feature = "fake")))]
172pub use net::FakePorts;
173pub use net::HostPorts;
174pub use options::{Occupied, RunOptions};
175#[cfg(any(test, feature = "fake"))]
176#[cfg_attr(docsrs, doc(cfg(feature = "fake")))]
177pub use process::fake;
178pub use process::{Captured, Exit, OnLine, ProcessError, ProcessRunner, ProcessSpec, SystemProcesses, capture, may_manage_hyperv};
179pub use reap::{Orphans, Place, Tagged};
180pub use run::{AccessPick, AttachReport, Running};
181pub use runner::{Runner, RunnerConfig};
182pub use secrets::{SecretValue, Secrets};
183pub use state::{Op, Park, RunState};
184pub use status::{MachineState, MachineStatus, NetworkView, OutputValue, PublishedPort, Started, Status, status_schema};
185pub use store::{LastOp, RunRecord};
186pub use tool_output::{vagrant_plugins, version_found};