utils.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. import os
  2. from collections import deque
  3. from sentry_sdk._compat import PY311
  4. from sentry_sdk.utils import filename_for_module
  5. from typing import TYPE_CHECKING
  6. if TYPE_CHECKING:
  7. from sentry_sdk._lru_cache import LRUCache
  8. from types import FrameType
  9. from typing import Deque
  10. from typing import List
  11. from typing import Optional
  12. from typing import Sequence
  13. from typing import Tuple
  14. from typing_extensions import TypedDict
  15. ThreadId = str
  16. ProcessedStack = List[int]
  17. ProcessedFrame = TypedDict(
  18. "ProcessedFrame",
  19. {
  20. "abs_path": str,
  21. "filename": Optional[str],
  22. "function": str,
  23. "lineno": int,
  24. "module": Optional[str],
  25. },
  26. )
  27. ProcessedThreadMetadata = TypedDict(
  28. "ProcessedThreadMetadata",
  29. {"name": str},
  30. )
  31. FrameId = Tuple[
  32. str, # abs_path
  33. int, # lineno
  34. str, # function
  35. ]
  36. FrameIds = Tuple[FrameId, ...]
  37. # The exact value of this id is not very meaningful. The purpose
  38. # of this id is to give us a compact and unique identifier for a
  39. # raw stack that can be used as a key to a dictionary so that it
  40. # can be used during the sampled format generation.
  41. StackId = Tuple[int, int]
  42. ExtractedStack = Tuple[StackId, FrameIds, List[ProcessedFrame]]
  43. ExtractedSample = Sequence[Tuple[ThreadId, ExtractedStack]]
  44. # The default sampling frequency to use. This is set at 101 in order to
  45. # mitigate the effects of lockstep sampling.
  46. DEFAULT_SAMPLING_FREQUENCY = 101
  47. # We want to impose a stack depth limit so that samples aren't too large.
  48. MAX_STACK_DEPTH = 128
  49. if PY311:
  50. def get_frame_name(frame: "FrameType") -> str:
  51. return frame.f_code.co_qualname
  52. else:
  53. def get_frame_name(frame: "FrameType") -> str:
  54. f_code = frame.f_code
  55. co_varnames = f_code.co_varnames
  56. # co_name only contains the frame name. If the frame was a method,
  57. # the class name will NOT be included.
  58. name = f_code.co_name
  59. # if it was a method, we can get the class name by inspecting
  60. # the f_locals for the `self` argument
  61. try:
  62. if (
  63. # the co_varnames start with the frame's positional arguments
  64. # and we expect the first to be `self` if its an instance method
  65. co_varnames and co_varnames[0] == "self" and "self" in frame.f_locals
  66. ):
  67. for cls in type(frame.f_locals["self"]).__mro__:
  68. if name in cls.__dict__:
  69. return "{}.{}".format(cls.__name__, name)
  70. except (AttributeError, ValueError):
  71. pass
  72. # if it was a class method, (decorated with `@classmethod`)
  73. # we can get the class name by inspecting the f_locals for the `cls` argument
  74. try:
  75. if (
  76. # the co_varnames start with the frame's positional arguments
  77. # and we expect the first to be `cls` if its a class method
  78. co_varnames and co_varnames[0] == "cls" and "cls" in frame.f_locals
  79. ):
  80. for cls in frame.f_locals["cls"].__mro__:
  81. if name in cls.__dict__:
  82. return "{}.{}".format(cls.__name__, name)
  83. except (AttributeError, ValueError):
  84. pass
  85. # nothing we can do if it is a staticmethod (decorated with @staticmethod)
  86. # we've done all we can, time to give up and return what we have
  87. return name
  88. def frame_id(raw_frame: "FrameType") -> "FrameId":
  89. return (raw_frame.f_code.co_filename, raw_frame.f_lineno, get_frame_name(raw_frame))
  90. def extract_frame(fid: "FrameId", raw_frame: "FrameType", cwd: str) -> "ProcessedFrame":
  91. abs_path = raw_frame.f_code.co_filename
  92. try:
  93. module = raw_frame.f_globals["__name__"]
  94. except Exception:
  95. module = None
  96. # namedtuples can be many times slower when initialing
  97. # and accessing attribute so we opt to use a tuple here instead
  98. return {
  99. # This originally was `os.path.abspath(abs_path)` but that had
  100. # a large performance overhead.
  101. #
  102. # According to docs, this is equivalent to
  103. # `os.path.normpath(os.path.join(os.getcwd(), path))`.
  104. # The `os.getcwd()` call is slow here, so we precompute it.
  105. #
  106. # Additionally, since we are using normalized path already,
  107. # we skip calling `os.path.normpath` entirely.
  108. "abs_path": os.path.join(cwd, abs_path),
  109. "module": module,
  110. "filename": filename_for_module(module, abs_path) or None,
  111. "function": fid[2],
  112. "lineno": raw_frame.f_lineno,
  113. }
  114. def extract_stack(
  115. raw_frame: "Optional[FrameType]",
  116. cache: "LRUCache",
  117. cwd: str,
  118. max_stack_depth: int = MAX_STACK_DEPTH,
  119. ) -> "ExtractedStack":
  120. """
  121. Extracts the stack starting the specified frame. The extracted stack
  122. assumes the specified frame is the top of the stack, and works back
  123. to the bottom of the stack.
  124. In the event that the stack is more than `MAX_STACK_DEPTH` frames deep,
  125. only the first `MAX_STACK_DEPTH` frames will be returned.
  126. """
  127. raw_frames: "Deque[FrameType]" = deque(maxlen=max_stack_depth)
  128. while raw_frame is not None:
  129. f_back = raw_frame.f_back
  130. raw_frames.append(raw_frame)
  131. raw_frame = f_back
  132. frame_ids = tuple(frame_id(raw_frame) for raw_frame in raw_frames)
  133. frames = []
  134. for i, fid in enumerate(frame_ids):
  135. frame = cache.get(fid)
  136. if frame is None:
  137. frame = extract_frame(fid, raw_frames[i], cwd)
  138. cache.set(fid, frame)
  139. frames.append(frame)
  140. # Instead of mapping the stack into frame ids and hashing
  141. # that as a tuple, we can directly hash the stack.
  142. # This saves us from having to generate yet another list.
  143. # Additionally, using the stack as the key directly is
  144. # costly because the stack can be large, so we pre-hash
  145. # the stack, and use the hash as the key as this will be
  146. # needed a few times to improve performance.
  147. #
  148. # To Reduce the likelihood of hash collisions, we include
  149. # the stack depth. This means that only stacks of the same
  150. # depth can suffer from hash collisions.
  151. stack_id = len(raw_frames), hash(frame_ids)
  152. return stack_id, frame_ids, frames