1PERF-SCRIPT-PYTHON(1)             perf Manual            PERF-SCRIPT-PYTHON(1)
2
3
4

NAME

6       perf-script-python - Process trace data with a Python script
7

SYNOPSIS

9       perf script [-s [Python]:script[.py] ]
10

DESCRIPTION

12       This perf script option is used to process perf script data using
13       perf’s built-in Python interpreter. It reads and processes the input
14       file and displays the results of the trace analysis implemented in the
15       given Python script, if any.
16

A QUICK EXAMPLE

18       This section shows the process, start to finish, of creating a working
19       Python script that aggregates and extracts useful information from a
20       raw perf script stream. You can avoid reading the rest of this document
21       if an example is enough for you; the rest of the document provides more
22       details on each step and lists the library functions available to
23       script writers.
24
25       This example actually details the steps that were used to create the
26       syscall-counts script you see when you list the available perf script
27       scripts via perf script -l. As such, this script also shows how to
28       integrate your script into the list of general-purpose perf script
29       scripts listed by that command.
30
31       The syscall-counts script is a simple script, but demonstrates all the
32       basic ideas necessary to create a useful script. Here’s an example of
33       its output (syscall names are not yet supported, they will appear as
34       numbers):
35
36
37           .ft C
38           syscall events:
39
40           event                                          count
41           ----------------------------------------  -----------
42           sys_write                                     455067
43           sys_getdents                                    4072
44           sys_close                                       3037
45           sys_swapoff                                     1769
46           sys_read                                         923
47           sys_sched_setparam                               826
48           sys_open                                         331
49           sys_newfstat                                     326
50           sys_mmap                                         217
51           sys_munmap                                       216
52           sys_futex                                        141
53           sys_select                                       102
54           sys_poll                                          84
55           sys_setitimer                                     12
56           sys_writev                                         8
57           15                                                 8
58           sys_lseek                                          7
59           sys_rt_sigprocmask                                 6
60           sys_wait4                                          3
61           sys_ioctl                                          3
62           sys_set_robust_list                                1
63           sys_exit                                           1
64           56                                                 1
65           sys_access                                         1
66           .ft
67
68
69       Basically our task is to keep a per-syscall tally that gets updated
70       every time a system call occurs in the system. Our script will do that,
71       but first we need to record the data that will be processed by that
72       script. Theoretically, there are a couple of ways we could do that:
73
74       ·   we could enable every event under the tracing/events/syscalls
75           directory, but this is over 600 syscalls, well beyond the number
76           allowable by perf. These individual syscall events will however be
77           useful if we want to later use the guidance we get from the
78           general-purpose scripts to drill down and get more detail about
79           individual syscalls of interest.
80
81       ·   we can enable the sys_enter and/or sys_exit syscalls found under
82           tracing/events/raw_syscalls. These are called for all syscalls; the
83           id field can be used to distinguish between individual syscall
84           numbers.
85
86       For this script, we only need to know that a syscall was entered; we
87       don’t care how it exited, so we’ll use perf record to record only the
88       sys_enter events:
89
90
91           .ft C
92           # perf record -a -e raw_syscalls:sys_enter
93
94           ^C[ perf record: Woken up 1 times to write data ]
95           [ perf record: Captured and wrote 56.545 MB perf.data (~2470503 samples) ]
96           .ft
97
98
99       The options basically say to collect data for every syscall event
100       system-wide and multiplex the per-cpu output into a single stream. That
101       single stream will be recorded in a file in the current directory
102       called perf.data.
103
104       Once we have a perf.data file containing our data, we can use the -g
105       perf script option to generate a Python script that will contain a
106       callback handler for each event type found in the perf.data trace
107       stream (for more details, see the STARTER SCRIPTS section).
108
109
110           .ft C
111           # perf script -g python
112           generated Python script: perf-script.py
113
114           The output file created also in the current directory is named
115           perf-script.py.  Here´s the file in its entirety:
116
117           # perf script event handlers, generated by perf script -g python
118           # Licensed under the terms of the GNU GPL License version 2
119
120           # The common_* event handler fields are the most useful fields common to
121           # all events.  They don´t necessarily correspond to the ´common_*´ fields
122           # in the format files.  Those fields not available as handler params can
123           # be retrieved using Python functions of the form common_*(context).
124           # See the perf-script-python Documentation for the list of available functions.
125
126           import os
127           import sys
128
129           sys.path.append(os.environ[´PERF_EXEC_PATH´] + \
130                   ´/scripts/python/Perf-Trace-Util/lib/Perf/Trace´)
131
132           from perf_trace_context import *
133           from Core import *
134
135           def trace_begin():
136                   print "in trace_begin"
137
138           def trace_end():
139                   print "in trace_end"
140
141           def raw_syscalls__sys_enter(event_name, context, common_cpu,
142                   common_secs, common_nsecs, common_pid, common_comm,
143                   id, args):
144                           print_header(event_name, common_cpu, common_secs, common_nsecs,
145                                   common_pid, common_comm)
146
147                           print "id=%d, args=%s\n" % \
148                           (id, args),
149
150           def trace_unhandled(event_name, context, common_cpu, common_secs, common_nsecs,
151                           common_pid, common_comm):
152                           print_header(event_name, common_cpu, common_secs, common_nsecs,
153                           common_pid, common_comm)
154
155           def print_header(event_name, cpu, secs, nsecs, pid, comm):
156                   print "%-20s %5u %05u.%09u %8u %-20s " % \
157                   (event_name, cpu, secs, nsecs, pid, comm),
158           .ft
159
160
161       At the top is a comment block followed by some import statements and a
162       path append which every perf script script should include.
163
164       Following that are a couple generated functions, trace_begin() and
165       trace_end(), which are called at the beginning and the end of the
166       script respectively (for more details, see the SCRIPT_LAYOUT section
167       below).
168
169       Following those are the event handler functions generated one for every
170       event in the perf record output. The handler functions take the form
171       subsystemevent_name, and contain named parameters, one for each field
172       in the event; in this case, there’s only one event,
173       raw_syscallssys_enter(). (see the EVENT HANDLERS section below for more
174       info on event handlers).
175
176       The final couple of functions are, like the begin and end functions,
177       generated for every script. The first, trace_unhandled(), is called
178       every time the script finds an event in the perf.data file that doesn’t
179       correspond to any event handler in the script. This could mean either
180       that the record step recorded event types that it wasn’t really
181       interested in, or the script was run against a trace file that doesn’t
182       correspond to the script.
183
184       The script generated by -g option simply prints a line for each event
185       found in the trace stream i.e. it basically just dumps the event and
186       its parameter values to stdout. The print_header() function is simply a
187       utility function used for that purpose. Let’s rename the script and run
188       it to see the default output:
189
190
191           .ft C
192           # mv perf-script.py syscall-counts.py
193           # perf script -s syscall-counts.py
194
195           raw_syscalls__sys_enter     1 00840.847582083     7506 perf                  id=1, args=
196           raw_syscalls__sys_enter     1 00840.847595764     7506 perf                  id=1, args=
197           raw_syscalls__sys_enter     1 00840.847620860     7506 perf                  id=1, args=
198           raw_syscalls__sys_enter     1 00840.847710478     6533 npviewer.bin          id=78, args=
199           raw_syscalls__sys_enter     1 00840.847719204     6533 npviewer.bin          id=142, args=
200           raw_syscalls__sys_enter     1 00840.847755445     6533 npviewer.bin          id=3, args=
201           raw_syscalls__sys_enter     1 00840.847775601     6533 npviewer.bin          id=3, args=
202           raw_syscalls__sys_enter     1 00840.847781820     6533 npviewer.bin          id=3, args=
203           .
204           .
205           .
206           .ft
207
208
209       Of course, for this script, we’re not interested in printing every
210       trace event, but rather aggregating it in a useful way. So we’ll get
211       rid of everything to do with printing as well as the trace_begin() and
212       trace_unhandled() functions, which we won’t be using. That leaves us
213       with this minimalistic skeleton:
214
215
216           .ft C
217           import os
218           import sys
219
220           sys.path.append(os.environ[´PERF_EXEC_PATH´] + \
221                   ´/scripts/python/Perf-Trace-Util/lib/Perf/Trace´)
222
223           from perf_trace_context import *
224           from Core import *
225
226           def trace_end():
227                   print "in trace_end"
228
229           def raw_syscalls__sys_enter(event_name, context, common_cpu,
230                   common_secs, common_nsecs, common_pid, common_comm,
231                   id, args):
232           .ft
233
234
235       In trace_end(), we’ll simply print the results, but first we need to
236       generate some results to print. To do that we need to have our
237       sys_enter() handler do the necessary tallying until all events have
238       been counted. A hash table indexed by syscall id is a good way to store
239       that information; every time the sys_enter() handler is called, we
240       simply increment a count associated with that hash entry indexed by
241       that syscall id:
242
243
244           .ft C
245             syscalls = autodict()
246
247             try:
248               syscalls[id] += 1
249             except TypeError:
250               syscalls[id] = 1
251           .ft
252
253
254       The syscalls autodict object is a special kind of Python dictionary
255       (implemented in Core.py) that implements Perl’s autovivifying hashes in
256       Python i.e. with autovivifying hashes, you can assign nested hash
257       values without having to go to the trouble of creating intermediate
258       levels if they don’t exist e.g syscalls[comm][pid][id] = 1 will create
259       the intermediate hash levels and finally assign the value 1 to the hash
260       entry for id (because the value being assigned isn’t a hash object
261       itself, the initial value is assigned in the TypeError exception. Well,
262       there may be a better way to do this in Python but that’s what works
263       for now).
264
265       Putting that code into the raw_syscalls__sys_enter() handler, we
266       effectively end up with a single-level dictionary keyed on syscall id
267       and having the counts we’ve tallied as values.
268
269       The print_syscall_totals() function iterates over the entries in the
270       dictionary and displays a line for each entry containing the syscall
271       name (the dictionary keys contain the syscall ids, which are passed to
272       the Util function syscall_name(), which translates the raw syscall
273       numbers to the corresponding syscall name strings). The output is
274       displayed after all the events in the trace have been processed, by
275       calling the print_syscall_totals() function from the trace_end()
276       handler called at the end of script processing.
277
278       The final script producing the output shown above is shown in its
279       entirety below (syscall_name() helper is not yet available, you can
280       only deal with id’s for now):
281
282
283           .ft C
284           import os
285           import sys
286
287           sys.path.append(os.environ[´PERF_EXEC_PATH´] + \
288                   ´/scripts/python/Perf-Trace-Util/lib/Perf/Trace´)
289
290           from perf_trace_context import *
291           from Core import *
292           from Util import *
293
294           syscalls = autodict()
295
296           def trace_end():
297                   print_syscall_totals()
298
299           def raw_syscalls__sys_enter(event_name, context, common_cpu,
300                   common_secs, common_nsecs, common_pid, common_comm,
301                   id, args):
302                   try:
303                           syscalls[id] += 1
304                   except TypeError:
305                           syscalls[id] = 1
306
307           def print_syscall_totals():
308               if for_comm is not None:
309                       print "\nsyscall events for %s:\n\n" % (for_comm),
310               else:
311                       print "\nsyscall events:\n\n",
312
313               print "%-40s  %10s\n" % ("event", "count"),
314               print "%-40s  %10s\n" % ("----------------------------------------", \
315                                            "-----------"),
316
317               for id, val in sorted(syscalls.iteritems(), key = lambda(k, v): (v, k), \
318                                             reverse = True):
319                       print "%-40s  %10d\n" % (syscall_name(id), val),
320           .ft
321
322
323       The script can be run just as before:
324
325           # perf script -s syscall-counts.py
326
327       So those are the essential steps in writing and running a script. The
328       process can be generalized to any tracepoint or set of tracepoints
329       you’re interested in - basically find the tracepoint(s) you’re
330       interested in by looking at the list of available events shown by perf
331       list and/or look in /sys/kernel/debug/tracing events for detailed event
332       and field info, record the corresponding trace data using perf record,
333       passing it the list of interesting events, generate a skeleton script
334       using perf script -g python and modify the code to aggregate and
335       display it for your particular needs.
336
337       After you’ve done that you may end up with a general-purpose script
338       that you want to keep around and have available for future use. By
339       writing a couple of very simple shell scripts and putting them in the
340       right place, you can have your script listed alongside the other
341       scripts listed by the perf script -l command e.g.:
342
343
344           .ft C
345           root@tropicana:~# perf script -l
346           List of available trace scripts:
347             wakeup-latency                       system-wide min/max/avg wakeup latency
348             rw-by-file <comm>                    r/w activity for a program, by file
349             rw-by-pid                            system-wide r/w activity
350           .ft
351
352
353       A nice side effect of doing this is that you also then capture the
354       probably lengthy perf record command needed to record the events for
355       the script.
356
357       To have the script appear as a built-in script, you write two simple
358       scripts, one for recording and one for reporting.
359
360       The record script is a shell script with the same base name as your
361       script, but with -record appended. The shell script should be put into
362       the perf/scripts/python/bin directory in the kernel source tree. In
363       that script, you write the perf record command-line needed for your
364       script:
365
366
367           .ft C
368           # cat kernel-source/tools/perf/scripts/python/bin/syscall-counts-record
369
370           #!/bin/bash
371           perf record -a -e raw_syscalls:sys_enter
372           .ft
373
374
375       The report script is also a shell script with the same base name as
376       your script, but with -report appended. It should also be located in
377       the perf/scripts/python/bin directory. In that script, you write the
378       perf script -s command-line needed for running your script:
379
380
381           .ft C
382           # cat kernel-source/tools/perf/scripts/python/bin/syscall-counts-report
383
384           #!/bin/bash
385           # description: system-wide syscall counts
386           perf script -s ~/libexec/perf-core/scripts/python/syscall-counts.py
387           .ft
388
389
390       Note that the location of the Python script given in the shell script
391       is in the libexec/perf-core/scripts/python directory - this is where
392       the script will be copied by make install when you install perf. For
393       the installation to install your script there, your script needs to be
394       located in the perf/scripts/python directory in the kernel source tree:
395
396
397           .ft C
398           # ls -al kernel-source/tools/perf/scripts/python
399
400           root@tropicana:/home/trz/src/tip# ls -al tools/perf/scripts/python
401           total 32
402           drwxr-xr-x 4 trz trz 4096 2010-01-26 22:30 .
403           drwxr-xr-x 4 trz trz 4096 2010-01-26 22:29 ..
404           drwxr-xr-x 2 trz trz 4096 2010-01-26 22:29 bin
405           -rw-r--r-- 1 trz trz 2548 2010-01-26 22:29 check-perf-script.py
406           drwxr-xr-x 3 trz trz 4096 2010-01-26 22:49 Perf-Trace-Util
407           -rw-r--r-- 1 trz trz 1462 2010-01-26 22:30 syscall-counts.py
408           .ft
409
410
411       Once you’ve done that (don’t forget to do a new make install, otherwise
412       your script won’t show up at run-time), perf script -l should show a
413       new entry for your script:
414
415
416           .ft C
417           root@tropicana:~# perf script -l
418           List of available trace scripts:
419             wakeup-latency                       system-wide min/max/avg wakeup latency
420             rw-by-file <comm>                    r/w activity for a program, by file
421             rw-by-pid                            system-wide r/w activity
422             syscall-counts                       system-wide syscall counts
423           .ft
424
425
426       You can now perform the record step via perf script record:
427
428           # perf script record syscall-counts
429
430       and display the output using perf script report:
431
432           # perf script report syscall-counts
433

