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