From 263402d137ee061e9583b0569eb7f6c46bc92abc Mon Sep 17 00:00:00 2001 From: Pragyansh Chaturvedi Date: Tue, 14 Oct 2025 04:22:17 +0530 Subject: [PATCH] Add trace_fields --- pythonbpf/__init__.py | 3 ++- pythonbpf/utils.py | 22 ++++++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/pythonbpf/__init__.py b/pythonbpf/__init__.py index 3eda126..5f96339 100644 --- a/pythonbpf/__init__.py +++ b/pythonbpf/__init__.py @@ -1,6 +1,6 @@ from .decorators import bpf, map, section, bpfglobal, struct from .codegen import compile_to_ir, compile, BPF -from .utils import trace_pipe +from .utils import trace_pipe, trace_fields __all__ = [ "bpf", @@ -12,4 +12,5 @@ __all__ = [ "compile", "BPF", "trace_pipe", + "trace_fields", ] diff --git a/pythonbpf/utils.py b/pythonbpf/utils.py index 8664d80..8dbc5e5 100644 --- a/pythonbpf/utils.py +++ b/pythonbpf/utils.py @@ -1,4 +1,9 @@ import subprocess +import re + +TRACE_PATTERN = re.compile( + rb"^(.{1,16}?)-(\d+)\s+\[(\d+)\]\s+([a-zA-Z.]+)\s+([0-9.]+):\s+.*?:\s+(.*)$" +) def trace_pipe(): @@ -7,3 +12,20 @@ def trace_pipe(): subprocess.run(["cat", "/sys/kernel/tracing/trace_pipe"]) except KeyboardInterrupt: print("Tracing stopped.") + + +def trace_fields(): + """Parse one line from trace_pipe into fields.""" + with open("/sys/kernel/tracing/trace_pipe", "rb", buffering=0) as f: + while True: + line = f.readline().rstrip() + + if not line or line.startswith(b"CPU:"): + continue + + match = TRACE_PATTERN.match(line) + if not match: + raise ValueError("Cannot parse trace line") + + task, pid, cpu, flags, ts, msg = match.groups() + return (task.strip(), int(pid), int(cpu), flags, float(ts), msg)