Skip to content

Commit 67835c7

Browse files
committed
test(context): probe kernel telemetry feasibility
Signed-off-by: aihop <4408344+hhyykk@users.noreply.github.com>
1 parent 886e85d commit 67835c7

3 files changed

Lines changed: 240 additions & 0 deletions

File tree

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
"""Check taskstats access without storing exit records from other processes."""
2+
import json
3+
import os
4+
from pathlib import Path
5+
import socket
6+
import struct
7+
8+
sock = socket.socket(socket.AF_NETLINK, socket.SOCK_RAW, 16)
9+
sock.settimeout(2)
10+
sock.bind((0, 0))
11+
report = {'purpose': 'capability only; no CLI or I/O accounting acceptance'}
12+
family = None
13+
registered = False
14+
mask = ','.join(map(str, sorted(os.sched_getaffinity(0)))).encode() + b'\0'
15+
16+
17+
def attributes(payload):
18+
offset = 0
19+
while offset + 4 <= len(payload):
20+
length, kind = struct.unpack_from('HH', payload, offset)
21+
if length < 4 or offset + length > len(payload):
22+
raise ValueError('invalid netlink attribute length')
23+
yield kind & 0x3fff, payload[offset + 4:offset + length]
24+
offset += (length + 3) & ~3
25+
26+
27+
def request(family_id, command, kind, payload, sequence, ack=False):
28+
attr = struct.pack('HH', len(payload) + 4, kind) + payload
29+
attr += b'\0' * (-len(attr) % 4)
30+
body = struct.pack('BBH', command, 1, 0) + attr
31+
sock.sendto(struct.pack('IHHII', len(body) + 16, family_id, 5 if ack else 1,
32+
sequence, sock.getsockname()[0]) + body, (0, 0))
33+
# Ignore unrelated exit notifications; never persist their contents.
34+
for _ in range(128):
35+
data = sock.recv(65536)
36+
offset = 0
37+
while offset + 16 <= len(data):
38+
length, msg_kind, _, seq, _ = struct.unpack_from('IHHII', data, offset)
39+
if length < 16 or offset + length > len(data):
40+
raise ValueError('invalid netlink message length')
41+
if seq == sequence:
42+
if msg_kind == 2:
43+
error = struct.unpack_from('i', data, offset + 16)[0]
44+
if error:
45+
raise OSError(-error, os.strerror(-error))
46+
return b''
47+
return data[offset + 20:offset + length]
48+
offset += (length + 3) & ~3
49+
raise RuntimeError('no matching netlink response within bounded receive loop')
50+
51+
52+
try:
53+
attrs = dict(attributes(request(16, 3, 2, b'TASKSTATS\0', 1)))
54+
family = struct.unpack('H', attrs[1])[0]
55+
report['family_id'] = family
56+
own = request(family, 1, 1, struct.pack('I', os.getpid()), 2)
57+
report['own_pid_query_returned_attributes'] = [kind for kind, _ in attributes(own)]
58+
request(family, 1, 3, mask, 3, ack=True)
59+
registered = True
60+
report['exit_registration'] = 'available'
61+
except (OSError, ValueError, RuntimeError) as exc:
62+
report['error'] = f'{type(exc).__name__}: {exc}'
63+
finally:
64+
if registered:
65+
try:
66+
request(family, 1, 4, mask, 4, ack=True)
67+
report['exit_deregistration'] = 'complete'
68+
except (OSError, ValueError, RuntimeError) as exc:
69+
report['exit_deregistration_error'] = str(exc)
70+
sock.close()
71+
report['socket_closed'] = True
72+
supported = (report.get('exit_registration') == 'available'
73+
and report.get('exit_deregistration') == 'complete'
74+
and 4 in report.get('own_pid_query_returned_attributes', [])
75+
and not report.get('error'))
76+
report['capability_verdict'] = 'access_available' if supported else 'unsupported_or_incomplete'
77+
Path(__file__).with_name('taskstats-result.json').write_text(json.dumps(report, indent=2) + '\n')
78+
print(json.dumps(report, indent=2))
79+
if not supported:
80+
raise SystemExit(2)
Lines changed: 124 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,124 @@
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)
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
name: C2 Telemetry Capability Probe
2+
3+
on:
4+
push:
5+
branches:
6+
- codex/c2-telemetry-probe-20261030
7+
8+
permissions:
9+
contents: read
10+
11+
jobs:
12+
capability:
13+
runs-on: ubuntu-24.04
14+
timeout-minutes: 30
15+
steps:
16+
- uses: actions/checkout@v7
17+
with:
18+
persist-credentials: false
19+
- name: Probe existing kernel capabilities without installing dependencies
20+
run: |
21+
mkdir -p "$RUNNER_TEMP/c2-telemetry-probe"
22+
cp .github/c2-telemetry-probe/*.py "$RUNNER_TEMP/c2-telemetry-probe/"
23+
trace_status=0
24+
taskstats_status=0
25+
sudo -n python3 "$RUNNER_TEMP/c2-telemetry-probe/tracefs_toy.py" || trace_status=$?
26+
sudo -n python3 "$RUNNER_TEMP/c2-telemetry-probe/taskstats_probe.py" || taskstats_status=$?
27+
test "$trace_status" -eq 0 && test "$taskstats_status" -eq 0
28+
- name: Preserve capabilities and unsupported results
29+
if: always()
30+
uses: actions/upload-artifact@v7
31+
with:
32+
name: c2-telemetry-capabilities
33+
retention-days: 30
34+
path: |
35+
${{ runner.temp }}/c2-telemetry-probe/*-result.json
36+
${{ runner.temp }}/c2-telemetry-probe/*.trace

0 commit comments

Comments
 (0)