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

NAME

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

SYNOPSIS

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

DESCRIPTION

12       This perf trace option is used to process perf trace data using perf’s
13       built-in Python interpreter. It reads and processes the input file and
14       displays the results of the trace analysis implemented in the given
15       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 trace 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 trace
27       scripts via perf trace -l. As such, this script also shows how to
28       integrate your script into the list of general-purpose perf trace
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 trace 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 trace -g python
112           generated Python script: perf-trace.py
113
114           The output file created also in the current directory is named
115           perf-trace.py.  Here's the file in its entirety:
116
117           # perf trace event handlers, generated by perf trace -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-trace-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 trace 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-trace.py syscall-counts.py
193           # perf trace -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 dictonary 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 trace -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 trace -g python and modify the code to aggregate and display
335       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 trace -l command e.g.:
342
343
344           .ft C
345           root@tropicana:~# perf trace -l
346           List of available trace scripts:
347             workqueue-stats                      workqueue stats (ins/exe/create/destroy)
348             wakeup-latency                       system-wide min/max/avg wakeup latency
349             rw-by-file <comm>                    r/w activity for a program, by file
350             rw-by-pid                            system-wide r/w activity
351           .ft
352
353
354       A nice side effect of doing this is that you also then capture the
355       probably lengthy perf record command needed to record the events for
356       the script.
357
358       To have the script appear as a built-in script, you write two simple
359       scripts, one for recording and one for reporting.
360
361       The record script is a shell script with the same base name as your
362       script, but with -record appended. The shell script should be put into
363       the perf/scripts/python/bin directory in the kernel source tree. In
364       that script, you write the perf record command-line needed for your
365       script:
366
367
368           .ft C
369           # cat kernel-source/tools/perf/scripts/python/bin/syscall-counts-record
370
371           #!/bin/bash
372           perf record -a -e raw_syscalls:sys_enter
373           .ft
374
375
376       The report script is also a shell script with the same base name as
377       your script, but with -report appended. It should also be located in
378       the perf/scripts/python/bin directory. In that script, you write the
379       perf trace -s command-line needed for running your script:
380
381
382           .ft C
383           # cat kernel-source/tools/perf/scripts/python/bin/syscall-counts-report
384
385           #!/bin/bash
386           # description: system-wide syscall counts
387           perf trace -s ~/libexec/perf-core/scripts/python/syscall-counts.py
388           .ft
389
390
391       Note that the location of the Python script given in the shell script
392       is in the libexec/perf-core/scripts/python directory - this is where
393       the script will be copied by make install when you install perf. For
394       the installation to install your script there, your script needs to be
395       located in the perf/scripts/python directory in the kernel source tree:
396
397
398           .ft C
399           # ls -al kernel-source/tools/perf/scripts/python
400
401           root@tropicana:/home/trz/src/tip# ls -al tools/perf/scripts/python
402           total 32
403           drwxr-xr-x 4 trz trz 4096 2010-01-26 22:30 .
404           drwxr-xr-x 4 trz trz 4096 2010-01-26 22:29 ..
405           drwxr-xr-x 2 trz trz 4096 2010-01-26 22:29 bin
406           -rw-r--r-- 1 trz trz 2548 2010-01-26 22:29 check-perf-trace.py
407           drwxr-xr-x 3 trz trz 4096 2010-01-26 22:49 Perf-Trace-Util
408           -rw-r--r-- 1 trz trz 1462 2010-01-26 22:30 syscall-counts.py
409           .ft
410
411
412       Once you’ve done that (don’t forget to do a new make install, otherwise
413       your script won’t show up at run-time), perf trace -l should show a new
414       entry for your script:
415
416
417           .ft C
418           root@tropicana:~# perf trace -l
419           List of available trace scripts:
420             workqueue-stats                      workqueue stats (ins/exe/create/destroy)
421             wakeup-latency                       system-wide min/max/avg wakeup latency
422             rw-by-file <comm>                    r/w activity for a program, by file
423             rw-by-pid                            system-wide r/w activity
424             syscall-counts                       system-wide syscall counts
425           .ft
426
427
428       You can now perform the record step via perf trace record:
429
430           # perf trace record syscall-counts
431
432       and display the output using perf trace report:
433
434           # perf trace report syscall-counts
435

STARTER SCRIPTS

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

EVENT HANDLERS

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

SCRIPT LAYOUT

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

AVAILABLE MODULES AND FUNCTIONS

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

SEE ALSO

633       perf-trace(1)
634
635
636
637perf 2.6.35.14-106.fc             11/23/2011              PERF-TRACE-PYTHON(1)
Impressum