client.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  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) Golang/%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) InitWithRamRoleArnAndPolicy(regionId, accessKeyId, accessKeySecret, roleArn, roleSessionName, policy string) (err error) {
  118. config := client.InitClientConfig()
  119. credential := &credentials.RamRoleArnCredential{
  120. AccessKeyId: accessKeyId,
  121. AccessKeySecret: accessKeySecret,
  122. RoleArn: roleArn,
  123. RoleSessionName: roleSessionName,
  124. Policy: policy,
  125. }
  126. return client.InitWithOptions(regionId, config, credential)
  127. }
  128. func (client *Client) InitWithRsaKeyPair(regionId, publicKeyId, privateKey string, sessionExpiration int) (err error) {
  129. config := client.InitClientConfig()
  130. credential := &credentials.RsaKeyPairCredential{
  131. PrivateKey: privateKey,
  132. PublicKeyId: publicKeyId,
  133. SessionExpiration: sessionExpiration,
  134. }
  135. return client.InitWithOptions(regionId, config, credential)
  136. }
  137. func (client *Client) InitWithEcsRamRole(regionId, roleName string) (err error) {
  138. config := client.InitClientConfig()
  139. credential := &credentials.EcsRamRoleCredential{
  140. RoleName: roleName,
  141. }
  142. return client.InitWithOptions(regionId, config, credential)
  143. }
  144. func (client *Client) InitClientConfig() (config *Config) {
  145. if client.config != nil {
  146. return client.config
  147. } else {
  148. return NewConfig()
  149. }
  150. }
  151. func (client *Client) DoAction(request requests.AcsRequest, response responses.AcsResponse) (err error) {
  152. return client.DoActionWithSigner(request, response, nil)
  153. }
  154. func (client *Client) buildRequestWithSigner(request requests.AcsRequest, signer auth.Signer) (httpRequest *http.Request, err error) {
  155. // add clientVersion
  156. request.GetHeaders()["x-sdk-core-version"] = Version
  157. regionId := client.regionId
  158. if len(request.GetRegionId()) > 0 {
  159. regionId = request.GetRegionId()
  160. }
  161. // resolve endpoint
  162. resolveParam := &endpoints.ResolveParam{
  163. Domain: request.GetDomain(),
  164. Product: request.GetProduct(),
  165. RegionId: regionId,
  166. LocationProduct: request.GetLocationServiceCode(),
  167. LocationEndpointType: request.GetLocationEndpointType(),
  168. CommonApi: client.ProcessCommonRequest,
  169. }
  170. endpoint, err := endpoints.Resolve(resolveParam)
  171. if err != nil {
  172. return
  173. }
  174. request.SetDomain(endpoint)
  175. if request.GetScheme() == "" {
  176. request.SetScheme(client.config.Scheme)
  177. }
  178. // init request params
  179. err = requests.InitParams(request)
  180. if err != nil {
  181. return
  182. }
  183. // signature
  184. var finalSigner auth.Signer
  185. if signer != nil {
  186. finalSigner = signer
  187. } else {
  188. finalSigner = client.signer
  189. }
  190. httpRequest, err = buildHttpRequest(request, finalSigner, regionId)
  191. if err == nil {
  192. userAgent := DefaultUserAgent + getSendUserAgent(client.config.UserAgent, client.userAgent, request.GetUserAgent())
  193. httpRequest.Header.Set("User-Agent", userAgent)
  194. }
  195. return
  196. }
  197. func getSendUserAgent(configUserAgent string, clientUserAgent, requestUserAgent map[string]string) string {
  198. realUserAgent := ""
  199. for key1, value1 := range clientUserAgent {
  200. for key2, _ := range requestUserAgent {
  201. if key1 == key2 {
  202. key1 = ""
  203. }
  204. }
  205. if key1 != "" {
  206. realUserAgent += fmt.Sprintf(" %s/%s", key1, value1)
  207. }
  208. }
  209. for key, value := range requestUserAgent {
  210. realUserAgent += fmt.Sprintf(" %s/%s", key, value)
  211. }
  212. if configUserAgent != "" {
  213. return realUserAgent + fmt.Sprintf(" Extra/%s", configUserAgent)
  214. }
  215. return realUserAgent
  216. }
  217. func (client *Client) AppendUserAgent(key, value string) {
  218. newkey := true
  219. if client.userAgent == nil {
  220. client.userAgent = make(map[string]string)
  221. }
  222. if strings.ToLower(key) != "core" && strings.ToLower(key) != "go" {
  223. for tag, _ := range client.userAgent {
  224. if tag == key {
  225. client.userAgent[tag] = value
  226. newkey = false
  227. }
  228. }
  229. if newkey {
  230. client.userAgent[key] = value
  231. }
  232. }
  233. }
  234. func (client *Client) BuildRequestWithSigner(request requests.AcsRequest, signer auth.Signer) (err error) {
  235. _, err = client.buildRequestWithSigner(request, signer)
  236. return
  237. }
  238. func (client *Client) DoActionWithSigner(request requests.AcsRequest, response responses.AcsResponse, signer auth.Signer) (err error) {
  239. httpRequest, err := client.buildRequestWithSigner(request, signer)
  240. if err != nil {
  241. return
  242. }
  243. var httpResponse *http.Response
  244. for retryTimes := 0; retryTimes <= client.config.MaxRetryTime; retryTimes++ {
  245. debug("> %s %s %s", httpRequest.Method, httpRequest.URL.RequestURI(), httpRequest.Proto)
  246. debug("> Host: %s", httpRequest.Host)
  247. for key, value := range httpRequest.Header {
  248. debug("> %s: %v", key, strings.Join(value, ""))
  249. }
  250. debug(">")
  251. httpResponse, err = hookDo(client.httpClient.Do)(httpRequest)
  252. if err == nil {
  253. debug("< %s %s", httpResponse.Proto, httpResponse.Status)
  254. for key, value := range httpResponse.Header {
  255. debug("< %s: %v", key, strings.Join(value, ""))
  256. }
  257. }
  258. debug("<")
  259. // receive error
  260. if err != nil {
  261. if !client.config.AutoRetry {
  262. return
  263. } else if retryTimes >= client.config.MaxRetryTime {
  264. // timeout but reached the max retry times, return
  265. timeoutErrorMsg := fmt.Sprintf(errors.TimeoutErrorMessage, strconv.Itoa(retryTimes+1), strconv.Itoa(retryTimes+1))
  266. err = errors.NewClientError(errors.TimeoutErrorCode, timeoutErrorMsg, err)
  267. return
  268. }
  269. }
  270. // if status code >= 500 or timeout, will trigger retry
  271. if client.config.AutoRetry && (err != nil || isServerError(httpResponse)) {
  272. // rewrite signatureNonce and signature
  273. httpRequest, err = client.buildRequestWithSigner(request, signer)
  274. // buildHttpRequest(request, finalSigner, regionId)
  275. if err != nil {
  276. return
  277. }
  278. continue
  279. }
  280. break
  281. }
  282. err = responses.Unmarshal(response, httpResponse, request.GetAcceptFormat())
  283. // wrap server errors
  284. if serverErr, ok := err.(*errors.ServerError); ok {
  285. var wrapInfo = map[string]string{}
  286. wrapInfo["StringToSign"] = request.GetStringToSign()
  287. err = errors.WrapServerError(serverErr, wrapInfo)
  288. }
  289. return
  290. }
  291. func buildHttpRequest(request requests.AcsRequest, singer auth.Signer, regionId string) (httpRequest *http.Request, err error) {
  292. err = auth.Sign(request, singer, regionId)
  293. if err != nil {
  294. return
  295. }
  296. requestMethod := request.GetMethod()
  297. requestUrl := request.BuildUrl()
  298. body := request.GetBodyReader()
  299. httpRequest, err = http.NewRequest(requestMethod, requestUrl, body)
  300. if err != nil {
  301. return
  302. }
  303. for key, value := range request.GetHeaders() {
  304. httpRequest.Header[key] = []string{value}
  305. }
  306. // host is a special case
  307. if host, containsHost := request.GetHeaders()["Host"]; containsHost {
  308. httpRequest.Host = host
  309. }
  310. return
  311. }
  312. func isServerError(httpResponse *http.Response) bool {
  313. return httpResponse.StatusCode >= http.StatusInternalServerError
  314. }
  315. /**
  316. only block when any one of the following occurs:
  317. 1. the asyncTaskQueue is full, increase the queue size to avoid this
  318. 2. Shutdown() in progressing, the client is being closed
  319. **/
  320. func (client *Client) AddAsyncTask(task func()) (err error) {
  321. if client.asyncTaskQueue != nil {
  322. client.asyncChanLock.RLock()
  323. defer client.asyncChanLock.RUnlock()
  324. if client.isRunning {
  325. client.asyncTaskQueue <- task
  326. }
  327. } else {
  328. err = errors.NewClientError(errors.AsyncFunctionNotEnabledCode, errors.AsyncFunctionNotEnabledMessage, nil)
  329. }
  330. return
  331. }
  332. func (client *Client) GetConfig() *Config {
  333. return client.config
  334. }
  335. func NewClient() (client *Client, err error) {
  336. client = &Client{}
  337. err = client.Init()
  338. return
  339. }
  340. func NewClientWithOptions(regionId string, config *Config, credential auth.Credential) (client *Client, err error) {
  341. client = &Client{}
  342. err = client.InitWithOptions(regionId, config, credential)
  343. return
  344. }
  345. func NewClientWithAccessKey(regionId, accessKeyId, accessKeySecret string) (client *Client, err error) {
  346. client = &Client{}
  347. err = client.InitWithAccessKey(regionId, accessKeyId, accessKeySecret)
  348. return
  349. }
  350. func NewClientWithStsToken(regionId, stsAccessKeyId, stsAccessKeySecret, stsToken string) (client *Client, err error) {
  351. client = &Client{}
  352. err = client.InitWithStsToken(regionId, stsAccessKeyId, stsAccessKeySecret, stsToken)
  353. return
  354. }
  355. func NewClientWithRamRoleArn(regionId string, accessKeyId, accessKeySecret, roleArn, roleSessionName string) (client *Client, err error) {
  356. client = &Client{}
  357. err = client.InitWithRamRoleArn(regionId, accessKeyId, accessKeySecret, roleArn, roleSessionName)
  358. return
  359. }
  360. func NewClientWithRamRoleArnAndPolicy(regionId string, accessKeyId, accessKeySecret, roleArn, roleSessionName, policy string) (client *Client, err error) {
  361. client = &Client{}
  362. err = client.InitWithRamRoleArnAndPolicy(regionId, accessKeyId, accessKeySecret, roleArn, roleSessionName, policy)
  363. return
  364. }
  365. func NewClientWithEcsRamRole(regionId string, roleName string) (client *Client, err error) {
  366. client = &Client{}
  367. err = client.InitWithEcsRamRole(regionId, roleName)
  368. return
  369. }
  370. func NewClientWithRsaKeyPair(regionId string, publicKeyId, privateKey string, sessionExpiration int) (client *Client, err error) {
  371. client = &Client{}
  372. err = client.InitWithRsaKeyPair(regionId, publicKeyId, privateKey, sessionExpiration)
  373. return
  374. }
  375. // Deprecated: Use NewClientWithRamRoleArn in this package instead.
  376. func NewClientWithStsRoleArn(regionId string, accessKeyId, accessKeySecret, roleArn, roleSessionName string) (client *Client, err error) {
  377. return NewClientWithRamRoleArn(regionId, accessKeyId, accessKeySecret, roleArn, roleSessionName)
  378. }
  379. // Deprecated: Use NewClientWithEcsRamRole in this package instead.
  380. func NewClientWithStsRoleNameOnEcs(regionId string, roleName string) (client *Client, err error) {
  381. return NewClientWithEcsRamRole(regionId, roleName)
  382. }
  383. func (client *Client) ProcessCommonRequest(request *requests.CommonRequest) (response *responses.CommonResponse, err error) {
  384. request.TransToAcsRequest()
  385. response = responses.NewCommonResponse()
  386. err = client.DoAction(request, response)
  387. return
  388. }
  389. func (client *Client) ProcessCommonRequestWithSigner(request *requests.CommonRequest, signerInterface interface{}) (response *responses.CommonResponse, err error) {
  390. if signer, isSigner := signerInterface.(auth.Signer); isSigner {
  391. request.TransToAcsRequest()
  392. response = responses.NewCommonResponse()
  393. err = client.DoActionWithSigner(request, response, signer)
  394. return
  395. }
  396. panic("should not be here")
  397. }
  398. func (client *Client) Shutdown() {
  399. // lock the addAsync()
  400. client.asyncChanLock.Lock()
  401. defer client.asyncChanLock.Unlock()
  402. if client.asyncTaskQueue != nil {
  403. close(client.asyncTaskQueue)
  404. }
  405. client.isRunning = false
  406. }