Add CMS deployment builders, policy sources and regression suite

This commit is contained in:
Codex
2026-11-04 21:51:05 +03:00
parent 28d8466ef9
commit aeaaae50c3
22 changed files with 2316 additions and 0 deletions
+19
View File
@@ -0,0 +1,19 @@
# CMS Git deployment domain
Source: SILVER/DC_CMS, repository 33, master. Push → qualification → Gitea artifact → outbound durable queue → canonical installer.
The Device Core runner is scoped only to its own repository. CMS therefore registers its own build-runner in project nodedc-cms-ci, with the accepted Synology v4 resource and isolation profile. Existing Device Core registration, source and units are untouched. Both pinned images must already exist; bootstrap pulls neither. New runner registration is repository-scoped, staged separately from artifacts, imported to root0600 and removed from handoff storage. No credentials appear in Git, receipts or workflow artifacts.
`dc-cms-autodeploy` bootstraps exactly three source files under /volume1/docker/nodedc-cms-autodeploy, one build-runner service and two systemd units. Root-private queue state is /var/lib/nodedc-cms-autodeploy. Its read-only Gitea client uses the existing private Device Core read identity without copying it; preflight checks actual access to repository 33. The installed canonical receipt gates polling. Bootstrap preserves all preexisting containers and CMS data; rollback removes only the new runner/units/source partition, retaining private enrollment and queue for diagnosis.
`dc-cms-release` allows only flat admin/server application files and two exact dependency files. The initial predecessor is original CMS commit 4c6f133 with SMB-verified hashes in baseline.json. Foundation pins adm-zip 0.6.1 in foundation.json to fix known ZIP vulnerabilities. No later dependency, Dockerfile, Compose or Caddy change is admitted by this domain. Build uses the existing Dockerfile in an isolated temporary context with an empty projects directory. The canonical installer restarts only cms-app with no dependencies, no image pull and no rebuild during rollback. Acceptance verifies authentication, app hashes inside the running container, image generation, fixed ZIP dependency version, preserved env/mounts/networks/ports, other Compose services and site/project data.
## Build and checks
`python3 infra/cms-deploy/embed_runtime.py` refreshes only the explicitly marked standalone section. Registry and dispatcher wiring are ordinary reviewed runner source. Runtime never imports the fragment files from SMB.
`python3 -m unittest discover -s infra/cms-deploy -p 'test_*.py'`
`python3 -m unittest discover -s infra/deploy-runner -p 'test_device_core_*.py'`
`python3 infra/cms-deploy/build_autodeploy.py --output-dir <directory>`
Before production: SHA-pinned root runner promotion and verify-install; then fresh canonical plan/apply of the bootstrap artifact. Ordinary CMS pushes afterward need no operator NAS commands. A queued or green Actions run alone is not deployment evidence; require canonical receipt and product acceptance.
+21
View File
@@ -0,0 +1,21 @@
{
"baselineSourceCommit": "4c6f133ff1dba5975e45b3c7ab332c40eaf96ab8",
"branch": "master",
"buildRunner": "synology-cms-build",
"buildRunnerRepositoryId": 33,
"firstRunNumber": 1,
"installer": "/usr/local/sbin/nodedc-deploy",
"intervalAfterCompletionSeconds": 30,
"publishedPorts": [],
"releaseComponent": "dc-cms-release",
"releaseId": "dc-cms-autodeploy-v1-20261104-001",
"repository": "SILVER/DC_CMS",
"repositoryId": 33,
"scheduler": "native-systemd-timer",
"schemaVersion": "nodedc.dc-cms.autodeploy.v1",
"services": [
"cms-app"
],
"transport": "outbound-https",
"workflow": "ci.yml@refs/heads/master"
}
+351
View File
@@ -0,0 +1,351 @@
# DC CMS outbound automatic deployment. All authority stays in this file.
CMS_AUTODEPLOY_ID = 'dc-cms-autodeploy-v1-20261104-001'
CMS_AUTODEPLOY_ENTRY = 'deployment/dc-cms-autodeploy-v1.json'
CMS_AUTODEPLOY_ENTRIES = CMS_CI_V4_ENTRIES
CMS_AUTODEPLOY_ROOT = Path('/volume1/docker/nodedc-cms-autodeploy')
CMS_AUTODEPLOY_PRIVATE = Path('/var/lib/nodedc-cms-autodeploy')
CMS_AUTODEPLOY_PENDING = RUNTIME_DIR / 'dc-cms-autodeploy' / 'enrollment.pending.json'
CMS_AUTODEPLOY_UNIT_DIR = Path('/usr/local/lib/systemd/system')
CMS_AUTODEPLOY_SERVICE = 'nodedc-cms-autodeploy.service'
CMS_AUTODEPLOY_TIMER = 'nodedc-cms-autodeploy.timer'
CMS_AUTODEPLOY_BASELINE = CMS_BASELINE['sourceCommit']
CMS_AUTODEPLOY_DESCRIPTOR = {
'schemaVersion': 'nodedc.dc-cms.autodeploy.v1', 'releaseId': CMS_AUTODEPLOY_ID,
'repository': 'SILVER/DC_CMS', 'repositoryId': 33, 'branch': 'master',
'workflow': 'ci.yml@refs/heads/master', 'firstRunNumber': 1,
'baselineSourceCommit': CMS_AUTODEPLOY_BASELINE,
'transport': 'outbound-https', 'publishedPorts': [], 'scheduler': 'native-systemd-timer',
'intervalAfterCompletionSeconds': 30, 'installer': '/usr/local/sbin/nodedc-deploy',
'releaseComponent': 'dc-cms-release', 'services': ['cms-app'], 'buildRunner': 'synology-cms-build', 'buildRunnerRepositoryId': 33,
}
def cms_autodeploy_units():
return {
CMS_AUTODEPLOY_SERVICE: (
'[Unit]\nDescription=NODE.DC DC CMS canonical deployment controller\n'
'After=network-online.target\nWants=network-online.target\n\n'
'[Service]\nType=oneshot\nUser=root\nGroup=root\nUMask=0077\n'
'Environment=PATH=/usr/local/bin:/usr/bin:/bin\n'
'ExecStart=/usr/bin/python3 /usr/local/sbin/nodedc-deploy --dc-cms-autodeploy-tick\n'
'TimeoutStartSec=0\nTimeoutStopSec=300\nNice=10\n'
'StandardOutput=journal\nStandardError=journal\n'),
CMS_AUTODEPLOY_TIMER: (
'[Unit]\nDescription=Poll qualified DC CMS releases without inbound ports\n\n'
'[Timer]\nOnBootSec=120s\nOnUnitInactiveSec=30s\nAccuracySec=1s\n'
'Unit=nodedc-cms-autodeploy.service\n\n[Install]\nWantedBy=timers.target\n'),
}
def validate_cms_autodeploy_payload(payload, entries, identity):
if tuple(entries or ()) != CMS_AUTODEPLOY_ENTRIES or identity != CMS_AUTODEPLOY_ID:
die('DC CMS autodeploy requires its exact bootstrap descriptor')
try:
# Canonical byte representation prevents duplicate-key ambiguity.
data = (payload / CMS_AUTODEPLOY_ENTRY).read_bytes()
expected = (json.dumps(CMS_AUTODEPLOY_DESCRIPTOR, indent=2, sort_keys=True) + '\n').encode()
if data != expected:
die('DC CMS autodeploy descriptor differs from the registered contract')
except (OSError, ValueError):
die('DC CMS autodeploy descriptor is unreadable')
for rel,digest in CMS_CI_SOURCE_SHA256.items():
if sha256_file(payload/rel)!=digest:die('CMS CI immutable source mismatch')
return CMS_AUTODEPLOY_DESCRIPTOR
def cms_autodeploy_root_path(path, directory=False):
"""No runtime executable/state authority through a writable ancestor."""
for candidate in [path] + list(path.parents):
info = candidate.lstat()
if (stat.S_ISLNK(info.st_mode) or info.st_uid != 0 or info.st_mode & 0o022
or (candidate != path and not stat.S_ISDIR(info.st_mode))):
die('DC CMS autodeploy root path metadata rejected: ' + str(candidate))
info = path.lstat()
if not (stat.S_ISDIR(info.st_mode) if directory else stat.S_ISREG(info.st_mode)):
die('DC CMS autodeploy root path type rejected: ' + str(path))
return info
def cms_autodeploy_systemctl():
if Path('/proc/1/comm').read_text().strip() != 'systemd' or not Path('/run/systemd/system').is_dir():
die('DC CMS autodeploy requires the native systemd manager')
cms_autodeploy_root_path(CMS_AUTODEPLOY_UNIT_DIR, directory=True)
python = Path('/usr/bin/python3').resolve(strict=True)
cms_autodeploy_root_path(python)
candidates = []
for name in ('/bin/systemctl', '/usr/bin/systemctl'):
p = Path(name)
if p.exists():
resolved = p.resolve(strict=True)
cms_autodeploy_root_path(resolved)
if not os.access(str(resolved), os.X_OK):
die('DC CMS autodeploy systemctl is not executable')
if resolved not in candidates:
candidates.append(resolved)
if len(candidates) != 1:
die('DC CMS autodeploy native systemctl identity is ambiguous or missing')
return candidates[0]
def cms_autodeploy_ctl(*args, check=True):
return subprocess.run([str(cms_autodeploy_systemctl()), *args], text=True,
capture_output=True, check=check, timeout=35)
def cms_autodeploy_read_token(private=False):
# Reuse the existing read-only identity inside the root runner, never export
# or duplicate its secret. Source policy remains pinned to CMS repository 33.
return device_autodeploy_read_token(private=True)
def cms_autodeploy_enrollment():
return cms_autodeploy_read_token(private=True)[0]
def cms_autodeploy_import_token():
cms_autodeploy_read_token(private=True)
if not CMS_AUTODEPLOY_PRIVATE.exists():
cms_autodeploy_root_path(CMS_AUTODEPLOY_PRIVATE.parent,directory=True)
CMS_AUTODEPLOY_PRIVATE.mkdir(mode=0o700)
cms_autodeploy_root_path(CMS_AUTODEPLOY_PRIVATE,directory=True)
if stat.S_IMODE(CMS_AUTODEPLOY_PRIVATE.stat().st_mode)!=0o700:
die('CMS private queue directory must be 0700')
def cms_autodeploy_installed_source():
return cms_installed_release()['sourceCommit']
def preflight_cms_autodeploy(payload, entries, identity):
require_root()
validate_cms_autodeploy_payload(payload,entries,identity)
ctl=cms_autodeploy_systemctl()
preflight_cms_ci()
if cms_autodeploy_installed_source()!=CMS_AUTODEPLOY_BASELINE:
die('CMS bootstrap requires the registered initial predecessor')
if any(r.get('component')=='dc-cms-autodeploy' for r in load_state(STATE_FILE)):
die('CMS bootstrap is already applied')
for name in cms_autodeploy_units():
path=CMS_AUTODEPLOY_UNIT_DIR/name
if path.exists() or path.is_symlink():die('CMS controller unit already exists')
if cms_autodeploy_ctl('show',name,'--property=LoadState',check=False).stdout.strip()!='LoadState=not-found':
die('CMS controller unit name is already managed')
if not device_autodeploy_activated():die('CMS requires the established Gitea read identity')
_,Source,_,_=cms_autodeploy_library()
source=Source(cms_autodeploy_enrollment())
source.discover() # Fail before mutation unless the identity can read repo 33 Actions.
if not source.ancestor(CMS_AUTODEPLOY_BASELINE,source.main_commit()):die('CMS master diverged from installed baseline')
cms_healthchecks()
return {'systemctl':str(ctl),'inventory':cms_ci_inventory(),'runtime':cms_runtime_snapshot(),'data':cms_preserved_data(),'baseline':CMS_AUTODEPLOY_BASELINE}
def apply_cms_autodeploy(before):
apply_cms_ci()
cms_autodeploy_import_token()
for name, content in cms_autodeploy_units().items():
path = CMS_AUTODEPLOY_UNIT_DIR / name
fd, temporary = tempfile.mkstemp(prefix='.' + name + '.', dir=str(CMS_AUTODEPLOY_UNIT_DIR))
try:
with os.fdopen(fd, 'w') as stream:
os.fchmod(stream.fileno(), 0o644)
stream.write(content);stream.flush();os.fsync(stream.fileno())
os.link(temporary, str(path))
finally:
os.unlink(temporary)
fsync_directory(CMS_AUTODEPLOY_UNIT_DIR)
cms_autodeploy_ctl('daemon-reload')
cms_autodeploy_ctl('enable', CMS_AUTODEPLOY_TIMER)
cms_autodeploy_ctl('start', CMS_AUTODEPLOY_TIMER)
# The timer may fire immediately if boot was more than two minutes ago.
# Its worker refuses deployment until the canonical bootstrap receipt exists.
accept_cms_autodeploy(before)
def accept_cms_autodeploy(before):
accept_cms_ci(CMS_CI_V4_ENTRIES)
for name, content in cms_autodeploy_units().items():
path = CMS_AUTODEPLOY_UNIT_DIR / name
cms_autodeploy_root_path(path)
if path.read_text() != content:
die('DC CMS autodeploy installed unit differs')
result = cms_autodeploy_ctl('show', name, '--property=FragmentPath')
if result.stdout.strip() != 'FragmentPath=' + str(path):
die('DC CMS autodeploy effective unit origin mismatch')
if cms_autodeploy_ctl('show', name, '--property=DropInPaths').stdout.strip() != 'DropInPaths=':
die('DC CMS autodeploy unit has an undeclared drop-in')
if cms_autodeploy_ctl('is-enabled', CMS_AUTODEPLOY_TIMER).stdout.strip() != 'enabled':
die('DC CMS autodeploy timer is not enabled')
if cms_autodeploy_ctl('is-active', CMS_AUTODEPLOY_TIMER).stdout.strip() != 'active':
die('DC CMS autodeploy timer is not active')
cms_autodeploy_read_token(private=True)
if not cms_ci_inventory_preserved(before['inventory']) or cms_runtime_snapshot() != before['runtime'] or cms_preserved_data() != before['data'] or cms_autodeploy_installed_source() != before['baseline']:
die('DC CMS autodeploy bootstrap changed existing applications')
print('cms_autodeploy_accept=outbound-timer;ports=none;baseline=4c6f133;first-run=1;deploy-authority=canonical-runner')
def rollback_cms_autodeploy(root, backup_dir, entries, current_stamp, before):
# This domain owns only two previously absent units and the descriptor.
cms_autodeploy_ctl('stop', CMS_AUTODEPLOY_TIMER, check=False)
cms_autodeploy_ctl('stop', CMS_AUTODEPLOY_SERVICE, check=False)
cms_autodeploy_ctl('disable', CMS_AUTODEPLOY_TIMER, check=False)
for name, content in cms_autodeploy_units().items():
path = CMS_AUTODEPLOY_UNIT_DIR / name
if path.exists():
cms_autodeploy_root_path(path)
if path.read_text() != content:
die('DC CMS autodeploy rollback unit ownership mismatch')
path.unlink()
cms_autodeploy_ctl('daemon-reload')
capture_cms_ci_diagnostics(backup_dir)
stop_and_remove_compose_services('dc-cms-autodeploy', ('build-runner',))
restore_platform_overlay(root, backup_dir, entries, current_stamp)
if cms_ci_container_ids(own=True):die('CMS CI rollback left a runner')
for name in cms_autodeploy_units():
if (CMS_AUTODEPLOY_UNIT_DIR / name).exists():
die('DC CMS autodeploy rollback retained a unit')
if not cms_ci_inventory_preserved(before['inventory']) or cms_runtime_snapshot() != before['runtime'] or cms_preserved_data() != before['data']:
die('DC CMS autodeploy rollback application preservation failed')
# Credentials/queue are deliberately retained, never erased by rollback.
def cms_autodeploy_activated():
rows = [r for r in load_state(STATE_FILE) if r.get('component') == 'dc-cms-autodeploy']
if not rows:
return False
if len(rows) != 1 or rows[0].get('id') != CMS_AUTODEPLOY_ID or rows[0].get('status') != 'ok':
die('DC CMS autodeploy activation receipt mismatch')
row = rows[0]
with tempfile.TemporaryDirectory(prefix='autodeploy-activation-', dir=TMP_DIR) as tmp:
manifest, entries, payload = load_artifact(device_release_applied_archive(row), Path(tmp))
if manifest['component'] != 'dc-cms-autodeploy':
die('DC CMS autodeploy activation component mismatch')
validate_cms_autodeploy_payload(payload, entries, row['id'])
if (CMS_AUTODEPLOY_ROOT / CMS_AUTODEPLOY_ENTRY).read_bytes() != (payload / CMS_AUTODEPLOY_ENTRY).read_bytes():
die('DC CMS autodeploy activation descriptor drift')
return True
class CmsAutodeployInstaller:
def installed_source(self):
return cms_autodeploy_installed_source()
def stage(self, row, receipt, data):
expected = 'nodedc-dc-cms-release-v1-r' + str(row['id']) + '-' + row['sha'] + '.tgz'
if receipt['artifact'] != expected or hashlib.sha256(data).hexdigest() != receipt['sha256']:
die('DC CMS autodeploy staging identity mismatch')
identity = expected[len('nodedc-'):-4]
if any(r.get('id') == identity for r in load_state(STATE_FILE) + load_state(FAILED_STATE_FILE)):
die('DC CMS autodeploy artifact already has a terminal journal record')
with tempfile.TemporaryDirectory(prefix='autodeploy-stage-', dir=TMP_DIR) as tmp:
candidate = Path(tmp) / expected;candidate.write_bytes(data)
unpack = Path(tmp) / 'unpack';unpack.mkdir()
manifest, entries, payload = load_artifact(candidate, unpack)
if manifest['component'] != 'dc-cms-release' or manifest['id'] != identity:
die('DC CMS autodeploy canonical component scope mismatch')
d = validate_cms_release_payload(payload, entries, identity)
if (d['runId'],d['runNumber'],d['sourceCommit']) != (row['id'],row['number'],row['sha']):
die('DC CMS autodeploy payload run mismatch')
target = INBOX / expected
if target.exists() or target.is_symlink():
info = target.lstat()
if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1 or sha256_file(target) != receipt['sha256']:
die('DC CMS autodeploy inbox conflict')
else:
# Link a complete, fsynced file into the inbox without overwrite.
candidate.chmod(0o600)
with candidate.open('rb') as stream:os.fsync(stream.fileno())
os.link(str(candidate),str(target));candidate.unlink();fsync_directory(INBOX)
def plan(self, artifact):
plan_artifact(INBOX / artifact)
def apply(self, artifact):
apply_artifact(INBOX / artifact)
def receipt(self, row):
identity = row['artifact'][len('nodedc-'):-4]
applied = [r for r in load_state(STATE_FILE) if r.get('id') == identity]
failed = [r for r in load_state(FAILED_STATE_FILE) if r.get('id') == identity]
if len(applied) + len(failed) != 1:
return 'ambiguous', 'canonical-receipt-missing-or-conflicting'
record = (applied or failed)[0]
if record.get('component') != 'dc-cms-release' or record.get('sha256') != row['digest']:
return 'ambiguous', 'canonical-receipt-identity-mismatch'
archive = (APPLIED_DIR if applied else FAILED_DIR) / str(record.get('artifact',''))
backup = BACKUPS_DIR / str(record.get('backup_id',''))
if (archive.parent not in (APPLIED_DIR,FAILED_DIR) or archive.is_symlink() or not archive.is_file()
or sha256_file(archive) != row['digest'] or backup.parent != BACKUPS_DIR
or backup.is_symlink() or not backup.is_dir()):
return 'ambiguous', 'canonical-archive-or-backup-mismatch'
if applied and record.get('status') == 'ok':
outcome = 'deployed'
elif failed and record.get('rollback_status') == 'ok:dc-cms-release':
outcome = 'rolled-back'
else:
return 'ambiguous', 'canonical-rollback-unconfirmed'
return outcome, 'canonical:' + str(record['backup_id'])
def cms_autodeploy_publish_status(result):
# Public projection contains no credentials, API bodies or raw exceptions.
# It is an observation aid; only canonical journals authorize deployment.
result = dict(result, updatedAt=utc_now())
data = (json.dumps(result, sort_keys=True) + '\n').encode()
atomic_write_root_file(CMS_AUTODEPLOY_PRIVATE / 'status.json', data)
if CMS_AUTODEPLOY_ROOT.is_symlink() or not CMS_AUTODEPLOY_ROOT.is_dir():
die('DC CMS autodeploy status destination is not its descriptor root')
fd, temporary = tempfile.mkstemp(prefix='.status-', dir=str(CMS_AUTODEPLOY_ROOT))
try:
with os.fdopen(fd, 'wb') as stream:
os.fchmod(stream.fileno(), 0o644);stream.write(data);stream.flush();os.fsync(stream.fileno())
os.replace(temporary, str(CMS_AUTODEPLOY_ROOT / 'runtime-status.json'))
fsync_directory(CMS_AUTODEPLOY_ROOT)
finally:
if os.path.exists(temporary):os.unlink(temporary)
print('cms_autodeploy_tick=' + json.dumps(result, sort_keys=True))
def cms_autodeploy_tick():
require_root()
ensure_layout()
if not cms_autodeploy_activated():
return 0
cms_autodeploy_root_path(CMS_AUTODEPLOY_PRIVATE,directory=True)
os.umask(0o077)
lock_path = CMS_AUTODEPLOY_PRIVATE / 'controller.lock'
fd = os.open(str(lock_path), os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o600)
try:
try:
fcntl.flock(fd,fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
return 0
if LOCK_DIR.exists():
cms_autodeploy_publish_status({'status':'waiting','reason':'canonical-deploy-lock'})
return 0 # Another canonical installation owns the runtime.
Queue, Source, Controller, errors = cms_autodeploy_library()
token = cms_autodeploy_read_token(private=True)[0]
queue_path = CMS_AUTODEPLOY_PRIVATE / 'queue.sqlite3'
for path in (queue_path,Path(str(queue_path)+'-wal'),Path(str(queue_path)+'-shm')):
if path.exists() or path.is_symlink():
cms_autodeploy_root_path(path)
queue = Queue(queue_path,first_run_number=1)
try:
result = Controller(queue,Source(token),CmsAutodeployInstaller()).tick()
except Exception as error:
result = {'status':'attention','errorType':type(error).__name__}
# Policy errors contain only fixed codes/IDs; other exception text
# can originate in external tools and is never copied to status.
if isinstance(error,errors):result['reason']=str(error)[:200]
finally:
queue.close()
cms_autodeploy_publish_status(result)
return 0 if result['status'] != 'attention' else 1
finally:
os.close(fd)
+17
View File
@@ -0,0 +1,17 @@
{
"filesSha256": {
"admin/admin.css": "1aa723320a3920c9bba41bb7b16c077eadbd464908f9a539259ac15d00fffc7c",
"admin/admin.js": "149212254c93c31da1df914a6d8049be982c40a8661180c4c2b6291e76244297",
"admin/index.html": "a4d24b78a71a6d3bbd3c9aac8f900ddab1ff1dd10f324e30a37b2363fbcdae26",
"admin/nodedc-logo.svg": "b8a2c9bc1342819883e67c1b8fcde4b60175c0f4bdeafd2d08b3cb87873478e0",
"server/admin-server.mjs": "a1f7db4a03b831cfd94474bdd8e272f35bf5826d15441f9203c38955a8f8a3e2"
},
"foundationSha256": {
"Dockerfile": "ccb783bd76b1588cbe0157bd317f6da06888d79f8a199fd0c5515000948acd42",
"infra/docker-compose.yml": "abb3a9d4e4e2ce15eb2ca52b335289dcd00808d85c78da6d1bc583a8b3517f48",
"infra/reverse-proxy/Caddyfile": "4d30188eb1f11b52a0eaf2d9476e0b0adda93a63e66938e8028cc11de4c2038f",
"package-lock.json": "73e0f87dafe7c54539af30be0f4797ea02b4715ba306c5d69e150edb2d679794",
"package.json": "96cfd6cb47317d9f45ef9fcc7ad7f5ed2cfa0efbf83fe031d66acdd84a217a62"
},
"sourceCommit": "4c6f133ff1dba5975e45b3c7ab332c40eaf96ab8"
}
+33
View File
@@ -0,0 +1,33 @@
#!/usr/bin/env python3
"""Deterministic data-only controller bootstrap; executable policy is in the root runner."""
import argparse
import gzip
import hashlib
import io
import json
from pathlib import Path
import tarfile
ROOT=Path(__file__).resolve().parent
ENTRY='deployment/dc-cms-autodeploy-v1.json'
def bundle():
data=(ROOT/'autodeploy-v1.json').read_bytes()
identity=json.loads(data)['releaseId']
members={'manifest.env':('id='+identity+'\ncomponent=dc-cms-autodeploy\ntype=app-overlay\n').encode(),
'files.txt':('\n'.join((ENTRY,'docker-compose.cms-ci.yml','runner.yaml'))+'\n').encode(),'payload/'+ENTRY:data}
members.update({'payload/'+name:(ROOT/name).read_bytes() for name in ('docker-compose.cms-ci.yml','runner.yaml')})
output=io.BytesIO()
with gzip.GzipFile(fileobj=output,mode='wb',mtime=0,filename='') as compressed:
with tarfile.open(fileobj=compressed,mode='w') as archive:
for name,value in sorted(members.items()):
info=tarfile.TarInfo(name);info.mode=0o644;info.size=len(value)
archive.addfile(info,io.BytesIO(value))
return identity,output.getvalue()
if __name__=='__main__':
parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--output-dir',required=True,type=Path)
args=parser.parse_args();args.output_dir.mkdir(parents=True,exist_ok=True)
identity,data=bundle();path=args.output_dir/('nodedc-'+identity+'.tgz')
with path.open('xb') as stream:stream.write(data)
print(json.dumps(dict(artifact=str(path),sha256=hashlib.sha256(data).hexdigest(),id=identity)))
+4
View File
@@ -0,0 +1,4 @@
{
"docker-compose.cms-ci.yml": "9c6b6bf2a9da2f7d5097b8d110882da1587b4d49018aba5ccf258a0218b351c2",
"runner.yaml": "94d8e4d8345b2b5bc7c8923bff7c31ff59083ec7115d633af10152b93bcd9da6"
}
+309
View File
@@ -0,0 +1,309 @@
# CMS owns one separately registered, repository-scoped build runner.
CMS_CI_ROOT = Path('/volume1/docker/nodedc-cms-autodeploy')
CMS_CI_ENROLLMENT = RUNTIME_DIR / 'dc-cms-ci' / 'enrollment.pending.json'
CMS_CI_IMAGE = GITEA_CI_IMAGE
CMS_CI_JOB_IMAGE = GITEA_CI_JOB_IMAGE
CMS_CI_ENTRIES = CMS_CI_V2_ENTRIES = CMS_CI_V3_ENTRIES = CMS_CI_V4_ENTRIES = ('deployment/dc-cms-autodeploy-v1.json','docker-compose.cms-ci.yml','runner.yaml')
CMS_CI_SOURCE_SHA256 = __CMS_CI_HASHES__
def read_cms_ci_v2_input(runtime=False):
"""Read a bounded operator handoff or the private NAS copy, never SMB modes."""
path = (CMS_CI_ROOT / "secrets" / "registration-token"
if runtime else CMS_CI_ENROLLMENT)
for parent in path.parents:
if parent.is_symlink():
die("CMS CI enrollment path contains a symlink")
try:
operator_uid = pwd.getpwnam("dctouch").pw_uid
except KeyError:
die("CMS CI staging account dctouch is missing")
try:
fd = os.open(str(path), os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
except OSError:
die("CMS CI enrollment input cannot be opened safely")
with os.fdopen(fd, "rb") as stream:
info = os.fstat(stream.fileno())
if (not stat.S_ISREG(info.st_mode) or info.st_nlink != 1
or not 1 <= info.st_size <= 2048
or info.st_uid not in ((0,) if runtime else (0, operator_uid))
or (runtime and stat.S_IMODE(info.st_mode) != 0o600)):
die("CMS CI enrollment metadata rejected: "
f"runtime={runtime};mode={stat.S_IMODE(info.st_mode):04o};"
f"uid={info.st_uid};nlink={info.st_nlink};size={info.st_size}")
raw = stream.read(2049)
after = os.fstat(stream.fileno())
if (info.st_size, info.st_mtime_ns, info.st_ctime_ns) != (
after.st_size, after.st_mtime_ns, after.st_ctime_ns):
die("CMS CI enrollment changed while reading")
try:
if runtime:
token = raw.decode("ascii").strip()
else:
value = json.loads(raw)
if (not isinstance(value, dict) or set(value) != {"repository", "token"}
or value["repository"] != "SILVER/DC_CMS"):
raise ValueError()
token = value["token"]
if not isinstance(token, str) or not re.fullmatch(r"[A-Za-z0-9_-]{20,256}", token):
raise ValueError()
except (ValueError, UnicodeError):
die("CMS CI enrollment format is invalid")
return token, info
def preflight_cms_ci_v2_enrollment():
private = CMS_CI_ROOT / "secrets" / "registration-token"
if CMS_CI_ENROLLMENT.exists() or CMS_CI_ENROLLMENT.is_symlink():
token, info = read_cms_ci_v2_input()
if private.exists() or private.is_symlink():
if read_cms_ci_v2_input(runtime=True)[0] != token:
die("CMS CI existing runtime enrollment differs")
return f"import-staging;mode={stat.S_IMODE(info.st_mode):04o};uid={info.st_uid};nlink={info.st_nlink};size={info.st_size}"
read_cms_ci_v2_input(runtime=True)
return "reuse-root-private-runtime"
def import_cms_ci_v2_enrollment():
"""The v2 apply transition owns private creation; plan never changes rights."""
preflight_cms_ci_v2_enrollment()
pending = CMS_CI_ENROLLMENT.exists()
token, source_info = read_cms_ci_v2_input(runtime=not pending)
directory = CMS_CI_ROOT / "secrets"
directory.mkdir(mode=0o700, parents=True, exist_ok=True)
if directory.is_symlink():
die("CMS CI private directory cannot be a symlink")
os.chown(str(directory), 0, 0)
directory.chmod(0o700)
target = directory / "registration-token"
if not target.exists():
fd, temporary = tempfile.mkstemp(prefix=".enrollment-", dir=str(directory))
try:
with os.fdopen(fd, "w") as stream:
os.fchown(stream.fileno(), 0, 0)
os.fchmod(stream.fileno(), 0o600)
stream.write(token + "\n")
stream.flush()
os.fsync(stream.fileno())
# Atomic publication without replacing an existing identity.
os.link(temporary, str(target))
finally:
os.unlink(temporary)
if read_cms_ci_v2_input(runtime=True)[0] != token:
die("CMS CI private enrollment import verification failed")
for path in (directory, CMS_CI_ROOT):
fd = os.open(str(path), os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
try:
os.fsync(fd)
finally:
os.close(fd)
if pending:
current = CMS_CI_ENROLLMENT.lstat()
if (current.st_dev, current.st_ino, current.st_mtime_ns, current.st_size) != (
source_info.st_dev, source_info.st_ino, source_info.st_mtime_ns, source_info.st_size):
die("CMS CI enrollment staging changed before cleanup")
CMS_CI_ENROLLMENT.unlink()
print("ci_enrollment=root-owned-private-runtime;staging=removed")
return token
def cms_ci_container_ids(own=False):
command = [str(DOCKER), "ps", "-aq", "--no-trunc"]
if own:
command += ["--filter", "label=com.docker.compose.project=nodedc-cms-ci"]
result = subprocess.run(command, capture_output=True, text=True, check=True)
ids = result.stdout.split()
if any(not re.fullmatch(r"[a-f0-9]{64}", value) for value in ids):
die("CMS CI Docker container identity is invalid")
return ids
def cms_ci_inventory():
result = {}
for container_id in cms_ci_container_ids():
info = inspect_container(container_id)
if info.get("Config", {}).get("Labels", {}).get("com.docker.compose.project") == "nodedc-cms-ci":
continue
result[container_id] = {
"image": info.get("Image"),
"startedAt": info.get("State", {}).get("StartedAt"),
"running": info.get("State", {}).get("Running"),
}
return result
def cms_ci_check_affinity(pid, exact=False):
if type(pid) is not int or pid < 0 or (exact and pid == 0):
die("CMS CI CPU affinity process identity is invalid")
try:
available = os.sched_getaffinity(pid)
except (AttributeError, OSError):
die("CMS CI CPU affinity cannot be verified")
valid = available == {7} if exact else 7 in available
if not valid:
die("CMS CI requires logical CPU7 affinity")
def cms_ci_host_capabilities(entries):
result = subprocess.run([str(DOCKER), "info", "--format", "{{json .}}"],
capture_output=True, text=True, check=True, timeout=30)
try:
raw = json.loads(result.stdout)
if not isinstance(raw, dict):
raise ValueError()
except ValueError:
die("CMS CI Docker capability report is invalid")
# Do not print registry/proxy configuration, host identity or Docker credentials.
fields = ("ServerVersion", "KernelVersion", "OSType", "Architecture", "NCPU",
"MemTotal", "MemoryLimit", "SwapLimit", "CpuCfsPeriod", "CpuCfsQuota",
"CPUShares", "CPUSet", "PidsLimit", "CgroupVersion")
report = {key: raw.get(key) for key in fields}
print("ci_host=" + json.dumps(report, sort_keys=True, separators=(",", ":")))
required = ["MemoryLimit"]
if tuple(entries) == CMS_CI_V4_ENTRIES:
required += ["CPUShares", "CPUSet", "SwapLimit"]
elif tuple(entries) == CMS_CI_V3_ENTRIES:
required.append("PidsLimit")
required.append("CPUShares")
else:
required += ["PidsLimit", "CpuCfsPeriod", "CpuCfsQuota", "SwapLimit"]
missing = [name for name in required if raw.get(name) is not True]
if missing:
die("CMS CI host lacks required resource controls: " + ",".join(missing))
if raw.get("OSType") != "linux" or raw.get("Architecture") not in ("amd64", "x86_64"):
die("CMS CI pinned worker requires Linux amd64")
if tuple(entries) == CMS_CI_V4_ENTRIES:
if type(raw.get("NCPU")) is not int or raw["NCPU"] < 8:
die("CMS CI CPU7 profile requires at least eight logical CPUs")
cms_ci_check_affinity(0)
return report
def accept_cms_ci_container(info, entries=CMS_CI_ENTRIES):
host = info.get("HostConfig", {})
config = info.get("Config", {})
if config.get("Image") != CMS_CI_IMAGE or not info.get("State", {}).get("Running"):
die("CMS CI runner image or running state mismatch")
labels = config.get("Labels", {})
if (labels.get("com.docker.compose.project") != "nodedc-cms-ci"
or labels.get("com.docker.compose.service") != "build-runner"):
die("CMS CI runner Compose identity mismatch")
if (host.get("PortBindings") or host.get("PublishAllPorts")
or host.get("NetworkMode") in ("host", "none")
or any(info.get("NetworkSettings", {}).get("Ports", {}).values())):
die("CMS CI host network or published port rejected")
if (host.get("Privileged") or host.get("CapAdd") or host.get("Devices")
or not host.get("ReadonlyRootfs") or host.get("PidMode")
or host.get("IpcMode") == "host" or host.get("CapDrop") != ["ALL"]
or "no-new-privileges:true" not in host.get("SecurityOpt", [])):
die("CMS CI runner host isolation mismatch")
if any(value.startswith("GITEA_RUNNER_REGISTRATION_TOKEN=") for value in config.get("Env", [])):
die("CMS CI registration token must remain file-backed")
v4 = tuple(entries) == CMS_CI_V4_ENTRIES
if v4 or tuple(entries) == CMS_CI_V3_ENTRIES:
valid_cpu = (host.get("CpuShares") == 64 and not host.get("NanoCpus")
and not host.get("CpuQuota") and not host.get("CpuPeriod"))
else:
valid_cpu = host.get("NanoCpus") == 500000000
valid_pids = host.get("PidsLimit") in (None, 0, -1) if v4 else host.get("PidsLimit") == 128
if v4:
valid_cpu = valid_cpu and host.get("CpusetCpus") == "7"
if host.get("MemorySwap") != 512 * 1024 ** 2:
die("CMS CI daemon memory/swap limit mismatch")
if (host.get("Memory") != 512 * 1024 ** 2
or not valid_cpu or not valid_pids):
die("CMS CI daemon resource limit mismatch")
if v4:
cms_ci_check_affinity(info.get("State", {}).get("Pid"), exact=True)
expected_mounts = {
"/config/runner.yaml": (str(CMS_CI_ROOT / "runner.yaml"), False),
"/data": (str(CMS_CI_ROOT / "data"), True),
"/run/secrets/registration-token": (str(CMS_CI_ROOT / "secrets/registration-token"), False),
"/var/run/docker.sock": ("/var/run/docker.sock", False),
}
actual = {
mount.get("Destination"): (mount.get("Source"), mount.get("RW"))
for mount in info.get("Mounts", []) if mount.get("Type") != "tmpfs"
}
if actual != expected_mounts:
die("CMS CI daemon mount boundary mismatch")
def accept_cms_ci(entries=CMS_CI_ENTRIES):
deadline = time.monotonic() + 60
registration = CMS_CI_ROOT / "data" / ".runner"
expected_image = inspect_local_image(CMS_CI_IMAGE, "CMS CI running image")
registered_since = None
while True:
ids = cms_ci_container_ids(own=True)
if len(ids) != 1:
die("CMS CI requires exactly one build-runner container")
info = inspect_container(ids[0])
accept_cms_ci_container(info, entries)
if info.get("Image") != expected_image or info.get("RestartCount", 0) != 0:
die("CMS CI image identity or restart count mismatch")
if registration.is_file() and not registration.is_symlink():
try:
value = json.loads(registration.read_text())
valid = (value.get("name") == "synology-cms-build"
and value.get("address", "").rstrip("/") == "https://git.dcserve.ru"
and value.get("id") and value.get("uuid") and value.get("token"))
except (ValueError, UnicodeError):
valid = False
if valid:
registration.chmod(0o600)
if registered_since is None:
registered_since = time.monotonic()
if time.monotonic() - registered_since >= 10:
print("ci_accept=registered-daemon;published_ports=none;production_deploy=false")
return
else:
registered_since = None
if time.monotonic() >= deadline:
die("CMS CI runner registration did not complete")
time.sleep(2)
def capture_cms_ci_diagnostics(backup_dir):
# Logs can contain tokens. Retain only fixed categories and counts, never raw text.
report = {"containers": [], "rawLogsSaved": False}
try:
for container_id in cms_ci_container_ids(own=True):
result = subprocess.run([str(DOCKER), "logs", "--tail", "60", container_id],
capture_output=True, text=True, timeout=10)
text = (result.stdout + result.stderr).lower()
signatures = {"dns": ("no such host", "server misbehaving"),
"tls": ("x509", "tls handshake"),
"network": ("connection refused", "i/o timeout", "no route to host"),
"actions-disabled-or-route": ("404", "not found"),
"token-rejected": ("registration token", "unauthenticated"),
"filesystem": ("permission denied", "read-only file system"),
"configuration": ("unmarshal", "yaml:", "invalid config"),
"registered": ("runner registered successfully",)}
reasons = [key for key, patterns in signatures.items() if any(p in text for p in patterns)]
report["containers"].append({"id": container_id, "categories": reasons or ["unclassified"],
"logLines": len(text.splitlines())})
except Exception:
report["diagnosticStatus"] = "unavailable"
(backup_dir / "ci-startup-diagnostics.json").write_text(json.dumps(report, sort_keys=True) + "\n")
print("ci_startup_diagnostics=" + json.dumps(report, sort_keys=True))
def preflight_cms_ci():
for path in (CMS_CI_ROOT,*CMS_CI_ROOT.parents):
if path.is_symlink():die('CMS CI root contains a symlink')
if any((CMS_CI_ROOT/rel).exists() for rel in CMS_CI_ENTRIES):die('CMS CI requires an uninstalled source partition')
if cms_ci_container_ids(own=True):die('CMS CI already has a runner')
cms_ci_host_capabilities(CMS_CI_V4_ENTRIES)
require_gitea_actions_ping()
preflight_cms_ci_v2_enrollment()
# Existing Device Core CI already acquired these exact digests. No new pull.
for image in (CMS_CI_IMAGE,CMS_CI_JOB_IMAGE):inspect_local_image(image,'CMS CI pinned image')
if shutil.disk_usage(CMS_CI_ROOT.parent).free < 8*1024**3:die('CMS CI requires 8 GiB free disk')
memory={line.split(':')[0]:int(line.split()[1]) for line in Path('/proc/meminfo').read_text().splitlines() if len(line.split())>=2}
if memory.get('MemAvailable',0)<3*1024**2:die('CMS CI requires 3 GiB available memory')
def apply_cms_ci():
import_cms_ci_v2_enrollment()
data=CMS_CI_ROOT/'data'
if data.is_symlink():die('CMS CI data cannot be a symlink')
data.mkdir(mode=0o700,exist_ok=True);os.chown(str(data),0,0);data.chmod(0o700)
subprocess.run(compose_base_cmd('dc-cms-autodeploy')+['up','-d','--no-build','--pull','never','--no-deps','build-runner'],cwd=str(CMS_CI_ROOT),check=True)
accept_cms_ci(CMS_CI_V4_ENTRIES)
def cms_ci_inventory_preserved(before):
current=cms_ci_inventory()
# A registered worker can create ephemeral CI job containers immediately.
# Every preexisting container must retain its exact image and generation.
return all(current.get(identity)==row for identity,row in before.items())
+54
View File
@@ -0,0 +1,54 @@
"""One polling cycle with an injected canonical installer, no shell authority."""
from deployment_queue import REPOSITORY, REPOSITORY_ID, QueueError
class Controller:
def __init__(self, queue, source, installer):
self.queue, self.source, self.installer = queue, source, installer
def reconcile(self):
for row in self.queue.snapshot():
if row['phase'] != 'deploying':
continue
outcome, receipt = self.installer.receipt(row)
self.queue.reconcile(row['id'], digest=row['digest'], artifact=row['artifact'],
outcome=outcome, receipt=receipt)
def observe(self):
runs = self.source.discover()
# A disappeared pending run cannot be silently skipped. Keep its local
# reservation/order; a source error is actionable, never an expiry.
ids = {r['id'] for r in runs}
for row in self.queue.snapshot():
if row['phase'] in ('pending', 'ready') and row['id'] not in ids:
raise QueueError('observed_run_disappeared:' + str(row['id']))
self.queue.observe(runs, repository=REPOSITORY, repository_id=REPOSITORY_ID)
def tick(self):
self.reconcile()
self.observe()
row = self.queue.next_ready()
if row is None:
return {'status': 'waiting'}
run = self.source.successful_run(row)
baseline = self.installer.installed_source()
self.source.prove_lineage(baseline, row['sha'])
receipt, data = self.source.artifact(run)
# Staging validates the canonical payload and its relation to this run.
self.installer.stage(row, receipt, data)
self.installer.plan(receipt['artifact'])
# Recheck after potentially slow download/plan; a rerun/pending run may
# have appeared. Reserve still enforces the durable ordering atomically.
self.observe()
self.source.successful_run(row)
self.source.prove_lineage(baseline, row['sha'])
reserved = self.queue.reserve(row['id'], digest=receipt['sha256'], artifact=receipt['artifact'])
try:
self.installer.apply(receipt['artifact'])
finally:
# Even a clean rollback is terminal for this exact artifact. Missing
# or conflicting evidence blocks subsequent installs after restart.
outcome, canonical_receipt = self.installer.receipt(reserved)
self.queue.reconcile(row['id'], digest=receipt['sha256'], artifact=receipt['artifact'],
outcome=outcome, receipt=canonical_receipt)
return {'status': outcome, 'run': row['id'], 'source': row['sha']}
+178
View File
@@ -0,0 +1,178 @@
"""Durable release ordering. Pure state policy; no network or runtime authority.
The canonical installer remains the only production executor. A controller may
reserve a verified artifact here, then must reconcile its canonical receipt
after any crash before admitting another deployment.
"""
import re
import sqlite3
REPOSITORY = "SILVER/DC_CMS"
REPOSITORY_ID = 33
WORKFLOW = "ci.yml@refs/heads/master"
TERMINAL = {"deployed", "failed", "superseded", "blocked"}
SHA = re.compile(r"[0-9a-f]{40}")
DIGEST = re.compile(r"[0-9a-f]{64}")
class QueueError(ValueError):
pass
def positive(value):
return type(value) is int and 0 < value < 2**53
def normalize_run(run):
if not isinstance(run, dict):
raise QueueError("invalid_run")
if not all(positive(run.get(key)) for key in ("id", "run_number", "run_attempt")):
raise QueueError("invalid_run_identity")
if not isinstance(run.get("head_sha"), str) or not SHA.fullmatch(run["head_sha"]):
raise QueueError("invalid_source_sha")
status = run.get("status")
if status not in ("queued", "waiting", "in_progress", "completed"):
raise QueueError("unknown_run_status")
conclusion = run.get("conclusion")
if status == "completed" and conclusion not in (
"success", "failure", "cancelled", "skipped", "timed_out", "action_required", "neutral", "stale",
):
raise QueueError("unknown_run_conclusion")
relevant = (run.get("event") == "push" and run.get("head_branch") == "master"
and run.get("path") == WORKFLOW)
phase = "pending" if status != "completed" else "ready" if conclusion == "success" else "unqualified"
if not relevant:
phase = "ignored"
return (run["id"], run["run_number"], run["head_sha"], str(run.get("event", "")),
str(run.get("head_branch", "")), str(run.get("path", "")), run["run_attempt"], phase)
class DeploymentQueue:
def __init__(self, path, *, first_run_number):
if not positive(first_run_number):
raise QueueError("invalid_activation_floor")
self.db = sqlite3.connect(str(path), timeout=10, isolation_level=None)
self.db.row_factory = sqlite3.Row
self.db.execute("PRAGMA journal_mode=WAL")
self.db.execute("PRAGMA synchronous=FULL")
self.db.executescript("""
CREATE TABLE IF NOT EXISTS policy (
id INTEGER PRIMARY KEY CHECK(id=1),
repository TEXT NOT NULL, repository_id INTEGER NOT NULL,
first_run INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS runs (
id INTEGER PRIMARY KEY, number INTEGER NOT NULL UNIQUE,
sha TEXT NOT NULL, event TEXT NOT NULL, branch TEXT NOT NULL,
workflow TEXT NOT NULL, attempt INTEGER NOT NULL, phase TEXT NOT NULL,
artifact TEXT, digest TEXT, receipt TEXT
);
CREATE INDEX IF NOT EXISTS runs_phase_number ON runs(phase,number);
CREATE INDEX IF NOT EXISTS runs_sha_phase ON runs(sha,phase);
""")
self.db.execute("INSERT OR IGNORE INTO policy VALUES(1,?,?,?)", (REPOSITORY, REPOSITORY_ID, first_run_number))
policy = self.db.execute("SELECT * FROM policy WHERE id=1").fetchone()
if (policy["repository"], policy["repository_id"], policy["first_run"]) != (REPOSITORY, REPOSITORY_ID, first_run_number):
self.db.close()
raise QueueError("queue_policy_changed")
self.first_run = first_run_number
def close(self):
self.db.close()
def transaction(self, operation):
self.db.execute("BEGIN IMMEDIATE")
try:
value = operation()
self.db.execute("COMMIT")
return value
except BaseException:
self.db.execute("ROLLBACK")
raise
def observe(self, runs, *, repository, repository_id):
if repository != REPOSITORY or type(repository_id) is not int or repository_id != REPOSITORY_ID:
raise QueueError("repository_identity_mismatch")
values = [normalize_run(run) for run in runs]
def apply():
for value in values:
identity, number, sha, event, branch, workflow, attempt, phase = value
if number < self.first_run:
continue
existing = self.db.execute("SELECT * FROM runs WHERE id=?", (identity,)).fetchone()
if existing is None:
self.db.execute("INSERT INTO runs(id,number,sha,event,branch,workflow,attempt,phase) VALUES(?,?,?,?,?,?,?,?)", value)
continue
if tuple(existing[k] for k in ("number", "sha", "event", "branch", "workflow")) != (number, sha, event, branch, workflow):
raise QueueError("run_identity_changed")
if attempt < existing["attempt"]:
continue # A stale API page cannot rewind a rerun.
if existing["phase"] in TERMINAL or existing["phase"] == "deploying":
continue
if attempt == existing["attempt"] and existing["phase"] in ("ready", "unqualified") and phase == "pending":
continue
if attempt == existing["attempt"] and existing["phase"] in ("ready", "unqualified") and phase != existing["phase"]:
raise QueueError("terminal_run_outcome_changed")
self.db.execute("UPDATE runs SET phase=?,attempt=? WHERE id=?", (phase, attempt, identity))
self.transaction(apply)
def _next(self):
blocked = self.db.execute("SELECT id,phase FROM runs WHERE phase IN ('deploying','blocked') ORDER BY number LIMIT 1").fetchone()
if blocked:
raise QueueError("canonical_reconciliation_required:" + str(blocked["id"]))
while True:
row = self.db.execute("SELECT * FROM runs WHERE phase IN ('pending','ready') ORDER BY number LIMIT 1").fetchone()
if row is None or row["phase"] != "ready":
return None
newer = self.db.execute("SELECT id FROM runs WHERE phase='deployed' AND number>=? LIMIT 1", (row["number"],)).fetchone()
duplicate = self.db.execute("SELECT id FROM runs WHERE phase='deployed' AND sha=? LIMIT 1", (row["sha"],)).fetchone()
if newer or duplicate:
self.db.execute("UPDATE runs SET phase='superseded' WHERE id=?", (row["id"],))
continue
return dict(row)
def next_ready(self):
return self.transaction(self._next)
def reserve(self, identity, *, digest, artifact):
if not isinstance(digest, str) or not DIGEST.fullmatch(digest):
raise QueueError("invalid_artifact_digest")
def apply():
row = self._next()
if row is None or row["id"] != identity:
raise QueueError("deployment_order_mismatch")
expected = "nodedc-dc-cms-release-v1-r" + str(identity) + "-" + row["sha"] + ".tgz"
if artifact != expected:
raise QueueError("artifact_identity_mismatch")
self.db.execute("UPDATE runs SET phase='deploying',digest=?,artifact=? WHERE id=?", (digest, artifact, identity))
return {**row, "phase": "deploying", "digest": digest, "artifact": artifact}
return self.transaction(apply)
def reconcile(self, identity, *, digest, artifact, outcome, receipt):
"""Caller must prove the canonical applied/failed journal and archive.
No receipt or uncertain/failed rollback => blocked, never automatic retry.
A clean rollback may be followed by a new release, never this artifact.
"""
if outcome not in ("deployed", "rolled-back", "ambiguous"):
raise QueueError("invalid_canonical_outcome")
if not isinstance(receipt, str) or not receipt or len(receipt) > 240:
raise QueueError("canonical_receipt_required")
phase = {"deployed": "deployed", "rolled-back": "failed", "ambiguous": "blocked"}[outcome]
def apply():
row = self.db.execute("SELECT * FROM runs WHERE id=?", (identity,)).fetchone()
if row is None or (row["digest"], row["artifact"]) != (digest, artifact):
raise QueueError("canonical_artifact_mismatch")
if row["phase"] == phase and row["receipt"] == receipt:
return
if row["phase"] != "deploying":
raise QueueError("canonical_outcome_conflict")
self.db.execute("UPDATE runs SET phase=?,receipt=? WHERE id=?", (phase, receipt, identity))
self.transaction(apply)
def snapshot(self):
return [dict(row) for row in self.db.execute("SELECT * FROM runs ORDER BY number")]
@@ -0,0 +1,42 @@
services:
build-runner:
image: docker.io/gitea/runner@sha256:05e100d9c2268fb300f929cab014e9930591a2d66822454e175c1099d1464b14
platform: linux/amd64
pull_policy: never
restart: unless-stopped
read_only: true
cpu_shares: 64
cpuset: "7"
mem_limit: 512m
memswap_limit: 512m
cap_drop: [ALL]
security_opt: [no-new-privileges:true]
tmpfs:
- /tmp:rw,nosuid,nodev,size=134217728
environment:
HOME: /data
XDG_CACHE_HOME: /data/.cache
CONFIG_FILE: /config/runner.yaml
GITEA_INSTANCE_URL: https://git.dcserve.ru
GITEA_RUNNER_NAME: synology-cms-build
GITEA_RUNNER_REGISTRATION_TOKEN_FILE: /run/secrets/registration-token
volumes:
- type: bind
source: /volume1/docker/nodedc-cms-autodeploy/runner.yaml
target: /config/runner.yaml
read_only: true
bind: {create_host_path: false}
- type: bind
source: /volume1/docker/nodedc-cms-autodeploy/data
target: /data
bind: {create_host_path: false}
- type: bind
source: /volume1/docker/nodedc-cms-autodeploy/secrets/registration-token
target: /run/secrets/registration-token
read_only: true
bind: {create_host_path: false}
- type: bind
source: /var/run/docker.sock
target: /var/run/docker.sock
read_only: true
bind: {create_host_path: false}
+22
View File
@@ -0,0 +1,22 @@
"""Refresh the reviewed standalone section; runtime never imports from SMB."""
import json
from pathlib import Path
ROOT=Path(__file__).resolve().parent
RUNNER=ROOT.parent/'deploy-runner/nodedc-deploy'
START='# BEGIN GENERATED CMS DEPLOYMENT\n'
END='# END GENERATED CMS DEPLOYMENT\n'
def section():
release=(ROOT/'release_runtime.py').read_text().replace('__CMS_BASELINE__',repr(json.loads((ROOT/'baseline.json').read_text()))).replace('__CMS_FOUNDATION__',repr(json.loads((ROOT/'foundation.json').read_text())))
ci=(ROOT/'ci_runtime.py').read_text().replace('__CMS_CI_HASHES__',repr(json.loads((ROOT/'ci-source-sha256.json').read_text())))
auto=(ROOT/'autodeploy_runtime.py').read_text()
library='def cms_autodeploy_library():\n'
for file in ('deployment_queue.py','gitea_source.py','controller.py'):
lines=[line for line in (ROOT/file).read_text().splitlines() if not line.startswith('from deployment_queue import ')]
library+='\n'.join(' '+line if line else '' for line in lines)+'\n\n'
library+=' return DeploymentQueue, GiteaSource, Controller, (QueueError, SourceError)\n'
return START+release+'\n'+ci+'\n'+auto+'\n'+library+END
if __name__=='__main__':
before,rest=RUNNER.read_text().split(START,1);_,after=rest.split(END,1)
RUNNER.write_text(before+section()+after)
+211
View File
@@ -0,0 +1,211 @@
{
"name": "dc-cms",
"version": "0.1.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "dc-cms",
"version": "0.1.0",
"dependencies": {
"adm-zip": "0.6.1",
"jose": "^6.2.3",
"ssh2-sftp-client": "^12.1.1"
}
},
"node_modules/adm-zip": {
"version": "0.6.1",
"resolved": "https://registry.npmjs.org/adm-zip/-/adm-zip-0.6.1.tgz",
"integrity": "sha512-Xwrja8nx9e5o2N1my4DsKCeKpdrnACyr1wtbPxBDgGzKzKyE9kRtBFA8mWldI+RVlD7CBZNWY/wQ2+ydwOR6kQ==",
"license": "MIT",
"engines": {
"node": ">=14.0"
}
},
"node_modules/asn1": {
"version": "0.2.6",
"resolved": "https://registry.npmjs.org/asn1/-/asn1-0.2.6.tgz",
"integrity": "sha512-ix/FxPn0MDjeyJ7i/yoHGFt/EX6LyNbxSEhPPXODPL+KB0VPk86UYfL0lMdy+KCnv+fmvIzySwaK5COwqVbWTQ==",
"license": "MIT",
"dependencies": {
"safer-buffer": "~2.1.0"
}
},
"node_modules/bcrypt-pbkdf": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.2.tgz",
"integrity": "sha512-qeFIXtP4MSoi6NLqO12WfqARWWuCKi2Rn/9hJLEmtB5yTNr9DqFWkJRCf2qShWzPeAMRnOgCrq0sg/KLv5ES9w==",
"license": "BSD-3-Clause",
"dependencies": {
"tweetnacl": "^0.14.3"
}
},
"node_modules/buffer-from": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz",
"integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==",
"license": "MIT"
},
"node_modules/buildcheck": {
"version": "0.0.7",
"resolved": "https://registry.npmjs.org/buildcheck/-/buildcheck-0.0.7.tgz",
"integrity": "sha512-lHblz4ahamxpTmnsk+MNTRWsjYKv965MwOrSJyeD588rR3Jcu7swE+0wN5F+PbL5cjgu/9ObkhfzEPuofEMwLA==",
"optional": true,
"engines": {
"node": ">=10.0.0"
}
},
"node_modules/concat-stream": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-2.0.0.tgz",
"integrity": "sha512-MWufYdFw53ccGjCA+Ol7XJYpAlW6/prSMzuPOTRnJGcGzuhLn4Scrz7qf6o8bROZ514ltazcIFJZevcfbo0x7A==",
"engines": [
"node >= 6.0"
],
"license": "MIT",
"dependencies": {
"buffer-from": "^1.0.0",
"inherits": "^2.0.3",
"readable-stream": "^3.0.2",
"typedarray": "^0.0.6"
}
},
"node_modules/cpu-features": {
"version": "0.0.10",
"resolved": "https://registry.npmjs.org/cpu-features/-/cpu-features-0.0.10.tgz",
"integrity": "sha512-9IkYqtX3YHPCzoVg1Py+o9057a3i0fp7S530UWokCSaFVTc7CwXPRiOjRjBQQ18ZCNafx78YfnG+HALxtVmOGA==",
"hasInstallScript": true,
"optional": true,
"dependencies": {
"buildcheck": "~0.0.6",
"nan": "^2.19.0"
},
"engines": {
"node": ">=10.0.0"
}
},
"node_modules/inherits": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
"integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
"license": "ISC"
},
"node_modules/jose": {
"version": "6.2.3",
"resolved": "https://registry.npmjs.org/jose/-/jose-6.2.3.tgz",
"integrity": "sha512-YYVDInQKFJfR/xa3ojUTl8c2KoTwiL1R5Wg9YCydwH0x0B9grbzlg5HC7mMjCtUJjbQ/YnGEZIhI5tCgfTb4Hw==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/panva"
}
},
"node_modules/nan": {
"version": "2.28.0",
"resolved": "https://registry.npmjs.org/nan/-/nan-2.28.0.tgz",
"integrity": "sha512-fTsDz99OTq2sVePhGdp4qQhggZFtKr64ZNVyVajRKtMOkJxYekplBh577PiJB12v/D3s2E5cGtOI45LWp6rnLQ==",
"license": "MIT",
"optional": true
},
"node_modules/readable-stream": {
"version": "3.6.2",
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz",
"integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",
"license": "MIT",
"dependencies": {
"inherits": "^2.0.3",
"string_decoder": "^1.1.1",
"util-deprecate": "^1.0.1"
},
"engines": {
"node": ">= 6"
}
},
"node_modules/safe-buffer": {
"version": "5.2.1",
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
"integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/feross"
},
{
"type": "patreon",
"url": "https://www.patreon.com/feross"
},
{
"type": "consulting",
"url": "https://feross.org/support"
}
],
"license": "MIT"
},
"node_modules/safer-buffer": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
"license": "MIT"
},
"node_modules/ssh2": {
"version": "1.17.0",
"resolved": "https://registry.npmjs.org/ssh2/-/ssh2-1.17.0.tgz",
"integrity": "sha512-wPldCk3asibAjQ/kziWQQt1Wh3PgDFpC0XpwclzKcdT1vql6KeYxf5LIt4nlFkUeR8WuphYMKqUA56X4rjbfgQ==",
"hasInstallScript": true,
"dependencies": {
"asn1": "^0.2.6",
"bcrypt-pbkdf": "^1.0.2"
},
"engines": {
"node": ">=10.16.0"
},
"optionalDependencies": {
"cpu-features": "~0.0.10",
"nan": "^2.23.0"
}
},
"node_modules/ssh2-sftp-client": {
"version": "12.1.1",
"resolved": "https://registry.npmjs.org/ssh2-sftp-client/-/ssh2-sftp-client-12.1.1.tgz",
"integrity": "sha512-wYVDgwkpcKG2iPGQQ+QR33xkWqLFIaVrYvA+uON4pmxTPaPuB81f1aooUEPN75e/9DCK6rrKYXb6zR6zP3+EtA==",
"license": "Apache-2.0",
"dependencies": {
"concat-stream": "^2.0.0",
"ssh2": "^1.16.0"
},
"engines": {
"node": ">=18.20.4"
},
"funding": {
"type": "individual",
"url": "https://square.link/u/4g7sPflL"
}
},
"node_modules/string_decoder": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz",
"integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==",
"license": "MIT",
"dependencies": {
"safe-buffer": "~5.2.0"
}
},
"node_modules/tweetnacl": {
"version": "0.14.5",
"resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-0.14.5.tgz",
"integrity": "sha512-KXXFFdAbFXY4geFIwoyNK+f5Z1b7swfXABfL7HXCmoIWMKU3dmS26672A4EeQtDzLKy7SXmfBu51JolvEKwtGA==",
"license": "Unlicense"
},
"node_modules/typedarray": {
"version": "0.0.6",
"resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz",
"integrity": "sha512-/aCDEGatGvZ2BIk+HmLf4ifCJFwvKFNb9/JeZPMulfgFracn9QFcAf5GO8B/mweUjSoblS5In0cWhqpfs/5PQA==",
"license": "MIT"
},
"node_modules/util-deprecate": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
"integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==",
"license": "MIT"
}
}
}
+15
View File
@@ -0,0 +1,15 @@
{
"name": "dc-cms",
"version": "0.1.0",
"private": true,
"type": "module",
"scripts": {
"admin": "node server/admin-server.mjs",
"start": "node server/admin-server.mjs"
},
"dependencies": {
"adm-zip": "0.6.1",
"jose": "^6.2.3",
"ssh2-sftp-client": "^12.1.1"
}
}
+7
View File
@@ -0,0 +1,7 @@
{
"Dockerfile": "ccb783bd76b1588cbe0157bd317f6da06888d79f8a199fd0c5515000948acd42",
"infra/docker-compose.yml": "abb3a9d4e4e2ce15eb2ca52b335289dcd00808d85c78da6d1bc583a8b3517f48",
"infra/reverse-proxy/Caddyfile": "4d30188eb1f11b52a0eaf2d9476e0b0adda93a63e66938e8028cc11de4c2038f",
"package-lock.json": "aca65991c748c6e39b6cbc50405ab5a2bc7bb0d5d1b56a5a4c68bce5f645e47c",
"package.json": "40ee5bc4cf6b634612efa1fc293f6ab1955ee4520701a5dee7c8990fb5ad5fa2"
}
+259
View File
@@ -0,0 +1,259 @@
"""Read-only, bounded Gitea source verification. No production execution authority.
The privileged installer must independently validate the returned TGZ with its
canonical loader and reconcile its own journal. Nothing here accepts commands,
paths, origins, or credentials from a workflow artifact.
"""
import hashlib
import io
import json
import re
import stat
import urllib.error
import urllib.parse
import urllib.request
import zipfile
from deployment_queue import REPOSITORY, REPOSITORY_ID, WORKFLOW, SHA, normalize_run, positive
ORIGIN = "https://git.dcserve.ru"
PREFIX = "/api/v1/repos/" + REPOSITORY
PAGE_SIZE = 50
MAX_PAGES = 200
MAX_JSON = 8 * 1024 * 1024
MAX_ARCHIVE = 64 * 1024 * 1024
class SourceError(ValueError):
pass
def require(condition, code):
if not condition:
raise SourceError(code)
def strict_json(data):
def unique(pairs):
result = {}
for key, value in pairs:
require(key not in result, "duplicate_json_key")
result[key] = value
return result
try:
return json.loads(data, object_pairs_hook=unique)
except (UnicodeError, ValueError):
raise SourceError("invalid_json") from None
def signed_artifact_redirect(original, target):
origin, dest = urllib.parse.urlsplit(original), urllib.parse.urlsplit(target)
if (origin.scheme + "://" + origin.netloc != ORIGIN
or dest.scheme + "://" + dest.netloc != ORIGIN or origin.query or dest.fragment
or not re.fullmatch(re.escape(PREFIX) + r"/actions/artifacts/[1-9][0-9]*/zip", origin.path)
or dest.path != origin.path + "/raw"):
return False
pairs = urllib.parse.parse_qsl(dest.query, keep_blank_values=True)
params = dict(pairs)
return (len(pairs) == 2 and set(params) == {"sig", "expires"}
and re.fullmatch(r"[A-Za-z0-9_-]{32,128}", params["sig"]) is not None
and re.fullmatch(r"[0-9]{10,13}", params["expires"]) is not None)
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
# Gitea 1.27 signs a same-origin /zip/raw URL. Only this exact route is
# allowed and the persistent token is deliberately NOT forwarded.
if (req is not None and req.get_method() == "GET" and code in (302, 303)
and signed_artifact_redirect(req.full_url, newurl)):
return urllib.request.Request(newurl, headers={"Accept": "application/octet-stream"})
raise SourceError("api_redirect_refused")
class GiteaSource:
def __init__(self, token):
require(isinstance(token, str) and re.fullmatch(r"[0-9a-f]{40}", token), "invalid_read_token")
self._token = token
self._opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirect())
def request(self, suffix, *, archive=False):
require(isinstance(suffix, str) and (suffix == "" or suffix.startswith("/")), "invalid_api_path")
require(not any(value in suffix for value in ("..", "\\", "#", "@", "\r", "\n", "%")), "invalid_api_path")
# Only methods below construct suffixes; this additional allowlist keeps
# even accidental future callers from reading other API resources.
require(re.fullmatch(
r"(?:|/branches/master|/git/commits/[a-f0-9]{40}"
r"|/actions/runs(?:/[1-9][0-9]*(?:/jobs|/artifacts)?)?"
r"|/actions/artifacts/[1-9][0-9]*/zip)(?:\?page=[1-9][0-9]*&limit=50)?", suffix),
"api_route_not_allowed")
require(archive == suffix.endswith("/zip"), "api_response_type_mismatch")
maximum = MAX_ARCHIVE if archive else MAX_JSON
request = urllib.request.Request(ORIGIN + PREFIX + suffix,
headers={"Authorization": "token " + self._token,
"Accept": "application/octet-stream" if archive else "application/json"})
try:
with self._opener.open(request, timeout=25) as response:
require(response.status == 200 and (response.geturl() == request.full_url or (archive and signed_artifact_redirect(request.full_url, response.geturl()))), "api_response_identity")
data = response.read(maximum + 1)
except urllib.error.HTTPError as error:
raise SourceError("api_http_" + str(error.code)) from None
except (OSError, urllib.error.URLError):
raise SourceError("api_unavailable") from None
require(len(data) <= maximum, "api_response_too_large")
return data if archive else strict_json(data)
def repository(self):
repo = self.request("")
require(isinstance(repo, dict) and type(repo.get("id")) is int and repo["id"] == REPOSITORY_ID
and repo.get("full_name") == REPOSITORY and repo.get("default_branch") == "master"
and repo.get("archived") is False and repo.get("mirror") is False,
"repository_identity_mismatch")
return repo
def pages(self, suffix, key):
rows, identities, total = [], set(), None
for page in range(1, MAX_PAGES + 1):
data = self.request(suffix + "?page=" + str(page) + "&limit=50")
require(isinstance(data, dict) and type(data.get("total_count")) is int
and 0 <= data["total_count"] <= PAGE_SIZE * MAX_PAGES, "pagination_total_invalid")
require(total is None or total == data["total_count"], "pagination_changed")
total = data["total_count"]
batch = data.get(key)
require(isinstance(batch, list) and len(batch) <= PAGE_SIZE, "pagination_batch_invalid")
for item in batch:
require(isinstance(item, dict) and positive(item.get("id")) and item["id"] not in identities,
"pagination_duplicate_or_invalid_id")
identities.add(item["id"])
rows.extend(batch)
require(len(rows) <= total, "pagination_overflow")
if len(rows) == total:
return rows
require(len(batch) == PAGE_SIZE, "pagination_incomplete")
raise SourceError("pagination_limit")
def run(self, identity):
require(positive(identity), "invalid_run_id")
run = self.request("/actions/runs/" + str(identity))
self.validate_run(run)
require(run["id"] == identity, "run_identity_mismatch")
return run
@staticmethod
def validate_run(run):
normalize_run(run)
# Gitea 1.27.2 leaves top-level repository_id=0. The nested repository
# and fixed repository endpoint carry the actual identity instead.
repo = run.get("repository") or {}
require(type(repo.get("id")) is int and repo["id"] == REPOSITORY_ID
and repo.get("full_name") == REPOSITORY, "run_repository_mismatch")
def discover(self):
self.repository()
runs = self.pages("/actions/runs", "workflow_runs")
for run in runs:
self.validate_run(run)
require(len({run["run_number"] for run in runs}) == len(runs), "duplicate_run_number")
# A push/deletion while pages were read must not silently hide an older
# pending run. Recheck identity/count, without requiring phases to stop.
check = self.pages("/actions/runs", "workflow_runs")
identity = lambda values: sorted((r["id"], r["run_number"], r["head_sha"], r["event"], r["head_branch"], r["path"]) for r in values)
for run in check:
self.validate_run(run)
require(identity(runs) == identity(check), "discovery_changed")
return check
def successful_run(self, row):
run = self.run(row["id"])
require((run["run_number"], run["head_sha"], run["run_attempt"]) ==
(row["number"], row["sha"], row["attempt"]), "qualified_run_changed")
require(run["path"] == WORKFLOW and run["event"] == "push" and run["head_branch"] == "master"
and run["status"] == "completed" and run["conclusion"] == "success", "run_not_qualified")
jobs = self.pages("/actions/runs/" + str(run["id"]) + "/jobs", "jobs")
require(len(jobs) == 1, "qualification_job_count")
job = jobs[0]
require(job.get("run_id") == run["id"] and job.get("head_sha") == run["head_sha"]
and job.get("head_branch") == "master" and job.get("run_attempt") == run["run_attempt"]
and job.get("name") == "qualify" and job.get("labels") == ["nodedc-node22-build"]
and job.get("runner_id") == 1 and job.get("status") == "completed"
and job.get("conclusion") == "success", "qualification_job_mismatch")
steps = job.get("steps")
require(isinstance(steps, list) and all(isinstance(s, dict) for s in steps) and [s.get("name") for s in steps] ==
["Check the exact pushed commit", "Retain the qualified release in this Gitea run"]
and all(s.get("status") == "completed" and s.get("conclusion") == "success" for s in steps),
"qualification_steps_mismatch")
return run
def main_commit(self):
branch = self.request("/branches/master")
require(isinstance(branch, dict) and branch.get("name") == "master", "main_branch_mismatch")
sha = (branch.get("commit") or {}).get("id")
require(isinstance(sha, str) and SHA.fullmatch(sha), "main_commit_invalid")
return sha
def ancestor(self, ancestor, descendant, *, limit=1024):
require(all(isinstance(s, str) and SHA.fullmatch(s) for s in (ancestor, descendant)), "ancestry_sha_invalid")
pending, seen = [descendant], set()
while pending:
sha = pending.pop()
if sha == ancestor:
return True
if sha in seen:
continue
require(len(seen) < limit, "ancestry_limit")
seen.add(sha)
commit = self.request("/git/commits/" + sha)
require(isinstance(commit, dict) and commit.get("sha") == sha, "commit_identity_mismatch")
parents = commit.get("parents")
require(isinstance(parents, list) and len(parents) <= 32, "commit_parents_invalid")
for parent in parents:
value = parent.get("sha") if isinstance(parent, dict) else None
require(isinstance(value, str) and SHA.fullmatch(value), "commit_parent_invalid")
pending.append(value)
return False
def prove_lineage(self, installed, candidate):
main = self.main_commit()
require(candidate != installed and self.ancestor(installed, candidate)
and self.ancestor(candidate, main), "non_forward_main_release")
require(self.main_commit() == main, "main_changed_during_proof")
return main
def artifact(self, run):
artifacts = self.pages("/actions/runs/" + str(run["id"]) + "/artifacts", "artifacts")
candidates = [a for a in artifacts if a.get("name") == "dc-cms-release"]
require(len(candidates) == 1, "qualified_artifact_count")
artifact = candidates[0]
owner = artifact.get("workflow_run") or {}
require(owner.get("id") == run["id"] and owner.get("repository_id") == REPOSITORY_ID
and owner.get("head_sha") == run["head_sha"] and artifact.get("expired") is False
and type(artifact.get("size_in_bytes")) is int and 0 < artifact["size_in_bytes"] <= MAX_ARCHIVE,
"artifact_owner_or_size_mismatch")
blob = self.request("/actions/artifacts/" + str(artifact["id"]) + "/zip", archive=True)
require(len(blob) == artifact["size_in_bytes"], "artifact_download_size_mismatch")
return unpack_artifact(blob, run)
def unpack_artifact(blob, run):
identity = "nodedc-dc-cms-release-v1-r" + str(run["id"]) + "-" + run["head_sha"] + ".tgz"
require(len(blob) <= MAX_ARCHIVE, "archive_too_large")
try:
with zipfile.ZipFile(io.BytesIO(blob)) as archive:
members = archive.infolist()
require(len(members) == 2 and set(archive.namelist()) == {identity, "release.json"}, "zip_entry_mismatch")
for member in members:
require(not member.is_dir() and stat.S_IFMT(member.external_attr >> 16) in (0, stat.S_IFREG)
and not member.flag_bits & 1 and 0 < member.file_size <= MAX_ARCHIVE,
"zip_member_invalid")
if member.filename == "release.json":
require(member.file_size <= 4096, "zip_receipt_too_large")
data = archive.read(identity)
receipt = strict_json(archive.read("release.json"))
except (zipfile.BadZipFile, RuntimeError, NotImplementedError, OSError):
raise SourceError("archive_invalid") from None
expected = {"artifact": identity, "sourceCommit": run["head_sha"], "runId": run["id"],
"runNumber": run["run_number"], "deployed": False,
"sha256": hashlib.sha256(data).hexdigest()}
require(receipt == expected and type(receipt.get("runId")) is int
and type(receipt.get("runNumber")) is int and receipt.get("deployed") is False, "release_receipt_mismatch")
return receipt, data
+198
View File
@@ -0,0 +1,198 @@
# Embedded into the reviewed root runner. This file is never imported from SMB.
CMS_ROOT = Path('/volume1/docker/dc-cms/source')
CMS_RELEASE_ENTRY = 'server/cms-release.json'
CMS_RELEASE_SERVICES = ('cms-app',)
CMS_BASELINE = __CMS_BASELINE__
CMS_FOUNDATION = __CMS_FOUNDATION__
CMS_DEPENDENCY_FILES = ('package.json', 'package-lock.json')
def cms_release_path(rel, *, directory=False):
validate_posix_path(rel)
if directory and rel in ('admin', 'server'):
return True
if rel == CMS_RELEASE_ENTRY or rel in CMS_DEPENDENCY_FILES:
return True
parts = PurePosixPath(rel).parts
if (len(parts) == 2 and parts[0] in ('admin', 'server')
and re.fullmatch(r'[a-zA-Z0-9_-]+\.(?:mjs|js|css|html|svg)', parts[1])):
return True
die('CMS release path outside application scope: ' + rel)
def cms_release_entries(entries):
if not entries or len(set(entries)) != len(entries) or list(entries) != sorted(entries):
die('CMS release requires sorted unique application files')
required = {'admin/index.html', 'admin/admin.js', 'admin/admin.css', 'server/admin-server.mjs', CMS_RELEASE_ENTRY, *CMS_DEPENDENCY_FILES}
if not required <= set(entries):
die('CMS release is missing application entrypoints')
for rel in entries:
cms_release_path(rel)
def validate_cms_release_payload(payload, entries, identity):
cms_release_entries(entries)
d = read_strict_json(payload / CMS_RELEASE_ENTRY, 'CMS release', max_bytes=256*1024)
if (set(d) != {'schemaVersion','releaseId','repository','repositoryId','branch','sourceCommit','runId','runNumber','qualification','filesSha256','foundationSha256'}
or d.get('schemaVersion') != 'nodedc.dc-cms.release.v1'
or d.get('repository') != 'SILVER/DC_CMS' or type(d.get('repositoryId')) is not int or d['repositoryId'] != 33
or d.get('branch') != 'master' or not re.fullmatch('[a-f0-9]{40}', str(d.get('sourceCommit')))
or any(type(d.get(k)) is not int or not 0 < d[k] < 2**53 for k in ('runId','runNumber'))
or d.get('releaseId') != identity or identity != 'dc-cms-release-v1-r'+str(d['runId'])+'-'+d['sourceCommit']):
die('CMS release identity mismatch')
actual = collect_exact_files(payload, [p for p in entries if p != CMS_RELEASE_ENTRY], 'CMS release')
if d.get('filesSha256') != actual:
die('CMS release application digest mismatch')
if d.get('foundationSha256') != {p: CMS_FOUNDATION[p] for p in ('Dockerfile','package.json','package-lock.json','infra/docker-compose.yml')} or any(actual.get(p) != CMS_FOUNDATION[p] for p in CMS_DEPENDENCY_FILES):
die('CMS release cannot change dependencies, Dockerfile or Compose foundation')
if d.get('qualification') != {'status':'qualified','steps':['frozen-install','syntax','multisite-tests'],'deployed':False}:
die('CMS release qualification mismatch')
return d
def cms_foundation():
expected = CMS_FOUNDATION if (CMS_ROOT / CMS_RELEASE_ENTRY).exists() else CMS_BASELINE['foundationSha256']
if collect_exact_files(CMS_ROOT, sorted(expected), 'CMS foundation') != expected:
die('CMS foundation differs from the registered predecessor')
# Include env-file identity without disclosing any values.
env = CMS_ROOT / 'infra/.env.synology'
if env.is_symlink() or not env.is_file():
die('CMS environment file is missing or unsafe')
return {**expected, 'infra/.env.synology':sha256_file(env)}
def cms_installed_release():
for row in load_state(FAILED_STATE_FILE):
if row.get('component') in ('dc-cms-release','dc-cms-autodeploy') and row.get('started_apply') and not str(row.get('rollback_status','')).startswith('ok:'):
die('CMS deployment requires failed-rollback reconciliation')
rows = [r for r in load_state(STATE_FILE) if r.get('component') == 'dc-cms-release']
if rows:
row = rows[-1]
with tempfile.TemporaryDirectory(prefix='cms-baseline-',dir=TMP_DIR) as tmp:
manifest, entries, payload = load_artifact(device_release_applied_archive(row),Path(tmp))
if manifest['component'] != 'dc-cms-release' or manifest['id'] != row['id']:
die('CMS predecessor receipt mismatch')
descriptor = validate_cms_release_payload(payload, entries, row['id'])
expected = collect_exact_files(payload, entries, 'CMS predecessor')
else:
# Initial transition is independently anchored in the exact live CMS source.
descriptor = {'sourceCommit':CMS_BASELINE['sourceCommit'],'runNumber':0,'releaseId':'dc-cms-4c6f133'}
expected = {**CMS_BASELINE['filesSha256'], **{p:CMS_BASELINE['foundationSha256'][p] for p in CMS_DEPENDENCY_FILES}}
if collect_exact_files(CMS_ROOT, ('admin','server',*CMS_DEPENDENCY_FILES), 'CMS installed app') != expected:
die('CMS installed application differs from its canonical predecessor')
cms_foundation()
return descriptor
def cms_runtime_snapshot():
identity = compose_service_container_id('dc-cms-release','cms-app')
info = inspect_container(identity)
config = info.get('Config') or {}
labels = config.get('Labels') or {}
state = info.get('State') or {}
if labels.get('com.docker.compose.project') != 'dc-cms' or labels.get('com.docker.compose.service') != 'cms-app' or not state.get('Running'):
die('CMS application runtime identity or readiness mismatch')
host = json.loads(json.dumps(info.get('HostConfig') or {}))
for field in ('Mounts','Ulimits'):
if isinstance(host.get(field),list):host[field].sort(key=lambda x:json.dumps(x,sort_keys=True))
fields = {'host':host,'config':{k:config.get(k) for k in ('Env','User','Cmd','Entrypoint','WorkingDir','ExposedPorts')},
'mounts':sorted(info.get('Mounts') or [],key=lambda x:json.dumps(x,sort_keys=True)),
'networks':sorted((info.get('NetworkSettings') or {}).get('Networks') or {})}
if isinstance(fields['config']['Env'],list):fields['config']['Env'].sort()
image_ref = config.get('Image','')
if not re.fullmatch(r'[a-z0-9][a-z0-9_./:-]+',image_ref) or '@' in image_ref:
die('CMS existing image tag cannot be safely restored')
return {'id':identity,'imageId':info['Image'],'imageRef':image_ref,'configSha256':hashlib.sha256(json.dumps(fields,sort_keys=True).encode()).hexdigest()}
def cms_other_services():
result = {}
proc = subprocess.run([str(DOCKER),'ps','-aq','--no-trunc','--filter','label=com.docker.compose.project'],capture_output=True,text=True,check=True)
for identity in proc.stdout.split():
if not re.fullmatch('[a-f0-9]{64}',identity):die('CMS preserved container identity mismatch')
info = inspect_container(identity);labels=(info.get('Config') or {}).get('Labels') or {}
if labels.get('com.docker.compose.project') == 'dc-cms' and labels.get('com.docker.compose.service') == 'cms-app':continue
if str(labels.get('com.docker.compose.oneoff','False')).lower() == 'true':continue
result[identity]={'fingerprint':gitea_actions_fingerprint_v2(info),'running':(info.get('State') or {}).get('Running'),'startedAt':(info.get('State') or {}).get('StartedAt')}
return result
def cms_preserved_data():
# Hash configuration and content; runtime data never enters the build context.
return {'projects':collect_exact_files(CMS_ROOT,('projects',),'CMS projects'),
'sites':collect_exact_files(Path('/volume1/docker/dc-cms'),('sites',),'CMS sites')}
def cms_healthchecks():
healthcheck_url({'url':'http://172.22.0.222:9918/healthz','headers':{'Host':'cms.dcserve.ru'},
'expected_json':{'ok':True,'service':'dc-cms','authEnabled':True}})
for check in COMPONENTS['dc-cms']['healthchecks']:healthcheck_url(check)
def preflight_cms_release(payload, entries, identity):
require_root()
d = validate_cms_release_payload(payload,entries,identity)
previous = cms_installed_release()
if d['runNumber'] <= previous['runNumber'] or d['sourceCommit'] == previous['sourceCommit']:
die('CMS release is stale or already installed')
installed = collect_exact_files(CMS_ROOT,('admin','server',*CMS_DEPENDENCY_FILES),'CMS rollback source')
# v1 is additive: deleting an application file requires a reviewed transition.
if not set(installed) <= set(entries):die('CMS v1 release cannot remove existing application files')
cms_healthchecks()
return {'descriptor':d,'entries':list(entries),'predecessor':previous['sourceCommit'],
'runtime':cms_runtime_snapshot(),'otherServices':cms_other_services(),
'foundation':cms_foundation(),'data':cms_preserved_data(),'installedFiles':installed}
def build_cms_release(before):
# Legacy Dockerfile COPYs projects. Supply an empty directory, never the NAS
# project registry, encrypted passwords, uploaded ZIPs or site workspaces.
with tempfile.TemporaryDirectory(prefix='cms-build-',dir=TMP_DIR) as temp:
context=Path(temp)
(context/'projects').mkdir()
for rel in ('Dockerfile','package.json','package-lock.json',*before['entries']):
target=context/rel;target.parent.mkdir(parents=True,exist_ok=True);shutil.copyfile(CMS_ROOT/rel,target)
subprocess.run([str(DOCKER),'build','--file',str(context/'Dockerfile'),'--tag',before['runtime']['imageRef'],str(context)],check=True)
image=docker_json(['image','inspect',before['runtime']['imageRef']],'CMS built image')
if not isinstance(image,list) or len(image)!=1:die('CMS built image is ambiguous')
before['builtImageId']=image[0]['Id']
def run_cms_release_compose():
cmd=compose_base_cmd('dc-cms-release')+['up','-d','--force-recreate','--no-build','--pull','never','--no-deps','cms-app']
subprocess.run(cmd,cwd=str(CMS_ROOT/'infra'),check=True)
def cms_image_files(identity):
script="const fs=require('fs'),p=require('path'),c=require('crypto'),r={};for(const d of ['admin','server'])for(const n of fs.readdirSync('/app/'+d)){const f='/app/'+d+'/'+n;if(!fs.lstatSync(f).isFile())throw Error('unexpected runtime path');r[d+'/'+n]=c.createHash('sha256').update(fs.readFileSync(f)).digest('hex')}process.stdout.write(JSON.stringify(r))"
proc=subprocess.run([str(DOCKER),'exec',identity,'node','-e',script],capture_output=True,text=True,check=True,timeout=30)
return json.loads(proc.stdout)
def accept_cms_release(before, *, rollback=False):
cms_healthchecks()
current=cms_runtime_snapshot();old=before['runtime']
if current['configSha256'] != old['configSha256'] or current['imageRef'] != old['imageRef']:
die('CMS environment, mounts, ports or network topology changed')
expected_image=old['imageId'] if rollback else before['builtImageId']
if current['imageId'] != expected_image or (not rollback and current['id']==old['id']):
die('CMS selected service image/generation mismatch')
expected_foundation=before['foundation'] if rollback else {**CMS_FOUNDATION,'infra/.env.synology':before['foundation']['infra/.env.synology']}
if cms_other_services()!=before['otherServices'] or cms_foundation()!=expected_foundation or cms_preserved_data()!=before['data']:
die('CMS release changed preserved applications or project data')
actual=collect_exact_files(CMS_ROOT,('admin','server',*CMS_DEPENDENCY_FILES),'CMS installed app')
if rollback:
if actual!=before['installedFiles']:die('CMS rollback source mismatch')
else:
validate_cms_release_payload(CMS_ROOT,before['entries'],before['descriptor']['releaseId'])
version=subprocess.run([str(DOCKER),'exec',current['id'],'node','-p',"require('adm-zip/package.json').version"],capture_output=True,text=True,check=True,timeout=30).stdout.strip()
if version != '0.6.1':die('CMS running ZIP dependency differs from the qualified version')
if cms_image_files(current['id']) != {k:v for k,v in actual.items() if k not in CMS_DEPENDENCY_FILES}:die('CMS running image differs from accepted source')
print('cms_release_accept='+('rollback' if rollback else before['descriptor']['sourceCommit'])+';services=cms-app;sites-auth-databases-secrets=preserved')
def rollback_cms_release(root, backup_dir, entries, current_stamp, before, runtime_started):
restore_platform_overlay(root,backup_dir,entries,current_stamp)
subprocess.run([str(DOCKER),'image','tag',before['runtime']['imageId'],before['runtime']['imageRef']],check=True)
if runtime_started:run_cms_release_compose()
accept_cms_release(before,rollback=True)
+26
View File
@@ -0,0 +1,26 @@
log:
level: info
runner:
file: /data/.runner
capacity: 1
timeout: 1h
shutdown_timeout: 45m
insecure: false
fetch_interval: 5s
env_file: ""
envs:
NODE_OPTIONS: --max-old-space-size=1536
labels:
- nodedc-node22-build:docker://docker.io/library/node@sha256:9887ee8a5e5aa4fb02e09f03cdf81ef1b52184665549836fe3943eb0c2eaefdb
cache:
enabled: false
container:
network: ""
privileged: false
options: --cpuset-cpus=7 --cpu-shares=128 --memory=2g --memory-swap=2g --cap-drop=ALL --security-opt=no-new-privileges
valid_volumes: []
docker_host: "-"
force_pull: false
bind_workdir: false
metrics:
enabled: false
+74
View File
@@ -0,0 +1,74 @@
import hashlib
from pathlib import Path
import tempfile
import unittest
from unittest import mock
from deployment_queue import DeploymentQueue, QueueError
from controller import Controller
from test_gitea_source import run,A,B,C
class ControllerTests(unittest.TestCase):
def setUp(self):
self.tmp=tempfile.TemporaryDirectory();self.addCleanup(self.tmp.cleanup)
self.path=Path(self.tmp.name)/'queue.db'
self.q=DeploymentQueue(self.path,first_run_number=8);self.addCleanup(self.q.close)
self.s=mock.Mock();self.i=mock.Mock()
self.i.installed_source.return_value=A
self.r=run();self.s.discover.return_value=[self.r];self.s.successful_run.return_value=self.r
self.data=b'archive';self.artifact='nodedc-dc-cms-release-v1-r8-'+B+'.tgz'
self.receipt={'artifact':self.artifact,'sha256':hashlib.sha256(self.data).hexdigest()}
self.s.artifact.return_value=(self.receipt,self.data)
self.i.receipt.return_value=('deployed','canonical:line1')
self.c=Controller(self.q,self.s,self.i)
def test_success_is_reserved_before_apply_and_never_repeated(self):
def apply(a):self.assertEqual(self.q.snapshot()[0]['phase'],'deploying')
self.i.apply.side_effect=apply
self.assertEqual(self.c.tick()['status'],'deployed')
self.assertEqual(self.c.tick()['status'],'waiting')
self.i.apply.assert_called_once_with(self.artifact)
def test_earlier_pending_blocks_newer_ready_but_failed_ci_does_not(self):
pending=run();pending.update(status='in_progress',conclusion=None)
self.s.discover.return_value=[run(9,C),pending]
self.assertEqual(self.c.tick()['status'],'waiting');self.i.apply.assert_not_called()
pending.update(status='completed',conclusion='failure');self.c.observe()
self.assertEqual(self.q.next_ready()['id'],9)
def test_failure_with_clean_rollback_is_terminal(self):
self.i.apply.side_effect=RuntimeError('failure');self.i.receipt.return_value=('rolled-back','failed:line1')
with self.assertRaises(RuntimeError):self.c.tick()
self.assertEqual(self.q.snapshot()[0]['phase'],'failed')
self.assertEqual(self.c.tick()['status'],'waiting');self.assertEqual(self.i.apply.call_count,1)
def test_missing_receipt_blocks_restart(self):
self.i.apply.side_effect=RuntimeError('crash');self.i.receipt.return_value=('ambiguous','missing-receipt')
with self.assertRaises(RuntimeError):self.c.tick()
with self.assertRaises(QueueError):self.c.tick()
self.assertEqual(self.i.apply.call_count,1)
def test_restart_reconciles_success_without_second_apply(self):
self.c.observe();self.q.reserve(8,digest=self.receipt['sha256'],artifact=self.artifact)
self.assertEqual(self.c.tick()['status'],'waiting')
self.i.apply.assert_not_called();self.assertEqual(self.q.snapshot()[0]['phase'],'deployed')
def test_network_or_plan_error_before_reservation_preserves_ready_queue(self):
self.i.plan.side_effect=RuntimeError('network')
with self.assertRaises(RuntimeError):self.c.tick()
self.assertEqual(self.q.snapshot()[0]['phase'],'ready');self.i.apply.assert_not_called()
def test_new_rerun_before_reservation_prevents_apply(self):
pending=run();pending.update(run_attempt=2,status='in_progress',conclusion=None)
self.s.discover.side_effect=[[run()],[pending]]
with self.assertRaises(QueueError):self.c.tick()
self.i.apply.assert_not_called()
def test_disappeared_pending_run_never_skipped(self):
pending=run();pending.update(status='in_progress',conclusion=None)
self.s.discover.return_value=[pending];self.c.observe()
self.s.discover.return_value=[run(9,C)]
with self.assertRaisesRegex(QueueError,'disappeared'):self.c.tick()
self.i.apply.assert_not_called()
if __name__=='__main__':unittest.main()
+138
View File
@@ -0,0 +1,138 @@
import tempfile
from pathlib import Path
import unittest
from deployment_queue import DeploymentQueue, QueueError, REPOSITORY, REPOSITORY_ID
def run(number, *, status="completed", conclusion="success", **updates):
return {"id": number + 100, "run_number": number, "run_attempt": 1,
"head_sha": format(number, "040x"), "event": "push", "head_branch": "master",
"path": "ci.yml@refs/heads/master", "status": status, "conclusion": conclusion, **updates}
class QueueTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.path = Path(self.temp.name) / "queue.db"
self.q = DeploymentQueue(self.path, first_run_number=1)
self.addCleanup(lambda: self.q.close())
def observe(self, *values):
self.q.observe(list(values), repository=REPOSITORY, repository_id=REPOSITORY_ID)
def reserve(self, number):
r = self.q.next_ready()
self.assertEqual(r["number"], number)
return self.q.reserve(r["id"], digest="a"*64,
artifact="nodedc-dc-cms-release-v1-r"+str(r["id"])+"-"+r["sha"]+".tgz")
def finish(self, row, outcome="deployed"):
self.q.reconcile(row["id"], digest=row["digest"], artifact=row["artifact"],
outcome=outcome, receipt="canonical-test-receipt-"+str(row["id"]))
def test_overlapping_pushes_wait_for_older_qualification(self):
self.observe(run(2), run(1, status="in_progress", conclusion=None))
self.assertIsNone(self.q.next_ready())
self.observe(run(1))
self.finish(self.reserve(1))
self.finish(self.reserve(2))
self.assertIsNone(self.q.next_ready())
def test_failed_tests_do_not_deploy_and_next_push_can_proceed(self):
self.observe(run(2), run(1, conclusion="failure"))
self.finish(self.reserve(2))
self.assertEqual(self.q.snapshot()[0]["phase"], "unqualified")
def test_duplicate_observations_and_receipts_are_idempotent(self):
self.observe(run(1), run(1))
row = self.reserve(1)
self.finish(row)
self.finish(row)
self.observe(run(1))
self.assertEqual(len(self.q.snapshot()), 1)
self.assertIsNone(self.q.next_ready())
def test_wrong_branch_event_and_workflow_never_deploy(self):
self.observe(run(1, head_branch="feature"), run(2, event="workflow_dispatch"), run(3, path="other.yml@refs/heads/master"))
self.assertIsNone(self.q.next_ready())
self.assertEqual({r["phase"] for r in self.q.snapshot()}, {"ignored"})
def test_wrong_repository_and_malformed_sha_rejected(self):
for repo, identity in [("other/Device", 38), (REPOSITORY, 39), (REPOSITORY, 33.0)]:
with self.assertRaises(QueueError): self.q.observe([run(1)], repository=repo, repository_id=identity)
with self.assertRaises(QueueError): self.observe(run(1, head_sha="main; execute"))
self.assertEqual(self.q.snapshot(), [])
def test_identity_conflict_rolls_back_entire_observation(self):
self.observe(run(1))
with self.assertRaises(QueueError): self.observe(run(2), run(1, head_sha="b"*40))
self.assertEqual(len(self.q.snapshot()), 1)
def test_restart_preserves_pending_and_requires_reconciliation_for_reserved(self):
self.observe(run(1), run(2))
row = self.reserve(1)
self.q.close()
self.q = DeploymentQueue(self.path, first_run_number=1)
with self.assertRaisesRegex(QueueError, "reconciliation"): self.q.next_ready()
self.finish(row)
self.assertEqual(self.q.next_ready()["number"], 2)
def test_ambiguous_or_failed_rollback_halts_following_deploys(self):
self.observe(run(1), run(2))
self.finish(self.reserve(1), "ambiguous")
with self.assertRaisesRegex(QueueError, "reconciliation"): self.q.next_ready()
def test_clean_rollback_never_retries_same_artifact_but_allows_forward_fix(self):
self.observe(run(1), run(2))
self.finish(self.reserve(1), "rolled-back")
self.observe(run(1, run_attempt=2))
self.assertEqual(self.q.next_ready()["number"], 2)
def test_late_old_run_and_same_source_cannot_downgrade_installed_revision(self):
self.observe(run(5))
self.finish(self.reserve(5))
self.observe(run(4), run(6, head_sha=run(5)["head_sha"]))
self.assertIsNone(self.q.next_ready())
self.assertEqual([r["phase"] for r in self.q.snapshot()], ["superseded", "deployed", "superseded"])
def test_second_controller_cannot_reserve_another_deploy(self):
self.observe(run(1), run(2))
second = DeploymentQueue(self.path, first_run_number=1)
self.addCleanup(second.close)
self.reserve(1)
with self.assertRaises(QueueError): second.next_ready()
def test_wrong_receipt_cannot_close_crashed_deployment(self):
self.observe(run(1))
row = self.reserve(1)
with self.assertRaisesRegex(QueueError, "artifact_mismatch"):
self.q.reconcile(row["id"], digest="b"*64, artifact=row["artifact"], outcome="deployed", receipt="wrong")
with self.assertRaises(QueueError): self.q.next_ready()
def test_activation_floor_is_persistent_and_old_history_is_not_deployed(self):
self.q.close()
self.path = Path(self.temp.name) / "second.db"
self.q = DeploymentQueue(self.path, first_run_number=3)
self.observe(run(1), run(2), run(3))
self.assertEqual(self.q.next_ready()["number"], 3)
with self.assertRaisesRegex(QueueError, "policy_changed"):
DeploymentQueue(self.path, first_run_number=1)
def test_terminal_api_outcome_cannot_change_without_a_new_attempt(self):
self.observe(run(1, conclusion="failure"))
with self.assertRaisesRegex(QueueError, "outcome_changed"): self.observe(run(1))
self.observe(run(1, run_attempt=2))
self.assertEqual(self.q.next_ready()["number"], 1)
def test_large_backlog_of_duplicate_sources_is_iterative(self):
self.observe(run(1))
self.finish(self.reserve(1))
self.observe(*(run(n, head_sha=run(1)["head_sha"]) for n in range(2, 1200)))
self.assertIsNone(self.q.next_ready())
self.assertEqual(len(self.q.snapshot()), 1199)
if __name__ == "__main__":
unittest.main()
+108
View File
@@ -0,0 +1,108 @@
from contextlib import ExitStack,redirect_stdout,redirect_stderr
import hashlib
import io
import tarfile
from pathlib import Path
import tempfile
import unittest
from unittest.mock import patch
from test_runner import r,ROOT,fixture
from build_autodeploy import bundle
from embed_runtime import section,START,END
class CmsBootstrapDispatchTests(unittest.TestCase):
def test_exact_embedded_policy(self):
source=Path(r.__file__).read_text()
self.assertEqual(START+source.split(START,1)[1].split(END,1)[0]+END,section())
q,s,c,e=r.cms_autodeploy_library()
with tempfile.TemporaryDirectory() as d:
queue=q(Path(d)/'queue',first_run_number=1);self.assertIsNone(queue.next_ready());queue.close()
def test_archive_and_scope(self):
identity,data=bundle();self.assertEqual(data,bundle()[1])
with tempfile.TemporaryDirectory() as d:
root=Path(d);a=root/'a.tgz';a.write_bytes(data);work=root/'work';work.mkdir()
m,e,p=r.load_artifact(a,work)
self.assertEqual(m['id'],identity);self.assertEqual(tuple(e),r.CMS_AUTODEPLOY_ENTRIES)
self.assertEqual(r.component_services(m['component'],e),('build-runner',))
self.assertEqual(r.component_builds(m['component'],e),())
def test_unactivated_worker_never_reads_secret(self):
with patch.object(r,'require_root'),patch.object(r,'ensure_layout'),patch.object(r,'cms_autodeploy_activated',return_value=False),patch.object(r,'cms_autodeploy_read_token') as read:
self.assertEqual(r.cms_autodeploy_tick(),0);read.assert_not_called()
def execute(self,fail=False):
with tempfile.TemporaryDirectory() as d,ExitStack() as stack:
root=Path(d);live=root/'live';identity,data=bundle();events=[]
for name in ('inbox','applied','failed','backups','state','tmp'):(root/name).mkdir()
artifact=root/'inbox/bootstrap.tgz';artifact.write_bytes(data)
for name,value in [('INBOX',root/'inbox'),('APPLIED_DIR',root/'applied'),('FAILED_DIR',root/'failed'),('BACKUPS_DIR',root/'backups'),('STATE_DIR',root/'state'),('TMP_DIR',root/'tmp'),('STATE_FILE',root/'state/applied.jsonl'),('FAILED_STATE_FILE',root/'state/failed.jsonl'),('LOCK_DIR',root/'lock')]:stack.enter_context(patch.object(r,name,value))
stack.enter_context(patch.dict(r.COMPONENTS,{'dc-cms-autodeploy':{**r.COMPONENTS['dc-cms-autodeploy'],'payload_root':live,'compose_root':live,'compose_files':(live/'docker-compose.cms-ci.yml',)}}))
for name in ('require_root','ensure_layout','validate_artifact_location'):stack.enter_context(patch.object(r,name))
stack.enter_context(patch.object(r,'preflight_cms_autodeploy',return_value={'baseline':'test'}))
stack.enter_context(patch.object(r,'apply_cms_autodeploy',side_effect=lambda b:events.append('install')))
def accept(before):
events.append('accept')
if fail:raise r.DeployError('injected')
def rollback(target,backup,entries,stamp,before):
events.append('rollback');r.restore_platform_overlay(target,backup,entries,stamp)
stack.enter_context(patch.object(r,'accept_cms_autodeploy',side_effect=accept))
stack.enter_context(patch.object(r,'rollback_cms_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(artifact)
else:r.apply_artifact(artifact)
return events,r.load_state(r.STATE_FILE),r.load_state(r.FAILED_STATE_FILE)
def test_canonical_success_receipt_follows_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(bundle()[1]).hexdigest())
def test_canonical_failure_uses_cms_rollback(self):
events,applied,failed=self.execute(True)
self.assertEqual(events,['install','accept','rollback']);self.assertFalse(applied)
self.assertEqual(failed[0]['rollback_status'],'ok:dc-cms-autodeploy-bootstrap')
def test_application_dispatch_success_and_failed_build_or_acceptance(self):
for failure in (None,'build','accept'):
with self.subTest(failure=failure),tempfile.TemporaryDirectory() as d,ExitStack() as stack:
root=Path(d);payload=root/'payload';payload.mkdir();entries,descriptor=fixture(payload)
live=root/'live';live.mkdir();fixture(live)
(live/'server/admin-server.mjs').write_bytes(b'// predecessor')
installed=r.collect_exact_files(live,entries,'test')
before={'runtime':{'imageId':'old-id','imageRef':'dc-cms-cms-app'},'descriptor':descriptor,'entries':entries,'installedFiles':installed}
for name in ('inbox','applied','failed','backups','state','tmp'):(root/name).mkdir()
artifact=root/'inbox/app.tgz'
members={'manifest.env':f"id={descriptor['releaseId']}\ncomponent=dc-cms-release\ntype=app-overlay\n".encode(),'files.txt':('\n'.join(entries)+'\n').encode(),**{'payload/'+p:(payload/p).read_bytes() for p in entries}}
with tarfile.open(artifact,'w:gz') as archive:
for name,value in members.items():
info=tarfile.TarInfo(name);info.size=len(value);info.mode=0o644;archive.addfile(info,io.BytesIO(value))
compose=live/'compose.yml';compose.write_text('fixture');events=[]
for name,value in [('INBOX',root/'inbox'),('APPLIED_DIR',root/'applied'),('FAILED_DIR',root/'failed'),('BACKUPS_DIR',root/'backups'),('STATE_DIR',root/'state'),('TMP_DIR',root/'tmp'),('STATE_FILE',root/'state/applied.jsonl'),('FAILED_STATE_FILE',root/'state/failed.jsonl'),('LOCK_DIR',root/'lock')]:stack.enter_context(patch.object(r,name,value))
stack.enter_context(patch.dict(r.COMPONENTS,{'dc-cms-release':{**r.COMPONENTS['dc-cms-release'],'payload_root':live,'compose_root':live,'compose_files':(compose,),'compose_env_file':None}}))
for name in ('require_root','ensure_layout','validate_artifact_location'):stack.enter_context(patch.object(r,name))
stack.enter_context(patch.object(r,'preflight_cms_release',return_value=before))
def operation(name):
def call(*args,**kwargs):
events.append(name)
if name==failure:raise r.DeployError('injected '+name)
return call
stack.enter_context(patch.object(r,'build_cms_release',side_effect=operation('build')))
stack.enter_context(patch.object(r,'run_cms_release_compose',side_effect=operation('compose')))
stack.enter_context(patch.object(r,'run_healthchecks',side_effect=operation('health')))
def accept(b,rollback=False):
if rollback:
events.append('rollback-accept');self.assertEqual(r.collect_exact_files(live,entries,'restored'),installed)
else:operation('accept')()
stack.enter_context(patch.object(r,'accept_cms_release',side_effect=accept))
stack.enter_context(patch.object(r.subprocess,'run',side_effect=operation('tag')))
stack.enter_context(redirect_stdout(io.StringIO()));stack.enter_context(redirect_stderr(io.StringIO()))
if failure:
with self.assertRaises(r.DeployError):r.apply_artifact(artifact)
self.assertEqual(r.load_state(r.FAILED_STATE_FILE)[0]['rollback_status'],'ok:dc-cms-release')
self.assertFalse(r.load_state(r.STATE_FILE));self.assertEqual(events[-1],'rollback-accept')
else:
r.apply_artifact(artifact);self.assertEqual(events,['build','compose','health','accept']);self.assertEqual(len(r.load_state(r.STATE_FILE)),1)
if __name__=='__main__':unittest.main()
+136
View File
@@ -0,0 +1,136 @@
"""Untrusted API/ZIP boundaries and complete source lineage."""
import copy
import hashlib
import io
import json
import stat
import unittest
from unittest import mock
import zipfile
import urllib.request
from deployment_queue import REPOSITORY, REPOSITORY_ID, WORKFLOW
from gitea_source import GiteaSource, SourceError, NoRedirect, strict_json, unpack_artifact
A, B, C = 'a'*40, 'b'*40, 'c'*40
def run(number=8, sha=B):
return dict(id=number, run_number=number, run_attempt=1, head_sha=sha,
event='push', head_branch='master', path=WORKFLOW, status='completed', conclusion='success',
repository={'id':33, 'full_name':REPOSITORY})
def job(r):
return dict(id=8, run_id=r['id'], head_sha=r['head_sha'], head_branch='master', run_attempt=1,
name='qualify', labels=['nodedc-node22-build'], runner_id=1, status='completed', conclusion='success',
steps=[dict(name=n,status='completed',conclusion='success') for n in
('Check the exact pushed commit','Retain the qualified release in this Gitea run')])
def packed(r, mutate=None, names=None):
name='nodedc-dc-cms-release-v1-r'+str(r['id'])+'-'+r['head_sha']+'.tgz'
data=b'qualified tgz fixture'
receipt=dict(artifact=name,sourceCommit=r['head_sha'],runId=r['id'],runNumber=r['run_number'],
deployed=False,sha256=hashlib.sha256(data).hexdigest())
if mutate:mutate(receipt)
out=io.BytesIO()
with zipfile.ZipFile(out,'w') as z:
z.writestr(name,data)
z.writestr('release.json',json.dumps(receipt))
for n in names or []:z.writestr(n,b'extra')
return out.getvalue()
class SourceTests(unittest.TestCase):
def setUp(self):self.s=GiteaSource('a'*40)
def test_no_redirects_or_unapproved_routes(self):
with self.assertRaises(SourceError):NoRedirect().redirect_request(None,None,302,'',{},'https://other/')
for path in ['/../../user','/actions/runs?token=a','//user','/branches/other','/actions/artifacts/1/zip%3f']:
with self.subTest(path=path),self.assertRaises(SourceError):self.s.request(path)
def test_observed_signed_download_redirect_strips_persistent_token(self):
url='https://git.dcserve.ru/api/v1/repos/SILVER/DC_CMS/actions/artifacts/6/zip'
target=url+'/raw?sig='+'a'*43+'&expires=1790708000'
req=urllib.request.Request(url,headers={'Authorization':'token '+'b'*40})
redirected=NoRedirect().redirect_request(req,None,302,'',{},target)
self.assertIsNone(redirected.get_header('Authorization'))
self.assertEqual(redirected.full_url,target)
for bad in [target.replace('git.dcserve.ru','example.com'),target.replace('/6/','/7/'),
target+'&extra=1',target+'&sig='+'c'*43,target.replace('https:','http:')]:
with self.subTest(url=bad),self.assertRaises(SourceError):NoRedirect().redirect_request(req,None,302,'',{},bad)
with self.assertRaises(SourceError):NoRedirect().redirect_request(redirected,None,302,'',{},target)
def test_duplicate_json_keys_and_token_format(self):
for value in [b'{"id":1,"id":2}',b'invalid',b'\xff']:
with self.assertRaises(SourceError):strict_json(value)
for token in ['', 'A'*40,'a'*40+'\n','secret']:
with self.assertRaises(SourceError):GiteaSource(token)
def test_paginated_complete_unique(self):
with mock.patch.object(self.s,'request',side_effect=[dict(total_count=51,items=[dict(id=n) for n in range(1,51)]),dict(total_count=51,items=[dict(id=51)])]) as get:
self.assertEqual(len(self.s.pages('/actions/runs','items')),51)
self.assertEqual(get.call_args.args[0],'/actions/runs?page=2&limit=50')
def test_partial_changed_and_duplicate_pages_fail(self):
scenarios=[
[dict(total_count=2,items=[dict(id=1)])],
[dict(total_count=2,items=[dict(id=1),dict(id=1)])],
[dict(total_count=True,items=[])],
[dict(total_count=51,items=[dict(id=n) for n in range(1,51)]),dict(total_count=50,items=[])],
]
for pages in scenarios:
with self.subTest(pages=len(pages)),mock.patch.object(self.s,'request',side_effect=pages),self.assertRaises(SourceError):self.s.pages('/actions/runs','items')
def test_run_nested_repository_identity_not_broken_top_level_field(self):
r=run();r['repository_id']=0;self.s.validate_run(r)
r['repository']['id']=39
with self.assertRaises(SourceError):self.s.validate_run(r)
def test_discovery_rejects_change_between_complete_scans(self):
with mock.patch.object(self.s,'repository'),mock.patch.object(self.s,'pages',side_effect=[[run()],[run(),run(9,C)]]),self.assertRaises(SourceError):self.s.discover()
def test_discovery_allows_status_progress_without_loss(self):
pending=run();pending.update(status='in_progress',conclusion=None)
with mock.patch.object(self.s,'repository'),mock.patch.object(self.s,'pages',side_effect=[[pending],[run()]]):self.assertEqual(self.s.discover(),[run()])
def test_success_must_have_exact_job_and_steps(self):
r=run();row=dict(id=8,number=8,sha=B,attempt=1)
with mock.patch.object(self.s,'run',return_value=r),mock.patch.object(self.s,'pages',return_value=[job(r)]):self.assertEqual(self.s.successful_run(row),r)
for field,value in [('runner_id',2),('labels',['ubuntu-latest']),('steps',[]),('head_sha',A),('conclusion','failure')]:
j=job(r);j[field]=value
with mock.patch.object(self.s,'run',return_value=r),mock.patch.object(self.s,'pages',return_value=[j]),self.assertRaises(SourceError):self.s.successful_run(row)
def test_ancestry_proves_both_edges_and_stable_main(self):
graph={C:[B],B:[A],A:[]}
def get(path):
sha=path.rsplit('/',1)[1]
return dict(sha=sha,parents=[dict(sha=p) for p in graph[sha]])
with mock.patch.object(self.s,'request',side_effect=get),mock.patch.object(self.s,'main_commit',return_value=C):
self.assertEqual(self.s.prove_lineage(A,B),C)
with self.assertRaises(SourceError):self.s.prove_lineage(B,A)
with self.assertRaises(SourceError):self.s.prove_lineage(B,B)
with mock.patch.object(self.s,'ancestor',return_value=True),mock.patch.object(self.s,'main_commit',side_effect=[B,C]),self.assertRaises(SourceError):self.s.prove_lineage(A,B)
def test_ancestry_malformed_and_bound(self):
with mock.patch.object(self.s,'request',return_value=dict(sha=B,parents=[dict(sha=C)])),self.assertRaisesRegex(SourceError,'ancestry_limit'):self.s.ancestor(A,B,limit=1)
with mock.patch.object(self.s,'request',return_value=dict(sha=C,parents=[])),self.assertRaisesRegex(SourceError,'commit_identity'):self.s.ancestor(A,B)
def test_zip_requires_exact_receipt_and_only_two_files(self):
r=run();receipt,data=unpack_artifact(packed(r),r)
self.assertEqual(receipt['sha256'],hashlib.sha256(data).hexdigest())
for change in [lambda d:d.update(sourceCommit=A),lambda d:d.update(deployed=True),lambda d:d.update(sha256='f'*64),lambda d:d.update(extra='value')]:
with self.assertRaises(SourceError):unpack_artifact(packed(r,change),r)
for name in ['../../script','runtime/token','.DS_Store']:
with self.assertRaises(SourceError):unpack_artifact(packed(r,names=[name]),r)
with self.assertRaises(SourceError):unpack_artifact(b'bad zip',r)
def test_artifact_owner_download_digest_bound_to_run(self):
r=run();blob=packed(r)
a=dict(id=8,name='dc-cms-release',workflow_run=dict(id=8,repository_id=33,head_sha=B),expired=False,size_in_bytes=len(blob))
with mock.patch.object(self.s,'pages',return_value=[a]),mock.patch.object(self.s,'request',return_value=blob):self.assertEqual(self.s.artifact(r)[0]['sourceCommit'],B)
a['workflow_run']['repository_id']=39
with mock.patch.object(self.s,'pages',return_value=[a]),self.assertRaises(SourceError):self.s.artifact(r)
if __name__=='__main__':unittest.main()
+94
View File
@@ -0,0 +1,94 @@
import ast
import importlib.machinery
import importlib.util
import io
import json
from pathlib import Path
import subprocess
import tarfile
import tempfile
import unittest
from unittest.mock import patch
ROOT=Path(__file__).resolve().parents[2]
RUNNER=ROOT/'infra/deploy-runner/nodedc-deploy'
loader=importlib.machinery.SourceFileLoader('cms_runner',str(RUNNER))
spec=importlib.util.spec_from_loader(loader.name,loader)
r=importlib.util.module_from_spec(spec);loader.exec_module(r)
def fixture(root):
files={p:b'// fixture' for p in ('admin/index.html','admin/admin.js','admin/admin.css','admin/nodedc-logo.svg','server/admin-server.mjs','server/site-app.mjs','server/multisite-server.mjs')}
for p in r.CMS_DEPENDENCY_FILES:files[p]=(ROOT/'infra/cms-deploy/fixtures'/p).read_bytes()
d={'schemaVersion':'nodedc.dc-cms.release.v1','releaseId':'dc-cms-release-v1-r1-'+'a'*40,'repository':'SILVER/DC_CMS','repositoryId':33,'branch':'master','sourceCommit':'a'*40,'runId':1,'runNumber':1,'qualification':{'status':'qualified','steps':['frozen-install','syntax','multisite-tests'],'deployed':False},'foundationSha256':{k:v for k,v in r.CMS_FOUNDATION.items() if k!='infra/reverse-proxy/Caddyfile'},'filesSha256':{p:r.hashlib.sha256(v).hexdigest() for p,v in files.items()}}
files[r.CMS_RELEASE_ENTRY]=(json.dumps(d)+'\n').encode()
for p,data in files.items():
(root/p).parent.mkdir(parents=True,exist_ok=True);(root/p).write_bytes(data)
return sorted(files),d
class CmsRunnerTests(unittest.TestCase):
def test_fixed_scope(self):
with tempfile.TemporaryDirectory() as tmp:
entries,d=fixture(Path(tmp))
self.assertEqual(r.component_services('dc-cms-release',entries),('cms-app',))
self.assertEqual(r.validate_cms_release_payload(Path(tmp),entries,d['releaseId']),d)
for path in ('projects/nodedc.json','server/data/a.js','server/.env','admin/uploads/a.js','admin/../server/a.js','Dockerfile','infra/docker-compose.yml','server/cms-release.json/extra'):
with self.subTest(path=path),self.assertRaises(r.DeployError):r.allowed_payload_path('dc-cms-release',path)
self.assertEqual(r.component_services('dc-cms-autodeploy',r.CMS_AUTODEPLOY_ENTRIES),('build-runner',))
def test_descriptor_identity_foundation_and_digest(self):
for key,value in [('repositoryId',38),('branch','main'),('runId',True),('sourceCommit','short'),('filesSha256',{}),('foundationSha256',{}),('qualification',{'status':'qualified'})]:
with self.subTest(key=key),tempfile.TemporaryDirectory() as tmp:
root=Path(tmp);entries,d=fixture(root);identity=d['releaseId'];d[key]=value
(root/r.CMS_RELEASE_ENTRY).write_text(json.dumps(d))
with self.assertRaises(r.DeployError):r.validate_cms_release_payload(root,entries,identity)
def test_bootstrap_descriptor_exact_bytes(self):
with tempfile.TemporaryDirectory() as tmp:
root=Path(tmp);p=root/r.CMS_AUTODEPLOY_ENTRY;p.parent.mkdir()
for name in r.CMS_CI_SOURCE_SHA256:(root/name).write_bytes((ROOT/'infra/cms-deploy'/name).read_bytes())
p.write_text(json.dumps(r.CMS_AUTODEPLOY_DESCRIPTOR,indent=2,sort_keys=True)+'\n')
r.validate_cms_autodeploy_payload(root,r.CMS_AUTODEPLOY_ENTRIES,r.CMS_AUTODEPLOY_ID)
p.write_text(p.read_text()+' ')
with self.assertRaises(r.DeployError):r.validate_cms_autodeploy_payload(root,r.CMS_AUTODEPLOY_ENTRIES,r.CMS_AUTODEPLOY_ID)
self.assertEqual(r.CMS_AUTODEPLOY_DESCRIPTOR['repositoryId'],33)
self.assertEqual(r.CMS_AUTODEPLOY_DESCRIPTOR['branch'],'master')
self.assertIn('--dc-cms-autodeploy-tick',r.cms_autodeploy_units()[r.CMS_AUTODEPLOY_SERVICE])
self.assertEqual(r.CMS_AUTODEPLOY_DESCRIPTOR['publishedPorts'],[])
def test_build_context_excludes_projects_and_credentials(self):
with tempfile.TemporaryDirectory() as tmp:
root=Path(tmp);entries,_=fixture(root)
for name in ('Dockerfile','package.json','package-lock.json'):(root/name).write_text('fixture')
(root/'projects/sites').mkdir(parents=True);(root/'projects/secret.json').write_text('never copy')
before={'entries':entries,'runtime':{'imageRef':'dc-cms-cms-app'}}
def build(cmd,**kwargs):
context=Path(cmd[-1]);self.assertEqual(list((context/'projects').iterdir()),[])
self.assertEqual(set(p.relative_to(context).as_posix() for p in context.rglob('*') if p.is_file()),set(entries)|{'Dockerfile','package.json','package-lock.json'})
self.assertEqual(cmd[:2],[str(r.DOCKER),'build'])
with patch.object(r,'CMS_ROOT',root),patch.object(r,'TMP_DIR',root),patch.object(r.subprocess,'run',side_effect=build),patch.object(r,'docker_json',return_value=[{'Id':'sha256:built'}]):
r.build_cms_release(before)
self.assertEqual(before['builtImageId'],'sha256:built')
def test_no_dependency_recreation_or_rollback_rebuild(self):
with patch.object(r.subprocess,'run') as run:
r.run_cms_release_compose()
cmd=run.call_args.args[0]
self.assertEqual(cmd[-8:],['up','-d','--force-recreate','--no-build','--pull','never','--no-deps','cms-app'])
before={'runtime':{'imageId':'old-id','imageRef':'dc-cms-cms-app'}}
with patch.object(r,'restore_platform_overlay') as restore,patch.object(r.subprocess,'run') as run,patch.object(r,'run_cms_release_compose') as compose,patch.object(r,'accept_cms_release') as accept:
r.rollback_cms_release('root','backup',[], 'stamp',before,True)
restore.assert_called_once();compose.assert_called_once();accept.assert_called_once_with(before,rollback=True)
self.assertEqual(run.call_args.args[0],[str(r.DOCKER),'image','tag','old-id','dc-cms-cms-app'])
def test_existing_device_domain_unchanged(self):
old=subprocess.check_output(['git','show','27c155276a703dd4fd39385011fc5e3f86afcae4:infra/deploy-runner/nodedc-deploy'],cwd=ROOT,text=True)
current=RUNNER.read_text()
def domain(source):return source[source.index('# Device Core outbound automatic deployment.'):source.index('# END GENERATED DEVICE CORE AUTODEPLOY LIBRARY')]
self.assertEqual(domain(old),domain(current))
allowed={'allowed_payload_path','load_artifact','component_services','plan_artifact','apply_artifact','run_healthchecks','main'}
old_functions={n.name:ast.dump(n,include_attributes=False) for n in ast.parse(old).body if isinstance(n,(ast.FunctionDef,ast.ClassDef))}
current_functions={n.name:ast.dump(n,include_attributes=False) for n in ast.parse(current).body if isinstance(n,(ast.FunctionDef,ast.ClassDef))}
for name,node in old_functions.items():
if name not in allowed:self.assertEqual(current_functions[name],node,name)
if __name__=='__main__':unittest.main()