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

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