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

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