fix(ci): validate package loader and lifecycle in isolated Linux fixtures
This commit is contained in:
@@ -85,7 +85,7 @@ jobs:
|
||||
- name: Assemble combined private package
|
||||
run: |
|
||||
engine="${RUNNER_TEMP}/strata-static-cuda-${GITHUB_RUN_ID}/strata"
|
||||
python3 scripts/build-linux-package.py --engine "$engine" \
|
||||
python3 scripts/build-linux-package.py --engine "$engine" --probe-in-runtime-image \
|
||||
--sha256 "$(sha256sum "$engine" | cut -d ' ' -f 1)" --revision "$GITHUB_SHA" \
|
||||
--build-features "${RUNNER_TEMP}/strata-static-cuda-${GITHUB_RUN_ID}/BUILD-FEATURES.json" \
|
||||
--cargo-target-dir "${RUNNER_TEMP}/strata-package-build-${GITHUB_RUN_ID}" \
|
||||
@@ -141,6 +141,8 @@ jobs:
|
||||
echo "CUDAToolkit_ROOT=$RUNNER_TEMP/strata-cuda-toolkit" >> "$GITHUB_ENV"
|
||||
echo "STRATA_BUILD_DIR=$RUNNER_TEMP/strata-hosted-cuda-engine" >> "$GITHUB_ENV"
|
||||
apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y ca-certificates musl-tools binutils docker.io python3 time
|
||||
- name: Actual runtime-image loader boundary without GPU
|
||||
run: PYTHONDONTWRITEBYTECODE=1 python3 scripts/test-package-loader-container.py
|
||||
- name: Assemble pinned build-only CUDA components
|
||||
run: python3 scripts/bootstrap-cuda-toolkit.py --output "$CUDAToolkit_ROOT"
|
||||
- name: Build pinned GPU-hidden compiler image
|
||||
@@ -259,7 +261,7 @@ jobs:
|
||||
trap 'kill "$resource_sampler" 2>/dev/null || true; wait "$resource_sampler" 2>/dev/null || true' EXIT
|
||||
engine="$STRATA_BUILD_DIR/strata"
|
||||
package="$RUNNER_TEMP/strata-hosted-cuda-package"
|
||||
/usr/bin/time -v python3 scripts/build-linux-package.py --engine "$engine" \
|
||||
/usr/bin/time -v python3 scripts/build-linux-package.py --engine "$engine" --probe-in-runtime-image \
|
||||
--sha256 "$(sha256sum "$engine" | cut -d ' ' -f 1)" --revision "$GITHUB_SHA" \
|
||||
--build-features "$STRATA_BUILD_DIR/BUILD-FEATURES.json" \
|
||||
--cargo-target-dir "$RUNNER_TEMP/strata-hosted-package-build" --output "$package"
|
||||
@@ -357,12 +359,7 @@ jobs:
|
||||
run: python3 scripts/smoke-service-unit.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next
|
||||
- name: Native installer with actual isolated systemd user service
|
||||
run: |
|
||||
uid=$(id -u)
|
||||
sudo systemctl start "user@$uid.service"
|
||||
export XDG_RUNTIME_DIR="/run/user/$uid"
|
||||
export DBUS_SESSION_BUS_ADDRESS="unix:path=$XDG_RUNTIME_DIR/bus"
|
||||
python3 scripts/smoke-service-unit.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next --lifecycle
|
||||
python3 scripts/smoke-native-switch.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next
|
||||
python3 scripts/smoke-systemd-manager.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next
|
||||
- name: Native deployment configuration without worker launch
|
||||
run: python3 scripts/smoke-config-check.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next
|
||||
- name: Native deployment readiness deadline without GPU
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
FROM ubuntu@sha256:f610ab94648195aa356059f5b41d6085c9d4d903c072430cdd1af7bdb646106b
|
||||
RUN apt-get update -qq && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
|
||||
systemd=255.4-1ubuntu8.17 dbus=1.14.10-4ubuntu4.1 \
|
||||
dbus-user-session=1.14.10-4ubuntu4.1 python3=3.12.3-0ubuntu2.1 \
|
||||
util-linux=2.39.3-9ubuntu6.6 ca-certificates=20260601~24.04.1 && rm -rf /var/lib/apt/lists/*
|
||||
RUN useradd --create-home --uid 10001 fixture && \
|
||||
mkdir -p /run/systemd/system /run/user/10001 /home/fixture/.config && \
|
||||
chown fixture:fixture /run/user/10001 /home/fixture/.config && \
|
||||
chmod 0700 /run/user/10001 /home/fixture /home/fixture/.config
|
||||
# Empty disposable boot-context directory; the fixture starts a real user manager.
|
||||
# No system manager, host bus, host unit directory, or host cgroup is mounted.
|
||||
ENV XDG_RUNTIME_DIR=/run/user/10001
|
||||
WORKDIR /work
|
||||
@@ -14,7 +14,9 @@ import platform
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import uuid
|
||||
|
||||
REPO = Path(__file__).resolve().parents[1]
|
||||
TARGET = 'x86_64-unknown-linux-musl'
|
||||
@@ -105,6 +107,74 @@ def static_outer(binary):
|
||||
return {'program_headers': headers, 'dynamic_section': dynamic}
|
||||
|
||||
|
||||
def loader_probe(binary, probe, audit, container=False):
|
||||
if not container:
|
||||
run([binary, 'provision', '--config', probe],
|
||||
env={'PATH': os.defpath, 'CUDA_VISIBLE_DEVICES': '',
|
||||
'NVIDIA_VISIBLE_DEVICES': 'void'}, timeout=30)
|
||||
return {'environment': 'assembly-host'}
|
||||
# Use the same immutable base as the runtime image. A CPU runner's libc
|
||||
# need not satisfy the separately audited embedded engine's libc baseline.
|
||||
spec = importlib.util.spec_from_file_location('runtime_image', REPO / 'scripts/build-runtime-image.py')
|
||||
runtime = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(runtime)
|
||||
runtime.docker('pull', '--platform', 'linux/amd64', runtime.BASE, timeout=300)
|
||||
glibc = runtime.check_glibc({'engine_elf_audit': audit},
|
||||
runtime.isolated_run(runtime.BASE, ['GNU_LIBC_VERSION'], entrypoint='getconf'))
|
||||
image_id = runtime.docker('image', 'inspect', '--format', '{{.Id}}', runtime.BASE).stdout.strip()
|
||||
name = 'strata-package-probe-' + uuid.uuid4().hex
|
||||
staging_name = name + '-stage'
|
||||
volume = name
|
||||
try:
|
||||
with tempfile.TemporaryDirectory(prefix='strata-package-probe-') as tmp:
|
||||
copied = Path(tmp) / 'cli'
|
||||
shutil.copyfile(binary, copied)
|
||||
copied.chmod(0o755)
|
||||
config = Path(tmp) / 'probe.json'
|
||||
shutil.copyfile(probe, config)
|
||||
config.chmod(0o644)
|
||||
runtime.docker('volume', 'create', volume)
|
||||
runtime.docker('create', '--name', staging_name, '--platform', 'linux/amd64',
|
||||
'--network', 'none', '--cap-drop', 'ALL',
|
||||
'--mount', 'type=volume,source=' + volume + ',target=/probe',
|
||||
'--entrypoint', '/bin/true', runtime.BASE)
|
||||
# The staging container is never started. The serving probe receives
|
||||
# only a read-only volume, so docker cp cannot mutate its rootfs.
|
||||
runtime.docker('cp', copied, staging_name + ':/probe/cli', timeout=180)
|
||||
runtime.docker('cp', config, staging_name + ':/probe/probe.json')
|
||||
runtime.docker('create', '--name', name, '--platform', 'linux/amd64',
|
||||
'--network', 'none', '--read-only', '--user', '65532:65532',
|
||||
'--cap-drop', 'ALL', '--security-opt', 'no-new-privileges',
|
||||
'--tmpfs', '/tmp:rw,nosuid,nodev,size=1g',
|
||||
'--mount', 'type=volume,source=' + volume + ',target=/probe,readonly',
|
||||
'-e', 'CUDA_VISIBLE_DEVICES=', '-e', 'NVIDIA_VISIBLE_DEVICES=void',
|
||||
'-e', 'LD_LIBRARY_PATH=', '--entrypoint', '/bin/sh', runtime.BASE,
|
||||
'-c', 'for p in /dev/nvidia*; do if [ -e "$p" ]; then '
|
||||
'echo "package probe refuses NVIDIA devices" >&2; exit 1; fi; done; '
|
||||
'exec /probe/cli "$@"',
|
||||
'package-probe', 'provision', '--config', '/probe/probe.json')
|
||||
result = runtime.docker('start', '--attach', name, timeout=60, check=False)
|
||||
code = runtime.docker('inspect', '--format', '{{.State.ExitCode}}', name).stdout.strip()
|
||||
if result.returncode != 0 or code != '0':
|
||||
raise ValueError('pinned runtime package provision failed: ' + result.stderr.strip())
|
||||
finally:
|
||||
original_failure = sys.exc_info()[0] is not None
|
||||
errors = []
|
||||
for command in [('rm', '-f', name), ('rm', '-f', staging_name), ('volume', 'rm', volume)]:
|
||||
try:
|
||||
cleaned = runtime.docker(*command, check=False)
|
||||
if cleaned.returncode and 'No such ' not in cleaned.stderr:
|
||||
errors.append(cleaned.stderr.strip())
|
||||
except (OSError, subprocess.SubprocessError) as error:
|
||||
errors.append(str(error))
|
||||
if errors:
|
||||
print('Package probe cleanup failed: ' + '; '.join(errors), file=sys.stderr)
|
||||
if not original_failure:
|
||||
raise ValueError('owned package probe cleanup failed')
|
||||
return {'environment': 'pinned-runtime-container', 'base': runtime.BASE,
|
||||
'image_id': image_id, 'glibc': glibc, 'user': '65532:65532', 'gpu_tested': False}
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def lock(path):
|
||||
# Caller-controlled build/output paths are private; keep the inode for reuse.
|
||||
@@ -179,11 +249,13 @@ def assemble(args):
|
||||
raise ValueError('combined engine identity does not match pinned input')
|
||||
probe = stage / 'probe.json'
|
||||
probe.write_text(json.dumps({'engine': {'executable': '@embedded'}, 'engine_probe': True}))
|
||||
run([binary, 'provision', '--config', probe], env=probe_env, timeout=30)
|
||||
loader = loader_probe(binary, probe, audit,
|
||||
getattr(args, 'probe_in_runtime_image', False))
|
||||
source_check(REPO, args.revision)
|
||||
provenance = {'schema_version': 1, 'kind': 'cpu-fixture' if args.cpu_fixture else 'static-cuda-preview',
|
||||
'source_revision': args.revision, 'target': TARGET, 'engine': info,
|
||||
'engine_elf_audit': audit, 'outer_elf_audit': outer,
|
||||
'loader_probe': loader,
|
||||
'cargo_lock_sha256': sha256(REPO / 'Cargo.lock'),
|
||||
'rustc': run(['rustc', '--version']), 'cargo': run(['cargo', '--version']),
|
||||
'gpu_tested': False, 'model_tested': False, 'clean_node_tested': False,
|
||||
@@ -209,6 +281,8 @@ def main():
|
||||
parser.add_argument('--cpu-fixture', action='store_true', help='explicit non-CUDA test artifact; never a GPU release')
|
||||
parser.add_argument('--build-features', type=Path,
|
||||
help='exact build feature receipt emitted by build-static-cuda.sh')
|
||||
parser.add_argument('--probe-in-runtime-image', action='store_true',
|
||||
help='execute actual provision in the pinned runtime base instead of the assembly host')
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
print(json.dumps(assemble(args)))
|
||||
|
||||
@@ -0,0 +1,269 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run unchanged native lifecycle gates with a disposable real systemd manager.
|
||||
|
||||
CPU-only offline fixture. Setup alone gets mount/UID capabilities; journald,
|
||||
D-Bus, manager, Rust CLI and synthetic workers have empty capability sets.
|
||||
The private writable cgroup mount enables real manager process tracking.
|
||||
Setup uses fixture-only apparmor=unconfined for the private cgroup mount;
|
||||
default seccomp stays enabled. No host paths/devices/namespaces are shared.
|
||||
Existing tests exercise stop/rollback; this is not a separate forced-descendant
|
||||
KillMode test, installed-driver inference, or model quality evidence.
|
||||
"""
|
||||
import argparse
|
||||
import glob
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import uuid
|
||||
|
||||
UID = 10001
|
||||
CAPS = ('SYS_ADMIN', 'CHOWN', 'SETUID', 'SETGID', 'SETPCAP')
|
||||
FILES = ('smoke-service-unit.py', 'smoke-native-switch.py', 'smoke-worker-cancel.py')
|
||||
|
||||
|
||||
def run(*args, **kwargs):
|
||||
return subprocess.run(args, check=True, **kwargs)
|
||||
|
||||
|
||||
def no_gpu():
|
||||
assert not glob.glob('/dev/nvidia*'), 'raw NVIDIA devices are forbidden'
|
||||
assert os.environ.get('NVIDIA_VISIBLE_DEVICES') == 'void'
|
||||
assert os.environ.get('CUDA_VISIBLE_DEVICES') == ''
|
||||
|
||||
|
||||
def zero_caps(pid='self'):
|
||||
status = Path(f'/proc/{pid}/status').read_text()
|
||||
found = [line.split(':', 1)[1].strip() for line in status.splitlines()
|
||||
if line.startswith(('CapInh:', 'CapPrm:', 'CapEff:', 'CapBnd:', 'CapAmb:'))]
|
||||
assert found == ['0000000000000000'] * 5, (pid, found)
|
||||
assert any(line.startswith('NoNewPrivs:') and line.split(':', 1)[1].strip() == '1'
|
||||
for line in status.splitlines()), (pid, 'NoNewPrivs missing')
|
||||
|
||||
|
||||
def drop_command(*args):
|
||||
return ['setpriv', f'--reuid={UID}', f'--regid={UID}', '--clear-groups',
|
||||
'--bounding-set=-all', '--inh-caps=-all', '--ambient-caps=-all', *args]
|
||||
|
||||
|
||||
def root_setup():
|
||||
# Direct host invocation must fail before any mount, chown, or unit operation.
|
||||
assert Path('/.dockerenv').is_file() and os.getpid() == 1 and os.getuid() == 0
|
||||
nonce = os.environ['LELEKA_MANAGER_FIXTURE_NONCE']
|
||||
assert len(nonce) == 32 and all(c in '0123456789abcdef' for c in nonce)
|
||||
no_gpu()
|
||||
run('dpkg-query', '-W', 'systemd', 'dbus', 'dbus-user-session', 'python3', 'util-linux',
|
||||
'ca-certificates')
|
||||
assert Path('/proc/self/cgroup').read_text().strip() == '0::/'
|
||||
target = Path('/sys/fs/cgroup')
|
||||
assert target.is_dir() and not target.is_symlink()
|
||||
mounts = Path('/proc/self/mountinfo').read_text().splitlines()
|
||||
assert any(line.split()[4] == str(target) and ' - cgroup2 ' in line for line in mounts)
|
||||
owned = Path('/run') / ('leleka-cgroup-' + nonce)
|
||||
assert not owned.exists()
|
||||
owned.mkdir(mode=0o700)
|
||||
run('mount', '-t', 'cgroup2', 'none', str(owned))
|
||||
run('mount', '--move', str(owned), str(target))
|
||||
assert set(Path('/sys/fs/cgroup/cgroup.procs').read_text().split()) <= {str(os.getpid())}
|
||||
for path in (target, target/'cgroup.procs', target/'cgroup.subtree_control'):
|
||||
os.chown(path, UID, UID)
|
||||
# Only known staged regular files are normalized. The CLI remains root-owned.
|
||||
for name in (*FILES, 'smoke-systemd-manager.py', 'strata-next'):
|
||||
path = Path('/work') / name
|
||||
assert path.is_file() and not path.is_symlink()
|
||||
os.chown(path, 0, 0)
|
||||
path.chmod(0o755 if name == 'strata-next' else 0o644)
|
||||
for path in (Path('/run/systemd/journal'), Path('/run/log/journal')):
|
||||
path.mkdir(parents=True, exist_ok=True)
|
||||
os.chown(path, UID, UID)
|
||||
config = Path('/etc/systemd/journald.conf.d')
|
||||
config.mkdir(exist_ok=True)
|
||||
(config/'fixture.conf').write_text('[Journal]\nStorage=volatile\nReadKMsg=no\n'
|
||||
'ForwardToKMsg=no\nForwardToConsole=no\nForwardToWall=no\n')
|
||||
journal = subprocess.Popen(drop_command('/usr/lib/systemd/systemd-journald'))
|
||||
env = dict(os.environ, HOME='/home/fixture', USER='fixture', LOGNAME='fixture',
|
||||
XDG_CONFIG_HOME='/home/fixture/.config',
|
||||
DBUS_SESSION_BUS_ADDRESS='unix:path=/run/user/10001/fixture-bus',
|
||||
PYTHONDONTWRITEBYTECODE='1', LELEKA_JOURNAL_PID=str(journal.pid))
|
||||
# exec retains journald's parent for bounded waitpid/reaping by the test user.
|
||||
os.execvpe('setpriv', drop_command('python3', '/work/smoke-systemd-manager.py',
|
||||
'--inside-user'), env)
|
||||
|
||||
|
||||
def finish_process(process):
|
||||
if process is None:
|
||||
return
|
||||
if process.poll() is None:
|
||||
process.terminate()
|
||||
try:
|
||||
process.wait(timeout=5)
|
||||
except subprocess.TimeoutExpired:
|
||||
process.kill()
|
||||
process.wait(timeout=5)
|
||||
|
||||
|
||||
def finish_journal(pid):
|
||||
try:
|
||||
os.kill(pid, signal.SIGTERM)
|
||||
except ProcessLookupError:
|
||||
pass
|
||||
deadline = time.monotonic() + 5
|
||||
while time.monotonic() < deadline:
|
||||
if os.waitpid(pid, os.WNOHANG)[0]:
|
||||
return
|
||||
time.sleep(.05)
|
||||
os.kill(pid, signal.SIGKILL)
|
||||
deadline = time.monotonic() + 5
|
||||
while time.monotonic() < deadline:
|
||||
if os.waitpid(pid, os.WNOHANG)[0]:
|
||||
return
|
||||
time.sleep(.05)
|
||||
raise TimeoutError('journald did not reap after SIGKILL; outer container removal required')
|
||||
|
||||
|
||||
def user_tests():
|
||||
assert Path('/.dockerenv').is_file() and os.getpid() == 1
|
||||
no_gpu()
|
||||
assert os.getuid() == UID
|
||||
zero_caps()
|
||||
journal_pid = int(os.environ['LELEKA_JOURNAL_PID'])
|
||||
bus = manager = None
|
||||
failed = False
|
||||
cleanup_errors = []
|
||||
try:
|
||||
bus = subprocess.Popen(['dbus-daemon', '--session', '--nofork',
|
||||
'--address=' + os.environ['DBUS_SESSION_BUS_ADDRESS']])
|
||||
manager = subprocess.Popen(['/usr/lib/systemd/systemd', '--user', '--unit=basic.target',
|
||||
'--log-target=console', '--log-level=warning'])
|
||||
deadline = time.monotonic() + 25
|
||||
while True:
|
||||
assert manager.poll() is None and bus.poll() is None, 'manager or bus exited'
|
||||
result = subprocess.run(['systemctl', '--user', 'show', '--property=Version'],
|
||||
text=True, capture_output=True, timeout=3)
|
||||
if result.returncode == 0 and Path('/run/systemd/journal/stdout').exists():
|
||||
break
|
||||
assert time.monotonic() < deadline, result.stderr
|
||||
time.sleep(.2)
|
||||
zero_caps(manager.pid)
|
||||
zero_caps(bus.pid)
|
||||
zero_caps(journal_pid)
|
||||
assert str(manager.pid) in Path('/sys/fs/cgroup/init.scope/cgroup.procs').read_text().split()
|
||||
print(result.stdout.strip(), flush=True)
|
||||
print('Private real manager, bus, journal and cgroup ready; all capabilities zero', flush=True)
|
||||
run('python3', '/work/smoke-service-unit.py', '/work/strata-next', '--lifecycle', timeout=600)
|
||||
run('python3', '/work/smoke-native-switch.py', '/work/strata-next', timeout=300)
|
||||
except BaseException:
|
||||
failed = True
|
||||
raise
|
||||
finally:
|
||||
# Every owned process is cleaned even if another cleanup step fails.
|
||||
for cleanup in (
|
||||
lambda: subprocess.run(['systemctl', '--user', 'exit'], check=False, timeout=5),
|
||||
lambda: finish_process(manager), lambda: finish_process(bus),
|
||||
lambda: finish_journal(journal_pid),
|
||||
):
|
||||
try:
|
||||
cleanup()
|
||||
except Exception as error:
|
||||
cleanup_errors.append(str(error))
|
||||
if cleanup_errors:
|
||||
print('Fixture cleanup errors: ' + '; '.join(cleanup_errors), file=sys.stderr)
|
||||
if not failed:
|
||||
raise RuntimeError('owned manager fixture cleanup failed')
|
||||
|
||||
|
||||
def host(binary):
|
||||
assert not glob.glob('/dev/nvidia*'), 'manager fixture is restricted to a CPU host'
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
binary = binary.resolve(strict=True)
|
||||
nonce = uuid.uuid4().hex
|
||||
name = 'leleka-systemd-smoke-' + nonce
|
||||
image = name + ':fixture'
|
||||
with tempfile.TemporaryDirectory(prefix=name + '-') as directory:
|
||||
stage = Path(directory)
|
||||
dockerfile = root/'deploy/Dockerfile.systemd-smoke'
|
||||
context = stage/'image-context'
|
||||
context.mkdir()
|
||||
shutil.copy2(dockerfile, context/'Dockerfile')
|
||||
for filename in (*FILES, 'smoke-systemd-manager.py'):
|
||||
shutil.copy2(root/'scripts'/filename, stage/filename)
|
||||
shutil.copy2(binary, stage/'strata-next')
|
||||
def digest(path):
|
||||
checksum = hashlib.sha256()
|
||||
with path.open('rb') as source:
|
||||
for block in iter(lambda: source.read(1024 * 1024), b''):
|
||||
checksum.update(block)
|
||||
return checksum.hexdigest()
|
||||
hashes = {path.name: digest(path) for path in stage.iterdir() if path.is_file()}
|
||||
hashes['Dockerfile.systemd-smoke'] = digest(dockerfile)
|
||||
print(json.dumps({'fixture_sha256': hashes}, sort_keys=True), flush=True)
|
||||
try:
|
||||
run('docker', 'build', '--platform', 'linux/amd64', '-t', image, str(context), timeout=600)
|
||||
run('docker', 'create', '--name', name, '--platform', 'linux/amd64', '--tty',
|
||||
'--network', 'none', '--cgroupns', 'private', '--user', '0', '--cap-drop', 'ALL',
|
||||
*(arg for cap in CAPS for arg in ('--cap-add', cap)),
|
||||
'--security-opt', 'no-new-privileges',
|
||||
'--security-opt', 'apparmor=unconfined',
|
||||
'-e', 'NVIDIA_VISIBLE_DEVICES=void', '-e', 'CUDA_VISIBLE_DEVICES=',
|
||||
'-e', 'LELEKA_MANAGER_FIXTURE_NONCE=' + nonce,
|
||||
image, 'python3', '/work/smoke-systemd-manager.py', '--inside-root', timeout=30)
|
||||
info = json.loads(subprocess.check_output(['docker', 'inspect', name], text=True))[0]
|
||||
config = info['HostConfig']
|
||||
assert config['CgroupnsMode'] == 'private' and config['NetworkMode'] == 'none'
|
||||
assert not config['Privileged'] and config['PidMode'] == ''
|
||||
assert not config['Binds'] and not info['Mounts'] and not config['Devices']
|
||||
assert not config['DeviceRequests'] and config['IpcMode'] == 'private'
|
||||
assert config['CapDrop'] == ['ALL']
|
||||
assert {cap.removeprefix('CAP_') for cap in config['CapAdd']} == set(CAPS)
|
||||
assert set(config['SecurityOpt']) == {'no-new-privileges', 'apparmor=unconfined'}
|
||||
print(json.dumps({'image_id': info['Image'], 'source': 'isolated CPU fixture',
|
||||
'setup_security_options': config['SecurityOpt'],
|
||||
'setup_capabilities': config['CapAdd'],
|
||||
'user_capabilities': 'zero', 'seccomp': 'Docker default'}), flush=True)
|
||||
# docker cp works with a remote daemon; runner paths are not bind-mounted.
|
||||
for filename in (*FILES, 'smoke-systemd-manager.py', 'strata-next'):
|
||||
run('docker', 'cp', str(stage/filename), name + ':/work/' + filename, timeout=60)
|
||||
run('docker', 'start', '--attach', name, timeout=1000)
|
||||
state = json.loads(subprocess.check_output(['docker', 'inspect', name], text=True))[0]['State']
|
||||
assert state['ExitCode'] == 0, state
|
||||
finally:
|
||||
# Container removal is the final namespace-wide cleanup safety net.
|
||||
original_failure = sys.exc_info()[0] is not None
|
||||
errors = []
|
||||
for kind, command in (('container', ['docker', 'rm', '--force', name]),
|
||||
('image', ['docker', 'image', 'rm', image])):
|
||||
try:
|
||||
result = subprocess.run(command, text=True, capture_output=True, timeout=30)
|
||||
if result.returncode and 'No such ' not in result.stderr:
|
||||
errors.append(kind + ': ' + result.stderr)
|
||||
except Exception as error:
|
||||
errors.append(kind + ': ' + str(error))
|
||||
if errors:
|
||||
print('Outer fixture cleanup errors: ' + '; '.join(errors), file=sys.stderr)
|
||||
if not original_failure:
|
||||
raise RuntimeError('outer fixture cleanup failed')
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('binary', nargs='?', type=Path)
|
||||
parser.add_argument('--inside-root', action='store_true')
|
||||
parser.add_argument('--inside-user', action='store_true')
|
||||
args = parser.parse_args()
|
||||
if args.inside_root:
|
||||
root_setup()
|
||||
elif args.inside_user:
|
||||
user_tests()
|
||||
else:
|
||||
assert args.binary is not None
|
||||
host(args.binary)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,54 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Real CPU Docker transport/failure regression; not engine or GPU qualification."""
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
spec = importlib.util.spec_from_file_location('package', Path(__file__).with_name('build-linux-package.py'))
|
||||
package = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(package)
|
||||
|
||||
|
||||
class LoaderContainerTests(unittest.TestCase):
|
||||
def test_actual_nonroot_provision_and_failure_cleanup(self):
|
||||
runtime_spec = importlib.util.spec_from_file_location('runtime', Path(__file__).with_name('build-runtime-image.py'))
|
||||
runtime = importlib.util.module_from_spec(runtime_spec)
|
||||
runtime_spec.loader.exec_module(runtime)
|
||||
|
||||
def probes():
|
||||
containers = set(runtime.docker('ps', '-a', '--filter', 'name=strata-package-probe-',
|
||||
'--format', '{{.ID}}').stdout.splitlines())
|
||||
volumes = set(runtime.docker('volume', 'ls', '--filter', 'name=strata-package-probe-',
|
||||
'--format', '{{.Name}}').stdout.splitlines())
|
||||
return containers, volumes
|
||||
|
||||
before = probes()
|
||||
with tempfile.TemporaryDirectory(prefix='strata-loader-contract-') as tmp:
|
||||
binary, config = Path(tmp) / 'cli', Path(tmp) / 'config'
|
||||
config.write_text('{"engine":{"executable":"@embedded"},"engine_probe":true}')
|
||||
binary.write_text('#!/bin/sh\n'
|
||||
'test "$(id -u)" = 65532 || exit 21\n'
|
||||
'test "$1" = provision && test "$2" = --config || exit 22\n'
|
||||
'grep -q @embedded "$3" || exit 23\n'
|
||||
'test "$NVIDIA_VISIBLE_DEVICES" = void && test -z "$CUDA_VISIBLE_DEVICES" || exit 24\n'
|
||||
'touch /tmp/owned-loader-fixture || exit 25\n'
|
||||
'if touch /forbidden-loader-fixture 2>/dev/null; then exit 26; fi\n')
|
||||
original = binary.read_bytes()
|
||||
audit = {'minimum_glibc': '2.38'}
|
||||
result = package.loader_probe(binary, config, audit, container=True)
|
||||
self.assertEqual(result['base'], runtime.BASE)
|
||||
self.assertFalse(result['gpu_tested'])
|
||||
self.assertEqual(binary.read_bytes(), original)
|
||||
self.assertEqual(probes(), before)
|
||||
binary.write_text('#!/bin/sh\nexit 42\n')
|
||||
with self.assertRaisesRegex(ValueError, 'provision failed'):
|
||||
package.loader_probe(binary, config, audit, container=True)
|
||||
self.assertEqual(probes(), before)
|
||||
with self.assertRaisesRegex(ValueError, 'below engine requirement'):
|
||||
package.loader_probe(binary, config, {'minimum_glibc': '99.0'}, container=True)
|
||||
self.assertEqual(probes(), before)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user