354 lines
15 KiB
Python
354 lines
15 KiB
Python
"""生成兼容旧 Windows 包的自包含 first-aid 修复入口。"""
|
|
from __future__ import annotations
|
|
|
|
from contextlib import contextmanager
|
|
from datetime import datetime
|
|
import hashlib
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import tempfile
|
|
import uuid
|
|
|
|
MANAGER = 'deploy/offline/update_manager.py'
|
|
CONTROL = 'deploy/offline/control.py'
|
|
MANAGER_SOURCE = Path(__file__).with_name('update_manager.py')
|
|
CONTROL_SOURCE = Path(__file__).with_name('control.py')
|
|
|
|
# 仅接受已交付的历史源码。当前修复版本摘要在运行时由内嵌源码计算。
|
|
OLD_MANAGER_SHA256 = frozenset({
|
|
'29512f15a9ee329bc7c7777454bdd79aa7ffd11c3cffa9400b8a4585bdabf35b',
|
|
'b91cb7fec10e183d2904d86f032ff0ffcf7f19f7cb27aecd2d803d3448685482',
|
|
'a4bd05789f559fede0bed083ce61123307d6b5cf52fa638b6bde1fa112a0348a',
|
|
})
|
|
OLD_CONTROL_SHA256 = frozenset({
|
|
'd98fa24d17e9bdd90ff37f9886df280451eceabac0df35d2eeecf4fe615bc6f1',
|
|
})
|
|
JOURNAL_SAFE_PHASES = frozenset({'complete', 'rolledBack'})
|
|
JOURNAL_ACTIVE_PHASES = frozenset({
|
|
'stopping', 'backingUp', 'installing', 'restarting', 'rollingBack',
|
|
})
|
|
MODULE_MARKER = b'\r\n# QUALITY_UPDATE_CHECK_REPAIR_MODULE\r\n'
|
|
PAYLOAD_MARKER = b'\r\n# QUALITY_UPDATE_CHECK_REPAIR_PAYLOAD\r\n'
|
|
|
|
|
|
def sha(data: bytes) -> str:
|
|
return hashlib.sha256(data).hexdigest()
|
|
|
|
|
|
def unique_object(pairs):
|
|
value = {}
|
|
for key, item in pairs:
|
|
if key in value:
|
|
raise ValueError('duplicate JSON key')
|
|
value[key] = item
|
|
return value
|
|
|
|
|
|
def local(root: Path, name: str) -> Path:
|
|
path = root.joinpath(*name.split('/'))
|
|
if path.is_symlink() or not path.resolve().is_relative_to(root):
|
|
raise RuntimeError('修复路径异常,已停止。')
|
|
return path
|
|
|
|
|
|
def atomic(path: Path, data: bytes) -> None:
|
|
fd, temporary_name = tempfile.mkstemp(
|
|
prefix=path.name + '.firstaid-', suffix='.tmp', dir=path.parent,
|
|
)
|
|
temporary = Path(temporary_name)
|
|
try:
|
|
with os.fdopen(fd, 'wb') as stream:
|
|
stream.write(data)
|
|
stream.flush()
|
|
os.fsync(stream.fileno())
|
|
os.replace(temporary, path)
|
|
finally:
|
|
temporary.unlink(missing_ok=True)
|
|
|
|
|
|
@contextmanager
|
|
def update_lock(root: Path):
|
|
root = Path(root).resolve()
|
|
directory = local(root, '.runtime/update')
|
|
directory.mkdir(parents=True, exist_ok=True)
|
|
directory = local(root, '.runtime/update')
|
|
lock_path = local(root, '.runtime/update/worker.lock')
|
|
with lock_path.open('a+b') as stream:
|
|
if os.name == 'nt':
|
|
import msvcrt
|
|
# The updater locks byte 0 with msvcrt.locking as well.
|
|
stream.seek(0)
|
|
try:
|
|
msvcrt.locking(stream.fileno(), msvcrt.LK_NBLCK, 1)
|
|
except OSError:
|
|
raise RuntimeError('更新或恢复任务仍在运行,请等待结束后再运行本修复。') from None
|
|
try:
|
|
yield
|
|
finally:
|
|
stream.seek(0)
|
|
msvcrt.locking(stream.fileno(), msvcrt.LK_UNLCK, 1)
|
|
else:
|
|
import fcntl
|
|
try:
|
|
fcntl.flock(stream.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
except OSError:
|
|
raise RuntimeError('更新或恢复任务仍在运行,请等待结束后再运行本修复。') from None
|
|
try:
|
|
yield
|
|
finally:
|
|
fcntl.flock(stream.fileno(), fcntl.LOCK_UN)
|
|
|
|
|
|
def windows_process_active(pid: int) -> bool:
|
|
"""只读查询 Windows PID;不存在返回 False,权限或 API 问题 fail closed。"""
|
|
import ctypes
|
|
from ctypes import wintypes
|
|
|
|
kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
|
|
kernel32.OpenProcess.argtypes = (wintypes.DWORD, wintypes.BOOL, wintypes.DWORD)
|
|
kernel32.OpenProcess.restype = wintypes.HANDLE
|
|
kernel32.GetExitCodeProcess.argtypes = (wintypes.HANDLE, ctypes.POINTER(wintypes.DWORD))
|
|
kernel32.GetExitCodeProcess.restype = wintypes.BOOL
|
|
kernel32.CloseHandle.argtypes = (wintypes.HANDLE,)
|
|
kernel32.CloseHandle.restype = wintypes.BOOL
|
|
|
|
process_query_limited_information = 0x1000
|
|
error_invalid_parameter = 87
|
|
still_active = 259
|
|
handle = kernel32.OpenProcess(process_query_limited_information, False, pid)
|
|
if not handle:
|
|
error = ctypes.get_last_error()
|
|
if error == error_invalid_parameter:
|
|
return False
|
|
raise RuntimeError('无法只读确认 Windows 更新工作进程,未修改文件。')
|
|
|
|
try:
|
|
exit_code = wintypes.DWORD()
|
|
if not kernel32.GetExitCodeProcess(handle, ctypes.byref(exit_code)):
|
|
raise RuntimeError('无法读取 Windows 更新工作进程状态,未修改文件。')
|
|
return exit_code.value == still_active
|
|
finally:
|
|
if not kernel32.CloseHandle(handle):
|
|
raise RuntimeError('无法关闭 Windows 进程查询句柄,未修改文件。')
|
|
|
|
|
|
def worker_active(root: Path) -> bool:
|
|
worker_path = local(root, '.runtime/update/worker.json')
|
|
if not worker_path.exists():
|
|
return False
|
|
try:
|
|
value = json.loads(worker_path.read_text(encoding='utf-8'), object_pairs_hook=unique_object)
|
|
except (OSError, ValueError, UnicodeError):
|
|
raise RuntimeError('更新工作记录无法识别,未修改文件。') from None
|
|
pid = value.get('pid') if isinstance(value, dict) else None
|
|
if type(pid) is not int or pid <= 0:
|
|
raise RuntimeError('更新工作记录无法识别,未修改文件。')
|
|
if os.name == 'nt':
|
|
return windows_process_active(pid)
|
|
try:
|
|
os.kill(pid, 0)
|
|
except ProcessLookupError:
|
|
return False
|
|
except PermissionError:
|
|
return True
|
|
except OSError as error:
|
|
if getattr(error, 'winerror', None) == 87:
|
|
return False
|
|
raise RuntimeError('无法确认更新工作进程状态,未修改文件。') from None
|
|
return True
|
|
|
|
|
|
def check_journal(root: Path) -> None:
|
|
journal_path = local(root, '.runtime/update/journal.json')
|
|
if not journal_path.exists():
|
|
return
|
|
try:
|
|
journal = json.loads(journal_path.read_text(encoding='utf-8'), object_pairs_hook=unique_object)
|
|
except (OSError, ValueError, UnicodeError):
|
|
raise RuntimeError('更新恢复记录无法识别,未修改文件。') from None
|
|
phase = journal.get('phase') if isinstance(journal, dict) else None
|
|
if isinstance(phase, str) and phase in JOURNAL_SAFE_PHASES:
|
|
return
|
|
if isinstance(phase, str) and phase in JOURNAL_ACTIVE_PHASES:
|
|
raise RuntimeError('上次更新或恢复尚未结束,请先使用原启动入口恢复。')
|
|
raise RuntimeError('更新恢复记录状态未知,未修改文件。')
|
|
|
|
|
|
def read_hardened_sources() -> tuple[bytes, bytes]:
|
|
for path in (MANAGER_SOURCE, CONTROL_SOURCE):
|
|
if path.is_symlink() or not path.is_file():
|
|
raise RuntimeError('当前修复源码不完整,无法生成 first-aid 入口。')
|
|
return MANAGER_SOURCE.read_bytes(), CONTROL_SOURCE.read_bytes()
|
|
|
|
|
|
def check_source_state(actual: str, recorded: str, old_hashes: frozenset[str], target: str, label: str) -> None:
|
|
accepted = old_hashes | {target}
|
|
if actual not in accepted or recorded not in accepted:
|
|
raise RuntimeError(label + '版本与本修复不匹配,未覆盖现有程序。')
|
|
# 只允许原版到目标版之间的中断混合,不接纳两个互不相同的旧版本。
|
|
if actual != recorded and target not in (actual, recorded):
|
|
raise RuntimeError(label + '源码与清单摘要不一致,未覆盖现有程序。')
|
|
|
|
|
|
def make_backup(root: Path, before: dict[str, bytes]) -> Path:
|
|
backup_parent = local(root, '.runtime/update-check-repair-backups')
|
|
backup_parent.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
backup_parent = local(root, '.runtime/update-check-repair-backups')
|
|
temporary = Path(tempfile.mkdtemp(prefix='.firstaid-', dir=backup_parent))
|
|
final = backup_parent / (datetime.now().strftime('%Y%m%d-%H%M%S') + '-' + uuid.uuid4().hex[:8])
|
|
try:
|
|
for name, data in before.items():
|
|
target = temporary / name
|
|
with target.open('xb') as stream:
|
|
stream.write(data)
|
|
stream.flush()
|
|
os.fsync(stream.fileno())
|
|
os.replace(temporary, final)
|
|
except BaseException:
|
|
for child in temporary.iterdir():
|
|
child.unlink(missing_ok=True)
|
|
temporary.rmdir()
|
|
raise
|
|
return final
|
|
|
|
|
|
def repair(root: Path, manager_payload: bytes | None = None,
|
|
control_payload: bytes | None = None) -> dict:
|
|
root = Path(root).resolve()
|
|
if manager_payload is None or control_payload is None:
|
|
manager_payload, control_payload = read_hardened_sources()
|
|
if not isinstance(manager_payload, bytes) or not isinstance(control_payload, bytes):
|
|
raise TypeError('修复源码必须为字节。')
|
|
|
|
manifest_path = local(root, 'manifest.json')
|
|
manager_path = local(root, MANAGER)
|
|
control_path = local(root, CONTROL)
|
|
if (not manifest_path.is_file() or not manager_path.is_file() or not control_path.is_file()
|
|
or not local(root, 'deploy/bootstrap/windows-start.ps1').is_file()):
|
|
raise RuntimeError('请将本文件放到原 QualityCenter 目录,与“一键部署启动.cmd”并列后运行。')
|
|
|
|
with update_lock(root):
|
|
if worker_active(root):
|
|
raise RuntimeError('更新或恢复工作进程仍在运行,请等待结束后再运行本修复。')
|
|
check_journal(root)
|
|
|
|
before = {
|
|
'manifest.json': manifest_path.read_bytes(),
|
|
'update_manager.py': manager_path.read_bytes(),
|
|
'control.py': control_path.read_bytes(),
|
|
}
|
|
try:
|
|
manifest = json.loads(before['manifest.json'].decode('utf-8-sig'), object_pairs_hook=unique_object)
|
|
except (ValueError, UnicodeError):
|
|
raise RuntimeError('Windows 文件清单无法识别,未修改文件。') from None
|
|
if not isinstance(manifest, dict) or manifest.get('platform') != 'windows':
|
|
raise RuntimeError('本修复仅适用于 Windows 离线包。')
|
|
entries = manifest.get('files')
|
|
if not isinstance(entries, list) or any(not isinstance(entry, dict) for entry in entries):
|
|
raise RuntimeError('Windows 文件清单结构无法识别,未修改文件。')
|
|
names = [entry.get('path') for entry in entries]
|
|
if any(not isinstance(name, str) for name in names) or len(set(names)) != len(names):
|
|
raise RuntimeError('文件清单存在重复路径,未修改。')
|
|
|
|
targets = {
|
|
MANAGER: (manager_path, before['update_manager.py'], manager_payload,
|
|
OLD_MANAGER_SHA256, '更新检查脚本'),
|
|
CONTROL: (control_path, before['control.py'], control_payload,
|
|
OLD_CONTROL_SHA256, '服务控制脚本'),
|
|
}
|
|
selected = {}
|
|
for name, (path, current, payload, old_hashes, label) in targets.items():
|
|
rows = [entry for entry in entries if entry.get('path') == name]
|
|
if len(rows) != 1 or not isinstance(rows[0].get('sha256'), str):
|
|
raise RuntimeError('文件清单缺少唯一的' + label + '摘要,未修改文件。')
|
|
target_hash = sha(payload)
|
|
check_source_state(sha(current), rows[0]['sha256'], old_hashes, target_hash, label)
|
|
selected[name] = (rows[0], target_hash)
|
|
|
|
if (before['update_manager.py'] == manager_payload
|
|
and before['control.py'] == control_payload
|
|
and all(row['sha256'] == digest for row, digest in selected.values())):
|
|
return {'alreadyRepaired': True, 'changedFiles': 0}
|
|
|
|
for name, (path, current, payload, _old_hashes, _label) in targets.items():
|
|
if local(root, name).read_bytes() != current:
|
|
raise RuntimeError('程序文件正被其他进程更新,未执行修复。')
|
|
if manifest_path.read_bytes() != before['manifest.json']:
|
|
raise RuntimeError('文件清单正被其他进程更新,未执行修复。')
|
|
|
|
for name, (row, digest) in selected.items():
|
|
row['sha256'] = digest
|
|
after_manifest = (json.dumps(manifest, ensure_ascii=False, indent=2) + '\n').encode('utf-8')
|
|
backup = make_backup(root, before)
|
|
try:
|
|
atomic(manager_path, manager_payload)
|
|
atomic(control_path, control_payload)
|
|
atomic(manifest_path, after_manifest)
|
|
except BaseException as original_error:
|
|
rollback_errors = []
|
|
for path, data in ((manager_path, before['update_manager.py']),
|
|
(control_path, before['control.py']),
|
|
(manifest_path, before['manifest.json'])):
|
|
try:
|
|
atomic(path, data)
|
|
except BaseException as rollback_error:
|
|
rollback_errors.append(str(rollback_error))
|
|
if rollback_errors:
|
|
raise RuntimeError('first-aid 写入失败,自动回滚未全部完成;原备份位于 '
|
|
+ str(backup.relative_to(root))) from original_error
|
|
raise
|
|
return {
|
|
'changedFiles': 3,
|
|
'backup': str(backup.relative_to(root)),
|
|
'updateCheckRepaired': True,
|
|
'controlRecoveryRepaired': True,
|
|
}
|
|
|
|
|
|
def command_file() -> bytes:
|
|
"""生成单个可双击 CMD;源码字节以内嵌 Python 字节字面量保存。"""
|
|
manager_payload, control_payload = read_hardened_sources()
|
|
header = r'''@echo off
|
|
setlocal
|
|
chcp 65001 >nul
|
|
set "PYTHONUTF8=1"
|
|
set "PYTHONIOENCODING=utf-8"
|
|
set "PYTHONDONTWRITEBYTECODE=1"
|
|
if not exist "%~dp0runtimes\python\python.exe" (
|
|
echo 请将本文件放到原 QualityCenter 目录,与一键部署启动放在一起。
|
|
pause
|
|
exit /b 1
|
|
)
|
|
"%~dp0runtimes\python\python.exe" -I -S -B -X utf8 -c "import sys;from pathlib import Path;p=Path(sys.argv[1]);b=p.read_bytes();m=bytes((13,10))+b'# QUALITY_UPDATE_CHECK_REPAIR_MODULE'+bytes((13,10));t=b.rsplit(m,1)[1];q=bytes((13,10))+b'# QUALITY_UPDATE_CHECK_REPAIR_PAYLOAD'+bytes((13,10));s,d=t.rsplit(q,1);n={'__name__':'quality_firstaid','__file__':str(p)};exec(compile(s.decode('utf-8'),str(p),'exec'),n);v={};exec(compile(d.decode('ascii'),str(p),'exec'),v);import json;print(json.dumps(n['repair'](p.parent,v['PATCHED_MANAGER'],v['PATCHED_CONTROL']),ensure_ascii=False))" "%~f0"
|
|
if errorlevel 1 (
|
|
echo 修复未完成,请保留上方报错;文件和恢复备份已按修复结果保留。
|
|
pause
|
|
exit /b 1
|
|
)
|
|
echo 更新检查和中断恢复兼容代码已修复;服务、数据、版本信息和更新缓存未启动或导入。
|
|
pause
|
|
exit /b
|
|
'''
|
|
output = header.replace('\n', '\r\n').encode('utf-8')
|
|
output += MODULE_MARKER + Path(__file__).read_bytes()
|
|
payload = (
|
|
'PATCHED_MANAGER = ' + repr(manager_payload) + '\n'
|
|
+ 'PATCHED_CONTROL = ' + repr(control_payload) + '\n'
|
|
).encode('ascii')
|
|
return output + PAYLOAD_MARKER + payload
|
|
|
|
|
|
if __name__ == '__main__':
|
|
import argparse
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument('--root', type=Path)
|
|
parser.add_argument('--write-command', type=Path)
|
|
args = parser.parse_args()
|
|
if args.write_command:
|
|
args.write_command.write_bytes(command_file())
|
|
elif args.root:
|
|
print(json.dumps(repair(args.root), ensure_ascii=False))
|
|
else:
|
|
parser.error('请选择 --root 或 --write-command')
|