Python API

Generated from the docstrings in src/cloud_boot. cloud-boot is a command-line tool, so this reference is for contributors and includes private members.

Errors

Shared error contract for cloud-boot components.

This module holds only the base error, its phases, and the exit-code table, and imports nothing else from the package. Each component defines its own CloudBootError subclasses next to the code that raises them, so callers can handle every expected failure through one stable shape.

class cloud_boot.errors.ErrorPhase(*values)

Bases: StrEnum

Where in a run a failure happened.

ErrorPhase tells a reader where to look; it does not choose the exit code. The two are independent on purpose: a timeout can happen in any phase but always exits with ExitCode.TIMEOUT, and a PROCESS failure exits with HOST_UNAVAILABLE when a command cannot start or TIMEOUT when it runs out of time. INTERRUPT marks a run the user stopped. INTERNAL marks a cloud-boot bug and is the default for an unclassified error.

A failed assertion is a run outcome, not an error; ASSERTION marks only a run that ran out of time while assertions were being checked. Scenario validation fails before any run exists and is reported by the CLI directly.

Values appear in report.json and on stderr as ERROR <phase>: ..., so renaming one is a breaking change to the report schema.

class cloud_boot.errors.ExitCode(*values)

Bases: IntEnum

Process exit codes; the public contract scripts and CI rely on.

Codes 3-9 follow the order of a run, so a larger code means the run got further. Code 1 is left unused so that a Python crash outside cloud-boot’s own handling stays distinguishable. Signal codes follow the shell convention of 128 plus the signal number.

Only SIGINT is produced today (Ctrl-C, after normal cleanup). SIGHUP and SIGTERM are reserved: their handlers do not exist yet, so those signals currently end the process without cleanup.

exception cloud_boot.errors.CloudBootError(message, *, code='internal-error', phase=ErrorPhase.INTERNAL, remediation=None, context=None, exit_code=ExitCode.INTERNAL)

Bases: Exception

Base class for expected failures: anything cloud-boot anticipates and can report.

Each component subclasses this next to the code that raises it and sets its own code, phase, and exit_code. Unexpected exceptions are not subclasses; the coordinator wraps them as an internal error instead.

Parameters:
  • message (str) – Short user-facing text, printed as ERROR.

  • code (str) – Stable kebab-case identifier that scripts can match instead of parsing message.

  • phase (str) – Where the failure happened; must be an ErrorPhase value. An unknown value is a programming error and raises ValueError.

  • remediation (str | None) – Optional next step for the user, printed as HINT.

  • context (Mapping[str, object]) – Structured diagnostics for report.json. It is copied on construction and exposed as a read-only Mapping, so code that catches the error cannot edit it. Keep it to metadata such as paths, URLs, and return codes, plus bounded tails of command output. Never put secrets here: it is written to disk unredacted.

  • exit_code (int) – Process exit code for this failure.

The defaults all mean “internal”, so an unclassified error is reported as a cloud-boot bug.

Running commands

Bounded, injectable host-process execution: every external command goes through here.

Guarantees for every command:

  • No shell: argv is passed as a list with shell=False, so nothing is ever shell-parsed.

  • Bounded time: every wait has a monotonic deadline; on expiry the whole process group gets SIGTERM, then SIGKILL after a grace period.

  • Own process group: children start in a new session, so stopping one also stops anything it spawned and a terminal Ctrl-C reaches cloud-boot first.

  • Minimal environment: only allowlisted variables are inherited from the host.

  • Bounded memory: captured stdout/stderr stop growing at a limit; live sinks still see every byte.

This layer reports what happened and does not interpret exit statuses. Callers decide what a status means and which cloud-boot phase and exit code it maps to.

exception cloud_boot.process.ProcessStartError(message, *, context=None, remediation=None)

Bases: CloudBootError

The child process could not be created at all (missing binary, no permission, bad argv).

Raised by CommandRunner.start when Popen itself fails, so no process exists and nothing needs cleaning up. The exit code is always HOST_UNAVAILABLE because the usual cause is a host tool that preflight did not catch, such as a binary that exists but cannot run.

exception cloud_boot.process.ProcessTimeoutError(message='command exceeded its deadline', *, context=None, result=None)

Bases: CloudBootError

A deadline expired before a command finished; callers treat it as “out of time”.

Raised in three situations:

  • ManagedProcess.wait reached its deadline. The process group has already received SIGTERM and, if needed, SIGKILL.

  • ManagedProcess.stop sent SIGKILL and the process still had not exited by the deadline. It may still be running, for example while blocked in uninterruptible I/O.

  • The coordinator refused to start a guest command because the run deadline had already passed. No process exists in this case.

result holds whatever output was captured, or None when no process was involved. The exit code is always ExitCode.TIMEOUT.

class cloud_boot.process.ByteWriter(*args, **kwargs)

Bases: Protocol

Interface for one output destination: anything with a write(bytes) method.

Sink is what a single stream accepts (this, a plain callable, or None), and StreamSinks pairs one Sink for stdout with one for stderr. The return type is object so both file.write, which returns a byte count, and writers that return None qualify.

write(data)

Consume a chunk of output.

class cloud_boot.process.PopenLike(*args, **kwargs)

Bases: Protocol

The part of subprocess.Popen that ManagedProcess uses; test fakes implement only this.

class cloud_boot.process.MemorySink(limit=None)

Bases: object

Thread-safe in-memory byte buffer, optionally keeping only the newest limit bytes.

ManagedProcess uses one per stream for the output that ends up in CommandResult; callers can also pass one as a live sink. The lock is needed because the stream’s reader thread writes while another thread may read.

Without a limit, every byte is kept. With a limit, only the most recent limit bytes are kept, because the end of a child’s output usually explains its failure; older bytes are counted in dropped_bytes so truncation is never silent.

write(data)

Append bytes under a lock so concurrent writers cannot interleave chunks.

getvalue()

Return an immutable snapshot unaffected by later writes.

property dropped_bytes: int

Return how many of the oldest bytes were discarded to stay within the limit.

class cloud_boot.process.StreamSinks(stdout=None, stderr=None)

Bases: object

Live destinations for one process: a Sink for stdout and one for stderr.

Bundled into one object so it can pass unchanged through CommandRunner down to the stream reader threads. These receive every byte, in addition to the bounded in-memory capture; None, the default, means capture only. For example, vm.py streams the QEMU serial console to the console log, and ssh.py streams a guest file straight to disk.

class cloud_boot.process.SinkFailure(stream, error)

Bases: object

A live output sink that raised and stopped receiving output.

The reader keeps draining the stream after a failure, so the child never blocks on a full pipe or receives SIGPIPE; only forwarding to the failed sink stops.

Failures are reported in CommandResult.sink_failures, and the caller decides whether they matter: the coordinator logs a console-log failure as a warning, while a guest file copy treats one as a failed copy.

cloud_boot.process._write_sink(sink, data)

Forward one chunk of child output to a caller-provided sink.

A sink is either an object with a write(data) method, such as an open file or MemorySink, or a plain callable, such as list.append. None disables forwarding, and any other value is silently ignored. The value returned by the sink is discarded.

This runs on a stream reader thread. A sink shared by stdout and stderr receives writes from two threads at once and must be thread-safe. Exceptions raised by the sink propagate to the reader thread, which records them as a SinkFailure and stops forwarding to that sink.

Parameters:
  • sink (Sink) – Destination for the chunk, or None to drop it.

  • data (bytes) – Bytes just read from the child’s stdout or stderr.

class cloud_boot.process.CommandSpec(argv, cwd=None, env=None, env_allowlist=<factory>, stdin=None, name=None, capture_limit_bytes=1048576)

Bases: object

What to run and how, validated on construction so a bad command fails before any process.

Fields are normalized: argv becomes a tuple, cwd a Path, and env and env_allowlist are copied, so the spec cannot change after it is built.

Parameters:
  • argv (tuple[str, ...]) – Program and arguments, passed to the OS without a shell. Empty arguments are allowed (ssh-keygen -N "" needs one); NUL bytes and an empty program name are not.

  • cwd (Path | str | None) – Working directory for the child, or None to inherit cloud-boot’s.

  • env (Mapping[str, str] | None) – Extra variables merged over the inherited host variables. Every key must itself be in env_allowlist, so a typo or a secret is rejected instead of silently passed.

  • env_allowlist (frozenset[str]) – Host variables the child may inherit and env may set.

  • stdin (bytes | None) – Bytes written to the child’s stdin, which is then closed; None connects stdin to /dev/null so a child can never wait for terminal input.

  • name (str | None) – Short label for diagnostics, such as "qemu-img", used instead of argv[0].

  • capture_limit_bytes (int) – Per-stream in-memory capture limit; see MemorySink.

cloud_boot.process.tail_text(data, limit)

Decode the last limit bytes of data, such as a command’s stderr, for a message.

A multibyte character cut at the boundary decodes as U+FFFD instead of raising.

class cloud_boot.process.CommandResult(argv, returncode, stdout, stderr, duration_seconds, timed_out=False, sink_failures=(), stdout_dropped_bytes=0, stderr_dropped_bytes=0)

Bases: object

What a finished child process did. Nothing here is interpreted; callers decide meaning.

returncode follows subprocess: a negative value means the child was killed by that signal, for example -9 for SIGKILL. stdout and stderr hold only the newest bytes up to the capture limit; stdout_dropped_bytes and stderr_dropped_bytes count what was cut, so callers can tell complete output from a tail. timed_out is set when cloud-boot had to stop the child at its deadline, even if the child then exited 0. sink_failures lists live sinks that failed.

property succeeded: bool

Whether the child exited 0 on its own, without being stopped at its deadline.

stderr_tail(limit=2048)

Decode the last limit bytes of stderr for an error’s context.

A multibyte character cut at the boundary decodes as U+FFFD instead of raising.

cloud_boot.process._resolve_deadline(*, timeout, deadline, clock, default)

Turn a relative timeout or an absolute deadline into one absolute monotonic deadline.

Exactly one of timeout and deadline may be given; with neither, default seconds from now is used. A deadline already in the past is allowed and simply means “expired”. Infinite and NaN values are rejected, so every wait stays bounded.

