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
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
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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  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. dbImage, err := models.GetImageByTag(params.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: params.ImageTag,
  184. }
  185. } else {
  186. if dbImage.Status == models.IMAGE_STATUS_COMMIT {
  187. return models.ErrorImageCommitting{
  188. Tag: params.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: params.ImageTag,
  232. Description: params.ImageDescription,
  233. Place: setting.Cloudbrain.ImageURLPrefix + params.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. exist, err := models.IsImageExist(params.ImageTag)
  265. if err != nil {
  266. return fmt.Errorf("resty CommitImage: %v", err)
  267. }
  268. if exist {
  269. return models.ErrorImageTagExist{
  270. Tag: params.ImageTag,
  271. }
  272. }
  273. image := models.Image{
  274. CloudbrainType: params.CloudBrainType,
  275. UID: params.UID,
  276. IsPrivate: params.IsPrivate,
  277. Tag: params.ImageTag,
  278. Description: params.ImageDescription,
  279. Place: params.Place,
  280. Status: models.IMAGE_STATUS_SUCCESS,
  281. Type: params.Type,
  282. }
  283. err = models.WithTx(func(ctx models.DBContext) error {
  284. if err := models.CreateLocalImage(&image); err != nil {
  285. log.Error("Failed to insert image record.", err)
  286. return fmt.Errorf("resty CommitImage: %v", err)
  287. }
  288. if err := models.SaveImageTopics(image.ID, params.Topics...); err != nil {
  289. log.Error("Failed to insert image record.", err)
  290. return fmt.Errorf("resty CommitImage: %v", err)
  291. }
  292. return nil
  293. })
  294. return err
  295. }
  296. func updateImageStatus(image models.Image, isSetCreatedUnix bool, createTime time.Time) {
  297. attemps := 5
  298. commitSuccess := false
  299. time.Sleep(5 * time.Second)
  300. for i := 0; i < attemps; i++ {
  301. if commitSuccess {
  302. break
  303. }
  304. result, err := GetImagesPageable(1, pageSize, Custom, "")
  305. if err == nil && result.Code == "S000" {
  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. //第一次循环等待4秒,第二次等待4的2次方16秒,...,第5次。。。 ,总共大概是20多分钟内进行5次重试
  316. var sleepTime = time.Duration(int(math.Pow(4, (float64(i + 1)))))
  317. time.Sleep(sleepTime * time.Second)
  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. }