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