Skip to content

Commit 263402d

Browse files
committed
Add trace_fields
1 parent 37d1e1b commit 263402d

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

pythonbpf/__init__.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
from .decorators import bpf, map, section, bpfglobal, struct
22
from .codegen import compile_to_ir, compile, BPF
3-
from .utils import trace_pipe
3+
from .utils import trace_pipe, trace_fields
44

55
__all__ = [
66
"bpf",
@@ -12,4 +12,5 @@
1212
"compile",
1313
"BPF",
1414
"trace_pipe",
15+
"trace_fields",
1516
]

pythonbpf/utils.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,9 @@
11
import subprocess
2+
import re
3+
4+
TRACE_PATTERN = re.compile(
5+
rb"^(.{1,16}?)-(\d+)\s+\[(\d+)\]\s+([a-zA-Z.]+)\s+([0-9.]+):\s+.*?:\s+(.*)$"
6+
)
27

38

49
def trace_pipe():
@@ -7,3 +12,20 @@ def trace_pipe():
712
subprocess.run(["cat", "/sys/kernel/tracing/trace_pipe"])
813
except KeyboardInterrupt:
914
print("Tracing stopped.")
15+
16+
17+
def trace_fields():
18+
"""Parse one line from trace_pipe into fields."""
19+
with open("/sys/kernel/tracing/trace_pipe", "rb", buffering=0) as f:
20+
while True:
21+
line = f.readline().rstrip()
22+
23+
if not line or line.startswith(b"CPU:"):
24+
continue
25+
26+
match = TRACE_PATTERN.match(line)
27+
if not match:
28+
raise ValueError("Cannot parse trace line")
29+
30+
task, pid, cpu, flags, ts, msg = match.groups()
31+
return (task.strip(), int(pid), int(cpu), flags, float(ts), msg)

0 commit comments

Comments
 (0)