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 63 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
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
4 years ago
5 years ago
4 years ago
4 years ago
5 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
5 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
3 years ago
3 years ago
4 years ago
4 years ago
3 years ago
5 years ago
3 years ago
3 years ago
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
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
4 years ago
3 years ago
5 years ago
3 years ago
4 years ago
4 years ago
5 years ago
3 years ago
4 years ago
5 years ago
4 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
5 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
4 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
3 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
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
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
4 years ago
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
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
4 years ago
3 years ago
3 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
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.Data["branchName"] = task.BranchName
  522. ctx.HTML(200, tpName)
  523. }
  524. func CloudBrainDebug(ctx *context.Context) {
  525. task := ctx.Cloudbrain
  526. debugUrl := setting.DebugServerHost + "jpylab_" + task.JobID + "_" + task.SubTaskName
  527. ctx.Redirect(debugUrl)
  528. }
  529. func CloudBrainCommitImageShow(ctx *context.Context) {
  530. ctx.Data["PageIsCloudBrain"] = true
  531. ctx.Data["Type"] = ctx.Cloudbrain.Type
  532. ctx.HTML(200, tplCloudBrainImageSubmit)
  533. }
  534. func CloudBrainImageEdit(ctx *context.Context) {
  535. ctx.Data["PageIsImageEdit"] = true
  536. ctx.Data["PageFrom"] = ctx.Params(":from")
  537. var ID = ctx.Params(":id")
  538. id, err := strconv.ParseInt(ID, 10, 64)
  539. if err != nil {
  540. log.Error("GetImageByID failed:%v", err.Error())
  541. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  542. }
  543. image, err := models.GetImageByID(id)
  544. if err != nil {
  545. log.Error("GetImageByID failed:%v", err.Error())
  546. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  547. }
  548. ctx.Data["Image"] = image
  549. ctx.HTML(http.StatusOK, tplCloudBrainImageEdit)
  550. }
  551. func CloudBrainImageEditPost(ctx *context.Context, form auth.EditImageCloudBrainForm) {
  552. if utf8.RuneCountInString(form.Description) > 255 {
  553. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("dataset.description_format_err", 255)))
  554. return
  555. }
  556. validTopics, errMessage := checkTopics(form.Topics)
  557. if errMessage != "" {
  558. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr(errMessage)))
  559. return
  560. }
  561. image, err := models.GetImageByID(form.ID)
  562. if err != nil {
  563. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("repo.image_not_exist")))
  564. }
  565. image.IsPrivate = form.IsPrivate
  566. image.Description = form.Description
  567. err = models.WithTx(func(ctx models.DBContext) error {
  568. if err := models.UpdateLocalImage(image); err != nil {
  569. return err
  570. }
  571. if err := models.SaveImageTopics(image.ID, validTopics...); err != nil {
  572. return err
  573. }
  574. return nil
  575. })
  576. if err != nil {
  577. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("repo.image_not_exist")))
  578. } else {
  579. ctx.JSON(http.StatusOK, models.BaseOKMessage)
  580. }
  581. }
  582. func CloudBrainImageDelete(ctx *context.Context) {
  583. var ID = ctx.Params(":id")
  584. id, err := strconv.ParseInt(ID, 10, 64)
  585. if err != nil {
  586. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("repo.image_not_exist")))
  587. return
  588. }
  589. err = models.DeleteLocalImage(id)
  590. if err != nil {
  591. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("repo.image_delete_fail")))
  592. } else {
  593. ctx.JSON(http.StatusOK, models.BaseOKMessage)
  594. }
  595. }
  596. func CloudBrainCommitImageCheck(ctx *context.Context, form auth.CommitImageCloudBrainForm) {
  597. isExist, _ := models.IsImageExistByUser(form.Tag, ctx.User.ID)
  598. if isExist {
  599. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("repo.image_overwrite")))
  600. } else {
  601. ctx.JSON(http.StatusOK, models.BaseOKMessage)
  602. }
  603. }
  604. func CloudBrainAdminCommitImage(ctx *context.Context, form auth.CommitAdminImageCloudBrainForm) {
  605. if !NamePattern.MatchString(form.Tag) {
  606. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("dataset.title_format_err")))
  607. return
  608. }
  609. if utf8.RuneCountInString(form.Description) > 255 {
  610. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("dataset.description_format_err", 255)))
  611. return
  612. }
  613. validTopics, errMessage := checkTopics(form.Topics)
  614. if errMessage != "" {
  615. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr(errMessage)))
  616. return
  617. }
  618. err := cloudbrain.CommitAdminImage(models.CommitImageParams{
  619. CommitImageCloudBrainParams: models.CommitImageCloudBrainParams{
  620. ImageDescription: form.Description,
  621. ImageTag: form.Tag,
  622. },
  623. IsPrivate: form.IsPrivate,
  624. CloudBrainType: form.Type,
  625. Topics: validTopics,
  626. UID: ctx.User.ID,
  627. Type: models.GetRecommondType(form.IsRecommend),
  628. Place: form.Place,
  629. })
  630. if err != nil {
  631. log.Error("CommitImagefailed")
  632. if models.IsErrImageTagExist(err) {
  633. ctx.JSON(200, models.BaseErrorMessage(ctx.Tr("repo.image_exist")))
  634. } else if models.IsErrorImageCommitting(err) {
  635. ctx.JSON(200, models.BaseErrorMessage(ctx.Tr("repo.image_committing")))
  636. } else {
  637. ctx.JSON(200, models.BaseErrorMessage(ctx.Tr("repo.image_commit_fail")))
  638. }
  639. return
  640. }
  641. ctx.JSON(200, models.BaseOKMessage)
  642. }
  643. func CloudBrainCommitImage(ctx *context.Context, form auth.CommitImageCloudBrainForm) {
  644. if !NamePattern.MatchString(form.Tag) {
  645. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("dataset.title_format_err")))
  646. return
  647. }
  648. if utf8.RuneCountInString(form.Description) > 255 {
  649. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("dataset.description_format_err", 255)))
  650. return
  651. }
  652. validTopics, errMessage := checkTopics(form.Topics)
  653. if errMessage != "" {
  654. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr(errMessage)))
  655. return
  656. }
  657. err := cloudbrain.CommitImage(ctx.Cloudbrain.JobID, models.CommitImageParams{
  658. CommitImageCloudBrainParams: models.CommitImageCloudBrainParams{
  659. Ip: ctx.Cloudbrain.ContainerIp,
  660. TaskContainerId: ctx.Cloudbrain.ContainerID,
  661. ImageDescription: form.Description,
  662. ImageTag: form.Tag,
  663. },
  664. IsPrivate: form.IsPrivate,
  665. CloudBrainType: form.Type,
  666. Topics: validTopics,
  667. UID: ctx.User.ID,
  668. })
  669. if err != nil {
  670. log.Error("CommitImage(%s) failed:%v", ctx.Cloudbrain.JobName, err.Error(), ctx.Data["msgID"])
  671. if models.IsErrImageTagExist(err) {
  672. ctx.JSON(200, models.BaseErrorMessage(ctx.Tr("repo.image_exist")))
  673. } else if models.IsErrorImageCommitting(err) {
  674. ctx.JSON(200, models.BaseErrorMessage(ctx.Tr("repo.image_committing")))
  675. } else {
  676. ctx.JSON(200, models.BaseErrorMessage(ctx.Tr("repo.image_commit_fail")))
  677. }
  678. return
  679. }
  680. ctx.JSON(200, models.BaseOKMessage)
  681. }
  682. func checkTopics(Topics string) ([]string, string) {
  683. var topics = make([]string, 0)
  684. var topicsStr = strings.TrimSpace(Topics)
  685. if len(topicsStr) > 0 {
  686. topics = strings.Split(topicsStr, ",")
  687. }
  688. validTopics, invalidTopics := models.SanitizeAndValidateImageTopics(topics)
  689. if len(validTopics) > 25 {
  690. return nil, "repo.topic.count_prompt"
  691. }
  692. if len(invalidTopics) > 0 {
  693. return nil, "repo.imagetopic.format_prompt"
  694. }
  695. return validTopics, ""
  696. }
  697. func CloudBrainStop(ctx *context.Context) {
  698. var ID = ctx.Params(":id")
  699. var resultCode = "0"
  700. var errorMsg = ""
  701. var status = ""
  702. task := ctx.Cloudbrain
  703. for {
  704. if task.Status == string(models.JobStopped) || task.Status == string(models.JobFailed) || task.Status == string(models.JobSucceeded) {
  705. log.Error("the job(%s) has been stopped", task.JobName, ctx.Data["msgID"])
  706. resultCode = "-1"
  707. errorMsg = "system error"
  708. break
  709. }
  710. err := cloudbrain.StopJob(task.JobID)
  711. if err != nil {
  712. log.Error("StopJob(%s) failed:%v", task.JobName, err, ctx.Data["msgID"])
  713. resultCode = "-1"
  714. errorMsg = "system error"
  715. break
  716. }
  717. task.Status = string(models.JobStopped)
  718. if task.EndTime == 0 {
  719. task.EndTime = timeutil.TimeStampNow()
  720. }
  721. task.ComputeAndSetDuration()
  722. err = models.UpdateJob(task)
  723. if err != nil {
  724. log.Error("UpdateJob(%s) failed:%v", task.JobName, err, ctx.Data["msgID"])
  725. resultCode = "-1"
  726. errorMsg = "system error"
  727. break
  728. }
  729. status = task.Status
  730. break
  731. }
  732. ctx.JSON(200, map[string]interface{}{
  733. "result_code": resultCode,
  734. "error_msg": errorMsg,
  735. "status": status,
  736. "id": ID,
  737. "StatusOK": 0,
  738. })
  739. }
  740. func StopJobsByUserID(userID int64) {
  741. cloudBrains, err := models.GetCloudbrainsNeededStopByUserID(userID)
  742. if err != nil {
  743. log.Warn("Failed to get cloudBrain info", err)
  744. return
  745. }
  746. StopJobs(cloudBrains)
  747. }
  748. func StopJobsByRepoID(repoID int64) {
  749. cloudBrains, err := models.GetCloudbrainsNeededStopByRepoID(repoID)
  750. if err != nil {
  751. log.Warn("Failed to get cloudBrain info", err)
  752. return
  753. }
  754. StopJobs(cloudBrains)
  755. }
  756. /**
  757. */
  758. func StopJobs(cloudBrains []*models.Cloudbrain) {
  759. for _, taskInfo := range cloudBrains {
  760. if taskInfo.Type == models.TypeCloudBrainOne {
  761. err := retry(3, time.Second*30, func() error {
  762. return cloudbrain.StopJob(taskInfo.JobID)
  763. })
  764. logErrorAndUpdateJobStatus(err, taskInfo)
  765. } else {
  766. if taskInfo.JobType == string(models.JobTypeTrain) {
  767. err := retry(3, time.Second*30, func() error {
  768. _, err := modelarts.StopTrainJob(taskInfo.JobID, strconv.FormatInt(taskInfo.VersionID, 10))
  769. return err
  770. })
  771. logErrorAndUpdateJobStatus(err, taskInfo)
  772. } else {
  773. param := models.NotebookAction{
  774. Action: models.ActionStop,
  775. }
  776. err := retry(3, time.Second*30, func() error {
  777. _, err := modelarts.ManageNotebook(taskInfo.JobID, param)
  778. return err
  779. })
  780. logErrorAndUpdateJobStatus(err, taskInfo)
  781. }
  782. }
  783. }
  784. }
  785. func retry(attempts int, sleep time.Duration, f func() error) (err error) {
  786. for i := 0; i < attempts; i++ {
  787. if i > 0 {
  788. log.Warn("retrying after error:", err)
  789. time.Sleep(sleep)
  790. }
  791. err = f()
  792. if err == nil {
  793. return nil
  794. }
  795. }
  796. return fmt.Errorf("after %d attempts, last error: %s", attempts, err)
  797. }
  798. func logErrorAndUpdateJobStatus(err error, taskInfo *models.Cloudbrain) {
  799. if err != nil {
  800. log.Warn("Failed to stop cloudBrain job:"+taskInfo.JobID, err)
  801. } else {
  802. taskInfo.Status = string(models.JobStopped)
  803. if taskInfo.EndTime == 0 {
  804. taskInfo.EndTime = timeutil.TimeStampNow()
  805. }
  806. taskInfo.ComputeAndSetDuration()
  807. err = models.UpdateJob(taskInfo)
  808. if err != nil {
  809. log.Warn("UpdateJob failed", err)
  810. }
  811. }
  812. }
  813. func CloudBrainDel(ctx *context.Context) {
  814. var listType = ctx.Query("debugListType")
  815. if err := deleteCloudbrainJob(ctx); err != nil {
  816. log.Error("deleteCloudbrainJob failed: %v", err, ctx.Data["msgID"])
  817. ctx.ServerError(err.Error(), err)
  818. return
  819. }
  820. var isAdminPage = ctx.Query("isadminpage")
  821. var isHomePage = ctx.Query("ishomepage")
  822. if ctx.IsUserSiteAdmin() && isAdminPage == "true" {
  823. ctx.Redirect(setting.AppSubURL + "/admin" + "/cloudbrains")
  824. } else if isHomePage == "true" {
  825. ctx.Redirect(setting.AppSubURL + "/cloudbrains")
  826. } else {
  827. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/debugjob?debugListType=" + listType)
  828. }
  829. }
  830. func deleteCloudbrainJob(ctx *context.Context) error {
  831. task := ctx.Cloudbrain
  832. if task.Status != string(models.JobStopped) && task.Status != string(models.JobFailed) && task.Status != string(models.JobSucceeded) {
  833. log.Error("the job(%s) has not been stopped", task.JobName, ctx.Data["msgID"])
  834. return errors.New("the job has not been stopped")
  835. }
  836. err := models.DeleteJob(task)
  837. if err != nil {
  838. log.Error("DeleteJob failed: %v", err, ctx.Data["msgID"])
  839. return err
  840. }
  841. deleteJobStorage(task.JobName, models.TypeCloudBrainOne)
  842. return nil
  843. }
  844. func CloudBrainShowModels(ctx *context.Context) {
  845. ctx.Data["PageIsCloudBrain"] = true
  846. ID := ctx.Params(":id")
  847. parentDir := ctx.Query("parentDir")
  848. dirArray := strings.Split(parentDir, "/")
  849. task, err := models.GetCloudbrainByID(ID)
  850. if err != nil {
  851. log.Error("no such job!", ctx.Data["msgID"])
  852. ctx.ServerError("no such job:", err)
  853. return
  854. }
  855. //get dirs
  856. dirs, err := GetModelDirs(task.JobName, parentDir)
  857. if err != nil {
  858. log.Error("GetModelDirs failed:%v", err.Error(), ctx.Data["msgID"])
  859. ctx.ServerError("GetModelDirs failed:", err)
  860. return
  861. }
  862. var fileInfos []storage.FileInfo
  863. err = json.Unmarshal([]byte(dirs), &fileInfos)
  864. if err != nil {
  865. log.Error("json.Unmarshal failed:%v", err.Error(), ctx.Data["msgID"])
  866. ctx.ServerError("json.Unmarshal failed:", err)
  867. return
  868. }
  869. for i, fileInfo := range fileInfos {
  870. temp, _ := time.Parse("2006-01-02 15:04:05", fileInfo.ModTime)
  871. fileInfos[i].ModTime = temp.Local().Format("2006-01-02 15:04:05")
  872. }
  873. sort.Slice(fileInfos, func(i, j int) bool {
  874. return fileInfos[i].ModTime > fileInfos[j].ModTime
  875. })
  876. ctx.Data["Path"] = dirArray
  877. ctx.Data["Dirs"] = fileInfos
  878. ctx.Data["task"] = task
  879. ctx.Data["ID"] = ID
  880. ctx.HTML(200, tplCloudBrainShowModels)
  881. }
  882. func GetPublicImages(ctx *context.Context) {
  883. uid := getUID(ctx)
  884. opts := models.SearchImageOptions{
  885. IncludePublicOnly: true,
  886. UID: uid,
  887. Keyword: ctx.Query("q"),
  888. Topics: ctx.Query("topic"),
  889. IncludeOfficialOnly: ctx.QueryBool("recommend"),
  890. SearchOrderBy: "type desc, num_stars desc,id desc",
  891. Status: models.IMAGE_STATUS_SUCCESS,
  892. }
  893. getImages(ctx, &opts)
  894. }
  895. func GetCustomImages(ctx *context.Context) {
  896. uid := getUID(ctx)
  897. opts := models.SearchImageOptions{
  898. UID: uid,
  899. IncludeOwnerOnly: true,
  900. Keyword: ctx.Query("q"),
  901. Topics: ctx.Query("topic"),
  902. Status: -1,
  903. SearchOrderBy: "id desc",
  904. }
  905. getImages(ctx, &opts)
  906. }
  907. func GetStarImages(ctx *context.Context) {
  908. uid := getUID(ctx)
  909. opts := models.SearchImageOptions{
  910. UID: uid,
  911. IncludeStarByMe: true,
  912. Keyword: ctx.Query("q"),
  913. Topics: ctx.Query("topic"),
  914. Status: models.IMAGE_STATUS_SUCCESS,
  915. SearchOrderBy: "id desc",
  916. }
  917. getImages(ctx, &opts)
  918. }
  919. func getUID(ctx *context.Context) int64 {
  920. var uid int64 = -1
  921. if ctx.IsSigned {
  922. uid = ctx.User.ID
  923. }
  924. return uid
  925. }
  926. func GetAllImages(ctx *context.Context) {
  927. uid := getUID(ctx)
  928. opts := models.SearchImageOptions{
  929. UID: uid,
  930. Keyword: ctx.Query("q"),
  931. Topics: ctx.Query("topic"),
  932. IncludeOfficialOnly: ctx.QueryBool("recommend"),
  933. SearchOrderBy: "id desc",
  934. Status: -1,
  935. }
  936. if ctx.Query("private") != "" {
  937. if ctx.QueryBool("private") {
  938. opts.IncludePrivateOnly = true
  939. } else {
  940. opts.IncludePublicOnly = true
  941. }
  942. }
  943. getImages(ctx, &opts)
  944. }
  945. func getImages(ctx *context.Context, opts *models.SearchImageOptions) {
  946. page := ctx.QueryInt("page")
  947. if page <= 0 {
  948. page = 1
  949. }
  950. pageSize := ctx.QueryInt("pageSize")
  951. if pageSize <= 0 {
  952. pageSize = 15
  953. }
  954. opts.ListOptions = models.ListOptions{
  955. Page: page,
  956. PageSize: pageSize,
  957. }
  958. imageList, total, err := models.SearchImage(opts)
  959. if err != nil {
  960. log.Error("Can not get images:%v", err)
  961. ctx.JSON(http.StatusOK, models.ImagesPageResult{
  962. Count: 0,
  963. Images: []*models.Image{},
  964. })
  965. } else {
  966. ctx.JSON(http.StatusOK, models.ImagesPageResult{
  967. Count: total,
  968. Images: imageList,
  969. })
  970. }
  971. }
  972. func GetModelDirs(jobName string, parentDir string) (string, error) {
  973. var req string
  974. modelActualPath := storage.GetMinioPath(jobName, cloudbrain.ModelMountPath+"/")
  975. if parentDir == "" {
  976. req = "baseDir=" + modelActualPath
  977. } else {
  978. req = "baseDir=" + modelActualPath + "&parentDir=" + parentDir
  979. }
  980. return getDirs(req)
  981. }
  982. func CloudBrainDownloadModel(ctx *context.Context) {
  983. parentDir := ctx.Query("parentDir")
  984. fileName := ctx.Query("fileName")
  985. jobName := ctx.Query("jobName")
  986. filePath := "jobs/" + jobName + "/model/" + parentDir
  987. url, err := storage.Attachments.PresignedGetURL(filePath, fileName)
  988. if err != nil {
  989. log.Error("PresignedGetURL failed: %v", err.Error(), ctx.Data["msgID"])
  990. ctx.ServerError("PresignedGetURL", err)
  991. return
  992. }
  993. http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusMovedPermanently)
  994. }
  995. func GetRate(ctx *context.Context) {
  996. isObjectDetcionAll := ctx.QueryBool("isObjectDetcionAll")
  997. if isObjectDetcionAll {
  998. ctx.Redirect(setting.BenchmarkServerHost + "?username=admin")
  999. return
  1000. }
  1001. var ID = ctx.Params(":id")
  1002. job, err := models.GetCloudbrainByID(ID)
  1003. if err != nil {
  1004. ctx.ServerError("GetCloudbrainByJobID failed", err)
  1005. return
  1006. }
  1007. if job.JobType == string(models.JobTypeBenchmark) {
  1008. log.Info("url=" + setting.BenchmarkServerHost + "?username=" + ctx.User.Name)
  1009. ctx.Redirect(setting.BenchmarkServerHost + "?username=" + ctx.User.Name)
  1010. } else if job.JobType == string(models.JobTypeSnn4imagenet) {
  1011. ctx.Redirect(setting.Snn4imagenetServerHost)
  1012. } else if job.JobType == string(models.JobTypeBrainScore) {
  1013. ctx.Redirect(setting.BrainScoreServerHost)
  1014. } else {
  1015. log.Error("JobType error:%s", job.JobType, ctx.Data["msgID"])
  1016. }
  1017. }
  1018. func downloadCode(repo *models.Repository, codePath, branchName string) error {
  1019. //add "file:///" prefix to make the depth valid
  1020. if err := git.Clone(CLONE_FILE_PREFIX+repo.RepoPath(), codePath, git.CloneRepoOptions{Branch: branchName, Depth: 1}); err != nil {
  1021. log.Error("Failed to clone repository: %s (%v)", repo.FullName(), err)
  1022. return err
  1023. }
  1024. configFile, err := os.OpenFile(codePath+"/.git/config", os.O_RDWR, 0666)
  1025. if err != nil {
  1026. log.Error("open file(%s) failed:%v", codePath+"/,git/config", err)
  1027. return err
  1028. }
  1029. defer configFile.Close()
  1030. pos := int64(0)
  1031. reader := bufio.NewReader(configFile)
  1032. for {
  1033. line, err := reader.ReadString('\n')
  1034. if err != nil {
  1035. if err == io.EOF {
  1036. log.Error("not find the remote-url")
  1037. return nil
  1038. } else {
  1039. log.Error("read error: %v", err)
  1040. return err
  1041. }
  1042. }
  1043. if strings.Contains(line, "url") && strings.Contains(line, ".git") {
  1044. originUrl := "\turl = " + repo.CloneLink().HTTPS + "\n"
  1045. if len(line) > len(originUrl) {
  1046. originUrl += strings.Repeat(" ", len(line)-len(originUrl))
  1047. }
  1048. bytes := []byte(originUrl)
  1049. _, err := configFile.WriteAt(bytes, pos)
  1050. if err != nil {
  1051. log.Error("WriteAt failed:%v", err)
  1052. return err
  1053. }
  1054. break
  1055. }
  1056. pos += int64(len(line))
  1057. }
  1058. return nil
  1059. }
  1060. func downloadRateCode(repo *models.Repository, taskName, rateOwnerName, rateRepoName, codePath, benchmarkCategory, gpuType string) error {
  1061. err := os.MkdirAll(codePath, os.ModePerm)
  1062. if err != nil {
  1063. log.Error("mkdir codePath failed", err.Error())
  1064. return err
  1065. }
  1066. repoExt, err := models.GetRepositoryByOwnerAndName(rateOwnerName, rateRepoName)
  1067. if err != nil {
  1068. log.Error("GetRepositoryByOwnerAndName(%s) failed", rateRepoName, err.Error())
  1069. return err
  1070. }
  1071. if err := git.Clone(CLONE_FILE_PREFIX+repoExt.RepoPath(), codePath, git.CloneRepoOptions{Depth: 1}); err != nil {
  1072. log.Error("Failed to clone repository: %s (%v)", repoExt.FullName(), err)
  1073. return err
  1074. }
  1075. fileName := codePath + cloudbrain.TaskInfoName
  1076. f, err := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.ModePerm)
  1077. if err != nil {
  1078. log.Error("OpenFile failed", err.Error())
  1079. return err
  1080. }
  1081. defer f.Close()
  1082. data, err := json.Marshal(models.TaskInfo{
  1083. Username: repo.Owner.Name,
  1084. TaskName: taskName,
  1085. CodeName: repo.Name,
  1086. BenchmarkCategory: strings.Split(benchmarkCategory, ","),
  1087. CodeLink: strings.TrimSuffix(repo.CloneLink().HTTPS, ".git"),
  1088. GpuType: gpuType,
  1089. })
  1090. if err != nil {
  1091. log.Error("json.Marshal failed", err.Error())
  1092. return err
  1093. }
  1094. _, err = f.Write(data)
  1095. if err != nil {
  1096. log.Error("WriteString failed", err.Error())
  1097. return err
  1098. }
  1099. return nil
  1100. }
  1101. func uploadCodeToMinio(codePath, jobName, parentDir string) error {
  1102. files, err := readDir(codePath)
  1103. if err != nil {
  1104. log.Error("readDir(%s) failed: %s", codePath, err.Error())
  1105. return err
  1106. }
  1107. for _, file := range files {
  1108. if file.IsDir() {
  1109. if err = uploadCodeToMinio(codePath+file.Name()+"/", jobName, parentDir+file.Name()+"/"); err != nil {
  1110. log.Error("uploadCodeToMinio(%s) failed: %s", file.Name(), err.Error())
  1111. return err
  1112. }
  1113. } else {
  1114. destObject := setting.CBCodePathPrefix + jobName + parentDir + file.Name()
  1115. sourceFile := codePath + file.Name()
  1116. err = storage.Attachments.UploadObject(destObject, sourceFile)
  1117. if err != nil {
  1118. log.Error("UploadObject(%s) failed: %s", file.Name(), err.Error())
  1119. return err
  1120. }
  1121. }
  1122. }
  1123. return nil
  1124. }
  1125. func mkModelPath(modelPath string) error {
  1126. err := os.MkdirAll(modelPath, os.ModePerm)
  1127. if err != nil {
  1128. log.Error("MkdirAll(%s) failed:%v", modelPath, err)
  1129. return err
  1130. }
  1131. fileName := modelPath + "README"
  1132. f, err := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.ModePerm)
  1133. if err != nil {
  1134. log.Error("OpenFile failed", err.Error())
  1135. return err
  1136. }
  1137. defer f.Close()
  1138. _, err = f.WriteString("You can put the model file into this directory and download it by the web page.")
  1139. if err != nil {
  1140. log.Error("WriteString failed", err.Error())
  1141. return err
  1142. }
  1143. return nil
  1144. }
  1145. func deleteJobStorage(jobName string, cloudbrainType int) error {
  1146. //delete local
  1147. localJobPath := setting.JobPath + jobName
  1148. err := os.RemoveAll(localJobPath)
  1149. if err != nil {
  1150. log.Error("RemoveAll(%s) failed:%v", localJobPath, err)
  1151. }
  1152. //delete oss
  1153. if cloudbrainType == models.TypeCloudBrainOne {
  1154. dirPath := setting.CBCodePathPrefix + jobName + "/"
  1155. err = storage.Attachments.DeleteDir(dirPath)
  1156. if err != nil {
  1157. log.Error("DeleteDir(%s) failed:%v", localJobPath, err)
  1158. }
  1159. } else if cloudbrainType == models.TypeCloudBrainTwo {
  1160. //dirPath := setting.CodePathPrefix + jobName + "/"
  1161. //err = storage.ObsRemoveObject(setting.Bucket, dirPath)
  1162. //if err != nil {
  1163. // log.Error("ObsRemoveObject(%s) failed:%v", localJobPath, err)
  1164. //}
  1165. log.Info("no need to delete")
  1166. } else {
  1167. log.Error("cloudbrainType(%d) error", cloudbrainType)
  1168. }
  1169. return nil
  1170. }
  1171. func SyncCloudbrainStatus() {
  1172. cloudBrains, err := models.GetCloudBrainUnStoppedJob()
  1173. if err != nil {
  1174. log.Error("GetCloudBrainUnStoppedJob failed:", err.Error())
  1175. return
  1176. }
  1177. for _, task := range cloudBrains {
  1178. if task.Type == models.TypeCloudBrainOne {
  1179. result, err := cloudbrain.GetJob(task.JobID)
  1180. if err != nil {
  1181. log.Error("GetJob(%s) failed:%v", task.JobName, err)
  1182. continue
  1183. }
  1184. if result != nil {
  1185. jobRes, _ := models.ConvertToJobResultPayload(result.Payload)
  1186. taskRoles := jobRes.TaskRoles
  1187. taskRes, _ := models.ConvertToTaskPod(taskRoles[cloudbrain.SubTaskName].(map[string]interface{}))
  1188. task.Status = taskRes.TaskStatuses[0].State
  1189. if task.Status != string(models.JobWaiting) {
  1190. models.ParseAndSetDurationFromCloudBrainOne(jobRes, task)
  1191. err = models.UpdateJob(task)
  1192. if err != nil {
  1193. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1194. }
  1195. var maxDuration int64
  1196. if task.JobType == string(models.JobTypeBenchmark) {
  1197. maxDuration = setting.BenchmarkMaxDuration
  1198. } else {
  1199. maxDuration = setting.MaxDuration
  1200. }
  1201. if task.Duration >= maxDuration && task.JobType != string(models.JobTypeTrain) {
  1202. log.Info("begin to stop job(%s), because of the duration", task.DisplayJobName)
  1203. err = cloudbrain.StopJob(task.JobID)
  1204. if err != nil {
  1205. log.Error("StopJob(%s) failed:%v", task.DisplayJobName, err)
  1206. continue
  1207. }
  1208. task.Status = string(models.JobStopped)
  1209. if task.EndTime == 0 {
  1210. task.EndTime = timeutil.TimeStampNow()
  1211. }
  1212. task.ComputeAndSetDuration()
  1213. err = models.UpdateJob(task)
  1214. if err != nil {
  1215. log.Error("UpdateJob(%s) failed:%v", task.DisplayJobName, err)
  1216. continue
  1217. }
  1218. }
  1219. }
  1220. }
  1221. } else if task.Type == models.TypeCloudBrainTwo {
  1222. if task.JobType == string(models.JobTypeDebug) {
  1223. //result, err := modelarts.GetJob(task.JobID)
  1224. result, err := modelarts.GetNotebook2(task.JobID)
  1225. if err != nil {
  1226. log.Error("GetJob(%s) failed:%v", task.JobName, err)
  1227. continue
  1228. }
  1229. if result != nil {
  1230. task.Status = result.Status
  1231. if task.StartTime == 0 && result.Lease.UpdateTime > 0 {
  1232. task.StartTime = timeutil.TimeStamp(result.Lease.UpdateTime / 1000)
  1233. }
  1234. if task.EndTime == 0 && models.IsModelArtsDebugJobTerminal(task.Status) {
  1235. task.EndTime = timeutil.TimeStampNow()
  1236. }
  1237. task.CorrectCreateUnix()
  1238. task.ComputeAndSetDuration()
  1239. err = models.UpdateJob(task)
  1240. if err != nil {
  1241. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1242. continue
  1243. }
  1244. }
  1245. } else if task.JobType == string(models.JobTypeTrain) || task.JobType == string(models.JobTypeInference) {
  1246. result, err := modelarts.GetTrainJob(task.JobID, strconv.FormatInt(task.VersionID, 10))
  1247. if err != nil {
  1248. log.Error("GetTrainJob(%s) failed:%v", task.JobName, err)
  1249. continue
  1250. }
  1251. if result != nil {
  1252. task.Status = modelarts.TransTrainJobStatus(result.IntStatus)
  1253. task.Duration = result.Duration / 1000
  1254. task.TrainJobDuration = result.TrainJobDuration
  1255. if task.StartTime == 0 && result.StartTime > 0 {
  1256. task.StartTime = timeutil.TimeStamp(result.StartTime / 1000)
  1257. }
  1258. task.TrainJobDuration = models.ConvertDurationToStr(task.Duration)
  1259. if task.EndTime == 0 && models.IsTrainJobTerminal(task.Status) && task.StartTime > 0 {
  1260. task.EndTime = task.StartTime.Add(task.Duration)
  1261. }
  1262. task.CorrectCreateUnix()
  1263. err = models.UpdateJob(task)
  1264. if err != nil {
  1265. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1266. continue
  1267. }
  1268. }
  1269. } else {
  1270. log.Error("task.JobType(%s) is error:%s", task.JobName, task.JobType)
  1271. }
  1272. } else {
  1273. log.Error("task.Type(%s) is error:%d", task.JobName, task.Type)
  1274. }
  1275. }
  1276. return
  1277. }
  1278. func HandleTaskWithNoDuration(ctx *context.Context) {
  1279. log.Info("HandleTaskWithNoDuration start")
  1280. count := 0
  1281. start := time.Now().Unix()
  1282. for {
  1283. cloudBrains, err := models.GetStoppedJobWithNoDurationJob()
  1284. if err != nil {
  1285. log.Error("HandleTaskWithNoTrainJobDuration failed:", err.Error())
  1286. break
  1287. }
  1288. if len(cloudBrains) == 0 {
  1289. log.Info("HandleTaskWithNoTrainJobDuration:no task need handle")
  1290. break
  1291. }
  1292. handleNoDurationTask(cloudBrains)
  1293. count += len(cloudBrains)
  1294. if len(cloudBrains) < 100 {
  1295. log.Info("HandleTaskWithNoTrainJobDuration:task less than 100")
  1296. break
  1297. }
  1298. if time.Now().Unix()-start > 600 {
  1299. log.Info("HandleTaskWithNoDuration : time out")
  1300. ctx.JSON(200, fmt.Sprintf("task stop for time out,count=%d", count))
  1301. return
  1302. }
  1303. }
  1304. log.Info("HandleTaskWithNoTrainJobDuration:count=%d", count)
  1305. ctx.JSON(200, fmt.Sprintf("success,count=%d", count))
  1306. }
  1307. func handleNoDurationTask(cloudBrains []*models.Cloudbrain) {
  1308. for _, task := range cloudBrains {
  1309. time.Sleep(time.Millisecond * 100)
  1310. log.Info("Handle job ,%+v", task)
  1311. if task.Type == models.TypeCloudBrainOne {
  1312. result, err := cloudbrain.GetJob(task.JobID)
  1313. if err != nil {
  1314. log.Error("GetJob(%s) failed:%v", task.JobName, err)
  1315. updateDefaultDuration(task)
  1316. continue
  1317. }
  1318. if result != nil {
  1319. if result.Msg != "success" {
  1320. updateDefaultDuration(task)
  1321. continue
  1322. }
  1323. jobRes, err := models.ConvertToJobResultPayload(result.Payload)
  1324. if err != nil || len(jobRes.TaskRoles) == 0 {
  1325. updateDefaultDuration(task)
  1326. continue
  1327. }
  1328. taskRoles := jobRes.TaskRoles
  1329. taskRes, err := models.ConvertToTaskPod(taskRoles[cloudbrain.SubTaskName].(map[string]interface{}))
  1330. if err != nil || len(taskRes.TaskStatuses) == 0 {
  1331. updateDefaultDuration(task)
  1332. continue
  1333. }
  1334. task.Status = taskRes.TaskStatuses[0].State
  1335. log.Info("task startTime = %v endTime= %v ,jobId=%d", jobRes.JobStatus.StartTime, jobRes.JobStatus.EndTime, task.ID)
  1336. if jobRes.JobStatus.CreatedTime > 0 {
  1337. task.StartTime = timeutil.TimeStamp(jobRes.JobStatus.CreatedTime / 1000)
  1338. if jobRes.JobStatus.CompletedTime > 0 {
  1339. task.EndTime = timeutil.TimeStamp(jobRes.JobStatus.CompletedTime / 1000)
  1340. } else {
  1341. task.EndTime = task.UpdatedUnix
  1342. }
  1343. } else {
  1344. task.StartTime = 0
  1345. task.EndTime = 0
  1346. }
  1347. if task.EndTime < task.StartTime {
  1348. log.Info("endTime[%v] is less than starTime[%v],jobId=%d", task.EndTime, task.StartTime, task.ID)
  1349. st := task.StartTime
  1350. task.StartTime = task.EndTime
  1351. task.EndTime = st
  1352. }
  1353. task.Duration = task.EndTime.AsTime().Unix() - task.StartTime.AsTime().Unix()
  1354. task.TrainJobDuration = models.ConvertDurationToStr(task.Duration)
  1355. err = models.UpdateJob(task)
  1356. if err != nil {
  1357. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1358. }
  1359. }
  1360. } else if task.Type == models.TypeCloudBrainTwo {
  1361. if task.JobType == string(models.JobTypeDebug) {
  1362. //result, err := modelarts.GetJob(task.JobID)
  1363. result, err := modelarts.GetNotebook2(task.JobID)
  1364. if err != nil {
  1365. log.Error("GetJob(%s) failed:%v", task.JobName, err)
  1366. updateDefaultDuration(task)
  1367. continue
  1368. }
  1369. if result != nil {
  1370. task.Status = result.Status
  1371. startTime := result.Lease.CreateTime
  1372. duration := result.Lease.Duration / 1000
  1373. if startTime > 0 {
  1374. task.StartTime = timeutil.TimeStamp(startTime / 1000)
  1375. task.EndTime = task.StartTime.Add(duration)
  1376. }
  1377. task.CorrectCreateUnix()
  1378. task.ComputeAndSetDuration()
  1379. err = models.UpdateJob(task)
  1380. if err != nil {
  1381. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1382. continue
  1383. }
  1384. }
  1385. } else if task.JobType == string(models.JobTypeTrain) || task.JobType == string(models.JobTypeInference) {
  1386. result, err := modelarts.GetTrainJob(task.JobID, strconv.FormatInt(task.VersionID, 10))
  1387. if err != nil {
  1388. log.Error("GetTrainJob(%s) failed:%v", task.JobName, err)
  1389. updateDefaultDuration(task)
  1390. continue
  1391. }
  1392. if result != nil {
  1393. startTime := result.StartTime / 1000
  1394. if startTime > 0 {
  1395. task.StartTime = timeutil.TimeStamp(startTime)
  1396. task.EndTime = task.StartTime.Add(result.Duration / 1000)
  1397. }
  1398. task.ComputeAndSetDuration()
  1399. err = models.UpdateJob(task)
  1400. if err != nil {
  1401. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1402. continue
  1403. }
  1404. }
  1405. } else {
  1406. log.Error("task.JobType(%s) is error:%s", task.JobName, task.JobType)
  1407. }
  1408. } else {
  1409. log.Error("task.Type(%s) is error:%d", task.JobName, task.Type)
  1410. }
  1411. }
  1412. }
  1413. func updateDefaultDuration(task *models.Cloudbrain) {
  1414. log.Info("updateDefaultDuration: taskId=%d", task.ID)
  1415. task.StartTime = task.CreatedUnix
  1416. task.EndTime = task.UpdatedUnix
  1417. task.ComputeAndSetDuration()
  1418. err := models.UpdateJob(task)
  1419. if err != nil {
  1420. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1421. }
  1422. }
  1423. func CloudBrainBenchmarkIndex(ctx *context.Context) {
  1424. MustEnableCloudbrain(ctx)
  1425. repo := ctx.Repo.Repository
  1426. page := ctx.QueryInt("page")
  1427. if page <= 0 {
  1428. page = 1
  1429. }
  1430. var jobTypes []string
  1431. jobTypes = append(jobTypes, string(models.JobTypeBenchmark))
  1432. ciTasks, count, err := models.Cloudbrains(&models.CloudbrainsOptions{
  1433. ListOptions: models.ListOptions{
  1434. Page: page,
  1435. PageSize: setting.UI.IssuePagingNum,
  1436. },
  1437. RepoID: repo.ID,
  1438. Type: models.TypeCloudBrainOne,
  1439. JobTypes: jobTypes,
  1440. })
  1441. if err != nil {
  1442. ctx.ServerError("Get debugjob faild:", err)
  1443. return
  1444. }
  1445. for i, task := range ciTasks {
  1446. ciTasks[i].CanDel = cloudbrain.CanDeleteJob(ctx, &task.Cloudbrain)
  1447. ciTasks[i].Cloudbrain.ComputeResource = task.ComputeResource
  1448. if ciTasks[i].TrainJobDuration == "" {
  1449. if ciTasks[i].Duration == 0 {
  1450. var duration int64
  1451. if task.Status == string(models.JobRunning) {
  1452. duration = time.Now().Unix() - int64(task.Cloudbrain.CreatedUnix)
  1453. } else {
  1454. duration = int64(task.Cloudbrain.UpdatedUnix) - int64(task.Cloudbrain.CreatedUnix)
  1455. }
  1456. ciTasks[i].Duration = duration
  1457. }
  1458. ciTasks[i].TrainJobDuration = models.ConvertDurationToStr(ciTasks[i].Duration)
  1459. }
  1460. ciTasks[i].BenchmarkTypeName = ""
  1461. if task.BenchmarkTypeID > 0 {
  1462. for _, benchmarkType := range GetBenchmarkTypes(ctx).BenchmarkType {
  1463. if task.BenchmarkTypeID == benchmarkType.Id {
  1464. ciTasks[i].BenchmarkTypeRankLink = benchmarkType.RankLink
  1465. ciTasks[i].BenchmarkTypeName = benchmarkType.First
  1466. break
  1467. }
  1468. }
  1469. }
  1470. }
  1471. pager := context.NewPagination(int(count), setting.UI.IssuePagingNum, page, 5)
  1472. ctx.Data["Page"] = pager
  1473. ctx.Data["PageIsCloudBrain"] = true
  1474. ctx.Data["Tasks"] = ciTasks
  1475. ctx.Data["CanCreate"] = cloudbrain.CanCreateOrDebugJob(ctx)
  1476. ctx.Data["RepoIsEmpty"] = repo.IsEmpty
  1477. ctx.HTML(200, tplCloudBrainBenchmarkIndex)
  1478. }
  1479. func GetChildTypes(ctx *context.Context) {
  1480. benchmarkTypeID := ctx.QueryInt("benchmark_type_id")
  1481. re := make(map[string]interface{})
  1482. for {
  1483. var isExist bool
  1484. for _, benchmarkType := range GetBenchmarkTypes(ctx).BenchmarkType {
  1485. if benchmarkTypeID == benchmarkType.Id {
  1486. isExist = true
  1487. re["child_types"] = benchmarkType.Second
  1488. re["result_code"] = "0"
  1489. break
  1490. }
  1491. }
  1492. if !isExist {
  1493. re["result_code"] = "1"
  1494. log.Error("no such benchmark_type_id", ctx.Data["MsgID"])
  1495. re["errMsg"] = "system error"
  1496. break
  1497. }
  1498. break
  1499. }
  1500. ctx.JSON(200, re)
  1501. }
  1502. func CloudBrainBenchmarkNew(ctx *context.Context) {
  1503. ctx.Data["description"] = ""
  1504. ctx.Data["benchmarkTypeID"] = -1
  1505. ctx.Data["benchmark_child_types_id_hidden"] = -1
  1506. err := cloudBrainNewDataPrepare(ctx)
  1507. if err != nil {
  1508. ctx.ServerError("get new cloudbrain info failed", err)
  1509. return
  1510. }
  1511. ctx.HTML(200, tplCloudBrainBenchmarkNew)
  1512. }
  1513. func getBenchmarkAttachment(benchmarkTypeID, benchmarkChildTypeID int, ctx *context.Context) (*models.BenchmarkDataset, error) {
  1514. var childInfo *models.BenchmarkDataset
  1515. var isExist bool
  1516. for _, benchmarkType := range GetBenchmarkTypes(ctx).BenchmarkType {
  1517. if benchmarkType.Id == benchmarkTypeID {
  1518. for _, childType := range benchmarkType.Second {
  1519. if childType.Id == benchmarkChildTypeID {
  1520. childInfo = childType
  1521. isExist = true
  1522. break
  1523. }
  1524. }
  1525. break
  1526. }
  1527. }
  1528. if !isExist {
  1529. log.Error("no such benchmark_type_id&benchmark_child_type_id")
  1530. return childInfo, errors.New("no such benchmark_type_id&benchmark_child_type_id")
  1531. }
  1532. return childInfo, nil
  1533. }
  1534. func getBenchmarkGpuQueue(gpuQueue string) (string, error) {
  1535. queue := ""
  1536. if benchmarkGpuInfos == nil {
  1537. if err := json.Unmarshal([]byte(setting.BenchmarkGpuTypes), &benchmarkGpuInfos); err != nil {
  1538. log.Error("json.Unmarshal BenchmarkGpuTypes(%s) failed:%v", setting.BenchmarkGpuTypes, err)
  1539. return queue, err
  1540. }
  1541. }
  1542. var isExist bool
  1543. for _, gpuInfo := range benchmarkGpuInfos.GpuInfo {
  1544. if gpuQueue == gpuInfo.Queue {
  1545. isExist = true
  1546. queue = gpuQueue
  1547. break
  1548. }
  1549. }
  1550. if !isExist {
  1551. log.Error("no such gpuQueue, %s", gpuQueue)
  1552. return queue, errors.New("no such gpuQueue")
  1553. }
  1554. return queue, nil
  1555. }
  1556. func getBenchmarkResourceSpec(resourceSpecID int) (int, error) {
  1557. var id int
  1558. if benchmarkResourceSpecs == nil {
  1559. if err := json.Unmarshal([]byte(setting.BenchmarkResourceSpecs), &benchmarkResourceSpecs); err != nil {
  1560. log.Error("json.Unmarshal BenchmarkResourceSpecs(%s) failed:%v", setting.BenchmarkResourceSpecs, err)
  1561. return id, err
  1562. }
  1563. }
  1564. var isExist bool
  1565. for _, resourceSpec := range benchmarkResourceSpecs.ResourceSpec {
  1566. if resourceSpecID == resourceSpec.Id {
  1567. isExist = true
  1568. id = resourceSpecID
  1569. break
  1570. }
  1571. }
  1572. if !isExist {
  1573. log.Error("no such resourceSpecID, %d", resourceSpecID)
  1574. return id, errors.New("no such resourceSpec")
  1575. }
  1576. return id, nil
  1577. }
  1578. func CloudBrainBenchmarkCreate(ctx *context.Context, form auth.CreateCloudBrainForm) {
  1579. ctx.Data["PageIsCloudBrain"] = true
  1580. displayJobName := form.DisplayJobName
  1581. jobName := util.ConvertDisplayJobNameToJobName(displayJobName)
  1582. image := form.Image
  1583. gpuQueue := form.GpuType
  1584. command := cloudbrain.CommandBenchmark
  1585. codePath := setting.JobPath + jobName + cloudbrain.CodeMountPath
  1586. resourceSpecId := cloudbrain.BenchMarkResourceID
  1587. benchmarkTypeID := form.BenchmarkTypeID
  1588. benchmarkChildTypeID := form.BenchmarkChildTypeID
  1589. ctx.Data["description"] = form.Description
  1590. ctx.Data["benchmarkTypeID"] = benchmarkTypeID
  1591. ctx.Data["benchmark_child_types_id_hidden"] = benchmarkChildTypeID
  1592. repo := ctx.Repo.Repository
  1593. tasks, err := models.GetCloudbrainsByDisplayJobName(repo.ID, string(models.JobTypeBenchmark), displayJobName)
  1594. if err == nil {
  1595. if len(tasks) != 0 {
  1596. log.Error("the job name did already exist", ctx.Data["MsgID"])
  1597. cloudBrainNewDataPrepare(ctx)
  1598. ctx.RenderWithErr("the job name did already exist", tplCloudBrainBenchmarkNew, &form)
  1599. return
  1600. }
  1601. } else {
  1602. if !models.IsErrJobNotExist(err) {
  1603. log.Error("system error, %v", err, ctx.Data["MsgID"])
  1604. cloudBrainNewDataPrepare(ctx)
  1605. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  1606. return
  1607. }
  1608. }
  1609. if !jobNamePattern.MatchString(jobName) {
  1610. cloudBrainNewDataPrepare(ctx)
  1611. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_jobname_err"), tplCloudBrainBenchmarkNew, &form)
  1612. return
  1613. }
  1614. childInfo, err := getBenchmarkAttachment(benchmarkTypeID, benchmarkChildTypeID, ctx)
  1615. if err != nil {
  1616. log.Error("getBenchmarkAttachment failed:%v", err, ctx.Data["MsgID"])
  1617. cloudBrainNewDataPrepare(ctx)
  1618. ctx.RenderWithErr("benchmark type error", tplCloudBrainBenchmarkNew, &form)
  1619. return
  1620. }
  1621. _, err = getBenchmarkGpuQueue(gpuQueue)
  1622. if err != nil {
  1623. log.Error("getBenchmarkGpuQueue failed:%v", err, ctx.Data["MsgID"])
  1624. cloudBrainNewDataPrepare(ctx)
  1625. ctx.RenderWithErr("gpu queue error", tplCloudBrainBenchmarkNew, &form)
  1626. return
  1627. }
  1628. _, err = getBenchmarkResourceSpec(resourceSpecId)
  1629. if err != nil {
  1630. log.Error("getBenchmarkResourceSpec failed:%v", err, ctx.Data["MsgID"])
  1631. cloudBrainNewDataPrepare(ctx)
  1632. ctx.RenderWithErr("resource spec error", tplCloudBrainBenchmarkNew, &form)
  1633. return
  1634. }
  1635. count, err := models.GetCloudbrainCountByUserID(ctx.User.ID, string(models.JobTypeBenchmark))
  1636. if err != nil {
  1637. log.Error("GetCloudbrainCountByUserID failed:%v", err, ctx.Data["MsgID"])
  1638. cloudBrainNewDataPrepare(ctx)
  1639. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  1640. return
  1641. } else {
  1642. if count >= 1 {
  1643. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  1644. cloudBrainNewDataPrepare(ctx)
  1645. ctx.RenderWithErr("you have already a running or waiting task, can not create more", tplCloudBrainBenchmarkNew, &form)
  1646. return
  1647. }
  1648. }
  1649. os.RemoveAll(codePath)
  1650. if err := downloadCode(repo, codePath, cloudbrain.DefaultBranchName); err != nil {
  1651. log.Error("downloadCode failed, %v", err, ctx.Data["MsgID"])
  1652. cloudBrainNewDataPrepare(ctx)
  1653. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  1654. return
  1655. }
  1656. if _, err := os.Stat(codePath + "/train.py"); err != nil {
  1657. if os.IsNotExist(err) {
  1658. // file does not exist
  1659. log.Error("train.py does not exist, %v", err, ctx.Data["MsgID"])
  1660. cloudBrainNewDataPrepare(ctx)
  1661. ctx.RenderWithErr("train.py does not exist", tplCloudBrainBenchmarkNew, &form)
  1662. } else {
  1663. log.Error("Stat failed, %v", err, ctx.Data["MsgID"])
  1664. cloudBrainNewDataPrepare(ctx)
  1665. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  1666. }
  1667. return
  1668. } else if _, err := os.Stat(codePath + "/test.py"); err != nil {
  1669. if os.IsNotExist(err) {
  1670. // file does not exist
  1671. log.Error("test.py does not exist, %v", err, ctx.Data["MsgID"])
  1672. cloudBrainNewDataPrepare(ctx)
  1673. ctx.RenderWithErr("test.py does not exist", tplCloudBrainBenchmarkNew, &form)
  1674. } else {
  1675. log.Error("Stat failed, %v", err, ctx.Data["MsgID"])
  1676. cloudBrainNewDataPrepare(ctx)
  1677. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  1678. }
  1679. return
  1680. }
  1681. if err := uploadCodeToMinio(codePath+"/", jobName, cloudbrain.CodeMountPath+"/"); err != nil {
  1682. log.Error("uploadCodeToMinio failed, %v", err, ctx.Data["MsgID"])
  1683. cloudBrainNewDataPrepare(ctx)
  1684. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  1685. return
  1686. }
  1687. benchmarkPath := setting.JobPath + jobName + cloudbrain.BenchMarkMountPath
  1688. var gpuType string
  1689. for _, gpuInfo := range gpuInfos.GpuInfo {
  1690. if gpuInfo.Queue == gpuQueue {
  1691. gpuType = gpuInfo.Value
  1692. }
  1693. }
  1694. if err := downloadRateCode(repo, jobName, childInfo.Owner, childInfo.RepoName, benchmarkPath, form.BenchmarkCategory, gpuType); err != nil {
  1695. log.Error("downloadRateCode failed, %v", err, ctx.Data["MsgID"])
  1696. //cloudBrainNewDataPrepare(ctx)
  1697. //ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  1698. //return
  1699. }
  1700. if err := uploadCodeToMinio(benchmarkPath+"/", jobName, cloudbrain.BenchMarkMountPath+"/"); err != nil {
  1701. log.Error("uploadCodeToMinio failed, %v", err, ctx.Data["MsgID"])
  1702. //cloudBrainNewDataPrepare(ctx)
  1703. //ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  1704. //return
  1705. }
  1706. err = cloudbrain.GenerateTask(ctx, displayJobName, jobName, image, command, childInfo.Attachment, storage.GetMinioPath(jobName, cloudbrain.CodeMountPath+"/"),
  1707. storage.GetMinioPath(jobName, cloudbrain.ModelMountPath+"/"),
  1708. storage.GetMinioPath(jobName, cloudbrain.BenchMarkMountPath+"/"), storage.GetMinioPath(jobName, cloudbrain.Snn4imagenetMountPath+"/"),
  1709. storage.GetMinioPath(jobName, cloudbrain.BrainScoreMountPath+"/"), string(models.JobTypeBenchmark), gpuQueue, form.Description, cloudbrain.DefaultBranchName, "", "",
  1710. benchmarkTypeID, benchmarkChildTypeID, resourceSpecId)
  1711. if err != nil {
  1712. cloudBrainNewDataPrepare(ctx)
  1713. ctx.RenderWithErr(err.Error(), tplCloudBrainBenchmarkNew, &form)
  1714. return
  1715. }
  1716. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/cloudbrain/benchmark")
  1717. }
  1718. func BenchmarkDel(ctx *context.Context) {
  1719. if err := deleteCloudbrainJob(ctx); err != nil {
  1720. log.Error("deleteCloudbrainJob failed: %v", err, ctx.Data["msgID"])
  1721. ctx.ServerError(err.Error(), err)
  1722. return
  1723. }
  1724. var isAdminPage = ctx.Query("isadminpage")
  1725. var isHomePage = ctx.Query("ishomepage")
  1726. if ctx.IsUserSiteAdmin() && isAdminPage == "true" {
  1727. ctx.Redirect(setting.AppSubURL + "/admin" + "/cloudbrains")
  1728. } else if isHomePage == "true" {
  1729. ctx.Redirect(setting.AppSubURL + "/cloudbrains")
  1730. } else {
  1731. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/cloudbrain/benchmark")
  1732. }
  1733. }
  1734. func CloudBrainTrainJobNew(ctx *context.Context) {
  1735. err := cloudBrainNewDataPrepare(ctx)
  1736. if err != nil {
  1737. ctx.ServerError("get new train-job info failed", err)
  1738. return
  1739. }
  1740. ctx.HTML(http.StatusOK, tplCloudBrainTrainJobNew)
  1741. }
  1742. func getTrainJobCommand(form auth.CreateCloudBrainForm) (string, error) {
  1743. var command string
  1744. bootFile := form.BootFile
  1745. params := form.Params
  1746. if !strings.HasSuffix(bootFile, ".py") {
  1747. log.Error("bootFile(%s) format error", bootFile)
  1748. return command, errors.New("bootFile format error")
  1749. }
  1750. var parameters models.Parameters
  1751. var param string
  1752. if len(params) != 0 {
  1753. err := json.Unmarshal([]byte(params), &parameters)
  1754. if err != nil {
  1755. log.Error("Failed to Unmarshal params: %s (%v)", params, err)
  1756. return command, err
  1757. }
  1758. for _, parameter := range parameters.Parameter {
  1759. param += " --" + parameter.Label + "=" + parameter.Value
  1760. }
  1761. }
  1762. command += "python /code/" + bootFile + param + " > " + cloudbrain.ModelMountPath + "/" + form.DisplayJobName + "-" + cloudbrain.LogFile
  1763. return command, nil
  1764. }
  1765. func CloudBrainTrainJobDel(ctx *context.Context) {
  1766. var listType = ctx.Query("listType")
  1767. if err := deleteCloudbrainJob(ctx); err != nil {
  1768. log.Error("deleteCloudbrainJob failed: %v", err, ctx.Data["msgID"])
  1769. ctx.ServerError(err.Error(), err)
  1770. return
  1771. }
  1772. var isAdminPage = ctx.Query("isadminpage")
  1773. var isHomePage = ctx.Query("ishomepage")
  1774. if ctx.IsUserSiteAdmin() && isAdminPage == "true" {
  1775. ctx.Redirect(setting.AppSubURL + "/admin" + "/cloudbrains")
  1776. } else if isHomePage == "true" {
  1777. ctx.Redirect(setting.AppSubURL + "/cloudbrains")
  1778. } else {
  1779. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/train-job?listType=" + listType)
  1780. }
  1781. }
  1782. func GetBenchmarkTypes(ctx *context.Context) *models.BenchmarkTypes {
  1783. var lang = ctx.Locale.Language()
  1784. if benchmarkTypesMap[lang] == nil {
  1785. var val = i18n.Tr(lang, BENCHMARK_TYPE_CODE)
  1786. //use config
  1787. val = setting.BenchmarkTypes
  1788. var tempType *models.BenchmarkTypes
  1789. if err := json.Unmarshal([]byte(val), &tempType); err != nil {
  1790. log.Error("json.Unmarshal BenchmarkTypes(%s) failed:%v", val, err, ctx.Data["MsgID"])
  1791. return &models.BenchmarkTypes{}
  1792. }
  1793. benchmarkTypesMap[lang] = tempType
  1794. }
  1795. return benchmarkTypesMap[lang]
  1796. }