|
| 1 | +import time |
| 2 | + |
| 3 | +from pythonbpf import bpf, map, section, bpfglobal, BPF |
| 4 | +from pythonbpf.helpers import pid |
| 5 | +from pythonbpf.maps import HashMap |
| 6 | +from pylibbpf import * |
| 7 | +from ctypes import c_void_p, c_int64, c_uint64, c_int32 |
| 8 | +import matplotlib.pyplot as plt |
| 9 | + |
| 10 | +# This program attaches an eBPF tracepoint to sys_enter_clone, |
| 11 | +# counts per-PID clone syscalls, stores them in a hash map, |
| 12 | +# and then plots the distribution as a histogram using matplotlib. |
| 13 | +# It provides a quick view of process creation activity over 10 seconds. |
| 14 | +# Everything is done with Python only code and with the new pylibbpf library. |
| 15 | +# Run `sudo /path/to/python/binary/ pybpf4.py` |
| 16 | + |
| 17 | +@bpf |
| 18 | +@map |
| 19 | +def hist() -> HashMap: |
| 20 | + return HashMap(key=c_int32, value=c_uint64, max_entries=4096) |
| 21 | + |
| 22 | +@bpf |
| 23 | +@section("tracepoint/syscalls/sys_enter_clone") |
| 24 | +def hello(ctx: c_void_p) -> c_int64: |
| 25 | + process_id = pid() |
| 26 | + one = 1 |
| 27 | + prev = hist().lookup(process_id) |
| 28 | + if prev: |
| 29 | + previous_value = prev + 1 |
| 30 | + print(f"count: {previous_value} with {process_id}") |
| 31 | + hist().update(process_id, previous_value) |
| 32 | + return c_int64(0) |
| 33 | + else: |
| 34 | + hist().update(process_id, one) |
| 35 | + return c_int64(0) |
| 36 | + |
| 37 | + |
| 38 | +@bpf |
| 39 | +@bpfglobal |
| 40 | +def LICENSE() -> str: |
| 41 | + return "GPL" |
| 42 | + |
| 43 | + |
| 44 | +b = BPF() |
| 45 | +b.load_and_attach() |
| 46 | +hist = BpfMap(b, hist) |
| 47 | +print("Recording") |
| 48 | +time.sleep(10) |
| 49 | + |
| 50 | +counts = list(hist.values()) |
| 51 | + |
| 52 | +plt.hist(counts, bins=20) |
| 53 | +plt.xlabel("Clone calls per PID") |
| 54 | +plt.ylabel("Frequency") |
| 55 | +plt.title("Syscall clone counts") |
| 56 | +plt.show() |
0 commit comments