Captain / Documentation / Part 6. The standard library

System and tool modules

Contents ↓

The modules under lib/system/ wrap the runtime's native host capabilities; the modules under lib/tools/ wrap command-line programs. A wrapper owns everything a careless exec would get wrong: argument vectors, a supported version floor, bounded output, exit codes, and typed failures. Prefer one of these to a raw exec when it covers what you need.

They are production code in the sense that they are written and tested to be relied on, but they are not published packages: build them from source with -I lib. All of them need only VM generation 2.

Two things to know before calling them

Exports with no keywords are entry points only. Captain has no zero-argument calls (a deliberate rule: reading a member is always (x member)). So minimumVersion, version, update, daemonReload, osRelease, nameServiceHosts, listeningPorts and maximumTextRead can be run with captain run module.capb version, but no Captain code can call them.

Most results are enums. Captain v0.1 has combinators only for Option and Result (ifSome:ifNone:, ifOk:ifFail:); a general match is deferred. So a CurlResult or ServiceInspectResult is mostly returned from an entry point, where captain run prints it, or passed on to a caller. Structs and enums has the details.

The wrappers' failures share a shape: a struct { code: i32, kind: Symbol, message: Text } where code is the program's exit status (or -1 when the wrapper failed before running it), kind a symbol such as #UnsupportedVersion, #VersionProbeFailed or a tool-specific one, and message the program's standard error. A missing binary, an output overflow or a timeout is not one of these: it fails the underlying exec effect.

System::File

lib/system/file.capt. Bounded UTF-8 file reading through the native readFileText, never through cat.

Export Gives What it does
readText path: Path maxBytes: Bytes FileText the file's content, size and SHA-256; regular files only, no links, valid UTF-8 only. Effect: readFileText
maximumTextRead Bytes 16MiB, the runtime's ceiling for one read (entry point only)

System::Diagnostics

