client.go 20 KB

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