File: tracecmd.py

package info (click to toggle)
trace-cmd 3.3-2
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 1,992 kB
  • sloc: ansic: 33,558; makefile: 967; python: 604; sh: 400
file content (255 lines) | stat: -rw-r--r-- 7,831 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
#!/usr/bin/python3
#
# Copyright (C) International Business Machines  Corp., 2009
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# 2009-Dec-17:	Initial version by Darren Hart <[email protected]>
#

from functools import cached_property
from collections.abc import Mapping
from itertools import chain
from ctracecmd import *

"""
Python interface to the tracecmd library for parsing ftrace traces

Python tracecmd applications should be written to this interface. It will be
updated as the tracecmd C API changes and try to minimze the impact to python
applications. The ctracecmd Python module is automatically generated using SWIG
and it is recommended applications not use it directly.

TODO: consider a complete class hierarchy of ftrace events...
"""

class Event(Mapping):
    """
    This class can be used to access event data
    according to an event's record and format.
    """
    def __init__(self, pevent, record, format):
        self._pevent = pevent
        self._record = record
        self._format = format

    def __str__(self):
        return "%d.	d CPU%d %s: pid=%d comm=%s type=%d" % \
               (self.ts/1000000000, self.ts00000000, self.cpu, self.name,
                self.num_field("common_pid"), self.comm, self.type)

    def __del__(self):
        tracecmd_free_record(self._record)

    def __getitem__(self, n):
        if n.startswith('common_'):
            f = tep_find_common_field(self._format, n)
        else:
            f = tep_find_field(self._format, n)
        if f is None:
            raise KeyError("no field '%s'" % n)
        return Field(self._record, f)

    def __iter__(self):
        yield from chain(self.common_keys, self.keys)

    def __len__(self):
        return len(self.common_keys)   len(self.keys)

    @cached_property
    def common_keys(self):
        return py_format_get_keys(self._format, True)

    @cached_property
    def keys(self):
        return py_format_get_keys(self._format, False)

    @cached_property
    def comm(self):
        return tep_data_comm_from_pid(self._pevent, self.pid)

    @cached_property
    def cpu(self):
        return tep_record_cpu_get(self._record)

    @cached_property
    def name(self):
        return tep_event_name_get(self._format)

    @cached_property
    def pid(self):
        return tep_data_pid(self._pevent, self._record)

    @cached_property
    def ts(self):
        return tep_record_ts_get(self._record)

    @cached_property
    def type(self):
        return tep_data_type(self._pevent, self._record)

    def num_field(self, name):
        f = tep_find_any_field(self._format, name)
        if f is None:
            return None
        ret, val = tep_read_number_field(f, tep_record_data_get(self._record))
        if ret:
            return None
        return val

    def str_field(self, name):
        f = tep_find_any_field(self._format, name)
        if f is None:
            return None
        return py_field_get_str(f, self._record)

    def stack_field(self, long_size):
        return py_field_get_stack(self._pevent, self._record, self._format,
                                  long_size)

class TraceSeq(object):
    def __init__(self, trace_seq):
        self._trace_seq = trace_seq

    def puts(self, s):
        return trace_seq_puts(self._trace_seq, s)

class FieldError(Exception):
    pass

class Field(object):
    def __init__(self, record, field):
        self._record = record
        self._field = field

    @cached_property
    def data(self):
        return py_field_get_data(self._field, self._record)

    def __long__(self):
        ret, val =  tep_read_number_field(self._field,
                                          tep_record_data_get(self._record))
        if ret:
            raise FieldError("Not a number field")
        return val
    __int__ = __long__

    def __str__(self):
        return py_field_get_str(self._field, self._record)

class PEvent(object):
    def __init__(self, pevent):
        self._pevent = pevent

    def _handler(self, cb, s, record, event_fmt):
        return cb(TraceSeq(s), Event(self._pevent, record, event_fmt))

    def register_event_handler(self, subsys, event_name, callback):
        l = lambda s, r, e: self._handler(callback, s, r, e)

        py_pevent_register_event_handler(
                  self._pevent, -1, subsys, event_name, l)

    @cached_property
    def file_endian(self):
        if tep_is_file_bigendian(self._pevent):
            return '>'
        return '<'


class FileFormatError(Exception):
    pass

class Trace(object):
    """
    Trace object represents the trace file it is created with.

    The Trace object aggregates the tracecmd structures and functions that are
    used to manage the trace and extract events from it.
    """
    def __init__(self, filename):
        self._handle = tracecmd_open(filename, 0)
        self._pevent = tracecmd_get_tep(self._handle)

    @cached_property
    def cpus(self):
        return tracecmd_cpus(self._handle)

    @cached_property
    def long_size(self):
        return tracecmd_long_size(self._handle)

    def read_event(self, cpu):
        rec = tracecmd_read_data(self._handle, cpu)
        if rec:
            type = tep_data_type(self._pevent, rec)
            format = tep_find_event(self._pevent, type)
            # rec ownership goes over to Event instance
            return Event(self._pevent, rec, format)
        return None

    def read_event_at(self, offset):
        res = tracecmd_read_at(self._handle, offset)
        # SWIG only returns the CPU if the record is None for some reason
        if isinstance(res, int):
            return None
        rec, cpu = res
        type = tep_data_type(self._pevent, rec)
        format = tep_find_event(self._pevent, type)
        # rec ownership goes over to Event instance
        return Event(self._pevent, rec, format)

    def read_next_event(self):
        res = tracecmd_read_next_data(self._handle)
        if isinstance(res, int):
            return None
        rec, cpu = res
        type = tep_data_type(self._pevent, rec)
        format = tep_find_event(self._pevent, type)
        return Event(self._pevent, rec, format)

    def peek_event(self, cpu):
        rec = tracecmd_peek_data_ref(self._handle, cpu)
        if rec is None:
            return None
        type = tep_data_type(self._pevent, rec)
        format = tep_find_event(self._pevent, type)
        # rec ownership goes over to Event instance
        return Event(self._pevent, rec, format)


# Basic builtin test, execute module directly
if __name__ == "__main__":
    t = Trace("trace.dat")
    print(f"Trace contains data for {t.cpus} cpus, long has {t.long_size} bytes")

    print("Peek the first event on CPU0")
    print("\t%s" % (t.peek_event(0)))

    print("Events by CPUs")
    for cpu in range(0, t.cpus):
        print("CPU %d" % (cpu))
        ev = t.read_event(cpu)
        while ev:
            print("\t%s" % (ev))
            ev = t.read_event(cpu)

    t = Trace("trace.dat")

    print("Events by time")
    ev = t.read_next_event()
    while ev:
        print("\t%s" % (ev))
        ev = t.read_next_event()