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