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

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