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

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