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 54 kB

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