cmvr-wms/mobile-app/deploy/install-ota.py
lixiaolong 149bde836f feat(assistant): 扩展业务助手功能支持更多文档类型和业务场景
- 新增 PDF 文档支持,包括格式校验和完整性检查
- 扩展 Word、TXT 和 ZIP 格式附件处理能力
- 添加 Excel 附件可选择仅作为业务文件不解析行数据
- 实现业务助手表格布局配置新增库存和预算字段
- 集成通知、反馈通知等新的业务助手动作类型
- 完善部门管理包含父级部门和排序字段支持
- 增强业务规则校验涵盖更多系统管理场景
- 优化附件上传限制提示信息更准确
- 添加生成文件下载的安全性校验机制
- 扩展测试覆盖确保各业务动作规则正确性
2026-10-18 08:49:30 +08:00

131 lines
6.4 KiB
Python

"""Initial OTA deployment only. Upload public, signed release files; never keys.
Run on the authorized production server as its existing deployment user.
Backs up nginx, validates before reload, and preserves the existing backend.
"""
import datetime
import fcntl
import hashlib
import json
import os
from pathlib import Path
import re
import shutil
import subprocess
import sys
import tarfile
import time
import urllib.request
APP = Path('/data/apps/cmvr-project-prod')
OTA = APP / 'mobile-ota'
RUNTIME = 'ac523f4137469f9f4b0faaca30982e68445686df'
def run(*args):
return subprocess.check_output(args, stderr=subprocess.STDOUT, text=True).strip()
def get(url, headers=None):
with urllib.request.urlopen(urllib.request.Request(url, headers=headers or {}), timeout=10) as response:
return response.status, dict(response.headers), response.read()
def main():
archive, expected_hash, image = sys.argv[1:]
if not re.fullmatch(r'(?:node@)?sha256:[a-f0-9]{64}', image):
raise ValueError('Require a pinned, verified Node runtime image digest')
if not run('docker', 'run', '--rm', '--network', 'none', image, 'node', '--version').startswith('v24.'):
raise ValueError('Require the verified Node 24 runtime')
if hashlib.sha256(Path(archive).read_bytes()).hexdigest() != expected_hash:
raise ValueError('Deployment archive hash mismatch')
if (OTA / 'deployment.json').exists():
raise RuntimeError('Initial deployment already completed; inspect before a subsequent release')
nginx = (APP / 'current/nginx.conf').resolve(strict=True)
if not str(nginx).startswith(str(APP / 'releases') + '/'):
raise RuntimeError('Unexpected production nginx path')
original = nginx.read_bytes()
if b'/updates/prod' in original or b'127.0.0.1:8190' in original:
raise RuntimeError('OTA nginx routes already exist; inspect before modifying')
before = run('docker', 'inspect', 'cmvr-project-prod-backend', '--format', '{{.State.StartedAt}}')
frontend_before = run('docker', 'inspect', 'cmvr-project-prod-frontend', '--format', '{{.State.StartedAt}}')
date = datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%d-%H%M%S')
backup = APP / 'backups' / ('mobile-ota-' + date)
backup.mkdir(mode=0o700)
shutil.copy2(nginx, backup / 'nginx.conf')
OTA.mkdir(mode=0o700, exist_ok=True)
release = OTA / 'releases' / date
release.mkdir(parents=True)
with tarfile.open(archive, 'r:gz') as bundle:
for member in bundle.getmembers():
target = (release / member.name).resolve()
if not target.is_relative_to(release.resolve()) or not (member.isfile() or member.isdir()):
raise ValueError('Unsafe deployment archive member')
bundle.extractall(release)
for entry in release.rglob('*'):
if entry.suffix in {'.p12', '.jks', '.keystore', '.dpapi'} or 'private-key' in entry.name:
raise ValueError('Private material is forbidden on update server')
entry.chmod(0o755 if entry.is_dir() else 0o644)
release.chmod(0o755)
os.symlink(release, OTA / 'current')
shutil.copytree(release / 'data', OTA / 'data')
shutil.copy2(release / 'docker-compose.yml', OTA / 'docker-compose.yml')
(OTA / '.env').write_text('OTA_NODE_IMAGE=' + image + '\n')
(OTA / '.env').chmod(0o600)
locations = (release / 'nginx-ota.locations.conf').read_text()
candidate = original.decode().rstrip()
if not candidate.endswith('}'):
raise ValueError('Unexpected nginx structure')
candidate = candidate[:-1] + locations + '\n}\n'
candidate_path = backup / 'nginx-candidate.conf'
candidate_path.write_text(candidate)
run('docker', 'run', '--rm', '--network', 'none', '-v', str(candidate_path) + ':/etc/nginx/conf.d/default.conf:ro',
'nginx:1.25.5', 'nginx', '-t')
compose = ['docker', 'compose', '--project-directory', str(OTA), '-f', str(OTA / 'docker-compose.yml')]
nginx_changed = False
try:
run(*compose, 'up', '-d', '--no-deps', 'ota')
for attempt in range(20):
try:
if get('http://127.0.0.1:8190/health')[0] == 200:
break
except Exception:
time.sleep(1)
else:
raise RuntimeError('OTA health check timed out')
# Preserve the inode: the running nginx has a read-only bind mount of this file.
nginx.write_text(candidate)
nginx_changed = True
run('docker', 'exec', 'cmvr-project-prod-frontend', 'nginx', '-t')
run('docker', 'exec', 'cmvr-project-prod-frontend', 'nginx', '-s', 'reload')
time.sleep(1)
status, headers, body = get('http://127.0.0.1/updates/prod', {
'expo-platform': 'android', 'expo-runtime-version': RUNTIME, 'expo-protocol-version': '1'})
manifest = json.loads(body)
if status != 200 or manifest['runtimeVersion'] != RUNTIME or manifest['metadata']['environment'] != 'prod':
raise RuntimeError('Public route did not return production manifest')
if not any(key.lower() == 'expo-signature' for key in headers):
raise RuntimeError('Signature header missing after proxy')
after = run('docker', 'inspect', 'cmvr-project-prod-backend', '--format', '{{.State.StartedAt}}')
frontend_after = run('docker', 'inspect', 'cmvr-project-prod-frontend', '--format', '{{.State.StartedAt}}')
if before != after or frontend_before != frontend_after:
raise RuntimeError('Existing application container unexpectedly restarted')
result = {'deployedAt': date, 'url': 'http://192.168.28.10/updates/prod', 'container': 'cmvr-mobile-ota-prod',
'image': image, 'runtime': RUNTIME, 'updateId': manifest['id'], 'backup': str(backup),
'backendRestarted': False, 'frontendRestarted': False, 'databaseTouched': False}
(OTA / 'deployment.json').write_text(json.dumps(result, indent=2))
print(json.dumps(result))
except Exception:
if nginx_changed:
nginx.write_bytes(original)
run('docker', 'exec', 'cmvr-project-prod-frontend', 'nginx', '-t')
run('docker', 'exec', 'cmvr-project-prod-frontend', 'nginx', '-s', 'reload')
run(*compose, 'stop', 'ota')
raise
if __name__ == '__main__':
with (APP / '.mobile-ota-deploy.lock').open('w') as lock:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
main()