zstack.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  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 zstack
  15. import (
  16. "context"
  17. "crypto/hmac"
  18. "crypto/sha1"
  19. "crypto/sha512"
  20. "encoding/base64"
  21. "fmt"
  22. "io"
  23. "net/http"
  24. "net/url"
  25. "strings"
  26. "time"
  27. "yunion.io/x/jsonutils"
  28. "yunion.io/x/log"
  29. "yunion.io/x/pkg/errors"
  30. "yunion.io/x/pkg/gotypes"
  31. "yunion.io/x/pkg/util/httputils"
  32. api "yunion.io/x/cloudmux/pkg/apis/compute"
  33. "yunion.io/x/cloudmux/pkg/cloudprovider"
  34. )
  35. const (
  36. CLOUD_PROVIDER_ZSTACK = api.CLOUD_PROVIDER_ZSTACK
  37. ZSTACK_DEFAULT_REGION = "ZStack"
  38. ZSTACK_API_VERSION = "v1"
  39. )
  40. var (
  41. SkipEsxi bool = true
  42. )
  43. type ZstackClientConfig struct {
  44. cpcfg cloudprovider.ProviderConfig
  45. authURL string
  46. username string
  47. password string
  48. debug bool
  49. }
  50. func NewZstackClientConfig(authURL, username, password string) *ZstackClientConfig {
  51. cfg := &ZstackClientConfig{
  52. authURL: strings.TrimSuffix(authURL, "/"),
  53. username: username,
  54. password: password,
  55. }
  56. return cfg
  57. }
  58. func (cfg *ZstackClientConfig) CloudproviderConfig(cpcfg cloudprovider.ProviderConfig) *ZstackClientConfig {
  59. cfg.cpcfg = cpcfg
  60. return cfg
  61. }
  62. func (cfg *ZstackClientConfig) Debug(debug bool) *ZstackClientConfig {
  63. cfg.debug = debug
  64. return cfg
  65. }
  66. type SZStackClient struct {
  67. *ZstackClientConfig
  68. httpClient *http.Client
  69. iregions []cloudprovider.ICloudRegion
  70. }
  71. func getTime() string {
  72. zone, _ := time.LoadLocation("Asia/Shanghai")
  73. return time.Now().In(zone).Format("Mon, 02 Jan 2006 15:04:05 MST")
  74. }
  75. func sign(accessId, accessKey, method, date, url string) string {
  76. h := hmac.New(sha1.New, []byte(accessKey))
  77. h.Write([]byte(fmt.Sprintf("%s\n%s\n%s", method, date, url)))
  78. return base64.StdEncoding.EncodeToString(h.Sum(nil))
  79. }
  80. func getSignUrl(uri string) (string, error) {
  81. u, err := url.Parse(uri)
  82. if err != nil {
  83. return "", err
  84. }
  85. return strings.TrimPrefix(u.Path, "/zstack"), nil
  86. }
  87. func NewZStackClient(cfg *ZstackClientConfig) (*SZStackClient, error) {
  88. httpClient := cfg.cpcfg.AdaptiveTimeoutHttpClient()
  89. ts, _ := httpClient.Transport.(*http.Transport)
  90. httpClient.Transport = cloudprovider.GetCheckTransport(ts, func(req *http.Request) (func(resp *http.Response) error, error) {
  91. if cfg.cpcfg.ReadOnly {
  92. if req.Method == "GET" || req.Method == "HEAD" {
  93. return nil, nil
  94. }
  95. // 认证
  96. if req.Method == "PUT" && req.URL.Path == "/zstack/v1/accounts/login" {
  97. return nil, nil
  98. }
  99. return nil, errors.Wrapf(cloudprovider.ErrAccountReadOnly, "%s %s", req.Method, req.URL.Path)
  100. }
  101. return nil, nil
  102. })
  103. cli := &SZStackClient{
  104. ZstackClientConfig: cfg,
  105. httpClient: httpClient,
  106. }
  107. if err := cli.connect(); err != nil {
  108. return nil, err
  109. }
  110. cli.iregions = []cloudprovider.ICloudRegion{&SRegion{client: cli, Name: ZSTACK_DEFAULT_REGION}}
  111. return cli, nil
  112. }
  113. func (cli *SZStackClient) GetCloudRegionExternalIdPrefix() string {
  114. return fmt.Sprintf("%s/%s", CLOUD_PROVIDER_ZSTACK, cli.cpcfg.Id)
  115. }
  116. func (cli *SZStackClient) GetSubAccounts() ([]cloudprovider.SSubAccount, error) {
  117. subAccount := cloudprovider.SSubAccount{
  118. Id: cli.cpcfg.Id,
  119. Account: cli.username,
  120. Name: cli.cpcfg.Name,
  121. HealthStatus: api.CLOUD_PROVIDER_HEALTH_NORMAL,
  122. }
  123. return []cloudprovider.SSubAccount{subAccount}, nil
  124. }
  125. func (cli *SZStackClient) GetIRegions() ([]cloudprovider.ICloudRegion, error) {
  126. return cli.iregions, nil
  127. }
  128. func (cli *SZStackClient) GetIRegionById(id string) (cloudprovider.ICloudRegion, error) {
  129. for i := 0; i < len(cli.iregions); i++ {
  130. if cli.iregions[i].GetGlobalId() == id {
  131. return cli.iregions[i], nil
  132. }
  133. }
  134. return nil, cloudprovider.ErrNotFound
  135. }
  136. func (cli *SZStackClient) getRequestURL(resource string, params url.Values) string {
  137. return cli.authURL + fmt.Sprintf("/zstack/%s/%s", ZSTACK_API_VERSION, resource) + "?" + params.Encode()
  138. }
  139. func (cli *SZStackClient) testAccessKey() error {
  140. zones := []SZone{}
  141. err := cli.listAll("zones", url.Values{}, &zones)
  142. if err != nil {
  143. return errors.Wrap(err, "testAccessKey")
  144. }
  145. return nil
  146. }
  147. func (cli *SZStackClient) connect() error {
  148. header := http.Header{}
  149. header.Add("Content-Type", "application/json")
  150. authURL := cli.authURL + "/zstack/v1/accounts/login"
  151. body := jsonutils.Marshal(map[string]interface{}{
  152. "logInByAccount": map[string]string{
  153. "accountName": cli.username,
  154. "password": fmt.Sprintf("%x", sha512.Sum512([]byte(cli.password))),
  155. },
  156. })
  157. _, _, err := httputils.JSONRequest(cli.httpClient, context.Background(), "PUT", authURL, header, body, cli.debug)
  158. if err != nil {
  159. err = cli.testAccessKey()
  160. if err == nil {
  161. return nil
  162. }
  163. if !strings.Contains(cli.authURL, "8080") {
  164. return errors.Wrapf(err, "please set port to 8080, try again")
  165. }
  166. return errors.Wrapf(err, "connect")
  167. }
  168. return fmt.Errorf("password auth has been deprecated, please using ak sk auth")
  169. }
  170. func (cli *SZStackClient) listAll(resource string, params url.Values, retVal interface{}) error {
  171. result := []jsonutils.JSONObject{}
  172. start, limit := 0, 50
  173. for {
  174. resp, err := cli._list(resource, start, limit, params)
  175. if err != nil {
  176. return err
  177. }
  178. if gotypes.IsNil(resp) {
  179. return errors.Wrapf(errors.ErrEmpty, "empty response")
  180. }
  181. objs, err := resp.GetArray("inventories")
  182. if err != nil {
  183. return err
  184. }
  185. result = append(result, objs...)
  186. if start+limit > len(result) {
  187. inventories := jsonutils.Marshal(map[string][]jsonutils.JSONObject{"inventories": result})
  188. return inventories.Unmarshal(retVal, "inventories")
  189. }
  190. start += limit
  191. }
  192. }
  193. func (cli *SZStackClient) sign(uri, method string, header http.Header) error {
  194. url, err := getSignUrl(uri)
  195. if err != nil {
  196. return errors.Wrap(err, "sign.getSignUrl")
  197. }
  198. date := getTime()
  199. signature := sign(cli.username, cli.password, method, date, url)
  200. header.Add("Signature", signature)
  201. header.Add("Authorization", fmt.Sprintf("ZStack %s:%s", cli.username, signature))
  202. header.Add("Date", date)
  203. return nil
  204. }
  205. func (cli *SZStackClient) _list(resource string, start int, limit int, params url.Values) (jsonutils.JSONObject, error) {
  206. header := http.Header{}
  207. if params == nil {
  208. params = url.Values{}
  209. }
  210. params.Set("replyWithCount", "true")
  211. params.Set("start", fmt.Sprintf("%d", start))
  212. if limit == 0 {
  213. limit = 50
  214. }
  215. params.Set("limit", fmt.Sprintf("%d", limit))
  216. requestURL := cli.getRequestURL(resource, params)
  217. err := cli.sign(requestURL, "GET", header)
  218. if err != nil {
  219. return nil, err
  220. }
  221. _, resp, err := httputils.JSONRequest(cli.httpClient, context.Background(), "GET", requestURL, header, nil, cli.debug)
  222. if err != nil {
  223. if e, ok := err.(*httputils.JSONClientError); ok {
  224. if strings.Contains(e.Details, "wrong accessKey signature") || strings.Contains(e.Details, "access key id") {
  225. return nil, errors.Wrapf(cloudprovider.ErrInvalidAccessKey, "%s", err.Error())
  226. }
  227. }
  228. return nil, err
  229. }
  230. return resp, nil
  231. }
  232. func (cli *SZStackClient) getDeleteURL(resource, resourceId, deleteMode string) string {
  233. if len(resourceId) == 0 {
  234. return cli.authURL + fmt.Sprintf("/zstack/%s/%s", ZSTACK_API_VERSION, resource)
  235. }
  236. url := cli.authURL + fmt.Sprintf("/zstack/%s/%s/%s", ZSTACK_API_VERSION, resource, resourceId)
  237. if len(deleteMode) > 0 {
  238. url += "?deleteMode=" + deleteMode
  239. }
  240. return url
  241. }
  242. func (cli *SZStackClient) delete(resource, resourceId, deleteMode string) error {
  243. _, err := cli._delete(resource, resourceId, deleteMode)
  244. return err
  245. }
  246. func (cli *SZStackClient) _delete(resource, resourceId, deleteMode string) (jsonutils.JSONObject, error) {
  247. header := http.Header{}
  248. requestURL := cli.getDeleteURL(resource, resourceId, deleteMode)
  249. err := cli.sign(requestURL, "DELETE", header)
  250. if err != nil {
  251. return nil, err
  252. }
  253. _, resp, err := httputils.JSONRequest(cli.httpClient, context.Background(), "DELETE", requestURL, header, nil, cli.debug)
  254. if err != nil {
  255. return nil, errors.Wrapf(err, "DELETE %s %s %s", resource, resourceId, deleteMode)
  256. }
  257. if resp.Contains("location") {
  258. location, _ := resp.GetString("location")
  259. return cli.wait(header, "delete", requestURL, jsonutils.NewDict(), location)
  260. }
  261. return resp, nil
  262. }
  263. func (cli *SZStackClient) getURL(resource, resourceId, spec string) string {
  264. if len(resourceId) == 0 {
  265. return cli.authURL + fmt.Sprintf("/zstack/%s/%s", ZSTACK_API_VERSION, resource)
  266. }
  267. if len(spec) == 0 {
  268. return cli.authURL + fmt.Sprintf("/zstack/%s/%s/%s", ZSTACK_API_VERSION, resource, resourceId)
  269. }
  270. return cli.authURL + fmt.Sprintf("/zstack/%s/%s/%s/%s", ZSTACK_API_VERSION, resource, resourceId, spec)
  271. }
  272. func (cli *SZStackClient) getPostURL(resource string) string {
  273. return cli.authURL + fmt.Sprintf("/zstack/%s/%s", ZSTACK_API_VERSION, resource)
  274. }
  275. func (cli *SZStackClient) put(resource, resourceId string, params jsonutils.JSONObject) (jsonutils.JSONObject, error) {
  276. return cli._put(resource, resourceId, params)
  277. }
  278. func (cli *SZStackClient) _put(resource, resourceId string, params jsonutils.JSONObject) (jsonutils.JSONObject, error) {
  279. header := http.Header{}
  280. requestURL := cli.getURL(resource, resourceId, "actions")
  281. err := cli.sign(requestURL, "PUT", header)
  282. if err != nil {
  283. return nil, err
  284. }
  285. _, resp, err := httputils.JSONRequest(cli.httpClient, context.Background(), "PUT", requestURL, header, params, cli.debug)
  286. if err != nil {
  287. return nil, err
  288. }
  289. if resp.Contains("location") {
  290. location, _ := resp.GetString("location")
  291. return cli.wait(header, "update", requestURL, params, location)
  292. }
  293. return resp, nil
  294. }
  295. func (cli *SZStackClient) getResource(resource, resourceId string, retval interface{}) error {
  296. if len(resourceId) == 0 {
  297. return cloudprovider.ErrNotFound
  298. }
  299. resp, err := cli._get(resource, resourceId, "")
  300. if err != nil {
  301. return err
  302. }
  303. inventories, err := resp.GetArray("inventories")
  304. if err != nil {
  305. return err
  306. }
  307. if len(inventories) == 1 {
  308. return inventories[0].Unmarshal(retval)
  309. }
  310. if len(inventories) == 0 {
  311. return cloudprovider.ErrNotFound
  312. }
  313. return cloudprovider.ErrDuplicateId
  314. }
  315. func (cli *SZStackClient) getMonitor(resource string, params jsonutils.JSONObject) (jsonutils.JSONObject, error) {
  316. return cli._getMonitor(resource, params)
  317. }
  318. func (cli *SZStackClient) _getMonitor(resource string, params jsonutils.JSONObject) (jsonutils.JSONObject, error) {
  319. header := http.Header{}
  320. requestURL := cli.getPostURL(resource)
  321. paramDict := params.(*jsonutils.JSONDict)
  322. if paramDict.Size() > 0 {
  323. values := url.Values{}
  324. for _, key := range paramDict.SortedKeys() {
  325. value, _ := paramDict.GetString(key)
  326. values.Add(key, value)
  327. }
  328. requestURL += fmt.Sprintf("?%s", values.Encode())
  329. }
  330. var resp jsonutils.JSONObject
  331. startTime := time.Now()
  332. for time.Now().Sub(startTime) < time.Minute*5 {
  333. err := cli.sign(requestURL, "GET", header)
  334. if err != nil {
  335. return nil, err
  336. }
  337. _, resp, err = cli.jsonRequest(context.TODO(), "GET", requestURL, header, nil)
  338. if err != nil {
  339. if strings.Contains(err.Error(), "exceeded while awaiting headers") {
  340. time.Sleep(time.Second * 5)
  341. continue
  342. }
  343. return nil, errors.Wrapf(err, "GET %s %s", resource, params)
  344. }
  345. break
  346. }
  347. if resp.Contains("location") {
  348. location, _ := resp.GetString("location")
  349. return cli.wait(header, "get", requestURL, jsonutils.NewDict(), location)
  350. }
  351. return resp, nil
  352. }
  353. func (cli *SZStackClient) get(resource, resourceId string, spec string) (jsonutils.JSONObject, error) {
  354. return cli._get(resource, resourceId, spec)
  355. }
  356. func (cli *SZStackClient) _get(resource, resourceId string, spec string) (jsonutils.JSONObject, error) {
  357. header := http.Header{}
  358. requestURL := cli.getURL(resource, resourceId, spec)
  359. var resp jsonutils.JSONObject
  360. startTime := time.Now()
  361. for time.Now().Sub(startTime) < time.Minute*5 {
  362. err := cli.sign(requestURL, "GET", header)
  363. if err != nil {
  364. return nil, err
  365. }
  366. _, resp, err = cli.jsonRequest(context.TODO(), "GET", requestURL, header, nil)
  367. if err != nil {
  368. if strings.Contains(err.Error(), "exceeded while awaiting headers") {
  369. time.Sleep(time.Second * 5)
  370. continue
  371. }
  372. return nil, errors.Wrapf(err, "GET %s %s %s", resource, resourceId, spec)
  373. }
  374. break
  375. }
  376. if resp.Contains("location") {
  377. location, _ := resp.GetString("location")
  378. return cli.wait(header, "get", requestURL, jsonutils.NewDict(), location)
  379. }
  380. return resp, nil
  381. }
  382. func (cli *SZStackClient) create(resource string, params jsonutils.JSONObject, retval interface{}) error {
  383. resp, err := cli._post(resource, params)
  384. if err != nil {
  385. return err
  386. }
  387. if retval == nil {
  388. return nil
  389. }
  390. return resp.Unmarshal(retval, "inventory")
  391. }
  392. func (cli *SZStackClient) post(resource string, params jsonutils.JSONObject) (jsonutils.JSONObject, error) {
  393. return cli._post(resource, params)
  394. }
  395. func (cli *SZStackClient) request(ctx context.Context, method httputils.THttpMethod, urlStr string, header http.Header, body io.Reader) (*http.Response, error) {
  396. resp, err := httputils.Request(cli.httpClient, ctx, method, urlStr, header, body, cli.debug)
  397. return resp, err
  398. }
  399. func (cli *SZStackClient) jsonRequest(ctx context.Context, method httputils.THttpMethod, urlStr string, header http.Header, body jsonutils.JSONObject) (http.Header, jsonutils.JSONObject, error) {
  400. hdr, data, err := httputils.JSONRequest(cli.httpClient, ctx, method, urlStr, header, body, cli.debug)
  401. return hdr, data, err
  402. }
  403. func (cli *SZStackClient) wait(header http.Header, action string, requestURL string, params jsonutils.JSONObject, location string) (jsonutils.JSONObject, error) {
  404. startTime := time.Now()
  405. timeout := time.Minute * 30
  406. for {
  407. resp, err := cli.request(context.TODO(), "GET", location, header, nil)
  408. if err != nil {
  409. return nil, errors.Wrap(err, fmt.Sprintf("wait location %s", location))
  410. }
  411. _, result, err := httputils.ParseJSONResponse("", resp, err, cli.debug)
  412. if err != nil {
  413. if strings.Contains(err.Error(), "not found") {
  414. return nil, cloudprovider.ErrNotFound
  415. }
  416. return nil, err
  417. }
  418. if time.Now().Sub(startTime) > timeout {
  419. return nil, fmt.Errorf("timeout for waitting %s %s params: %s", action, requestURL, params.PrettyString())
  420. }
  421. if resp.StatusCode != 200 {
  422. log.Debugf("wait for job %s %s %s complete", action, requestURL, params.String())
  423. time.Sleep(5 * time.Second)
  424. continue
  425. }
  426. return result, nil
  427. }
  428. }
  429. func (cli *SZStackClient) _post(resource string, params jsonutils.JSONObject) (jsonutils.JSONObject, error) {
  430. header := http.Header{}
  431. requestURL := cli.getPostURL(resource)
  432. err := cli.sign(requestURL, "POST", header)
  433. if err != nil {
  434. return nil, err
  435. }
  436. _, resp, err := cli.jsonRequest(context.TODO(), "POST", requestURL, header, params)
  437. if err != nil {
  438. return nil, errors.Wrapf(err, "POST %s %s", resource, params.String())
  439. }
  440. if resp.Contains("location") {
  441. location, _ := resp.GetString("location")
  442. return cli.wait(header, "create", requestURL, params, location)
  443. }
  444. return resp, nil
  445. }
  446. func (cli *SZStackClient) list(baseURL string, start int, limit int, params url.Values, retVal interface{}) error {
  447. resp, err := cli._list(baseURL, start, limit, params)
  448. if err != nil {
  449. return err
  450. }
  451. return resp.Unmarshal(retVal, "inventories")
  452. }
  453. func (cli *SZStackClient) GetRegion(regionId string) *SRegion {
  454. for i := 0; i < len(cli.iregions); i++ {
  455. if cli.iregions[i].GetId() == regionId {
  456. return cli.iregions[i].(*SRegion)
  457. }
  458. }
  459. return nil
  460. }
  461. func (cli *SZStackClient) GetRegions() []SRegion {
  462. regions := make([]SRegion, len(cli.iregions))
  463. for i := 0; i < len(regions); i++ {
  464. region := cli.iregions[i].(*SRegion)
  465. regions[i] = *region
  466. }
  467. return regions
  468. }
  469. func (cli *SZStackClient) GetIProjects() ([]cloudprovider.ICloudProject, error) {
  470. return nil, cloudprovider.ErrNotImplemented
  471. }
  472. func (self *SZStackClient) GetCapabilities() []string {
  473. caps := []string{
  474. // cloudprovider.CLOUD_CAPABILITY_PROJECT,
  475. cloudprovider.CLOUD_CAPABILITY_COMPUTE,
  476. cloudprovider.CLOUD_CAPABILITY_NETWORK,
  477. cloudprovider.CLOUD_CAPABILITY_SECURITY_GROUP,
  478. cloudprovider.CLOUD_CAPABILITY_EIP,
  479. cloudprovider.CLOUD_CAPABILITY_QUOTA + cloudprovider.READ_ONLY_SUFFIX,
  480. // cloudprovider.CLOUD_CAPABILITY_LOADBALANCER,
  481. // cloudprovider.CLOUD_CAPABILITY_OBJECTSTORE,
  482. // cloudprovider.CLOUD_CAPABILITY_RDS,
  483. // cloudprovider.CLOUD_CAPABILITY_CACHE,
  484. // cloudprovider.CLOUD_CAPABILITY_EVENT,
  485. }
  486. return caps
  487. }