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

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