client.go 24 KB

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