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