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