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
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
5 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107
  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. ctx.ServerError("Get minio get SignedUrl failed", err)
  559. return
  560. }
  561. log.Info("fileName=" + fileName)
  562. http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusTemporaryRedirect)
  563. } else {
  564. log.Info("fileName is null.")
  565. }
  566. }
  567. func CloudbrainGetLog(ctx *context.APIContext) {
  568. ID := ctx.Params(":id")
  569. job, err := models.GetCloudbrainByID(ID)
  570. if err != nil {
  571. log.Error("GetCloudbrainByJobName failed: %v", err, ctx.Data["MsgID"])
  572. ctx.ServerError(err.Error(), err)
  573. return
  574. }
  575. if job.JobType == string(models.JobTypeModelSafety) {
  576. if job.Type == models.TypeCloudBrainOne {
  577. result, err := cloudbrain.GetJob(job.JobID)
  578. existStr := ""
  579. if err == nil && result != nil {
  580. jobRes, _ := models.ConvertToJobResultPayload(result.Payload)
  581. taskRoles := jobRes.TaskRoles
  582. taskRes, _ := models.ConvertToTaskPod(taskRoles[cloudbrain.SubTaskName].(map[string]interface{}))
  583. existStr = taskRes.TaskStatuses[0].ExitDiagnostics
  584. }
  585. ctx.Data["existStr"] = existStr
  586. log.Info("existStr=" + existStr)
  587. } else {
  588. ModelSafetyGetLog(ctx)
  589. return
  590. }
  591. }
  592. lines := ctx.QueryInt("lines")
  593. baseLine := ctx.Query("base_line")
  594. order := ctx.Query("order")
  595. var result map[string]interface{}
  596. resultPath := "/model"
  597. if job.JobType == string(models.JobTypeInference) || job.JobType == string(models.JobTypeModelSafety) {
  598. resultPath = "/result"
  599. }
  600. if baseLine == "" && order == "desc" {
  601. result = getLastLogFromModelDir(job.JobName, lines, resultPath)
  602. } else {
  603. startLine := ctx.QueryInt("base_line")
  604. endLine := startLine + lines
  605. if order == "asc" {
  606. if baseLine == "" {
  607. startLine = 0
  608. endLine = lines
  609. } else {
  610. endLine = startLine
  611. startLine = endLine - lines
  612. if startLine < 0 {
  613. startLine = 0
  614. }
  615. }
  616. } else {
  617. if startLine > 0 {
  618. startLine += 1
  619. endLine += 1
  620. }
  621. }
  622. result = getLogFromModelDir(job.JobName, startLine, endLine, resultPath)
  623. if result == nil {
  624. log.Error("GetJobLog failed: %v", err, ctx.Data["MsgID"])
  625. ctx.ServerError(err.Error(), err)
  626. return
  627. }
  628. }
  629. content := ""
  630. if result["Content"] != nil {
  631. content = result["Content"].(string)
  632. }
  633. if ctx.Data["existStr"] != nil && result["Lines"].(int) < 50 {
  634. content = content + ctx.Data["existStr"].(string)
  635. }
  636. re := map[string]interface{}{
  637. "JobID": ID,
  638. "LogFileName": result["FileName"],
  639. "StartLine": result["StartLine"],
  640. "EndLine": result["EndLine"],
  641. "Content": content,
  642. "Lines": result["Lines"],
  643. "CanLogDownload": result["FileName"] != "",
  644. "StartTime": job.StartTime,
  645. }
  646. //result := CloudbrainGetLogByJobId(job.JobID, job.JobName)
  647. ctx.JSON(http.StatusOK, re)
  648. }
  649. func getAllLineFromFile(path string) int {
  650. count := 0
  651. reader, err := os.Open(path)
  652. defer reader.Close()
  653. if err == nil {
  654. r := bufio.NewReader(reader)
  655. for {
  656. _, error := r.ReadString('\n')
  657. if error == io.EOF {
  658. log.Info("read file completed.")
  659. break
  660. }
  661. if error != nil {
  662. log.Info("read file error." + error.Error())
  663. break
  664. }
  665. count = count + 1
  666. }
  667. } else {
  668. log.Info("error:" + err.Error())
  669. }
  670. return count
  671. }
  672. func getLastLogFromModelDir(jobName string, lines int, resultPath string) map[string]interface{} {
  673. prefix := setting.CBCodePathPrefix + jobName + resultPath
  674. files, err := storage.GetOneLevelAllObjectUnderDirMinio(setting.Attachment.Minio.Bucket, prefix, "")
  675. if err != nil {
  676. log.Error("query cloudbrain model failed: %v", err)
  677. return nil
  678. }
  679. re := ""
  680. fileName := ""
  681. count := 0
  682. allLines := 0
  683. startLine := 0
  684. for _, file := range files {
  685. if strings.HasSuffix(file.FileName, "log.txt") {
  686. fileName = file.FileName
  687. path := storage.GetMinioPath(jobName+resultPath+"/", file.FileName)
  688. allLines = getAllLineFromFile(path)
  689. startLine = allLines - lines
  690. if startLine < 0 {
  691. startLine = 0
  692. }
  693. count = allLines - startLine
  694. log.Info("path=" + path)
  695. reader, err := os.Open(path)
  696. defer reader.Close()
  697. if err == nil {
  698. r := bufio.NewReader(reader)
  699. for i := 0; i < allLines; i++ {
  700. line, error := r.ReadString('\n')
  701. if error == io.EOF {
  702. log.Info("read file completed.")
  703. break
  704. }
  705. if error != nil {
  706. log.Info("read file error." + error.Error())
  707. break
  708. }
  709. if error == nil {
  710. if i >= startLine {
  711. re = re + line
  712. }
  713. }
  714. }
  715. } else {
  716. log.Info("error:" + err.Error())
  717. }
  718. break
  719. }
  720. }
  721. return map[string]interface{}{
  722. "JobName": jobName,
  723. "Content": re,
  724. "FileName": fileName,
  725. "Lines": count,
  726. "EndLine": allLines,
  727. "StartLine": startLine,
  728. }
  729. }
  730. func getLogFromModelDir(jobName string, startLine int, endLine int, resultPath string) map[string]interface{} {
  731. prefix := setting.CBCodePathPrefix + jobName + resultPath
  732. files, err := storage.GetOneLevelAllObjectUnderDirMinio(setting.Attachment.Minio.Bucket, prefix, "")
  733. if err != nil {
  734. log.Error("query cloudbrain model failed: %v", err)
  735. return nil
  736. }
  737. if startLine == endLine {
  738. return map[string]interface{}{
  739. "JobName": jobName,
  740. "Content": "",
  741. "FileName": "",
  742. "Lines": 0,
  743. "EndLine": startLine,
  744. "StartLine": startLine,
  745. }
  746. }
  747. re := ""
  748. fileName := ""
  749. count := 0
  750. fileEndLine := endLine
  751. for _, file := range files {
  752. if strings.HasSuffix(file.FileName, "log.txt") {
  753. fileName = file.FileName
  754. path := storage.GetMinioPath(jobName+resultPath+"/", file.FileName)
  755. log.Info("path=" + path)
  756. reader, err := os.Open(path)
  757. defer reader.Close()
  758. if err == nil {
  759. r := bufio.NewReader(reader)
  760. for i := 0; i < endLine; i++ {
  761. line, error := r.ReadString('\n')
  762. if error == io.EOF {
  763. if i >= startLine {
  764. re = re + line
  765. count++
  766. }
  767. fileEndLine = i + 1
  768. log.Info("read file completed.")
  769. break
  770. }
  771. if error != nil {
  772. log.Info("read file error." + error.Error())
  773. break
  774. }
  775. if error == nil {
  776. if i >= startLine {
  777. fileEndLine = i + 1
  778. re = re + line
  779. count++
  780. }
  781. }
  782. }
  783. } else {
  784. log.Info("error:" + err.Error())
  785. }
  786. break
  787. }
  788. }
  789. return map[string]interface{}{
  790. "JobName": jobName,
  791. "Content": re,
  792. "FileName": fileName,
  793. "Lines": count,
  794. "EndLine": fileEndLine,
  795. "StartLine": startLine,
  796. }
  797. }
  798. func CloudBrainModelConvertList(ctx *context.APIContext) {
  799. var (
  800. err error
  801. )
  802. ID := ctx.Params(":id")
  803. parentDir := ctx.Query("parentDir")
  804. dirArray := strings.Split(parentDir, "/")
  805. job, err := models.QueryModelConvertById(ID)
  806. if err != nil {
  807. log.Error("GetCloudbrainByJobID(%s) failed:%v", job.Name, err.Error())
  808. return
  809. }
  810. if job.IsGpuTrainTask() {
  811. //get dirs
  812. dirs, err := routerRepo.GetModelDirs(job.ID, parentDir)
  813. if err != nil {
  814. log.Error("GetModelDirs failed:%v", err.Error(), ctx.Data["msgID"])
  815. ctx.ServerError("GetModelDirs failed:", err)
  816. return
  817. }
  818. var fileInfos []storage.FileInfo
  819. err = json.Unmarshal([]byte(dirs), &fileInfos)
  820. if err != nil {
  821. log.Error("json.Unmarshal failed:%v", err.Error(), ctx.Data["msgID"])
  822. ctx.ServerError("json.Unmarshal failed:", err)
  823. return
  824. }
  825. for i, fileInfo := range fileInfos {
  826. temp, _ := time.Parse("2006-01-02 15:04:05", fileInfo.ModTime)
  827. fileInfos[i].ModTime = temp.Local().Format("2006-01-02 15:04:05")
  828. }
  829. sort.Slice(fileInfos, func(i, j int) bool {
  830. return fileInfos[i].ModTime > fileInfos[j].ModTime
  831. })
  832. ctx.JSON(http.StatusOK, map[string]interface{}{
  833. "JobID": ID,
  834. "VersionName": "",
  835. "StatusOK": 0,
  836. "Path": dirArray,
  837. "Dirs": fileInfos,
  838. "task": job,
  839. "PageIsCloudBrain": true,
  840. })
  841. } else {
  842. var jobID = ctx.Params(":id")
  843. var versionName = "V0001"
  844. parentDir := ctx.Query("parentDir")
  845. dirArray := strings.Split(parentDir, "/")
  846. models, err := storage.GetObsListObject(job.ID, "output/", parentDir, versionName)
  847. if err != nil {
  848. log.Info("get TrainJobListModel failed:", err)
  849. ctx.ServerError("GetObsListObject:", err)
  850. return
  851. }
  852. ctx.JSON(http.StatusOK, map[string]interface{}{
  853. "JobID": jobID,
  854. "VersionName": versionName,
  855. "StatusOK": 0,
  856. "Path": dirArray,
  857. "Dirs": models,
  858. "task": job,
  859. "PageIsCloudBrain": true,
  860. })
  861. }
  862. }
  863. func CloudBrainModelList(ctx *context.APIContext) {
  864. var (
  865. err error
  866. )
  867. var jobID = ctx.Params(":jobid")
  868. var versionName = ctx.Query("version_name")
  869. parentDir := ctx.Query("parentDir")
  870. dirArray := strings.Split(parentDir, "/")
  871. task, err := models.GetCloudbrainByJobIDAndVersionName(jobID, versionName)
  872. if err != nil {
  873. log.Error("GetCloudbrainByJobID(%s) failed:%v", task.JobName, err.Error())
  874. return
  875. }
  876. //get dirs
  877. dirs, err := routerRepo.GetModelDirs(task.JobName, parentDir)
  878. if err != nil {
  879. log.Error("GetModelDirs failed:%v", err.Error(), ctx.Data["msgID"])
  880. ctx.ServerError("GetModelDirs failed:", err)
  881. return
  882. }
  883. var fileInfos []storage.FileInfo
  884. err = json.Unmarshal([]byte(dirs), &fileInfos)
  885. if err != nil {
  886. log.Error("json.Unmarshal failed:%v", err.Error(), ctx.Data["msgID"])
  887. ctx.ServerError("json.Unmarshal failed:", err)
  888. return
  889. }
  890. for i, fileInfo := range fileInfos {
  891. temp, _ := time.Parse("2006-01-02 15:04:05", fileInfo.ModTime)
  892. fileInfos[i].ModTime = temp.Local().Format("2006-01-02 15:04:05")
  893. }
  894. sort.Slice(fileInfos, func(i, j int) bool {
  895. return fileInfos[i].ModTime > fileInfos[j].ModTime
  896. })
  897. ctx.JSON(http.StatusOK, map[string]interface{}{
  898. "JobID": jobID,
  899. "VersionName": versionName,
  900. "StatusOK": 0,
  901. "Path": dirArray,
  902. "Dirs": fileInfos,
  903. "task": task,
  904. "PageIsCloudBrain": true,
  905. })
  906. }
  907. type JobInfo struct {
  908. JobName string `json:"job_name"`
  909. AiCenterId int `json:"ai_center_id"`
  910. }
  911. func GetNewestJobs(ctx *context.APIContext) {
  912. idsC2Net, err := models.GetNewestJobsByAiCenter()
  913. if err != nil {
  914. log.Error("GetNewestJobsByAiCenter(%s) failed:%v", err.Error())
  915. return
  916. }
  917. idsCloudbrain, err := models.GetNewestJobsByType()
  918. if err != nil {
  919. log.Error("GetNewestJobsByType(%s) failed:%v", err.Error())
  920. return
  921. }
  922. ids := make([]int64, len(idsC2Net), cap(idsC2Net)*2)
  923. copy(ids, idsC2Net)
  924. for _, id := range idsCloudbrain {
  925. ids = append(ids, id)
  926. }
  927. jobs, err := models.GetCloudbrainByIDs(ids)
  928. if err != nil {
  929. log.Error("GetCloudbrainByIDs(%s) failed:%v", err.Error())
  930. return
  931. }
  932. jobInfos := make([]JobInfo, 0)
  933. for _, job := range jobs {
  934. var id int
  935. var content string
  936. switch job.Type {
  937. case models.TypeCloudBrainOne:
  938. id, content = getAICenterID("cloudbrain_one")
  939. if content == "" {
  940. log.Error("job(%s) has no match config info", job.DisplayJobName)
  941. continue
  942. }
  943. case models.TypeCloudBrainTwo:
  944. id, content = getAICenterID("cloudbrain_two")
  945. if content == "" {
  946. log.Error("job(%s) has no match config info", job.DisplayJobName)
  947. continue
  948. }
  949. case models.TypeC2Net:
  950. centerInfo := strings.Split(job.AiCenter, "+")
  951. if len(centerInfo) != 2 {
  952. log.Error("job(%s):ai_center(%s) is wrong", job.DisplayJobName, job.AiCenter)
  953. continue
  954. }
  955. id, content = getAICenterID(centerInfo[0])
  956. if content == "" {
  957. log.Error("job(%s) has no match config info", job.DisplayJobName)
  958. continue
  959. }
  960. default:
  961. log.Error("no match info")
  962. continue
  963. }
  964. jobInfos = append(jobInfos, JobInfo{
  965. JobName: job.DisplayJobName,
  966. AiCenterId: id,
  967. })
  968. }
  969. ctx.JSON(http.StatusOK, jobInfos)
  970. }
  971. func GetAICenterInfo(ctx *context.APIContext) {
  972. if setting.C2NetInfos == nil {
  973. log.Error("C2NET_SEQUENCE is incorrect")
  974. return
  975. }
  976. ctx.JSON(http.StatusOK, setting.C2NetInfos.C2NetSqInfo)
  977. }
  978. func getAICenterID(name string) (int, string) {
  979. for _, info := range setting.C2NetInfos.C2NetSqInfo {
  980. if name == info.Name {
  981. return info.ID, info.Content
  982. }
  983. }
  984. return 0, ""
  985. }