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

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