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 14 kB

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