Files
ProxMenux/oci/remote/oci_image_cache.py
T
MacRimiandClaude Opus 5 bcabcb618c feat(oci): run official container images as native LXC containers
Adds the OCI manager: an engine that turns a Docker Compose file into an
LXC definition, a catalog of 365 applications drawn from LinuxServer.io
and other container image sources, and a per-instance registry recording
what each container was built from. Reachable from the main menu.

Catalog text is translated like every other string in the project: the
taglines go through translate() and land in lang/*.json, so the entries
read in all eight languages instead of only English.

Translation cache builder:
- a failed translation leaves the key absent rather than writing English,
  which previously made the string count as translated forever
- a result identical to a 3+ word source is rejected, catching a provider
  that silently returns the text it was given
- strings that are nothing but glossary terms keep their source spelling
  instead of being discarded as failures
- no backoff between attempts when the provider is deterministic
- application names are protected so "HAOS One" survives translation
- argos joins the provider list, and the workflow reads the OCI sources

Audit & Report:
- findings that moved in the wrong direction between runs are reported
  alongside the ones that improved
- an accepted risk can carry a review date and is flagged when it falls due
- backup checks explain in plain language what they looked at and what to
  do next

Monitor:
- disks can be excluded from periodic reads, and an idle disk says so
  instead of showing a stale temperature
- per-disk identity survives a controller or enclosure change
- scheduled Borg backups resolve their SSH key from the repository entry
- PVE upgrades log the package list and the resulting dpkg changes

The web build no longer copies scripts/ into public/: the documentation
links to GitHub, so nothing read that folder.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-22 18:24:59 +02:00

108 lines
3.9 KiB
Python

#!/usr/bin/env python3
"""Image archives that ProxMenux downloaded to the template storage and that
no installation uses any more are removed after a successful operation."""
from __future__ import annotations
import json
from pathlib import Path
import re
import sys
import time
import oci_instances as instances
# Names given by the OCI installers and by updates; other archives are never touched.
NAME = re.compile(r'(?:proxmenux-update-[a-z0-9]+-[0-9a-f]{64}'
r'|(?:image|linuxserver)-[A-Za-z0-9._-]+_[a-z0-9]+_[0-9a-f]{16})\.tar')
IN_PROGRESS = {'installing', 'assembling', 'updating', 'recovering'}
# A recent archive may belong to an installation that has not saved its record yet.
MIN_AGE_SECONDS = 3600
def unused_archives(root=instances.ROOT):
"""Archives no installed guest uses; empty while any operation is pending
or a record cannot be read."""
keep, folders = set(), set()
for path in Path(root).glob('*/oci-compose.json'):
try:
record = json.loads(path.read_text())
vmid = int(record['vmid'])
except (OSError, ValueError, KeyError, TypeError):
return []
exists = instances.guest_exists(vmid)
if (record.get('pending_transaction') or record.get('pending_stack_transaction')
or (exists and record.get('status') in IN_PROGRESS)):
return []
archive = (record.get('observed') or {}).get('archive_path')
if not archive:
continue
folders.add(Path(archive).parent)
if exists:
keep.add(Path(archive))
now = time.time()
result = []
for folder in folders:
for candidate in folder.glob('*.tar'):
if candidate in keep or not NAME.fullmatch(candidate.name) or candidate.is_symlink():
continue
info = candidate.stat()
if candidate.is_file() and now - info.st_mtime >= MIN_AGE_SECONDS:
result.append((candidate, info.st_size))
return result
def prune(root=instances.ROOT, lock=True):
"""Removes the unused archives and returns them as (path, size). Callers
that already hold the registry lock pass lock=False."""
if lock:
with instances.locked(root):
return prune(root, lock=False)
removed = []
for candidate, size in unused_archives(root):
try:
candidate.unlink()
except OSError:
continue
removed.append((candidate, size))
return removed
def archives_of(vmids, root=instances.ROOT):
"""The downloaded archives the given installations were created from."""
result = {}
for vmid in vmids:
archive = (instances.read(root, vmid).get('observed') or {}).get('archive_path')
path = Path(archive) if archive else None
if path and NAME.fullmatch(path.name) and path.is_file() and not path.is_symlink():
result[path] = path.stat().st_size
return result
def main(arguments):
command = arguments[0] if arguments else 'prune'
if command == 'prune':
for path, size in prune():
print(f'removed unused image archive: {path} ({size} bytes)')
return 0
if command not in ('list', 'remove') or not all(a.isdigit() for a in arguments[1:]):
print('usage: oci_image_cache.py [prune | list VMID... | remove VMID...]', file=sys.stderr)
return 2
with instances.locked(instances.ROOT):
archives = archives_of([int(a) for a in arguments[1:]])
freed = 0
if command == 'remove':
for path, size in archives.items():
path.unlink()
freed += size
print(json.dumps({'archives': [{'path': str(p), 'size': s} for p, s in archives.items()],
'freed': freed}))
return 0
if __name__ == '__main__':
try:
sys.exit(main(sys.argv[1:]))
except (OSError, ValueError, BlockingIOError) as error:
print(f'image cache: {error}', file=sys.stderr)
sys.exit(1)