You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

resty.go 11 kB

4 years ago
3 years ago
3 years ago
5 years ago
3 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
3 years ago
3 years ago
3 years ago
5 years ago
3 years ago
5 years ago
5 years ago
5 years ago
5 years ago
3 years ago
3 years ago
3 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. package cloudbrain
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "math"
  7. "net/http"
  8. "strconv"
  9. "strings"
  10. "time"
  11. "code.gitea.io/gitea/modules/log"
  12. "code.gitea.io/gitea/models"
  13. "code.gitea.io/gitea/modules/setting"
  14. "github.com/go-resty/resty/v2"
  15. )
  16. var (
  17. restyClient *resty.Client
  18. HOST string
  19. TOKEN string
  20. ImagesUrlMap = map[string]string{Public: "/rest-server/api/v1/image/public/list/", Custom: "/rest-server/api/v1/image/list/"}
  21. )
  22. const (
  23. JobHasBeenStopped = "S410"
  24. Public = "public"
  25. Custom = "custom"
  26. LogPageSize = 500
  27. LogPageTokenExpired = "5m"
  28. )
  29. func getRestyClient() *resty.Client {
  30. if restyClient == nil {
  31. restyClient = resty.New()
  32. }
  33. return restyClient
  34. }
  35. func checkSetting() {
  36. if len(HOST) != 0 && len(TOKEN) != 0 && restyClient != nil {
  37. return
  38. }
  39. _ = loginCloudbrain()
  40. }
  41. func loginCloudbrain() error {
  42. conf := setting.GetCloudbrainConfig()
  43. username := conf.Username
  44. password := conf.Password
  45. HOST = conf.Host
  46. var loginResult models.CloudBrainLoginResult
  47. client := getRestyClient()
  48. res, err := client.R().
  49. SetHeader("Content-Type", "application/json").
  50. SetBody(map[string]interface{}{"username": username, "password": password, "expiration": "604800"}).
  51. SetResult(&loginResult).
  52. Post(HOST + "/rest-server/api/v1/token")
  53. if err != nil {
  54. return fmt.Errorf("resty loginCloudbrain: %s", err)
  55. }
  56. if loginResult.Code != Success {
  57. return fmt.Errorf("%s: %s", loginResult.Msg, res.String())
  58. }
  59. TOKEN = loginResult.Payload["token"].(string)
  60. return nil
  61. }
  62. func CreateJob(jobName string, createJobParams models.CreateJobParams) (*models.CreateJobResult, error) {
  63. checkSetting()
  64. client := getRestyClient()
  65. var jobResult models.CreateJobResult
  66. retry := 0
  67. sendjob:
  68. res, err := client.R().
  69. SetHeader("Content-Type", "application/json").
  70. SetAuthToken(TOKEN).
  71. SetBody(createJobParams).
  72. SetResult(&jobResult).
  73. Post(HOST + "/rest-server/api/v1/jobs/")
  74. if err != nil {
  75. if res != nil {
  76. var response models.CloudBrainResult
  77. json.Unmarshal(res.Body(), &response)
  78. log.Error("code(%s), msg(%s)", response.Code, response.Msg)
  79. return nil, fmt.Errorf(response.Msg)
  80. }
  81. return nil, fmt.Errorf("resty create job: %s", err)
  82. }
  83. if jobResult.Code == "S401" && retry < 1 {
  84. retry++
  85. _ = loginCloudbrain()
  86. goto sendjob
  87. }
  88. if jobResult.Code != Success {
  89. return &jobResult, fmt.Errorf("jobResult err: %s", res.String())
  90. }
  91. return &jobResult, nil
  92. }
  93. func GetJob(jobID string) (*models.GetJobResult, error) {
  94. checkSetting()
  95. // http://192.168.204.24/rest-server/api/v1/jobs/90e26e500c4b3011ea0a251099a987938b96
  96. client := getRestyClient()
  97. var getJobResult models.GetJobResult
  98. retry := 0
  99. sendjob:
  100. res, err := client.R().
  101. SetHeader("Content-Type", "application/json").
  102. SetAuthToken(TOKEN).
  103. SetResult(&getJobResult).
  104. Get(HOST + "/rest-server/api/v1/jobs/" + jobID)
  105. if err != nil {
  106. return nil, fmt.Errorf("resty GetJob: %v", err)
  107. }
  108. if getJobResult.Code == "S401" && retry < 1 {
  109. retry++
  110. _ = loginCloudbrain()
  111. goto sendjob
  112. }
  113. if getJobResult.Code != Success {
  114. return &getJobResult, fmt.Errorf("jobResult GetJob err: %s", res.String())
  115. }
  116. return &getJobResult, nil
  117. }
  118. func GetImages() (*models.GetImagesResult, error) {
  119. return GetImagesPageable(1, 100, Custom, "")
  120. }
  121. func GetPublicImages() (*models.GetImagesResult, error) {
  122. return GetImagesPageable(1, 100, Public, "")
  123. }
  124. func GetImagesPageable(page int, size int, imageType string, name string) (*models.GetImagesResult, error) {
  125. checkSetting()
  126. client := getRestyClient()
  127. var getImagesResult models.GetImagesResult
  128. retry := 0
  129. sendjob:
  130. res, err := client.R().
  131. SetHeader("Content-Type", "application/json").
  132. SetAuthToken(TOKEN).
  133. SetQueryString(getQueryString(page, size, name)).
  134. SetResult(&getImagesResult).
  135. Get(HOST + ImagesUrlMap[imageType])
  136. if err != nil {
  137. return nil, fmt.Errorf("resty GetImages: %v", err)
  138. }
  139. var response models.CloudBrainResult
  140. err = json.Unmarshal(res.Body(), &response)
  141. if err != nil {
  142. log.Error("json.Unmarshal failed: %s", err.Error())
  143. return &getImagesResult, fmt.Errorf("json.Unmarshal failed: %s", err.Error())
  144. }
  145. if response.Code == "S401" && retry < 1 {
  146. retry++
  147. _ = loginCloudbrain()
  148. goto sendjob
  149. }
  150. if getImagesResult.Code != Success {
  151. return &getImagesResult, fmt.Errorf("getImagesResult err: %s", res.String())
  152. }
  153. getImagesResult.Payload.TotalPages = getTotalPages(getImagesResult, size)
  154. return &getImagesResult, nil
  155. }
  156. func getTotalPages(getImagesResult models.GetImagesResult, size int) int {
  157. totalCount := getImagesResult.Payload.Count
  158. var totalPages int
  159. if totalCount%size != 0 {
  160. totalPages = totalCount/size + 1
  161. } else {
  162. totalPages = totalCount / size
  163. }
  164. return totalPages
  165. }
  166. func getQueryString(page int, size int, name string) string {
  167. if strings.TrimSpace(name) == "" {
  168. return fmt.Sprintf("pageIndex=%d&pageSize=%d", page, size)
  169. }
  170. return fmt.Sprintf("pageIndex=%d&pageSize=%d&name=%s", page, size, name)
  171. }
  172. func CommitImage(jobID string, params models.CommitImageParams) error {
  173. dbImage, err := models.GetImageByTag(params.ImageTag)
  174. if err != nil && !models.IsErrImageNotExist(err) {
  175. return fmt.Errorf("resty CommitImage: %v", err)
  176. }
  177. if dbImage != nil {
  178. if dbImage.UID != params.UID {
  179. return models.ErrorImageTagExist{
  180. Tag: params.ImageTag,
  181. }
  182. } else {
  183. if dbImage.Status == models.IMAGE_STATUS_COMMIT {
  184. return models.ErrorImageCommitting{
  185. Tag: params.ImageTag,
  186. }
  187. }
  188. }
  189. }
  190. checkSetting()
  191. client := getRestyClient()
  192. var result models.CommitImageResult
  193. retry := 0
  194. sendjob:
  195. res, err := client.R().
  196. SetHeader("Content-Type", "application/json").
  197. SetAuthToken(TOKEN).
  198. SetBody(params.CommitImageCloudBrainParams).
  199. SetResult(&result).
  200. Post(HOST + "/rest-server/api/v1/jobs/" + jobID + "/commitImage")
  201. if err != nil {
  202. return fmt.Errorf("resty CommitImage: %v", err)
  203. }
  204. if result.Code == "S401" && retry < 1 {
  205. retry++
  206. _ = loginCloudbrain()
  207. goto sendjob
  208. }
  209. if result.Code != Success {
  210. return fmt.Errorf("CommitImage err: %s", res.String())
  211. }
  212. image := models.Image{
  213. Type: models.NORMAL_TYPE,
  214. CloudbrainType: params.CloudBrainType,
  215. UID: params.UID,
  216. IsPrivate: params.IsPrivate,
  217. Tag: params.ImageTag,
  218. Description: params.ImageDescription,
  219. Place: setting.Cloudbrain.ImageURLPrefix + params.ImageTag,
  220. Status: models.IMAGE_STATUS_COMMIT,
  221. }
  222. err = models.WithTx(func(ctx models.DBContext) error {
  223. if dbImage != nil {
  224. dbImage.IsPrivate = params.IsPrivate
  225. dbImage.Description = params.ImageDescription
  226. dbImage.Status = models.IMAGE_STATUS_COMMIT
  227. if err := models.UpdateLocalImage(dbImage); err != nil {
  228. log.Error("Failed to update image record.", err)
  229. return fmt.Errorf("CommitImage err: %s", res.String())
  230. }
  231. } else {
  232. if err := models.CreateLocalImage(&image); err != nil {
  233. log.Error("Failed to insert image record.", err)
  234. return fmt.Errorf("CommitImage err: %s", res.String())
  235. }
  236. }
  237. if err := models.SaveImageTopics(image.ID, params.Topics...); err != nil {
  238. log.Error("Failed to insert image record.", err)
  239. return fmt.Errorf("CommitImage err: %s", res.String())
  240. }
  241. return nil
  242. })
  243. if err == nil {
  244. go updateImageStatus(image)
  245. }
  246. return err
  247. }
  248. func updateImageStatus(image models.Image) {
  249. attemps := 5
  250. commitSuccess := false
  251. time.Sleep(5 * time.Second)
  252. for i := 0; i < attemps; i++ {
  253. pageSize := models.GetCommittingImageCount()
  254. result, err := GetImagesPageable(1, pageSize, Custom, "")
  255. if err == nil && result.Code == "S000" {
  256. for _, v := range result.Payload.ImageInfo {
  257. if v.Place == image.Place {
  258. image.Status = models.IMAGE_STATUS_SUCCESS
  259. models.UpdateLocalImageStatus(&image)
  260. commitSuccess = true
  261. break
  262. }
  263. }
  264. }
  265. //第一次循环等待4秒,第二次等待4的2次方16秒,...,第5次。。。 ,总共大概是20多分钟内进行5次重试
  266. var sleepTime = time.Duration(int(math.Pow(4, (float64(i + 1)))))
  267. time.Sleep(sleepTime * time.Second)
  268. }
  269. if !commitSuccess {
  270. image.Status = models.IMAGE_STATUS_Failed
  271. models.UpdateLocalImageStatus(&image)
  272. }
  273. }
  274. func StopJob(jobID string) error {
  275. checkSetting()
  276. client := getRestyClient()
  277. var result models.CloudBrainResult
  278. retry := 0
  279. sendjob:
  280. res, err := client.R().
  281. SetHeader("Content-Type", "application/json").
  282. SetAuthToken(TOKEN).
  283. SetResult(&result).
  284. Delete(HOST + "/rest-server/api/v1/jobs/" + jobID)
  285. if err != nil {
  286. return fmt.Errorf("resty StopJob: %v", err)
  287. }
  288. if result.Code == "S401" && retry < 1 {
  289. retry++
  290. _ = loginCloudbrain()
  291. goto sendjob
  292. }
  293. if result.Code != Success {
  294. if result.Code == JobHasBeenStopped {
  295. log.Info("StopJob(%s) failed:%s", jobID, result.Msg)
  296. } else {
  297. return fmt.Errorf("StopJob err: %s", res.String())
  298. }
  299. }
  300. return nil
  301. }
  302. func GetJobLog(jobID string) (*models.GetJobLogResult, error) {
  303. checkSetting()
  304. client := getRestyClient()
  305. var result models.GetJobLogResult
  306. req := models.GetJobLogParams{
  307. Size: strconv.Itoa(LogPageSize),
  308. Sort: "log.offset",
  309. QueryInfo: models.QueryInfo{
  310. MatchInfo: models.MatchInfo{
  311. PodName: jobID + "-task1-0",
  312. },
  313. },
  314. }
  315. res, err := client.R().
  316. SetHeader("Content-Type", "application/json").
  317. SetAuthToken(TOKEN).
  318. SetBody(req).
  319. SetResult(&result).
  320. Post(HOST + "es/_search?_source=message&scroll=" + LogPageTokenExpired)
  321. if err != nil {
  322. log.Error("GetJobLog failed: %v", err)
  323. return &result, fmt.Errorf("resty GetJobLog: %v, %s", err, res.String())
  324. }
  325. if !strings.Contains(res.Status(), strconv.Itoa(http.StatusOK)) {
  326. log.Error("res.Status(): %s, response: %s", res.Status(), res.String())
  327. return &result, errors.New(res.String())
  328. }
  329. return &result, nil
  330. }
  331. func GetJobAllLog(scrollID string) (*models.GetJobLogResult, error) {
  332. checkSetting()
  333. client := getRestyClient()
  334. var result models.GetJobLogResult
  335. req := models.GetAllJobLogParams{
  336. Scroll: LogPageTokenExpired,
  337. ScrollID: scrollID,
  338. }
  339. res, err := client.R().
  340. SetHeader("Content-Type", "application/json").
  341. SetAuthToken(TOKEN).
  342. SetBody(req).
  343. SetResult(&result).
  344. Post(HOST + "es/_search/scroll")
  345. if err != nil {
  346. log.Error("GetJobAllLog failed: %v", err)
  347. return &result, fmt.Errorf("resty GetJobAllLog: %v, %s", err, res.String())
  348. }
  349. if !strings.Contains(res.Status(), strconv.Itoa(http.StatusOK)) {
  350. log.Error("res.Status(): %s, response: %s", res.Status(), res.String())
  351. return &result, errors.New(res.String())
  352. }
  353. return &result, nil
  354. }
  355. func DeleteJobLogToken(scrollID string) (error) {
  356. checkSetting()
  357. client := getRestyClient()
  358. var result models.DeleteJobLogTokenResult
  359. req := models.DeleteJobLogTokenParams{
  360. ScrollID: scrollID,
  361. }
  362. res, err := client.R().
  363. SetHeader("Content-Type", "application/json").
  364. SetAuthToken(TOKEN).
  365. SetBody(req).
  366. SetResult(&result).
  367. Delete(HOST + "es/_search/scroll")
  368. if err != nil {
  369. log.Error("DeleteJobLogToken failed: %v", err)
  370. return fmt.Errorf("resty DeleteJobLogToken: %v, %s", err, res.String())
  371. }
  372. if !strings.Contains(res.Status(), strconv.Itoa(http.StatusOK)) {
  373. log.Error("res.Status(): %s, response: %s", res.Status(), res.String())
  374. return errors.New(res.String())
  375. }
  376. if !result.Succeeded {
  377. log.Error("DeleteJobLogToken failed")
  378. return errors.New("DeleteJobLogToken failed")
  379. }
  380. return nil
  381. }