Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions install/MANIFEST
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
bec5194c6f5bd79a5ff4d9084bc506bb7cbaebe3cf54d87e72e8f1fd7c4b6791 a2_admit.py
3ad0ffc23873d3e992c062771bd7fc5ee8b17298ed4c36a7f0e7f3efce068bf3 a2_args.py
dd017bc0b416ad7086e3927d0ee62809c39bd9068805159dd4d81abb978da705 a2_budget.py
2dc58399662865a303815c52278c4dd8a69dc6eefa6a775c6e647a279787bd52 a2_causes.py
46b397539b9b446dd29503e4f20a046ce2e1a1bc121307a8f867fe4308d049dc a2_git.py
2a8e38f3d54370bc31fccc0f95db37582ba1ad83a607b78e17f87fa4a6919220 a2_guard.py
9272cfc691275927782da4837e03350e86d820fb412b5cf6e8ee5d6127899efb a2_host.py
689f5874a6cc7edc40796e3fc77c6894b0a52fa322227598bd7969be1d8e89c6 a2_locks.py
04c8ba632288d042d99db92a7aa61348f746bc3531519b0c82565eaa6b232d0f a2_main.py
00155a41a6fb235c21f0154aece8b08affd10912872a7d294cd478821240bbc1 a2_private.py
9476d0aa8480359a90a064462f9087a8e870733b4c57fec0af0400f3fc429881 a2_record.py
289e4a9697d16a00a263bf89b52031fafa6e17799e6cd3bac3183f8531f0f240 a2_rundir.py
6441b8a0cf1868c1d2920b92d689359fe3348324b149f50df5d258fd6cfdd187 a2_s0.py
b7e60509feca71514b2b6b60010f36d65b3fd54d2adfedbfef4020d0e18dd129 a2_s1.py
bfd120bb797044f68ee6c568d47d52fc2c4ff09cce32bd5476b612309eabd425 a2_s10.py
b086241daab1f78d4d7defa88380e7a7c04a8068df423049d8db9b4cfcc7dc9f a2_site.py
83a03a4ca834117409902822675fae23c291f87d37bdae30c91a692d5f61c58b a2_stop.py
762ddb48fd5940d8ec0cbb5d0dcb182f3b763b2c6ae257faa8ad7c2eb200d710 alpha2_install.py
202 changes: 202 additions & 0 deletions install/a2_admit.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,202 @@
"""The launcher (section 5.1a) and S0's admission (5.1a, 5.3, 5.3b, 5.3c).

The launcher refuses early. S0 is the admission authority: it re-checks
every launcher condition on its own reads, so a run that reaches it by any
route passes every limit or refuses.
"""

import hashlib
import os
import stat
import time

import a2_args
import a2_budget
import a2_host
import a2_locks
import a2_private
import a2_rundir
import a2_stop
from a2_causes import Refusal

LOCK_FILE = "alpha2.lock"
HOSTS_FILE = "alpha2.hosts"
READ_MAX = 1 << 20


def _read_to_eof(fd, limit):
"""Every byte up to EOF; at most limit + 1 are read."""
chunks, n = [], 0
while n <= limit:
b = os.read(fd, limit + 1 - n)
if not b:
break
chunks.append(b)
n += len(b)
return b"".join(chunks)


def _read_private(site):
return read_private_pair(site.private_dir)


def read_private_pair(private_dir):
"""The raw bytes of alpha2.lock and alpha2.hosts in the private overlay
checkout `private_dir`, as S0 reads them: each opened O_RDONLY |
O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC, a regular file, read to EOF, at
most READ_MAX bytes. O_NOFOLLOW covers the last path component only.
Nothing is parsed. Every failure, an unset `private_dir` included, is
PREFLIGHT.PRIVATE_SOURCE. Returns (lock_raw, hosts_raw)."""
if not private_dir:
raise Refusal("PREFLIGHT.PRIVATE_SOURCE")
out = []
for name in (LOCK_FILE, HOSTS_FILE):
path = os.path.join(private_dir, name)
try:
fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK | os.O_CLOEXEC)
except OSError:
raise Refusal("PREFLIGHT.PRIVATE_SOURCE")
try:
if not stat.S_ISREG(os.fstat(fd).st_mode):
raise Refusal("PREFLIGHT.PRIVATE_SOURCE")
raw = _read_to_eof(fd, READ_MAX)
except OSError:
raise Refusal("PREFLIGHT.PRIVATE_SOURCE")
finally:
os.close(fd)
if len(raw) > READ_MAX:
raise Refusal("PREFLIGHT.PRIVATE_SOURCE")
out.append(raw)
return tuple(out)


