Add canonical outbound Device Core deployment controller
This commit is contained in:
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,126 @@
|
||||
"""Canonical bootstrap scope, unit ownership, live-dispatch ordering and receipts."""
|
||||
import copy
|
||||
from contextlib import ExitStack,redirect_stdout,redirect_stderr
|
||||
import hashlib
|
||||
import importlib.machinery
|
||||
import importlib.util
|
||||
import io
|
||||
import json
|
||||
from pathlib import Path
|
||||
import stat
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
loader=importlib.machinery.SourceFileLoader('autodeploy_runner',str(Path(__file__).with_name('nodedc-deploy')))
|
||||
spec=importlib.util.spec_from_loader(loader.name,loader);R=importlib.util.module_from_spec(spec);loader.exec_module(R)
|
||||
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'device-core-deploy'))
|
||||
from build_autodeploy import bundle
|
||||
from embed_library import section,START,END
|
||||
|
||||
class AutodeployTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp=tempfile.TemporaryDirectory();self.addCleanup(self.tmp.cleanup);self.root=Path(self.tmp.name)
|
||||
self.identity,self.data=bundle();self.artifact=self.root/'bootstrap.tgz';self.artifact.write_bytes(self.data)
|
||||
self.work=self.root/'work';self.work.mkdir()
|
||||
|
||||
def test_deterministic_archive_and_canonical_scope(self):
|
||||
self.assertEqual(bundle()[1],self.data)
|
||||
manifest,entries,payload=R.load_artifact(self.artifact,self.work)
|
||||
self.assertEqual(manifest['id'],self.identity);self.assertEqual(entries,[R.DEVICE_AUTODEPLOY_ENTRY])
|
||||
self.assertEqual(R.component_services('device-core-autodeploy',entries),())
|
||||
self.assertEqual(R.component_builds('device-core-autodeploy',entries),())
|
||||
self.assertTrue(R.component_artifact_only('device-core-autodeploy'))
|
||||
for path in ['deployment/other.json','runtime/token','docker-compose.yml','hook.py']:
|
||||
with self.assertRaises(R.DeployError):R.allowed_payload_path('device-core-autodeploy',path)
|
||||
|
||||
def test_descriptor_cannot_change_authority_or_baseline(self):
|
||||
m,e,p=R.load_artifact(self.artifact,self.work)
|
||||
for key,value in [('firstRunNumber',1),('installer','/tmp/runner'),('services',['device-postgres']),('publishedPorts',[9000]),('baselineSourceCommit','a'*40)]:
|
||||
d=copy.deepcopy(R.DEVICE_AUTODEPLOY_DESCRIPTOR);d[key]=value
|
||||
(p/e[0]).write_text(json.dumps(d,sort_keys=True,indent=2)+'\n')
|
||||
with self.subTest(key=key),self.assertRaises(R.DeployError):R.validate_device_autodeploy_payload(p,e,m['id'])
|
||||
|
||||
def test_generated_library_is_exact_and_operates_without_source_imports(self):
|
||||
text=Path(R.__file__).read_text();actual=START+text.split(START,1)[1].split(END,1)[0]+END
|
||||
self.assertEqual(actual,section())
|
||||
Q,S,C,errors=R.device_autodeploy_library();q=Q(self.root/'queue',first_run_number=8)
|
||||
self.assertIsNone(q.next_ready());q.close()
|
||||
self.assertEqual(S('a'*40)._token,'a'*40)
|
||||
|
||||
def test_units_have_only_internal_worker_no_listeners_or_external_hooks(self):
|
||||
units=R.device_autodeploy_units();self.assertEqual(set(units),{R.DEVICE_AUTODEPLOY_SERVICE,R.DEVICE_AUTODEPLOY_TIMER})
|
||||
self.assertIn('ExecStart=/usr/bin/python3 /usr/local/sbin/nodedc-deploy --device-core-autodeploy-tick',units[R.DEVICE_AUTODEPLOY_SERVICE])
|
||||
self.assertIn('OnUnitInactiveSec=30s',units[R.DEVICE_AUTODEPLOY_TIMER])
|
||||
self.assertNotIn('Listen',str(units));self.assertNotIn('/Volumes/',str(units));self.assertNotIn('/inbox/',str(units))
|
||||
|
||||
def test_bootstrap_worker_cannot_deploy_before_canonical_receipt(self):
|
||||
with mock.patch.object(R,'require_root'),mock.patch.object(R,'ensure_layout'),mock.patch.object(R,'device_autodeploy_activated',return_value=False),mock.patch.object(R,'device_autodeploy_read_token') as token:
|
||||
self.assertEqual(R.device_autodeploy_tick(),0);token.assert_not_called()
|
||||
|
||||
def test_unit_install_and_rollback_preserve_applications_and_secrets(self):
|
||||
unitdir=self.root/'units';unitdir.mkdir();live=self.root/'live';live.mkdir();secret=self.root/'secret';secret.write_text('retain')
|
||||
before={'inventory':{'fixture':1}}
|
||||
with mock.patch.object(R,'DEVICE_AUTODEPLOY_UNIT_DIR',unitdir),mock.patch.object(R,'device_autodeploy_import_token'),mock.patch.object(R,'device_autodeploy_ctl') as ctl,mock.patch.object(R,'accept_device_autodeploy'),mock.patch.object(R,'device_autodeploy_root_path'),mock.patch.object(R,'restore_platform_overlay'),mock.patch.object(R,'gitea_ci_inventory',return_value=before['inventory']):
|
||||
R.apply_device_autodeploy(before)
|
||||
for name,data in R.device_autodeploy_units().items():self.assertEqual((unitdir/name).read_text(),data)
|
||||
R.rollback_device_autodeploy(live,self.root,[R.DEVICE_AUTODEPLOY_ENTRY],'stamp',before)
|
||||
self.assertFalse(list(unitdir.iterdir()));self.assertEqual(secret.read_text(),'retain')
|
||||
self.assertIn(mock.call('disable',R.DEVICE_AUTODEPLOY_TIMER,check=False),ctl.call_args_list)
|
||||
|
||||
def test_wrong_unit_bytes_and_inventory_prevent_false_acceptance(self):
|
||||
d=self.root/'units';d.mkdir()
|
||||
for name,value in R.device_autodeploy_units().items():(d/name).write_text(value)
|
||||
(d/R.DEVICE_AUTODEPLOY_SERVICE).write_text('changed')
|
||||
with mock.patch.object(R,'DEVICE_AUTODEPLOY_UNIT_DIR',d),mock.patch.object(R,'device_autodeploy_root_path'),self.assertRaises(R.DeployError):R.accept_device_autodeploy({'inventory':{}})
|
||||
|
||||
def execute(self,fail=False):
|
||||
live=self.root/'live'
|
||||
for name in ['inbox','applied','failed','backups','state','tmp']:(self.root/name).mkdir()
|
||||
a=self.root/'inbox/bootstrap.tgz';a.write_bytes(self.data)
|
||||
events=[];before={'inventory':{},'baseline':R.DEVICE_AUTODEPLOY_BASELINE}
|
||||
def acceptance(*args):
|
||||
events.append('accept')
|
||||
if fail:raise R.DeployError('injected acceptance failure')
|
||||
def rollback(root,backup,entries,stamp,proof):
|
||||
events.append('rollback');R.restore_platform_overlay(root,backup,entries,stamp)
|
||||
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')]:stack.enter_context(mock.patch.object(R,name,value))
|
||||
stack.enter_context(mock.patch.dict(R.COMPONENTS,{'device-core-autodeploy':{'payload_root':live,'bootstrap_root':True,'artifact_only':True,'services':()}}))
|
||||
for name in ['require_root','ensure_layout','validate_artifact_location']:stack.enter_context(mock.patch.object(R,name))
|
||||
stack.enter_context(mock.patch.object(R,'preflight_device_autodeploy',return_value=before))
|
||||
stack.enter_context(mock.patch.object(R,'apply_device_autodeploy',side_effect=lambda b:events.append('install')))
|
||||
stack.enter_context(mock.patch.object(R,'accept_device_autodeploy',side_effect=acceptance))
|
||||
stack.enter_context(mock.patch.object(R,'rollback_device_autodeploy',side_effect=rollback))
|
||||
stack.enter_context(redirect_stdout(io.StringIO()));stack.enter_context(redirect_stderr(io.StringIO()))
|
||||
if fail:
|
||||
with self.assertRaises(R.DeployError):R.apply_artifact(a)
|
||||
else:R.apply_artifact(a)
|
||||
applied=R.load_state(R.STATE_FILE);failed=R.load_state(R.FAILED_STATE_FILE)
|
||||
return events,applied,failed
|
||||
|
||||
def test_real_canonical_apply_success_after_acceptance(self):
|
||||
events,applied,failed=self.execute()
|
||||
self.assertEqual(events,['install','accept']);self.assertEqual(len(applied),1);self.assertFalse(failed)
|
||||
self.assertEqual(applied[0]['sha256'],hashlib.sha256(self.data).hexdigest())
|
||||
|
||||
def test_real_canonical_failure_dispatches_only_own_rollback(self):
|
||||
events,applied,failed=self.execute(True)
|
||||
self.assertEqual(events,['install','accept','rollback']);self.assertFalse(applied)
|
||||
self.assertEqual(failed[0]['rollback_status'],'ok:device-core-autodeploy-bootstrap')
|
||||
|
||||
def test_receipt_requires_archive_backup_and_exact_digest(self):
|
||||
applied=self.root/'applied';failed=self.root/'failed';backups=self.root/'backups'
|
||||
for d in (applied,failed,backups):d.mkdir()
|
||||
name='nodedc-device-core-release-v1-r8-'+'a'*40+'.tgz';identity=name[7:-4]
|
||||
archive=applied/name;archive.write_bytes(b'archive');(backups/'backup').mkdir()
|
||||
row={'artifact':name,'digest':hashlib.sha256(b'archive').hexdigest()}
|
||||
record={'id':identity,'artifact':name,'component':'device-core-release','sha256':row['digest'],'backup_id':'backup','status':'ok'}
|
||||
with mock.patch.object(R,'APPLIED_DIR',applied),mock.patch.object(R,'FAILED_DIR',failed),mock.patch.object(R,'BACKUPS_DIR',backups):
|
||||
with mock.patch.object(R,'load_state',side_effect=[[record],[]]):self.assertEqual(R.DeviceAutodeployInstaller().receipt(row)[0],'deployed')
|
||||
archive.write_bytes(b'changed')
|
||||
with mock.patch.object(R,'load_state',side_effect=[[record],[]]):self.assertEqual(R.DeviceAutodeployInstaller().receipt(row)[0],'ambiguous')
|
||||
with mock.patch.object(R,'load_state',side_effect=[[],[]]):self.assertEqual(R.DeviceAutodeployInstaller().receipt(row)[0],'ambiguous')
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
@@ -152,14 +152,14 @@ class ReleaseTests(unittest.TestCase):
|
||||
|
||||
def test_rollback_uses_previous_images_without_build_or_registry(self):
|
||||
before={'runtime':runtime()}; calls=[]
|
||||
with mock.patch.object(R,'restore_platform_overlay',side_effect=lambda *a:calls.append('source')),mock.patch.object(R.subprocess,'run',side_effect=lambda *a,**k:calls.append(a[0])),mock.patch.object(R,'run_compose',side_effect=lambda *a:calls.append('compose')),mock.patch.object(R,'run_healthchecks',side_effect=lambda *a:calls.append('health')),mock.patch.object(R,'accept_device_release',side_effect=lambda *a,**k:calls.append('accept')),mock.patch.object(R,'run_build') as build:
|
||||
with mock.patch.object(R,'restore_platform_overlay',side_effect=lambda *a:calls.append('source')),mock.patch.object(R.subprocess,'run',side_effect=lambda *a,**k:calls.append(a[0])),mock.patch.object(R,'run_device_release_compose',side_effect=lambda *a:calls.append('compose')),mock.patch.object(R,'run_healthchecks',side_effect=lambda *a:calls.append('health')),mock.patch.object(R,'accept_device_release',side_effect=lambda *a,**k:calls.append('accept')),mock.patch.object(R,'run_build') as build:
|
||||
R.rollback_device_release(self.root,self.root,R.DEVICE_RELEASE_ENTRIES,'stamp',before,True)
|
||||
self.assertEqual(calls[0],'source');self.assertEqual(calls[-3:],['compose','health','accept']);build.assert_not_called()
|
||||
self.assertEqual([x[1:3] for x in calls if isinstance(x,list)],[['image','tag'],['image','tag']])
|
||||
self.assertEqual(calls[1][-2],before['runtime']['device-control-core']['imageId'])
|
||||
|
||||
def test_build_failure_restores_tags_but_does_not_restart_services(self):
|
||||
with mock.patch.object(R,'restore_platform_overlay'),mock.patch.object(R.subprocess,'run') as command,mock.patch.object(R,'run_compose') as compose,mock.patch.object(R,'run_healthchecks') as health,mock.patch.object(R,'accept_device_release'):
|
||||
with mock.patch.object(R,'restore_platform_overlay'),mock.patch.object(R.subprocess,'run') as command,mock.patch.object(R,'run_device_release_compose') as compose,mock.patch.object(R,'run_healthchecks') as health,mock.patch.object(R,'accept_device_release'):
|
||||
R.rollback_device_release(self.root,self.root,R.DEVICE_RELEASE_ENTRIES,'stamp',{'runtime':runtime()},False)
|
||||
self.assertEqual(command.call_count,2);compose.assert_not_called();health.assert_not_called()
|
||||
|
||||
@@ -173,7 +173,7 @@ class ReleaseTests(unittest.TestCase):
|
||||
|
||||
def test_compose_never_rebuilds_pulls_or_starts_dependencies(self):
|
||||
with mock.patch.object(R,'compose_base_cmd',return_value=['docker','compose']),mock.patch.object(R,'component_compose_root',return_value=self.root),mock.patch.object(R.subprocess,'run') as command:
|
||||
R.run_compose('device-core-release',R.DEVICE_RELEASE_SERVICES,R.DEVICE_RELEASE_ENTRIES)
|
||||
R.run_device_release_compose(R.DEVICE_RELEASE_SERVICES,R.DEVICE_RELEASE_ENTRIES)
|
||||
cmd=command.call_args_list[0].args[0]
|
||||
for arg in ['--no-deps','--no-build','--force-recreate']:self.assertIn(arg,cmd)
|
||||
self.assertEqual(cmd[cmd.index('--pull')+1],'never');self.assertEqual(cmd[-2:],list(R.DEVICE_RELEASE_SERVICES))
|
||||
@@ -204,7 +204,7 @@ class ReleaseTests(unittest.TestCase):
|
||||
stack.enter_context(mock.patch.object(R,name))
|
||||
stack.enter_context(mock.patch.object(R,'component_compose_files',return_value=(compose,)))
|
||||
stack.enter_context(mock.patch.object(R,'preflight_device_release',return_value=before))
|
||||
for name,label in [('run_build','build'),('run_compose','compose'),('run_healthchecks','health')]:
|
||||
for name,label in [('run_build','build'),('run_device_release_compose','compose'),('run_healthchecks','health')]:
|
||||
stack.enter_context(mock.patch.object(R,name,side_effect=operation(label)))
|
||||
def acceptance(*args,**kwargs):
|
||||
if kwargs.get('rollback'):
|
||||
|
||||
Reference in New Issue
Block a user