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