def _gate_open(gate):
"""("open", remaining seconds), the seconds a non-bool int >= 0."""
return (isinstance(gate, tuple) and len(gate) == 2 and gate[0] == "open"
and isinstance(gate[1], int) and not isinstance(gate[1], bool) and gate[1] >= 0)


class Checked:
"""What the shared checks established, for the launcher and for S0."""

def __init__(self, **kw):
self.__dict__.update(kw)


def _common(argv, site):
"""Steps both sides run, in the launcher's order up to the locks:
environment names, argv, the private files with L1 to L4, the account,
the full environment, and the arm gate."""
if site.environ is None:
site.environ = a2_host.received_environ()
a2_host.check_env_names(site.environ)
inv = a2_args.parse(argv)
lock_raw, hosts_raw = _read_private(site)
try:
lock, hosts = a2_private.load_pair(lock_raw, hosts_raw)
except a2_private.PairInvalid as e:
raise Refusal(e.cause, e.detail)
account, _name, home = a2_host.kernel_account(hosts["runner"], site.getuid, site.geteuid,
site.getpwuid)
a2_host.check_account(inv, account)
a2_host.check_env(site.environ, account, home)
if inv.command == "destroy" or (inv.command == "install" and inv.loop in ("L3", None)):
gate = site.arm_gate(hosts)
if not _gate_open(gate):
raise Refusal("PREFLIGHT.HANDOFF")
if inv.command == "install":
if site.full_run_bound_s is None or gate[1] < site.full_run_bound_s:
raise Refusal("PREFLIGHT.HANDOFF")
kw = {}
if site.fs_type_of is not None:
kw["fs_type_of"] = site.fs_type_of
if site.account_ids is not None:
kw["account_ids"] = site.account_ids
a2_locks.check_lock_root(hosts, site.host_identity(), site.root_uid, **kw)
a2_locks.check_names_distinct(hosts)
vms = a2_locks.run_vms(hosts, inv, account)
order = a2_locks.lock_order(hosts["runner"]["lock_root"],
a2_locks.targets(hosts, vms), inv.writes_target)
return Checked(inv=inv, lock=lock, hosts=hosts, account=account, home=home,
lock_raw=lock_raw, hosts_raw=hosts_raw,
lock_sha=hashlib.sha256(lock_raw).hexdigest(),
hosts_sha=hashlib.sha256(hosts_raw).hexdigest(),
order=order, lock_root=hosts["runner"]["lock_root"])


def _handoff_and_usage(c, site):
"""Stop file, loop tasks, and path (a) usage, for a command that can
write to a target (5.1a step 4; S0 again)."""
if not c.inv.writes_target:
return
if a2_stop.applies(c.inv) and a2_stop.read(c.lock_root) != "unset":
raise Refusal("PREFLIGHT.HANDOFF")
if site.loop_tasks(c.hosts) != "none":
raise Refusal("PREFLIGHT.HANDOFF")
if site.usage_path == "a":
pct = site.usage_read(c.hosts)
if not isinstance(pct, int) or isinstance(pct, bool) or pct >= 80 or pct < 0:
raise Refusal("PREFLIGHT.BUDGET")
elif site.usage_path != "b":
raise Refusal("PREFLIGHT.BUDGET")


# ------------------------------------------------------------ launcher


def prepare_launch(argv, site):
"""5.1a steps 1 to 4. Returns (exec argv, held lock descriptors). On a
refusal nothing stays held."""
c = _common(argv, site)
held = a2_locks.acquire(c.order, site.root_uid)
try:
_handoff_and_usage(c, site)
if c.inv.writes_target:
run_id, _sha = a2_budget.ask_broker(c.lock_root, c.inv, c.lock_sha, c.hosts_sha,
site.installer_sha, site.root_uid)
else:
run_id = a2_rundir.mint_run_id(site.now)
except BaseException:
a2_locks.release(held)
raise
args = [site.interpreter, "-I", "-B", site.entry, "--runner", "--run-id", run_id] + list(argv)
return args, held, run_id


def launch(argv, site):
"""5.1a steps 1 to 5. On success the runner replaces this process with
every lock descriptor still open (step 5), and this does not return."""
args, held, run_id = prepare_launch(argv, site)
try:
site.execve(site.interpreter, args, dict(site.environ))
except Exception:
pass
a2_locks.release(held)
# 5.1a step 5: an exec that fails in any way. A target-writing run's
# start record stays counted (5.3c); the terminal names the run id.
raise Refusal("RUNNER.NOT_STARTED", "run id: " + run_id)


# ------------------------------------------------------------------ S0