class cloud_boot.process.ManagedProcess(process, spec, sinks, *, clock, sleeper, termination_grace_seconds)

Bases: object

A running child process: bounded waiting, process-group signals, and live output capture.

Created by CommandRunner.start; most callers use CommandRunner.run instead and never see one. It is for long-running children such as QEMU, which vm.py starts, leaves running, and later stops. Reader threads start on construction, so every instance must end with wait or stop, which collect the threads and return the CommandResult.

property pid: int

Return the child PID, also its process-group ID since the child starts a new session.

poll()

Return the current exit status without waiting.

property sink_failures: tuple[SinkFailure, ...]

Return output sinks that have failed so far; readable while the child still runs.

_start_reader(stream, name, capture, sink)

Start a daemon thread that copies one child stream into capture and the live sink.

It uses read1 when available, which returns as soon as any bytes arrive instead of waiting for a full 64 KiB block, so live sinks such as the console log stay current. Each chunk reaches capture first, so the in-memory tail survives a failing sink. The thread ends at EOF, which comes only once every process holding the pipe’s write end has exited; _finish handles children whose descendants keep it open.

_start_stdin_writer()

Start a daemon thread that writes spec.stdin once and then closes the pipe.

Closing sends EOF, which is how sh -s on the guest knows the script is complete. If the child exits without reading everything, the write fails with BrokenPipeError (Python ignores SIGPIPE, so cloud-boot itself is not killed). That is not an error here: the child’s exit status already says what happened.

_signal_group(sig)

Send sig to the child’s whole process group, falling back to the child alone.

The child leads its own session, so its PID is the group ID and killpg also reaches anything it spawned, such as a grandchild still holding an output pipe. If the group no longer exists, only the child itself is signalled, which Popen ignores once the child has been reaped. Errors are swallowed: signalling is best effort, and callers check the outcome with poll.

POSIX only, like the rest of cloud-boot: Windows would need a Job Object to reach a child’s descendants, not a branch here.

terminate()

Send SIGTERM to the process group, asking it to exit.

kill()

Send SIGKILL to the process group; it cannot be caught or ignored.

_join_threads(deadline)

Wait for every helper thread to end, but never past deadline.

_fallback_returncode()

Return the real exit status if the child has exited, else -SIGKILL as a placeholder.

Used only when the child survived SIGKILL until the deadline, so the result is always marked timed_out and the placeholder is never mistaken for a real status.

_finish(returncode, *, timed_out=False, join_deadline)

Collect the helper threads and build the result, never waiting past join_deadline.

Readers still running after the first join mean a descendant still holds an output pipe, so the whole group is killed to release it. Threads still alive at the deadline are left behind (they are daemons), and the result uses whatever output was captured so far.

_wait_until(deadline)

Poll until the child exits or deadline passes; return its status, or None on timeout.

Polls every 20 ms through the injected clock and sleeper rather than Popen.wait, which uses real time, so tests can drive deadlines with a fake clock.

stop(*, timeout=None, deadline=None)

Stop the process group: SIGTERM first, then SIGKILL if needed, within one deadline.

The end of the deadline, up to the grace period but never more than half of the time left, is reserved for SIGKILL to take effect; SIGTERM gets the rest. With neither timeout nor deadline, the grace period plus one second is used.

Raises:

ProcessTimeoutError – If the child is still running at the deadline even after SIGKILL. Its result holds the output captured so far.

wait(*, timeout=None, deadline=None)

Wait for the child to exit and return its result; on timeout, stop it and raise.

An explicit deadline is a hard boundary: cleanup after a timeout must finish by it too, so an overrunning child gets SIGTERM and SIGKILL with no extra time. A relative timeout allows up to twice the grace period of cleanup after it expires. With neither, DEFAULT_TIMEOUT_SECONDS applies.

Raises:

ProcessTimeoutError – If the deadline passes first. The process group has been signalled, and result holds the output captured before it stopped, marked timed_out. context["survived_sigkill"] is true when the child may still be running.

class cloud_boot.process.CommandRunner(*, clock=<built-in function monotonic>, sleeper=<built-in function sleep>, popen_factory=<class 'subprocess.Popen'>, default_timeout_seconds=300.0, termination_grace_seconds=2.0)

Bases: object

The only way cloud-boot starts host commands; the module docstring lists its guarantees.

One instance is shared by every component. Time and process creation are injected, so tests can replace subprocess.Popen with a fake and drive deadlines with a fake clock.

Parameters:
  • clock (Clock) – Monotonic time source for deadlines.

  • sleeper (Sleeper) – Sleep function used while polling.

  • popen_factory (PopenFactory) – Creates the child process; subprocess.Popen in production.

  • default_timeout_seconds (float) – Used by run when a caller passes neither timeout nor deadline.

  • termination_grace_seconds (float) – Time a process group gets after SIGTERM before SIGKILL.

_environment(spec)

Build the child environment: allowlisted host variables, overridden by spec.env.

start(spec, sinks=None)

Start one command and return it running; the caller must end it with wait or stop.

Raises:

ProcessStartError – If the OS cannot create the process, for example because the program is missing or not executable.

run(spec, *, timeout=None, deadline=None, sinks=None)

Run one command to completion within a bounded time and return its result.

Raises:

Scenario model

The scenario schema: what a valid scenario YAML file looks like, as Pydantic models.

These models only describe and validate data; scenario.py reads the YAML and payload files. Every field uses a strict type, so a value of the wrong type is rejected instead of coerced: YAML and Pydantic would otherwise silently turn "2" into 2 or yes into True. ScenarioV1 is the user-facing schema and BootPlan the normalized form the runner consumes.

class cloud_boot.models.StrictModel

Bases: BaseModel

Base for every scenario model: unknown keys rejected, frozen, defaults validated.

extra="forbid" turns a misspelled key such as timeout_second into an error instead of a silently ignored setting. frozen=True keeps a validated scenario from changing while it is passed between components. validate_default=True checks defaults against the same constraints as user values.

class cloud_boot.models.ImageSpec(*, release='noble', architecture='amd64', variant='server-cloudimg', source='official')

Bases: StrictModel

Which Ubuntu cloud image to boot; only the official Noble amd64 server image for now.

Each field allows a single value today, so the schema already has a place for future releases and architectures: widening a Literal keeps existing scenario files valid. The fields form the image file name, such as noble-server-cloudimg-amd64.img, and source is reserved for non-official images. ImageStore re-checks the values, since it can be called without going through scenario validation.

class cloud_boot.models.ResourceSpec(*, cpus=2, memory_mib=2048, disk_gib=8)

Bases: StrictModel

Virtual hardware for the guest, each value bounded to catch typos before QEMU sees them.

cpus and memory_mib are passed to QEMU as the virtual CPU count (-smp) and memory size in MiB (-m). disk_gib is the virtual size of the qcow2 overlay, which is sparse, so it costs host space only as the guest writes. Its minimum of 4 sits just above the 3.5 GiB virtual size of the Noble cloud image, which an overlay must not be smaller than.

cloud_boot.models._validate_relative_file(value)

Validate that a payload path stays inside the scenario directory.

The path is checked as both a POSIX path and a Windows path, so a scenario is rejected if either platform would read it as absolute or as escaping the directory. This text-only check is the first of three: cloud_boot.scenario._validate_payload_containment resolves symlinks when the scenario loads, and cloud_boot.seed._read_payload_file checks again when the file is read, since it may have changed in between.

Parameters:

value (str) – A file path from the scenario, relative to the scenario file’s directory.

Returns:

The unchanged value when it is a safe relative path.

Raises:

ValueError – If value is empty, contains a NUL byte, is absolute, or contains a component.

Return type:

str

class cloud_boot.models.PayloadSpec(*, inline=None, file=None)

Bases: StrictModel

One cloud-init input (user-data, vendor-data, or network-config), inline or from a file.

Exactly one of inline and file must be set. Inline text is encoded as UTF-8; a file’s bytes are passed through unchanged, so they reach cloud-init exactly as written. file is relative to the scenario file’s directory and must stay inside it. Either way, a payload is limited to cloud_boot.seed.MAX_PAYLOAD_BYTES (16 MiB).

classmethod validate_file(value)

Reject absolute or traversing file paths when a source is provided.

require_one_source()

Raise ValueError unless exactly one payload source is provided.

class cloud_boot.models.SeedSpec(*, instance_id, local_hostname=None, user_data, vendor_data=None, network_config=None)

Bases: StrictModel

What goes on the NoCloud seed disk that cloud-init reads at boot.

cloud-boot writes meta-data itself from instance_id, local_hostname, and the run’s SSH public key, so the run’s own key is always installed. user_data is required. A missing vendor_data becomes an empty file, which cloud-init reads as no vendor configuration, and a missing network_config leaves the file off the disk, so cloud-init applies its default networking.

instance_id is how cloud-init tells instances apart: modules that run once per instance run again only when it changes. local_hostname must be a valid DNS name.

class cloud_boot.models.AssertionBase(*, id, required=True, timeout_seconds=30)

Bases: StrictModel

Fields every assertion has: its ID, whether it counts, and its own time limit.

An assertion with required: false is still run and reported, but its failure does not fail the run. timeout_seconds bounds this one check on the guest; the run’s own limit still applies.

class cloud_boot.models.CloudInitStatusAssertion(*, id, required=True, timeout_seconds=30, type, expected='done')

Bases: AssertionBase

Require cloud-init to have finished cleanly: its extended status must be exactly done.

A run that finished with warnings reports degraded done and fails this check. expected allows only done today; the field leaves room for other terminal states later.

class cloud_boot.models.FileAssertion(*, id, required=True, timeout_seconds=30, type, path, exists=True, content_contains=None)

Bases: AssertionBase

Require a guest file to exist, optionally containing some text, or to be absent.

content_contains is a plain substring match on the file’s bytes and only works for files up to cloud_boot.assertions.MAX_FILE_CONTENT_BYTES (512 KiB); a larger file fails the check.

classmethod validate_guest_path(value)

