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 28 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
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
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
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
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
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045
  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. "strconv"
  14. "strings"
  15. "time"
  16. "code.gitea.io/gitea/modules/convert"
  17. "code.gitea.io/gitea/services/cloudbrain/cloudbrainTask"
  18. api "code.gitea.io/gitea/modules/structs"
  19. "code.gitea.io/gitea/modules/notification"
  20. "code.gitea.io/gitea/modules/setting"
  21. "code.gitea.io/gitea/models"
  22. "code.gitea.io/gitea/modules/cloudbrain"
  23. "code.gitea.io/gitea/modules/context"
  24. "code.gitea.io/gitea/modules/log"
  25. "code.gitea.io/gitea/modules/modelarts"
  26. "code.gitea.io/gitea/modules/storage"
  27. routerRepo "code.gitea.io/gitea/routers/repo"
  28. )
  29. func CloudBrainShow(ctx *context.APIContext) {
  30. task, err := models.GetCloudbrainByJobID(ctx.Params(":jobid"))
  31. if err != nil {
  32. log.Info("error:" + err.Error())
  33. ctx.JSON(http.StatusOK, models.BaseErrorMessageApi("repo.cloudbrain_query_fail"))
  34. return
  35. }
  36. cloudbrainTask.PrepareSpec4Show(task)
  37. task.ContainerIp = ""
  38. if cloudbrainTask.IsTaskNotStop(task) {
  39. cloudbrainTask.SyncTaskStatus(task)
  40. }
  41. if task.TrainJobDuration == "" {
  42. if task.Duration == 0 {
  43. var duration int64
  44. if task.Status == string(models.JobWaiting) {
  45. duration = 0
  46. } else if task.Status == string(models.JobRunning) {
  47. duration = time.Now().Unix() - int64(task.CreatedUnix)
  48. } else {
  49. duration = int64(task.UpdatedUnix) - int64(task.CreatedUnix)
  50. }
  51. task.Duration = duration
  52. }
  53. task.TrainJobDuration = models.ConvertDurationToStr(task.Duration)
  54. }
  55. //to unify image output
  56. if task.Type == models.TypeCloudBrainTwo || task.Type == models.TypeCDCenter {
  57. task.ImageID = strconv.FormatInt(task.EngineID, 10)
  58. task.Image = task.EngineName
  59. } else if task.Type == models.TypeC2Net {
  60. task.Image = task.EngineName
  61. }
  62. ctx.JSON(http.StatusOK, models.BaseMessageWithDataApi{Code: 0, Message: "", Data: convert.ToCloudBrain(task)})
  63. }
  64. func CreateCloudBrain(ctx *context.APIContext, option api.CreateTrainJobOption) {
  65. if option.Type == 2 {
  66. cloudbrainTask.GrampusTrainJobGpuCreate(ctx.Context, option)
  67. }
  68. if option.Type == 3 {
  69. cloudbrainTask.GrampusTrainJobNpuCreate(ctx.Context, option)
  70. }
  71. }
  72. func CreateCloudBrainInferenceTask(ctx *context.APIContext, option api.CreateTrainJobOption) {
  73. if option.Type == 0 {
  74. cloudbrainTask.CloudBrainInferenceJobCreate(ctx.Context, option)
  75. }
  76. if option.Type == 1 {
  77. cloudbrainTask.ModelArtsInferenceJobCreate(ctx.Context, option)
  78. }
  79. }
  80. // cloudbrain get job task by jobid
  81. func GetCloudbrainTask(ctx *context.APIContext) {
  82. // swagger:operation GET /repos/{owner}/{repo}/cloudbrain/{jobid} cloudbrain jobTask
  83. // ---
  84. // summary: Get a single task
  85. // produces:
  86. // - application/json
  87. // parameters:
  88. // - name: owner
  89. // in: path
  90. // description: owner of the repo
  91. // type: string
  92. // required: true
  93. // - name: repo
  94. // in: path
  95. // description: name of the repo
  96. // type: string
  97. // required: true
  98. // - name: jobid
  99. // in: path
  100. // description: id of cloudbrain jobid
  101. // type: string
  102. // required: true
  103. // responses:
  104. // "200":
  105. // "$ref": "#/responses/Label"
  106. var (
  107. err error
  108. )
  109. ID := ctx.Params(":id")
  110. job, err := models.GetCloudbrainByID(ID)
  111. if err != nil {
  112. ctx.NotFound(err)
  113. log.Error("GetCloudbrainByID failed:", err)
  114. return
  115. }
  116. if job.JobType == string(models.JobTypeModelSafety) {
  117. routerRepo.GetAiSafetyTaskByJob(job)
  118. job, err = models.GetCloudbrainByID(ID)
  119. ctx.JSON(http.StatusOK, map[string]interface{}{
  120. "ID": ID,
  121. "JobName": job.JobName,
  122. "JobStatus": job.Status,
  123. "SubState": "",
  124. "CreatedTime": job.CreatedUnix.Format("2006-01-02 15:04:05"),
  125. "CompletedTime": job.UpdatedUnix.Format("2006-01-02 15:04:05"),
  126. "JobDuration": job.TrainJobDuration,
  127. })
  128. } else {
  129. jobResult, err := cloudbrain.GetJob(job.JobID)
  130. if err != nil {
  131. ctx.NotFound(err)
  132. log.Error("GetJob failed:", err)
  133. return
  134. }
  135. result, _ := models.ConvertToJobResultPayload(jobResult.Payload)
  136. if err != nil {
  137. ctx.NotFound(err)
  138. log.Error("ConvertToJobResultPayload failed:", err)
  139. return
  140. }
  141. oldStatus := job.Status
  142. job.Status = result.JobStatus.State
  143. taskRoles := result.TaskRoles
  144. taskRes, _ := models.ConvertToTaskPod(taskRoles[cloudbrain.SubTaskName].(map[string]interface{}))
  145. if result.JobStatus.State != string(models.JobWaiting) && result.JobStatus.State != string(models.JobFailed) {
  146. job.ContainerIp = taskRes.TaskStatuses[0].ContainerIP
  147. job.ContainerID = taskRes.TaskStatuses[0].ContainerID
  148. job.Status = taskRes.TaskStatuses[0].State
  149. }
  150. if result.JobStatus.State != string(models.JobWaiting) {
  151. models.ParseAndSetDurationFromCloudBrainOne(result, job)
  152. if oldStatus != job.Status {
  153. notification.NotifyChangeCloudbrainStatus(job, oldStatus)
  154. }
  155. err = models.UpdateJob(job)
  156. if err != nil {
  157. log.Error("UpdateJob failed:", err)
  158. }
  159. }
  160. ctx.JSON(http.StatusOK, map[string]interface{}{
  161. "ID": ID,
  162. "JobName": result.Config.JobName,
  163. "JobStatus": result.JobStatus.State,
  164. "SubState": result.JobStatus.SubState,
  165. "CreatedTime": time.Unix(result.JobStatus.CreatedTime/1000, 0).Format("2006-01-02 15:04:05"),
  166. "CompletedTime": time.Unix(result.JobStatus.CompletedTime/1000, 0).Format("2006-01-02 15:04:05"),
  167. "JobDuration": job.TrainJobDuration,
  168. })
  169. }
  170. }
  171. func GetCloudBrainInferenceJob(ctx *context.APIContext) {
  172. jobID := ctx.Params(":jobid")
  173. job, err := models.GetCloudbrainByJobID(jobID)
  174. if err != nil {
  175. ctx.NotFound(err)
  176. return
  177. }
  178. jobResult, err := cloudbrain.GetJob(job.JobID)
  179. if err != nil {
  180. ctx.NotFound(err)
  181. log.Error("GetJob failed:", err)
  182. return
  183. }
  184. result, err := models.ConvertToJobResultPayload(jobResult.Payload)
  185. if err != nil {
  186. ctx.NotFound(err)
  187. log.Error("ConvertToJobResultPayload failed:", err)
  188. return
  189. }
  190. oldStatus := job.Status
  191. job.Status = result.JobStatus.State
  192. if result.JobStatus.State != string(models.JobWaiting) && result.JobStatus.State != string(models.JobFailed) {
  193. taskRoles := result.TaskRoles
  194. taskRes, _ := models.ConvertToTaskPod(taskRoles[cloudbrain.SubTaskName].(map[string]interface{}))
  195. job.ContainerIp = taskRes.TaskStatuses[0].ContainerIP
  196. job.ContainerID = taskRes.TaskStatuses[0].ContainerID
  197. job.Status = taskRes.TaskStatuses[0].State
  198. }
  199. if result.JobStatus.State != string(models.JobWaiting) {
  200. models.ParseAndSetDurationFromCloudBrainOne(result, job)
  201. if oldStatus != job.Status {
  202. notification.NotifyChangeCloudbrainStatus(job, oldStatus)
  203. }
  204. err = models.UpdateJob(job)
  205. if err != nil {
  206. log.Error("UpdateJob failed:", err)
  207. }
  208. }
  209. ctx.JSON(http.StatusOK, map[string]interface{}{
  210. "JobID": jobID,
  211. "JobStatus": job.Status,
  212. "JobDuration": job.TrainJobDuration,
  213. })
  214. }
  215. func DelCloudBrainJob(ctx *context.APIContext) {
  216. jobID := ctx.Params(":jobid")
  217. errStr := cloudbrain.DelCloudBrainJob(jobID)
  218. if errStr != "" {
  219. ctx.JSON(http.StatusOK, map[string]interface{}{
  220. "Message": ctx.Tr(errStr),
  221. "VersionName": "1",
  222. "Code": 1,
  223. })
  224. } else {
  225. ctx.JSON(http.StatusOK, map[string]interface{}{
  226. "Message": "",
  227. "VersionName": "1",
  228. "Code": 0,
  229. })
  230. }
  231. }
  232. func InferencJobResultList(ctx *context.APIContext) {
  233. jobID := ctx.Params(":jobid")
  234. parentDir := ctx.Query("parentDir")
  235. dirArray := strings.Split(parentDir, "/")
  236. task, err := models.GetCloudbrainByJobID(jobID)
  237. if err != nil {
  238. log.Error("get cloud brain err:", err)
  239. ctx.ServerError("get cloud brain information failed:", err)
  240. }
  241. //get dirs
  242. dirs, err := routerRepo.GetResultDirs(task.JobName, parentDir)
  243. if err != nil {
  244. log.Error("GetModelDirs failed:%v", err.Error(), ctx.Data["msgID"])
  245. ctx.ServerError("GetModelDirs failed:", err)
  246. return
  247. }
  248. var fileInfos []storage.FileInfo
  249. err = json.Unmarshal([]byte(dirs), &fileInfos)
  250. if err != nil {
  251. log.Error("json.Unmarshal failed:%v", err.Error(), ctx.Data["msgID"])
  252. ctx.ServerError("json.Unmarshal failed:", err)
  253. return
  254. }
  255. for i, fileInfo := range fileInfos {
  256. temp, _ := time.Parse("2006-01-02 15:04:05", fileInfo.ModTime)
  257. fileInfos[i].ModTime = temp.Local().Format("2006-01-02 15:04:05")
  258. }
  259. sort.Slice(fileInfos, func(i, j int) bool {
  260. return fileInfos[i].ModTime > fileInfos[j].ModTime
  261. })
  262. ctx.JSON(http.StatusOK, map[string]interface{}{
  263. "JobID": jobID,
  264. "StatusOK": 0,
  265. "Path": dirArray,
  266. "Dirs": fileInfos,
  267. "task": task,
  268. "PageIsCloudBrain": true,
  269. })
  270. }
  271. func GetCloudbrainModelConvertTask(ctx *context.APIContext) {
  272. var (
  273. err error
  274. )
  275. ID := ctx.Params(":id")
  276. job, err := models.QueryModelConvertById(ID)
  277. if err != nil {
  278. ctx.NotFound(err)
  279. log.Error("GetCloudbrainByID failed:", err)
  280. return
  281. }
  282. if job.IsGpuTrainTask() {
  283. jobResult, err := cloudbrain.GetJob(job.CloudBrainTaskId)
  284. if err != nil {
  285. ctx.NotFound(err)
  286. log.Error("GetJob failed:", err)
  287. return
  288. }
  289. result, _ := models.ConvertToJobResultPayload(jobResult.Payload)
  290. if err != nil {
  291. ctx.NotFound(err)
  292. log.Error("ConvertToJobResultPayload failed:", err)
  293. return
  294. }
  295. job.Status = result.JobStatus.State
  296. taskRoles := result.TaskRoles
  297. taskRes, _ := models.ConvertToTaskPod(taskRoles[cloudbrain.SubTaskName].(map[string]interface{}))
  298. if result.JobStatus.State != string(models.JobWaiting) && result.JobStatus.State != string(models.JobFailed) {
  299. job.ContainerIp = taskRes.TaskStatuses[0].ContainerIP
  300. job.ContainerID = taskRes.TaskStatuses[0].ContainerID
  301. job.Status = taskRes.TaskStatuses[0].State
  302. }
  303. if result.JobStatus.State != string(models.JobWaiting) {
  304. models.ModelComputeAndSetDuration(job, result)
  305. err = models.UpdateModelConvert(job)
  306. if err != nil {
  307. log.Error("UpdateJob failed:", err)
  308. }
  309. }
  310. ctx.JSON(http.StatusOK, map[string]interface{}{
  311. "ID": ID,
  312. "JobName": result.Config.JobName,
  313. "JobStatus": result.JobStatus.State,
  314. "SubState": result.JobStatus.SubState,
  315. "CreatedTime": time.Unix(result.JobStatus.CreatedTime/1000, 0).Format("2006-01-02 15:04:05"),
  316. "CompletedTime": time.Unix(result.JobStatus.CompletedTime/1000, 0).Format("2006-01-02 15:04:05"),
  317. })
  318. } else {
  319. result, err := modelarts.GetTrainJob(job.CloudBrainTaskId, job.ModelArtsVersionId)
  320. if err != nil {
  321. log.Error("get modelart job failed:", err)
  322. ctx.NotFound(err)
  323. return
  324. }
  325. job.Status = modelarts.TransTrainJobStatus(result.IntStatus)
  326. job.RunTime = result.Duration / 1000
  327. job.TrainJobDuration = models.ConvertDurationToStr(job.RunTime)
  328. err = models.UpdateModelConvert(job)
  329. if err != nil {
  330. log.Error("UpdateJob failed:", err)
  331. }
  332. ctx.JSON(http.StatusOK, map[string]interface{}{
  333. "ID": ID,
  334. "JobStatus": job.Status,
  335. })
  336. }
  337. }
  338. func CloudbrainGetLogByJobId(jobId string, jobName string) map[string]interface{} {
  339. var hits []models.Hits
  340. result, err := cloudbrain.GetJobLog(jobId)
  341. if err != nil {
  342. log.Error("GetJobLog failed: %v", err)
  343. return nil
  344. }
  345. hits = result.Hits.Hits
  346. //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)
  347. if len(result.Hits.Hits) >= cloudbrain.LogPageSize {
  348. for {
  349. resultNext, err := cloudbrain.GetJobAllLog(result.ScrollID)
  350. if err != nil {
  351. log.Error("GetJobAllLog failed: %v", err)
  352. } else {
  353. for _, hit := range resultNext.Hits.Hits {
  354. hits = append(hits, hit)
  355. }
  356. }
  357. if len(resultNext.Hits.Hits) < cloudbrain.LogPageSize {
  358. log.Info("get all log already")
  359. break
  360. }
  361. }
  362. }
  363. cloudbrain.DeleteJobLogToken(result.ScrollID)
  364. sort.Slice(hits, func(i, j int) bool {
  365. return hits[i].Sort[0] < hits[j].Sort[0]
  366. })
  367. var content string
  368. for _, log := range hits {
  369. content += log.Source.Message + "\n"
  370. }
  371. return map[string]interface{}{
  372. "JobName": jobName,
  373. "Content": content,
  374. }
  375. }
  376. func CloudbrainForModelConvertGetLog(ctx *context.Context) {
  377. ID := ctx.Params(":id")
  378. job, err := models.QueryModelConvertById(ID)
  379. if err != nil {
  380. log.Error("GetCloudbrainByJobName failed: %v", err, ctx.Data["MsgID"])
  381. ctx.ServerError(err.Error(), err)
  382. return
  383. }
  384. result := CloudbrainGetLogByJobId(job.CloudBrainTaskId, job.Name)
  385. if result == nil {
  386. log.Error("GetJobLog failed: %v", err, ctx.Data["MsgID"])
  387. ctx.ServerError(err.Error(), err)
  388. return
  389. }
  390. ctx.JSON(http.StatusOK, result)
  391. }
  392. func ModelSafetyGetLog(ctx *context.APIContext) {
  393. ID := ctx.Params(":id")
  394. job, err := models.GetCloudbrainByID(ID)
  395. if err != nil {
  396. log.Error("GetCloudbrainByJobName failed: %v", err, ctx.Data["MsgID"])
  397. ctx.ServerError(err.Error(), err)
  398. return
  399. }
  400. if job.JobType == string(models.JobTypeModelSafety) {
  401. if job.Type == models.TypeCloudBrainTwo {
  402. //TrainJobForModelConvertGetLog(ctx)
  403. var baseLine = ctx.Query("base_line")
  404. var order = ctx.Query("order")
  405. var lines = ctx.Query("lines")
  406. lines_int, err := strconv.Atoi(lines)
  407. if err != nil {
  408. log.Error("change lines(%d) string to int failed", lines_int)
  409. }
  410. if order != modelarts.OrderDesc && order != modelarts.OrderAsc {
  411. log.Error("order(%s) check failed", order)
  412. ctx.JSON(http.StatusBadRequest, map[string]interface{}{
  413. "err_msg": "order check failed",
  414. })
  415. return
  416. }
  417. resultLogFile, err := modelarts.GetTrainJobLogFileNames(job.JobID, strconv.FormatInt(job.VersionID, 10))
  418. if err != nil {
  419. log.Error("GetTrainJobLogFileNames(%s) failed:%v", job.JobID, err.Error())
  420. }
  421. result, err := modelarts.GetTrainJobLog(job.JobID, strconv.FormatInt(job.VersionID, 10), baseLine, resultLogFile.LogFileList[0], order, lines_int)
  422. if err != nil {
  423. log.Error("GetTrainJobLog(%s) failed:%v", job.JobID, err.Error())
  424. }
  425. if err != nil {
  426. log.Error("trainJobGetLog(%s) failed:%v", job.JobID, err.Error())
  427. // ctx.RenderWithErr(err.Error(), tplModelArtsTrainJobShow, nil)
  428. ctx.JSON(http.StatusOK, map[string]interface{}{
  429. "JobID": job.JobID,
  430. "LogFileName": "",
  431. "StartLine": "0",
  432. "EndLine": "0",
  433. "Content": "",
  434. "Lines": 0,
  435. "CanLogDownload": false,
  436. })
  437. return
  438. }
  439. ctx.Data["log_file_name"] = resultLogFile.LogFileList[0]
  440. ctx.JSON(http.StatusOK, map[string]interface{}{
  441. "JobID": job.JobID,
  442. "LogFileName": resultLogFile.LogFileList[0],
  443. "StartLine": result.StartLine,
  444. "EndLine": result.EndLine,
  445. "Content": result.Content,
  446. "Lines": result.Lines,
  447. "CanLogDownload": isCanDownloadLog(ctx, job),
  448. })
  449. }
  450. }
  451. //result := ""
  452. //ctx.JSON(http.StatusOK, result)
  453. }
  454. func isCanDownloadLog(ctx *context.APIContext, job *models.Cloudbrain) bool {
  455. if !ctx.IsSigned {
  456. return false
  457. }
  458. return ctx.IsUserSiteAdmin() || ctx.User.ID == job.UserID
  459. }
  460. func ModelSafetyDownloadLogFile(ctx *context.Context) {
  461. ID := ctx.Params(":id")
  462. job, err := models.GetCloudbrainByID(ID)
  463. if err != nil {
  464. log.Error("GetCloudbrainByJobName failed: %v", err, ctx.Data["MsgID"])
  465. ctx.ServerError(err.Error(), err)
  466. return
  467. }
  468. if job.JobType == string(models.JobTypeModelSafety) {
  469. if job.Type == models.TypeCloudBrainOne {
  470. CloudbrainDownloadLogFile(ctx)
  471. } else if job.Type == models.TypeCloudBrainTwo {
  472. ctx.SetParams("jobid", job.JobID)
  473. ctx.Req.Form.Set("version_name", job.VersionName)
  474. routerRepo.TrainJobDownloadLogFile(ctx)
  475. }
  476. }
  477. }
  478. func CloudbrainDownloadLogFile(ctx *context.Context) {
  479. ID := ctx.Params(":id")
  480. job, err := models.GetCloudbrainByID(ID)
  481. if err != nil {
  482. log.Error("GetCloudbrainByJobName failed: %v", err, ctx.Data["MsgID"])
  483. ctx.ServerError(err.Error(), err)
  484. return
  485. }
  486. if job.JobType == string(models.JobTypeModelSafety) {
  487. if job.Type == models.TypeCloudBrainTwo {
  488. ModelSafetyDownloadLogFile(ctx)
  489. return
  490. }
  491. }
  492. logDir := "/model"
  493. if job.JobType == string(models.JobTypeInference) || job.JobType == string(models.JobTypeModelSafety) {
  494. logDir = cloudbrain.ResultPath
  495. }
  496. files, err := storage.GetOneLevelAllObjectUnderDirMinio(setting.Attachment.Minio.Bucket, setting.CBCodePathPrefix+job.JobName+logDir, "")
  497. if err != nil {
  498. log.Error("query cloudbrain model failed: %v", err)
  499. return
  500. }
  501. fileName := ""
  502. for _, file := range files {
  503. if strings.HasSuffix(file.FileName, "log.txt") {
  504. fileName = file.FileName
  505. break
  506. }
  507. }
  508. if fileName != "" {
  509. prefix := "/" + setting.CBCodePathPrefix + job.JobName + logDir
  510. url, err := storage.Attachments.PresignedGetURL(prefix+"/"+fileName, fileName)
  511. if err != nil {
  512. log.Error("Get minio get SignedUrl failed: %v", err.Error(), ctx.Data["msgID"])
  513. ctx.ServerError("Get minio get SignedUrl failed", err)
  514. return
  515. }
  516. log.Info("fileName=" + fileName)
  517. http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusTemporaryRedirect)
  518. } else {
  519. log.Info("fileName is null.")
  520. }
  521. }
  522. func CloudbrainGetLog(ctx *context.APIContext) {
  523. ID := ctx.Params(":id")
  524. job, err := models.GetCloudbrainByID(ID)
  525. if err != nil {
  526. log.Error("GetCloudbrainByJobName failed: %v", err, ctx.Data["MsgID"])
  527. ctx.ServerError(err.Error(), err)
  528. return
  529. }
  530. if job.JobType == string(models.JobTypeModelSafety) {
  531. if job.Type == models.TypeCloudBrainOne {
  532. result, err := cloudbrain.GetJob(job.JobID)
  533. existStr := ""
  534. if err == nil && result != nil {
  535. jobRes, _ := models.ConvertToJobResultPayload(result.Payload)
  536. taskRoles := jobRes.TaskRoles
  537. taskRes, _ := models.ConvertToTaskPod(taskRoles[cloudbrain.SubTaskName].(map[string]interface{}))
  538. existStr = taskRes.TaskStatuses[0].ExitDiagnostics
  539. }
  540. ctx.Data["existStr"] = existStr
  541. log.Info("existStr=" + existStr)
  542. } else {
  543. ModelSafetyGetLog(ctx)
  544. return
  545. }
  546. }
  547. lines := ctx.QueryInt("lines")
  548. baseLine := ctx.Query("base_line")
  549. order := ctx.Query("order")
  550. var result map[string]interface{}
  551. resultPath := "/model"
  552. if job.JobType == string(models.JobTypeInference) || job.JobType == string(models.JobTypeModelSafety) {
  553. resultPath = "/result"
  554. }
  555. if baseLine == "" && order == "desc" {
  556. result = getLastLogFromModelDir(job.JobName, lines, resultPath)
  557. } else {
  558. startLine := ctx.QueryInt("base_line")
  559. endLine := startLine + lines
  560. if order == "asc" {
  561. if baseLine == "" {
  562. startLine = 0
  563. endLine = lines
  564. } else {
  565. endLine = startLine
  566. startLine = endLine - lines
  567. if startLine < 0 {
  568. startLine = 0
  569. }
  570. }
  571. }
  572. result = getLogFromModelDir(job.JobName, startLine, endLine, resultPath)
  573. if result == nil {
  574. log.Error("GetJobLog failed: %v", err, ctx.Data["MsgID"])
  575. ctx.ServerError(err.Error(), err)
  576. return
  577. }
  578. }
  579. content := ""
  580. if result["Content"] != nil {
  581. content = result["Content"].(string)
  582. }
  583. if ctx.Data["existStr"] != nil && result["Lines"].(int) < 50 {
  584. content = content + ctx.Data["existStr"].(string)
  585. }
  586. re := map[string]interface{}{
  587. "JobID": ID,
  588. "LogFileName": result["FileName"],
  589. "StartLine": result["StartLine"],
  590. "EndLine": result["EndLine"],
  591. "Content": content,
  592. "Lines": result["Lines"],
  593. "CanLogDownload": result["FileName"] != "",
  594. }
  595. //result := CloudbrainGetLogByJobId(job.JobID, job.JobName)
  596. ctx.JSON(http.StatusOK, re)
  597. }
  598. func getAllLineFromFile(path string) int {
  599. count := 0
  600. reader, err := os.Open(path)
  601. defer reader.Close()
  602. if err == nil {
  603. r := bufio.NewReader(reader)
  604. for {
  605. _, error := r.ReadString('\n')
  606. if error == io.EOF {
  607. log.Info("read file completed.")
  608. break
  609. }
  610. if error != nil {
  611. log.Info("read file error." + error.Error())
  612. break
  613. }
  614. count = count + 1
  615. }
  616. } else {
  617. log.Info("error:" + err.Error())
  618. }
  619. return count
  620. }
  621. func getLastLogFromModelDir(jobName string, lines int, resultPath string) map[string]interface{} {
  622. prefix := setting.CBCodePathPrefix + jobName + resultPath
  623. files, err := storage.GetOneLevelAllObjectUnderDirMinio(setting.Attachment.Minio.Bucket, prefix, "")
  624. if err != nil {
  625. log.Error("query cloudbrain model failed: %v", err)
  626. return nil
  627. }
  628. re := ""
  629. fileName := ""
  630. count := 0
  631. allLines := 0
  632. startLine := 0
  633. for _, file := range files {
  634. if strings.HasSuffix(file.FileName, "log.txt") {
  635. fileName = file.FileName
  636. path := storage.GetMinioPath(jobName+resultPath+"/", file.FileName)
  637. allLines = getAllLineFromFile(path)
  638. startLine = allLines - lines
  639. if startLine < 0 {
  640. startLine = 0
  641. }
  642. count = allLines - startLine
  643. log.Info("path=" + path)
  644. reader, err := os.Open(path)
  645. defer reader.Close()
  646. if err == nil {
  647. r := bufio.NewReader(reader)
  648. for i := 0; i < allLines; i++ {
  649. line, error := r.ReadString('\n')
  650. if error == io.EOF {
  651. log.Info("read file completed.")
  652. break
  653. }
  654. if error != nil {
  655. log.Info("read file error." + error.Error())
  656. break
  657. }
  658. if error == nil {
  659. if i >= startLine {
  660. re = re + line
  661. }
  662. }
  663. }
  664. } else {
  665. log.Info("error:" + err.Error())
  666. }
  667. break
  668. }
  669. }
  670. return map[string]interface{}{
  671. "JobName": jobName,
  672. "Content": re,
  673. "FileName": fileName,
  674. "Lines": count,
  675. "EndLine": allLines,
  676. "StartLine": startLine,
  677. }
  678. }
  679. func getLogFromModelDir(jobName string, startLine int, endLine int, resultPath string) map[string]interface{} {
  680. prefix := setting.CBCodePathPrefix + jobName + resultPath
  681. files, err := storage.GetOneLevelAllObjectUnderDirMinio(setting.Attachment.Minio.Bucket, prefix, "")
  682. if err != nil {
  683. log.Error("query cloudbrain model failed: %v", err)
  684. return nil
  685. }
  686. if startLine == endLine {
  687. return map[string]interface{}{
  688. "JobName": jobName,
  689. "Content": "",
  690. "FileName": "",
  691. "Lines": 0,
  692. "EndLine": startLine,
  693. "StartLine": startLine,
  694. }
  695. }
  696. re := ""
  697. fileName := ""
  698. count := 0
  699. fileEndLine := endLine
  700. for _, file := range files {
  701. if strings.HasSuffix(file.FileName, "log.txt") {
  702. fileName = file.FileName
  703. path := storage.GetMinioPath(jobName+resultPath+"/", file.FileName)
  704. log.Info("path=" + path)
  705. reader, err := os.Open(path)
  706. defer reader.Close()
  707. if err == nil {
  708. r := bufio.NewReader(reader)
  709. for i := 0; i < endLine; i++ {
  710. line, error := r.ReadString('\n')
  711. if error == io.EOF {
  712. if i >= startLine {
  713. fileEndLine = i
  714. re = re + line
  715. count++
  716. }
  717. log.Info("read file completed.")
  718. break
  719. }
  720. if error != nil {
  721. log.Info("read file error." + error.Error())
  722. break
  723. }
  724. if error == nil {
  725. if i >= startLine {
  726. fileEndLine = i
  727. re = re + line
  728. count++
  729. }
  730. }
  731. }
  732. fileEndLine = fileEndLine + 1
  733. } else {
  734. log.Info("error:" + err.Error())
  735. }
  736. break
  737. }
  738. }
  739. return map[string]interface{}{
  740. "JobName": jobName,
  741. "Content": re,
  742. "FileName": fileName,
  743. "Lines": count,
  744. "EndLine": fileEndLine,
  745. "StartLine": startLine,
  746. }
  747. }
  748. func CloudBrainModelConvertList(ctx *context.APIContext) {
  749. var (
  750. err error
  751. )
  752. ID := ctx.Params(":id")
  753. parentDir := ctx.Query("parentDir")
  754. dirArray := strings.Split(parentDir, "/")
  755. job, err := models.QueryModelConvertById(ID)
  756. if err != nil {
  757. log.Error("GetCloudbrainByJobID(%s) failed:%v", job.Name, err.Error())
  758. return
  759. }
  760. if job.IsGpuTrainTask() {
  761. //get dirs
  762. dirs, err := routerRepo.GetModelDirs(job.ID, parentDir)
  763. if err != nil {
  764. log.Error("GetModelDirs failed:%v", err.Error(), ctx.Data["msgID"])
  765. ctx.ServerError("GetModelDirs failed:", err)
  766. return
  767. }
  768. var fileInfos []storage.FileInfo
  769. err = json.Unmarshal([]byte(dirs), &fileInfos)
  770. if err != nil {
  771. log.Error("json.Unmarshal failed:%v", err.Error(), ctx.Data["msgID"])
  772. ctx.ServerError("json.Unmarshal failed:", err)
  773. return
  774. }
  775. for i, fileInfo := range fileInfos {
  776. temp, _ := time.Parse("2006-01-02 15:04:05", fileInfo.ModTime)
  777. fileInfos[i].ModTime = temp.Local().Format("2006-01-02 15:04:05")
  778. }
  779. sort.Slice(fileInfos, func(i, j int) bool {
  780. return fileInfos[i].ModTime > fileInfos[j].ModTime
  781. })
  782. ctx.JSON(http.StatusOK, map[string]interface{}{
  783. "JobID": ID,
  784. "VersionName": "",
  785. "StatusOK": 0,
  786. "Path": dirArray,
  787. "Dirs": fileInfos,
  788. "task": job,
  789. "PageIsCloudBrain": true,
  790. })
  791. } else {
  792. var jobID = ctx.Params(":id")
  793. var versionName = "V0001"
  794. parentDir := ctx.Query("parentDir")
  795. dirArray := strings.Split(parentDir, "/")
  796. models, err := storage.GetObsListObject(job.ID, "output/", parentDir, versionName)
  797. if err != nil {
  798. log.Info("get TrainJobListModel failed:", err)
  799. ctx.ServerError("GetObsListObject:", err)
  800. return
  801. }
  802. ctx.JSON(http.StatusOK, map[string]interface{}{
  803. "JobID": jobID,
  804. "VersionName": versionName,
  805. "StatusOK": 0,
  806. "Path": dirArray,
  807. "Dirs": models,
  808. "task": job,
  809. "PageIsCloudBrain": true,
  810. })
  811. }
  812. }
  813. func CloudBrainModelList(ctx *context.APIContext) {
  814. var (
  815. err error
  816. )
  817. var jobID = ctx.Params(":jobid")
  818. var versionName = ctx.Query("version_name")
  819. parentDir := ctx.Query("parentDir")
  820. dirArray := strings.Split(parentDir, "/")
  821. task, err := models.GetCloudbrainByJobIDAndVersionName(jobID, versionName)
  822. if err != nil {
  823. log.Error("GetCloudbrainByJobID(%s) failed:%v", task.JobName, err.Error())
  824. return
  825. }
  826. //get dirs
  827. dirs, err := routerRepo.GetModelDirs(task.JobName, parentDir)
  828. if err != nil {
  829. log.Error("GetModelDirs failed:%v", err.Error(), ctx.Data["msgID"])
  830. ctx.ServerError("GetModelDirs failed:", err)
  831. return
  832. }
  833. var fileInfos []storage.FileInfo
  834. err = json.Unmarshal([]byte(dirs), &fileInfos)
  835. if err != nil {
  836. log.Error("json.Unmarshal failed:%v", err.Error(), ctx.Data["msgID"])
  837. ctx.ServerError("json.Unmarshal failed:", err)
  838. return
  839. }
  840. for i, fileInfo := range fileInfos {
  841. temp, _ := time.Parse("2006-01-02 15:04:05", fileInfo.ModTime)
  842. fileInfos[i].ModTime = temp.Local().Format("2006-01-02 15:04:05")
  843. }
  844. sort.Slice(fileInfos, func(i, j int) bool {
  845. return fileInfos[i].ModTime > fileInfos[j].ModTime
  846. })
  847. ctx.JSON(http.StatusOK, map[string]interface{}{
  848. "JobID": jobID,
  849. "VersionName": versionName,
  850. "StatusOK": 0,
  851. "Path": dirArray,
  852. "Dirs": fileInfos,
  853. "task": task,
  854. "PageIsCloudBrain": true,
  855. })
  856. }
  857. type JobInfo struct {
  858. JobName string `json:"job_name"`
  859. AiCenterId int `json:"ai_center_id"`
  860. }
  861. func GetNewestJobs(ctx *context.APIContext) {
  862. idsC2Net, err := models.GetNewestJobsByAiCenter()
  863. if err != nil {
  864. log.Error("GetNewestJobsByAiCenter(%s) failed:%v", err.Error())
  865. return
  866. }
  867. idsCloudbrain, err := models.GetNewestJobsByType()
  868. if err != nil {
  869. log.Error("GetNewestJobsByType(%s) failed:%v", err.Error())
  870. return
  871. }
  872. ids := make([]int64, len(idsC2Net), cap(idsC2Net)*2)
  873. copy(ids, idsC2Net)
  874. for _, id := range idsCloudbrain {
  875. ids = append(ids, id)
  876. }
  877. jobs, err := models.GetCloudbrainByIDs(ids)
  878. if err != nil {
  879. log.Error("GetCloudbrainByIDs(%s) failed:%v", err.Error())
  880. return
  881. }
  882. jobInfos := make([]JobInfo, 0)
  883. for _, job := range jobs {
  884. var id int
  885. var content string
  886. switch job.Type {
  887. case models.TypeCloudBrainOne:
  888. id, content = getAICenterID("cloudbrain_one")
  889. if content == "" {
  890. log.Error("job(%s) has no match config info", job.DisplayJobName)
  891. continue
  892. }
  893. case models.TypeCloudBrainTwo:
  894. id, content = getAICenterID("cloudbrain_two")
  895. if content == "" {
  896. log.Error("job(%s) has no match config info", job.DisplayJobName)
  897. continue
  898. }
  899. case models.TypeC2Net:
  900. centerInfo := strings.Split(job.AiCenter, "+")
  901. if len(centerInfo) != 2 {
  902. log.Error("job(%s):ai_center(%s) is wrong", job.DisplayJobName, job.AiCenter)
  903. continue
  904. }
  905. id, content = getAICenterID(centerInfo[0])
  906. if content == "" {
  907. log.Error("job(%s) has no match config info", job.DisplayJobName)
  908. continue
  909. }
  910. default:
  911. log.Error("no match info")
  912. continue
  913. }
  914. jobInfos = append(jobInfos, JobInfo{
  915. JobName: job.DisplayJobName,
  916. AiCenterId: id,
  917. })
  918. }
  919. ctx.JSON(http.StatusOK, jobInfos)
  920. }
  921. func GetAICenterInfo(ctx *context.APIContext) {
  922. if setting.C2NetInfos == nil {
  923. log.Error("C2NET_SEQUENCE is incorrect")
  924. return
  925. }
  926. ctx.JSON(http.StatusOK, setting.C2NetInfos.C2NetSqInfo)
  927. }
  928. func getAICenterID(name string) (int, string) {
  929. for _, info := range setting.C2NetInfos.C2NetSqInfo {
  930. if name == info.Name {
  931. return info.ID, info.Content
  932. }
  933. }
  934. return 0, ""
  935. }