client.go 17 KB

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