A Python client for Tetragon
tetragon-client gives Python programs direct access to Tetragon's events: a live stream over its gRPC API, or the JSON export file it writes to disk, read with rotation handling and resumable checkpoints.
About Tetragon
Tetragon is an eBPF-based security observability and runtime enforcement tool, developed as part of the Cilium project. It runs on each host and observes activity inside the kernel: process executions and exits, and whatever kernel functions, system calls or tracepoints its tracing policies tell it to watch, such as file access, network connections or credential changes. Because the filtering happens in the kernel, it can watch busy code paths at low cost, and a policy can also act on a match, for example by killing the offending process.
Tetragon publishes what it sees in two ways: a gRPC API, which the tetra command-line tool uses, and a JSON file with one event per line, which it rotates as it grows and can compress. Tetragon's own documentation
is thorough, and the place to start for installing it and writing policies.
Tetragon vs auditd and OSSEC
On Linux hosts, the audit framework (auditd) and OSSEC are long-established ways to record and detect security-relevant activity. I use both, and have written about shipping OSSEC alerts to Loki . Tetragon overlaps with them in places and works at a different layer, so the three sit well together.
auditd is the userspace half of the kernel's audit subsystem. Rules loaded with auditctl select system calls and watched paths, the kernel evaluates them, and auditd writes the matching records to /var/log/audit/audit.log as key-value text. One event often spans several records (SYSCALL, EXECVE, PATH, CWD and others), linked by a shared serial number. Every major distribution packages it, many compliance benchmarks are written as audit rules, and immutable mode (-e 2) locks the rules until the next reboot. It is an observing tool: it records events and leaves any response to other software.
OSSEC is a host-based intrusion detection system (HIDS). It reads logs, including audit.log and syslog, and matches them against its decoders and rules. It also checks file integrity, on a schedule or as files change, looks for rootkits, and can run active responses such as blocking an address at the firewall. In a distributed setup, agents send events to a manager, which raises the alerts. Its view of process activity comes from what the host's logs record.
Tetragon works inside the kernel through eBPF. It reports every process execution and exit with the full command line, the parent process and the container it ran in, and gives each execution an ID that links later events back to the process that caused them. Tracing policies attach to kernel functions, tracepoints and LSM hooks, read arguments such as the path behind a struct file or the addresses on a socket, and filter on them in the kernel. A policy can also act at the moment of the call, for example by killing the process before the operation completes.
| auditd | OSSEC | Tetragon | |
|---|---|---|---|
| Events from | the kernel audit subsystem: system calls and watched paths | logs, file integrity checks, rootkit checks | eBPF: process lifecycle, kernel functions, tracepoints, LSM hooks |
| Context per event | user, process and arguments, across several linked records | what the source log contains | process, parent, execution ID, container or pod |
| Response | records only | active response scripts after an alert | in-kernel actions such as killing the process |
| Output | text records in audit.log |
alerts, including as JSON | JSON lines, and a gRPC stream |
| Needs | a distribution kernel | an agent on each host, optionally a manager | a recent kernel with BTF |
They combine well. auditd provides the audit trail many compliance frameworks ask for, OSSEC correlates logs and watches file integrity across hosts, and Tetragon adds process-level detail from inside the kernel, with the option to enforce. I kind of think of Tetragon's enforcement policies as OSSEC's active response on steroids, though - it feels a lot stronger and more of an interception than a reaction.
Why Python?
I wanted to consume Tetragon's events from Python: in small scripts on a host, and in longer-running services that collect events for later review (if you've been reading my blog lately, you'll know this means Keen!
). I didn't want to have to subproess out to Tetragon's own tetra CLI tool.
tetragon-client for Python provides:
- gRPC clients, blocking and asyncio, covering every method of Tetragon's API: event streams with server-side filters, tracing policy management, health, log levels, and the export file's rotation settings.
- An export file reader that follows Tetragon's log rotation, reads gzipped rotated files, and resumes from a checkpoint after a restart.
- One event type for both. Each source yields Tetragon's own
GetEventsResponseprotobuf messages, or plain dictionaries in the same shape astetra getevents -o json. - A small command,
tetragon-events, that prints events as JSON lines for use withjqand similar tools.
Installing
It is on PyPI :
pip install tetragon-client
There are also packages for Debian 12 and 13, Ubuntu 24.04 and 26.04, and Fedora 43 and 44, named python3-tetragon-client, in my apt and rpm repositories. For Debian and Ubuntu:
sudo mkdir -p /usr/share/keyrings
curl -fsSL https://mig5.net/static/mig5.asc | sudo gpg --dearmor -o /usr/share/keyrings/mig5.gpg
echo "deb [arch=amd64 signed-by=/usr/share/keyrings/mig5.gpg] https://apt.mig5.net $(lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/mig5.list
sudo apt update
sudo apt install python3-tetragon-client
For Fedora:
sudo rpm --import https://mig5.net/static/mig5.asc
sudo tee /etc/yum.repos.d/mig5.repo > /dev/null << 'EOF'
[mig5]
name=mig5 Repository
baseurl=https://rpm.mig5.net/$releasever/rpm/$basearch
enabled=1
gpgcheck=1
repo_gpgcheck=1
gpgkey=https://mig5.net/static/mig5.asc
EOF
sudo dnf install python3-tetragon-client
The distribution packages use the distribution's own python3-grpcio and python3-protobuf.
Reaching Tetragon
The client connects to Tetragon's Unix socket at /var/run/tetragon/tetragon.sock by default. If Tetragon runs in Docker, mount that directory (and, for the export file, its log directory) from the host:
docker run --name tetragon --rm --pid=host --cgroupns=host --privileged \
-v /sys/kernel/btf/vmlinux:/var/lib/tetragon/btf \
-v /var/run/tetragon:/var/run/tetragon \
-v /var/log/tetragon:/var/log/tetragon \
quay.io/cilium/tetragon:v1.8.0 \
--export-filename /var/log/tetragon/tetragon.log
Both are readable by root only, and that is worth keeping: anything that can connect to the socket can also change or remove Tetragon's policies, and the export file records every command line Tetragon sees.
Streaming events
The simplest use is a live stream:
from tetragon_client import TetragonClient, event_filter
with TetragonClient() as client:
print("Connected to Tetragon", client.version())
allow = [event_filter(kinds=["process_exec"])]
for event in client.events(allow=allow):
proc = event.process_exec.process
print(proc.pid.value, proc.binary, proc.arguments)
Each event has exactly one event field set (process_exec, process_exit, process_kprobe and so on), and the fields are typed, so an editor can complete them. If dictionaries are more convenient, event_to_dict() gives the same structure as Tetragon's JSON. This prints every match of a tracing policy, with the action the policy took:
from tetragon_client import TetragonClient, event_filter, event_to_dict
with TetragonClient() as client:
allow = [event_filter(kinds=["process_kprobe"])]
for event in client.events(allow=allow):
hit = event_to_dict(event)["process_kprobe"]
print(hit.get("policy_name"), hit["function_name"], hit.get("action"))
event_filter() also matches binaries by regular expression and events by policy name. Fields within one filter must all match, and a list of filters matches if any one of them does.
The stream reconnects with exponential backoff when Tetragon restarts. Events that occur while it is disconnected are lost, which is the nature of a live stream; the export file covers that case.
The same methods exist on AsyncTetragonClient for asyncio programs:
import asyncio
from tetragon_client import AsyncTetragonClient, event_filter
async def main():
async with AsyncTetragonClient() as client:
allow = [event_filter(kinds=["process_exec"], binary_regex=["^/usr/bin/(curl|wget)$"])]
async for event in client.events(allow=allow):
print("fetch:", event.process_exec.process.arguments)
asyncio.run(main())
Reading the export file
With --export-filename, Tetragon appends each event to a file as a line of JSON. When the file reaches its size limit, Tetragon renames it with a timestamp, compresses it if asked to, and starts a new one. ExportFileReader reads across those rotations.
For a one-off report, read everything on disk and stop at the end:
from collections import Counter
from tetragon_client import ExportFileReader, event_kind
reader = ExportFileReader("/var/log/tetragon/tetragon.log", start_at="beginning", follow=False)
with reader:
counts = Counter(event_kind(e) for e in reader)
print(counts.most_common())
For a service that collects events, give the reader a checkpoint. It follows the file as it grows, and records its position as it goes. After a restart it carries on where it stopped, first reading any files that were rotated, and perhaps compressed, in the meantime:
import signal
from tetragon_client import ExportFileReader, FileCheckpoint
reader = ExportFileReader(
"/var/log/tetragon/tetragon.log",
FileCheckpoint("/var/lib/my-collector/tetragon.pos"),
)
signal.signal(signal.SIGTERM, lambda *_: reader.stop())
with reader:
for record in reader.dicts():
store(record) # write to your database, queue or API here
dicts() yields each event as the JSON object Tetragon wrote, which also keeps any fields from a newer Tetragon. Iterating the reader itself yields protobuf messages, as the gRPC client does.
Delivery is at-least-once. An event counts as handled once the loop asks for the next one, and the position is saved every hundred events or five seconds, whenever the reader is idle, and on shutdown. After a crash, the events since the last save are delivered again. If that matters, store the position in your own database in the same transaction as the events: ExportFileReader accepts any object with load() and save() methods, and the repository has an example that does this with SQLite.
A line that is not valid JSON is logged and skipped, so one damaged record never stops the reader.
Managing policies and the rest of the API
Every gRPC method has a matching call, so scripts can inspect and adjust Tetragon while it runs. For example, switching a policy to monitor mode stops its enforcement actions while keeping its events, which helps while tuning it:
from tetragon_client import TetragonClient
with TetragonClient() as client:
for policy in client.list_tracing_policies():
print(policy.name, policy.enabled, policy.error or "-")
client.configure_tracing_policy("file-monitoring-filtered", mode="monitor")
add_tracing_policy() loads a policy from its YAML, which makes it straightforward to check that a new policy is accepted by a running Tetragon and attaches to that host's kernel before putting it into the policy directory.
From the shell
tetragon-events prints events as JSON lines:
# Every program started, live
tetragon-events grpc --kind process_exec | jq -r '.process_exec.process.binary'
# Policy matches from the export file, including rotated files
tetragon-events file /var/log/tetragon/tetragon.log --from-beginning --no-follow \
--kind process_kprobe | jq -r '.process_kprobe.policy_name' | sort | uniq -c
With --checkpoint FILE, the file mode resumes where the previous run stopped.
Keeping in step with upstream
The Python code for Tetragon's messages is generated from the API definitions of a Tetragon release, currently v1.8.0. The update script fetches them only from a release tag whose SSH signature verifies against a pinned Tetragon maintainer's signing key, checks that the tag points at the expected commit, and records SHA-256 checksums of the files, which every build verifies.
Protobuf's compatibility rules mean the client works (kind of) with newer Tetragon versions too: fields it does not know are ignored, and new kinds of event arrive with event_kind() returning None.
The wheel on PyPI needs grpcio 1.71.2 or later and protobuf 5.29 or later. Debian, Ubuntu and Fedora ship older protobuf releases, so their packages regenerate that code at build time with the distribution's own compiler, and each package build runs the test suite against the distribution's libraries.
The source, documentation and examples are on my Forgejo. Let me know if you try it out!
- Sources: Tetragon's gRPC API, and its JSON export files
- Python: 3.11 to 3.14
- Packages: PyPI; Debian 12 and 13, Ubuntu 24.04 and 26.04, Fedora 43 and 44