Require an absolute guest path without NUL bytes or components.

Rejecting keeps the reported path the one that was checked. It is not a security boundary: checks run with sudo and may read any guest file.

validate_content_expectation()

Reject content matching when the file is expected to be absent.

class cloud_boot.models.PackageInstalledAssertion(*, id, required=True, timeout_seconds=30, type, name)

Bases: AssertionBase

Require a Debian package to be installed on the guest, as reported by dpkg.

name follows Debian Policy: at least two characters of lowercase letters, digits, +, -, and , starting with a letter or digit.

class cloud_boot.models.BootPlan(*, name, seed, wait_for_cloud_init=True, assertions=<factory>)

Bases: StrictModel

One boot of the guest, in the normalized form every downstream component consumes.

ScenarioV1.to_boot_plan builds it from the single-boot scenario. Scenarios with several boots will produce one plan per boot, so components already handle plans rather than raw scenarios. name names the boot’s artifact directory, such as boots/001-boot.

wait_for_cloud_init is reserved for multi-boot scenarios. Nothing reads it yet: the runner always waits for cloud-init, and the cloud-init status assertion decides what counts as success.

class cloud_boot.models.ScenarioV1(*, scenario_version, name, description=None, image=<factory>, resources=<factory>, network_mode='nat', timeout_seconds=300, seed, assertions=<factory>)

Bases: StrictModel

A version 1 scenario file: one VM boot, its NoCloud seed, and the checks to run.

scenario_version

Schema version; must be 1.

Type:

Literal[1]

name

Scenario identifier, also used as the QEMU VM name.

Type:

cloud_boot.models.Identifier

description

Free text for readers; no code reads it.

Type:

str | None

image

Which Ubuntu cloud image to boot (a VM disk image, not a container image).

Type:

cloud_boot.models.ImageSpec

resources

Virtual CPU, memory, and disk for the guest.

Type:

cloud_boot.models.ResourceSpec

network_mode

Guest networking; only nat (QEMU user networking). It is not yet passed to the VM backend, which also defaults to nat.

Type:

cloud_boot.models.NetworkMode

timeout_seconds

Limit for the whole run: boot, waiting for cloud-init, and assertions.

Type:

cloud_boot.models.PositiveTimeout

seed

Contents of the NoCloud seed disk.

Type:

cloud_boot.models.SeedSpec

assertions

Checks run on the guest after cloud-init finishes. IDs must be unique.

Type:

list[cloud_boot.models.AssertionSpec]

require_unique_assertion_ids()

Reject repeated assertion IDs; reports identify each result by its ID.

to_boot_plan()

Convert this single-boot scenario into its one BootPlan, named boot.

Loading scenarios

Load a scenario file safely and turn it into validated models.

load_scenario reads at most MAX_SCENARIO_BYTES of UTF-8, parses it with a strict YAML loader (no duplicate keys, bounded aliases and nesting), rejects input that Milestone 0 does not support, validates it against ScenarioV1, and checks that payload files stay inside the scenario’s directory. Every problem is reported as a ScenarioValidationError carrying the field locations.

ScenarioValidationError is deliberately not a CloudBootError: validation fails before any run exists, so there is no report to write, and the CLI prints it and exits with ExitCode.VALIDATION.

class cloud_boot.scenario.ScenarioIssue(location, message)

Bases: object

One problem found while loading a scenario, and where it is.

location is the path of mapping keys and list indices to the offending value, as produced by Pydantic. The loader adds two pseudo-locations of its own: ("source",) for problems reading the file, and ("yaml", "line N", "column M") for YAML syntax errors.

property field: str

The location as a JSONPath-like string, such as $.assertions[1].path.

exception cloud_boot.scenario.ScenarioValidationError(issues)

Bases: ValueError

The scenario cannot be loaded; carries every issue found, not just the first.

The message joins all issues as invalid scenario: <field>: <message>; ..., and issues keeps them as structured values for callers that need more than the text.

Raises:

ValueError – If issues is empty, which would be a loader bug.

class cloud_boot.scenario.LoadedScenario(source_path, source_sha256, scenario, boots)

Bases: object

A validated scenario, where it came from, and the boot plans to run.

source_path is absolute, and payload files are resolved relative to its directory. source_sha256 is the digest of the bytes that were validated, so the report names what ran even if the file changes later. boots holds one plan per boot, in order, and always exactly one in Milestone 0.

class cloud_boot.scenario._StrictSafeLoader(stream)

Bases: SafeLoader

yaml.SafeLoader with the extra checks a scenario needs.

SafeLoader already refuses to build arbitrary Python objects. This subclass also rejects duplicate mapping keys (see _construct_unique_mapping), more than MAX_YAML_ALIASES aliases, and nesting deeper than MAX_YAML_DEPTH. The limits raise ComposerError at the offending node, so they are reported as YAML issues with a line and column.

The counters are per document; yaml.load creates a new loader for each one.

compose_node(parent, index)

Count nesting and aliases, then compose the node as SafeLoader does.

PyYAML calls this once per node and recurses into children, so nesting_depth is the depth of the node being composed, with the root at 1. An alias reuses a node composed earlier instead of recursing, so aliases are counted separately.

cloud_boot.scenario._construct_unique_mapping(loader, node, deep=False)

Build a mapping as SafeLoader does, but reject duplicate and unhashable keys.

PyYAML normally keeps the last of two equal keys, so a repeated name: would silently replace the first. flatten_mapping expands YAML merge keys (<<: *base) first, and merged keys count as present: overriding one in the same mapping is reported as a duplicate. That is stricter than YAML’s merge rules, and it keeps every value explicit.

The mapping is built in one pass, so a mapping that contains itself through an alias fails with PyYAML’s “unconstructable recursive node” error. Lists still use SafeLoader’s constructor and can contain themselves; _find_secret_references reports those.

cloud_boot.scenario._yaml_issue(error)

Turn a PyYAML error into an issue at $.yaml, with a 1-based line and column if known.

Only the error’s one-line problem is kept; PyYAML’s full message adds context lines and a source excerpt. Errors without a position, such as a ReaderError for a control character, keep their whole message instead.

cloud_boot.scenario._find_secret_references(document)

Report every ${secret:...} in the document’s keys or values; Milestone 0 has none.

This runs before schema validation because a secret in a free-text field such as user_data.inline would otherwise pass validation and reach the guest unexpanded. It also reports lists that contain themselves through an alias.

Each container is checked once, even when aliases share it, so the work grows with the document rather than with its expanded tree, and a secret in a shared container is reported at its first location only. Only the dicts and lists that plain YAML produces are walked; tagged collections such as !set are skipped, and no schema field accepts them.

cloud_boot.scenario._pydantic_issues(error)

Turn each Pydantic error into an issue at the same location.

Input values and documentation URLs are left out: a value may be a whole user_data document, and the URLs are aimed at developers rather than scenario authors.

cloud_boot.scenario._payloads(seed)

The seed’s payloads that are set, each with its field name, in seed order.

cloud_boot.scenario._validate_payload_containment(scenario, scenario_dir)

Check that each payload file, after resolving symlinks, is a regular file in the directory.

This is the second of the three containment checks described in cloud_boot.models._validate_relative_file. It runs at load time so that a missing or misplaced file fails validation before any image is downloaded. cloud_boot.seed checks again when it reads the file, since the file can change in between.

cloud_boot.scenario._read_scenario(path)

Read the scenario as UTF-8 text, refusing anything over MAX_SCENARIO_BYTES.

At most one byte past the limit is read, so even a huge file or a device such as /dev/zero is rejected without being read in full.

Returns:

The decoded text, and the SHA-256 of the exact bytes it was decoded from.

Raises:

ScenarioValidationError – At $.source if the file cannot be read, is too large, or is not valid UTF-8.

Return type:

tuple[str, str]

cloud_boot.scenario.load_scenario(path, environ=None)

Load, validate, and normalize one Milestone 0 scenario file.

The checks run in order, and the first stage that finds problems raises with all of that stage’s issues: reading the file, parsing YAML, rejecting input Milestone 0 does not support (boots, fault, and ${secret:...} references), schema validation, and payload file checks.

Parameters:
  • path (str | Path) – The scenario file. It is resolved, following symlinks, so payload files are relative to the directory of the real scenario file.

  • environ (Mapping[str, str] | None) – Reserved for expanding ${secret:NAME} from CLOUD_BOOT_SECRET_NAME variables in a later milestone. It is not read now: every secret reference is rejected.

Raises:

ScenarioValidationError – If any check fails.

Image store

Checksum-verified Ubuntu cloud-image download and cache primitives.

ImageStore.resolve returns a VerifiedImage whose bytes match the SHA-256 listed in the release’s SHA256SUMS. That file itself is not yet signature-checked (Task 12 adds gpgv), so results are checksum_verified but never signature_authenticated.

Cache layout under cache_dir:

.locks/<release>.lock     flock held for a whole resolve
.partial-*                image download in progress; removed on the next resolve
sha256/<digest>.img       content-addressed images
releases/<release>.json   pointer to the release's current image and its provenance
releases/.metadata-*      pointer write in progress
cloud_boot.image_store._sleep_until_cancelled(seconds, cancelled)

Sleep for seconds, returning early once cancelled is set.

cloud_boot.image_store._content_length(response)

Return the response’s declared body size, or None if absent or invalid.

cloud_boot.image_store._is_retryable(status)

Return whether an HTTP status may clear up on retry: server errors and rate limiting.

exception cloud_boot.image_store.ImageStoreError(message, *, context=None, exit_code=ExitCode.PREPARATION)

Bases: CloudBootError

Expected failure while resolving or caching a cloud image.

Failures default to the preparation exit code; deadline expiry uses the timeout exit code.

class cloud_boot.image_store.VerifiedImage(path, digest, size_bytes, source_url, retrieved_at, checksum_verified=True, signature_authenticated=False)

Bases: object

Immutable identity and provenance for a checksum-verified image.

path

Content-addressed cache file; the VM uses it as a read-only backing image.

Type:

pathlib.Path

digest

Lowercase hex SHA-256 of the image bytes.

Type:

