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