AwsClient.php 15 KB

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