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

4 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
4 years ago
5 years ago
3 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
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
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
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
4 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  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. if dbImage != nil {
  256. dbImage.IsPrivate = params.IsPrivate
  257. dbImage.Description = params.ImageDescription
  258. dbImage.Status = models.IMAGE_STATUS_COMMIT
  259. image = *dbImage
  260. if err := models.UpdateLocalImage(dbImage); err != nil {
  261. log.Error("Failed to update image record.", err)
  262. return fmt.Errorf("CommitImage err: %s", res.String())
  263. }
  264. } else {
  265. if err := models.CreateLocalImage(&image); err != nil {
  266. log.Error("Failed to insert image record.", err)
  267. return fmt.Errorf("CommitImage err: %s", res.String())
  268. }
  269. }
  270. if err := models.SaveImageTopics(image.ID, params.Topics...); err != nil {
  271. log.Error("Failed to insert image record.", err)
  272. return fmt.Errorf("CommitImage err: %s", res.String())
  273. }
  274. return nil
  275. })
  276. if err == nil {
  277. go updateImageStatus(image, isSetCreatedUnix, createTime)
  278. }
  279. return err
  280. }
  281. func CommitAdminImage(params models.CommitImageParams) error {
  282. imageTag := strings.TrimSpace(params.ImageTag)
  283. exist, err := models.IsImageExist(imageTag)
  284. if err != nil {
  285. return fmt.Errorf("resty CommitImage: %v", err)
  286. }
  287. if exist {
  288. return models.ErrorImageTagExist{
  289. Tag: imageTag,
  290. }
  291. }
  292. image := models.Image{
  293. CloudbrainType: params.CloudBrainType,
  294. UID: params.UID,
  295. IsPrivate: params.IsPrivate,
  296. Tag: imageTag,
  297. Description: params.ImageDescription,
  298. Place: params.Place,
  299. Status: models.IMAGE_STATUS_SUCCESS,
  300. Type: params.Type,
  301. }
  302. err = models.WithTx(func(ctx models.DBContext) error {
  303. if err := models.CreateLocalImage(&image); err != nil {
  304. log.Error("Failed to insert image record.", err)
  305. return fmt.Errorf("resty CommitImage: %v", err)
  306. }
  307. if err := models.SaveImageTopics(image.ID, params.Topics...); err != nil {
  308. log.Error("Failed to insert image record.", err)
  309. return fmt.Errorf("resty CommitImage: %v", err)
  310. }
  311. return nil
  312. })
  313. return err
  314. }
  315. func updateImageStatus(image models.Image, isSetCreatedUnix bool, createTime time.Time) {
  316. attemps := 60
  317. commitSuccess := false
  318. for i := 0; i < attemps; i++ {
  319. time.Sleep(20 * time.Second)
  320. log.Info("the " + strconv.Itoa(i) + " times query cloudbrain images.Imagetag:" + image.Tag + "isSetCreate:" + strconv.FormatBool(isSetCreatedUnix))
  321. result, err := GetImagesPageable(1, pageSize, Custom, "")
  322. if err == nil && result.Code == "S000" {
  323. log.Info("images count:" + strconv.Itoa(result.Payload.Count))
  324. for _, v := range result.Payload.ImageInfo {
  325. if v.Place == image.Place && (!isSetCreatedUnix || (isSetCreatedUnix && createTimeUpdated(v, createTime))) {
  326. image.Status = models.IMAGE_STATUS_SUCCESS
  327. models.UpdateLocalImageStatus(&image)
  328. commitSuccess = true
  329. break
  330. }
  331. }
  332. }
  333. if commitSuccess {
  334. break
  335. }
  336. }
  337. if !commitSuccess {
  338. image.Status = models.IMAGE_STATUS_Failed
  339. models.UpdateLocalImageStatus(&image)
  340. }
  341. }
  342. func createTimeUpdated(v *models.ImageInfo, createTime time.Time) bool {
  343. newTime, err := time.Parse(time.RFC3339, v.Createtime)
  344. if err != nil {
  345. return false
  346. }
  347. return newTime.After(createTime)
  348. }
  349. func StopJob(jobID string) error {
  350. checkSetting()
  351. client := getRestyClient()
  352. var result models.CloudBrainResult
  353. retry := 0
  354. sendjob:
  355. res, err := client.R().
  356. SetHeader("Content-Type", "application/json").
  357. SetAuthToken(TOKEN).
  358. SetResult(&result).
  359. Delete(HOST + "/rest-server/api/v1/jobs/" + jobID)
  360. if err != nil {
  361. return fmt.Errorf("resty StopJob: %v", err)
  362. }
  363. if result.Code == "S401" && retry < 1 {
  364. retry++
  365. _ = loginCloudbrain()
  366. goto sendjob
  367. }
  368. if result.Code != Success {
  369. if result.Code == JobHasBeenStopped {
  370. log.Info("StopJob(%s) failed:%s", jobID, result.Msg)
  371. } else {
  372. return fmt.Errorf("StopJob err: %s", res.String())
  373. }
  374. }
  375. return nil
  376. }
  377. func GetJobLog(jobID string) (*models.GetJobLogResult, error) {
  378. checkSetting()
  379. client := getRestyClient()
  380. var result models.GetJobLogResult
  381. req := models.GetJobLogParams{
  382. Size: strconv.Itoa(LogPageSize),
  383. Sort: "log.offset",
  384. QueryInfo: models.QueryInfo{
  385. MatchInfo: models.MatchInfo{
  386. PodName: jobID + "-task1-0",
  387. },
  388. },
  389. }
  390. res, err := client.R().
  391. SetHeader("Content-Type", "application/json").
  392. SetAuthToken(TOKEN).
  393. SetBody(req).
  394. SetResult(&result).
  395. Post(HOST + "es/_search?_source=message&scroll=" + LogPageTokenExpired)
  396. if err != nil {
  397. log.Error("GetJobLog failed: %v", err)
  398. return &result, fmt.Errorf("resty GetJobLog: %v, %s", err, res.String())
  399. }
  400. if !strings.Contains(res.Status(), strconv.Itoa(http.StatusOK)) {
  401. log.Error("res.Status(): %s, response: %s", res.Status(), res.String())
  402. return &result, errors.New(res.String())
  403. }
  404. return &result, nil
  405. }
  406. func GetJobAllLog(scrollID string) (*models.GetJobLogResult, error) {
  407. checkSetting()
  408. client := getRestyClient()
  409. var result models.GetJobLogResult
  410. req := models.GetAllJobLogParams{
  411. Scroll: LogPageTokenExpired,
  412. ScrollID: scrollID,
  413. }
  414. res, err := client.R().
  415. SetHeader("Content-Type", "application/json").
  416. SetAuthToken(TOKEN).
  417. SetBody(req).
  418. SetResult(&result).
  419. Post(HOST + "es/_search/scroll")
  420. if err != nil {
  421. log.Error("GetJobAllLog failed: %v", err)
  422. return &result, fmt.Errorf("resty GetJobAllLog: %v, %s", err, res.String())
  423. }
  424. if !strings.Contains(res.Status(), strconv.Itoa(http.StatusOK)) {
  425. log.Error("res.Status(): %s, response: %s", res.Status(), res.String())
  426. return &result, errors.New(res.String())
  427. }
  428. return &result, nil
  429. }
  430. func DeleteJobLogToken(scrollID string) (error) {
  431. checkSetting()
  432. client := getRestyClient()
  433. var result models.DeleteJobLogTokenResult
  434. req := models.DeleteJobLogTokenParams{
  435. ScrollID: scrollID,
  436. }
  437. res, err := client.R().
  438. SetHeader("Content-Type", "application/json").
  439. SetAuthToken(TOKEN).
  440. SetBody(req).
  441. SetResult(&result).
  442. Delete(HOST + "es/_search/scroll")
  443. if err != nil {
  444. log.Error("DeleteJobLogToken failed: %v", err)
  445. return fmt.Errorf("resty DeleteJobLogToken: %v, %s", err, res.String())
  446. }
  447. if !strings.Contains(res.Status(), strconv.Itoa(http.StatusOK)) {
  448. log.Error("res.Status(): %s, response: %s", res.Status(), res.String())
  449. return errors.New(res.String())
  450. }
  451. if !result.Succeeded {
  452. log.Error("DeleteJobLogToken failed")
  453. return errors.New("DeleteJobLogToken failed")
  454. }
  455. return nil
  456. }