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