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