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

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