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

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