Files
cbb-refresh-verify-795/src/cbb_refresh_verify/residual_sessions.py
T

380 lines
20 KiB
Python

"""Preview and cooperatively close the exact native sessions a user confirms."""
from contextlib import contextmanager
import json
import os
from pathlib import Path
import re
import time
from uuid import uuid4
from .owner_probe import query_process_snapshot
from .native_engineering_identity import _OWNER_NAMES
_NAMES = {'expeditionpcb.exe', 'librarymanager.exe', 'icdbprojectbackup.exe',
'viewdraw.exe', 'icdbnetserver.exe', 'icdbserver.exe',
'reuseblockimporter.exe', 'cleanwglib.exe', 'cscript.exe', 'wscript.exe'} | _OWNER_NAMES
_WORKER_NAMES = {'python.exe', 'pythonw.exe', 'cbbrefreshverify.exe'}
_WORKER_FLAGS = ('--verify-worker', '--repair-worker', '--management-worker', '--native-backup-worker')
@contextmanager
def _process_handle(pid, *, terminate=False):
import win32api, win32con
handle = win32api.OpenProcess(win32con.SYNCHRONIZE | 0x1000 | (1 if terminate else 0), False, int(pid))
try:
yield handle
finally:
handle.Close()
def _handle_identity(handle):
import ctypes
from ctypes import wintypes
import win32process
kernel = ctypes.WinDLL('kernel32', use_last_error=True)
kernel.QueryFullProcessImageNameW.argtypes = [wintypes.HANDLE, wintypes.DWORD,
wintypes.LPWSTR, ctypes.POINTER(wintypes.DWORD)]
kernel.QueryFullProcessImageNameW.restype = wintypes.BOOL
buffer = ctypes.create_unicode_buffer(32768)
length = wintypes.DWORD(len(buffer))
if not kernel.QueryFullProcessImageNameW(int(handle), 0, buffer, ctypes.byref(length)):
raise ctypes.WinError(ctypes.get_last_error())
return {'created_handle': win32process.GetProcessTimes(handle)['CreationTime'].isoformat(),
'image': buffer.value}
def _process_identity(row):
with _process_handle(row['pid']) as handle:
return _handle_identity(handle)
def _process_windows(pids):
if not pids: return {}
import win32api, win32con, win32gui, win32process, win32service
from .native_repair_ui import _native_output
result = {pid: [] for pid in pids}
observed = set()
def capture(hwnd, _=None):
pid = win32process.GetWindowThreadProcessId(hwnd)[1]
if pid not in result or hwnd in observed or not win32gui.IsWindowVisible(hwnd):
return
observed.add(hwnd)
children, documents = [], []
def child(handle, _):
kind = win32gui.GetClassName(handle)
if kind == 'MDIClient' and win32gui.GetWindow(handle, win32con.GW_CHILD):
documents.append(handle)
if win32gui.IsWindowVisible(handle):
children.append({'hwnd': int(handle), 'class': kind,
'id': win32gui.GetDlgCtrlID(handle) & 0xffff,
'text': win32gui.GetWindowText(handle), 'enabled': bool(win32gui.IsWindowEnabled(handle))})
win32api.SetLastError(0)
win32gui.EnumChildWindows(hwnd, child, None)
window = {'hwnd': int(hwnd), 'title': win32gui.GetWindowText(hwnd),
'class': win32gui.GetClassName(hwnd), 'enabled': bool(win32gui.IsWindowEnabled(hwnd)),
'children': children, 'documents': documents, 'rect': list(win32gui.GetWindowRect(hwnd))}
if any(c['class'].casefold().startswith('richedit') for c in children):
window['output'] = _native_output([window])
result[pid].append(window)
win32api.SetLastError(0)
def incomplete():
for pid in result:
result[pid].append({'hwnd': 0, 'title': '窗口状态读取不完整', 'class': 'UNCONFIRMED',
'enabled': False, 'children': []})
try:
win32gui.EnumWindows(capture, None)
except Exception:
incomplete()
try:
desktops = win32service.GetProcessWindowStation().EnumDesktops()
except Exception:
incomplete()
return result
for name in desktops:
if name != 'Default' and not name.startswith(('CbbVerify_', 'CbbRepair_', 'CbbManagement_', 'CbbStatusRead_', 'CbbFlagRead_')):
continue
desktop = None
try:
desktop = win32service.OpenDesktop(name, 0, False, win32con.DESKTOP_READOBJECTS)
for hwnd in desktop.EnumDesktopWindows(): capture(int(hwnd))
except Exception:
incomplete()
finally:
if desktop is not None: desktop.CloseDesktop()
return result
def _project_name(row, library):
from .failed_session import _command_args
for arg in _command_args(row['command'])[1:]:
try:
relative = Path(arg.split('=', 1)[-1]).relative_to(library.parent/'ReusableBlocksLP')
if len(relative.parts) >= 2 and relative.parts[1].casefold() == 'work':
return relative.parts[0]
except ValueError:
continue
return '当前库关联会话'
def close_target(name, windows):
"""No save/restore approval and no close against an unknown modal/window."""
main = [w for w in windows if w['class'].startswith('Afx:') and (
name.casefold() == 'icdbprojectbackup.exe' and w['title'].startswith('iCDB Project Backup')
or name.casefold() == 'librarymanager.exe' and w['title'].startswith('Library Manager')
or name.casefold() == 'expeditionpcb.exe' and 'Expedition PCB' in w['title'])]
if len(main) != 1:
return None, '未确认空闲主窗口;有工程时请先在原生窗口保存并关闭'
window = main[0]
for other in windows:
if other is window: continue
benign = (not other['title'] and other['class'] in
('UAC_InputIndicatorOverlayWnd', 'UAC Input Indicator'))
benign = benign or (other['class'] == 'Internet Explorer_Hidden' and not other['title']
and not other.get('children') and other.get('rect', [1, 1, 2, 2])[0:2] == other.get('rect', [1, 1, 2, 2])[2:4])
if not benign: return None, '存在原生弹窗,请先处理该窗口后重新检查'
if not window['enabled']:
return None, '原生程序正在工作,请稍后重新检查'
if any(c['class'].casefold() == 'msctls_progress32' for c in window['children']):
return None, '原生操作尚未结束'
if name.casefold() == 'icdbprojectbackup.exe':
output = window.get('output')
if not isinstance(output, str): return None, '原生输出尚无法确认,请重新检查'
active = list(re.finditer(r'(?i)repairing|restoring|backing up|creating (?:a )?backup', output))
last_load = output.rfind('Backup information loaded correctly.')
failure = output.rfind('Repair project error [')
if active and max(last_load, failure) < active[-1].start():
return None, '备份、恢复或修复需要在原生窗口确认结束后再释放'
return window, ('将正常关闭工程;未保存时等待确认' if window.get('documents') else '可正常关闭')
def _save_question(windows):
for window in windows:
text = '\n'.join(c['text'] for c in window['children'] if c['class'] == 'Static')
buttons = {c['id']: c for c in window['children'] if c['class'] == 'Button' and c['enabled']}
if (window['class'] == '#32770' and 'Expedition' in window['title']
and re.search(r'\bsave\b', text, re.I) and re.search(r'changes|modified', text, re.I)
and set(buttons) == {6, 7, 2}):
return {'hwnd': window['hwnd'], 'text': text, 'buttons': buttons}
return None
def inspect_residual_sessions(library, *, block_names=()):
from .library_lock import _owner_matches_scope, blocker_path, checkpoint_record, has_retained_library
library = Path(library).resolve()
if library.suffix.casefold() != '.lmc' or not library.is_file():
raise ValueError('请选择有效的中心库 .lmc 文件')
blocks = tuple(dict.fromkeys(str(name) for name in block_names))
if any(not name or name in ('.', '..') or any(c in name for c in '\\/:*?"<>|') for name in blocks):
raise ValueError('残留检查的工程名称无效')
roots = tuple(library.parent/'ReusableBlocksLP'/b/'Work' for b in blocks) + (library.parent/'SymbolLibs',)
if not blocks: roots = (library.parent,)
candidates = []
for row in query_process_snapshot():
if row['pid'] == os.getpid(): continue
native = row['name'].casefold() in _NAMES
worker = (row['name'].casefold() in _WORKER_NAMES
and any(flag in row['command'].casefold() for flag in _WORKER_FLAGS))
if not (native or worker): continue
scope = _owner_matches_scope(row, library, roots)
if scope is not False:
candidates.append({**row, 'scope_confirmed': scope is True})
windows = _process_windows({r['pid'] for r in candidates})
sessions = []
for row in candidates:
item = dict(row)
try:
item.update(_process_identity(row))
target, detail = close_target(row['name'], windows.get(row['pid'], [])) if row['scope_confirmed'] else (
None, '归属未确认,请在原生窗口确认工程并关闭后重新检查')
item.update(can_close=target is not None, detail=detail)
except Exception as error:
item.update(can_close=False, detail=f'进程已变化或暂时无法确认:{error}')
item['project'] = _project_name(row, library) if row['scope_confirmed'] else '归属未确认'
item['prompt'] = _save_question(windows.get(row['pid'], [])) if row['scope_confirmed'] else None
sessions.append(item)
previous = []
marker = blocker_path(library)
for path in (marker, marker.with_suffix('.pending')):
if path.exists():
record = checkpoint_record(path)
previous.append({'path': str(path), 'recognized': record is not None,
'status': record.get('status', 'UNRECOGNIZED') if record else 'UNRECOGNIZED',
'time': record.get('time', '') if record else '',
'pid': record.get('pid') if record else None})
if has_retained_library(library):
previous.append({'path': str(library), 'status': 'RETAINED_IN_MEMORY', 'time': '',
'pid': os.getpid(), 'kind': 'in_memory'})
return {'library': str(library), 'block_names': list(blocks), 'sessions': sessions,
'previous_records': previous}
def _request_close(row, *, stop=None):
import win32con, win32event, win32gui, win32process
with _process_handle(row['pid']) as handle:
if win32event.WaitForSingleObject(handle, 0) == win32con.WAIT_OBJECT_0:
return {'release_status': 'RELEASED', 'detail': '已退出'}
identity = _handle_identity(handle)
if identity != {key: row.get(key) for key in ('created_handle', 'image')}:
return {'release_status': 'IDENTITY_CHANGED', 'detail': '进程身份已变化,未关闭'}
windows = _process_windows({row['pid']}).get(row['pid'], [])
if row['name'].casefold() == 'expeditionpcb.exe':
from .failed_session import _startup_snapshot, _cancel_target
for window in windows:
if window['class'] != '#32770': continue
target = _cancel_target(_startup_snapshot(window['hwnd'], row['pid']))
if target:
win32gui.PostMessage(target[1].handle, win32con.BM_CLICK, 0, 0)
deadline = time.monotonic()+3
while time.monotonic() < deadline:
if win32event.WaitForSingleObject(handle, 100) == win32con.WAIT_OBJECT_0:
return {'release_status': 'RELEASED', 'detail': '已取消启动并退出'}
if stop is not None and stop.is_set():
return {'release_status': 'CANCELLED', 'detail': '已停止释放'}
windows = _process_windows({row['pid']}).get(row['pid'], [])
if close_target(row['name'], windows)[0] is not None: break
break
target, detail = close_target(row['name'], windows)
if target is None: return {'release_status': 'WAITING', 'detail': detail}
if stop is not None and stop.is_set():
return {'release_status': 'CANCELLED', 'detail': '已停止释放'}
if win32process.GetWindowThreadProcessId(target['hwnd'])[1] != row['pid']:
return {'release_status': 'IDENTITY_CHANGED', 'detail': '窗口归属已变化,未关闭'}
win32gui.PostMessage(target['hwnd'], win32con.WM_CLOSE, 0, 0)
deadline = time.monotonic()+3
while time.monotonic() < deadline:
if win32event.WaitForSingleObject(handle, 100) == win32con.WAIT_OBJECT_0:
return {'release_status': 'RELEASED', 'detail': '已正常退出'}
if stop is not None and stop.is_set(): break
return {'release_status': 'WAITING', 'detail': '已请求正常关闭;请处理原生窗口,完成后重新检查'}
def _force_close(row, *, stop=None):
"""Separate UI consent permits ending only this exact, scoped process handle."""
import win32api, win32con, win32event
if stop is not None and stop.is_set():
return {'release_status': 'CANCELLED', 'detail': '已停止释放'}
with _process_handle(row['pid'], terminate=True) as handle:
if win32event.WaitForSingleObject(handle, 0) == win32con.WAIT_OBJECT_0:
return {'release_status': 'RELEASED', 'detail': '已退出'}
if _handle_identity(handle) != {k: row.get(k) for k in ('created_handle', 'image')}:
return {'release_status': 'IDENTITY_CHANGED', 'detail': '进程身份已变化,未结束'}
win32api.TerminateProcess(handle, 1)
exited = win32event.WaitForSingleObject(handle, 3000) == win32con.WAIT_OBJECT_0
return {'release_status': 'RELEASED' if exited else 'WAITING',
'detail': '已强制结束,工程需重新检查' if exited else '已请求结束,等待退出'}
def _finish_library_release(library, evidence):
from .library_lock import release_retained_library
return release_retained_library(library, evidence)
def _release_residual_sessions(plan, evidence_dir, *, stop=None, force=False):
library = Path(plan['library']).resolve()
root = Path(evidence_dir).resolve()/('sessions-'+uuid4().hex[:12])
if root.is_relative_to(library.parent) or library.parent.is_relative_to(root):
raise ValueError('释放记录需位于中心库之外')
root.mkdir(parents=True)
result = {'status': 'PARTIAL', 'library': str(library), 'sessions': [], 'force': force,
'evidence_path': str(root/'result.json'), 'previous_records': plan.get('previous_records', [])}
fresh = {r['pid']: r for r in query_process_snapshot()}
# Close native children first, so their supervisors can finish and drop leases.
ordered = sorted(plan['sessions'], key=lambda r: r['name'].casefold() in _WORKER_NAMES)
for original in ordered:
current = fresh.get(original['pid'])
outcome = {'release_status': 'RELEASED', 'detail': '已退出'}
if stop is not None and stop.is_set():
outcome = {'release_status': 'CANCELLED', 'detail': '已停止释放'}
elif current is not None:
from .library_lock import _owner_matches_scope
scoped = _owner_matches_scope(current, library, (library.parent,)) is True
if original.get('scope_confirmed') is not True or not scoped or original['pid'] == os.getpid():
outcome = {'release_status': 'WAITING', 'detail': '未在确认名单中证明属于当前库,未关闭;请重新检查'}
elif any(current.get(key) != original.get(key) for key in ('created', 'executable', 'command', 'name')):
outcome = {'release_status': 'IDENTITY_CHANGED', 'detail': '确认后进程身份已变化,未关闭'}
else:
try: outcome = (_force_close if force else _request_close)(original, stop=stop)
except Exception as error:
outcome = {'release_status': 'WAITING', 'detail': str(error)}
result['sessions'].append({**original, **outcome})
by_pid = {r['pid']: r for r in result['sessions']}
result['sessions'] = [by_pid[r['pid']] for r in plan['sessions']]
# Launchers may exit only after the GUI child processed its close request.
after = {r['pid']: r for r in query_process_snapshot()}
remaining_windows = _process_windows({r['pid'] for r in result['sessions']
if r['release_status'] == 'WAITING' and r['pid'] in after})
for row in result['sessions']:
if row['release_status'] == 'WAITING' and row['pid'] not in after:
row.update(release_status='RELEASED', detail='已退出')
elif row['release_status'] == 'WAITING':
row['prompt'] = _save_question(remaining_windows.get(row['pid'], []))
if all(row['release_status'] == 'RELEASED' for row in result['sessions']) and not (stop and stop.is_set()):
try:
result['proof'] = _finish_library_release(library, root/'library-proof')
proof = result['proof']
if (proof.get('status') != 'RELEASE_CONFIRMED'
or Path(proof.get('library', '')).resolve() != library):
raise ValueError('释放证明与当前库不一致')
result['status'] = 'RELEASE_CONFIRMED'
except Exception as error:
result['detail'] = str(error)
try:
(root/'result.json').write_text(json.dumps(result, ensure_ascii=False, indent=2), 'utf-8')
except OSError as error:
result['evidence_error'] = str(error)
return result
def release_residual_sessions(plan, evidence_dir, *, stop=None, force=False):
import win32con, win32event
mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795')
acquired = False
try:
deadline = time.monotonic()+15
while time.monotonic() < deadline and not (stop and stop.is_set()):
acquired = win32event.WaitForSingleObject(mutex, 0) in (win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED)
if acquired: break
time.sleep(.2)
if not acquired:
return {'status': 'PARTIAL', 'library': plan['library'], 'sessions': [
{**r, 'release_status': 'WAITING', 'detail': '其它批次尚在执行;请停止该批次后重试'}
for r in plan['sessions']], 'detail': '未取得执行通道,未关闭任何进程。'}
return _release_residual_sessions(plan, evidence_dir, stop=stop, force=force)
finally:
if acquired: win32event.ReleaseMutex(mutex)
mutex.Close()
def answer_save_question(row, choice):
"""Only the exact displayed save question receives an explicit user answer."""
import win32con, win32event, win32gui
if choice not in (6, 7, 2): raise ValueError('无效的保存选择')
mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795')
acquired = win32event.WaitForSingleObject(mutex, 0) in (win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED)
if not acquired:
mutex.Close()
raise ValueError('其它批次正在执行,请稍后处理保存提示')
try:
_answer_save_question(row, choice)
finally:
win32event.ReleaseMutex(mutex)
mutex.Close()
def _answer_save_question(row, choice):
import win32con, win32gui
fresh = next((r for r in query_process_snapshot() if r['pid'] == row['pid']), None)
if fresh is None or any(fresh.get(k) != row.get(k) for k in ('created', 'command', 'executable')):
raise ValueError('进程已变化,请重新检查')
with _process_handle(row['pid']) as handle:
if _handle_identity(handle) != {k: row.get(k) for k in ('created_handle', 'image')}:
raise ValueError('进程已变化,请重新检查')
prompt = _save_question(_process_windows({row['pid']}).get(row['pid'], []))
if not prompt or prompt != row.get('prompt'):
raise ValueError('原生提示已变化,请重新检查')
button = prompt['buttons'][choice]
import win32process
if win32process.GetWindowThreadProcessId(button['hwnd'])[1] != row['pid']:
raise ValueError('保存按钮归属已变化')
win32gui.PostMessage(button['hwnd'], win32con.BM_CLICK, 0, 0)