str

size_bytes

Image size in bytes.

Type:

int

source_url

URL the image was downloaded from.

Type:

str

retrieved_at

Wall-clock time of the download, in seconds since the epoch.

Type:

float

checksum_verified

The bytes match the digest listed in SHA256SUMS.

Type:

bool

signature_authenticated

SHA256SUMS was checked against Ubuntu’s signing key; always False until Task 12.

Type:

bool

class cloud_boot.image_store.ImageStore(cache_dir, *, downloader=None, command_runner=None, wall_clock=<built-in function time>, monotonic=<built-in function monotonic>, sleeper=<function _sleep_until_cancelled>, base_url='https://cloud-images.ubuntu.com/noble/current/', max_image_bytes=2147483648, max_checksums_bytes=8388608, chunk_size=1048576, retry_attempts=3, retry_base_seconds=0.5, resolve_timeout_seconds=1800.0)

Bases: object

Resolve and cache the checksum-verified Noble image.

A single monotonic budget covers lock acquisition, cache hashing, network reads, and retries. Cached releases stay pinned until their metadata is removed. The sleeper receives the download’s cancellation event during retry backoff and None while polling the cache lock, so the default backoff returns early once a resolve gives up.

Network operations run in a daemon producer with bounded buffering. On expiry the caller cancels consumption and removes its partial file. An uncooperative downloader may keep its worker blocked until its I/O returns, but the worker never owns cache files or writes after cancellation.

Parameters:
  • cache_dir (str | Path) – Root of the cache; created on first use.

  • downloader (Downloader | None) – Opens a URL for streaming; defaults to urllib with a 30-second socket timeout.

  • command_runner (CommandRunner | None) – Reserved for signature verification (Task 12); never invoked yet.

  • wall_clock (Clock) – Source of retrieved_at and of Retry-After dates.

  • monotonic (Clock) – Clock for every deadline.

  • sleeper (CancellableSleeper) – Waits between lock polls and download retries.

  • base_url (str) – Directory holding the image and SHA256SUMS.

  • max_image_bytes (int) – Largest image accepted, downloaded or cached.

  • max_checksums_bytes (int) – Largest SHA256SUMS accepted.

  • chunk_size (int) – Bytes per read, and the most the downloader may return at once.

  • retry_attempts (int) – Total download attempts per URL, including the first.

  • retry_base_seconds (float) – First backoff delay; doubles on each attempt.

  • resolve_timeout_seconds (float) – Budget for one resolve call.

Raises:

ValueError – A limit, retry setting, or timeout is out of range.

resolve(spec=None, *, deadline=None)

Return a verified image, rehashing a cache hit or downloading within one deadline.

A cached release is reused without checking for a newer upstream image.

Parameters:
  • spec (ImageSpec | None) – Image to resolve; defaults to the official Noble amd64 image.

  • deadline (float | None) – Optional monotonic deadline; it may shorten the store’s budget but never extends it.

Returns:

The verified image in the content-addressed cache.

Raises:
  • ValueError – deadline is not finite.

  • ImageStoreError – The spec is unsupported, the cache is unusable, the download or its verification fails (exit code 4), or the budget runs out (exit code 8).

Return type:

VerifiedImage

_require_time_left(deadline, operation)

Return seconds left before deadline, or raise a timeout naming operation.

_validate_spec(spec)

Reject anything but the official Noble amd64 server image.

ImageSpec already allows only these values; this guards callers that bypass scenario validation, such as ImageSpec.model_construct.

static _basename(spec)

Return the upstream file name, such as noble-server-cloudimg-amd64.img.

_resolve_locked(spec, basename, deadline)

Take the release lock, then return a verified cache hit or a fresh download.

_acquire_lock(fd, deadline)

Poll for the exclusive cache lock until it is free or the deadline passes.

_remove_stale_partials(deadline)

Delete temporaries left by an interrupted resolve; the caller holds the lock.

_read_cached(spec, basename, deadline)

Return the cached image if its pointer is valid and its bytes still hash correctly.

Any missing, unreadable, malformed, or mismatched pointer or image is a cache miss rather than an error, so the caller downloads a fresh copy, which rewrites both.

_hash_file(path, deadline)

Return the SHA-256 hex digest and size of path, read in chunks within the deadline.

An unreadable or oversized file yields an empty digest, which never matches.

_download_and_cache(spec, basename, deadline)

Download, verify, and atomically publish the image, then point the release at it.

Nothing is written until SHA256SUMS names the image. The partial file is removed on any failure, so the cache holds only verified images.

_read_checksums(url, deadline)

Download SHA256SUMS into memory, refusing more than max_checksums_bytes.

_parse_checksums(data, basename)

Return the lowercase digest that SHA256SUMS lists for basename.

The whole file must look like sha256sum output: one malformed or unsafe line, or a duplicate entry for basename, rejects it.

_stream_image(url, destination, deadline)

Stream the image into destination, returning its SHA-256 hex digest and size.

_write_metadata(spec, basename, image, deadline)

Atomically point the release at image, recording its provenance.

Only the fields _read_cached checks are read back; the rest are for people inspecting the cache.

_download_chunks(url, deadline)

Yield the body of url in chunks, enforcing deadline even if the network stalls.

urllib’s timeout covers each socket operation, and one buffered read (header parsing included) can make many of them, so a slow server can stretch a single read indefinitely. All network I/O, including open and close, therefore runs in a daemon producer thread, while this generator polls a one-slot queue and checks the deadline. Closing the generator cancels the producer, which then stops publishing.

Raises:

ImageStoreError – The download fails, is cut short, or the deadline passes.

_open_with_retry(url, deadline, cancelled)

Open url, retrying connection failures, HTTP 429, and 5xx with backoff.

Other HTTP statuses fail at once. Backoff never outlasts the deadline and ends early once cancelled is set.

Raises:

ImageStoreError – A non-retryable status, exhausted attempts, cancellation, or timeout.

_retry_delay(response, attempt)

Return the backoff before the next attempt, honoring Retry-After up to 60 seconds.

Retry-After may be seconds or an HTTP date; anything else falls back to exponential backoff from retry_base_seconds.

static _urllib_downloader(url)

Open url with urllib; the 30-second timeout applies to each socket operation.

Seed media

Build and verify NoCloud seed media for one boot plan.

cloud-init’s NoCloud datasource looks for a filesystem labeled CIDATA and reads its configuration from files at the root. build_seed writes them into an ISO 9660 image, which the VM attaches as a read-only disk:

  • meta-data: written by cloud-boot, with the instance ID, hostname, and the run’s SSH key.

  • user-data: the scenario’s payload.

  • vendor-data: the scenario’s payload, or empty.

  • network-config: the scenario’s payload, only when given.

Every file is read back from the finished ISO and compared byte for byte before the seed is published as seed.iso.

exception cloud_boot.seed.SeedBuildError(message, *, context=None)

Bases: CloudBootError

Expected failure while preparing NoCloud seed media.

class cloud_boot.seed.SeedFile(name, sha256, size_bytes)

Bases: object

Digest and size of one file stored on the seed media.

name

NoCloud file name, such as user-data.

Type:

str

sha256

Lowercase hex SHA-256 of the file’s bytes.

Type:

str

size_bytes

File size in bytes; the run report does not include it yet.

Type:

int

class cloud_boot.seed.SeedArtifact(path, files)

Bases: object

A verified NoCloud seed ISO and the identity of each file it contains.

path

The published seed.iso.

Type:

pathlib.Path

files

One entry per file on the media, in the order written.

Type:

tuple[cloud_boot.seed.SeedFile, …]

cloud_boot.seed.build_seed(plan, *, ssh_public_key, scenario_dir, output_dir)

Build seed.iso for one boot plan and verify it before publishing.

The ISO is written to a temporary file in output_dir, reopened, and checked for the CIDATA label, the exact Rock Ridge and Joliet file sets, and byte-identical contents. Only then is it renamed to seed.iso, so an unverified seed never appears under the final name.

Parameters:
  • plan (BootPlan) – The boot plan whose seed inputs are materialized.

  • ssh_public_key (str) – The run’s single-line OpenSSH public key, added to public-keys.

  • scenario_dir (str | Path) – Directory that scenario-relative payload files resolve against.

  • output_dir (str | Path) – Run directory that receives seed.iso; created with mode 0700 if missing.

Returns:

The verified seed’s path and per-file SHA-256 digests.

Raises:

SeedBuildError – If a payload cannot be read, exceeds the size limit, or the ISO cannot be written or fails verification.

Return type:

SeedArtifact

cloud_boot.seed._collect_seed_contents(seed, ssh_public_key, scenario_dir)

Return each NoCloud file’s bytes, keyed by file name, in the order they are written.

cloud_boot.seed.render_meta_data(seed, ssh_public_key)

Serialize the meta-data file, the one seed file cloud-boot writes itself.

cloud-init installs public-keys for the image’s default user, which is how cloud-boot later connects over SSH.

Parameters:
  • seed (SeedSpec) – Seed inputs supplying the instance ID and optional hostname.

  • ssh_public_key (str) – The run’s single-line OpenSSH public key.

Returns:

UTF-8 YAML containing instance-id, optional local-hostname, and public-keys.

Raises:

SeedBuildError – If the public key is empty or spans more than one line.

Return type:

bytes

cloud_boot.seed._validate_public_key(key)

Reject a public key that is not one type data [comment] line.

Raises:

SeedBuildError – If the key is empty, padded, multi-line, or lacks key data.

cloud_boot.seed._load_payload(field, payload, scenario_dir)

Return one payload’s bytes, from inline text or a scenario-relative file.

Raises:

SeedBuildError – If the file cannot be read or the payload exceeds MAX_PAYLOAD_BYTES.

cloud_boot.seed._read_payload_file(field, relative, scenario_dir)

Read a payload file, checking again that it is a regular file inside scenario_dir.

Returns:

At most MAX_PAYLOAD_BYTES + 1 bytes, so the caller can detect an oversized file without reading all of it.

Return type:

bytes

cloud_boot.seed._write_iso(contents, stream)

