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

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