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

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