Iomatex_OS/offline/git_delivery.py

547 lines
26 KiB
Python

#!/usr/bin/env python3
"""Small Edge snapshot + on-demand, hash-checked downloads from our Git only.
APT method protocol: https://sources.debian.org/src/apt/2.2.4/doc/method.dbk/
"""
import base64
from concurrent.futures import ThreadPoolExecutor, wait, FIRST_COMPLETED
import fcntl
import gzip
import importlib.util
import hashlib
import http.client
import json
import os
from pathlib import Path, PurePosixPath
import pwd
import re
import shutil
import signal
import socket
import subprocess
import sys
import tempfile
import time
import ssl
import urllib.error
import urllib.parse
import urllib.request
HOST = 'git.iomatex.com'
ALLOWED_HOSTS = (HOST, 'git.it-screen.com')
def git_host(value=HOST):
if value not in ALLOWED_HOSTS:
raise ValueError('Unsupported Git host')
# Normalize legacy saved credentials/snapshots before any network request.
return HOST
STATE = Path('/var/lib/iomatex/packages')
AUTH = Path('/etc/iomatex/git-credentials.json')
CACHE = Path('/userdata/iomatex-apt-cache')
DEBIAN = 'third_party/debian/bullseye-arm64'
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, *args, **kwargs):
raise ValueError('Git download redirect refused')
def safe_path(value):
p = PurePosixPath(value)
if p.is_absolute() or '..' in p.parts or not p.parts or any(c in value for c in '\r\n\\'):
raise ValueError('Unsafe repository path')
return p.as_posix()
def repo_name(url):
u = urllib.parse.urlparse(url)
if u.scheme != 'https' or u.netloc not in ALLOWED_HOSTS or u.query or u.fragment:
raise ValueError('Only HTTPS repositories on our Git are allowed')
name = u.path.strip('/').removesuffix('.git')
if not re.fullmatch(r'[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+', name):
raise ValueError('Invalid repository')
return name
def auth_from_env():
user, password = os.environ.get('IOMATEX_GIT_USERNAME'), os.environ.get('IOMATEX_GIT_PASSWORD')
if user and password:
return {'username': user, 'password': password}
return json.loads(AUTH.read_text())
def open_git(repo, endpoint, auth, timeout=120):
url = 'https://' + git_host(auth.get('host', HOST)) + '/api/v1/repos/' + repo + '/' + endpoint
token = base64.b64encode((auth['username'] + ':' + auth['password']).encode()).decode()
req = urllib.request.Request(url, headers={'Authorization': 'Basic ' + token, 'User-Agent': 'IomatexOS-Updater/1.0'})
return urllib.request.build_opener(NoRedirect).open(req, timeout=timeout)
def raw_endpoint(path, commit):
if not re.fullmatch('[a-f0-9]{40}', commit):
raise ValueError('Download must be pinned to a commit')
return 'raw/' + urllib.parse.quote(safe_path(path), safe='/') + '?ref=' + commit
def blob_hash(data):
return hashlib.sha1(b'blob ' + str(len(data)).encode() + b'\0' + data).hexdigest()
def write_json(path, value, mode=0o644):
path.parent.mkdir(parents=True, exist_ok=True)
fd, tmp = tempfile.mkstemp(dir=path.parent)
try:
with os.fdopen(fd, 'w') as f:
json.dump(value, f)
os.chmod(tmp, mode)
os.replace(tmp, path)
finally:
Path(tmp).unlink(missing_ok=True)
def platform_check():
if os.geteuid() != 0:
raise PermissionError('Run as root')
if subprocess.check_output(['dpkg', '--print-architecture'], text=True).strip() != 'arm64' or 'VERSION_CODENAME=bullseye' not in Path('/etc/os-release').read_text():
raise ValueError('Supported image: Debian 11 Bullseye arm64')
def is_payload(path):
return path.endswith(('.deb', '.tar.gz')) or path == 'stage_itscreen/itscreen'
def snapshot_changes(dest):
changes = []
source = json.loads((dest / '.iomatex-source.json').read_text())
for entry in source['files']:
relative = safe_path(entry['path'])
p = dest / relative
if p.is_symlink() or not p.resolve().is_relative_to(dest.resolve()):
raise ValueError('Preserve snapshot symlink before updating: ' + relative)
if p.exists() and not p.is_file():
raise ValueError('Snapshot file replaced by directory: ' + relative)
if not p.exists():
changes.append({'path': relative, 'deleted': True})
elif blob_hash(p.read_bytes()) != entry['sha']:
changes.append({'path': relative, 'deleted': False})
return changes
def check_existing(dest, preserve_local_changes=False):
if (dest / '.git').exists():
changed = subprocess.check_output(['git', '-C', str(dest), 'status', '--porcelain', '--untracked-files=no'], text=True)
if changed.strip():
raise ValueError('Existing checkout has tracked local changes; preserve them before updating')
elif (dest / '.iomatex-source.json').exists():
changes = snapshot_changes(dest)
if changes and not preserve_local_changes:
raise ValueError('Local change in snapshot: ' + changes[0]['path'])
elif dest.exists() and any(dest.iterdir()):
raise ValueError('Refusing to replace an unidentified nonempty directory')
def preserve_snapshot_changes(dest):
"""Retain local hotfixes outside the managed snapshot before a confirmed update."""
changes = snapshot_changes(dest)
if not changes:
return None
backup = Path(tempfile.mkdtemp(prefix='.' + dest.name + '-local-changes-', dir=dest.parent))
try:
records = []
for change in changes:
record = dict(change)
if not change['deleted']:
source = dest / change['path']
data = source.read_bytes()
target = backup / 'files' / change['path']
target.parent.mkdir(parents=True, exist_ok=True)
with target.open('wb') as stream:
stream.write(data)
stream.flush()
os.fsync(stream.fileno())
shutil.copystat(source, target)
record['sha256'] = hashlib.sha256(data).hexdigest()
if hashlib.sha256(target.read_bytes()).hexdigest() != record['sha256']:
raise RuntimeError('Local change backup verification failed')
records.append(record)
write_json(backup / 'backup.json', {
'source': json.loads((dest / '.iomatex-source.json').read_text()),
'changes': records, 'created_at': int(time.time()), 'checkout': str(dest)}, 0o600)
with (backup / 'backup.json').open('rb') as manifest_file:
os.fsync(manifest_file.fileno())
for directory in [*sorted((p for p in backup.rglob('*') if p.is_dir()), key=lambda p: len(p.parts), reverse=True), backup, backup.parent]:
fd = os.open(directory, os.O_RDONLY | os.O_DIRECTORY)
try:
os.fsync(fd)
finally:
os.close(fd)
print(f'Preserved {len(records)} local installer changes in {backup}', flush=True)
return backup
except BaseException:
shutil.rmtree(backup)
raise
def transient_download_error(error):
if isinstance(error, urllib.error.HTTPError):
return error.code in (408, 429, 500, 502, 503, 504)
if isinstance(error, urllib.error.URLError):
error = error.reason
return isinstance(error, (TimeoutError, socket.timeout, ConnectionError, http.client.IncompleteRead)) and not isinstance(error, ssl.SSLCertVerificationError)
def snapshot_bytes(repo, commit, auth, path):
for attempt in range(1, 4):
started = time.monotonic()
try:
with open_git(repo, raw_endpoint(path, commit), auth, timeout=30) as response:
return response.read()
except Exception as error:
if not transient_download_error(error):
raise
elapsed = time.monotonic() - started
print(f'Download {path}: {type(error).__name__} after {elapsed:.1f}s '
f'(attempt {attempt}/3)', flush=True)
if attempt == 3:
raise RuntimeError(f'Git download failed after 3 attempts: {path} '
f'({type(error).__name__})') from error
time.sleep(attempt * 2)
def download_snapshot(files, download):
started = time.monotonic()
completed = 0
print(f'Downloading {len(files)} files, 3 workers; network timeout 30s, up to 3 attempts per file', flush=True)
with ThreadPoolExecutor(max_workers=3) as pool:
pending = {pool.submit(download, item): item['path'] for item in files}
try:
while pending:
done, _ = wait(pending, timeout=10, return_when=FIRST_COMPLETED)
if not done:
print(f'Download progress: {completed}/{len(files)}, '
f'{time.monotonic() - started:.0f}s elapsed; waiting for HTTPS', flush=True)
for future in done:
path = pending.pop(future)
try:
future.result()
except Exception:
print('Download failed: ' + path, flush=True)
raise
completed += 1
print(f'Download progress: {completed}/{len(files)} verified: {path}', flush=True)
finally:
for future in pending:
future.cancel()
print(f'Download complete: {completed} files in {time.monotonic() - started:.1f}s', flush=True)
def materialize_file(repo, commit, auth, entry, existing, staged):
old = existing / entry['path']
data = old.read_bytes() if old.is_file() and not old.is_symlink() else None
if data is None or blob_hash(data) != entry['sha']:
data = snapshot_bytes(repo, commit, auth, entry['path'])
if blob_hash(data) != entry['sha']:
raise ValueError('Git blob checksum mismatch: ' + entry['path'])
p = staged / entry['path']
p.parent.mkdir(parents=True, exist_ok=True)
p.write_bytes(data)
p.chmod(int(entry['mode'][-3:], 8))
class RecoveryPending(Exception):
"""Boot recovery owns continuation; callers must not install or report success."""
def recovery_gate(repo, branch, commit, auth, files, stages, job=None):
entry = next((e for e in files if e['path'] == 'stage_env/userdata_recovery.py'), None)
if entry is None:
return # Older pinned releases do not contain this recovery contract.
with tempfile.TemporaryDirectory(prefix='iomatex-storage-probe-') as folder:
folder = Path(folder)
materialize_file(repo, commit, auth, entry, folder / 'absent', folder)
spec = importlib.util.spec_from_file_location('iomatex_userdata_recovery', folder / entry['path'])
recovery = importlib.util.module_from_spec(spec)
spec.loader.exec_module(recovery)
report = recovery.inspect()
if not report or not report['needed']:
return
if not stages:
raise RuntimeError('Damaged userdata detected. Download the current install_iomatex_edge.sh and run it again.')
recovery.storage_directory(report['device'])
if recovery.REQUEST.exists():
previous = json.loads(recovery.REQUEST.read_text())
if previous.get('status') not in ('complete', 'installer_reboot_pending'):
raise RuntimeError('Storage recovery already pending or failed; see ' + str(recovery.REQUEST))
# Fresh, verified snapshot on root: never read/replace the corrupt checkout.
root = Path(tempfile.mkdtemp(prefix='installer-', dir=recovery.BASE))
try:
print('Fetching verified recovery installer onto the system filesystem...', flush=True)
def download(item):
if shutil.disk_usage(root).free < recovery.RESERVE:
raise RuntimeError('Not enough system disk space for recovery installer')
materialize_file(repo, commit, auth, item, root / 'absent', root)
download_snapshot(files, download)
write_json(root / '.iomatex-source.json',
{'repo': repo, 'host': git_host(auth.get('host', HOST)), 'branch': branch, 'commit': commit, 'files': files})
print('Verifying recovery package catalog...', flush=True)
catalog(root)
write_json(AUTH, auth, 0o600)
print('Preparing offline recovery...', flush=True)
recovery.arm(root, stages, report, job)
except Exception:
# Keep evidence and snapshots once a boot recovery request exists.
if not recovery.REQUEST.exists():
shutil.rmtree(root)
raise
raise RecoveryPending('Offline userdata recovery queued; update is pending, not complete')
def bootstrap(url, branch, checkout, commit=None, recovery_stages=None, recovery_job=None, preserve_local_changes=False):
platform_check()
repo = repo_name(url)
requested = Path(checkout)
dest = requested.resolve()
if not requested.is_absolute() or len(dest.parts) < 3 or requested.is_symlink():
raise ValueError('Use a dedicated absolute installer subdirectory')
auth = {**auth_from_env(), 'host': git_host(urllib.parse.urlparse(url).netloc)}
if commit is None:
with open_git(repo, 'branches/' + urllib.parse.quote(branch, safe=''), auth) as r:
commit = json.load(r)['commit']['id']
if not re.fullmatch('[a-f0-9]{40}', commit):
raise ValueError('Invalid pinned commit')
with open_git(repo, 'git/trees/' + commit + '?recursive=true', auth) as r:
tree = json.load(r)
if tree.get('truncated'):
raise ValueError('Git returned an incomplete repository tree')
files = []
for item in tree['tree']:
path = safe_path(item['path'])
if item['type'] == 'tree' or is_payload(path):
continue
if item['type'] != 'blob' or item['mode'] not in ('100644', '100755'):
raise ValueError('Unsupported Git tree member: ' + path)
files.append({k: item[k] for k in ('path', 'sha', 'mode')})
stages = recovery_stages or os.environ.get('IOMATEX_RECOVERY_STAGES', '').split(',')
recovery_gate(repo, branch, commit, auth, files, [stage for stage in stages if stage], recovery_job)
check_existing(dest, preserve_local_changes=preserve_local_changes)
if (dest / '.git').exists():
origin = subprocess.check_output(['git', '-C', str(dest), 'remote', 'get-url', 'origin'], text=True).strip()
if repo_name(origin) != repo:
raise ValueError('Existing checkout origin mismatch')
elif (dest / '.iomatex-source.json').exists():
if json.loads((dest / '.iomatex-source.json').read_text()).get('repo') != repo:
raise ValueError('Existing snapshot origin mismatch')
dest.parent.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(prefix='.iomatex-install-', dir=dest.parent) as tmp:
staged = Path(tmp) / 'snapshot'
staged.mkdir()
def download(entry):
materialize_file(repo, commit, auth, entry, dest, staged)
print('Fetching', len(files), 'installer/metadata files; package payloads excluded', flush=True)
download_snapshot(files, download)
source = {'repo': repo, 'host': git_host(auth.get('host', HOST)), 'commit': commit, 'branch': branch, 'files': files}
write_json(staged / '.iomatex-source.json', source)
# Validate all metadata before replacing an existing installation snapshot.
catalog(staged)
if preserve_local_changes and (dest / '.iomatex-source.json').exists() and not (dest / '.git').exists():
preserve_snapshot_changes(dest)
previous = Path(tmp) / 'previous'
if dest.exists():
# Keep untracked operator files/state/logs, never carry the old Git pack or payloads.
tracked = set()
if (dest / '.git').exists():
tracked = set(subprocess.check_output(['git', '-C', str(dest), 'ls-files'], text=True).splitlines())
else:
tracked = {e['path'] for e in json.loads((dest / '.iomatex-source.json').read_text()).get('files', [])}
for p in dest.rglob('*'):
relative = p.relative_to(dest).as_posix()
if '.git' in p.relative_to(dest).parts or relative in tracked or relative == '.iomatex-source.json':
continue
if p.is_symlink():
raise ValueError('Preserve untracked symlink before updating: ' + relative)
if p.is_file() and not (staged / relative).exists():
(staged / relative).parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(p, staged / relative)
dest.rename(previous)
try:
staged.rename(dest)
write_json(AUTH, auth, 0o600)
# Execute the NEW activator from the downloaded commit, not an old bootstrap copy.
subprocess.run([sys.executable, str(dest / 'offline/git_delivery.py'), 'activate', str(dest)], check=True)
except BaseException:
if dest.exists(): shutil.rmtree(dest)
if previous.exists(): previous.rename(dest)
raise
print('Lightweight installer ready:', commit, str(dest), flush=True)
def manifest(path):
result = {}
for line in path.read_text().splitlines():
digest, name = line.split(' ', 1)
name = safe_path(name)
if not re.fullmatch('[a-f0-9]{64}', digest) or name in result:
raise ValueError('Invalid checksum manifest')
result[name] = digest
return result
def catalog(root):
root = Path(root)
sums = manifest(root / DEBIAN / 'SHA256SUMS')
runtime = manifest(root / 'third_party/SHA256SUMS')
for name, digest in sums.items():
if not name.endswith('.deb') and hashlib.sha256((root / DEBIAN / name).read_bytes()).hexdigest() != digest:
raise ValueError('Metadata checksum mismatch: ' + name)
if (root / DEBIAN / 'platform').read_text().splitlines() != ['bullseye', 'arm64']:
raise ValueError('Unsupported package catalog')
objects = {}
stanzas = []
for text, prefix, base, hashes in [
((root / DEBIAN / 'repo/Packages').read_text(), 'debian', DEBIAN + '/repo', {k.removeprefix('repo/'):v for k,v in sums.items() if k.endswith('.deb')}),
((root / 'third_party/node/Packages').read_text(), 'node', 'third_party/node', {k.removeprefix('node/'):v for k,v in runtime.items() if k.startswith('node/')}),
]:
for stanza in text.strip().split('\n\n'):
fields = dict(line.split(': ', 1) for line in stanza.splitlines() if ': ' in line and not line.startswith(' '))
name = safe_path(fields['Filename'].removeprefix('./'))
digest = fields['SHA256']
if hashes.get(name) != digest:
raise ValueError('Package index not covered by SHA256SUMS: ' + name)
logical = prefix + '/' + name
objects[logical] = {'path': base + '/' + name, 'sha256': digest, 'size': int(fields['Size'])}
stanzas.append(re.sub(r'^Filename: .*$', 'Filename: ' + logical, stanza, flags=re.M))
for name, digest in runtime.items():
objects['third_party/' + name] = {'path': 'third_party/' + name, 'sha256': digest}
digest = manifest(root / 'stage_itscreen/itscreen.sha256')['itscreen']
objects['stage_itscreen/itscreen'] = {'path': 'stage_itscreen/itscreen', 'sha256': digest}
return '\n\n'.join(stanzas) + '\n\n', objects
def activate(root):
platform_check()
root = Path(root).resolve()
source = json.loads((root / '.iomatex-source.json').read_text())
repo_name('https://' + git_host(source.get('host', HOST)) + '/' + source['repo'])
raw_endpoint('probe', source['commit'])
auth_from_env() # fail before modifying APT if reboot credentials are missing
text, objects = catalog(root)
STATE.mkdir(parents=True, exist_ok=True)
(STATE / 'Packages').write_text(text)
(STATE / 'Packages.gz').write_bytes(gzip.compress(text.encode(), mtime=0))
write_json(STATE / 'source.json', {'repo':source['repo'], 'host':git_host(source.get('host', HOST)), 'commit':source['commit'], 'objects':objects})
owner = Path('/usr/local/lib/iomatex')
owner.mkdir(parents=True, exist_ok=True)
shutil.copy2(root / 'offline/git_delivery.py', owner / 'git_delivery.py')
if (root / 'offline/stage_versions.py').exists():
shutil.copy2(root / 'offline/stage_versions.py', owner / 'stage_versions.py')
subprocess.run([sys.executable, str(owner / 'stage_versions.py'), 'configure', str(root)], check=True)
method = Path('/usr/lib/apt/methods/iomatex')
method.write_text('#!/bin/sh\nexec /usr/bin/python3 /usr/local/lib/iomatex/git_delivery.py apt-method\n')
method.chmod(0o755)
CACHE.mkdir(parents=True, exist_ok=True)
(CACHE / 'partial').mkdir(exist_ok=True)
apt = Path('/etc/apt')
(apt / 'iomatex-offline.list').write_text('deb [trusted=yes] iomatex://git.iomatex.com/ ./\n')
(apt / 'apt.conf.d/99iomatex-offline').write_text(
'Dir::Etc::sourcelist "/etc/apt/iomatex-offline.list";\n'
'Dir::Etc::sourceparts "-";\n'
'Dir::Cache::archives "/userdata/iomatex-apt-cache/";\n'
'APT::Install-Recommends "false";\nAPT::Install-Suggests "false";\nAcquire::Languages "none";\n'
'APT::Keep-Downloaded-Packages "false";\nBinary::apt-get::APT::Keep-Downloaded-Packages "false";\n'
'DPkg::Post-Invoke { "rm -f /userdata/iomatex-apt-cache/*.deb /userdata/iomatex-apt-cache/partial/*.deb"; };\n')
cleanup()
print('Git-only APT ready; payloads downloaded on demand:', source['commit'], flush=True)
def cleanup():
CACHE.mkdir(parents=True, exist_ok=True)
with (CACHE / 'lock').open('a') as lock:
try: fcntl.lockf(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError: return
for folder in [CACHE, CACHE / 'partial']:
if folder.exists():
for p in folder.iterdir():
if p.is_file() and p.name != 'lock': p.unlink()
def download_object(config, key, dest, auth):
entry = config['objects'].get(key)
if entry is None:
raise FileNotFoundError('Object absent from the pinned Git catalog')
path = Path(dest)
digest = hashlib.sha256()
size = 0
try:
with open_git(config['repo'], raw_endpoint(entry['path'], config['commit']), {**auth, 'host': git_host(config.get('host', HOST))}) as response, path.open('wb') as output:
while True:
chunk = response.read(1024 * 1024)
if not chunk: break
output.write(chunk)
digest.update(chunk)
size += len(chunk)
if digest.hexdigest() != entry['sha256'] or ('size' in entry and size != entry['size']):
raise ValueError('Git payload checksum or size mismatch')
except BaseException:
path.unlink(missing_ok=True)
raise
return digest.hexdigest(), size
def message(code, fields):
print(code)
for k, v in fields.items():
print(k + ': ' + str(v).replace('\n', ' ').replace('\r', ' '))
print('', flush=True)
def apt_key(uri, objects):
u = urllib.parse.urlparse(uri)
if u.scheme != 'iomatex' or u.netloc not in ALLOWED_HOSTS or u.query or u.fragment:
raise ValueError('Unsupported APT source')
# APT's method protocol may already decode the URI displayed by apt-get.
# Preserve literal %3a in Git filenames; never decode it twice into an epoch colon.
for path in (u.path, urllib.parse.unquote(u.path)):
key = safe_path(path.lstrip('/'))
if key in ('Packages', 'Packages.gz') or key in objects:
return key
raise FileNotFoundError('File absent from the pinned Git catalog')
def apt_method():
def stopped(signum, frame):
raise SystemExit(0)
signal.signal(signal.SIGINT, stopped)
signal.signal(signal.SIGTERM, stopped)
config = json.loads((STATE / 'source.json').read_text())
auth = auth_from_env()
# APT launches this helper as root; read private credentials before dropping privileges.
if os.geteuid() == 0:
user = pwd.getpwnam('_apt')
os.setgroups([])
os.setgid(user.pw_gid)
os.setuid(user.pw_uid)
message('100 Capabilities', {'Version':'1.0', 'Single-Instance':'true', 'Pipeline':'false', 'Send-Config':'false'})
while True:
first = sys.stdin.readline()
if not first: return
if not first.strip(): continue
fields = {}
while True:
line = sys.stdin.readline().rstrip('\n')
if not line: break
k, _, value = line.partition(': ')
fields[k] = value
if not first.startswith('600 '): continue
uri, filename = fields.get('URI', ''), fields.get('Filename', '')
try:
key = apt_key(uri, config['objects'])
message('200 URI Start', {'URI':uri})
if key in ('Packages', 'Packages.gz'):
data = (STATE / key).read_bytes()
Path(filename).write_bytes(data)
digest, size = hashlib.sha256(data).hexdigest(), len(data)
else:
digest, size = download_object(config, key, filename, auth)
message('201 URI Done', {'URI':uri, 'Filename':filename, 'Size':size, 'SHA256-Hash':digest})
except Exception as e:
# Never print authenticated URLs, response bodies, or credentials.
message('400 URI Failure', {'URI':uri, 'Message':type(e).__name__ + ': Git download failed or object absent'})
def main():
cmd = sys.argv[1]
if cmd == 'bootstrap': bootstrap(*sys.argv[2:])
elif cmd == 'activate': activate(sys.argv[2])
elif cmd == 'cleanup': cleanup()
elif cmd == 'fetch':
download_object(json.loads((STATE / 'source.json').read_text()), sys.argv[2], sys.argv[3], auth_from_env())
elif cmd == 'apt-method': apt_method()
else: raise ValueError('Unknown command')
if __name__ == '__main__':
try: main()
except RecoveryPending as error:
print(str(error), flush=True)
sys.exit(75)
except Exception as error:
print('Iomatex Git delivery failed: ' + type(error).__name__ + ': ' + str(error), file=sys.stderr)
sys.exit(1)