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