client.go 12 KB

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