Isolate CMS sites, transfer publication settings and qualify Git releases
This commit is contained in:
@@ -0,0 +1,73 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Qualify an exact CMS commit and package application files, never runtime state."""
|
||||
import argparse
|
||||
import gzip
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
import tarfile
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
ENTRY = 'server/cms-release.json'
|
||||
STEPS = ['frozen-install', 'syntax', 'multisite-tests']
|
||||
|
||||
def digest(data): return hashlib.sha256(data).hexdigest()
|
||||
def run(args): subprocess.run(args, cwd=ROOT, check=True)
|
||||
def tracked_payload():
|
||||
names = subprocess.check_output(['git','ls-files','-z','admin','server'], cwd=ROOT).decode().split('\0')
|
||||
files = {}
|
||||
for name in sorted(filter(None,names)):
|
||||
path=ROOT/name
|
||||
if path.is_symlink() or not path.is_file() or path.suffix not in ('.js','.mjs','.html','.css','.svg'):
|
||||
raise ValueError('unsupported runtime path: '+name)
|
||||
files[name]=path.read_bytes()
|
||||
if not {'admin/index.html','admin/admin.js','admin/admin.css','server/admin-server.mjs'} <= set(files):
|
||||
raise ValueError('missing CMS application entrypoints')
|
||||
return files
|
||||
|
||||
def bundle(files, commit, run_id, run_number, foundation):
|
||||
if not re.fullmatch('[a-f0-9]{40}',commit) or any(type(n) is not int or n<=0 for n in (run_id,run_number)):
|
||||
raise ValueError('full source and positive run identity required')
|
||||
for name, data in files.items():
|
||||
if not re.fullmatch(r'(?:admin|server)/[a-zA-Z0-9_-]+\.(?:mjs|js|css|html|svg)', name) or not isinstance(data, bytes):
|
||||
raise ValueError('unsupported application payload: '+name)
|
||||
if not files:
|
||||
raise ValueError('empty application payload')
|
||||
identity=f'dc-cms-release-v1-r{run_id}-{commit}'
|
||||
descriptor={'schemaVersion':'nodedc.dc-cms.release.v1','releaseId':identity,'repository':'SILVER/DC_CMS','repositoryId':33,'branch':'master','sourceCommit':commit,'runId':run_id,'runNumber':run_number,'qualification':{'status':'qualified','steps':STEPS,'deployed':False},'filesSha256':{k:digest(v) for k,v in files.items()},'foundationSha256':foundation}
|
||||
payload=dict(files);payload[ENTRY]=(json.dumps(descriptor,indent=2,sort_keys=True)+'\n').encode()
|
||||
members={'manifest.env':f'id={identity}\ncomponent=dc-cms-release\ntype=app-overlay\n'.encode(),'files.txt':('\n'.join(sorted(payload))+'\n').encode()}
|
||||
members.update({'payload/'+k:v for k,v in payload.items()})
|
||||
output=io.BytesIO()
|
||||
with gzip.GzipFile(fileobj=output,mode='wb',mtime=0,filename='') as zipped:
|
||||
with tarfile.open(fileobj=zipped,mode='w') as archive:
|
||||
for name,data in sorted(members.items()):
|
||||
item=tarfile.TarInfo(name);item.size=len(data);item.mode=0o644
|
||||
archive.addfile(item,io.BytesIO(data))
|
||||
return identity,output.getvalue()
|
||||
|
||||
def main():
|
||||
parser=argparse.ArgumentParser();parser.add_argument('--commit',required=True);parser.add_argument('--run-id',type=int,required=True);parser.add_argument('--run-number',type=int,required=True);parser.add_argument('--output-dir',type=Path,required=True);args=parser.parse_args()
|
||||
head=subprocess.check_output(['git','rev-parse','HEAD'],cwd=ROOT).decode().strip()
|
||||
dirty=subprocess.check_output(['git','status','--porcelain','--untracked-files=no'],cwd=ROOT)
|
||||
if head!=args.commit or dirty: raise ValueError('qualification requires exact clean commit')
|
||||
run(['npm','ci','--ignore-scripts'])
|
||||
files=tracked_payload()
|
||||
for name in files:
|
||||
if name.endswith(('.js','.mjs')): run(['node','--check',name])
|
||||
run(['node','--test','test/multisite.test.mjs'])
|
||||
run(['python3','-m','unittest','discover','-s','infra/ci','-p','test_*.py'])
|
||||
# The ordinary release cannot change its build, dependency or deployment foundation.
|
||||
foundation={name:digest((ROOT/name).read_bytes()) for name in ['Dockerfile','package.json','package-lock.json','infra/docker-compose.yml']}
|
||||
identity,data=bundle(files,args.commit,args.run_id,args.run_number,foundation)
|
||||
args.output_dir.mkdir(parents=True,exist_ok=True)
|
||||
name='nodedc-'+identity+'.tgz'
|
||||
with (args.output_dir/name).open('xb') as stream:stream.write(data)
|
||||
receipt={'artifact':name,'sourceCommit':args.commit,'runId':args.run_id,'runNumber':args.run_number,'deployed':False,'sha256':digest(data)}
|
||||
(args.output_dir/'release.json').write_text(json.dumps(receipt,sort_keys=True)+'\n')
|
||||
print(json.dumps(receipt))
|
||||
|
||||
if __name__=='__main__':main()
|
||||
@@ -0,0 +1,29 @@
|
||||
import io
|
||||
import json
|
||||
import tarfile
|
||||
import unittest
|
||||
from release import bundle, ENTRY
|
||||
|
||||
class ReleaseTests(unittest.TestCase):
|
||||
def test_deterministic_application_bundle(self):
|
||||
files={'server/admin-server.mjs':b'// app','admin/admin.js':b'// ui'}
|
||||
args=(files,'a'*40,12,3,{'Dockerfile':'b'*64})
|
||||
identity,data=bundle(*args)
|
||||
self.assertEqual(bundle(*args)[1],data)
|
||||
with tarfile.open(fileobj=io.BytesIO(data),mode='r:gz') as archive:
|
||||
names=archive.getnames()
|
||||
self.assertEqual(set(names),{'manifest.env','files.txt','payload/'+ENTRY,'payload/admin/admin.js','payload/server/admin-server.mjs'})
|
||||
self.assertTrue(all(x.isfile() for x in archive.getmembers()))
|
||||
descriptor=json.load(archive.extractfile('payload/'+ENTRY))
|
||||
self.assertEqual(descriptor['repositoryId'],33)
|
||||
self.assertEqual(descriptor['branch'],'master')
|
||||
self.assertFalse(descriptor['qualification']['deployed'])
|
||||
self.assertIn(identity,archive.extractfile('manifest.env').read().decode())
|
||||
def test_run_identity_required(self):
|
||||
for sha,run_id in [('short',1),('a'*40,0),('a'*40,True)]:
|
||||
with self.assertRaises(ValueError):bundle({},sha,run_id,1,{})
|
||||
def test_runtime_paths_never_enter_bundle(self):
|
||||
for path in ['server/../secrets.js','server/.env','projects/nodedc.json','admin/uploads/a.js','server/data/a.js','Dockerfile','server/cms-release.json','/server/a.js']:
|
||||
with self.subTest(path=path),self.assertRaises(ValueError):bundle({path:b'x'},'a'*40,1,1,{})
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
Reference in New Issue
Block a user