"""One-second Linux job-load evidence. Missing counters are null, never zero. Disk await is delta(read_ms + write_ms) / delta(completed reads + writes), per device from diskstats (the r_await/w_await weighted mean, not a sum across stacked devices). PSI retains the kernel's avg10/60/300 and total microseconds. cpu.max includes every visible ancestor, since a parent may impose the quota. The sampler is diagnostic only; it has a job-sized lifetime even if stop is lost. """ import argparse import datetime import json import os import pathlib import re import select import signal import subprocess import sys import threading import time def read_snapshot(proc=pathlib.Path('/proc')): errors = [] def read(path, parse): try: return parse(path.read_text()) except (OSError, ValueError, IndexError, StopIteration) as error: errors.append(str(path)+': '+str(error)) return None def pressure(text): return {parts[0]: {k: (int(v) if k == 'total' else float(v)) for k, v in (item.split('=') for item in parts[1:])} for parts in (line.split() for line in text.splitlines()) if parts} def diskstats(text): result = {} for line in text.splitlines(): fields = line.split() # fields after the device name: reads, merges, sectors, ms, # writes, merges, sectors, ms (present on all supported kernels). result[fields[2]] = [int(fields[3])+int(fields[7]), int(fields[6])+int(fields[10])] return result def quotas(_): group = next(line.split('::', 1)[1] for line in (proc/'self/cgroup').read_text().splitlines() if line.startswith('0::')) for line in (proc/'self/mountinfo').read_text().splitlines(): fields, filesystem = line.split(' - ', 1) if filesystem.split()[0] != 'cgroup2': continue # mountinfo escapes whitespace and backslash with octal codes. unescape = lambda value: re.sub(r'\\([0-7]{3})', lambda m: chr(int(m[1], 8)), value) fields = fields.split() base, mount = unescape(fields[3]), pathlib.Path(unescape(fields[4])) if base != '/' and (group == base or group.startswith(base+'/')): relative = group[len(base):].lstrip('/') else: # cgroup namespace: membership is relative to its visible root. relative = group.lstrip('/') current = mount / relative current.relative_to(mount) result = {} while True: path = current/'cpu.max' # The real hierarchy root need not expose cpu.max. Preserve # readable leaf/parent quotas even if another level is absent. result[str(path)] = read(path, str.strip) if current == mount: return result current = current.parent raise ValueError('no visible cgroup v2 mount (v1 or unavailable)') return dict(load1=read(proc/'loadavg', lambda text: float(text.split()[0])), cpu=read(proc/'stat', lambda text: [int(v) for v in next( line for line in text.splitlines() if line.startswith('cpu ')).split()[1:]]), disks=read(proc/'diskstats', diskstats), psi={kind: read(proc/'pressure'/filename, pressure) for kind, filename in [('cpu', 'cpu'), ('io', 'io'), ('mem', 'memory')]}, cpu_max=read(proc/'self/cgroup', quotas), errors=errors) def interval(before, after): cpu = dict(steal_pct=None, iowait_pct=None) old, new = before['cpu'], after['cpu'] if old is not None and new is not None and len(old) >= 8 and len(new) >= 8: deltas = [new[i]-old[i] for i in range(8)] # guest already included in user/nice total = sum(deltas) if min(deltas) >= 0 and total > 0: cpu = dict(steal_pct=100*deltas[7]/total, iowait_pct=100*deltas[4]/total) disks = None if after['disks'] is not None: disks = {} for name, values in after['disks'].items(): previous = (before['disks'] or {}).get(name) disks[name] = None if previous and values[0] > previous[0] and values[1] >= previous[1]: disks[name] = (values[1]-previous[1])/(values[0]-previous[0]) return cpu, disks def sample(output, duration): output.parent.mkdir(parents=True, exist_ok=True) previous = dict(cpu=None, disks=None) end, due = time.monotonic()+duration, time.monotonic() stopped = threading.Event() signal.signal(signal.SIGTERM, lambda *_: stopped.set()) with output.open('w', buffering=1) as stream: stream.write('ts_utc\tload1\tsteal_pct\tiowait_pct\tpsi_cpu\tpsi_io\tpsi_mem\tdisk_await_ms\tcgroup_cpu_max\terrors\n') while not stopped.is_set() and time.monotonic() < end: timestamp = datetime.datetime.now(datetime.timezone.utc).isoformat(timespec='milliseconds') current = read_snapshot() cpu, disks = interval(previous, current) fields = [timestamp, current['load1'], cpu['steal_pct'], cpu['iowait_pct'], current['psi']['cpu'], current['psi']['io'], current['psi']['mem'], disks, current['cpu_max'], current['errors']] stream.write('\t'.join(json.dumps(v, separators=(',', ':')) if not isinstance(v, str) else v for v in fields)+'\n') previous = current due += 1 stopped.wait(max(0, min(due, end)-time.monotonic())) # Do not emit a burst of fictitious one-second samples after a stall. due = max(due, time.monotonic()) def identity(pid): # comm may contain spaces or parentheses; starttime is field 22. return pathlib.Path(f'/proc/{pid}/stat').read_text().rsplit(')', 1)[1].split()[19] def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('action', choices=['start', 'sample', 'stop']) parser.add_argument('output', type=pathlib.Path) parser.add_argument('--duration', type=int, default=5400) args = parser.parse_args() receipt = args.output.with_suffix('.pid.json') if args.action == 'sample': sample(args.output, args.duration) elif args.action == 'start': args.output.parent.mkdir(parents=True, exist_ok=True) with args.output.with_suffix('.sampler.log').open('w') as log: child = subprocess.Popen([sys.executable, '-I', str(pathlib.Path(__file__).resolve()), 'sample', str(args.output), '--duration', str(args.duration)], stdin=subprocess.DEVNULL, stdout=log, stderr=log, start_new_session=True) receipt.write_text(json.dumps(dict(pid=child.pid, start=identity(child.pid)))) elif receipt.exists(): owner = json.loads(receipt.read_text()) handle = None try: # A pidfd makes the identity-check/signal pair safe even if the # process exits and its numeric PID is recycled between the two. handle = os.pidfd_open(owner['pid']) if identity(owner['pid']) == owner['start']: signal.pidfd_send_signal(handle, signal.SIGTERM) # Flush the last row before the uploader reads the file. Never # signal a reused PID and never wait indefinitely for evidence. # The pidfd turns readable when the sampler exits; one still # alive after 2 s leaves load.incomplete beside its rows. if not select.select([handle], [], [], 2)[0]: note = args.output.with_suffix('.incomplete') note.write_text('the sampler did not exit within 2 s of SIGTERM; its last rows may be missing\n') print('load evidence incomplete: '+str(note), file=sys.stderr) except ProcessLookupError: pass except FileNotFoundError: pass finally: if handle is not None: os.close(handle) if __name__ == '__main__': main()