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 62 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
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
5 years ago
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
3 years ago
5 years ago
4 years ago
4 years ago
5 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
5 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
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
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
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
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
3 years ago
5 years ago
3 years ago
3 years ago
3 years ago
5 years ago
3 years ago
5 years ago
5 years ago
5 years ago
3 years ago
3 years ago
3 years ago
5 years ago
3 years ago
3 years ago
3 years ago
5 years ago
3 years ago
3 years ago
5 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
5 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
5 years ago
4 years ago
4 years ago
3 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
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
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
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
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
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
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
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
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
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061
  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. "unicode/utf8"
  16. "code.gitea.io/gitea/modules/timeutil"
  17. "github.com/unknwon/i18n"
  18. "code.gitea.io/gitea/models"
  19. "code.gitea.io/gitea/modules/auth"
  20. "code.gitea.io/gitea/modules/base"
  21. "code.gitea.io/gitea/modules/cloudbrain"
  22. "code.gitea.io/gitea/modules/context"
  23. "code.gitea.io/gitea/modules/git"
  24. "code.gitea.io/gitea/modules/log"
  25. "code.gitea.io/gitea/modules/modelarts"
  26. "code.gitea.io/gitea/modules/setting"
  27. "code.gitea.io/gitea/modules/storage"
  28. "code.gitea.io/gitea/modules/util"
  29. )
  30. const (
  31. tplCloudBrainNew base.TplName = "repo/cloudbrain/new"
  32. tplCloudBrainShow base.TplName = "repo/cloudbrain/show"
  33. tplCloudBrainShowModels base.TplName = "repo/cloudbrain/models/index"
  34. tplCloudBrainBenchmarkIndex base.TplName = "repo/cloudbrain/benchmark/index"
  35. tplCloudBrainBenchmarkNew base.TplName = "repo/cloudbrain/benchmark/new"
  36. tplCloudBrainBenchmarkShow base.TplName = "repo/cloudbrain/benchmark/show"
  37. tplCloudBrainImageSubmit base.TplName = "repo/cloudbrain/image/submit"
  38. tplCloudBrainImageEdit base.TplName = "repo/cloudbrain/image/edit"
  39. tplCloudBrainTrainJobNew base.TplName = "repo/cloudbrain/trainjob/new"
  40. tplCloudBrainTrainJobShow base.TplName = "repo/cloudbrain/trainjob/show"
  41. )
  42. var (
  43. gpuInfos *models.GpuInfos
  44. categories *models.Categories
  45. benchmarkTypes *models.BenchmarkTypes
  46. benchmarkGpuInfos *models.GpuInfos
  47. benchmarkResourceSpecs *models.ResourceSpecs
  48. trainGpuInfos *models.GpuInfos
  49. )
  50. const BENCHMARK_TYPE_CODE = "repo.cloudbrain.benchmark.types"
  51. const CLONE_FILE_PREFIX = "file:///"
  52. var benchmarkTypesMap = make(map[string]*models.BenchmarkTypes, 0)
  53. var jobNamePattern = regexp.MustCompile(`^[a-z0-9][a-z0-9-_]{1,34}[a-z0-9-]$`)
  54. // MustEnableDataset check if repository enable internal cb
  55. func MustEnableCloudbrain(ctx *context.Context) {
  56. if !ctx.Repo.CanRead(models.UnitTypeCloudBrain) {
  57. ctx.NotFound("MustEnableCloudbrain", nil)
  58. return
  59. }
  60. }
  61. func cutString(str string, lens int) string {
  62. if len(str) < lens {
  63. return str
  64. }
  65. return str[:lens]
  66. }
  67. func jobNamePrefixValid(s string) string {
  68. lowStr := strings.ToLower(s)
  69. re := regexp.MustCompile(`[^a-z0-9_\\-]+`)
  70. removeSpecial := re.ReplaceAllString(lowStr, "")
  71. re = regexp.MustCompile(`^[_\\-]+`)
  72. return re.ReplaceAllString(removeSpecial, "")
  73. }
  74. func cloudBrainNewDataPrepare(ctx *context.Context) error {
  75. ctx.Data["PageIsCloudBrain"] = true
  76. t := time.Now()
  77. var displayJobName = jobNamePrefixValid(cutString(ctx.User.Name, 5)) + t.Format("2006010215") + strconv.Itoa(int(t.Unix()))[5:]
  78. ctx.Data["display_job_name"] = displayJobName
  79. result, err := cloudbrain.GetImages()
  80. if err != nil {
  81. ctx.Data["error"] = err.Error()
  82. log.Error("cloudbrain.GetImages failed:", err.Error(), ctx.Data["MsgID"])
  83. }
  84. for i, payload := range result.Payload.ImageInfo {
  85. if strings.HasPrefix(result.Payload.ImageInfo[i].Place, "192.168") {
  86. result.Payload.ImageInfo[i].PlaceView = payload.Place[strings.Index(payload.Place, "/"):len(payload.Place)]
  87. } else {
  88. result.Payload.ImageInfo[i].PlaceView = payload.Place
  89. }
  90. }
  91. ctx.Data["images"] = result.Payload.ImageInfo
  92. resultPublic, err := cloudbrain.GetPublicImages()
  93. if err != nil {
  94. ctx.Data["error"] = err.Error()
  95. log.Error("cloudbrain.GetPublicImages failed:", err.Error(), ctx.Data["MsgID"])
  96. }
  97. for i, payload := range resultPublic.Payload.ImageInfo {
  98. if strings.HasPrefix(resultPublic.Payload.ImageInfo[i].Place, "192.168") {
  99. resultPublic.Payload.ImageInfo[i].PlaceView = payload.Place[strings.Index(payload.Place, "/"):len(payload.Place)]
  100. } else {
  101. resultPublic.Payload.ImageInfo[i].PlaceView = payload.Place
  102. }
  103. }
  104. ctx.Data["public_images"] = resultPublic.Payload.ImageInfo
  105. attachs, err := models.GetAllUserAttachments(ctx.User.ID)
  106. if err != nil {
  107. log.Error("GetAllUserAttachments failed: %v", err, ctx.Data["MsgID"])
  108. return err
  109. }
  110. ctx.Data["attachments"] = attachs
  111. ctx.Data["command"] = cloudbrain.Command
  112. ctx.Data["code_path"] = cloudbrain.CodeMountPath
  113. ctx.Data["dataset_path"] = cloudbrain.DataSetMountPath
  114. ctx.Data["model_path"] = cloudbrain.ModelMountPath
  115. ctx.Data["benchmark_path"] = cloudbrain.BenchMarkMountPath
  116. ctx.Data["is_benchmark_enabled"] = setting.IsBenchmarkEnabled
  117. if categories == nil {
  118. json.Unmarshal([]byte(setting.BenchmarkCategory), &categories)
  119. }
  120. ctx.Data["benchmark_categories"] = categories.Category
  121. ctx.Data["benchmark_types"] = GetBenchmarkTypes(ctx).BenchmarkType
  122. if gpuInfos == nil {
  123. json.Unmarshal([]byte(setting.GpuTypes), &gpuInfos)
  124. }
  125. ctx.Data["gpu_types"] = gpuInfos.GpuInfo
  126. if trainGpuInfos == nil {
  127. json.Unmarshal([]byte(setting.TrainGpuTypes), &trainGpuInfos)
  128. }
  129. ctx.Data["train_gpu_types"] = trainGpuInfos.GpuInfo
  130. if benchmarkGpuInfos == nil {
  131. json.Unmarshal([]byte(setting.BenchmarkGpuTypes), &benchmarkGpuInfos)
  132. }
  133. ctx.Data["benchmark_gpu_types"] = benchmarkGpuInfos.GpuInfo
  134. if benchmarkResourceSpecs == nil {
  135. json.Unmarshal([]byte(setting.BenchmarkResourceSpecs), &benchmarkResourceSpecs)
  136. }
  137. ctx.Data["benchmark_resource_specs"] = benchmarkResourceSpecs.ResourceSpec
  138. if cloudbrain.ResourceSpecs == nil {
  139. json.Unmarshal([]byte(setting.ResourceSpecs), &cloudbrain.ResourceSpecs)
  140. }
  141. ctx.Data["resource_specs"] = cloudbrain.ResourceSpecs.ResourceSpec
  142. if cloudbrain.TrainResourceSpecs == nil {
  143. json.Unmarshal([]byte(setting.TrainResourceSpecs), &cloudbrain.TrainResourceSpecs)
  144. }
  145. ctx.Data["train_resource_specs"] = cloudbrain.TrainResourceSpecs.ResourceSpec
  146. ctx.Data["params"] = ""
  147. ctx.Data["branchName"] = ctx.Repo.BranchName
  148. ctx.Data["snn4imagenet_path"] = cloudbrain.Snn4imagenetMountPath
  149. ctx.Data["is_snn4imagenet_enabled"] = setting.IsSnn4imagenetEnabled
  150. ctx.Data["brainscore_path"] = cloudbrain.BrainScoreMountPath
  151. ctx.Data["is_brainscore_enabled"] = setting.IsBrainScoreEnabled
  152. ctx.Data["cloudbraintype"] = models.TypeCloudBrainOne
  153. return nil
  154. }
  155. func CloudBrainNew(ctx *context.Context) {
  156. err := cloudBrainNewDataPrepare(ctx)
  157. if err != nil {
  158. ctx.ServerError("get new cloudbrain info failed", err)
  159. return
  160. }
  161. ctx.HTML(200, tplCloudBrainNew)
  162. }
  163. func CloudBrainCreate(ctx *context.Context, form auth.CreateCloudBrainForm) {
  164. ctx.Data["PageIsCloudBrain"] = true
  165. displayJobName := form.DisplayJobName
  166. jobName := util.ConvertDisplayJobNameToJobName(displayJobName)
  167. image := form.Image
  168. uuid := form.Attachment
  169. jobType := form.JobType
  170. gpuQueue := form.GpuType
  171. codePath := setting.JobPath + jobName + cloudbrain.CodeMountPath
  172. resourceSpecId := form.ResourceSpecId
  173. branchName := form.BranchName
  174. repo := ctx.Repo.Repository
  175. tpl := tplCloudBrainNew
  176. command := cloudbrain.Command
  177. if jobType == string(models.JobTypeTrain) {
  178. tpl = tplCloudBrainTrainJobNew
  179. commandTrain, err := getTrainJobCommand(form)
  180. if err != nil {
  181. log.Error("getTrainJobCommand failed: %v", err)
  182. ctx.RenderWithErr(err.Error(), tpl, &form)
  183. return
  184. }
  185. command = commandTrain
  186. }
  187. tasks, err := models.GetCloudbrainsByDisplayJobName(repo.ID, jobType, displayJobName)
  188. if err == nil {
  189. if len(tasks) != 0 {
  190. log.Error("the job name did already exist", ctx.Data["MsgID"])
  191. cloudBrainNewDataPrepare(ctx)
  192. ctx.RenderWithErr("the job name did already exist", tpl, &form)
  193. return
  194. }
  195. } else {
  196. if !models.IsErrJobNotExist(err) {
  197. log.Error("system error, %v", err, ctx.Data["MsgID"])
  198. cloudBrainNewDataPrepare(ctx)
  199. ctx.RenderWithErr("system error", tpl, &form)
  200. return
  201. }
  202. }
  203. if !jobNamePattern.MatchString(displayJobName) {
  204. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_jobname_err"), tpl, &form)
  205. return
  206. }
  207. if jobType != string(models.JobTypeBenchmark) && jobType != string(models.JobTypeDebug) && jobType != string(models.JobTypeSnn4imagenet) && jobType != string(models.JobTypeBrainScore) && jobType != string(models.JobTypeTrain) {
  208. log.Error("jobtype error:", jobType, ctx.Data["MsgID"])
  209. cloudBrainNewDataPrepare(ctx)
  210. ctx.RenderWithErr("jobtype error", tpl, &form)
  211. return
  212. }
  213. count, err := models.GetCloudbrainCountByUserID(ctx.User.ID, jobType)
  214. if err != nil {
  215. log.Error("GetCloudbrainCountByUserID failed:%v", err, ctx.Data["MsgID"])
  216. cloudBrainNewDataPrepare(ctx)
  217. ctx.RenderWithErr("system error", tpl, &form)
  218. return
  219. } else {
  220. if count >= 1 {
  221. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  222. cloudBrainNewDataPrepare(ctx)
  223. ctx.RenderWithErr("you have already a running or waiting task, can not create more", tpl, &form)
  224. return
  225. }
  226. }
  227. if branchName == "" {
  228. branchName = cloudbrain.DefaultBranchName
  229. }
  230. downloadCode(repo, codePath, branchName)
  231. uploadCodeToMinio(codePath+"/", jobName, cloudbrain.CodeMountPath+"/")
  232. modelPath := setting.JobPath + jobName + cloudbrain.ModelMountPath + "/"
  233. mkModelPath(modelPath)
  234. uploadCodeToMinio(modelPath, jobName, cloudbrain.ModelMountPath+"/")
  235. benchmarkPath := setting.JobPath + jobName + cloudbrain.BenchMarkMountPath
  236. if setting.IsBenchmarkEnabled && jobType == string(models.JobTypeBenchmark) {
  237. var gpuType string
  238. for _, gpuInfo := range gpuInfos.GpuInfo {
  239. if gpuInfo.Queue == gpuQueue {
  240. gpuType = gpuInfo.Value
  241. }
  242. }
  243. downloadRateCode(repo, jobName, setting.BenchmarkOwner, setting.BenchmarkName, benchmarkPath, form.BenchmarkCategory, gpuType)
  244. uploadCodeToMinio(benchmarkPath+"/", jobName, cloudbrain.BenchMarkMountPath+"/")
  245. }
  246. snn4imagenetPath := setting.JobPath + jobName + cloudbrain.Snn4imagenetMountPath
  247. if setting.IsSnn4imagenetEnabled && jobType == string(models.JobTypeSnn4imagenet) {
  248. downloadRateCode(repo, jobName, setting.Snn4imagenetOwner, setting.Snn4imagenetName, snn4imagenetPath, "", "")
  249. uploadCodeToMinio(snn4imagenetPath+"/", jobName, cloudbrain.Snn4imagenetMountPath+"/")
  250. }
  251. brainScorePath := setting.JobPath + jobName + cloudbrain.BrainScoreMountPath
  252. if setting.IsBrainScoreEnabled && jobType == string(models.JobTypeBrainScore) {
  253. downloadRateCode(repo, jobName, setting.BrainScoreOwner, setting.BrainScoreName, brainScorePath, "", "")
  254. uploadCodeToMinio(brainScorePath+"/", jobName, cloudbrain.BrainScoreMountPath+"/")
  255. }
  256. err = cloudbrain.GenerateTask(ctx, displayJobName, jobName, image, command, uuid, storage.GetMinioPath(jobName, cloudbrain.CodeMountPath+"/"),
  257. storage.GetMinioPath(jobName, cloudbrain.ModelMountPath+"/"),
  258. storage.GetMinioPath(jobName, cloudbrain.BenchMarkMountPath+"/"), storage.GetMinioPath(jobName, cloudbrain.Snn4imagenetMountPath+"/"),
  259. storage.GetMinioPath(jobName, cloudbrain.BrainScoreMountPath+"/"), jobType, gpuQueue, form.Description, branchName, form.BootFile, form.Params,
  260. 0, 0, resourceSpecId)
  261. if err != nil {
  262. cloudBrainNewDataPrepare(ctx)
  263. ctx.RenderWithErr(err.Error(), tpl, &form)
  264. return
  265. }
  266. if jobType == string(models.JobTypeTrain) {
  267. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/train-job?listType=all")
  268. } else {
  269. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/debugjob?debugListType=all")
  270. }
  271. }
  272. func CloudBrainRestart(ctx *context.Context) {
  273. var ID = ctx.Params(":id")
  274. var resultCode = "0"
  275. var errorMsg = ""
  276. var status = string(models.JobWaiting)
  277. task := ctx.Cloudbrain
  278. for {
  279. if task.Status != string(models.JobStopped) && task.Status != string(models.JobSucceeded) && task.Status != string(models.JobFailed) {
  280. log.Error("the job(%s) is not stopped", task.JobName, ctx.Data["MsgID"])
  281. resultCode = "-1"
  282. errorMsg = "the job is not stopped"
  283. break
  284. }
  285. if task.Image == "" || task.GpuQueue == "" || task.Type != models.TypeCloudBrainOne {
  286. log.Error("the job(%s) version is too old", task.JobName, ctx.Data["MsgID"])
  287. resultCode = "-1"
  288. errorMsg = "the job's version is too old and can not be restarted"
  289. break
  290. }
  291. if !ctx.IsSigned || (ctx.User.ID != task.UserID && !ctx.IsUserSiteAdmin()) {
  292. log.Error("the user has no right ro restart the job", task.JobName, ctx.Data["MsgID"])
  293. resultCode = "-1"
  294. errorMsg = "you have no right to restart the job"
  295. break
  296. }
  297. var hasSameResource bool
  298. if gpuInfos == nil {
  299. json.Unmarshal([]byte(setting.GpuTypes), &gpuInfos)
  300. }
  301. for _, resourceType := range gpuInfos.GpuInfo {
  302. if resourceType.Queue == task.GpuQueue {
  303. hasSameResource = true
  304. continue
  305. }
  306. }
  307. if !hasSameResource {
  308. log.Error("has no same resource, can not restart", ctx.Data["MsgID"])
  309. resultCode = "-1"
  310. errorMsg = "the job's version is too old and can not be restarted"
  311. break
  312. }
  313. count, err := models.GetCloudbrainCountByUserID(ctx.User.ID, string(models.JobTypeDebug))
  314. if err != nil {
  315. log.Error("GetCloudbrainCountByUserID failed:%v", err, ctx.Data["MsgID"])
  316. resultCode = "-1"
  317. errorMsg = "system error"
  318. break
  319. } else {
  320. if count >= 1 {
  321. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  322. resultCode = "-1"
  323. errorMsg = "you have already a running or waiting task, can not create more"
  324. break
  325. }
  326. }
  327. err = cloudbrain.RestartTask(ctx, task, &ID)
  328. if err != nil {
  329. log.Error("RestartTask failed:%v", err.Error(), ctx.Data["MsgID"])
  330. resultCode = "-1"
  331. errorMsg = "system error"
  332. break
  333. }
  334. break
  335. }
  336. ctx.JSON(200, map[string]string{
  337. "result_code": resultCode,
  338. "error_msg": errorMsg,
  339. "status": status,
  340. "id": ID,
  341. })
  342. }
  343. func CloudBrainBenchMarkShow(ctx *context.Context) {
  344. cloudBrainShow(ctx, tplCloudBrainBenchmarkShow, models.JobTypeBenchmark)
  345. }
  346. func CloudBrainShow(ctx *context.Context) {
  347. cloudBrainShow(ctx, tplCloudBrainShow, models.JobTypeDebug)
  348. }
  349. func CloudBrainTrainJobShow(ctx *context.Context) {
  350. cloudBrainShow(ctx, tplCloudBrainTrainJobShow, models.JobTypeTrain)
  351. }
  352. func cloudBrainShow(ctx *context.Context, tpName base.TplName, jobType models.JobType) {
  353. ctx.Data["PageIsCloudBrain"] = true
  354. debugListType := ctx.Query("debugListType")
  355. var task *models.Cloudbrain
  356. var err error
  357. if jobType == models.JobTypeTrain {
  358. task, err = models.GetCloudbrainByJobID(ctx.Params(":jobid"))
  359. } else {
  360. task, err = models.GetCloudbrainByIDWithDeleted(ctx.Params(":id"))
  361. }
  362. if err != nil {
  363. log.Info("error:" + err.Error())
  364. ctx.Data["error"] = err.Error()
  365. return
  366. }
  367. result, err := cloudbrain.GetJob(task.JobID)
  368. if err != nil {
  369. log.Info("error:" + err.Error())
  370. ctx.Data["error"] = err.Error()
  371. return
  372. }
  373. if task.JobType == string(models.JobTypeTrain) {
  374. if cloudbrain.TrainResourceSpecs == nil {
  375. json.Unmarshal([]byte(setting.TrainResourceSpecs), &cloudbrain.TrainResourceSpecs)
  376. }
  377. for _, tmp := range cloudbrain.TrainResourceSpecs.ResourceSpec {
  378. if tmp.Id == task.ResourceSpecId {
  379. ctx.Data["GpuNum"] = tmp.GpuNum
  380. ctx.Data["CpuNum"] = tmp.CpuNum
  381. ctx.Data["MemMiB"] = tmp.MemMiB
  382. ctx.Data["ShareMemMiB"] = tmp.ShareMemMiB
  383. }
  384. }
  385. } else {
  386. if cloudbrain.ResourceSpecs == nil {
  387. json.Unmarshal([]byte(setting.ResourceSpecs), &cloudbrain.ResourceSpecs)
  388. }
  389. for _, tmp := range cloudbrain.ResourceSpecs.ResourceSpec {
  390. if tmp.Id == task.ResourceSpecId {
  391. ctx.Data["GpuNum"] = tmp.GpuNum
  392. ctx.Data["CpuNum"] = tmp.CpuNum
  393. ctx.Data["MemMiB"] = tmp.MemMiB
  394. ctx.Data["ShareMemMiB"] = tmp.ShareMemMiB
  395. }
  396. }
  397. }
  398. if result != nil {
  399. jobRes, _ := models.ConvertToJobResultPayload(result.Payload)
  400. jobRes.Resource.Memory = strings.ReplaceAll(jobRes.Resource.Memory, "Mi", "MB")
  401. spec := "GPU数:" + strconv.Itoa(jobRes.Resource.NvidiaComGpu) + ",CPU数:" + strconv.Itoa(jobRes.Resource.CPU) + ",内存(MB):" + jobRes.Resource.Memory
  402. ctx.Data["resource_spec"] = spec
  403. if task.JobType == string(models.JobTypeTrain) {
  404. if trainGpuInfos == nil {
  405. json.Unmarshal([]byte(setting.TrainGpuTypes), &trainGpuInfos)
  406. }
  407. for _, resourceType := range trainGpuInfos.GpuInfo {
  408. if resourceType.Queue == jobRes.Config.GpuType {
  409. ctx.Data["resource_type"] = resourceType.Value
  410. }
  411. }
  412. } else {
  413. if gpuInfos == nil {
  414. json.Unmarshal([]byte(setting.GpuTypes), &gpuInfos)
  415. }
  416. for _, resourceType := range gpuInfos.GpuInfo {
  417. if resourceType.Queue == jobRes.Config.GpuType {
  418. ctx.Data["resource_type"] = resourceType.Value
  419. }
  420. }
  421. }
  422. taskRoles := jobRes.TaskRoles
  423. if jobRes.JobStatus.State != string(models.JobFailed) {
  424. taskRes, _ := models.ConvertToTaskPod(taskRoles[cloudbrain.SubTaskName].(map[string]interface{}))
  425. ctx.Data["taskRes"] = taskRes
  426. task.Status = taskRes.TaskStatuses[0].State
  427. task.ContainerID = taskRes.TaskStatuses[0].ContainerID
  428. task.ContainerIp = taskRes.TaskStatuses[0].ContainerIP
  429. models.ParseAndSetDurationFromCloudBrainOne(jobRes, task)
  430. if task.DeletedAt.IsZero() { //normal record
  431. err = models.UpdateJob(task)
  432. if err != nil {
  433. ctx.Data["error"] = err.Error()
  434. return
  435. }
  436. } else { //deleted record
  437. }
  438. } else {
  439. task.Status = jobRes.JobStatus.State
  440. taskRes := models.TaskPod{TaskStatuses: []models.TaskStatuses{
  441. {
  442. State: jobRes.JobStatus.State,
  443. },
  444. }}
  445. ctx.Data["taskRes"] = taskRes
  446. jobRes.JobStatus.StartTime = time.Unix(int64(task.CreatedUnix), 0).Format("2006-01-02 15:04:05")
  447. jobRes.JobStatus.EndTime = time.Unix(int64(task.UpdatedUnix), 0).Format("2006-01-02 15:04:05")
  448. }
  449. ctx.Data["result"] = jobRes
  450. } else {
  451. log.Info("error:" + err.Error())
  452. return
  453. }
  454. user, err := models.GetUserByID(task.UserID)
  455. if err == nil {
  456. task.User = user
  457. }
  458. if task.BenchmarkTypeID > 0 {
  459. for _, benchmarkType := range GetBenchmarkTypes(ctx).BenchmarkType {
  460. if task.BenchmarkTypeID == benchmarkType.Id {
  461. ctx.Data["BenchmarkTypeName"] = benchmarkType.First
  462. for _, benchmarkChildType := range benchmarkType.Second {
  463. if task.BenchmarkChildTypeID == benchmarkChildType.Id {
  464. ctx.Data["BenchmarkChildTypeName"] = benchmarkChildType.Value
  465. break
  466. }
  467. }
  468. break
  469. }
  470. }
  471. }
  472. if task.TrainJobDuration == "" {
  473. if task.Duration == 0 {
  474. var duration int64
  475. if task.Status == string(models.JobRunning) {
  476. duration = time.Now().Unix() - int64(task.CreatedUnix)
  477. } else {
  478. duration = int64(task.UpdatedUnix) - int64(task.CreatedUnix)
  479. }
  480. task.Duration = duration
  481. }
  482. task.TrainJobDuration = models.ConvertDurationToStr(task.Duration)
  483. }
  484. ctx.Data["duration"] = task.TrainJobDuration
  485. if len(task.Parameters) > 0 {
  486. var parameters models.Parameters
  487. err := json.Unmarshal([]byte(task.Parameters), &parameters)
  488. if err != nil {
  489. log.Error("Failed to Unmarshal Parameters: %s (%v)", task.Parameters, err)
  490. task.Parameters = ""
  491. } else {
  492. if len(parameters.Parameter) > 0 {
  493. paramTemp := ""
  494. for _, Parameter := range parameters.Parameter {
  495. param := Parameter.Label + " = " + Parameter.Value + "; "
  496. paramTemp = paramTemp + param
  497. }
  498. task.Parameters = paramTemp[:len(paramTemp)-2]
  499. } else {
  500. task.Parameters = ""
  501. }
  502. }
  503. }
  504. attachment, err := models.GetAttachmentByUUID(task.Uuid)
  505. if err == nil {
  506. ctx.Data["datasetname"] = attachment.Name
  507. } else {
  508. ctx.Data["datasetname"] = ""
  509. }
  510. ctx.Data["task"] = task
  511. ctx.Data["jobName"] = task.JobName
  512. ctx.Data["displayJobName"] = task.DisplayJobName
  513. version_list_task := make([]*models.Cloudbrain, 0)
  514. version_list_task = append(version_list_task, task)
  515. ctx.Data["version_list_task"] = version_list_task
  516. ctx.Data["debugListType"] = debugListType
  517. ctx.Data["code_path"] = cloudbrain.CodeMountPath
  518. ctx.Data["dataset_path"] = cloudbrain.DataSetMountPath
  519. ctx.Data["model_path"] = cloudbrain.ModelMountPath
  520. ctx.Data["canDownload"] = cloudbrain.CanModifyJob(ctx, task)
  521. ctx.HTML(200, tpName)
  522. }
  523. func CloudBrainDebug(ctx *context.Context) {
  524. task := ctx.Cloudbrain
  525. debugUrl := setting.DebugServerHost + "jpylab_" + task.JobID + "_" + task.SubTaskName
  526. ctx.Redirect(debugUrl)
  527. }
  528. func CloudBrainCommitImageShow(ctx *context.Context) {
  529. ctx.Data["PageIsCloudBrain"] = true
  530. ctx.Data["Type"] = ctx.Cloudbrain.Type
  531. ctx.HTML(200, tplCloudBrainImageSubmit)
  532. }
  533. func CloudBrainImageEdit(ctx *context.Context) {
  534. ctx.Data["PageIsImageEdit"] = true
  535. ctx.Data["PageFrom"] = ctx.Params(":from")
  536. var ID = ctx.Params(":id")
  537. id, err := strconv.ParseInt(ID, 10, 64)
  538. if err != nil {
  539. log.Error("GetImageByID failed:%v", err.Error())
  540. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  541. }
  542. image, err := models.GetImageByID(id)
  543. if err != nil {
  544. log.Error("GetImageByID failed:%v", err.Error())
  545. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  546. }
  547. ctx.Data["Image"] = image
  548. ctx.HTML(http.StatusOK, tplCloudBrainImageEdit)
  549. }
  550. func CloudBrainImageEditPost(ctx *context.Context, form auth.EditImageCloudBrainForm) {
  551. if utf8.RuneCountInString(form.Description) > 255 {
  552. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("dataset.description_format_err", 255)))
  553. return
  554. }
  555. validTopics, errMessage := checkTopics(form.Topics)
  556. if errMessage != "" {
  557. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr(errMessage)))
  558. return
  559. }
  560. image, err := models.GetImageByID(form.ID)
  561. if err != nil {
  562. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("repo.image_not_exist")))
  563. }
  564. image.IsPrivate = form.IsPrivate
  565. image.Description = form.Description
  566. err = models.WithTx(func(ctx models.DBContext) error {
  567. if err := models.UpdateLocalImage(image); err != nil {
  568. return err
  569. }
  570. if err := models.SaveImageTopics(image.ID, validTopics...); err != nil {
  571. return err
  572. }
  573. return nil
  574. })
  575. if err != nil {
  576. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("repo.image_not_exist")))
  577. } else {
  578. ctx.JSON(http.StatusOK, models.BaseOKMessage)
  579. }
  580. }
  581. func CloudBrainImageDelete(ctx *context.Context) {
  582. var ID = ctx.Params(":id")
  583. id, err := strconv.ParseInt(ID, 10, 64)
  584. if err != nil {
  585. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("repo.image_not_exist")))
  586. return
  587. }
  588. err = models.DeleteLocalImage(id)
  589. if err != nil {
  590. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("repo.image_delete_fail")))
  591. } else {
  592. ctx.JSON(http.StatusOK, models.BaseOKMessage)
  593. }
  594. }
  595. func CloudBrainCommitImageCheck(ctx *context.Context, form auth.CommitImageCloudBrainForm) {
  596. isExist, _ := models.IsImageExistByUser(form.Tag, ctx.User.ID)
  597. if isExist {
  598. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("repo.image_overwrite")))
  599. } else {
  600. ctx.JSON(http.StatusOK, models.BaseOKMessage)
  601. }
  602. }
  603. func CloudBrainAdminCommitImage(ctx *context.Context, form auth.CommitAdminImageCloudBrainForm) {
  604. if !NamePattern.MatchString(form.Tag) {
  605. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("dataset.title_format_err")))
  606. return
  607. }
  608. if utf8.RuneCountInString(form.Description) > 255 {
  609. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("dataset.description_format_err", 255)))
  610. return
  611. }
  612. validTopics, errMessage := checkTopics(form.Topics)
  613. if errMessage != "" {
  614. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr(errMessage)))
  615. return
  616. }
  617. err := cloudbrain.CommitAdminImage(models.CommitImageParams{
  618. CommitImageCloudBrainParams: models.CommitImageCloudBrainParams{
  619. ImageDescription: form.Description,
  620. ImageTag: form.Tag,
  621. },
  622. IsPrivate: form.IsPrivate,
  623. CloudBrainType: form.Type,
  624. Topics: validTopics,
  625. UID: ctx.User.ID,
  626. Type: models.GetRecommondType(form.IsRecommend),
  627. Place: form.Place,
  628. })
  629. if err != nil {
  630. log.Error("CommitImagefailed")
  631. if models.IsErrImageTagExist(err) {
  632. ctx.JSON(200, models.BaseErrorMessage(ctx.Tr("repo.image_exist")))
  633. } else if models.IsErrorImageCommitting(err) {
  634. ctx.JSON(200, models.BaseErrorMessage(ctx.Tr("repo.image_committing")))
  635. } else {
  636. ctx.JSON(200, models.BaseErrorMessage(ctx.Tr("repo.image_commit_fail")))
  637. }
  638. return
  639. }
  640. ctx.JSON(200, models.BaseOKMessage)
  641. }
  642. func CloudBrainCommitImage(ctx *context.Context, form auth.CommitImageCloudBrainForm) {
  643. if !NamePattern.MatchString(form.Tag) {
  644. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("dataset.title_format_err")))
  645. return
  646. }
  647. if utf8.RuneCountInString(form.Description) > 255 {
  648. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("dataset.description_format_err", 255)))
  649. return
  650. }
  651. validTopics, errMessage := checkTopics(form.Topics)
  652. if errMessage != "" {
  653. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr(errMessage)))
  654. return
  655. }
  656. err := cloudbrain.CommitImage(ctx.Cloudbrain.JobID, models.CommitImageParams{
  657. CommitImageCloudBrainParams: models.CommitImageCloudBrainParams{
  658. Ip: ctx.Cloudbrain.ContainerIp,
  659. TaskContainerId: ctx.Cloudbrain.ContainerID,
  660. ImageDescription: form.Description,
  661. ImageTag: form.Tag,
  662. },
  663. IsPrivate: form.IsPrivate,
  664. CloudBrainType: form.Type,
  665. Topics: validTopics,
  666. UID: ctx.User.ID,
  667. })
  668. if err != nil {
  669. log.Error("CommitImage(%s) failed:%v", ctx.Cloudbrain.JobName, err.Error(), ctx.Data["msgID"])
  670. if models.IsErrImageTagExist(err) {
  671. ctx.JSON(200, models.BaseErrorMessage(ctx.Tr("repo.image_exist")))
  672. } else if models.IsErrorImageCommitting(err) {
  673. ctx.JSON(200, models.BaseErrorMessage(ctx.Tr("repo.image_committing")))
  674. } else {
  675. ctx.JSON(200, models.BaseErrorMessage(ctx.Tr("repo.image_commit_fail")))
  676. }
  677. return
  678. }
  679. ctx.JSON(200, models.BaseOKMessage)
  680. }
  681. func checkTopics(Topics string) ([]string, string) {
  682. var topics = make([]string, 0)
  683. var topicsStr = strings.TrimSpace(Topics)
  684. if len(topicsStr) > 0 {
  685. topics = strings.Split(topicsStr, ",")
  686. }
  687. validTopics, invalidTopics := models.SanitizeAndValidateImageTopics(topics)
  688. if len(validTopics) > 25 {
  689. return nil, "repo.topic.count_prompt"
  690. }
  691. if len(invalidTopics) > 0 {
  692. return nil, "repo.imagetopic.format_prompt"
  693. }
  694. return validTopics, ""
  695. }
  696. func CloudBrainStop(ctx *context.Context) {
  697. var ID = ctx.Params(":id")
  698. var resultCode = "0"
  699. var errorMsg = ""
  700. var status = ""
  701. task := ctx.Cloudbrain
  702. for {
  703. if task.Status == string(models.JobStopped) || task.Status == string(models.JobFailed) || task.Status == string(models.JobSucceeded) {
  704. log.Error("the job(%s) has been stopped", task.JobName, ctx.Data["msgID"])
  705. resultCode = "-1"
  706. errorMsg = "system error"
  707. break
  708. }
  709. err := cloudbrain.StopJob(task.JobID)
  710. if err != nil {
  711. log.Error("StopJob(%s) failed:%v", task.JobName, err, ctx.Data["msgID"])
  712. resultCode = "-1"
  713. errorMsg = "system error"
  714. break
  715. }
  716. task.Status = string(models.JobStopped)
  717. if task.EndTime == 0 {
  718. task.EndTime = timeutil.TimeStampNow()
  719. }
  720. task.ComputeAndSetDuration()
  721. err = models.UpdateJob(task)
  722. if err != nil {
  723. log.Error("UpdateJob(%s) failed:%v", task.JobName, err, ctx.Data["msgID"])
  724. resultCode = "-1"
  725. errorMsg = "system error"
  726. break
  727. }
  728. status = task.Status
  729. break
  730. }
  731. ctx.JSON(200, map[string]interface{}{
  732. "result_code": resultCode,
  733. "error_msg": errorMsg,
  734. "status": status,
  735. "id": ID,
  736. "StatusOK": 0,
  737. })
  738. }
  739. func StopJobsByUserID(userID int64) {
  740. cloudBrains, err := models.GetCloudbrainsNeededStopByUserID(userID)
  741. if err != nil {
  742. log.Warn("Failed to get cloudBrain info", err)
  743. return
  744. }
  745. StopJobs(cloudBrains)
  746. }
  747. func StopJobsByRepoID(repoID int64) {
  748. cloudBrains, err := models.GetCloudbrainsNeededStopByRepoID(repoID)
  749. if err != nil {
  750. log.Warn("Failed to get cloudBrain info", err)
  751. return
  752. }
  753. StopJobs(cloudBrains)
  754. }
  755. /**
  756. */
  757. func StopJobs(cloudBrains []*models.Cloudbrain) {
  758. for _, taskInfo := range cloudBrains {
  759. if taskInfo.Type == models.TypeCloudBrainOne {
  760. err := retry(3, time.Second*30, func() error {
  761. return cloudbrain.StopJob(taskInfo.JobID)
  762. })
  763. logErrorAndUpdateJobStatus(err, taskInfo)
  764. } else {
  765. if taskInfo.JobType == string(models.JobTypeTrain) {
  766. err := retry(3, time.Second*30, func() error {
  767. _, err := modelarts.StopTrainJob(taskInfo.JobID, strconv.FormatInt(taskInfo.VersionID, 10))
  768. return err
  769. })
  770. logErrorAndUpdateJobStatus(err, taskInfo)
  771. } else {
  772. param := models.NotebookAction{
  773. Action: models.ActionStop,
  774. }
  775. err := retry(3, time.Second*30, func() error {
  776. _, err := modelarts.ManageNotebook(taskInfo.JobID, param)
  777. return err
  778. })
  779. logErrorAndUpdateJobStatus(err, taskInfo)
  780. }
  781. }
  782. }
  783. }
  784. func retry(attempts int, sleep time.Duration, f func() error) (err error) {
  785. for i := 0; i < attempts; i++ {
  786. if i > 0 {
  787. log.Warn("retrying after error:", err)
  788. time.Sleep(sleep)
  789. }
  790. err = f()
  791. if err == nil {
  792. return nil
  793. }
  794. }
  795. return fmt.Errorf("after %d attempts, last error: %s", attempts, err)
  796. }
  797. func logErrorAndUpdateJobStatus(err error, taskInfo *models.Cloudbrain) {
  798. if err != nil {
  799. log.Warn("Failed to stop cloudBrain job:"+taskInfo.JobID, err)
  800. } else {
  801. taskInfo.Status = string(models.JobStopped)
  802. if taskInfo.EndTime == 0 {
  803. taskInfo.EndTime = timeutil.TimeStampNow()
  804. }
  805. taskInfo.ComputeAndSetDuration()
  806. err = models.UpdateJob(taskInfo)
  807. if err != nil {
  808. log.Warn("UpdateJob failed", err)
  809. }
  810. }
  811. }
  812. func CloudBrainDel(ctx *context.Context) {
  813. var listType = ctx.Query("debugListType")
  814. if err := deleteCloudbrainJob(ctx); err != nil {
  815. log.Error("deleteCloudbrainJob failed: %v", err, ctx.Data["msgID"])
  816. ctx.ServerError(err.Error(), err)
  817. return
  818. }
  819. var isAdminPage = ctx.Query("isadminpage")
  820. var isHomePage = ctx.Query("ishomepage")
  821. if ctx.IsUserSiteAdmin() && isAdminPage == "true" {
  822. ctx.Redirect(setting.AppSubURL + "/admin" + "/cloudbrains")
  823. } else if isHomePage == "true" {
  824. ctx.Redirect(setting.AppSubURL + "/cloudbrains")
  825. } else {
  826. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/debugjob?debugListType=" + listType)
  827. }
  828. }
  829. func deleteCloudbrainJob(ctx *context.Context) error {
  830. task := ctx.Cloudbrain
  831. if task.Status != string(models.JobStopped) && task.Status != string(models.JobFailed) && task.Status != string(models.JobSucceeded) {
  832. log.Error("the job(%s) has not been stopped", task.JobName, ctx.Data["msgID"])
  833. return errors.New("the job has not been stopped")
  834. }
  835. err := models.DeleteJob(task)
  836. if err != nil {
  837. log.Error("DeleteJob failed: %v", err, ctx.Data["msgID"])
  838. return err
  839. }
  840. deleteJobStorage(task.JobName, models.TypeCloudBrainOne)
  841. return nil
  842. }
  843. func CloudBrainShowModels(ctx *context.Context) {
  844. ctx.Data["PageIsCloudBrain"] = true
  845. ID := ctx.Params(":id")
  846. parentDir := ctx.Query("parentDir")
  847. dirArray := strings.Split(parentDir, "/")
  848. task, err := models.GetCloudbrainByID(ID)
  849. if err != nil {
  850. log.Error("no such job!", ctx.Data["msgID"])
  851. ctx.ServerError("no such job:", err)
  852. return
  853. }
  854. //get dirs
  855. dirs, err := GetModelDirs(task.JobName, parentDir)
  856. if err != nil {
  857. log.Error("GetModelDirs failed:%v", err.Error(), ctx.Data["msgID"])
  858. ctx.ServerError("GetModelDirs failed:", err)
  859. return
  860. }
  861. var fileInfos []storage.FileInfo
  862. err = json.Unmarshal([]byte(dirs), &fileInfos)
  863. if err != nil {
  864. log.Error("json.Unmarshal failed:%v", err.Error(), ctx.Data["msgID"])
  865. ctx.ServerError("json.Unmarshal failed:", err)
  866. return
  867. }
  868. for i, fileInfo := range fileInfos {
  869. temp, _ := time.Parse("2006-01-02 15:04:05", fileInfo.ModTime)
  870. fileInfos[i].ModTime = temp.Local().Format("2006-01-02 15:04:05")
  871. }
  872. sort.Slice(fileInfos, func(i, j int) bool {
  873. return fileInfos[i].ModTime > fileInfos[j].ModTime
  874. })
  875. ctx.Data["Path"] = dirArray
  876. ctx.Data["Dirs"] = fileInfos
  877. ctx.Data["task"] = task
  878. ctx.Data["ID"] = ID
  879. ctx.HTML(200, tplCloudBrainShowModels)
  880. }
  881. func GetPublicImages(ctx *context.Context) {
  882. uid := getUID(ctx)
  883. opts := models.SearchImageOptions{
  884. IncludePublicOnly: true,
  885. UID: uid,
  886. Keyword: ctx.Query("q"),
  887. Topics: ctx.Query("topic"),
  888. IncludeOfficialOnly: ctx.QueryBool("recommend"),
  889. SearchOrderBy: "type desc, num_stars desc,id desc",
  890. Status: models.IMAGE_STATUS_SUCCESS,
  891. }
  892. getImages(ctx, &opts)
  893. }
  894. func GetCustomImages(ctx *context.Context) {
  895. uid := getUID(ctx)
  896. opts := models.SearchImageOptions{
  897. UID: uid,
  898. IncludeOwnerOnly: true,
  899. Keyword: ctx.Query("q"),
  900. Topics: ctx.Query("topic"),
  901. Status: -1,
  902. SearchOrderBy: "id desc",
  903. }
  904. getImages(ctx, &opts)
  905. }
  906. func GetStarImages(ctx *context.Context) {
  907. uid := getUID(ctx)
  908. opts := models.SearchImageOptions{
  909. UID: uid,
  910. IncludeStarByMe: true,
  911. Keyword: ctx.Query("q"),
  912. Topics: ctx.Query("topic"),
  913. Status: models.IMAGE_STATUS_SUCCESS,
  914. SearchOrderBy: "id desc",
  915. }
  916. getImages(ctx, &opts)
  917. }
  918. func getUID(ctx *context.Context) int64 {
  919. var uid int64 = -1
  920. if ctx.IsSigned {
  921. uid = ctx.User.ID
  922. }
  923. return uid
  924. }
  925. func GetAllImages(ctx *context.Context) {
  926. uid := getUID(ctx)
  927. opts := models.SearchImageOptions{
  928. UID: uid,
  929. Keyword: ctx.Query("q"),
  930. Topics: ctx.Query("topic"),
  931. IncludeOfficialOnly: ctx.QueryBool("recommend"),
  932. SearchOrderBy: "id desc",
  933. Status: -1,
  934. }
  935. if ctx.Query("private") != "" {
  936. if ctx.QueryBool("private") {
  937. opts.IncludePrivateOnly = true
  938. } else {
  939. opts.IncludePublicOnly = true
  940. }
  941. }
  942. getImages(ctx, &opts)
  943. }
  944. func getImages(ctx *context.Context, opts *models.SearchImageOptions) {
  945. page := ctx.QueryInt("page")
  946. if page <= 0 {
  947. page = 1
  948. }
  949. pageSize := ctx.QueryInt("pageSize")
  950. if pageSize <= 0 {
  951. pageSize = 15
  952. }
  953. opts.ListOptions = models.ListOptions{
  954. Page: page,
  955. PageSize: pageSize,
  956. }
  957. imageList, total, err := models.SearchImage(opts)
  958. if err != nil {
  959. log.Error("Can not get images:%v", err)
  960. ctx.JSON(http.StatusOK, models.ImagesPageResult{
  961. Count: 0,
  962. Images: []*models.Image{},
  963. })
  964. } else {
  965. ctx.JSON(http.StatusOK, models.ImagesPageResult{
  966. Count: total,
  967. Images: imageList,
  968. })
  969. }
  970. }
  971. func GetModelDirs(jobName string, parentDir string) (string, error) {
  972. var req string
  973. modelActualPath := storage.GetMinioPath(jobName, cloudbrain.ModelMountPath+"/")
  974. if parentDir == "" {
  975. req = "baseDir=" + modelActualPath
  976. } else {
  977. req = "baseDir=" + modelActualPath + "&parentDir=" + parentDir
  978. }
  979. return getDirs(req)
  980. }
  981. func CloudBrainDownloadModel(ctx *context.Context) {
  982. parentDir := ctx.Query("parentDir")
  983. fileName := ctx.Query("fileName")
  984. jobName := ctx.Query("jobName")
  985. filePath := "jobs/" + jobName + "/model/" + parentDir
  986. url, err := storage.Attachments.PresignedGetURL(filePath, fileName)
  987. if err != nil {
  988. log.Error("PresignedGetURL failed: %v", err.Error(), ctx.Data["msgID"])
  989. ctx.ServerError("PresignedGetURL", err)
  990. return
  991. }
  992. http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusMovedPermanently)
  993. }
  994. func GetRate(ctx *context.Context) {
  995. isObjectDetcionAll := ctx.QueryBool("isObjectDetcionAll")
  996. if isObjectDetcionAll {
  997. ctx.Redirect(setting.BenchmarkServerHost + "?username=admin")
  998. return
  999. }
  1000. var ID = ctx.Params(":id")
  1001. job, err := models.GetCloudbrainByID(ID)
  1002. if err != nil {
  1003. ctx.ServerError("GetCloudbrainByJobID failed", err)
  1004. return
  1005. }
  1006. if job.JobType == string(models.JobTypeBenchmark) {
  1007. log.Info("url=" + setting.BenchmarkServerHost + "?username=" + ctx.User.Name)
  1008. ctx.Redirect(setting.BenchmarkServerHost + "?username=" + ctx.User.Name)
  1009. } else if job.JobType == string(models.JobTypeSnn4imagenet) {
  1010. ctx.Redirect(setting.Snn4imagenetServerHost)
  1011. } else if job.JobType == string(models.JobTypeBrainScore) {
  1012. ctx.Redirect(setting.BrainScoreServerHost)
  1013. } else {
  1014. log.Error("JobType error:%s", job.JobType, ctx.Data["msgID"])
  1015. }
  1016. }
  1017. func downloadCode(repo *models.Repository, codePath, branchName string) error {
  1018. //add "file:///" prefix to make the depth valid
  1019. if err := git.Clone(CLONE_FILE_PREFIX+repo.RepoPath(), codePath, git.CloneRepoOptions{Branch: branchName, Depth: 1}); err != nil {
  1020. log.Error("Failed to clone repository: %s (%v)", repo.FullName(), err)
  1021. return err
  1022. }
  1023. configFile, err := os.OpenFile(codePath+"/.git/config", os.O_RDWR, 0666)
  1024. if err != nil {
  1025. log.Error("open file(%s) failed:%v", codePath+"/,git/config", err)
  1026. return err
  1027. }
  1028. defer configFile.Close()
  1029. pos := int64(0)
  1030. reader := bufio.NewReader(configFile)
  1031. for {
  1032. line, err := reader.ReadString('\n')
  1033. if err != nil {
  1034. if err == io.EOF {
  1035. log.Error("not find the remote-url")
  1036. return nil
  1037. } else {
  1038. log.Error("read error: %v", err)
  1039. return err
  1040. }
  1041. }
  1042. if strings.Contains(line, "url") && strings.Contains(line, ".git") {
  1043. originUrl := "\turl = " + repo.CloneLink().HTTPS + "\n"
  1044. if len(line) > len(originUrl) {
  1045. originUrl += strings.Repeat(" ", len(line)-len(originUrl))
  1046. }
  1047. bytes := []byte(originUrl)
  1048. _, err := configFile.WriteAt(bytes, pos)
  1049. if err != nil {
  1050. log.Error("WriteAt failed:%v", err)
  1051. return err
  1052. }
  1053. break
  1054. }
  1055. pos += int64(len(line))
  1056. }
  1057. return nil
  1058. }
  1059. func downloadRateCode(repo *models.Repository, taskName, rateOwnerName, rateRepoName, codePath, benchmarkCategory, gpuType string) error {
  1060. err := os.MkdirAll(codePath, os.ModePerm)
  1061. if err != nil {
  1062. log.Error("mkdir codePath failed", err.Error())
  1063. return err
  1064. }
  1065. repoExt, err := models.GetRepositoryByOwnerAndName(rateOwnerName, rateRepoName)
  1066. if err != nil {
  1067. log.Error("GetRepositoryByOwnerAndName(%s) failed", rateRepoName, err.Error())
  1068. return err
  1069. }
  1070. if err := git.Clone(CLONE_FILE_PREFIX+repoExt.RepoPath(), codePath, git.CloneRepoOptions{Depth: 1}); err != nil {
  1071. log.Error("Failed to clone repository: %s (%v)", repoExt.FullName(), err)
  1072. return err
  1073. }
  1074. fileName := codePath + cloudbrain.TaskInfoName
  1075. f, err := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.ModePerm)
  1076. if err != nil {
  1077. log.Error("OpenFile failed", err.Error())
  1078. return err
  1079. }
  1080. defer f.Close()
  1081. data, err := json.Marshal(models.TaskInfo{
  1082. Username: repo.Owner.Name,
  1083. TaskName: taskName,
  1084. CodeName: repo.Name,
  1085. BenchmarkCategory: strings.Split(benchmarkCategory, ","),
  1086. CodeLink: strings.TrimSuffix(repo.CloneLink().HTTPS, ".git"),
  1087. GpuType: gpuType,
  1088. })
  1089. if err != nil {
  1090. log.Error("json.Marshal failed", err.Error())
  1091. return err
  1092. }
  1093. _, err = f.Write(data)
  1094. if err != nil {
  1095. log.Error("WriteString failed", err.Error())
  1096. return err
  1097. }
  1098. return nil
  1099. }
  1100. func uploadCodeToMinio(codePath, jobName, parentDir string) error {
  1101. files, err := readDir(codePath)
  1102. if err != nil {
  1103. log.Error("readDir(%s) failed: %s", codePath, err.Error())
  1104. return err
  1105. }
  1106. for _, file := range files {
  1107. if file.IsDir() {
  1108. if err = uploadCodeToMinio(codePath+file.Name()+"/", jobName, parentDir+file.Name()+"/"); err != nil {
  1109. log.Error("uploadCodeToMinio(%s) failed: %s", file.Name(), err.Error())
  1110. return err
  1111. }
  1112. } else {
  1113. destObject := setting.CBCodePathPrefix + jobName + parentDir + file.Name()
  1114. sourceFile := codePath + file.Name()
  1115. err = storage.Attachments.UploadObject(destObject, sourceFile)
  1116. if err != nil {
  1117. log.Error("UploadObject(%s) failed: %s", file.Name(), err.Error())
  1118. return err
  1119. }
  1120. }
  1121. }
  1122. return nil
  1123. }
  1124. func mkModelPath(modelPath string) error {
  1125. err := os.MkdirAll(modelPath, os.ModePerm)
  1126. if err != nil {
  1127. log.Error("MkdirAll(%s) failed:%v", modelPath, err)
  1128. return err
  1129. }
  1130. fileName := modelPath + "README"
  1131. f, err := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.ModePerm)
  1132. if err != nil {
  1133. log.Error("OpenFile failed", err.Error())
  1134. return err
  1135. }
  1136. defer f.Close()
  1137. _, err = f.WriteString("You can put the model file into this directory and download it by the web page.")
  1138. if err != nil {
  1139. log.Error("WriteString failed", err.Error())
  1140. return err
  1141. }
  1142. return nil
  1143. }
  1144. func deleteJobStorage(jobName string, cloudbrainType int) error {
  1145. //delete local
  1146. localJobPath := setting.JobPath + jobName
  1147. err := os.RemoveAll(localJobPath)
  1148. if err != nil {
  1149. log.Error("RemoveAll(%s) failed:%v", localJobPath, err)
  1150. }
  1151. //delete oss
  1152. if cloudbrainType == models.TypeCloudBrainOne {
  1153. dirPath := setting.CBCodePathPrefix + jobName + "/"
  1154. err = storage.Attachments.DeleteDir(dirPath)
  1155. if err != nil {
  1156. log.Error("DeleteDir(%s) failed:%v", localJobPath, err)
  1157. }
  1158. } else if cloudbrainType == models.TypeCloudBrainTwo {
  1159. //dirPath := setting.CodePathPrefix + jobName + "/"
  1160. //err = storage.ObsRemoveObject(setting.Bucket, dirPath)
  1161. //if err != nil {
  1162. // log.Error("ObsRemoveObject(%s) failed:%v", localJobPath, err)
  1163. //}
  1164. log.Info("no need to delete")
  1165. } else {
  1166. log.Error("cloudbrainType(%d) error", cloudbrainType)
  1167. }
  1168. return nil
  1169. }
  1170. func SyncCloudbrainStatus() {
  1171. cloudBrains, err := models.GetCloudBrainUnStoppedJob()
  1172. if err != nil {
  1173. log.Error("GetCloudBrainUnStoppedJob failed:", err.Error())
  1174. return
  1175. }
  1176. for _, task := range cloudBrains {
  1177. if task.Type == models.TypeCloudBrainOne {
  1178. result, err := cloudbrain.GetJob(task.JobID)
  1179. if err != nil {
  1180. log.Error("GetJob(%s) failed:%v", task.JobName, err)
  1181. continue
  1182. }
  1183. if result != nil {
  1184. jobRes, _ := models.ConvertToJobResultPayload(result.Payload)
  1185. taskRoles := jobRes.TaskRoles
  1186. taskRes, _ := models.ConvertToTaskPod(taskRoles[cloudbrain.SubTaskName].(map[string]interface{}))
  1187. task.Status = taskRes.TaskStatuses[0].State
  1188. if task.Status != string(models.JobWaiting) {
  1189. models.ParseAndSetDurationFromCloudBrainOne(jobRes, task)
  1190. err = models.UpdateJob(task)
  1191. if err != nil {
  1192. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1193. }
  1194. var maxDuration int64
  1195. if task.JobType == string(models.JobTypeBenchmark) {
  1196. maxDuration = setting.BenchmarkMaxDuration
  1197. } else {
  1198. maxDuration = setting.MaxDuration
  1199. }
  1200. if task.Duration >= maxDuration {
  1201. log.Info("begin to stop job(%s), because of the duration", task.JobName)
  1202. err = cloudbrain.StopJob(task.JobID)
  1203. if err != nil {
  1204. log.Error("StopJob(%s) failed:%v", task.JobName, err)
  1205. continue
  1206. }
  1207. task.Status = string(models.JobStopped)
  1208. if task.EndTime == 0 {
  1209. task.EndTime = timeutil.TimeStampNow()
  1210. }
  1211. task.ComputeAndSetDuration()
  1212. err = models.UpdateJob(task)
  1213. if err != nil {
  1214. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1215. }
  1216. }
  1217. }
  1218. }
  1219. } else if task.Type == models.TypeCloudBrainTwo {
  1220. if task.JobType == string(models.JobTypeDebug) {
  1221. //result, err := modelarts.GetJob(task.JobID)
  1222. result, err := modelarts.GetNotebook2(task.JobID)
  1223. if err != nil {
  1224. log.Error("GetJob(%s) failed:%v", task.JobName, err)
  1225. continue
  1226. }
  1227. if result != nil {
  1228. task.Status = result.Status
  1229. if task.StartTime == 0 && result.Lease.UpdateTime > 0 {
  1230. task.StartTime = timeutil.TimeStamp(result.Lease.UpdateTime / 1000)
  1231. }
  1232. if task.EndTime == 0 && models.IsModelArtsDebugJobTerminal(task.Status) {
  1233. task.EndTime = timeutil.TimeStampNow()
  1234. }
  1235. task.CorrectCreateUnix()
  1236. task.ComputeAndSetDuration()
  1237. err = models.UpdateJob(task)
  1238. if err != nil {
  1239. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1240. continue
  1241. }
  1242. }
  1243. } else if task.JobType == string(models.JobTypeTrain) || task.JobType == string(models.JobTypeInference) {
  1244. result, err := modelarts.GetTrainJob(task.JobID, strconv.FormatInt(task.VersionID, 10))
  1245. if err != nil {
  1246. log.Error("GetTrainJob(%s) failed:%v", task.JobName, err)
  1247. continue
  1248. }
  1249. if result != nil {
  1250. task.Status = modelarts.TransTrainJobStatus(result.IntStatus)
  1251. task.Duration = result.Duration / 1000
  1252. task.TrainJobDuration = result.TrainJobDuration
  1253. if task.StartTime == 0 && result.StartTime > 0 {
  1254. task.StartTime = timeutil.TimeStamp(result.StartTime / 1000)
  1255. }
  1256. task.TrainJobDuration = models.ConvertDurationToStr(task.Duration)
  1257. if task.EndTime == 0 && models.IsTrainJobTerminal(task.Status) && task.StartTime > 0 {
  1258. task.EndTime = task.StartTime.Add(task.Duration)
  1259. }
  1260. task.CorrectCreateUnix()
  1261. err = models.UpdateJob(task)
  1262. if err != nil {
  1263. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1264. continue
  1265. }
  1266. }
  1267. } else {
  1268. log.Error("task.JobType(%s) is error:%s", task.JobName, task.JobType)
  1269. }
  1270. } else {
  1271. log.Error("task.Type(%s) is error:%d", task.JobName, task.Type)
  1272. }
  1273. }
  1274. return
  1275. }
  1276. func HandleTaskWithNoDuration(ctx *context.Context) {
  1277. log.Info("HandleTaskWithNoDuration start")
  1278. count := 0
  1279. start := time.Now().Unix()
  1280. for {
  1281. cloudBrains, err := models.GetStoppedJobWithNoDurationJob()
  1282. if err != nil {
  1283. log.Error("HandleTaskWithNoTrainJobDuration failed:", err.Error())
  1284. break
  1285. }
  1286. if len(cloudBrains) == 0 {
  1287. log.Info("HandleTaskWithNoTrainJobDuration:no task need handle")
  1288. break
  1289. }
  1290. handleNoDurationTask(cloudBrains)
  1291. count += len(cloudBrains)
  1292. if len(cloudBrains) < 100 {
  1293. log.Info("HandleTaskWithNoTrainJobDuration:task less than 100")
  1294. break
  1295. }
  1296. if time.Now().Unix()-start > 600 {
  1297. log.Info("HandleTaskWithNoDuration : time out")
  1298. ctx.JSON(200, fmt.Sprintf("task stop for time out,count=%d", count))
  1299. return
  1300. }
  1301. }
  1302. log.Info("HandleTaskWithNoTrainJobDuration:count=%d", count)
  1303. ctx.JSON(200, fmt.Sprintf("success,count=%d", count))
  1304. }
  1305. func handleNoDurationTask(cloudBrains []*models.Cloudbrain) {
  1306. for _, task := range cloudBrains {
  1307. time.Sleep(time.Millisecond * 100)
  1308. log.Info("Handle job ,%+v", task)
  1309. if task.Type == models.TypeCloudBrainOne {
  1310. result, err := cloudbrain.GetJob(task.JobID)
  1311. if err != nil {
  1312. log.Error("GetJob(%s) failed:%v", task.JobName, err)
  1313. updateDefaultDuration(task)
  1314. continue
  1315. }
  1316. if result != nil {
  1317. if result.Msg != "success" {
  1318. updateDefaultDuration(task)
  1319. continue
  1320. }
  1321. jobRes, err := models.ConvertToJobResultPayload(result.Payload)
  1322. if err != nil || len(jobRes.TaskRoles) == 0 {
  1323. updateDefaultDuration(task)
  1324. continue
  1325. }
  1326. taskRoles := jobRes.TaskRoles
  1327. taskRes, err := models.ConvertToTaskPod(taskRoles[cloudbrain.SubTaskName].(map[string]interface{}))
  1328. if err != nil || len(taskRes.TaskStatuses) == 0 {
  1329. updateDefaultDuration(task)
  1330. continue
  1331. }
  1332. task.Status = taskRes.TaskStatuses[0].State
  1333. log.Info("task startTime = %v endTime= %v ,jobId=%d", jobRes.JobStatus.StartTime, jobRes.JobStatus.EndTime, task.ID)
  1334. if jobRes.JobStatus.CreatedTime > 0 {
  1335. task.StartTime = timeutil.TimeStamp(jobRes.JobStatus.CreatedTime / 1000)
  1336. if jobRes.JobStatus.CompletedTime > 0 {
  1337. task.EndTime = timeutil.TimeStamp(jobRes.JobStatus.CompletedTime / 1000)
  1338. } else {
  1339. task.EndTime = task.UpdatedUnix
  1340. }
  1341. } else {
  1342. task.StartTime = 0
  1343. task.EndTime = 0
  1344. }
  1345. if task.EndTime < task.StartTime {
  1346. log.Info("endTime[%v] is less than starTime[%v],jobId=%d", task.EndTime, task.StartTime, task.ID)
  1347. st := task.StartTime
  1348. task.StartTime = task.EndTime
  1349. task.EndTime = st
  1350. }
  1351. task.Duration = task.EndTime.AsTime().Unix() - task.StartTime.AsTime().Unix()
  1352. task.TrainJobDuration = models.ConvertDurationToStr(task.Duration)
  1353. err = models.UpdateJob(task)
  1354. if err != nil {
  1355. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1356. }
  1357. }
  1358. } else if task.Type == models.TypeCloudBrainTwo {
  1359. if task.JobType == string(models.JobTypeDebug) {
  1360. //result, err := modelarts.GetJob(task.JobID)
  1361. result, err := modelarts.GetNotebook2(task.JobID)
  1362. if err != nil {
  1363. log.Error("GetJob(%s) failed:%v", task.JobName, err)
  1364. updateDefaultDuration(task)
  1365. continue
  1366. }
  1367. if result != nil {
  1368. task.Status = result.Status
  1369. startTime := result.Lease.CreateTime
  1370. duration := result.Lease.Duration / 1000
  1371. if startTime > 0 {
  1372. task.StartTime = timeutil.TimeStamp(startTime / 1000)
  1373. task.EndTime = task.StartTime.Add(duration)
  1374. }
  1375. task.CorrectCreateUnix()
  1376. task.ComputeAndSetDuration()
  1377. err = models.UpdateJob(task)
  1378. if err != nil {
  1379. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1380. continue
  1381. }
  1382. }
  1383. } else if task.JobType == string(models.JobTypeTrain) || task.JobType == string(models.JobTypeInference) {
  1384. result, err := modelarts.GetTrainJob(task.JobID, strconv.FormatInt(task.VersionID, 10))
  1385. if err != nil {
  1386. log.Error("GetTrainJob(%s) failed:%v", task.JobName, err)
  1387. updateDefaultDuration(task)
  1388. continue
  1389. }
  1390. if result != nil {
  1391. startTime := result.StartTime / 1000
  1392. if startTime > 0 {
  1393. task.StartTime = timeutil.TimeStamp(startTime)
  1394. task.EndTime = task.StartTime.Add(result.Duration / 1000)
  1395. }
  1396. task.ComputeAndSetDuration()
  1397. err = models.UpdateJob(task)
  1398. if err != nil {
  1399. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1400. continue
  1401. }
  1402. }
  1403. } else {
  1404. log.Error("task.JobType(%s) is error:%s", task.JobName, task.JobType)
  1405. }
  1406. } else {
  1407. log.Error("task.Type(%s) is error:%d", task.JobName, task.Type)
  1408. }
  1409. }
  1410. }
  1411. func updateDefaultDuration(task *models.Cloudbrain) {
  1412. log.Info("updateDefaultDuration: taskId=%d", task.ID)
  1413. task.StartTime = task.CreatedUnix
  1414. task.EndTime = task.UpdatedUnix
  1415. task.ComputeAndSetDuration()
  1416. err := models.UpdateJob(task)
  1417. if err != nil {
  1418. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1419. }
  1420. }
  1421. func CloudBrainBenchmarkIndex(ctx *context.Context) {
  1422. MustEnableCloudbrain(ctx)
  1423. repo := ctx.Repo.Repository
  1424. page := ctx.QueryInt("page")
  1425. if page <= 0 {
  1426. page = 1
  1427. }
  1428. var jobTypes []string
  1429. jobTypes = append(jobTypes, string(models.JobTypeBenchmark))
  1430. ciTasks, count, err := models.Cloudbrains(&models.CloudbrainsOptions{
  1431. ListOptions: models.ListOptions{
  1432. Page: page,
  1433. PageSize: setting.UI.IssuePagingNum,
  1434. },
  1435. RepoID: repo.ID,
  1436. Type: models.TypeCloudBrainOne,
  1437. JobTypes: jobTypes,
  1438. })
  1439. if err != nil {
  1440. ctx.ServerError("Get debugjob faild:", err)
  1441. return
  1442. }
  1443. for i, task := range ciTasks {
  1444. ciTasks[i].CanDel = cloudbrain.CanDeleteJob(ctx, &task.Cloudbrain)
  1445. ciTasks[i].Cloudbrain.ComputeResource = task.ComputeResource
  1446. if ciTasks[i].TrainJobDuration == "" {
  1447. if ciTasks[i].Duration == 0 {
  1448. var duration int64
  1449. if task.Status == string(models.JobRunning) {
  1450. duration = time.Now().Unix() - int64(task.Cloudbrain.CreatedUnix)
  1451. } else {
  1452. duration = int64(task.Cloudbrain.UpdatedUnix) - int64(task.Cloudbrain.CreatedUnix)
  1453. }
  1454. ciTasks[i].Duration = duration
  1455. }
  1456. ciTasks[i].TrainJobDuration = models.ConvertDurationToStr(ciTasks[i].Duration)
  1457. }
  1458. ciTasks[i].BenchmarkTypeName = ""
  1459. if task.BenchmarkTypeID > 0 {
  1460. for _, benchmarkType := range GetBenchmarkTypes(ctx).BenchmarkType {
  1461. if task.BenchmarkTypeID == benchmarkType.Id {
  1462. ciTasks[i].BenchmarkTypeRankLink = benchmarkType.RankLink
  1463. ciTasks[i].BenchmarkTypeName = benchmarkType.First
  1464. break
  1465. }
  1466. }
  1467. }
  1468. }
  1469. pager := context.NewPagination(int(count), setting.UI.IssuePagingNum, page, 5)
  1470. ctx.Data["Page"] = pager
  1471. ctx.Data["PageIsCloudBrain"] = true
  1472. ctx.Data["Tasks"] = ciTasks
  1473. ctx.Data["CanCreate"] = cloudbrain.CanCreateOrDebugJob(ctx)
  1474. ctx.Data["RepoIsEmpty"] = repo.IsEmpty
  1475. ctx.HTML(200, tplCloudBrainBenchmarkIndex)
  1476. }
  1477. func GetChildTypes(ctx *context.Context) {
  1478. benchmarkTypeID := ctx.QueryInt("benchmark_type_id")
  1479. re := make(map[string]interface{})
  1480. for {
  1481. var isExist bool
  1482. for _, benchmarkType := range GetBenchmarkTypes(ctx).BenchmarkType {
  1483. if benchmarkTypeID == benchmarkType.Id {
  1484. isExist = true
  1485. re["child_types"] = benchmarkType.Second
  1486. re["result_code"] = "0"
  1487. break
  1488. }
  1489. }
  1490. if !isExist {
  1491. re["result_code"] = "1"
  1492. log.Error("no such benchmark_type_id", ctx.Data["MsgID"])
  1493. re["errMsg"] = "system error"
  1494. break
  1495. }
  1496. break
  1497. }
  1498. ctx.JSON(200, re)
  1499. }
  1500. func CloudBrainBenchmarkNew(ctx *context.Context) {
  1501. ctx.Data["description"] = ""
  1502. ctx.Data["benchmarkTypeID"] = -1
  1503. ctx.Data["benchmark_child_types_id_hidden"] = -1
  1504. err := cloudBrainNewDataPrepare(ctx)
  1505. if err != nil {
  1506. ctx.ServerError("get new cloudbrain info failed", err)
  1507. return
  1508. }
  1509. ctx.HTML(200, tplCloudBrainBenchmarkNew)
  1510. }
  1511. func getBenchmarkAttachment(benchmarkTypeID, benchmarkChildTypeID int, ctx *context.Context) (*models.BenchmarkDataset, error) {
  1512. var childInfo *models.BenchmarkDataset
  1513. var isExist bool
  1514. for _, benchmarkType := range GetBenchmarkTypes(ctx).BenchmarkType {
  1515. if benchmarkType.Id == benchmarkTypeID {
  1516. for _, childType := range benchmarkType.Second {
  1517. if childType.Id == benchmarkChildTypeID {
  1518. childInfo = childType
  1519. isExist = true
  1520. break
  1521. }
  1522. }
  1523. break
  1524. }
  1525. }
  1526. if !isExist {
  1527. log.Error("no such benchmark_type_id&benchmark_child_type_id")
  1528. return childInfo, errors.New("no such benchmark_type_id&benchmark_child_type_id")
  1529. }
  1530. return childInfo, nil
  1531. }
  1532. func getBenchmarkGpuQueue(gpuQueue string) (string, error) {
  1533. queue := ""
  1534. if benchmarkGpuInfos == nil {
  1535. if err := json.Unmarshal([]byte(setting.BenchmarkGpuTypes), &benchmarkGpuInfos); err != nil {
  1536. log.Error("json.Unmarshal BenchmarkGpuTypes(%s) failed:%v", setting.BenchmarkGpuTypes, err)
  1537. return queue, err
  1538. }
  1539. }
  1540. var isExist bool
  1541. for _, gpuInfo := range benchmarkGpuInfos.GpuInfo {
  1542. if gpuQueue == gpuInfo.Queue {
  1543. isExist = true
  1544. queue = gpuQueue
  1545. break
  1546. }
  1547. }
  1548. if !isExist {
  1549. log.Error("no such gpuQueue, %s", gpuQueue)
  1550. return queue, errors.New("no such gpuQueue")
  1551. }
  1552. return queue, nil
  1553. }
  1554. func getBenchmarkResourceSpec(resourceSpecID int) (int, error) {
  1555. var id int
  1556. if benchmarkResourceSpecs == nil {
  1557. if err := json.Unmarshal([]byte(setting.BenchmarkResourceSpecs), &benchmarkResourceSpecs); err != nil {
  1558. log.Error("json.Unmarshal BenchmarkResourceSpecs(%s) failed:%v", setting.BenchmarkResourceSpecs, err)
  1559. return id, err
  1560. }
  1561. }
  1562. var isExist bool
  1563. for _, resourceSpec := range benchmarkResourceSpecs.ResourceSpec {
  1564. if resourceSpecID == resourceSpec.Id {
  1565. isExist = true
  1566. id = resourceSpecID
  1567. break
  1568. }
  1569. }
  1570. if !isExist {
  1571. log.Error("no such resourceSpecID, %d", resourceSpecID)
  1572. return id, errors.New("no such resourceSpec")
  1573. }
  1574. return id, nil
  1575. }
  1576. func CloudBrainBenchmarkCreate(ctx *context.Context, form auth.CreateCloudBrainForm) {
  1577. ctx.Data["PageIsCloudBrain"] = true
  1578. displayJobName := form.DisplayJobName
  1579. jobName := util.ConvertDisplayJobNameToJobName(displayJobName)
  1580. image := form.Image
  1581. gpuQueue := form.GpuType
  1582. command := cloudbrain.CommandBenchmark
  1583. codePath := setting.JobPath + jobName + cloudbrain.CodeMountPath
  1584. resourceSpecId := cloudbrain.BenchMarkResourceID
  1585. benchmarkTypeID := form.BenchmarkTypeID
  1586. benchmarkChildTypeID := form.BenchmarkChildTypeID
  1587. ctx.Data["description"] = form.Description
  1588. ctx.Data["benchmarkTypeID"] = benchmarkTypeID
  1589. ctx.Data["benchmark_child_types_id_hidden"] = benchmarkChildTypeID
  1590. repo := ctx.Repo.Repository
  1591. tasks, err := models.GetCloudbrainsByDisplayJobName(repo.ID, string(models.JobTypeBenchmark), displayJobName)
  1592. if err == nil {
  1593. if len(tasks) != 0 {
  1594. log.Error("the job name did already exist", ctx.Data["MsgID"])
  1595. cloudBrainNewDataPrepare(ctx)
  1596. ctx.RenderWithErr("the job name did already exist", tplCloudBrainBenchmarkNew, &form)
  1597. return
  1598. }
  1599. } else {
  1600. if !models.IsErrJobNotExist(err) {
  1601. log.Error("system error, %v", err, ctx.Data["MsgID"])
  1602. cloudBrainNewDataPrepare(ctx)
  1603. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  1604. return
  1605. }
  1606. }
  1607. if !jobNamePattern.MatchString(jobName) {
  1608. cloudBrainNewDataPrepare(ctx)
  1609. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_jobname_err"), tplCloudBrainBenchmarkNew, &form)
  1610. return
  1611. }
  1612. childInfo, err := getBenchmarkAttachment(benchmarkTypeID, benchmarkChildTypeID, ctx)
  1613. if err != nil {
  1614. log.Error("getBenchmarkAttachment failed:%v", err, ctx.Data["MsgID"])
  1615. cloudBrainNewDataPrepare(ctx)
  1616. ctx.RenderWithErr("benchmark type error", tplCloudBrainBenchmarkNew, &form)
  1617. return
  1618. }
  1619. _, err = getBenchmarkGpuQueue(gpuQueue)
  1620. if err != nil {
  1621. log.Error("getBenchmarkGpuQueue failed:%v", err, ctx.Data["MsgID"])
  1622. cloudBrainNewDataPrepare(ctx)
  1623. ctx.RenderWithErr("gpu queue error", tplCloudBrainBenchmarkNew, &form)
  1624. return
  1625. }
  1626. _, err = getBenchmarkResourceSpec(resourceSpecId)
  1627. if err != nil {
  1628. log.Error("getBenchmarkResourceSpec failed:%v", err, ctx.Data["MsgID"])
  1629. cloudBrainNewDataPrepare(ctx)
  1630. ctx.RenderWithErr("resource spec error", tplCloudBrainBenchmarkNew, &form)
  1631. return
  1632. }
  1633. count, err := models.GetCloudbrainCountByUserID(ctx.User.ID, string(models.JobTypeBenchmark))
  1634. if err != nil {
  1635. log.Error("GetCloudbrainCountByUserID failed:%v", err, ctx.Data["MsgID"])
  1636. cloudBrainNewDataPrepare(ctx)
  1637. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  1638. return
  1639. } else {
  1640. if count >= 1 {
  1641. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  1642. cloudBrainNewDataPrepare(ctx)
  1643. ctx.RenderWithErr("you have already a running or waiting task, can not create more", tplCloudBrainBenchmarkNew, &form)
  1644. return
  1645. }
  1646. }
  1647. os.RemoveAll(codePath)
  1648. if err := downloadCode(repo, codePath, cloudbrain.DefaultBranchName); err != nil {
  1649. log.Error("downloadCode failed, %v", err, ctx.Data["MsgID"])
  1650. cloudBrainNewDataPrepare(ctx)
  1651. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  1652. return
  1653. }
  1654. if _, err := os.Stat(codePath + "/train.py"); err != nil {
  1655. if os.IsNotExist(err) {
  1656. // file does not exist
  1657. log.Error("train.py does not exist, %v", err, ctx.Data["MsgID"])
  1658. cloudBrainNewDataPrepare(ctx)
  1659. ctx.RenderWithErr("train.py does not exist", tplCloudBrainBenchmarkNew, &form)
  1660. } else {
  1661. log.Error("Stat failed, %v", err, ctx.Data["MsgID"])
  1662. cloudBrainNewDataPrepare(ctx)
  1663. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  1664. }
  1665. return
  1666. } else if _, err := os.Stat(codePath + "/test.py"); err != nil {
  1667. if os.IsNotExist(err) {
  1668. // file does not exist
  1669. log.Error("test.py does not exist, %v", err, ctx.Data["MsgID"])
  1670. cloudBrainNewDataPrepare(ctx)
  1671. ctx.RenderWithErr("test.py does not exist", tplCloudBrainBenchmarkNew, &form)
  1672. } else {
  1673. log.Error("Stat failed, %v", err, ctx.Data["MsgID"])
  1674. cloudBrainNewDataPrepare(ctx)
  1675. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  1676. }
  1677. return
  1678. }
  1679. if err := uploadCodeToMinio(codePath+"/", jobName, cloudbrain.CodeMountPath+"/"); err != nil {
  1680. log.Error("uploadCodeToMinio failed, %v", err, ctx.Data["MsgID"])
  1681. cloudBrainNewDataPrepare(ctx)
  1682. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  1683. return
  1684. }
  1685. benchmarkPath := setting.JobPath + jobName + cloudbrain.BenchMarkMountPath
  1686. var gpuType string
  1687. for _, gpuInfo := range gpuInfos.GpuInfo {
  1688. if gpuInfo.Queue == gpuQueue {
  1689. gpuType = gpuInfo.Value
  1690. }
  1691. }
  1692. if err := downloadRateCode(repo, jobName, childInfo.Owner, childInfo.RepoName, benchmarkPath, form.BenchmarkCategory, gpuType); err != nil {
  1693. log.Error("downloadRateCode failed, %v", err, ctx.Data["MsgID"])
  1694. //cloudBrainNewDataPrepare(ctx)
  1695. //ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  1696. //return
  1697. }
  1698. if err := uploadCodeToMinio(benchmarkPath+"/", jobName, cloudbrain.BenchMarkMountPath+"/"); err != nil {
  1699. log.Error("uploadCodeToMinio failed, %v", err, ctx.Data["MsgID"])
  1700. //cloudBrainNewDataPrepare(ctx)
  1701. //ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  1702. //return
  1703. }
  1704. err = cloudbrain.GenerateTask(ctx, displayJobName, jobName, image, command, childInfo.Attachment, storage.GetMinioPath(jobName, cloudbrain.CodeMountPath+"/"),
  1705. storage.GetMinioPath(jobName, cloudbrain.ModelMountPath+"/"),
  1706. storage.GetMinioPath(jobName, cloudbrain.BenchMarkMountPath+"/"), storage.GetMinioPath(jobName, cloudbrain.Snn4imagenetMountPath+"/"),
  1707. storage.GetMinioPath(jobName, cloudbrain.BrainScoreMountPath+"/"), string(models.JobTypeBenchmark), gpuQueue, form.Description, cloudbrain.DefaultBranchName, "", "",
  1708. benchmarkTypeID, benchmarkChildTypeID, resourceSpecId)
  1709. if err != nil {
  1710. cloudBrainNewDataPrepare(ctx)
  1711. ctx.RenderWithErr(err.Error(), tplCloudBrainBenchmarkNew, &form)
  1712. return
  1713. }
  1714. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/cloudbrain/benchmark")
  1715. }
  1716. func BenchmarkDel(ctx *context.Context) {
  1717. if err := deleteCloudbrainJob(ctx); err != nil {
  1718. log.Error("deleteCloudbrainJob failed: %v", err, ctx.Data["msgID"])
  1719. ctx.ServerError(err.Error(), err)
  1720. return
  1721. }
  1722. var isAdminPage = ctx.Query("isadminpage")
  1723. var isHomePage = ctx.Query("ishomepage")
  1724. if ctx.IsUserSiteAdmin() && isAdminPage == "true" {
  1725. ctx.Redirect(setting.AppSubURL + "/admin" + "/cloudbrains")
  1726. } else if isHomePage == "true" {
  1727. ctx.Redirect(setting.AppSubURL + "/cloudbrains")
  1728. } else {
  1729. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/cloudbrain/benchmark")
  1730. }
  1731. }
  1732. func CloudBrainTrainJobNew(ctx *context.Context) {
  1733. err := cloudBrainNewDataPrepare(ctx)
  1734. if err != nil {
  1735. ctx.ServerError("get new train-job info failed", err)
  1736. return
  1737. }
  1738. ctx.HTML(http.StatusOK, tplCloudBrainTrainJobNew)
  1739. }
  1740. func getTrainJobCommand(form auth.CreateCloudBrainForm) (string, error) {
  1741. var command string
  1742. bootFile := form.BootFile
  1743. params := form.Params
  1744. if !strings.HasSuffix(bootFile, ".py") {
  1745. log.Error("bootFile(%s) format error", bootFile)
  1746. return command, errors.New("bootFile format error")
  1747. }
  1748. var parameters models.Parameters
  1749. var param string
  1750. if len(params) != 0 {
  1751. err := json.Unmarshal([]byte(params), &parameters)
  1752. if err != nil {
  1753. log.Error("Failed to Unmarshal params: %s (%v)", params, err)
  1754. return command, err
  1755. }
  1756. for _, parameter := range parameters.Parameter {
  1757. param += " --" + parameter.Label + "=" + parameter.Value
  1758. }
  1759. }
  1760. command += "python /code/" + bootFile + param + " > " + cloudbrain.ModelMountPath + "/" + form.DisplayJobName + "-" + cloudbrain.LogFile
  1761. return command, nil
  1762. }
  1763. func CloudBrainTrainJobDel(ctx *context.Context) {
  1764. var listType = ctx.Query("listType")
  1765. if err := deleteCloudbrainJob(ctx); err != nil {
  1766. log.Error("deleteCloudbrainJob failed: %v", err, ctx.Data["msgID"])
  1767. ctx.ServerError(err.Error(), err)
  1768. return
  1769. }
  1770. var isAdminPage = ctx.Query("isadminpage")
  1771. var isHomePage = ctx.Query("ishomepage")
  1772. if ctx.IsUserSiteAdmin() && isAdminPage == "true" {
  1773. ctx.Redirect(setting.AppSubURL + "/admin" + "/cloudbrains")
  1774. } else if isHomePage == "true" {
  1775. ctx.Redirect(setting.AppSubURL + "/cloudbrains")
  1776. } else {
  1777. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/train-job?listType=" + listType)
  1778. }
  1779. }
  1780. func GetBenchmarkTypes(ctx *context.Context) *models.BenchmarkTypes {
  1781. var lang = ctx.Locale.Language()
  1782. if benchmarkTypesMap[lang] == nil {
  1783. var val = i18n.Tr(lang, BENCHMARK_TYPE_CODE)
  1784. //use config
  1785. val = setting.BenchmarkTypes
  1786. var tempType *models.BenchmarkTypes
  1787. if err := json.Unmarshal([]byte(val), &tempType); err != nil {
  1788. log.Error("json.Unmarshal BenchmarkTypes(%s) failed:%v", val, err, ctx.Data["MsgID"])
  1789. return &models.BenchmarkTypes{}
  1790. }
  1791. benchmarkTypesMap[lang] = tempType
  1792. }
  1793. return benchmarkTypesMap[lang]
  1794. }