wait.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. # -*- encoding: utf-8 -*-
  2. #
  3. # Copyright 2016–2021 Julien Danjou
  4. # Copyright 2016 Joshua Harlow
  5. # Copyright 2013-2014 Ray Holder
  6. #
  7. # Licensed under the Apache License, Version 2.0 (the "License");
  8. # you may not use this file except in compliance with the License.
  9. # You may obtain a copy of the License at
  10. #
  11. # http://www.apache.org/licenses/LICENSE-2.0
  12. #
  13. # Unless required by applicable law or agreed to in writing, software
  14. # distributed under the License is distributed on an "AS IS" BASIS,
  15. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. # See the License for the specific language governing permissions and
  17. # limitations under the License.
  18. import abc
  19. import random
  20. from pip._vendor import six
  21. from pip._vendor.tenacity import _utils
  22. @six.add_metaclass(abc.ABCMeta)
  23. class wait_base(object):
  24. """Abstract base class for wait strategies."""
  25. @abc.abstractmethod
  26. def __call__(self, retry_state):
  27. pass
  28. def __add__(self, other):
  29. return wait_combine(self, other)
  30. def __radd__(self, other):
  31. # make it possible to use multiple waits with the built-in sum function
  32. if other == 0:
  33. return self
  34. return self.__add__(other)
  35. class wait_fixed(wait_base):
  36. """Wait strategy that waits a fixed amount of time between each retry."""
  37. def __init__(self, wait):
  38. self.wait_fixed = wait
  39. def __call__(self, retry_state):
  40. return self.wait_fixed
  41. class wait_none(wait_fixed):
  42. """Wait strategy that doesn't wait at all before retrying."""
  43. def __init__(self):
  44. super(wait_none, self).__init__(0)
  45. class wait_random(wait_base):
  46. """Wait strategy that waits a random amount of time between min/max."""
  47. def __init__(self, min=0, max=1): # noqa
  48. self.wait_random_min = min
  49. self.wait_random_max = max
  50. def __call__(self, retry_state):
  51. return self.wait_random_min + (
  52. random.random() * (self.wait_random_max - self.wait_random_min)
  53. )
  54. class wait_combine(wait_base):
  55. """Combine several waiting strategies."""
  56. def __init__(self, *strategies):
  57. self.wait_funcs = strategies
  58. def __call__(self, retry_state):
  59. return sum(x(retry_state=retry_state) for x in self.wait_funcs)
  60. class wait_chain(wait_base):
  61. """Chain two or more waiting strategies.
  62. If all strategies are exhausted, the very last strategy is used
  63. thereafter.
  64. For example::
  65. @retry(wait=wait_chain(*[wait_fixed(1) for i in range(3)] +
  66. [wait_fixed(2) for j in range(5)] +
  67. [wait_fixed(5) for k in range(4)))
  68. def wait_chained():
  69. print("Wait 1s for 3 attempts, 2s for 5 attempts and 5s
  70. thereafter.")
  71. """
  72. def __init__(self, *strategies):
  73. self.strategies = strategies
  74. def __call__(self, retry_state):
  75. wait_func_no = min(max(retry_state.attempt_number, 1), len(self.strategies))
  76. wait_func = self.strategies[wait_func_no - 1]
  77. return wait_func(retry_state=retry_state)
  78. class wait_incrementing(wait_base):
  79. """Wait an incremental amount of time after each attempt.
  80. Starting at a starting value and incrementing by a value for each attempt
  81. (and restricting the upper limit to some maximum value).
  82. """
  83. def __init__(self, start=0, increment=100, max=_utils.MAX_WAIT): # noqa
  84. self.start = start
  85. self.increment = increment
  86. self.max = max
  87. def __call__(self, retry_state):
  88. result = self.start + (self.increment * (retry_state.attempt_number - 1))
  89. return max(0, min(result, self.max))
  90. class wait_exponential(wait_base):
  91. """Wait strategy that applies exponential backoff.
  92. It allows for a customized multiplier and an ability to restrict the
  93. upper and lower limits to some maximum and minimum value.
  94. The intervals are fixed (i.e. there is no jitter), so this strategy is
  95. suitable for balancing retries against latency when a required resource is
  96. unavailable for an unknown duration, but *not* suitable for resolving
  97. contention between multiple processes for a shared resource. Use
  98. wait_random_exponential for the latter case.
  99. """
  100. def __init__(self, multiplier=1, max=_utils.MAX_WAIT, exp_base=2, min=0): # noqa
  101. self.multiplier = multiplier
  102. self.min = min
  103. self.max = max
  104. self.exp_base = exp_base
  105. def __call__(self, retry_state):
  106. try:
  107. exp = self.exp_base ** (retry_state.attempt_number - 1)
  108. result = self.multiplier * exp
  109. except OverflowError:
  110. return self.max
  111. return max(max(0, self.min), min(result, self.max))
  112. class wait_random_exponential(wait_exponential):
  113. """Random wait with exponentially widening window.
  114. An exponential backoff strategy used to mediate contention between multiple
  115. uncoordinated processes for a shared resource in distributed systems. This
  116. is the sense in which "exponential backoff" is meant in e.g. Ethernet
  117. networking, and corresponds to the "Full Jitter" algorithm described in
  118. this blog post:
  119. https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/
  120. Each retry occurs at a random time in a geometrically expanding interval.
  121. It allows for a custom multiplier and an ability to restrict the upper
  122. limit of the random interval to some maximum value.
  123. Example::
  124. wait_random_exponential(multiplier=0.5, # initial window 0.5s
  125. max=60) # max 60s timeout
  126. When waiting for an unavailable resource to become available again, as
  127. opposed to trying to resolve contention for a shared resource, the
  128. wait_exponential strategy (which uses a fixed interval) may be preferable.
  129. """
  130. def __call__(self, retry_state):
  131. high = super(wait_random_exponential, self).__call__(retry_state=retry_state)
  132. return random.uniform(0, high)