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