{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "b0d1ab05-0c1f-4578-9c1b-568202b95a5c", "metadata": {}, "outputs": [], "source": [ "from pythonbpf import bpf, map, struct, section, bpfglobal, BPF\n", "from pythonbpf.helper import ktime\n", "from pythonbpf.maps import HashMap, PerfEventArray\n", "from ctypes import c_void_p, c_int64" ] }, { "cell_type": "code", "execution_count": null, "id": "85e50d0a-f9d8-468f-8e03-f5f7128f05d8", "metadata": {}, "outputs": [], "source": [ "@bpf\n", "@struct\n", "class data_t:\n", " ts: c_int64\n", " ms: c_int64\n", "\n", "\n", "@bpf\n", "@map\n", "def events() -> PerfEventArray:\n", " return PerfEventArray(key_size=c_int64, value_size=c_int64)\n", "\n", "\n", "@bpf\n", "@map\n", "def last() -> HashMap:\n", " return HashMap(key=c_int64, value=c_int64, max_entries=1)\n", "\n", "\n", "@bpf\n", "@section(\"tracepoint/syscalls/sys_enter_sync\")\n", "def do_trace(ctx: c_void_p) -> c_int64:\n", " dat, dat.ts, key = data_t(), ktime(), 0\n", " tsp = last.lookup(key)\n", " if tsp:\n", " delta = ktime() - tsp\n", " if delta < 1000000000:\n", " dat.ms = delta // 1000000\n", " events.output(dat)\n", " last.delete(key)\n", " else:\n", " last.update(key, ktime())\n", " return 0\n", "\n", "\n", "@bpf\n", "@bpfglobal\n", "def LICENSE() -> str:\n", " return \"GPL\"\n", "\n", "\n", "# Compile and load\n", "b = BPF()\n", "b.load()\n", "b.attach_all()" ] }, { "cell_type": "code", "execution_count": null, "id": "40bb1107-369f-4be7-9f10-37201900c16b", "metadata": {}, "outputs": [], "source": [ "print(\"Tracing for quick sync's... Ctrl-C to end\")\n", "\n", "# format output\n", "start = 0\n", "\n", "\n", "def callback(cpu, event):\n", " global start\n", " if start == 0:\n", " start = event.ts\n", " event.ts -= start\n", " print(\n", " f\"At time {event.ts / 1e9} s: Multiple sync detected, Last sync: {event.ms} ms ago\"\n", " )\n", "\n", "\n", "perf = b[\"events\"].open_perf_buffer(callback, struct_name=\"data_t\")\n", "print(\"Starting to poll... (Ctrl+C to stop)\")\n", "print(\"Try running: fork() or clone() system calls to trigger events\")\n", "\n", "try:\n", " while True:\n", " b[\"events\"].poll(1000)\n", "except KeyboardInterrupt:\n", " print(\"Stopping...\")" ] }, { "cell_type": "code", "execution_count": null, "id": "94a588d9-3a40-437c-a35b-fc40410f3eb7", "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.13.3" } }, "nbformat": 4, "nbformat_minor": 5 }