# DC CMS outbound automatic deployment. All authority stays in this file. CMS_AUTODEPLOY_ID = 'dc-cms-autodeploy-v1-20261104-002' 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 cms_r39_reconciled(record): return 'rolled-back', 'canonical-reconciled:' + CMS_RECON_ID 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_error_status(error, policy_errors): result={'status':'attention','errorType':type(error).__name__} if isinstance(error,policy_errors):result['reason']=str(error)[:200] # Only fixed CMS codes are added. External stderr/raw exception text stays # private, even if a caller mutates the exception's message or code. if isinstance(error,CmsBuildBaseError) and error.code in CMS_BUILD_BASE_ERROR_CODES: result['reason']=error.code diagnostic=cms_base_public_diagnostic(error.diagnostic) if diagnostic is not None:result['baseLookup']=diagnostic return result 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,runner_id=cms_ci_registered_runner_id()),CmsAutodeployInstaller()).tick() except Exception as error: result = cms_autodeploy_error_status(error,errors) finally: queue.close() cms_autodeploy_publish_status(result) return 0 if result['status'] != 'attention' else 1 finally: os.close(fd)