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

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