client.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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. "fmt"
  17. "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth"
  18. "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials"
  19. "github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints"
  20. "github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors"
  21. "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
  22. "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
  23. "net"
  24. "net/http"
  25. "strconv"
  26. "sync"
  27. )
  28. // this value will be replaced while build: -ldflags="-X sdk.version=x.x.x"
  29. var Version = "0.0.1"
  30. type Client struct {
  31. regionId string
  32. config *Config
  33. signer auth.Signer
  34. httpClient *http.Client
  35. asyncTaskQueue chan func()
  36. debug bool
  37. isRunning bool
  38. // void "panic(write to close channel)" cause of addAsync() after Shutdown()
  39. asyncChanLock *sync.RWMutex
  40. }
  41. func (client *Client) Init() (err error) {
  42. panic("not support yet")
  43. }
  44. func (client *Client) InitWithOptions(regionId string, config *Config, credential auth.Credential) (err error) {
  45. client.isRunning = true
  46. client.asyncChanLock = new(sync.RWMutex)
  47. client.regionId = regionId
  48. client.config = config
  49. if err != nil {
  50. return
  51. }
  52. client.httpClient = &http.Client{}
  53. if config.HttpTransport != nil {
  54. client.httpClient.Transport = config.HttpTransport
  55. }
  56. if config.Timeout > 0 {
  57. client.httpClient.Timeout = config.Timeout
  58. }
  59. if config.EnableAsync {
  60. client.EnableAsync(config.GoRoutinePoolSize, config.MaxTaskQueueSize)
  61. }
  62. client.signer, err = auth.NewSignerWithCredential(credential, client.ProcessCommonRequestWithSigner)
  63. return
  64. }
  65. func (client *Client) EnableAsync(routinePoolSize, maxTaskQueueSize int) {
  66. client.asyncTaskQueue = make(chan func(), maxTaskQueueSize)
  67. for i := 0; i < routinePoolSize; i++ {
  68. go func() {
  69. for client.isRunning {
  70. select {
  71. case task, notClosed := <-client.asyncTaskQueue:
  72. if notClosed {
  73. task()
  74. }
  75. }
  76. }
  77. }()
  78. }
  79. }
  80. func (client *Client) InitWithAccessKey(regionId, accessKeyId, accessKeySecret string) (err error) {
  81. config := client.InitClientConfig()
  82. credential := &credentials.BaseCredential{
  83. AccessKeyId: accessKeyId,
  84. AccessKeySecret: accessKeySecret,
  85. }
  86. return client.InitWithOptions(regionId, config, credential)
  87. }
  88. func (client *Client) InitWithSecurityToken(regionId, accessKeyId, accessKeySecret, securityToken string) (err error) {
  89. config := client.InitClientConfig()
  90. credential := &credentials.StsTokenCredential{
  91. AccessKeyId: accessKeyId,
  92. AccessKeySecret: accessKeySecret,
  93. AccessKeyStsToken: securityToken,
  94. }
  95. return client.InitWithOptions(regionId, config, credential)
  96. }
  97. func (client *Client) InitWithStsRoleArn(regionId, accessKeyId, accessKeySecret, roleArn, roleSessionName string) (err error) {
  98. config := client.InitClientConfig()
  99. credential := &credentials.StsRoleArnCredential{
  100. AccessKeyId: accessKeyId,
  101. AccessKeySecret: accessKeySecret,
  102. RoleArn: roleArn,
  103. RoleSessionName: roleSessionName,
  104. }
  105. return client.InitWithOptions(regionId, config, credential)
  106. }
  107. func (client *Client) InitWithRsaKeyPair(regionId, publicKeyId, privateKey string, sessionExpiration int) (err error) {
  108. config := client.InitClientConfig()
  109. credential := &credentials.RsaKeyPairCredential{
  110. PrivateKey: privateKey,
  111. PublicKeyId: publicKeyId,
  112. SessionExpiration: sessionExpiration,
  113. }
  114. return client.InitWithOptions(regionId, config, credential)
  115. }
  116. func (client *Client) InitWithStsRoleNameOnEcs(regionId, roleName string) (err error) {
  117. config := client.InitClientConfig()
  118. credential := &credentials.StsRoleNameOnEcsCredential{
  119. RoleName: roleName,
  120. }
  121. return client.InitWithOptions(regionId, config, credential)
  122. }
  123. func (client *Client) InitClientConfig() (config *Config) {
  124. if client.config != nil {
  125. return client.config
  126. } else {
  127. return NewConfig()
  128. }
  129. }
  130. func (client *Client) DoAction(request requests.AcsRequest, response responses.AcsResponse) (err error) {
  131. return client.DoActionWithSigner(request, response, nil)
  132. }
  133. func (client *Client) DoActionWithSigner(request requests.AcsRequest, response responses.AcsResponse, signer auth.Signer) (err error) {
  134. // add clientVersion
  135. request.GetHeaders()["x-sdk-core-version"] = Version
  136. regionId := client.regionId
  137. if len(request.GetRegionId()) > 0 {
  138. regionId = request.GetRegionId()
  139. }
  140. // resolve endpoint
  141. resolveParam := &endpoints.ResolveParam{
  142. Domain: request.GetDomain(),
  143. Product: request.GetProduct(),
  144. RegionId: regionId,
  145. LocationProduct: request.GetLocationServiceCode(),
  146. LocationEndpointType: request.GetLocationEndpointType(),
  147. CommonApi: client.ProcessCommonRequest,
  148. }
  149. endpoint, err := endpoints.Resolve(resolveParam)
  150. if err != nil {
  151. return
  152. }
  153. request.SetDomain(endpoint)
  154. // init request params
  155. err = requests.InitParams(request)
  156. if err != nil {
  157. return
  158. }
  159. // signature
  160. var finalSigner auth.Signer
  161. if signer != nil {
  162. finalSigner = signer
  163. } else {
  164. finalSigner = client.signer
  165. }
  166. httpRequest, err := buildHttpRequest(request, finalSigner, regionId)
  167. if err != nil {
  168. return
  169. }
  170. var httpResponse *http.Response
  171. for retryTimes := 0; retryTimes <= client.config.MaxRetryTime; retryTimes++ {
  172. httpResponse, err = client.httpClient.Do(httpRequest)
  173. var timeout bool
  174. // receive error
  175. if err != nil {
  176. if timeout = isTimeout(err); !timeout {
  177. // if not timeout error, return
  178. return
  179. } else if retryTimes >= client.config.MaxRetryTime {
  180. // timeout but reached the max retry times, return
  181. timeoutErrorMsg := fmt.Sprintf(errors.TimeoutErrorMessage, strconv.Itoa(retryTimes+1), strconv.Itoa(retryTimes+1))
  182. err = errors.NewClientError(errors.TimeoutErrorCode, timeoutErrorMsg, err)
  183. return
  184. }
  185. }
  186. // if status code >= 500 or timeout, will trigger retry
  187. if client.config.AutoRetry && (timeout || isServerError(httpResponse)) {
  188. // rewrite signatureNonce and signature
  189. httpRequest, err = buildHttpRequest(request, finalSigner, regionId)
  190. if err != nil {
  191. return
  192. }
  193. continue
  194. }
  195. break
  196. }
  197. err = responses.Unmarshal(response, httpResponse, request.GetAcceptFormat())
  198. return
  199. }
  200. func buildHttpRequest(request requests.AcsRequest, singer auth.Signer, regionId string) (httpRequest *http.Request, err error) {
  201. err = auth.Sign(request, singer, regionId)
  202. if err != nil {
  203. return
  204. }
  205. requestMethod := request.GetMethod()
  206. requestUrl := request.BuildUrl()
  207. body := request.GetBodyReader()
  208. httpRequest, err = http.NewRequest(requestMethod, requestUrl, body)
  209. if err != nil {
  210. return
  211. }
  212. for key, value := range request.GetHeaders() {
  213. httpRequest.Header[key] = []string{value}
  214. }
  215. // host is a special case
  216. if host, containsHost := request.GetHeaders()["Host"]; containsHost {
  217. httpRequest.Host = host
  218. }
  219. return
  220. }
  221. func isTimeout(err error) bool {
  222. if err == nil {
  223. return false
  224. }
  225. netErr, isNetError := err.(net.Error)
  226. return isNetError && netErr.Timeout()
  227. }
  228. func isServerError(httpResponse *http.Response) bool {
  229. return httpResponse.StatusCode >= http.StatusInternalServerError
  230. }
  231. /**
  232. only block when any one of the following occurs:
  233. 1. the asyncTaskQueue is full, increase the queue size to avoid this
  234. 2. Shutdown() in progressing, the client is being closed
  235. **/
  236. func (client *Client) AddAsyncTask(task func()) (err error) {
  237. if client.asyncTaskQueue != nil {
  238. client.asyncChanLock.RLock()
  239. defer client.asyncChanLock.RUnlock()
  240. if client.isRunning {
  241. client.asyncTaskQueue <- task
  242. }
  243. } else {
  244. err = errors.NewClientError(errors.AsyncFunctionNotEnabledCode, errors.AsyncFunctionNotEnabledMessage, nil)
  245. }
  246. return
  247. }
  248. func NewClient() (client *Client, err error) {
  249. client = &Client{}
  250. err = client.Init()
  251. return
  252. }
  253. func NewClientWithOptions(regionId string, config *Config, credential auth.Credential) (client *Client, err error) {
  254. client = &Client{}
  255. err = client.InitWithOptions(regionId, config, credential)
  256. return
  257. }
  258. func NewClientWithAccessKey(regionId, accessKeyId, accessKeySecret string) (client *Client, err error) {
  259. client = &Client{}
  260. err = client.InitWithAccessKey(regionId, accessKeyId, accessKeySecret)
  261. return
  262. }
  263. func NewClientWithStsToken(regionId, accessKeyId, accessKeySecret, accessKeyStsToken string) (client *Client, err error) {
  264. client = &Client{}
  265. err = client.InitWithSecurityToken(regionId, accessKeyId, accessKeySecret, accessKeyStsToken)
  266. return
  267. }
  268. func NewClientWithRsaKeyPair(regionId string, publicKeyId, privateKey string, sessionExpiration int) (client *Client, err error) {
  269. client = &Client{}
  270. err = client.InitWithRsaKeyPair(regionId, publicKeyId, privateKey, sessionExpiration)
  271. return
  272. }
  273. func NewClientWithStsRoleNameOnEcs(regionId string, roleName string) (client *Client, err error) {
  274. client = &Client{}
  275. err = client.InitWithStsRoleNameOnEcs(regionId, roleName)
  276. return
  277. }
  278. func NewClientWithStsRoleArn(regionId string, accessKeyId, accessKeySecret, roleArn, roleSessionName string) (client *Client, err error) {
  279. client = &Client{}
  280. err = client.InitWithStsRoleArn(regionId, accessKeyId, accessKeySecret, roleArn, roleSessionName)
  281. return
  282. }
  283. func (client *Client) ProcessCommonRequest(request *requests.CommonRequest) (response *responses.CommonResponse, err error) {
  284. request.TransToAcsRequest()
  285. response = responses.NewCommonResponse()
  286. err = client.DoAction(request, response)
  287. return
  288. }
  289. func (client *Client) ProcessCommonRequestWithSigner(request *requests.CommonRequest, signerInterface interface{}) (response *responses.CommonResponse, err error) {
  290. if signer, isSigner := signerInterface.(auth.Signer); isSigner {
  291. request.TransToAcsRequest()
  292. response = responses.NewCommonResponse()
  293. err = client.DoActionWithSigner(request, response, signer)
  294. return
  295. } else {
  296. panic("should not be here")
  297. }
  298. }
  299. func (client *Client) Shutdown() {
  300. client.signer.Shutdown()
  301. // lock the addAsync()
  302. client.asyncChanLock.Lock()
  303. defer client.asyncChanLock.Unlock()
  304. client.isRunning = false
  305. close(client.asyncTaskQueue)
  306. }