Files
knowledge-governance/scripts/candidate_runtime.py
T
zheromiku a655f4cca8
build / build (push) Successful in 2m56s
fix(reconciliation): 用 RECONCILIATION_ENABLED 独立接线对账服务
T6 的 9 个接口此前只在 TEST_WEKNORA_ENABLED=true 时才构造对账服务,
而该开关同时要求旧测试库端点/KB/Key 文件与 spool 根(appconfig 校验),
候选环境给不出这些旧材料,于是 9 个接口恒 503 reconciliation_not_configured,
QA 无法执行任一用例。

对账本身只需要知识库绑定里的租户 Key(需求书 §5/§6),与旧取件/上传链路无关,
因此新增 RECONCILIATION_ENABLED(默认 false)单独接线 api 与 worker 的对账服务:
- appconfig 解析该开关,不再借用 TEST_WEKNORA_ENABLED
- compose/.env.example 透传,默认关闭,生产按授权再开
- 验收候选(candidate_runtime.py 连 QA 库分支)显式置 true
- 文档补开关口径,加配置解析用例
2026-12-01 18:33:04 +08:00

194 lines
10 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""Run the sealed candidate on an isolated acceptance stack."""
import argparse
import ipaddress
import json
from pathlib import Path
import re
import secrets
import sys
import tempfile
from types import SimpleNamespace
from urllib.parse import quote
import production_cd as cd
import qa_env
STATE = Path.home() / '.local/state/kg-candidate-release'
def isolated_subnet(exclude=()):
nets = cd.run(['docker', 'network', 'ls', '-q'], 'list Docker networks').decode().split()
data = json.loads(cd.run(['docker', 'network', 'inspect', *nets], 'read Docker networks')) if nets else []
occupied = [ipaddress.ip_network(row['Subnet']) for net in data for row in net['IPAM']['Config'] or []
if row.get('Subnet') and ':' not in row['Subnet']]
routes = json.loads(cd.run(['ip', '-j', '-4', 'route'], 'read host routes'))
occupied += [ipaddress.ip_network(route['dst'], strict=False) for route in routes if route['dst'] != 'default']
occupied += [ipaddress.ip_network(subnet) for subnet in exclude]
for subnet in ipaddress.ip_network('10.241.233.0/24').subnets(new_prefix=28):
if not any(subnet.overlaps(other) for other in occupied):
return str(subnet)
raise cd.CDError('no available candidate subnet')
def qa_database(path):
db = qa_env.database_config(path)
passfile, cert = [path.parent / name for name in ('qa.pgpass', 'rds-ca.pem')]
qa_env.private_file(passfile)
qa_env.private_file(cert)
endpoint = f"{db['host']}:{db['port']}:"
expected = f"{endpoint}{db['database']}:{db['user']}:"
entries = [line for line in passfile.read_text().splitlines() if line and not line.startswith('#')]
qa_entry = re.compile(re.escape(endpoint) + r'kg_qa_[a-z0-9_]{1,56}:kg_qa_[a-z0-9_]{1,56}:(?:[^:\\]|\\.)+')
cd.require(all(qa_entry.fullmatch(line) for line in entries), 'pgpass must contain only exact QA entries at the configured endpoint')
matching = [line for line in entries if line.startswith(expected)]
cd.require(len(matching) == 1, 'pgpass must contain exactly one entry for the configured QA database and role')
password = re.sub(r'\\(.)', r'\1', matching[0][len(expected):])
cd.require(bool(password), 'dedicated QA database password missing')
url = (f"postgresql://{db['user']}:{quote(password, safe='')}@{db['host']}:{db['port']}/{db['database']}"
'?sslmode=verify-full&sslrootcert=/run/qa/rds-ca.pem')
return url, cert
def qa_process_command(role):
if role not in ('api', 'worker'):
raise ValueError('unexpected QA process')
return ['/bin/sh', '-ec', 'export DATABASE_URL="$${DATABASE_URL}&pool_max_conns=2"; exec /app/' + role]
APP_UID = 65532
def qa_binding_key(image):
"""Give QA candidates one stable binding master key, readable by the application user."""
path = STATE / 'qa-binding-master.key'
if not path.exists():
cd.atomic_write(path, secrets.token_bytes(32), mode=0o600)
cd.run(['docker', 'run', '--rm', '--user', '0', '-v', f'{path.parent}:/run/kg-key', image,
'chown', f'{APP_UID}:{APP_UID}', f'/run/kg-key/{path.name}'],
'hand the QA binding master key to the application user', timeout=90)
info = path.lstat()
cd.require(info.st_mode & 0o777 == 0o600 and info.st_size == 32 and info.st_uid == APP_UID,
'QA binding master key must be a 32-byte file owned by the application user with mode 0600')
return path
def ready(directory, bundle, test_database=None):
bundle = bundle.resolve()
manifest = cd.read_json(bundle / 'release.json')
digest = cd.hash_file(bundle / 'release.json')
request = {key: manifest[key] for key in ('sha', 'task')}
request['bundle'] = digest
cd.verify_bundle(bundle, request)
project = 'kg-batch-' + digest[:20] + ('-smoke' if test_database is None else '')
cf = directory / 'compose.json'
receipt_path = directory / 'ready.json'
cmd = ['docker', 'compose', '-p', project, '-f', str(cf)]
if cf.exists():
cd.require(receipt_path.exists(), 'candidate startup is unresolved; inspect its Compose project')
receipt = cd.read_json(cd.immutable_file(receipt_path))
cd.require(receipt['task'] == request['task'] and receipt['bundle'] == digest, 'candidate already holds another bundle')
attest(bundle, receipt)
return receipt
services = {}
env = {'APP_ADDR': '0.0.0.0:8080', 'TEST_WEKNORA_ENABLED': 'false', 'PP_SCAN_ENABLED': 'false',
'RELEASE_WORKER_ENABLED': 'false', 'PRODUCTION_RELEASE_REQUESTS_ENABLED': 'false',
'DOBOTAI_OPS_READ_ENABLED': 'false', 'DOBOTAI_OPS_DIRECTORY_SYNC_ENABLED': 'false'}
if test_database is None:
password = secrets.token_hex(24)
cd.atomic_write(directory / 'postgres.env', f'POSTGRES_USER=qa\nPOSTGRES_DB=governance\nPOSTGRES_PASSWORD={password}\n'.encode())
env['DATA' + 'BASE_URL'] = f'postgres://qa:{password}@postgres:5432/governance?sslmode=disable'
services['postgres'] = {'image': 'postgres:17-alpine', 'env_file': [str(directory / 'postgres.env')],
'tmpfs': ['/var/lib/postgresql/data'],
'healthcheck': {'test': ['CMD', 'pg_isready', '-U', 'qa', '-d', 'governance'],
'interval': '2s', 'timeout': '2s', 'retries': 20}}
else:
url, cert = qa_database(test_database)
env['DATA' + 'BASE_URL'] = url
cd.atomic_write(directory / 'rds-ca.pem', cert.read_bytes(), mode=0o444)
env['WEKNORA_BINDING_MASTER_KEY_FILE'] = '/run/qa/binding-master.key'
# 验收候选要连 QA 的测试 WeKnora(同网段明文 http),与生产部署口径一致。
env['WEKNORA_ALLOW_PRIVATE_HTTP'] = 'true'
# 导入对账(T6)只对测试库做,候选必须真的接线;它与旧的取件/上传链路
# (TEST_WEKNORA_ENABLED)解耦,租户 Key 走知识库绑定。
env['RECONCILIATION_ENABLED'] = 'true'
app_env = directory / 'app.env'
cd.atomic_write(app_env, ''.join(f'{k}={v}\n' for k, v in env.items()).encode())
names = {role: f'{project}-{role}' for role in cd.ROLES}
for role, item in manifest['images'].items():
archive = bundle / f'{role}.tar'
cd.verify_archive(archive, item['id'])
cd.run(['docker', 'load', '-i', str(archive)], 'load sealed candidate image', timeout=150)
services[role] = {'image': item['id'], 'container_name': names[role]}
key = qa_binding_key(manifest['images']['api']['id']) if test_database is not None else None
for role in ('api', 'worker'):
services[role]['env_file'] = [str(app_env)]
if test_database is not None:
services[role]['volumes'] = [f'{directory / "rds-ca.pem"}:/run/qa/rds-ca.pem:ro',
f'{key}:/run/qa/binding-master.key:ro']
services['api']['healthcheck'] = {'test': ['CMD', 'curl', '-fsS', 'http://127.0.0.1:8080/health'],
'interval': '2s', 'timeout': '3s', 'retries': 45}
if test_database is None:
services['api']['depends_on'] = {'postgres': {'condition': 'service_healthy'}}
services['worker'].update(command=['/app/worker'], depends_on={'api': {'condition': 'service_healthy'}})
if test_database is not None:
# Apply the pgx budget to the application process. The independent libpq
# migration probe reads the original, TLS-verified DSN from Docker exec.
for role in ('api', 'worker'):
services[role]['command'] = qa_process_command(role)
services['web'].update(ports=['127.0.0.1::8080'], depends_on={'api': {'condition': 'service_healthy'}})
internal_subnet = isolated_subnet()
networks = {'default': {'internal': test_database is None, 'ipam': {'config': [{'subnet': internal_subnet}]}}}
if test_database is None:
# The private smoke network has no NAT. Only the web container gets an ingress network.
networks['ingress'] = {'ipam': {'config': [{'subnet': isolated_subnet([internal_subnet])}]}}
services['web']['networks'] = {'default': {}, 'ingress': {}}
cd.record(cf, {'services': services, 'networks': networks})
try:
cd.run(cmd + ['up', '-d', '--no-build', '--pull', 'never'], 'start candidate Compose project', timeout=130)
raw_ports = json.loads(cd.run(['docker', 'inspect', '--format', '{{json .NetworkSettings.Ports}}', names['web']],
'read candidate web binding'))
port = (raw_ports or {}).get('8080/tcp') or []
cd.require(len(port) == 1 and port[0].get('HostIp') == '127.0.0.1'
and re.fullmatch(r'[1-9][0-9]{0,4}', port[0].get('HostPort', '')),
'candidate web has no verified loopback binding')
receipt = {**request, 'url': f'http://127.0.0.1:{port[0]["HostPort"]}', 'containers': names,
'images': {role: image['id'] for role, image in manifest['images'].items()},
'mode': 'smoke' if test_database is None else 'acceptance'}
cd.wait_ready(lambda: attest(bundle, receipt), seconds=65)
receipt['ready_at'] = cd.stamp()
cd.record(receipt_path, receipt)
return receipt
except Exception:
cd.run(cmd + ['down', '--timeout', '3'], 'stop unsuccessful candidate Compose project', timeout=40)
raise
def attest(bundle, receipt):
cd.require(cd.hash_file(bundle / 'release.json') == receipt['bundle'], 'candidate bundle changed after deployment')
cd.attest(SimpleNamespace(sha=receipt['sha'], task=receipt['task'], directory=bundle,
test_url=receipt['url'], **receipt['containers']))
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('bundle', type=Path)
args = parser.parse_args()
with tempfile.TemporaryDirectory(prefix='kg-candidate-smoke-') as temp:
directory = Path(temp)
try:
print(json.dumps(ready(directory, args.bundle)))
finally:
if (directory / 'compose.json').exists():
digest = cd.hash_file(args.bundle / 'release.json')
cmd = ['docker', 'compose', '-p', 'kg-batch-' + digest[:20] + '-smoke', '-f', str(directory / 'compose.json')]
cd.run(cmd + ['down', '--timeout', '3'], 'remove disposable rehearsal containers', timeout=45)
if __name__ == '__main__':
try:
main()
except (cd.CDError, qa_env.QAError, OSError, ValueError) as exc:
sys.exit(f'Candidate runtime: {exc}')