Skip to main content

Crate isothrum_runner

Crate isothrum_runner 

Source
Expand description

The Isothrum runner: runs a project folder (a Compose project, a Vagrantfile, a Terraform module) through its own tool, with that tool’s own lifecycle, and reads nothing else of it.

The format comes from the folder’s files (Format::detect), and each format has one driver that knows its tool: Compose’s up --wait and down, Vagrant’s up, suspend, halt and destroy, Terraform’s init, apply and destroy. The runner adds what only it can know: the run’s name, key and private state, one operation per run at a time, journaled in the home’s store, the values and secrets the tools get in their environment, the resources each tool reports, and the event stream an embedder (an app, the isothrum command line) shows. It depends on no UI and on no generator: any project of a format it runs is a project.

§Example

Opening a folder detects its format, and nothing runs yet:

use isothrum_runner::{Format, RunName, Runner, RunnerConfig};

let home = tempfile::tempdir()?;
let dir = tempfile::tempdir()?;
std::fs::write(dir.path().join("compose.yaml"), "services:\n  web:\n    image: nginx\n")?;

let runner = Runner::new(RunnerConfig::new(home.path()))?;
let run = runner.open(dir.path(), Some(RunName::new("demo")?))?;
assert_eq!(run.project().format, Format::Compose);
assert_eq!(run.name().as_str(), "demo");
assert!(runner.runs()?.is_empty(), "no operation has run");

Running it takes its tool (here Docker), and an event sink (Events, implemented for closures):

use isothrum_runner::{Event, Park, RunOptions};

let events = |event: &Event| println!("{}", serde_json::to_string(event).unwrap_or_default());
let opts = RunOptions::new().with_env("GREETING", "hello");
let started = run.up(&opts, &events).await?;
let report = run.exec("web", &["true".to_owned()], &opts, &events).await?;
run.park(Park::Shutdown, &opts, &events).await?;
run.resume(&opts, &events).await?;
run.down(&opts, &events).await?;

§Ports

Every outside effect goes through a port: ProcessRunner (the tools), HostPorts (the host’s ports) and Events (where events go). ProcessRunner and Events are open traits, since embedders implement them. HostPorts is sealed: RunnerConfig::new binds the loopback itself, and the fake feature’s FakePorts stands in for it in tests, as its FakeProcesses does for the tools. A few programs run outside ProcessRunner, each for a reason of its own: on Windows whoami and icacls, which make the home owner-only when the runner is built (Runner::new), before any operation, and, only for a tool a killed operation left running, ps (Windows: PowerShell) to tell it is still that tool, and on Windows taskkill to end it. Whether the process holding a lease of the home’s store still runs is the system’s answer (Unix: signal 0; Windows: OpenProcess). The runner’s one network client is its own: Proxmox VE’s API, for a VM’s console and its state on the server, the server’s certificate checked by the system’s trust store or by the SHA-256 the run pins (tls).

§Inputs

Values (RunOptions::env) and secrets (RunOptions::secrets) reach the tools only in their environment, never on a command line and never in a file: Compose interpolates ${NAME} from it, a Vagrantfile reads ENV, and Terraform also gets each as TF_VAR_<NAME>. Every tool of a run also gets the run’s key (RUN_KEY_VAR). A secret is masked in every event.

§Concurrency

The runner is async, on Tokio, chosen once for the whole crate: every tool runs as an async process with a time limit, and dropping an operation’s future stops the process trees it started: on Unix each gets SIGINT (so Terraform saves its state) and SIGKILL once it exited or 30 seconds later; on Windows Ctrl-C on its own console, then its job ended the same way (SystemProcesses). Operations on one run in one Runner wait for each other; an operation on it from another process (or another runner) fails with locked once it has waited a second for the run’s lock. Operations on different runs run side by side. One exception to “no blocking call in async code”: the home’s store (store::Store, SQLite) and the run’s lock are a few KB on the local disk, each transaction a few rows, so they are read and written inline rather than through spawn_blocking.

§Errors and tracing

Every fallible call returns Result, whose Error has a stable ErrorCode; an operation also reports its failure as its last event. The runner logs through tracing (spans run and driver, events for each process), never by printing.

Re-exports§

pub use store::LastOp;
pub use store::RunRecord;

Modules§