STARTER SCRIPTS

435       You can quickly get started writing a script for a particular set of
436       trace data by generating a skeleton script using perf script -g python
437       in the same directory as an existing perf.data trace file. That will
438       generate a starter script containing a handler for each of the event
439       types in the trace file; it simply prints every available field for
440       each event in the trace file.
441
442       You can also look at the existing scripts in
443       ~/libexec/perf-core/scripts/python for typical examples showing how to
444       do basic things like aggregate event data, print results, etc. Also,
445       the check-perf-script.py script, while not interesting for its results,
446       attempts to exercise all of the main scripting features.
447

EVENT HANDLERS

449       When perf script is invoked using a trace script, a user-defined
450       handler function is called for each event in the trace. If there’s no
451       handler function defined for a given event type, the event is ignored
452       (or passed to a trace_handled function, see below) and the next event
453       is processed.
454
455       Most of the event’s field values are passed as arguments to the handler
456       function; some of the less common ones aren’t - those are available as
457       calls back into the perf executable (see below).
458
459       As an example, the following perf record command can be used to record
460       all sched_wakeup events in the system:
461
462           # perf record -a -e sched:sched_wakeup
463
464       Traces meant to be processed using a script should be recorded with the
465       above option: -a to enable system-wide collection.
466
467       The format file for the sched_wakep event defines the following fields
468       (see /sys/kernel/debug/tracing/events/sched/sched_wakeup/format):
469
470
471           .ft C
472            format:
473                   field:unsigned short common_type;
474                   field:unsigned char common_flags;
475                   field:unsigned char common_preempt_count;
476                   field:int common_pid;
477                   field:int common_lock_depth;
478
479                   field:char comm[TASK_COMM_LEN];
480                   field:pid_t pid;
481                   field:int prio;
482                   field:int success;
483                   field:int target_cpu;
484           .ft
485
486
487       The handler function for this event would be defined as:
488
489
490           .ft C
491           def sched__sched_wakeup(event_name, context, common_cpu, common_secs,
492                  common_nsecs, common_pid, common_comm,
493                  comm, pid, prio, success, target_cpu):
494                  pass
495           .ft
496
497
498       The handler function takes the form subsystem__event_name.
499
500       The common_* arguments in the handler’s argument list are the set of
501       arguments passed to all event handlers; some of the fields correspond
502       to the common_* fields in the format file, but some are synthesized,
503       and some of the common_* fields aren’t common enough to to be passed to
504       every event as arguments but are available as library functions.
505
506       Here’s a brief description of each of the invariant event args:
507
508           event_name                 the name of the event as text
509           context                    an opaque ´cookie´ used in calls back into perf
510           common_cpu                 the cpu the event occurred on
511           common_secs                the secs portion of the event timestamp
512           common_nsecs               the nsecs portion of the event timestamp
513           common_pid                 the pid of the current task
514           common_comm                the name of the current process
515
516       All of the remaining fields in the event’s format file have
517       counterparts as handler function arguments of the same name, as can be
518       seen in the example above.
519
520       The above provides the basics needed to directly access every field of
521       every event in a trace, which covers 90% of what you need to know to
522       write a useful trace script. The sections below cover the rest.
523