Write contents to stream as an ISO 9660 image labeled SEED_LABEL.

Raises:

SeedBuildError – If pycdlib rejects the image.

cloud_boot.seed._verify_iso(contents, stream)

Reopen the written image and check its label, file names, and file contents.

Both name sets must equal the expected NoCloud files exactly, and each file read back through its Rock Ridge path must match its input byte for byte.

Raises:

SeedBuildError – If any check fails or the image cannot be reopened.

cloud_boot.seed._read_rock_ridge_names(iso)

Return the Rock Ridge name of each root entry, the names Linux and cloud-init see.

Raises:

SeedBuildError – If an entry has no Rock Ridge name.

QEMU backend

Launch and stop one QEMU/KVM guest on a qcow2 overlay of a verified base image.

  • QemuBackend covers one guest’s process lifecycle:
    • prepare creates the run’s overlay

    • start launches QEMU and returns once it survives a short startup window

    • stop waits for QEMU to exit before escalating to signals.

Surviving the window means only that QEMU did not fail at once; whether the guest booted is decided later, over SSH. The caller asks the guest to shut down; this module only manages the QEMU process.

exception cloud_boot.vm.OverlayError(message, *, context=None)

Bases: CloudBootError

Expected failure while creating the run’s qcow2 overlay.

exception cloud_boot.vm.VmLaunchError(message, *, context=None)

Bases: CloudBootError

Expected failure while starting QEMU.

class cloud_boot.vm.DiskArtifact(path)

Bases: object

A per-run qcow2 overlay backed read-only by the verified base image.

Only QemuBackend.prepare creates one, so VmLaunchSpec.disk cannot be the base image itself, which a guest would otherwise write to.

path

The overlay, overlay.qcow2 in the run directory.

Type:

pathlib.Path

class cloud_boot.vm.VmLaunchSpec(disk, seed_image, resources, console, name='cloud-boot', network_mode='nat')

Bases: object

Inputs for one QEMU launch.

disk

The run’s overlay; the base image is never passed to QEMU directly.

Type:

cloud_boot.vm.DiskArtifact

seed_image

NoCloud seed media, attached read-only.

Type:

pathlib.Path

resources

vCPU, memory, and disk bounds.

Type:

cloud_boot.models.ResourceSpec

console

Sink receiving every byte of the serial console.

Type:

cloud_boot.vm.ConsoleSink

name

QEMU guest name; restricted so it cannot inject QEMU option separators.

Type:

str

network_mode

Only nat (QEMU user networking) is supported by this backend.

Type:

cloud_boot.models.NetworkMode

class cloud_boot.vm.VmHandle(process, argv, ssh_host, ssh_port, launch_attempts)

Bases: object

A running guest and its loopback SSH endpoint.

process

The QEMU process.

Type:

cloud_boot.process.ManagedProcess

argv

The exact QEMU command line, recorded in the run’s artifacts.

Type:

tuple[str, …]

ssh_host

Always SSH_HOST; carried so callers need not import it.

Type:

str

ssh_port

The host port forwarded to the guest’s port 22.

Type:

int

launch_attempts

QEMU launches needed, counting retries after port conflicts; the run report does not include it yet.

Type:

int

class cloud_boot.vm.StopReason(*values)

Bases: StrEnum

How QEMU ended during QemuBackend.stop.

EXITED

QEMU exited by itself, typically after the guest shut down.

TERMINATED

QEMU exited after SIGTERM.

KILLED

QEMU needed SIGKILL.

class cloud_boot.vm.StopResult(reason, result)

Bases: object

The outcome of stopping a guest.

reason

How QEMU ended.

Type:

cloud_boot.vm.StopReason

result

QEMU’s exit status, stderr, and the console tail.

Type:

cloud_boot.process.CommandResult

cloud_boot.vm.allocate_loopback_port()

Return a TCP port on 127.0.0.1 that was free a moment ago.

The probe socket closes before QEMU binds the port, so another process can still take it in between; QemuBackend.start retries when QEMU reports that conflict.

cloud_boot.vm.build_qemu_argv(spec, ssh_port, *, qemu_binary='qemu-system-x86_64')

Assemble the deterministic QEMU argument array for one launch.

The guest gets KVM with the host CPU model, virtio disks, the serial console on stdout, no display or monitor, and QEMU user networking whose only host forward is loopback SSH.

Parameters:
  • spec (VmLaunchSpec) – Disk, seed, resources, and guest name for the launch.

  • ssh_port (int) – Host port on 127.0.0.1 forwarded to guest port 22.

  • qemu_binary (str) – The QEMU system emulator to execute.

Returns:

The full argument array, starting with qemu_binary.

Raises:

ValueError – If ssh_port is not a valid TCP port.

Return type:

tuple[str, …]

cloud_boot.vm._option_path(path)

Return path as an absolute QEMU option value.

QEMU resolves a relative path against its own working directory, and it separates suboptions with “,” so a literal comma is written as “,,”.

class cloud_boot.vm.QemuBackend(runner, *, qemu_binary='qemu-system-x86_64', qemu_img_binary='qemu-img', port_allocator=<function allocate_loopback_port>, clock=<built-in function monotonic>, sleeper=<built-in function sleep>, startup_window_seconds=2.0, termination_seconds=10.0)

Bases: object

Process-only QEMU backend: overlay creation, launch with port retry, and bounded stop.

Pass the same monotonic clock and sleeper to this backend and its CommandRunner so startup observation and shutdown deadlines are measured on one timeline.

Parameters:
  • runner (CommandRunner) – Runs qemu-img and starts QEMU.

  • qemu_binary (str) – The QEMU system emulator to execute.

  • qemu_img_binary (str) – The qemu-img executable.

  • port_allocator (PortAllocator) – Returns a free loopback port for SSH forwarding.

  • clock (Clock) – Monotonic clock, shared with runner.

  • sleeper (Sleeper) – Waits between process polls.

  • startup_window_seconds (float) – How long QEMU must keep running for start to succeed.

  • termination_seconds (float) – The end of stop’s deadline reserved for SIGTERM and SIGKILL.

Raises:

ValueError – If a window is not positive and finite.

prepare(image, run_dir, *, disk_gib, deadline)

Create overlay.qcow2 in run_dir, backed read-only by the verified image.

The backing path is absolute because qemu-img resolves a relative one against the overlay’s directory. An existing overlay is never overwritten.

Parameters:
  • image (VerifiedImage) – The checksum-verified base image.

  • run_dir (str | Path) – The run’s directory, which must already exist.

  • disk_gib (int) – Virtual size of the guest disk. qemu-img accepts a size below the base image’s, so ResourceSpec keeps it at least 4 GiB.

  • deadline (float) – Monotonic deadline for qemu-img.

Returns:

The overlay, ready to pass to start in a VmLaunchSpec.

Raises:
  • ValueError – If disk_gib is not a positive integer.

  • OverlayError – If the overlay already exists or qemu-img fails.

  • ProcessStartError – If qemu-img cannot be executed.

  • ProcessTimeoutError – If qemu-img does not finish by deadline.

Return type:

DiskArtifact

start(spec)

Launch QEMU and return once it survives the startup window.

The console streams to spec.console; only a bounded tail stays in memory. After a forwarding-port conflict QEMU is relaunched on a fresh port, up to MAX_LAUNCH_ATTEMPTS launches in all; any other early exit fails immediately.

Returns:

The running guest. The caller must end it with stop.

Raises:
Return type:

VmHandle

_await_startup(process)

Poll QEMU until it exits or the startup window ends.

Returns:

QEMU’s result if it exited during the window, with its output fully collected, or None if it is still running.

Return type:

CommandResult | None

stop(handle, *, deadline)

Wait for QEMU to exit, then escalate to SIGTERM and SIGKILL within deadline.

The caller requests guest shutdown first (for example over SSH). The last termination_seconds before deadline are reserved for process-group signals, so the whole stop never outlasts the caller’s deadline.

Returns:

How QEMU ended, with its exit status and captured output.

Raises:
  • ValueError – If deadline is not finite.

  • ProcessTimeoutError – If QEMU survives SIGKILL until deadline.

Return type:

StopResult

SSH transport

Run-scoped SSH identity and the loopback SSH transport into the guest.

create_access_identity makes a fresh Ed25519 key for one run; its public key goes into the seed’s meta-data, and AccessIdentity.destroy deletes the key pair at cleanup. SshTransport reaches the guest only through QEMU’s loopback port forward, never reads the user’s SSH configuration or keys, and trusts only host keys recorded during this run.

exception cloud_boot.ssh.AccessKeyError(message, *, context=None)

Bases: CloudBootError

Expected failure while creating the run’s SSH identity.

exception cloud_boot.ssh.SshTransportError(message, *, context=None)

Bases: CloudBootError

The guest could not be reached or controlled over SSH.

exception cloud_boot.ssh.GuestCopyError(message, *, context=None)

Bases: CloudBootError

A guest file was read but could not be written on the host.

class cloud_boot.ssh.AccessIdentity(private_key, public_key, known_hosts)

Bases: object

A run-scoped Ed25519 key pair and the run’s own known-hosts file.

private_key

The private key file, mode 0600.

Type:

pathlib.Path

public_key

The single-line OpenSSH public key, as written to meta-data.

Type:

str

known_hosts

Host keys accepted during this run only.

Type:

pathlib.Path

property public_key_path: Path

Return the path of the pub file next to the private key.

destroy()

Delete both key files; safe to call more than once.

The known-hosts file holds only the guest’s public host key, so it is left in place; it is removed with the rest of the run’s transient directory.

class cloud_boot.ssh.GuestResult(exit_status, stdout, stderr, duration_seconds, stdout_dropped_bytes=0, stderr_dropped_bytes=0)

Bases: object

The exact outcome of one script run in the guest.

exit_status is the script’s status in the guest; the ssh client’s own failures are raised as SshTransportError instead.

exit_status

The script’s exit status.

Type:

int

stdout

Captured stdout, or only its tail when stdout_dropped_bytes is non-zero.

Type:

bytes

stderr

Captured stderr, likewise bounded.

Type:

bytes

duration_seconds

