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
2 years ago
2 years ago
2 years ago
3 years ago
3 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
3 years ago
3 years ago
2 years ago
4 years ago
2 years ago
2 years ago
3 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
3 years ago
3 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
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. 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. logFileName := result["FileName"]
  577. //Logs can only be downloaded if the file exists
  578. //and the current user is an administrator or the creator of the task
  579. canLogDownload := logFileName != nil && logFileName != "" && job.IsUserHasRight(ctx.User)
  580. re := map[string]interface{}{
  581. "JobID": ID,
  582. "LogFileName": logFileName,
  583. "StartLine": result["StartLine"],
  584. "EndLine": result["EndLine"],
  585. "Content": content,
  586. "Lines": result["Lines"],
  587. "CanLogDownload": canLogDownload,
  588. "StartTime": job.StartTime,
  589. }
  590. //result := CloudbrainGetLogByJobId(job.JobID, job.JobName)
  591. ctx.JSON(http.StatusOK, re)
  592. }
  593. func getAllLineFromFile(path string) int {
  594. count := 0
  595. reader, err := os.Open(path)
  596. defer reader.Close()
  597. if err == nil {
  598. r := bufio.NewReader(reader)
  599. for {
  600. _, error := r.ReadString('\n')
  601. if error == io.EOF {
  602. log.Info("read file completed.")
  603. break
  604. }
  605. if error != nil {
  606. log.Info("read file error." + error.Error())
  607. break
  608. }
  609. count = count + 1
  610. }
  611. } else {
  612. log.Info("error:" + err.Error())
  613. }
  614. return count
  615. }
  616. func getLastLogFromModelDir(jobName string, lines int, resultPath string) map[string]interface{} {
  617. prefix := setting.CBCodePathPrefix + jobName + resultPath
  618. files, err := storage.GetOneLevelAllObjectUnderDirMinio(setting.Attachment.Minio.Bucket, prefix, "")
  619. if err != nil {
  620. log.Error("query cloudbrain model failed: %v", err)
  621. return nil
  622. }
  623. re := ""
  624. fileName := ""
  625. count := 0
  626. allLines := 0
  627. startLine := 0
  628. for _, file := range files {
  629. if strings.HasSuffix(file.FileName, "log.txt") {
  630. fileName = file.FileName
  631. path := storage.GetMinioPath(jobName+resultPath+"/", file.FileName)
  632. allLines = getAllLineFromFile(path)
  633. startLine = allLines - lines
  634. if startLine < 0 {
  635. startLine = 0
  636. }
  637. count = allLines - startLine
  638. log.Info("path=" + path)
  639. reader, err := os.Open(path)
  640. defer reader.Close()
  641. if err == nil {
  642. r := bufio.NewReader(reader)
  643. for i := 0; i < allLines; i++ {
  644. line, error := r.ReadString('\n')
  645. if error == io.EOF {
  646. log.Info("read file completed.")
  647. break
  648. }
  649. if error != nil {
  650. log.Info("read file error." + error.Error())
  651. break
  652. }
  653. if error == nil {
  654. if i >= startLine {
  655. re = re + line
  656. }
  657. }
  658. }
  659. } else {
  660. log.Info("error:" + err.Error())
  661. }
  662. break
  663. }
  664. }
  665. return map[string]interface{}{
  666. "JobName": jobName,
  667. "Content": re,
  668. "FileName": fileName,
  669. "Lines": count,
  670. "EndLine": allLines,
  671. "StartLine": startLine,
  672. }
  673. }
  674. func getLogFromModelDir(jobName string, startLine int, endLine int, resultPath string) map[string]interface{} {
  675. prefix := setting.CBCodePathPrefix + jobName + resultPath
  676. files, err := storage.GetOneLevelAllObjectUnderDirMinio(setting.Attachment.Minio.Bucket, prefix, "")
  677. if err != nil {
  678. log.Error("query cloudbrain model failed: %v", err)
  679. return nil
  680. }
  681. if startLine == endLine {
  682. return map[string]interface{}{
  683. "JobName": jobName,
  684. "Content": "",
  685. "FileName": "",
  686. "Lines": 0,
  687. "EndLine": startLine,
  688. "StartLine": startLine,
  689. }
  690. }
  691. re := ""
  692. fileName := ""
  693. count := 0
  694. fileEndLine := endLine
  695. for _, file := range files {
  696. if strings.HasSuffix(file.FileName, "log.txt") {
  697. fileName = file.FileName
  698. path := storage.GetMinioPath(jobName+resultPath+"/", file.FileName)
  699. log.Info("path=" + path)
  700. reader, err := os.Open(path)
  701. defer reader.Close()
  702. if err == nil {
  703. r := bufio.NewReader(reader)
  704. for i := 0; i < endLine; i++ {
  705. line, error := r.ReadString('\n')
  706. if error == io.EOF {
  707. if i >= startLine {
  708. re = re + line
  709. count++
  710. }
  711. fileEndLine = i + 1
  712. log.Info("read file completed.")
  713. break
  714. }
  715. if error != nil {
  716. log.Info("read file error." + error.Error())
  717. break
  718. }
  719. if error == nil {
  720. if i >= startLine {
  721. fileEndLine = i + 1
  722. re = re + line
  723. count++
  724. }
  725. }
  726. }
  727. } else {
  728. log.Info("error:" + err.Error())
  729. }
  730. break
  731. }
  732. }
  733. return map[string]interface{}{
  734. "JobName": jobName,
  735. "Content": re,
  736. "FileName": fileName,
  737. "Lines": count,
  738. "EndLine": fileEndLine,
  739. "StartLine": startLine,
  740. }
  741. }
  742. func CloudBrainModelConvertList(ctx *context.APIContext) {
  743. var (
  744. err error
  745. )
  746. ID := ctx.Params(":id")
  747. parentDir := ctx.Query("parentDir")
  748. dirArray := strings.Split(parentDir, "/")
  749. job, err := models.QueryModelConvertById(ID)
  750. if err != nil {
  751. log.Error("GetCloudbrainByJobID(%s) failed:%v", job.Name, err.Error())
  752. return
  753. }
  754. if job.IsGpuTrainTask() {
  755. //get dirs
  756. dirs, err := routerRepo.GetModelDirs(job.ID, parentDir)
  757. if err != nil {
  758. log.Error("GetModelDirs failed:%v", err.Error(), ctx.Data["msgID"])
  759. ctx.ServerError("GetModelDirs failed:", err)
  760. return
  761. }
  762. var fileInfos []storage.FileInfo
  763. err = json.Unmarshal([]byte(dirs), &fileInfos)
  764. if err != nil {
  765. log.Error("json.Unmarshal failed:%v", err.Error(), ctx.Data["msgID"])
  766. ctx.ServerError("json.Unmarshal failed:", err)
  767. return
  768. }
  769. for i, fileInfo := range fileInfos {
  770. temp, _ := time.Parse("2006-01-02 15:04:05", fileInfo.ModTime)
  771. fileInfos[i].ModTime = temp.Local().Format("2006-01-02 15:04:05")
  772. }
  773. sort.Slice(fileInfos, func(i, j int) bool {
  774. return fileInfos[i].ModTime > fileInfos[j].ModTime
  775. })
  776. ctx.JSON(http.StatusOK, map[string]interface{}{
  777. "JobID": ID,
  778. "VersionName": "",
  779. "StatusOK": 0,
  780. "Path": dirArray,
  781. "Dirs": fileInfos,
  782. "task": job,
  783. "PageIsCloudBrain": true,
  784. })
  785. } else {
  786. var jobID = ctx.Params(":id")
  787. var versionName = "V0001"
  788. parentDir := ctx.Query("parentDir")
  789. dirArray := strings.Split(parentDir, "/")
  790. models, err := storage.GetObsListObject(job.ID, "output/", parentDir, versionName)
  791. if err != nil {
  792. log.Info("get TrainJobListModel failed:", err)
  793. ctx.ServerError("GetObsListObject:", err)
  794. return
  795. }
  796. ctx.JSON(http.StatusOK, map[string]interface{}{
  797. "JobID": jobID,
  798. "VersionName": versionName,
  799. "StatusOK": 0,
  800. "Path": dirArray,
  801. "Dirs": models,
  802. "task": job,
  803. "PageIsCloudBrain": true,
  804. })
  805. }
  806. }
  807. func CloudBrainModelList(ctx *context.APIContext) {
  808. var (
  809. err error
  810. )
  811. var jobID = ctx.Params(":jobid")
  812. var versionName = ctx.Query("version_name")
  813. parentDir := ctx.Query("parentDir")
  814. dirArray := strings.Split(parentDir, "/")
  815. task, err := models.GetCloudbrainByJobIDAndVersionName(jobID, versionName)
  816. if err != nil {
  817. log.Error("GetCloudbrainByJobID(%s) failed:%v", task.JobName, err.Error())
  818. return
  819. }
  820. //get dirs
  821. dirs, err := routerRepo.GetModelDirs(task.JobName, parentDir)
  822. if err != nil {
  823. log.Error("GetModelDirs failed:%v", err.Error(), ctx.Data["msgID"])
  824. ctx.ServerError("GetModelDirs failed:", err)
  825. return
  826. }
  827. var fileInfos []storage.FileInfo
  828. err = json.Unmarshal([]byte(dirs), &fileInfos)
  829. if err != nil {
  830. log.Error("json.Unmarshal failed:%v", err.Error(), ctx.Data["msgID"])
  831. ctx.ServerError("json.Unmarshal failed:", err)
  832. return
  833. }
  834. for i, fileInfo := range fileInfos {
  835. temp, _ := time.Parse("2006-01-02 15:04:05", fileInfo.ModTime)
  836. fileInfos[i].ModTime = temp.Local().Format("2006-01-02 15:04:05")
  837. }
  838. sort.Slice(fileInfos, func(i, j int) bool {
  839. return fileInfos[i].ModTime > fileInfos[j].ModTime
  840. })
  841. ctx.JSON(http.StatusOK, map[string]interface{}{
  842. "JobID": jobID,
  843. "VersionName": versionName,
  844. "StatusOK": 0,
  845. "Path": dirArray,
  846. "Dirs": fileInfos,
  847. "task": task,
  848. "PageIsCloudBrain": true,
  849. })
  850. }
  851. type JobInfo struct {
  852. JobName string `json:"job_name"`
  853. AiCenterId int `json:"ai_center_id"`
  854. }
  855. func GetNewestJobs(ctx *context.APIContext) {
  856. idsC2Net, err := models.GetNewestJobsByAiCenter()
  857. if err != nil {
  858. log.Error("GetNewestJobsByAiCenter(%s) failed:%v", err.Error())
  859. return
  860. }
  861. idsCloudbrain, err := models.GetNewestJobsByType()
  862. if err != nil {
  863. log.Error("GetNewestJobsByType(%s) failed:%v", err.Error())
  864. return
  865. }
  866. ids := make([]int64, len(idsC2Net), cap(idsC2Net)*2)
  867. copy(ids, idsC2Net)
  868. for _, id := range idsCloudbrain {
  869. ids = append(ids, id)
  870. }
  871. jobs, err := models.GetCloudbrainByIDs(ids)
  872. if err != nil {
  873. log.Error("GetCloudbrainByIDs(%s) failed:%v", err.Error())
  874. return
  875. }
  876. jobInfos := make([]JobInfo, 0)
  877. for _, job := range jobs {
  878. var id int
  879. var content string
  880. switch job.Type {
  881. case models.TypeCloudBrainOne:
  882. id, content = getAICenterID("cloudbrain_one")
  883. if content == "" {
  884. log.Error("job(%s) has no match config info", job.DisplayJobName)
  885. continue
  886. }
  887. case models.TypeCloudBrainTwo:
  888. id, content = getAICenterID("cloudbrain_two")
  889. if content == "" {
  890. log.Error("job(%s) has no match config info", job.DisplayJobName)
  891. continue
  892. }
  893. case models.TypeC2Net:
  894. centerInfo := strings.Split(job.AiCenter, "+")
  895. if len(centerInfo) != 2 {
  896. log.Error("job(%s):ai_center(%s) is wrong", job.DisplayJobName, job.AiCenter)
  897. continue
  898. }
  899. id, content = getAICenterID(centerInfo[0])
  900. if content == "" {
  901. log.Error("job(%s) has no match config info", job.DisplayJobName)
  902. continue
  903. }
  904. default:
  905. log.Error("no match info")
  906. continue
  907. }
  908. jobInfos = append(jobInfos, JobInfo{
  909. JobName: job.DisplayJobName,
  910. AiCenterId: id,
  911. })
  912. }
  913. ctx.JSON(http.StatusOK, jobInfos)
  914. }
  915. func GetAICenterInfo(ctx *context.APIContext) {
  916. if setting.C2NetInfos == nil {
  917. log.Error("C2NET_SEQUENCE is incorrect")
  918. return
  919. }
  920. ctx.JSON(http.StatusOK, setting.C2NetInfos.C2NetSqInfo)
  921. }
  922. func getAICenterID(name string) (int, string) {
  923. for _, info := range setting.C2NetInfos.C2NetSqInfo {
  924. if name == info.Name {
  925. return info.ID, info.Content
  926. }
  927. }
  928. return 0, ""
  929. }