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

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