fakefake
Scripted processes for tests (feature fake): every call is recorded and answered from the test’s script, so code that drives docker, vagrant or terraform runs without them and never touches real ones. In this crate’s tests a reply can take time (Reply::after) and print its lines over time (Reply::paced): under Tokio’s paused clock that time passes at once, so timeouts are tested without waiting.
fake_httpsfake
A test’s HTTPS server on the loopback, standing for a server whose certificate is self-signed (fake_https/server.crt.der, made once with openssl req -x509 -newkey ec): each request answered by the test, and every request that reached it kept, so a test tells a request refused before it was sent.
ledger
The tools an operation runs, kept in the run’s state folder while they run, so the next operation can end those a killed process left behind. An embedder keeps the tools it starts itself the same way, in a folder of its own (ProcessSpec::ledger_dir), and ends what its previous process left there when it starts (end_orphans).
store
The runner’s state: the home’s transactional store (Store, <home>/state.db: the runs, the journal of operations, the events, the resources each run made, what the runs’ downloads fetched, the host ports reserved, the leases), and one folder per run for what the tools keep (the reference, with what each target keeps in a run’s folder: docs/reference/state.md):
tls
How a TLS client trusts a server: by the system’s trust store (the chain to a trusted authority, and the name in it), or by one certificate’s SHA-256 fingerprint alone, for a server whose certificate is self-signed. A pinned certificate is still made to prove it holds its key: the handshake’s signatures are checked against it as for any certificate; only the chain and the name are replaced by the fingerprint.

Structs§

Adoption
An existing Terraform deployment to adopt as a run (Runner::adopt): where its local state is, and what the runner can’t read from that state (where it is, when it expires).
Captured
What a process printed, kept: its standard output, and its last standard error lines.
Console
A machine’s graphical console the runner reached: where it answers, and how to sign in.
ConsoleOffer
What a status says of a machine’s graphical console: its protocol, or none and why.
Download
One recorded download.
DownloadId
A recorded download’s id in the home’s store.
DownloadRemoval
The removal of one recorded download.
ErrorDetail
A failure’s typed fields.
ErrorReport
A failure, as one value: its stable code, its message, the step it happened in, its typed fields, and whether the run was touched. An embedder branches on ErrorReport::code and reads ErrorReport::detail’s fields; it never needs the runner’s Error variants.
Event
One event of the stream.
EventLog
A run’s logged events (crate::Runner::events), and how many of the log’s lines it couldn’t read as one: a line another version of the runner wrote (an event kind or a code this one doesn’t know), or one cut short.
ExecReport
What a command run in a machine of the run said (Running::exec).
Exit
How a process ended.
FakePortsfake
Ports answered from a test’s setup (feature fake): the free ones handed out in order. An embedder’s tests script those only; the runner’s own also mark ports taken, addresses answering and binds refused.
GuestPort
A port inside a machine: a container’s target port, a VM’s own port. Reached from this computer only through the host port its driver gives it (HostPort).
HostPort
The port a published port is reached at, at its machine’s host address: on this computer’s loopback where the engine forwards it here (Compose, a local VM). Only a host port is reserved, checked free or reported.
IllegalTransition
A move the table doesn’t allow.
InputVariable
One input variable of a Terraform module, as its variable block declares it.
MachineStatus
One machine of the run, as its tool reports it.
MachineUsage
What one machine of a run uses now, as its engine reports it (several instances of it, a service scaled up, summed).
NativeApp
The hypervisor’s own app that shows a running VM’s screen in a window of its own, and what of it this computer must have (any one of needs).
NativeConsole
What opens a running VM’s screen in its hypervisor’s own app.
OutputValue
An output’s value (a Terraform module’s output). A sensitive one shows as *** wherever it is written out (its JSON, its Debug, an event); the runner keeps the value itself for the embedder (OutputValue::revealed).
PortHolder
The process that holds a host port: what a port_in_use names so the user knows what to stop.
ProcessFailed
A process that ran to its end and didn’t exit 0 (Captured::output): how it ended, and why, in the one wording every failed tool’s error uses (Captured::reason).
ProcessSpec
One process to start.
Project
A project to run: its folder, its format and the files that make it one.
ProxmoxVnc
Proxmox VE’s VNC websocket for one VM, opened for one session: connect to websocket with the authorization header (its certificate pinned, not chain-verified, when insecure), then speak VNC with ticket as the password. Every secret is a SecretValue: never print or log one.
PublishedPort
A published port: where a machine’s port answers on the host.
RunName
A run’s name: 1 to 63 lowercase letters, digits, - or _, starting with a letter or digit (Compose’s rule for a project name), and not a Windows device name (con, nul, com1…), which can’t name a folder there.
RunOptions
The options of one operation.
Runner
The runner.
RunnerConfig
How a runner is built: its home, and the ports it reaches the world through. Start from RunnerConfig::new and set a field to change it (config.processes = Arc::new(fake)).
Running
A run of a project folder.
SecretValue
A secret’s value. Its Debug never shows it.
Secrets
Sensitive values, by the name the tools get each under.
ServiceEndpoint
A service endpoint the deployment publishes, as this computer reaches it.
ShellCommand
The command that opens an interactive console into a machine (a shell in a container, vagrant ssh, an SSH login): the runner builds it (it alone knows the runtime: the Compose project and files, the Vagrant define, the address and user a module gives), the embedder runs it in its own terminal. Addresses the machine by service or define name, or by the address the run gives it, never a guessed container.
ShownOutput
An output as a result event shows it.
Started
A run that came up (or resumed).
Status
A run as it stands.
StepCount
How far a step is: done of its total items, when the total is known.
SweepFailure
A run a reap couldn’t destroy.
SystemProcesses
Starts real processes. SystemProcesses::default reads the Docker CLI’s config ($DOCKER_CONFIG/config.json, else ~/.docker/config.json) to learn whether the user picked an engine context of their own.
Transition
A legal move of a run, from one state to another, with what moved it. Its fields are private: the constructors are the only way to one, and each checks the move.
Tunnel
An open tunnel to a machine’s console: where it listens, and its ssh, ended when it is dropped (and its ledger entry removed).
Version
A tool’s version: major.minor.patch, with an optional pre-release (2.17.0, 1.0.0-rc.1). Ordered as versions are (semver precedence): by the numbers, then a pre-release before the release it leads to, two pre-releases by their dot-separated fields (numbers as numbers, a number before text, fewer fields first when they tie).

