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