415 lines
24 KiB
Python
415 lines
24 KiB
Python
# 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_without_synology_metadata(files, label):
|
|
"""Partition only NAS EA streams attached to a present application file.
|
|
|
|
Synology exposes these files to POSIX but hides them from SMB. They are
|
|
never application payload or build input. Unknown paths remain rejected.
|
|
"""
|
|
application = {}
|
|
metadata = {}
|
|
for rel, digest in files.items():
|
|
parts = PurePosixPath(rel).parts
|
|
if '@eaDir' not in parts:
|
|
application[rel] = digest
|
|
continue
|
|
if (len(parts) != 3 or parts[0] not in ('admin', 'server')
|
|
or parts[1] != '@eaDir' or not parts[2].endswith('@SynoEAStream')):
|
|
die(label + ' has an unrecognized Synology metadata path: ' + rel)
|
|
sibling = parts[0] + '/' + parts[2][:-len('@SynoEAStream')]
|
|
cms_release_path(sibling)
|
|
if sibling not in files:
|
|
die(label + ' has orphaned Synology metadata: ' + rel)
|
|
metadata[rel] = digest
|
|
return application, metadata
|
|
|
|
|
|
def cms_application_inventory():
|
|
files = collect_exact_files(CMS_ROOT, ('admin', 'server', *CMS_DEPENDENCY_FILES), 'CMS installed app')
|
|
return cms_without_synology_metadata(files, 'CMS installed app')
|
|
|
|
|
|
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:') and not cms_r39_reconciled(row)):
|
|
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}}
|
|
actual, _ = cms_application_inventory()
|
|
if actual != expected:
|
|
delta = {'missing':sorted(set(expected)-set(actual)), 'unexpected':sorted(set(actual)-set(expected)),
|
|
'changed':sorted(p for p in set(actual)&set(expected) if actual[p]!=expected[p])}
|
|
die('CMS installed application differs from its canonical predecessor: ' + json.dumps(delta, sort_keys=True))
|
|
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 cms_image_env(config):
|
|
# Values remain in process memory. Reject ambiguous duplicate keys.
|
|
values=config.get('Env')
|
|
if not isinstance(values,list):die('CMS image environment is missing')
|
|
result={}
|
|
for value in values:
|
|
if not isinstance(value,str) or '=' not in value or '\0' in value:
|
|
die('CMS image environment is malformed')
|
|
key,data=value.split('=',1)
|
|
if not re.fullmatch('[A-Za-z_][A-Za-z0-9_]*',key) or key in result:
|
|
die('CMS image environment has ambiguous keys')
|
|
result[key]=data
|
|
return result
|
|
|
|
|
|
CMS_BUILD_BASE_ERROR_CODES = frozenset((
|
|
'cms-base-docker-timeout','cms-base-docker-unavailable','cms-base-docker-failed',
|
|
'cms-base-json-invalid','cms-base-output-limit','cms-base-image-mismatch',
|
|
'cms-base-parent-invalid','cms-base-parent-cycle','cms-base-parent-depth',
|
|
'cms-base-parent-layers','cms-base-parent-platform','cms-base-inventory-format',
|
|
'cms-base-inventory-limit','cms-base-missing','cms-base-ambiguous',
|
|
))
|
|
|
|
|
|
class CmsBuildBaseError(DeployError):
|
|
def __init__(self, code):
|
|
if code not in CMS_BUILD_BASE_ERROR_CODES:
|
|
raise ValueError('Unknown CMS base error code')
|
|
self.code=code
|
|
super().__init__(code)
|
|
|
|
|
|
def cms_base_docker_json(args, *, lines=False):
|
|
# CMS-only bounded read. Neither Docker stderr nor image Env is public.
|
|
try:
|
|
proc=subprocess.run([str(DOCKER),*args],capture_output=True,text=True,check=True,timeout=30)
|
|
except subprocess.TimeoutExpired:
|
|
raise CmsBuildBaseError('cms-base-docker-timeout') from None
|
|
except subprocess.CalledProcessError:
|
|
raise CmsBuildBaseError('cms-base-docker-failed') from None
|
|
except (OSError,UnicodeError):
|
|
raise CmsBuildBaseError('cms-base-docker-unavailable') from None
|
|
if len(proc.stdout)>8*1024*1024:
|
|
raise CmsBuildBaseError('cms-base-output-limit')
|
|
try:
|
|
return [json.loads(line) for line in proc.stdout.splitlines()] if lines else json.loads(proc.stdout)
|
|
except (ValueError,TypeError):
|
|
raise CmsBuildBaseError('cms-base-json-invalid') from None
|
|
|
|
|
|
def cms_inspect_image(identity):
|
|
if not re.fullmatch('sha256:[a-f0-9]{64}',str(identity)):
|
|
die('CMS immutable image identity is invalid')
|
|
rows=cms_base_docker_json(['image','inspect',identity])
|
|
if not isinstance(rows,list) or len(rows)!=1 or not isinstance(rows[0],dict) or rows[0].get('Id')!=identity:
|
|
raise CmsBuildBaseError('cms-base-image-mismatch')
|
|
return rows[0]
|
|
|
|
|
|
def cms_node_base_matches(image, accepted):
|
|
# Prove filesystem ancestry AND the exact config inherited by the fixed
|
|
# Dockerfile. Neither a mutable tag nor a matching NODE_VERSION is proof.
|
|
layers=(image.get('RootFS') or {}).get('Layers')
|
|
original=(accepted.get('RootFS') or {}).get('Layers')
|
|
if ((image.get('RootFS') or {}).get('Type')!='layers'
|
|
or (accepted.get('RootFS') or {}).get('Type')!='layers'
|
|
or not isinstance(layers,list) or not isinstance(original,list) or not layers
|
|
or len(layers)>=len(original) or original[:len(layers)]!=layers
|
|
or any(not re.fullmatch('sha256:[a-f0-9]{64}',str(v)) for v in layers)):
|
|
return False
|
|
if any(image.get(key)!=accepted.get(key) for key in ('Os','Architecture','Variant')):
|
|
return False
|
|
config=image.get('Config') or {};old=accepted.get('Config') or {}
|
|
if (image.get('Os')!='linux' or config.get('Cmd')!=['node']
|
|
or config.get('WorkingDir') not in ('',None)
|
|
or config.get('OnBuild') not in (None,[]) or config.get('Volumes') not in (None,{})
|
|
or config.get('ExposedPorts') not in (None,{})):
|
|
return False
|
|
for key in ('User','Entrypoint','Shell','StopSignal','Healthcheck','Labels'):
|
|
if config.get(key)!=old.get(key):return False
|
|
try:
|
|
env=cms_image_env(config);old_env=cms_image_env(old)
|
|
except DeployError:
|
|
return False
|
|
if not re.fullmatch(r'24\.[0-9]+\.[0-9]+',env.get('NODE_VERSION','')):return False
|
|
return {**env,'HOST':'0.0.0.0','PORT':'8090'}==old_env
|
|
|
|
|
|
def cms_resolve_build_base(runtime):
|
|
accepted=cms_inspect_image(runtime['imageId'])
|
|
# Legacy builds retain immutable Parent edges, including untagged bases.
|
|
# Follow this app's ancestry, never enumerate another component's cache.
|
|
current=accepted;seen={accepted['Id']};base=None
|
|
for depth in range(128):
|
|
parent=current.get('Parent')
|
|
if parent in ('',None):break
|
|
if not re.fullmatch('sha256:[a-f0-9]{64}',str(parent)):
|
|
raise CmsBuildBaseError('cms-base-parent-invalid')
|
|
if parent in seen:raise CmsBuildBaseError('cms-base-parent-cycle')
|
|
seen.add(parent);image=cms_inspect_image(parent)
|
|
layers=(image.get('RootFS') or {}).get('Layers')
|
|
child=(current.get('RootFS') or {}).get('Layers')
|
|
if ((image.get('RootFS') or {}).get('Type')!='layers'
|
|
or (current.get('RootFS') or {}).get('Type')!='layers'
|
|
or not isinstance(layers,list) or not isinstance(child,list)
|
|
or len(layers)>len(child) or child[:len(layers)]!=layers
|
|
or any(not re.fullmatch('sha256:[a-f0-9]{64}',str(v)) for v in child)):
|
|
raise CmsBuildBaseError('cms-base-parent-layers')
|
|
if any(image.get(k)!=current.get(k) for k in ('Os','Architecture','Variant')):
|
|
raise CmsBuildBaseError('cms-base-parent-platform')
|
|
if cms_node_base_matches(image,accepted):
|
|
base=image;break
|
|
current=image
|
|
else:
|
|
raise CmsBuildBaseError('cms-base-parent-depth')
|
|
method='parent-chain'
|
|
if base is None:
|
|
# BuildKit/pulled images may have no Parent. Only inspect local official
|
|
# Node repository candidates; a tag never substitutes for ancestry proof.
|
|
rows=cms_base_docker_json(['image','ls','--all','--no-trunc',
|
|
'--filter','reference=node:*','--filter','reference=docker.io/library/node:*',
|
|
'--format','{{json .ID}}'],lines=True)
|
|
if len(rows)>256:raise CmsBuildBaseError('cms-base-inventory-limit')
|
|
if any(not isinstance(v,str) or not re.fullmatch('sha256:[a-f0-9]{64}',v) for v in rows):
|
|
raise CmsBuildBaseError('cms-base-inventory-format')
|
|
matches=[]
|
|
for identity in sorted(set(rows)):
|
|
image=cms_inspect_image(identity)
|
|
if cms_node_base_matches(image,accepted):matches.append(image)
|
|
if not matches:raise CmsBuildBaseError('cms-base-missing')
|
|
if len(matches)!=1:raise CmsBuildBaseError('cms-base-ambiguous')
|
|
base=matches[0];method='node-cache'
|
|
proof={'imageId':base['Id'],'acceptedImageId':accepted['Id'],
|
|
'layersSha256':cms_audit_digest(base['RootFS']['Layers']),
|
|
'configSha256':cms_audit_digest(base['Config'])}
|
|
print('cms_build_base=accepted-image-ancestor;lookup='+method+';immutable-id='+base['Id']+';pull=never')
|
|
return proof
|
|
|
|
|
|
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, metadata = cms_application_inventory()
|
|
# 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()
|
|
runtime=cms_runtime_snapshot_v2()
|
|
base=cms_resolve_build_base(runtime)
|
|
return {'descriptor':d,'entries':list(entries),'predecessor':previous['sourceCommit'],
|
|
'runtimeFingerprintVersion':2,'runtime':runtime,'buildBase':base,'otherServices':cms_other_services(),
|
|
'foundation':cms_foundation(),'data':cms_preserved_data(),'installedFiles':installed,'installedMetadata':metadata}
|
|
|
|
|
|
def build_cms_release(before):
|
|
proof=before['buildBase']
|
|
if proof.get('acceptedImageId')!=before['runtime']['imageId']:
|
|
die('CMS build base predecessor changed')
|
|
base=cms_inspect_image(proof['imageId']);accepted=cms_inspect_image(proof['acceptedImageId'])
|
|
if (not cms_node_base_matches(base,accepted)
|
|
or cms_audit_digest(base['RootFS']['Layers'])!=proof['layersSha256']
|
|
or cms_audit_digest(base['Config'])!=proof['configSha256']):
|
|
die('CMS build base differs from its preflight proof')
|
|
dockerfile=(CMS_ROOT/'Dockerfile').read_bytes()
|
|
if hashlib.sha256(dockerfile).hexdigest()!=CMS_FOUNDATION['Dockerfile'] or not dockerfile.startswith(b'FROM node:24-alpine\n'):
|
|
die('CMS build recipe differs from the registered foundation')
|
|
# 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)
|
|
# Pin only the temporary recipe. The registered source Dockerfile is
|
|
# unchanged; no previous application/project layers enter this image.
|
|
(context/'Dockerfile').write_bytes(('FROM '+base['Id']+'\n').encode()+dockerfile.split(b'\n',1)[1])
|
|
# Docker 24's legacy builder accepts a local image ID in FROM. BuildKit
|
|
# interprets sha256:<id> as a registry repository and must not be used.
|
|
subprocess.run([str(DOCKER),'build','--pull=false','--file',str(context/'Dockerfile'),'--tag',before['runtime']['imageRef'],str(context)],
|
|
check=True,env={**os.environ,'DOCKER_BUILDKIT':'0'})
|
|
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']
|
|
expected=accepted.get('Config') or {};actual=image[0].get('Config') or {}
|
|
changed=[key for key in ('User','Cmd','Entrypoint','WorkingDir','ExposedPorts','Shell','StopSignal','Healthcheck','Labels','Volumes','OnBuild')
|
|
if actual.get(key)!=expected.get(key)]
|
|
actual_env=cms_image_env(actual);expected_env=cms_image_env(expected)
|
|
if actual_env!=expected_env:
|
|
names=sorted(k for k in set(actual_env)|set(expected_env) if actual_env.get(k)!=expected_env.get(k))
|
|
changed.append('Env['+','.join(names)+']')
|
|
if changed:die('CMS built image changes inherited configuration before recreation: '+','.join(changed))
|
|
print('cms_build_accept=inherited-config-exact;runtime-not-recreated')
|
|
|
|
|
|
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'),c=require('crypto'),r={};
|
|
for(const d of ['admin','server'])for(const n of fs.readdirSync('/app/'+d)){
|
|
const rel=d+'/'+n,f='/app/'+rel,s=fs.lstatSync(f);
|
|
if(s.isFile())r[rel]=c.createHash('sha256').update(fs.readFileSync(f)).digest('hex');
|
|
else if(n==='@eaDir'&&s.isDirectory())for(const m of fs.readdirSync(f)){
|
|
const q=f+'/'+m;if(!fs.lstatSync(q).isFile())throw Error('unexpected runtime metadata path');
|
|
r[rel+'/'+m]=c.createHash('sha256').update(fs.readFileSync(q)).digest('hex');
|
|
}else throw Error('unexpected runtime path');
|
|
}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 cms_without_synology_metadata(json.loads(proc.stdout), 'CMS running image')[0]
|
|
|
|
|
|
def accept_cms_release(before, *, rollback=False):
|
|
cms_healthchecks()
|
|
version=before.get('runtimeFingerprintVersion',1)
|
|
if type(version) is not int or version not in (1,2):die('CMS runtime fingerprint version mismatch')
|
|
current=cms_runtime_snapshot_v2() if version==2 else cms_runtime_snapshot();old=before['runtime']
|
|
if current['configSha256'] != old['configSha256'] or current['imageRef'] != old['imageRef']:
|
|
detail=''
|
|
if version==2:
|
|
previous=old.get('fieldSha256') or {};actual=current.get('fieldSha256') or {}
|
|
changed=sorted(k for k in set(previous)|set(actual) if previous.get(k)!=actual.get(k))
|
|
detail='; fields='+','.join(changed)
|
|
die('CMS environment, mounts, ports or network topology changed'+detail)
|
|
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, metadata=cms_application_inventory()
|
|
if metadata != before['installedMetadata']:die('CMS release changed preserved Synology metadata')
|
|
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)
|