Enums§

Arch
A CPU architecture.
Cause
What moved a run.
Cloud
A public cloud.
ConsoleProtocol
The protocol a graphical console speaks.
Desired
What a user wants of a run: set by the commands, never by an observation.
Detail
A failure’s typed fields, by its kind.
DownloadItem
What a run’s tool fetched.
DownloadKind
What a download fetches.
DownloadToAdopt
A download to adopt, as the program that fetched it recorded it.
DownloadsToRemove
Which recorded downloads a removal takes: all, or those of the given ids.
Endpoint
Where a graphical console answers.
Error
Why an operation of the runner failed.
ErrorCode
The stable code of a failure, the same in the Rust API and the event stream (error.code).
EventKind
What happened.
Format
The format of a project, which is the tool that runs it.
HostOs
A host operating system.
HyperVRights
Whether this account may manage Hyper-V (may_manage_hyperv’s answer).
MachineState
A machine’s state, as its engine reports it.
NativeNeed
What of a hypervisor’s app must be on this computer for a way to open it.
NativeOpen
One way to open a VM in its hypervisor’s app: what to run, never through a shell.
Op
An operation on a run.
OperationPhase
Where a journaled operation stands.
Park
How a run is parked: the manifest’s lifecycle.park.pause or .shutdown steps.
Phase
A step of an operation: its id in a step event.
ProcessError
Why a process couldn’t run to its end.
Protocol
A port’s transport protocol.
Provider
A Vagrant provider: the hypervisor vagrant up --provider takes. Exhaustive: whoever detects or offers providers (isothrum-machine) fails to compile until a new one has its row.
ProviderNeed
What a computer lacks for a Vagrant provider to run a run.
RemovalOutcome
How the removal of one recorded download went.
ResultData
What an operation found or produced, by operation.
RunState
Where a run stands.
StepState
Where a step stands.
Stream
Which output of a tool a line came from.
TimedOut
Which limit a step ran into: a timeout’s, also the error event’s timeout.
WarningCode
What kind of warning a warning event is, the same in the Rust API and the event stream.

Constants§

DETAIL_VERSION
The version of ErrorDetail’s fields.
RUN_KEY_VAR
The variable every tool of a run gets its run’s key in (copy_key): Isothrum’s, set for every command of every driver, for a project that names what it makes on the host after it (two copies of one project then never share a VM, a network or a domain name).

Traits§

Events
Where an operation’s events go. Implemented for closures (|e: &Event| …).
HostPorts
The host’s ports. Sealed: RunnerConfig::new gives the real host’s (sockets on the loopback), and the fake feature’s FakePorts answers from a test’s setup; no other implementation is needed, and only the runner asks them anything.
ProcessRunner
Starts processes. Dropping the future of ProcessRunner::run before it resolves (a timeout, a cancelled operation) ends the process and everything it started.

