utils.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  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 hcso
  15. import (
  16. "fmt"
  17. "reflect"
  18. "strings"
  19. "yunion.io/x/jsonutils"
  20. "yunion.io/x/log"
  21. "yunion.io/x/pkg/errors"
  22. "yunion.io/x/pkg/util/httputils"
  23. "yunion.io/x/pkg/utils"
  24. "yunion.io/x/cloudmux/pkg/cloudprovider"
  25. "yunion.io/x/cloudmux/pkg/multicloud/hcso/client/manager"
  26. "yunion.io/x/cloudmux/pkg/multicloud/hcso/client/responses"
  27. )
  28. // 常用的方法
  29. type listFunc func(querys map[string]string) (*responses.ListResult, error)
  30. type getFunc func(id string, querys map[string]string) (jsonutils.JSONObject, error)
  31. type createFunc func(params jsonutils.JSONObject) (jsonutils.JSONObject, error)
  32. type updateFunc func(id string, params jsonutils.JSONObject) (jsonutils.JSONObject, error)
  33. type updateFunc2 func(ctx manager.IManagerContext, id string, spec string, params jsonutils.JSONObject, responseKey string) (jsonutils.JSONObject, error)
  34. type deleteFunc func(id string, params jsonutils.JSONObject) (jsonutils.JSONObject, error)
  35. type deleteFunc2 func(ctx manager.IManagerContext, id string, spec string, queries map[string]string, params jsonutils.JSONObject, responseKey string) (jsonutils.JSONObject, error)
  36. type listInCtxFunc func(ctx manager.IManagerContext, querys map[string]string) (*responses.ListResult, error)
  37. type listInCtxWithSpecFunc func(ctx manager.IManagerContext, spec string, querys map[string]string, responseKey string) (*responses.ListResult, error)
  38. func unmarshalResult(resp jsonutils.JSONObject, respErr error, result interface{}, method string) error {
  39. if respErr != nil {
  40. switch e := respErr.(type) {
  41. case *httputils.JSONClientError:
  42. if (e.Code == 404 || utils.IsInStringArray(e.Class, NOT_FOUND_CODES)) && method != "POST" {
  43. return cloudprovider.ErrNotFound
  44. }
  45. return e
  46. default:
  47. return e
  48. }
  49. }
  50. if result == nil {
  51. return nil
  52. }
  53. err := resp.Unmarshal(result)
  54. if err != nil {
  55. log.Errorf("unmarshal json error %s", err)
  56. }
  57. return err
  58. }
  59. var pageLimit = 100
  60. // offset 表示的是页码
  61. func doListAllWithPagerOffset(doList listFunc, queries map[string]string, result interface{}) error {
  62. startIndex := 0
  63. resultValue := reflect.Indirect(reflect.ValueOf(result))
  64. queries["limit"] = fmt.Sprintf("%d", pageLimit)
  65. queries["offset"] = fmt.Sprintf("%d", startIndex)
  66. for {
  67. total, part, err := doListPart(doList, queries, result)
  68. if err != nil {
  69. return err
  70. }
  71. if (total > 0 && resultValue.Len() >= total) || (total == 0 && pageLimit > part) {
  72. break
  73. }
  74. startIndex++
  75. queries["offset"] = fmt.Sprintf("%d", startIndex)
  76. }
  77. return nil
  78. }
  79. func doListAllWithNextLink(doList listFunc, querys map[string]string, result interface{}) error {
  80. values := []jsonutils.JSONObject{}
  81. for {
  82. ret, err := doList(querys)
  83. if err != nil {
  84. return errors.Wrap(err, "doList")
  85. }
  86. values = append(values, ret.Data...)
  87. if len(ret.NextLink) == 0 || ret.NextLink == "null" {
  88. break
  89. }
  90. }
  91. if result != nil {
  92. return jsonutils.Update(result, values)
  93. }
  94. return nil
  95. }
  96. func doListAllWithOffset(doList listFunc, queries map[string]string, result interface{}) error {
  97. startIndex := 0
  98. resultValue := reflect.Indirect(reflect.ValueOf(result))
  99. queries["limit"] = fmt.Sprintf("%d", pageLimit)
  100. queries["offset"] = fmt.Sprintf("%d", startIndex)
  101. for {
  102. total, part, err := doListPart(doList, queries, result)
  103. if err != nil {
  104. return err
  105. }
  106. if (total > 0 && resultValue.Len() >= total) || (total == 0 && pageLimit > part) {
  107. break
  108. }
  109. queries["offset"] = fmt.Sprintf("%d", startIndex+resultValue.Len())
  110. }
  111. return nil
  112. }
  113. func doListAllWithPage(doList listFunc, queries map[string]string, result interface{}) error {
  114. startIndex := 1
  115. resultValue := reflect.Indirect(reflect.ValueOf(result))
  116. queries["limit"] = fmt.Sprintf("%d", pageLimit)
  117. queries["page"] = fmt.Sprintf("%d", startIndex)
  118. for {
  119. total, part, err := doListPart(doList, queries, result)
  120. if err != nil {
  121. return err
  122. }
  123. if (total > 0 && resultValue.Len() >= total) || (total == 0 && pageLimit > part) {
  124. break
  125. }
  126. queries["page"] = fmt.Sprintf("%d", startIndex+resultValue.Len())
  127. }
  128. return nil
  129. }
  130. func doListAllWithMarker(doList listFunc, queries map[string]string, result interface{}) error {
  131. resultValue := reflect.Indirect(reflect.ValueOf(result))
  132. queries["limit"] = fmt.Sprintf("%d", pageLimit)
  133. for {
  134. total, part, err := doListPart(doList, queries, result)
  135. if err != nil {
  136. return err
  137. }
  138. if (total > 0 && resultValue.Len() >= total) || (total == 0 && pageLimit > part) {
  139. break
  140. }
  141. lastValue := resultValue.Index(resultValue.Len() - 1)
  142. markerValue := lastValue.FieldByNameFunc(func(key string) bool {
  143. if strings.ToLower(key) == "id" {
  144. return true
  145. }
  146. return false
  147. })
  148. queries["marker"] = markerValue.String()
  149. }
  150. return nil
  151. }
  152. func doListAll(doList listFunc, queries map[string]string, result interface{}) error {
  153. total, _, err := doListPart(doList, queries, result)
  154. if err != nil {
  155. return err
  156. }
  157. resultValue := reflect.Indirect(reflect.ValueOf(result))
  158. if total > 0 && resultValue.Len() < total {
  159. log.Warningf("INCOMPLETE QUERY, total %d queried %d", total, resultValue.Len())
  160. }
  161. return nil
  162. }
  163. func doListPart(doList listFunc, queries map[string]string, result interface{}) (int, int, error) {
  164. ret, err := doList(queries)
  165. if err != nil {
  166. return 0, 0, err
  167. }
  168. resultValue := reflect.Indirect(reflect.ValueOf(result))
  169. elemType := resultValue.Type().Elem()
  170. for i := range ret.Data {
  171. elemPtr := reflect.New(elemType)
  172. err = ret.Data[i].Unmarshal(elemPtr.Interface())
  173. if err != nil {
  174. return 0, 0, err
  175. }
  176. resultValue.Set(reflect.Append(resultValue, elemPtr.Elem()))
  177. }
  178. return ret.Total, len(ret.Data), nil
  179. }
  180. func DoGet(doGet getFunc, id string, queries map[string]string, result interface{}) error {
  181. if len(id) == 0 {
  182. resultType := reflect.Indirect(reflect.ValueOf(result)).Type()
  183. return errors.Wrap(cloudprovider.ErrNotFound, fmt.Sprintf(" Get %s id should not be empty", resultType.Name()))
  184. }
  185. ret, err := doGet(id, queries)
  186. return unmarshalResult(ret, err, result, "GET")
  187. }
  188. func DoListInContext(listFunc listInCtxFunc, ctx manager.IManagerContext, querys map[string]string, result interface{}) error {
  189. ret, err := listFunc(ctx, querys)
  190. if err != nil {
  191. return err
  192. }
  193. obj := responses.ListResult2JSON(ret)
  194. err = obj.Unmarshal(result, "data")
  195. if err != nil {
  196. log.Errorf("unmarshal json error %s", err)
  197. return err
  198. }
  199. return nil
  200. }
  201. func DoCreate(createFunc createFunc, params jsonutils.JSONObject, result interface{}) error {
  202. ret, err := createFunc(params)
  203. return unmarshalResult(ret, err, result, "POST")
  204. }
  205. func DoUpdate(updateFunc updateFunc, id string, params jsonutils.JSONObject, result interface{}) error {
  206. ret, err := updateFunc(id, params)
  207. return unmarshalResult(ret, err, result, "PUT")
  208. }
  209. func DoUpdateWithSpec(updateFunc updateFunc2, id string, spec string, params jsonutils.JSONObject) error {
  210. _, err := updateFunc(nil, id, spec, params, "")
  211. return err
  212. }
  213. func DoUpdateWithSpec2(updateFunc updateFunc2, id string, spec string, params jsonutils.JSONObject, result interface{}) error {
  214. ret, err := updateFunc(nil, id, spec, params, "")
  215. return unmarshalResult(ret, err, result, "PUT")
  216. }
  217. func DoDelete(deleteFunc deleteFunc, id string, params jsonutils.JSONObject, result interface{}) error {
  218. if len(id) == 0 {
  219. return fmt.Errorf(" id should not be empty")
  220. }
  221. ret, err := deleteFunc(id, params)
  222. return unmarshalResult(ret, err, result, "DELETE")
  223. }
  224. func DoDeleteWithSpec(deleteFunc deleteFunc2, ctx manager.IManagerContext, id string, spec string, queries map[string]string, params jsonutils.JSONObject) error {
  225. if len(id) == 0 {
  226. return fmt.Errorf(" id should not be empty")
  227. }
  228. _, err := deleteFunc(ctx, id, spec, queries, params, "")
  229. return err
  230. }
  231. func ErrMessage(err error) string {
  232. switch v := err.(type) {
  233. case *httputils.JSONClientError:
  234. return fmt.Sprintf("%d(%s):%s", v.Code, v.Class, v.Details)
  235. default:
  236. return err.Error()
  237. }
  238. }