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
4 years ago
3 years ago
3 years ago
4 years ago
5 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  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. 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. imageTag := strings.TrimSpace(params.ImageTag)
  174. dbImage, err := models.GetImageByTag(imageTag)
  175. if err != nil && !models.IsErrImageNotExist(err) {
  176. return fmt.Errorf("resty CommitImage: %v", err)
  177. }
  178. var createTime time.Time
  179. var isSetCreatedUnix = false
  180. if dbImage != nil {
  181. if dbImage.UID != params.UID {
  182. return models.ErrorImageTagExist{
  183. Tag: imageTag,
  184. }
  185. } else {
  186. if dbImage.Status == models.IMAGE_STATUS_COMMIT {
  187. return models.ErrorImageCommitting{
  188. Tag: imageTag,
  189. }
  190. } else { //覆盖提交
  191. result, err := GetImagesPageable(1, pageSize, Custom, "")
  192. if err == nil && result.Code == "S000" {
  193. for _, v := range result.Payload.ImageInfo {
  194. if v.Place == dbImage.Place {
  195. isSetCreatedUnix = true
  196. createTime, _ = time.Parse(time.RFC3339, v.Createtime)
  197. break
  198. }
  199. }
  200. }
  201. }
  202. }
  203. }
  204. checkSetting()
  205. client := getRestyClient()
  206. var result models.CommitImageResult
  207. retry := 0
  208. sendjob:
  209. res, err := client.R().
  210. SetHeader("Content-Type", "application/json").
  211. SetAuthToken(TOKEN).
  212. SetBody(params.CommitImageCloudBrainParams).
  213. SetResult(&result).
  214. Post(HOST + "/rest-server/api/v1/jobs/" + jobID + "/commitImage")
  215. if err != nil {
  216. return fmt.Errorf("resty CommitImage: %v", err)
  217. }
  218. if result.Code == "S401" && retry < 1 {
  219. retry++
  220. _ = loginCloudbrain()
  221. goto sendjob
  222. }
  223. if result.Code != Success {
  224. return fmt.Errorf("CommitImage err: %s", res.String())
  225. }
  226. image := models.Image{
  227. Type: models.NORMAL_TYPE,
  228. CloudbrainType: params.CloudBrainType,
  229. UID: params.UID,
  230. IsPrivate: params.IsPrivate,
  231. Tag: imageTag,
  232. Description: params.ImageDescription,
  233. Place: setting.Cloudbrain.ImageURLPrefix + imageTag,
  234. Status: models.IMAGE_STATUS_COMMIT,
  235. }
  236. err = models.WithTx(func(ctx models.DBContext) error {
  237. if dbImage != nil {
  238. dbImage.IsPrivate = params.IsPrivate
  239. dbImage.Description = params.ImageDescription
  240. dbImage.Status = models.IMAGE_STATUS_COMMIT
  241. image = *dbImage
  242. if err := models.UpdateLocalImage(dbImage); err != nil {
  243. log.Error("Failed to update image record.", err)
  244. return fmt.Errorf("CommitImage err: %s", res.String())
  245. }
  246. } else {
  247. if err := models.CreateLocalImage(&image); err != nil {
  248. log.Error("Failed to insert image record.", err)
  249. return fmt.Errorf("CommitImage err: %s", res.String())
  250. }
  251. }
  252. if err := models.SaveImageTopics(image.ID, params.Topics...); err != nil {
  253. log.Error("Failed to insert image record.", err)
  254. return fmt.Errorf("CommitImage err: %s", res.String())
  255. }
  256. return nil
  257. })
  258. if err == nil {
  259. go updateImageStatus(image, isSetCreatedUnix, createTime)
  260. }
  261. return err
  262. }
  263. func CommitAdminImage(params models.CommitImageParams) error {
  264. imageTag := strings.TrimSpace(params.ImageTag)
  265. exist, err := models.IsImageExist(imageTag)
  266. if err != nil {
  267. return fmt.Errorf("resty CommitImage: %v", err)
  268. }
  269. if exist {
  270. return models.ErrorImageTagExist{
  271. Tag: imageTag,
  272. }
  273. }
  274. image := models.Image{
  275. CloudbrainType: params.CloudBrainType,
  276. UID: params.UID,
  277. IsPrivate: params.IsPrivate,
  278. Tag: imageTag,
  279. Description: params.ImageDescription,
  280. Place: params.Place,
  281. Status: models.IMAGE_STATUS_SUCCESS,
  282. Type: params.Type,
  283. }
  284. err = models.WithTx(func(ctx models.DBContext) error {
  285. if err := models.CreateLocalImage(&image); err != nil {
  286. log.Error("Failed to insert image record.", err)
  287. return fmt.Errorf("resty CommitImage: %v", err)
  288. }
  289. if err := models.SaveImageTopics(image.ID, params.Topics...); err != nil {
  290. log.Error("Failed to insert image record.", err)
  291. return fmt.Errorf("resty CommitImage: %v", err)
  292. }
  293. return nil
  294. })
  295. return err
  296. }
  297. func updateImageStatus(image models.Image, isSetCreatedUnix bool, createTime time.Time) {
  298. attemps := 60
  299. commitSuccess := false
  300. for i := 0; i < attemps; i++ {
  301. time.Sleep(20 * time.Second)
  302. log.Info("the " + strconv.Itoa(i) + " times query cloudbrain images.Imagetag:" + image.Tag + "isSetCreate:" + strconv.FormatBool(isSetCreatedUnix))
  303. result, err := GetImagesPageable(1, pageSize, Custom, "")
  304. if err == nil && result.Code == "S000" {
  305. log.Info("images count:" + strconv.Itoa(result.Payload.Count))
  306. for _, v := range result.Payload.ImageInfo {
  307. if v.Place == image.Place && (!isSetCreatedUnix || (isSetCreatedUnix && createTimeUpdated(v, createTime))) {
  308. image.Status = models.IMAGE_STATUS_SUCCESS
  309. models.UpdateLocalImageStatus(&image)
  310. commitSuccess = true
  311. break
  312. }
  313. }
  314. }
  315. if commitSuccess {
  316. break
  317. }
  318. }
  319. if !commitSuccess {
  320. image.Status = models.IMAGE_STATUS_Failed
  321. models.UpdateLocalImageStatus(&image)
  322. }
  323. }
  324. func createTimeUpdated(v *models.ImageInfo, createTime time.Time) bool {
  325. newTime, err := time.Parse(time.RFC3339, v.Createtime)
  326. if err != nil {
  327. return false
  328. }
  329. return newTime.After(createTime)
  330. }
  331. func StopJob(jobID string) error {
  332. checkSetting()
  333. client := getRestyClient()
  334. var result models.CloudBrainResult
  335. retry := 0
  336. sendjob:
  337. res, err := client.R().
  338. SetHeader("Content-Type", "application/json").
  339. SetAuthToken(TOKEN).
  340. SetResult(&result).
  341. Delete(HOST + "/rest-server/api/v1/jobs/" + jobID)
  342. if err != nil {
  343. return fmt.Errorf("resty StopJob: %v", err)
  344. }
  345. if result.Code == "S401" && retry < 1 {
  346. retry++
  347. _ = loginCloudbrain()
  348. goto sendjob
  349. }
  350. if result.Code != Success {
  351. if result.Code == JobHasBeenStopped {
  352. log.Info("StopJob(%s) failed:%s", jobID, result.Msg)
  353. } else {
  354. return fmt.Errorf("StopJob err: %s", res.String())
  355. }
  356. }
  357. return nil
  358. }
  359. func GetJobLog(jobID string) (*models.GetJobLogResult, error) {
  360. checkSetting()
  361. client := getRestyClient()
  362. var result models.GetJobLogResult
  363. req := models.GetJobLogParams{
  364. Size: strconv.Itoa(LogPageSize),
  365. Sort: "log.offset",
  366. QueryInfo: models.QueryInfo{
  367. MatchInfo: models.MatchInfo{
  368. PodName: jobID + "-task1-0",
  369. },
  370. },
  371. }
  372. res, err := client.R().
  373. SetHeader("Content-Type", "application/json").
  374. SetAuthToken(TOKEN).
  375. SetBody(req).
  376. SetResult(&result).
  377. Post(HOST + "es/_search?_source=message&scroll=" + LogPageTokenExpired)
  378. if err != nil {
  379. log.Error("GetJobLog failed: %v", err)
  380. return &result, fmt.Errorf("resty GetJobLog: %v, %s", err, res.String())
  381. }
  382. if !strings.Contains(res.Status(), strconv.Itoa(http.StatusOK)) {
  383. log.Error("res.Status(): %s, response: %s", res.Status(), res.String())
  384. return &result, errors.New(res.String())
  385. }
  386. return &result, nil
  387. }
  388. func GetJobAllLog(scrollID string) (*models.GetJobLogResult, error) {
  389. checkSetting()
  390. client := getRestyClient()
  391. var result models.GetJobLogResult
  392. req := models.GetAllJobLogParams{
  393. Scroll: LogPageTokenExpired,
  394. ScrollID: scrollID,
  395. }
  396. res, err := client.R().
  397. SetHeader("Content-Type", "application/json").
  398. SetAuthToken(TOKEN).
  399. SetBody(req).
  400. SetResult(&result).
  401. Post(HOST + "es/_search/scroll")
  402. if err != nil {
  403. log.Error("GetJobAllLog failed: %v", err)
  404. return &result, fmt.Errorf("resty GetJobAllLog: %v, %s", err, res.String())
  405. }
  406. if !strings.Contains(res.Status(), strconv.Itoa(http.StatusOK)) {
  407. log.Error("res.Status(): %s, response: %s", res.Status(), res.String())
  408. return &result, errors.New(res.String())
  409. }
  410. return &result, nil
  411. }
  412. func DeleteJobLogToken(scrollID string) (error) {
  413. checkSetting()
  414. client := getRestyClient()
  415. var result models.DeleteJobLogTokenResult
  416. req := models.DeleteJobLogTokenParams{
  417. ScrollID: scrollID,
  418. }
  419. res, err := client.R().
  420. SetHeader("Content-Type", "application/json").
  421. SetAuthToken(TOKEN).
  422. SetBody(req).
  423. SetResult(&result).
  424. Delete(HOST + "es/_search/scroll")
  425. if err != nil {
  426. log.Error("DeleteJobLogToken failed: %v", err)
  427. return fmt.Errorf("resty DeleteJobLogToken: %v, %s", err, res.String())
  428. }
  429. if !strings.Contains(res.Status(), strconv.Itoa(http.StatusOK)) {
  430. log.Error("res.Status(): %s, response: %s", res.Status(), res.String())
  431. return errors.New(res.String())
  432. }
  433. if !result.Succeeded {
  434. log.Error("DeleteJobLogToken failed")
  435. return errors.New("DeleteJobLogToken failed")
  436. }
  437. return nil
  438. }