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