# 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)