266 lines
7.7 KiB
Python
266 lines
7.7 KiB
Python
"""Read-only release retention planning.
|
|
|
|
The caller must supply a complete and trustworthy
|
|
inventory of releases and transaction protections.
|
|
|
|
No filesystem modification is performed.
|
|
"""
|
|
|
|
import re
|
|
|
|
from core.compatibility import canonical_hash
|
|
|
|
|
|
class RetentionError(RuntimeError):
|
|
"""Invalid or unsafe release retention policy."""
|
|
|
|
|
|
FIELDS = {
|
|
"inventory",
|
|
"current",
|
|
"keep",
|
|
"protected",
|
|
"failed",
|
|
"unresolved",
|
|
}
|
|
|
|
|
|
def require(condition, message):
|
|
if not condition:
|
|
raise RetentionError(message)
|
|
|
|
|
|
def validate_release(value):
|
|
require(
|
|
isinstance(value, str)
|
|
and re.fullmatch(
|
|
r"[1-9][0-9]{0,19}",
|
|
value,
|
|
) is not None,
|
|
"Invalid release identifier",
|
|
)
|
|
|
|
|
|
def validate_inventory(values):
|
|
require(
|
|
isinstance(values, list)
|
|
and len(values) <= 100000,
|
|
"Invalid release inventory",
|
|
)
|
|
|
|
for value in values:
|
|
validate_release(value)
|
|
|
|
require(
|
|
len(values) == len(set(values)),
|
|
"Duplicate release identifiers",
|
|
)
|
|
|
|
return sorted(values, key=int)
|
|
|
|
|
|
def plan_retention(policy):
|
|
require(
|
|
isinstance(policy, dict)
|
|
and set(policy) == FIELDS,
|
|
"Invalid retention policy structure",
|
|
)
|
|
|
|
inventory = validate_inventory(
|
|
policy["inventory"]
|
|
)
|
|
|
|
require(
|
|
bool(inventory),
|
|
"Release inventory is empty",
|
|
)
|
|
|
|
current = policy["current"]
|
|
|
|
validate_release(current)
|
|
|
|
available = set(inventory)
|
|
|
|
require(
|
|
current in available,
|
|
"Active release missing from inventory",
|
|
)
|
|
|
|
keep = policy["keep"]
|
|
|
|
require(
|
|
type(keep) is int
|
|
and 2 <= keep <= 1000,
|
|
"Retention count must be between 2 and 1000",
|
|
)
|
|
|
|
protections = {}
|
|
|
|
for field in (
|
|
"protected",
|
|
"failed",
|
|
"unresolved",
|
|
):
|
|
values = validate_inventory(
|
|
policy[field]
|
|
)
|
|
|
|
require(
|
|
set(values) <= available,
|
|
f"Unknown release in {field} inventory",
|
|
)
|
|
|
|
protections[field] = values
|
|
|
|
failed = set(protections["failed"])
|
|
|
|
require(
|
|
current not in failed,
|
|
"Active release is marked failed",
|
|
)
|
|
|
|
reasons = {}
|
|
|
|
def protect(release, reason):
|
|
reasons.setdefault(release, set()).add(reason)
|
|
|
|
protect(current, "active")
|
|
|
|
for release in inventory[-keep:]:
|
|
protect(release, "recent_release")
|
|
|
|
for release in protections["protected"]:
|
|
protect(release, "explicitly_protected")
|
|
|
|
for release in protections["failed"]:
|
|
protect(release, "failed_release")
|
|
|
|
for release in protections["unresolved"]:
|
|
protect(release, "unresolved_transaction")
|
|
|
|
previous = [
|
|
release
|
|
for release in inventory
|
|
if int(release) < int(current)
|
|
and release not in failed
|
|
]
|
|
|
|
if previous:
|
|
protect(previous[-1], "previous_available")
|
|
|
|
blocked = bool(protections["unresolved"])
|
|
|
|
if blocked:
|
|
for release in inventory:
|
|
protect(release, "operation_unresolved")
|
|
|
|
retained = [
|
|
release
|
|
for release in inventory
|
|
if release in reasons
|
|
]
|
|
|
|
candidates = [
|
|
release
|
|
for release in inventory
|
|
if release not in reasons
|
|
]
|
|
|
|
plan = {
|
|
"format_version": 1,
|
|
"status": "BLOCKED" if blocked else "READY",
|
|
"current": current,
|
|
"keep": keep,
|
|
"inventory": inventory,
|
|
"protected": protections["protected"],
|
|
"failed": protections["failed"],
|
|
"unresolved": protections["unresolved"],
|
|
"retained": retained,
|
|
"archive_candidates": candidates,
|
|
"reasons": {
|
|
release: sorted(reasons[release])
|
|
for release in retained
|
|
},
|
|
"automatic_archival": False,
|
|
"automatic_deletion": False,
|
|
"execution_permitted": False,
|
|
}
|
|
|
|
plan["fingerprint"] = canonical_hash(plan)
|
|
|
|
return plan
|
|
|
|
|
|
def plan_site_retention(runtime_root, *, keep, site=None):
|
|
"""Read canonical runtime state under its deployment and journal locks."""
|
|
from pathlib import Path
|
|
|
|
from core.approval_store import ApprovalStore
|
|
from core.archive import TransactionArchive
|
|
from core.backup_evidence import BackupEvidence
|
|
from core.locking import DeploymentLock
|
|
from core.operation_guard import OperationGuard
|
|
from core.releases import ReleaseManager
|
|
from core.transactions import TransactionJournal
|
|
|
|
root = Path(runtime_root)
|
|
require(root.is_absolute() and root.resolve() == root, "Invalid retention runtime directory")
|
|
try:
|
|
journal = TransactionJournal(root / "state")
|
|
with DeploymentLock(journal.directory / ".deployment.lock"), DeploymentLock(journal.lock_path):
|
|
approvals = journal.migration_guard_directory()
|
|
require(approvals == root / "approvals", "Missing trusted migration guard binding")
|
|
guard = OperationGuard(ApprovalStore(approvals)).inspect()
|
|
transaction = journal.load()
|
|
releases = ReleaseManager(root / "app")
|
|
inventory = releases.inventory()
|
|
current = releases.current()
|
|
protected = set()
|
|
archive_directory = root / "archive"
|
|
if archive_directory.exists() or archive_directory.is_symlink():
|
|
require(isinstance(site, str) and re.fullmatch(r"[a-z0-9][a-z0-9-]{0,62}", site),
|
|
"Configured site identity required for retention archives")
|
|
archives = TransactionArchive(
|
|
site=site, directory=archive_directory,
|
|
lock_path=journal.directory / ".deployment.lock", journal=journal,
|
|
releases=releases, provenance=None, backup_evidence=BackupEvidence(journal.directory),
|
|
backup_verify=None, health_probe=None,
|
|
)
|
|
matching = []
|
|
for path in archive_directory.iterdir():
|
|
require(re.fullmatch(r"[a-f0-9]{32}\.archive\.json", path.name),
|
|
"Unexpected retention archive entry")
|
|
archived = archives.load(path.name[:32])["transaction"]
|
|
protected.update((archived["previous"], archived["candidate"]))
|
|
if archived["candidate"] == current:
|
|
matching.append(archived)
|
|
if transaction is None:
|
|
require(len(matching) == 1, "Active release has no unambiguous verified archive")
|
|
transaction = matching[0]
|
|
require(transaction is not None, "No verified retention transaction")
|
|
require(site is None or transaction["site"] == site, "Retention transaction belongs to another site")
|
|
references = [transaction["previous"], transaction["candidate"]]
|
|
protected.update(references)
|
|
require(current in references, "Live active release differs from the transaction")
|
|
unresolved = (
|
|
transaction["phase"] != "VERIFIED"
|
|
or current != transaction["candidate"]
|
|
or guard["status"] != "CLEAR"
|
|
)
|
|
plan = plan_retention({
|
|
"inventory": inventory,
|
|
"current": current,
|
|
"keep": keep,
|
|
"protected": sorted(protected),
|
|
"failed": [],
|
|
"unresolved": inventory if unresolved else [],
|
|
})
|
|
del plan["fingerprint"]
|
|
plan.update(inventory_source="site_runtime", journal_checksum=transaction["checksum"])
|
|
plan["fingerprint"] = canonical_hash(plan)
|
|
return plan
|
|
except RetentionError:
|
|
raise
|
|
except Exception:
|
|
raise RetentionError("Unable to verify trusted retention inventory") from None
|