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

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