__init__.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014-2016 OpenMarket Ltd
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import logging
  16. import re
  17. import attr
  18. from twisted.internet import defer, task
  19. from synapse.logging import context
  20. logger = logging.getLogger(__name__)
  21. def unwrapFirstError(failure):
  22. # defer.gatherResults and DeferredLists wrap failures.
  23. failure.trap(defer.FirstError)
  24. return failure.value.subFailure
  25. @attr.s
  26. class Clock(object):
  27. """
  28. A Clock wraps a Twisted reactor and provides utilities on top of it.
  29. Args:
  30. reactor: The Twisted reactor to use.
  31. """
  32. _reactor = attr.ib()
  33. @defer.inlineCallbacks
  34. def sleep(self, seconds):
  35. d = defer.Deferred()
  36. with context.PreserveLoggingContext():
  37. self._reactor.callLater(seconds, d.callback, seconds)
  38. res = yield d
  39. return res
  40. def time(self):
  41. """Returns the current system time in seconds since epoch."""
  42. return self._reactor.seconds()
  43. def time_msec(self):
  44. """Returns the current system time in miliseconds since epoch."""
  45. return int(self.time() * 1000)
  46. def looping_call(self, f, msec, *args, **kwargs):
  47. """Call a function repeatedly.
  48. Waits `msec` initially before calling `f` for the first time.
  49. Note that the function will be called with no logcontext, so if it is anything
  50. other than trivial, you probably want to wrap it in run_as_background_process.
  51. Args:
  52. f(function): The function to call repeatedly.
  53. msec(float): How long to wait between calls in milliseconds.
  54. *args: Postional arguments to pass to function.
  55. **kwargs: Key arguments to pass to function.
  56. """
  57. call = task.LoopingCall(f, *args, **kwargs)
  58. call.clock = self._reactor
  59. d = call.start(msec / 1000.0, now=False)
  60. d.addErrback(log_failure, "Looping call died", consumeErrors=False)
  61. return call
  62. def call_later(self, delay, callback, *args, **kwargs):
  63. """Call something later
  64. Note that the function will be called with no logcontext, so if it is anything
  65. other than trivial, you probably want to wrap it in run_as_background_process.
  66. Args:
  67. delay(float): How long to wait in seconds.
  68. callback(function): Function to call
  69. *args: Postional arguments to pass to function.
  70. **kwargs: Key arguments to pass to function.
  71. """
  72. def wrapped_callback(*args, **kwargs):
  73. with context.PreserveLoggingContext():
  74. callback(*args, **kwargs)
  75. with context.PreserveLoggingContext():
  76. return self._reactor.callLater(delay, wrapped_callback, *args, **kwargs)
  77. def cancel_call_later(self, timer, ignore_errs=False):
  78. try:
  79. timer.cancel()
  80. except Exception:
  81. if not ignore_errs:
  82. raise
  83. def log_failure(failure, msg, consumeErrors=True):
  84. """Creates a function suitable for passing to `Deferred.addErrback` that
  85. logs any failures that occur.
  86. Args:
  87. msg (str): Message to log
  88. consumeErrors (bool): If true consumes the failure, otherwise passes
  89. on down the callback chain
  90. Returns:
  91. func(Failure)
  92. """
  93. logger.error(
  94. msg, exc_info=(failure.type, failure.value, failure.getTracebackObject())
  95. )
  96. if not consumeErrors:
  97. return failure
  98. def glob_to_regex(glob):
  99. """Converts a glob to a compiled regex object.
  100. The regex is anchored at the beginning and end of the string.
  101. Args:
  102. glob (str)
  103. Returns:
  104. re.RegexObject
  105. """
  106. res = ""
  107. for c in glob:
  108. if c == "*":
  109. res = res + ".*"
  110. elif c == "?":
  111. res = res + "."
  112. else:
  113. res = res + re.escape(c)
  114. # \A anchors at start of string, \Z at end of string
  115. return re.compile(r"\A" + res + r"\Z", re.IGNORECASE)