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