client.go 21 KB

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