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. Three 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, and on Windows `whoami` and `icacls`, which make the home
60//! owner-only when the runner is built ([`Runner::new`]), before any operation.
61//!
62//! # Deliveries
63//!
64//! Params and slot values reach the tools only through the manifest's deliveries, never on a
65//! command line: `env` (a step's variables), `tf_var` (`TF_VAR_<var>`, a `map_entry` making one
66//! JSON object), `state_file` (an owner-only Terraform variable file in the run's state folder,
67//! 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
68//! store (DigitalOcean, Linode): once the step it names (else every `up` step) succeeded, one
69//! SSH session per machine, to the outputs `address_<machine>` and `ssh_user_<machine>` (else
70//! `ssh_user`; the machine's name with `-` and `.` as `_`, in lower case), runs a fixed script as root that keeps each value
71//! owner-only under `/var/lib/isoloom/secrets/<slot name>` and then touches
72//! `/var/lib/isoloom/secrets/.delivered`, which the machine's set-up waits for; the values travel
73//! base64-encoded on its standard input, retried while SSH can't connect (up to 15 minutes),
74//! from an owner-only `guest-<machine>.in` in the run's state folder that is removed once
75//! delivered (a removal that fails, fails the delivery) or once the operation is cut short.
76//!
77//! # Concurrency
78//!
79//! The runner is **async**, on Tokio, chosen once for the whole crate: every tool runs as an async
80//! process with a time limit (a step's `provider_timeout_s` for the run's provider, else its
81//! `timeout_s`, else an hour; 25 s for a probe; two minutes for an action's own Docker calls),
82//! and dropping an operation's future stops the process trees it started: on Unix each gets
83//! SIGINT (so Terraform saves its state) and SIGKILL once it exited or 30 seconds later; on
84//! Windows each is ended at once ([`SystemProcesses`]). The limit counts the time
85//! a tool shows no progress: it is stopped once it printed no new line for that long (a line, on
86//! either stream, that isn't blank and isn't one of its last distinct lines; from its start when
87//! it prints nothing), and at the latest six hours after its start, or at its limit when that is
88//! longer ([`TimedOut`] says which). The images a Compose `up` starts are pulled before it, and
89//! the boxes a `vagrant up` boots downloaded before it (those the manifest lists that Vagrant
90//! hasn't), each in a step of their own (`pull-<step>`, `boxes-<step>`) with no such ceiling: a
91//! download still moving runs as long as it moves, and one that shows no progress for 15 minutes
92//! fails with `download_stalled` (a download that fails, with `download_failed`). A step the
93//! 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;
94//! an operation on it from another process (or another runner) fails with `locked` once it has
95//! waited a second for the run's lock. Operations on different runs run side by side. One
96//! exception to "no blocking call in async code": the run's state files (a record, a lock, the
97//! pinned ports, the event log) are a few KB on the local disk, so they are read and written
98//! inline rather than through `spawn_blocking`.
99//!
100//! # Errors and tracing
101//!
102//! Every fallible call returns [`Result`], whose [`Error`] has a stable [`ErrorCode`]; an
103//! operation also reports its failure as its last event. The runner logs through `tracing` (spans
104//! `run`, `step` and `driver`, events for each process), never by printing.
105
106#![cfg_attr(docsrs, feature(doc_cfg))]
107
108mod adopt;
109mod archive;
110mod checks;
111mod clock;
112mod console;
113mod container;
114mod driver;
115mod encoding;
116mod error;
117mod events;
118mod executor;
119mod future;
120#[cfg(feature = "fuzzing")]
121#[doc(hidden)]
122pub mod fuzzing;
123mod graphical;
124mod guest;
125mod host_env;
126mod in_vm;
127mod manifest;
128mod name;
129mod net;
130mod network_env;
131mod options;
132mod outputs;
133mod params;
134mod process;
135mod ready;
136mod reap;
137mod relay;
138mod run;
139mod runner;
140mod scope;
141mod secrets;
142mod slot;
143mod ssh;
144mod state;
145mod status;
146mod store;
147#[cfg(test)]
148mod testing;
149mod tool_output;
150mod tools;
151mod vars;
152
153pub use adopt::Adoption;
154pub use checks::{CheckReport, CheckResult};
155pub use clock::rfc3339;
156pub use console::ShellCommand;
157pub use encoding::{every_name, from_wire_name, wire_name};
158pub use error::{Error, ErrorCode, Result, TimedOut};
159#[cfg(test)]
160pub(crate) use events::Recorder;
161pub use events::{Event, EventKind, EventLog, Events, ReadyState, StepState, Stream, WarningCode, events_schema};
162pub use future::BoxFuture;
163pub use graphical::{Console, ConsoleOffer, Endpoint, NativeApp, NativeConsole, NativeNeed, NativeOpen, ProxmoxVnc};
164pub use isoloom_manifest;
165pub use manifest::{LoadedManifest, MANIFEST_FILE, is_outputs_folder, load_manifest};
166pub use name::RunName;
167#[cfg(any(test, feature = "fake"))]
168#[cfg_attr(docsrs, doc(cfg(feature = "fake")))]
169pub use net::FakePorts;
170pub use net::HostPorts;
171pub use options::{Occupied, RunOptions};
172#[cfg(any(test, feature = "fake"))]
173#[cfg_attr(docsrs, doc(cfg(feature = "fake")))]
174pub use process::fake;
175pub use process::{Captured, Exit, OnLine, ProcessError, ProcessRunner, ProcessSpec, SystemProcesses, capture, may_manage_hyperv};
176pub use reap::{Orphans, Place, Tagged};
177pub use run::{AccessPick, AttachReport, Running};
178pub use runner::{Runner, RunnerConfig};
179pub use secrets::{SecretValue, Secrets};
180pub use state::{Op, Park, RunState};
181pub use status::{MachineState, MachineStatus, NetworkView, OutputValue, PublishedPort, Started, Status, status_schema};
182pub use store::{LastOp, RunRecord};
183pub use tool_output::{vagrant_plugins, version_found};