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

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