Wall time of the ssh invocation.

Type:

float

stdout_dropped_bytes

Bytes of stdout not kept in memory.

Type:

int

stderr_dropped_bytes

Bytes of stderr not kept in memory.

Type:

int

stderr_tail(limit=2048)

Decode the last limit bytes of the guest’s stderr for a message.

cloud_boot.ssh.create_access_identity(runner, run_dir, *, deadline, ssh_keygen_binary='ssh-keygen')

Generate a passphrase-less Ed25519 key and an empty known-hosts file in run_dir.

The key never touches the user’s ssh. Create it before building seed media, because the public key goes into NoCloud metadata.

Parameters:
  • runner (CommandRunner) – Runs ssh-keygen.

  • run_dir (str | Path) – The run’s existing directory.

  • deadline (float) – Monotonic deadline for ssh-keygen.

  • ssh_keygen_binary (str) – The key generator to execute.

Returns:

The private key path (mode 0600), the single-line public key, and the known-hosts path.

Raises:
  • AccessKeyError – If identity files already exist, or the key cannot be created or read.

  • ProcessStartError – If ssh-keygen cannot be executed.

  • ProcessTimeoutError – If ssh-keygen does not finish by deadline. Partial key files stay in run_dir until the run’s transient directory is removed.

Return type:

AccessIdentity

cloud_boot.ssh._config_path(path)

Quote path as an ssh -o value that ssh reads back unchanged.

The path is made absolute so it does not depend on ssh’s working directory. ssh splits unquoted values on whitespace, expands %-tokens, and unescapes backslashes inside quotes, so “%” is doubled and characters that cannot be quoted safely are rejected.

Raises:

ValueError – If the path contains a double quote, backslash, or line break.

cloud_boot.ssh._guest_result(result)

Return result as the guest script’s outcome, with ssh’s exit status as the script’s.

class cloud_boot.ssh.SshTransport(runner, identity, *, host, port, user='ubuntu', ssh_binary='ssh', clock=<built-in function monotonic>, sleeper=<built-in function sleep>, connect_timeout_seconds=5)

Bases: object

Run fixed scripts in the guest over loopback SSH with a run-scoped identity.

Every invocation ignores the user’s SSH configuration, uses only the run key, records host keys only in the run’s known-hosts file, disables agent, X11, and port forwarding, and bounds the connection with a timeout and keepalives. Scripts travel on stdin to sh -s --; values are positional parameters, each quoted because ssh joins the remote command into one string.

Parameters:
  • runner (CommandRunner) – Runs every ssh invocation.

  • identity (AccessIdentity) – The run’s key pair and known-hosts file.

  • host (str) – A loopback IP address; QEMU forwards SSH only on loopback.

  • port (int) – The host port QEMU forwards to the guest’s port 22.

  • user (str) – The guest account that holds the run key.

  • ssh_binary (str) – The ssh client to execute.

  • clock (Clock) – Monotonic clock for wait_ready.

  • sleeper (Sleeper) – Waits between wait_ready attempts.

  • connect_timeout_seconds (int) – ssh’s ConnectTimeout, in whole seconds.

Raises:

ValueError – If host is not a loopback address, or another argument is out of range.

property base_argv: tuple[str, ...]

Return the ssh invocation shared by every guest operation, up to the destination.

wait_ready(*, deadline)

Retry true over SSH with bounded exponential backoff until it succeeds.

Ready means sshd accepts the run key; cloud-init may still be running, and the caller waits for it separately. Early in boot, connections are refused before sshd starts and the key is refused until cloud-init installs it, so every failure is retried until deadline. That includes failures that will never clear, such as a changed host key; the error’s last_failure then shows ssh’s own message.

Returns:

The number of attempts made; the run report does not include it yet.

Raises:
  • ValueError – If deadline is not finite.

  • SshTransportError – If the guest is not reachable before deadline.

Return type:

int

execute(script, args=(), *, timeout=60.0)

Run script in the guest with args as $1, $2, …

A non-zero guest exit status is returned, not raised; scripts must not exit 255.

Raises:
_run_script(script, args, *, timeout, sinks=None, capture_limit_bytes=1048576)

Run script in the guest with sh -s, reading it from stdin.

ssh joins the remote command into one string for the guest’s shell, so each argument is quoted to arrive as exactly one positional parameter. The script itself never passes through that shell. Commands in a script must not read stdin, which holds the script.

Raises:

TypeError – If args is a single string rather than a sequence of strings.

static _raise_on_transport_failure(result, operation)

Raise SshTransportError when ssh itself failed, which it reports as exit 255.

copy_from(remote, local, *, timeout=60.0)

Stream the guest file remote into a new host file local with mode 0600.

Bytes stream to disk; memory holds only a bounded tail, and the returned stdout is empty. If the guest cannot read the file, the partial host file is removed and the non-zero result, including the guest’s stderr, is returned.

Raises:
  • ValueError – If remote is not an absolute guest path.

  • SshTransportError – If ssh itself fails.

  • GuestCopyError – If the host file cannot be created or written.

shutdown(*, timeout=30.0)

Ask the guest to power off; follow with QemuBackend.stop to wait for QEMU to exit.

systemd’s shutdown -h powers off rather than halting, so QEMU exits with the guest.

Raises:
reboot(*, timeout=30.0)

Ask the guest to reboot; call wait_ready again before using the transport.

Raises:
_request_power_change(command, operation, timeout)

Run a privileged power command with sudo -n, so a password prompt fails at once.

Assertions

Evaluate Milestone 0 guest assertions over the SSH transport.

Each assertion type has one evaluator in an AssertionRegistry. An evaluator runs one fixed script in the guest through GuestTransport.execute, passing scenario values only as positional parameters, and turns the output into an Evaluation. run_assertions wraps each one into an AssertionResult: passed, failed when the guest did not match or the check timed out, or blocked when the check could not run because the SSH transport was lost or the run’s time was already used up.

class cloud_boot.assertions.GuestTransport(*args, **kwargs)

Bases: Protocol

The part of SshTransport that evaluators need.

The coordinator passes a wrapper that caps each command’s timeout at the time left in the run.

execute(script, args=(), *, timeout=Ellipsis)

Run a fixed script in the guest with positional values.

class cloud_boot.assertions.CommandReference(*, script, args)

Bases: BaseModel

Which fixed guest script ran, and with which positional values, for reproduction.

script

The script’s name, such as file, not its text.

Type:

str

args

The positional values passed as $1, $2, …

Type:

tuple[str, …]

class cloud_boot.assertions.AssertionResult(*, id, type, boot, required, status, expected, observed, reason, duration_seconds, command)

Bases: BaseModel

The uniform outcome of one assertion, as written to the run report.

failed means the check did not confirm the expectation: the guest did not match, the check timed out, or the guest lacked a tool or sudo -n to observe it; reason says which. blocked means it could not run: the SSH transport was lost, or the run’s time was used up before it started.

id

The assertion’s ID from the scenario.

Type:

str

type

The assertion type, such as file.

Type:

str

boot

The boot plan it ran in.

Type:

str

required

Whether a non-pass fails the boot.

Type:

bool

status

passed, failed, or blocked.

Type:

cloud_boot.assertions.AssertionStatus

expected

What the scenario asked for.

Type:

pydantic.types.JsonValue

observed

What the guest showed, or None when nothing was observed.

Type:

pydantic.types.JsonValue

reason

A one-line explanation of the status.

Type:

str

duration_seconds

Time spent on this assertion.

Type:

float

command

The script that ran, or None when none finished.

Type:

cloud_boot.assertions.CommandReference | None

class cloud_boot.assertions.Evaluation(passed, observed, reason, command)

Bases: object

What one evaluator observed in the guest.

passed

Whether the guest matched the expectation.

Type:

bool

observed

What the guest showed, for the report.

Type:

pydantic.types.JsonValue

reason

A one-line explanation.

Type:

str

command

The script that ran.

Type:

cloud_boot.assertions.CommandReference

class cloud_boot.assertions.AssertionRegistry

Bases: object

Map each assertion type to exactly one evaluator.

register(type_name, evaluator)

Add the evaluator for type_name.

Raises:

ValueError – If type_name already has an evaluator.

evaluate(assertion, transport)

Run the evaluator registered for the assertion’s type.

Raises:

LookupError – If no evaluator handles the assertion’s type.

cloud_boot.assertions.default_registry()

Return a registry with the three Milestone 0 evaluators.

cloud_boot.assertions.run_assertions(assertions, transport, *, boot, registry=None, clock=<built-in function monotonic>)

Evaluate assertions in declaration order.

A per-assertion timeout fails only that assertion. Losing the SSH transport blocks the assertion in progress and every assertion after it; nothing is reported as passed without running.

Parameters:
  • assertions (Sequence[AssertionSpec]) – The boot plan’s assertions, in declaration order.

  • transport (GuestTransport) – Runs fixed scripts in the guest.

  • boot (str) – The boot plan name recorded on every result.

  • registry (AssertionRegistry | None) – Evaluators by type; defaults to the Milestone 0 evaluators.

  • clock (Clock) – Monotonic clock for durations.

Returns:

One result per assertion, in the same order.

Return type:

list[AssertionResult]

cloud_boot.assertions.block_all(assertions, *, boot, reason)

Mark every assertion blocked, for example when SSH never became ready.

cloud_boot.assertions.all_required_passed(results)

Return whether every required assertion passed; failed or blocked ones fail the boot.

A boot with no required assertions passes.

cloud_boot.assertions._expected(assertion)

Return the scenario’s expectation for assertion as report JSON.

cloud_boot.assertions._result(assertion, boot, *, status, observed, reason, duration, command)

Build the AssertionResult for assertion, clamping a clock step back to zero duration.

cloud_boot.assertions._blocked(assertion, boot, reason, duration=0.0)

Build a blocked result: nothing was observed and no command finished.

cloud_boot.assertions._unobservable_reason(result, what)

Return why the script could not observe what, from its reserved exit statuses, or None.

cloud_boot.assertions._stderr_text(result)

Return the end of the guest’s stderr, trimmed for a one-line reason.