lib/system/diagnostics.capt. Read-only workstation observation. Every entry observes and nothing more, but exec is one effect whatever it runs, so the manifest still says mutating: run it under the read-only policy (captain run --read-only) to have the host enforce the boundary. That policy admits the programs these entries run (getent, ss, systemctl's reporting verbs), and needs no --allow-exec; without --read-only, captain run refuses an entry that runs a program unless it is given --allow-exec (Host policies). Imports Std::Text, System::File and Tool::Systemctl.

Export Gives What it does
resolveHost name: Text NameResolution resolves through the system name service with getent hosts, so /etc/hosts, mDNS and DNS all apply as they would to any program
service name: Text Systemctl::ServiceInspectResult a unit's load, active, sub and unit-file states, via Systemctl::inspect service:
readConfig path: Path maxBytes: Bytes FileText one bounded configuration file
nameServiceHosts NameServiceOrder the sources on the hosts: line of /etc/nsswitch.conf (entry point only)
listeningPorts List[ListeningSocket] listening TCP sockets from ss -H -l -t -n (entry point only)
osRelease OsRelease ID, VERSION_ID and PRETTY_NAME from /usr/lib/os-release (entry point only)
Type Fields
NameResolution name: Text, resolved: bool, addresses: List[Text]
ListeningSocket state: Text, localAddress: Text
NameServiceOrder sources: List[Text]
OsRelease id: Text, versionId: Text, prettyName: Text

osRelease reads /usr/lib/os-release, not /etc/os-release: on Debian and Ubuntu the latter is a symbolic link, and the native read refuses links. A local override in /etc is therefore not seen.

System::Linux

lib/system/linux.capt. The small set of facts needed to choose a package and service adapter for a Linux host. Imports Std::Text.

Export Gives What it does
inspect host: bool Result[LinuxHost] kernel name (uname -s, must be Linux), architecture (uname -m), ID and VERSION_ID from /etc/os-release (via shell), and the file system of /run (findmnt)
effect requireBootstrapHost on: SshHost expectedPackageManager: Symbol Text inspect on the remote host, failing unless the package manager matches, the service manager is systemd and /run is tmpfs; gives "compatible"

LinuxHost has osId, osVersion, architecture, runFilesystem: Text, and packageManager, serviceManager: Symbol. packageManager is #Apt for Ubuntu and Debian, #Dnf for Fedora and RHEL, else #Unknown; serviceManager is always #Systemd. Because it uses shell, no read-only policy admits it; System::Diagnostics::osRelease is the read-only alternative.

System::RemoteLinux

lib/system/remote_linux.capt. Imports System::Linux.

Export Gives What it does
inspect at: Address Result[Linux::LinuxHost] binds the host with observe serverAt:, enters it over SSH, and runs Linux::inspect host: there

System::RemoteFile

lib/system/remote_file.capt.

Export Gives What it does
effect installText on: SshHost path: Path content: Text expectedDigest: Digest owner: Text mode: Text FileInstall exact-content atomic installation through the native installFileText (Files); unchanged if the file already matches

Tool::Curl

lib/tools/curl.capt. Requires curl 7.68.0 or newer. Imports Std::Text.

Export Gives What it does
get url: Url CurlResult checks the installed version, then fetches with --fail --silent --show-error --location --max-time 30; body up to 8 MiB
version Result[CurlVersion] the installed version (entry point only)
minimumVersion CurlVersion 7.68.0 (entry point only)

CurlResult is CurlOk(response: CurlResponse { body: Text }) or CurlFail(error: CurlFailure). Failure kinds name curl's exit codes: #UnsupportedProtocol, #MalformedUrl, #ProxyResolutionFailed, #HostResolutionFailed, #ConnectionFailed, #HttpError, #TimedOut, #TlsHandshakeFailed, #TooManyRedirects, #CertificateRejected, else #TransferFailed. CurlVersion is { major, minor, patch: i32 }. The prelude's http get: is the native alternative.

Tool::AptGet

lib/tools/apt_get.capt. Debian and Ubuntu package installation. Requires apt-get 2.0.0 or newer. Imports Std::Text.

Export Gives What it does
install packages: List[Text] AptResult apt-get -q -y --no-install-recommends install -- ... for exact specifications such as "name=1.2.3"; an empty list does nothing
install package: Text AptResult the same for one package
refresh indexes: bool AptResult apt-get -q update
update AptResult the same (entry point only)
version, minimumVersion Result[AptVersion], AptVersion entry points only

AptResult is AptOk(output: Text) or AptFail(error: AptFailure); exit code 100 is #PackageOperationFailed, other failures #AptFailed.

Tool::DpkgQuery

lib/tools/dpkg_query.capt. Installed-package observation. Requires dpkg-query 1.19.7 or newer. Imports Std::Text.

Export Gives What it does
inspect package: Text PackageInspectResult status, name, version and architecture of one installed package
version, minimumVersion Result[DpkgToolVersion], DpkgToolVersion entry points only

PackageInspectResult is PackageFound(package: InstalledPackage), PackageAbsent or PackageInspectFailed(error: DpkgFailure). InstalledPackage has status, name, version and architecture, all Text. Debian versions stay Text on purpose: their epochs, revisions and ordering are not semantic versioning.

Tool::Systemctl

lib/tools/systemctl.capt. Requires systemd 245 or newer. Imports Std::Text. Observation uses systemctl show, never the human-oriented status display.

Export Gives What it does
inspect service: Text ServiceInspectResult LoadState, ActiveState, SubState and UnitFileState of one unit
start service:, stop service:, restart service:, reload service:, enable service: ServiceActionResult that action on one unit
enableAndStart service: Text ServiceActionResult enable --now
reload units: bool ServiceActionResult daemon-reload, after installing or replacing a unit file
daemonReload ServiceActionResult the same (entry point only)
effect requireStart on: SshHost service: Text Text start, failing the effect if systemctl fails
effect requireStop, requireRestart, requireEnable (on: SshHost service: Text) Text the same for those actions
effect requireDaemonReload on: SshHost units: bool Text the same for daemon-reload
version, minimumVersion Result[SystemdVersion], SystemdVersion entry points only

ServiceInspectResult is ServiceFound(state: ServiceState) or ServiceInspectFailed(error: SystemctlFailure); ServiceState has loadState, activeState, subState and unitFileState, all Text. ServiceActionResult is ServiceActionOk(output: Text) or ServiceActionFailed(error: SystemctlFailure). The require... effects are for steps where carrying on after a service-manager error would be unsafe: they stop the run instead of returning a value to inspect.

Tool::Ripgrep

lib/tools/ripgrep.capt. Recursive text search that returns where matches are, never the matched text. Requires rg 11.0.0 or newer. Imports Std::Text.

Export Gives What it does
findText pattern: Text beneath: Path maxMatches: i32 SearchOutcome regular-expression search beneath a directory or in one file
findLiteral text: Text beneath: Path maxMatches: i32 SearchOutcome the same, matching text literally
version, minimumVersion Result[RipgrepVersion], RipgrepVersion entry points only

SearchOutcome is MatchesFound(matches: List[Match], truncated: bool), NoMatches or SearchFailed(error: RipgrepFailure). Match has path: Text, lineNumber: i32 and column: i32. maxMatches bounds both ripgrep's per-file count and the total returned. To see a matched line, read the file with File::readText, which also gives the digest of what you saw. Binary files, links and ignored paths are skipped by ripgrep's own defaults. Run it under a policy that admits rg with named flags only: --pre and --search-zip would start other programs.

Tool::Useradd

lib/tools/useradd.capt.

Export Gives What it does
effect ensureSystemUser on: SshHost name: Text UserEnsureResult id -u name; if the account is missing, useradd --system --user-group with no home directory and /usr/sbin/nologin as its shell. Fails the effect if creation fails

UserEnsureResult is { changed: bool, name: Text }.

Example

workstation.capt
module Example::Workstation.

use System::File.
use System::Diagnostics.
use Tool::Ripgrep.

;; Where a setting is mentioned beneath a directory: paths and positions only.
export mentions of: Text beneath: Path -> Ripgrep::SearchOutcome [
  ret Ripgrep::findLiteral text: of beneath: beneath maxMatches: 50.
].

;; Whether a name resolves, through the system's real name service.
export resolves name: Text -> bool [
  ret ((Diagnostics::resolveHost name: name) resolved).
].

;; A configuration file with its size and digest.
export config path: Path -> FileText [
  ret File::readText path: path maxBytes: 256KiB.
].

captain inspect shows what the program may do before it does anything:

Terminal
$ captain inspect workstation.capt -I lib
package  Example::Workstation 0.0.0
sha256   [..]
compiler 0.1.0   vm 2   stripped

exports
  config path: Path -> FileText  (mutating)  [readFileText path:maxBytes:]
  mentions of: Text beneath: Path -> Tool::Ripgrep::SearchOutcome  (mutating)  [exec program:args:]
  resolves name: Text -> bool  (mutating)  [exec program:args:]
...
tools
  getent  *
  rg  >=11.0.0
  ss  *
  systemctl  >=245.0.0
...

The tools list covers every module linked into the artifact, not only the code each export reaches: ss and systemctl appear because System::Diagnostics is linked whole, although no export here runs them.