client.go 13 KB

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