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:
StrEnumWhere in a run a failure happened.
ErrorPhasetells 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 withExitCode.TIMEOUT, and aPROCESSfailure exits withHOST_UNAVAILABLEwhen a command cannot start orTIMEOUTwhen it runs out of time.INTERRUPTmarks a run the user stopped.INTERNALmarks a cloud-boot bug and is the default for an unclassified error.A failed assertion is a run outcome, not an error;
ASSERTIONmarks 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.jsonand on stderr asERROR <phase>: ..., so renaming one is a breaking change to the report schema.
- class cloud_boot.errors.ExitCode(*values)¶
Bases:
IntEnumProcess 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
SIGINTis produced today (Ctrl-C, after normal cleanup).SIGHUPandSIGTERMare 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:
ExceptionBase 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, andexit_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
ErrorPhasevalue. An unknown value is a programming error and raisesValueError.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-onlyMapping, 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:
CloudBootErrorThe child process could not be created at all (missing binary, no permission, bad argv).
Raised by
CommandRunner.startwhenPopenitself fails, so no process exists and nothing needs cleaning up. The exit code is alwaysHOST_UNAVAILABLEbecause 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:
CloudBootErrorA deadline expired before a command finished; callers treat it as “out of time”.
Raised in three situations:
ManagedProcess.waitreached its deadline. The process group has already received SIGTERM and, if needed, SIGKILL.ManagedProcess.stopsent 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.
resultholds whatever output was captured, orNonewhen no process was involved. The exit code is alwaysExitCode.TIMEOUT.
- class cloud_boot.process.ByteWriter(*args, **kwargs)¶
Bases:
ProtocolInterface for one output destination: anything with a
write(bytes)method.Sinkis what a single stream accepts (this, a plain callable, orNone), andStreamSinkspairs oneSinkfor stdout with one for stderr. The return type isobjectso bothfile.write, which returns a byte count, and writers that returnNonequalify.- write(data)¶
Consume a chunk of output.
- class cloud_boot.process.PopenLike(*args, **kwargs)¶
Bases:
ProtocolThe part of
subprocess.PopenthatManagedProcessuses; test fakes implement only this.
- class cloud_boot.process.MemorySink(limit=None)¶
Bases:
objectThread-safe in-memory byte buffer, optionally keeping only the newest
limitbytes.ManagedProcessuses one per stream for the output that ends up inCommandResult; 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 alimit, only the most recentlimitbytes are kept, because the end of a child’s output usually explains its failure; older bytes are counted indropped_bytesso 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:
objectLive destinations for one process: a
Sinkfor stdout and one for stderr.Bundled into one object so it can pass unchanged through
CommandRunnerdown 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.pystreams the QEMU serial console to the console log, andssh.pystreams a guest file straight to disk.
- class cloud_boot.process.SinkFailure(stream, error)¶
Bases:
objectA 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 orMemorySink, or a plain callable, such aslist.append.Nonedisables 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
SinkFailureand stops forwarding to that sink.- Parameters:
sink (Sink) – Destination for the chunk, or
Noneto 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:
objectWhat to run and how, validated on construction so a bad command fails before any process.
Fields are normalized:
argvbecomes a tuple,cwdaPath, andenvandenv_allowlistare 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
Noneto 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
envmay set.stdin (bytes | None) – Bytes written to the child’s stdin, which is then closed;
Noneconnects stdin to/dev/nullso a child can never wait for terminal input.name (str | None) – Short label for diagnostics, such as
"qemu-img", used instead ofargv[0].capture_limit_bytes (int) – Per-stream in-memory capture limit; see
MemorySink.
- cloud_boot.process.tail_text(data, limit)¶
Decode the last
limitbytes ofdata, 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:
objectWhat a finished child process did. Nothing here is interpreted; callers decide meaning.
returncodefollowssubprocess: a negative value means the child was killed by that signal, for example -9 for SIGKILL.stdoutandstderrhold only the newest bytes up to the capture limit;stdout_dropped_bytesandstderr_dropped_bytescount what was cut, so callers can tell complete output from a tail.timed_outis set when cloud-boot had to stop the child at its deadline, even if the child then exited 0.sink_failureslists 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
limitbytes 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
timeoutor an absolutedeadlineinto one absolute monotonic deadline.Exactly one of
timeoutanddeadlinemay be given; with neither,defaultseconds 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:
objectA running child process: bounded waiting, process-group signals, and live output capture.
Created by
CommandRunner.start; most callers useCommandRunner.runinstead and never see one. It is for long-running children such as QEMU, whichvm.pystarts, leaves running, and later stops. Reader threads start on construction, so every instance must end withwaitorstop, which collect the threads and return theCommandResult.- 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
captureand the livesink.It uses
read1when 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 reachescapturefirst, 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;_finishhandles children whose descendants keep it open.
- _start_stdin_writer()¶
Start a daemon thread that writes
spec.stdinonce and then closes the pipe.Closing sends EOF, which is how
sh -son the guest knows the script is complete. If the child exits without reading everything, the write fails withBrokenPipeError(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
sigto 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
killpgalso 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, whichPopenignores once the child has been reaped. Errors are swallowed: signalling is best effort, and callers check the outcome withpoll.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_outand 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
deadlinepasses; return its status, orNoneon 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
timeoutnordeadline, the grace period plus one second is used.- Raises:
ProcessTimeoutError – If the child is still running at the deadline even after SIGKILL. Its
resultholds 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
deadlineis 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 relativetimeoutallows up to twice the grace period of cleanup after it expires. With neither,DEFAULT_TIMEOUT_SECONDSapplies.- Raises:
ProcessTimeoutError – If the deadline passes first. The process group has been signalled, and
resultholds the output captured before it stopped, markedtimed_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:
objectThe 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.Popenwith 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.Popenin production.default_timeout_seconds (float) – Used by
runwhen 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
waitorstop.- 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:
ProcessStartError – If the command cannot be started.
ProcessTimeoutError – If it does not finish in time; see
ManagedProcess.wait.ValueError – For an invalid
timeoutordeadline, before anything is started.
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:
BaseModelBase for every scenario model: unknown keys rejected, frozen, defaults validated.
extra="forbid"turns a misspelled key such astimeout_secondinto an error instead of a silently ignored setting.frozen=Truekeeps a validated scenario from changing while it is passed between components.validate_default=Truechecks defaults against the same constraints as user values.
- class cloud_boot.models.ImageSpec(*, release='noble', architecture='amd64', variant='server-cloudimg', source='official')¶
Bases:
StrictModelWhich 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
Literalkeeps existing scenario files valid. The fields form the image file name, such asnoble-server-cloudimg-amd64.img, andsourceis reserved for non-official images.ImageStorere-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:
StrictModelVirtual hardware for the guest, each value bounded to catch typos before QEMU sees them.
cpusandmemory_mibare passed to QEMU as the virtual CPU count (-smp) and memory size in MiB (-m).disk_gibis 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_containmentresolves symlinks when the scenario loads, andcloud_boot.seed._read_payload_filechecks 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
valuewhen it is a safe relative path.- Raises:
ValueError – If
valueis empty, contains a NUL byte, is absolute, or contains acomponent.- Return type:
str
- class cloud_boot.models.PayloadSpec(*, inline=None, file=None)¶
Bases:
StrictModelOne cloud-init input (user-data, vendor-data, or network-config), inline or from a file.
Exactly one of
inlineandfilemust 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.fileis relative to the scenario file’s directory and must stay inside it. Either way, a payload is limited tocloud_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:
StrictModelWhat goes on the NoCloud seed disk that cloud-init reads at boot.
cloud-boot writes
meta-dataitself frominstance_id,local_hostname, and the run’s SSH public key, so the run’s own key is always installed.user_datais required. A missingvendor_databecomes an empty file, which cloud-init reads as no vendor configuration, and a missingnetwork_configleaves the file off the disk, so cloud-init applies its default networking.instance_idis how cloud-init tells instances apart: modules that run once per instance run again only when it changes.local_hostnamemust be a valid DNS name.
- class cloud_boot.models.AssertionBase(*, id, required=True, timeout_seconds=30)¶
Bases:
StrictModelFields every assertion has: its ID, whether it counts, and its own time limit.
An assertion with
required: falseis still run and reported, but its failure does not fail the run.timeout_secondsbounds 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:
AssertionBaseRequire cloud-init to have finished cleanly: its extended status must be exactly
done.A run that finished with warnings reports
degraded doneand fails this check.expectedallows onlydonetoday; 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:
AssertionBaseRequire a guest file to exist, optionally containing some text, or to be absent.
content_containsis a plain substring match on the file’s bytes and only works for files up tocloud_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:
AssertionBaseRequire a Debian package to be installed on the guest, as reported by dpkg.
namefollows 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:
StrictModelOne boot of the guest, in the normalized form every downstream component consumes.
ScenarioV1.to_boot_planbuilds 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.namenames the boot’s artifact directory, such asboots/001-boot.wait_for_cloud_initis 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:
StrictModelA 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).
- resources¶
Virtual CPU, memory, and disk for the guest.
- network_mode¶
Guest networking; only
nat(QEMU user networking). It is not yet passed to the VM backend, which also defaults tonat.- 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.
- 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.
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:
objectOne problem found while loading a scenario, and where it is.
locationis 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:
ValueErrorThe scenario cannot be loaded; carries every issue found, not just the first.
The message joins all issues as
invalid scenario: <field>: <message>; ..., andissueskeeps them as structured values for callers that need more than the text.- Raises:
ValueError – If
issuesis empty, which would be a loader bug.
- class cloud_boot.scenario.LoadedScenario(source_path, source_sha256, scenario, boots)¶
Bases:
objectA validated scenario, where it came from, and the boot plans to run.
source_pathis absolute, and payload files are resolved relative to its directory.source_sha256is the digest of the bytes that were validated, so the report names what ran even if the file changes later.bootsholds one plan per boot, in order, and always exactly one in Milestone 0.
- class cloud_boot.scenario._StrictSafeLoader(stream)¶
Bases:
SafeLoaderyaml.SafeLoaderwith 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 thanMAX_YAML_ALIASESaliases, and nesting deeper thanMAX_YAML_DEPTH. The limits raiseComposerErrorat the offending node, so they are reported as YAML issues with a line and column.The counters are per document;
yaml.loadcreates 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_depthis 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_mappingexpands 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_referencesreports 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
problemis kept; PyYAML’s full message adds context lines and a source excerpt. Errors without a position, such as aReaderErrorfor 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.inlinewould 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
!setare 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_datadocument, 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.seedchecks 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/zerois 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
$.sourceif 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}fromCLOUD_BOOT_SECRET_NAMEvariables 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 oncecancelledis set.
- cloud_boot.image_store._content_length(response)¶
Return the response’s declared body size, or
Noneif 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:
CloudBootErrorExpected 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:
objectImmutable 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¶
SHA256SUMSwas checked against Ubuntu’s signing key; alwaysFalseuntil 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:
objectResolve 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
Nonewhile 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_atand ofRetry-Afterdates.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
SHA256SUMSaccepted.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
resolvecall.
- 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 –
deadlineis 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:
- _require_time_left(deadline, operation)¶
Return seconds left before
deadline, or raise a timeout namingoperation.
- _validate_spec(spec)¶
Reject anything but the official Noble amd64 server image.
ImageSpecalready allows only these values; this guards callers that bypass scenario validation, such asImageSpec.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
SHA256SUMSnames the image. The partial file is removed on any failure, so the cache holds only verified images.
- _read_checksums(url, deadline)¶
Download
SHA256SUMSinto memory, refusing more thanmax_checksums_bytes.
- _parse_checksums(data, basename)¶
Return the lowercase digest that
SHA256SUMSlists forbasename.The whole file must look like
sha256sumoutput: one malformed or unsafe line, or a duplicate entry forbasename, 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_cachedchecks are read back; the rest are for people inspecting the cache.
- _download_chunks(url, deadline)¶
Yield the body of
urlin chunks, enforcingdeadlineeven 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
cancelledis 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-Afterup to 60 seconds.Retry-Aftermay be seconds or an HTTP date; anything else falls back to exponential backoff fromretry_base_seconds.
- static _urllib_downloader(url)¶
Open
urlwith 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:
CloudBootErrorExpected failure while preparing NoCloud seed media.
- class cloud_boot.seed.SeedFile(name, sha256, size_bytes)¶
Bases:
objectDigest 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:
objectA 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.isofor one boot plan and verify it before publishing.The ISO is written to a temporary file in
output_dir, reopened, and checked for theCIDATAlabel, the exact Rock Ridge and Joliet file sets, and byte-identical contents. Only then is it renamed toseed.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:
- 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-datafile, the one seed file cloud-boot writes itself.cloud-init installs
public-keysfor 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, optionallocal-hostname, andpublic-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 + 1bytes, so the caller can detect an oversized file without reading all of it.- Return type:
bytes
- cloud_boot.seed._write_iso(contents, stream)¶
Write
contentstostreamas an ISO 9660 image labeledSEED_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.
QemuBackendcovers one guest’s process lifecycle:
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:
CloudBootErrorExpected failure while creating the run’s qcow2 overlay.
- exception cloud_boot.vm.VmLaunchError(message, *, context=None)¶
Bases:
CloudBootErrorExpected failure while starting QEMU.
- class cloud_boot.vm.DiskArtifact(path)¶
Bases:
objectA per-run qcow2 overlay backed read-only by the verified base image.
Only
QemuBackend.preparecreates one, soVmLaunchSpec.diskcannot be the base image itself, which a guest would otherwise write to.- path¶
The overlay,
overlay.qcow2in the run directory.- Type:
pathlib.Path
- class cloud_boot.vm.VmLaunchSpec(disk, seed_image, resources, console, name='cloud-boot', network_mode='nat')¶
Bases:
objectInputs for one QEMU launch.
- disk¶
The run’s overlay; the base image is never passed to QEMU directly.
- seed_image¶
NoCloud seed media, attached read-only.
- Type:
pathlib.Path
- resources¶
vCPU, memory, and disk bounds.
- 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:
objectA running guest and its loopback SSH endpoint.
- process¶
The QEMU process.
- 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:
StrEnumHow 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:
objectThe outcome of stopping a guest.
- reason¶
How QEMU ended.
- Type:
- result¶
QEMU’s exit status, stderr, and the console tail.
- 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.startretries 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_portis not a valid TCP port.- Return type:
tuple[str, …]
- cloud_boot.vm._option_path(path)¶
Return
pathas 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:
objectProcess-only QEMU backend: overlay creation, launch with port retry, and bounded stop.
Pass the same monotonic clock and sleeper to this backend and its
CommandRunnerso startup observation and shutdown deadlines are measured on one timeline.- Parameters:
runner (CommandRunner) – Runs
qemu-imgand starts QEMU.qemu_binary (str) – The QEMU system emulator to execute.
qemu_img_binary (str) – The
qemu-imgexecutable.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
startto 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.qcow2inrun_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
ResourceSpeckeeps it at least 4 GiB.deadline (float) – Monotonic deadline for qemu-img.
- Returns:
The overlay, ready to pass to
startin aVmLaunchSpec.- Raises:
ValueError – If
disk_gibis 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:
- 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 toMAX_LAUNCH_ATTEMPTSlaunches in all; any other early exit fails immediately.- Returns:
The running guest. The caller must end it with
stop.- Raises:
VmLaunchError – If QEMU exits during the startup window.
ProcessStartError – If the QEMU binary cannot be executed.
- Return type:
- _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
Noneif 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_secondsbeforedeadlineare 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
deadlineis not finite.ProcessTimeoutError – If QEMU survives SIGKILL until
deadline.
- Return type:
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:
CloudBootErrorExpected failure while creating the run’s SSH identity.
- exception cloud_boot.ssh.SshTransportError(message, *, context=None)¶
Bases:
CloudBootErrorThe guest could not be reached or controlled over SSH.
- exception cloud_boot.ssh.GuestCopyError(message, *, context=None)¶
Bases:
CloudBootErrorA guest file was read but could not be written on the host.
- class cloud_boot.ssh.AccessIdentity(private_key, public_key, known_hosts)¶
Bases:
objectA 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
pubfile 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:
objectThe exact outcome of one script run in the guest.
exit_statusis the script’s status in the guest; the ssh client’s own failures are raised asSshTransportErrorinstead.- exit_status¶
The script’s exit status.
- Type:
int
- stdout¶
Captured stdout, or only its tail when
stdout_dropped_bytesis 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
limitbytes 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 inrun_diruntil the run’s transient directory is removed.
- Return type:
- cloud_boot.ssh._config_path(path)¶
Quote
pathas an ssh-ovalue 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
resultas 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:
objectRun 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_readyattempts.connect_timeout_seconds (int) – ssh’s ConnectTimeout, in whole seconds.
- Raises:
ValueError – If
hostis 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
trueover 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’slast_failurethen shows ssh’s own message.- Returns:
The number of attempts made; the run report does not include it yet.
- Raises:
ValueError – If
deadlineis not finite.SshTransportError – If the guest is not reachable before
deadline.
- Return type:
int
- execute(script, args=(), *, timeout=60.0)¶
Run
scriptin the guest withargsas$1,$2, …A non-zero guest exit status is returned, not raised; scripts must not exit 255.
- Raises:
SshTransportError – If ssh itself fails (exit status 255).
ProcessTimeoutError – If the script outlives
timeout.
- _run_script(script, args, *, timeout, sinks=None, capture_limit_bytes=1048576)¶
Run
scriptin the guest withsh -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
argsis a single string rather than a sequence of strings.
- static _raise_on_transport_failure(result, operation)¶
Raise
SshTransportErrorwhen ssh itself failed, which it reports as exit 255.
- copy_from(remote, local, *, timeout=60.0)¶
Stream the guest file
remoteinto a new host filelocalwith 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
remoteis 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.stopto wait for QEMU to exit.systemd’s
shutdown -hpowers off rather than halting, so QEMU exits with the guest.- Raises:
SshTransportError – If the guest refuses the request, for example when sudo needs a password.
ProcessTimeoutError – If ssh does not return within
timeout.
- reboot(*, timeout=30.0)¶
Ask the guest to reboot; call
wait_readyagain before using the transport.- Raises:
SshTransportError – If the guest refuses the request.
ProcessTimeoutError – If ssh does not return within
timeout.
- _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:
ProtocolThe part of
SshTransportthat 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:
BaseModelWhich 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:
BaseModelThe uniform outcome of one assertion, as written to the run report.
failedmeans the check did not confirm the expectation: the guest did not match, the check timed out, or the guest lacked a tool orsudo -nto observe it;reasonsays which.blockedmeans 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, orblocked.- Type:
cloud_boot.assertions.AssertionStatus
- expected¶
What the scenario asked for.
- Type:
pydantic.types.JsonValue
- observed¶
What the guest showed, or
Nonewhen 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
Nonewhen none finished.- Type:
- class cloud_boot.assertions.Evaluation(passed, observed, reason, command)¶
Bases:
objectWhat 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.
- class cloud_boot.assertions.AssertionRegistry¶
Bases:
objectMap each assertion type to exactly one evaluator.
- register(type_name, evaluator)¶
Add the evaluator for
type_name.- Raises:
ValueError – If
type_namealready 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
assertionas report JSON.
- cloud_boot.assertions._result(assertion, boot, *, status, observed, reason, duration, command)¶
Build the
AssertionResultforassertion, clamping a clock step back to zero duration.
- cloud_boot.assertions._blocked(assertion, boot, reason, duration=0.0)¶
Build a
blockedresult: 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, orNone.
- 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
statusalone 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-filesafter 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:
CloudBootErrorRun evidence could not be created or written.
- cloud_boot.artifacts.new_run_id(now, token)¶
Return a sortable run ID such as
20261107T190512Z-a1b2c3d4from 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
nowhas 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:
objectOne 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
createfor 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_rootitself 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
relativeis empty, names the run directory itself, is absolute, contains NUL or, or crosses a symlink.
- relative(path)¶
Return
pathrelative to the run directory, for portable report references.- Raises:
ValueError – If
pathis 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.
- 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:
_ReportModelWhich scenario ran, identified by the bytes that were validated.
- 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:
_ReportModelThe 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:
_ReportModelWhat 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, orkilled), orNoneif QEMU never started or did not stop cleanly.- Type:
cloud_boot.vm.StopReason | None
- assertions¶
One result per assertion, in declaration order.
- Type:
- cloud_boot.report._json_value(value)¶
Return
valueas JSON: lists and tuples recurse, dict keys become text, the reststr().
- class cloud_boot.report.FailureRecord(*, code, phase, message, remediation, exit_code, context)¶
Bases:
_ReportModelThe
CloudBootErrorthat 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
ErrorPhasevalue).
- 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:
_ReportModelThe 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.
- image¶
The base image, or
Noneif the run failed before resolving one.- Type:
- 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, orerror.- 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:
- 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:
- 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
errorand the exit code is the failure’s. Without one, the outcome ispassedwith exit code 0 when every required assertion passed, andfailedwith 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.jsonatomically.- 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.
Bases:
CloudBootErrorA required host command or KVM access is missing.
- exception cloud_boot.coordinator.RunTimeoutError(message, *, phase, context=None)¶
Bases:
CloudBootErrorThe run exceeded the scenario’s time limit, in the phase it was in at the time.
- exception cloud_boot.coordinator.RunInterruptedError¶
Bases:
CloudBootErrorThe user interrupted the run; cleanup and the report still completed.
- exception cloud_boot.coordinator.UnexpectedRunError(error)¶
Bases:
CloudBootErrorAn unexpected exception, wrapped so the run still reports exit code 10.
- class cloud_boot.coordinator.ImageResolver(*args, **kwargs)¶
Bases:
ProtocolResolves 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:
ProtocolCreates the overlay and starts and stops the guest (
QemuBackend).prepareruns before boot,startboots the guest, andstopruns 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:
ProtocolTalks 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:
objectEvery 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.
- 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.
- 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:
objectWhat the CLI needs: the exit code, where evidence lives, and what went wrong.
- exit_code¶
The process exit code.
- Type:
int
- outcome¶
passed,failed, orerror.- Type:
cloud_boot.report.Outcome
- run_dir¶
The run directory, or
Noneif the run failed before creating it.- Type:
pathlib.Path | None
- report_path¶
The written report, or
Noneif it was never written.- Type:
pathlib.Path | None
- failure¶
The error that ended the run, or
None.- Type:
- 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:
objectWhat the run has learned so far, so a run that fails midway still reports it.
- class cloud_boot.coordinator._DeadlineSession(session, deadline, clock)¶
Bases:
objectCaps every guest command at the time left before the run deadline.
Once the deadline has passed it refuses the command with a
ProcessTimeoutErrorthat has noresult:run_assertionsrelies 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/kvmis not usable.
- cloud_boot.coordinator.default_cache_dir(environ)¶
Return
$XDG_CACHE_HOME/cloud-boot, falling back tocache/cloud-boot.
- cloud_boot.coordinator.default_artifact_root(environ)¶
Return
$XDG_STATE_HOME/cloud-boot, falling back tolocal/state/cloud-boot.
- cloud_boot.coordinator._xdg_base(environ, variable, fallback)¶
Return the XDG base directory in
variable, orfallbackunder 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
CommandRunnerand the default monotonic clock, whichQemuBackendrequires to measure its deadlines on the same timeline as its runner.
- class cloud_boot.coordinator.RunCoordinator(dependencies, *, progress=None)¶
Bases:
objectSequence 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
finallyblock. 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
secondsfrom 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: theValidationErrorpropagates 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:
ProtocolThe coordinator surface the CLI drives.
- run(loaded)¶
Run one loaded scenario.
- exception cloud_boot.cli._ParserExit(status)¶
Bases:
ExceptionRaised by
_Parserin place ofsys.exit, carrying the exit status.
- class cloud_boot.cli._Parser(*args, stdout, stderr, **kwargs)¶
Bases:
ArgumentParserAn ArgumentParser that returns control to
maininstead of callingsys.exit.- 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.