cloud_boot.assertions._evaluate_cloud_init_status(assertion, transport)

Check cloud-init’s extended status, which reports warnings that status alone hides.

The observation keeps error counts only; the collected cloud-init logs hold the details.

cloud_boot.assertions._evaluate_file(assertion, transport)

Check that a guest path is a regular file, optionally containing text, or is absent.

Content is matched on the host as bytes, so the expected text is never parsed by the guest. A path that exists but is not a regular file fails either way.

cloud_boot.assertions._evaluate_package(assertion, transport)

Check that dpkg reports the package as installed for at least one architecture.

A package dpkg does not know is not installed. A known package in another state, such as config-files after removal, fails with that state.

Run workspace

Run workspace: a private, contained directory for one run’s evidence and transient assets.

Each run gets <artifact root>/runs/<run ID>/, mode 0700. Evidence (the report, console logs, the QEMU command line, collected guest logs) stays; transient/ holds what only the run needs (seed media, the overlay, the SSH key pair, known hosts) and is removed when the run ends. Every path is checked to stay inside the run directory without crossing a symlink.

exception cloud_boot.artifacts.ArtifactError(message, *, context=None)

Bases: CloudBootError

Run evidence could not be created or written.

cloud_boot.artifacts.new_run_id(now, token)

Return a sortable run ID such as 20261107T190512Z-a1b2c3d4 from a UTC time and token.

The fixed-width UTC timestamp makes IDs sort by start time; the token separates runs that start in the same second.

Raises:

ValueError – If now has no time zone, so its moment is ambiguous.

cloud_boot.artifacts.boot_directory(index, name)

Return the run-relative directory for one boot, such as boots/001-boot.

cloud_boot.artifacts._sync_directory(directory)

Persist a rename in directory, best effort.

The file’s data is already durable. Some file systems refuse to sync a directory; then a crash may only lose the rename, leaving the previous version in place.

class cloud_boot.artifacts.RunWorkspace(path)

Bases: object

One run’s directory under <artifact root>/runs/, with mode 0700 throughout.

Every path handed out stays inside the run directory and has no symlink components, so a planted link cannot redirect a write elsewhere. Files are created 0600 and never overwrite an existing file, except through write_text_atomic, which replaces it in one step.

Use create for a new run; the constructor only wraps an existing run directory.

Parameters:

path (Path) – The run directory.

classmethod create(artifact_root, *, wall_clock=<function RunWorkspace.<lambda>>, token_factory=<function RunWorkspace.<lambda>>)

Allocate a new, uniquely named run directory and its transient/ subdirectory.

artifact_root itself may be a symlink, for example to another disk; everything cloud-boot creates below it must be a real directory.

Parameters:
  • artifact_root (str | Path) – Where runs/ lives; created if missing.

  • wall_clock (WallClock) – Source of the run ID’s timestamp.

  • token_factory (TokenFactory) – Source of the run ID’s random suffix.

Raises:

ArtifactError – If the runs directory is unusable or no unique name could be created.

property path: Path

Return the run directory.

property run_id: str

Return the run ID, which is also the run directory’s name.

property transient_dir: Path

Return the directory for seed media, overlays, keys, and known hosts.

artifact_path(relative)

Return the path for a run-relative name after checking it cannot escape.

Raises:

ValueError – If relative is empty, names the run directory itself, is absolute, contains NUL or , or crosses a symlink.

relative(path)

Return path relative to the run directory, for portable report references.

Raises:

ValueError – If path is outside the run directory.

make_dirs(relative)

Create the run-relative directory and any missing parents with mode 0700.

Existing directories keep their mode. Each component is checked after creation, so a symlink planted under that name is refused.

Raises:
  • ValueError – If the path escapes the run directory or crosses a symlink.

  • ArtifactError – If a directory cannot be created.

_prepare_path(relative)

Check relative and create its parent directories, ready for a new file.

open_new(relative)

Create a new 0600 file for streaming, such as the serial console log.

The caller owns the stream and must close it. O_EXCL never overwrites evidence, and O_NOFOLLOW refuses a symlink planted after the path was checked.

Raises:
  • ValueError – If the path escapes the run directory or crosses a symlink.

  • ArtifactError – If the file already exists or cannot be created.

write_bytes(relative, data)

Write a new 0600 file in one call, refusing to overwrite.

Raises:
  • ValueError – If the path escapes the run directory or crosses a symlink.

  • ArtifactError – If the file exists or cannot be written.

write_text_atomic(relative, text)

Replace a structured file in one step so readers never see a partial document.

The text goes to a 0600 sibling temporary file, which is flushed, synced, and renamed over the destination; the directory is then synced so the rename survives a crash.

Raises:

ArtifactError – If any step fails; the previous file, if any, is left intact.

cleanup_transient()

Delete transient/ with its seed media, overlay, and keys; keep all other evidence.

Safe to call more than once. Failures are returned as warnings instead of raised, so a cleanup problem never replaces the run’s primary outcome.

Run report

The minimal versioned run report and the single source of a run’s exit code.

decide_outcome turns a run’s failure and assertion results into its outcome and exit code; the CLI and the report both use it, so they cannot disagree. RunReportV1 refuses to be built when its fields contradict each other, and write_report saves it atomically as report.json.

class cloud_boot.report._ReportModel

Bases: BaseModel

class cloud_boot.report.ScenarioIdentity(*, name, source_path, source_sha256)

Bases: _ReportModel

Which scenario ran, identified by the bytes that were validated.

name

The scenario’s name field.

Type:

str

source_path

The absolute path of the scenario file.

Type:

str

source_sha256

SHA-256 of the file as it was loaded, even if it changed during the run.

Type:

str

class cloud_boot.report.ImageIdentity(*, digest, size_bytes, source_url, checksum_verified, signature_authenticated)

Bases: _ReportModel

The base image the guest booted from, with its honest verification level.

digest

SHA-256 of the image file.

Type:

str

size_bytes

The image file’s size.

Type:

int

source_url

Where the image was downloaded from.

Type:

str

checksum_verified

Whether the image matched the release’s SHA256SUMS.

Type:

bool

signature_authenticated

Whether SHA256SUMS itself was signature-checked; false until signature verification exists.

Type:

bool

class cloud_boot.report.BootResult(*, name, index, instance_id, seed_digests, stop_reason, assertions)

Bases: _ReportModel

What happened during one boot plan.

name

The boot plan’s name.

Type:

str

index

Its 1-based position in the run.

Type:

int

instance_id

The NoCloud instance ID the plan boots with.

Type:

str | None

seed_digests

SHA-256 of each NoCloud file on its seed media, by file name; empty if the seed was never built.

Type:

dict[str, str]

stop_reason

How QEMU ended (exited, terminated, or killed), or None if QEMU never started or did not stop cleanly.

Type:

cloud_boot.vm.StopReason | None

assertions

One result per assertion, in declaration order.

Type:

list[cloud_boot.assertions.AssertionResult]

cloud_boot.report._json_value(value)

Return value as JSON: lists and tuples recurse, dict keys become text, the rest str().

class cloud_boot.report.FailureRecord(*, code, phase, message, remediation, exit_code, context)

Bases: _ReportModel

The CloudBootError that ended the run, in its stable serialized shape.

code

The error’s stable machine-readable code, such as seed-build-failed.

Type:

str

phase

Where in the run it happened (an ErrorPhase value).

Type:

cloud_boot.errors.ErrorPhase

message

What went wrong.

Type:

str

remediation

What the user can do about it, if known.

Type:

str | None

exit_code

The exit code the run ends with.

Type:

int

context

Details for diagnosis, reduced to JSON values.

Type:

dict[str, pydantic.types.JsonValue]

classmethod from_error(error)

Build a record whose context holds only JSON values; anything else becomes text.

class cloud_boot.report.RunReportV1(*, report_version=1, run_id, scenario, image, started_at, finished_at, duration_seconds, outcome, exit_code, boots, artifacts, warnings, failure)

Bases: _ReportModel

The minimal version-1 run report written as report.json.

Construction fails if the outcome, exit code, failure, and assertion results disagree, so an inconsistent report can never be written.

report_version

The report format version, always 1.

Type:

Literal[1]

run_id

The run ID, which is also the run directory’s name.

Type:

str

scenario

Which scenario ran.

Type:

cloud_boot.report.ScenarioIdentity

image

The base image, or None if the run failed before resolving one.

Type:

cloud_boot.report.ImageIdentity | None

started_at

Wall-clock start time.

Type:

pydantic.types.AwareDatetime

finished_at

Wall-clock end time. The two are not checked against each other: the wall clock may be adjusted during a run, which must not make the report unwritable.

Type:

pydantic.types.AwareDatetime

duration_seconds

Elapsed time, measured on a monotonic clock.

Type:

float

outcome

passed, failed, or error.

Type:

cloud_boot.report.Outcome

exit_code

The exit code the run ends with.

Type:

int

boots

One result per boot plan, in order.

Type:

list[cloud_boot.report.BootResult]

artifacts

Run-relative paths of every file the run left, sorted, except the report.

Type:

list[str]

warnings

Problems that did not change the outcome, such as cleanup failures.

Type:

list[str]

failure

The error that ended the run, or None.

Type:

cloud_boot.report.FailureRecord | None

classmethod require_finite_duration(value)

Reject negative, infinite, or NaN durations.

classmethod require_relative_artifacts(paths)

Keep artifact references portable: run-relative, never absolute or traversing.

require_consistent_outcome()

Tie outcome, exit code, failure, and assertion results together.

With a failure, the outcome is error and the exit code is the failure’s. Without one, the outcome is passed with exit code 0 when every required assertion passed, and failed with exit code 7 otherwise.

cloud_boot.report.decide_outcome(*, failure, assertions)

Return the run outcome and exit code; the CLI and the report must both use this result.

The most specific terminal condition wins: an error’s own exit code beats assertion results.

cloud_boot.report.write_report(workspace, report)

Write report.json atomically.

Raises:

ArtifactError – If the report cannot be persisted; the run must then exit 9, never 0.

cloud_boot.report.scenario_identity(loaded)