SCRIPT LAYOUT

525       Every perf script Python script should start by setting up a Python
526       module search path and ´import’ing a few support modules (see module
527       descriptions below):
528
529
530           .ft C
531            import os
532            import sys
533
534            sys.path.append(os.environ[´PERF_EXEC_PATH´] + \
535                         ´/scripts/python/Perf-Trace-Util/lib/Perf/Trace´)
536
537            from perf_trace_context import *
538            from Core import *
539           .ft
540
541
542       The rest of the script can contain handler functions and support
543       functions in any order.
544
545       Aside from the event handler functions discussed above, every script
546       can implement a set of optional functions:
547
548       trace_begin, if defined, is called before any event is processed and
549       gives scripts a chance to do setup tasks:
550
551
552           .ft C
553           def trace_begin:
554               pass
555           .ft
556
557
558       trace_end, if defined, is called after all events have been processed
559       and gives scripts a chance to do end-of-script tasks, such as display
560       results:
561
562
563           .ft C
564           def trace_end:
565               pass
566           .ft
567
568
569       trace_unhandled, if defined, is called after for any event that doesn’t
570       have a handler explicitly defined for it. The standard set of common
571       arguments are passed into it:
572
573
574           .ft C
575           def trace_unhandled(event_name, context, common_cpu, common_secs,
576                   common_nsecs, common_pid, common_comm):
577               pass
578           .ft
579
580
581       The remaining sections provide descriptions of each of the available
582       built-in perf script Python modules and their associated functions.
583

