AwsClient.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  1. <?php
  2. namespace Aws;
  3. use Aws\Api\ApiProvider;
  4. use Aws\Api\DocModel;
  5. use Aws\Api\Service;
  6. use Aws\ClientSideMonitoring\ApiCallAttemptMonitoringMiddleware;
  7. use Aws\ClientSideMonitoring\ApiCallMonitoringMiddleware;
  8. use Aws\ClientSideMonitoring\ConfigurationProvider;
  9. use Aws\EndpointDiscovery\EndpointDiscoveryMiddleware;
  10. use Aws\Signature\SignatureProvider;
  11. use GuzzleHttp\Psr7\Uri;
  12. /**
  13. * Default AWS client implementation
  14. */
  15. class AwsClient implements AwsClientInterface
  16. {
  17. use AwsClientTrait;
  18. /** @var array */
  19. private $aliases;
  20. /** @var array */
  21. private $config;
  22. /** @var string */
  23. private $region;
  24. /** @var string */
  25. private $endpoint;
  26. /** @var Service */
  27. private $api;
  28. /** @var callable */
  29. private $signatureProvider;
  30. /** @var callable */
  31. private $credentialProvider;
  32. /** @var HandlerList */
  33. private $handlerList;
  34. /** @var array*/
  35. private $defaultRequestOptions;
  36. /**
  37. * Get an array of client constructor arguments used by the client.
  38. *
  39. * @return array
  40. */
  41. public static function getArguments()
  42. {
  43. return ClientResolver::getDefaultArguments();
  44. }
  45. /**
  46. * The client constructor accepts the following options:
  47. *
  48. * - api_provider: (callable) An optional PHP callable that accepts a
  49. * type, service, and version argument, and returns an array of
  50. * corresponding configuration data. The type value can be one of api,
  51. * waiter, or paginator.
  52. * - credentials:
  53. * (Aws\Credentials\CredentialsInterface|array|bool|callable) Specifies
  54. * the credentials used to sign requests. Provide an
  55. * Aws\Credentials\CredentialsInterface object, an associative array of
  56. * "key", "secret", and an optional "token" key, `false` to use null
  57. * credentials, or a callable credentials provider used to create
  58. * credentials or return null. See Aws\Credentials\CredentialProvider for
  59. * a list of built-in credentials providers. If no credentials are
  60. * provided, the SDK will attempt to load them from the environment.
  61. * - csm:
  62. * (Aws\ClientSideMonitoring\ConfigurationInterface|array|callable) Specifies
  63. * the credentials used to sign requests. Provide an
  64. * Aws\ClientSideMonitoring\ConfigurationInterface object, a callable
  65. * configuration provider used to create client-side monitoring configuration,
  66. * `false` to disable csm, or an associative array with the following keys:
  67. * enabled: (bool) Set to true to enable client-side monitoring, defaults
  68. * to false; host: (string) the host location to send monitoring events to,
  69. * defaults to 127.0.0.1; port: (int) The port used for the host connection,
  70. * defaults to 31000; client_id: (string) An identifier for this project
  71. * - debug: (bool|array) Set to true to display debug information when
  72. * sending requests. Alternatively, you can provide an associative array
  73. * with the following keys: logfn: (callable) Function that is invoked
  74. * with log messages; stream_size: (int) When the size of a stream is
  75. * greater than this number, the stream data will not be logged (set to
  76. * "0" to not log any stream data); scrub_auth: (bool) Set to false to
  77. * disable the scrubbing of auth data from the logged messages; http:
  78. * (bool) Set to false to disable the "debug" feature of lower level HTTP
  79. * adapters (e.g., verbose curl output).
  80. * - stats: (bool|array) Set to true to gather transfer statistics on
  81. * requests sent. Alternatively, you can provide an associative array with
  82. * the following keys: retries: (bool) Set to false to disable reporting
  83. * on retries attempted; http: (bool) Set to true to enable collecting
  84. * statistics from lower level HTTP adapters (e.g., values returned in
  85. * GuzzleHttp\TransferStats). HTTP handlers must support an
  86. * `http_stats_receiver` option for this to have an effect; timer: (bool)
  87. * Set to true to enable a command timer that reports the total wall clock
  88. * time spent on an operation in seconds.
  89. * - disable_host_prefix_injection: (bool) Set to true to disable host prefix
  90. * injection logic for services that use it. This disables the entire
  91. * prefix injection, including the portions supplied by user-defined
  92. * parameters. Setting this flag will have no effect on services that do
  93. * not use host prefix injection.
  94. * - endpoint: (string) The full URI of the webservice. This is only
  95. * required when connecting to a custom endpoint (e.g., a local version
  96. * of S3).
  97. * - endpoint_discovery: (Aws\EndpointDiscovery\ConfigurationInterface,
  98. * Aws\CacheInterface, array, callable) Settings for endpoint discovery.
  99. * Provide an instance of Aws\EndpointDiscovery\ConfigurationInterface,
  100. * an instance Aws\CacheInterface, a callable that provides a promise for
  101. * a Configuration object, or an associative array with the following
  102. * keys: enabled: (bool) Set to true to enable endpoint discovery, false
  103. * to explicitly disable it, defaults to false; cache_limit: (int) The
  104. * maximum number of keys in the endpoints cache, defaults to 1000.
  105. * - endpoint_provider: (callable) An optional PHP callable that
  106. * accepts a hash of options including a "service" and "region" key and
  107. * returns NULL or a hash of endpoint data, of which the "endpoint" key
  108. * is required. See Aws\Endpoint\EndpointProvider for a list of built-in
  109. * providers.
  110. * - handler: (callable) A handler that accepts a command object,
  111. * request object and returns a promise that is fulfilled with an
  112. * Aws\ResultInterface object or rejected with an
  113. * Aws\Exception\AwsException. A handler does not accept a next handler
  114. * as it is terminal and expected to fulfill a command. If no handler is
  115. * provided, a default Guzzle handler will be utilized.
  116. * - http: (array, default=array(0)) Set to an array of SDK request
  117. * options to apply to each request (e.g., proxy, verify, etc.).
  118. * - http_handler: (callable) An HTTP handler is a function that
  119. * accepts a PSR-7 request object and returns a promise that is fulfilled
  120. * with a PSR-7 response object or rejected with an array of exception
  121. * data. NOTE: This option supersedes any provided "handler" option.
  122. * - idempotency_auto_fill: (bool|callable) Set to false to disable SDK to
  123. * populate parameters that enabled 'idempotencyToken' trait with a random
  124. * UUID v4 value on your behalf. Using default value 'true' still allows
  125. * parameter value to be overwritten when provided. Note: auto-fill only
  126. * works when cryptographically secure random bytes generator functions
  127. * (random_bytes, openssl_random_pseudo_bytes or mcrypt_create_iv) can be
  128. * found. You may also provide a callable source of random bytes.
  129. * - profile: (string) Allows you to specify which profile to use when
  130. * credentials are created from the AWS credentials file in your HOME
  131. * directory. This setting overrides the AWS_PROFILE environment
  132. * variable. Note: Specifying "profile" will cause the "credentials" key
  133. * to be ignored.
  134. * - region: (string, required) Region to connect to. See
  135. * http://docs.aws.amazon.com/general/latest/gr/rande.html for a list of
  136. * available regions.
  137. * - retries: (int, Aws\Retry\ConfigurationInterface, Aws\CacheInterface,
  138. * array, callable) Configures the retry mode and maximum number of
  139. * allowed retries for a client (pass 0 to disable retries). Provide an
  140. * integer for 'legacy' mode with the specified number of retries.
  141. * Otherwise provide an instance of Aws\Retry\ConfigurationInterface, an
  142. * instance of Aws\CacheInterface, a callable function, or an array with
  143. * the following keys: mode: (string) Set to 'legacy', 'standard' (uses
  144. * retry quota management), or 'adapative' (an experimental mode that adds
  145. * client-side rate limiting to standard mode); max_attempts (int) The
  146. * maximum number of attempts for a given request.
  147. * - scheme: (string, default=string(5) "https") URI scheme to use when
  148. * connecting connect. The SDK will utilize "https" endpoints (i.e.,
  149. * utilize SSL/TLS connections) by default. You can attempt to connect to
  150. * a service over an unencrypted "http" endpoint by setting ``scheme`` to
  151. * "http".
  152. * - signature_provider: (callable) A callable that accepts a signature
  153. * version name (e.g., "v4"), a service name, and region, and
  154. * returns a SignatureInterface object or null. This provider is used to
  155. * create signers utilized by the client. See
  156. * Aws\Signature\SignatureProvider for a list of built-in providers
  157. * - signature_version: (string) A string representing a custom
  158. * signature version to use with a service (e.g., v4). Note that
  159. * per/operation signature version MAY override this requested signature
  160. * version.
  161. * - use_aws_shared_config_files: (bool, default=bool(true)) Set to false to
  162. * disable checking for shared config file in '~/.aws/config' and
  163. * '~/.aws/credentials'. This will override the AWS_CONFIG_FILE
  164. * environment variable.
  165. * - validate: (bool, default=bool(true)) Set to false to disable
  166. * client-side parameter validation.
  167. * - version: (string, required) The version of the webservice to
  168. * utilize (e.g., 2006-03-01).
  169. *
  170. * @param array $args Client configuration arguments.
  171. *
  172. * @throws \InvalidArgumentException if any required options are missing or
  173. * the service is not supported.
  174. */
  175. public function __construct(array $args)
  176. {
  177. list($service, $exceptionClass) = $this->parseClass();
  178. if (!isset($args['service'])) {
  179. $args['service'] = manifest($service)['endpoint'];
  180. }
  181. if (!isset($args['exception_class'])) {
  182. $args['exception_class'] = $exceptionClass;
  183. }
  184. $this->handlerList = new HandlerList();
  185. $resolver = new ClientResolver(static::getArguments());
  186. $config = $resolver->resolve($args, $this->handlerList);
  187. $this->api = $config['api'];
  188. $this->signatureProvider = $config['signature_provider'];
  189. $this->endpoint = new Uri($config['endpoint']);
  190. $this->credentialProvider = $config['credentials'];
  191. $this->region = isset($config['region']) ? $config['region'] : null;
  192. $this->config = $config['config'];
  193. $this->defaultRequestOptions = $config['http'];
  194. $this->addSignatureMiddleware();
  195. $this->addInvocationId();
  196. $this->addEndpointParameterMiddleware($args);
  197. $this->addEndpointDiscoveryMiddleware($config, $args);
  198. $this->loadAliases();
  199. $this->addStreamRequestPayload();
  200. if (isset($args['with_resolved'])) {
  201. $args['with_resolved']($config);
  202. }
  203. }
  204. public function getHandlerList()
  205. {
  206. return $this->handlerList;
  207. }
  208. public function getConfig($option = null)
  209. {
  210. return $option === null
  211. ? $this->config
  212. : (isset($this->config[$option])
  213. ? $this->config[$option]
  214. : null);
  215. }
  216. public function getCredentials()
  217. {
  218. $fn = $this->credentialProvider;
  219. return $fn();
  220. }
  221. public function getEndpoint()
  222. {
  223. return $this->endpoint;
  224. }
  225. public function getRegion()
  226. {
  227. return $this->region;
  228. }
  229. public function getApi()
  230. {
  231. return $this->api;
  232. }
  233. public function getCommand($name, array $args = [])
  234. {
  235. // Fail fast if the command cannot be found in the description.
  236. if (!isset($this->getApi()['operations'][$name])) {
  237. $name = ucfirst($name);
  238. if (!isset($this->getApi()['operations'][$name])) {
  239. throw new \InvalidArgumentException("Operation not found: $name");
  240. }
  241. }
  242. if (!isset($args['@http'])) {
  243. $args['@http'] = $this->defaultRequestOptions;
  244. } else {
  245. $args['@http'] += $this->defaultRequestOptions;
  246. }
  247. return new Command($name, $args, clone $this->getHandlerList());
  248. }
  249. public function __sleep()
  250. {
  251. throw new \RuntimeException('Instances of ' . static::class
  252. . ' cannot be serialized');
  253. }
  254. /**
  255. * Get the signature_provider function of the client.
  256. *
  257. * @return callable
  258. */
  259. final public function getSignatureProvider()
  260. {
  261. return $this->signatureProvider;
  262. }
  263. /**
  264. * Parse the class name and setup the custom exception class of the client
  265. * and return the "service" name of the client and "exception_class".
  266. *
  267. * @return array
  268. */
  269. private function parseClass()
  270. {
  271. $klass = get_class($this);
  272. if ($klass === __CLASS__) {
  273. return ['', 'Aws\Exception\AwsException'];
  274. }
  275. $service = substr($klass, strrpos($klass, '\\') + 1, -6);
  276. return [
  277. strtolower($service),
  278. "Aws\\{$service}\\Exception\\{$service}Exception"
  279. ];
  280. }
  281. private function addEndpointParameterMiddleware($args)
  282. {
  283. if (empty($args['disable_host_prefix_injection'])) {
  284. $list = $this->getHandlerList();
  285. $list->appendBuild(
  286. EndpointParameterMiddleware::wrap(
  287. $this->api
  288. ),
  289. 'endpoint_parameter'
  290. );
  291. }
  292. }
  293. private function addEndpointDiscoveryMiddleware($config, $args)
  294. {
  295. $list = $this->getHandlerList();
  296. if (!isset($args['endpoint'])) {
  297. $list->appendBuild(
  298. EndpointDiscoveryMiddleware::wrap(
  299. $this,
  300. $args,
  301. $config['endpoint_discovery']
  302. ),
  303. 'EndpointDiscoveryMiddleware'
  304. );
  305. }
  306. }
  307. private function addSignatureMiddleware()
  308. {
  309. $api = $this->getApi();
  310. $provider = $this->signatureProvider;
  311. $version = $this->config['signature_version'];
  312. $name = $this->config['signing_name'];
  313. $region = $this->config['signing_region'];
  314. $resolver = static function (
  315. CommandInterface $c
  316. ) use ($api, $provider, $name, $region, $version) {
  317. if (!empty($c['@context']['signing_region'])) {
  318. $region = $c['@context']['signing_region'];
  319. }
  320. if (!empty($c['@context']['signing_service'])) {
  321. $name = $c['@context']['signing_service'];
  322. }
  323. $authType = $api->getOperation($c->getName())['authtype'];
  324. switch ($authType){
  325. case 'none':
  326. $version = 'anonymous';
  327. break;
  328. case 'v4-unsigned-body':
  329. $version = 'v4-unsigned-body';
  330. break;
  331. }
  332. return SignatureProvider::resolve($provider, $version, $name, $region);
  333. };
  334. $this->handlerList->appendSign(
  335. Middleware::signer($this->credentialProvider, $resolver),
  336. 'signer'
  337. );
  338. }
  339. private function addInvocationId()
  340. {
  341. // Add invocation id to each request
  342. $this->handlerList->prependSign(Middleware::invocationId(), 'invocation-id');
  343. }
  344. private function loadAliases($file = null)
  345. {
  346. if (!isset($this->aliases)) {
  347. if (is_null($file)) {
  348. $file = __DIR__ . '/data/aliases.json';
  349. }
  350. $aliases = \Aws\load_compiled_json($file);
  351. $serviceId = $this->api->getServiceId();
  352. $version = $this->getApi()->getApiVersion();
  353. if (!empty($aliases['operations'][$serviceId][$version])) {
  354. $this->aliases = array_flip($aliases['operations'][$serviceId][$version]);
  355. }
  356. }
  357. }
  358. private function addStreamRequestPayload()
  359. {
  360. $streamRequestPayloadMiddleware = StreamRequestPayloadMiddleware::wrap(
  361. $this->api
  362. );
  363. $this->handlerList->prependSign(
  364. $streamRequestPayloadMiddleware,
  365. 'StreamRequestPayloadMiddleware'
  366. );
  367. }
  368. /**
  369. * Returns a service model and doc model with any necessary changes
  370. * applied.
  371. *
  372. * @param array $api Array of service data being documented.
  373. * @param array $docs Array of doc model data.
  374. *
  375. * @return array Tuple containing a [Service, DocModel]
  376. *
  377. * @internal This should only used to document the service API.
  378. * @codeCoverageIgnore
  379. */
  380. public static function applyDocFilters(array $api, array $docs)
  381. {
  382. $aliases = \Aws\load_compiled_json(__DIR__ . '/data/aliases.json');
  383. $serviceId = $api['metadata']['serviceId'];
  384. $version = $api['metadata']['apiVersion'];
  385. // Replace names for any operations with SDK aliases
  386. if (!empty($aliases['operations'][$serviceId][$version])) {
  387. foreach ($aliases['operations'][$serviceId][$version] as $op => $alias) {
  388. $api['operations'][$alias] = $api['operations'][$op];
  389. $docs['operations'][$alias] = $docs['operations'][$op];
  390. unset($api['operations'][$op], $docs['operations'][$op]);
  391. }
  392. }
  393. ksort($api['operations']);
  394. return [
  395. new Service($api, ApiProvider::defaultProvider()),
  396. new DocModel($docs)
  397. ];
  398. }
  399. /**
  400. * @deprecated
  401. * @return static
  402. */
  403. public static function factory(array $config = [])
  404. {
  405. return new static($config);
  406. }
  407. }