145 lines
5.9 KiB
Python
145 lines
5.9 KiB
Python
"""Recognize native iCDB recovery requests without changing database state."""
|
|
import hashlib
|
|
import ntpath
|
|
from pathlib import Path
|
|
import re
|
|
|
|
|
|
ERROR_CODE = 'ICDB_REPAIR_REQUIRED'
|
|
LOG_LIMIT = 128 * 1024
|
|
RECOVERY_ACTION = (
|
|
'停止批次并确认原服务器及其他客户端已正常关闭;保留完整一致副本后,'
|
|
"使用同版本 iCDB Project Backup 的 Repair project 检查并修复正确目标。"
|
|
'共享符号库问题需核对中心库,不能只修复单个 CBB 的 Work 工程。'
|
|
'不要删除 sAddress.adr/锁文件;修复后重新打开、校验并确认权威 READY。'
|
|
)
|
|
_SESSION_LOSS = re.compile(
|
|
r'\bthe\s+last\s+server\s+session\s+on\s+different\s+server\s+machine\s+'
|
|
r'lost\s+the\s+connection\s+to\s+the\s+database\b', re.IGNORECASE)
|
|
|
|
|
|
def parse_session_loss(text):
|
|
"""Keep the native target verbatim; never infer a local repair target."""
|
|
text = str(text or '')
|
|
match = _SESSION_LOSS.search(text)
|
|
if match is None:
|
|
return None
|
|
# A log may contain several sessions. Use the identity following this
|
|
# error, never an unrelated Machine/Path header earlier in the log.
|
|
message = text[match.start():]
|
|
next_error = _SESSION_LOSS.search(message, 1)
|
|
if next_error:
|
|
message = message[:next_error.start()]
|
|
record = {'error_code': ERROR_CODE, 'native_message': message,
|
|
'machine': '', 'database_path': '', 'session': '', 'scope': 'unknown'}
|
|
for native_key, key in (('machine', 'machine'), ('path', 'database_path'),
|
|
('session', 'session')):
|
|
field = re.search(
|
|
rf'\b{native_key}\s*:\s*(?:\[([^\]]*)\]|([^\r\n]*?)(?=\s+\b(?:machine|path|session)\s*:|[\r\n]|$))',
|
|
message, re.IGNORECASE)
|
|
if field:
|
|
record[key] = (field.group(1) if field.group(1) is not None else field.group(2)).strip()
|
|
parts = ntpath.normpath(record['database_path']).casefold().split('\\')
|
|
if 'symbollibs' in parts:
|
|
record['scope'] = 'central_library'
|
|
elif 'work' in parts and parts[-1] == 'database':
|
|
record['scope'] = 'project'
|
|
return record
|
|
|
|
|
|
def recovery_detail(record):
|
|
target = ('中心库共享符号数据库' if record['scope'] == 'central_library' else
|
|
'工程数据库' if record['scope'] == 'project' else '报错中指定的数据库')
|
|
return (
|
|
f"{ERROR_CODE}: {target}的上次服务器会话失联。\n"
|
|
f"{record['native_message']}\n"
|
|
f'{RECOVERY_ACTION}'
|
|
)
|
|
|
|
|
|
def snapshot_log(path):
|
|
"""Fingerprint a bounded tail before launch, including a missing log."""
|
|
try:
|
|
with Path(path).open('rb') as stream:
|
|
stream.seek(0, 2)
|
|
size = stream.tell()
|
|
stream.seek(max(0, size-LOG_LIMIT))
|
|
tail = stream.read(LOG_LIMIT)
|
|
losses = [_session_identity(record) for record in _session_losses(decode_log(tail))]
|
|
return {'size': size, 'tail_sha256': hashlib.sha256(tail).hexdigest(),
|
|
'truncated': size > LOG_LIMIT,
|
|
'session_losses': losses}
|
|
except FileNotFoundError:
|
|
return {'size': 0, 'tail_sha256': hashlib.sha256(b'').hexdigest()}
|
|
except OSError as error:
|
|
return {'error': str(error)}
|
|
|
|
|
|
def _read_log_delta(path, baseline):
|
|
"""Read new bytes, detecting truncate/rewrite as well as append.
|
|
|
|
Unknown baselines cannot prove freshness. At most two bounded tails are
|
|
read, even when a native log is large or located on a network share.
|
|
"""
|
|
if not baseline or 'error' in baseline:
|
|
return b'', False
|
|
old_size = int(baseline['size'])
|
|
try:
|
|
with Path(path).open('rb') as stream:
|
|
stream.seek(0, 2)
|
|
size = stream.tell()
|
|
offset = 0
|
|
appended = False
|
|
if size >= old_size:
|
|
stream.seek(max(0, old_size-LOG_LIMIT))
|
|
old_tail = stream.read(min(old_size, LOG_LIMIT))
|
|
if hashlib.sha256(old_tail).hexdigest() == baseline['tail_sha256']:
|
|
offset = old_size
|
|
appended = True
|
|
stream.seek(max(offset, size-LOG_LIMIT))
|
|
return stream.read(LOG_LIMIT), appended
|
|
except OSError:
|
|
return b'', False
|
|
|
|
|
|
def _session_losses(text):
|
|
matches = list(_SESSION_LOSS.finditer(text))
|
|
for index, match in enumerate(matches):
|
|
end = matches[index+1].start() if index+1 < len(matches) else len(text)
|
|
yield parse_session_loss(text[match.start():end])
|
|
|
|
|
|
def _session_identity(record):
|
|
return [record[key] for key in ('machine', 'database_path', 'session')]
|
|
|
|
|
|
def read_log_failure(path, baseline):
|
|
"""Return new log text and a recovery request with evidence of freshness.
|
|
|
|
A rewritten header does not prove that a retained old session failed
|
|
again. In that ambiguous case keep the generic failure; a verified append
|
|
can report even the same old session as a current native error.
|
|
"""
|
|
data, appended = _read_log_delta(path, baseline)
|
|
text = decode_log(data)
|
|
if not appended and baseline and baseline.get('truncated'):
|
|
# A rewrite may expose an old error outside our bounded baseline.
|
|
# Without positive append evidence its age cannot be established.
|
|
return text, None
|
|
historical = baseline.get('session_losses', []) if baseline else []
|
|
recovery = next((record for record in _session_losses(text)
|
|
if appended or _session_identity(record) not in historical), None)
|
|
return text, recovery
|
|
|
|
|
|
def decode_log(data):
|
|
if data.startswith((b'\xff\xfe', b'\xfe\xff')):
|
|
return data.decode('utf-16', errors='replace')
|
|
# Appended UTF-16 bytes and bounded tails no longer contain a BOM.
|
|
sample = data[:200]
|
|
if sample[1::2].count(0) > len(sample)//8:
|
|
return data.decode('utf-16-le', errors='replace')
|
|
if sample[::2].count(0) > len(sample)//8:
|
|
return data.decode('utf-16-be', errors='replace')
|
|
return data.decode('utf-8', errors='replace')
|