client.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794
  1. /*
  2. * Licensed under the Apache License, Version 2.0 (the "License");
  3. * you may not use this file except in compliance with the License.
  4. * You may obtain a copy of the License at
  5. *
  6. * http://www.apache.org/licenses/LICENSE-2.0
  7. *
  8. * Unless required by applicable law or agreed to in writing, software
  9. * distributed under the License is distributed on an "AS IS" BASIS,
  10. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. * See the License for the specific language governing permissions and
  12. * limitations under the License.
  13. */
  14. package sdk
  15. import (
  16. "context"
  17. "crypto/tls"
  18. "fmt"
  19. "net"
  20. "net/http"
  21. "net/url"
  22. "os"
  23. "runtime"
  24. "strconv"
  25. "strings"
  26. "sync"
  27. "time"
  28. "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth"
  29. "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials"
  30. "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/provider"
  31. "github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints"
  32. "github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors"
  33. "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
  34. "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
  35. "github.com/aliyun/alibaba-cloud-sdk-go/sdk/utils"
  36. )
  37. var debug utils.Debug
  38. func init() {
  39. debug = utils.Init("sdk")
  40. }
  41. // Version this value will be replaced while build: -ldflags="-X sdk.version=x.x.x"
  42. var Version = "0.0.1"
  43. var defaultConnectTimeout = 5 * time.Second
  44. var defaultReadTimeout = 10 * time.Second
  45. var DefaultUserAgent = fmt.Sprintf("AlibabaCloud (%s; %s) Golang/%s Core/%s", runtime.GOOS, runtime.GOARCH, strings.Trim(runtime.Version(), "go"), Version)
  46. var hookDo = func(fn func(req *http.Request) (*http.Response, error)) func(req *http.Request) (*http.Response, error) {
  47. return fn
  48. }
  49. // Client the type Client
  50. type Client struct {
  51. isInsecure bool
  52. regionId string
  53. config *Config
  54. httpProxy string
  55. httpsProxy string
  56. noProxy string
  57. logger *Logger
  58. userAgent map[string]string
  59. signer auth.Signer
  60. httpClient *http.Client
  61. asyncTaskQueue chan func()
  62. readTimeout time.Duration
  63. connectTimeout time.Duration
  64. EndpointMap map[string]string
  65. EndpointType string
  66. Network string
  67. Domain string
  68. debug bool
  69. isRunning bool
  70. // void "panic(write to close channel)" cause of addAsync() after Shutdown()
  71. asyncChanLock *sync.RWMutex
  72. }
  73. func (client *Client) Init() (err error) {
  74. panic("not support yet")
  75. }
  76. func (client *Client) SetEndpointRules(endpointMap map[string]string, endpointType string, netWork string) {
  77. client.EndpointMap = endpointMap
  78. client.Network = netWork
  79. client.EndpointType = endpointType
  80. }
  81. func (client *Client) SetHTTPSInsecure(isInsecure bool) {
  82. client.isInsecure = isInsecure
  83. }
  84. func (client *Client) GetHTTPSInsecure() bool {
  85. return client.isInsecure
  86. }
  87. func (client *Client) SetHttpsProxy(httpsProxy string) {
  88. client.httpsProxy = httpsProxy
  89. }
  90. func (client *Client) GetHttpsProxy() string {
  91. return client.httpsProxy
  92. }
  93. func (client *Client) SetHttpProxy(httpProxy string) {
  94. client.httpProxy = httpProxy
  95. }
  96. func (client *Client) GetHttpProxy() string {
  97. return client.httpProxy
  98. }
  99. func (client *Client) SetNoProxy(noProxy string) {
  100. client.noProxy = noProxy
  101. }
  102. func (client *Client) GetNoProxy() string {
  103. return client.noProxy
  104. }
  105. // InitWithProviderChain will get credential from the providerChain,
  106. // the RsaKeyPairCredential Only applicable to regionID `ap-northeast-1`,
  107. // if your providerChain may return a credential type with RsaKeyPairCredential,
  108. // please ensure your regionID is `ap-northeast-1`.
  109. func (client *Client) InitWithProviderChain(regionId string, provider provider.Provider) (err error) {
  110. config := client.InitClientConfig()
  111. credential, err := provider.Resolve()
  112. if err != nil {
  113. return
  114. }
  115. return client.InitWithOptions(regionId, config, credential)
  116. }
  117. func (client *Client) InitWithOptions(regionId string, config *Config, credential auth.Credential) (err error) {
  118. client.isRunning = true
  119. client.asyncChanLock = new(sync.RWMutex)
  120. client.regionId = regionId
  121. client.config = config
  122. client.httpClient = &http.Client{}
  123. if config.HttpTransport != nil {
  124. client.httpClient.Transport = config.HttpTransport
  125. }
  126. if config.Timeout > 0 {
  127. client.httpClient.Timeout = config.Timeout
  128. }
  129. if config.EnableAsync {
  130. client.EnableAsync(config.GoRoutinePoolSize, config.MaxTaskQueueSize)
  131. }
  132. client.signer, err = auth.NewSignerWithCredential(credential, client.ProcessCommonRequestWithSigner)
  133. return
  134. }
  135. func (client *Client) SetReadTimeout(readTimeout time.Duration) {
  136. client.readTimeout = readTimeout
  137. }
  138. func (client *Client) SetConnectTimeout(connectTimeout time.Duration) {
  139. client.connectTimeout = connectTimeout
  140. }
  141. func (client *Client) GetReadTimeout() time.Duration {
  142. return client.readTimeout
  143. }
  144. func (client *Client) GetConnectTimeout() time.Duration {
  145. return client.connectTimeout
  146. }
  147. func (client *Client) getHttpProxy(scheme string) (proxy *url.URL, err error) {
  148. if scheme == "https" {
  149. if client.GetHttpsProxy() != "" {
  150. proxy, err = url.Parse(client.httpsProxy)
  151. } else if rawurl := os.Getenv("HTTPS_PROXY"); rawurl != "" {
  152. proxy, err = url.Parse(rawurl)
  153. } else if rawurl := os.Getenv("https_proxy"); rawurl != "" {
  154. proxy, err = url.Parse(rawurl)
  155. }
  156. } else {
  157. if client.GetHttpProxy() != "" {
  158. proxy, err = url.Parse(client.httpProxy)
  159. } else if rawurl := os.Getenv("HTTP_PROXY"); rawurl != "" {
  160. proxy, err = url.Parse(rawurl)
  161. } else if rawurl := os.Getenv("http_proxy"); rawurl != "" {
  162. proxy, err = url.Parse(rawurl)
  163. }
  164. }
  165. return proxy, err
  166. }
  167. func (client *Client) getNoProxy(scheme string) []string {
  168. var urls []string
  169. if client.GetNoProxy() != "" {
  170. urls = strings.Split(client.noProxy, ",")
  171. } else if rawurl := os.Getenv("NO_PROXY"); rawurl != "" {
  172. urls = strings.Split(rawurl, ",")
  173. } else if rawurl := os.Getenv("no_proxy"); rawurl != "" {
  174. urls = strings.Split(rawurl, ",")
  175. }
  176. return urls
  177. }
  178. // EnableAsync enable the async task queue
  179. func (client *Client) EnableAsync(routinePoolSize, maxTaskQueueSize int) {
  180. client.asyncTaskQueue = make(chan func(), maxTaskQueueSize)
  181. for i := 0; i < routinePoolSize; i++ {
  182. go func() {
  183. for client.isRunning {
  184. select {
  185. case task, notClosed := <-client.asyncTaskQueue:
  186. if notClosed {
  187. task()
  188. }
  189. }
  190. }
  191. }()
  192. }
  193. }
  194. func (client *Client) InitWithAccessKey(regionId, accessKeyId, accessKeySecret string) (err error) {
  195. config := client.InitClientConfig()
  196. credential := &credentials.BaseCredential{
  197. AccessKeyId: accessKeyId,
  198. AccessKeySecret: accessKeySecret,
  199. }
  200. return client.InitWithOptions(regionId, config, credential)
  201. }
  202. func (client *Client) InitWithStsToken(regionId, accessKeyId, accessKeySecret, securityToken string) (err error) {
  203. config := client.InitClientConfig()
  204. credential := &credentials.StsTokenCredential{
  205. AccessKeyId: accessKeyId,
  206. AccessKeySecret: accessKeySecret,
  207. AccessKeyStsToken: securityToken,
  208. }
  209. return client.InitWithOptions(regionId, config, credential)
  210. }
  211. func (client *Client) InitWithRamRoleArn(regionId, accessKeyId, accessKeySecret, roleArn, roleSessionName string) (err error) {
  212. config := client.InitClientConfig()
  213. credential := &credentials.RamRoleArnCredential{
  214. AccessKeyId: accessKeyId,
  215. AccessKeySecret: accessKeySecret,
  216. RoleArn: roleArn,
  217. RoleSessionName: roleSessionName,
  218. }
  219. return client.InitWithOptions(regionId, config, credential)
  220. }
  221. func (client *Client) InitWithRamRoleArnAndPolicy(regionId, accessKeyId, accessKeySecret, roleArn, roleSessionName, policy string) (err error) {
  222. config := client.InitClientConfig()
  223. credential := &credentials.RamRoleArnCredential{
  224. AccessKeyId: accessKeyId,
  225. AccessKeySecret: accessKeySecret,
  226. RoleArn: roleArn,
  227. RoleSessionName: roleSessionName,
  228. Policy: policy,
  229. }
  230. return client.InitWithOptions(regionId, config, credential)
  231. }
  232. func (client *Client) InitWithRsaKeyPair(regionId, publicKeyId, privateKey string, sessionExpiration int) (err error) {
  233. config := client.InitClientConfig()
  234. credential := &credentials.RsaKeyPairCredential{
  235. PrivateKey: privateKey,
  236. PublicKeyId: publicKeyId,
  237. SessionExpiration: sessionExpiration,
  238. }
  239. return client.InitWithOptions(regionId, config, credential)
  240. }
  241. func (client *Client) InitWithEcsRamRole(regionId, roleName string) (err error) {
  242. config := client.InitClientConfig()
  243. credential := &credentials.EcsRamRoleCredential{
  244. RoleName: roleName,
  245. }
  246. return client.InitWithOptions(regionId, config, credential)
  247. }
  248. func (client *Client) InitWithBearerToken(regionId, bearerToken string) (err error) {
  249. config := client.InitClientConfig()
  250. credential := &credentials.BearerTokenCredential{
  251. BearerToken: bearerToken,
  252. }
  253. return client.InitWithOptions(regionId, config, credential)
  254. }
  255. func (client *Client) InitClientConfig() (config *Config) {
  256. if client.config != nil {
  257. return client.config
  258. } else {
  259. return NewConfig()
  260. }
  261. }
  262. func (client *Client) DoAction(request requests.AcsRequest, response responses.AcsResponse) (err error) {
  263. return client.DoActionWithSigner(request, response, nil)
  264. }
  265. func (client *Client) GetEndpointRules(regionId string, product string) (endpointRaw string, err error) {
  266. if client.EndpointType == "regional" {
  267. if regionId == "" {
  268. err = fmt.Errorf("RegionId is empty, please set a valid RegionId.")
  269. return "", err
  270. }
  271. endpointRaw = strings.Replace("<product><network>.<region_id>.aliyuncs.com", "<region_id>", regionId, 1)
  272. } else {
  273. endpointRaw = "<product><network>.aliyuncs.com"
  274. }
  275. endpointRaw = strings.Replace(endpointRaw, "<product>", strings.ToLower(product), 1)
  276. if client.Network == "" || client.Network == "public" {
  277. endpointRaw = strings.Replace(endpointRaw, "<network>", "", 1)
  278. } else {
  279. endpointRaw = strings.Replace(endpointRaw, "<network>", "-"+client.Network, 1)
  280. }
  281. return endpointRaw, nil
  282. }
  283. func (client *Client) buildRequestWithSigner(request requests.AcsRequest, signer auth.Signer) (httpRequest *http.Request, err error) {
  284. // add clientVersion
  285. request.GetHeaders()["x-sdk-core-version"] = Version
  286. regionId := client.regionId
  287. if len(request.GetRegionId()) > 0 {
  288. regionId = request.GetRegionId()
  289. }
  290. // resolve endpoint
  291. endpoint := request.GetDomain()
  292. if endpoint == "" && client.Domain != "" {
  293. endpoint = client.Domain
  294. }
  295. if endpoint == "" {
  296. endpoint = endpoints.GetEndpointFromMap(regionId, request.GetProduct())
  297. }
  298. if endpoint == "" && client.EndpointType != "" && request.GetProduct() != "Sts" {
  299. if client.EndpointMap != nil && client.Network == "" || client.Network == "public" {
  300. endpoint = client.EndpointMap[regionId]
  301. }
  302. if endpoint == "" {
  303. endpoint, err = client.GetEndpointRules(regionId, request.GetProduct())
  304. if err != nil {
  305. return
  306. }
  307. }
  308. }
  309. if endpoint == "" {
  310. resolveParam := &endpoints.ResolveParam{
  311. Domain: request.GetDomain(),
  312. Product: request.GetProduct(),
  313. RegionId: regionId,
  314. LocationProduct: request.GetLocationServiceCode(),
  315. LocationEndpointType: request.GetLocationEndpointType(),
  316. CommonApi: client.ProcessCommonRequest,
  317. }
  318. endpoint, err = endpoints.Resolve(resolveParam)
  319. if err != nil {
  320. return
  321. }
  322. }
  323. request.SetDomain(endpoint)
  324. if request.GetScheme() == "" {
  325. request.SetScheme(client.config.Scheme)
  326. }
  327. // init request params
  328. err = requests.InitParams(request)
  329. if err != nil {
  330. return
  331. }
  332. // signature
  333. var finalSigner auth.Signer
  334. if signer != nil {
  335. finalSigner = signer
  336. } else {
  337. finalSigner = client.signer
  338. }
  339. httpRequest, err = buildHttpRequest(request, finalSigner, regionId)
  340. if err == nil {
  341. userAgent := DefaultUserAgent + getSendUserAgent(client.config.UserAgent, client.userAgent, request.GetUserAgent())
  342. httpRequest.Header.Set("User-Agent", userAgent)
  343. }
  344. return
  345. }
  346. func getSendUserAgent(configUserAgent string, clientUserAgent, requestUserAgent map[string]string) string {
  347. realUserAgent := ""
  348. for key1, value1 := range clientUserAgent {
  349. for key2, _ := range requestUserAgent {
  350. if key1 == key2 {
  351. key1 = ""
  352. }
  353. }
  354. if key1 != "" {
  355. realUserAgent += fmt.Sprintf(" %s/%s", key1, value1)
  356. }
  357. }
  358. for key, value := range requestUserAgent {
  359. realUserAgent += fmt.Sprintf(" %s/%s", key, value)
  360. }
  361. if configUserAgent != "" {
  362. return realUserAgent + fmt.Sprintf(" Extra/%s", configUserAgent)
  363. }
  364. return realUserAgent
  365. }
  366. func (client *Client) AppendUserAgent(key, value string) {
  367. newkey := true
  368. if client.userAgent == nil {
  369. client.userAgent = make(map[string]string)
  370. }
  371. if strings.ToLower(key) != "core" && strings.ToLower(key) != "go" {
  372. for tag, _ := range client.userAgent {
  373. if tag == key {
  374. client.userAgent[tag] = value
  375. newkey = false
  376. }
  377. }
  378. if newkey {
  379. client.userAgent[key] = value
  380. }
  381. }
  382. }
  383. func (client *Client) BuildRequestWithSigner(request requests.AcsRequest, signer auth.Signer) (err error) {
  384. _, err = client.buildRequestWithSigner(request, signer)
  385. return
  386. }
  387. func (client *Client) getTimeout(request requests.AcsRequest) (time.Duration, time.Duration) {
  388. readTimeout := defaultReadTimeout
  389. connectTimeout := defaultConnectTimeout
  390. reqReadTimeout := request.GetReadTimeout()
  391. reqConnectTimeout := request.GetConnectTimeout()
  392. if reqReadTimeout != 0*time.Millisecond {
  393. readTimeout = reqReadTimeout
  394. } else if client.readTimeout != 0*time.Millisecond {
  395. readTimeout = client.readTimeout
  396. } else if client.httpClient.Timeout != 0 {
  397. readTimeout = client.httpClient.Timeout
  398. } else if timeout, ok := getAPIMaxTimeout(request.GetProduct(), request.GetActionName()); ok {
  399. readTimeout = timeout
  400. }
  401. if reqConnectTimeout != 0*time.Millisecond {
  402. connectTimeout = reqConnectTimeout
  403. } else if client.connectTimeout != 0*time.Millisecond {
  404. connectTimeout = client.connectTimeout
  405. }
  406. return readTimeout, connectTimeout
  407. }
  408. func Timeout(connectTimeout time.Duration) func(cxt context.Context, net, addr string) (c net.Conn, err error) {
  409. return func(ctx context.Context, network, address string) (net.Conn, error) {
  410. return (&net.Dialer{
  411. Timeout: connectTimeout,
  412. DualStack: true,
  413. }).DialContext(ctx, network, address)
  414. }
  415. }
  416. func (client *Client) setTimeout(request requests.AcsRequest) {
  417. readTimeout, connectTimeout := client.getTimeout(request)
  418. client.httpClient.Timeout = readTimeout
  419. if trans, ok := client.httpClient.Transport.(*http.Transport); ok && trans != nil {
  420. trans.DialContext = Timeout(connectTimeout)
  421. client.httpClient.Transport = trans
  422. } else {
  423. client.httpClient.Transport = &http.Transport{
  424. DialContext: Timeout(connectTimeout),
  425. }
  426. }
  427. }
  428. func (client *Client) getHTTPSInsecure(request requests.AcsRequest) (insecure bool) {
  429. if request.GetHTTPSInsecure() != nil {
  430. insecure = *request.GetHTTPSInsecure()
  431. } else {
  432. insecure = client.GetHTTPSInsecure()
  433. }
  434. return insecure
  435. }
  436. func (client *Client) DoActionWithSigner(request requests.AcsRequest, response responses.AcsResponse, signer auth.Signer) (err error) {
  437. fieldMap := make(map[string]string)
  438. initLogMsg(fieldMap)
  439. defer func() {
  440. client.printLog(fieldMap, err)
  441. }()
  442. httpRequest, err := client.buildRequestWithSigner(request, signer)
  443. if err != nil {
  444. return
  445. }
  446. client.setTimeout(request)
  447. proxy, err := client.getHttpProxy(httpRequest.URL.Scheme)
  448. if err != nil {
  449. return err
  450. }
  451. noProxy := client.getNoProxy(httpRequest.URL.Scheme)
  452. var flag bool
  453. for _, value := range noProxy {
  454. if value == httpRequest.Host {
  455. flag = true
  456. break
  457. }
  458. }
  459. // Set whether to ignore certificate validation.
  460. // Default InsecureSkipVerify is false.
  461. if trans, ok := client.httpClient.Transport.(*http.Transport); ok && trans != nil {
  462. trans.TLSClientConfig = &tls.Config{
  463. InsecureSkipVerify: client.getHTTPSInsecure(request),
  464. }
  465. if proxy != nil && !flag {
  466. trans.Proxy = http.ProxyURL(proxy)
  467. }
  468. client.httpClient.Transport = trans
  469. }
  470. var httpResponse *http.Response
  471. for retryTimes := 0; retryTimes <= client.config.MaxRetryTime; retryTimes++ {
  472. if proxy != nil && proxy.User != nil {
  473. if password, passwordSet := proxy.User.Password(); passwordSet {
  474. httpRequest.SetBasicAuth(proxy.User.Username(), password)
  475. }
  476. }
  477. if retryTimes > 0 {
  478. client.printLog(fieldMap, err)
  479. initLogMsg(fieldMap)
  480. }
  481. putMsgToMap(fieldMap, httpRequest)
  482. debug("> %s %s %s", httpRequest.Method, httpRequest.URL.RequestURI(), httpRequest.Proto)
  483. debug("> Host: %s", httpRequest.Host)
  484. for key, value := range httpRequest.Header {
  485. debug("> %s: %v", key, strings.Join(value, ""))
  486. }
  487. debug(">")
  488. debug(" Retry Times: %d.", retryTimes)
  489. startTime := time.Now()
  490. fieldMap["{start_time}"] = startTime.Format("2006-01-02 15:04:05")
  491. httpResponse, err = hookDo(client.httpClient.Do)(httpRequest)
  492. fieldMap["{cost}"] = time.Now().Sub(startTime).String()
  493. if err == nil {
  494. fieldMap["{code}"] = strconv.Itoa(httpResponse.StatusCode)
  495. fieldMap["{res_headers}"] = TransToString(httpResponse.Header)
  496. debug("< %s %s", httpResponse.Proto, httpResponse.Status)
  497. for key, value := range httpResponse.Header {
  498. debug("< %s: %v", key, strings.Join(value, ""))
  499. }
  500. }
  501. debug("<")
  502. // receive error
  503. if err != nil {
  504. debug(" Error: %s.", err.Error())
  505. if !client.config.AutoRetry {
  506. return
  507. } else if retryTimes >= client.config.MaxRetryTime {
  508. // timeout but reached the max retry times, return
  509. times := strconv.Itoa(retryTimes + 1)
  510. timeoutErrorMsg := fmt.Sprintf(errors.TimeoutErrorMessage, times, times)
  511. if strings.Contains(err.Error(), "Client.Timeout") {
  512. timeoutErrorMsg += " Read timeout. Please set a valid ReadTimeout."
  513. } else {
  514. timeoutErrorMsg += " Connect timeout. Please set a valid ConnectTimeout."
  515. }
  516. err = errors.NewClientError(errors.TimeoutErrorCode, timeoutErrorMsg, err)
  517. return
  518. }
  519. }
  520. if isCertificateError(err) {
  521. return
  522. }
  523. // if status code >= 500 or timeout, will trigger retry
  524. if client.config.AutoRetry && (err != nil || isServerError(httpResponse)) {
  525. client.setTimeout(request)
  526. // rewrite signatureNonce and signature
  527. httpRequest, err = client.buildRequestWithSigner(request, signer)
  528. // buildHttpRequest(request, finalSigner, regionId)
  529. if err != nil {
  530. return
  531. }
  532. continue
  533. }
  534. break
  535. }
  536. err = responses.Unmarshal(response, httpResponse, request.GetAcceptFormat())
  537. fieldMap["{res_body}"] = response.GetHttpContentString()
  538. debug("%s", response.GetHttpContentString())
  539. // wrap server errors
  540. if serverErr, ok := err.(*errors.ServerError); ok {
  541. var wrapInfo = map[string]string{}
  542. wrapInfo["StringToSign"] = request.GetStringToSign()
  543. err = errors.WrapServerError(serverErr, wrapInfo)
  544. }
  545. return
  546. }
  547. func isCertificateError(err error) bool {
  548. if err != nil && strings.Contains(err.Error(), "x509: certificate signed by unknown authority") {
  549. return true
  550. }
  551. return false
  552. }
  553. func putMsgToMap(fieldMap map[string]string, request *http.Request) {
  554. fieldMap["{host}"] = request.Host
  555. fieldMap["{method}"] = request.Method
  556. fieldMap["{uri}"] = request.URL.RequestURI()
  557. fieldMap["{pid}"] = strconv.Itoa(os.Getpid())
  558. fieldMap["{version}"] = strings.Split(request.Proto, "/")[1]
  559. hostname, _ := os.Hostname()
  560. fieldMap["{hostname}"] = hostname
  561. fieldMap["{req_headers}"] = TransToString(request.Header)
  562. fieldMap["{target}"] = request.URL.Path + request.URL.RawQuery
  563. }
  564. func buildHttpRequest(request requests.AcsRequest, singer auth.Signer, regionId string) (httpRequest *http.Request, err error) {
  565. err = auth.Sign(request, singer, regionId)
  566. if err != nil {
  567. return
  568. }
  569. requestMethod := request.GetMethod()
  570. requestUrl := request.BuildUrl()
  571. body := request.GetBodyReader()
  572. httpRequest, err = http.NewRequest(requestMethod, requestUrl, body)
  573. if err != nil {
  574. return
  575. }
  576. for key, value := range request.GetHeaders() {
  577. httpRequest.Header[key] = []string{value}
  578. }
  579. // host is a special case
  580. if host, containsHost := request.GetHeaders()["Host"]; containsHost {
  581. httpRequest.Host = host
  582. }
  583. return
  584. }
  585. func isServerError(httpResponse *http.Response) bool {
  586. return httpResponse.StatusCode >= http.StatusInternalServerError
  587. }
  588. /**
  589. only block when any one of the following occurs:
  590. 1. the asyncTaskQueue is full, increase the queue size to avoid this
  591. 2. Shutdown() in progressing, the client is being closed
  592. **/
  593. func (client *Client) AddAsyncTask(task func()) (err error) {
  594. if client.asyncTaskQueue != nil {
  595. client.asyncChanLock.RLock()
  596. defer client.asyncChanLock.RUnlock()
  597. if client.isRunning {
  598. client.asyncTaskQueue <- task
  599. }
  600. } else {
  601. err = errors.NewClientError(errors.AsyncFunctionNotEnabledCode, errors.AsyncFunctionNotEnabledMessage, nil)
  602. }
  603. return
  604. }
  605. func (client *Client) GetConfig() *Config {
  606. return client.config
  607. }
  608. func NewClient() (client *Client, err error) {
  609. client = &Client{}
  610. err = client.Init()
  611. return
  612. }
  613. func NewClientWithProvider(regionId string, providers ...provider.Provider) (client *Client, err error) {
  614. client = &Client{}
  615. var pc provider.Provider
  616. if len(providers) == 0 {
  617. pc = provider.DefaultChain
  618. } else {
  619. pc = provider.NewProviderChain(providers)
  620. }
  621. err = client.InitWithProviderChain(regionId, pc)
  622. return
  623. }
  624. func NewClientWithOptions(regionId string, config *Config, credential auth.Credential) (client *Client, err error) {
  625. client = &Client{}
  626. err = client.InitWithOptions(regionId, config, credential)
  627. return
  628. }
  629. func NewClientWithAccessKey(regionId, accessKeyId, accessKeySecret string) (client *Client, err error) {
  630. client = &Client{}
  631. err = client.InitWithAccessKey(regionId, accessKeyId, accessKeySecret)
  632. return
  633. }
  634. func NewClientWithStsToken(regionId, stsAccessKeyId, stsAccessKeySecret, stsToken string) (client *Client, err error) {
  635. client = &Client{}
  636. err = client.InitWithStsToken(regionId, stsAccessKeyId, stsAccessKeySecret, stsToken)
  637. return
  638. }
  639. func NewClientWithRamRoleArn(regionId string, accessKeyId, accessKeySecret, roleArn, roleSessionName string) (client *Client, err error) {
  640. client = &Client{}
  641. err = client.InitWithRamRoleArn(regionId, accessKeyId, accessKeySecret, roleArn, roleSessionName)
  642. return
  643. }
  644. func NewClientWithRamRoleArnAndPolicy(regionId string, accessKeyId, accessKeySecret, roleArn, roleSessionName, policy string) (client *Client, err error) {
  645. client = &Client{}
  646. err = client.InitWithRamRoleArnAndPolicy(regionId, accessKeyId, accessKeySecret, roleArn, roleSessionName, policy)
  647. return
  648. }
  649. func NewClientWithEcsRamRole(regionId string, roleName string) (client *Client, err error) {
  650. client = &Client{}
  651. err = client.InitWithEcsRamRole(regionId, roleName)
  652. return
  653. }
  654. func NewClientWithRsaKeyPair(regionId string, publicKeyId, privateKey string, sessionExpiration int) (client *Client, err error) {
  655. client = &Client{}
  656. err = client.InitWithRsaKeyPair(regionId, publicKeyId, privateKey, sessionExpiration)
  657. return
  658. }
  659. func NewClientWithBearerToken(regionId, bearerToken string) (client *Client, err error) {
  660. client = &Client{}
  661. err = client.InitWithBearerToken(regionId, bearerToken)
  662. return
  663. }
  664. func (client *Client) ProcessCommonRequest(request *requests.CommonRequest) (response *responses.CommonResponse, err error) {
  665. request.TransToAcsRequest()
  666. response = responses.NewCommonResponse()
  667. err = client.DoAction(request, response)
  668. return
  669. }
  670. func (client *Client) ProcessCommonRequestWithSigner(request *requests.CommonRequest, signerInterface interface{}) (response *responses.CommonResponse, err error) {
  671. if signer, isSigner := signerInterface.(auth.Signer); isSigner {
  672. request.TransToAcsRequest()
  673. response = responses.NewCommonResponse()
  674. err = client.DoActionWithSigner(request, response, signer)
  675. return
  676. }
  677. panic("should not be here")
  678. }
  679. func (client *Client) Shutdown() {
  680. // lock the addAsync()
  681. client.asyncChanLock.Lock()
  682. defer client.asyncChanLock.Unlock()
  683. if client.asyncTaskQueue != nil {
  684. close(client.asyncTaskQueue)
  685. }
  686. client.isRunning = false
  687. }
  688. // Deprecated: Use NewClientWithRamRoleArn in this package instead.
  689. func NewClientWithStsRoleArn(regionId string, accessKeyId, accessKeySecret, roleArn, roleSessionName string) (client *Client, err error) {
  690. return NewClientWithRamRoleArn(regionId, accessKeyId, accessKeySecret, roleArn, roleSessionName)
  691. }
  692. // Deprecated: Use NewClientWithEcsRamRole in this package instead.
  693. func NewClientWithStsRoleNameOnEcs(regionId string, roleName string) (client *Client, err error) {
  694. return NewClientWithEcsRamRole(regionId, roleName)
  695. }