client.go 22 KB

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