Functions§

azure_cli_version
The Azure CLI’s version, the azure-cli entry of the JSON az version --output json prints; none when the answer isn’t that JSON or the entry isn’t text. A --query would need quotes, which can’t pass through cmd.exe (az is a .cmd).
capture
Runs spec, keeping what it prints.
copy_key
The key of run name‘s copy on the runner whose home is home: six lowercase letters and digits (FNV-1a of the home and the name, in base 36), the same at every operation of the run. Every tool of the run gets it in RUN_KEY_VAR; an embedder hands it on under the name a project reads (RunOptions::with_env). The runner’s clean-up only ever takes a VM whose name carries it. For an embedder that finds its runs’ VMs by name.
events_schema
The JSON Schema of one event.
every_name
Every name the unit enum T is written as, from its JSON Schema (each variant’s const, or the enum that lists them), in the schema’s order: the values a command line offers for a type of another crate’s, so a variant added there is offered without a list of its own to keep in step.
from_wire_name
The value of the unit enum T that the manifest writes as name (vmware_desktop): the way back from wire_name. None when no value of T has that name.
may_manage_hyperv
Whether this account may manage Hyper-V, as Vagrant’s Hyper-V provider requires for every command on its machines (vagrant status included): its token is elevated, or it is a member of “Hyper-V Administrators”. Read from whoami /groups, run through processes (no unsafe). HyperVRights::Unknown when whoami can’t say (it didn’t run, or failed), which is traced.
park_modes
The ways a run of format, on the Vagrant provider (none: not Vagrant’s, or not known yet), can be parked: Compose pauses (pause) and stops; Vagrant suspends and halts, but for QEMU’s provider, which has no suspend; Terraform parks nothing (park is refused).
percent_encoded
s percent-encoded for a URL’s query value: unreserved characters (A-Z a-z 0-9 - . _ ~) as they are, every other byte as %XX.
port_holder
The process listening on this computer’s host port (protocol), asked of the system’s own tools through processes, each given limit: when one is found. Best-effort: none when no tool answers or names a process (ss run without root names none, nor does a listener of another user’s on some systems).
process_started_at
When process pid started, in whole seconds since the Unix epoch, as the OS stored it (on Unix ps’s lstart, on Windows its creation time); none when no process has that pid, or the OS couldn’t say. A process whose start is after a moment can’t be one that ran at it: what tells a reused pid from the process that had it.
rfc3339
time as YYYY-MM-DDTHH:MM:SSZ (UTC, whole seconds; before 1970 reads as 1970).
rfc3339_seconds
A time rfc3339 wrote (YYYY-MM-DDTHH:MM:SSZ, a fraction of a second allowed and dropped) as whole seconds since the Unix epoch; none for any other text.
sign_in_expired
Whether said, what a cloud’s tool printed, says its sign-in ran out or is missing.
status_schema
The JSON Schema of a run’s status (isothrum status --json).
this_arch
This build’s CPU architecture, as Vagrant names a box’s build (an x86-64 build reads as amd64, an ARM one as arm64).
this_host
This build’s host operating system.
vagrant_plugins
Each plugin vagrant plugin list --machine-readable names (its plugin-name lines), with its version when a plugin-version line gives one (0.12.2%!(VAGRANT_COMMA) global: the version before Vagrant’s escaped comma).
variables_of
The input variables of the Terraform module in dir.
version_found
The version text says (what a tool prints: Vagrant 2.4.1, v2.29.1, 1.0.0-rc.1), as a Version, so versions compare in its order (a pre-release before its release): its first word that is one, else its first <major>.<minor>[.<patch>] (2.3.8.dev is 2.3.8, a missing patch 0). None when it says none: nothing is held back then. The one reading of a version for the runner’s tool probes and isothrum-machine’s minimums.
virtualbox_vms
(name, uuid) of each VM VBoxManage list vms prints ("<name>" {<uuid>} per line).
wire_name
value’s name as the manifest and the event stream write it (a target, a provider, a machine’s role: vmware_desktop), without JSON’s quotes. It is meant for the unit enums serde writes as a string; any other value is named by its JSON text (3), and one serde can’t write by why, so a name is never silently empty.

Type Aliases§

BoxFuture
A boxed future that can be sent between threads.
OnLine
Receives each line a process prints, with the output it came from.
Result
The runner’s Result: its error is a Error unless said otherwise.