277 lines
17 KiB
Python
277 lines
17 KiB
Python
"""Readiness convergence and metadata-only reconciliation; no Docker required."""
|
|
import copy
|
|
from contextlib import ExitStack, redirect_stdout, redirect_stderr
|
|
import hashlib
|
|
import importlib.util
|
|
import io
|
|
import json
|
|
from pathlib import Path
|
|
from types import SimpleNamespace
|
|
import tempfile
|
|
import unittest
|
|
from unittest import mock
|
|
|
|
from test_device_b2_foundation import R
|
|
|
|
spec = importlib.util.spec_from_file_location('b2_reconciliation_builder', Path(__file__).with_name('build_device_b2_reconciliation.py'))
|
|
B = importlib.util.module_from_spec(spec)
|
|
spec.loader.exec_module(B)
|
|
|
|
|
|
def baseline_fields():
|
|
return {'HostConfig': {'Mounts': []}, 'Config': {'Env': ['PRESERVED=synthetic']}, 'Mounts': [], 'networks': ['private']}
|
|
|
|
|
|
def snapshot(fields):
|
|
return {service: {'service': service, 'containerId': service + '-old', 'imageId': 'same-image',
|
|
'health': 'healthy', 'running': True, 'status': 'running', 'restartCount': 0,
|
|
'runtimeConfigSha256': R.device_release_drift_digest(fields)}
|
|
for service in R.DEVICE_RELEASE_INVENTORY}
|
|
|
|
|
|
class Readiness(unittest.TestCase):
|
|
def accept_with_startup(self, rollback, unhealthy=False, drift=None):
|
|
fields = baseline_fields()
|
|
current_fields = copy.deepcopy(fields)
|
|
if not rollback:
|
|
current_fields['Config']['Env'].append('DEVICE_B2_SECRET_ROOT=' + R.DEVICE_B2_DESTINATION)
|
|
current_fields['HostConfig']['Mounts'].append({'Type': 'bind', 'Source': str(R.DEVICE_B2_SECRET_ROOT),
|
|
'Target': R.DEVICE_B2_DESTINATION, 'ReadOnly': False})
|
|
current_fields['Mounts'].append({'Type': 'bind', 'Source': str(R.DEVICE_B2_SECRET_ROOT),
|
|
'Destination': R.DEVICE_B2_DESTINATION, 'RW': True, 'Propagation': 'rprivate'})
|
|
before = {'runtime': snapshot(fields), 'compose': {}, 'otherComposeServices': {}, 'installedFiles': {}}
|
|
state = {'health': 'starting', 'polls': 0, 'snapshots': 0}
|
|
|
|
def inspect(command, **kwargs):
|
|
self.assertEqual(command[1], 'inspect')
|
|
service = command[-1]
|
|
if service == 'device-control-core':
|
|
state['polls'] += 1
|
|
state['health'] = 'unhealthy' if unhealthy else ('starting' if state['polls'] == 1 else 'healthy')
|
|
return SimpleNamespace(stdout=state['health'], stderr='', returncode=0)
|
|
return SimpleNamespace(stdout='healthy', stderr='', returncode=0)
|
|
|
|
def samples():
|
|
state['snapshots'] += 1
|
|
result = {service: {'runtime': copy.deepcopy(row), 'fields': copy.deepcopy(fields)}
|
|
for service, row in before['runtime'].items()}
|
|
core = result['device-control-core']
|
|
core['runtime']['containerId'] = 'new-generation'
|
|
core['runtime']['health'] = state['health']
|
|
core['fields'] = copy.deepcopy(current_fields)
|
|
if drift == 'image': core['runtime']['imageId'] = 'changed-image'
|
|
if drift == 'network': core['fields']['networks'] = ['other']
|
|
if drift == 'preserved': result['device-postgres']['runtime']['containerId'] = 'unexpected-recreate'
|
|
return result
|
|
|
|
with ExitStack() as stack:
|
|
stack.enter_context(mock.patch.object(R, 'compose_service_container_id', side_effect=lambda c, s: s))
|
|
stack.enter_context(mock.patch.object(R.subprocess, 'run', side_effect=inspect))
|
|
stack.enter_context(mock.patch.object(R.time, 'sleep'))
|
|
stack.enter_context(mock.patch.object(R, 'healthcheck_url'))
|
|
stack.enter_context(mock.patch.object(R, 'device_release_drift_sample', side_effect=samples))
|
|
stack.enter_context(mock.patch.object(R, 'device_release_other_compose_services', return_value={}))
|
|
stack.enter_context(mock.patch.object(R, 'collect_exact_files', return_value={}))
|
|
stack.enter_context(mock.patch.object(R, 'device_b2_private_directory'))
|
|
stack.enter_context(mock.patch.object(R, 'device_b2_schema', return_value=R.DEVICE_B2_EXPECTED_SCHEMA))
|
|
stack.enter_context(mock.patch.object(R, 'read_strict_json', return_value={'schemaSha256': R.device_release_drift_digest(R.DEVICE_B2_EXPECTED_SCHEMA)}))
|
|
stack.enter_context(redirect_stdout(io.StringIO()))
|
|
if unhealthy or drift:
|
|
with self.assertRaises(R.DeployError): R.accept_device_b2(before, Path('/synthetic'), rollback=rollback)
|
|
else:
|
|
R.accept_device_b2(before, Path('/synthetic'), rollback=rollback)
|
|
return state
|
|
|
|
def test_apply_and_rollback_wait_for_healthy_before_strict_snapshot(self):
|
|
for rollback in (False, True):
|
|
with self.subTest(rollback=rollback):
|
|
state = self.accept_with_startup(rollback)
|
|
self.assertEqual(state['polls'], 2)
|
|
self.assertGreater(state['snapshots'], 0)
|
|
|
|
def test_persistent_unhealthy_does_not_reach_snapshot_or_accept(self):
|
|
for rollback in (False, True):
|
|
state = self.accept_with_startup(rollback, unhealthy=True)
|
|
self.assertEqual(state['polls'], 60)
|
|
self.assertEqual(state['snapshots'], 0)
|
|
|
|
def test_readiness_never_weakens_image_network_or_preserved_service_guards(self):
|
|
for rollback in (False, True):
|
|
for drift in ('image', 'network', 'preserved'):
|
|
with self.subTest(rollback=rollback, drift=drift):
|
|
self.accept_with_startup(rollback, drift=drift)
|
|
|
|
|
|
class Reconciliation(unittest.TestCase):
|
|
def setUp(self):
|
|
self.tmp = tempfile.TemporaryDirectory()
|
|
self.addCleanup(self.tmp.cleanup)
|
|
self.root = Path(self.tmp.name)
|
|
self.live = self.root / 'live'
|
|
self.live.mkdir()
|
|
self.archive = self.root / 'reconciliation.tgz'
|
|
B.build(self.archive)
|
|
self.manifest, self.entries, self.payload = R.load_artifact(self.archive, self.root / 'unpack')
|
|
|
|
def test_real_archive_is_deterministic_data_only_and_has_no_runtime_action(self):
|
|
other = self.root / 'second.tgz'
|
|
B.build(other)
|
|
self.assertEqual(self.archive.read_bytes(), other.read_bytes())
|
|
with self.assertRaises(FileExistsError): B.build(other)
|
|
self.assertEqual(self.entries, [R.DEVICE_B2_RECON_ENTRY])
|
|
self.assertEqual(R.component_services(self.manifest['component'], self.entries), ())
|
|
self.assertFalse(R.component_builds(self.manifest['component'], self.entries))
|
|
with mock.patch.object(R.subprocess, 'run', side_effect=AssertionError('runtime command forbidden')):
|
|
R.run_component_runtime(self.manifest['component'], self.entries, ())
|
|
for p in ('secrets/key', '.env', R.DEVICE_B2_SQL, R.DEVICE_B2_OVERRIDE, 'hooks.sh'):
|
|
with self.subTest(path=p), self.assertRaises(R.DeployError):
|
|
R.allowed_payload_path(self.manifest['component'], p)
|
|
for entries in ([], self.entries + ['services/device-control-core']):
|
|
with self.assertRaises(R.DeployError): R.component_services(self.manifest['component'], entries)
|
|
|
|
def test_descriptor_cannot_select_other_incident_or_commands(self):
|
|
descriptor = self.payload / R.DEVICE_B2_RECON_ENTRY
|
|
for key, value in [('failedReleaseId', 'another'), ('backupId', '../escape'), ('mode', 'restart'), ('command', 'sh')]:
|
|
d = R.device_b2_reconciliation_descriptor()
|
|
d[key] = value
|
|
descriptor.write_text(json.dumps(d))
|
|
with self.subTest(key=key), self.assertRaises(R.DeployError):
|
|
R.validate_device_b2_reconciliation_payload(self.payload, self.entries, R.DEVICE_B2_RECON_ID)
|
|
|
|
def proof_context(self, stack, **overrides):
|
|
applied = [{'component': 'device-core-release', 'id': R.DEVICE_B2_BASELINE_ID, 'sha256': R.DEVICE_B2_BASELINE_SHA}]
|
|
failures = [R.device_b2_002_failed_row()]
|
|
stack.enter_context(mock.patch.object(R, 'DEVICE_PLANE_ROOT', self.live))
|
|
stack.enter_context(mock.patch.object(R, 'DEVICE_B2_SECRET_ROOT', self.live / 'vault'))
|
|
stack.enter_context(mock.patch.object(R, 'device_b2_002_evidence', return_value={'proof': 'pinned-backup'}))
|
|
stack.enter_context(mock.patch.object(R, 'device_b2_schema', return_value=overrides.get('schema', [])))
|
|
stack.enter_context(mock.patch.object(R, 'load_state', side_effect=lambda path: overrides.get('failed', failures) if path == R.FAILED_STATE_FILE else overrides.get('applied', applied)))
|
|
return stack.enter_context(mock.patch.object(R, 'accept_device_b2'))
|
|
|
|
def test_readonly_proof_rejects_remaining_files_vault_schema_and_other_incident(self):
|
|
for case in ('good', 'file', 'symlink', 'vault', 'schema', 'newer-release', 'another-failed', 'installed-foundation'):
|
|
with self.subTest(case=case), ExitStack() as stack:
|
|
changes = {}
|
|
target = None
|
|
if case in ('file', 'symlink'):
|
|
target = self.live / R.DEVICE_B2_OVERRIDE
|
|
if case == 'file': target.write_text('retained')
|
|
else: target.symlink_to(self.live / 'missing')
|
|
if case == 'vault':
|
|
target = self.live / 'vault'; target.mkdir()
|
|
if case == 'schema': changes['schema'] = R.DEVICE_B2_EXPECTED_SCHEMA
|
|
if case == 'newer-release': changes['applied'] = []
|
|
if case == 'installed-foundation': changes['applied'] = [{'component': 'device-b2-foundation'}]
|
|
if case == 'another-failed': changes['failed'] = [R.device_b2_002_failed_row(), {'component': 'device-b2-foundation', 'started_apply': True, 'id': 'another'}]
|
|
accept = self.proof_context(stack, **changes)
|
|
stack.enter_context(redirect_stdout(io.StringIO()))
|
|
if case == 'good':
|
|
R.preflight_device_b2_reconciliation(self.payload, self.entries, R.DEVICE_B2_RECON_ID)
|
|
accept.assert_called_once()
|
|
self.assertTrue(accept.call_args.kwargs['rollback'])
|
|
else:
|
|
with self.assertRaises(R.DeployError): R.preflight_device_b2_reconciliation(self.payload, self.entries, R.DEVICE_B2_RECON_ID)
|
|
accept.assert_not_called()
|
|
if target:
|
|
if target.is_dir(): target.rmdir()
|
|
else: target.unlink()
|
|
|
|
def test_marker_alone_cannot_clear_failure_and_other_failed_rows_never_match(self):
|
|
with mock.patch.object(R, 'DEVICE_PLANE_ROOT', self.live), mock.patch.object(R, 'load_state', return_value=[]):
|
|
self.assertFalse(R.device_b2_002_reconciled(R.device_b2_002_failed_row()))
|
|
marker = self.live / R.DEVICE_B2_RECON_ENTRY
|
|
marker.parent.mkdir()
|
|
marker.write_text(json.dumps(R.device_b2_reconciliation_descriptor()))
|
|
with self.assertRaises(R.DeployError): R.device_b2_002_reconciled(R.device_b2_002_failed_row())
|
|
wrong = R.device_b2_002_failed_row(); wrong['sha256'] = '0'*64
|
|
self.assertFalse(R.device_b2_002_reconciled(wrong))
|
|
|
|
def test_failed_foundation_blocks_ordinary_releases_even_without_overlay(self):
|
|
with mock.patch.object(R, 'DEVICE_PLANE_ROOT', self.live), mock.patch.object(R, 'load_state', return_value=[R.device_b2_002_failed_row()]):
|
|
with self.assertRaises(R.DeployError): R.device_b2_compose_files(())
|
|
|
|
def test_incident_evidence_checks_exact_journal_archive_and_every_backup_file(self):
|
|
failed_dir = self.root/'incident-failed'; failed_dir.mkdir()
|
|
backups = self.root/'incident-backups'; backups.mkdir()
|
|
backup = backups/R.DEVICE_B2_002_BACKUP; backup.mkdir()
|
|
files = {'device-b2-before.json': b'{"runtime":{}}', 'device-b2-schema.json': b'{}',
|
|
'manifest.env': b'synthetic', 'files.txt': ('\n'.join(R.DEVICE_B2_ENTRIES)+'\n').encode(),
|
|
'existing-files.txt': b'', 'missing-files.txt': ('\n'.join(R.DEVICE_B2_ENTRIES)+'\n').encode(),
|
|
'source-before.tgz': b'synthetic-empty-source'}
|
|
for name, value in files.items(): (backup/name).write_bytes(value)
|
|
archive = failed_dir/R.device_b2_002_failed_row()['artifact']; archive.write_bytes(b'synthetic-archive')
|
|
hashes = {name: hashlib.sha256(value).hexdigest() for name, value in files.items()}
|
|
with ExitStack() as stack:
|
|
for name, value in [('FAILED_DIR', failed_dir), ('BACKUPS_DIR', backups),
|
|
('DEVICE_B2_002_SHA', hashlib.sha256(archive.read_bytes()).hexdigest()),
|
|
('DEVICE_B2_002_BACKUP_HASHES', hashes)]:
|
|
stack.enter_context(mock.patch.object(R, name, value))
|
|
failed = [R.device_b2_002_failed_row()]; applied = []
|
|
stack.enter_context(mock.patch.object(R, 'load_state', side_effect=lambda p: failed if p == R.FAILED_STATE_FILE else applied))
|
|
self.assertEqual(R.device_b2_002_evidence(), {'runtime': {}})
|
|
for name, value in files.items():
|
|
(backup/name).write_bytes(value+b'changed')
|
|
with self.subTest(file=name), self.assertRaises(R.DeployError): R.device_b2_002_evidence()
|
|
(backup/name).write_bytes(value)
|
|
archive.write_bytes(b'changed')
|
|
with self.assertRaises(R.DeployError): R.device_b2_002_evidence()
|
|
archive.write_bytes(b'synthetic-archive')
|
|
applied.append({'id': R.DEVICE_B2_002_ID})
|
|
with self.assertRaises(R.DeployError): R.device_b2_002_evidence()
|
|
applied.clear()
|
|
failed[0]['rollback_status'] = 'different'
|
|
with self.assertRaises(R.DeployError): R.device_b2_002_evidence()
|
|
|
|
def execute_metadata_apply(self, fail_after_marker=False):
|
|
for name in ('inbox', 'applied', 'failed', 'backups', 'state', 'tmp'): (self.root / name).mkdir()
|
|
with ExitStack() as stack:
|
|
for name, value in [('INBOX', self.root/'inbox'), ('APPLIED_DIR', self.root/'applied'),
|
|
('FAILED_DIR', self.root/'failed'), ('BACKUPS_DIR', self.root/'backups'),
|
|
('STATE_DIR', self.root/'state'), ('TMP_DIR', self.root/'tmp'),
|
|
('STATE_FILE', self.root/'state/applied.jsonl'), ('FAILED_STATE_FILE', self.root/'state/failed.jsonl'),
|
|
('LOCK_DIR', self.root/'lock'), ('DEVICE_PLANE_ROOT', self.live),
|
|
('DEVICE_B2_SECRET_ROOT', self.live/'vault')]:
|
|
stack.enter_context(mock.patch.object(R, name, value))
|
|
stack.enter_context(mock.patch.dict(R.COMPONENTS, {'device-b2-foundation-reconciliation': {'payload_root': self.live, 'artifact_only': True, 'services': ()}}))
|
|
for name in ('require_root', 'ensure_layout', 'validate_artifact_location'):
|
|
stack.enter_context(mock.patch.object(R, name))
|
|
for name in ('run_build', 'run_compose', 'prepare_component_runtime'):
|
|
stack.enter_context(mock.patch.object(R, name, side_effect=AssertionError('runtime mutation forbidden')))
|
|
stack.enter_context(mock.patch.object(R.subprocess, 'run', side_effect=AssertionError('external commands forbidden')))
|
|
stack.enter_context(mock.patch.object(R, 'device_b2_002_evidence', return_value={}))
|
|
stack.enter_context(mock.patch.object(R, 'device_b2_schema', return_value=[]))
|
|
events = []
|
|
def accept(*args, **kwargs):
|
|
installed = (self.live / R.DEVICE_B2_RECON_ENTRY).exists()
|
|
events.append('post' if installed else 'pre')
|
|
if fail_after_marker and installed: raise R.DeployError('injected restored runtime drift')
|
|
stack.enter_context(mock.patch.object(R, 'accept_device_b2', side_effect=accept))
|
|
R.append_jsonl(R.FAILED_STATE_FILE, R.device_b2_002_failed_row())
|
|
R.append_jsonl(R.STATE_FILE, {'component': 'device-core-release', 'id': R.DEVICE_B2_BASELINE_ID, 'sha256': R.DEVICE_B2_BASELINE_SHA})
|
|
stack.enter_context(redirect_stdout(io.StringIO())); stack.enter_context(redirect_stderr(io.StringIO()))
|
|
if fail_after_marker:
|
|
with self.assertRaises(R.DeployError): R.apply_artifact(self.archive)
|
|
self.assertFalse((self.live/R.DEVICE_B2_RECON_ENTRY).exists())
|
|
self.assertEqual(R.load_state(R.FAILED_STATE_FILE)[-1]['rollback_status'], 'ok:device-b2-reconciliation-marker-only')
|
|
self.assertEqual(len(R.load_state(R.STATE_FILE)), 1)
|
|
else:
|
|
R.apply_artifact(self.archive)
|
|
receipt = R.load_state(R.STATE_FILE)[-1]
|
|
self.assertEqual(receipt['component'], 'device-b2-foundation-reconciliation')
|
|
self.assertTrue(R.device_b2_002_reconciled(R.device_b2_002_failed_row()))
|
|
R.device_b2_failed_barrier()
|
|
self.assertEqual(len(R.load_state(R.FAILED_STATE_FILE)), 1) # Original failure retained.
|
|
(R.APPLIED_DIR/receipt['artifact']).write_bytes(b'changed archive')
|
|
with self.assertRaises(R.DeployError): R.device_b2_002_reconciled(R.device_b2_002_failed_row())
|
|
self.assertEqual(events, ['pre', 'post'])
|
|
|
|
def test_metadata_apply_uses_real_journal_archive_and_receipt_without_runtime_commands(self):
|
|
self.execute_metadata_apply()
|
|
|
|
def test_metadata_apply_failure_removes_only_new_marker_and_retains_incident(self):
|
|
self.execute_metadata_apply(fail_after_marker=True)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
unittest.main()
|