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

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