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.

cloudbrain.go 16 kB

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
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
2 years ago
3 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 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
3 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  1. // Copyright 2016 The Gogs Authors. All rights reserved.
  2. // Copyright 2018 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package repo
  6. import (
  7. "code.gitea.io/gitea/modules/notification"
  8. "encoding/json"
  9. "net/http"
  10. "sort"
  11. "strings"
  12. "time"
  13. "code.gitea.io/gitea/modules/setting"
  14. "code.gitea.io/gitea/models"
  15. "code.gitea.io/gitea/modules/cloudbrain"
  16. "code.gitea.io/gitea/modules/context"
  17. "code.gitea.io/gitea/modules/log"
  18. "code.gitea.io/gitea/modules/modelarts"
  19. "code.gitea.io/gitea/modules/storage"
  20. routerRepo "code.gitea.io/gitea/routers/repo"
  21. )
  22. // cloudbrain get job task by jobid
  23. func GetCloudbrainTask(ctx *context.APIContext) {
  24. // swagger:operation GET /repos/{owner}/{repo}/cloudbrain/{jobid} cloudbrain jobTask
  25. // ---
  26. // summary: Get a single task
  27. // produces:
  28. // - application/json
  29. // parameters:
  30. // - name: owner
  31. // in: path
  32. // description: owner of the repo
  33. // type: string
  34. // required: true
  35. // - name: repo
  36. // in: path
  37. // description: name of the repo
  38. // type: string
  39. // required: true
  40. // - name: jobid
  41. // in: path
  42. // description: id of cloudbrain jobid
  43. // type: string
  44. // required: true
  45. // responses:
  46. // "200":
  47. // "$ref": "#/responses/Label"
  48. var (
  49. err error
  50. )
  51. ID := ctx.Params(":id")
  52. job, err := models.GetCloudbrainByID(ID)
  53. if err != nil {
  54. ctx.NotFound(err)
  55. log.Error("GetCloudbrainByID failed:", err)
  56. return
  57. }
  58. jobResult, err := cloudbrain.GetJob(job.JobID)
  59. if err != nil {
  60. ctx.NotFound(err)
  61. log.Error("GetJob failed:", err)
  62. return
  63. }
  64. result, _ := models.ConvertToJobResultPayload(jobResult.Payload)
  65. if err != nil {
  66. ctx.NotFound(err)
  67. log.Error("ConvertToJobResultPayload failed:", err)
  68. return
  69. }
  70. oldStatus := job.Status
  71. job.Status = result.JobStatus.State
  72. taskRoles := result.TaskRoles
  73. taskRes, _ := models.ConvertToTaskPod(taskRoles[cloudbrain.SubTaskName].(map[string]interface{}))
  74. if result.JobStatus.State != string(models.JobWaiting) && result.JobStatus.State != string(models.JobFailed) {
  75. job.ContainerIp = taskRes.TaskStatuses[0].ContainerIP
  76. job.ContainerID = taskRes.TaskStatuses[0].ContainerID
  77. job.Status = taskRes.TaskStatuses[0].State
  78. }
  79. if result.JobStatus.State != string(models.JobWaiting) {
  80. models.ParseAndSetDurationFromCloudBrainOne(result, job)
  81. if oldStatus != job.Status {
  82. notification.NotifyChangeCloudbrainStatus(job, oldStatus)
  83. }
  84. err = models.UpdateJob(job)
  85. if err != nil {
  86. log.Error("UpdateJob failed:", err)
  87. }
  88. }
  89. ctx.JSON(http.StatusOK, map[string]interface{}{
  90. "ID": ID,
  91. "JobName": result.Config.JobName,
  92. "JobStatus": result.JobStatus.State,
  93. "SubState": result.JobStatus.SubState,
  94. "CreatedTime": time.Unix(result.JobStatus.CreatedTime/1000, 0).Format("2006-01-02 15:04:05"),
  95. "CompletedTime": time.Unix(result.JobStatus.CompletedTime/1000, 0).Format("2006-01-02 15:04:05"),
  96. "JobDuration": job.TrainJobDuration,
  97. })
  98. }
  99. func GetCloudBrainInferenceJob(ctx *context.APIContext) {
  100. jobID := ctx.Params(":jobid")
  101. job, err := models.GetCloudbrainByJobID(jobID)
  102. if err != nil {
  103. ctx.NotFound(err)
  104. return
  105. }
  106. jobResult, err := cloudbrain.GetJob(job.JobID)
  107. if err != nil {
  108. ctx.NotFound(err)
  109. log.Error("GetJob failed:", err)
  110. return
  111. }
  112. result, err := models.ConvertToJobResultPayload(jobResult.Payload)
  113. if err != nil {
  114. ctx.NotFound(err)
  115. log.Error("ConvertToJobResultPayload failed:", err)
  116. return
  117. }
  118. oldStatus := job.Status
  119. job.Status = result.JobStatus.State
  120. if result.JobStatus.State != string(models.JobWaiting) && result.JobStatus.State != string(models.JobFailed) {
  121. taskRoles := result.TaskRoles
  122. taskRes, _ := models.ConvertToTaskPod(taskRoles[cloudbrain.SubTaskName].(map[string]interface{}))
  123. job.ContainerIp = taskRes.TaskStatuses[0].ContainerIP
  124. job.ContainerID = taskRes.TaskStatuses[0].ContainerID
  125. job.Status = taskRes.TaskStatuses[0].State
  126. }
  127. if result.JobStatus.State != string(models.JobWaiting) {
  128. models.ParseAndSetDurationFromCloudBrainOne(result, job)
  129. if oldStatus != job.Status {
  130. notification.NotifyChangeCloudbrainStatus(job, oldStatus)
  131. }
  132. err = models.UpdateJob(job)
  133. if err != nil {
  134. log.Error("UpdateJob failed:", err)
  135. }
  136. }
  137. ctx.JSON(http.StatusOK, map[string]interface{}{
  138. "JobID": jobID,
  139. "JobStatus": job.Status,
  140. "JobDuration": job.TrainJobDuration,
  141. })
  142. }
  143. func DelCloudBrainJob(ctx *context.APIContext) {
  144. jobID := ctx.Params(":jobid")
  145. errStr := cloudbrain.DelCloudBrainJob(jobID)
  146. if errStr != "" {
  147. ctx.JSON(http.StatusOK, map[string]interface{}{
  148. "Message": ctx.Tr(errStr),
  149. "VersionName": "1",
  150. "Code": 1,
  151. })
  152. } else {
  153. ctx.JSON(http.StatusOK, map[string]interface{}{
  154. "Message": "",
  155. "VersionName": "1",
  156. "Code": 0,
  157. })
  158. }
  159. }
  160. func InferencJobResultList(ctx *context.APIContext) {
  161. jobID := ctx.Params(":jobid")
  162. parentDir := ctx.Query("parentDir")
  163. dirArray := strings.Split(parentDir, "/")
  164. task, err := models.GetCloudbrainByJobID(jobID)
  165. if err != nil {
  166. log.Error("get cloud brain err:", err)
  167. ctx.ServerError("get cloud brain information failed:", err)
  168. }
  169. //get dirs
  170. dirs, err := routerRepo.GetResultDirs(task.JobName, parentDir)
  171. if err != nil {
  172. log.Error("GetModelDirs failed:%v", err.Error(), ctx.Data["msgID"])
  173. ctx.ServerError("GetModelDirs failed:", err)
  174. return
  175. }
  176. var fileInfos []storage.FileInfo
  177. err = json.Unmarshal([]byte(dirs), &fileInfos)
  178. if err != nil {
  179. log.Error("json.Unmarshal failed:%v", err.Error(), ctx.Data["msgID"])
  180. ctx.ServerError("json.Unmarshal failed:", err)
  181. return
  182. }
  183. for i, fileInfo := range fileInfos {
  184. temp, _ := time.Parse("2006-01-02 15:04:05", fileInfo.ModTime)
  185. fileInfos[i].ModTime = temp.Local().Format("2006-01-02 15:04:05")
  186. }
  187. sort.Slice(fileInfos, func(i, j int) bool {
  188. return fileInfos[i].ModTime > fileInfos[j].ModTime
  189. })
  190. ctx.JSON(http.StatusOK, map[string]interface{}{
  191. "JobID": jobID,
  192. "StatusOK": 0,
  193. "Path": dirArray,
  194. "Dirs": fileInfos,
  195. "task": task,
  196. "PageIsCloudBrain": true,
  197. })
  198. }
  199. func GetCloudbrainModelConvertTask(ctx *context.APIContext) {
  200. var (
  201. err error
  202. )
  203. ID := ctx.Params(":id")
  204. job, err := models.QueryModelConvertById(ID)
  205. if err != nil {
  206. ctx.NotFound(err)
  207. log.Error("GetCloudbrainByID failed:", err)
  208. return
  209. }
  210. if job.IsGpuTrainTask() {
  211. jobResult, err := cloudbrain.GetJob(job.CloudBrainTaskId)
  212. if err != nil {
  213. ctx.NotFound(err)
  214. log.Error("GetJob failed:", err)
  215. return
  216. }
  217. result, _ := models.ConvertToJobResultPayload(jobResult.Payload)
  218. if err != nil {
  219. ctx.NotFound(err)
  220. log.Error("ConvertToJobResultPayload failed:", err)
  221. return
  222. }
  223. job.Status = result.JobStatus.State
  224. taskRoles := result.TaskRoles
  225. taskRes, _ := models.ConvertToTaskPod(taskRoles[cloudbrain.SubTaskName].(map[string]interface{}))
  226. if result.JobStatus.State != string(models.JobWaiting) && result.JobStatus.State != string(models.JobFailed) {
  227. job.ContainerIp = taskRes.TaskStatuses[0].ContainerIP
  228. job.ContainerID = taskRes.TaskStatuses[0].ContainerID
  229. job.Status = taskRes.TaskStatuses[0].State
  230. }
  231. if result.JobStatus.State != string(models.JobWaiting) {
  232. models.ModelComputeAndSetDuration(job, result)
  233. err = models.UpdateModelConvert(job)
  234. if err != nil {
  235. log.Error("UpdateJob failed:", err)
  236. }
  237. }
  238. ctx.JSON(http.StatusOK, map[string]interface{}{
  239. "ID": ID,
  240. "JobName": result.Config.JobName,
  241. "JobStatus": result.JobStatus.State,
  242. "SubState": result.JobStatus.SubState,
  243. "CreatedTime": time.Unix(result.JobStatus.CreatedTime/1000, 0).Format("2006-01-02 15:04:05"),
  244. "CompletedTime": time.Unix(result.JobStatus.CompletedTime/1000, 0).Format("2006-01-02 15:04:05"),
  245. })
  246. } else {
  247. result, err := modelarts.GetTrainJob(job.CloudBrainTaskId, job.ModelArtsVersionId)
  248. if err != nil {
  249. log.Error("get modelart job failed:", err)
  250. ctx.NotFound(err)
  251. return
  252. }
  253. job.Status = modelarts.TransTrainJobStatus(result.IntStatus)
  254. job.RunTime = result.Duration / 1000
  255. job.TrainJobDuration = models.ConvertDurationToStr(job.RunTime)
  256. err = models.UpdateModelConvert(job)
  257. if err != nil {
  258. log.Error("UpdateJob failed:", err)
  259. }
  260. ctx.JSON(http.StatusOK, map[string]interface{}{
  261. "ID": ID,
  262. "JobStatus": job.Status,
  263. })
  264. }
  265. }
  266. func CloudbrainGetLogByJobId(jobId string, jobName string) map[string]interface{} {
  267. var hits []models.Hits
  268. result, err := cloudbrain.GetJobLog(jobId)
  269. if err != nil {
  270. log.Error("GetJobLog failed: %v", err)
  271. return nil
  272. }
  273. hits = result.Hits.Hits
  274. //if the size equal page_size, then take the scroll_id to get all log and delete the scroll_id(the num of scroll_id is limited)
  275. if len(result.Hits.Hits) >= cloudbrain.LogPageSize {
  276. for {
  277. resultNext, err := cloudbrain.GetJobAllLog(result.ScrollID)
  278. if err != nil {
  279. log.Error("GetJobAllLog failed: %v", err)
  280. } else {
  281. for _, hit := range resultNext.Hits.Hits {
  282. hits = append(hits, hit)
  283. }
  284. }
  285. if len(resultNext.Hits.Hits) < cloudbrain.LogPageSize {
  286. log.Info("get all log already")
  287. break
  288. }
  289. }
  290. }
  291. cloudbrain.DeleteJobLogToken(result.ScrollID)
  292. sort.Slice(hits, func(i, j int) bool {
  293. return hits[i].Sort[0] < hits[j].Sort[0]
  294. })
  295. var content string
  296. for _, log := range hits {
  297. content += log.Source.Message + "\n"
  298. }
  299. return map[string]interface{}{
  300. "JobName": jobName,
  301. "Content": content,
  302. }
  303. }
  304. func CloudbrainForModelConvertGetLog(ctx *context.Context) {
  305. ID := ctx.Params(":id")
  306. job, err := models.QueryModelConvertById(ID)
  307. if err != nil {
  308. log.Error("GetCloudbrainByJobName failed: %v", err, ctx.Data["MsgID"])
  309. ctx.ServerError(err.Error(), err)
  310. return
  311. }
  312. result := CloudbrainGetLogByJobId(job.CloudBrainTaskId, job.Name)
  313. if result == nil {
  314. log.Error("GetJobLog failed: %v", err, ctx.Data["MsgID"])
  315. ctx.ServerError(err.Error(), err)
  316. return
  317. }
  318. ctx.JSON(http.StatusOK, result)
  319. }
  320. func CloudbrainGetLog(ctx *context.Context) {
  321. ID := ctx.Params(":id")
  322. job, err := models.GetCloudbrainByID(ID)
  323. if err != nil {
  324. log.Error("GetCloudbrainByJobName failed: %v", err, ctx.Data["MsgID"])
  325. ctx.ServerError(err.Error(), err)
  326. return
  327. }
  328. result := CloudbrainGetLogByJobId(job.JobID, job.JobName)
  329. if result == nil {
  330. log.Error("GetJobLog failed: %v", err, ctx.Data["MsgID"])
  331. ctx.ServerError(err.Error(), err)
  332. return
  333. }
  334. ctx.JSON(http.StatusOK, result)
  335. }
  336. func CloudBrainModelConvertList(ctx *context.APIContext) {
  337. var (
  338. err error
  339. )
  340. ID := ctx.Params(":id")
  341. parentDir := ctx.Query("parentDir")
  342. dirArray := strings.Split(parentDir, "/")
  343. job, err := models.QueryModelConvertById(ID)
  344. if err != nil {
  345. log.Error("GetCloudbrainByJobID(%s) failed:%v", job.Name, err.Error())
  346. return
  347. }
  348. if job.IsGpuTrainTask() {
  349. //get dirs
  350. dirs, err := routerRepo.GetModelDirs(job.ID, parentDir)
  351. if err != nil {
  352. log.Error("GetModelDirs failed:%v", err.Error(), ctx.Data["msgID"])
  353. ctx.ServerError("GetModelDirs failed:", err)
  354. return
  355. }
  356. var fileInfos []storage.FileInfo
  357. err = json.Unmarshal([]byte(dirs), &fileInfos)
  358. if err != nil {
  359. log.Error("json.Unmarshal failed:%v", err.Error(), ctx.Data["msgID"])
  360. ctx.ServerError("json.Unmarshal failed:", err)
  361. return
  362. }
  363. for i, fileInfo := range fileInfos {
  364. temp, _ := time.Parse("2006-01-02 15:04:05", fileInfo.ModTime)
  365. fileInfos[i].ModTime = temp.Local().Format("2006-01-02 15:04:05")
  366. }
  367. sort.Slice(fileInfos, func(i, j int) bool {
  368. return fileInfos[i].ModTime > fileInfos[j].ModTime
  369. })
  370. ctx.JSON(http.StatusOK, map[string]interface{}{
  371. "JobID": ID,
  372. "VersionName": "",
  373. "StatusOK": 0,
  374. "Path": dirArray,
  375. "Dirs": fileInfos,
  376. "task": job,
  377. "PageIsCloudBrain": true,
  378. })
  379. } else {
  380. var jobID = ctx.Params(":id")
  381. var versionName = "V0001"
  382. parentDir := ctx.Query("parentDir")
  383. dirArray := strings.Split(parentDir, "/")
  384. models, err := storage.GetObsListObject(job.ID, "output/", parentDir, versionName)
  385. if err != nil {
  386. log.Info("get TrainJobListModel failed:", err)
  387. ctx.ServerError("GetObsListObject:", err)
  388. return
  389. }
  390. ctx.JSON(http.StatusOK, map[string]interface{}{
  391. "JobID": jobID,
  392. "VersionName": versionName,
  393. "StatusOK": 0,
  394. "Path": dirArray,
  395. "Dirs": models,
  396. "task": job,
  397. "PageIsCloudBrain": true,
  398. })
  399. }
  400. }
  401. func CloudBrainModelList(ctx *context.APIContext) {
  402. var (
  403. err error
  404. )
  405. var jobID = ctx.Params(":jobid")
  406. var versionName = ctx.Query("version_name")
  407. parentDir := ctx.Query("parentDir")
  408. dirArray := strings.Split(parentDir, "/")
  409. task, err := models.GetCloudbrainByJobIDAndVersionName(jobID, versionName)
  410. if err != nil {
  411. log.Error("GetCloudbrainByJobID(%s) failed:%v", task.JobName, err.Error())
  412. return
  413. }
  414. //get dirs
  415. dirs, err := routerRepo.GetModelDirs(task.JobName, parentDir)
  416. if err != nil {
  417. log.Error("GetModelDirs failed:%v", err.Error(), ctx.Data["msgID"])
  418. ctx.ServerError("GetModelDirs failed:", err)
  419. return
  420. }
  421. var fileInfos []storage.FileInfo
  422. err = json.Unmarshal([]byte(dirs), &fileInfos)
  423. if err != nil {
  424. log.Error("json.Unmarshal failed:%v", err.Error(), ctx.Data["msgID"])
  425. ctx.ServerError("json.Unmarshal failed:", err)
  426. return
  427. }
  428. for i, fileInfo := range fileInfos {
  429. temp, _ := time.Parse("2006-01-02 15:04:05", fileInfo.ModTime)
  430. fileInfos[i].ModTime = temp.Local().Format("2006-01-02 15:04:05")
  431. }
  432. sort.Slice(fileInfos, func(i, j int) bool {
  433. return fileInfos[i].ModTime > fileInfos[j].ModTime
  434. })
  435. ctx.JSON(http.StatusOK, map[string]interface{}{
  436. "JobID": jobID,
  437. "VersionName": versionName,
  438. "StatusOK": 0,
  439. "Path": dirArray,
  440. "Dirs": fileInfos,
  441. "task": task,
  442. "PageIsCloudBrain": true,
  443. })
  444. }
  445. type JobInfo struct {
  446. JobName string `json:"job_name"`
  447. AiCenterId int `json:"ai_center_id"`
  448. }
  449. func GetNewestJobs(ctx *context.APIContext) {
  450. idsC2Net, err := models.GetNewestJobsByAiCenter()
  451. if err != nil {
  452. log.Error("GetNewestJobsByAiCenter(%s) failed:%v", err.Error())
  453. return
  454. }
  455. idsCloudbrain, err := models.GetNewestJobsByType()
  456. if err != nil {
  457. log.Error("GetNewestJobsByType(%s) failed:%v", err.Error())
  458. return
  459. }
  460. ids := make([]int64, len(idsC2Net), cap(idsC2Net)*2)
  461. copy(ids, idsC2Net)
  462. for _, id := range idsCloudbrain {
  463. ids = append(ids, id)
  464. }
  465. jobs, err := models.GetCloudbrainByIDs(ids)
  466. if err != nil {
  467. log.Error("GetCloudbrainByIDs(%s) failed:%v", err.Error())
  468. return
  469. }
  470. jobInfos := make([]JobInfo, 0)
  471. for _, job := range jobs {
  472. var id int
  473. var content string
  474. switch job.Type {
  475. case models.TypeCloudBrainOne:
  476. id, content = getAICenterID("cloudbrain_one")
  477. if content == "" {
  478. log.Error("job(%s) has no match config info", job.DisplayJobName)
  479. continue
  480. }
  481. case models.TypeCloudBrainTwo:
  482. id, content = getAICenterID("cloudbrain_two")
  483. if content == "" {
  484. log.Error("job(%s) has no match config info", job.DisplayJobName)
  485. continue
  486. }
  487. case models.TypeC2Net:
  488. centerInfo := strings.Split(job.AiCenter, "+")
  489. if len(centerInfo) != 2 {
  490. log.Error("job(%s):ai_center(%s) is wrong", job.DisplayJobName, job.AiCenter)
  491. continue
  492. }
  493. id, content = getAICenterID(centerInfo[0])
  494. if content == "" {
  495. log.Error("job(%s) has no match config info", job.DisplayJobName)
  496. continue
  497. }
  498. default:
  499. log.Error("no match info")
  500. continue
  501. }
  502. jobInfos = append(jobInfos, JobInfo{
  503. JobName: job.DisplayJobName,
  504. AiCenterId: id,
  505. })
  506. }
  507. ctx.JSON(http.StatusOK, jobInfos)
  508. }
  509. func GetAICenterInfo(ctx *context.APIContext) {
  510. if setting.C2NetInfos == nil {
  511. log.Error("C2NET_SEQUENCE is incorrect")
  512. return
  513. }
  514. ctx.JSON(http.StatusOK, setting.C2NetInfos.C2NetSqInfo)
  515. }
  516. func getAICenterID(name string) (int, string) {
  517. for _, info := range setting.C2NetInfos.C2NetSqInfo {
  518. if name == info.Name {
  519. return info.ID, info.Content
  520. }
  521. }
  522. return 0, ""
  523. }