Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 
 
 
 

238 строки
8.8 KiB

  1. # Copyright 2018 New Vector Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import functools
  15. import sys
  16. from typing import Any, Callable, Generator, List, TypeVar, cast
  17. from typing_extensions import ParamSpec
  18. from twisted.internet import defer
  19. from twisted.internet.defer import Deferred
  20. from twisted.python.failure import Failure
  21. # Tracks if we've already patched inlineCallbacks
  22. _already_patched = False
  23. T = TypeVar("T")
  24. P = ParamSpec("P")
  25. def do_patch() -> None:
  26. """
  27. Patch defer.inlineCallbacks so that it checks the state of the logcontext on exit
  28. """
  29. from synapse.logging.context import current_context
  30. global _already_patched
  31. orig_inline_callbacks = defer.inlineCallbacks
  32. if _already_patched:
  33. return
  34. def new_inline_callbacks(
  35. f: Callable[P, Generator["Deferred[object]", object, T]]
  36. ) -> Callable[P, "Deferred[T]"]:
  37. @functools.wraps(f)
  38. def wrapped(*args: P.args, **kwargs: P.kwargs) -> "Deferred[T]":
  39. start_context = current_context()
  40. changes: List[str] = []
  41. orig: Callable[P, "Deferred[T]"] = orig_inline_callbacks(
  42. _check_yield_points(f, changes)
  43. )
  44. try:
  45. res: "Deferred[T]" = orig(*args, **kwargs)
  46. except Exception:
  47. if current_context() != start_context:
  48. for err in changes:
  49. print(err, file=sys.stderr)
  50. err = "%s changed context from %s to %s on exception" % (
  51. f,
  52. start_context,
  53. current_context(),
  54. )
  55. print(err, file=sys.stderr)
  56. raise Exception(err)
  57. raise
  58. if not isinstance(res, Deferred) or res.called:
  59. if current_context() != start_context:
  60. for err in changes:
  61. print(err, file=sys.stderr)
  62. err = "Completed %s changed context from %s to %s" % (
  63. f,
  64. start_context,
  65. current_context(),
  66. )
  67. # print the error to stderr because otherwise all we
  68. # see in travis-ci is the 500 error
  69. print(err, file=sys.stderr)
  70. raise Exception(err)
  71. return res
  72. if current_context():
  73. err = (
  74. "%s returned incomplete deferred in non-sentinel context "
  75. "%s (start was %s)"
  76. ) % (f, current_context(), start_context)
  77. print(err, file=sys.stderr)
  78. raise Exception(err)
  79. def check_ctx(r: T) -> T:
  80. if current_context() != start_context:
  81. for err in changes:
  82. print(err, file=sys.stderr)
  83. err = "%s completion of %s changed context from %s to %s" % (
  84. "Failure" if isinstance(r, Failure) else "Success",
  85. f,
  86. start_context,
  87. current_context(),
  88. )
  89. print(err, file=sys.stderr)
  90. raise Exception(err)
  91. return r
  92. res.addBoth(check_ctx)
  93. return res
  94. return wrapped
  95. defer.inlineCallbacks = new_inline_callbacks
  96. _already_patched = True
  97. def _check_yield_points(
  98. f: Callable[P, Generator["Deferred[object]", object, T]],
  99. changes: List[str],
  100. ) -> Callable:
  101. """Wraps a generator that is about to be passed to defer.inlineCallbacks
  102. checking that after every yield the log contexts are correct.
  103. It's perfectly valid for log contexts to change within a function, e.g. due
  104. to new Measure blocks, so such changes are added to the given `changes`
  105. list instead of triggering an exception.
  106. Args:
  107. f: generator function to wrap
  108. changes: A list of strings detailing how the contexts
  109. changed within a function.
  110. Returns:
  111. function
  112. """
  113. from synapse.logging.context import current_context
  114. @functools.wraps(f)
  115. def check_yield_points_inner(
  116. *args: P.args, **kwargs: P.kwargs
  117. ) -> Generator["Deferred[object]", object, T]:
  118. gen = f(*args, **kwargs)
  119. last_yield_line_no = gen.gi_frame.f_lineno
  120. result: Any = None
  121. while True:
  122. expected_context = current_context()
  123. try:
  124. isFailure = isinstance(result, Failure)
  125. if isFailure:
  126. d = result.throwExceptionIntoGenerator(gen)
  127. else:
  128. d = gen.send(result)
  129. except (StopIteration, defer._DefGen_Return) as e:
  130. if current_context() != expected_context:
  131. # This happens when the context is lost sometime *after* the
  132. # final yield and returning. E.g. we forgot to yield on a
  133. # function that returns a deferred.
  134. #
  135. # We don't raise here as it's perfectly valid for contexts to
  136. # change in a function, as long as it sets the correct context
  137. # on resolving (which is checked separately).
  138. err = (
  139. "Function %r returned and changed context from %s to %s,"
  140. " in %s between %d and end of func"
  141. % (
  142. f.__qualname__,
  143. expected_context,
  144. current_context(),
  145. f.__code__.co_filename,
  146. last_yield_line_no,
  147. )
  148. )
  149. changes.append(err)
  150. # The `StopIteration` or `_DefGen_Return` contains the return value from the
  151. # generator.
  152. return cast(T, e.value)
  153. frame = gen.gi_frame
  154. if isinstance(d, defer.Deferred) and not d.called:
  155. # This happens if we yield on a deferred that doesn't follow
  156. # the log context rules without wrapping in a `make_deferred_yieldable`.
  157. # We raise here as this should never happen.
  158. if current_context():
  159. err = (
  160. "%s yielded with context %s rather than sentinel,"
  161. " yielded on line %d in %s"
  162. % (
  163. frame.f_code.co_name,
  164. current_context(),
  165. frame.f_lineno,
  166. frame.f_code.co_filename,
  167. )
  168. )
  169. raise Exception(err)
  170. # the wrapped function yielded a Deferred: yield it back up to the parent
  171. # inlineCallbacks().
  172. try:
  173. result = yield d
  174. except Exception:
  175. # this will fish an earlier Failure out of the stack where possible, and
  176. # thus is preferable to passing in an exception to the Failure
  177. # constructor, since it results in less stack-mangling.
  178. result = Failure()
  179. if current_context() != expected_context:
  180. # This happens because the context is lost sometime *after* the
  181. # previous yield and *after* the current yield. E.g. the
  182. # deferred we waited on didn't follow the rules, or we forgot to
  183. # yield on a function between the two yield points.
  184. #
  185. # We don't raise here as its perfectly valid for contexts to
  186. # change in a function, as long as it sets the correct context
  187. # on resolving (which is checked separately).
  188. err = (
  189. "%s changed context from %s to %s, happened between lines %d and %d in %s"
  190. % (
  191. frame.f_code.co_name,
  192. expected_context,
  193. current_context(),
  194. last_yield_line_no,
  195. frame.f_lineno,
  196. frame.f_code.co_filename,
  197. )
  198. )
  199. changes.append(err)
  200. last_yield_line_no = frame.f_lineno
  201. return check_yield_points_inner