def admit(run_id, argv, site):
"""S0's admission, before the run directory exists. Returns the
admission facts and the created run directory."""
s0_began = time.time() if site.now is None else site.now
if not a2_private.matches("run_id", run_id):
raise Refusal("RUNNER.ADMISSION")
c = _common(argv, site)
held = a2_locks.find_held(c.order, site.root_uid, site.fd_dir)
a2_locks.adopt(held, c.lock_root, site.fd_dir)
_handoff_and_usage(c, site)
admission_sha = None
if c.inv.writes_target:
admission_sha = a2_budget.check_start_record(
os.path.join(c.lock_root, "budget.d"), c.account, run_id, c.inv,
c.lock_sha, c.hosts_sha, site.installer_sha, s0_began, site.root_uid)
c.run_fd = a2_rundir.create_run_dir(c.home, run_id, site.getuid())
c.run_id = run_id
c.held = held
c.admission_sha = admission_sha
return c
117 changes: 117 additions & 0 deletions install/a2_args.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
"""argv to (command, loop, options), per the flag table of section 5.1.

Every argv value is matched in full against its pattern before it is used
or recorded (section 3.3). A mismatch, an unknown flag, or a forbidden
combination is `RUNNER.ARGS`; the detail never echoes the argument.
"""

import re

from a2_causes import Refusal
from a2_private import matches

STAGE_IDS = ("S0", "S1", "S2", "S3", "S4", "S5", "S6", "S6b", "S7", "S8", "S9", "S10")
NONCE = re.compile(r"[A-Za-z0-9]{8,64}")

#: Commands that can write to a target (5.1, 5.3b): every command except
#: these three.
NON_WRITING = ("dry-run", "verify", "check-roundtrip")


class Invocation:
def __init__(self, command, loop, opts):
self.command = command
self.loop = loop
self.opts = opts

@property
def writes_target(self):
return self.command not in NON_WRITING

def __eq__(self, other):
return (isinstance(other, Invocation) and self.command == other.command
and self.loop == other.loop and self.opts == other.opts)

def __repr__(self):
return "Invocation(%r, %r, %r)" % (self.command, self.loop, self.opts)


def _bad():
return Refusal("RUNNER.ARGS")


def parse(argv):
flags = {}
i = 0
takes_value = {"--add-agent": "name", "--id": "name", "--check-roundtrip": "nonce",
"--only": "stage", "--from": "stage", "--loop": "loop"}
bare = ("--dry-run", "--verify", "--canary", "--rotate-key", "--leak-run", "--destroy")
while i < len(argv):
a = argv[i]
if a in bare:
if a in flags:
raise _bad()
flags[a] = True
i += 1
elif a in takes_value:
if a in flags or i + 1 >= len(argv):
raise _bad()
v = argv[i + 1]
kind = takes_value[a]
ok = (matches("name", v) if kind == "name"
else NONCE.fullmatch(v) is not None if kind == "nonce"
else v in STAGE_IDS if kind == "stage"
else v in ("L2", "L3"))
if not ok:
raise _bad()
flags[a] = v
i += 2
else:
raise _bad()
return _resolve(flags)


def _resolve(f):
keys = set(f)
modes = keys & {"--dry-run", "--verify", "--add-agent", "--rotate-key",
"--check-roundtrip", "--destroy"}
if len(modes) > 1:
raise _bad()
if "--canary" in keys and "--verify" not in keys:
raise _bad()
if "--id" in keys and "--add-agent" not in keys:
raise _bad()
install_mods = keys & {"--only", "--from", "--leak-run", "--loop"}
if modes and install_mods:
raise _bad()
if len(keys & {"--only", "--from"}) > 1:
raise _bad()
if "--loop" in keys and keys & {"--only", "--from", "--leak-run"}:
raise _bad()
if "--leak-run" in keys and keys & {"--only", "--from"}:
raise _bad()

if "--dry-run" in keys:
return Invocation("dry-run", None, {})
if "--verify" in keys:
return Invocation("canary" if "--canary" in keys else "verify", None, {})
if "--add-agent" in keys:
opts = {"host": f["--add-agent"]}
if "--id" in keys:
opts["id"] = f["--id"]
return Invocation("add-agent", None, opts)
if "--rotate-key" in keys:
return Invocation("rotate-key", None, {})
if "--check-roundtrip" in keys:
return Invocation("check-roundtrip", None, {"nonce": f["--check-roundtrip"]})
if "--destroy" in keys:
return Invocation("destroy", None, {})
if "--only" in keys:
return Invocation("install", "L1", {"only": f["--only"]})
if "--from" in keys:
return Invocation("install", "L1", {"from": f["--from"]})
if "--leak-run" in keys:
return Invocation("install", "L2-leak", {})
if "--loop" in keys:
return Invocation("install", f["--loop"], {})
return Invocation("install", None, {})
Loading
Loading