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

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