collector.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  1. # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0
  2. # For details: https://bitbucket.org/ned/coveragepy/src/default/NOTICE.txt
  3. """Raw data collector for coverage.py."""
  4. import os
  5. import sys
  6. from coverage import env
  7. from coverage.backward import litems, range # pylint: disable=redefined-builtin
  8. from coverage.debug import short_stack
  9. from coverage.files import abs_file
  10. from coverage.misc import CoverageException, isolate_module
  11. from coverage.pytracer import PyTracer
  12. os = isolate_module(os)
  13. try:
  14. # Use the C extension code when we can, for speed.
  15. from coverage.tracer import CTracer, CFileDisposition
  16. except ImportError:
  17. # Couldn't import the C extension, maybe it isn't built.
  18. if os.getenv('COVERAGE_TEST_TRACER') == 'c':
  19. # During testing, we use the COVERAGE_TEST_TRACER environment variable
  20. # to indicate that we've fiddled with the environment to test this
  21. # fallback code. If we thought we had a C tracer, but couldn't import
  22. # it, then exit quickly and clearly instead of dribbling confusing
  23. # errors. I'm using sys.exit here instead of an exception because an
  24. # exception here causes all sorts of other noise in unittest.
  25. sys.stderr.write("*** COVERAGE_TEST_TRACER is 'c' but can't import CTracer!\n")
  26. sys.exit(1)
  27. CTracer = None
  28. class FileDisposition(object):
  29. """A simple value type for recording what to do with a file."""
  30. pass
  31. def should_start_context(frame):
  32. """Who-Tests-What hack: Determine whether this frame begins a new who-context."""
  33. fn_name = frame.f_code.co_name
  34. if fn_name.startswith("test"):
  35. return fn_name
  36. class Collector(object):
  37. """Collects trace data.
  38. Creates a Tracer object for each thread, since they track stack
  39. information. Each Tracer points to the same shared data, contributing
  40. traced data points.
  41. When the Collector is started, it creates a Tracer for the current thread,
  42. and installs a function to create Tracers for each new thread started.
  43. When the Collector is stopped, all active Tracers are stopped.
  44. Threads started while the Collector is stopped will never have Tracers
  45. associated with them.
  46. """
  47. # The stack of active Collectors. Collectors are added here when started,
  48. # and popped when stopped. Collectors on the stack are paused when not
  49. # the top, and resumed when they become the top again.
  50. _collectors = []
  51. # The concurrency settings we support here.
  52. SUPPORTED_CONCURRENCIES = set(["greenlet", "eventlet", "gevent", "thread"])
  53. def __init__(self, should_trace, check_include, timid, branch, warn, concurrency):
  54. """Create a collector.
  55. `should_trace` is a function, taking a file name and a frame, and
  56. returning a `coverage.FileDisposition object`.
  57. `check_include` is a function taking a file name and a frame. It returns
  58. a boolean: True if the file should be traced, False if not.
  59. If `timid` is true, then a slower simpler trace function will be
  60. used. This is important for some environments where manipulation of
  61. tracing functions make the faster more sophisticated trace function not
  62. operate properly.
  63. If `branch` is true, then branches will be measured. This involves
  64. collecting data on which statements followed each other (arcs). Use
  65. `get_arc_data` to get the arc data.
  66. `warn` is a warning function, taking a single string message argument
  67. and an optional slug argument which will be a string or None, to be
  68. used if a warning needs to be issued.
  69. `concurrency` is a list of strings indicating the concurrency libraries
  70. in use. Valid values are "greenlet", "eventlet", "gevent", or "thread"
  71. (the default). Of these four values, only one can be supplied. Other
  72. values are ignored.
  73. """
  74. self.should_trace = should_trace
  75. self.check_include = check_include
  76. self.warn = warn
  77. self.branch = branch
  78. self.threading = None
  79. self.origin = short_stack()
  80. self.concur_id_func = None
  81. # We can handle a few concurrency options here, but only one at a time.
  82. these_concurrencies = self.SUPPORTED_CONCURRENCIES.intersection(concurrency)
  83. if len(these_concurrencies) > 1:
  84. raise CoverageException("Conflicting concurrency settings: %s" % concurrency)
  85. self.concurrency = these_concurrencies.pop() if these_concurrencies else ''
  86. try:
  87. if self.concurrency == "greenlet":
  88. import greenlet
  89. self.concur_id_func = greenlet.getcurrent
  90. elif self.concurrency == "eventlet":
  91. import eventlet.greenthread # pylint: disable=import-error,useless-suppression
  92. self.concur_id_func = eventlet.greenthread.getcurrent
  93. elif self.concurrency == "gevent":
  94. import gevent # pylint: disable=import-error,useless-suppression
  95. self.concur_id_func = gevent.getcurrent
  96. elif self.concurrency == "thread" or not self.concurrency:
  97. # It's important to import threading only if we need it. If
  98. # it's imported early, and the program being measured uses
  99. # gevent, then gevent's monkey-patching won't work properly.
  100. import threading
  101. self.threading = threading
  102. else:
  103. raise CoverageException("Don't understand concurrency=%s" % concurrency)
  104. except ImportError:
  105. raise CoverageException(
  106. "Couldn't trace with concurrency=%s, the module isn't installed." % (
  107. self.concurrency,
  108. )
  109. )
  110. # Who-Tests-What is just a hack at the moment, so turn it on with an
  111. # environment variable.
  112. self.wtw = int(os.getenv('COVERAGE_WTW', 0))
  113. self.reset()
  114. if timid:
  115. # Being timid: use the simple Python trace function.
  116. self._trace_class = PyTracer
  117. else:
  118. # Being fast: use the C Tracer if it is available, else the Python
  119. # trace function.
  120. self._trace_class = CTracer or PyTracer
  121. if self._trace_class is CTracer:
  122. self.file_disposition_class = CFileDisposition
  123. self.supports_plugins = True
  124. else:
  125. self.file_disposition_class = FileDisposition
  126. self.supports_plugins = False
  127. def __repr__(self):
  128. return "<Collector at 0x%x: %s>" % (id(self), self.tracer_name())
  129. def tracer_name(self):
  130. """Return the class name of the tracer we're using."""
  131. return self._trace_class.__name__
  132. def _clear_data(self):
  133. """Clear out existing data, but stay ready for more collection."""
  134. self.data.clear()
  135. for tracer in self.tracers:
  136. tracer.reset_activity()
  137. def reset(self):
  138. """Clear collected data, and prepare to collect more."""
  139. # A dictionary mapping file names to dicts with line number keys (if not
  140. # branch coverage), or mapping file names to dicts with line number
  141. # pairs as keys (if branch coverage).
  142. self.data = {}
  143. # A dict mapping contexts to data dictionaries.
  144. self.contexts = {}
  145. self.contexts[None] = self.data
  146. # A dictionary mapping file names to file tracer plugin names that will
  147. # handle them.
  148. self.file_tracers = {}
  149. # The .should_trace_cache attribute is a cache from file names to
  150. # coverage.FileDisposition objects, or None. When a file is first
  151. # considered for tracing, a FileDisposition is obtained from
  152. # Coverage.should_trace. Its .trace attribute indicates whether the
  153. # file should be traced or not. If it should be, a plugin with dynamic
  154. # file names can decide not to trace it based on the dynamic file name
  155. # being excluded by the inclusion rules, in which case the
  156. # FileDisposition will be replaced by None in the cache.
  157. if env.PYPY:
  158. import __pypy__ # pylint: disable=import-error
  159. # Alex Gaynor said:
  160. # should_trace_cache is a strictly growing key: once a key is in
  161. # it, it never changes. Further, the keys used to access it are
  162. # generally constant, given sufficient context. That is to say, at
  163. # any given point _trace() is called, pypy is able to know the key.
  164. # This is because the key is determined by the physical source code
  165. # line, and that's invariant with the call site.
  166. #
  167. # This property of a dict with immutable keys, combined with
  168. # call-site-constant keys is a match for PyPy's module dict,
  169. # which is optimized for such workloads.
  170. #
  171. # This gives a 20% benefit on the workload described at
  172. # https://bitbucket.org/pypy/pypy/issue/1871/10x-slower-than-cpython-under-coverage
  173. self.should_trace_cache = __pypy__.newdict("module")
  174. else:
  175. self.should_trace_cache = {}
  176. # Our active Tracers.
  177. self.tracers = []
  178. self._clear_data()
  179. def _start_tracer(self):
  180. """Start a new Tracer object, and store it in self.tracers."""
  181. tracer = self._trace_class()
  182. tracer.data = self.data
  183. tracer.trace_arcs = self.branch
  184. tracer.should_trace = self.should_trace
  185. tracer.should_trace_cache = self.should_trace_cache
  186. tracer.warn = self.warn
  187. if hasattr(tracer, 'concur_id_func'):
  188. tracer.concur_id_func = self.concur_id_func
  189. elif self.concur_id_func:
  190. raise CoverageException(
  191. "Can't support concurrency=%s with %s, only threads are supported" % (
  192. self.concurrency, self.tracer_name(),
  193. )
  194. )
  195. if hasattr(tracer, 'file_tracers'):
  196. tracer.file_tracers = self.file_tracers
  197. if hasattr(tracer, 'threading'):
  198. tracer.threading = self.threading
  199. if hasattr(tracer, 'check_include'):
  200. tracer.check_include = self.check_include
  201. if self.wtw:
  202. if hasattr(tracer, 'should_start_context'):
  203. tracer.should_start_context = should_start_context
  204. if hasattr(tracer, 'switch_context'):
  205. tracer.switch_context = self.switch_context
  206. fn = tracer.start()
  207. self.tracers.append(tracer)
  208. return fn
  209. # The trace function has to be set individually on each thread before
  210. # execution begins. Ironically, the only support the threading module has
  211. # for running code before the thread main is the tracing function. So we
  212. # install this as a trace function, and the first time it's called, it does
  213. # the real trace installation.
  214. def _installation_trace(self, frame, event, arg):
  215. """Called on new threads, installs the real tracer."""
  216. # Remove ourselves as the trace function.
  217. sys.settrace(None)
  218. # Install the real tracer.
  219. fn = self._start_tracer()
  220. # Invoke the real trace function with the current event, to be sure
  221. # not to lose an event.
  222. if fn:
  223. fn = fn(frame, event, arg)
  224. # Return the new trace function to continue tracing in this scope.
  225. return fn
  226. def start(self):
  227. """Start collecting trace information."""
  228. if self._collectors:
  229. self._collectors[-1].pause()
  230. self.tracers = []
  231. # Check to see whether we had a fullcoverage tracer installed. If so,
  232. # get the stack frames it stashed away for us.
  233. traces0 = []
  234. fn0 = sys.gettrace()
  235. if fn0:
  236. tracer0 = getattr(fn0, '__self__', None)
  237. if tracer0:
  238. traces0 = getattr(tracer0, 'traces', [])
  239. try:
  240. # Install the tracer on this thread.
  241. fn = self._start_tracer()
  242. except:
  243. if self._collectors:
  244. self._collectors[-1].resume()
  245. raise
  246. # If _start_tracer succeeded, then we add ourselves to the global
  247. # stack of collectors.
  248. self._collectors.append(self)
  249. # Replay all the events from fullcoverage into the new trace function.
  250. for args in traces0:
  251. (frame, event, arg), lineno = args
  252. try:
  253. fn(frame, event, arg, lineno=lineno)
  254. except TypeError:
  255. raise Exception("fullcoverage must be run with the C trace function.")
  256. # Install our installation tracer in threading, to jump-start other
  257. # threads.
  258. if self.threading:
  259. self.threading.settrace(self._installation_trace)
  260. def stop(self):
  261. """Stop collecting trace information."""
  262. assert self._collectors
  263. if self._collectors[-1] is not self:
  264. print("self._collectors:")
  265. for c in self._collectors:
  266. print(" {!r}\n{}".format(c, c.origin))
  267. assert self._collectors[-1] is self, (
  268. "Expected current collector to be %r, but it's %r" % (self, self._collectors[-1])
  269. )
  270. self.pause()
  271. # Remove this Collector from the stack, and resume the one underneath
  272. # (if any).
  273. self._collectors.pop()
  274. if self._collectors:
  275. self._collectors[-1].resume()
  276. def pause(self):
  277. """Pause tracing, but be prepared to `resume`."""
  278. for tracer in self.tracers:
  279. tracer.stop()
  280. stats = tracer.get_stats()
  281. if stats:
  282. print("\nCoverage.py tracer stats:")
  283. for k in sorted(stats.keys()):
  284. print("%20s: %s" % (k, stats[k]))
  285. if self.threading:
  286. self.threading.settrace(None)
  287. def resume(self):
  288. """Resume tracing after a `pause`."""
  289. for tracer in self.tracers:
  290. tracer.start()
  291. if self.threading:
  292. self.threading.settrace(self._installation_trace)
  293. else:
  294. self._start_tracer()
  295. def _activity(self):
  296. """Has any activity been traced?
  297. Returns a boolean, True if any trace function was invoked.
  298. """
  299. return any(tracer.activity() for tracer in self.tracers)
  300. def switch_context(self, new_context):
  301. """Who-Tests-What hack: switch to a new who-context."""
  302. # Make a new data dict, or find the existing one, and switch all the
  303. # tracers to use it.
  304. data = self.contexts.setdefault(new_context, {})
  305. for tracer in self.tracers:
  306. tracer.data = data
  307. def save_data(self, covdata):
  308. """Save the collected data to a `CoverageData`.
  309. Returns True if there was data to save, False if not.
  310. """
  311. if not self._activity():
  312. return False
  313. def abs_file_dict(d):
  314. """Return a dict like d, but with keys modified by `abs_file`."""
  315. # The call to litems() ensures that the GIL protects the dictionary
  316. # iterator against concurrent modifications by tracers running
  317. # in other threads. We try three times in case of concurrent
  318. # access, hoping to get a clean copy.
  319. runtime_err = None
  320. for _ in range(3):
  321. try:
  322. items = litems(d)
  323. except RuntimeError as ex:
  324. runtime_err = ex
  325. else:
  326. break
  327. else:
  328. raise runtime_err # pylint: disable=raising-bad-type
  329. return dict((abs_file(k), v) for k, v in items)
  330. if self.branch:
  331. covdata.add_arcs(abs_file_dict(self.data))
  332. else:
  333. covdata.add_lines(abs_file_dict(self.data))
  334. covdata.add_file_tracers(abs_file_dict(self.file_tracers))
  335. if self.wtw:
  336. # Just a hack, so just hack it.
  337. import pprint
  338. out_file = "coverage_wtw_{:06}.py".format(os.getpid())
  339. with open(out_file, "w") as wtw_out:
  340. pprint.pprint(self.contexts, wtw_out)
  341. self._clear_data()
  342. return True