__init__.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. """
  4. Machinery for generating tracing-related intermediate files.
  5. """
  6. __author__ = "Lluís Vilanova <vilanova@ac.upc.edu>"
  7. __copyright__ = "Copyright 2012, Lluís Vilanova <vilanova@ac.upc.edu>"
  8. __license__ = "GPL version 2 or (at your option) any later version"
  9. __maintainer__ = "Stefan Hajnoczi"
  10. __email__ = "stefanha@linux.vnet.ibm.com"
  11. import re
  12. import sys
  13. import tracetool.format
  14. import tracetool.backend
  15. def error_write(*lines):
  16. """Write a set of error lines."""
  17. sys.stderr.writelines("\n".join(lines) + "\n")
  18. def error(*lines):
  19. """Write a set of error lines and exit."""
  20. error_write(*lines)
  21. sys.exit(1)
  22. def out(*lines, **kwargs):
  23. """Write a set of output lines.
  24. You can use kwargs as a shorthand for mapping variables when formating all
  25. the strings in lines.
  26. """
  27. lines = [ l % kwargs for l in lines ]
  28. sys.stdout.writelines("\n".join(lines) + "\n")
  29. class Arguments:
  30. """Event arguments description."""
  31. def __init__(self, args):
  32. """
  33. Parameters
  34. ----------
  35. args :
  36. List of (type, name) tuples.
  37. """
  38. self._args = args
  39. @staticmethod
  40. def build(arg_str):
  41. """Build and Arguments instance from an argument string.
  42. Parameters
  43. ----------
  44. arg_str : str
  45. String describing the event arguments.
  46. """
  47. res = []
  48. for arg in arg_str.split(","):
  49. arg = arg.strip()
  50. if arg == 'void':
  51. continue
  52. if '*' in arg:
  53. arg_type, identifier = arg.rsplit('*', 1)
  54. arg_type += '*'
  55. identifier = identifier.strip()
  56. else:
  57. arg_type, identifier = arg.rsplit(None, 1)
  58. res.append((arg_type, identifier))
  59. return Arguments(res)
  60. def __iter__(self):
  61. """Iterate over the (type, name) pairs."""
  62. return iter(self._args)
  63. def __len__(self):
  64. """Number of arguments."""
  65. return len(self._args)
  66. def __str__(self):
  67. """String suitable for declaring function arguments."""
  68. if len(self._args) == 0:
  69. return "void"
  70. else:
  71. return ", ".join([ " ".join([t, n]) for t,n in self._args ])
  72. def __repr__(self):
  73. """Evaluable string representation for this object."""
  74. return "Arguments(\"%s\")" % str(self)
  75. def names(self):
  76. """List of argument names."""
  77. return [ name for _, name in self._args ]
  78. def types(self):
  79. """List of argument types."""
  80. return [ type_ for type_, _ in self._args ]
  81. class Event(object):
  82. """Event description.
  83. Attributes
  84. ----------
  85. name : str
  86. The event name.
  87. fmt : str
  88. The event format string.
  89. properties : set(str)
  90. Properties of the event.
  91. args : Arguments
  92. The event arguments.
  93. """
  94. _CRE = re.compile("((?P<props>.*)\s+)?(?P<name>[^(\s]+)\((?P<args>[^)]*)\)\s*(?P<fmt>\".*)?")
  95. _VALID_PROPS = set(["disable"])
  96. def __init__(self, name, props, fmt, args):
  97. """
  98. Parameters
  99. ----------
  100. name : string
  101. Event name.
  102. props : list of str
  103. Property names.
  104. fmt : str
  105. Event printing format.
  106. args : Arguments
  107. Event arguments.
  108. """
  109. self.name = name
  110. self.properties = props
  111. self.fmt = fmt
  112. self.args = args
  113. unknown_props = set(self.properties) - self._VALID_PROPS
  114. if len(unknown_props) > 0:
  115. raise ValueError("Unknown properties: %s" % ", ".join(unknown_props))
  116. @staticmethod
  117. def build(line_str):
  118. """Build an Event instance from a string.
  119. Parameters
  120. ----------
  121. line_str : str
  122. Line describing the event.
  123. """
  124. m = Event._CRE.match(line_str)
  125. assert m is not None
  126. groups = m.groupdict('')
  127. name = groups["name"]
  128. props = groups["props"].split()
  129. fmt = groups["fmt"]
  130. args = Arguments.build(groups["args"])
  131. return Event(name, props, fmt, args)
  132. def __repr__(self):
  133. """Evaluable string representation for this object."""
  134. return "Event('%s %s(%s) %s')" % (" ".join(self.properties),
  135. self.name,
  136. self.args,
  137. self.fmt)
  138. def _read_events(fobj):
  139. res = []
  140. for line in fobj:
  141. if not line.strip():
  142. continue
  143. if line.lstrip().startswith('#'):
  144. continue
  145. res.append(Event.build(line))
  146. return res
  147. class TracetoolError (Exception):
  148. """Exception for calls to generate."""
  149. pass
  150. def try_import(mod_name, attr_name = None, attr_default = None):
  151. """Try to import a module and get an attribute from it.
  152. Parameters
  153. ----------
  154. mod_name : str
  155. Module name.
  156. attr_name : str, optional
  157. Name of an attribute in the module.
  158. attr_default : optional
  159. Default value if the attribute does not exist in the module.
  160. Returns
  161. -------
  162. A pair indicating whether the module could be imported and the module or
  163. object or attribute value.
  164. """
  165. try:
  166. module = __import__(mod_name, globals(), locals(), ["__package__"])
  167. if attr_name is None:
  168. return True, module
  169. return True, getattr(module, str(attr_name), attr_default)
  170. except ImportError:
  171. return False, None
  172. def generate(fevents, format, backend,
  173. binary = None, probe_prefix = None):
  174. """Generate the output for the given (format, backend) pair.
  175. Parameters
  176. ----------
  177. fevents : file
  178. Event description file.
  179. format : str
  180. Output format name.
  181. backend : str
  182. Output backend name.
  183. binary : str or None
  184. See tracetool.backend.dtrace.BINARY.
  185. probe_prefix : str or None
  186. See tracetool.backend.dtrace.PROBEPREFIX.
  187. """
  188. # fix strange python error (UnboundLocalError tracetool)
  189. import tracetool
  190. format = str(format)
  191. if len(format) is 0:
  192. raise TracetoolError("format not set")
  193. mformat = format.replace("-", "_")
  194. if not tracetool.format.exists(mformat):
  195. raise TracetoolError("unknown format: %s" % format)
  196. backend = str(backend)
  197. if len(backend) is 0:
  198. raise TracetoolError("backend not set")
  199. mbackend = backend.replace("-", "_")
  200. if not tracetool.backend.exists(mbackend):
  201. raise TracetoolError("unknown backend: %s" % backend)
  202. if not tracetool.backend.compatible(mbackend, mformat):
  203. raise TracetoolError("backend '%s' not compatible with format '%s'" %
  204. (backend, format))
  205. import tracetool.backend.dtrace
  206. tracetool.backend.dtrace.BINARY = binary
  207. tracetool.backend.dtrace.PROBEPREFIX = probe_prefix
  208. events = _read_events(fevents)
  209. if backend == "nop":
  210. ( e.properies.add("disable") for e in events )
  211. tracetool.format.generate_begin(mformat, events)
  212. tracetool.backend.generate("nop", format,
  213. [ e
  214. for e in events
  215. if "disable" in e.properties ])
  216. tracetool.backend.generate(backend, format,
  217. [ e
  218. for e in events
  219. if "disable" not in e.properties ])
  220. tracetool.format.generate_end(mformat, events)