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 44 kB

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