2 # -*- coding: utf-8 -*-
5 Machinery for generating tracing-related intermediate files.
8 __author__
= "Lluís Vilanova <vilanova@ac.upc.edu>"
9 __copyright__
= "Copyright 2012-2014, Lluís Vilanova <vilanova@ac.upc.edu>"
10 __license__
= "GPL version 2 or (at your option) any later version"
12 __maintainer__
= "Stefan Hajnoczi"
13 __email__
= "stefanha@linux.vnet.ibm.com"
20 import tracetool
.format
21 import tracetool
.backend
24 def error_write(*lines
):
25 """Write a set of error lines."""
26 sys
.stderr
.writelines("\n".join(lines
) + "\n")
29 """Write a set of error lines and exit."""
34 def out(*lines
, **kwargs
):
35 """Write a set of output lines.
37 You can use kwargs as a shorthand for mapping variables when formating all
40 lines
= [ l
% kwargs
for l
in lines
]
41 sys
.stdout
.writelines("\n".join(lines
) + "\n")
45 """Event arguments description."""
47 def __init__(self
, args
):
52 List of (type, name) tuples.
57 """Create a new copy."""
58 return Arguments(list(self
._args
))
62 """Build and Arguments instance from an argument string.
67 String describing the event arguments.
70 for arg
in arg_str
.split(","):
76 arg_type
, identifier
= arg
.rsplit('*', 1)
78 identifier
= identifier
.strip()
80 arg_type
, identifier
= arg
.rsplit(None, 1)
82 res
.append((arg_type
, identifier
))
86 """Iterate over the (type, name) pairs."""
87 return iter(self
._args
)
90 """Number of arguments."""
91 return len(self
._args
)
94 """String suitable for declaring function arguments."""
95 if len(self
._args
) == 0:
98 return ", ".join([ " ".join([t
, n
]) for t
,n
in self
._args
])
101 """Evaluable string representation for this object."""
102 return "Arguments(\"%s\")" % str(self
)
105 """List of argument names."""
106 return [ name
for _
, name
in self
._args
]
109 """List of argument types."""
110 return [ type_
for type_
, _
in self
._args
]
112 def transform(self
, *trans
):
113 """Return a new Arguments instance with transformed types.
115 The types in the resulting Arguments instance are transformed according
116 to tracetool.transform.transform_type.
119 for type_
, name
in self
._args
:
120 res
.append((tracetool
.transform
.transform_type(type_
, *trans
),
122 return Arguments(res
)
126 """Event description.
133 The event format string.
134 properties : set(str)
135 Properties of the event.
140 _CRE
= re
.compile("((?P<props>.*)\s+)?(?P<name>[^(\s]+)\((?P<args>[^)]*)\)\s*(?P<fmt>\".*)?")
142 _VALID_PROPS
= set(["disable"])
144 def __init__(self
, name
, props
, fmt
, args
, orig
=None):
153 Event printing format.
157 Original Event before transformation.
160 self
.properties
= props
165 self
.original
= weakref
.ref(self
)
169 unknown_props
= set(self
.properties
) - self
._VALID
_PROPS
170 if len(unknown_props
) > 0:
171 raise ValueError("Unknown properties: %s"
172 % ", ".join(unknown_props
))
175 """Create a new copy."""
176 return Event(self
.name
, list(self
.properties
), self
.fmt
,
177 self
.args
.copy(), self
)
181 """Build an Event instance from a string.
186 Line describing the event.
188 m
= Event
._CRE
.match(line_str
)
190 groups
= m
.groupdict('')
192 name
= groups
["name"]
193 props
= groups
["props"].split()
195 args
= Arguments
.build(groups
["args"])
197 return Event(name
, props
, fmt
, args
)
200 """Evaluable string representation for this object."""
201 return "Event('%s %s(%s) %s')" % (" ".join(self
.properties
),
206 QEMU_TRACE
= "trace_%(name)s"
208 def api(self
, fmt
=None):
210 fmt
= Event
.QEMU_TRACE
211 return fmt
% {"name": self
.name
}
213 def transform(self
, *trans
):
214 """Return a new Event with transformed Arguments."""
215 return Event(self
.name
,
216 list(self
.properties
),
218 self
.args
.transform(*trans
),
222 def _read_events(fobj
):
227 if line
.lstrip().startswith('#'):
229 res
.append(Event
.build(line
))
233 class TracetoolError (Exception):
234 """Exception for calls to generate."""
238 def try_import(mod_name
, attr_name
=None, attr_default
=None):
239 """Try to import a module and get an attribute from it.
245 attr_name : str, optional
246 Name of an attribute in the module.
247 attr_default : optional
248 Default value if the attribute does not exist in the module.
252 A pair indicating whether the module could be imported and the module or
253 object or attribute value.
256 module
= __import__(mod_name
, globals(), locals(), ["__package__"])
257 if attr_name
is None:
259 return True, getattr(module
, str(attr_name
), attr_default
)
264 def generate(fevents
, format
, backends
,
265 binary
=None, probe_prefix
=None):
266 """Generate the output for the given (format, backends) pair.
271 Event description file.
275 Output backend names.
277 See tracetool.backend.dtrace.BINARY.
278 probe_prefix : str or None
279 See tracetool.backend.dtrace.PROBEPREFIX.
281 # fix strange python error (UnboundLocalError tracetool)
286 raise TracetoolError("format not set")
287 if not tracetool
.format
.exists(format
):
288 raise TracetoolError("unknown format: %s" % format
)
290 if len(backends
) is 0:
291 raise TracetoolError("no backends specified")
292 for backend
in backends
:
293 if not tracetool
.backend
.exists(backend
):
294 raise TracetoolError("unknown backend: %s" % backend
)
295 backend
= tracetool
.backend
.Wrapper(backends
, format
)
297 import tracetool
.backend
.dtrace
298 tracetool
.backend
.dtrace
.BINARY
= binary
299 tracetool
.backend
.dtrace
.PROBEPREFIX
= probe_prefix
301 events
= _read_events(fevents
)
303 tracetool
.format
.generate(events
, format
, backend
)