87 lines
3.7 KiB
Python
87 lines
3.7 KiB
Python
"""Durable, untruncated action logs and lifecycle events for the private portal."""
|
|
from datetime import datetime, timezone
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import shutil
|
|
import subprocess
|
|
import time
|
|
|
|
|
|
def now():
|
|
return datetime.now(timezone.utc).isoformat()
|
|
|
|
|
|
def atomic(path, value):
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
temp = path.with_suffix('.tmp')
|
|
temp.write_text(json.dumps(value, indent=2) + '\n')
|
|
temp.replace(path)
|
|
|
|
|
|
def log_files(root):
|
|
"""Do not traverse package payloads, OSTree objects or build-tool roots."""
|
|
if not root.exists():
|
|
return
|
|
prune = {'repo', 'objects', 'tools', 'iso-work', 'profile', 'extractor', 'core-base',
|
|
'purpose-stage', 'composed', 'layer', 'purpose-layer', 'purpose-input',
|
|
'flatpak-seed', 'source', 'target', '.git', 'root.x86_64', 'node_modules'}
|
|
for directory, dirs, files in os.walk(root, followlinks=False):
|
|
here = Path(directory)
|
|
dirs[:] = sorted(d for d in dirs if d not in prune and not (here / d).is_symlink()
|
|
and not (d == 'core' and here.name == 'build'))
|
|
for name in sorted(files):
|
|
path = here / name
|
|
if not path.is_symlink() and (path.suffix in ('.log', '.serial', '.jsonl', '.txt')
|
|
or name in ('state.json', 'native-acceptance.json', 'summary.json')):
|
|
yield path
|
|
|
|
|
|
class Monitor:
|
|
def __init__(self, base, run):
|
|
self.root = base / 'data/private/pipeline-monitor' / run
|
|
self.root.mkdir(parents=True, exist_ok=True)
|
|
self.phase = 'starting'
|
|
self.number = 0
|
|
|
|
def event(self, kind, **data):
|
|
with (self.root / 'events.jsonl').open('a') as stream:
|
|
stream.write(json.dumps(dict(time=now(), event=kind, **data)) + '\n')
|
|
stream.flush()
|
|
os.fsync(stream.fileno())
|
|
|
|
def update(self, state):
|
|
if state['state'] != self.phase:
|
|
self.event('phase', previous=self.phase, phase=state['state'], error=state.get('error'))
|
|
self.phase = state['state']
|
|
atomic(self.root / 'state.json', state)
|
|
|
|
def call(self, argv, timeout=14400, check=True, capture=False):
|
|
self.number += 1
|
|
identity = f'{self.number:04d}'
|
|
log = self.root / ('action-' + identity + '.log')
|
|
record = dict(id=identity, phase=self.phase, command=[str(x) for x in argv],
|
|
started=now(), state='running', timeout_seconds=timeout, log=log.name)
|
|
path = self.root / ('action-' + identity + '.json')
|
|
atomic(path, record)
|
|
self.event('action-start', **record)
|
|
start = time.monotonic()
|
|
try:
|
|
with log.open('ab', buffering=0) as stream:
|
|
result = subprocess.run(record['command'], check=check, timeout=timeout, stdout=stream, stderr=subprocess.STDOUT)
|
|
record.update(state='succeeded' if result.returncode == 0 else 'failed', returncode=result.returncode)
|
|
return log.read_text() if capture else result
|
|
except BaseException as error:
|
|
record.update(state='failed', returncode=getattr(error, 'returncode', None), error=str(error))
|
|
raise
|
|
finally:
|
|
record.update(finished=now(), duration_seconds=round(time.monotonic() - start, 3))
|
|
atomic(path, record)
|
|
self.event('action-finish', **record)
|
|
|
|
def retain_logs(self, roots):
|
|
for label, root in roots.items():
|
|
for source in log_files(Path(root)):
|
|
destination = self.root / 'retained' / label / source.relative_to(root)
|
|
destination.parent.mkdir(parents=True, exist_ok=True)
|
|
shutil.copyfile(source, destination)
|