327 lines
15 KiB
Python
327 lines
15 KiB
Python
"""Complete, metadata-verified snapshots with scoped semantic SHA256 manifests.
|
|
|
|
Unknown engineering files are primary. Only explicit runtime, history and
|
|
generated categories are ignored by semantic comparisons; they are still copied
|
|
and their membership/size/mtime must remain stable throughout the snapshot.
|
|
"""
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
from contextlib import ExitStack
|
|
from dataclasses import asdict, dataclass
|
|
import hashlib
|
|
import os
|
|
from pathlib import Path
|
|
import shutil
|
|
import stat
|
|
|
|
|
|
MANIFEST_VERSION = 1
|
|
_NONPRIMARY_DIRECTORIES = frozenset({
|
|
'log', 'logs', 'temp', 'tmp', '__pycache__', 'backup', 'backups',
|
|
'output', 'outputs', 'report', 'reports', 'gerber', 'gerbers', 'odb++',
|
|
'log files', 'logfiles',
|
|
})
|
|
_NONPRIMARY_SUFFIXES = frozenset({
|
|
'.log', '.tmp', '.temp', '.lck', '.lock', '.bak', '.backup', '.pdf',
|
|
})
|
|
|
|
|
|
def _root_runtime(directories):
|
|
"""Known runtime/history children of a library or project workspace root."""
|
|
return bool(directories and (
|
|
directories[0] in _NONPRIMARY_DIRECTORIES
|
|
or directories[0].startswith('work.before-restore-')
|
|
or directories[:2] == ('projectbackup', 'backups')))
|
|
|
|
|
|
def _native_runtime(directories, database_prefix):
|
|
runtime_prefix = database_prefix + ('cdbsvr',)
|
|
return (directories[:len(runtime_prefix)] == runtime_prefix
|
|
and len(directories) > len(runtime_prefix)
|
|
and directories[len(runtime_prefix)] in ('log', 'dbcheck', 'dbrestore'))
|
|
|
|
|
|
def _project_runtime(directories):
|
|
return (_root_runtime(directories)
|
|
or (directories[:1] == ('pcb',) and _root_runtime(directories[1:]))
|
|
or _native_runtime(directories, ('database',))
|
|
or _native_runtime(directories, ('pcb', 'database')))
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class ManifestScope:
|
|
"""Project root by default; library selects one CBB and shared dependencies."""
|
|
|
|
kind: str = 'project'
|
|
block_name: str = ''
|
|
library_name: str = ''
|
|
|
|
def __post_init__(self):
|
|
if self.kind not in ('project', 'library'):
|
|
raise ValueError('Unknown manifest scope')
|
|
if self.kind == 'library':
|
|
for value in (self.block_name, self.library_name):
|
|
if not value or value in ('.', '..') or any(c in value for c in '/\\:'):
|
|
raise ValueError('Library scope requires single-component block/library names')
|
|
|
|
@classmethod
|
|
def library(cls, block_name, library_name):
|
|
return cls('library', block_name, library_name)
|
|
|
|
def includes_directory(self, relative):
|
|
parts = tuple(part.casefold() for part in Path(relative).parts)
|
|
if self._runtime_path(parts, directory=True):
|
|
return False
|
|
if self.kind == 'project' or not parts or parts[0] != 'reusableblockslp':
|
|
return True
|
|
return ((len(parts) < 2 or parts[1] == self.block_name.casefold())
|
|
and (len(parts) < 3 or parts[2] in ('work', 'cert')))
|
|
|
|
def _runtime_path(self, parts, *, directory=False):
|
|
"""Recognize runtime locations only in their structural context.
|
|
|
|
Generic names such as ``Logs`` are runtime when they are a project-root
|
|
or selected Work/Cert child. The same name deeper in an engineering
|
|
partition (or in shared SymbolLibs data) remains primary.
|
|
"""
|
|
directories = parts if directory else parts[:-1]
|
|
if not directory and (Path(parts[-1]).suffix in _NONPRIMARY_SUFFIXES
|
|
or parts[-1] == 'saddress.adr' or parts[-1].startswith('~$')):
|
|
return True
|
|
if self.kind == 'project':
|
|
return _project_runtime(directories)
|
|
if directories[:1] == ('reusableblockslp',):
|
|
# Identity and Work/Cert role components never act as runtime names.
|
|
if (len(directories) >= 3 and directories[1] == self.block_name.casefold()
|
|
and directories[2] in ('work', 'cert')):
|
|
return _project_runtime(directories[3:])
|
|
return False
|
|
if _root_runtime(directories):
|
|
return True
|
|
# Shared dependency names/partitions are engineering data. Only native
|
|
# server runtime subtrees within known DB positions are excluded.
|
|
if directories[:1] == ('symbollibs',) and len(directories) >= 2:
|
|
return _native_runtime(directories, directories[:2])
|
|
return bool(directories and _native_runtime(directories, directories[:1]))
|
|
|
|
def classify(self, relative):
|
|
"""Return a semantic scope label or None; paths are relative to the root."""
|
|
parts = tuple(part.casefold() for part in Path(relative).parts)
|
|
if self._runtime_path(parts):
|
|
return None
|
|
if self.kind == 'project':
|
|
return 'project'
|
|
if parts[0] == 'reusableblockslp':
|
|
if len(parts) < 4 or parts[1] != self.block_name.casefold():
|
|
return None
|
|
return {'work': 'target_work', 'cert': 'target_cert'}.get(parts[2])
|
|
if len(parts) == 1:
|
|
if Path(parts[0]).suffix == '.lmc' and parts[0] != self.library_name.casefold():
|
|
return None
|
|
return 'library_config'
|
|
# Shared DB/config/dependency trees are conservative: new dependency
|
|
# directory names remain primary without adding them to an allowlist.
|
|
return 'shared_dependency'
|
|
|
|
|
|
def hash_file(path):
|
|
digest = hashlib.sha256()
|
|
with Path(path).open('rb') as stream:
|
|
for data in iter(lambda: stream.read(1024 * 1024), b''):
|
|
digest.update(data)
|
|
return digest.hexdigest()
|
|
|
|
|
|
def _coordination_checkpoint(path):
|
|
from .library_lock import checkpoint_record
|
|
return checkpoint_record(path) is not None
|
|
|
|
|
|
def scan_tree(root, *, scope=None, exclude=None):
|
|
"""Refuse links/special files; optionally prune trees outside semantic scope.
|
|
|
|
Copies always call this without a scope, validating complete membership.
|
|
Later semantic scans avoid entering runtime or unrelated CBB directories.
|
|
"""
|
|
root = Path(root)
|
|
if root.lstat().st_file_attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT:
|
|
raise ValueError(f'不支持通过目录链接恢复:{root}')
|
|
entries = {}
|
|
folders = [root]
|
|
while folders:
|
|
with os.scandir(folders.pop()) as scanned:
|
|
for entry in scanned:
|
|
path = Path(entry.path)
|
|
if exclude is not None and path.is_relative_to(exclude):
|
|
continue
|
|
if scope is not None:
|
|
relative = path.relative_to(root)
|
|
if entry.is_dir(follow_symlinks=False):
|
|
if not scope.includes_directory(relative):
|
|
continue
|
|
elif scope.classify(relative) is None or _coordination_checkpoint(path):
|
|
continue
|
|
metadata = entry.stat(follow_symlinks=False)
|
|
if metadata.st_file_attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT:
|
|
raise ValueError(f'目录含文件或目录链接,停止恢复:{entry.path}')
|
|
if not (stat.S_ISDIR(metadata.st_mode) or stat.S_ISREG(metadata.st_mode)):
|
|
raise ValueError(f'不支持的特殊文件:{entry.path}')
|
|
entries[path] = metadata
|
|
if stat.S_ISDIR(metadata.st_mode):
|
|
folders.append(path)
|
|
return dict(sorted(entries.items()))
|
|
|
|
|
|
def _metadata_record(root, entries):
|
|
return {path.relative_to(root).as_posix():
|
|
('file', info.st_size, info.st_mtime_ns) if stat.S_ISREG(info.st_mode) else ('dir',)
|
|
for path, info in entries.items()}
|
|
|
|
|
|
def _manifest(scope, files):
|
|
return {'version': MANIFEST_VERSION, 'scope': asdict(scope), 'files': dict(sorted(files.items()))}
|
|
|
|
|
|
def _emit(progress, stage, hashed_files, hashed_bytes, **extra):
|
|
if progress:
|
|
progress({'stage': stage, 'hashed_files': hashed_files, 'hashed_bytes': hashed_bytes, **extra})
|
|
|
|
|
|
def build_manifest(root, *, scope=None, exclude=None, progress=None, hash_function=hash_file):
|
|
"""Hash primary files only. Excluded subtrees are for private incoming Work.
|
|
|
|
The returned dict is versioned, JSON-compatible and relocatable. Equality
|
|
compares primary path membership, size, hash and scope, never runtime mtimes.
|
|
"""
|
|
root = Path(root)
|
|
scope = scope or ManifestScope()
|
|
entries = scan_tree(root, scope=scope, exclude=exclude)
|
|
selected = {path: scope.classify(path.relative_to(root)) for path, info in entries.items()
|
|
if stat.S_ISREG(info.st_mode)}
|
|
selected = {path: label for path, label in selected.items() if label is not None}
|
|
def hashed(path):
|
|
digest = hash_function(path)
|
|
after = path.stat()
|
|
before = entries[path]
|
|
if (before.st_size, before.st_mtime_ns) != (after.st_size, after.st_mtime_ns):
|
|
raise OSError(f'计算哈希期间文件变化:{path}')
|
|
return path.relative_to(root).as_posix(), {
|
|
'size': before.st_size, 'sha256': digest, 'scope': selected[path]}
|
|
files = {}
|
|
hashed_bytes = 0
|
|
_emit(progress, 'hash', 0, 0, total_files=len(selected))
|
|
with ThreadPoolExecutor(max_workers=8) as pool:
|
|
for count, (relative, item) in enumerate(pool.map(hashed, selected), 1):
|
|
files[relative] = item
|
|
hashed_bytes += item['size']
|
|
if count % 256 == 0 or count == len(selected):
|
|
_emit(progress, 'hash', count, hashed_bytes, total_files=len(selected))
|
|
# Check primary membership and metadata again after every hash completed.
|
|
# Runtime files can change/add/disappear without a semantic conflict.
|
|
after = scan_tree(root, scope=scope, exclude=exclude)
|
|
before_primary = {p: entries[p] for p in selected}
|
|
after_primary = {p: info for p, info in after.items() if stat.S_ISREG(info.st_mode)
|
|
and (exclude is None or not p.is_relative_to(exclude))
|
|
and scope.classify(p.relative_to(root)) is not None}
|
|
if _metadata_record(root, before_primary) != _metadata_record(root, after_primary):
|
|
raise OSError(f'计算哈希期间主要文件变化:{root}')
|
|
return _manifest(scope, files)
|
|
|
|
|
|
def copy_verified(source, destination, *, scope=None, progress=None, hash_function=hash_file):
|
|
"""Copy the whole tree, validate all metadata, SHA256 only scoped primary files.
|
|
|
|
Native icdb.dat/LMC files are held with exclusive read handles for the copy.
|
|
Their expected SHA256 comes from the source read stream, independently of
|
|
hashing destination bytes. Failures retain the partial destination evidence.
|
|
Progress receives one dict with stage, hashed_files/bytes and copied_files.
|
|
"""
|
|
import win32con
|
|
import win32file
|
|
|
|
source, destination = Path(source), Path(destination)
|
|
scope = scope or ManifestScope()
|
|
if destination.resolve().is_relative_to(source.resolve()):
|
|
raise ValueError('复制目标不能位于源目录内。')
|
|
entries = scan_tree(source)
|
|
expected_metadata = _metadata_record(source, entries)
|
|
destination.mkdir(parents=True, exist_ok=False)
|
|
files = [path for path, info in entries.items() if stat.S_ISREG(info.st_mode)]
|
|
from .library_lock import owned_snapshot
|
|
# Resolve ownership on the operation thread, before parallel copy workers.
|
|
owned = {path: data for path in files
|
|
if path.name.endswith('.cbb-upload.lock')
|
|
and (data := owned_snapshot(path)) is not None}
|
|
record = {}
|
|
hashed_count = hashed_bytes = 0
|
|
_emit(progress, 'copy', 0, 0, copied_files=0, total_files=len(files))
|
|
with ExitStack() as stack:
|
|
locks = {}
|
|
for path in files:
|
|
if path.name.casefold() == 'icdb.dat' or path.suffix.casefold() == '.lmc':
|
|
handle = win32file.CreateFile(str(path), win32con.GENERIC_READ, 0, None,
|
|
win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None)
|
|
stack.callback(handle.Close)
|
|
locks[path] = handle
|
|
for path, info in entries.items():
|
|
if stat.S_ISDIR(info.st_mode):
|
|
(destination/path.relative_to(source)).mkdir(parents=True, exist_ok=True)
|
|
|
|
def copy_file(path):
|
|
relative = path.relative_to(source)
|
|
copied = destination/relative
|
|
copied.parent.mkdir(parents=True, exist_ok=True)
|
|
label = None if _coordination_checkpoint(path) else scope.classify(relative)
|
|
digest = None
|
|
if path in owned:
|
|
copied.write_bytes(owned[path])
|
|
shutil.copystat(path, copied)
|
|
if label is not None:
|
|
digest = hashlib.sha256(owned[path]).hexdigest()
|
|
elif path in locks:
|
|
stream_hash = hashlib.sha256() if label is not None else None
|
|
with copied.open('wb') as stream:
|
|
while True:
|
|
_, data = win32file.ReadFile(locks[path], 1024 * 1024)
|
|
if not data:
|
|
break
|
|
if stream_hash is not None:
|
|
stream_hash.update(data)
|
|
stream.write(data)
|
|
shutil.copystat(path, copied)
|
|
if stream_hash is not None:
|
|
digest = stream_hash.hexdigest()
|
|
else:
|
|
if label is not None:
|
|
digest = hash_function(path)
|
|
shutil.copy2(path, copied)
|
|
before, after = entries[path], path.stat()
|
|
if (before.st_size, before.st_mtime_ns) != (after.st_size, after.st_mtime_ns):
|
|
raise OSError(f'复制期间文件变化:{path}')
|
|
return relative.as_posix(), digest, label
|
|
|
|
with ThreadPoolExecutor(max_workers=8) as pool:
|
|
for count, (relative, digest, label) in enumerate(pool.map(copy_file, files), 1):
|
|
if label is not None:
|
|
size = entries[source/relative].st_size
|
|
record[relative] = {'size': size, 'sha256': digest, 'scope': label}
|
|
hashed_count += 1
|
|
hashed_bytes += size
|
|
if count % 256 == 0 or count == len(files):
|
|
_emit(progress, 'copy', hashed_count, hashed_bytes,
|
|
copied_files=count, total_files=len(files))
|
|
|
|
def validate_bytes(relative):
|
|
item = record[relative]
|
|
path = source/relative
|
|
if path not in locks and hash_function(path) != item['sha256']:
|
|
raise OSError(f'复制期间主要文件内容变化:{path}')
|
|
if hash_function(destination/relative) != item['sha256']:
|
|
raise OSError(f'复制内容校验失败:{path}')
|
|
with ThreadPoolExecutor(max_workers=8) as pool:
|
|
list(pool.map(validate_bytes, record))
|
|
if _metadata_record(source, scan_tree(source)) != expected_metadata:
|
|
raise OSError(f'复制期间目录内容变化:{source}')
|
|
if _metadata_record(destination, scan_tree(destination)) != expected_metadata:
|
|
raise OSError(f'复制目标目录或文件元数据不一致:{destination}')
|
|
return _manifest(scope, record)
|