Reconcile existing registry data without overwriting conflicts
This commit is contained in:
parent
fb492c13f6
commit
ea82de2b90
|
|
@ -22,8 +22,14 @@ have identical SHA-256 checksums. Changed source data, special files, failed
|
|||
transfers or verification errors stop publication. Staging directories are
|
||||
retained for investigation, and source data is never removed. If source
|
||||
inspection confirms an absent or empty directory, an empty retained destination
|
||||
is prepared instead. Unrecorded, nonempty destination directories are refused
|
||||
instead of overwritten or merged.
|
||||
is prepared instead. An existing destination is checksummed and reused unchanged
|
||||
when it already contains the source files. Otherwise, non-conflicting files are
|
||||
merged in staging and the complete union is verified. The original destination
|
||||
is renamed to a timestamped backup before publishing the staged directory; a
|
||||
publication failure restores it. Conflicting files or a running Docker container
|
||||
with write access to the destination block automatic publication. Destination
|
||||
checksums must also remain stable throughout reconciliation. Existing data is
|
||||
never silently overwritten or discarded.
|
||||
|
||||
Successful copies write a profile-scoped `registry-migration.json` receipt.
|
||||
Subsequent runs preserve existing destination data. The storage and deployment
|
||||
|
|
|
|||
|
|
@ -84,6 +84,41 @@ def main():
|
|||
Path(args.result).chmod(0o600)
|
||||
|
||||
|
||||
def manifest_files(manifest):
|
||||
files = {}
|
||||
for line in manifest.splitlines():
|
||||
checksum, separator, name = line.partition(" ")
|
||||
if not separator or not re.fullmatch(r"[a-f0-9]{64}", checksum) or not name.startswith("./"):
|
||||
raise RuntimeError("Unsupported registry filename/checksum format; refusing ambiguous reconciliation")
|
||||
files[name] = checksum
|
||||
return files
|
||||
|
||||
|
||||
def local_manifest(path):
|
||||
special = run(["sudo", "-n", "find", path, "-mindepth", "1", "!", "-type", "f", "!", "-type", "d", "-print", "-quit"])
|
||||
if special:
|
||||
raise RuntimeError("Registry destination contains non-regular files; refusing staged reconciliation")
|
||||
return run(["sudo", "-n", "bash", "-o", "pipefail", "-c",
|
||||
"cd " + shlex.quote(path) + " && find . -type f -print0 | sort -z | xargs -0 -r sha256sum"], timeout=1800)
|
||||
|
||||
|
||||
def require_no_local_writer(path):
|
||||
docker = shutil.which("docker") or "/usr/bin/docker"
|
||||
if not Path(docker).exists():
|
||||
return
|
||||
ids = run(["sudo", "-n", docker, "ps", "-q"]).splitlines()
|
||||
if not ids:
|
||||
return
|
||||
for container in json.loads(run(["sudo", "-n", docker, "inspect", *ids])):
|
||||
for mount in container.get("Mounts") or []:
|
||||
source = mount.get("Source", "")
|
||||
if not source.startswith("/") or not mount.get("RW", True):
|
||||
continue
|
||||
common = os.path.commonpath([os.path.realpath(source), os.path.realpath(path)])
|
||||
if common in (os.path.realpath(source), os.path.realpath(path)):
|
||||
raise RuntimeError("A running Docker container can write registry storage; refusing to swap its directory")
|
||||
|
||||
|
||||
def prepare_local(args, path, existing_pv):
|
||||
state = Path(args.state_dir)
|
||||
state.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||
|
|
@ -107,8 +142,8 @@ def prepare_local(args, path, existing_pv):
|
|||
exists = subprocess.run(["sudo", "test", "-e", path], check=False).returncode == 0
|
||||
if exists:
|
||||
run(["sudo", "test", "-d", path])
|
||||
if run(["sudo", "find", path, "-mindepth", "1", "-maxdepth", "1", "-print", "-quit"]):
|
||||
raise RuntimeError("Unrecorded registry data already exists at destination; refusing to overwrite or merge it")
|
||||
destination_manifest = local_manifest(path) if exists else ""
|
||||
destination_files = manifest_files(destination_manifest)
|
||||
|
||||
source_ssh = lambda command: ssh(args.source_host, args.source_user, args.source_key, command)
|
||||
hyper_ssh = lambda command: ssh(args.hypervisor_host, args.hypervisor_user, args.hypervisor_key, command)
|
||||
|
|
@ -152,14 +187,21 @@ def prepare_local(args, path, existing_pv):
|
|||
run(["sudo", "mkdir", "-p", parent])
|
||||
stage = run(["sudo", "mktemp", "-d", parent + "/.registry-migration.XXXXXX"])
|
||||
digest = None
|
||||
source_files = {}
|
||||
if has_data:
|
||||
source_bytes = int(run(source_ssh("sudo -n du -sb " + shlex.quote(args.source_path))).split()[0])
|
||||
destination_bytes = int(run(["sudo", "du", "-sb", path]).split()[0]) if exists else 0
|
||||
available = int(run(["df", "-B1", "--output=avail", parent]).splitlines()[-1].strip())
|
||||
if available < source_bytes + 256 * 1024 * 1024:
|
||||
if available < source_bytes + destination_bytes + 256 * 1024 * 1024:
|
||||
raise RuntimeError("Insufficient destination disk space for a verified registry copy")
|
||||
manifest_command = "cd " + shlex.quote(args.source_path) + " && find . -type f -print0 | sort -z | xargs -0 -r sha256sum"
|
||||
manifest_ssh = source_ssh("sudo -n bash -o pipefail -c " + shlex.quote(manifest_command))
|
||||
before = run(manifest_ssh, timeout=1800)
|
||||
source_files = manifest_files(before)
|
||||
conflicts = [name for name, checksum in source_files.items()
|
||||
if name in destination_files and destination_files[name] != checksum]
|
||||
if conflicts:
|
||||
raise RuntimeError(f"Registry has {len(conflicts)} conflicting source/destination file(s); both copies preserved, automatic overwrite refused")
|
||||
special = run(source_ssh("sudo -n find " + shlex.quote(args.source_path) + " -mindepth 1 ! -type f ! -type d -print -quit"))
|
||||
if special:
|
||||
raise RuntimeError("Source registry contains non-regular files; refusing unsafe archive extraction")
|
||||
|
|
@ -182,18 +224,49 @@ def prepare_local(args, path, existing_pv):
|
|||
raise RuntimeError("Registry changed during copy or verification failed; staging retained, source preserved")
|
||||
digest = hashlib.sha256(before.encode()).hexdigest()
|
||||
else:
|
||||
print("Source inspection confirmed no registry data; preparing a fresh retained registry directory", flush=True)
|
||||
run(["sudo", "chown", "-R", "1000:1000", stage])
|
||||
run(["sudo", "chmod", "0750", stage])
|
||||
# The existing directory, if any, was verified empty above.
|
||||
if exists:
|
||||
run(["sudo", "rmdir", path])
|
||||
run(["sudo", "mv", "-T", stage, path])
|
||||
stage = None
|
||||
print("Source inspection confirmed no registry data; preserving any existing destination data", flush=True)
|
||||
backup = None
|
||||
# A complete existing destination is authoritative and stays in
|
||||
# place. This covers earlier successful copies without a receipt.
|
||||
reuse = exists and bool(destination_files) and all(
|
||||
destination_files.get(name) == checksum for name, checksum in source_files.items())
|
||||
if reuse:
|
||||
if local_manifest(path) != destination_manifest:
|
||||
raise RuntimeError("Destination changed during reconciliation; refusing to record a completed migration")
|
||||
print(f"Existing registry at {path} already contains all source files; reusing it unchanged", flush=True)
|
||||
if not has_data:
|
||||
run(["sudo", "rmdir", stage])
|
||||
stage = None
|
||||
else:
|
||||
if exists:
|
||||
require_no_local_writer(path)
|
||||
run(["sudo", "cp", "-a", "--no-clobber", path + "/.", stage + "/"], timeout=1800)
|
||||
if local_manifest(path) != destination_manifest:
|
||||
raise RuntimeError("Destination changed during staged merge; original data preserved")
|
||||
expected = dict(destination_files, **source_files)
|
||||
if manifest_files(local_manifest(stage)) != expected:
|
||||
raise RuntimeError("Merged registry file verification failed; original directories preserved")
|
||||
run(["sudo", "chown", "-R", "1000:1000", stage])
|
||||
run(["sudo", "chmod", "0750", stage])
|
||||
if exists:
|
||||
require_no_local_writer(path)
|
||||
backup = path + f".before-migration-{time.time_ns()}"
|
||||
run(["sudo", "mv", "-T", path, backup])
|
||||
try:
|
||||
run(["sudo", "mv", "-T", stage, path])
|
||||
except subprocess.SubprocessError:
|
||||
if backup:
|
||||
run(["sudo", "mv", "-T", backup, path])
|
||||
raise
|
||||
stage = None
|
||||
if backup:
|
||||
print(f"Original destination retained at {backup}", flush=True)
|
||||
receipt_tmp = state / "registry-migration.json.tmp"
|
||||
receipt_tmp.write_text(json.dumps({"destination": path, "source_host": args.source_host,
|
||||
"source_path": args.source_path, "copied": has_data,
|
||||
"manifest_sha256": digest}) + "\n")
|
||||
"manifest_sha256": digest, "destination_backup": backup,
|
||||
"reused_destination": reuse,
|
||||
"staged_source_backup": stage}) + "\n")
|
||||
receipt_tmp.chmod(0o600)
|
||||
os.replace(receipt_tmp, receipt)
|
||||
print(f"Registry storage ready at {path}; original source retained", flush=True)
|
||||
|
|
|
|||
Loading…
Reference in New Issue