|
| 1 | +"""Bounded, task-scoped tracefs lifecycle feasibility probe; no LoopX workload.""" |
| 2 | +import json |
| 3 | +import os |
| 4 | +from pathlib import Path |
| 5 | +import re |
| 6 | +import subprocess |
| 7 | +import sys |
| 8 | +import time |
| 9 | + |
| 10 | +ROOT = Path('/sys/kernel/tracing') |
| 11 | +OUT = Path(__file__).resolve().parent |
| 12 | +INSTANCE = ROOT / 'instances' / f'c2-toy-{os.getpid()}' |
| 13 | +EVENTS = ['sched_process_fork', 'sched_process_exec', 'sched_process_exit', |
| 14 | + 'sched_switch', 'sched_wakeup', 'sched_wakeup_new'] |
| 15 | +CONTROLS = ['tracing_on', 'set_event_pid', 'options/event-fork', 'trace_clock'] |
| 16 | +report = {'purpose': 'toy feasibility only; no CLI/performance qualification', |
| 17 | + 'instance': str(INSTANCE), 'created': False, 'removed': False} |
| 18 | +before = {} |
| 19 | + |
| 20 | + |
| 21 | +def write(name, value): |
| 22 | + (INSTANCE / name).write_text(str(value)) |
| 23 | + |
| 24 | + |
| 25 | +try: |
| 26 | + before = {name: (ROOT / name).read_text() for name in CONTROLS} |
| 27 | + available_kib = int(next(line.split()[1] for line in Path('/proc/meminfo').read_text().splitlines() |
| 28 | + if line.startswith('MemAvailable:'))) |
| 29 | + assert available_kib > 512 * 1024, 'Need 512MiB memory reserve' |
| 30 | + INSTANCE.mkdir() |
| 31 | + report['created'] = True |
| 32 | + write('tracing_on', 0) |
| 33 | + write('buffer_size_kb', 256) |
| 34 | + report['buffer_total_kib'] = int((INSTANCE / 'buffer_total_size_kb').read_text()) |
| 35 | + assert report['buffer_total_kib'] < 16 * 1024, 'Unexpected trace buffer allocation' |
| 36 | + write('trace_clock', 'mono') |
| 37 | + write('set_event_pid', os.getpid()) |
| 38 | + write('options/event-fork', 1) |
| 39 | + for event in EVENTS: |
| 40 | + write(f'events/sched/{event}/enable', 1) |
| 41 | + write('tracing_on', 1) |
| 42 | + write('trace_marker', f'C2_BEGIN {time.perf_counter_ns()}') |
| 43 | + child = subprocess.run([sys.executable, '-c', ''' |
| 44 | +import json, os, subprocess, sys, threading, time |
| 45 | +sys.stdin.buffer.read(1) |
| 46 | +thread_ids = [] |
| 47 | +def tiny(): |
| 48 | + thread_ids.append(threading.get_native_id()) |
| 49 | + time.sleep(.002) |
| 50 | +t = threading.Thread(target=tiny) |
| 51 | +t.start() |
| 52 | +t.join() |
| 53 | +p = subprocess.Popen([sys.executable, '-c', 'import time;time.sleep(.10)'], |
| 54 | + start_new_session=True, stdin=subprocess.DEVNULL, |
| 55 | + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) |
| 56 | +print(json.dumps({'pid':os.getpid(),'tids':thread_ids,'detached_pid':p.pid}),flush=True) |
| 57 | +'''], input=b'x', capture_output=True, timeout=5, check=True) |
| 58 | + ids = json.loads(child.stdout) |
| 59 | + time.sleep(.25) |
| 60 | + write('trace_marker', f'C2_END {time.perf_counter_ns()}') |
| 61 | + write('tracing_on', 0) |
| 62 | + trace = (INSTANCE / 'trace').read_text() |
| 63 | + (OUT / 'tracefs-toy.trace').write_text(trace) |
| 64 | + report['ids'] = ids |
| 65 | + report['event_counts'] = {event: len(re.findall(rf': {event}:', trace)) for event in EVENTS} |
| 66 | + events = [(float(match[1]), match[2], match[3]) for line in trace.splitlines() |
| 67 | + if (match := re.search(r'(\d+\.\d+): (\w+): (.*)', line))] |
| 68 | + report['lifecycle'] = {} |
| 69 | + for pid in [ids['pid'], *ids['tids'], ids['detached_pid']]: |
| 70 | + births = [ts for ts, event, text in events if event == 'sched_process_fork' |
| 71 | + and re.search(rf'child_pid={pid}\b', text)] |
| 72 | + exits = [ts for ts, event, text in events if event == 'sched_process_exit' |
| 73 | + and re.search(rf'\bpid={pid}\b', text)] |
| 74 | + ins = [ts for ts, event, text in events if event == 'sched_switch' |
| 75 | + and re.search(rf'next_pid={pid}\b', text)] |
| 76 | + outs = [ts for ts, event, text in events if event == 'sched_switch' |
| 77 | + and re.search(rf'prev_pid={pid}\b', text)] |
| 78 | + report['lifecycle'][str(pid)] = { |
| 79 | + 'birth_observed': len(births) == 1, 'exit_observed': len(exits) == 1, |
| 80 | + 'switch_in_observed': bool(ins), 'switch_out_observed': bool(outs), |
| 81 | + 'birth_before_first_run': bool(births and ins and births[0] <= min(ins)), |
| 82 | + 'terminal_switch_after_exit': bool(exits and outs and max(outs) >= exits[-1]), |
| 83 | + 'not_running_at_end': bool(ins and outs and max(outs) >= max(ins)), |
| 84 | + } |
| 85 | + report['per_cpu_stats'] = {path.parent.name: path.read_text() |
| 86 | + for path in (INSTANCE / 'per_cpu').glob('cpu*/stats')} |
| 87 | + report['markers_present'] = 'C2_BEGIN ' in trace and 'C2_END ' in trace |
| 88 | + report['lifecycle_complete'] = all(all(v.values()) for v in report['lifecycle'].values()) |
| 89 | + losses = [int(match[1]) for text in report['per_cpu_stats'].values() |
| 90 | + for line in text.splitlines() |
| 91 | + if (match := re.fullmatch(r'(?:overrun|commit overrun|dropped events):\s*(\d+)', line))] |
| 92 | + report['loss_counters_complete_and_zero'] = (len(losses) == 3 * len(report['per_cpu_stats']) |
| 93 | + and bool(losses) and not any(losses)) |
| 94 | +except Exception as exc: |
| 95 | + report['error'] = f'{type(exc).__name__}: {exc}' |
| 96 | +finally: |
| 97 | + if report['created']: |
| 98 | + cleanup_errors = [] |
| 99 | + for name in ['tracing_on', *(f'events/sched/{event}/enable' for event in EVENTS)]: |
| 100 | + try: |
| 101 | + if (INSTANCE / name).exists(): |
| 102 | + write(name, 0) |
| 103 | + except OSError as exc: |
| 104 | + cleanup_errors.append(f'{name}: {exc}') |
| 105 | + try: |
| 106 | + INSTANCE.rmdir() |
| 107 | + report['removed'] = not INSTANCE.exists() |
| 108 | + except OSError as exc: |
| 109 | + cleanup_errors.append(f'rmdir: {exc}') |
| 110 | + report['cleanup_errors'] = cleanup_errors |
| 111 | + report['global_controls_unchanged'] = (all((ROOT / name).read_text() == value |
| 112 | + for name, value in before.items()) |
| 113 | + if before else None) |
| 114 | + supported = (report.get('lifecycle_complete') and report.get('markers_present') |
| 115 | + and report.get('loss_counters_complete_and_zero') and report['removed'] |
| 116 | + and report['global_controls_unchanged'] and not report.get('error')) |
| 117 | + report['capability_verdict'] = ('toy_event_availability_confirmed' if supported else 'unsupported_or_incomplete') |
| 118 | + report['complete_cli_accounting_proven'] = False |
| 119 | + (OUT / 'tracefs-toy-result.json').write_text(json.dumps(report, indent=2) + '\n') |
| 120 | + print(json.dumps(report, indent=2)) |
| 121 | +assert report['removed'] or not report['created'] |
| 122 | +assert report['global_controls_unchanged'] is not False |
| 123 | +if not supported: |
| 124 | + raise SystemExit(2) |
0 commit comments