client.go 17 KB

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