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