client.go 23 KB

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