You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

cloudbrain.go 43 kB

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