Waiter.php 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. <?php
  2. namespace Aws;
  3. use Aws\Exception\AwsException;
  4. use GuzzleHttp\Promise;
  5. use GuzzleHttp\Promise\PromisorInterface;
  6. use GuzzleHttp\Promise\RejectedPromise;
  7. /**
  8. * "Waiters" are associated with an AWS resource (e.g., EC2 instance), and poll
  9. * that resource and until it is in a particular state.
  10. * The Waiter object produces a promise that is either a.) resolved once the
  11. * waiting conditions are met, or b.) rejected if the waiting conditions cannot
  12. * be met or has exceeded the number of allowed attempts at meeting the
  13. * conditions. You can use waiters in a blocking or non-blocking way, depending
  14. * on whether you call wait() on the promise.
  15. * The configuration for the waiter must include information about the operation
  16. * and the conditions for wait completion.
  17. */
  18. class Waiter implements PromisorInterface
  19. {
  20. /** @var AwsClientInterface Client used to execute each attempt. */
  21. private $client;
  22. /** @var string Name of the waiter. */
  23. private $name;
  24. /** @var array Params to use with each attempt operation. */
  25. private $args;
  26. /** @var array Waiter configuration. */
  27. private $config;
  28. /** @var array Default configuration options. */
  29. private static $defaults = ['initDelay' => 0, 'before' => null];
  30. /** @var array Required configuration options. */
  31. private static $required = [
  32. 'acceptors',
  33. 'delay',
  34. 'maxAttempts',
  35. 'operation',
  36. ];
  37. /**
  38. * The array of configuration options include:
  39. *
  40. * - acceptors: (array) Array of acceptor options
  41. * - delay: (int) Number of seconds to delay between attempts
  42. * - maxAttempts: (int) Maximum number of attempts before failing
  43. * - operation: (string) Name of the API operation to use for polling
  44. * - before: (callable) Invoked before attempts. Accepts command and tries.
  45. *
  46. * @param AwsClientInterface $client Client used to execute commands.
  47. * @param string $name Waiter name.
  48. * @param array $args Command arguments.
  49. * @param array $config Waiter config that overrides defaults.
  50. *
  51. * @throws \InvalidArgumentException if the configuration is incomplete.
  52. */
  53. public function __construct(
  54. AwsClientInterface $client,
  55. $name,
  56. array $args = [],
  57. array $config = []
  58. ) {
  59. $this->client = $client;
  60. $this->name = $name;
  61. $this->args = $args;
  62. // Prepare and validate config.
  63. $this->config = $config + self::$defaults;
  64. foreach (self::$required as $key) {
  65. if (!isset($this->config[$key])) {
  66. throw new \InvalidArgumentException(
  67. 'The provided waiter configuration was incomplete.'
  68. );
  69. }
  70. }
  71. if ($this->config['before'] && !is_callable($this->config['before'])) {
  72. throw new \InvalidArgumentException(
  73. 'The provided "before" callback is not callable.'
  74. );
  75. }
  76. }
  77. public function promise()
  78. {
  79. return Promise\coroutine(function () {
  80. $name = $this->config['operation'];
  81. for ($state = 'retry', $attempt = 1; $state === 'retry'; $attempt++) {
  82. // Execute the operation.
  83. $args = $this->getArgsForAttempt($attempt);
  84. $command = $this->client->getCommand($name, $args);
  85. try {
  86. if ($this->config['before']) {
  87. $this->config['before']($command, $attempt);
  88. }
  89. $result = (yield $this->client->executeAsync($command));
  90. } catch (AwsException $e) {
  91. $result = $e;
  92. }
  93. // Determine the waiter's state and what to do next.
  94. $state = $this->determineState($result);
  95. if ($state === 'success') {
  96. yield $command;
  97. } elseif ($state === 'failed') {
  98. $msg = "The {$this->name} waiter entered a failure state.";
  99. if ($result instanceof \Exception) {
  100. $msg .= ' Reason: ' . $result->getMessage();
  101. }
  102. yield new RejectedPromise(new \RuntimeException($msg));
  103. } elseif ($state === 'retry'
  104. && $attempt >= $this->config['maxAttempts']
  105. ) {
  106. $state = 'failed';
  107. yield new RejectedPromise(new \RuntimeException(
  108. "The {$this->name} waiter failed after attempt #{$attempt}."
  109. ));
  110. }
  111. }
  112. });
  113. }
  114. /**
  115. * Gets the operation arguments for the attempt, including the delay.
  116. *
  117. * @param $attempt Number of the current attempt.
  118. *
  119. * @return mixed integer
  120. */
  121. private function getArgsForAttempt($attempt)
  122. {
  123. $args = $this->args;
  124. // Determine the delay.
  125. $delay = ($attempt === 1)
  126. ? $this->config['initDelay']
  127. : $this->config['delay'];
  128. if (is_callable($delay)) {
  129. $delay = $delay($attempt);
  130. }
  131. // Set the delay. (Note: handlers except delay in milliseconds.)
  132. if (!isset($args['@http'])) {
  133. $args['@http'] = [];
  134. }
  135. $args['@http']['delay'] = $delay * 1000;
  136. return $args;
  137. }
  138. /**
  139. * Determines the state of the waiter attempt, based on the result of
  140. * polling the resource. A waiter can have the state of "success", "failed",
  141. * or "retry".
  142. *
  143. * @param mixed $result
  144. *
  145. * @return string Will be "success", "failed", or "retry"
  146. */
  147. private function determineState($result)
  148. {
  149. foreach ($this->config['acceptors'] as $acceptor) {
  150. $matcher = 'matches' . ucfirst($acceptor['matcher']);
  151. if ($this->{$matcher}($result, $acceptor)) {
  152. return $acceptor['state'];
  153. }
  154. }
  155. return $result instanceof \Exception ? 'failed' : 'retry';
  156. }
  157. /**
  158. * @param result $result Result or exception.
  159. * @param array $acceptor Acceptor configuration being checked.
  160. *
  161. * @return bool
  162. */
  163. private function matchesPath($result, array $acceptor)
  164. {
  165. return !($result instanceof ResultInterface)
  166. ? false
  167. : $acceptor['expected'] == $result->search($acceptor['argument']);
  168. }
  169. /**
  170. * @param result $result Result or exception.
  171. * @param array $acceptor Acceptor configuration being checked.
  172. *
  173. * @return bool
  174. */
  175. private function matchesPathAll($result, array $acceptor)
  176. {
  177. if (!($result instanceof ResultInterface)) {
  178. return false;
  179. }
  180. $actuals = $result->search($acceptor['argument']) ?: [];
  181. foreach ($actuals as $actual) {
  182. if ($actual != $acceptor['expected']) {
  183. return false;
  184. }
  185. }
  186. return true;
  187. }
  188. /**
  189. * @param result $result Result or exception.
  190. * @param array $acceptor Acceptor configuration being checked.
  191. *
  192. * @return bool
  193. */
  194. private function matchesPathAny($result, array $acceptor)
  195. {
  196. if (!($result instanceof ResultInterface)) {
  197. return false;
  198. }
  199. $actuals = $result->search($acceptor['argument']) ?: [];
  200. foreach ($actuals as $actual) {
  201. if ($actual == $acceptor['expected']) {
  202. return true;
  203. }
  204. }
  205. return false;
  206. }
  207. /**
  208. * @param result $result Result or exception.
  209. * @param array $acceptor Acceptor configuration being checked.
  210. *
  211. * @return bool
  212. */
  213. private function matchesStatus($result, array $acceptor)
  214. {
  215. if ($result instanceof ResultInterface) {
  216. return $acceptor['expected'] == $result['@metadata']['statusCode'];
  217. } elseif ($result instanceof AwsException && $response = $result->getResponse()) {
  218. return $acceptor['expected'] == $response->getStatusCode();
  219. } else {
  220. return false;
  221. }
  222. }
  223. /**
  224. * @param result $result Result or exception.
  225. * @param array $acceptor Acceptor configuration being checked.
  226. *
  227. * @return bool
  228. */
  229. private function matchesError($result, array $acceptor)
  230. {
  231. if ($result instanceof AwsException) {
  232. return $result->isConnectionError()
  233. || $result->getAwsErrorCode() == $acceptor['expected'];
  234. }
  235. return false;
  236. }
  237. }