337 行
19 KiB
Python
可执行文件
337 行
19 KiB
Python
可执行文件
#!/usr/bin/env python3
|
|
"""Targeted local delivery: no task leases, whole builds or manual SHA approval."""
|
|
import argparse
|
|
from contextlib import contextmanager
|
|
import fcntl
|
|
import hashlib
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import re
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
|
|
from deployment_artifacts import artifact_digest, verify_image
|
|
|
|
ROOT = Path(__file__).resolve().parents[2]
|
|
BASE = ROOT / 'script/datagov'
|
|
CONFIG = BASE / 'deployment'
|
|
STATE = ROOT / '.cache/datagov'
|
|
PROJECT = 'aixun-datagov-local'
|
|
OWNER = 'aixun-datagov'
|
|
SERVICES = ('auth', 'gateway', 'system', 'resource', 'integration', 'dataops', 'governance', 'dataproduct', 'frontend')
|
|
CONFIGURABLE_FIELDS = {'image','environment','command','entrypoint','working_dir','restart'}
|
|
|
|
class Rejected(Exception):
|
|
pass
|
|
|
|
def need(condition, code):
|
|
if not condition:
|
|
raise Rejected(code)
|
|
|
|
def digest(value):
|
|
return hashlib.sha256(json.dumps(value, sort_keys=True, separators=(',', ':')).encode()).hexdigest()
|
|
|
|
def stable_model_sha(item):
|
|
return digest({k:v for k,v in item.items() if k not in CONFIGURABLE_FIELDS})
|
|
|
|
def compose_input(value):
|
|
# Compose interpolates input again. Preserve literal dollars in resolved
|
|
# values without persisting the secret-bearing model to a temporary file.
|
|
if isinstance(value,str):
|
|
return value.replace('$','$$')
|
|
if isinstance(value,list):
|
|
return [compose_input(v) for v in value]
|
|
if isinstance(value,dict):
|
|
return {k:compose_input(v) for k,v in value.items()}
|
|
return value
|
|
|
|
def run(args, env=None, input_text=None):
|
|
try:
|
|
p = subprocess.run(args, cwd=ROOT, env={**os.environ, **(env or {})}, input=input_text, capture_output=True, text=True, timeout=120)
|
|
except subprocess.TimeoutExpired:
|
|
raise Rejected('command timed out: ' + Path(args[0]).name + '; reconcile any apply attempt before retrying') from None
|
|
need(p.returncode == 0, 'command failed: ' + Path(args[0]).name + '; raw output withheld')
|
|
return p.stdout
|
|
|
|
def docker(*args):
|
|
return json.loads(run(['docker', *args]))
|
|
|
|
def env_values(values):
|
|
return dict(item.split('=', 1) for item in values or [] if '=' in item)
|
|
|
|
def own(labels, service=None):
|
|
need(labels.get('com.aixun.project') == OWNER and labels.get('com.docker.compose.project') == PROJECT, 'foreign runtime object')
|
|
if service:
|
|
need(labels.get('com.docker.compose.service') == service, 'wrong service')
|
|
|
|
def mount_source(mount):
|
|
source = mount['Source']
|
|
if mount['Type'] == 'bind' and source.startswith('/host_mnt/'):
|
|
return source[len('/host_mnt'):]
|
|
return source
|
|
|
|
def mounts(container):
|
|
return sorted([{'type':m['Type'], 'source':mount_source(m), 'destination':m['Destination'], 'rw':m['RW']} for m in container['Mounts']], key=lambda m:m['destination'])
|
|
|
|
def identity(service):
|
|
return json.loads((CONFIG/'identities.json').read_text())[service]
|
|
|
|
def network_ip(value):
|
|
return value['IPAddress'] or (value.get('IPAMConfig') or {}).get('IPv4Address', '')
|
|
|
|
def current(service, allow_stopped=False):
|
|
b = identity(service)
|
|
c = docker('inspect', b['container'])[0]
|
|
own(c['Config'].get('Labels') or {}, service)
|
|
need(c['Name'] == '/' + b['container'] and (c['State']['Running'] or (allow_stopped and c['State']['Status'] == 'exited')), 'target is not the expected running or stopped container')
|
|
observed = {k:{'id':v['NetworkID'], 'ip':network_ip(v)} for k,v in c['NetworkSettings']['Networks'].items()}
|
|
need(observed == b['networks'], 'network identity or IP drift')
|
|
for name, expected in b['networks'].items():
|
|
network = docker('network', 'inspect', name)[0]
|
|
own(network.get('Labels') or {})
|
|
need(network['Id'] == expected['id'], 'network replacement detected')
|
|
need(mounts(c) == sorted(b['mounts'], key=lambda m:m['destination']), 'mount identity drift')
|
|
for mount in b['mounts']:
|
|
if mount['type'] == 'volume':
|
|
own(docker('volume', 'inspect', Path(mount['source']).parts[-2])[0].get('Labels') or {})
|
|
return c
|
|
|
|
def snapshot(c):
|
|
config = dict(c['Config'])
|
|
config.pop('Hostname', None)
|
|
config.pop('Image', None)
|
|
config['Labels'] = {k:v for k,v in (config.get('Labels') or {}).items() if not k.startswith('com.docker.compose.') and k != 'org.opencontainers.image.version'}
|
|
return digest({'config':config, 'host':c['HostConfig'], 'mounts':mounts(c), 'networks':{k:{'id':v['NetworkID'],'ip':v['IPAddress']} for k,v in c['NetworkSettings']['Networks'].items()}})
|
|
|
|
def compose(service, image, config_change=False):
|
|
env = {'AIXUN_DATAGOV_DEPLOY_IMAGE':image}
|
|
cmd = ['docker', 'compose', '--project-directory', str(BASE), '--env-file', str(BASE/'.env.datagov'), '-p', PROJECT, '-f', str(CONFIG/(service+'.json'))]
|
|
model = json.loads(run(cmd + ['config', '--format', 'json'], env))
|
|
need(model.get('name') == PROJECT and set(model['services']) == {service}, 'unexpected deployment scope')
|
|
item = model['services'][service]
|
|
need(item['container_name'] == 'aixun-datagov-' + service and item['labels']['com.aixun.project'] == OWNER and item['image'] == image, 'invalid service model')
|
|
need(all(n.get('external') for n in model['networks'].values()), 'deployment cannot manage network lifecycle')
|
|
need(all(v.get('external') for v in model.get('volumes', {}).values()), 'deployment cannot manage volume lifecycle')
|
|
if config_change:
|
|
need(stable_model_sha(item)==identity(service).get('stableModelSha256'),'configuration note covers only environment, launch and restart; runtime identity or privilege fields changed')
|
|
else:
|
|
need(digest({k:v for k,v in item.items() if k != 'image'}) == identity(service)['runtimeModelSha256'], 'configuration changed; record the intended change with --config-change-note in this plan')
|
|
return cmd, env, model
|
|
|
|
def validate_runtime_model(service, model, c, config_change=False):
|
|
s = model['services'][service]
|
|
for key,value in s.get('environment',{}).items():
|
|
name=key.upper().replace('.','_').replace('-','_')
|
|
if 'NACOS' in name and name.endswith('NAMESPACE'):
|
|
need(value==PROJECT,'Nacos namespace must remain DataGov-only')
|
|
if 'NACOS' in name and name.endswith('GROUP'):
|
|
need(value=='AIXUN_DATAGOV_GROUP','Nacos group must remain DataGov-only')
|
|
if not config_change:
|
|
need(all(env_values(c['Config']['Env']).get(k) == str(v) for k,v in s.get('environment',{}).items()), 'declared environment drift')
|
|
expected_ports = {}
|
|
for port in s.get('ports', []):
|
|
key = str(port['target']) + '/' + port.get('protocol','tcp')
|
|
expected_ports.setdefault(key, []).append({'HostIp':port.get('host_ip',''), 'HostPort':str(port['published'])})
|
|
# Docker represents explicit 0.0.0.0 as either 0.0.0.0 or empty.
|
|
normalize = lambda values: {k:sorted((p['HostIp'] or '0.0.0.0',p['HostPort']) for p in v) for k,v in values.items()}
|
|
need(normalize(expected_ports) == normalize(c['HostConfig'].get('PortBindings') or {}), 'declared port drift')
|
|
expected_mounts = []
|
|
for m in s.get('volumes', []):
|
|
source = model['volumes'][m['source']]['name'] if m['type'] == 'volume' else m['source']
|
|
expected_mounts.append((m['type'], source, m['target'], not m.get('read_only',False)))
|
|
actual_mounts = [(m['Type'], m.get('Name') if m['Type']=='volume' else mount_source(m), m['Destination'], m['RW']) for m in c['Mounts']]
|
|
need(sorted(expected_mounts) == sorted(actual_mounts), 'declared mount drift')
|
|
declared = {model['networks'][k]['name']:v.get('ipv4_address') for k,v in s['networks'].items()}
|
|
need(declared == {k:network_ip(v) for k,v in c['NetworkSettings']['Networks'].items()}, 'declared network drift')
|
|
if not config_change:
|
|
need(s.get('restart','no') == c['HostConfig']['RestartPolicy']['Name'], 'restart policy drift')
|
|
|
|
def effective_launch(service, model, image):
|
|
s=model['services'][service];config=image['Config']
|
|
result={k:config.get(k) for k in ('Entrypoint','Cmd','WorkingDir','User')}
|
|
for field,key in [('entrypoint','Entrypoint'),('command','Cmd'),('working_dir','WorkingDir'),('user','User')]:
|
|
if field in s and s[field] is not None:
|
|
result[key]=s[field]
|
|
# An explicit Compose entrypoint suppresses the image's default command.
|
|
if s.get('entrypoint') is not None and s.get('command') is None:
|
|
result['Cmd']=None
|
|
return result
|
|
|
|
def validate_launch(service, model, image, c, config_change=False):
|
|
launch=effective_launch(service,model,image)
|
|
changed=[k for k,v in launch.items() if (v or None)!=(c['Config'].get(k) or None)]
|
|
need('User' not in changed,'container user change needs an explicit runtime identity change')
|
|
need(config_change or not changed,'launch configuration changed; record it with --config-change-note')
|
|
return changed
|
|
|
|
def inspect_image(service, ref):
|
|
need(bool(re.fullmatch(r'aixun-datagov/'+service+r':[a-z0-9][a-z0-9_.-]*',ref)) and not ref.endswith(':latest'), 'use an exact DataGov image tag')
|
|
image = docker('image', 'inspect', ref)[0]
|
|
need((image['Config'].get('Labels') or {}).get('com.aixun.project') == OWNER, 'foreign image')
|
|
return image
|
|
|
|
def artifact_source(service, image):
|
|
if service != 'frontend':
|
|
return None
|
|
values = env_values(image['Config'].get('Env'))
|
|
source = values.get('AIXUN_DATAGOV_FRONTEND_SOURCE', '/opt/aixun-datagov/frontend-current')
|
|
need(bool(re.fullmatch(r'/opt/aixun-datagov/frontend-[A-Za-z0-9_.-]+', source)),
|
|
'unexpected frontend artifact source')
|
|
return source
|
|
|
|
@contextmanager
|
|
def deployment_lock():
|
|
STATE.mkdir(parents=True, exist_ok=True)
|
|
with (STATE/'deployment.lock').open('a') as lock:
|
|
try:
|
|
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
except BlockingIOError:
|
|
raise Rejected('another deployment is applying; coding remains available')
|
|
try:
|
|
yield
|
|
finally:
|
|
fcntl.flock(lock, fcntl.LOCK_UN)
|
|
|
|
def plan_path(service, release):
|
|
need(bool(re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9._-]{0,95}',release)), 'invalid release name')
|
|
return CONFIG/'releases'/(release+'-'+service+'.json')
|
|
|
|
def write_json(path, value, exclusive=False):
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
with path.open('x' if exclusive else 'w') as f:
|
|
json.dump(value, f, indent=2); f.write('\n')
|
|
path.chmod(0o600)
|
|
|
|
def plan(args):
|
|
need(args.image is not None, 'plan needs IMAGE_TAG')
|
|
path = plan_path(args.service,args.release)
|
|
c = current(args.service, allow_stopped=True)
|
|
image = inspect_image(args.service,args.image)
|
|
source = artifact_source(args.service,image)
|
|
note=(getattr(args,'config_change_note',None) or '').strip()
|
|
cmd, env, model = compose(args.service,image['Id'],config_change=bool(note))
|
|
validate_runtime_model(args.service,model,c,config_change=bool(note))
|
|
launch_changes=validate_launch(args.service,model,image,c,config_change=bool(note))
|
|
expected = artifact_digest(args.artifact) if args.artifact else args.artifact_sha
|
|
need(bool(expected and re.fullmatch('[0-9a-f]{64}',expected)), 'supply --artifact PATH or --artifact-sha SHA256')
|
|
verification = verify_image(image['Id'],expected,STATE/'artifacts',args.service=='frontend',
|
|
source or '/opt/aixun-datagov/frontend-current')
|
|
result = {'version':1,'service':args.service,'release':args.release,'imageTag':args.image,'imageId':image['Id'],'artifactSha256':expected,'sourceContainerId':c['Id'],'sourceImageId':c['Image'],'sourceImageTag':c['Config']['Image'],'sourceStateSha256':snapshot(c),'modelSha256':digest(model),'identitySha256':digest(identity(args.service))}
|
|
if source:
|
|
result['artifactPath'] = source
|
|
if note:
|
|
declared=model['services'][args.service]
|
|
result['configurationChange']={'note':note,'environmentKeys':[k for k,v in declared.get('environment',{}).items() if env_values(c['Config']['Env']).get(k)!=str(v)],'launchFields':launch_changes,'restartPolicyChanged':declared.get('restart','no')!=c['HostConfig']['RestartPolicy']['Name'],'previousModelSha256':identity(args.service)['runtimeModelSha256'],'desiredModelSha256':digest({k:v for k,v in declared.items() if k!='image'})}
|
|
if path.exists():
|
|
need(json.loads(path.read_text()) == result, 'plan changed; use a new release name')
|
|
else:
|
|
write_json(path,result,exclusive=True)
|
|
print(json.dumps({'plan':str(path.relative_to(ROOT)),'service':args.service,'imageId':image['Id'],'artifactVerification':verification,'runtimeMutation':False}))
|
|
|
|
def verify_deployed_artifact(service, container_id, expected,
|
|
frontend_source='/opt/aixun-datagov/frontend-current'):
|
|
if service != 'frontend':
|
|
actual = run(['docker','exec',container_id,'sha256sum','/aixun-datagov/app/app.jar']).split()
|
|
need(bool(actual) and actual[0] == expected, 'deployed JAR hash mismatch')
|
|
return
|
|
# The existing entrypoint activates index.html after copying immutable assets.
|
|
# Wait only for that technical activation, not for functional UAT.
|
|
# The measured wave15 asset activation took 67s while backend images started.
|
|
# This remains a bounded, read-only activation check; it never retries apply.
|
|
deadline = time.monotonic() + 120
|
|
while True:
|
|
output = run(['docker','exec',container_id,'sha256sum',frontend_source + '/index.html',
|
|
'/usr/share/nginx/html/index.html'])
|
|
hashes = [line.split()[0] for line in output.splitlines() if line.split()]
|
|
if len(hashes) == 2 and hashes[0] == hashes[1]:
|
|
return
|
|
need(time.monotonic() < deadline, 'frontend entrypoint did not activate the image index')
|
|
time.sleep(0.5)
|
|
|
|
def apply(args):
|
|
need(bool(args.authorized_by and args.authorized_by.strip()), 'record the existing user deployment request with --authorized-by')
|
|
path = plan_path(args.service,args.release)
|
|
p = json.loads(path.read_text())
|
|
need(p.get('version')==1 and p['service']==args.service and p['release']==args.release, 'plan scope mismatch')
|
|
attempt = path.with_name(path.stem+'-attempt.json')
|
|
with deployment_lock():
|
|
need(not attempt.exists(), 'prior apply outcome must be reconciled; no automatic retry')
|
|
# Target preflight is performed below: owned live container/network/volume,
|
|
# exact immutable image and declared config. Bootstrap seeds and unrelated
|
|
# services are not prerequisites for updating an existing application.
|
|
c = current(args.service, allow_stopped=True)
|
|
need(c['Id']==p['sourceContainerId'] and c['Image']==p['sourceImageId'] and snapshot(c)==p['sourceStateSha256'], 'live source drift; replan')
|
|
need(digest(identity(args.service))==p['identitySha256'], 'identity baseline drift')
|
|
image = inspect_image(args.service,p['imageTag'])
|
|
need(image['Id']==p['imageId'], 'image tag moved; replan')
|
|
source = artifact_source(args.service,image)
|
|
if source:
|
|
need(p.get('artifactPath') == source, 'frontend artifact source is not bound by this plan')
|
|
verify_image(image['Id'],p['artifactSha256'],STATE/'artifacts',args.service=='frontend',
|
|
source or '/opt/aixun-datagov/frontend-current')
|
|
config_change=bool(p.get('configurationChange',{}).get('note'))
|
|
cmd, env, model = compose(args.service,image['Id'],config_change=config_change)
|
|
need(digest(model)==p['modelSha256'], 'configuration changed; replan')
|
|
validate_runtime_model(args.service,model,c,config_change=config_change)
|
|
validate_launch(args.service,model,image,c,config_change=config_change)
|
|
# Bind the immutable image ID, avoiding mutable-tag races.
|
|
operation = ['up','-d','--no-deps','--no-build','--pull','never','--force-recreate',args.service]
|
|
write_json(attempt,{'sourceContainerId':c['Id'],'imageId':image['Id'],'authorizedBy':args.authorized_by,'startedAt':time.time()},exclusive=True)
|
|
# Apply exactly the model just checked. A concurrent edit of the source
|
|
# Compose/env files cannot silently change this deployment's inputs.
|
|
frozen_cmd=['docker','compose','--project-directory',str(BASE),'-p',PROJECT,'-f','-']
|
|
run(frozen_cmd+operation,env,input_text=json.dumps(compose_input(model)))
|
|
after = current(args.service)
|
|
need(after['Id']!=c['Id'] and after['Image']==image['Id'], 'post-apply image identity mismatch')
|
|
validate_runtime_model(args.service,model,after)
|
|
validate_launch(args.service,model,image,after)
|
|
if source:
|
|
verify_deployed_artifact(args.service,after['Id'],p['artifactSha256'],source)
|
|
else:
|
|
verify_deployed_artifact(args.service,after['Id'],p['artifactSha256'])
|
|
after = current(args.service)
|
|
need(not after['State'].get('OOMKilled') and after['RestartCount']==0,'post-apply startup failure')
|
|
result = {'service':args.service,'containerId':after['Id'],'imageId':image['Id'],'status':'DEPLOYED_FUNCTIONAL_UAT_NOT_RUN','artifactReadback':'PASS','applicationReadiness':'NOT_RUN','recoveryImageId':p['sourceImageId']}
|
|
if config_change:
|
|
baselines=json.loads((CONFIG/'identities.json').read_text())
|
|
baselines[args.service]['runtimeModelSha256']=digest({k:v for k,v in model['services'][args.service].items() if k!='image'})
|
|
temporary=CONFIG/'identities.json.tmp'
|
|
write_json(temporary,baselines)
|
|
os.replace(temporary,CONFIG/'identities.json')
|
|
result['configurationChangeVerified']=True
|
|
write_json(path.with_name(path.stem+'-result.json'),result)
|
|
print(json.dumps(result))
|
|
|
|
def main(argv=None):
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
modes = parser.add_mutually_exclusive_group(required=True)
|
|
modes.add_argument('--plan',action='store_true')
|
|
modes.add_argument('--apply',action='store_true')
|
|
modes.add_argument('--check-config',action='store_true',help='inspect live identity/config without creating a release')
|
|
parser.add_argument('service',choices=SERVICES)
|
|
parser.add_argument('release',nargs='?')
|
|
parser.add_argument('image',nargs='?')
|
|
parser.add_argument('--artifact',help='local JAR or frontend dist directory')
|
|
parser.add_argument('--artifact-sha',help='known JAR/tree SHA when no local artifact copy is needed')
|
|
parser.add_argument('--authorized-by',help='existing user request authorizing this local deployment; not a new approval')
|
|
parser.add_argument('--config-change-note',help='describe an intended environment/launch/restart change in this authorized task; no new approval')
|
|
args = parser.parse_args(argv)
|
|
if args.check_config:
|
|
c = current(args.service)
|
|
_,_,model = compose(args.service,c['Image'])
|
|
validate_runtime_model(args.service,model,c)
|
|
print(json.dumps({'service':args.service,'configuration':'PASS','runtimeMutation':False}))
|
|
else:
|
|
need(args.release is not None,'release name required')
|
|
plan(args) if args.plan else apply(args)
|
|
|
|
if __name__ == '__main__':
|
|
try:
|
|
main()
|
|
except (Rejected,ValueError,KeyError,OSError) as exc:
|
|
# Avoid printing configuration/secret values from parser or command errors.
|
|
print('BLOCKED: '+(str(exc) if isinstance(exc,Rejected) else type(exc).__name__),file=sys.stderr)
|
|
sys.exit(2)
|