You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

cloudbrain.go 53 kB

4 years ago
5 years ago
3 years ago
4 years ago
5 years ago
5 years ago
3 years ago
5 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
4 years ago
3 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
4 years ago
4 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
5 years ago
4 years ago
5 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
5 years ago
4 years ago
4 years ago
5 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
5 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
5 years ago
3 years ago
3 years ago
5 years ago
3 years ago
3 years ago
5 years ago
3 years ago
5 years ago
3 years ago
5 years ago
3 years ago
5 years ago
4 years ago
3 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
5 years ago
4 years ago
5 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
5 years ago
3 years ago
3 years ago
3 years ago
5 years ago
5 years ago
5 years ago
3 years ago
3 years ago
5 years ago
5 years ago
3 years ago
3 years ago
5 years ago
3 years ago
5 years ago
5 years ago
5 years ago
3 years ago
4 years ago
4 years ago
5 years ago
3 years ago
4 years ago
4 years ago
5 years ago
3 years ago
4 years ago
5 years ago
4 years ago
3 years ago
3 years ago
4 years ago
4 years ago
4 years ago
5 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
3 years ago
4 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
3 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
5 years ago
4 years ago
4 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717
  1. package repo
  2. import (
  3. "bufio"
  4. "code.gitea.io/gitea/modules/timeutil"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "github.com/unknwon/i18n"
  9. "io"
  10. "net/http"
  11. "os"
  12. "regexp"
  13. "sort"
  14. "strconv"
  15. "strings"
  16. "time"
  17. "code.gitea.io/gitea/models"
  18. "code.gitea.io/gitea/modules/auth"
  19. "code.gitea.io/gitea/modules/base"
  20. "code.gitea.io/gitea/modules/cloudbrain"
  21. "code.gitea.io/gitea/modules/context"
  22. "code.gitea.io/gitea/modules/git"
  23. "code.gitea.io/gitea/modules/log"
  24. "code.gitea.io/gitea/modules/modelarts"
  25. "code.gitea.io/gitea/modules/setting"
  26. "code.gitea.io/gitea/modules/storage"
  27. "code.gitea.io/gitea/modules/util"
  28. )
  29. const (
  30. tplCloudBrainNew base.TplName = "repo/cloudbrain/new"
  31. tplCloudBrainShow base.TplName = "repo/cloudbrain/show"
  32. tplCloudBrainShowModels base.TplName = "repo/cloudbrain/models/index"
  33. tplCloudBrainBenchmarkIndex base.TplName = "repo/cloudbrain/benchmark/index"
  34. tplCloudBrainBenchmarkNew base.TplName = "repo/cloudbrain/benchmark/new"
  35. tplCloudBrainBenchmarkShow base.TplName = "repo/cloudbrain/benchmark/show"
  36. tplCloudBrainTrainJobNew base.TplName = "repo/cloudbrain/trainjob/new"
  37. tplCloudBrainTrainJobShow base.TplName = "repo/cloudbrain/trainjob/show"
  38. )
  39. var (
  40. gpuInfos *models.GpuInfos
  41. categories *models.Categories
  42. benchmarkTypes *models.BenchmarkTypes
  43. benchmarkGpuInfos *models.GpuInfos
  44. benchmarkResourceSpecs *models.ResourceSpecs
  45. trainGpuInfos *models.GpuInfos
  46. )
  47. const BENCHMARK_TYPE_CODE = "repo.cloudbrain.benchmark.types"
  48. var benchmarkTypesMap = make(map[string]*models.BenchmarkTypes, 0)
  49. var jobNamePattern = regexp.MustCompile(`^[a-z0-9][a-z0-9-_]{1,34}[a-z0-9-]$`)
  50. // MustEnableDataset check if repository enable internal cb
  51. func MustEnableCloudbrain(ctx *context.Context) {
  52. if !ctx.Repo.CanRead(models.UnitTypeCloudBrain) {
  53. ctx.NotFound("MustEnableCloudbrain", nil)
  54. return
  55. }
  56. }
  57. func cutString(str string, lens int) string {
  58. if len(str) < lens {
  59. return str
  60. }
  61. return str[:lens]
  62. }
  63. func jobNamePrefixValid(s string) string {
  64. lowStr := strings.ToLower(s)
  65. re := regexp.MustCompile(`[^a-z0-9_\\-]+`)
  66. removeSpecial := re.ReplaceAllString(lowStr, "")
  67. re = regexp.MustCompile(`^[_\\-]+`)
  68. return re.ReplaceAllString(removeSpecial, "")
  69. }
  70. func cloudBrainNewDataPrepare(ctx *context.Context) error {
  71. ctx.Data["PageIsCloudBrain"] = true
  72. t := time.Now()
  73. var displayJobName = jobNamePrefixValid(cutString(ctx.User.Name, 5)) + t.Format("2006010215") + strconv.Itoa(int(t.Unix()))[5:]
  74. ctx.Data["display_job_name"] = displayJobName
  75. result, err := cloudbrain.GetImages()
  76. if err != nil {
  77. ctx.Data["error"] = err.Error()
  78. log.Error("cloudbrain.GetImages failed:", err.Error(), ctx.Data["MsgID"])
  79. }
  80. for i, payload := range result.Payload.ImageInfo {
  81. if strings.HasPrefix(result.Payload.ImageInfo[i].Place, "192.168") {
  82. result.Payload.ImageInfo[i].PlaceView = payload.Place[strings.Index(payload.Place, "/"):len(payload.Place)]
  83. } else {
  84. result.Payload.ImageInfo[i].PlaceView = payload.Place
  85. }
  86. }
  87. ctx.Data["images"] = result.Payload.ImageInfo
  88. resultPublic, err := cloudbrain.GetPublicImages()
  89. if err != nil {
  90. ctx.Data["error"] = err.Error()
  91. log.Error("cloudbrain.GetPublicImages failed:", err.Error(), ctx.Data["MsgID"])
  92. }
  93. for i, payload := range resultPublic.Payload.ImageInfo {
  94. if strings.HasPrefix(resultPublic.Payload.ImageInfo[i].Place, "192.168") {
  95. resultPublic.Payload.ImageInfo[i].PlaceView = payload.Place[strings.Index(payload.Place, "/"):len(payload.Place)]
  96. } else {
  97. resultPublic.Payload.ImageInfo[i].PlaceView = payload.Place
  98. }
  99. }
  100. ctx.Data["public_images"] = resultPublic.Payload.ImageInfo
  101. attachs, err := models.GetAllUserAttachments(ctx.User.ID)
  102. if err != nil {
  103. log.Error("GetAllUserAttachments failed: %v", err, ctx.Data["MsgID"])
  104. return err
  105. }
  106. ctx.Data["attachments"] = attachs
  107. ctx.Data["command"] = cloudbrain.Command
  108. ctx.Data["code_path"] = cloudbrain.CodeMountPath
  109. ctx.Data["dataset_path"] = cloudbrain.DataSetMountPath
  110. ctx.Data["model_path"] = cloudbrain.ModelMountPath
  111. ctx.Data["benchmark_path"] = cloudbrain.BenchMarkMountPath
  112. ctx.Data["is_benchmark_enabled"] = setting.IsBenchmarkEnabled
  113. if categories == nil {
  114. json.Unmarshal([]byte(setting.BenchmarkCategory), &categories)
  115. }
  116. ctx.Data["benchmark_categories"] = categories.Category
  117. ctx.Data["benchmark_types"] = GetBenchmarkTypes(ctx).BenchmarkType
  118. if gpuInfos == nil {
  119. json.Unmarshal([]byte(setting.GpuTypes), &gpuInfos)
  120. }
  121. ctx.Data["gpu_types"] = gpuInfos.GpuInfo
  122. if trainGpuInfos == nil {
  123. json.Unmarshal([]byte(setting.TrainGpuTypes), &trainGpuInfos)
  124. }
  125. ctx.Data["train_gpu_types"] = trainGpuInfos.GpuInfo
  126. if benchmarkGpuInfos == nil {
  127. json.Unmarshal([]byte(setting.BenchmarkGpuTypes), &benchmarkGpuInfos)
  128. }
  129. ctx.Data["benchmark_gpu_types"] = benchmarkGpuInfos.GpuInfo
  130. if benchmarkResourceSpecs == nil {
  131. json.Unmarshal([]byte(setting.BenchmarkResourceSpecs), &benchmarkResourceSpecs)
  132. }
  133. ctx.Data["benchmark_resource_specs"] = benchmarkResourceSpecs.ResourceSpec
  134. if cloudbrain.ResourceSpecs == nil {
  135. json.Unmarshal([]byte(setting.ResourceSpecs), &cloudbrain.ResourceSpecs)
  136. }
  137. ctx.Data["resource_specs"] = cloudbrain.ResourceSpecs.ResourceSpec
  138. if cloudbrain.TrainResourceSpecs == nil {
  139. json.Unmarshal([]byte(setting.TrainResourceSpecs), &cloudbrain.TrainResourceSpecs)
  140. }
  141. ctx.Data["train_resource_specs"] = cloudbrain.TrainResourceSpecs.ResourceSpec
  142. ctx.Data["params"] = ""
  143. ctx.Data["branchName"] = ctx.Repo.BranchName
  144. ctx.Data["snn4imagenet_path"] = cloudbrain.Snn4imagenetMountPath
  145. ctx.Data["is_snn4imagenet_enabled"] = setting.IsSnn4imagenetEnabled
  146. ctx.Data["brainscore_path"] = cloudbrain.BrainScoreMountPath
  147. ctx.Data["is_brainscore_enabled"] = setting.IsBrainScoreEnabled
  148. ctx.Data["cloudbraintype"] = models.TypeCloudBrainOne
  149. return nil
  150. }
  151. func CloudBrainNew(ctx *context.Context) {
  152. err := cloudBrainNewDataPrepare(ctx)
  153. if err != nil {
  154. ctx.ServerError("get new cloudbrain info failed", err)
  155. return
  156. }
  157. ctx.HTML(200, tplCloudBrainNew)
  158. }
  159. func CloudBrainCreate(ctx *context.Context, form auth.CreateCloudBrainForm) {
  160. ctx.Data["PageIsCloudBrain"] = true
  161. displayJobName := form.DisplayJobName
  162. jobName := util.ConvertDisplayJobNameToJobName(displayJobName)
  163. image := form.Image
  164. uuid := form.Attachment
  165. jobType := form.JobType
  166. gpuQueue := form.GpuType
  167. codePath := setting.JobPath + jobName + cloudbrain.CodeMountPath
  168. resourceSpecId := form.ResourceSpecId
  169. branchName := form.BranchName
  170. repo := ctx.Repo.Repository
  171. tpl := tplCloudBrainNew
  172. command := cloudbrain.Command
  173. if jobType == string(models.JobTypeTrain) {
  174. tpl = tplCloudBrainTrainJobNew
  175. commandTrain, err := getTrainJobCommand(form)
  176. if err != nil {
  177. log.Error("getTrainJobCommand failed: %v", err)
  178. ctx.RenderWithErr(err.Error(), tpl, &form)
  179. return
  180. }
  181. command = commandTrain
  182. }
  183. tasks, err := models.GetCloudbrainsByDisplayJobName(repo.ID, jobType, displayJobName)
  184. if err == nil {
  185. if len(tasks) != 0 {
  186. log.Error("the job name did already exist", ctx.Data["MsgID"])
  187. cloudBrainNewDataPrepare(ctx)
  188. ctx.RenderWithErr("the job name did already exist", tpl, &form)
  189. return
  190. }
  191. } else {
  192. if !models.IsErrJobNotExist(err) {
  193. log.Error("system error, %v", err, ctx.Data["MsgID"])
  194. cloudBrainNewDataPrepare(ctx)
  195. ctx.RenderWithErr("system error", tpl, &form)
  196. return
  197. }
  198. }
  199. if !jobNamePattern.MatchString(displayJobName) {
  200. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_jobname_err"), tpl, &form)
  201. return
  202. }
  203. if jobType != string(models.JobTypeBenchmark) && jobType != string(models.JobTypeDebug) && jobType != string(models.JobTypeSnn4imagenet) && jobType != string(models.JobTypeBrainScore) && jobType != string(models.JobTypeTrain) {
  204. log.Error("jobtype error:", jobType, ctx.Data["MsgID"])
  205. cloudBrainNewDataPrepare(ctx)
  206. ctx.RenderWithErr("jobtype error", tpl, &form)
  207. return
  208. }
  209. count, err := models.GetCloudbrainCountByUserID(ctx.User.ID, jobType)
  210. if err != nil {
  211. log.Error("GetCloudbrainCountByUserID failed:%v", err, ctx.Data["MsgID"])
  212. cloudBrainNewDataPrepare(ctx)
  213. ctx.RenderWithErr("system error", tpl, &form)
  214. return
  215. } else {
  216. if count >= 1 {
  217. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  218. cloudBrainNewDataPrepare(ctx)
  219. ctx.RenderWithErr("you have already a running or waiting task, can not create more", tpl, &form)
  220. return
  221. }
  222. }
  223. if branchName == "" {
  224. branchName = cloudbrain.DefaultBranchName
  225. }
  226. downloadCode(repo, codePath, branchName)
  227. uploadCodeToMinio(codePath+"/", jobName, cloudbrain.CodeMountPath+"/")
  228. modelPath := setting.JobPath + jobName + cloudbrain.ModelMountPath + "/"
  229. mkModelPath(modelPath)
  230. uploadCodeToMinio(modelPath, jobName, cloudbrain.ModelMountPath+"/")
  231. benchmarkPath := setting.JobPath + jobName + cloudbrain.BenchMarkMountPath
  232. if setting.IsBenchmarkEnabled && jobType == string(models.JobTypeBenchmark) {
  233. var gpuType string
  234. for _, gpuInfo := range gpuInfos.GpuInfo {
  235. if gpuInfo.Queue == gpuQueue {
  236. gpuType = gpuInfo.Value
  237. }
  238. }
  239. downloadRateCode(repo, jobName, setting.BenchmarkOwner, setting.BenchmarkName, benchmarkPath, form.BenchmarkCategory, gpuType)
  240. uploadCodeToMinio(benchmarkPath+"/", jobName, cloudbrain.BenchMarkMountPath+"/")
  241. }
  242. snn4imagenetPath := setting.JobPath + jobName + cloudbrain.Snn4imagenetMountPath
  243. if setting.IsSnn4imagenetEnabled && jobType == string(models.JobTypeSnn4imagenet) {
  244. downloadRateCode(repo, jobName, setting.Snn4imagenetOwner, setting.Snn4imagenetName, snn4imagenetPath, "", "")
  245. uploadCodeToMinio(snn4imagenetPath+"/", jobName, cloudbrain.Snn4imagenetMountPath+"/")
  246. }
  247. brainScorePath := setting.JobPath + jobName + cloudbrain.BrainScoreMountPath
  248. if setting.IsBrainScoreEnabled && jobType == string(models.JobTypeBrainScore) {
  249. downloadRateCode(repo, jobName, setting.BrainScoreOwner, setting.BrainScoreName, brainScorePath, "", "")
  250. uploadCodeToMinio(brainScorePath+"/", jobName, cloudbrain.BrainScoreMountPath+"/")
  251. }
  252. err = cloudbrain.GenerateTask(ctx, displayJobName, jobName, image, command, uuid, storage.GetMinioPath(jobName, cloudbrain.CodeMountPath+"/"),
  253. storage.GetMinioPath(jobName, cloudbrain.ModelMountPath+"/"),
  254. storage.GetMinioPath(jobName, cloudbrain.BenchMarkMountPath+"/"), storage.GetMinioPath(jobName, cloudbrain.Snn4imagenetMountPath+"/"),
  255. storage.GetMinioPath(jobName, cloudbrain.BrainScoreMountPath+"/"), jobType, gpuQueue, form.Description, branchName, form.BootFile, form.Params,
  256. 0, 0, resourceSpecId)
  257. if err != nil {
  258. cloudBrainNewDataPrepare(ctx)
  259. ctx.RenderWithErr(err.Error(), tpl, &form)
  260. return
  261. }
  262. if jobType == string(models.JobTypeTrain) {
  263. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/train-job?listType=all")
  264. } else {
  265. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/debugjob?debugListType=all")
  266. }
  267. }
  268. func CloudBrainRestart(ctx *context.Context) {
  269. var ID = ctx.Params(":id")
  270. var resultCode = "0"
  271. var errorMsg = ""
  272. var status = string(models.JobWaiting)
  273. task := ctx.Cloudbrain
  274. for {
  275. if task.Status != string(models.JobStopped) && task.Status != string(models.JobSucceeded) && task.Status != string(models.JobFailed) {
  276. log.Error("the job(%s) is not stopped", task.JobName, ctx.Data["MsgID"])
  277. resultCode = "-1"
  278. errorMsg = "the job is not stopped"
  279. break
  280. }
  281. if task.Image == "" || task.GpuQueue == "" || task.Type != models.TypeCloudBrainOne {
  282. log.Error("the job(%s) version is too old", task.JobName, ctx.Data["MsgID"])
  283. resultCode = "-1"
  284. errorMsg = "the job's version is too old and can not be restarted"
  285. break
  286. }
  287. if !ctx.IsSigned || (ctx.User.ID != task.UserID && !ctx.IsUserSiteAdmin()) {
  288. log.Error("the user has no right ro restart the job", task.JobName, ctx.Data["MsgID"])
  289. resultCode = "-1"
  290. errorMsg = "you have no right to restart the job"
  291. break
  292. }
  293. count, err := models.GetCloudbrainCountByUserID(ctx.User.ID, string(models.JobTypeDebug))
  294. if err != nil {
  295. log.Error("GetCloudbrainCountByUserID failed:%v", err, ctx.Data["MsgID"])
  296. resultCode = "-1"
  297. errorMsg = "system error"
  298. break
  299. } else {
  300. if count >= 1 {
  301. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  302. resultCode = "-1"
  303. errorMsg = "you have already a running or waiting task, can not create more"
  304. break
  305. }
  306. }
  307. err = cloudbrain.RestartTask(ctx, task, &ID)
  308. if err != nil {
  309. log.Error("RestartTask failed:%v", err.Error(), ctx.Data["MsgID"])
  310. resultCode = "-1"
  311. errorMsg = "system error"
  312. break
  313. }
  314. break
  315. }
  316. ctx.JSON(200, map[string]string{
  317. "result_code": resultCode,
  318. "error_msg": errorMsg,
  319. "status": status,
  320. "id": ID,
  321. })
  322. }
  323. func CloudBrainBenchMarkShow(ctx *context.Context) {
  324. cloudBrainShow(ctx, tplCloudBrainBenchmarkShow, models.JobTypeBenchmark)
  325. }
  326. func CloudBrainShow(ctx *context.Context) {
  327. cloudBrainShow(ctx, tplCloudBrainShow, models.JobTypeDebug)
  328. }
  329. func CloudBrainTrainJobShow(ctx *context.Context) {
  330. cloudBrainShow(ctx, tplCloudBrainTrainJobShow, models.JobTypeTrain)
  331. }
  332. func cloudBrainShow(ctx *context.Context, tpName base.TplName, jobType models.JobType) {
  333. ctx.Data["PageIsCloudBrain"] = true
  334. debugListType := ctx.Query("debugListType")
  335. var task *models.Cloudbrain
  336. var err error
  337. if jobType == models.JobTypeTrain {
  338. task, err = models.GetCloudbrainByJobID(ctx.Params(":jobid"))
  339. } else {
  340. task, err = models.GetCloudbrainByID(ctx.Params(":id"))
  341. }
  342. if err != nil {
  343. log.Info("error:" + err.Error())
  344. ctx.Data["error"] = err.Error()
  345. }
  346. result, err := cloudbrain.GetJob(task.JobID)
  347. if err != nil {
  348. log.Info("error:" + err.Error())
  349. ctx.Data["error"] = err.Error()
  350. }
  351. if result != nil {
  352. jobRes, _ := models.ConvertToJobResultPayload(result.Payload)
  353. jobRes.Resource.Memory = strings.ReplaceAll(jobRes.Resource.Memory, "Mi", "MB")
  354. spec := "GPU数:" + strconv.Itoa(jobRes.Resource.NvidiaComGpu) + ",CPU数:" + strconv.Itoa(jobRes.Resource.CPU) + ",内存(MB):" + jobRes.Resource.Memory
  355. ctx.Data["resource_spec"] = spec
  356. if task.JobType == string(models.JobTypeTrain) {
  357. if trainGpuInfos == nil {
  358. json.Unmarshal([]byte(setting.TrainGpuTypes), &trainGpuInfos)
  359. }
  360. for _, resourceType := range trainGpuInfos.GpuInfo {
  361. if resourceType.Queue == jobRes.Config.GpuType {
  362. ctx.Data["resource_type"] = resourceType.Value
  363. }
  364. }
  365. }
  366. taskRoles := jobRes.TaskRoles
  367. if jobRes.JobStatus.State != string(models.JobFailed) {
  368. taskRes, _ := models.ConvertToTaskPod(taskRoles[cloudbrain.SubTaskName].(map[string]interface{}))
  369. ctx.Data["taskRes"] = taskRes
  370. task.Status = taskRes.TaskStatuses[0].State
  371. task.ContainerID = taskRes.TaskStatuses[0].ContainerID
  372. task.ContainerIp = taskRes.TaskStatuses[0].ContainerIP
  373. if task.StartTime == 0 && !taskRes.TaskStatuses[0].StartAt.IsZero() {
  374. task.StartTime = timeutil.TimeStamp(taskRes.TaskStatuses[0].StartAt.Unix())
  375. }
  376. err = models.UpdateJob(task)
  377. if err != nil {
  378. ctx.Data["error"] = err.Error()
  379. }
  380. } else {
  381. task.Status = jobRes.JobStatus.State
  382. taskRes := models.TaskPod{TaskStatuses: []models.TaskStatuses{
  383. {
  384. State: jobRes.JobStatus.State,
  385. },
  386. }}
  387. ctx.Data["taskRes"] = taskRes
  388. jobRes.JobStatus.StartTime = time.Unix(int64(task.CreatedUnix), 0).Format("2006-01-02 15:04:05")
  389. jobRes.JobStatus.EndTime = time.Unix(int64(task.UpdatedUnix), 0).Format("2006-01-02 15:04:05")
  390. }
  391. ctx.Data["result"] = jobRes
  392. } else {
  393. log.Info("error:" + err.Error())
  394. }
  395. user, err := models.GetUserByID(task.UserID)
  396. if err == nil {
  397. task.User = user
  398. }
  399. if task.BenchmarkTypeID > 0 {
  400. for _, benchmarkType := range GetBenchmarkTypes(ctx).BenchmarkType {
  401. if task.BenchmarkTypeID == benchmarkType.Id {
  402. ctx.Data["BenchmarkTypeName"] = benchmarkType.First
  403. for _, benchmarkChildType := range benchmarkType.Second {
  404. if task.BenchmarkChildTypeID == benchmarkChildType.Id {
  405. ctx.Data["BenchmarkChildTypeName"] = benchmarkChildType.Value
  406. break
  407. }
  408. }
  409. break
  410. }
  411. }
  412. }
  413. if task.TrainJobDuration == "" {
  414. if task.Duration == 0 {
  415. var duration int64
  416. if task.Status == string(models.JobRunning) {
  417. duration = time.Now().Unix() - int64(task.CreatedUnix)
  418. } else {
  419. duration = int64(task.UpdatedUnix) - int64(task.CreatedUnix)
  420. }
  421. task.Duration = duration
  422. }
  423. task.TrainJobDuration = models.ConvertDurationToStr(task.Duration)
  424. }
  425. ctx.Data["duration"] = task.TrainJobDuration
  426. if len(task.Parameters) > 0 {
  427. var parameters models.Parameters
  428. err := json.Unmarshal([]byte(task.Parameters), &parameters)
  429. if err != nil {
  430. log.Error("Failed to Unmarshal Parameters: %s (%v)", task.Parameters, err)
  431. task.Parameters = ""
  432. } else {
  433. if len(parameters.Parameter) > 0 {
  434. paramTemp := ""
  435. for _, Parameter := range parameters.Parameter {
  436. param := Parameter.Label + " = " + Parameter.Value + "; "
  437. paramTemp = paramTemp + param
  438. }
  439. task.Parameters = paramTemp[:len(paramTemp)-2]
  440. } else {
  441. task.Parameters = ""
  442. }
  443. }
  444. }
  445. ctx.Data["task"] = task
  446. ctx.Data["jobName"] = task.JobName
  447. ctx.Data["displayJobName"] = task.DisplayJobName
  448. version_list_task := make([]*models.Cloudbrain, 0)
  449. version_list_task = append(version_list_task, task)
  450. ctx.Data["version_list_task"] = version_list_task
  451. ctx.Data["debugListType"] = debugListType
  452. ctx.Data["canDownload"] = cloudbrain.CanDeleteJob(ctx, task)
  453. ctx.HTML(200, tpName)
  454. }
  455. func CloudBrainDebug(ctx *context.Context) {
  456. task := ctx.Cloudbrain
  457. debugUrl := setting.DebugServerHost + "jpylab_" + task.JobID + "_" + task.SubTaskName
  458. ctx.Redirect(debugUrl)
  459. }
  460. func CloudBrainCommitImage(ctx *context.Context, form auth.CommitImageCloudBrainForm) {
  461. err := cloudbrain.CommitImage(ctx.Cloudbrain.JobID, models.CommitImageParams{
  462. Ip: ctx.Cloudbrain.ContainerIp,
  463. TaskContainerId: ctx.Cloudbrain.ContainerID,
  464. ImageDescription: form.Description,
  465. ImageTag: form.Tag,
  466. })
  467. if err != nil {
  468. log.Error("CommitImage(%s) failed:%v", ctx.Cloudbrain.JobName, err.Error(), ctx.Data["msgID"])
  469. ctx.JSON(200, map[string]string{
  470. "result_code": "-1",
  471. "error_msg": "CommitImage failed",
  472. })
  473. return
  474. }
  475. ctx.JSON(200, map[string]string{
  476. "result_code": "0",
  477. "error_msg": "",
  478. })
  479. }
  480. func CloudBrainStop(ctx *context.Context) {
  481. var ID = ctx.Params(":id")
  482. var resultCode = "0"
  483. var errorMsg = ""
  484. var status = ""
  485. task := ctx.Cloudbrain
  486. for {
  487. if task.Status == string(models.JobStopped) || task.Status == string(models.JobFailed) || task.Status == string(models.JobSucceeded) {
  488. log.Error("the job(%s) has been stopped", task.JobName, ctx.Data["msgID"])
  489. resultCode = "-1"
  490. errorMsg = "system error"
  491. break
  492. }
  493. err := cloudbrain.StopJob(task.JobID)
  494. if err != nil {
  495. log.Error("StopJob(%s) failed:%v", task.JobName, err, ctx.Data["msgID"])
  496. resultCode = "-1"
  497. errorMsg = "system error"
  498. break
  499. }
  500. task.Status = string(models.JobStopped)
  501. if task.EndTime == 0 {
  502. task.EndTime = timeutil.TimeStampNow()
  503. }
  504. task.ComputeAndSetDuration()
  505. err = models.UpdateJob(task)
  506. if err != nil {
  507. log.Error("UpdateJob(%s) failed:%v", task.JobName, err, ctx.Data["msgID"])
  508. resultCode = "-1"
  509. errorMsg = "system error"
  510. break
  511. }
  512. status = task.Status
  513. break
  514. }
  515. ctx.JSON(200, map[string]interface{}{
  516. "result_code": resultCode,
  517. "error_msg": errorMsg,
  518. "status": status,
  519. "id": ID,
  520. "StatusOK": 0,
  521. })
  522. }
  523. func StopJobsByUserID(userID int64) {
  524. cloudBrains, err := models.GetCloudbrainsNeededStopByUserID(userID)
  525. if err != nil {
  526. log.Warn("Failed to get cloudBrain info", err)
  527. return
  528. }
  529. StopJobs(cloudBrains)
  530. }
  531. func StopJobsByRepoID(repoID int64) {
  532. cloudBrains, err := models.GetCloudbrainsNeededStopByRepoID(repoID)
  533. if err != nil {
  534. log.Warn("Failed to get cloudBrain info", err)
  535. return
  536. }
  537. StopJobs(cloudBrains)
  538. }
  539. /**
  540. */
  541. func StopJobs(cloudBrains []*models.Cloudbrain) {
  542. for _, taskInfo := range cloudBrains {
  543. if taskInfo.Type == models.TypeCloudBrainOne {
  544. err := retry(3, time.Second*30, func() error {
  545. return cloudbrain.StopJob(taskInfo.JobID)
  546. })
  547. logErrorAndUpdateJobStatus(err, taskInfo)
  548. } else {
  549. if taskInfo.JobType == string(models.JobTypeTrain) {
  550. err := retry(3, time.Second*30, func() error {
  551. _, err := modelarts.StopTrainJob(taskInfo.JobID, strconv.FormatInt(taskInfo.VersionID, 10))
  552. return err
  553. })
  554. logErrorAndUpdateJobStatus(err, taskInfo)
  555. } else {
  556. param := models.NotebookAction{
  557. Action: models.ActionStop,
  558. }
  559. err := retry(3, time.Second*30, func() error {
  560. _, err := modelarts.ManageNotebook(taskInfo.JobID, param)
  561. return err
  562. })
  563. logErrorAndUpdateJobStatus(err, taskInfo)
  564. }
  565. }
  566. }
  567. }
  568. func retry(attempts int, sleep time.Duration, f func() error) (err error) {
  569. for i := 0; i < attempts; i++ {
  570. if i > 0 {
  571. log.Warn("retrying after error:", err)
  572. time.Sleep(sleep)
  573. }
  574. err = f()
  575. if err == nil {
  576. return nil
  577. }
  578. }
  579. return fmt.Errorf("after %d attempts, last error: %s", attempts, err)
  580. }
  581. func logErrorAndUpdateJobStatus(err error, taskInfo *models.Cloudbrain) {
  582. if err != nil {
  583. log.Warn("Failed to stop cloudBrain job:"+taskInfo.JobID, err)
  584. } else {
  585. taskInfo.Status = string(models.JobStopped)
  586. if taskInfo.EndTime == 0 {
  587. taskInfo.EndTime = timeutil.TimeStampNow()
  588. }
  589. taskInfo.ComputeAndSetDuration()
  590. err = models.UpdateJob(taskInfo)
  591. if err != nil {
  592. log.Warn("UpdateJob failed", err)
  593. }
  594. }
  595. }
  596. func CloudBrainDel(ctx *context.Context) {
  597. var listType = ctx.Query("debugListType")
  598. if err := deleteCloudbrainJob(ctx); err != nil {
  599. log.Error("deleteCloudbrainJob failed: %v", err, ctx.Data["msgID"])
  600. ctx.ServerError(err.Error(), err)
  601. return
  602. }
  603. var isAdminPage = ctx.Query("isadminpage")
  604. if ctx.IsUserSiteAdmin() && isAdminPage == "true" {
  605. ctx.Redirect(setting.AppSubURL + "/admin" + "/cloudbrains")
  606. } else {
  607. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/debugjob?debugListType=" + listType)
  608. }
  609. }
  610. func deleteCloudbrainJob(ctx *context.Context) error {
  611. task := ctx.Cloudbrain
  612. if task.Status != string(models.JobStopped) && task.Status != string(models.JobFailed) && task.Status != string(models.JobSucceeded) {
  613. log.Error("the job(%s) has not been stopped", task.JobName, ctx.Data["msgID"])
  614. return errors.New("the job has not been stopped")
  615. }
  616. err := models.DeleteJob(task)
  617. if err != nil {
  618. log.Error("DeleteJob failed: %v", err, ctx.Data["msgID"])
  619. return err
  620. }
  621. deleteJobStorage(task.JobName, models.TypeCloudBrainOne)
  622. return nil
  623. }
  624. func CloudBrainShowModels(ctx *context.Context) {
  625. ctx.Data["PageIsCloudBrain"] = true
  626. ID := ctx.Params(":id")
  627. parentDir := ctx.Query("parentDir")
  628. dirArray := strings.Split(parentDir, "/")
  629. task, err := models.GetCloudbrainByID(ID)
  630. if err != nil {
  631. log.Error("no such job!", ctx.Data["msgID"])
  632. ctx.ServerError("no such job:", err)
  633. return
  634. }
  635. //get dirs
  636. dirs, err := GetModelDirs(task.JobName, parentDir)
  637. if err != nil {
  638. log.Error("GetModelDirs failed:%v", err.Error(), ctx.Data["msgID"])
  639. ctx.ServerError("GetModelDirs failed:", err)
  640. return
  641. }
  642. var fileInfos []storage.FileInfo
  643. err = json.Unmarshal([]byte(dirs), &fileInfos)
  644. if err != nil {
  645. log.Error("json.Unmarshal failed:%v", err.Error(), ctx.Data["msgID"])
  646. ctx.ServerError("json.Unmarshal failed:", err)
  647. return
  648. }
  649. for i, fileInfo := range fileInfos {
  650. temp, _ := time.Parse("2006-01-02 15:04:05", fileInfo.ModTime)
  651. fileInfos[i].ModTime = temp.Local().Format("2006-01-02 15:04:05")
  652. }
  653. sort.Slice(fileInfos, func(i, j int) bool {
  654. return fileInfos[i].ModTime > fileInfos[j].ModTime
  655. })
  656. ctx.Data["Path"] = dirArray
  657. ctx.Data["Dirs"] = fileInfos
  658. ctx.Data["task"] = task
  659. ctx.Data["ID"] = ID
  660. ctx.HTML(200, tplCloudBrainShowModels)
  661. }
  662. func GetPublicImages(ctx *context.Context) {
  663. getImages(ctx, cloudbrain.Public)
  664. }
  665. func GetCustomImages(ctx *context.Context) {
  666. getImages(ctx, cloudbrain.Custom)
  667. }
  668. func getImages(ctx *context.Context, imageType string) {
  669. log.Info("Get images begin")
  670. page := ctx.QueryInt("page")
  671. size := ctx.QueryInt("size")
  672. name := ctx.Query("name")
  673. getImagesResult, err := cloudbrain.GetImagesPageable(page, size, imageType, name)
  674. if err != nil {
  675. log.Error("Can not get images:%v", err)
  676. ctx.JSON(http.StatusOK, models.GetImagesPayload{
  677. Count: 0,
  678. TotalPages: 0,
  679. ImageInfo: []*models.ImageInfo{},
  680. })
  681. } else {
  682. ctx.JSON(http.StatusOK, getImagesResult.Payload)
  683. }
  684. log.Info("Get images end")
  685. }
  686. func GetModelDirs(jobName string, parentDir string) (string, error) {
  687. var req string
  688. modelActualPath := storage.GetMinioPath(jobName, cloudbrain.ModelMountPath+"/")
  689. if parentDir == "" {
  690. req = "baseDir=" + modelActualPath
  691. } else {
  692. req = "baseDir=" + modelActualPath + "&parentDir=" + parentDir
  693. }
  694. return getDirs(req)
  695. }
  696. func CloudBrainDownloadModel(ctx *context.Context) {
  697. parentDir := ctx.Query("parentDir")
  698. fileName := ctx.Query("fileName")
  699. jobName := ctx.Query("jobName")
  700. filePath := "jobs/" + jobName + "/model/" + parentDir
  701. url, err := storage.Attachments.PresignedGetURL(filePath, fileName)
  702. if err != nil {
  703. log.Error("PresignedGetURL failed: %v", err.Error(), ctx.Data["msgID"])
  704. ctx.ServerError("PresignedGetURL", err)
  705. return
  706. }
  707. http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusMovedPermanently)
  708. }
  709. func GetRate(ctx *context.Context) {
  710. isObjectDetcionAll := ctx.QueryBool("isObjectDetcionAll")
  711. if isObjectDetcionAll {
  712. ctx.Redirect(setting.BenchmarkServerHost + "?username=admin")
  713. return
  714. }
  715. var ID = ctx.Params(":id")
  716. job, err := models.GetCloudbrainByID(ID)
  717. if err != nil {
  718. ctx.ServerError("GetCloudbrainByJobID failed", err)
  719. return
  720. }
  721. if job.JobType == string(models.JobTypeBenchmark) {
  722. log.Info("url=" + setting.BenchmarkServerHost + "?username=" + ctx.User.Name)
  723. ctx.Redirect(setting.BenchmarkServerHost + "?username=" + ctx.User.Name)
  724. } else if job.JobType == string(models.JobTypeSnn4imagenet) {
  725. ctx.Redirect(setting.Snn4imagenetServerHost)
  726. } else if job.JobType == string(models.JobTypeBrainScore) {
  727. ctx.Redirect(setting.BrainScoreServerHost)
  728. } else {
  729. log.Error("JobType error:%s", job.JobType, ctx.Data["msgID"])
  730. }
  731. }
  732. func downloadCode(repo *models.Repository, codePath, branchName string) error {
  733. if err := git.Clone(repo.RepoPath(), codePath, git.CloneRepoOptions{Branch: branchName}); err != nil {
  734. log.Error("Failed to clone repository: %s (%v)", repo.FullName(), err)
  735. return err
  736. }
  737. configFile, err := os.OpenFile(codePath+"/.git/config", os.O_RDWR, 0666)
  738. if err != nil {
  739. log.Error("open file(%s) failed:%v", codePath+"/,git/config", err)
  740. return err
  741. }
  742. defer configFile.Close()
  743. pos := int64(0)
  744. reader := bufio.NewReader(configFile)
  745. for {
  746. line, err := reader.ReadString('\n')
  747. if err != nil {
  748. if err == io.EOF {
  749. log.Error("not find the remote-url")
  750. return nil
  751. } else {
  752. log.Error("read error: %v", err)
  753. return err
  754. }
  755. }
  756. if strings.Contains(line, "url") && strings.Contains(line, ".git") {
  757. originUrl := "\turl = " + repo.CloneLink().HTTPS + "\n"
  758. if len(line) > len(originUrl) {
  759. originUrl += strings.Repeat(" ", len(line)-len(originUrl))
  760. }
  761. bytes := []byte(originUrl)
  762. _, err := configFile.WriteAt(bytes, pos)
  763. if err != nil {
  764. log.Error("WriteAt failed:%v", err)
  765. return err
  766. }
  767. break
  768. }
  769. pos += int64(len(line))
  770. }
  771. return nil
  772. }
  773. func downloadRateCode(repo *models.Repository, taskName, rateOwnerName, rateRepoName, codePath, benchmarkCategory, gpuType string) error {
  774. err := os.MkdirAll(codePath, os.ModePerm)
  775. if err != nil {
  776. log.Error("mkdir codePath failed", err.Error())
  777. return err
  778. }
  779. repoExt, err := models.GetRepositoryByOwnerAndName(rateOwnerName, rateRepoName)
  780. if err != nil {
  781. log.Error("GetRepositoryByOwnerAndName(%s) failed", rateRepoName, err.Error())
  782. return err
  783. }
  784. if err := git.Clone(repoExt.RepoPath(), codePath, git.CloneRepoOptions{}); err != nil {
  785. log.Error("Failed to clone repository: %s (%v)", repoExt.FullName(), err)
  786. return err
  787. }
  788. fileName := codePath + cloudbrain.TaskInfoName
  789. f, err := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.ModePerm)
  790. if err != nil {
  791. log.Error("OpenFile failed", err.Error())
  792. return err
  793. }
  794. defer f.Close()
  795. data, err := json.Marshal(models.TaskInfo{
  796. Username: repo.Owner.Name,
  797. TaskName: taskName,
  798. CodeName: repo.Name,
  799. BenchmarkCategory: strings.Split(benchmarkCategory, ","),
  800. CodeLink: strings.TrimSuffix(repo.CloneLink().HTTPS, ".git"),
  801. GpuType: gpuType,
  802. })
  803. if err != nil {
  804. log.Error("json.Marshal failed", err.Error())
  805. return err
  806. }
  807. _, err = f.Write(data)
  808. if err != nil {
  809. log.Error("WriteString failed", err.Error())
  810. return err
  811. }
  812. return nil
  813. }
  814. func uploadCodeToMinio(codePath, jobName, parentDir string) error {
  815. files, err := readDir(codePath)
  816. if err != nil {
  817. log.Error("readDir(%s) failed: %s", codePath, err.Error())
  818. return err
  819. }
  820. for _, file := range files {
  821. if file.IsDir() {
  822. if err = uploadCodeToMinio(codePath+file.Name()+"/", jobName, parentDir+file.Name()+"/"); err != nil {
  823. log.Error("uploadCodeToMinio(%s) failed: %s", file.Name(), err.Error())
  824. return err
  825. }
  826. } else {
  827. destObject := setting.CBCodePathPrefix + jobName + parentDir + file.Name()
  828. sourceFile := codePath + file.Name()
  829. err = storage.Attachments.UploadObject(destObject, sourceFile)
  830. if err != nil {
  831. log.Error("UploadObject(%s) failed: %s", file.Name(), err.Error())
  832. return err
  833. }
  834. }
  835. }
  836. return nil
  837. }
  838. func mkModelPath(modelPath string) error {
  839. err := os.MkdirAll(modelPath, os.ModePerm)
  840. if err != nil {
  841. log.Error("MkdirAll(%s) failed:%v", modelPath, err)
  842. return err
  843. }
  844. fileName := modelPath + "README"
  845. f, err := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.ModePerm)
  846. if err != nil {
  847. log.Error("OpenFile failed", err.Error())
  848. return err
  849. }
  850. defer f.Close()
  851. _, err = f.WriteString("You can put the model file into this directory and download it by the web page.")
  852. if err != nil {
  853. log.Error("WriteString failed", err.Error())
  854. return err
  855. }
  856. return nil
  857. }
  858. func deleteJobStorage(jobName string, cloudbrainType int) error {
  859. //delete local
  860. localJobPath := setting.JobPath + jobName
  861. err := os.RemoveAll(localJobPath)
  862. if err != nil {
  863. log.Error("RemoveAll(%s) failed:%v", localJobPath, err)
  864. }
  865. //delete oss
  866. if cloudbrainType == models.TypeCloudBrainOne {
  867. dirPath := setting.CBCodePathPrefix + jobName + "/"
  868. err = storage.Attachments.DeleteDir(dirPath)
  869. if err != nil {
  870. log.Error("DeleteDir(%s) failed:%v", localJobPath, err)
  871. }
  872. } else if cloudbrainType == models.TypeCloudBrainTwo {
  873. //dirPath := setting.CodePathPrefix + jobName + "/"
  874. //err = storage.ObsRemoveObject(setting.Bucket, dirPath)
  875. //if err != nil {
  876. // log.Error("ObsRemoveObject(%s) failed:%v", localJobPath, err)
  877. //}
  878. log.Info("no need to delete")
  879. } else {
  880. log.Error("cloudbrainType(%d) error", cloudbrainType)
  881. }
  882. return nil
  883. }
  884. func SyncCloudbrainStatus() {
  885. cloudBrains, err := models.GetCloudBrainUnStoppedJob()
  886. if err != nil {
  887. log.Error("GetCloudBrainUnStoppedJob failed:", err.Error())
  888. return
  889. }
  890. for _, task := range cloudBrains {
  891. if task.Type == models.TypeCloudBrainOne {
  892. result, err := cloudbrain.GetJob(task.JobID)
  893. if err != nil {
  894. log.Error("GetJob(%s) failed:%v", task.JobName, err)
  895. continue
  896. }
  897. if result != nil {
  898. jobRes, _ := models.ConvertToJobResultPayload(result.Payload)
  899. taskRoles := jobRes.TaskRoles
  900. taskRes, _ := models.ConvertToTaskPod(taskRoles[cloudbrain.SubTaskName].(map[string]interface{}))
  901. task.Status = taskRes.TaskStatuses[0].State
  902. if task.Status != string(models.JobWaiting) {
  903. task.Duration = time.Now().Unix() - taskRes.TaskStatuses[0].StartAt.Unix()
  904. if task.StartTime == 0 && !taskRes.TaskStatuses[0].StartAt.IsZero() {
  905. task.StartTime = timeutil.TimeStamp(taskRes.TaskStatuses[0].StartAt.Unix())
  906. }
  907. if task.EndTime == 0 && models.IsCloudBrainOneDebugJobTerminal(task.Status) {
  908. task.EndTime = timeutil.TimeStampNow()
  909. }
  910. task.ComputeAndSetDuration()
  911. err = models.UpdateJob(task)
  912. if err != nil {
  913. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  914. }
  915. var maxDuration int64
  916. if task.JobType == string(models.JobTypeBenchmark) {
  917. maxDuration = setting.BenchmarkMaxDuration
  918. } else {
  919. maxDuration = setting.MaxDuration
  920. }
  921. if task.Duration >= maxDuration {
  922. log.Info("begin to stop job(%s), because of the duration", task.JobName)
  923. err = cloudbrain.StopJob(task.JobID)
  924. if err != nil {
  925. log.Error("StopJob(%s) failed:%v", task.JobName, err)
  926. continue
  927. }
  928. task.Status = string(models.JobStopped)
  929. if task.EndTime == 0 {
  930. task.EndTime = timeutil.TimeStampNow()
  931. }
  932. task.ComputeAndSetDuration()
  933. err = models.UpdateJob(task)
  934. if err != nil {
  935. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  936. }
  937. }
  938. }
  939. }
  940. } else if task.Type == models.TypeCloudBrainTwo {
  941. if task.JobType == string(models.JobTypeDebug) {
  942. //result, err := modelarts.GetJob(task.JobID)
  943. result, err := modelarts.GetNotebook2(task.JobID)
  944. if err != nil {
  945. log.Error("GetJob(%s) failed:%v", task.JobName, err)
  946. continue
  947. }
  948. if result != nil {
  949. task.Status = result.Status
  950. if task.StartTime == 0 && result.Lease.UpdateTime > 0 {
  951. task.StartTime = timeutil.TimeStamp(result.Lease.UpdateTime / 1000)
  952. }
  953. if task.EndTime == 0 && models.IsModelArtsDebugJobTerminal(task.Status) {
  954. task.EndTime = timeutil.TimeStampNow()
  955. }
  956. task.ComputeAndSetDuration()
  957. err = models.UpdateJob(task)
  958. if err != nil {
  959. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  960. continue
  961. }
  962. }
  963. } else if task.JobType == string(models.JobTypeTrain) {
  964. result, err := modelarts.GetTrainJob(task.JobID, strconv.FormatInt(task.VersionID, 10))
  965. if err != nil {
  966. log.Error("GetTrainJob(%s) failed:%v", task.JobName, err)
  967. continue
  968. }
  969. if result != nil {
  970. task.Status = modelarts.TransTrainJobStatus(result.IntStatus)
  971. task.Duration = result.Duration / 1000
  972. task.TrainJobDuration = result.TrainJobDuration
  973. if task.StartTime == 0 && result.StartTime > 0 {
  974. task.StartTime = timeutil.TimeStamp(result.StartTime / 1000)
  975. }
  976. task.TrainJobDuration = models.ConvertDurationToStr(task.Duration)
  977. if task.EndTime == 0 && models.IsTrainJobTerminal(task.Status) && task.StartTime > 0 {
  978. task.EndTime = task.StartTime.Add(task.Duration)
  979. }
  980. err = models.UpdateJob(task)
  981. if err != nil {
  982. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  983. continue
  984. }
  985. }
  986. } else {
  987. log.Error("task.JobType(%s) is error:%s", task.JobName, task.JobType)
  988. }
  989. } else {
  990. log.Error("task.Type(%s) is error:%d", task.JobName, task.Type)
  991. }
  992. }
  993. return
  994. }
  995. func HandleTaskWithNoDuration(ctx *context.Context) {
  996. log.Info("HandleTaskWithNoDuration start")
  997. count := 0
  998. for {
  999. cloudBrains, err := models.GetStoppedJobWithNoDurationJob()
  1000. if err != nil {
  1001. log.Error("HandleTaskWithNoTrainJobDuration failed:", err.Error())
  1002. break
  1003. }
  1004. if len(cloudBrains) == 0 {
  1005. log.Info("HandleTaskWithNoTrainJobDuration:no task need handle")
  1006. break
  1007. }
  1008. handleNoDurationTask(cloudBrains)
  1009. count += len(cloudBrains)
  1010. if len(cloudBrains) < 100 {
  1011. log.Info("HandleTaskWithNoTrainJobDuration:task less than 100")
  1012. break
  1013. }
  1014. }
  1015. log.Info("HandleTaskWithNoTrainJobDuration:count=%d", count)
  1016. ctx.JSON(200, "success")
  1017. }
  1018. func handleNoDurationTask(cloudBrains []*models.Cloudbrain) {
  1019. for _, task := range cloudBrains {
  1020. log.Info("Handle job ,%+v", task)
  1021. if task.Type == models.TypeCloudBrainOne {
  1022. result, err := cloudbrain.GetJob(task.JobID)
  1023. if err != nil {
  1024. log.Error("GetJob(%s) failed:%v", task.JobName, err)
  1025. updateDefaultDuration(task)
  1026. continue
  1027. }
  1028. if result != nil {
  1029. if result.Msg != "success" {
  1030. updateDefaultDuration(task)
  1031. continue
  1032. }
  1033. jobRes, err := models.ConvertToJobResultPayload(result.Payload)
  1034. if err != nil || len(jobRes.TaskRoles) == 0 {
  1035. updateDefaultDuration(task)
  1036. continue
  1037. }
  1038. taskRoles := jobRes.TaskRoles
  1039. taskRes, err := models.ConvertToTaskPod(taskRoles[cloudbrain.SubTaskName].(map[string]interface{}))
  1040. if err != nil || len(taskRes.TaskStatuses) == 0 {
  1041. updateDefaultDuration(task)
  1042. continue
  1043. }
  1044. task.Status = taskRes.TaskStatuses[0].State
  1045. startTime := taskRes.TaskStatuses[0].StartAt.Unix()
  1046. endTime := taskRes.TaskStatuses[0].FinishedAt.Unix()
  1047. log.Info("task startTime = %v endTime= %v ,jobId=%d", startTime, endTime, task.ID)
  1048. if startTime > 0 {
  1049. task.StartTime = timeutil.TimeStamp(startTime)
  1050. } else {
  1051. task.StartTime = task.CreatedUnix
  1052. }
  1053. if endTime > 0 {
  1054. task.EndTime = timeutil.TimeStamp(endTime)
  1055. } else {
  1056. task.EndTime = task.UpdatedUnix
  1057. }
  1058. if task.EndTime < task.StartTime {
  1059. log.Info("endTime[%v] is less than starTime[%v],jobId=%d", task.EndTime, task.StartTime, task.ID)
  1060. st := task.StartTime
  1061. task.StartTime = task.EndTime
  1062. task.EndTime = st
  1063. }
  1064. task.ComputeAndSetDuration()
  1065. err = models.UpdateJob(task)
  1066. if err != nil {
  1067. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1068. }
  1069. }
  1070. } else if task.Type == models.TypeCloudBrainTwo {
  1071. if task.JobType == string(models.JobTypeDebug) {
  1072. //result, err := modelarts.GetJob(task.JobID)
  1073. result, err := modelarts.GetNotebook2(task.JobID)
  1074. if err != nil {
  1075. log.Error("GetJob(%s) failed:%v", task.JobName, err)
  1076. task.StartTime = task.CreatedUnix
  1077. task.EndTime = task.UpdatedUnix
  1078. task.ComputeAndSetDuration()
  1079. err = models.UpdateJob(task)
  1080. if err != nil {
  1081. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1082. }
  1083. continue
  1084. }
  1085. if result != nil {
  1086. task.Status = result.Status
  1087. startTime := result.Lease.CreateTime
  1088. duration := result.Lease.Duration / 1000
  1089. if startTime > 0 {
  1090. task.StartTime = timeutil.TimeStamp(startTime)
  1091. task.EndTime = task.StartTime.Add(duration)
  1092. }
  1093. task.ComputeAndSetDuration()
  1094. err = models.UpdateJob(task)
  1095. if err != nil {
  1096. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1097. continue
  1098. }
  1099. }
  1100. } else if task.JobType == string(models.JobTypeTrain) {
  1101. result, err := modelarts.GetTrainJob(task.JobID, strconv.FormatInt(task.VersionID, 10))
  1102. if err != nil {
  1103. log.Error("GetTrainJob(%s) failed:%v", task.JobName, err)
  1104. continue
  1105. }
  1106. if result != nil {
  1107. startTime := result.StartTime / 1000
  1108. if startTime > 0 {
  1109. task.StartTime = timeutil.TimeStamp(startTime)
  1110. task.EndTime = task.StartTime.Add(result.Duration / 1000)
  1111. }
  1112. task.ComputeAndSetDuration()
  1113. err = models.UpdateJob(task)
  1114. if err != nil {
  1115. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1116. continue
  1117. }
  1118. }
  1119. } else {
  1120. log.Error("task.JobType(%s) is error:%s", task.JobName, task.JobType)
  1121. }
  1122. } else {
  1123. log.Error("task.Type(%s) is error:%d", task.JobName, task.Type)
  1124. }
  1125. }
  1126. }
  1127. func updateDefaultDuration(task *models.Cloudbrain) {
  1128. log.Info("updateDefaultDuration: taskId=%d", task.ID)
  1129. task.StartTime = task.CreatedUnix
  1130. task.EndTime = task.UpdatedUnix
  1131. task.ComputeAndSetDuration()
  1132. err := models.UpdateJob(task)
  1133. if err != nil {
  1134. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1135. }
  1136. }
  1137. func CloudBrainBenchmarkIndex(ctx *context.Context) {
  1138. MustEnableCloudbrain(ctx)
  1139. repo := ctx.Repo.Repository
  1140. page := ctx.QueryInt("page")
  1141. if page <= 0 {
  1142. page = 1
  1143. }
  1144. var jobTypes []string
  1145. jobTypes = append(jobTypes, string(models.JobTypeBenchmark))
  1146. ciTasks, count, err := models.Cloudbrains(&models.CloudbrainsOptions{
  1147. ListOptions: models.ListOptions{
  1148. Page: page,
  1149. PageSize: setting.UI.IssuePagingNum,
  1150. },
  1151. RepoID: repo.ID,
  1152. Type: models.TypeCloudBrainOne,
  1153. JobTypes: jobTypes,
  1154. })
  1155. if err != nil {
  1156. ctx.ServerError("Get debugjob faild:", err)
  1157. return
  1158. }
  1159. for i, task := range ciTasks {
  1160. ciTasks[i].CanDel = cloudbrain.CanDeleteJob(ctx, &task.Cloudbrain)
  1161. ciTasks[i].Cloudbrain.ComputeResource = task.ComputeResource
  1162. if ciTasks[i].TrainJobDuration == "" {
  1163. if ciTasks[i].Duration == 0 {
  1164. var duration int64
  1165. if task.Status == string(models.JobRunning) {
  1166. duration = time.Now().Unix() - int64(task.Cloudbrain.CreatedUnix)
  1167. } else {
  1168. duration = int64(task.Cloudbrain.UpdatedUnix) - int64(task.Cloudbrain.CreatedUnix)
  1169. }
  1170. ciTasks[i].Duration = duration
  1171. }
  1172. ciTasks[i].TrainJobDuration = models.ConvertDurationToStr(ciTasks[i].Duration)
  1173. }
  1174. ciTasks[i].BenchmarkTypeName = ""
  1175. if task.BenchmarkTypeID > 0 {
  1176. for _, benchmarkType := range GetBenchmarkTypes(ctx).BenchmarkType {
  1177. if task.BenchmarkTypeID == benchmarkType.Id {
  1178. ciTasks[i].BenchmarkTypeRankLink = benchmarkType.RankLink
  1179. ciTasks[i].BenchmarkTypeName = benchmarkType.First
  1180. break
  1181. }
  1182. }
  1183. }
  1184. }
  1185. pager := context.NewPagination(int(count), setting.UI.IssuePagingNum, page, 5)
  1186. ctx.Data["Page"] = pager
  1187. ctx.Data["PageIsCloudBrain"] = true
  1188. ctx.Data["Tasks"] = ciTasks
  1189. ctx.Data["CanCreate"] = cloudbrain.CanCreateOrDebugJob(ctx)
  1190. ctx.Data["RepoIsEmpty"] = repo.IsEmpty
  1191. ctx.HTML(200, tplCloudBrainBenchmarkIndex)
  1192. }
  1193. func GetChildTypes(ctx *context.Context) {
  1194. benchmarkTypeID := ctx.QueryInt("benchmark_type_id")
  1195. re := make(map[string]interface{})
  1196. for {
  1197. var isExist bool
  1198. for _, benchmarkType := range GetBenchmarkTypes(ctx).BenchmarkType {
  1199. if benchmarkTypeID == benchmarkType.Id {
  1200. isExist = true
  1201. re["child_types"] = benchmarkType.Second
  1202. re["result_code"] = "0"
  1203. break
  1204. }
  1205. }
  1206. if !isExist {
  1207. re["result_code"] = "1"
  1208. log.Error("no such benchmark_type_id", ctx.Data["MsgID"])
  1209. re["errMsg"] = "system error"
  1210. break
  1211. }
  1212. break
  1213. }
  1214. ctx.JSON(200, re)
  1215. }
  1216. func CloudBrainBenchmarkNew(ctx *context.Context) {
  1217. ctx.Data["description"] = ""
  1218. ctx.Data["benchmarkTypeID"] = -1
  1219. ctx.Data["benchmark_child_types_id_hidden"] = -1
  1220. err := cloudBrainNewDataPrepare(ctx)
  1221. if err != nil {
  1222. ctx.ServerError("get new cloudbrain info failed", err)
  1223. return
  1224. }
  1225. ctx.HTML(200, tplCloudBrainBenchmarkNew)
  1226. }
  1227. func getBenchmarkAttachment(benchmarkTypeID, benchmarkChildTypeID int, ctx *context.Context) (*models.BenchmarkDataset, error) {
  1228. var childInfo *models.BenchmarkDataset
  1229. var isExist bool
  1230. for _, benchmarkType := range GetBenchmarkTypes(ctx).BenchmarkType {
  1231. if benchmarkType.Id == benchmarkTypeID {
  1232. for _, childType := range benchmarkType.Second {
  1233. if childType.Id == benchmarkChildTypeID {
  1234. childInfo = childType
  1235. isExist = true
  1236. break
  1237. }
  1238. }
  1239. break
  1240. }
  1241. }
  1242. if !isExist {
  1243. log.Error("no such benchmark_type_id&benchmark_child_type_id")
  1244. return childInfo, errors.New("no such benchmark_type_id&benchmark_child_type_id")
  1245. }
  1246. return childInfo, nil
  1247. }
  1248. func getBenchmarkGpuQueue(gpuQueue string) (string, error) {
  1249. queue := ""
  1250. if benchmarkGpuInfos == nil {
  1251. if err := json.Unmarshal([]byte(setting.BenchmarkGpuTypes), &benchmarkGpuInfos); err != nil {
  1252. log.Error("json.Unmarshal BenchmarkGpuTypes(%s) failed:%v", setting.BenchmarkGpuTypes, err)
  1253. return queue, err
  1254. }
  1255. }
  1256. var isExist bool
  1257. for _, gpuInfo := range benchmarkGpuInfos.GpuInfo {
  1258. if gpuQueue == gpuInfo.Queue {
  1259. isExist = true
  1260. queue = gpuQueue
  1261. break
  1262. }
  1263. }
  1264. if !isExist {
  1265. log.Error("no such gpuQueue, %s", gpuQueue)
  1266. return queue, errors.New("no such gpuQueue")
  1267. }
  1268. return queue, nil
  1269. }
  1270. func getBenchmarkResourceSpec(resourceSpecID int) (int, error) {
  1271. var id int
  1272. if benchmarkResourceSpecs == nil {
  1273. if err := json.Unmarshal([]byte(setting.BenchmarkResourceSpecs), &benchmarkResourceSpecs); err != nil {
  1274. log.Error("json.Unmarshal BenchmarkResourceSpecs(%s) failed:%v", setting.BenchmarkResourceSpecs, err)
  1275. return id, err
  1276. }
  1277. }
  1278. var isExist bool
  1279. for _, resourceSpec := range benchmarkResourceSpecs.ResourceSpec {
  1280. if resourceSpecID == resourceSpec.Id {
  1281. isExist = true
  1282. id = resourceSpecID
  1283. break
  1284. }
  1285. }
  1286. if !isExist {
  1287. log.Error("no such resourceSpecID, %d", resourceSpecID)
  1288. return id, errors.New("no such resourceSpec")
  1289. }
  1290. return id, nil
  1291. }
  1292. func CloudBrainBenchmarkCreate(ctx *context.Context, form auth.CreateCloudBrainForm) {
  1293. ctx.Data["PageIsCloudBrain"] = true
  1294. displayJobName := form.DisplayJobName
  1295. jobName := util.ConvertDisplayJobNameToJobName(displayJobName)
  1296. image := form.Image
  1297. gpuQueue := form.GpuType
  1298. command := cloudbrain.CommandBenchmark
  1299. codePath := setting.JobPath + jobName + cloudbrain.CodeMountPath
  1300. resourceSpecId := cloudbrain.BenchMarkResourceID
  1301. benchmarkTypeID := form.BenchmarkTypeID
  1302. benchmarkChildTypeID := form.BenchmarkChildTypeID
  1303. ctx.Data["description"] = form.Description
  1304. ctx.Data["benchmarkTypeID"] = benchmarkTypeID
  1305. ctx.Data["benchmark_child_types_id_hidden"] = benchmarkChildTypeID
  1306. repo := ctx.Repo.Repository
  1307. tasks, err := models.GetCloudbrainsByDisplayJobName(repo.ID, string(models.JobTypeBenchmark), displayJobName)
  1308. if err == nil {
  1309. if len(tasks) != 0 {
  1310. log.Error("the job name did already exist", ctx.Data["MsgID"])
  1311. cloudBrainNewDataPrepare(ctx)
  1312. ctx.RenderWithErr("the job name did already exist", tplCloudBrainBenchmarkNew, &form)
  1313. return
  1314. }
  1315. } else {
  1316. if !models.IsErrJobNotExist(err) {
  1317. log.Error("system error, %v", err, ctx.Data["MsgID"])
  1318. cloudBrainNewDataPrepare(ctx)
  1319. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  1320. return
  1321. }
  1322. }
  1323. if !jobNamePattern.MatchString(jobName) {
  1324. cloudBrainNewDataPrepare(ctx)
  1325. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_jobname_err"), tplCloudBrainBenchmarkNew, &form)
  1326. return
  1327. }
  1328. childInfo, err := getBenchmarkAttachment(benchmarkTypeID, benchmarkChildTypeID, ctx)
  1329. if err != nil {
  1330. log.Error("getBenchmarkAttachment failed:%v", err, ctx.Data["MsgID"])
  1331. cloudBrainNewDataPrepare(ctx)
  1332. ctx.RenderWithErr("benchmark type error", tplCloudBrainBenchmarkNew, &form)
  1333. return
  1334. }
  1335. _, err = getBenchmarkGpuQueue(gpuQueue)
  1336. if err != nil {
  1337. log.Error("getBenchmarkGpuQueue failed:%v", err, ctx.Data["MsgID"])
  1338. cloudBrainNewDataPrepare(ctx)
  1339. ctx.RenderWithErr("gpu queue error", tplCloudBrainBenchmarkNew, &form)
  1340. return
  1341. }
  1342. _, err = getBenchmarkResourceSpec(resourceSpecId)
  1343. if err != nil {
  1344. log.Error("getBenchmarkResourceSpec failed:%v", err, ctx.Data["MsgID"])
  1345. cloudBrainNewDataPrepare(ctx)
  1346. ctx.RenderWithErr("resource spec error", tplCloudBrainBenchmarkNew, &form)
  1347. return
  1348. }
  1349. count, err := models.GetCloudbrainCountByUserID(ctx.User.ID, string(models.JobTypeBenchmark))
  1350. if err != nil {
  1351. log.Error("GetCloudbrainCountByUserID failed:%v", err, ctx.Data["MsgID"])
  1352. cloudBrainNewDataPrepare(ctx)
  1353. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  1354. return
  1355. } else {
  1356. if count >= 1 {
  1357. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  1358. cloudBrainNewDataPrepare(ctx)
  1359. ctx.RenderWithErr("you have already a running or waiting task, can not create more", tplCloudBrainBenchmarkNew, &form)
  1360. return
  1361. }
  1362. }
  1363. os.RemoveAll(codePath)
  1364. if err := downloadCode(repo, codePath, cloudbrain.DefaultBranchName); err != nil {
  1365. log.Error("downloadCode failed, %v", err, ctx.Data["MsgID"])
  1366. cloudBrainNewDataPrepare(ctx)
  1367. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  1368. return
  1369. }
  1370. if _, err := os.Stat(codePath + "/train.py"); err != nil {
  1371. if os.IsNotExist(err) {
  1372. // file does not exist
  1373. log.Error("train.py does not exist, %v", err, ctx.Data["MsgID"])
  1374. cloudBrainNewDataPrepare(ctx)
  1375. ctx.RenderWithErr("train.py does not exist", tplCloudBrainBenchmarkNew, &form)
  1376. } else {
  1377. log.Error("Stat failed, %v", err, ctx.Data["MsgID"])
  1378. cloudBrainNewDataPrepare(ctx)
  1379. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  1380. }
  1381. return
  1382. } else if _, err := os.Stat(codePath + "/test.py"); err != nil {
  1383. if os.IsNotExist(err) {
  1384. // file does not exist
  1385. log.Error("test.py does not exist, %v", err, ctx.Data["MsgID"])
  1386. cloudBrainNewDataPrepare(ctx)
  1387. ctx.RenderWithErr("test.py does not exist", tplCloudBrainBenchmarkNew, &form)
  1388. } else {
  1389. log.Error("Stat failed, %v", err, ctx.Data["MsgID"])
  1390. cloudBrainNewDataPrepare(ctx)
  1391. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  1392. }
  1393. return
  1394. }
  1395. if err := uploadCodeToMinio(codePath+"/", jobName, cloudbrain.CodeMountPath+"/"); err != nil {
  1396. log.Error("uploadCodeToMinio failed, %v", err, ctx.Data["MsgID"])
  1397. cloudBrainNewDataPrepare(ctx)
  1398. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  1399. return
  1400. }
  1401. benchmarkPath := setting.JobPath + jobName + cloudbrain.BenchMarkMountPath
  1402. var gpuType string
  1403. for _, gpuInfo := range gpuInfos.GpuInfo {
  1404. if gpuInfo.Queue == gpuQueue {
  1405. gpuType = gpuInfo.Value
  1406. }
  1407. }
  1408. if err := downloadRateCode(repo, jobName, childInfo.Owner, childInfo.RepoName, benchmarkPath, form.BenchmarkCategory, gpuType); err != nil {
  1409. log.Error("downloadRateCode failed, %v", err, ctx.Data["MsgID"])
  1410. //cloudBrainNewDataPrepare(ctx)
  1411. //ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  1412. //return
  1413. }
  1414. if err := uploadCodeToMinio(benchmarkPath+"/", jobName, cloudbrain.BenchMarkMountPath+"/"); err != nil {
  1415. log.Error("uploadCodeToMinio failed, %v", err, ctx.Data["MsgID"])
  1416. //cloudBrainNewDataPrepare(ctx)
  1417. //ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  1418. //return
  1419. }
  1420. err = cloudbrain.GenerateTask(ctx, displayJobName, jobName, image, command, childInfo.Attachment, storage.GetMinioPath(jobName, cloudbrain.CodeMountPath+"/"),
  1421. storage.GetMinioPath(jobName, cloudbrain.ModelMountPath+"/"),
  1422. storage.GetMinioPath(jobName, cloudbrain.BenchMarkMountPath+"/"), storage.GetMinioPath(jobName, cloudbrain.Snn4imagenetMountPath+"/"),
  1423. storage.GetMinioPath(jobName, cloudbrain.BrainScoreMountPath+"/"), string(models.JobTypeBenchmark), gpuQueue, form.Description, cloudbrain.DefaultBranchName, "", "",
  1424. benchmarkTypeID, benchmarkChildTypeID, resourceSpecId)
  1425. if err != nil {
  1426. cloudBrainNewDataPrepare(ctx)
  1427. ctx.RenderWithErr(err.Error(), tplCloudBrainBenchmarkNew, &form)
  1428. return
  1429. }
  1430. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/cloudbrain/benchmark")
  1431. }
  1432. func BenchmarkDel(ctx *context.Context) {
  1433. if err := deleteCloudbrainJob(ctx); err != nil {
  1434. log.Error("deleteCloudbrainJob failed: %v", err, ctx.Data["msgID"])
  1435. ctx.ServerError(err.Error(), err)
  1436. return
  1437. }
  1438. var isAdminPage = ctx.Query("isadminpage")
  1439. if ctx.IsUserSiteAdmin() && isAdminPage == "true" {
  1440. ctx.Redirect(setting.AppSubURL + "/admin" + "/cloudbrains")
  1441. } else {
  1442. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/cloudbrain/benchmark")
  1443. }
  1444. }
  1445. func CloudBrainTrainJobNew(ctx *context.Context) {
  1446. err := cloudBrainNewDataPrepare(ctx)
  1447. if err != nil {
  1448. ctx.ServerError("get new train-job info failed", err)
  1449. return
  1450. }
  1451. ctx.HTML(http.StatusOK, tplCloudBrainTrainJobNew)
  1452. }
  1453. func getTrainJobCommand(form auth.CreateCloudBrainForm) (string, error) {
  1454. var command string
  1455. bootFile := form.BootFile
  1456. params := form.Params
  1457. if !strings.HasSuffix(bootFile, ".py") {
  1458. log.Error("bootFile(%s) format error", bootFile)
  1459. return command, errors.New("bootFile format error")
  1460. }
  1461. var parameters models.Parameters
  1462. var param string
  1463. if len(params) != 0 {
  1464. err := json.Unmarshal([]byte(params), &parameters)
  1465. if err != nil {
  1466. log.Error("Failed to Unmarshal params: %s (%v)", params, err)
  1467. return command, err
  1468. }
  1469. for _, parameter := range parameters.Parameter {
  1470. param += " --" + parameter.Label + "=" + parameter.Value
  1471. }
  1472. }
  1473. command += "python /code/" + bootFile + param + " > " + cloudbrain.ModelMountPath + "/" + form.DisplayJobName + "-" + cloudbrain.LogFile
  1474. return command, nil
  1475. }
  1476. func CloudBrainTrainJobDel(ctx *context.Context) {
  1477. var listType = ctx.Query("listType")
  1478. if err := deleteCloudbrainJob(ctx); err != nil {
  1479. log.Error("deleteCloudbrainJob failed: %v", err, ctx.Data["msgID"])
  1480. ctx.ServerError(err.Error(), err)
  1481. return
  1482. }
  1483. var isAdminPage = ctx.Query("isadminpage")
  1484. if ctx.IsUserSiteAdmin() && isAdminPage == "true" {
  1485. ctx.Redirect(setting.AppSubURL + "/admin" + "/cloudbrains")
  1486. } else {
  1487. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/train-job?listType=" + listType)
  1488. }
  1489. }
  1490. func GetBenchmarkTypes(ctx *context.Context) *models.BenchmarkTypes {
  1491. var lang = ctx.Locale.Language()
  1492. if benchmarkTypesMap[lang] == nil {
  1493. var val = i18n.Tr(lang, BENCHMARK_TYPE_CODE)
  1494. //use config
  1495. val = setting.BenchmarkTypes
  1496. var tempType *models.BenchmarkTypes
  1497. if err := json.Unmarshal([]byte(val), &tempType); err != nil {
  1498. log.Error("json.Unmarshal BenchmarkTypes(%s) failed:%v", val, err, ctx.Data["MsgID"])
  1499. return &models.BenchmarkTypes{}
  1500. }
  1501. benchmarkTypesMap[lang] = tempType
  1502. }
  1503. return benchmarkTypesMap[lang]
  1504. }