Path: blob/master/tools/perf/Documentation/perf-script-python.txt
10821 views
perf-script-python(1)1====================23NAME4----5perf-script-python - Process trace data with a Python script67SYNOPSIS8--------9[verse]10'perf script' [-s [Python]:script[.py] ]1112DESCRIPTION13-----------1415This perf script option is used to process perf script data using perf's16built-in Python interpreter. It reads and processes the input file and17displays the results of the trace analysis implemented in the given18Python script, if any.1920A QUICK EXAMPLE21---------------2223This section shows the process, start to finish, of creating a working24Python script that aggregates and extracts useful information from a25raw perf script stream. You can avoid reading the rest of this26document if an example is enough for you; the rest of the document27provides more details on each step and lists the library functions28available to script writers.2930This example actually details the steps that were used to create the31'syscall-counts' script you see when you list the available perf script32scripts via 'perf script -l'. As such, this script also shows how to33integrate your script into the list of general-purpose 'perf script'34scripts listed by that command.3536The syscall-counts script is a simple script, but demonstrates all the37basic ideas necessary to create a useful script. Here's an example38of its output (syscall names are not yet supported, they will appear39as numbers):4041----42syscall events:4344event count45---------------------------------------- -----------46sys_write 45506747sys_getdents 407248sys_close 303749sys_swapoff 176950sys_read 92351sys_sched_setparam 82652sys_open 33153sys_newfstat 32654sys_mmap 21755sys_munmap 21656sys_futex 14157sys_select 10258sys_poll 8459sys_setitimer 1260sys_writev 86115 862sys_lseek 763sys_rt_sigprocmask 664sys_wait4 365sys_ioctl 366sys_set_robust_list 167sys_exit 16856 169sys_access 170----7172Basically our task is to keep a per-syscall tally that gets updated73every time a system call occurs in the system. Our script will do74that, but first we need to record the data that will be processed by75that script. Theoretically, there are a couple of ways we could do76that:7778- we could enable every event under the tracing/events/syscalls79directory, but this is over 600 syscalls, well beyond the number80allowable by perf. These individual syscall events will however be81useful if we want to later use the guidance we get from the82general-purpose scripts to drill down and get more detail about83individual syscalls of interest.8485- we can enable the sys_enter and/or sys_exit syscalls found under86tracing/events/raw_syscalls. These are called for all syscalls; the87'id' field can be used to distinguish between individual syscall88numbers.8990For this script, we only need to know that a syscall was entered; we91don't care how it exited, so we'll use 'perf record' to record only92the sys_enter events:9394----95# perf record -a -e raw_syscalls:sys_enter9697^C[ perf record: Woken up 1 times to write data ]98[ perf record: Captured and wrote 56.545 MB perf.data (~2470503 samples) ]99----100101The options basically say to collect data for every syscall event102system-wide and multiplex the per-cpu output into a single stream.103That single stream will be recorded in a file in the current directory104called perf.data.105106Once we have a perf.data file containing our data, we can use the -g107'perf script' option to generate a Python script that will contain a108callback handler for each event type found in the perf.data trace109stream (for more details, see the STARTER SCRIPTS section).110111----112# perf script -g python113generated Python script: perf-script.py114115The output file created also in the current directory is named116perf-script.py. Here's the file in its entirety:117118# perf script event handlers, generated by perf script -g python119# Licensed under the terms of the GNU GPL License version 2120121# The common_* event handler fields are the most useful fields common to122# all events. They don't necessarily correspond to the 'common_*' fields123# in the format files. Those fields not available as handler params can124# be retrieved using Python functions of the form common_*(context).125# See the perf-script-python Documentation for the list of available functions.126127import os128import sys129130sys.path.append(os.environ['PERF_EXEC_PATH'] + \131'/scripts/python/perf-script-Util/lib/Perf/Trace')132133from perf_trace_context import *134from Core import *135136def trace_begin():137print "in trace_begin"138139def trace_end():140print "in trace_end"141142def raw_syscalls__sys_enter(event_name, context, common_cpu,143common_secs, common_nsecs, common_pid, common_comm,144id, args):145print_header(event_name, common_cpu, common_secs, common_nsecs,146common_pid, common_comm)147148print "id=%d, args=%s\n" % \149(id, args),150151def trace_unhandled(event_name, context, common_cpu, common_secs, common_nsecs,152common_pid, common_comm):153print_header(event_name, common_cpu, common_secs, common_nsecs,154common_pid, common_comm)155156def print_header(event_name, cpu, secs, nsecs, pid, comm):157print "%-20s %5u %05u.%09u %8u %-20s " % \158(event_name, cpu, secs, nsecs, pid, comm),159----160161At the top is a comment block followed by some import statements and a162path append which every perf script script should include.163164Following that are a couple generated functions, trace_begin() and165trace_end(), which are called at the beginning and the end of the166script respectively (for more details, see the SCRIPT_LAYOUT section167below).168169Following those are the 'event handler' functions generated one for170every event in the 'perf record' output. The handler functions take171the form subsystem__event_name, and contain named parameters, one for172each field in the event; in this case, there's only one event,173raw_syscalls__sys_enter(). (see the EVENT HANDLERS section below for174more info on event handlers).175176The final couple of functions are, like the begin and end functions,177generated for every script. The first, trace_unhandled(), is called178every time the script finds an event in the perf.data file that179doesn't correspond to any event handler in the script. This could180mean either that the record step recorded event types that it wasn't181really interested in, or the script was run against a trace file that182doesn't correspond to the script.183184The script generated by -g option simply prints a line for each185event found in the trace stream i.e. it basically just dumps the event186and its parameter values to stdout. The print_header() function is187simply a utility function used for that purpose. Let's rename the188script and run it to see the default output:189190----191# mv perf-script.py syscall-counts.py192# perf script -s syscall-counts.py193194raw_syscalls__sys_enter 1 00840.847582083 7506 perf id=1, args=195raw_syscalls__sys_enter 1 00840.847595764 7506 perf id=1, args=196raw_syscalls__sys_enter 1 00840.847620860 7506 perf id=1, args=197raw_syscalls__sys_enter 1 00840.847710478 6533 npviewer.bin id=78, args=198raw_syscalls__sys_enter 1 00840.847719204 6533 npviewer.bin id=142, args=199raw_syscalls__sys_enter 1 00840.847755445 6533 npviewer.bin id=3, args=200raw_syscalls__sys_enter 1 00840.847775601 6533 npviewer.bin id=3, args=201raw_syscalls__sys_enter 1 00840.847781820 6533 npviewer.bin id=3, args=202.203.204.205----206207Of course, for this script, we're not interested in printing every208trace event, but rather aggregating it in a useful way. So we'll get209rid of everything to do with printing as well as the trace_begin() and210trace_unhandled() functions, which we won't be using. That leaves us211with this minimalistic skeleton:212213----214import os215import sys216217sys.path.append(os.environ['PERF_EXEC_PATH'] + \218'/scripts/python/perf-script-Util/lib/Perf/Trace')219220from perf_trace_context import *221from Core import *222223def trace_end():224print "in trace_end"225226def raw_syscalls__sys_enter(event_name, context, common_cpu,227common_secs, common_nsecs, common_pid, common_comm,228id, args):229----230231In trace_end(), we'll simply print the results, but first we need to232generate some results to print. To do that we need to have our233sys_enter() handler do the necessary tallying until all events have234been counted. A hash table indexed by syscall id is a good way to235store that information; every time the sys_enter() handler is called,236we simply increment a count associated with that hash entry indexed by237that syscall id:238239----240syscalls = autodict()241242try:243syscalls[id] += 1244except TypeError:245syscalls[id] = 1246----247248The syscalls 'autodict' object is a special kind of Python dictionary249(implemented in Core.py) that implements Perl's 'autovivifying' hashes250in Python i.e. with autovivifying hashes, you can assign nested hash251values without having to go to the trouble of creating intermediate252levels if they don't exist e.g syscalls[comm][pid][id] = 1 will create253the intermediate hash levels and finally assign the value 1 to the254hash entry for 'id' (because the value being assigned isn't a hash255object itself, the initial value is assigned in the TypeError256exception. Well, there may be a better way to do this in Python but257that's what works for now).258259Putting that code into the raw_syscalls__sys_enter() handler, we260effectively end up with a single-level dictionary keyed on syscall id261and having the counts we've tallied as values.262263The print_syscall_totals() function iterates over the entries in the264dictionary and displays a line for each entry containing the syscall265name (the dictonary keys contain the syscall ids, which are passed to266the Util function syscall_name(), which translates the raw syscall267numbers to the corresponding syscall name strings). The output is268displayed after all the events in the trace have been processed, by269calling the print_syscall_totals() function from the trace_end()270handler called at the end of script processing.271272The final script producing the output shown above is shown in its273entirety below (syscall_name() helper is not yet available, you can274only deal with id's for now):275276----277import os278import sys279280sys.path.append(os.environ['PERF_EXEC_PATH'] + \281'/scripts/python/perf-script-Util/lib/Perf/Trace')282283from perf_trace_context import *284from Core import *285from Util import *286287syscalls = autodict()288289def trace_end():290print_syscall_totals()291292def raw_syscalls__sys_enter(event_name, context, common_cpu,293common_secs, common_nsecs, common_pid, common_comm,294id, args):295try:296syscalls[id] += 1297except TypeError:298syscalls[id] = 1299300def print_syscall_totals():301if for_comm is not None:302print "\nsyscall events for %s:\n\n" % (for_comm),303else:304print "\nsyscall events:\n\n",305306print "%-40s %10s\n" % ("event", "count"),307print "%-40s %10s\n" % ("----------------------------------------", \308"-----------"),309310for id, val in sorted(syscalls.iteritems(), key = lambda(k, v): (v, k), \311reverse = True):312print "%-40s %10d\n" % (syscall_name(id), val),313----314315The script can be run just as before:316317# perf script -s syscall-counts.py318319So those are the essential steps in writing and running a script. The320process can be generalized to any tracepoint or set of tracepoints321you're interested in - basically find the tracepoint(s) you're322interested in by looking at the list of available events shown by323'perf list' and/or look in /sys/kernel/debug/tracing events for324detailed event and field info, record the corresponding trace data325using 'perf record', passing it the list of interesting events,326generate a skeleton script using 'perf script -g python' and modify the327code to aggregate and display it for your particular needs.328329After you've done that you may end up with a general-purpose script330that you want to keep around and have available for future use. By331writing a couple of very simple shell scripts and putting them in the332right place, you can have your script listed alongside the other333scripts listed by the 'perf script -l' command e.g.:334335----336root@tropicana:~# perf script -l337List of available trace scripts:338workqueue-stats workqueue stats (ins/exe/create/destroy)339wakeup-latency system-wide min/max/avg wakeup latency340rw-by-file <comm> r/w activity for a program, by file341rw-by-pid system-wide r/w activity342----343344A nice side effect of doing this is that you also then capture the345probably lengthy 'perf record' command needed to record the events for346the script.347348To have the script appear as a 'built-in' script, you write two simple349scripts, one for recording and one for 'reporting'.350351The 'record' script is a shell script with the same base name as your352script, but with -record appended. The shell script should be put353into the perf/scripts/python/bin directory in the kernel source tree.354In that script, you write the 'perf record' command-line needed for355your script:356357----358# cat kernel-source/tools/perf/scripts/python/bin/syscall-counts-record359360#!/bin/bash361perf record -a -e raw_syscalls:sys_enter362----363364The 'report' script is also a shell script with the same base name as365your script, but with -report appended. It should also be located in366the perf/scripts/python/bin directory. In that script, you write the367'perf script -s' command-line needed for running your script:368369----370# cat kernel-source/tools/perf/scripts/python/bin/syscall-counts-report371372#!/bin/bash373# description: system-wide syscall counts374perf script -s ~/libexec/perf-core/scripts/python/syscall-counts.py375----376377Note that the location of the Python script given in the shell script378is in the libexec/perf-core/scripts/python directory - this is where379the script will be copied by 'make install' when you install perf.380For the installation to install your script there, your script needs381to be located in the perf/scripts/python directory in the kernel382source tree:383384----385# ls -al kernel-source/tools/perf/scripts/python386387root@tropicana:/home/trz/src/tip# ls -al tools/perf/scripts/python388total 32389drwxr-xr-x 4 trz trz 4096 2010-01-26 22:30 .390drwxr-xr-x 4 trz trz 4096 2010-01-26 22:29 ..391drwxr-xr-x 2 trz trz 4096 2010-01-26 22:29 bin392-rw-r--r-- 1 trz trz 2548 2010-01-26 22:29 check-perf-script.py393drwxr-xr-x 3 trz trz 4096 2010-01-26 22:49 perf-script-Util394-rw-r--r-- 1 trz trz 1462 2010-01-26 22:30 syscall-counts.py395----396397Once you've done that (don't forget to do a new 'make install',398otherwise your script won't show up at run-time), 'perf script -l'399should show a new entry for your script:400401----402root@tropicana:~# perf script -l403List of available trace scripts:404workqueue-stats workqueue stats (ins/exe/create/destroy)405wakeup-latency system-wide min/max/avg wakeup latency406rw-by-file <comm> r/w activity for a program, by file407rw-by-pid system-wide r/w activity408syscall-counts system-wide syscall counts409----410411You can now perform the record step via 'perf script record':412413# perf script record syscall-counts414415and display the output using 'perf script report':416417# perf script report syscall-counts418419STARTER SCRIPTS420---------------421422You can quickly get started writing a script for a particular set of423trace data by generating a skeleton script using 'perf script -g424python' in the same directory as an existing perf.data trace file.425That will generate a starter script containing a handler for each of426the event types in the trace file; it simply prints every available427field for each event in the trace file.428429You can also look at the existing scripts in430~/libexec/perf-core/scripts/python for typical examples showing how to431do basic things like aggregate event data, print results, etc. Also,432the check-perf-script.py script, while not interesting for its results,433attempts to exercise all of the main scripting features.434435EVENT HANDLERS436--------------437438When perf script is invoked using a trace script, a user-defined439'handler function' is called for each event in the trace. If there's440no handler function defined for a given event type, the event is441ignored (or passed to a 'trace_handled' function, see below) and the442next event is processed.443444Most of the event's field values are passed as arguments to the445handler function; some of the less common ones aren't - those are446available as calls back into the perf executable (see below).447448As an example, the following perf record command can be used to record449all sched_wakeup events in the system:450451# perf record -a -e sched:sched_wakeup452453Traces meant to be processed using a script should be recorded with454the above option: -a to enable system-wide collection.455456The format file for the sched_wakep event defines the following fields457(see /sys/kernel/debug/tracing/events/sched/sched_wakeup/format):458459----460format:461field:unsigned short common_type;462field:unsigned char common_flags;463field:unsigned char common_preempt_count;464field:int common_pid;465466field:char comm[TASK_COMM_LEN];467field:pid_t pid;468field:int prio;469field:int success;470field:int target_cpu;471----472473The handler function for this event would be defined as:474475----476def sched__sched_wakeup(event_name, context, common_cpu, common_secs,477common_nsecs, common_pid, common_comm,478comm, pid, prio, success, target_cpu):479pass480----481482The handler function takes the form subsystem__event_name.483484The common_* arguments in the handler's argument list are the set of485arguments passed to all event handlers; some of the fields correspond486to the common_* fields in the format file, but some are synthesized,487and some of the common_* fields aren't common enough to to be passed488to every event as arguments but are available as library functions.489490Here's a brief description of each of the invariant event args:491492event_name the name of the event as text493context an opaque 'cookie' used in calls back into perf494common_cpu the cpu the event occurred on495common_secs the secs portion of the event timestamp496common_nsecs the nsecs portion of the event timestamp497common_pid the pid of the current task498common_comm the name of the current process499500All of the remaining fields in the event's format file have501counterparts as handler function arguments of the same name, as can be502seen in the example above.503504The above provides the basics needed to directly access every field of505every event in a trace, which covers 90% of what you need to know to506write a useful trace script. The sections below cover the rest.507508SCRIPT LAYOUT509-------------510511Every perf script Python script should start by setting up a Python512module search path and 'import'ing a few support modules (see module513descriptions below):514515----516import os517import sys518519sys.path.append(os.environ['PERF_EXEC_PATH'] + \520'/scripts/python/perf-script-Util/lib/Perf/Trace')521522from perf_trace_context import *523from Core import *524----525526The rest of the script can contain handler functions and support527functions in any order.528529Aside from the event handler functions discussed above, every script530can implement a set of optional functions:531532*trace_begin*, if defined, is called before any event is processed and533gives scripts a chance to do setup tasks:534535----536def trace_begin:537pass538----539540*trace_end*, if defined, is called after all events have been541processed and gives scripts a chance to do end-of-script tasks, such542as display results:543544----545def trace_end:546pass547----548549*trace_unhandled*, if defined, is called after for any event that550doesn't have a handler explicitly defined for it. The standard set551of common arguments are passed into it:552553----554def trace_unhandled(event_name, context, common_cpu, common_secs,555common_nsecs, common_pid, common_comm):556pass557----558559The remaining sections provide descriptions of each of the available560built-in perf script Python modules and their associated functions.561562AVAILABLE MODULES AND FUNCTIONS563-------------------------------564565The following sections describe the functions and variables available566via the various perf script Python modules. To use the functions and567variables from the given module, add the corresponding 'from XXXX568import' line to your perf script script.569570Core.py Module571~~~~~~~~~~~~~~572573These functions provide some essential functions to user scripts.574575The *flag_str* and *symbol_str* functions provide human-readable576strings for flag and symbolic fields. These correspond to the strings577and values parsed from the 'print fmt' fields of the event format578files:579580flag_str(event_name, field_name, field_value) - returns the string represention corresponding to field_value for the flag field field_name of event event_name581symbol_str(event_name, field_name, field_value) - returns the string represention corresponding to field_value for the symbolic field field_name of event event_name582583The *autodict* function returns a special kind of Python584dictionary that implements Perl's 'autovivifying' hashes in Python585i.e. with autovivifying hashes, you can assign nested hash values586without having to go to the trouble of creating intermediate levels if587they don't exist.588589autodict() - returns an autovivifying dictionary instance590591592perf_trace_context Module593~~~~~~~~~~~~~~~~~~~~~~~~~594595Some of the 'common' fields in the event format file aren't all that596common, but need to be made accessible to user scripts nonetheless.597598perf_trace_context defines a set of functions that can be used to599access this data in the context of the current event. Each of these600functions expects a context variable, which is the same as the601context variable passed into every event handler as the second602argument.603604common_pc(context) - returns common_preempt count for the current event605common_flags(context) - returns common_flags for the current event606common_lock_depth(context) - returns common_lock_depth for the current event607608Util.py Module609~~~~~~~~~~~~~~610611Various utility functions for use with perf script:612613nsecs(secs, nsecs) - returns total nsecs given secs/nsecs pair614nsecs_secs(nsecs) - returns whole secs portion given nsecs615nsecs_nsecs(nsecs) - returns nsecs remainder given nsecs616nsecs_str(nsecs) - returns printable string in the form secs.nsecs617avg(total, n) - returns average given a sum and a total number of values618619SEE ALSO620--------621linkperf:perf-script[1]622623624