client.go 22 KB

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