|
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171 |
- // Copyright 2016 The Gogs Authors. All rights reserved.
- // Copyright 2018 The Gitea Authors. All rights reserved.
- // Use of this source code is governed by a MIT-style
- // license that can be found in the LICENSE file.
-
- package repo
-
- import (
- "bufio"
- "encoding/json"
- "io"
- "io/ioutil"
- "net/http"
- "os"
- "path"
- "sort"
- "strconv"
- "strings"
- "time"
-
- cloudbrainService "code.gitea.io/gitea/services/cloudbrain"
-
- "code.gitea.io/gitea/modules/convert"
-
- "code.gitea.io/gitea/services/cloudbrain/cloudbrainTask"
-
- api "code.gitea.io/gitea/modules/structs"
-
- "code.gitea.io/gitea/modules/notification"
-
- "code.gitea.io/gitea/modules/setting"
-
- "code.gitea.io/gitea/models"
- "code.gitea.io/gitea/modules/cloudbrain"
- "code.gitea.io/gitea/modules/context"
- "code.gitea.io/gitea/modules/log"
- "code.gitea.io/gitea/modules/modelarts"
- "code.gitea.io/gitea/modules/storage"
- routerRepo "code.gitea.io/gitea/routers/repo"
- )
-
- func CloudBrainShow(ctx *context.APIContext) {
-
- task, err := models.GetCloudbrainByJobID(ctx.Params(":jobid"))
-
- if err != nil {
- log.Info("error:" + err.Error())
- ctx.JSON(http.StatusOK, models.BaseErrorMessageApi("repo.cloudbrain_query_fail"))
- return
- }
- cloudbrainTask.PrepareSpec4Show(task)
- task.ContainerIp = ""
- if cloudbrainTask.IsTaskNotStop(task) {
- cloudbrainTask.SyncTaskStatus(task)
- }
-
- if task.TrainJobDuration == "" {
- if task.Duration == 0 {
- var duration int64
- if task.Status == string(models.JobWaiting) {
- duration = 0
- } else if task.Status == string(models.JobRunning) {
- duration = time.Now().Unix() - int64(task.CreatedUnix)
- } else {
- duration = int64(task.UpdatedUnix) - int64(task.CreatedUnix)
- }
- task.Duration = duration
- }
- task.TrainJobDuration = models.ConvertDurationToStr(task.Duration)
- }
- //to unify image output
- if task.Type == models.TypeCloudBrainTwo || task.Type == models.TypeCDCenter {
- task.ImageID = strconv.FormatInt(task.EngineID, 10)
- task.Image = task.EngineName
-
- } else if task.Type == models.TypeC2Net {
- task.Image = task.EngineName
- }
- task.AiCenter = cloudbrainService.GetAiCenterShow(task.AiCenter, ctx.Context)
-
- ctx.JSON(http.StatusOK, models.BaseMessageWithDataApi{Code: 0, Message: "", Data: convert.ToCloudBrain(task)})
-
- }
- func CreateFileNoteBook(ctx *context.APIContext, option api.CreateFileNotebookJobOption) {
- cloudbrainTask.FileNotebookCreate(ctx.Context, option)
- }
-
- func GetFileNoteBookInfo(ctx *context.APIContext) {
- //image description spec description waiting count
-
- specs, err := models.GetResourceSpecificationByIds([]int64{setting.FileNoteBook.SpecIdCPU, setting.FileNoteBook.SpecIdGPU, setting.FileNoteBook.SpecIdNPU, setting.FileNoteBook.SpecIdNPUCD})
- if err != nil {
- log.Error("Fail to query specifications", err)
- ctx.JSON(http.StatusOK, models.BaseErrorMessageApi(ctx.Tr("repo.notebook_query_fail")))
- return
- }
-
- var specCPU, specGpu, specNPU, specNPUCD *api.SpecificationShow
- var specGpuQueueCode string
- for _, spec := range specs {
- if spec.ID == setting.FileNoteBook.SpecIdCPU {
- specCPU = convert.ToSpecification(spec)
- } else if spec.ID == setting.FileNoteBook.SpecIdGPU {
- specGpu = convert.ToSpecification(spec)
- specGpuQueueCode = spec.QueueCode
- } else if spec.ID == setting.FileNoteBook.SpecIdNPU {
- specNPU = convert.ToSpecification(spec)
- } else if spec.ID == setting.FileNoteBook.SpecIdNPUCD {
- specNPUCD = convert.ToSpecification(spec)
- }
- }
-
- waitCountNpu := cloudbrain.GetWaitingCloudbrainCount(models.TypeCloudBrainTwo, "")
-
- queuesMap, err := cloudbrain.GetQueuesDetail()
- if err != nil {
- log.Error("Fail to query gpu queues waiting count", err)
- ctx.JSON(http.StatusOK, models.BaseErrorMessageApi(ctx.Tr("repo.notebook_query_fail")))
- return
- }
- waitCountGPU := (*queuesMap)[specGpuQueueCode]
- if !setting.ModelartsCD.Enabled {
- ctx.JSON(http.StatusOK, map[string]interface{}{
- "code": 0,
- "projectName": setting.FileNoteBook.ProjectName,
- "specCpu": specCPU,
- "specGpu": specGpu,
- "specNpu": specNPU,
- "waitCountGpu": waitCountGPU,
- "waitCountNpu": waitCountNpu,
- "imageCpuDescription": setting.FileNoteBook.ImageCPUDescription,
- "imageGpuDescription": setting.FileNoteBook.ImageGPUDescription,
- "imageNpuDescription": setting.FileNoteBook.ImageNPUDescription,
- })
- } else {
- ctx.JSON(http.StatusOK, map[string]interface{}{
- "code": 0,
- "projectName": setting.FileNoteBook.ProjectName,
- "specCpu": specCPU,
- "specGpu": specGpu,
- "specNpu": specNPUCD,
- "waitCountGpu": waitCountGPU,
- "waitCountNpu": waitCountNpu,
- "imageCpuDescription": setting.FileNoteBook.ImageCPUDescription,
- "imageGpuDescription": setting.FileNoteBook.ImageGPUDescription,
- "imageNpuDescription": setting.FileNoteBook.ImageNPUCDDescription,
- })
-
- }
-
- }
-
- func CreateCloudBrain(ctx *context.APIContext, option api.CreateTrainJobOption) {
- if option.Type == cloudbrainTask.TaskTypeCloudbrainOne {
- cloudbrainTask.CloudbrainOneTrainJobCreate(ctx.Context, option)
- }
- if option.Type == cloudbrainTask.TaskTypeModelArts {
- cloudbrainTask.ModelArtsTrainJobNpuCreate(ctx.Context, option)
- }
-
- if option.Type == cloudbrainTask.TaskTypeGrampusGPU {
- cloudbrainTask.GrampusTrainJobGpuCreate(ctx.Context, option)
- }
- if option.Type == cloudbrainTask.TaskTypeGrampusNPU {
- cloudbrainTask.GrampusTrainJobNpuCreate(ctx.Context, option)
- }
-
- }
-
- func CreateCloudBrainInferenceTask(ctx *context.APIContext, option api.CreateTrainJobOption) {
-
- if option.Type == 0 {
- cloudbrainTask.CloudBrainInferenceJobCreate(ctx.Context, option)
- }
- if option.Type == 1 {
- cloudbrainTask.ModelArtsInferenceJobCreate(ctx.Context, option)
- }
-
- }
-
- // cloudbrain get job task by jobid
- func GetCloudbrainTask(ctx *context.APIContext) {
- // swagger:operation GET /repos/{owner}/{repo}/cloudbrain/{jobid} cloudbrain jobTask
- // ---
- // summary: Get a single task
- // produces:
- // - application/json
- // parameters:
- // - name: owner
- // in: path
- // description: owner of the repo
- // type: string
- // required: true
- // - name: repo
- // in: path
- // description: name of the repo
- // type: string
- // required: true
- // - name: jobid
- // in: path
- // description: id of cloudbrain jobid
- // type: string
- // required: true
- // responses:
- // "200":
-
- // "$ref": "#/responses/Label"
-
- var (
- err error
- )
-
- ID := ctx.Params(":id")
-
- job, err := cloudbrain.GetCloudBrainByIdOrJobId(ID)
-
- if err != nil {
- ctx.NotFound(err)
- return
- }
- if job.JobType == string(models.JobTypeModelSafety) {
- routerRepo.GetAiSafetyTaskByJob(job)
- job, err = models.GetCloudbrainByID(ID)
- ctx.JSON(http.StatusOK, map[string]interface{}{
- "ID": ID,
- "JobName": job.JobName,
- "JobStatus": job.Status,
- "SubState": "",
- "CreatedTime": job.CreatedUnix.Format("2006-01-02 15:04:05"),
- "CompletedTime": job.UpdatedUnix.Format("2006-01-02 15:04:05"),
- "JobDuration": job.TrainJobDuration,
- })
- } else {
- jobAfter, err := cloudbrainTask.SyncCloudBrainOneStatus(job)
-
- if err != nil {
- ctx.NotFound(err)
- log.Error("Sync cloud brain one status failed:", err)
- return
- }
-
- ctx.JSON(http.StatusOK, map[string]interface{}{
- "ID": ID,
- "JobName": jobAfter.JobName,
- "JobStatus": jobAfter.Status,
- "SubState": "",
- "CreatedTime": jobAfter.CreatedUnix.Format("2006-01-02 15:04:05"),
- "CompletedTime": jobAfter.UpdatedUnix.Format("2006-01-02 15:04:05"),
- "JobDuration": jobAfter.TrainJobDuration,
- })
- }
- }
-
- func GetCloudBrainInferenceJob(ctx *context.APIContext) {
-
- jobID := ctx.Params(":jobid")
- job, err := models.GetCloudbrainByJobID(jobID)
- if err != nil {
- ctx.NotFound(err)
- return
- }
- jobResult, err := cloudbrain.GetJob(job.JobID)
- if err != nil {
- ctx.NotFound(err)
- log.Error("GetJob failed:", err)
- return
- }
- result, err := models.ConvertToJobResultPayload(jobResult.Payload)
- if err != nil {
- ctx.NotFound(err)
- log.Error("ConvertToJobResultPayload failed:", err)
- return
- }
- oldStatus := job.Status
- job.Status = result.JobStatus.State
- if result.JobStatus.State != string(models.JobWaiting) && result.JobStatus.State != string(models.JobFailed) {
- taskRoles := result.TaskRoles
- taskRes, _ := models.ConvertToTaskPod(taskRoles[cloudbrain.SubTaskName].(map[string]interface{}))
-
- job.ContainerIp = taskRes.TaskStatuses[0].ContainerIP
- job.ContainerID = taskRes.TaskStatuses[0].ContainerID
- job.Status = taskRes.TaskStatuses[0].State
- }
-
- if result.JobStatus.State != string(models.JobWaiting) {
- models.ParseAndSetDurationFromCloudBrainOne(result, job)
- if oldStatus != job.Status {
- notification.NotifyChangeCloudbrainStatus(job, oldStatus)
- }
- err = models.UpdateJob(job)
- if err != nil {
- log.Error("UpdateJob failed:", err)
- }
- }
-
- ctx.JSON(http.StatusOK, map[string]interface{}{
- "JobID": jobID,
- "JobStatus": job.Status,
- "JobDuration": job.TrainJobDuration,
- "StartTime": job.StartTime,
- })
-
- }
-
- func DelCloudBrainJob(ctx *context.APIContext) {
- jobID := ctx.Params(":jobid")
-
- errStr := cloudbrain.DelCloudBrainJob(jobID)
-
- if errStr != "" {
- ctx.JSON(http.StatusOK, map[string]interface{}{
- "Message": ctx.Tr(errStr),
- "VersionName": "1",
- "Code": 1,
- })
- } else {
- ctx.JSON(http.StatusOK, map[string]interface{}{
- "Message": "",
- "VersionName": "1",
- "Code": 0,
- })
- }
-
- }
-
- func InferencJobResultList(ctx *context.APIContext) {
- jobID := ctx.Params(":jobid")
- parentDir := ctx.Query("parentDir")
- dirArray := strings.Split(parentDir, "/")
-
- task, err := models.GetCloudbrainByJobID(jobID)
- if err != nil {
- log.Error("get cloud brain err:", err)
- ctx.ServerError("get cloud brain information failed:", err)
-
- }
-
- //get dirs
- dirs, err := routerRepo.GetResultDirs(task.JobName, parentDir)
- if err != nil {
- log.Error("GetModelDirs failed:%v", err.Error(), ctx.Data["msgID"])
- ctx.ServerError("GetModelDirs failed:", err)
- return
- }
-
- var fileInfos []storage.FileInfo
- err = json.Unmarshal([]byte(dirs), &fileInfos)
- if err != nil {
- log.Error("json.Unmarshal failed:%v", err.Error(), ctx.Data["msgID"])
- ctx.ServerError("json.Unmarshal failed:", err)
- return
- }
-
- for i, fileInfo := range fileInfos {
- temp, _ := time.Parse("2006-01-02 15:04:05", fileInfo.ModTime)
- fileInfos[i].ModTime = temp.Local().Format("2006-01-02 15:04:05")
- }
-
- sort.Slice(fileInfos, func(i, j int) bool {
- return fileInfos[i].ModTime > fileInfos[j].ModTime
- })
-
- ctx.JSON(http.StatusOK, map[string]interface{}{
- "JobID": jobID,
- "StatusOK": 0,
- "Path": dirArray,
- "Dirs": fileInfos,
- "task": task,
- "PageIsCloudBrain": true,
- })
-
- }
-
- func GetCloudbrainModelConvertTask(ctx *context.APIContext) {
- var (
- err error
- )
- ID := ctx.Params(":id")
- job, err := models.QueryModelConvertById(ID)
- if err != nil {
- ctx.NotFound(err)
- log.Error("GetCloudbrainByID failed:", err)
- return
- }
- if job.IsGpuTrainTask() {
- jobResult, err := cloudbrain.GetJob(job.CloudBrainTaskId)
- if err != nil {
- ctx.NotFound(err)
- log.Error("GetJob failed:", err)
- return
- }
- result, _ := models.ConvertToJobResultPayload(jobResult.Payload)
- if err != nil {
- ctx.NotFound(err)
- log.Error("ConvertToJobResultPayload failed:", err)
- return
- }
-
- job.Status = result.JobStatus.State
- taskRoles := result.TaskRoles
- taskRes, _ := models.ConvertToTaskPod(taskRoles[cloudbrain.SubTaskName].(map[string]interface{}))
- if result.JobStatus.State != string(models.JobWaiting) && result.JobStatus.State != string(models.JobFailed) {
- job.ContainerIp = taskRes.TaskStatuses[0].ContainerIP
- job.ContainerID = taskRes.TaskStatuses[0].ContainerID
- job.Status = taskRes.TaskStatuses[0].State
- }
-
- if result.JobStatus.State != string(models.JobWaiting) {
- models.ModelComputeAndSetDuration(job, result)
- err = models.UpdateModelConvert(job)
- if err != nil {
- log.Error("UpdateJob failed:", err)
- }
- }
- ctx.JSON(http.StatusOK, map[string]interface{}{
- "ID": ID,
- "JobName": result.Config.JobName,
- "JobStatus": result.JobStatus.State,
- "SubState": result.JobStatus.SubState,
- "CreatedTime": time.Unix(result.JobStatus.CreatedTime/1000, 0).Format("2006-01-02 15:04:05"),
- "CompletedTime": time.Unix(result.JobStatus.CompletedTime/1000, 0).Format("2006-01-02 15:04:05"),
- })
- } else {
-
- result, err := modelarts.GetTrainJob(job.CloudBrainTaskId, job.ModelArtsVersionId)
- if err != nil {
- log.Error("get modelart job failed:", err)
- ctx.NotFound(err)
- return
- }
-
- job.Status = modelarts.TransTrainJobStatus(result.IntStatus)
- job.RunTime = result.Duration / 1000
- job.TrainJobDuration = models.ConvertDurationToStr(job.RunTime)
- err = models.UpdateModelConvert(job)
- if err != nil {
- log.Error("UpdateJob failed:", err)
- }
-
- ctx.JSON(http.StatusOK, map[string]interface{}{
- "ID": ID,
- "JobStatus": job.Status,
- })
-
- }
-
- }
-
- func CloudbrainGetLogByJobId(jobId string, jobName string) map[string]interface{} {
- var hits []models.Hits
- result, err := cloudbrain.GetJobLog(jobId)
- if err != nil {
- log.Error("GetJobLog failed: %v", err)
- return nil
- }
- hits = result.Hits.Hits
-
- //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)
- if len(result.Hits.Hits) >= cloudbrain.LogPageSize {
- for {
- resultNext, err := cloudbrain.GetJobAllLog(result.ScrollID)
- if err != nil {
- log.Error("GetJobAllLog failed: %v", err)
- } else {
- for _, hit := range resultNext.Hits.Hits {
- hits = append(hits, hit)
- }
- }
-
- if len(resultNext.Hits.Hits) < cloudbrain.LogPageSize {
- log.Info("get all log already")
- break
- }
- }
- }
-
- cloudbrain.DeleteJobLogToken(result.ScrollID)
-
- sort.Slice(hits, func(i, j int) bool {
- return hits[i].Sort[0] < hits[j].Sort[0]
- })
-
- var content string
- for _, log := range hits {
- content += log.Source.Message + "\n"
- }
-
- return map[string]interface{}{
- "JobName": jobName,
- "Content": content,
- }
-
- }
-
- func CloudbrainForModelConvertGetLog(ctx *context.Context) {
- ID := ctx.Params(":id")
- job, err := models.QueryModelConvertById(ID)
- if err != nil {
- log.Error("GetCloudbrainByJobName failed: %v", err, ctx.Data["MsgID"])
- ctx.ServerError(err.Error(), err)
- return
- }
-
- result := CloudbrainGetLogByJobId(job.CloudBrainTaskId, job.Name)
- if result == nil {
- log.Error("GetJobLog failed: %v", err, ctx.Data["MsgID"])
- ctx.ServerError(err.Error(), err)
- return
- }
- ctx.JSON(http.StatusOK, result)
- }
-
- func ModelSafetyGetLog(ctx *context.APIContext) {
- ID := ctx.Params(":id")
- job, err := models.GetCloudbrainByID(ID)
- if err != nil {
- log.Error("GetCloudbrainByJobName failed: %v", err, ctx.Data["MsgID"])
- ctx.ServerError(err.Error(), err)
- return
- }
- if job.JobType == string(models.JobTypeModelSafety) {
- if job.Type == models.TypeCloudBrainTwo {
- //TrainJobForModelConvertGetLog(ctx)
- var baseLine = ctx.Query("base_line")
- var order = ctx.Query("order")
- var lines = ctx.Query("lines")
- lines_int, err := strconv.Atoi(lines)
- if err != nil {
- log.Error("change lines(%d) string to int failed", lines_int)
- }
-
- if order != modelarts.OrderDesc && order != modelarts.OrderAsc {
- log.Error("order(%s) check failed", order)
- ctx.JSON(http.StatusBadRequest, map[string]interface{}{
- "err_msg": "order check failed",
- })
- return
- }
- resultLogFile, err := modelarts.GetTrainJobLogFileNames(job.JobID, strconv.FormatInt(job.VersionID, 10))
- if err != nil {
- log.Error("GetTrainJobLogFileNames(%s) failed:%v", job.JobID, err.Error())
- }
- result, err := modelarts.GetTrainJobLog(job.JobID, strconv.FormatInt(job.VersionID, 10), baseLine, resultLogFile.LogFileList[0], order, lines_int)
- if err != nil {
- log.Error("GetTrainJobLog(%s) failed:%v", job.JobID, err.Error())
- }
- if err != nil {
- log.Error("trainJobGetLog(%s) failed:%v", job.JobID, err.Error())
- // ctx.RenderWithErr(err.Error(), tplModelArtsTrainJobShow, nil)
- ctx.JSON(http.StatusOK, map[string]interface{}{
- "JobID": job.JobID,
- "LogFileName": "",
- "StartLine": "0",
- "EndLine": "0",
- "Content": "",
- "Lines": 0,
- "CanLogDownload": false,
- })
- return
- }
- prefix := strings.TrimPrefix(path.Join(setting.TrainJobModelPath, job.JobName, modelarts.LogPath, job.VersionName), "/") + "/job"
- _, err = storage.GetObsLogFileName(prefix)
- canLogDownload := isCanDownloadLog(ctx, job)
- if err != nil {
- canLogDownload = false
- }
- ctx.Data["log_file_name"] = resultLogFile.LogFileList[0]
- ctx.JSON(http.StatusOK, map[string]interface{}{
- "JobID": job.JobID,
- "LogFileName": resultLogFile.LogFileList[0],
- "StartLine": result.StartLine,
- "EndLine": result.EndLine,
- "Content": result.Content,
- "Lines": result.Lines,
- "CanLogDownload": canLogDownload,
- "StartTime": job.StartTime,
- })
- }
- }
- //result := ""
- //ctx.JSON(http.StatusOK, result)
- }
-
- func isCanDownloadLog(ctx *context.APIContext, job *models.Cloudbrain) bool {
- if !ctx.IsSigned {
- return false
- }
- return ctx.IsUserSiteAdmin() || ctx.User.ID == job.UserID
- }
-
- func ModelSafetyDownloadLogFile(ctx *context.Context) {
- ID := ctx.Params(":id")
- job, err := models.GetCloudbrainByID(ID)
- if err != nil {
- log.Error("GetCloudbrainByJobName failed: %v", err, ctx.Data["MsgID"])
- ctx.ServerError(err.Error(), err)
- return
- }
- if job.JobType == string(models.JobTypeModelSafety) {
- if job.Type == models.TypeCloudBrainOne {
- CloudbrainDownloadLogFile(ctx)
- } else if job.Type == models.TypeCloudBrainTwo {
- ctx.SetParams("jobid", job.JobID)
- ctx.Req.Form.Set("version_name", job.VersionName)
- routerRepo.TrainJobDownloadLogFile(ctx)
- }
- }
- }
-
- func CloudbrainDownloadLogFile(ctx *context.Context) {
- ID := ctx.Params(":id")
- job, err := models.GetCloudbrainByID(ID)
- if err != nil {
- log.Error("GetCloudbrainByJobName failed: %v", err, ctx.Data["MsgID"])
- ctx.ServerError(err.Error(), err)
- return
- }
- if job.JobType == string(models.JobTypeModelSafety) {
- if job.Type == models.TypeCloudBrainTwo {
- ModelSafetyDownloadLogFile(ctx)
- return
- }
- }
-
- existStr := ""
- if job.JobType == string(models.JobTypeTrain) || job.JobType == string(models.JobTypeInference) {
- if job.Type == models.TypeCloudBrainOne {
- result, err := cloudbrain.GetJob(job.JobID)
- if err == nil && result != nil {
- jobRes, _ := models.ConvertToJobResultPayload(result.Payload)
- taskRoles := jobRes.TaskRoles
- taskRes, _ := models.ConvertToTaskPod(taskRoles[cloudbrain.SubTaskName].(map[string]interface{}))
- existStr = taskRes.TaskStatuses[0].ExitDiagnostics
- }
- }
- }
-
- logDir := "/model"
- if job.JobType == string(models.JobTypeInference) || job.JobType == string(models.JobTypeModelSafety) {
- logDir = cloudbrain.ResultPath
- }
- files, err := storage.GetOneLevelAllObjectUnderDirMinio(setting.Attachment.Minio.Bucket, setting.CBCodePathPrefix+job.JobName+logDir, "")
- if err != nil {
- log.Error("query cloudbrain model failed: %v", err)
- return
- }
- fileName := ""
- for _, file := range files {
- if strings.HasSuffix(file.FileName, "log.txt") {
- fileName = file.FileName
- break
- }
- }
- if fileName != "" {
- prefix := "/" + setting.CBCodePathPrefix + job.JobName + "/model"
- filePath := setting.Attachment.Minio.RealPath + setting.Attachment.Minio.Bucket + prefix + "/" + fileName
- // Read the file contents into a byte slice
- data, err := ioutil.ReadFile(filePath)
- if err != nil {
- ctx.ServerError("ReadFile", err)
- return
- }
-
- // Set the appropriate response headers
- ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
- ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+fileName)
-
- // Write the file contents to the response
- if _, err := ctx.Resp.Write(data); err != nil {
- ctx.ServerError("Write", err)
- return
- }
- if _, err := ctx.Resp.Write([]byte(existStr)); err != nil {
- log.Error("Write failed: %v", err.Error(), ctx.Data["msgID"])
- return
- }
- } else {
- log.Info("fileName is null.")
- }
- }
-
- func CloudbrainGetLog(ctx *context.APIContext) {
- ID := ctx.Params(":id")
- job, err := models.GetCloudbrainByID(ID)
- if err != nil {
- log.Error("GetCloudbrainByJobName failed: %v", err, ctx.Data["MsgID"])
- ctx.ServerError(err.Error(), err)
- return
- }
- if job.JobType == string(models.JobTypeModelSafety) {
- if job.Type == models.TypeCloudBrainOne {
- result, err := cloudbrain.GetJob(job.JobID)
- existStr := ""
- if err == nil && result != nil {
- jobRes, _ := models.ConvertToJobResultPayload(result.Payload)
- taskRoles := jobRes.TaskRoles
- taskRes, _ := models.ConvertToTaskPod(taskRoles[cloudbrain.SubTaskName].(map[string]interface{}))
- existStr = taskRes.TaskStatuses[0].ExitDiagnostics
- }
- ctx.Data["existStr"] = existStr
- } else {
- ModelSafetyGetLog(ctx)
- return
- }
- }
-
- if job.JobType == string(models.JobTypeTrain) || job.JobType == string(models.JobTypeInference) {
- if job.Type == models.TypeCloudBrainOne {
- result, err := cloudbrain.GetJob(job.JobID)
- existStr := ""
- if err == nil && result != nil {
- jobRes, _ := models.ConvertToJobResultPayload(result.Payload)
- taskRoles := jobRes.TaskRoles
- taskRes, _ := models.ConvertToTaskPod(taskRoles[cloudbrain.SubTaskName].(map[string]interface{}))
- existStr = taskRes.TaskStatuses[0].ExitDiagnostics
- }
- ctx.Data["existStr"] = existStr
- }
- }
-
- lines := ctx.QueryInt("lines")
- baseLine := ctx.Query("base_line")
- order := ctx.Query("order")
- var result map[string]interface{}
- resultPath := "/model"
- if job.JobType == string(models.JobTypeInference) || job.JobType == string(models.JobTypeModelSafety) {
- resultPath = "/result"
- }
- if baseLine == "" && order == "desc" {
- result = getLastLogFromModelDir(job.JobName, lines, resultPath)
- } else {
- startLine := ctx.QueryInt("base_line")
- endLine := startLine + lines
- if order == "asc" {
- if baseLine == "" {
- startLine = 0
- endLine = lines
- } else {
- endLine = startLine
- startLine = endLine - lines
- if startLine < 0 {
- startLine = 0
- }
- }
- } else {
- if startLine > 0 {
- startLine += 1
- endLine += 1
- }
- }
-
- result = getLogFromModelDir(job.JobName, startLine, endLine, resultPath)
- if result == nil {
- log.Error("GetJobLog failed: %v", err, ctx.Data["MsgID"])
- //ctx.ServerError(err.Error(), err)
- return
- }
- }
- content := ""
- if result["Content"] != nil {
- content = result["Content"].(string)
- }
-
- if (job.JobType == string(models.JobTypeTrain) || job.JobType == string(models.JobTypeInference)) && job.Type == models.TypeCloudBrainOne && job.Status == string(models.JobFailed) {
- if ctx.Data["existStr"] != nil {
- if baseLine == "" && order == "desc" && result["Lines"].(int) == 0 {
- result["Lines"] = 1
- result["EndLine"] = 1
- }
- if ctx.Data["existStr"] != nil && result["Lines"].(int) < 60 || ctx.Data["existStr"] != nil && result["Lines"] == 0 {
- content = content + ctx.Data["existStr"].(string)
- }
- }
- } else {
- if ctx.Data["existStr"] != nil && result["Lines"].(int) < 50 {
- content = content + ctx.Data["existStr"].(string)
- }
- }
-
- logFileName := result["FileName"]
-
- //Logs can only be downloaded if the file exists
- //and the current user is an administrator or the creator of the task
- canLogDownload := logFileName != nil && logFileName != "" && job.IsUserHasRight(ctx.User)
-
- re := map[string]interface{}{
- "JobID": ID,
- "LogFileName": logFileName,
- "StartLine": result["StartLine"],
- "EndLine": result["EndLine"],
- "Content": content,
- "Lines": result["Lines"],
- "CanLogDownload": canLogDownload,
- "StartTime": job.StartTime,
- }
- //result := CloudbrainGetLogByJobId(job.JobID, job.JobName)
- ctx.JSON(http.StatusOK, re)
- }
-
- func getAllLineFromFile(path string) int {
- count := 0
- reader, err := os.Open(path)
- defer reader.Close()
- if err == nil {
- r := bufio.NewReader(reader)
- for {
- _, error := r.ReadString('\n')
- if error == io.EOF {
- log.Info("read file completed.")
- break
- }
- if error != nil {
- log.Info("read file error." + error.Error())
- break
- }
- count = count + 1
- }
- } else {
- log.Info("error:" + err.Error())
- }
- return count
- }
-
- func getLastLogFromModelDir(jobName string, lines int, resultPath string) map[string]interface{} {
- prefix := setting.CBCodePathPrefix + jobName + resultPath
- files, err := storage.GetOneLevelAllObjectUnderDirMinio(setting.Attachment.Minio.Bucket, prefix, "")
- if err != nil {
- log.Error("query cloudbrain model failed: %v", err)
- return nil
- }
-
- re := ""
- fileName := ""
- count := 0
- allLines := 0
- startLine := 0
- for _, file := range files {
- if strings.HasSuffix(file.FileName, "log.txt") {
- fileName = file.FileName
- path := storage.GetMinioPath(jobName+resultPath+"/", file.FileName)
- allLines = getAllLineFromFile(path)
- startLine = allLines - lines
- if startLine < 0 {
- startLine = 0
- }
- count = allLines - startLine
- log.Info("path=" + path)
- reader, err := os.Open(path)
- defer reader.Close()
- if err == nil {
- r := bufio.NewReader(reader)
- for i := 0; i < allLines; i++ {
- line, error := r.ReadString('\n')
- if error == io.EOF {
- log.Info("read file completed.")
- break
- }
- if error != nil {
- log.Info("read file error." + error.Error())
- break
- }
- if error == nil {
- if i >= startLine {
- re = re + line
- }
- }
- }
- } else {
- log.Info("error:" + err.Error())
- }
- break
- }
- }
-
- return map[string]interface{}{
- "JobName": jobName,
- "Content": re,
- "FileName": fileName,
- "Lines": count,
- "EndLine": allLines,
- "StartLine": startLine,
- }
- }
-
- func getLogFromModelDir(jobName string, startLine int, endLine int, resultPath string) map[string]interface{} {
- prefix := setting.CBCodePathPrefix + jobName + resultPath
- files, err := storage.GetOneLevelAllObjectUnderDirMinio(setting.Attachment.Minio.Bucket, prefix, "")
- if err != nil {
- log.Error("query cloudbrain model failed: %v", err)
- return nil
- }
- if startLine == endLine {
- return map[string]interface{}{
- "JobName": jobName,
- "Content": "",
- "FileName": "",
- "Lines": 0,
- "EndLine": startLine,
- "StartLine": startLine,
- }
- }
- re := ""
- fileName := ""
- count := 0
- fileEndLine := endLine
- for _, file := range files {
- if strings.HasSuffix(file.FileName, "log.txt") {
- fileName = file.FileName
- path := storage.GetMinioPath(jobName+resultPath+"/", file.FileName)
- log.Info("path=" + path)
- reader, err := os.Open(path)
- defer reader.Close()
- if err == nil {
- r := bufio.NewReader(reader)
- for i := 0; i < endLine; i++ {
- line, error := r.ReadString('\n')
- if error == io.EOF {
- if i >= startLine {
- re = re + line
- count++
- }
- fileEndLine = i + 1
- log.Info("read file completed.")
- break
- }
- if error != nil {
- log.Info("read file error." + error.Error())
- break
- }
- if error == nil {
- if i >= startLine {
- fileEndLine = i + 1
- re = re + line
- count++
- }
- }
- }
- } else {
- log.Info("error:" + err.Error())
- }
- break
- }
- }
-
- return map[string]interface{}{
- "JobName": jobName,
- "Content": re,
- "FileName": fileName,
- "Lines": count,
- "EndLine": fileEndLine,
- "StartLine": startLine,
- }
- }
-
- func CloudBrainModelConvertList(ctx *context.APIContext) {
- var (
- err error
- )
-
- ID := ctx.Params(":id")
- parentDir := ctx.Query("parentDir")
- dirArray := strings.Split(parentDir, "/")
-
- job, err := models.QueryModelConvertById(ID)
- if err != nil {
- log.Error("GetCloudbrainByJobID(%s) failed:%v", job.Name, err.Error())
- return
- }
- if job.IsGpuTrainTask() {
- //get dirs
- dirs, err := routerRepo.GetModelDirs(job.ID, parentDir)
- if err != nil {
- log.Error("GetModelDirs failed:%v", err.Error(), ctx.Data["msgID"])
- ctx.ServerError("GetModelDirs failed:", err)
- return
- }
-
- var fileInfos []storage.FileInfo
- err = json.Unmarshal([]byte(dirs), &fileInfos)
- if err != nil {
- log.Error("json.Unmarshal failed:%v", err.Error(), ctx.Data["msgID"])
- //ctx.ServerError("json.Unmarshal failed:", err)
- return
- }
-
- for i, fileInfo := range fileInfos {
- temp, _ := time.Parse("2006-01-02 15:04:05", fileInfo.ModTime)
- fileInfos[i].ModTime = temp.Local().Format("2006-01-02 15:04:05")
- }
-
- sort.Slice(fileInfos, func(i, j int) bool {
- return fileInfos[i].ModTime > fileInfos[j].ModTime
- })
-
- ctx.JSON(http.StatusOK, map[string]interface{}{
- "JobID": ID,
- "VersionName": "",
- "StatusOK": 0,
- "Path": dirArray,
- "Dirs": fileInfos,
- "task": job,
- "PageIsCloudBrain": true,
- })
- } else {
- var jobID = ctx.Params(":id")
- var versionName = "V0001"
- parentDir := ctx.Query("parentDir")
- dirArray := strings.Split(parentDir, "/")
-
- models, err := storage.GetObsListObject(job.ID, "output/", parentDir, versionName)
- if err != nil {
- log.Info("get TrainJobListModel failed:", err)
- //ctx.ServerError("GetObsListObject:", err)
- return
- }
-
- ctx.JSON(http.StatusOK, map[string]interface{}{
- "JobID": jobID,
- "VersionName": versionName,
- "StatusOK": 0,
- "Path": dirArray,
- "Dirs": models,
- "task": job,
- "PageIsCloudBrain": true,
- })
- }
-
- }
-
- func CloudBrainModelList(ctx *context.APIContext) {
- var (
- err error
- )
-
- var jobID = ctx.Params(":jobid")
- var versionName = ctx.Query("version_name")
- parentDir := ctx.Query("parentDir")
- dirArray := strings.Split(parentDir, "/")
-
- task, err := models.GetCloudbrainByJobIDAndVersionName(jobID, versionName)
- if err != nil {
- log.Error("GetCloudbrainByJobID(%s) failed:%v", task.JobName, err.Error())
- return
- }
-
- //get dirs
- dirs, err := routerRepo.GetModelDirs(task.JobName, parentDir)
- if err != nil {
- log.Error("GetModelDirs failed:%v", err.Error(), ctx.Data["msgID"])
- ctx.ServerError("GetModelDirs failed:", err)
- return
- }
-
- var fileInfos []storage.FileInfo
- err = json.Unmarshal([]byte(dirs), &fileInfos)
- if err != nil {
- log.Error("json.Unmarshal failed:%v", err.Error(), ctx.Data["msgID"])
- //ctx.ServerError("json.Unmarshal failed:", err)
- return
- }
-
- for i, fileInfo := range fileInfos {
- temp, _ := time.Parse("2006-01-02 15:04:05", fileInfo.ModTime)
- fileInfos[i].ModTime = temp.Local().Format("2006-01-02 15:04:05")
- }
-
- sort.Slice(fileInfos, func(i, j int) bool {
- return fileInfos[i].ModTime > fileInfos[j].ModTime
- })
-
- ctx.JSON(http.StatusOK, map[string]interface{}{
- "JobID": jobID,
- "VersionName": versionName,
- "StatusOK": 0,
- "Path": dirArray,
- "Dirs": fileInfos,
- "task": task,
- "PageIsCloudBrain": true,
- })
- }
-
- type JobInfo struct {
- JobName string `json:"job_name"`
- AiCenterId int `json:"ai_center_id"`
- }
-
- func GetNewestJobs(ctx *context.APIContext) {
- idsC2Net, err := models.GetNewestJobsByAiCenter()
- if err != nil {
- log.Error("GetNewestJobsByAiCenter(%s) failed:%v", err.Error())
- return
- }
-
- idsCloudbrain, err := models.GetNewestJobsByType()
- if err != nil {
- log.Error("GetNewestJobsByType(%s) failed:%v", err.Error())
- return
- }
-
- ids := make([]int64, len(idsC2Net), cap(idsC2Net)*2)
- copy(ids, idsC2Net)
- for _, id := range idsCloudbrain {
- ids = append(ids, id)
- }
-
- jobs, err := models.GetCloudbrainByIDs(ids)
- if err != nil {
- log.Error("GetCloudbrainByIDs(%s) failed:%v", err.Error())
- return
- }
-
- jobInfos := make([]JobInfo, 0)
- for _, job := range jobs {
- var id int
- var content string
- switch job.Type {
- case models.TypeCloudBrainOne:
- id, content = getAICenterID("cloudbrain_one")
- if content == "" {
- log.Error("job(%s) has no match config info", job.DisplayJobName)
- continue
- }
- case models.TypeCloudBrainTwo:
- id, content = getAICenterID("cloudbrain_two")
- if content == "" {
- log.Error("job(%s) has no match config info", job.DisplayJobName)
- continue
- }
- case models.TypeC2Net:
- centerInfo := strings.Split(job.AiCenter, "+")
- if len(centerInfo) != 2 {
- log.Error("job(%s):ai_center(%s) is wrong", job.DisplayJobName, job.AiCenter)
- continue
- }
- id, content = getAICenterID(centerInfo[0])
- if content == "" {
- log.Error("job(%s) has no match config info", job.DisplayJobName)
- continue
- }
- default:
- log.Error("no match info")
- continue
- }
-
- jobInfos = append(jobInfos, JobInfo{
- JobName: job.DisplayJobName,
- AiCenterId: id,
- })
- }
-
- ctx.JSON(http.StatusOK, jobInfos)
- }
-
- func GetAICenterInfo(ctx *context.APIContext) {
- if setting.C2NetInfos == nil {
- log.Error("C2NET_SEQUENCE is incorrect")
- return
- }
-
- ctx.JSON(http.StatusOK, setting.C2NetInfos.C2NetSqInfo)
- }
-
- func getAICenterID(name string) (int, string) {
- for _, info := range setting.C2NetInfos.C2NetSqInfo {
- if name == info.Name {
- return info.ID, info.Content
- }
- }
-
- return 0, ""
- }
|