Day 13: Tracing with ftrace and perf
Goal: make individual events in the kernel and in programs visible – process starts, function calls, system calls –, count them instead of only logging them, and know how much each tool slows down the measured system · Duration: about 3 hours · Prerequisite: Day 0–12
Where we start
The tracing tools from Day 0 are installed on perf1, nginx from Day 12 is running.
# on perf1
command -v trace-cmd strace perf funccount-bpfcccommand -vprints for each name the path under which the shell finds the program.
Expected:
/usr/bin/trace-cmd
/usr/bin/strace
/usr/bin/perf
/usr/sbin/funccount-bpfcc
If a line is missing, install the package as on Day 0.
# on perf1
systemctl is-active nginxExpected:
active
Introduction
So far you have mostly worked with counters
(vmstat, iostat, sar) and, on Day
5, with profiling (perf record). Both tell
you how much happens. Sometimes, though, you need the
individual events: Which process keeps starting? Which
file does a service open? How often does it make a particular
system call? That is what tracing is for.
Tracing has a price. It records every event of a kind, and the effort grows with the number of events. A badly chosen tool can slow a service down a hundredfold – exactly when it already has problems. That is why today you measure not only with tracers but also the tracer itself.
Today you learn:
- what tracepoints, kprobes and uprobes are and how they differ,
- to record tracepoints with
trace-cmdand see the call tree of a kernel function, - to count function calls in the kernel with
funccount, - to count system calls with
strace,perf traceandperf stat– and to measure the cost of the three, - to set your own probe points in the kernel and in libraries with
perf probe, - to find a service that makes a system call far too often.
Background
The picture for today: traffic monitoring
Think of the kernel as a road network; the events are cars.
- Tracepoints are permanently installed counting stations at well-known junctions. They have been there for years, always have the same name and always deliver the same data.
- kprobes are mobile measuring devices you can put on (almost) any road. But roads are rebuilt, renamed or disappear – after a kernel update your device may be standing in the middle of nowhere.
- uprobes are the same on private property: in programs and libraries.
And how you measure decides about the traffic jam:
- Counting (
funccount,perf stat) is an induction loop in the asphalt: every car increments a number, nobody brakes. - Summarizing (
perf trace) is a camera that photographs every car. If the cars come faster than the pictures are collected, the memory fills up and pictures are missing. straceis the police checkpoint: every car is stopped, the papers are read, then it may go on. You see everything – and there is a jam.
The terms
| Term | Meaning | in the picture |
|---|---|---|
| tracepoint | fixed, named, stable probe point in the kernel, for example
sched:sched_process_exec |
permanently installed counting station |
| kprobe | probe point on any kernel function, not stable | mobile measuring device |
| uprobe | probe point on a function in a program or library | measuring device on private property |
ftrace / trace-cmd |
the tracer in the kernel and its user interface | control center |
| counting in the kernel | only increment a number, read it out once at the end | induction loop |
| reporting events to user space | hand over each event individually | camera |
ptrace |
stop the program at every system call | police checkpoint |
Remember: If there is a tracepoint, use it. And: counting is cheap, reporting individually is expensive, stopping is very expensive.
Where the events come from
- Tracepoints are fixed, named probe points that
kernel developers built into the source code, for example
sched:sched_process_exec(a process starts a program) orsyscalls:sys_enter_openat(a program callsopenat). Name and fields stay the same across kernel versions. - kprobes attach to (almost) any function in
the kernel. But functions get renamed, embedded
(inlined) or dropped. You experienced that on Day 9 when
biosnoopfound nothing on kernel 6.8. - uprobes attach to functions in user
space, for example to
getaddrinfoin the C library, which resolves host names to addresses.
The tools
- ftrace is the tracer built into the kernel. It is
controlled through files in
/sys/kernel/tracing.trace-cmdis its user interface: it switches events on, collects the data into a file (trace.dat) and shows it. perfyou know from Day 5. Besidesperf recordit can count events (perf stat), trace system calls (perf trace) and create new probe points (perf probe).funccountfrom the bcc tools counts function calls directly in the kernel with eBPF. How eBPF works is the topic of Day 14; today you only use the finished tool.straceusesptrace: at every system call the kernel stops the program, wakesstrace, waits until it has read the data and lets the program continue – twice per call, on entry and on exit.
Drill 1: Who is starting processes here?
Where you are: in two terminals on perf1.
What you have afterwards: a list of all programs that were started on perf1 during 15 seconds, recorded via a tracepoint.
Short-lived processes are a typical cause of load you do not see in
top: they only run for milliseconds and are gone before
top looks again. A tracepoint sees every single one.
Step 1 – The directory for today.
# on perf1
mkdir -p ~/tag13# on perf1
cd ~/tag13Step 2 – How many counting stations are there?
trace-cmd list -e lists all events ftrace knows. There are
so many that you only count them here – wc -l counts the
lines:
# on perf1
sudo trace-cmd list -e | wc -lExpected (the number depends on the kernel, about 1,850 on 6.8):
1852
Step 3 – The scheduler’s counting stations. The
pattern after -e is a regular expression;
sched: shows only the group sched:
# on perf1
sudo trace-cmd list -e sched:Expected (excerpt – the lines with
process; the order may differ):
sched:sched_process_hang
sched:sched_process_exec
sched:sched_process_fork
sched:sched_process_wait
sched:sched_process_exit
sched:sched_process_free
sched_process_exec fires when a process loads a new
program (the system call execve), that is, at every program
start.
Step 4 – Record. Start the recording for 15 seconds in terminal 1:
# on perf1, terminal 1
sudo trace-cmd record -e sched:sched_process_exec sleep 15recordswitches the events on and writes everything into the filetrace.datin the current directory.-e sched:sched_process_execselects the tracepoint. You can give-eseveral times.sleep 15is the command; recording lasts as long as it runs. Without a command,trace-cmd recordruns until Ctrl+C.
Step 5 – Let something happen. During these 15 seconds, log in to perf1 again via SSH in terminal 2:
# on your computer, terminal 2
ssh perf1Then two commands:
# on perf1, terminal 2
ls / > /dev/null# on perf1, terminal 2
dateStep 6 – Evaluate. When trace-cmd in
terminal 1 is done:
# on perf1, terminal 1
sudo trace-cmd reporttrace-cmd report reads trace.dat and prints
each event as a line.
Expected (shortened – you will see other PIDs and times):
cpus=4
sleep-13136 [003] 22219.171723: sched_process_exec: filename=/usr/bin/sleep pid=13136 old_pid=13136
sshd-13137 [003] 22224.045611: sched_process_exec: filename=/usr/sbin/sshd pid=13137 old_pid=13137
sh-13139 [003] 22224.320522: sched_process_exec: filename=/bin/sh pid=13139 old_pid=13139
run-parts-13140 [002] 22224.328783: sched_process_exec: filename=/usr/bin/run-parts pid=13140 old_pid=13140
00-header-13141 [001] 22224.332776: sched_process_exec: filename=/etc/update-motd.d/00-header pid=13141 old_pid=13141
uname-13142 [000] 22224.336329: sched_process_exec: filename=/usr/bin/uname pid=13142 old_pid=13142
50-landscape-sy-13146 [000] 22224.372580: sched_process_exec: filename=/etc/update-motd.d/50-landscape-sysinfo pid=13146 old_pid=13146
90-updates-avai-13156 [001] 22224.409429: sched_process_exec: filename=/etc/update-motd.d/90-updates-available pid=13156 old_pid=13156
date-13186 [003] 22224.663566: sched_process_exec: filename=/bin/bash pid=13186 old_pid=13186
ls-13187 [000] 22224.670877: sched_process_exec: filename=/usr/bin/ls pid=13187 old_pid=13187
date-13186 [003] 22224.675611: sched_process_exec: filename=/usr/bin/date pid=13186 old_pid=13186
How to read a line:
| Column | Example | Meaning |
|---|---|---|
| name-PID | ls-13187 |
process name and process ID |
[000] |
CPU | on which CPU the event occurred |
| timestamp | 22224.670877 |
seconds since the machine booted |
| event | sched_process_exec: |
the tracepoint |
| fields | filename=/usr/bin/ls |
the data the tracepoint delivers |
The real surprise is between sshd and your
ls: the SSH login alone started about 50
programs on perf1. Those are the scripts in
/etc/update-motd.d/ that Ubuntu runs at every login to
build the welcome message. You would have seen nothing of this in
top.
Remember:
topdoes not see short-lived processes; the tracepointsched:sched_process_execsees every one.
If it doesn’t work:
trace.datis empty or only containssleep: You logged in after the 15 seconds had passed. Restart Step 4 and log in immediately.trace-cmd: Permission denied: You forgotsudo– ftrace needs root privileges.
Save your progress? Sign up for free
Drill 2: A system call from the inside
Where you are: on perf1, in the directory
~/tag13.What you have afterwards: the call tree of the kernel function behind
openatwith the time of each step, and an explanation of whycatwants to open 31 files for one file.
ftrace’s function_graph tracer records which kernel
function calls which other one and how long each takes. You look at what
happens in the kernel when cat opens a file.
Step 1 – Record.
# on perf1
sudo trace-cmd record -p function_graph -g do_sys_openat2 --max-graph-depth 2 -o graph.dat -F cat /etc/hostname| Option | Meaning |
|---|---|
-p function_graph |
select the tracer (plugin) function_graph |
-g do_sys_openat2 |
only this function and everything it calls; it is behind
open and openat |
--max-graph-depth 2 |
only two levels deep – without a limit there are thousands of lines |
-o graph.dat |
write into this file instead of trace.dat |
-F |
only record the following command, not the whole system |
cat /etc/hostname |
the command |
Step 2 – Look at it.
# on perf1
sudo trace-cmd report -i graph.dat-i graph.datreads this file.
Expected (excerpt – two of the blocks; the times vary):
cat-11260 [002] 21400.812581: funcgraph_entry: | do_sys_openat2() {
cat-11260 [002] 21400.812583: funcgraph_entry: 4.409 us | getname();
cat-11260 [002] 21400.812588: funcgraph_entry: 2.245 us | get_unused_fd_flags();
cat-11260 [002] 21400.812590: funcgraph_entry: + 36.678 us | do_filp_open();
cat-11260 [002] 21400.812628: funcgraph_entry: 0.540 us | fd_install();
cat-11260 [002] 21400.812629: funcgraph_entry: 0.897 us | putname();
cat-11260 [002] 21400.812630: funcgraph_exit: + 51.030 us | }
cat-11260 [002] 21400.816449: funcgraph_entry: | do_sys_openat2() {
cat-11260 [002] 21400.816450: funcgraph_entry: 6.741 us | getname();
cat-11260 [002] 21400.816458: funcgraph_entry: 2.583 us | get_unused_fd_flags();
cat-11260 [002] 21400.816461: funcgraph_entry: + 32.218 us | do_filp_open();
cat-11260 [002] 21400.816494: funcgraph_entry: 1.909 us | put_unused_fd();
cat-11260 [002] 21400.816497: funcgraph_entry: 1.442 us | putname();
cat-11260 [002] 21400.816499: funcgraph_exit: + 50.605 us | }
How to read the tree:
- The indentation shows who calls whom:
do_sys_openat2callsgetname(copy the file name from the program),get_unused_fd_flags(find a free file descriptor),do_filp_open(resolve the path and open the file) andfd_install(attach the file descriptor to the opened file). - For functions without children the time is directly in the line, for
the others in the line with
}. +means: longer than 10 µs,!longer than 100 µs. That way the expensive calls stand out when you scroll.- In the second block there is
put_unused_fdinstead offd_install: the reserved file descriptor was released again, the open failed.
Step 3 – Count. grep -c counts the
matching lines instead of showing them. First the calls:
# on perf1
sudo trace-cmd report -i graph.dat | grep -c "do_sys_openat2() {"Expected:
31
Then the failed ones:
# on perf1
sudo trace-cmd report -i graph.dat | grep -c put_unused_fdExpected:
12
A cat for a single file calls openat 31
times, 12 of them fail.
Step 4 – Which files? function_graph
does not tell you – strace is more convenient for that:
# on perf1
strace -e trace=openat cat /etc/hostnamestracestartscatand prints every system call,-e trace=openatonlyopenat.
Expected (excerpt):
openat(AT_FDCWD, "/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3
openat(AT_FDCWD, "/lib/x86_64-linux-gnu/libc.so.6", O_RDONLY|O_CLOEXEC) = 3
openat(AT_FDCWD, "/usr/lib/locale/locale-archive", O_RDONLY|O_CLOEXEC) = 3
openat(AT_FDCWD, "/usr/share/locale/locale.alias", O_RDONLY|O_CLOEXEC) = 3
openat(AT_FDCWD, "/usr/lib/locale/C.UTF-8/LC_IDENTIFICATION", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)
openat(AT_FDCWD, "/usr/lib/locale/C.utf8/LC_IDENTIFICATION", O_RDONLY|O_CLOEXEC) = 3
The failed calls are the language and regional settings
(locale): the C library looks for each file first under
C.UTF-8, does not find it there (ENOENT) and
then takes C.utf8. That is harmless – but exactly this
pattern (“looks in the wrong place first”) costs noticeable time in
larger programs.
Remember:
function_graphshows how the kernel does something and how long each step takes;straceshows with what (the arguments).put_unused_fdinstead offd_installmeans: open failed.
If it doesn’t work:
trace-cmd reportshows thousands of lines:--max-graph-depth 2is missing.- After aborting with Ctrl+C the tracer keeps running
(
sudo cat /sys/kernel/tracing/current_tracerdoes not shownop):sudo trace-cmd resetswitches ftrace off again.
Save your progress? Sign up for free
Drill 3: Counting function calls instead of logging them
Where you are: in two terminals on perf1.
What you have afterwards: counted how often the kernel calls its read and write functions while
ddcopies 200,000 blocks – without recording every event individually.
Often you do not want to see every event, only know how
often it happens. Then counting in the kernel – the induction
loop – is much cheaper than recording. funccount does
exactly that.
Step 1 – Count. Start in terminal 1:
# on perf1, terminal 1
sudo funccount-bpfcc -d 15 'vfs_*'funccount-bpfccisfunccountfrom the bcc tools (on Ubuntu with the suffix-bpfcc).-d 15counts for 15 seconds and then prints the result.'vfs_*'counts all kernel functions whose name starts withvfs_– the layer that all file systems share (Virtual File System). The quotes prevent the shell from expanding the asterisk itself.
Wait until Tracing 78 functions … appears. That takes a
few seconds because funccount first compiles a program for
the kernel.
Step 2 – Load. Then in terminal 2:
# on perf1, terminal 2
dd if=/dev/zero of=/tmp/null.test bs=4k count=200000 status=noneddreads 4 KiB from/dev/zero200,000 times and writes it into a file;status=noneswitches offdd’s statistics.
# on perf1, terminal 2
rm /tmp/null.testExpected in terminal 1 (excerpt, the small numbers vary):
Tracing 78 functions for "b'vfs_*'"... Hit Ctrl-C to end.
FUNC COUNT
vfs_fstat 56
vfs_statx 115
vfs_open 181
vfs_write 200354
vfs_read 200377
Detaching...
200,000 calls each of vfs_read and
vfs_write – one call per block, as expected. The rest comes
from other processes. For this funccount only incremented
one counter each in the kernel and read them out once at the end.
Remember: If you only want to know “how often”, count in the kernel (
funccount). It is exact and does not slow anything down.
If it doesn’t work:
- The numbers are much smaller than 200,000:
ddwas already running beforefunccountwas ready. Wait for the lineTracing …first. could not determine address of symbol: The function name does not exist in your kernel (see kprobes in the background).sudo grep -c "^vfs_" /sys/kernel/tracing/available_filter_functionsshows how many there are.
Save your progress? Sign up for free
Drill 4: Counting system calls – and what it costs
Where you are: on perf1, in the directory
~/tag13.What you have afterwards: the same work measured four times – without a tracer, with
strace, withperf traceand withperf stat– and a number for how much each tracer slows things down.
The victim is a dd that copies a single byte from
/dev/zero to /dev/null 100,000 times. That is
200,000 system calls, but no disk and hardly any computation – an
extreme case in which the tracers’ cost becomes obvious.
Step 1 – Without a tracer.
# on perf1
/usr/bin/time -f "%e s" dd if=/dev/zero of=/dev/null bs=1 count=100000 status=none/usr/bin/timemeasures how long the command after it runs. The full path is needed because the shell has its owntimewithout a format option.-f "%e s"only prints the elapsed time in seconds.bs=1 count=100000: 100,000 blocks of 1 byte, so 100,000 each ofreadandwrite.
Run the command three times. Expected: around
0.26 s (for us 0.24, 0.28, 0.26).
Step 2 – With strace (the police checkpoint):
# on perf1
/usr/bin/time -f "%e s" strace -c -o strace.txt dd if=/dev/zero of=/dev/null bs=1 count=100000 status=none-ccounts the calls and prints a table at the end instead of showing every call individually.-o strace.txtwrites this table into a file.
Expected:
49.09 s
The table itself:
# on perf1
head -5 strace.txthead -5shows the first five lines of a file.
Expected:
% time seconds usecs/call calls errors syscall
------ ----------- ----------- --------- --------- ----------------
50.97 3.209871 32 100003 read
48.95 3.083087 30 100000 write
0.02 0.001527 47 32 12 openat
The table is correct – 100,000 read, 100,000
write, and again the 32 openat with 12 errors
from Drill 2. But dd needed 49 seconds instead of
0.26: almost 200 times as long. Even with -c,
strace stops the program twice at every call.
Step 3 – With perf trace (the camera):
# on perf1
/usr/bin/time -f "%e s" sudo perf trace -s -o perftrace.txt dd if=/dev/zero of=/dev/null bs=1 count=100000 status=noneperf tracefollows system calls via the kernel’s tracepoints instead of viaptrace.-sprints a summary per system call at the end,-owrites into a file.
Expected:
2.40 s
# on perf1
head -10 perftrace.txtExpected:
Summary of events:
dd (11677), 398874 events, 100.0%
syscall calls errors total min avg max stddev
(msec) (msec) (msec) (msec) (%)
--------------- -------- ------ -------- --------- --------- --------- ------
write 99596 0 365.586 0.002 0.004 0.337 0.31%
read 99522 0 344.601 0.002 0.003 0.390 0.37%
2.4 seconds: about nine times – much better than strace,
but not free. And events are missing: 99,596 instead of 100,000
write. If the events come faster than perf
collects them, the buffer overflows and perf trace drops
some. For an overview that is enough, for exact counting it is not.
Step 4 – Only counting with perf stat (the induction loop):
# on perf1
sudo perf stat -e raw_syscalls:sys_enter dd if=/dev/zero of=/dev/null bs=1 count=100000 status=noneperf statcounts events without printing them individually.-e raw_syscalls:sys_enteris the tracepoint that fires on entry to every system call.
Expected (excerpt):
Performance counter stats for 'dd if=/dev/zero of=/dev/null bs=1 count=100000 status=none':
200122 raw_syscalls:sys_enter
0.318345209 seconds time elapsed
200,122 system calls, counted exactly, in 0.32 instead of 0.26 seconds.
The four measurements side by side:
| Tool | Run time | Factor | What you get |
|---|---|---|---|
| none | 0.26 s | 1 | – |
perf stat -e raw_syscalls:sys_enter |
0.32 s | ~1.2 | total count, exact |
perf trace -s |
2.40 s | ~9 | count and time per system call, can lose events |
strace -c |
49.09 s | ~190 | count and time per system call, exact |
The factors apply to this extreme case with one system call per
microsecond. A program that makes hardly any system calls is hardly
slowed down even by strace. But the order always stays the
same.
Remember: First count (
perf stat), then summarize (perf trace -s),straceonly briefly and targeted – induction loop, camera, police checkpoint.
If it doesn’t work:
perf tracereportsNo permissionsorError: No permissions to read …/tracing/events: start it withsudo.straceruns and runs: That is not an error – it really takes almost a minute.
Save your progress? Sign up for free
Drill 5: Your own probe points with perf probe
Where you are: on perf1.
What you have afterwards: one probe point each in the C library (uprobe) and in the kernel (kprobe), and counted how often
curlresolves a name and establishes a TCP connection.
For kernel functions without a tracepoint and for functions in programs, you set up a mobile measuring device yourself.
Step 1 – Find the C library.
# on perf1
ldd /usr/bin/curllddlists the libraries a program loads.
Expected (excerpt – look for the line with
libc.so):
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x000077901a400000)
On an arm64 machine it says
/lib/aarch64-linux-gnu/libc.so.6. Use the path you see in
the next commands.
Step 2 – A uprobe on getaddrinfo.
# on perf1
sudo perf probe -x /lib/x86_64-linux-gnu/libc.so.6 getaddrinfoperf probe -x DATEI FUNKTIONcreates a uprobe on the function in this program or library.getaddrinforesolves a host name to addresses.
Expected:
Added new event:
probe_libc:getaddrinfo (on getaddrinfo in /usr/lib/x86_64-linux-gnu/libc.so.6)
You can now use it in all perf tools, such as:
perf record -e probe_libc:getaddrinfo -aR sleep 1
Step 3 – Two kprobes.
perf probe -a FUNKTION (add) creates a
kprobe on a kernel function.
tcp_v4_connect and tcp_v6_connect run when a
program establishes a TCP connection over IPv4 or IPv6.
# on perf1
sudo perf probe -a tcp_v4_connectExpected:
Added new event:
probe:tcp_v4_connect (on tcp_v4_connect)
You can now use it in all perf tools, such as:
perf record -e probe:tcp_v4_connect -aR sleep 1
# on perf1
sudo perf probe -a tcp_v6_connectExpected:
Added new event:
probe:tcp_v6_connect (on tcp_v6_connect)
You can now use it in all perf tools, such as:
perf record -e probe:tcp_v6_connect -aR sleep 1
The new events are called probe:tcp_v4_connect and
probe:tcp_v6_connect.
Step 4 – Count via the name perf1. Call
the nginx from Day 12:
# on perf1
sudo perf stat -e probe_libc:getaddrinfo -e probe:tcp_v4_connect -e probe:tcp_v6_connect -- curl -s -o /dev/null http://perf1/--separatesperf’s options from the command being measured.curl -s -o /dev/null URLfetches the page without printing anything.
Expected (excerpt, the time varies):
Performance counter stats for 'curl -s -o /dev/null http://perf1/':
1 probe_libc:getaddrinfo
1 probe:tcp_v4_connect
0 probe:tcp_v6_connect
0.034953648 seconds time elapsed
Step 5 – Count via localhost.
# on perf1
sudo perf stat -e probe_libc:getaddrinfo -e probe:tcp_v4_connect -e probe:tcp_v6_connect -- curl -s -o /dev/null http://localhost/Expected (excerpt):
Performance counter stats for 'curl -s -o /dev/null http://localhost/':
0 probe_libc:getaddrinfo
0 probe:tcp_v4_connect
1 probe:tcp_v6_connect
0.033477542 seconds time elapsed
For perf1, curl resolves the name via the C
library (the entry from /etc/hosts, Day 0) and connects
over IPv4. For localhost, curl does
not call getaddrinfo at
all – it knows the name itself – and connects over
IPv6 (::1). You find such details in no
documentation, but in two probe points.
Step 6 – Remove the probe points.
# on perf1
sudo perf probe -d 'probe:*' -d 'probe_libc:*'-d MUSTER(delete) removes probe points; the quotes protect the asterisk from the shell.
# on perf1
sudo perf probe -l-llists the existing probe points.
Expected: no output.
Remember:
perf probe -xfor programs (uprobe),perf probe -afor the kernel (kprobe),perf statfor counting – and alwaysperf probe -dafterwards, otherwise the measuring device stays put.
If it doesn’t work:
Failed to find symbol getaddrinfo: wrong path to the C library – use the one from Step 1.Error: event "tcp_v4_connect" already exists: The probe point already exists (for example from an earlier attempt). Clean up with Step 6 and create it again.
Save your progress? Sign up for free
Diagnosis task
A colleague wrote a small service that applies a discount to orders. It manages “only” about 18,000 orders per second and keeps a CPU fully busy. “Python is just slow,” says the colleague.
Setup. Create the settings file:
# on perf1
cd ~/tag13# on perf1
nano dienst.json{"rabatt": 0.1, "waehrung": "EUR"}Then the service:
# on perf1
nano dienst.pyimport json, time
def einstellungen():
with open("/home/ubuntu/tag13/dienst.json") as f:
return json.load(f)
def bearbeite(auftrag):
e = einstellungen()
return round(auftrag * (1 - e["rabatt"]), 2)
fertig, start = 0, time.time()
while True:
bearbeite(fertig % 1000)
fertig += 1
if time.time() - start >= 5:
print(time.strftime("%H:%M:%S"), round(fertig / 5), "Auftraege/s", flush=True)
fertig, start = 0, time.time()(einstellungen means “settings”, bearbeite
“process”, rabatt “discount”, Auftraege/s
“orders per second”.) If your user is not called ubuntu,
adjust the path in line 4. The loop is the program itself – you do not
type it into the shell. Every five seconds the service prints how many
orders per second it managed. Start it in the background:
# on perf1
nohup python3 dienst.py > dienst.log 2>&1 &nohupkeeps the process running even if you log out.> dienst.log 2>&1writes output and error messages intodienst.log;&starts it in the background.
Task (20 minutes): Is it really “Python”? Find out
what the service spends its time on and speed it up – without letting
strace run for longer than one second.
Solution path
Step 1 – The rate.
# on perf1
tail -3 dienst.logtail -3shows the last three lines.
Expected:
19:05:59 18824 Auftraege/s
19:06:04 16244 Auftraege/s
19:06:09 19337 Auftraege/s
Step 2 – The PID.
# on perf1
pgrep -f "python3 [d]ienst.py"pgrep -f MUSTERsearches for the pattern in the whole command line. The square brackets are the trick from Day 11:[d]ienstmatches “dienst” but notpgrep’s own command line, which contains[d]ienst.
Expected: a number, in the lab 12089.
Use your PID in the following commands.
Step 3 – The CPU split.
# on perf1
pidstat -u -p 12089 1 3pidstat -u -p PID 1 3shows this process’s CPU usage, three times at one-second intervals.
Expected (excerpt – the line
Average):
Average: 1000 12089 76.74 23.26 0.00 0.00 100.00 - python3
The columns after the PID are %usr,
%system, %guest, %wait and
%CPU. The service spends 23 % of its time in the
kernel (%system). A program that only computes
would be close to 0 %. So the service makes many system calls.
Step 4 – Which system calls? Summarize cheaply with
perf trace, for five seconds:
# on perf1
sudo perf trace -s -p 12089 -o pt.txt -- sleep 5-p 12089attaches to the running process instead of starting a new one.-- sleep 5decides how long the recording lasts.
# on perf1
cat pt.txtExpected:
Summary of events:
python3 (12089), 799033 events, 100.0%
syscall calls errors total min avg max stddev
(msec) (msec) (msec) (msec) (%)
--------------- -------- ------ -------- --------- --------- --------- ------
openat 44325 0 476.712 0.005 0.011 0.366 0.27%
close 44350 0 338.302 0.002 0.008 0.359 0.36%
read 88746 0 291.051 0.001 0.003 0.378 0.36%
fstat 88829 0 270.318 0.002 0.003 0.362 0.29%
lseek 88857 0 233.419 0.001 0.003 0.076 0.24%
ioctl 44450 44450 109.215 0.002 0.002 0.332 0.39%
write 1 0 0.034 0.034 0.034 0.034 0.00%
For every openat there is one close, two
read, two fstat, two lseek and
one failed ioctl – nine system calls that always occur
together. So the service keeps opening a file. And
dienst.log shows the price of the measurement: during these
five seconds the rate fell to about 9,900.
Step 5 – Which file? On this system
perf trace only shows file names as addresses. Here
strace is right – but only for one
second:
# on perf1
sudo timeout 1 strace -p 12089 -e trace=openat -o open.txttimeout 1stopsstraceafter one second;stracethen detaches cleanly from the process.-p 12089attaches to the process,-e trace=openatonly toopenat.
# on perf1
head -3 open.txtExpected:
openat(AT_FDCWD, "/home/ubuntu/tag13/dienst.json", O_RDONLY|O_CLOEXEC) = 3
openat(AT_FDCWD, "/home/ubuntu/tag13/dienst.json", O_RDONLY|O_CLOEXEC) = 3
openat(AT_FDCWD, "/home/ubuntu/tag13/dienst.json", O_RDONLY|O_CLOEXEC) = 3
The service reads its settings again for every order
– line 8 in dienst.py calls einstellungen()
inside bearbeite(). By the way, open.txt has
only 391 lines for the whole second (wc -l open.txt counts
them, in the lab: 391 open.txt): under strace
the rate fell from 16,000 to about 400 per second. That is why never
longer than necessary.
Step 6 – The cross-check with a counter. How often per second does the service open a file, measured without much effort?
# on perf1
sudo funccount-bpfcc -i 1 -d 4 -p 12089 do_sys_openat2-i 1prints an interim result every second,-d 4stops after four seconds.-p 12089counts only for this process.
Expected (excerpt):
FUNC COUNT
do_sys_openat2 15044
FUNC COUNT
do_sys_openat2 17236
One openat per order – the numbers match the rate in the
log, and the service kept running at full speed meanwhile.
Step 7 – Fix it. Stop the service:
# on perf1
kill 12089and change it so that it reads the settings only once at startup:
# on perf1
nano dienst.pyimport json, time
def einstellungen():
with open("/home/ubuntu/tag13/dienst.json") as f:
return json.load(f)
EINSTELLUNGEN = einstellungen()
def bearbeite(auftrag):
e = EINSTELLUNGEN
return round(auftrag * (1 - e["rabatt"]), 2)
fertig, start = 0, time.time()
while True:
bearbeite(fertig % 1000)
fertig += 1
if time.time() - start >= 5:
print(time.strftime("%H:%M:%S"), round(fertig / 5), "Auftraege/s", flush=True)
fertig, start = 0, time.time()- Lines 7–8: the settings are read once at startup and stored in
EINSTELLUNGEN. - Line 10:
bearbeite()uses the stored settings instead of opening the file again.
Step 8 – Check. Restart the service:
# on perf1
nohup python3 dienst.py > dienst.log 2>&1 &Wait a good 15 seconds, then:
# on perf1
cat dienst.logExpected:
19:08:54 632774 Auftraege/s
19:08:59 570291 Auftraege/s
19:09:04 641979 Auftraege/s
You get the new PID (in the lab 12582) again with
pgrep -f "python3 [d]ienst.py". Then:
# on perf1
pidstat -u -p 12582 1 3Expected (excerpt):
Average: 1000 12582 100.00 0.00 0.00 0.00 100.00 - python3
Over 600,000 instead of 18,000 orders per second –
about 35 times –, and %system is at 0. A
sudo perf trace -s -p 12582 -- sleep 5 now counts exactly
one system call in five seconds: the write of the status
line. It was not Python, it was one file access per order.
Step 9 – Stop it.
# on perf1
pkill -f "python3 [d]ienst.py"If the settings can change during operation, you reread them on a
signal (for example SIGHUP) or check the file’s
modification time at most once per second – not for every order.
Remember: High
%systemin a “computing” program means: system calls. Counting and summarizing show which, one second ofstraceshows with what.
If it doesn’t work
pidstatreports no process: The service is not running.cat dienst.logshows the error, often a wrong path in line 4 (FileNotFoundError).pgrepfinds two PIDs: An old service is still running.pkill -f "python3 [d]ienst.py"and start again.
Challenge
On perf1 a program starts regularly without you having called it. Find out with a tracepoint which one, at what interval, and who starts it.
Solution path: Record the program starts for longer than one minute without logging in during that time:
# on perf1
sudo trace-cmd record -e sched:sched_process_exec -o minute.dat sleep 65# on perf1
sudo trace-cmd report -i minute.datExpected:
cpus=4
sleep-12992 [001] 22134.024170: sched_process_exec: filename=/usr/bin/sleep pid=12992 old_pid=12992
sadc-12993 [001] 22198.291456: sched_process_exec: filename=/proc/self/fd/9 pid=12993 old_pid=12993
sadc-12993 [001] 22198.354580: sched_process_exec: filename=/usr/lib/sysstat/sa1 pid=12993 old_pid=12993
sadc-12993 [001] 22198.359093: sched_process_exec: filename=/usr/lib/sysstat/sadc pid=12993 old_pid=12993
It is sa1, which starts sadc – the
collector of sar. On Day 0 you set it to one measurement
per minute. The cross-check:
# on perf1
systemctl list-timers sysstat-collect.timer --no-pagerExpected (your times differ):
NEXT LEFT LAST PASSED UNIT ACTIVATES
Mon 2026-11-30 19:12:00 UTC 36s Mon 2026-11-30 19:11:15 UTC 8s ago sysstat-collect.timer sysstat-collect.service
The systemd timer sysstat-collect.timer starts the
service that calls sa1 every minute.
Save your progress? Sign up for free
Checkpoint
# on perf1
sudo perf probe -lExpected: no output – all probe points from Drill 5 are removed.
# on perf1
sudo cat /sys/kernel/tracing/current_tracerExpected: nop – ftrace is switched off. If it says
something else, sudo trace-cmd reset.
# on perf1
pgrep -f "python3 [d]ienst.py"Expected: no output – the service is stopped.
Test yourself
- What is the difference between a tracepoint and a kprobe, and which do you use if both work?
- Why does a tracepoint see processes that
topdoes not see? - How do you recognize in a
function_graphtree ofdo_sys_openat2that the open failed? - Order by cost:
strace -c,perf stat -e raw_syscalls:sys_enter,perf trace -s. Which tool can lose events? - A service shows 23 %
%system. How do you proceed without slowing it down much? - What do you have to check after
perf probeand after an abortedtrace-cmd?
Answers:
- A tracepoint is a fixed, stable probe point; a kprobe attaches to any kernel function and can be missing after an update. If both work: tracepoint.
- Because it sees every single event;
toponly looks at intervals and misses processes that live for milliseconds. - Instead of
fd_installthere isput_unused_fd: the reserved file descriptor was released again. perf stat(×1.2) <perf trace -s(×9) <strace -c(×190).perf tracecan lose events.- Count (
perf stat,funccount), summarize (perf trace -s -p PID), then at most one second ofstrace -p PIDfor the arguments. perf probe -lmust be empty,/sys/kernel/tracing/current_tracermust shownop.
Interview Note
“You suspect that a production service makes too many system calls.
How do you proceed?” – Not with strace -p as the first
step: strace stops the process at every call and can slow
it down by two orders of magnitude. First look at %system
in pidstat or top, then count
(perf stat -e raw_syscalls:sys_enter -p PID,
funccount), then summarize
(perf trace -s -p PID), and strace for at most
one second to see arguments like file names. If you can also distinguish
tracepoints, kprobes and uprobes and know that kprobes are not stable,
you have understood the topic.
Enterprise Note
Tracing on production systems needs rules: Who may run
perf, trace-cmd and bcc tools (all need root
or CAP_PERFMON/CAP_BPF)? Which tools are
approved for ongoing operation? Many organizations allow counters and
summaries at any time, but strace and
function_graph only with an announcement or in a
maintenance window. Function names change with kernel updates – scripts
with kprobes must therefore be tested after every update; tracepoints
are the safer choice. A forgotten tracer (current_tracer
not nop) or forgotten probe points cost performance
permanently; check both after every analysis.
Summary
- Tracepoints are fixed, stable probe points in the kernel, kprobes attach to any kernel function (not stable), uprobes to functions in programs and libraries.
trace-cmd record -e GRUPPE:EREIGNIS BEFEHLrecords tracepoints,trace-cmd reportshows them. An SSH login started about 50 programs on perf1 (motd).-p function_graph -g FUNKTIONshows the call tree with times;catopened 31 files, 12 of them in vain (locale).- Counting is cheap:
funccountandperf stat -e …count in the kernel. - Overhead with 200,000 system calls:
perf stat×1.2,perf trace -s×9 (loses events),strace -c×190. perf probecreates your own probe points:curl http://localhost/calls nogetaddrinfoand connects over IPv6.- Diagnosis: a service read its settings file for every order – nine system calls per order, 23 % system time. Reading it once: 600,000 instead of 18,000 orders per second.
Commands at a glance
| Command | What it does | Parameters |
|---|---|---|
trace-cmd list -e [MUSTER] |
list tracepoints | the pattern is a regular expression |
trace-cmd record -e EREIGNIS [-o DATEI] BEFEHL |
record tracepoints while the command runs | -e can be repeated, -F only the
command |
trace-cmd record -p function_graph -g FUNKTION --max-graph-depth N |
call tree of a kernel function | -p tracer, -g start function |
trace-cmd report [-i DATEI] |
show a recording | -i input file |
trace-cmd reset |
switch ftrace off | – |
funccount-bpfcc [-i N] [-d N] [-p PID] 'MUSTER' |
count kernel functions | -i interim result, -d duration,
-p process |
strace -c [-o DATEI] BEFEHL |
count system calls (expensive) | -c table |
timeout 1 strace -p PID -e trace=AUFRUF -o DATEI |
watch a process briefly | -p attach, -e trace= selection |
perf trace -s [-p PID] [-o DATEI] -- BEFEHL |
summarize system calls | -s summary |
perf stat -e raw_syscalls:sys_enter BEFEHL |
count system calls (cheap) | -e event |
perf probe -x DATEI FUNKTION /
perf probe -a FUNKTION |
create uprobe / kprobe | -x program or library |
perf probe -l /
perf probe -d 'MUSTER' |
list / remove probe points | – |
ldd PROGRAMM |
libraries of a program | – |
pgrep -f "MUSTER" |
find a PID via the command line | [x] trick against matching itself |
pidstat -u -p PID 1 3 |
CPU of a process, split into usr and system | – |
/usr/bin/time -f "%e s" BEFEHL |
measure run time | -f format |
systemctl list-timers EINHEIT |
when a timer last ran and runs next | – |