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

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