"""Prepared metadata-bound API image rollout/rollback. No action on import.""" from pathlib import Path import importlib.util import json import re import shlex import time PROJECT = 'dify_v1110_eera' SERVICE = 'api' COMPOSE = '/www/dk_project/dk_app/dify_v1110/dify_v1110_Eera/docker-compose.yml' WORKDIR = '/www/dk_project/dk_app/dify_v1110/dify_v1110_Eera' ACTIONS = frozenset({'prepare-deploy', 'deploy', 'rollback', 'deployment-status'}) def _base(root): spec = importlib.util.spec_from_file_location('private_rollout_fixed_base', root / 'artifacts/private_dify_ops_actions_20261027.py') module = importlib.util.module_from_spec(spec); spec.loader.exec_module(module) return module def _prefix(extra=None): parts = ['docker', 'compose', '--project-directory', WORKDIR, '-p', PROJECT, '-f', COMPOSE] if extra: parts += ['-f', extra] return ' '.join(map(shlex.quote, parts)) def _current(client, base): # Include exited/created containers: a failed replacement must remain recoverable. raw, meta = base._exec(client, _prefix() + ' ps --all -q ' + SERVICE, cap=4096) identifier = raw.decode('ascii').strip() if not identifier: return None base._require(re.fullmatch(r'[0-9a-f]{12,64}', identifier) is not None, 'COMPOSE_API_IDENTITY_AMBIGUOUS') template = '{"container_id":{{json .Id}},"image_id":{{json .Image}},"status":{{json .State.Status}},"restart_count":{{json .RestartCount}},"health":{{with (index .State "Health")}}{{json (index . "Status")}}{{else}}null{{end}},"project":{{json (index .Config.Labels "com.docker.compose.project")}},"service":{{json (index .Config.Labels "com.docker.compose.service")}}}' data, command = base._json_command(client, 'docker inspect --format ' + shlex.quote(template) + ' ' + identifier) base._require(isinstance(data, dict) and data.get('project') == PROJECT and data.get('service') == SERVICE, 'COMPOSE_API_BINDING_MISMATCH') base._require(re.fullmatch(r'[0-9a-f]{64}', data.get('container_id', '')) is not None and data['container_id'].startswith(identifier) and re.fullmatch(r'sha256:[0-9a-f]{64}', data.get('image_id', '')) is not None, 'COMPOSE_API_METADATA_INVALID') return data def _compose_fingerprint(client, base): """Hash resolved inputs on their original host; never export config/Env values.""" code = '''import hashlib,json,pathlib,subprocess,sys command=json.loads(sys.argv[1]); result=subprocess.run(command,stdout=subprocess.PIPE,stderr=subprocess.DEVNULL,timeout=25) assert result.returncode==0 and len(result.stdout)<=16777216 model=json.loads(result.stdout); assert isinstance(model,dict) and 'api' in model.get('services',{}) canonical=json.dumps(model,sort_keys=True,separators=(',',':')).encode() source=pathlib.Path(sys.argv[2]).read_bytes(); assert len(source)<=2097152 print(json.dumps({'resolved_sha256':hashlib.sha256(canonical).hexdigest(),'compose_sha256':hashlib.sha256(source).hexdigest()})) ''' args = ['docker', 'compose', '--project-directory', WORKDIR, '-p', PROJECT, '-f', COMPOSE, 'config', '--format', 'json'] result, command = base._json_command(client, 'python3 -c ' + shlex.quote(code) + ' ' + shlex.quote(json.dumps(args)) + ' ' + shlex.quote(COMPOSE), timeout=30) base._require(isinstance(result, dict) and set(result) == {'resolved_sha256', 'compose_sha256'} and all(isinstance(v, str) and re.fullmatch(r'[0-9a-f]{64}', v) for v in result.values()), 'COMPOSE_FINGERPRINT_INVALID') return result def _immutable_override(image_id): if re.fullmatch(r'sha256:[0-9a-f]{64}', image_id or '') is None: raise ValueError('invalid immutable image identity') return json.dumps({'services': {SERVICE: {'image': image_id, 'pull_policy': 'never'}}}).encode() def _verify_override(client, base, path, image_id): code = '''import json,pathlib,sys value=json.loads(pathlib.Path(sys.argv[1]).read_bytes()) assert value=={'services':{'api':{'image':sys.argv[2],'pull_policy':'never'}}} print(json.dumps({'ok':True})) ''' result, command = base._json_command(client, 'python3 -c ' + shlex.quote(code) + ' ' + shlex.quote(path) + ' ' + shlex.quote(image_id), timeout=15) base._require(result == {'ok': True}, 'ROLLOUT_OVERRIDE_CHANGED') def _copy_compose_private(client, base, target, expected_sha256): code = '''import hashlib,json,os,pathlib,sys source=pathlib.Path(sys.argv[1]).read_bytes(); assert len(source)<=2097152 assert hashlib.sha256(source).hexdigest()==sys.argv[3] fd=os.open(sys.argv[2],os.O_WRONLY|os.O_CREAT|os.O_EXCL,0o600) with os.fdopen(fd,'wb') as output: output.write(source) assert hashlib.sha256(pathlib.Path(sys.argv[2]).read_bytes()).hexdigest()==sys.argv[3] print(json.dumps({'ok':True})) ''' result, command = base._json_command(client, 'python3 -c ' + shlex.quote(code) + ' ' + ' '.join(map(shlex.quote, [COMPOSE, target, expected_sha256])), timeout=20) base._require(result == {'ok': True}, 'COMPOSE_PRIVATE_BACKUP_FAILED') def _up_command(override): # Image IDs and --no-build prevent a mutable tag/build/pull from selecting different bytes. return _prefix(override) + ' up -d --no-deps --no-build --pull never --force-recreate ' + SERVICE def _write_new_private(client, path, content): sftp = client.open_sftp() try: sftp.get_channel().settimeout(20) with sftp.file(path, 'wx') as handle: handle.write(content) sftp.chmod(path, 0o600) finally: sftp.close() def _tree_check(client, base, identifier, manifest, which): checks = [{'path': row['path'], 'sha256': row[which]} for row in manifest['targets']] code = '''import hashlib,json,pathlib rows=ROWS; root=pathlib.Path('/app/api'); good=0 for row in rows: p=root/row['path']; assert (hashlib.sha256(p.read_bytes()).hexdigest() if p.is_file() else None)==row['sha256']; good+=1 print(json.dumps({'ok':True,'target_count':good})) '''.replace('ROWS', repr(checks)) data, command = base._json_command(client, 'docker exec ' + shlex.quote(identifier) + ' python -B -c ' + shlex.quote(code), timeout=30) base._require(data.get('ok') is True and data.get('target_count') == 17, 'ROLLOUT_TREE_CHECK_FAILED') return data def _stopped_candidate_tree_check(client, base, identifier, manifest): """Check only the 17 fixed files even when the candidate process cannot exec.""" checks = [{'path': row['path'], 'sha256': row['after_sha256']} for row in manifest['targets']] code = '''import hashlib,io,json,os,selectors,subprocess,sys,tarfile,time rows=json.loads(sys.argv[2]); good=0; overall=time.monotonic()+35 for row in rows: command=['docker','cp',sys.argv[1]+':/app/api/'+row['path'],'-'] child=subprocess.Popen(command,stdout=subprocess.PIPE,stderr=subprocess.DEVNULL) poll=selectors.DefaultSelector(); poll.register(child.stdout,selectors.EVENT_READ) try: data=bytearray(); deadline=min(overall,time.monotonic()+8) while True: assert time.monotonic()