SendRequestTrait.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710
  1. <?php
  2. /**
  3. * Copyright 2019 Huawei Technologies Co.,Ltd.
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not use
  5. * this file except in compliance with the License. You may obtain a copy of the
  6. * 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 distributed
  11. * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
  12. * CONDITIONS OF ANY KIND, either express or implied. See the License for the
  13. * specific language governing permissions and limitations under the License.
  14. *
  15. */
  16. namespace Obs\Internal;
  17. use GuzzleHttp\Psr7;
  18. use Obs\Log\ObsLog;
  19. use GuzzleHttp\Psr7\Request;
  20. use GuzzleHttp\Psr7\Response;
  21. use GuzzleHttp\Exception\RequestException;
  22. use GuzzleHttp\Exception\ConnectException;
  23. use Obs\Internal\Common\Model;
  24. use Obs\Internal\Resource\V2Constants;
  25. use Obs\ObsException;
  26. use Obs\Internal\Signature\V4Signature;
  27. use Obs\Internal\Signature\DefaultSignature;
  28. use GuzzleHttp\Client;
  29. use Obs\Internal\Resource\Constants;
  30. use Psr\Http\Message\StreamInterface;
  31. use Obs\Internal\Resource\V2RequestResource;
  32. trait SendRequestTrait
  33. {
  34. protected $ak;
  35. protected $sk;
  36. protected $securityToken = false;
  37. protected $endpoint = '';
  38. protected $pathStyle = false;
  39. protected $region = 'region';
  40. protected $signature = 'v2';
  41. protected $sslVerify = false;
  42. protected $maxRetryCount = 3;
  43. protected $timeout = 0;
  44. protected $socketTimeout = 60;
  45. protected $connectTimeout = 60;
  46. /** @var Client */
  47. protected $httpClient;
  48. public function createSignedUrl(array $args=[]){
  49. if (strcasecmp($this -> signature, 'v4') === 0) {
  50. return $this -> createV4SignedUrl($args);
  51. }
  52. return $this->createCommonSignedUrl($args, $this->signature);
  53. }
  54. public function createV2SignedUrl(array $args=[]) {
  55. return $this->createCommonSignedUrl($args, 'v2');
  56. }
  57. private function createCommonSignedUrl(array $args=[], $signature) {
  58. if(!isset($args['Method'])){
  59. $obsException = new ObsException('Method param must be specified, allowed values: GET | PUT | HEAD | POST | DELETE | OPTIONS');
  60. $obsException-> setExceptionType('client');
  61. throw $obsException;
  62. }
  63. $method = strval($args['Method']);
  64. $bucketName = isset($args['Bucket'])? strval($args['Bucket']): null;
  65. $objectKey = isset($args['Key'])? strval($args['Key']): null;
  66. $specialParam = isset($args['SpecialParam'])? strval($args['SpecialParam']): null;
  67. $expires = isset($args['Expires']) && is_numeric($args['Expires']) ? intval($args['Expires']): 300;
  68. $headers = [];
  69. if(isset($args['Headers']) && is_array($args['Headers']) ){
  70. foreach ($args['Headers'] as $key => $val){
  71. if(is_string($key) && $key !== ''){
  72. $headers[$key] = $val;
  73. }
  74. }
  75. }
  76. $queryParams = [];
  77. if(isset($args['QueryParams']) && is_array($args['QueryParams']) ){
  78. foreach ($args['QueryParams'] as $key => $val){
  79. if(is_string($key) && $key !== ''){
  80. $queryParams[$key] = $val;
  81. }
  82. }
  83. }
  84. $constants = Constants::selectConstants($signature);
  85. if($this->securityToken && !isset($queryParams[$constants::SECURITY_TOKEN_HEAD])){
  86. $queryParams[$constants::SECURITY_TOKEN_HEAD] = $this->securityToken;
  87. }
  88. $sign = new DefaultSignature($this->ak, $this->sk, $this->pathStyle, $this->endpoint, $method, $this->signature);
  89. $url = parse_url($this->endpoint);
  90. $host = $url['host'];
  91. $result = '';
  92. if($bucketName){
  93. if($this-> pathStyle){
  94. $result = '/' . $bucketName;
  95. }else{
  96. $host = $bucketName . '.' . $host;
  97. }
  98. }
  99. if($objectKey){
  100. $objectKey = $sign ->urlencodeWithSafe($objectKey);
  101. $result .= '/' . $objectKey;
  102. }
  103. $result .= '?';
  104. if($specialParam){
  105. $queryParams[$specialParam] = '';
  106. }
  107. $queryParams[$constants::TEMPURL_AK_HEAD] = $this->ak;
  108. if(!is_numeric($expires) || $expires < 0){
  109. $expires = 300;
  110. }
  111. $expires = intval($expires) + intval(microtime(true));
  112. $queryParams['Expires'] = strval($expires);
  113. $_queryParams = [];
  114. foreach ($queryParams as $key => $val){
  115. $key = $sign -> urlencodeWithSafe($key);
  116. $val = $sign -> urlencodeWithSafe($val);
  117. $_queryParams[$key] = $val;
  118. $result .= $key;
  119. if($val){
  120. $result .= '=' . $val;
  121. }
  122. $result .= '&';
  123. }
  124. $canonicalstring = $sign ->makeCanonicalstring($method, $headers, $_queryParams, $bucketName, $objectKey, $expires);
  125. $signatureContent = base64_encode(hash_hmac('sha1', $canonicalstring, $this->sk, true));
  126. $result .= 'Signature=' . $sign->urlencodeWithSafe($signatureContent);
  127. $model = new Model();
  128. $model['ActualSignedRequestHeaders'] = $headers;
  129. $model['SignedUrl'] = $url['scheme'] . '://' . $host . ':' . (isset($url['port']) ? $url['port'] : (strtolower($url['scheme']) === 'https' ? '443' : '80')) . $result;
  130. return $model;
  131. }
  132. public function createV4SignedUrl(array $args=[]){
  133. if(!isset($args['Method'])){
  134. $obsException= new ObsException('Method param must be specified, allowed values: GET | PUT | HEAD | POST | DELETE | OPTIONS');
  135. $obsException-> setExceptionType('client');
  136. throw $obsException;
  137. }
  138. $method = strval($args['Method']);
  139. $bucketName = isset($args['Bucket'])? strval($args['Bucket']): null;
  140. $objectKey = isset($args['Key'])? strval($args['Key']): null;
  141. $specialParam = isset($args['SpecialParam'])? strval($args['SpecialParam']): null;
  142. $expires = isset($args['Expires']) && is_numeric($args['Expires']) ? intval($args['Expires']): 300;
  143. $headers = [];
  144. if(isset($args['Headers']) && is_array($args['Headers']) ){
  145. foreach ($args['Headers'] as $key => $val){
  146. if(is_string($key) && $key !== ''){
  147. $headers[$key] = $val;
  148. }
  149. }
  150. }
  151. $queryParams = [];
  152. if(isset($args['QueryParams']) && is_array($args['QueryParams']) ){
  153. foreach ($args['QueryParams'] as $key => $val){
  154. if(is_string($key) && $key !== ''){
  155. $queryParams[$key] = $val;
  156. }
  157. }
  158. }
  159. if($this->securityToken && !isset($queryParams['x-amz-security-token'])){
  160. $queryParams['x-amz-security-token'] = $this->securityToken;
  161. }
  162. $v4 = new V4Signature($this->ak, $this->sk, $this->pathStyle, $this->endpoint, $this->region, $method, $this->signature);
  163. $url = parse_url($this->endpoint);
  164. $host = $url['host'];
  165. $result = '';
  166. if($bucketName){
  167. if($this-> pathStyle){
  168. $result = '/' . $bucketName;
  169. }else{
  170. $host = $bucketName . '.' . $host;
  171. }
  172. }
  173. if($objectKey){
  174. $objectKey = $v4 -> urlencodeWithSafe($objectKey);
  175. $result .= '/' . $objectKey;
  176. }
  177. $result .= '?';
  178. if($specialParam){
  179. $queryParams[$specialParam] = '';
  180. }
  181. if(!is_numeric($expires) || $expires < 0){
  182. $expires = 300;
  183. }
  184. $expires = strval($expires);
  185. $date = isset($headers['date']) ? $headers['date'] : (isset($headers['Date']) ? $headers['Date'] : null);
  186. $timestamp = $date ? date_create_from_format('D, d M Y H:i:s \G\M\T', $date, new \DateTimeZone ('UTC')) -> getTimestamp()
  187. :time();
  188. $longDate = gmdate('Ymd\THis\Z', $timestamp);
  189. $shortDate = substr($longDate, 0, 8);
  190. $headers['host'] = $host;
  191. if(isset($url['port'])){
  192. $port = $url['port'];
  193. if($port !== 443 && $port !== 80){
  194. $headers['host'] = $headers['host'] . ':' . $port;
  195. }
  196. }
  197. $signedHeaders = $v4 -> getSignedHeaders($headers);
  198. $queryParams['X-Amz-Algorithm'] = 'AWS4-HMAC-SHA256';
  199. $queryParams['X-Amz-Credential'] = $v4 -> getCredential($shortDate);
  200. $queryParams['X-Amz-Date'] = $longDate;
  201. $queryParams['X-Amz-Expires'] = $expires;
  202. $queryParams['X-Amz-SignedHeaders'] = $signedHeaders;
  203. $_queryParams = [];
  204. foreach ($queryParams as $key => $val){
  205. $key = rawurlencode($key);
  206. $val = rawurlencode($val);
  207. $_queryParams[$key] = $val;
  208. $result .= $key;
  209. if($val){
  210. $result .= '=' . $val;
  211. }
  212. $result .= '&';
  213. }
  214. $canonicalstring = $v4 -> makeCanonicalstring($method, $headers, $_queryParams, $bucketName, $objectKey, $signedHeaders, 'UNSIGNED-PAYLOAD');
  215. $signatureContent = $v4 -> getSignature($canonicalstring, $longDate, $shortDate);
  216. $result .= 'X-Amz-Signature=' . $v4 -> urlencodeWithSafe($signatureContent);
  217. $model = new Model();
  218. $model['ActualSignedRequestHeaders'] = $headers;
  219. $model['SignedUrl'] = $url['scheme'] . '://' . $host . ':' . (isset($url['port']) ? $url['port'] : (strtolower($url['scheme']) === 'https' ? '443' : '80')) . $result;
  220. return $model;
  221. }
  222. public function createPostSignature(array $args=[]) {
  223. if (strcasecmp($this -> signature, 'v4') === 0) {
  224. return $this -> createV4PostSignature($args);
  225. }
  226. $bucketName = isset($args['Bucket'])? strval($args['Bucket']): null;
  227. $objectKey = isset($args['Key'])? strval($args['Key']): null;
  228. $expires = isset($args['Expires']) && is_numeric($args['Expires']) ? intval($args['Expires']): 300;
  229. $formParams = [];
  230. if(isset($args['FormParams']) && is_array($args['FormParams'])){
  231. foreach ($args['FormParams'] as $key => $val){
  232. $formParams[$key] = $val;
  233. }
  234. }
  235. $constants = Constants::selectConstants($this -> signature);
  236. if($this->securityToken && !isset($formParams[$constants::SECURITY_TOKEN_HEAD])){
  237. $formParams[$constants::SECURITY_TOKEN_HEAD] = $this->securityToken;
  238. }
  239. $timestamp = time();
  240. $expires = gmdate('Y-m-d\TH:i:s\Z', $timestamp + $expires);
  241. if($bucketName){
  242. $formParams['bucket'] = $bucketName;
  243. }
  244. if($objectKey){
  245. $formParams['key'] = $objectKey;
  246. }
  247. $policy = [];
  248. $policy[] = '{"expiration":"';
  249. $policy[] = $expires;
  250. $policy[] = '", "conditions":[';
  251. $matchAnyBucket = true;
  252. $matchAnyKey = true;
  253. $conditionAllowKeys = ['acl', 'bucket', 'key', 'success_action_redirect', 'redirect', 'success_action_status'];
  254. foreach($formParams as $key => $val){
  255. if($key){
  256. $key = strtolower(strval($key));
  257. if($key === 'bucket'){
  258. $matchAnyBucket = false;
  259. }else if($key === 'key'){
  260. $matchAnyKey = false;
  261. }
  262. if(!in_array($key, Constants::ALLOWED_REQUEST_HTTP_HEADER_METADATA_NAMES) && strpos($key, $constants::HEADER_PREFIX) !== 0 && !in_array($key, $conditionAllowKeys)){
  263. $key = $constants::METADATA_PREFIX . $key;
  264. }
  265. $policy[] = '{"';
  266. $policy[] = $key;
  267. $policy[] = '":"';
  268. $policy[] = $val !== null ? strval($val) : '';
  269. $policy[] = '"},';
  270. }
  271. }
  272. if($matchAnyBucket){
  273. $policy[] = '["starts-with", "$bucket", ""],';
  274. }
  275. if($matchAnyKey){
  276. $policy[] = '["starts-with", "$key", ""],';
  277. }
  278. $policy[] = ']}';
  279. $originPolicy = implode('', $policy);
  280. $policy = base64_encode($originPolicy);
  281. $signatureContent = base64_encode(hash_hmac('sha1', $policy, $this->sk, true));
  282. $model = new Model();
  283. $model['OriginPolicy'] = $originPolicy;
  284. $model['Policy'] = $policy;
  285. $model['Signature'] = $signatureContent;
  286. return $model;
  287. }
  288. public function createV4PostSignature(array $args=[]){
  289. $bucketName = isset($args['Bucket'])? strval($args['Bucket']): null;
  290. $objectKey = isset($args['Key'])? strval($args['Key']): null;
  291. $expires = isset($args['Expires']) && is_numeric($args['Expires']) ? intval($args['Expires']): 300;
  292. $formParams = [];
  293. if(isset($args['FormParams']) && is_array($args['FormParams'])){
  294. foreach ($args['FormParams'] as $key => $val){
  295. $formParams[$key] = $val;
  296. }
  297. }
  298. if($this->securityToken && !isset($formParams['x-amz-security-token'])){
  299. $formParams['x-amz-security-token'] = $this->securityToken;
  300. }
  301. $timestamp = time();
  302. $longDate = gmdate('Ymd\THis\Z', $timestamp);
  303. $shortDate = substr($longDate, 0, 8);
  304. $credential = sprintf('%s/%s/%s/s3/aws4_request', $this->ak, $shortDate, $this->region);
  305. $expires = gmdate('Y-m-d\TH:i:s\Z', $timestamp + $expires);
  306. $formParams['X-Amz-Algorithm'] = 'AWS4-HMAC-SHA256';
  307. $formParams['X-Amz-Date'] = $longDate;
  308. $formParams['X-Amz-Credential'] = $credential;
  309. if($bucketName){
  310. $formParams['bucket'] = $bucketName;
  311. }
  312. if($objectKey){
  313. $formParams['key'] = $objectKey;
  314. }
  315. $policy = [];
  316. $policy[] = '{"expiration":"';
  317. $policy[] = $expires;
  318. $policy[] = '", "conditions":[';
  319. $matchAnyBucket = true;
  320. $matchAnyKey = true;
  321. $conditionAllowKeys = ['acl', 'bucket', 'key', 'success_action_redirect', 'redirect', 'success_action_status'];
  322. foreach($formParams as $key => $val){
  323. if($key){
  324. $key = strtolower(strval($key));
  325. if($key === 'bucket'){
  326. $matchAnyBucket = false;
  327. }else if($key === 'key'){
  328. $matchAnyKey = false;
  329. }
  330. if(!in_array($key, Constants::ALLOWED_REQUEST_HTTP_HEADER_METADATA_NAMES) && strpos($key, V2Constants::HEADER_PREFIX) !== 0 && !in_array($key, $conditionAllowKeys)){
  331. $key = V2Constants::METADATA_PREFIX . $key;
  332. }
  333. $policy[] = '{"';
  334. $policy[] = $key;
  335. $policy[] = '":"';
  336. $policy[] = $val !== null ? strval($val) : '';
  337. $policy[] = '"},';
  338. }
  339. }
  340. if($matchAnyBucket){
  341. $policy[] = '["starts-with", "$bucket", ""],';
  342. }
  343. if($matchAnyKey){
  344. $policy[] = '["starts-with", "$key", ""],';
  345. }
  346. $policy[] = ']}';
  347. $originPolicy = implode('', $policy);
  348. $policy = base64_encode($originPolicy);
  349. $dateKey = hash_hmac('sha256', $shortDate, 'AWS4' . $this -> sk, true);
  350. $regionKey = hash_hmac('sha256', $this->region, $dateKey, true);
  351. $serviceKey = hash_hmac('sha256', 's3', $regionKey, true);
  352. $signingKey = hash_hmac('sha256', 'aws4_request', $serviceKey, true);
  353. $signatureContent = hash_hmac('sha256', $policy, $signingKey);
  354. $model = new Model();
  355. $model['OriginPolicy'] = $originPolicy;
  356. $model['Policy'] = $policy;
  357. $model['Algorithm'] = $formParams['X-Amz-Algorithm'];
  358. $model['Credential'] = $formParams['X-Amz-Credential'];
  359. $model['Date'] = $formParams['X-Amz-Date'];
  360. $model['Signature'] = $signatureContent;
  361. return $model;
  362. }
  363. public function __call($originMethod, $args)
  364. {
  365. $method = $originMethod;
  366. $contents = Constants::selectRequestResource($this->signature);
  367. $resource = &$contents::$RESOURCE_ARRAY;
  368. $async = false;
  369. if(strpos($method, 'Async') === (strlen($method) - 5)){
  370. $method = substr($method, 0, strlen($method) - 5);
  371. $async = true;
  372. }
  373. if(isset($resource['aliases'][$method])){
  374. $method = $resource['aliases'][$method];
  375. }
  376. $method = lcfirst($method);
  377. $operation = isset($resource['operations'][$method]) ?
  378. $resource['operations'][$method] : null;
  379. if(!$operation){
  380. ObsLog::commonLog(WARNING, 'unknow method ' . $originMethod);
  381. $obsException= new ObsException('unknow method '. $originMethod);
  382. $obsException-> setExceptionType('client');
  383. throw $obsException;
  384. }
  385. $start = microtime(true);
  386. if(!$async){
  387. ObsLog::commonLog(INFO, 'enter method '. $originMethod. '...');
  388. $model = new Model();
  389. $model['method'] = $method;
  390. $params = empty($args) ? [] : $args[0];
  391. $this->checkMimeType($method, $params);
  392. $this->doRequest($model, $operation, $params);
  393. ObsLog::commonLog(INFO, 'obsclient cost ' . round(microtime(true) - $start, 3) * 1000 . ' ms to execute '. $originMethod);
  394. unset($model['method']);
  395. return $model;
  396. }else{
  397. if(empty($args) || !(is_callable($callback = $args[count($args) -1]))){
  398. ObsLog::commonLog(WARNING, 'async method ' . $originMethod . ' must pass a CallbackInterface as param');
  399. $obsException= new ObsException('async method ' . $originMethod . ' must pass a CallbackInterface as param');
  400. $obsException-> setExceptionType('client');
  401. throw $obsException;
  402. }
  403. ObsLog::commonLog(INFO, 'enter method '. $originMethod. '...');
  404. $params = count($args) === 1 ? [] : $args[0];
  405. $this->checkMimeType($method, $params);
  406. $model = new Model();
  407. $model['method'] = $method;
  408. return $this->doRequestAsync($model, $operation, $params, $callback, $start, $originMethod);
  409. }
  410. }
  411. private function checkMimeType($method, &$params){
  412. // fix bug that guzzlehttp lib will add the content-type if not set
  413. if(($method === 'putObject' || $method === 'initiateMultipartUpload' || $method === 'uploadPart') && (!isset($params['ContentType']) || $params['ContentType'] === null)){
  414. if(isset($params['Key'])){
  415. $params['ContentType'] = Psr7\mimetype_from_filename($params['Key']);
  416. }
  417. if((!isset($params['ContentType']) || $params['ContentType'] === null) && isset($params['SourceFile'])){
  418. $params['ContentType'] = Psr7\mimetype_from_filename($params['SourceFile']);
  419. }
  420. if(!isset($params['ContentType']) || $params['ContentType'] === null){
  421. $params['ContentType'] = 'binary/octet-stream';
  422. }
  423. }
  424. }
  425. protected function makeRequest($model, &$operation, $params, $endpoint = null)
  426. {
  427. if($endpoint === null){
  428. $endpoint = $this->endpoint;
  429. }
  430. $signatureInterface = strcasecmp($this-> signature, 'v4') === 0 ?
  431. new V4Signature($this->ak, $this->sk, $this->pathStyle, $endpoint, $this->region, $model['method'], $this->signature, $this->securityToken) :
  432. new DefaultSignature($this->ak, $this->sk, $this->pathStyle, $endpoint, $model['method'], $this->signature, $this->securityToken);
  433. $authResult = $signatureInterface -> doAuth($operation, $params, $model);
  434. $httpMethod = $authResult['method'];
  435. ObsLog::commonLog(DEBUG, 'perform '. strtolower($httpMethod) . ' request with url ' . $authResult['requestUrl']);
  436. ObsLog::commonLog(DEBUG, 'cannonicalRequest:' . $authResult['cannonicalRequest']);
  437. ObsLog::commonLog(DEBUG, 'request headers ' . var_export($authResult['headers'],true));
  438. $authResult['headers']['User-Agent'] = self::default_user_agent();
  439. if($model['method'] === 'putObject'){
  440. $model['ObjectURL'] = ['value' => $authResult['requestUrl']];
  441. }
  442. return new Request($httpMethod, $authResult['requestUrl'], $authResult['headers'], $authResult['body']);
  443. }
  444. protected function doRequest($model, &$operation, $params, $endpoint = null)
  445. {
  446. $request = $this -> makeRequest($model, $operation, $params, $endpoint);
  447. $this->sendRequest($model, $operation, $params, $request);
  448. }
  449. protected function sendRequest($model, &$operation, $params, $request, $requestCount = 1)
  450. {
  451. $start = microtime(true);
  452. $saveAsStream = false;
  453. if(isset($operation['stream']) && $operation['stream']){
  454. $saveAsStream = isset($params['SaveAsStream']) ? $params['SaveAsStream'] : false;
  455. if(isset($params['SaveAsFile'])){
  456. if($saveAsStream){
  457. $obsException = new ObsException('SaveAsStream cannot be used with SaveAsFile together');
  458. $obsException-> setExceptionType('client');
  459. throw $obsException;
  460. }
  461. $saveAsStream = true;
  462. }
  463. if(isset($params['FilePath'])){
  464. if($saveAsStream){
  465. $obsException = new ObsException('SaveAsStream cannot be used with FilePath together');
  466. $obsException-> setExceptionType('client');
  467. throw $obsException;
  468. }
  469. $saveAsStream = true;
  470. }
  471. if(isset($params['SaveAsFile']) && isset($params['FilePath'])){
  472. $obsException = new ObsException('SaveAsFile cannot be used with FilePath together');
  473. $obsException-> setExceptionType('client');
  474. throw $obsException;
  475. }
  476. }
  477. $promise = $this->httpClient->sendAsync($request, ['stream' => $saveAsStream])->then(
  478. function(Response $response) use ($model, $operation, $params, $request, $requestCount, $start){
  479. ObsLog::commonLog(INFO, 'http request cost ' . round(microtime(true) - $start, 3) * 1000 . ' ms');
  480. $statusCode = $response -> getStatusCode();
  481. $readable = isset($params['Body']) && ($params['Body'] instanceof StreamInterface || is_resource($params['Body']));
  482. if($statusCode >= 300 && $statusCode <400 && $statusCode !== 304 && !$readable && $requestCount <= $this->maxRetryCount){
  483. if($location = $response -> getHeaderLine('location')){
  484. $url = parse_url($this->endpoint);
  485. $newUrl = parse_url($location);
  486. $scheme = (isset($newUrl['scheme']) ? $newUrl['scheme'] : $url['scheme']);
  487. $defaultPort = strtolower($scheme) === 'https' ? '443' : '80';
  488. $this->doRequest($model, $operation, $params, $scheme. '://' . $newUrl['host'] .
  489. ':' . (isset($newUrl['port']) ? $newUrl['port'] : $defaultPort));
  490. return;
  491. }
  492. }
  493. $this -> parseResponse($model, $request, $response, $operation);
  494. },
  495. function (RequestException $exception) use ($model, $operation, $params, $request, $requestCount, $start) {
  496. ObsLog::commonLog(INFO, 'http request cost ' . round(microtime(true) - $start, 3) * 1000 . ' ms');
  497. $message = null;
  498. if($exception instanceof ConnectException){
  499. if($requestCount <= $this->maxRetryCount){
  500. $this -> sendRequest($model, $operation, $params, $request, $requestCount + 1);
  501. return;
  502. }else{
  503. $message = 'Exceeded retry limitation, max retry count:'. $this->maxRetryCount . ', error message:' . $exception -> getMessage();
  504. }
  505. }
  506. $this -> parseException($model, $request, $exception, $message);
  507. });
  508. $promise -> wait();
  509. }
  510. protected function doRequestAsync($model, &$operation, $params, $callback, $startAsync, $originMethod, $endpoint = null){
  511. $request = $this -> makeRequest($model, $operation, $params, $endpoint);
  512. return $this->sendRequestAsync($model, $operation, $params, $callback, $startAsync, $originMethod, $request);
  513. }
  514. protected function sendRequestAsync($model, &$operation, $params, $callback, $startAsync, $originMethod, $request, $requestCount = 1)
  515. {
  516. $start = microtime(true);
  517. $saveAsStream = false;
  518. if(isset($operation['stream']) && $operation['stream']){
  519. $saveAsStream = isset($params['SaveAsStream']) ? $params['SaveAsStream'] : false;
  520. if($saveAsStream){
  521. if(isset($params['SaveAsFile'])){
  522. $obsException = new ObsException('SaveAsStream cannot be used with SaveAsFile together');
  523. $obsException-> setExceptionType('client');
  524. throw $obsException;
  525. }
  526. if(isset($params['FilePath'])){
  527. $obsException = new ObsException('SaveAsStream cannot be used with FilePath together');
  528. $obsException-> setExceptionType('client');
  529. throw $obsException;
  530. }
  531. }
  532. if(isset($params['SaveAsFile']) && isset($params['FilePath'])){
  533. $obsException = new ObsException('SaveAsFile cannot be used with FilePath together');
  534. $obsException-> setExceptionType('client');
  535. throw $obsException;
  536. }
  537. }
  538. return $this->httpClient->sendAsync($request, ['stream' => $saveAsStream])->then(
  539. function(Response $response) use ($model, $operation, $params, $callback, $startAsync, $originMethod, $request, $start){
  540. ObsLog::commonLog(INFO, 'http request cost ' . round(microtime(true) - $start, 3) * 1000 . ' ms');
  541. $statusCode = $response -> getStatusCode();
  542. $readable = isset($params['Body']) && ($params['Body'] instanceof StreamInterface || is_resource($params['Body']));
  543. if($statusCode === 307 && !$readable){
  544. if($location = $response -> getHeaderLine('location')){
  545. $url = parse_url($this->endpoint);
  546. $newUrl = parse_url($location);
  547. $scheme = (isset($newUrl['scheme']) ? $newUrl['scheme'] : $url['scheme']);
  548. $defaultPort = strtolower($scheme) === 'https' ? '443' : '80';
  549. return $this->doRequestAsync($model, $operation, $params, $callback, $startAsync, $originMethod, $scheme. '://' . $newUrl['host'] .
  550. ':' . (isset($newUrl['port']) ? $newUrl['port'] : $defaultPort));
  551. }
  552. }
  553. $this -> parseResponse($model, $request, $response, $operation);
  554. ObsLog::commonLog(INFO, 'obsclient cost ' . round(microtime(true) - $startAsync, 3) * 1000 . ' ms to execute '. $originMethod);
  555. unset($model['method']);
  556. $callback(null, $model);
  557. },
  558. function (RequestException $exception) use ($model, $operation, $params, $callback, $startAsync, $originMethod, $request, $start, $requestCount){
  559. ObsLog::commonLog(INFO, 'http request cost ' . round(microtime(true) - $start, 3) * 1000 . ' ms');
  560. $message = null;
  561. if($exception instanceof ConnectException){
  562. if($requestCount <= $this->maxRetryCount){
  563. return $this -> sendRequestAsync($model, $operation, $params, $callback, $startAsync, $originMethod, $request, $requestCount + 1);
  564. }else{
  565. $message = 'Exceeded retry limitation, max retry count:'. $this->maxRetryCount . ', error message:' . $exception -> getMessage();
  566. }
  567. }
  568. $obsException = $this -> parseExceptionAsync($request, $exception, $message);
  569. ObsLog::commonLog(INFO, 'obsclient cost ' . round(microtime(true) - $startAsync, 3) * 1000 . ' ms to execute '. $originMethod);
  570. $callback($obsException, null);
  571. }
  572. );
  573. }
  574. }