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