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 22 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831
  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. "bufio"
  8. "encoding/json"
  9. "io"
  10. "net/http"
  11. "os"
  12. "sort"
  13. "strings"
  14. "time"
  15. "code.gitea.io/gitea/modules/notification"
  16. "code.gitea.io/gitea/modules/setting"
  17. "code.gitea.io/gitea/models"
  18. "code.gitea.io/gitea/modules/cloudbrain"
  19. "code.gitea.io/gitea/modules/context"
  20. "code.gitea.io/gitea/modules/log"
  21. "code.gitea.io/gitea/modules/modelarts"
  22. "code.gitea.io/gitea/modules/storage"
  23. routerRepo "code.gitea.io/gitea/routers/repo"
  24. )
  25. // cloudbrain get job task by jobid
  26. func GetCloudbrainTask(ctx *context.APIContext) {
  27. // swagger:operation GET /repos/{owner}/{repo}/cloudbrain/{jobid} cloudbrain jobTask
  28. // ---
  29. // summary: Get a single task
  30. // produces:
  31. // - application/json
  32. // parameters:
  33. // - name: owner
  34. // in: path
  35. // description: owner of the repo
  36. // type: string
  37. // required: true
  38. // - name: repo
  39. // in: path
  40. // description: name of the repo
  41. // type: string
  42. // required: true
  43. // - name: jobid
  44. // in: path
  45. // description: id of cloudbrain jobid
  46. // type: string
  47. // required: true
  48. // responses:
  49. // "200":
  50. // "$ref": "#/responses/Label"
  51. var (
  52. err error
  53. )
  54. ID := ctx.Params(":id")
  55. job, err := models.GetCloudbrainByID(ID)
  56. if err != nil {
  57. ctx.NotFound(err)
  58. log.Error("GetCloudbrainByID failed:", err)
  59. return
  60. }
  61. jobResult, err := cloudbrain.GetJob(job.JobID)
  62. if err != nil {
  63. ctx.NotFound(err)
  64. log.Error("GetJob failed:", err)
  65. return
  66. }
  67. result, _ := models.ConvertToJobResultPayload(jobResult.Payload)
  68. if err != nil {
  69. ctx.NotFound(err)
  70. log.Error("ConvertToJobResultPayload failed:", err)
  71. return
  72. }
  73. oldStatus := job.Status
  74. job.Status = result.JobStatus.State
  75. taskRoles := result.TaskRoles
  76. taskRes, _ := models.ConvertToTaskPod(taskRoles[cloudbrain.SubTaskName].(map[string]interface{}))
  77. if result.JobStatus.State != string(models.JobWaiting) && result.JobStatus.State != string(models.JobFailed) {
  78. job.ContainerIp = taskRes.TaskStatuses[0].ContainerIP
  79. job.ContainerID = taskRes.TaskStatuses[0].ContainerID
  80. job.Status = taskRes.TaskStatuses[0].State
  81. }
  82. if result.JobStatus.State != string(models.JobWaiting) {
  83. models.ParseAndSetDurationFromCloudBrainOne(result, job)
  84. if oldStatus != job.Status {
  85. notification.NotifyChangeCloudbrainStatus(job, oldStatus)
  86. }
  87. err = models.UpdateJob(job)
  88. if err != nil {
  89. log.Error("UpdateJob failed:", err)
  90. }
  91. }
  92. ctx.JSON(http.StatusOK, map[string]interface{}{
  93. "ID": ID,
  94. "JobName": result.Config.JobName,
  95. "JobStatus": result.JobStatus.State,
  96. "SubState": result.JobStatus.SubState,
  97. "CreatedTime": time.Unix(result.JobStatus.CreatedTime/1000, 0).Format("2006-01-02 15:04:05"),
  98. "CompletedTime": time.Unix(result.JobStatus.CompletedTime/1000, 0).Format("2006-01-02 15:04:05"),
  99. "JobDuration": job.TrainJobDuration,
  100. })
  101. }
  102. func GetCloudBrainInferenceJob(ctx *context.APIContext) {
  103. jobID := ctx.Params(":jobid")
  104. job, err := models.GetCloudbrainByJobID(jobID)
  105. if err != nil {
  106. ctx.NotFound(err)
  107. return
  108. }
  109. jobResult, err := cloudbrain.GetJob(job.JobID)
  110. if err != nil {
  111. ctx.NotFound(err)
  112. log.Error("GetJob failed:", err)
  113. return
  114. }
  115. result, err := models.ConvertToJobResultPayload(jobResult.Payload)
  116. if err != nil {
  117. ctx.NotFound(err)
  118. log.Error("ConvertToJobResultPayload failed:", err)
  119. return
  120. }
  121. oldStatus := job.Status
  122. job.Status = result.JobStatus.State
  123. if result.JobStatus.State != string(models.JobWaiting) && result.JobStatus.State != string(models.JobFailed) {
  124. taskRoles := result.TaskRoles
  125. taskRes, _ := models.ConvertToTaskPod(taskRoles[cloudbrain.SubTaskName].(map[string]interface{}))
  126. job.ContainerIp = taskRes.TaskStatuses[0].ContainerIP
  127. job.ContainerID = taskRes.TaskStatuses[0].ContainerID
  128. job.Status = taskRes.TaskStatuses[0].State
  129. }
  130. if result.JobStatus.State != string(models.JobWaiting) {
  131. models.ParseAndSetDurationFromCloudBrainOne(result, job)
  132. if oldStatus != job.Status {
  133. notification.NotifyChangeCloudbrainStatus(job, oldStatus)
  134. }
  135. err = models.UpdateJob(job)
  136. if err != nil {
  137. log.Error("UpdateJob failed:", err)
  138. }
  139. }
  140. ctx.JSON(http.StatusOK, map[string]interface{}{
  141. "JobID": jobID,
  142. "JobStatus": job.Status,
  143. "JobDuration": job.TrainJobDuration,
  144. })
  145. }
  146. func DelCloudBrainJob(ctx *context.APIContext) {
  147. jobID := ctx.Params(":jobid")
  148. errStr := cloudbrain.DelCloudBrainJob(jobID)
  149. if errStr != "" {
  150. ctx.JSON(http.StatusOK, map[string]interface{}{
  151. "Message": ctx.Tr(errStr),
  152. "VersionName": "1",
  153. "Code": 1,
  154. })
  155. } else {
  156. ctx.JSON(http.StatusOK, map[string]interface{}{
  157. "Message": "",
  158. "VersionName": "1",
  159. "Code": 0,
  160. })
  161. }
  162. }
  163. func InferencJobResultList(ctx *context.APIContext) {
  164. jobID := ctx.Params(":jobid")
  165. parentDir := ctx.Query("parentDir")
  166. dirArray := strings.Split(parentDir, "/")
  167. task, err := models.GetCloudbrainByJobID(jobID)
  168. if err != nil {
  169. log.Error("get cloud brain err:", err)
  170. ctx.ServerError("get cloud brain information failed:", err)
  171. }
  172. //get dirs
  173. dirs, err := routerRepo.GetResultDirs(task.JobName, parentDir)
  174. if err != nil {
  175. log.Error("GetModelDirs failed:%v", err.Error(), ctx.Data["msgID"])
  176. ctx.ServerError("GetModelDirs failed:", err)
  177. return
  178. }
  179. var fileInfos []storage.FileInfo
  180. err = json.Unmarshal([]byte(dirs), &fileInfos)
  181. if err != nil {
  182. log.Error("json.Unmarshal failed:%v", err.Error(), ctx.Data["msgID"])
  183. ctx.ServerError("json.Unmarshal failed:", err)
  184. return
  185. }
  186. for i, fileInfo := range fileInfos {
  187. temp, _ := time.Parse("2006-01-02 15:04:05", fileInfo.ModTime)
  188. fileInfos[i].ModTime = temp.Local().Format("2006-01-02 15:04:05")
  189. }
  190. sort.Slice(fileInfos, func(i, j int) bool {
  191. return fileInfos[i].ModTime > fileInfos[j].ModTime
  192. })
  193. ctx.JSON(http.StatusOK, map[string]interface{}{
  194. "JobID": jobID,
  195. "StatusOK": 0,
  196. "Path": dirArray,
  197. "Dirs": fileInfos,
  198. "task": task,
  199. "PageIsCloudBrain": true,
  200. })
  201. }
  202. func GetCloudbrainModelConvertTask(ctx *context.APIContext) {
  203. var (
  204. err error
  205. )
  206. ID := ctx.Params(":id")
  207. job, err := models.QueryModelConvertById(ID)
  208. if err != nil {
  209. ctx.NotFound(err)
  210. log.Error("GetCloudbrainByID failed:", err)
  211. return
  212. }
  213. if job.IsGpuTrainTask() {
  214. jobResult, err := cloudbrain.GetJob(job.CloudBrainTaskId)
  215. if err != nil {
  216. ctx.NotFound(err)
  217. log.Error("GetJob failed:", err)
  218. return
  219. }
  220. result, _ := models.ConvertToJobResultPayload(jobResult.Payload)
  221. if err != nil {
  222. ctx.NotFound(err)
  223. log.Error("ConvertToJobResultPayload failed:", err)
  224. return
  225. }
  226. job.Status = result.JobStatus.State
  227. taskRoles := result.TaskRoles
  228. taskRes, _ := models.ConvertToTaskPod(taskRoles[cloudbrain.SubTaskName].(map[string]interface{}))
  229. if result.JobStatus.State != string(models.JobWaiting) && result.JobStatus.State != string(models.JobFailed) {
  230. job.ContainerIp = taskRes.TaskStatuses[0].ContainerIP
  231. job.ContainerID = taskRes.TaskStatuses[0].ContainerID
  232. job.Status = taskRes.TaskStatuses[0].State
  233. }
  234. if result.JobStatus.State != string(models.JobWaiting) {
  235. models.ModelComputeAndSetDuration(job, result)
  236. err = models.UpdateModelConvert(job)
  237. if err != nil {
  238. log.Error("UpdateJob failed:", err)
  239. }
  240. }
  241. ctx.JSON(http.StatusOK, map[string]interface{}{
  242. "ID": ID,
  243. "JobName": result.Config.JobName,
  244. "JobStatus": result.JobStatus.State,
  245. "SubState": result.JobStatus.SubState,
  246. "CreatedTime": time.Unix(result.JobStatus.CreatedTime/1000, 0).Format("2006-01-02 15:04:05"),
  247. "CompletedTime": time.Unix(result.JobStatus.CompletedTime/1000, 0).Format("2006-01-02 15:04:05"),
  248. })
  249. } else {
  250. result, err := modelarts.GetTrainJob(job.CloudBrainTaskId, job.ModelArtsVersionId)
  251. if err != nil {
  252. log.Error("get modelart job failed:", err)
  253. ctx.NotFound(err)
  254. return
  255. }
  256. job.Status = modelarts.TransTrainJobStatus(result.IntStatus)
  257. job.RunTime = result.Duration / 1000
  258. job.TrainJobDuration = models.ConvertDurationToStr(job.RunTime)
  259. err = models.UpdateModelConvert(job)
  260. if err != nil {
  261. log.Error("UpdateJob failed:", err)
  262. }
  263. ctx.JSON(http.StatusOK, map[string]interface{}{
  264. "ID": ID,
  265. "JobStatus": job.Status,
  266. })
  267. }
  268. }
  269. func CloudbrainGetLogByJobId(jobId string, jobName string) map[string]interface{} {
  270. var hits []models.Hits
  271. result, err := cloudbrain.GetJobLog(jobId)
  272. if err != nil {
  273. log.Error("GetJobLog failed: %v", err)
  274. return nil
  275. }
  276. hits = result.Hits.Hits
  277. //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)
  278. if len(result.Hits.Hits) >= cloudbrain.LogPageSize {
  279. for {
  280. resultNext, err := cloudbrain.GetJobAllLog(result.ScrollID)
  281. if err != nil {
  282. log.Error("GetJobAllLog failed: %v", err)
  283. } else {
  284. for _, hit := range resultNext.Hits.Hits {
  285. hits = append(hits, hit)
  286. }
  287. }
  288. if len(resultNext.Hits.Hits) < cloudbrain.LogPageSize {
  289. log.Info("get all log already")
  290. break
  291. }
  292. }
  293. }
  294. cloudbrain.DeleteJobLogToken(result.ScrollID)
  295. sort.Slice(hits, func(i, j int) bool {
  296. return hits[i].Sort[0] < hits[j].Sort[0]
  297. })
  298. var content string
  299. for _, log := range hits {
  300. content += log.Source.Message + "\n"
  301. }
  302. return map[string]interface{}{
  303. "JobName": jobName,
  304. "Content": content,
  305. }
  306. }
  307. func CloudbrainForModelConvertGetLog(ctx *context.Context) {
  308. ID := ctx.Params(":id")
  309. job, err := models.QueryModelConvertById(ID)
  310. if err != nil {
  311. log.Error("GetCloudbrainByJobName failed: %v", err, ctx.Data["MsgID"])
  312. ctx.ServerError(err.Error(), err)
  313. return
  314. }
  315. result := CloudbrainGetLogByJobId(job.CloudBrainTaskId, job.Name)
  316. if result == nil {
  317. log.Error("GetJobLog failed: %v", err, ctx.Data["MsgID"])
  318. ctx.ServerError(err.Error(), err)
  319. return
  320. }
  321. ctx.JSON(http.StatusOK, result)
  322. }
  323. func CloudbrainDownloadLogFile(ctx *context.Context) {
  324. ID := ctx.Params(":id")
  325. job, err := models.GetCloudbrainByID(ID)
  326. if err != nil {
  327. log.Error("GetCloudbrainByJobName failed: %v", err, ctx.Data["MsgID"])
  328. ctx.ServerError(err.Error(), err)
  329. return
  330. }
  331. logDir := "/model"
  332. if job.JobType == string(models.JobTypeInference) {
  333. logDir = cloudbrain.ResultPath
  334. }
  335. prefix := "/" + setting.CBCodePathPrefix + job.JobName + logDir
  336. files, err := storage.GetOneLevelAllObjectUnderDirMinio(setting.Attachment.Minio.Bucket, prefix, "")
  337. if err != nil {
  338. log.Error("query cloudbrain model failed: %v", err)
  339. return
  340. }
  341. fileName := ""
  342. for _, file := range files {
  343. if strings.HasSuffix(file.FileName, "log.txt") {
  344. fileName = file.FileName
  345. break
  346. }
  347. }
  348. if fileName != "" {
  349. url, err := storage.Attachments.PresignedGetURL(prefix+"/"+fileName, fileName)
  350. if err != nil {
  351. log.Error("Get minio get SignedUrl failed: %v", err.Error(), ctx.Data["msgID"])
  352. ctx.ServerError("Get minio get SignedUrl failed", err)
  353. return
  354. }
  355. http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusTemporaryRedirect)
  356. }
  357. }
  358. func CloudbrainGetLog(ctx *context.Context) {
  359. ID := ctx.Params(":id")
  360. job, err := models.GetCloudbrainByID(ID)
  361. if err != nil {
  362. log.Error("GetCloudbrainByJobName failed: %v", err, ctx.Data["MsgID"])
  363. ctx.ServerError(err.Error(), err)
  364. return
  365. }
  366. lines := ctx.QueryInt("lines")
  367. baseLine := ctx.Query("base_line")
  368. order := ctx.Query("order")
  369. var result map[string]interface{}
  370. resultPath := "/model"
  371. if job.JobType == string(models.JobTypeInference) {
  372. resultPath = "/result"
  373. }
  374. if baseLine == "" && order == "desc" {
  375. result = getLastLogFromModelDir(job.JobName, lines, resultPath)
  376. } else {
  377. startLine := ctx.QueryInt("base_line")
  378. endLine := startLine + lines
  379. if order == "asc" {
  380. if baseLine == "" {
  381. startLine = 0
  382. endLine = lines
  383. } else {
  384. endLine = startLine
  385. startLine = endLine - lines
  386. if startLine < 0 {
  387. startLine = 0
  388. }
  389. }
  390. }
  391. result = getLogFromModelDir(job.JobName, startLine, endLine, resultPath)
  392. if result == nil {
  393. log.Error("GetJobLog failed: %v", err, ctx.Data["MsgID"])
  394. ctx.ServerError(err.Error(), err)
  395. return
  396. }
  397. }
  398. re := map[string]interface{}{
  399. "JobID": ID,
  400. "LogFileName": result["FileName"],
  401. "StartLine": result["StartLine"],
  402. "EndLine": result["EndLine"],
  403. "Content": result["Content"],
  404. "Lines": result["Lines"],
  405. "CanLogDownload": result["FileName"] != "",
  406. }
  407. //result := CloudbrainGetLogByJobId(job.JobID, job.JobName)
  408. ctx.JSON(http.StatusOK, re)
  409. }
  410. func getAllLineFromFile(path string) int {
  411. count := 0
  412. reader, err := os.Open(path)
  413. defer reader.Close()
  414. if err == nil {
  415. r := bufio.NewReader(reader)
  416. for {
  417. _, error := r.ReadString('\n')
  418. if error == io.EOF {
  419. log.Info("read file completed.")
  420. break
  421. }
  422. if error != nil {
  423. log.Info("read file error." + error.Error())
  424. break
  425. }
  426. count = count + 1
  427. }
  428. } else {
  429. log.Info("error:" + err.Error())
  430. }
  431. return count
  432. }
  433. func getLastLogFromModelDir(jobName string, lines int, resultPath string) map[string]interface{} {
  434. prefix := "/" + setting.CBCodePathPrefix + jobName + resultPath
  435. files, err := storage.GetOneLevelAllObjectUnderDirMinio(setting.Attachment.Minio.Bucket, prefix, "")
  436. if err != nil {
  437. log.Error("query cloudbrain model failed: %v", err)
  438. return nil
  439. }
  440. re := ""
  441. fileName := ""
  442. count := 0
  443. allLines := 0
  444. startLine := 0
  445. for _, file := range files {
  446. if strings.HasSuffix(file.FileName, "log.txt") {
  447. fileName = file.FileName
  448. path := storage.GetMinioPath(jobName+resultPath+"/", file.FileName)
  449. allLines = getAllLineFromFile(path)
  450. startLine = allLines - lines
  451. if startLine < 0 {
  452. startLine = 0
  453. }
  454. count = allLines - startLine
  455. log.Info("path=" + path)
  456. reader, err := os.Open(path)
  457. defer reader.Close()
  458. if err == nil {
  459. r := bufio.NewReader(reader)
  460. for i := 0; i < allLines; i++ {
  461. line, error := r.ReadString('\n')
  462. if error == io.EOF {
  463. log.Info("read file completed.")
  464. break
  465. }
  466. if error != nil {
  467. log.Info("read file error." + error.Error())
  468. break
  469. }
  470. if error == nil {
  471. if i >= startLine {
  472. re = re + line
  473. }
  474. }
  475. }
  476. } else {
  477. log.Info("error:" + err.Error())
  478. }
  479. break
  480. }
  481. }
  482. return map[string]interface{}{
  483. "JobName": jobName,
  484. "Content": re,
  485. "FileName": fileName,
  486. "Lines": count,
  487. "EndLine": allLines,
  488. "StartLine": startLine,
  489. }
  490. }
  491. func getLogFromModelDir(jobName string, startLine int, endLine int, resultPath string) map[string]interface{} {
  492. prefix := "/" + setting.CBCodePathPrefix + jobName + resultPath
  493. files, err := storage.GetOneLevelAllObjectUnderDirMinio(setting.Attachment.Minio.Bucket, prefix, "")
  494. if err != nil {
  495. log.Error("query cloudbrain model failed: %v", err)
  496. return nil
  497. }
  498. if startLine == endLine {
  499. return map[string]interface{}{
  500. "JobName": jobName,
  501. "Content": "",
  502. "FileName": "",
  503. "Lines": 0,
  504. "EndLine": startLine,
  505. "StartLine": startLine,
  506. }
  507. }
  508. re := ""
  509. fileName := ""
  510. count := 0
  511. fileEndLine := endLine
  512. for _, file := range files {
  513. if strings.HasSuffix(file.FileName, "log.txt") {
  514. fileName = file.FileName
  515. path := storage.GetMinioPath(jobName+resultPath+"/", file.FileName)
  516. log.Info("path=" + path)
  517. reader, err := os.Open(path)
  518. defer reader.Close()
  519. if err == nil {
  520. r := bufio.NewReader(reader)
  521. for i := 0; i < endLine; i++ {
  522. line, error := r.ReadString('\n')
  523. log.Info("line=" + line)
  524. if error == io.EOF {
  525. log.Info("read file completed.")
  526. break
  527. }
  528. if error != nil {
  529. log.Info("read file error." + error.Error())
  530. break
  531. }
  532. if error == nil {
  533. if i >= startLine {
  534. fileEndLine = i
  535. re = re + line
  536. count++
  537. }
  538. }
  539. }
  540. fileEndLine = fileEndLine + 1
  541. } else {
  542. log.Info("error:" + err.Error())
  543. }
  544. break
  545. }
  546. }
  547. return map[string]interface{}{
  548. "JobName": jobName,
  549. "Content": re,
  550. "FileName": fileName,
  551. "Lines": count,
  552. "EndLine": fileEndLine,
  553. "StartLine": startLine,
  554. }
  555. }
  556. func CloudBrainModelConvertList(ctx *context.APIContext) {
  557. var (
  558. err error
  559. )
  560. ID := ctx.Params(":id")
  561. parentDir := ctx.Query("parentDir")
  562. dirArray := strings.Split(parentDir, "/")
  563. job, err := models.QueryModelConvertById(ID)
  564. if err != nil {
  565. log.Error("GetCloudbrainByJobID(%s) failed:%v", job.Name, err.Error())
  566. return
  567. }
  568. if job.IsGpuTrainTask() {
  569. //get dirs
  570. dirs, err := routerRepo.GetModelDirs(job.ID, parentDir)
  571. if err != nil {
  572. log.Error("GetModelDirs failed:%v", err.Error(), ctx.Data["msgID"])
  573. ctx.ServerError("GetModelDirs failed:", err)
  574. return
  575. }
  576. var fileInfos []storage.FileInfo
  577. err = json.Unmarshal([]byte(dirs), &fileInfos)
  578. if err != nil {
  579. log.Error("json.Unmarshal failed:%v", err.Error(), ctx.Data["msgID"])
  580. ctx.ServerError("json.Unmarshal failed:", err)
  581. return
  582. }
  583. for i, fileInfo := range fileInfos {
  584. temp, _ := time.Parse("2006-01-02 15:04:05", fileInfo.ModTime)
  585. fileInfos[i].ModTime = temp.Local().Format("2006-01-02 15:04:05")
  586. }
  587. sort.Slice(fileInfos, func(i, j int) bool {
  588. return fileInfos[i].ModTime > fileInfos[j].ModTime
  589. })
  590. ctx.JSON(http.StatusOK, map[string]interface{}{
  591. "JobID": ID,
  592. "VersionName": "",
  593. "StatusOK": 0,
  594. "Path": dirArray,
  595. "Dirs": fileInfos,
  596. "task": job,
  597. "PageIsCloudBrain": true,
  598. })
  599. } else {
  600. var jobID = ctx.Params(":id")
  601. var versionName = "V0001"
  602. parentDir := ctx.Query("parentDir")
  603. dirArray := strings.Split(parentDir, "/")
  604. models, err := storage.GetObsListObject(job.ID, "output/", parentDir, versionName)
  605. if err != nil {
  606. log.Info("get TrainJobListModel failed:", err)
  607. ctx.ServerError("GetObsListObject:", err)
  608. return
  609. }
  610. ctx.JSON(http.StatusOK, map[string]interface{}{
  611. "JobID": jobID,
  612. "VersionName": versionName,
  613. "StatusOK": 0,
  614. "Path": dirArray,
  615. "Dirs": models,
  616. "task": job,
  617. "PageIsCloudBrain": true,
  618. })
  619. }
  620. }
  621. func CloudBrainModelList(ctx *context.APIContext) {
  622. var (
  623. err error
  624. )
  625. var jobID = ctx.Params(":jobid")
  626. var versionName = ctx.Query("version_name")
  627. parentDir := ctx.Query("parentDir")
  628. dirArray := strings.Split(parentDir, "/")
  629. task, err := models.GetCloudbrainByJobIDAndVersionName(jobID, versionName)
  630. if err != nil {
  631. log.Error("GetCloudbrainByJobID(%s) failed:%v", task.JobName, err.Error())
  632. return
  633. }
  634. //get dirs
  635. dirs, err := routerRepo.GetModelDirs(task.JobName, parentDir)
  636. if err != nil {
  637. log.Error("GetModelDirs failed:%v", err.Error(), ctx.Data["msgID"])
  638. ctx.ServerError("GetModelDirs failed:", err)
  639. return
  640. }
  641. var fileInfos []storage.FileInfo
  642. err = json.Unmarshal([]byte(dirs), &fileInfos)
  643. if err != nil {
  644. log.Error("json.Unmarshal failed:%v", err.Error(), ctx.Data["msgID"])
  645. ctx.ServerError("json.Unmarshal failed:", err)
  646. return
  647. }
  648. for i, fileInfo := range fileInfos {
  649. temp, _ := time.Parse("2006-01-02 15:04:05", fileInfo.ModTime)
  650. fileInfos[i].ModTime = temp.Local().Format("2006-01-02 15:04:05")
  651. }
  652. sort.Slice(fileInfos, func(i, j int) bool {
  653. return fileInfos[i].ModTime > fileInfos[j].ModTime
  654. })
  655. ctx.JSON(http.StatusOK, map[string]interface{}{
  656. "JobID": jobID,
  657. "VersionName": versionName,
  658. "StatusOK": 0,
  659. "Path": dirArray,
  660. "Dirs": fileInfos,
  661. "task": task,
  662. "PageIsCloudBrain": true,
  663. })
  664. }
  665. type JobInfo struct {
  666. JobName string `json:"job_name"`
  667. AiCenterId int `json:"ai_center_id"`
  668. }
  669. func GetNewestJobs(ctx *context.APIContext) {
  670. idsC2Net, err := models.GetNewestJobsByAiCenter()
  671. if err != nil {
  672. log.Error("GetNewestJobsByAiCenter(%s) failed:%v", err.Error())
  673. return
  674. }
  675. idsCloudbrain, err := models.GetNewestJobsByType()
  676. if err != nil {
  677. log.Error("GetNewestJobsByType(%s) failed:%v", err.Error())
  678. return
  679. }
  680. ids := make([]int64, len(idsC2Net), cap(idsC2Net)*2)
  681. copy(ids, idsC2Net)
  682. for _, id := range idsCloudbrain {
  683. ids = append(ids, id)
  684. }
  685. jobs, err := models.GetCloudbrainByIDs(ids)
  686. if err != nil {
  687. log.Error("GetCloudbrainByIDs(%s) failed:%v", err.Error())
  688. return
  689. }
  690. jobInfos := make([]JobInfo, 0)
  691. for _, job := range jobs {
  692. var id int
  693. var content string
  694. switch job.Type {
  695. case models.TypeCloudBrainOne:
  696. id, content = getAICenterID("cloudbrain_one")
  697. if content == "" {
  698. log.Error("job(%s) has no match config info", job.DisplayJobName)
  699. continue
  700. }
  701. case models.TypeCloudBrainTwo:
  702. id, content = getAICenterID("cloudbrain_two")
  703. if content == "" {
  704. log.Error("job(%s) has no match config info", job.DisplayJobName)
  705. continue
  706. }
  707. case models.TypeC2Net:
  708. centerInfo := strings.Split(job.AiCenter, "+")
  709. if len(centerInfo) != 2 {
  710. log.Error("job(%s):ai_center(%s) is wrong", job.DisplayJobName, job.AiCenter)
  711. continue
  712. }
  713. id, content = getAICenterID(centerInfo[0])
  714. if content == "" {
  715. log.Error("job(%s) has no match config info", job.DisplayJobName)
  716. continue
  717. }
  718. default:
  719. log.Error("no match info")
  720. continue
  721. }
  722. jobInfos = append(jobInfos, JobInfo{
  723. JobName: job.DisplayJobName,
  724. AiCenterId: id,
  725. })
  726. }
  727. ctx.JSON(http.StatusOK, jobInfos)
  728. }
  729. func GetAICenterInfo(ctx *context.APIContext) {
  730. if setting.C2NetInfos == nil {
  731. log.Error("C2NET_SEQUENCE is incorrect")
  732. return
  733. }
  734. ctx.JSON(http.StatusOK, setting.C2NetInfos.C2NetSqInfo)
  735. }
  736. func getAICenterID(name string) (int, string) {
  737. for _, info := range setting.C2NetInfos.C2NetSqInfo {
  738. if name == info.Name {
  739. return info.ID, info.Content
  740. }
  741. }
  742. return 0, ""
  743. }