153 lines
8.5 KiB
Python
153 lines
8.5 KiB
Python
import hashlib
|
|
import os
|
|
import copy
|
|
import json
|
|
from pathlib import Path
|
|
import tempfile
|
|
import unittest
|
|
import fcntl
|
|
from unittest.mock import patch
|
|
from types import SimpleNamespace
|
|
|
|
import activate
|
|
from release import Refused,canonical
|
|
|
|
|
|
class ActivationFailureTests(unittest.TestCase):
|
|
def test_install_permissions_survive_restrictive_launcher_umask(self):
|
|
payload=self.root/'permission-payload'
|
|
(payload/'app/nested').mkdir(parents=True)
|
|
(payload/'app/nested/asset').write_bytes(b'qualified bytes')
|
|
destination=self.root/'releases/permission-release'
|
|
previous=os.umask(0o077)
|
|
try:
|
|
with patch.object(activate.os,'chown'):
|
|
activate.install(payload,destination,'root')
|
|
finally:
|
|
os.umask(previous)
|
|
for directory in [destination,*[p for p in destination.rglob('*') if p.is_dir()]]:
|
|
self.assertEqual(directory.stat().st_mode & 0o777,0o750)
|
|
self.assertEqual((destination/'app/nested/asset').stat().st_mode & 0o777,0o440)
|
|
self.assertEqual((destination/'app/nested/asset').read_bytes(),b'qualified bytes')
|
|
|
|
def setUp(self):
|
|
self.temp=tempfile.TemporaryDirectory();self.root=Path(self.temp.name)
|
|
for name in ('releases','inbox/new-release','evidence','backup','old/app'):(self.root/name).mkdir(parents=True)
|
|
(self.root/'inbox/new-release/package.tar').write_bytes(b'fixture')
|
|
(self.root/'deployment.lock').write_bytes(b'')
|
|
(self.root/'current').symlink_to(self.root/'releases/old-release/app')
|
|
(self.root/'releases/old-release/app').mkdir(parents=True)
|
|
(self.root/'active-deployment.json').write_text('{"deployment":"previous-success","release":"old-release","package_sha256":"'+('b'*64)+'"}')
|
|
self.cfg={'root':str(self.root),'inbox':str(self.root/'inbox'),'evidence':str(self.root/'evidence'),
|
|
'backup':str(self.root/'backup'),'runtime_account':'root','migration_account':'root',
|
|
'public_key':'not-used','minimum_free_bytes':1,'service':'plotdirector-qualification.service',
|
|
'health_base':'http://127.0.0.1:5999','database':'PlotLine','environment':'Production'}
|
|
self.receipts=[];self.calls=[];self.state='active';self.failure=None;self.status='200';self.complete=False;self.activations=[]
|
|
outer=self
|
|
class FakeWorker:
|
|
def __init__(self,cfg):outer.calls.append('worker-open')
|
|
def call(self,op,**values):
|
|
outer.calls.append(op)
|
|
if outer.failure==op:raise Refused('Injected '+op+' failure')
|
|
if op=='backup':Path(values['path']).write_bytes(b'verified-fixture')
|
|
if op=='begin':return {'complete':outer.complete,'database_bytes':1024}
|
|
if op=='activated':outer.activations.append(values)
|
|
if op=='migrate':return {'executed':0,'baselined':0,'committed':[]}
|
|
return {}
|
|
def close(self):outer.calls.append('worker-close')
|
|
self.FakeWorker=FakeWorker
|
|
|
|
def tearDown(self):self.temp.cleanup()
|
|
|
|
def bundle(self,source,work,key,meter=None):
|
|
payload=Path(work)/'payload';(payload/'app').mkdir(parents=True)
|
|
(payload/'app/PlotLine.dll').write_bytes(b'qualified-fixture')
|
|
(payload/'manifest.json').write_bytes(b'{}')
|
|
return {'application_sha256':'c'*64,'release_id':'new-release','version':'1.0.0','source_commit':'a'*40,'files':{'app/PlotLine.dll':hashlib.sha256(b'qualified-fixture').hexdigest()}}, {'package_sha256':'a'*64,'manifest_sha256':'d'*64},payload
|
|
|
|
def command(self,args,**kwargs):
|
|
if args[0].endswith('systemctl'):
|
|
action=args[1];self.calls.append('service-'+action)
|
|
if action=='stop':self.state='inactive'
|
|
if action=='start':self.state='active'
|
|
return self.state
|
|
if args[0].endswith('curl'):
|
|
self.calls.append('http')
|
|
return self.status if '--output' in args else json.dumps({'healthy':True,'version':'1.0.0','sourceCommit':'a'*40,'database':'PlotLine','environment':'Production'})
|
|
raise AssertionError('Unexpected executable')
|
|
|
|
def run_activation(self,validate=False,free=10**12,rollback=False):
|
|
# Root-only OS operations are mocked; archive validation and actual SQL
|
|
# transactions/concurrency are independently exercised by their test suites.
|
|
with patch.object(activate,'configuration',return_value=self.cfg),patch.object(activate,'protected'),\
|
|
patch.object(activate,'verify_bundle',side_effect=self.bundle),patch.object(activate,'Worker',self.FakeWorker),\
|
|
patch.object(activate,'command',side_effect=self.command),patch.object(activate.os,'chown'),\
|
|
patch.object(activate,'persist_receipt',side_effect=lambda cfg,meter:self.receipts.append(copy.deepcopy(meter.data))),\
|
|
patch.object(activate.time,'sleep'),patch.object(activate.shutil,'disk_usage',return_value=SimpleNamespace(free=free)):
|
|
activate.activate('new-release',validate,rollback)
|
|
|
|
def test_validation_does_not_backup_migrate_or_stop_service(self):
|
|
self.run_activation(validate=True)
|
|
self.assertNotIn('backup',self.calls);self.assertNotIn('migrate',self.calls);self.assertNotIn('service-stop',self.calls)
|
|
|
|
def test_backup_verification_failure_prevents_shutdown(self):
|
|
self.failure='backup'
|
|
with self.assertRaises(Refused):self.run_activation()
|
|
self.assertNotIn('service-stop',self.calls);self.assertNotIn('migrate',self.calls)
|
|
|
|
def test_migration_failure_keeps_old_target_and_service_stopped(self):
|
|
self.failure='migrate'
|
|
with self.assertRaises(Refused):self.run_activation()
|
|
self.assertEqual((self.root/'current').resolve(),self.root/'releases/old-release/app')
|
|
self.assertEqual(self.state,'inactive');self.assertNotIn('activated',self.calls)
|
|
|
|
def test_failed_application_health_never_records_success(self):
|
|
self.status='500'
|
|
with self.assertRaises(Refused):self.run_activation()
|
|
self.assertEqual(self.state,'inactive');self.assertNotIn('activated',self.calls)
|
|
self.assertEqual(json.loads((self.root/'active-deployment.json').read_text())['deployment'],'previous-success')
|
|
|
|
def test_success_is_recorded_after_http_and_database_health(self):
|
|
self.run_activation()
|
|
self.assertLess(self.calls.index('http'),self.calls.index('health'))
|
|
self.assertLess(self.calls.index('health'),self.calls.index('activated'))
|
|
self.assertEqual((self.root/'current').resolve(),self.root/'releases/new-release/app')
|
|
self.assertEqual(self.state,'active')
|
|
|
|
def test_insufficient_space_prevents_any_database_or_service_operations(self):
|
|
with self.assertRaises(Refused):self.run_activation(free=0)
|
|
self.assertEqual(self.calls,[])
|
|
|
|
def test_database_backup_budget_is_checked_before_backup_or_shutdown(self):
|
|
with self.assertRaises(Refused):self.run_activation(free=1024)
|
|
self.assertIn('begin',self.calls);self.assertNotIn('backup',self.calls);self.assertNotIn('service-stop',self.calls)
|
|
|
|
def test_install_permission_failure_leaves_service_stopped(self):
|
|
with patch.object(activate,'install',side_effect=PermissionError('injected')):
|
|
with self.assertRaises(PermissionError):self.run_activation()
|
|
self.assertEqual(self.state,'inactive');self.assertNotIn('activated',self.calls)
|
|
|
|
def test_failed_release_history_write_stops_application(self):
|
|
self.failure='activated'
|
|
with self.assertRaises(Refused):self.run_activation()
|
|
self.assertEqual(self.state,'inactive')
|
|
self.assertEqual(json.loads((self.root/'active-deployment.json').read_text())['deployment'],'previous-success')
|
|
|
|
def test_competing_filesystem_activation_is_rejected(self):
|
|
with (self.root/'deployment.lock').open('r+') as held:
|
|
fcntl.flock(held,fcntl.LOCK_EX|fcntl.LOCK_NB)
|
|
with self.assertRaises(Refused):self.run_activation()
|
|
self.assertEqual(self.calls,[])
|
|
|
|
def test_rollback_refuses_outstanding_sql(self):
|
|
with self.assertRaises(Refused):self.run_activation(rollback=True)
|
|
self.assertNotIn('backup',self.calls);self.assertNotIn('migrate',self.calls)
|
|
|
|
def test_rollback_records_new_success_only_after_health(self):
|
|
self.complete=True;self.run_activation(rollback=True)
|
|
self.assertEqual(self.activations[0]['kind'],'Rollback')
|
|
self.assertEqual(self.activations[0]['previous_deployment'],'previous-success')
|
|
|
|
|
|
if __name__=='__main__':unittest.main()
|