client.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762
  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) {
  265. if client.EndpointType == "regional" {
  266. endpointRaw = strings.Replace("<product><network>.<region_id>.aliyuncs.com", "<region_id>", regionId, 1)
  267. } else {
  268. endpointRaw = "<product><network>.aliyuncs.com"
  269. }
  270. endpointRaw = strings.Replace(endpointRaw, "<product>", strings.ToLower(product), 1)
  271. if client.Network == "" || client.Network == "public" {
  272. endpointRaw = strings.Replace(endpointRaw, "<network>", "", 1)
  273. } else {
  274. endpointRaw = strings.Replace(endpointRaw, "<network>", "-"+client.Network, 1)
  275. }
  276. return endpointRaw
  277. }
  278. func (client *Client) buildRequestWithSigner(request requests.AcsRequest, signer auth.Signer) (httpRequest *http.Request, err error) {
  279. // add clientVersion
  280. request.GetHeaders()["x-sdk-core-version"] = Version
  281. regionId := client.regionId
  282. if len(request.GetRegionId()) > 0 {
  283. regionId = request.GetRegionId()
  284. }
  285. // resolve endpoint
  286. endpoint := request.GetDomain()
  287. if endpoint == "" && client.EndpointType != "" {
  288. if client.EndpointMap != nil && client.Network == "" || client.Network == "public" {
  289. endpoint = client.EndpointMap[regionId]
  290. }
  291. if endpoint == "" {
  292. endpoint = client.GetEndpointRules(regionId, request.GetProduct())
  293. }
  294. }
  295. if endpoint == "" {
  296. resolveParam := &endpoints.ResolveParam{
  297. Domain: request.GetDomain(),
  298. Product: request.GetProduct(),
  299. RegionId: regionId,
  300. LocationProduct: request.GetLocationServiceCode(),
  301. LocationEndpointType: request.GetLocationEndpointType(),
  302. CommonApi: client.ProcessCommonRequest,
  303. }
  304. endpoint, err = endpoints.Resolve(resolveParam)
  305. if err != nil {
  306. return
  307. }
  308. }
  309. request.SetDomain(endpoint)
  310. if request.GetScheme() == "" {
  311. request.SetScheme(client.config.Scheme)
  312. }
  313. // init request params
  314. err = requests.InitParams(request)
  315. if err != nil {
  316. return
  317. }
  318. // signature
  319. var finalSigner auth.Signer
  320. if signer != nil {
  321. finalSigner = signer
  322. } else {
  323. finalSigner = client.signer
  324. }
  325. httpRequest, err = buildHttpRequest(request, finalSigner, regionId)
  326. if err == nil {
  327. userAgent := DefaultUserAgent + getSendUserAgent(client.config.UserAgent, client.userAgent, request.GetUserAgent())
  328. httpRequest.Header.Set("User-Agent", userAgent)
  329. }
  330. return
  331. }
  332. func getSendUserAgent(configUserAgent string, clientUserAgent, requestUserAgent map[string]string) string {
  333. realUserAgent := ""
  334. for key1, value1 := range clientUserAgent {
  335. for key2, _ := range requestUserAgent {
  336. if key1 == key2 {
  337. key1 = ""
  338. }
  339. }
  340. if key1 != "" {
  341. realUserAgent += fmt.Sprintf(" %s/%s", key1, value1)
  342. }
  343. }
  344. for key, value := range requestUserAgent {
  345. realUserAgent += fmt.Sprintf(" %s/%s", key, value)
  346. }
  347. if configUserAgent != "" {
  348. return realUserAgent + fmt.Sprintf(" Extra/%s", configUserAgent)
  349. }
  350. return realUserAgent
  351. }
  352. func (client *Client) AppendUserAgent(key, value string) {
  353. newkey := true
  354. if client.userAgent == nil {
  355. client.userAgent = make(map[string]string)
  356. }
  357. if strings.ToLower(key) != "core" && strings.ToLower(key) != "go" {
  358. for tag, _ := range client.userAgent {
  359. if tag == key {
  360. client.userAgent[tag] = value
  361. newkey = false
  362. }
  363. }
  364. if newkey {
  365. client.userAgent[key] = value
  366. }
  367. }
  368. }
  369. func (client *Client) BuildRequestWithSigner(request requests.AcsRequest, signer auth.Signer) (err error) {
  370. _, err = client.buildRequestWithSigner(request, signer)
  371. return
  372. }
  373. func (client *Client) getTimeout(request requests.AcsRequest) (time.Duration, time.Duration) {
  374. readTimeout := defaultReadTimeout
  375. connectTimeout := defaultConnectTimeout
  376. reqReadTimeout := request.GetReadTimeout()
  377. reqConnectTimeout := request.GetConnectTimeout()
  378. if reqReadTimeout != 0*time.Millisecond {
  379. readTimeout = reqReadTimeout
  380. } else if client.readTimeout != 0*time.Millisecond {
  381. readTimeout = client.readTimeout
  382. } else if client.httpClient.Timeout != 0 && client.httpClient.Timeout != 10000000000 {
  383. readTimeout = client.httpClient.Timeout
  384. }
  385. if reqConnectTimeout != 0*time.Millisecond {
  386. connectTimeout = reqConnectTimeout
  387. } else if client.connectTimeout != 0*time.Millisecond {
  388. connectTimeout = client.connectTimeout
  389. }
  390. return readTimeout, connectTimeout
  391. }
  392. func Timeout(connectTimeout time.Duration) func(cxt context.Context, net, addr string) (c net.Conn, err error) {
  393. return func(ctx context.Context, network, address string) (net.Conn, error) {
  394. return (&net.Dialer{
  395. Timeout: connectTimeout,
  396. DualStack: true,
  397. }).DialContext(ctx, network, address)
  398. }
  399. }
  400. func (client *Client) setTimeout(request requests.AcsRequest) {
  401. readTimeout, connectTimeout := client.getTimeout(request)
  402. client.httpClient.Timeout = readTimeout
  403. if trans, ok := client.httpClient.Transport.(*http.Transport); ok && trans != nil {
  404. trans.DialContext = Timeout(connectTimeout)
  405. client.httpClient.Transport = trans
  406. } else {
  407. client.httpClient.Transport = &http.Transport{
  408. DialContext: Timeout(connectTimeout),
  409. }
  410. }
  411. }
  412. func (client *Client) getHTTPSInsecure(request requests.AcsRequest) (insecure bool) {
  413. if request.GetHTTPSInsecure() != nil {
  414. insecure = *request.GetHTTPSInsecure()
  415. } else {
  416. insecure = client.GetHTTPSInsecure()
  417. }
  418. return insecure
  419. }
  420. func (client *Client) DoActionWithSigner(request requests.AcsRequest, response responses.AcsResponse, signer auth.Signer) (err error) {
  421. fieldMap := make(map[string]string)
  422. initLogMsg(fieldMap)
  423. defer func() {
  424. client.printLog(fieldMap, err)
  425. }()
  426. httpRequest, err := client.buildRequestWithSigner(request, signer)
  427. if err != nil {
  428. return
  429. }
  430. client.setTimeout(request)
  431. proxy, err := client.getHttpProxy(httpRequest.URL.Scheme)
  432. if err != nil {
  433. return err
  434. }
  435. noProxy := client.getNoProxy(httpRequest.URL.Scheme)
  436. var flag bool
  437. for _, value := range noProxy {
  438. if value == httpRequest.Host {
  439. flag = true
  440. break
  441. }
  442. }
  443. // Set whether to ignore certificate validation.
  444. // Default InsecureSkipVerify is false.
  445. if trans, ok := client.httpClient.Transport.(*http.Transport); ok && trans != nil {
  446. trans.TLSClientConfig = &tls.Config{
  447. InsecureSkipVerify: client.getHTTPSInsecure(request),
  448. }
  449. if proxy != nil && !flag {
  450. trans.Proxy = http.ProxyURL(proxy)
  451. }
  452. client.httpClient.Transport = trans
  453. }
  454. var httpResponse *http.Response
  455. for retryTimes := 0; retryTimes <= client.config.MaxRetryTime; retryTimes++ {
  456. if proxy != nil && proxy.User != nil {
  457. if password, passwordSet := proxy.User.Password(); passwordSet {
  458. httpRequest.SetBasicAuth(proxy.User.Username(), password)
  459. }
  460. }
  461. if retryTimes > 0 {
  462. client.printLog(fieldMap, err)
  463. initLogMsg(fieldMap)
  464. }
  465. putMsgToMap(fieldMap, httpRequest)
  466. debug("> %s %s %s", httpRequest.Method, httpRequest.URL.RequestURI(), httpRequest.Proto)
  467. debug("> Host: %s", httpRequest.Host)
  468. for key, value := range httpRequest.Header {
  469. debug("> %s: %v", key, strings.Join(value, ""))
  470. }
  471. debug(">")
  472. debug(" Retry Times: %d.", retryTimes)
  473. startTime := time.Now()
  474. fieldMap["{start_time}"] = startTime.Format("2006-01-02 15:04:05")
  475. httpResponse, err = hookDo(client.httpClient.Do)(httpRequest)
  476. fieldMap["{cost}"] = time.Now().Sub(startTime).String()
  477. if err == nil {
  478. fieldMap["{code}"] = strconv.Itoa(httpResponse.StatusCode)
  479. fieldMap["{res_headers}"] = TransToString(httpResponse.Header)
  480. debug("< %s %s", httpResponse.Proto, httpResponse.Status)
  481. for key, value := range httpResponse.Header {
  482. debug("< %s: %v", key, strings.Join(value, ""))
  483. }
  484. }
  485. debug("<")
  486. // receive error
  487. if err != nil {
  488. debug(" Error: %s.", err.Error())
  489. if !client.config.AutoRetry {
  490. return
  491. } else if retryTimes >= client.config.MaxRetryTime {
  492. // timeout but reached the max retry times, return
  493. times := strconv.Itoa(retryTimes + 1)
  494. timeoutErrorMsg := fmt.Sprintf(errors.TimeoutErrorMessage, times, times)
  495. if strings.Contains(err.Error(), "Client.Timeout") {
  496. timeoutErrorMsg += " Read timeout. Please set a valid ReadTimeout."
  497. } else {
  498. timeoutErrorMsg += " Connect timeout. Please set a valid ConnectTimeout."
  499. }
  500. err = errors.NewClientError(errors.TimeoutErrorCode, timeoutErrorMsg, err)
  501. return
  502. }
  503. }
  504. // if status code >= 500 or timeout, will trigger retry
  505. if client.config.AutoRetry && (err != nil || isServerError(httpResponse)) {
  506. client.setTimeout(request)
  507. // rewrite signatureNonce and signature
  508. httpRequest, err = client.buildRequestWithSigner(request, signer)
  509. // buildHttpRequest(request, finalSigner, regionId)
  510. if err != nil {
  511. return
  512. }
  513. continue
  514. }
  515. break
  516. }
  517. err = responses.Unmarshal(response, httpResponse, request.GetAcceptFormat())
  518. // wrap server errors
  519. if serverErr, ok := err.(*errors.ServerError); ok {
  520. var wrapInfo = map[string]string{}
  521. wrapInfo["StringToSign"] = request.GetStringToSign()
  522. err = errors.WrapServerError(serverErr, wrapInfo)
  523. }
  524. return
  525. }
  526. func putMsgToMap(fieldMap map[string]string, request *http.Request) {
  527. fieldMap["{host}"] = request.Host
  528. fieldMap["{method}"] = request.Method
  529. fieldMap["{uri}"] = request.URL.RequestURI()
  530. fieldMap["{pid}"] = strconv.Itoa(os.Getpid())
  531. fieldMap["{version}"] = strings.Split(request.Proto, "/")[1]
  532. hostname, _ := os.Hostname()
  533. fieldMap["{hostname}"] = hostname
  534. fieldMap["{req_headers}"] = TransToString(request.Header)
  535. fieldMap["{target}"] = request.URL.Path + request.URL.RawQuery
  536. }
  537. func buildHttpRequest(request requests.AcsRequest, singer auth.Signer, regionId string) (httpRequest *http.Request, err error) {
  538. err = auth.Sign(request, singer, regionId)
  539. if err != nil {
  540. return
  541. }
  542. requestMethod := request.GetMethod()
  543. requestUrl := request.BuildUrl()
  544. body := request.GetBodyReader()
  545. httpRequest, err = http.NewRequest(requestMethod, requestUrl, body)
  546. if err != nil {
  547. return
  548. }
  549. for key, value := range request.GetHeaders() {
  550. httpRequest.Header[key] = []string{value}
  551. }
  552. // host is a special case
  553. if host, containsHost := request.GetHeaders()["Host"]; containsHost {
  554. httpRequest.Host = host
  555. }
  556. return
  557. }
  558. func isServerError(httpResponse *http.Response) bool {
  559. return httpResponse.StatusCode >= http.StatusInternalServerError
  560. }
  561. /**
  562. only block when any one of the following occurs:
  563. 1. the asyncTaskQueue is full, increase the queue size to avoid this
  564. 2. Shutdown() in progressing, the client is being closed
  565. **/
  566. func (client *Client) AddAsyncTask(task func()) (err error) {
  567. if client.asyncTaskQueue != nil {
  568. client.asyncChanLock.RLock()
  569. defer client.asyncChanLock.RUnlock()
  570. if client.isRunning {
  571. client.asyncTaskQueue <- task
  572. }
  573. } else {
  574. err = errors.NewClientError(errors.AsyncFunctionNotEnabledCode, errors.AsyncFunctionNotEnabledMessage, nil)
  575. }
  576. return
  577. }
  578. func (client *Client) GetConfig() *Config {
  579. return client.config
  580. }
  581. func NewClient() (client *Client, err error) {
  582. client = &Client{}
  583. err = client.Init()
  584. return
  585. }
  586. func NewClientWithProvider(regionId string, providers ...provider.Provider) (client *Client, err error) {
  587. client = &Client{}
  588. var pc provider.Provider
  589. if len(providers) == 0 {
  590. pc = provider.DefaultChain
  591. } else {
  592. pc = provider.NewProviderChain(providers)
  593. }
  594. err = client.InitWithProviderChain(regionId, pc)
  595. return
  596. }
  597. func NewClientWithOptions(regionId string, config *Config, credential auth.Credential) (client *Client, err error) {
  598. client = &Client{}
  599. err = client.InitWithOptions(regionId, config, credential)
  600. return
  601. }
  602. func NewClientWithAccessKey(regionId, accessKeyId, accessKeySecret string) (client *Client, err error) {
  603. client = &Client{}
  604. err = client.InitWithAccessKey(regionId, accessKeyId, accessKeySecret)
  605. return
  606. }
  607. func NewClientWithStsToken(regionId, stsAccessKeyId, stsAccessKeySecret, stsToken string) (client *Client, err error) {
  608. client = &Client{}
  609. err = client.InitWithStsToken(regionId, stsAccessKeyId, stsAccessKeySecret, stsToken)
  610. return
  611. }
  612. func NewClientWithRamRoleArn(regionId string, accessKeyId, accessKeySecret, roleArn, roleSessionName string) (client *Client, err error) {
  613. client = &Client{}
  614. err = client.InitWithRamRoleArn(regionId, accessKeyId, accessKeySecret, roleArn, roleSessionName)
  615. return
  616. }
  617. func NewClientWithRamRoleArnAndPolicy(regionId string, accessKeyId, accessKeySecret, roleArn, roleSessionName, policy string) (client *Client, err error) {
  618. client = &Client{}
  619. err = client.InitWithRamRoleArnAndPolicy(regionId, accessKeyId, accessKeySecret, roleArn, roleSessionName, policy)
  620. return
  621. }
  622. func NewClientWithEcsRamRole(regionId string, roleName string) (client *Client, err error) {
  623. client = &Client{}
  624. err = client.InitWithEcsRamRole(regionId, roleName)
  625. return
  626. }
  627. func NewClientWithRsaKeyPair(regionId string, publicKeyId, privateKey string, sessionExpiration int) (client *Client, err error) {
  628. client = &Client{}
  629. err = client.InitWithRsaKeyPair(regionId, publicKeyId, privateKey, sessionExpiration)
  630. return
  631. }
  632. func NewClientWithBearerToken(regionId, bearerToken string) (client *Client, err error) {
  633. client = &Client{}
  634. err = client.InitWithBearerToken(regionId, bearerToken)
  635. return
  636. }
  637. func (client *Client) ProcessCommonRequest(request *requests.CommonRequest) (response *responses.CommonResponse, err error) {
  638. request.TransToAcsRequest()
  639. response = responses.NewCommonResponse()
  640. err = client.DoAction(request, response)
  641. return
  642. }
  643. func (client *Client) ProcessCommonRequestWithSigner(request *requests.CommonRequest, signerInterface interface{}) (response *responses.CommonResponse, err error) {
  644. if signer, isSigner := signerInterface.(auth.Signer); isSigner {
  645. request.TransToAcsRequest()
  646. response = responses.NewCommonResponse()
  647. err = client.DoActionWithSigner(request, response, signer)
  648. return
  649. }
  650. panic("should not be here")
  651. }
  652. func (client *Client) Shutdown() {
  653. // lock the addAsync()
  654. client.asyncChanLock.Lock()
  655. defer client.asyncChanLock.Unlock()
  656. if client.asyncTaskQueue != nil {
  657. close(client.asyncTaskQueue)
  658. }
  659. client.isRunning = false
  660. }
  661. // Deprecated: Use NewClientWithRamRoleArn in this package instead.
  662. func NewClientWithStsRoleArn(regionId string, accessKeyId, accessKeySecret, roleArn, roleSessionName string) (client *Client, err error) {
  663. return NewClientWithRamRoleArn(regionId, accessKeyId, accessKeySecret, roleArn, roleSessionName)
  664. }
  665. // Deprecated: Use NewClientWithEcsRamRole in this package instead.
  666. func NewClientWithStsRoleNameOnEcs(regionId string, roleName string) (client *Client, err error) {
  667. return NewClientWithEcsRamRole(regionId, roleName)
  668. }