diff --git a/infra/deploy-runner/nodedc-deploy b/infra/deploy-runner/nodedc-deploy index c0bb214..f463907 100755 --- a/infra/deploy-runner/nodedc-deploy +++ b/infra/deploy-runner/nodedc-deploy @@ -2962,6 +2962,21 @@ GITEA_SALVAGE_UNSUPPORTED_SCHEMA_TABLES = tuple( ) COMPONENTS = { + "dc-cms-release": { + "payload_root": Path("/volume1/docker/dc-cms/source"), + "compose_root": Path("/volume1/docker/dc-cms/source/infra"), + "compose_project": "dc-cms", + "compose_env_file": Path("/volume1/docker/dc-cms/source/infra/.env.synology"), + "compose_files": (Path("/volume1/docker/dc-cms/source/infra/docker-compose.yml"),), + "compose_no_deps": True, "services": ("cms-app",), + }, + "dc-cms-autodeploy": { + "payload_root": Path("/volume1/docker/nodedc-cms-autodeploy"), + "bootstrap_root": True, "compose_root": Path("/volume1/docker/nodedc-cms-autodeploy"), + "compose_project": "nodedc-cms-ci", "compose_no_deps": True, + "compose_files": (Path("/volume1/docker/nodedc-cms-autodeploy/docker-compose.cms-ci.yml"),), + "services": ("build-runner",), + }, "device-b2-shared-contours": { "payload_root": DEVICE_PLANE_ROOT, "artifact_only": True, "services": (), }, @@ -4993,6 +5008,11 @@ def denied_payload_path(component, rel): def allowed_payload_path(component, rel): + if component == "dc-cms-release": + return cms_release_path(rel, directory=True) + if component == "dc-cms-autodeploy": + if rel in ("deployment", *CMS_AUTODEPLOY_ENTRIES): return True + die("CMS autodeploy accepts only its fixed descriptor") validate_posix_path(rel) if component == "device-b2-shared-contours": if rel in ("deployment", *DEVICE_B2_SHARED_ENTRIES): @@ -11646,6 +11666,10 @@ def load_artifact(artifact, work_dir): validate_device_b2_payload(payload_dir, entries, manifest["id"]) if manifest["component"] == "device-core-network-priority": validate_device_priority_payload(payload_dir, entries, manifest["id"]) + if manifest["component"] == "dc-cms-release": + validate_cms_release_payload(payload_dir, entries, manifest["id"]) + if manifest["component"] == "dc-cms-autodeploy": + validate_cms_autodeploy_payload(payload_dir, entries, manifest["id"]) if manifest["component"] == "device-core-autodeploy": validate_device_autodeploy_payload(payload_dir, entries, manifest["id"]) if manifest["component"] == "device-core-release-drift-audit": @@ -22502,6 +22526,12 @@ def is_platform_provider_catalog_only(entries): def component_services(component, entries=None): + if component == "dc-cms-release": + cms_release_entries(entries) + return CMS_RELEASE_SERVICES + if component == "dc-cms-autodeploy": + if tuple(entries or ()) != CMS_AUTODEPLOY_ENTRIES: die("CMS bootstrap requires its exact descriptor and CI configuration") + return ("build-runner",) if component == "device-b2-shared-contours": if tuple(entries or ()) != DEVICE_B2_SHARED_ENTRIES: die("Device B2 shared contours requires all three exact entries") @@ -33365,6 +33395,15 @@ def plan_artifact(artifact): print("device_network_priority_delta=core-private:100,manager-private:100;secondary:0") print("device_network_priority_source=accepted-r12;services=none;build=none;runtime-mutation=none") print("device_network_priority_preserved=all-runtime,databases,volumes,ports,secrets;rollback=two-new-files-only") + if manifest["component"] == "dc-cms-release": + cms_before = preflight_cms_release(payload_dir, entries, manifest["id"]) + print("cms_release_source=" + cms_before["descriptor"]["sourceCommit"]) + print("cms_release_scope=cms-app-only;no-deps;isolated-build-context;rollback=exact-old-image") + print("cms_release_preserved=sites,projects,secrets,authentik,databases,ports,mounts,networks") + if manifest["component"] == "dc-cms-autodeploy": + preflight_cms_autodeploy(payload_dir, entries, manifest["id"]) + print("cms_autodeploy_scope=repo33;branch=master;first-run=1;outbound-https;new-ports=none") + print("cms_autodeploy_scheduler=native-systemd;queue=root-private;existing-read-identity;installer=canonical-runner") if manifest["component"] == "device-core-autodeploy": auto_before = preflight_device_autodeploy(payload_dir, entries, manifest["id"]) print("device_autodeploy_scheduler=native-systemd;binary=" + auto_before["systemctl"]) @@ -39550,6 +39589,10 @@ process.stdout.write('engine-l2-closed-loop:0.7.0:cas+safe-profile+external-plan def run_healthchecks(component, entries=None, services=None): + if component in ("dc-cms-release", "dc-cms-autodeploy"): + if tuple(services or ()) != component_services(component, entries): die("CMS health service scope mismatch") + if component == "dc-cms-release": cms_healthchecks() + return if component == "device-b2-shared-contours": if tuple(entries or ()) != DEVICE_B2_SHARED_ENTRIES or tuple(services or ()) != (): die("Device B2 shared contours health scope mismatch") @@ -40696,6 +40739,8 @@ def apply_artifact(artifact): device_release_before = None gitea_actions_before = None device_autodeploy_before = None + cms_release_before = None + cms_autodeploy_before = None device_priority_before = None device_b2_before = None device_b2_shared_before = None @@ -40761,6 +40806,10 @@ def apply_artifact(artifact): preflight_device_release_reconciliation(payload_dir, entries, patch_id) if component == "device-core-release": device_release_before = preflight_device_release(payload_dir, entries, patch_id) + if component == "dc-cms-release": + cms_release_before = preflight_cms_release(payload_dir, entries, patch_id) + if component == "dc-cms-autodeploy": + cms_autodeploy_before = preflight_cms_autodeploy(payload_dir, entries, patch_id) if component == "device-core-autodeploy": device_autodeploy_before = preflight_device_autodeploy(payload_dir, entries, patch_id) artifact_only = component_artifact_only(component) @@ -41298,6 +41347,10 @@ def apply_artifact(artifact): proof = backup_dir / "device-network-priority-before.json" proof.write_text(json.dumps(device_priority_before, sort_keys=True) + "\n", encoding="utf-8") proof.chmod(0o600) + if component in ("dc-cms-release", "dc-cms-autodeploy"): + proof = backup_dir / "cms-runtime-before.json" + proof.write_text(json.dumps(cms_release_before or cms_autodeploy_before, sort_keys=True) + "\n", encoding="utf-8") + proof.chmod(0o600) if component == "device-core-autodeploy": proof = backup_dir / "autodeploy-before.json" proof.write_text(json.dumps(device_autodeploy_before, sort_keys=True) + "\n", encoding="utf-8") @@ -41397,6 +41450,13 @@ def apply_artifact(artifact): run_build(component, entries) runtime_started = True run_device_release_compose(services, entries) + elif component == "dc-cms-release": + build_cms_release(cms_release_before) + runtime_started = True + run_cms_release_compose() + elif component == "dc-cms-autodeploy": + runtime_started = True + apply_cms_autodeploy(cms_autodeploy_before) elif component == "device-core-autodeploy": runtime_started = True apply_device_autodeploy(device_autodeploy_before) @@ -41455,6 +41515,10 @@ def apply_artifact(artifact): accept_device_b2(device_b2_before, backup_dir) if component == "device-core-network-priority": accept_device_priority(device_priority_before) + if component == "dc-cms-release": + accept_cms_release(cms_release_before) + if component == "dc-cms-autodeploy": + accept_cms_autodeploy(cms_autodeploy_before) if component == "device-core-autodeploy": accept_device_autodeploy(device_autodeploy_before) if component == "device-core-release": @@ -41552,6 +41616,18 @@ def apply_artifact(artifact): rollback_status = "ok:device-core-network-priority-metadata-only" except Exception as rollback_exc: rollback_status = "failed:" + type(rollback_exc).__name__ + elif component == "dc-cms-release": + try: + rollback_cms_release(root, backup_dir, entries, current_stamp, cms_release_before, runtime_started) + rollback_status = "ok:dc-cms-release" + except Exception as rollback_exc: + rollback_status = "failed:" + type(rollback_exc).__name__ + elif component == "dc-cms-autodeploy": + try: + rollback_cms_autodeploy(root, backup_dir, entries, current_stamp, cms_autodeploy_before) + rollback_status = "ok:dc-cms-autodeploy-bootstrap" + except Exception as rollback_exc: + rollback_status = "failed:" + type(rollback_exc).__name__ elif component == "device-core-autodeploy": try: rollback_device_autodeploy(root, backup_dir, entries, current_stamp, device_autodeploy_before) @@ -42835,7 +42911,1367 @@ def device_autodeploy_library(): # END GENERATED DEVICE CORE AUTODEPLOY LIBRARY +# BEGIN GENERATED CMS DEPLOYMENT +# 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 = {'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'} +CMS_FOUNDATION = {'Dockerfile': 'ccb783bd76b1588cbe0157bd317f6da06888d79f8a199fd0c5515000948acd42', 'infra/docker-compose.yml': 'abb3a9d4e4e2ce15eb2ca52b335289dcd00808d85c78da6d1bc583a8b3517f48', 'infra/reverse-proxy/Caddyfile': '4d30188eb1f11b52a0eaf2d9476e0b0adda93a63e66938e8028cc11de4c2038f', 'package-lock.json': 'aca65991c748c6e39b6cbc50405ab5a2bc7bb0d5d1b56a5a4c68bce5f645e47c', 'package.json': '40ee5bc4cf6b634612efa1fc293f6ab1955ee4520701a5dee7c8990fb5ad5fa2'} +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) + +# 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 = {'docker-compose.cms-ci.yml': '9c6b6bf2a9da2f7d5097b8d110882da1587b4d49018aba5ccf258a0218b351c2', 'runner.yaml': '94d8e4d8345b2b5bc7c8923bff7c31ff59083ec7115d633af10152b93bcd9da6'} + +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()) + +# 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) + + + +def cms_autodeploy_library(): + """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")] + + """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 + + + + 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 + + """One polling cycle with an injected canonical installer, no shell authority.""" + + + 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']} + + return DeploymentQueue, GiteaSource, Controller, (QueueError, SourceError) +# END GENERATED CMS DEPLOYMENT + def main(argv): + if argv == ["--dc-cms-autodeploy-tick"]: + return cms_autodeploy_tick() if argv == ["--device-core-autodeploy-tick"]: return device_autodeploy_tick() if sys.version_info < (3, 8):