AVAILABLE MODULES AND FUNCTIONS

585       The following sections describe the functions and variables available
586       via the various perf script Python modules. To use the functions and
587       variables from the given module, add the corresponding from XXXX import
588       line to your perf script script.
589
590   Core.py Module
591       These functions provide some essential functions to user scripts.
592
593       The flag_str and symbol_str functions provide human-readable strings
594       for flag and symbolic fields. These correspond to the strings and
595       values parsed from the print fmt fields of the event format files:
596
597           flag_str(event_name, field_name, field_value) - returns the string representation corresponding to field_value for the flag field field_name of event event_name
598           symbol_str(event_name, field_name, field_value) - returns the string representation corresponding to field_value for the symbolic field field_name of event event_name
599
600       The autodict function returns a special kind of Python dictionary that
601       implements Perl’s autovivifying hashes in Python i.e. with
602       autovivifying hashes, you can assign nested hash values without having
603       to go to the trouble of creating intermediate levels if they don’t
604       exist.
605
606           autodict() - returns an autovivifying dictionary instance
607
608   perf_trace_context Module
609       Some of the common fields in the event format file aren’t all that
610       common, but need to be made accessible to user scripts nonetheless.
611
612       perf_trace_context defines a set of functions that can be used to
613       access this data in the context of the current event. Each of these
614       functions expects a context variable, which is the same as the context
615       variable passed into every event handler as the second argument.
616
617           common_pc(context) - returns common_preempt count for the current event
618           common_flags(context) - returns common_flags for the current event
619           common_lock_depth(context) - returns common_lock_depth for the current event
620
621   Util.py Module
622       Various utility functions for use with perf script:
623
624           nsecs(secs, nsecs) - returns total nsecs given secs/nsecs pair
625           nsecs_secs(nsecs) - returns whole secs portion given nsecs
626           nsecs_nsecs(nsecs) - returns nsecs remainder given nsecs
627           nsecs_str(nsecs) - returns printable string in the form secs.nsecs
628           avg(total, n) - returns average given a sum and a total number of values
629

SEE ALSO

631       perf-script(1)
632
633
634
635perf                              06/18/2019             PERF-SCRIPT-PYTHON(1)
Impressum