Identify the scenario by name, path, and the SHA-256 of the bytes that were validated.

cloud_boot.report.image_identity(image)

Copy the verified image’s identity, including that its signature was not authenticated.

cloud_boot.report.seed_digests(seed)

Map each NoCloud file on the seed media to its SHA-256, keyed by file name.

Run coordinator

Milestone 0 run coordinator: one scenario, one boot, one VM, one deterministic exit code.

RunCoordinator sequences a run through the ports in RunDependencies, so tests drive it with fakes and production_dependencies wires the real image cache, QEMU, and SSH. Every resource registers its cleanup as soon as it exists; cleanup always runs, and the report is written after it, with the exit code the CLI returns.

exception cloud_boot.coordinator.HostUnavailableError(message, *, context=None)

Bases: CloudBootError

A required host command or KVM access is missing.

exception cloud_boot.coordinator.RunTimeoutError(message, *, phase, context=None)

Bases: CloudBootError

The run exceeded the scenario’s time limit, in the phase it was in at the time.

exception cloud_boot.coordinator.RunInterruptedError

Bases: CloudBootError

The user interrupted the run; cleanup and the report still completed.

exception cloud_boot.coordinator.UnexpectedRunError(error)

Bases: CloudBootError

An unexpected exception, wrapped so the run still reports exit code 10.

class cloud_boot.coordinator.ImageResolver(*args, **kwargs)

Bases: Protocol

Resolves the scenario’s image to a verified local file (ImageStore); the first step.

resolve(spec=Ellipsis, *, deadline=Ellipsis)

Return a verified cached or freshly downloaded image.

class cloud_boot.coordinator.VmBackend(*args, **kwargs)

Bases: Protocol

Creates the overlay and starts and stops the guest (QemuBackend).

prepare runs before boot, start boots the guest, and stop runs during cleanup.

prepare(image, run_dir, *, disk_gib, deadline)

Create the run’s overlay.

start(spec)

Launch the guest.

stop(handle, *, deadline)

Stop the guest within the deadline.

class cloud_boot.coordinator.GuestSession(*args, **kwargs)

Bases: Protocol

Talks to the running guest (SshTransport), from SSH readiness to shutdown.

Assertions get only the narrower GuestTransport, which can run scripts but not copy files or power the guest off.

wait_ready(*, deadline)

Wait until the guest accepts commands.

execute(script, args=Ellipsis, *, timeout=Ellipsis)

Run a fixed script in the guest.

copy_from(remote, local, *, timeout=Ellipsis)

Copy a guest file to the host.

shutdown(*, timeout=Ellipsis)

Ask the guest to power off.

class cloud_boot.coordinator.RunDependencies(preflight, create_workspace, image_store, create_identity, build_seed, vm_backend, connect, clock=<built-in function monotonic>, wall_clock=<function RunDependencies.<lambda>>)

Bases: object

Every port the coordinator uses; production wiring and test fakes both fill this.

preflight

Checks host commands and KVM access.

Type:

collections.abc.Callable[[], None]

create_workspace

Allocates the run directory.

Type:

collections.abc.Callable[[], cloud_boot.artifacts.RunWorkspace]

image_store

Resolves the scenario’s image.

Type:

cloud_boot.coordinator.ImageResolver

create_identity

(run_dir, deadline) to the run’s SSH key pair.

Type:

collections.abc.Callable[[pathlib.Path, float], cloud_boot.ssh.AccessIdentity]

build_seed

(plan, public_key, scenario_dir, output_dir) to the seed media.

Type:

collections.abc.Callable[[cloud_boot.models.BootPlan, str, pathlib.Path, pathlib.Path], cloud_boot.seed.SeedArtifact]

vm_backend

Creates the overlay and starts and stops the guest.

Type:

cloud_boot.coordinator.VmBackend

connect

(identity, handle) to a session with the running guest.

Type:

collections.abc.Callable[[cloud_boot.ssh.AccessIdentity, cloud_boot.vm.VmHandle], cloud_boot.coordinator.GuestSession]

clock

Monotonic clock for every deadline.

Type:

cloud_boot.process.Clock

wall_clock

Source of the report’s timestamps.

Type:

cloud_boot.coordinator.WallClock

class cloud_boot.coordinator.RunResult(exit_code, outcome, run_dir, report_path, failure, assertions=())

Bases: object

What the CLI needs: the exit code, where evidence lives, and what went wrong.

exit_code

The process exit code.

Type:

int

outcome

passed, failed, or error.

Type:

cloud_boot.report.Outcome

run_dir

The run directory, or None if the run failed before creating it.

Type:

pathlib.Path | None

report_path

The written report, or None if it was never written.

Type:

pathlib.Path | None

failure

The error that ended the run, or None.

Type:

cloud_boot.errors.CloudBootError | None

assertions

Every assertion result, for the CLI’s summary.

Type:

tuple[cloud_boot.assertions.AssertionResult, …]

class cloud_boot.coordinator._RunState(image=None, seed=None, stop_reason=None, assertions=<factory>, warnings=<factory>)

Bases: object

What the run has learned so far, so a run that fails midway still reports it.

class cloud_boot.coordinator._DeadlineSession(session, deadline, clock)

Bases: object

Caps every guest command at the time left before the run deadline.

Once the deadline has passed it refuses the command with a ProcessTimeoutError that has no result: run_assertions relies on that to block the remaining assertions instead of reporting them as timed out.

cloud_boot.coordinator.check_host(*, which=<function which>, kvm_device=PosixPath('/dev/kvm'), access=<built-in function access>)

Check the commands and KVM access a run needs, reporting every problem at once.

Whether KVM actually works is known only when QEMU starts; a failure there is a VmLaunchError.

Raises:

HostUnavailableError – If any command is missing or /dev/kvm is not usable.

cloud_boot.coordinator.default_cache_dir(environ)

Return $XDG_CACHE_HOME/cloud-boot, falling back to cache/cloud-boot.

cloud_boot.coordinator.default_artifact_root(environ)

Return $XDG_STATE_HOME/cloud-boot, falling back to local/state/cloud-boot.

cloud_boot.coordinator._xdg_base(environ, variable, fallback)

Return the XDG base directory in variable, or fallback under the home directory.

An empty or relative value is ignored, as the XDG specification requires.

cloud_boot.coordinator.production_dependencies(*, cache_dir, artifact_root)

Wire the real host adapters: image cache, QEMU, SSH, and the run workspace.

Every adapter shares one CommandRunner and the default monotonic clock, which QemuBackend requires to measure its deadlines on the same timeline as its runner.

class cloud_boot.coordinator.RunCoordinator(dependencies, *, progress=None)

Bases: object

Sequence one Milestone 0 run and always finish with cleanup and a consistent report.

Every acquired resource registers its cleanup at once; cleanups run in reverse order from a finally block. The report is written after cleanup, so its warnings include cleanup problems, and its exit code is the one the CLI returns.

run(loaded)

Run the scenario’s single boot and return its exit code and evidence location.

A failure in preflight or while creating the run directory returns at once, with no run directory and no report. After that, cleanup always runs and a report is always attempted, and every declared assertion appears in it.

_execute(loaded, workspace, state, cleanup)

Run the steps in order, registering each resource’s cleanup as soon as it exists.

Cleanups run in reverse order, so the console closes after QEMU stops and the run key is removed last. Each one goes through _run_quietly, so its failure is only a warning.

_deadline_in(seconds)

Return the monotonic deadline seconds from now.

static _run_quietly(state, action, step)

Run one cleanup step; a failure becomes a warning, never the run’s outcome.

KeyboardInterrupt still propagates: the run is then reported as interrupted, and the remaining cleanups still run.

_stop_guest(handle, session, workspace, boot_dir, state)

Collect the guest logs, ask the guest to power off, then stop QEMU and keep its stderr.

Logs and the shutdown request need SSH, so they are skipped if it never became ready. QEMU is then signalled at once instead of waiting for a guest that was not asked to stop. Every problem becomes a warning.

_collect(guest, workspace, boot_dir, state)

Copy the cloud-init logs while the guest is still up; a failure is only a warning.

_finish(loaded, workspace, state, failure, started_at, started)

Decide the outcome, build the report, and write it; runs after every cleanup.

The report lists every file the run left, except itself; transient/ is already gone. If the report model refuses the fields, the coordinator has a bug: the ValidationError propagates and the CLI exits 10 without a report.

Command line

Command-line entry point. Milestone 0 offers only cloud-boot run.

stdout carries only the run directory’s path, so scripts can capture it; everything else goes to stderr, one line each: INFO <phase>: … for progress, FAIL/WARN <id> (<status>): … for required and optional assertions that did not pass, then ERROR <phase>: … and HINT … for the failure that ended the run. The return value is the process exit code.

class cloud_boot.cli.Runner(*args, **kwargs)

Bases: Protocol

The coordinator surface the CLI drives.

run(loaded)

Run one loaded scenario.

exception cloud_boot.cli._ParserExit(status)

Bases: Exception

Raised by _Parser in place of sys.exit, carrying the exit status.

class cloud_boot.cli._Parser(*args, stdout, stderr, **kwargs)

Bases: ArgumentParser

An ArgumentParser that returns control to main instead of calling sys.exit.

exit(status=0, message=None)

Raise instead of exiting, so main can return the status.

error(message)

Report a usage error with the validation exit code.

cloud_boot.cli.build_parser(*, stdout, stderr)

Build the Milestone 0 parser: run, --help, and --version.

cloud_boot.cli._production_runner(progress, environ)

Build the real coordinator, with directories taken from the XDG environment.

cloud_boot.cli.main(argv=None, *, stdout=None, stderr=None, environ=None, runner_factory=<function _production_runner>)

Parse arguments, run the command, and return the process exit code.

Progress, failures, and remediation go to stderr; stdout carries only the run directory path so scripts can capture it.

cloud_boot.cli._run(scenario, out, err, environ, runner_factory)

Load and run one scenario, write its summary to stderr, and return its exit code.

cloud_boot.cli._write_failure(err, failure)

Write the failure that ended the run, and its remediation if there is one.