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 31 kB

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