client.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  1. /*
  2. * Licensed under the Apache License, Version 2.0 (the "License");
  3. * you may not use this file except in compliance with the License.
  4. * You may obtain a copy of the License at
  5. *
  6. * http://www.apache.org/licenses/LICENSE-2.0
  7. *
  8. * Unless required by applicable law or agreed to in writing, software
  9. * distributed under the License is distributed on an "AS IS" BASIS,
  10. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. * See the License for the specific language governing permissions and
  12. * limitations under the License.
  13. */
  14. package sdk
  15. import (
  16. "context"
  17. "crypto/tls"
  18. "fmt"
  19. "net"
  20. "net/http"
  21. "net/url"
  22. "os"
  23. "runtime"
  24. "strconv"
  25. "strings"
  26. "sync"
  27. "time"
  28. "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth"
  29. "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials"
  30. "github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints"
  31. "github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors"
  32. "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
  33. "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
  34. "github.com/aliyun/alibaba-cloud-sdk-go/sdk/utils"
  35. )
  36. var debug utils.Debug
  37. func init() {
  38. debug = utils.Init("sdk")
  39. }
  40. // Version this value will be replaced while build: -ldflags="-X sdk.version=x.x.x"
  41. var Version = "0.0.1"
  42. var defaultConnectTimeout = 5 * time.Second
  43. var defaultReadTimeout = 10 * time.Second
  44. var DefaultUserAgent = fmt.Sprintf("AlibabaCloud (%s; %s) Golang/%s Core/%s", runtime.GOOS, runtime.GOARCH, strings.Trim(runtime.Version(), "go"), Version)
  45. var hookDo = func(fn func(req *http.Request) (*http.Response, error)) func(req *http.Request) (*http.Response, error) {
  46. return fn
  47. }
  48. // Client the type Client
  49. type Client struct {
  50. isInsecure bool
  51. regionId string
  52. config *Config
  53. userAgent map[string]string
  54. signer auth.Signer
  55. httpClient *http.Client
  56. asyncTaskQueue chan func()
  57. readTimeout time.Duration
  58. connectTimeout time.Duration
  59. debug bool
  60. isRunning bool
  61. // void "panic(write to close channel)" cause of addAsync() after Shutdown()
  62. asyncChanLock *sync.RWMutex
  63. }
  64. func (client *Client) Init() (err error) {
  65. panic("not support yet")
  66. }
  67. func (client *Client) SetHTTPSInsecure(isInsecure bool) {
  68. client.isInsecure = isInsecure
  69. }
  70. func (client *Client) GetHTTPSInsecure() bool {
  71. return client.isInsecure
  72. }
  73. func (client *Client) InitWithOptions(regionId string, config *Config, credential auth.Credential) (err error) {
  74. client.isRunning = true
  75. client.asyncChanLock = new(sync.RWMutex)
  76. client.regionId = regionId
  77. client.config = config
  78. client.httpClient = &http.Client{}
  79. if config.HttpTransport != nil {
  80. client.httpClient.Transport = config.HttpTransport
  81. }
  82. if config.Timeout > 0 {
  83. client.httpClient.Timeout = config.Timeout
  84. }
  85. if config.EnableAsync {
  86. client.EnableAsync(config.GoRoutinePoolSize, config.MaxTaskQueueSize)
  87. }
  88. client.signer, err = auth.NewSignerWithCredential(credential, client.ProcessCommonRequestWithSigner)
  89. return
  90. }
  91. func (client *Client) SetReadTimeout(readTimeout time.Duration) {
  92. client.readTimeout = readTimeout
  93. }
  94. func (client *Client) SetConnectTimeout(connectTimeout time.Duration) {
  95. client.connectTimeout = connectTimeout
  96. }
  97. func (client *Client) GetReadTimeout() time.Duration {
  98. return client.readTimeout
  99. }
  100. func (client *Client) GetConnectTimeout() time.Duration {
  101. return client.connectTimeout
  102. }
  103. func getHttpProxy(scheme string) *url.URL {
  104. var proxy *url.URL
  105. if scheme == "https" {
  106. if rawurl := os.Getenv("HTTPS_PROXY"); rawurl != "" {
  107. proxy, _ = url.Parse(rawurl)
  108. }
  109. if rawurl := os.Getenv("https_proxy"); rawurl != "" && proxy == nil {
  110. proxy, _ = url.Parse(rawurl)
  111. }
  112. } else {
  113. if rawurl := os.Getenv("HTTP_PROXY"); rawurl != "" {
  114. proxy, _ = url.Parse(rawurl)
  115. }
  116. if rawurl := os.Getenv("http_proxy"); rawurl != "" && proxy == nil {
  117. proxy, _ = url.Parse(rawurl)
  118. }
  119. }
  120. return proxy
  121. }
  122. // EnableAsync enable the async task queue
  123. func (client *Client) EnableAsync(routinePoolSize, maxTaskQueueSize int) {
  124. client.asyncTaskQueue = make(chan func(), maxTaskQueueSize)
  125. for i := 0; i < routinePoolSize; i++ {
  126. go func() {
  127. for client.isRunning {
  128. select {
  129. case task, notClosed := <-client.asyncTaskQueue:
  130. if notClosed {
  131. task()
  132. }
  133. }
  134. }
  135. }()
  136. }
  137. }
  138. func (client *Client) InitWithAccessKey(regionId, accessKeyId, accessKeySecret string) (err error) {
  139. config := client.InitClientConfig()
  140. credential := &credentials.BaseCredential{
  141. AccessKeyId: accessKeyId,
  142. AccessKeySecret: accessKeySecret,
  143. }
  144. return client.InitWithOptions(regionId, config, credential)
  145. }
  146. func (client *Client) InitWithStsToken(regionId, accessKeyId, accessKeySecret, securityToken string) (err error) {
  147. config := client.InitClientConfig()
  148. credential := &credentials.StsTokenCredential{
  149. AccessKeyId: accessKeyId,
  150. AccessKeySecret: accessKeySecret,
  151. AccessKeyStsToken: securityToken,
  152. }
  153. return client.InitWithOptions(regionId, config, credential)
  154. }
  155. func (client *Client) InitWithRamRoleArn(regionId, accessKeyId, accessKeySecret, roleArn, roleSessionName string) (err error) {
  156. config := client.InitClientConfig()
  157. credential := &credentials.RamRoleArnCredential{
  158. AccessKeyId: accessKeyId,
  159. AccessKeySecret: accessKeySecret,
  160. RoleArn: roleArn,
  161. RoleSessionName: roleSessionName,
  162. }
  163. return client.InitWithOptions(regionId, config, credential)
  164. }
  165. func (client *Client) InitWithRamRoleArnAndPolicy(regionId, accessKeyId, accessKeySecret, roleArn, roleSessionName, policy string) (err error) {
  166. config := client.InitClientConfig()
  167. credential := &credentials.RamRoleArnCredential{
  168. AccessKeyId: accessKeyId,
  169. AccessKeySecret: accessKeySecret,
  170. RoleArn: roleArn,
  171. RoleSessionName: roleSessionName,
  172. Policy: policy,
  173. }
  174. return client.InitWithOptions(regionId, config, credential)
  175. }
  176. func (client *Client) InitWithRsaKeyPair(regionId, publicKeyId, privateKey string, sessionExpiration int) (err error) {
  177. config := client.InitClientConfig()
  178. credential := &credentials.RsaKeyPairCredential{
  179. PrivateKey: privateKey,
  180. PublicKeyId: publicKeyId,
  181. SessionExpiration: sessionExpiration,
  182. }
  183. return client.InitWithOptions(regionId, config, credential)
  184. }
  185. func (client *Client) InitWithEcsRamRole(regionId, roleName string) (err error) {
  186. config := client.InitClientConfig()
  187. credential := &credentials.EcsRamRoleCredential{
  188. RoleName: roleName,
  189. }
  190. return client.InitWithOptions(regionId, config, credential)
  191. }
  192. func (client *Client) InitClientConfig() (config *Config) {
  193. if client.config != nil {
  194. return client.config
  195. } else {
  196. return NewConfig()
  197. }
  198. }
  199. func (client *Client) DoAction(request requests.AcsRequest, response responses.AcsResponse) (err error) {
  200. return client.DoActionWithSigner(request, response, nil)
  201. }
  202. func (client *Client) buildRequestWithSigner(request requests.AcsRequest, signer auth.Signer) (httpRequest *http.Request, err error) {
  203. // add clientVersion
  204. request.GetHeaders()["x-sdk-core-version"] = Version
  205. regionId := client.regionId
  206. if len(request.GetRegionId()) > 0 {
  207. regionId = request.GetRegionId()
  208. }
  209. // resolve endpoint
  210. resolveParam := &endpoints.ResolveParam{
  211. Domain: request.GetDomain(),
  212. Product: request.GetProduct(),
  213. RegionId: regionId,
  214. LocationProduct: request.GetLocationServiceCode(),
  215. LocationEndpointType: request.GetLocationEndpointType(),
  216. CommonApi: client.ProcessCommonRequest,
  217. }
  218. endpoint, err := endpoints.Resolve(resolveParam)
  219. if err != nil {
  220. return
  221. }
  222. request.SetDomain(endpoint)
  223. if request.GetScheme() == "" {
  224. request.SetScheme(client.config.Scheme)
  225. }
  226. // init request params
  227. err = requests.InitParams(request)
  228. if err != nil {
  229. return
  230. }
  231. // signature
  232. var finalSigner auth.Signer
  233. if signer != nil {
  234. finalSigner = signer
  235. } else {
  236. finalSigner = client.signer
  237. }
  238. httpRequest, err = buildHttpRequest(request, finalSigner, regionId)
  239. if err == nil {
  240. userAgent := DefaultUserAgent + getSendUserAgent(client.config.UserAgent, client.userAgent, request.GetUserAgent())
  241. httpRequest.Header.Set("User-Agent", userAgent)
  242. }
  243. return
  244. }
  245. func getSendUserAgent(configUserAgent string, clientUserAgent, requestUserAgent map[string]string) string {
  246. realUserAgent := ""
  247. for key1, value1 := range clientUserAgent {
  248. for key2, _ := range requestUserAgent {
  249. if key1 == key2 {
  250. key1 = ""
  251. }
  252. }
  253. if key1 != "" {
  254. realUserAgent += fmt.Sprintf(" %s/%s", key1, value1)
  255. }
  256. }
  257. for key, value := range requestUserAgent {
  258. realUserAgent += fmt.Sprintf(" %s/%s", key, value)
  259. }
  260. if configUserAgent != "" {
  261. return realUserAgent + fmt.Sprintf(" Extra/%s", configUserAgent)
  262. }
  263. return realUserAgent
  264. }
  265. func (client *Client) AppendUserAgent(key, value string) {
  266. newkey := true
  267. if client.userAgent == nil {
  268. client.userAgent = make(map[string]string)
  269. }
  270. if strings.ToLower(key) != "core" && strings.ToLower(key) != "go" {
  271. for tag, _ := range client.userAgent {
  272. if tag == key {
  273. client.userAgent[tag] = value
  274. newkey = false
  275. }
  276. }
  277. if newkey {
  278. client.userAgent[key] = value
  279. }
  280. }
  281. }
  282. func (client *Client) BuildRequestWithSigner(request requests.AcsRequest, signer auth.Signer) (err error) {
  283. _, err = client.buildRequestWithSigner(request, signer)
  284. return
  285. }
  286. func (client *Client) getTimeout(request requests.AcsRequest) (time.Duration, time.Duration) {
  287. readTimeout := defaultReadTimeout
  288. connectTimeout := defaultConnectTimeout
  289. reqReadTimeout := request.GetReadTimeout()
  290. reqConnectTimeout := request.GetConnectTimeout()
  291. if reqReadTimeout != 0*time.Millisecond {
  292. readTimeout = reqReadTimeout
  293. } else if client.readTimeout != 0*time.Millisecond {
  294. readTimeout = client.readTimeout
  295. }
  296. if reqConnectTimeout != 0*time.Millisecond {
  297. connectTimeout = reqConnectTimeout
  298. } else if client.connectTimeout != 0*time.Millisecond {
  299. connectTimeout = client.connectTimeout
  300. }
  301. return readTimeout, connectTimeout
  302. }
  303. func Timeout(connectTimeout, readTimeout time.Duration) func(cxt context.Context, net, addr string) (c net.Conn, err error) {
  304. return func(ctx context.Context, network, address string) (net.Conn, error) {
  305. conn, err := (&net.Dialer{
  306. Timeout: connectTimeout,
  307. KeepAlive: 0 * time.Second,
  308. DualStack: true,
  309. }).DialContext(ctx, network, address)
  310. if err == nil {
  311. conn.SetDeadline(time.Now().Add(readTimeout))
  312. }
  313. return conn, err
  314. }
  315. }
  316. func (client *Client) setTimeout(request requests.AcsRequest) {
  317. readTimeout, connectTimeout := client.getTimeout(request)
  318. if trans, ok := client.httpClient.Transport.(*http.Transport); ok && trans != nil {
  319. trans.DialContext = Timeout(connectTimeout, readTimeout)
  320. client.httpClient.Transport = trans
  321. } else {
  322. client.httpClient.Transport = &http.Transport{
  323. DialContext: Timeout(connectTimeout, readTimeout),
  324. }
  325. }
  326. }
  327. func (client *Client) getHTTPSInsecure(request requests.AcsRequest) (insecure bool) {
  328. if request.GetHTTPSInsecure() != nil {
  329. insecure = *request.GetHTTPSInsecure()
  330. } else {
  331. insecure = client.GetHTTPSInsecure()
  332. }
  333. return insecure
  334. }
  335. func (client *Client) DoActionWithSigner(request requests.AcsRequest, response responses.AcsResponse, signer auth.Signer) (err error) {
  336. httpRequest, err := client.buildRequestWithSigner(request, signer)
  337. if err != nil {
  338. return
  339. }
  340. client.setTimeout(request)
  341. proxy := getHttpProxy(httpRequest.URL.Scheme)
  342. // Set whether to ignore certificate validation.
  343. // Default InsecureSkipVerify is false.
  344. if trans, ok := client.httpClient.Transport.(*http.Transport); ok && trans != nil {
  345. trans.TLSClientConfig = &tls.Config{
  346. InsecureSkipVerify: client.getHTTPSInsecure(request),
  347. }
  348. if proxy != nil {
  349. trans.Proxy = http.ProxyURL(proxy)
  350. }
  351. client.httpClient.Transport = trans
  352. }
  353. var httpResponse *http.Response
  354. for retryTimes := 0; retryTimes <= client.config.MaxRetryTime; retryTimes++ {
  355. debug("> %s %s %s", httpRequest.Method, httpRequest.URL.RequestURI(), httpRequest.Proto)
  356. debug("> Host: %s", httpRequest.Host)
  357. for key, value := range httpRequest.Header {
  358. debug("> %s: %v", key, strings.Join(value, ""))
  359. }
  360. debug(">")
  361. httpResponse, err = hookDo(client.httpClient.Do)(httpRequest)
  362. if err == nil {
  363. debug("< %s %s", httpResponse.Proto, httpResponse.Status)
  364. for key, value := range httpResponse.Header {
  365. debug("< %s: %v", key, strings.Join(value, ""))
  366. }
  367. }
  368. debug("<")
  369. // receive error
  370. if err != nil {
  371. if !client.config.AutoRetry {
  372. return
  373. } else if retryTimes >= client.config.MaxRetryTime {
  374. // timeout but reached the max retry times, return
  375. var timeoutErrorMsg string
  376. if strings.Contains(err.Error(), "read tcp") {
  377. timeoutErrorMsg = fmt.Sprintf(errors.TimeoutErrorMessage, strconv.Itoa(retryTimes+1), strconv.Itoa(retryTimes+1)) + " Read timeout. Please set a valid ReadTimeout."
  378. } else {
  379. timeoutErrorMsg = fmt.Sprintf(errors.TimeoutErrorMessage, strconv.Itoa(retryTimes+1), strconv.Itoa(retryTimes+1)) + " Connect timeout. Please set a valid ConnectTimeout."
  380. }
  381. err = errors.NewClientError(errors.TimeoutErrorCode, timeoutErrorMsg, err)
  382. return
  383. }
  384. }
  385. // if status code >= 500 or timeout, will trigger retry
  386. if client.config.AutoRetry && (err != nil || isServerError(httpResponse)) {
  387. client.setTimeout(request)
  388. // rewrite signatureNonce and signature
  389. httpRequest, err = client.buildRequestWithSigner(request, signer)
  390. // buildHttpRequest(request, finalSigner, regionId)
  391. if err != nil {
  392. return
  393. }
  394. continue
  395. }
  396. break
  397. }
  398. err = responses.Unmarshal(response, httpResponse, request.GetAcceptFormat())
  399. // wrap server errors
  400. if serverErr, ok := err.(*errors.ServerError); ok {
  401. var wrapInfo = map[string]string{}
  402. wrapInfo["StringToSign"] = request.GetStringToSign()
  403. err = errors.WrapServerError(serverErr, wrapInfo)
  404. }
  405. return
  406. }
  407. func buildHttpRequest(request requests.AcsRequest, singer auth.Signer, regionId string) (httpRequest *http.Request, err error) {
  408. err = auth.Sign(request, singer, regionId)
  409. if err != nil {
  410. return
  411. }
  412. requestMethod := request.GetMethod()
  413. requestUrl := request.BuildUrl()
  414. body := request.GetBodyReader()
  415. httpRequest, err = http.NewRequest(requestMethod, requestUrl, body)
  416. if err != nil {
  417. return
  418. }
  419. for key, value := range request.GetHeaders() {
  420. httpRequest.Header[key] = []string{value}
  421. }
  422. // host is a special case
  423. if host, containsHost := request.GetHeaders()["Host"]; containsHost {
  424. httpRequest.Host = host
  425. }
  426. return
  427. }
  428. func isServerError(httpResponse *http.Response) bool {
  429. return httpResponse.StatusCode >= http.StatusInternalServerError
  430. }
  431. /**
  432. only block when any one of the following occurs:
  433. 1. the asyncTaskQueue is full, increase the queue size to avoid this
  434. 2. Shutdown() in progressing, the client is being closed
  435. **/
  436. func (client *Client) AddAsyncTask(task func()) (err error) {
  437. if client.asyncTaskQueue != nil {
  438. client.asyncChanLock.RLock()
  439. defer client.asyncChanLock.RUnlock()
  440. if client.isRunning {
  441. client.asyncTaskQueue <- task
  442. }
  443. } else {
  444. err = errors.NewClientError(errors.AsyncFunctionNotEnabledCode, errors.AsyncFunctionNotEnabledMessage, nil)
  445. }
  446. return
  447. }
  448. func (client *Client) GetConfig() *Config {
  449. return client.config
  450. }
  451. func NewClient() (client *Client, err error) {
  452. client = &Client{}
  453. err = client.Init()
  454. return
  455. }
  456. func NewClientWithOptions(regionId string, config *Config, credential auth.Credential) (client *Client, err error) {
  457. client = &Client{}
  458. err = client.InitWithOptions(regionId, config, credential)
  459. return
  460. }
  461. func NewClientWithAccessKey(regionId, accessKeyId, accessKeySecret string) (client *Client, err error) {
  462. client = &Client{}
  463. err = client.InitWithAccessKey(regionId, accessKeyId, accessKeySecret)
  464. return
  465. }
  466. func NewClientWithStsToken(regionId, stsAccessKeyId, stsAccessKeySecret, stsToken string) (client *Client, err error) {
  467. client = &Client{}
  468. err = client.InitWithStsToken(regionId, stsAccessKeyId, stsAccessKeySecret, stsToken)
  469. return
  470. }
  471. func NewClientWithRamRoleArn(regionId string, accessKeyId, accessKeySecret, roleArn, roleSessionName string) (client *Client, err error) {
  472. client = &Client{}
  473. err = client.InitWithRamRoleArn(regionId, accessKeyId, accessKeySecret, roleArn, roleSessionName)
  474. return
  475. }
  476. func NewClientWithRamRoleArnAndPolicy(regionId string, accessKeyId, accessKeySecret, roleArn, roleSessionName, policy string) (client *Client, err error) {
  477. client = &Client{}
  478. err = client.InitWithRamRoleArnAndPolicy(regionId, accessKeyId, accessKeySecret, roleArn, roleSessionName, policy)
  479. return
  480. }
  481. func NewClientWithEcsRamRole(regionId string, roleName string) (client *Client, err error) {
  482. client = &Client{}
  483. err = client.InitWithEcsRamRole(regionId, roleName)
  484. return
  485. }
  486. func NewClientWithRsaKeyPair(regionId string, publicKeyId, privateKey string, sessionExpiration int) (client *Client, err error) {
  487. client = &Client{}
  488. err = client.InitWithRsaKeyPair(regionId, publicKeyId, privateKey, sessionExpiration)
  489. return
  490. }
  491. // Deprecated: Use NewClientWithRamRoleArn in this package instead.
  492. func NewClientWithStsRoleArn(regionId string, accessKeyId, accessKeySecret, roleArn, roleSessionName string) (client *Client, err error) {
  493. return NewClientWithRamRoleArn(regionId, accessKeyId, accessKeySecret, roleArn, roleSessionName)
  494. }
  495. // Deprecated: Use NewClientWithEcsRamRole in this package instead.
  496. func NewClientWithStsRoleNameOnEcs(regionId string, roleName string) (client *Client, err error) {
  497. return NewClientWithEcsRamRole(regionId, roleName)
  498. }
  499. func (client *Client) ProcessCommonRequest(request *requests.CommonRequest) (response *responses.CommonResponse, err error) {
  500. request.TransToAcsRequest()
  501. response = responses.NewCommonResponse()
  502. err = client.DoAction(request, response)
  503. return
  504. }
  505. func (client *Client) ProcessCommonRequestWithSigner(request *requests.CommonRequest, signerInterface interface{}) (response *responses.CommonResponse, err error) {
  506. if signer, isSigner := signerInterface.(auth.Signer); isSigner {
  507. request.TransToAcsRequest()
  508. response = responses.NewCommonResponse()
  509. err = client.DoActionWithSigner(request, response, signer)
  510. return
  511. }
  512. panic("should not be here")
  513. }
  514. func (client *Client) Shutdown() {
  515. // lock the addAsync()
  516. client.asyncChanLock.Lock()
  517. defer client.asyncChanLock.Unlock()
  518. if client.asyncTaskQueue != nil {
  519. close(client.asyncTaskQueue)
  520. }
  521. client.isRunning = false
  522. }