ob.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package oceanbase
  15. import (
  16. "context"
  17. "crypto/tls"
  18. "fmt"
  19. "net/http"
  20. "net/url"
  21. "strings"
  22. "sync"
  23. "time"
  24. "github.com/icholy/digest"
  25. "yunion.io/x/jsonutils"
  26. "yunion.io/x/log"
  27. "yunion.io/x/pkg/errors"
  28. "yunion.io/x/pkg/gotypes"
  29. "yunion.io/x/pkg/util/httputils"
  30. api "yunion.io/x/cloudmux/pkg/apis/compute"
  31. "yunion.io/x/cloudmux/pkg/cloudprovider"
  32. )
  33. const (
  34. OB_DEFAULT_REGION_NAME = "OceanBase Cloud"
  35. )
  36. type OceanBaseClientConfig struct {
  37. cpcfg cloudprovider.ProviderConfig
  38. accessKeyId string
  39. accessKeySecret string
  40. debug bool
  41. }
  42. type SOceanBaseClient struct {
  43. *OceanBaseClientConfig
  44. client *http.Client
  45. lock sync.Mutex
  46. ctx context.Context
  47. }
  48. func NewOceanBaseClientConfig(accessKeyId, accessKeySecret string) *OceanBaseClientConfig {
  49. cfg := &OceanBaseClientConfig{
  50. accessKeyId: accessKeyId,
  51. accessKeySecret: accessKeySecret,
  52. }
  53. return cfg
  54. }
  55. func (cfg *OceanBaseClientConfig) Debug(debug bool) *OceanBaseClientConfig {
  56. cfg.debug = debug
  57. return cfg
  58. }
  59. func (cfg *OceanBaseClientConfig) CloudproviderConfig(cpcfg cloudprovider.ProviderConfig) *OceanBaseClientConfig {
  60. cfg.cpcfg = cpcfg
  61. return cfg
  62. }
  63. func NewOceanBaseClient(cfg *OceanBaseClientConfig) (*SOceanBaseClient, error) {
  64. client := &SOceanBaseClient{
  65. OceanBaseClientConfig: cfg,
  66. ctx: context.Background(),
  67. }
  68. client.ctx = context.WithValue(client.ctx, "time", time.Now())
  69. _, err := client.list("/api/v2/instances", nil)
  70. return client, err
  71. }
  72. func (cli *SOceanBaseClient) GetRegion() *SRegion {
  73. return &SRegion{
  74. client: cli,
  75. }
  76. }
  77. func (cli *SOceanBaseClient) getDefaultClient() *http.Client {
  78. cli.lock.Lock()
  79. defer cli.lock.Unlock()
  80. if !gotypes.IsNil(cli.client) {
  81. return cli.client
  82. }
  83. cli.client = httputils.GetAdaptiveTimeoutClient()
  84. httputils.SetClientProxyFunc(cli.client, cli.cpcfg.ProxyFunc)
  85. ts, _ := cli.client.Transport.(*http.Transport)
  86. ts.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
  87. t := &digest.Transport{
  88. Username: cli.accessKeyId,
  89. Password: cli.accessKeySecret,
  90. Transport: cloudprovider.GetCheckTransport(ts, func(req *http.Request) (func(resp *http.Response) error, error) {
  91. if cli.cpcfg.ReadOnly {
  92. if req.Method == "GET" {
  93. return nil, nil
  94. }
  95. return nil, errors.Wrapf(cloudprovider.ErrAccountReadOnly, "%s %s", req.Method, req.URL.Path)
  96. }
  97. return nil, nil
  98. }),
  99. }
  100. cli.client.Transport = t
  101. return cli.client
  102. }
  103. type sObError struct {
  104. StatusCode int `json:"statusCode"`
  105. method httputils.THttpMethod
  106. url string
  107. body jsonutils.JSONObject
  108. }
  109. func (e *sObError) Error() string {
  110. return jsonutils.Marshal(e).String()
  111. }
  112. func (e *sObError) ParseErrorFromJsonResponse(statusCode int, status string, body jsonutils.JSONObject) error {
  113. if body != nil {
  114. body.Unmarshal(e)
  115. }
  116. e.StatusCode = statusCode
  117. log.Infof("%s %s body: %s error: %v", e.method, e.url, e.body, e.Error())
  118. if e.StatusCode == 404 {
  119. return errors.Wrapf(cloudprovider.ErrNotFound, "%s", e.Error())
  120. }
  121. return e
  122. }
  123. func (cli *SOceanBaseClient) Do(req *http.Request) (*http.Response, error) {
  124. client := cli.getDefaultClient()
  125. return client.Do(req)
  126. }
  127. func (cli *SOceanBaseClient) list(resource string, params url.Values) (jsonutils.JSONObject, error) {
  128. return cli.request(httputils.GET, resource, params, nil)
  129. }
  130. func (cli *SOceanBaseClient) delete(resource string, body map[string]interface{}) (jsonutils.JSONObject, error) {
  131. return cli.request(httputils.DELETE, resource, nil, body)
  132. }
  133. func (cli *SOceanBaseClient) put(resource string, body map[string]interface{}) (jsonutils.JSONObject, error) {
  134. return cli.request(httputils.PUT, resource, nil, body)
  135. }
  136. func (cli *SOceanBaseClient) request(method httputils.THttpMethod, resource string, params url.Values, body map[string]interface{}) (jsonutils.JSONObject, error) {
  137. if body == nil {
  138. body = map[string]interface{}{}
  139. }
  140. uri := fmt.Sprintf("https://api-cloud-cn.oceanbase.com/%s", strings.TrimPrefix(resource, "/"))
  141. if len(params) > 0 {
  142. uri = fmt.Sprintf("%s?%s", uri, params.Encode())
  143. }
  144. req := httputils.NewJsonRequest(method, uri, body)
  145. bErr := &sObError{method: method, url: uri, body: jsonutils.Marshal(body)}
  146. client := httputils.NewJsonClient(cli)
  147. _, resp, err := client.Send(cli.ctx, req, bErr, cli.debug)
  148. if err != nil {
  149. return nil, err
  150. }
  151. if !jsonutils.QueryBoolean(resp, "success", true) {
  152. return nil, fmt.Errorf("request failed: %s", resp.String())
  153. }
  154. return resp, nil
  155. }
  156. func (cli *SOceanBaseClient) GetSubAccounts() ([]cloudprovider.SSubAccount, error) {
  157. subAccount := cloudprovider.SSubAccount{}
  158. subAccount.Id = cli.GetAccountId()
  159. subAccount.Name = cli.cpcfg.Name
  160. subAccount.Account = cli.accessKeyId
  161. subAccount.HealthStatus = api.CLOUD_PROVIDER_HEALTH_NORMAL
  162. return []cloudprovider.SSubAccount{subAccount}, nil
  163. }
  164. func (cli *SOceanBaseClient) GetAccountId() string {
  165. return ""
  166. }
  167. func (cli *SOceanBaseClient) GetCapabilities() []string {
  168. caps := []string{
  169. cloudprovider.CLOUD_CAPABILITY_RDS,
  170. }
  171. return caps
  172. }