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.

grampus.go 55 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
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
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
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
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
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
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
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648
  1. package repo
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "io/ioutil"
  7. "net/http"
  8. "os"
  9. "path"
  10. "strconv"
  11. "strings"
  12. "code.gitea.io/gitea/modules/urfs_client/urchin"
  13. "code.gitea.io/gitea/routers/response"
  14. "code.gitea.io/gitea/services/cloudbrain/cloudbrainTask"
  15. "code.gitea.io/gitea/modules/dataset"
  16. "code.gitea.io/gitea/services/cloudbrain/resource"
  17. "code.gitea.io/gitea/services/reward/point/account"
  18. "code.gitea.io/gitea/modules/auth"
  19. "code.gitea.io/gitea/modules/git"
  20. "code.gitea.io/gitea/modules/grampus"
  21. "code.gitea.io/gitea/modules/modelarts"
  22. "code.gitea.io/gitea/modules/notification"
  23. "code.gitea.io/gitea/modules/redis/redis_key"
  24. "code.gitea.io/gitea/modules/redis/redis_lock"
  25. "code.gitea.io/gitea/modules/timeutil"
  26. "code.gitea.io/gitea/modules/util"
  27. "github.com/unknwon/com"
  28. "code.gitea.io/gitea/models"
  29. "code.gitea.io/gitea/modules/base"
  30. "code.gitea.io/gitea/modules/cloudbrain"
  31. "code.gitea.io/gitea/modules/context"
  32. "code.gitea.io/gitea/modules/log"
  33. "code.gitea.io/gitea/modules/setting"
  34. cloudbrainService "code.gitea.io/gitea/services/cloudbrain"
  35. )
  36. const (
  37. tplGrampusTrainJobShow base.TplName = "repo/grampus/trainjob/show"
  38. tplGrampusNotebookShow base.TplName = "repo/grampus/notebook/show"
  39. //GPU
  40. tplGrampusNotebookGPUNew base.TplName = "repo/grampus/notebook/gpu/new"
  41. tplGrampusTrainJobGPUNew base.TplName = "repo/grampus/trainjob/gpu/new"
  42. //NPU
  43. tplGrampusNotebookNPUNew base.TplName = "repo/grampus/notebook/npu/new"
  44. tplGrampusTrainJobNPUNew base.TplName = "repo/grampus/trainjob/npu/new"
  45. )
  46. func GrampusNotebookNew(ctx *context.Context) {
  47. ctx.Data["IsCreate"] = true
  48. notebookType := ctx.QueryInt("type")
  49. processType := grampus.ProcessorTypeGPU
  50. if notebookType == 1 {
  51. processType = grampus.ProcessorTypeNPU
  52. }
  53. err := grampusNotebookNewDataPrepare(ctx, processType)
  54. if err != nil {
  55. ctx.ServerError("get new notebook-job info failed", err)
  56. return
  57. }
  58. if processType == grampus.ProcessorTypeGPU {
  59. ctx.HTML(http.StatusOK, tplGrampusNotebookGPUNew)
  60. } else {
  61. ctx.HTML(http.StatusOK, tplGrampusNotebookNPUNew)
  62. }
  63. }
  64. func GrampusTrainJobGPUNew(ctx *context.Context) {
  65. ctx.Data["IsCreate"] = true
  66. err := grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  67. if err != nil {
  68. ctx.ServerError("get new train-job info failed", err)
  69. return
  70. }
  71. ctx.HTML(http.StatusOK, tplGrampusTrainJobGPUNew)
  72. }
  73. func GrampusTrainJobNPUNew(ctx *context.Context) {
  74. ctx.Data["IsCreate"] = true
  75. err := grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  76. if err != nil {
  77. ctx.ServerError("get new train-job info failed", err)
  78. return
  79. }
  80. ctx.HTML(200, tplGrampusTrainJobNPUNew)
  81. }
  82. func GrampusNotebookCreate(ctx *context.Context, form auth.CreateGrampusNotebookForm) {
  83. ctx.Data["IsCreate"] = true
  84. displayJobName := form.DisplayJobName
  85. jobName := util.ConvertDisplayJobNameToJobName(displayJobName)
  86. uuid := form.Attachment
  87. description := form.Description
  88. repo := ctx.Repo.Repository
  89. branchName := form.BranchName
  90. image := strings.TrimSpace(form.Image)
  91. codeLocalPath := setting.JobPath + jobName + cloudbrain.CodeMountPath + "/"
  92. codeStoragePath := setting.CBCodePathPrefix + jobName + cloudbrain.CodeMountPath + "/"
  93. tpl := tplGrampusNotebookGPUNew
  94. processType := grampus.ProcessorTypeGPU
  95. computeSource := models.GPUResource
  96. computeSourceSimple := models.GPU
  97. if form.Type == 1 {
  98. tpl = tplGrampusNotebookNPUNew
  99. processType = grampus.ProcessorTypeNPU
  100. computeSource = models.NPUResource
  101. computeSourceSimple = models.NPU
  102. codeStoragePath = grampus.JobPath + jobName + modelarts.CodePath
  103. }
  104. lock := redis_lock.NewDistributeLock(redis_key.CloudbrainBindingJobNameKey(fmt.Sprint(repo.ID), string(models.JobTypeDebug), displayJobName))
  105. defer lock.UnLock()
  106. isOk, err := lock.Lock(models.CloudbrainKeyDuration)
  107. if !isOk {
  108. log.Error("lock processed failed:%v", err, ctx.Data["MsgID"])
  109. grampusNotebookNewDataPrepare(ctx, processType)
  110. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_samejob_err"), tpl, &form)
  111. return
  112. }
  113. if !jobNamePattern.MatchString(displayJobName) {
  114. grampusNotebookNewDataPrepare(ctx, processType)
  115. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_jobname_err"), tpl, &form)
  116. return
  117. }
  118. //check count limit
  119. count, err := cloudbrainTask.GetNotFinalStatusTaskCount(ctx.User.ID, models.TypeC2Net, string(models.JobTypeDebug), computeSource)
  120. if err != nil {
  121. log.Error("GetGrampusCountByUserID failed:%v", err, ctx.Data["MsgID"])
  122. grampusNotebookNewDataPrepare(ctx, processType)
  123. ctx.RenderWithErr("system error", tpl, &form)
  124. return
  125. } else {
  126. if count >= 1 {
  127. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  128. grampusNotebookNewDataPrepare(ctx, processType)
  129. ctx.RenderWithErr("you have already a running or waiting task, can not create more", tpl, &form)
  130. return
  131. }
  132. }
  133. //check whether the task name in the project is duplicated
  134. tasks, err := models.GetCloudbrainsByDisplayJobName(repo.ID, string(models.JobTypeDebug), displayJobName)
  135. if err == nil {
  136. if len(tasks) != 0 {
  137. log.Error("the job name did already exist", ctx.Data["MsgID"])
  138. grampusNotebookNewDataPrepare(ctx, processType)
  139. ctx.RenderWithErr("the job name did already exist", tpl, &form)
  140. return
  141. }
  142. } else {
  143. if !models.IsErrJobNotExist(err) {
  144. log.Error("system error, %v", err, ctx.Data["MsgID"])
  145. grampusNotebookNewDataPrepare(ctx, processType)
  146. ctx.RenderWithErr("system error", tpl, &form)
  147. return
  148. }
  149. }
  150. //check specification
  151. spec, err := resource.GetAndCheckSpec(ctx.User.ID, form.SpecId, models.FindSpecsOptions{
  152. JobType: models.JobTypeDebug,
  153. ComputeResource: computeSourceSimple,
  154. Cluster: models.C2NetCluster,
  155. })
  156. if err != nil || spec == nil {
  157. grampusNotebookNewDataPrepare(ctx, processType)
  158. ctx.RenderWithErr("Resource specification not available", tpl, &form)
  159. return
  160. }
  161. if !account.IsPointBalanceEnough(ctx.User.ID, spec.UnitPrice) {
  162. log.Error("point balance is not enough,userId=%d specId=%d", ctx.User.ID, spec.ID)
  163. grampusNotebookNewDataPrepare(ctx, processType)
  164. ctx.RenderWithErr(ctx.Tr("points.insufficient_points_balance"), tpl, &form)
  165. return
  166. }
  167. var datasetInfos map[string]models.DatasetInfo
  168. var datasetNames string
  169. //var
  170. if uuid != "" {
  171. datasetInfos, datasetNames, err = models.GetDatasetInfo(uuid, computeSourceSimple)
  172. if err != nil {
  173. log.Error("GetDatasetInfo failed: %v", err, ctx.Data["MsgID"])
  174. grampusNotebookNewDataPrepare(ctx, processType)
  175. ctx.RenderWithErr(ctx.Tr("cloudbrain.error.dataset_select"), tpl, &form)
  176. return
  177. }
  178. }
  179. //prepare code and out path
  180. _, err = ioutil.ReadDir(codeLocalPath)
  181. if err == nil {
  182. os.RemoveAll(codeLocalPath)
  183. }
  184. if err := downloadZipCode(ctx, codeLocalPath, branchName); err != nil {
  185. log.Error("downloadZipCode failed, server timed out: %s (%v)", repo.FullName(), err)
  186. grampusNotebookNewDataPrepare(ctx, processType)
  187. ctx.RenderWithErr(ctx.Tr("cloudbrain.load_code_failed"), tpl, &form)
  188. return
  189. }
  190. if processType == grampus.ProcessorTypeGPU {
  191. if err := uploadCodeToMinio(codeLocalPath+"/", jobName, cloudbrain.CodeMountPath+"/"); err != nil {
  192. log.Error("Failed to uploadCodeToMinio: %s (%v)", repo.FullName(), err, ctx.Data["MsgID"])
  193. grampusNotebookNewDataPrepare(ctx, processType)
  194. ctx.RenderWithErr(ctx.Tr("cloudbrain.load_code_failed"), tpl, &form)
  195. return
  196. }
  197. } else {
  198. if err := uploadCodeToObs(codeLocalPath, jobName, ""); err != nil {
  199. log.Error("Failed to uploadCodeToObs: %s (%v)", repo.FullName(), err)
  200. grampusNotebookNewDataPrepare(ctx, processType)
  201. ctx.RenderWithErr(ctx.Tr("cloudbrain.load_code_failed"), tpl, &form)
  202. return
  203. }
  204. }
  205. commitID, _ := ctx.Repo.GitRepo.GetBranchCommitID(branchName)
  206. req := &grampus.GenerateNotebookJobReq{
  207. JobName: jobName,
  208. DisplayJobName: displayJobName,
  209. ComputeResource: computeSource,
  210. ProcessType: processType,
  211. ImageUrl: image,
  212. ImageId: form.ImageID,
  213. Description: description,
  214. Uuid: uuid,
  215. CommitID: commitID,
  216. BranchName: branchName,
  217. DatasetNames: datasetNames,
  218. DatasetInfos: datasetInfos,
  219. Spec: spec,
  220. CodeStoragePath: codeStoragePath,
  221. CodeName: strings.ToLower(repo.Name),
  222. }
  223. _, err = grampus.GenerateNotebookJob(ctx, req)
  224. if err != nil {
  225. log.Error("GenerateNotebookJob failed:%v", err.Error(), ctx.Data["MsgID"])
  226. grampusTrainJobNewDataPrepare(ctx, processType)
  227. ctx.RenderWithErr(err.Error(), tpl, &form)
  228. return
  229. }
  230. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/debugjob?debugListType=all")
  231. }
  232. func grampusNotebookNewDataPrepare(ctx *context.Context, processType string) error {
  233. ctx.Data["PageIsCloudBrain"] = true
  234. var displayJobName = cloudbrainService.GetDisplayJobName(ctx.User.Name)
  235. ctx.Data["display_job_name"] = displayJobName
  236. //get valid images
  237. if processType == grampus.ProcessorTypeNPU {
  238. images, err := grampus.GetImages(processType, string(models.JobTypeDebug))
  239. if err != nil {
  240. log.Error("GetImages failed:", err.Error())
  241. } else {
  242. ctx.Data["images"] = images.Infos
  243. }
  244. }
  245. //prepare available specs
  246. computeResourceSimple := models.GPU
  247. datasetType := models.TypeCloudBrainOne
  248. computeResource := models.GPUResource
  249. if processType == grampus.ProcessorTypeNPU {
  250. computeResourceSimple = models.NPU
  251. datasetType = models.TypeCloudBrainTwo
  252. computeResource = models.NPUResource
  253. }
  254. prepareGrampusSpecs(ctx, computeResourceSimple, models.JobTypeDebug)
  255. //get branches
  256. branches, _, err := ctx.Repo.GitRepo.GetBranches(0, 0)
  257. if err != nil {
  258. log.Error("GetBranches error:", err.Error())
  259. } else {
  260. ctx.Data["branches"] = branches
  261. }
  262. ctx.Data["branchName"] = ctx.Repo.BranchName
  263. ctx.Data["datasetType"] = datasetType
  264. waitCount := cloudbrain.GetWaitingCloudbrainCount(models.TypeC2Net, computeResource, models.JobTypeDebug)
  265. ctx.Data["WaitCount"] = waitCount
  266. NotStopTaskCount, _ := cloudbrainTask.GetNotFinalStatusTaskCount(ctx.User.ID, models.TypeC2Net, string(models.JobTypeDebug), computeResource)
  267. ctx.Data["NotStopTaskCount"] = NotStopTaskCount
  268. ctx.Data["code_path"] = cloudbrain.CodeMountPath
  269. ctx.Data["dataset_path"] = cloudbrain.DataSetMountPath
  270. ctx.Data["model_path"] = cloudbrain.ModelMountPath
  271. return nil
  272. }
  273. func grampusTrainJobNewDataPrepare(ctx *context.Context, processType string) error {
  274. ctx.Data["PageIsCloudBrain"] = true
  275. var displayJobName = cloudbrainService.GetDisplayJobName(ctx.User.Name)
  276. ctx.Data["display_job_name"] = displayJobName
  277. //get valid images
  278. if processType == grampus.ProcessorTypeNPU {
  279. images, err := grampus.GetImages(processType, string(models.JobTypeTrain))
  280. if err != nil {
  281. log.Error("GetImages failed:", err.Error())
  282. } else {
  283. ctx.Data["images"] = images.Infos
  284. }
  285. }
  286. //prepare available specs
  287. if processType == grampus.ProcessorTypeNPU {
  288. prepareGrampusSpecs(ctx, models.NPU)
  289. } else if processType == grampus.ProcessorTypeGPU {
  290. prepareGrampusSpecs(ctx, models.GPU)
  291. }
  292. //get branches
  293. branches, _, err := ctx.Repo.GitRepo.GetBranches(0, 0)
  294. if err != nil {
  295. log.Error("GetBranches error:", err.Error())
  296. } else {
  297. ctx.Data["branches"] = branches
  298. }
  299. ctx.Data["branchName"] = ctx.Repo.BranchName
  300. if processType == grampus.ProcessorTypeGPU {
  301. ctx.Data["datasetType"] = models.TypeCloudBrainOne
  302. waitCount := cloudbrain.GetWaitingCloudbrainCount(models.TypeC2Net, models.GPUResource, models.JobTypeTrain)
  303. ctx.Data["WaitCount"] = waitCount
  304. NotStopTaskCount, _ := cloudbrainTask.GetNotFinalStatusTaskCount(ctx.User.ID, models.TypeC2Net, string(models.JobTypeTrain), models.GPUResource)
  305. ctx.Data["NotStopTaskCount"] = NotStopTaskCount
  306. } else if processType == grampus.ProcessorTypeNPU {
  307. ctx.Data["datasetType"] = models.TypeCloudBrainTwo
  308. waitCount := cloudbrain.GetWaitingCloudbrainCount(models.TypeC2Net, models.NPUResource, models.JobTypeTrain)
  309. ctx.Data["WaitCount"] = waitCount
  310. NotStopTaskCount, _ := cloudbrainTask.GetNotFinalStatusTaskCount(ctx.User.ID, models.TypeC2Net, string(models.JobTypeTrain), models.NPUResource)
  311. ctx.Data["NotStopTaskCount"] = NotStopTaskCount
  312. }
  313. if ctx.Cloudbrain != nil {
  314. uuids, datasetNames := dataset.GetFilterDeletedAttachments(ctx.Cloudbrain.Uuid)
  315. ctx.Data["attachment"] = uuids
  316. ctx.Data["boot_file"] = ctx.Cloudbrain.BootFile
  317. ctx.Data["image_id"] = ctx.Cloudbrain.ImageID
  318. ctx.Data["run_para_list"] = ctx.Cloudbrain.Parameters
  319. ctx.Data["description"] = ctx.Cloudbrain.Description
  320. ctx.Data["branch_name"] = ctx.Cloudbrain.BranchName
  321. ctx.Data["engine_name"] = ctx.Cloudbrain.EngineName
  322. ctx.Data["work_server_number"] = ctx.Cloudbrain.WorkServerNumber
  323. if ctx.Cloudbrain.Image != "" {
  324. ctx.Data["image"] = ctx.Cloudbrain.Image
  325. } else {
  326. ctx.Data["image"] = ctx.Cloudbrain.EngineName
  327. }
  328. ctx.Data["dataset_name"] = datasetNames
  329. ctx.Data["model_name"] = ctx.Cloudbrain.ModelName
  330. ctx.Data["model_version"] = ctx.Cloudbrain.ModelVersion
  331. ctx.Data["ckpt_name"] = ctx.Cloudbrain.CkptName
  332. ctx.Data["label_names"] = ctx.Cloudbrain.LabelName
  333. ctx.Data["pre_train_model_url"] = ctx.Cloudbrain.PreTrainModelUrl
  334. spec, _ := resource.GetCloudbrainSpec(ctx.Cloudbrain.ID)
  335. if spec != nil {
  336. ctx.Data["spec_id"] = spec.ID
  337. }
  338. }
  339. return nil
  340. }
  341. func GrampusTrainJobVersionNew(ctx *context.Context) {
  342. task := ctx.Cloudbrain
  343. ctx.Data["IsCreate"] = false
  344. if task.ComputeResource == models.GPUResource {
  345. err := grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  346. if err != nil {
  347. ctx.ServerError("get new train-job version info failed", err)
  348. return
  349. }
  350. ctx.HTML(http.StatusOK, tplGrampusTrainJobGPUNew)
  351. } else if task.ComputeResource == models.NPUResource {
  352. err := grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  353. if err != nil {
  354. ctx.ServerError("get new train-job version info failed", err)
  355. return
  356. }
  357. ctx.HTML(200, tplGrampusTrainJobNPUNew)
  358. }
  359. }
  360. func prepareGrampusSpecs(ctx *context.Context, computeResource string, jobType ...models.JobType) {
  361. tempJobType := models.JobTypeTrain
  362. if len(jobType) > 0 {
  363. tempJobType = jobType[0]
  364. }
  365. noteBookSpecs, _ := resource.FindAvailableSpecs(ctx.User.ID, models.FindSpecsOptions{
  366. JobType: tempJobType,
  367. ComputeResource: computeResource,
  368. Cluster: models.C2NetCluster,
  369. })
  370. ctx.Data["Specs"] = noteBookSpecs
  371. }
  372. func grampusParamCheckCreateTrainJob(form auth.CreateGrampusTrainJobForm) error {
  373. if !strings.HasSuffix(strings.TrimSpace(form.BootFile), ".py") {
  374. log.Error("the boot file(%s) must be a python file", form.BootFile)
  375. return errors.New("启动文件必须是python文件")
  376. }
  377. if form.BranchName == "" {
  378. log.Error("the branch must not be null!", form.BranchName)
  379. return errors.New("代码分支不能为空!")
  380. }
  381. return nil
  382. }
  383. func GrampusTrainJobGpuCreate(ctx *context.Context, form auth.CreateGrampusTrainJobForm) {
  384. ctx.Data["IsCreate"] = true
  385. grampusTrainJobGpuCreate(ctx, form)
  386. }
  387. func grampusTrainJobGpuCreate(ctx *context.Context, form auth.CreateGrampusTrainJobForm) {
  388. displayJobName := form.DisplayJobName
  389. jobName := util.ConvertDisplayJobNameToJobName(displayJobName)
  390. uuid := form.Attachment
  391. description := form.Description
  392. bootFile := strings.TrimSpace(form.BootFile)
  393. params := form.Params
  394. repo := ctx.Repo.Repository
  395. codeLocalPath := setting.JobPath + jobName + cloudbrain.CodeMountPath + "/"
  396. codeMinioPath := setting.CBCodePathPrefix + jobName + cloudbrain.CodeMountPath + "/"
  397. branchName := form.BranchName
  398. image := strings.TrimSpace(form.Image)
  399. tpl := tplGrampusTrainJobGPUNew
  400. lock := redis_lock.NewDistributeLock(redis_key.CloudbrainBindingJobNameKey(fmt.Sprint(repo.ID), string(models.JobTypeTrain), displayJobName))
  401. isOk, err := lock.Lock(models.CloudbrainKeyDuration)
  402. if !isOk {
  403. log.Error("lock processed failed:%v", err, ctx.Data["MsgID"])
  404. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  405. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_samejob_err"), tplGrampusTrainJobGPUNew, &form)
  406. return
  407. }
  408. defer lock.UnLock()
  409. if !jobNamePattern.MatchString(displayJobName) {
  410. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  411. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_jobname_err"), tpl, &form)
  412. return
  413. }
  414. bootFileExist, err := ctx.Repo.FileExists(bootFile, branchName)
  415. if err != nil || !bootFileExist {
  416. log.Error("Get bootfile error:", err, ctx.Data["MsgID"])
  417. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  418. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_bootfile_err"), tpl, &form)
  419. return
  420. }
  421. //check count limit
  422. count, err := cloudbrainTask.GetNotFinalStatusTaskCount(ctx.User.ID, models.TypeC2Net, string(models.JobTypeTrain), models.GPUResource)
  423. if err != nil {
  424. log.Error("GetGrampusCountByUserID failed:%v", err, ctx.Data["MsgID"])
  425. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  426. ctx.RenderWithErr("system error", tpl, &form)
  427. return
  428. } else {
  429. if count >= 1 {
  430. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  431. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  432. ctx.RenderWithErr("you have already a running or waiting task, can not create more", tpl, &form)
  433. return
  434. }
  435. }
  436. //check param
  437. if err := grampusParamCheckCreateTrainJob(form); err != nil {
  438. log.Error("paramCheckCreateTrainJob failed:(%v)", err, ctx.Data["MsgID"])
  439. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  440. ctx.RenderWithErr(err.Error(), tpl, &form)
  441. return
  442. }
  443. //check whether the task name in the project is duplicated
  444. tasks, err := models.GetCloudbrainsByDisplayJobName(repo.ID, string(models.JobTypeTrain), displayJobName)
  445. if err == nil {
  446. if len(tasks) != 0 {
  447. log.Error("the job name did already exist", ctx.Data["MsgID"])
  448. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  449. ctx.RenderWithErr("the job name did already exist", tpl, &form)
  450. return
  451. }
  452. } else {
  453. if !models.IsErrJobNotExist(err) {
  454. log.Error("system error, %v", err, ctx.Data["MsgID"])
  455. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  456. ctx.RenderWithErr("system error", tpl, &form)
  457. return
  458. }
  459. }
  460. //check specification
  461. spec, err := resource.GetAndCheckSpec(ctx.User.ID, form.SpecId, models.FindSpecsOptions{
  462. JobType: models.JobTypeTrain,
  463. ComputeResource: models.GPU,
  464. Cluster: models.C2NetCluster,
  465. })
  466. if err != nil || spec == nil {
  467. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  468. ctx.RenderWithErr("Resource specification not available", tpl, &form)
  469. return
  470. }
  471. if !account.IsPointBalanceEnough(ctx.User.ID, spec.UnitPrice) {
  472. log.Error("point balance is not enough,userId=%d specId=%d", ctx.User.ID, spec.ID)
  473. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  474. ctx.RenderWithErr(ctx.Tr("points.insufficient_points_balance"), tplGrampusTrainJobGPUNew, &form)
  475. return
  476. }
  477. //check dataset
  478. datasetInfos, datasetNames, err := models.GetDatasetInfo(uuid, models.GPU)
  479. if err != nil {
  480. log.Error("GetDatasetInfo failed: %v", err, ctx.Data["MsgID"])
  481. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  482. ctx.RenderWithErr(ctx.Tr("cloudbrain.error.dataset_select"), tpl, &form)
  483. return
  484. }
  485. //prepare code and out path
  486. _, err = ioutil.ReadDir(codeLocalPath)
  487. if err == nil {
  488. os.RemoveAll(codeLocalPath)
  489. }
  490. if err := downloadZipCode(ctx, codeLocalPath, branchName); err != nil {
  491. log.Error("downloadZipCode failed, server timed out: %s (%v)", repo.FullName(), err, ctx.Data["MsgID"])
  492. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  493. ctx.RenderWithErr(ctx.Tr("cloudbrain.load_code_failed"), tpl, &form)
  494. return
  495. }
  496. //todo: upload code (send to file_server todo this work?)
  497. //upload code
  498. if err := uploadCodeToMinio(codeLocalPath+"/", jobName, cloudbrain.CodeMountPath+"/"); err != nil {
  499. log.Error("Failed to uploadCodeToMinio: %s (%v)", repo.FullName(), err, ctx.Data["MsgID"])
  500. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  501. ctx.RenderWithErr(ctx.Tr("cloudbrain.load_code_failed"), tpl, &form)
  502. return
  503. }
  504. modelPath := setting.JobPath + jobName + cloudbrain.ModelMountPath + "/"
  505. if err := mkModelPath(modelPath); err != nil {
  506. log.Error("Failed to mkModelPath: %s (%v)", repo.FullName(), err, ctx.Data["MsgID"])
  507. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  508. ctx.RenderWithErr(ctx.Tr("cloudbrain.load_code_failed"), tpl, &form)
  509. return
  510. }
  511. //init model readme
  512. if err := uploadCodeToMinio(modelPath, jobName, cloudbrain.ModelMountPath+"/"); err != nil {
  513. log.Error("Failed to uploadCodeToMinio: %s (%v)", repo.FullName(), err, ctx.Data["MsgID"])
  514. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  515. ctx.RenderWithErr(ctx.Tr("cloudbrain.load_code_failed"), tpl, &form)
  516. return
  517. }
  518. var datasetRemotePath, allFileName string
  519. for _, datasetInfo := range datasetInfos {
  520. if datasetRemotePath == "" {
  521. datasetRemotePath = datasetInfo.DataLocalPath
  522. allFileName = datasetInfo.FullName
  523. } else {
  524. datasetRemotePath = datasetRemotePath + ";" + datasetInfo.DataLocalPath
  525. allFileName = allFileName + ";" + datasetInfo.FullName
  526. }
  527. }
  528. //prepare command
  529. preTrainModelPath := getPreTrainModelPath(form.PreTrainModelUrl, form.CkptName)
  530. command, err := generateCommand(repo.Name, grampus.ProcessorTypeGPU, codeMinioPath+cloudbrain.DefaultBranchName+".zip", datasetRemotePath, bootFile, params, setting.CBCodePathPrefix+jobName+cloudbrain.ModelMountPath+"/", allFileName, preTrainModelPath, form.CkptName, "")
  531. if err != nil {
  532. log.Error("Failed to generateCommand: %s (%v)", displayJobName, err, ctx.Data["MsgID"])
  533. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  534. ctx.RenderWithErr("Create task failed, internal error", tpl, &form)
  535. return
  536. }
  537. commitID, _ := ctx.Repo.GitRepo.GetBranchCommitID(branchName)
  538. req := &grampus.GenerateTrainJobReq{
  539. JobName: jobName,
  540. DisplayJobName: displayJobName,
  541. ComputeResource: models.GPUResource,
  542. ProcessType: grampus.ProcessorTypeGPU,
  543. Command: command,
  544. ImageUrl: image,
  545. Description: description,
  546. BootFile: bootFile,
  547. Uuid: uuid,
  548. CommitID: commitID,
  549. BranchName: branchName,
  550. Params: form.Params,
  551. EngineName: image,
  552. DatasetNames: datasetNames,
  553. DatasetInfos: datasetInfos,
  554. IsLatestVersion: modelarts.IsLatestVersion,
  555. VersionCount: modelarts.VersionCountOne,
  556. WorkServerNumber: 1,
  557. Spec: spec,
  558. }
  559. if form.ModelName != "" { //使用预训练模型训练
  560. req.ModelName = form.ModelName
  561. req.LabelName = form.LabelName
  562. req.CkptName = form.CkptName
  563. req.ModelVersion = form.ModelVersion
  564. req.PreTrainModelUrl = form.PreTrainModelUrl
  565. }
  566. _, err = grampus.GenerateTrainJob(ctx, req)
  567. if err != nil {
  568. log.Error("GenerateTrainJob failed:%v", err.Error(), ctx.Data["MsgID"])
  569. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  570. ctx.RenderWithErr(err.Error(), tpl, &form)
  571. return
  572. }
  573. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/train-job")
  574. }
  575. func getPreTrainModelPath(pretrainModelDir string, fileName string) string {
  576. index := strings.Index(pretrainModelDir, "/")
  577. if index > 0 {
  578. filterBucket := pretrainModelDir[index+1:]
  579. return filterBucket + fileName
  580. } else {
  581. return ""
  582. }
  583. }
  584. func GrampusTrainJobVersionCreate(ctx *context.Context, form auth.CreateGrampusTrainJobForm) {
  585. ctx.Data["IsCreate"] = false
  586. computeResource := ctx.Query("compute_resource")
  587. if computeResource == models.GPUResource {
  588. grampusTrainJobGpuCreate(ctx, form)
  589. } else if computeResource == models.NPUResource {
  590. grampusTrainJobNpuCreate(ctx, form)
  591. } else {
  592. ctx.ServerError("resource error", errors.New("compute resource is not support"))
  593. return
  594. }
  595. }
  596. func GrampusTrainJobNpuCreate(ctx *context.Context, form auth.CreateGrampusTrainJobForm) {
  597. ctx.Data["IsCreate"] = true
  598. grampusTrainJobNpuCreate(ctx, form)
  599. }
  600. func grampusTrainJobNpuCreate(ctx *context.Context, form auth.CreateGrampusTrainJobForm) {
  601. displayJobName := form.DisplayJobName
  602. jobName := util.ConvertDisplayJobNameToJobName(displayJobName)
  603. uuid := form.Attachment
  604. description := form.Description
  605. bootFile := strings.TrimSpace(form.BootFile)
  606. params := form.Params
  607. repo := ctx.Repo.Repository
  608. codeLocalPath := setting.JobPath + jobName + modelarts.CodePath
  609. codeObsPath := grampus.JobPath + jobName + modelarts.CodePath
  610. //dataObsPath := setting.BasePath + path.Join(uuid[0:1], uuid[1:2]) + "/" + uuid + "/"
  611. branchName := form.BranchName
  612. isLatestVersion := modelarts.IsLatestVersion
  613. versionCount := modelarts.VersionCountOne
  614. engineName := form.EngineName
  615. tpl := tplGrampusTrainJobNPUNew
  616. lock := redis_lock.NewDistributeLock(redis_key.CloudbrainBindingJobNameKey(fmt.Sprint(repo.ID), string(models.JobTypeTrain), displayJobName))
  617. isOk, err := lock.Lock(models.CloudbrainKeyDuration)
  618. if !isOk {
  619. log.Error("lock processed failed:%v", err, ctx.Data["MsgID"])
  620. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  621. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_samejob_err"), tplGrampusTrainJobNPUNew, &form)
  622. return
  623. }
  624. defer lock.UnLock()
  625. if !jobNamePattern.MatchString(displayJobName) {
  626. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  627. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_jobname_err"), tpl, &form)
  628. return
  629. }
  630. bootFileExist, err := ctx.Repo.FileExists(bootFile, branchName)
  631. if err != nil || !bootFileExist {
  632. log.Error("Get bootfile error:", err, ctx.Data["MsgID"])
  633. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  634. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_bootfile_err"), tpl, &form)
  635. return
  636. }
  637. //check count limit
  638. count, err := cloudbrainTask.GetNotFinalStatusTaskCount(ctx.User.ID, models.TypeC2Net, string(models.JobTypeTrain), models.NPUResource)
  639. if err != nil {
  640. log.Error("GetGrampusCountByUserID failed:%v", err, ctx.Data["MsgID"])
  641. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  642. ctx.RenderWithErr("system error", tpl, &form)
  643. return
  644. } else {
  645. if count >= 1 {
  646. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  647. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  648. ctx.RenderWithErr("you have already a running or waiting task, can not create more", tpl, &form)
  649. return
  650. }
  651. }
  652. //check param
  653. if err := grampusParamCheckCreateTrainJob(form); err != nil {
  654. log.Error("paramCheckCreateTrainJob failed:(%v)", err)
  655. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  656. ctx.RenderWithErr(err.Error(), tpl, &form)
  657. return
  658. }
  659. //check whether the task name in the project is duplicated
  660. tasks, err := models.GetCloudbrainsByDisplayJobName(repo.ID, string(models.JobTypeTrain), displayJobName)
  661. if err == nil {
  662. if len(tasks) != 0 {
  663. log.Error("the job name did already exist", ctx.Data["MsgID"])
  664. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  665. ctx.RenderWithErr("the job name did already exist", tpl, &form)
  666. return
  667. }
  668. } else {
  669. if !models.IsErrJobNotExist(err) {
  670. log.Error("system error, %v", err, ctx.Data["MsgID"])
  671. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  672. ctx.RenderWithErr("system error", tpl, &form)
  673. return
  674. }
  675. }
  676. //check specification
  677. spec, err := resource.GetAndCheckSpec(ctx.User.ID, form.SpecId, models.FindSpecsOptions{
  678. JobType: models.JobTypeTrain,
  679. ComputeResource: models.NPU,
  680. Cluster: models.C2NetCluster,
  681. })
  682. if err != nil || spec == nil {
  683. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  684. ctx.RenderWithErr("Resource specification not available", tpl, &form)
  685. return
  686. }
  687. if !account.IsPointBalanceEnough(ctx.User.ID, spec.UnitPrice) {
  688. log.Error("point balance is not enough,userId=%d specId=%d", ctx.User.ID, spec.ID)
  689. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  690. ctx.RenderWithErr(ctx.Tr("points.insufficient_points_balance"), tplGrampusTrainJobNPUNew, &form)
  691. return
  692. }
  693. //check dataset
  694. datasetInfos, datasetNames, err := models.GetDatasetInfo(uuid, models.NPU)
  695. if err != nil {
  696. log.Error("GetDatasetInfo failed: %v", err, ctx.Data["MsgID"])
  697. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  698. ctx.RenderWithErr(ctx.Tr("cloudbrain.error.dataset_select"), tpl, &form)
  699. return
  700. }
  701. //prepare code and out path
  702. _, err = ioutil.ReadDir(codeLocalPath)
  703. if err == nil {
  704. os.RemoveAll(codeLocalPath)
  705. }
  706. if err := downloadZipCode(ctx, codeLocalPath, branchName); err != nil {
  707. log.Error("downloadZipCode failed, server timed out: %s (%v)", repo.FullName(), err)
  708. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  709. ctx.RenderWithErr(ctx.Tr("cloudbrain.load_code_failed"), tpl, &form)
  710. return
  711. }
  712. //todo: upload code (send to file_server todo this work?)
  713. if err := obsMkdir(setting.CodePathPrefix + jobName + modelarts.OutputPath); err != nil {
  714. log.Error("Failed to obsMkdir_output: %s (%v)", repo.FullName(), err)
  715. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  716. ctx.RenderWithErr(ctx.Tr("cloudbrain.load_code_failed"), tpl, &form)
  717. return
  718. }
  719. if err := uploadCodeToObs(codeLocalPath, jobName, ""); err != nil {
  720. log.Error("Failed to uploadCodeToObs: %s (%v)", repo.FullName(), err)
  721. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  722. ctx.RenderWithErr(ctx.Tr("cloudbrain.load_code_failed"), tpl, &form)
  723. return
  724. }
  725. var datasetRemotePath, allFileName string
  726. for _, datasetInfo := range datasetInfos {
  727. if datasetRemotePath == "" {
  728. datasetRemotePath = datasetInfo.DataLocalPath + "'" + datasetInfo.FullName + "'"
  729. allFileName = datasetInfo.FullName
  730. } else {
  731. datasetRemotePath = datasetRemotePath + ";" + datasetInfo.DataLocalPath + "'" + datasetInfo.FullName + "'"
  732. allFileName = allFileName + ";" + datasetInfo.FullName
  733. }
  734. }
  735. //prepare command
  736. preTrainModelPath := getPreTrainModelPath(form.PreTrainModelUrl, form.CkptName)
  737. command, err := generateCommand(repo.Name, grampus.ProcessorTypeNPU, codeObsPath+cloudbrain.DefaultBranchName+".zip", datasetRemotePath, bootFile, params, setting.CodePathPrefix+jobName+modelarts.OutputPath, allFileName, preTrainModelPath, form.CkptName, grampus.GetNpuModelRemoteObsUrl(jobName))
  738. if err != nil {
  739. log.Error("Failed to generateCommand: %s (%v)", displayJobName, err, ctx.Data["MsgID"])
  740. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  741. ctx.RenderWithErr("Create task failed, internal error", tpl, &form)
  742. return
  743. }
  744. commitID, _ := ctx.Repo.GitRepo.GetBranchCommitID(branchName)
  745. req := &grampus.GenerateTrainJobReq{
  746. JobName: jobName,
  747. DisplayJobName: displayJobName,
  748. ComputeResource: models.NPUResource,
  749. ProcessType: grampus.ProcessorTypeNPU,
  750. Command: command,
  751. ImageId: form.ImageID,
  752. Description: description,
  753. CodeObsPath: codeObsPath,
  754. BootFileUrl: codeObsPath + bootFile,
  755. BootFile: bootFile,
  756. WorkServerNumber: form.WorkServerNumber,
  757. Uuid: uuid,
  758. CommitID: commitID,
  759. IsLatestVersion: isLatestVersion,
  760. BranchName: branchName,
  761. Params: form.Params,
  762. EngineName: engineName,
  763. VersionCount: versionCount,
  764. TotalVersionCount: modelarts.TotalVersionCount,
  765. DatasetNames: datasetNames,
  766. DatasetInfos: datasetInfos,
  767. Spec: spec,
  768. CodeName: strings.ToLower(repo.Name),
  769. }
  770. if form.ModelName != "" { //使用预训练模型训练
  771. req.ModelName = form.ModelName
  772. req.LabelName = form.LabelName
  773. req.CkptName = form.CkptName
  774. req.ModelVersion = form.ModelVersion
  775. req.PreTrainModelUrl = form.PreTrainModelUrl
  776. req.PreTrainModelPath = preTrainModelPath
  777. }
  778. _, err = grampus.GenerateTrainJob(ctx, req)
  779. if err != nil {
  780. log.Error("GenerateTrainJob failed:%v", err.Error())
  781. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  782. ctx.RenderWithErr(err.Error(), tpl, &form)
  783. return
  784. }
  785. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/train-job")
  786. }
  787. func GetGrampusNotebook(ctx *context.APIContext) {
  788. var (
  789. err error
  790. )
  791. ID := ctx.Params(":id")
  792. job, err := models.GetCloudbrainByID(ID)
  793. if err != nil {
  794. ctx.NotFound("", err)
  795. log.Error("GetCloudbrainByID failed:", err)
  796. return
  797. }
  798. jobAfter, err := cloudbrainTask.SyncGrampusNotebookStatus(job)
  799. aiCenterName := cloudbrainService.GetAiCenterShow(jobAfter.AiCenter, ctx.Context)
  800. if err != nil {
  801. ctx.NotFound(err)
  802. log.Error("Sync cloud brain one status failed:", err)
  803. return
  804. }
  805. ctx.JSON(http.StatusOK, map[string]interface{}{
  806. "ID": ID,
  807. "JobName": jobAfter.JobName,
  808. "JobStatus": jobAfter.Status,
  809. "AiCenter": aiCenterName,
  810. "CreatedTime": jobAfter.CreatedUnix.Format("2006-01-02 15:04:05"),
  811. "CompletedTime": jobAfter.UpdatedUnix.Format("2006-01-02 15:04:05"),
  812. "JobDuration": jobAfter.TrainJobDuration,
  813. })
  814. }
  815. func GrampusStopJob(ctx *context.Context) {
  816. var ID = ctx.Params(":id")
  817. var resultCode = "0"
  818. var errorMsg = ""
  819. var status = ""
  820. task := ctx.Cloudbrain
  821. for {
  822. if task.Status == models.GrampusStatusStopped || task.Status == models.GrampusStatusFailed || task.Status == models.GrampusStatusSucceeded {
  823. log.Error("the job(%s) has been stopped", task.JobName, ctx.Data["msgID"])
  824. resultCode = "-1"
  825. errorMsg = "System error"
  826. break
  827. }
  828. res, err := grampus.StopJob(task.JobID, task.JobType)
  829. if err != nil {
  830. log.Error("StopJob(%s) failed:%v", task.JobName, err, ctx.Data["msgID"])
  831. resultCode = strconv.Itoa(res.ErrorCode)
  832. errorMsg = res.ErrorMsg
  833. break
  834. }
  835. oldStatus := task.Status
  836. task.Status = getStopJobResponseStatus(res)
  837. if task.EndTime == 0 {
  838. task.EndTime = timeutil.TimeStampNow()
  839. }
  840. task.ComputeAndSetDuration()
  841. if oldStatus != task.Status {
  842. notification.NotifyChangeCloudbrainStatus(task, oldStatus)
  843. }
  844. err = models.UpdateJob(task)
  845. if err != nil {
  846. log.Error("UpdateJob(%s) failed:%v", task.JobName, err, ctx.Data["msgID"])
  847. resultCode = "-1"
  848. errorMsg = "system error"
  849. break
  850. }
  851. status = task.Status
  852. break
  853. }
  854. ctx.JSON(200, map[string]interface{}{
  855. "result_code": resultCode,
  856. "error_msg": errorMsg,
  857. "status": status,
  858. "id": ID,
  859. "StatusOK": 0,
  860. })
  861. }
  862. func getStopJobResponseStatus(res *models.GrampusStopJobResponse) string {
  863. newStatus := models.GrampusStatusStopping
  864. if res.Status != "" {
  865. newStatus = grampus.TransTrainJobStatus(res.Status)
  866. }
  867. return newStatus
  868. }
  869. func GrampusNotebookDel(ctx *context.Context) {
  870. var listType = ctx.Query("listType")
  871. if err := deleteGrampusJob(ctx); err != nil {
  872. log.Error("deleteGrampusJob failed: %v", err, ctx.Data["msgID"])
  873. ctx.ServerError(err.Error(), err)
  874. return
  875. }
  876. var isAdminPage = ctx.Query("isadminpage")
  877. var isHomePage = ctx.Query("ishomepage")
  878. if ctx.IsUserSiteAdmin() && isAdminPage == "true" {
  879. ctx.Redirect(setting.AppSubURL + "/admin" + "/cloudbrains")
  880. } else if isHomePage == "true" {
  881. ctx.Redirect(setting.AppSubURL + "/cloudbrains")
  882. } else {
  883. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/debugjob?debugListType=" + listType)
  884. }
  885. }
  886. func GrampusTrainJobDel(ctx *context.Context) {
  887. var listType = ctx.Query("listType")
  888. if err := deleteGrampusJob(ctx); err != nil {
  889. log.Error("deleteGrampusJob failed: %v", err, ctx.Data["msgID"])
  890. ctx.ServerError(err.Error(), err)
  891. return
  892. }
  893. var isAdminPage = ctx.Query("isadminpage")
  894. var isHomePage = ctx.Query("ishomepage")
  895. if ctx.IsUserSiteAdmin() && isAdminPage == "true" {
  896. ctx.Redirect(setting.AppSubURL + "/admin" + "/cloudbrains")
  897. } else if isHomePage == "true" {
  898. ctx.Redirect(setting.AppSubURL + "/cloudbrains")
  899. } else {
  900. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/train-job?listType=" + listType)
  901. }
  902. }
  903. func deleteGrampusJob(ctx *context.Context) error {
  904. task := ctx.Cloudbrain
  905. if task.Status != models.GrampusStatusStopped && task.Status != models.GrampusStatusSucceeded && task.Status != models.GrampusStatusFailed {
  906. log.Error("the job(%s) has not been stopped", task.JobName, ctx.Data["msgID"])
  907. return errors.New(ctx.Tr("cloudbrain.Not_Stopped"))
  908. }
  909. err := models.DeleteJob(task)
  910. if err != nil {
  911. log.Error("DeleteJob failed: %v", err, ctx.Data["msgID"])
  912. return err
  913. }
  914. storageType := models.TypeCloudBrainOne
  915. if task.ComputeResource == models.NPUResource {
  916. storageType = models.TypeCloudBrainTwo
  917. }
  918. DeleteCloudbrainJobStorage(task.JobName, storageType)
  919. return nil
  920. }
  921. type NotebookDataset struct {
  922. DatasetUrl string `json:"dataset_url"`
  923. }
  924. func GrampusNotebookShow(ctx *context.Context) {
  925. ctx.Data["PageIsCloudBrain"] = true
  926. var task *models.Cloudbrain
  927. task, err := models.GetCloudbrainByIDWithDeleted(ctx.Params(":id"))
  928. if err != nil {
  929. log.Error("GetCloudbrainByID failed:" + err.Error())
  930. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  931. return
  932. }
  933. task.ContainerIp = ""
  934. if task.DeletedAt.IsZero() && cloudbrainTask.IsTaskNotStop(task) { //normal record
  935. result, err := grampus.GetNotebookJob(task.JobID)
  936. if err != nil {
  937. log.Error("GetJob failed:" + err.Error())
  938. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  939. return
  940. }
  941. if result != nil {
  942. if len(result.JobInfo.Tasks[0].CenterID) == 1 && len(result.JobInfo.Tasks[0].CenterName) == 1 {
  943. task.AiCenter = result.JobInfo.Tasks[0].CenterID[0] + "+" + result.JobInfo.Tasks[0].CenterName[0]
  944. }
  945. oldStatus := task.Status
  946. task.Status = grampus.TransTrainJobStatus(result.JobInfo.Status)
  947. if task.Status != oldStatus || task.Status == models.GrampusStatusRunning {
  948. task.Duration = result.JobInfo.RunSec
  949. if task.Duration < 0 {
  950. task.Duration = 0
  951. }
  952. task.TrainJobDuration = models.ConvertDurationToStr(task.Duration)
  953. if task.StartTime == 0 && result.JobInfo.StartedAt > 0 {
  954. task.StartTime = timeutil.TimeStamp(result.JobInfo.StartedAt)
  955. }
  956. if task.EndTime == 0 && models.IsTrainJobTerminal(task.Status) && task.StartTime > 0 {
  957. task.EndTime = task.StartTime.Add(task.Duration)
  958. }
  959. task.CorrectCreateUnix()
  960. if oldStatus != task.Status {
  961. notification.NotifyChangeCloudbrainStatus(task, oldStatus)
  962. if models.IsTrainJobTerminal(task.Status) && task.ComputeResource == models.NPUResource {
  963. if len(result.JobInfo.Tasks[0].CenterID) == 1 {
  964. urchin.GetBackNpuModel(task.ID, grampus.GetRemoteEndPoint(result.JobInfo.Tasks[0].CenterID[0]), grampus.BucketRemote, grampus.GetNpuModelObjectKey(task.JobName), grampus.GetCenterProxy(setting.Grampus.LocalCenterID))
  965. }
  966. }
  967. }
  968. }
  969. err = models.UpdateJob(task)
  970. if err != nil {
  971. log.Error("UpdateJob failed:" + err.Error())
  972. }
  973. }
  974. }
  975. if len(task.Parameters) > 0 {
  976. var parameters models.Parameters
  977. err := json.Unmarshal([]byte(task.Parameters), &parameters)
  978. if err != nil {
  979. log.Error("Failed to Unmarshal Parameters: %s (%v)", task.Parameters, err)
  980. ctx.ServerError("system error", err)
  981. return
  982. }
  983. if len(parameters.Parameter) > 0 {
  984. paramTemp := ""
  985. for _, Parameter := range parameters.Parameter {
  986. param := Parameter.Label + " = " + Parameter.Value + "; "
  987. paramTemp = paramTemp + param
  988. }
  989. task.Parameters = paramTemp[:len(paramTemp)-2]
  990. } else {
  991. task.Parameters = ""
  992. }
  993. }
  994. user, err := models.GetUserByID(task.UserID)
  995. if err == nil {
  996. task.User = user
  997. }
  998. prepareSpec4Show(ctx, task)
  999. ctx.Data["task"] = task
  1000. ctx.Data["datasetDownload"] = getDatasetDownloadInfo(ctx, task)
  1001. ctx.Data["canDownload"] = cloudbrain.CanModifyJob(ctx, task)
  1002. ctx.Data["ai_center"] = cloudbrainService.GetAiCenterShow(task.AiCenter, ctx)
  1003. ctx.HTML(http.StatusOK, tplGrampusNotebookShow)
  1004. }
  1005. func getDatasetDownloadInfo(ctx *context.Context, task *models.Cloudbrain) []models.DatasetDownload {
  1006. datasetDownload := make([]models.DatasetDownload, 0)
  1007. if ctx.IsSigned {
  1008. if task.Uuid != "" && task.UserID == ctx.User.ID {
  1009. datasetDownload = GetCloudBrainDataSetInfo(task.Uuid, task.DatasetName, true)
  1010. }
  1011. }
  1012. datasetObsUrlList := make([]NotebookDataset, 0)
  1013. _ = json.Unmarshal([]byte(task.DataUrl), &datasetObsUrlList)
  1014. for _, datasetInfo := range datasetDownload {
  1015. match := false
  1016. for _, datasetObs := range datasetObsUrlList {
  1017. if strings.Contains(datasetObs.DatasetUrl, datasetInfo.DatasetName) {
  1018. datasetInfo.DatasetDownloadLink = datasetObs.DatasetUrl
  1019. match = true
  1020. break
  1021. }
  1022. }
  1023. if !match {
  1024. datasetInfo.DatasetDownloadLink = ""
  1025. }
  1026. }
  1027. return datasetDownload
  1028. }
  1029. func GrampusTrainJobShow(ctx *context.Context) {
  1030. ctx.Data["PageIsCloudBrain"] = true
  1031. var task *models.Cloudbrain
  1032. task, err := models.GetCloudbrainByJobIDWithDeleted(ctx.Params(":jobid"))
  1033. if err != nil {
  1034. log.Error("GetCloudbrainByJobID failed:" + err.Error())
  1035. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  1036. return
  1037. }
  1038. task.ContainerIp = ""
  1039. if task.DeletedAt.IsZero() { //normal record
  1040. result, err := grampus.GetJob(task.JobID)
  1041. if err != nil {
  1042. log.Error("GetJob failed:" + err.Error())
  1043. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  1044. return
  1045. }
  1046. if result != nil {
  1047. if len(result.JobInfo.Tasks[0].CenterID) == 1 && len(result.JobInfo.Tasks[0].CenterName) == 1 {
  1048. task.AiCenter = result.JobInfo.Tasks[0].CenterID[0] + "+" + result.JobInfo.Tasks[0].CenterName[0]
  1049. }
  1050. oldStatus := task.Status
  1051. task.Status = grampus.TransTrainJobStatus(result.JobInfo.Status)
  1052. if task.Status != oldStatus || task.Status == models.GrampusStatusRunning {
  1053. task.Duration = result.JobInfo.RunSec
  1054. if task.Duration < 0 {
  1055. task.Duration = 0
  1056. }
  1057. task.TrainJobDuration = models.ConvertDurationToStr(task.Duration)
  1058. if task.StartTime == 0 && result.JobInfo.StartedAt > 0 {
  1059. task.StartTime = timeutil.TimeStamp(result.JobInfo.StartedAt)
  1060. }
  1061. if task.EndTime == 0 && models.IsTrainJobTerminal(task.Status) && task.StartTime > 0 {
  1062. task.EndTime = task.StartTime.Add(task.Duration)
  1063. }
  1064. task.CorrectCreateUnix()
  1065. if oldStatus != task.Status {
  1066. notification.NotifyChangeCloudbrainStatus(task, oldStatus)
  1067. if models.IsTrainJobTerminal(task.Status) && task.ComputeResource == models.NPUResource {
  1068. if len(result.JobInfo.Tasks[0].CenterID) == 1 {
  1069. urchin.GetBackNpuModel(task.ID, grampus.GetRemoteEndPoint(result.JobInfo.Tasks[0].CenterID[0]), grampus.BucketRemote, grampus.GetNpuModelObjectKey(task.JobName), grampus.GetCenterProxy(setting.Grampus.LocalCenterID))
  1070. }
  1071. }
  1072. }
  1073. }
  1074. err = models.UpdateJob(task)
  1075. if err != nil {
  1076. log.Error("UpdateJob failed:" + err.Error())
  1077. }
  1078. }
  1079. }
  1080. if len(task.Parameters) > 0 {
  1081. var parameters models.Parameters
  1082. err := json.Unmarshal([]byte(task.Parameters), &parameters)
  1083. if err != nil {
  1084. log.Error("Failed to Unmarshal Parameters: %s (%v)", task.Parameters, err)
  1085. ctx.ServerError("system error", err)
  1086. return
  1087. }
  1088. if len(parameters.Parameter) > 0 {
  1089. paramTemp := ""
  1090. for _, Parameter := range parameters.Parameter {
  1091. param := Parameter.Label + " = " + Parameter.Value + "; "
  1092. paramTemp = paramTemp + param
  1093. }
  1094. task.Parameters = paramTemp[:len(paramTemp)-2]
  1095. } else {
  1096. task.Parameters = ""
  1097. }
  1098. }
  1099. taskList := make([]*models.Cloudbrain, 0)
  1100. taskList = append(taskList, task)
  1101. prepareSpec4Show(ctx, task)
  1102. ctx.Data["version_list_task"] = taskList
  1103. ctx.Data["datasetDownload"] = GetCloudBrainDataSetInfo(task.Uuid, task.DatasetName, false)
  1104. ctx.Data["canDownload"] = cloudbrain.CanModifyJob(ctx, task)
  1105. ctx.Data["displayJobName"] = task.DisplayJobName
  1106. ctx.Data["ai_center"] = cloudbrainService.GetAiCenterShow(task.AiCenter, ctx)
  1107. ctx.HTML(http.StatusOK, tplGrampusTrainJobShow)
  1108. }
  1109. func GrampusDownloadLog(ctx *context.Context) {
  1110. jobID := ctx.Params(":jobid")
  1111. job, err := models.GetCloudbrainByJobID(jobID)
  1112. if err != nil {
  1113. log.Error("GetCloudbrainByJobID failed: %v", err, ctx.Data["MsgID"])
  1114. ctx.ServerError(err.Error(), err)
  1115. return
  1116. }
  1117. content, err := grampus.GetTrainJobLog(job.JobID)
  1118. if err != nil {
  1119. log.Error("GetTrainJobLog failed: %v", err, ctx.Data["MsgID"])
  1120. content = ""
  1121. }
  1122. fileName := job.JobName + "-log.txt"
  1123. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+fileName)
  1124. ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
  1125. var b []byte = []byte(content)
  1126. ctx.Resp.Write(b)
  1127. }
  1128. func GrampusGetLog(ctx *context.Context) {
  1129. jobID := ctx.Params(":jobid")
  1130. job, err := models.GetCloudbrainByJobID(jobID)
  1131. if err != nil {
  1132. log.Error("GetCloudbrainByJobID failed: %v", err, ctx.Data["MsgID"])
  1133. ctx.ServerError(err.Error(), err)
  1134. return
  1135. }
  1136. content, err := grampus.GetTrainJobLog(job.JobID)
  1137. if err != nil {
  1138. log.Error("GetTrainJobLog failed: %v", err, ctx.Data["MsgID"])
  1139. ctx.JSON(http.StatusOK, map[string]interface{}{
  1140. "JobName": job.JobName,
  1141. "Content": "",
  1142. "CanLogDownload": false,
  1143. })
  1144. return
  1145. }
  1146. canLogDownload := err == nil && job.IsUserHasRight(ctx.User)
  1147. ctx.JSON(http.StatusOK, map[string]interface{}{
  1148. "JobName": job.JobName,
  1149. "Content": content,
  1150. "CanLogDownload": canLogDownload,
  1151. })
  1152. return
  1153. }
  1154. func GrampusMetrics(ctx *context.Context) {
  1155. jobID := ctx.Params(":jobid")
  1156. job, err := models.GetCloudbrainByJobID(jobID)
  1157. if err != nil {
  1158. log.Error("GetCloudbrainByJobID failed: %v", err, ctx.Data["MsgID"])
  1159. ctx.ServerError(err.Error(), err)
  1160. return
  1161. }
  1162. result, err := grampus.GetGrampusMetrics(job.JobID)
  1163. if err != nil {
  1164. log.Error("GetTrainJobLog failed: %v", err, ctx.Data["MsgID"])
  1165. }
  1166. ctx.JSON(http.StatusOK, map[string]interface{}{
  1167. "JobID": jobID,
  1168. "Interval": result.Interval,
  1169. "MetricsInfo": result.MetricsInfo,
  1170. })
  1171. return
  1172. }
  1173. func generateCommand(repoName, processorType, codeRemotePath, dataRemotePath, bootFile, paramSrc, outputRemotePath, datasetName, pretrainModelPath, pretrainModelFileName, modelRemoteObsUrl string) (string, error) {
  1174. var command string
  1175. //prepare
  1176. workDir := grampus.NpuWorkDir
  1177. if processorType == grampus.ProcessorTypeNPU {
  1178. command += "pwd;cd " + workDir + grampus.CommandPrepareScriptNpu
  1179. } else if processorType == grampus.ProcessorTypeGPU {
  1180. workDir = grampus.GpuWorkDir
  1181. command += "pwd;cd " + workDir + fmt.Sprintf(grampus.CommandPrepareScriptGpu, setting.Grampus.SyncScriptProject, setting.Grampus.SyncScriptProject)
  1182. }
  1183. //download code & dataset
  1184. if processorType == grampus.ProcessorTypeNPU {
  1185. //no need to download code & dataset by internet
  1186. } else if processorType == grampus.ProcessorTypeGPU {
  1187. commandDownload := "./downloader_for_minio " + setting.Grampus.Env + " " + codeRemotePath + " " + grampus.CodeArchiveName + " '" + dataRemotePath + "' '" + datasetName + "'"
  1188. commandDownload = processPretrainModelParameter(pretrainModelPath, pretrainModelFileName, commandDownload)
  1189. command += commandDownload
  1190. }
  1191. //unzip code & dataset
  1192. if processorType == grampus.ProcessorTypeNPU {
  1193. //no need to process
  1194. } else if processorType == grampus.ProcessorTypeGPU {
  1195. unZipDatasetCommand := cloudbrainTask.GenerateDatasetUnzipCommand(datasetName)
  1196. commandUnzip := "cd " + workDir + "code;unzip -q master.zip;rm -f master.zip;echo \"start to unzip dataset\";cd " + workDir + "dataset;" + unZipDatasetCommand
  1197. command += commandUnzip
  1198. }
  1199. command += "echo \"unzip finished;start to exec code;\";"
  1200. // set export
  1201. var commandExport string
  1202. if processorType == grampus.ProcessorTypeNPU {
  1203. commandExport = "export bucket=" + setting.Bucket + " && export remote_path=" + outputRemotePath + ";"
  1204. } else if processorType == grampus.ProcessorTypeGPU {
  1205. commandExport = "export env=" + setting.Grampus.Env + " && export remote_path=" + outputRemotePath + ";"
  1206. }
  1207. command += commandExport
  1208. //exec code
  1209. var parameters models.Parameters
  1210. var paramCode string
  1211. if len(paramSrc) != 0 {
  1212. err := json.Unmarshal([]byte(paramSrc), &parameters)
  1213. if err != nil {
  1214. log.Error("Failed to Unmarshal params: %s (%v)", paramSrc, err)
  1215. return command, err
  1216. }
  1217. for _, parameter := range parameters.Parameter {
  1218. paramCode += " --" + parameter.Label + "=" + parameter.Value
  1219. }
  1220. }
  1221. var commandCode string
  1222. if processorType == grampus.ProcessorTypeNPU {
  1223. paramCode += " --model_url=" + modelRemoteObsUrl
  1224. commandCode = "/bin/bash /home/work/run_train_for_openi.sh /home/work/openi.py " + grampus.NpuLocalLogUrl + paramCode + ";"
  1225. } else if processorType == grampus.ProcessorTypeGPU {
  1226. if pretrainModelFileName != "" {
  1227. paramCode += " --ckpt_url" + "=" + workDir + "pretrainmodel/" + pretrainModelFileName
  1228. }
  1229. commandCode = "cd " + workDir + "code/" + strings.ToLower(repoName) + ";python " + bootFile + paramCode + ";"
  1230. }
  1231. command += commandCode
  1232. //get exec result
  1233. commandGetRes := "result=$?;"
  1234. command += commandGetRes
  1235. //upload models
  1236. if processorType == grampus.ProcessorTypeNPU {
  1237. // no need to upload
  1238. } else if processorType == grampus.ProcessorTypeGPU {
  1239. commandUpload := "cd " + workDir + setting.Grampus.SyncScriptProject + "/;./uploader_for_gpu " + setting.Grampus.Env + " " + outputRemotePath + " " + workDir + "output/;"
  1240. command += commandUpload
  1241. }
  1242. //check exec result
  1243. commandCheckRes := "bash -c \"[[ $result -eq 0 ]] && exit 0 || exit -1\""
  1244. command += commandCheckRes
  1245. return command, nil
  1246. }
  1247. func processPretrainModelParameter(pretrainModelPath string, pretrainModelFileName string, commandDownload string) string {
  1248. commandDownloadTemp := commandDownload
  1249. if pretrainModelPath != "" {
  1250. commandDownloadTemp += " '" + pretrainModelPath + "' '" + pretrainModelFileName + "'"
  1251. }
  1252. commandDownloadTemp += ";"
  1253. return commandDownloadTemp
  1254. }
  1255. func downloadZipCode(ctx *context.Context, codePath, branchName string) error {
  1256. archiveType := git.ZIP
  1257. archivePath := codePath
  1258. if !com.IsDir(archivePath) {
  1259. if err := os.MkdirAll(archivePath, os.ModePerm); err != nil {
  1260. log.Error("MkdirAll failed:" + err.Error())
  1261. return err
  1262. }
  1263. }
  1264. // Get corresponding commit.
  1265. var (
  1266. commit *git.Commit
  1267. err error
  1268. )
  1269. gitRepo := ctx.Repo.GitRepo
  1270. if err != nil {
  1271. log.Error("OpenRepository failed:" + err.Error())
  1272. return err
  1273. }
  1274. if gitRepo.IsBranchExist(branchName) {
  1275. commit, err = gitRepo.GetBranchCommit(branchName)
  1276. if err != nil {
  1277. log.Error("GetBranchCommit failed:" + err.Error())
  1278. return err
  1279. }
  1280. } else {
  1281. log.Error("the branch is not exist: " + branchName)
  1282. return fmt.Errorf("The branch does not exist.")
  1283. }
  1284. archivePath = path.Join(archivePath, grampus.CodeArchiveName)
  1285. if !com.IsFile(archivePath) {
  1286. if err := commit.CreateArchive(archivePath, git.CreateArchiveOpts{
  1287. Format: archiveType,
  1288. Prefix: setting.Repository.PrefixArchiveFiles,
  1289. }); err != nil {
  1290. log.Error("CreateArchive failed:" + err.Error())
  1291. return err
  1292. }
  1293. }
  1294. return nil
  1295. }
  1296. func HandleTaskWithAiCenter(ctx *context.Context) {
  1297. log.Info("HandleTaskWithAiCenter start")
  1298. updateCounts := 0
  1299. cloudBrains, err := models.GetC2NetWithAiCenterWrongJob()
  1300. if err != nil {
  1301. log.Error("GetC2NetWithAiCenterWrongJob failed:" + err.Error())
  1302. return
  1303. }
  1304. if len(cloudBrains) == 0 {
  1305. log.Info("HandleC2NetWithAiCenterWrongJob:no task need handle")
  1306. return
  1307. }
  1308. cloudBrainCounts := len(cloudBrains)
  1309. for _, task := range cloudBrains {
  1310. result, err := grampus.GetJob(task.JobID)
  1311. if err != nil {
  1312. log.Error("GetJob failed:" + err.Error())
  1313. continue
  1314. }
  1315. if len(result.JobInfo.Tasks) != 0 {
  1316. if len(result.JobInfo.Tasks[0].CenterID) == 1 && len(result.JobInfo.Tasks[0].CenterName) == 1 {
  1317. task.AiCenter = result.JobInfo.Tasks[0].CenterID[0] + "+" + result.JobInfo.Tasks[0].CenterName[0]
  1318. }
  1319. err = models.UpdateJob(task)
  1320. if err != nil {
  1321. log.Error("UpdateJob failed:" + err.Error())
  1322. }
  1323. updateCounts++
  1324. }
  1325. }
  1326. r := make(map[string]interface{}, 0)
  1327. r["cloudBrainCounts"] = cloudBrainCounts
  1328. r["updateCounts"] = updateCounts
  1329. ctx.JSON(http.StatusOK, response.SuccessWithData(r))
  1330. }
  1331. func GrampusNotebookDebug(ctx *context.Context) {
  1332. result, err := grampus.GetNotebookJob(ctx.Cloudbrain.JobID)
  1333. if err != nil {
  1334. ctx.RenderWithErr(err.Error(), tplDebugJobIndex, nil)
  1335. return
  1336. }
  1337. if len(result.JobInfo.Tasks) > 0 {
  1338. ctx.Redirect(result.JobInfo.Tasks[0].Url + "?token=" + result.JobInfo.Tasks[0].Token)
  1339. return
  1340. }
  1341. ctx.NotFound("Can not find the job.", nil)
  1342. }
  1343. func GrampusNotebookRestart(ctx *context.Context) {
  1344. var id = ctx.Params(":id")
  1345. var resultCode = "-1"
  1346. var errorMsg = ""
  1347. var status = ""
  1348. var spec *models.Specification
  1349. task := ctx.Cloudbrain
  1350. if ctx.Written() {
  1351. return
  1352. }
  1353. for {
  1354. if task.Status != models.GrampusStatusStopped && task.Status != models.GrampusStatusSucceeded && task.Status != models.GrampusStatusFailed {
  1355. log.Error("the job(%s) is not stopped", task.JobName, ctx.Data["MsgID"])
  1356. errorMsg = "the job is not stopped"
  1357. break
  1358. }
  1359. count, err := cloudbrainTask.GetNotFinalStatusTaskCount(ctx.User.ID, models.TypeC2Net, string(models.JobTypeDebug), task.ComputeResource)
  1360. if err != nil {
  1361. log.Error("GetCloudbrainNotebookCountByUserID failed:%v", err, ctx.Data["MsgID"])
  1362. errorMsg = "system error"
  1363. break
  1364. } else {
  1365. if count >= 1 {
  1366. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  1367. resultCode = "2"
  1368. errorMsg = ctx.Tr("repo.cloudbrain.morethanonejob")
  1369. break
  1370. }
  1371. }
  1372. oldSpec, err := resource.GetCloudbrainSpec(task.ID)
  1373. if err != nil || oldSpec == nil {
  1374. log.Error("NotebookManage GetCloudbrainSpec error.%v", err)
  1375. errorMsg = "Resource specification not available"
  1376. break
  1377. }
  1378. computeSourceSimple := models.GPU
  1379. action := models.ActionCreateGrampusGPUDebugTask
  1380. if task.ComputeResource == models.NPUResource {
  1381. computeSourceSimple = models.NPU
  1382. action = models.ActionCreateGrampusNPUDebugTask
  1383. }
  1384. spec, err = resource.GetAndCheckSpec(ctx.User.ID, oldSpec.ID, models.FindSpecsOptions{
  1385. JobType: models.JobType(task.JobType),
  1386. ComputeResource: computeSourceSimple,
  1387. Cluster: models.C2NetCluster,
  1388. })
  1389. if err != nil || spec == nil {
  1390. log.Error("NotebookManage GetAndCheckSpec error.task.id = %d", task.ID)
  1391. errorMsg = "Resource specification not support any more"
  1392. break
  1393. }
  1394. if !account.IsPointBalanceEnough(ctx.User.ID, spec.UnitPrice) {
  1395. log.Error("point balance is not enough,userId=%d specId=%d", ctx.User.ID, spec.ID)
  1396. errorMsg = ctx.Tr("points.insufficient_points_balance")
  1397. break
  1398. }
  1399. createTime := timeutil.TimeStampNow()
  1400. res, err := grampus.RestartNotebookJob(task.JobID)
  1401. if err != nil {
  1402. log.Error("ManageNotebook2(%s) failed:%v", task.DisplayJobName, err.Error(), ctx.Data["MsgID"])
  1403. errorMsg = err.Error()
  1404. break
  1405. }
  1406. newTask := &models.Cloudbrain{
  1407. Status: res.Status,
  1408. UserID: task.UserID,
  1409. RepoID: task.RepoID,
  1410. JobID: res.NewId,
  1411. JobName: task.JobName,
  1412. DisplayJobName: task.DisplayJobName,
  1413. JobType: task.JobType,
  1414. Type: task.Type,
  1415. Uuid: task.Uuid,
  1416. Image: task.Image,
  1417. ComputeResource: task.ComputeResource,
  1418. Description: task.Description,
  1419. CreatedUnix: createTime,
  1420. UpdatedUnix: createTime,
  1421. Spec: spec,
  1422. }
  1423. err = models.RestartCloudbrain(task, newTask)
  1424. if err != nil {
  1425. log.Error("RestartCloudbrain(%s) failed:%v", task.JobName, err.Error(), ctx.Data["MsgID"])
  1426. errorMsg = "system error"
  1427. break
  1428. }
  1429. id = strconv.FormatInt(newTask.ID, 10)
  1430. status = res.Status
  1431. resultCode = "0"
  1432. notification.NotifyOtherTask(ctx.User, ctx.Repo.Repository, id, newTask.DisplayJobName, action)
  1433. break
  1434. }
  1435. ctx.JSON(200, map[string]string{
  1436. "result_code": resultCode,
  1437. "error_msg": errorMsg,
  1438. "status": status,
  1439. "id": id,
  1440. })
  1441. }