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

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
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
2 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
4 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
2 years ago
2 years ago
2 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
2 years ago
2 years ago
2 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
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
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
5 years ago
3 years ago
3 years ago
3 years ago
3 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
5 years ago
3 years ago
3 years ago
3 years ago
5 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
3 years ago
3 years ago
5 years ago
3 years ago
2 years ago
3 years ago
5 years ago
3 years ago
3 years ago
5 years ago
3 years ago
2 years ago
3 years ago
5 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
5 years ago
3 years ago
3 years ago
3 years ago
2 years ago
2 years ago
3 years ago
3 years ago
3 years ago
2 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
4 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
5 years ago
4 years ago
4 years ago
3 years ago
3 years ago
4 years ago
3 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
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
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
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
3 years ago
4 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691
  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. cloudbrain.InitSpecialPool()
  545. var task *models.Cloudbrain
  546. var err error
  547. if jobType == models.JobTypeTrain || jobType == models.JobTypeInference {
  548. task, err = models.GetCloudbrainByJobID(ctx.Params(":jobid"))
  549. } else {
  550. task, err = models.GetCloudbrainByIDWithDeleted(ctx.Params(":id"))
  551. }
  552. if err != nil {
  553. log.Info("error:" + err.Error())
  554. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  555. return
  556. }
  557. result, err := cloudbrain.GetJob(task.JobID)
  558. if err != nil {
  559. log.Info("error:" + err.Error())
  560. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  561. return
  562. }
  563. hasSpec := false
  564. if task.JobType == string(models.JobTypeTrain) {
  565. if cloudbrain.TrainResourceSpecs == nil {
  566. json.Unmarshal([]byte(setting.TrainResourceSpecs), &cloudbrain.TrainResourceSpecs)
  567. }
  568. for _, tmp := range cloudbrain.TrainResourceSpecs.ResourceSpec {
  569. if tmp.Id == task.ResourceSpecId {
  570. hasSpec = true
  571. ctx.Data["GpuNum"] = tmp.GpuNum
  572. ctx.Data["CpuNum"] = tmp.CpuNum
  573. ctx.Data["MemMiB"] = tmp.MemMiB
  574. ctx.Data["ShareMemMiB"] = tmp.ShareMemMiB
  575. break
  576. }
  577. }
  578. } else if task.JobType == string(models.JobTypeInference) {
  579. if cloudbrain.InferenceResourceSpecs == nil {
  580. json.Unmarshal([]byte(setting.InferenceResourceSpecs), &cloudbrain.InferenceResourceSpecs)
  581. }
  582. for _, tmp := range cloudbrain.InferenceResourceSpecs.ResourceSpec {
  583. if tmp.Id == task.ResourceSpecId {
  584. hasSpec = true
  585. ctx.Data["GpuNum"] = tmp.GpuNum
  586. ctx.Data["CpuNum"] = tmp.CpuNum
  587. ctx.Data["MemMiB"] = tmp.MemMiB
  588. ctx.Data["ShareMemMiB"] = tmp.ShareMemMiB
  589. break
  590. }
  591. }
  592. } else {
  593. if cloudbrain.ResourceSpecs == nil {
  594. json.Unmarshal([]byte(setting.ResourceSpecs), &cloudbrain.ResourceSpecs)
  595. }
  596. for _, tmp := range cloudbrain.ResourceSpecs.ResourceSpec {
  597. if tmp.Id == task.ResourceSpecId {
  598. hasSpec = true
  599. ctx.Data["GpuNum"] = tmp.GpuNum
  600. ctx.Data["CpuNum"] = tmp.CpuNum
  601. ctx.Data["MemMiB"] = tmp.MemMiB
  602. ctx.Data["ShareMemMiB"] = tmp.ShareMemMiB
  603. break
  604. }
  605. }
  606. }
  607. if !hasSpec && cloudbrain.SpecialPools != nil {
  608. for _, specialPool := range cloudbrain.SpecialPools.Pools {
  609. if specialPool.ResourceSpec != nil {
  610. for _, spec := range specialPool.ResourceSpec {
  611. if task.ResourceSpecId == spec.Id {
  612. ctx.Data["GpuNum"] = spec.GpuNum
  613. ctx.Data["CpuNum"] = spec.CpuNum
  614. ctx.Data["MemMiB"] = spec.MemMiB
  615. ctx.Data["ShareMemMiB"] = spec.ShareMemMiB
  616. break
  617. }
  618. }
  619. }
  620. }
  621. }
  622. if result != nil {
  623. jobRes, _ := models.ConvertToJobResultPayload(result.Payload)
  624. jobRes.Resource.Memory = strings.ReplaceAll(jobRes.Resource.Memory, "Mi", "MB")
  625. spec := "GPU数:" + strconv.Itoa(jobRes.Resource.NvidiaComGpu) + ",CPU数:" + strconv.Itoa(jobRes.Resource.CPU) + ",内存(MB):" + jobRes.Resource.Memory
  626. ctx.Data["resource_spec"] = spec
  627. if task.JobType == string(models.JobTypeTrain) {
  628. if trainGpuInfos == nil {
  629. json.Unmarshal([]byte(setting.TrainGpuTypes), &trainGpuInfos)
  630. }
  631. for _, resourceType := range trainGpuInfos.GpuInfo {
  632. if resourceType.Queue == jobRes.Config.GpuType {
  633. ctx.Data["resource_type"] = resourceType.Value
  634. }
  635. }
  636. } else if task.JobType == string(models.JobTypeInference) {
  637. if inferenceGpuInfos == nil {
  638. json.Unmarshal([]byte(setting.InferenceGpuTypes), &inferenceGpuInfos)
  639. }
  640. for _, resourceType := range inferenceGpuInfos.GpuInfo {
  641. if resourceType.Queue == jobRes.Config.GpuType {
  642. ctx.Data["resource_type"] = resourceType.Value
  643. }
  644. }
  645. } else if cloudbrain.IsBenchmarkJob(task.JobType) {
  646. if benchmarkGpuInfos == nil {
  647. json.Unmarshal([]byte(setting.BenchmarkGpuTypes), &benchmarkGpuInfos)
  648. }
  649. for _, resourceType := range benchmarkGpuInfos.GpuInfo {
  650. if resourceType.Queue == jobRes.Config.GpuType {
  651. ctx.Data["resource_type"] = resourceType.Value
  652. }
  653. }
  654. } else {
  655. if gpuInfos == nil {
  656. json.Unmarshal([]byte(setting.GpuTypes), &gpuInfos)
  657. }
  658. for _, resourceType := range gpuInfos.GpuInfo {
  659. if resourceType.Queue == jobRes.Config.GpuType {
  660. ctx.Data["resource_type"] = resourceType.Value
  661. }
  662. }
  663. }
  664. if cloudbrain.SpecialPools != nil {
  665. for _, specialPool := range cloudbrain.SpecialPools.Pools {
  666. for _, resourceType := range specialPool.Pool {
  667. if resourceType.Queue == jobRes.Config.GpuType {
  668. ctx.Data["resource_type"] = resourceType.Value
  669. }
  670. }
  671. }
  672. }
  673. taskRoles := jobRes.TaskRoles
  674. taskRes, _ := models.ConvertToTaskPod(taskRoles[cloudbrain.SubTaskName].(map[string]interface{}))
  675. ctx.Data["taskRes"] = taskRes
  676. ctx.Data["ExitDiagnostics"] = taskRes.TaskStatuses[0].ExitDiagnostics
  677. task.Status = taskRes.TaskStatuses[0].State
  678. task.ContainerID = taskRes.TaskStatuses[0].ContainerID
  679. task.ContainerIp = taskRes.TaskStatuses[0].ContainerIP
  680. models.ParseAndSetDurationFromCloudBrainOne(jobRes, task)
  681. if task.DeletedAt.IsZero() { //normal record
  682. err = models.UpdateJob(task)
  683. if err != nil {
  684. ctx.Data["error"] = err.Error()
  685. return
  686. }
  687. } else { //deleted record
  688. }
  689. ctx.Data["result"] = jobRes
  690. } else {
  691. log.Info("error:" + err.Error())
  692. return
  693. }
  694. user, err := models.GetUserByID(task.UserID)
  695. if err == nil {
  696. task.User = user
  697. }
  698. if task.BenchmarkTypeID > 0 {
  699. for _, benchmarkType := range GetBenchmarkTypes(ctx).BenchmarkType {
  700. if task.BenchmarkTypeID == benchmarkType.Id {
  701. ctx.Data["BenchmarkTypeName"] = benchmarkType.First
  702. task.BenchmarkTypeName = benchmarkType.First
  703. for _, benchmarkChildType := range benchmarkType.Second {
  704. if task.BenchmarkChildTypeID == benchmarkChildType.Id {
  705. ctx.Data["BenchmarkChildTypeName"] = benchmarkChildType.Value
  706. break
  707. }
  708. }
  709. break
  710. }
  711. }
  712. }
  713. if task.JobType == string(models.JobTypeBenchmark) {
  714. task.BenchmarkType = ctx.Tr("repo.cloudbrain.benchmark.algorithm")
  715. } else if task.JobType == string(models.JobTypeSnn4imagenet) || task.JobType == string(models.JobTypeBrainScore) {
  716. task.BenchmarkType = ctx.Tr("repo.cloudbrain.benchmark.model")
  717. task.BenchmarkTypeName = task.JobType
  718. ctx.Data["BenchmarkTypeName"] = task.JobType
  719. if task.JobType == string(models.JobTypeBrainScore) {
  720. ctx.Data["BenchmarkChildTypeName"] = getBrainRegion(task.BenchmarkChildTypeID)
  721. }
  722. }
  723. if task.TrainJobDuration == "" {
  724. if task.Duration == 0 {
  725. var duration int64
  726. if task.Status == string(models.JobWaiting) {
  727. duration = 0
  728. } else if task.Status == string(models.JobRunning) {
  729. duration = time.Now().Unix() - int64(task.CreatedUnix)
  730. } else {
  731. duration = int64(task.UpdatedUnix) - int64(task.CreatedUnix)
  732. }
  733. task.Duration = duration
  734. }
  735. task.TrainJobDuration = models.ConvertDurationToStr(task.Duration)
  736. }
  737. ctx.Data["duration"] = task.TrainJobDuration
  738. if len(task.Parameters) > 0 {
  739. var parameters models.Parameters
  740. err := json.Unmarshal([]byte(task.Parameters), &parameters)
  741. if err != nil {
  742. log.Error("Failed to Unmarshal Parameters: %s (%v)", task.Parameters, err)
  743. task.Parameters = ""
  744. } else {
  745. if len(parameters.Parameter) > 0 {
  746. paramTemp := ""
  747. for _, Parameter := range parameters.Parameter {
  748. param := Parameter.Label + " = " + Parameter.Value + "; "
  749. paramTemp = paramTemp + param
  750. }
  751. task.Parameters = paramTemp[:len(paramTemp)-2]
  752. } else {
  753. task.Parameters = ""
  754. }
  755. }
  756. }
  757. ctx.Data["task"] = task
  758. labelName := strings.Fields(task.LabelName)
  759. ctx.Data["LabelName"] = labelName
  760. ctx.Data["jobName"] = task.JobName
  761. ctx.Data["displayJobName"] = task.DisplayJobName
  762. version_list_task := make([]*models.Cloudbrain, 0)
  763. version_list_task = append(version_list_task, task)
  764. ctx.Data["version_list_task"] = version_list_task
  765. ctx.Data["debugListType"] = debugListType
  766. ctx.Data["code_path"] = cloudbrain.CodeMountPath
  767. ctx.Data["dataset_path"] = cloudbrain.DataSetMountPath
  768. ctx.Data["model_path"] = cloudbrain.ModelMountPath
  769. ctx.Data["canDownload"] = cloudbrain.CanModifyJob(ctx, task)
  770. ctx.Data["branchName"] = task.BranchName
  771. ctx.HTML(200, tpName)
  772. }
  773. func CloudBrainDebug(ctx *context.Context) {
  774. task := ctx.Cloudbrain
  775. debugUrl := setting.DebugServerHost + "jpylab_" + task.JobID + "_" + task.SubTaskName
  776. ctx.Redirect(debugUrl)
  777. }
  778. func CloudBrainCommitImageShow(ctx *context.Context) {
  779. ctx.Data["PageIsCloudBrain"] = true
  780. ctx.Data["Type"] = ctx.Cloudbrain.Type
  781. ctx.HTML(200, tplCloudBrainImageSubmit)
  782. }
  783. func GetImage(ctx *context.Context) {
  784. var ID = ctx.Params(":id")
  785. id, _ := strconv.ParseInt(ID, 10, 64)
  786. image, err := models.GetImageByID(id)
  787. if err != nil {
  788. log.Error("GetImageByID failed:%v", err.Error())
  789. ctx.JSON(http.StatusNotFound, nil)
  790. }
  791. ctx.JSON(http.StatusOK, image)
  792. }
  793. func CloudBrainImageEdit(ctx *context.Context) {
  794. ctx.Data["PageIsImageEdit"] = true
  795. ctx.Data["PageFrom"] = ctx.Params(":from")
  796. var ID = ctx.Params(":id")
  797. id, err := strconv.ParseInt(ID, 10, 64)
  798. if err != nil {
  799. log.Error("GetImageByID failed:%v", err.Error())
  800. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  801. }
  802. image, err := models.GetImageByID(id)
  803. if err != nil {
  804. log.Error("GetImageByID failed:%v", err.Error())
  805. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  806. }
  807. ctx.Data["Image"] = image
  808. ctx.HTML(http.StatusOK, tplCloudBrainImageEdit)
  809. }
  810. func CloudBrainImageEditPost(ctx *context.Context, form auth.EditImageCloudBrainForm) {
  811. if utf8.RuneCountInString(form.Description) > 255 {
  812. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("dataset.description_format_err", 255)))
  813. return
  814. }
  815. validTopics, errMessage := checkTopics(form.Topics)
  816. if errMessage != "" {
  817. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr(errMessage)))
  818. return
  819. }
  820. image, err := models.GetImageByID(form.ID)
  821. if err != nil {
  822. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("repo.image_not_exist")))
  823. }
  824. image.IsPrivate = form.IsPrivate
  825. image.Description = form.Description
  826. err = models.WithTx(func(ctx models.DBContext) error {
  827. if err := models.UpdateLocalImage(image); err != nil {
  828. return err
  829. }
  830. if err := models.SaveImageTopics(image.ID, validTopics...); err != nil {
  831. return err
  832. }
  833. return nil
  834. })
  835. if err != nil {
  836. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("repo.image_not_exist")))
  837. } else {
  838. ctx.JSON(http.StatusOK, models.BaseOKMessage)
  839. }
  840. }
  841. func CloudBrainImageDelete(ctx *context.Context) {
  842. var ID = ctx.Params(":id")
  843. id, err := strconv.ParseInt(ID, 10, 64)
  844. if err != nil {
  845. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("repo.image_not_exist")))
  846. return
  847. }
  848. err = models.DeleteLocalImage(id)
  849. if err != nil {
  850. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("repo.image_delete_fail")))
  851. } else {
  852. ctx.JSON(http.StatusOK, models.BaseOKMessage)
  853. }
  854. }
  855. func CloudBrainCommitImageCheck(ctx *context.Context, form auth.CommitImageCloudBrainForm) {
  856. isExist, _ := models.IsImageExistByUser(form.Tag, ctx.User.ID)
  857. if isExist {
  858. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("repo.image_overwrite")))
  859. } else {
  860. ctx.JSON(http.StatusOK, models.BaseOKMessage)
  861. }
  862. }
  863. func CloudBrainAdminCommitImage(ctx *context.Context, form auth.CommitAdminImageCloudBrainForm) {
  864. if !NamePattern.MatchString(form.Tag) {
  865. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("dataset.title_format_err")))
  866. return
  867. }
  868. if utf8.RuneCountInString(form.Description) > 255 {
  869. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("dataset.description_format_err", 255)))
  870. return
  871. }
  872. validTopics, errMessage := checkTopics(form.Topics)
  873. if errMessage != "" {
  874. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr(errMessage)))
  875. return
  876. }
  877. err := cloudbrain.CommitAdminImage(models.CommitImageParams{
  878. CommitImageCloudBrainParams: models.CommitImageCloudBrainParams{
  879. ImageDescription: form.Description,
  880. ImageTag: form.Tag,
  881. },
  882. IsPrivate: form.IsPrivate,
  883. CloudBrainType: form.Type,
  884. Topics: validTopics,
  885. UID: ctx.User.ID,
  886. Type: models.GetRecommondType(form.IsRecommend),
  887. Place: form.Place,
  888. })
  889. if err != nil {
  890. log.Error("CommitImagefailed")
  891. if models.IsErrImageTagExist(err) {
  892. ctx.JSON(200, models.BaseErrorMessage(ctx.Tr("repo.image_exist")))
  893. } else if models.IsErrorImageCommitting(err) {
  894. ctx.JSON(200, models.BaseErrorMessage(ctx.Tr("repo.image_committing")))
  895. } else {
  896. ctx.JSON(200, models.BaseErrorMessage(ctx.Tr("repo.image_commit_fail")))
  897. }
  898. return
  899. }
  900. ctx.JSON(200, models.BaseOKMessage)
  901. }
  902. func CloudBrainCommitImage(ctx *context.Context, form auth.CommitImageCloudBrainForm) {
  903. if !NamePattern.MatchString(form.Tag) {
  904. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("dataset.title_format_err")))
  905. return
  906. }
  907. if utf8.RuneCountInString(form.Description) > 255 {
  908. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("dataset.description_format_err", 255)))
  909. return
  910. }
  911. validTopics, errMessage := checkTopics(form.Topics)
  912. if errMessage != "" {
  913. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr(errMessage)))
  914. return
  915. }
  916. err := cloudbrain.CommitImage(ctx.Cloudbrain.JobID, models.CommitImageParams{
  917. CommitImageCloudBrainParams: models.CommitImageCloudBrainParams{
  918. Ip: ctx.Cloudbrain.ContainerIp,
  919. TaskContainerId: ctx.Cloudbrain.ContainerID,
  920. ImageDescription: form.Description,
  921. ImageTag: form.Tag,
  922. },
  923. IsPrivate: form.IsPrivate,
  924. CloudBrainType: form.Type,
  925. Topics: validTopics,
  926. UID: ctx.User.ID,
  927. })
  928. if err != nil {
  929. log.Error("CommitImage(%s) failed:%v", ctx.Cloudbrain.JobName, err.Error(), ctx.Data["msgID"])
  930. if models.IsErrImageTagExist(err) {
  931. ctx.JSON(200, models.BaseErrorMessage(ctx.Tr("repo.image_exist")))
  932. } else if models.IsErrorImageCommitting(err) {
  933. ctx.JSON(200, models.BaseErrorMessage(ctx.Tr("repo.image_committing")))
  934. } else {
  935. ctx.JSON(200, models.BaseErrorMessage(ctx.Tr("repo.image_commit_fail")))
  936. }
  937. return
  938. }
  939. ctx.JSON(200, models.BaseOKMessage)
  940. }
  941. func checkTopics(Topics string) ([]string, string) {
  942. var topics = make([]string, 0)
  943. var topicsStr = strings.TrimSpace(Topics)
  944. if len(topicsStr) > 0 {
  945. topics = strings.Split(topicsStr, ",")
  946. }
  947. validTopics, invalidTopics := models.SanitizeAndValidateImageTopics(topics)
  948. if len(validTopics) > 25 {
  949. return nil, "repo.topic.count_prompt"
  950. }
  951. if len(invalidTopics) > 0 {
  952. return nil, "repo.imagetopic.format_prompt"
  953. }
  954. return validTopics, ""
  955. }
  956. func CloudBrainStop(ctx *context.Context) {
  957. var ID = ctx.Params(":id")
  958. var resultCode = "0"
  959. var errorMsg = ""
  960. var status = ""
  961. task := ctx.Cloudbrain
  962. for {
  963. if task.Status == string(models.JobStopped) || task.Status == string(models.JobFailed) || task.Status == string(models.JobSucceeded) {
  964. log.Error("the job(%s) has been stopped", task.JobName, ctx.Data["msgID"])
  965. resultCode = "-1"
  966. errorMsg = "cloudbrain.Already_stopped"
  967. break
  968. }
  969. err := cloudbrain.StopJob(task.JobID)
  970. if err != nil {
  971. log.Error("StopJob(%s) failed:%v", task.JobName, err, ctx.Data["msgID"])
  972. resultCode = "-1"
  973. errorMsg = "cloudbrain.Stopped_failed"
  974. break
  975. }
  976. task.Status = string(models.JobStopped)
  977. if task.EndTime == 0 {
  978. task.EndTime = timeutil.TimeStampNow()
  979. }
  980. task.ComputeAndSetDuration()
  981. err = models.UpdateJob(task)
  982. if err != nil {
  983. log.Error("UpdateJob(%s) failed:%v", task.JobName, err, ctx.Data["msgID"])
  984. resultCode = "-1"
  985. errorMsg = "cloudbrain.Stopped_success_update_status_fail"
  986. break
  987. }
  988. status = task.Status
  989. break
  990. }
  991. ctx.JSON(200, map[string]interface{}{
  992. "result_code": resultCode,
  993. "error_msg": ctx.Tr(errorMsg),
  994. "status": status,
  995. "id": ID,
  996. "StatusOK": 0,
  997. })
  998. }
  999. func StopJobsByUserID(userID int64) {
  1000. cloudBrains, err := models.GetCloudbrainsNeededStopByUserID(userID)
  1001. if err != nil {
  1002. log.Warn("Failed to get cloudBrain info", err)
  1003. return
  1004. }
  1005. StopJobs(cloudBrains)
  1006. }
  1007. func StopJobsByRepoID(repoID int64) {
  1008. cloudBrains, err := models.GetCloudbrainsNeededStopByRepoID(repoID)
  1009. if err != nil {
  1010. log.Warn("Failed to get cloudBrain info", err)
  1011. return
  1012. }
  1013. StopJobs(cloudBrains)
  1014. }
  1015. /**
  1016. */
  1017. func StopJobs(cloudBrains []*models.Cloudbrain) {
  1018. for _, taskInfo := range cloudBrains {
  1019. if taskInfo.Type == models.TypeCloudBrainOne {
  1020. err := retry(3, time.Second*30, func() error {
  1021. return cloudbrain.StopJob(taskInfo.JobID)
  1022. })
  1023. logErrorAndUpdateJobStatus(err, taskInfo)
  1024. } else {
  1025. if taskInfo.JobType == string(models.JobTypeTrain) {
  1026. err := retry(3, time.Second*30, func() error {
  1027. _, err := modelarts.StopTrainJob(taskInfo.JobID, strconv.FormatInt(taskInfo.VersionID, 10))
  1028. return err
  1029. })
  1030. logErrorAndUpdateJobStatus(err, taskInfo)
  1031. } else {
  1032. param := models.NotebookAction{
  1033. Action: models.ActionStop,
  1034. }
  1035. err := retry(3, time.Second*30, func() error {
  1036. _, err := modelarts.ManageNotebook(taskInfo.JobID, param)
  1037. return err
  1038. })
  1039. logErrorAndUpdateJobStatus(err, taskInfo)
  1040. }
  1041. }
  1042. }
  1043. }
  1044. func retry(attempts int, sleep time.Duration, f func() error) (err error) {
  1045. for i := 0; i < attempts; i++ {
  1046. if i > 0 {
  1047. log.Warn("retrying after error:", err)
  1048. time.Sleep(sleep)
  1049. }
  1050. err = f()
  1051. if err == nil {
  1052. return nil
  1053. }
  1054. }
  1055. return fmt.Errorf("after %d attempts, last error: %s", attempts, err)
  1056. }
  1057. func logErrorAndUpdateJobStatus(err error, taskInfo *models.Cloudbrain) {
  1058. if err != nil {
  1059. log.Warn("Failed to stop cloudBrain job:"+taskInfo.JobID, err)
  1060. } else {
  1061. taskInfo.Status = string(models.JobStopped)
  1062. if taskInfo.EndTime == 0 {
  1063. taskInfo.EndTime = timeutil.TimeStampNow()
  1064. }
  1065. taskInfo.ComputeAndSetDuration()
  1066. err = models.UpdateJob(taskInfo)
  1067. if err != nil {
  1068. log.Warn("UpdateJob failed", err)
  1069. }
  1070. }
  1071. }
  1072. func CloudBrainDel(ctx *context.Context) {
  1073. var listType = ctx.Query("debugListType")
  1074. if err := deleteCloudbrainJob(ctx); err != nil {
  1075. log.Error("deleteCloudbrainJob failed: %v", err, ctx.Data["msgID"])
  1076. ctx.ServerError(err.Error(), err)
  1077. return
  1078. }
  1079. var isAdminPage = ctx.Query("isadminpage")
  1080. var isHomePage = ctx.Query("ishomepage")
  1081. if ctx.IsUserSiteAdmin() && isAdminPage == "true" {
  1082. ctx.Redirect(setting.AppSubURL + "/admin" + "/cloudbrains")
  1083. } else if isHomePage == "true" {
  1084. ctx.Redirect(setting.AppSubURL + "/cloudbrains")
  1085. } else {
  1086. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/debugjob?debugListType=" + listType)
  1087. }
  1088. }
  1089. func deleteCloudbrainJob(ctx *context.Context) error {
  1090. task := ctx.Cloudbrain
  1091. if task.Status != string(models.JobStopped) && task.Status != string(models.JobFailed) && task.Status != string(models.JobSucceeded) {
  1092. log.Error("the job(%s) has not been stopped", task.JobName, ctx.Data["msgID"])
  1093. return errors.New("the job has not been stopped")
  1094. }
  1095. err := models.DeleteJob(task)
  1096. if err != nil {
  1097. log.Error("DeleteJob failed: %v", err, ctx.Data["msgID"])
  1098. return err
  1099. }
  1100. deleteJobStorage(task.JobName, models.TypeCloudBrainOne)
  1101. return nil
  1102. }
  1103. func CloudBrainShowModels(ctx *context.Context) {
  1104. ctx.Data["PageIsCloudBrain"] = true
  1105. ID := ctx.Params(":id")
  1106. parentDir := ctx.Query("parentDir")
  1107. dirArray := strings.Split(parentDir, "/")
  1108. task, err := models.GetCloudbrainByID(ID)
  1109. if err != nil {
  1110. log.Error("no such job!", ctx.Data["msgID"])
  1111. ctx.ServerError("no such job:", err)
  1112. return
  1113. }
  1114. //get dirs
  1115. dirs, err := GetModelDirs(task.JobName, parentDir)
  1116. if err != nil {
  1117. log.Error("GetModelDirs failed:%v", err.Error(), ctx.Data["msgID"])
  1118. ctx.ServerError("GetModelDirs failed:", err)
  1119. return
  1120. }
  1121. var fileInfos []storage.FileInfo
  1122. err = json.Unmarshal([]byte(dirs), &fileInfos)
  1123. if err != nil {
  1124. log.Error("json.Unmarshal failed:%v", err.Error(), ctx.Data["msgID"])
  1125. ctx.ServerError("json.Unmarshal failed:", err)
  1126. return
  1127. }
  1128. for i, fileInfo := range fileInfos {
  1129. temp, _ := time.Parse("2006-01-02 15:04:05", fileInfo.ModTime)
  1130. fileInfos[i].ModTime = temp.Local().Format("2006-01-02 15:04:05")
  1131. }
  1132. sort.Slice(fileInfos, func(i, j int) bool {
  1133. return fileInfos[i].ModTime > fileInfos[j].ModTime
  1134. })
  1135. ctx.Data["Path"] = dirArray
  1136. ctx.Data["Dirs"] = fileInfos
  1137. ctx.Data["task"] = task
  1138. ctx.Data["ID"] = ID
  1139. ctx.HTML(200, tplCloudBrainShowModels)
  1140. }
  1141. func GetPublicImages(ctx *context.Context) {
  1142. uid := getUID(ctx)
  1143. opts := models.SearchImageOptions{
  1144. IncludePublicOnly: true,
  1145. UID: uid,
  1146. Keyword: ctx.Query("q"),
  1147. Topics: ctx.Query("topic"),
  1148. IncludeOfficialOnly: ctx.QueryBool("recommend"),
  1149. SearchOrderBy: "type desc, num_stars desc,id desc",
  1150. Status: models.IMAGE_STATUS_SUCCESS,
  1151. CloudbrainType: ctx.QueryInt("cloudbrainType"),
  1152. }
  1153. getImages(ctx, &opts)
  1154. }
  1155. func GetCustomImages(ctx *context.Context) {
  1156. uid := getUID(ctx)
  1157. opts := models.SearchImageOptions{
  1158. UID: uid,
  1159. IncludeOwnerOnly: true,
  1160. Keyword: ctx.Query("q"),
  1161. Topics: ctx.Query("topic"),
  1162. Status: -1,
  1163. SearchOrderBy: "id desc",
  1164. }
  1165. getImages(ctx, &opts)
  1166. }
  1167. func GetStarImages(ctx *context.Context) {
  1168. uid := getUID(ctx)
  1169. opts := models.SearchImageOptions{
  1170. UID: uid,
  1171. IncludeStarByMe: true,
  1172. Keyword: ctx.Query("q"),
  1173. Topics: ctx.Query("topic"),
  1174. Status: models.IMAGE_STATUS_SUCCESS,
  1175. SearchOrderBy: "id desc",
  1176. }
  1177. getImages(ctx, &opts)
  1178. }
  1179. func getUID(ctx *context.Context) int64 {
  1180. var uid int64 = -1
  1181. if ctx.IsSigned {
  1182. uid = ctx.User.ID
  1183. }
  1184. return uid
  1185. }
  1186. func GetAllImages(ctx *context.Context) {
  1187. uid := getUID(ctx)
  1188. opts := models.SearchImageOptions{
  1189. UID: uid,
  1190. Keyword: ctx.Query("q"),
  1191. Topics: ctx.Query("topic"),
  1192. IncludeOfficialOnly: ctx.QueryBool("recommend"),
  1193. SearchOrderBy: "id desc",
  1194. Status: -1,
  1195. }
  1196. if ctx.Query("private") != "" {
  1197. if ctx.QueryBool("private") {
  1198. opts.IncludePrivateOnly = true
  1199. } else {
  1200. opts.IncludePublicOnly = true
  1201. }
  1202. }
  1203. getImages(ctx, &opts)
  1204. }
  1205. func getImages(ctx *context.Context, opts *models.SearchImageOptions) {
  1206. page := ctx.QueryInt("page")
  1207. if page <= 0 {
  1208. page = 1
  1209. }
  1210. pageSize := ctx.QueryInt("pageSize")
  1211. if pageSize <= 0 {
  1212. pageSize = 15
  1213. }
  1214. opts.ListOptions = models.ListOptions{
  1215. Page: page,
  1216. PageSize: pageSize,
  1217. }
  1218. imageList, total, err := models.SearchImage(opts)
  1219. if err != nil {
  1220. log.Error("Can not get images:%v", err)
  1221. ctx.JSON(http.StatusOK, models.ImagesPageResult{
  1222. Count: 0,
  1223. Images: []*models.Image{},
  1224. })
  1225. } else {
  1226. ctx.JSON(http.StatusOK, models.ImagesPageResult{
  1227. Count: total,
  1228. Images: imageList,
  1229. })
  1230. }
  1231. }
  1232. func GetModelDirs(jobName string, parentDir string) (string, error) {
  1233. var req string
  1234. modelActualPath := storage.GetMinioPath(jobName, cloudbrain.ModelMountPath+"/")
  1235. if parentDir == "" {
  1236. req = "baseDir=" + modelActualPath
  1237. } else {
  1238. req = "baseDir=" + modelActualPath + "&parentDir=" + parentDir
  1239. }
  1240. return getDirs(req)
  1241. }
  1242. func GetResultDirs(jobName string, parentDir string) (string, error) {
  1243. var req string
  1244. modelActualPath := storage.GetMinioPath(jobName, cloudbrain.ResultPath+"/")
  1245. if parentDir == "" {
  1246. req = "baseDir=" + modelActualPath
  1247. } else {
  1248. req = "baseDir=" + modelActualPath + "&parentDir=" + parentDir
  1249. }
  1250. return getDirs(req)
  1251. }
  1252. func CloudBrainDownloadModel(ctx *context.Context) {
  1253. parentDir := ctx.Query("parentDir")
  1254. fileName := ctx.Query("fileName")
  1255. jobName := ctx.Query("jobName")
  1256. filePath := "jobs/" + jobName + "/model/" + parentDir
  1257. url, err := storage.Attachments.PresignedGetURL(filePath, fileName)
  1258. if err != nil {
  1259. log.Error("PresignedGetURL failed: %v", err.Error(), ctx.Data["msgID"])
  1260. ctx.ServerError("PresignedGetURL", err)
  1261. return
  1262. }
  1263. ctx.Resp.Header().Set("Cache-Control", "max-age=0")
  1264. http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusMovedPermanently)
  1265. }
  1266. func CloudBrainDownloadInferenceResult(ctx *context.Context) {
  1267. parentDir := ctx.Query("parentDir")
  1268. fileName := ctx.Query("fileName")
  1269. jobName := ctx.Query("jobName")
  1270. filePath := "jobs/" + jobName + "/result/" + parentDir
  1271. url, err := storage.Attachments.PresignedGetURL(filePath, fileName)
  1272. if err != nil {
  1273. log.Error("PresignedGetURL failed: %v", err.Error(), ctx.Data["msgID"])
  1274. ctx.ServerError("PresignedGetURL", err)
  1275. return
  1276. }
  1277. ctx.Resp.Header().Set("Cache-Control", "max-age=0")
  1278. http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusMovedPermanently)
  1279. }
  1280. func GetRate(ctx *context.Context) {
  1281. isObjectDetcionAll := ctx.QueryBool("isObjectDetcionAll")
  1282. if isObjectDetcionAll {
  1283. ctx.Redirect(setting.BenchmarkServerHost + "?username=admin")
  1284. return
  1285. }
  1286. var ID = ctx.Params(":id")
  1287. job, err := models.GetCloudbrainByID(ID)
  1288. if err != nil {
  1289. ctx.ServerError("GetCloudbrainByJobID failed", err)
  1290. return
  1291. }
  1292. if job.JobType == string(models.JobTypeBenchmark) {
  1293. log.Info("url=" + setting.BenchmarkServerHost + "?username=" + ctx.User.Name)
  1294. ctx.Redirect(setting.BenchmarkServerHost + "?username=" + ctx.User.Name)
  1295. } else if job.JobType == string(models.JobTypeSnn4imagenet) {
  1296. ctx.Redirect(setting.Snn4imagenetServerHost)
  1297. } else if job.JobType == string(models.JobTypeBrainScore) {
  1298. ctx.Redirect(setting.BrainScoreServerHost)
  1299. } else {
  1300. log.Error("JobType error:%s", job.JobType, ctx.Data["msgID"])
  1301. }
  1302. }
  1303. func downloadCode(repo *models.Repository, codePath, branchName string) error {
  1304. //add "file:///" prefix to make the depth valid
  1305. if err := git.Clone(CLONE_FILE_PREFIX+repo.RepoPath(), codePath, git.CloneRepoOptions{Branch: branchName, Depth: 1}); err != nil {
  1306. log.Error("Failed to clone repository: %s (%v)", repo.FullName(), err)
  1307. return err
  1308. }
  1309. configFile, err := os.OpenFile(codePath+"/.git/config", os.O_RDWR, 0666)
  1310. if err != nil {
  1311. log.Error("open file(%s) failed:%v", codePath+"/,git/config", err)
  1312. return err
  1313. }
  1314. defer configFile.Close()
  1315. pos := int64(0)
  1316. reader := bufio.NewReader(configFile)
  1317. for {
  1318. line, err := reader.ReadString('\n')
  1319. if err != nil {
  1320. if err == io.EOF {
  1321. log.Error("not find the remote-url")
  1322. return nil
  1323. } else {
  1324. log.Error("read error: %v", err)
  1325. return err
  1326. }
  1327. }
  1328. if strings.Contains(line, "url") && strings.Contains(line, ".git") {
  1329. originUrl := "\turl = " + repo.CloneLink().HTTPS + "\n"
  1330. if len(line) > len(originUrl) {
  1331. originUrl += strings.Repeat(" ", len(line)-len(originUrl))
  1332. }
  1333. bytes := []byte(originUrl)
  1334. _, err := configFile.WriteAt(bytes, pos)
  1335. if err != nil {
  1336. log.Error("WriteAt failed:%v", err)
  1337. return err
  1338. }
  1339. break
  1340. }
  1341. pos += int64(len(line))
  1342. }
  1343. return nil
  1344. }
  1345. func downloadRateCode(repo *models.Repository, taskName, rateOwnerName, rateRepoName, codePath, benchmarkCategory, gpuType, userName string) error {
  1346. err := os.MkdirAll(codePath, os.ModePerm)
  1347. if err != nil {
  1348. log.Error("mkdir codePath failed", err.Error())
  1349. return err
  1350. }
  1351. repoExt, err := models.GetRepositoryByOwnerAndName(rateOwnerName, rateRepoName)
  1352. if err != nil {
  1353. log.Error("GetRepositoryByOwnerAndName(%s) failed", rateRepoName, err.Error())
  1354. return err
  1355. }
  1356. if err := git.Clone(CLONE_FILE_PREFIX+repoExt.RepoPath(), codePath, git.CloneRepoOptions{Depth: 1}); err != nil {
  1357. log.Error("Failed to clone repository: %s (%v)", repoExt.FullName(), err)
  1358. return err
  1359. }
  1360. fileName := codePath + cloudbrain.TaskInfoName
  1361. f, err := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.ModePerm)
  1362. if err != nil {
  1363. log.Error("OpenFile failed", err.Error())
  1364. return err
  1365. }
  1366. defer f.Close()
  1367. data, err := json.Marshal(models.TaskInfo{
  1368. Username: userName,
  1369. TaskName: taskName,
  1370. CodeName: repo.Name,
  1371. BenchmarkCategory: strings.Split(benchmarkCategory, ","),
  1372. CodeLink: strings.TrimSuffix(repo.CloneLink().HTTPS, ".git"),
  1373. GpuType: gpuType,
  1374. })
  1375. if err != nil {
  1376. log.Error("json.Marshal failed", err.Error())
  1377. return err
  1378. }
  1379. _, err = f.Write(data)
  1380. if err != nil {
  1381. log.Error("WriteString failed", err.Error())
  1382. return err
  1383. }
  1384. return nil
  1385. }
  1386. func uploadCodeToMinio(codePath, jobName, parentDir string) error {
  1387. files, err := readDir(codePath)
  1388. if err != nil {
  1389. log.Error("readDir(%s) failed: %s", codePath, err.Error())
  1390. return err
  1391. }
  1392. for _, file := range files {
  1393. if file.IsDir() {
  1394. if err = uploadCodeToMinio(codePath+file.Name()+"/", jobName, parentDir+file.Name()+"/"); err != nil {
  1395. log.Error("uploadCodeToMinio(%s) failed: %s", file.Name(), err.Error())
  1396. return err
  1397. }
  1398. } else {
  1399. destObject := setting.CBCodePathPrefix + jobName + parentDir + file.Name()
  1400. sourceFile := codePath + file.Name()
  1401. err = storage.Attachments.UploadObject(destObject, sourceFile)
  1402. if err != nil {
  1403. log.Error("UploadObject(%s) failed: %s", file.Name(), err.Error())
  1404. return err
  1405. }
  1406. }
  1407. }
  1408. return nil
  1409. }
  1410. func mkModelPath(modelPath string) error {
  1411. return mkPathAndReadMeFile(modelPath, "You can put the model file into this directory and download it by the web page.")
  1412. }
  1413. func mkResultPath(resultPath string) error {
  1414. return mkPathAndReadMeFile(resultPath, "You can put the result file into this directory and download it by the web page.")
  1415. }
  1416. func mkPathAndReadMeFile(path string, text string) error {
  1417. err := os.MkdirAll(path, os.ModePerm)
  1418. if err != nil {
  1419. log.Error("MkdirAll(%s) failed:%v", path, err)
  1420. return err
  1421. }
  1422. fileName := path + "README"
  1423. f, err := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.ModePerm)
  1424. if err != nil {
  1425. log.Error("OpenFile failed", err.Error())
  1426. return err
  1427. }
  1428. defer f.Close()
  1429. _, err = f.WriteString(text)
  1430. if err != nil {
  1431. log.Error("WriteString failed", err.Error())
  1432. return err
  1433. }
  1434. return nil
  1435. }
  1436. func deleteJobStorage(jobName string, cloudbrainType int) error {
  1437. //delete local
  1438. localJobPath := setting.JobPath + jobName
  1439. err := os.RemoveAll(localJobPath)
  1440. if err != nil {
  1441. log.Error("RemoveAll(%s) failed:%v", localJobPath, err)
  1442. }
  1443. //delete oss
  1444. if cloudbrainType == models.TypeCloudBrainOne {
  1445. dirPath := setting.CBCodePathPrefix + jobName + "/"
  1446. err = storage.Attachments.DeleteDir(dirPath)
  1447. if err != nil {
  1448. log.Error("DeleteDir(%s) failed:%v", localJobPath, err)
  1449. }
  1450. } else if cloudbrainType == models.TypeCloudBrainTwo {
  1451. //dirPath := setting.CodePathPrefix + jobName + "/"
  1452. //err = storage.ObsRemoveObject(setting.Bucket, dirPath)
  1453. //if err != nil {
  1454. // log.Error("ObsRemoveObject(%s) failed:%v", localJobPath, err)
  1455. //}
  1456. log.Info("no need to delete")
  1457. } else {
  1458. log.Error("cloudbrainType(%d) error", cloudbrainType)
  1459. }
  1460. return nil
  1461. }
  1462. func SyncCloudbrainStatus() {
  1463. cloudBrains, err := models.GetCloudBrainUnStoppedJob()
  1464. if err != nil {
  1465. log.Error("GetCloudBrainUnStoppedJob failed:", err.Error())
  1466. return
  1467. }
  1468. for _, task := range cloudBrains {
  1469. if task.Type == models.TypeCloudBrainOne {
  1470. result, err := cloudbrain.GetJob(task.JobID)
  1471. if err != nil {
  1472. log.Error("GetJob(%s) failed:%v", task.JobName, err)
  1473. continue
  1474. }
  1475. if result != nil {
  1476. jobRes, _ := models.ConvertToJobResultPayload(result.Payload)
  1477. taskRoles := jobRes.TaskRoles
  1478. taskRes, _ := models.ConvertToTaskPod(taskRoles[cloudbrain.SubTaskName].(map[string]interface{}))
  1479. task.Status = taskRes.TaskStatuses[0].State
  1480. if task.Status != string(models.JobWaiting) {
  1481. models.ParseAndSetDurationFromCloudBrainOne(jobRes, task)
  1482. err = models.UpdateJob(task)
  1483. if err != nil {
  1484. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1485. }
  1486. var maxDuration int64
  1487. if task.JobType == string(models.JobTypeBenchmark) {
  1488. maxDuration = setting.BenchmarkMaxDuration
  1489. } else if task.JobType == string(models.JobTypeSnn4imagenet) || task.JobType == string(models.JobTypeBrainScore) {
  1490. maxDuration = setting.ModelBenchmarkMaxDuration
  1491. } else {
  1492. maxDuration = setting.MaxDuration
  1493. }
  1494. if task.Duration >= maxDuration && task.JobType != string(models.JobTypeTrain) {
  1495. log.Info("begin to stop job(%s), because of the duration", task.DisplayJobName)
  1496. err = cloudbrain.StopJob(task.JobID)
  1497. if err != nil {
  1498. log.Error("StopJob(%s) failed:%v", task.DisplayJobName, err)
  1499. continue
  1500. }
  1501. task.Status = string(models.JobStopped)
  1502. if task.EndTime == 0 {
  1503. task.EndTime = timeutil.TimeStampNow()
  1504. }
  1505. task.ComputeAndSetDuration()
  1506. err = models.UpdateJob(task)
  1507. if err != nil {
  1508. log.Error("UpdateJob(%s) failed:%v", task.DisplayJobName, err)
  1509. continue
  1510. }
  1511. }
  1512. }
  1513. }
  1514. } else if task.Type == models.TypeCloudBrainTwo {
  1515. if task.JobType == string(models.JobTypeDebug) {
  1516. //result, err := modelarts.GetJob(task.JobID)
  1517. result, err := modelarts.GetNotebook2(task.JobID)
  1518. if err != nil {
  1519. log.Error("GetJob(%s) failed:%v", task.JobName, err)
  1520. continue
  1521. }
  1522. if result != nil {
  1523. task.Status = result.Status
  1524. if task.StartTime == 0 && result.Lease.UpdateTime > 0 {
  1525. task.StartTime = timeutil.TimeStamp(result.Lease.UpdateTime / 1000)
  1526. }
  1527. if task.EndTime == 0 && models.IsModelArtsDebugJobTerminal(task.Status) {
  1528. task.EndTime = timeutil.TimeStampNow()
  1529. }
  1530. task.CorrectCreateUnix()
  1531. task.ComputeAndSetDuration()
  1532. err = models.UpdateJob(task)
  1533. if err != nil {
  1534. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1535. continue
  1536. }
  1537. }
  1538. } else if task.JobType == string(models.JobTypeTrain) || task.JobType == string(models.JobTypeInference) {
  1539. result, err := modelarts.GetTrainJob(task.JobID, strconv.FormatInt(task.VersionID, 10))
  1540. if err != nil {
  1541. log.Error("GetTrainJob(%s) failed:%v", task.JobName, err)
  1542. continue
  1543. }
  1544. if result != nil {
  1545. task.Status = modelarts.TransTrainJobStatus(result.IntStatus)
  1546. task.Duration = result.Duration / 1000
  1547. task.TrainJobDuration = result.TrainJobDuration
  1548. if task.StartTime == 0 && result.StartTime > 0 {
  1549. task.StartTime = timeutil.TimeStamp(result.StartTime / 1000)
  1550. }
  1551. task.TrainJobDuration = models.ConvertDurationToStr(task.Duration)
  1552. if task.EndTime == 0 && models.IsTrainJobTerminal(task.Status) && task.StartTime > 0 {
  1553. task.EndTime = task.StartTime.Add(task.Duration)
  1554. }
  1555. task.CorrectCreateUnix()
  1556. err = models.UpdateJob(task)
  1557. if err != nil {
  1558. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1559. continue
  1560. }
  1561. }
  1562. } else {
  1563. log.Error("task.JobType(%s) is error:%s", task.JobName, task.JobType)
  1564. }
  1565. } else if task.Type == models.TypeC2Net {
  1566. result, err := grampus.GetJob(task.JobID)
  1567. if err != nil {
  1568. log.Error("GetTrainJob(%s) failed:%v", task.JobName, err)
  1569. continue
  1570. }
  1571. if result != nil {
  1572. if len(result.JobInfo.Tasks[0].CenterID) == 1 && len(result.JobInfo.Tasks[0].CenterName) == 1 {
  1573. task.AiCenter = result.JobInfo.Tasks[0].CenterID[0] + "+" + result.JobInfo.Tasks[0].CenterName[0]
  1574. }
  1575. task.Status = grampus.TransTrainJobStatus(result.JobInfo.Status)
  1576. task.Duration = result.JobInfo.RunSec
  1577. task.TrainJobDuration = models.ConvertDurationToStr(task.Duration)
  1578. if task.StartTime == 0 && result.JobInfo.StartedAt > 0 {
  1579. task.StartTime = timeutil.TimeStamp(result.JobInfo.StartedAt)
  1580. }
  1581. if task.EndTime == 0 && models.IsTrainJobTerminal(task.Status) && task.StartTime > 0 {
  1582. task.EndTime = task.StartTime.Add(task.Duration)
  1583. }
  1584. task.CorrectCreateUnix()
  1585. err = models.UpdateJob(task)
  1586. if err != nil {
  1587. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1588. continue
  1589. }
  1590. }
  1591. } else {
  1592. log.Error("task.Type(%s) is error:%d", task.JobName, task.Type)
  1593. }
  1594. }
  1595. return
  1596. }
  1597. func HandleTaskWithNoDuration(ctx *context.Context) {
  1598. mode := ctx.Query("mode")
  1599. log.Info("HandleTaskWithNoDuration start")
  1600. count := 0
  1601. start := time.Now().Unix()
  1602. for {
  1603. var cloudBrains []*models.Cloudbrain
  1604. var err error
  1605. if mode == "1" {
  1606. cloudBrains, err = models.GetStoppedJobWithNoStartTimeEndTime()
  1607. } else {
  1608. cloudBrains, err = models.GetStoppedJobWithNoDurationJob()
  1609. }
  1610. if err != nil {
  1611. log.Error("HandleTaskWithNoTrainJobDuration failed:", err.Error())
  1612. break
  1613. }
  1614. if len(cloudBrains) == 0 {
  1615. log.Info("HandleTaskWithNoTrainJobDuration:no task need handle")
  1616. break
  1617. }
  1618. handleNoDurationTask(cloudBrains)
  1619. count += len(cloudBrains)
  1620. if len(cloudBrains) < 100 {
  1621. log.Info("HandleTaskWithNoTrainJobDuration:task less than 100")
  1622. break
  1623. }
  1624. if time.Now().Unix()-start > 600 {
  1625. log.Info("HandleTaskWithNoDuration : time out")
  1626. ctx.JSON(200, fmt.Sprintf("task stop for time out,count=%d", count))
  1627. return
  1628. }
  1629. }
  1630. log.Info("HandleTaskWithNoTrainJobDuration:count=%d", count)
  1631. ctx.JSON(200, fmt.Sprintf("success,count=%d", count))
  1632. }
  1633. func handleNoDurationTask(cloudBrains []*models.Cloudbrain) {
  1634. for _, task := range cloudBrains {
  1635. time.Sleep(time.Millisecond * 100)
  1636. log.Info("Handle job ,%+v", task)
  1637. if task.Type == models.TypeCloudBrainOne {
  1638. result, err := cloudbrain.GetJob(task.JobID)
  1639. if err != nil {
  1640. log.Error("GetJob(%s) failed:%v", task.JobName, err)
  1641. updateDefaultDuration(task)
  1642. continue
  1643. }
  1644. if result != nil {
  1645. if result.Msg != "success" {
  1646. updateDefaultDuration(task)
  1647. continue
  1648. }
  1649. jobRes, err := models.ConvertToJobResultPayload(result.Payload)
  1650. if err != nil || len(jobRes.TaskRoles) == 0 {
  1651. updateDefaultDuration(task)
  1652. continue
  1653. }
  1654. taskRoles := jobRes.TaskRoles
  1655. taskRes, err := models.ConvertToTaskPod(taskRoles[cloudbrain.SubTaskName].(map[string]interface{}))
  1656. if err != nil || len(taskRes.TaskStatuses) == 0 {
  1657. updateDefaultDuration(task)
  1658. continue
  1659. }
  1660. task.Status = taskRes.TaskStatuses[0].State
  1661. log.Info("task startTime = %v endTime= %v ,jobId=%d", jobRes.JobStatus.StartTime, jobRes.JobStatus.EndTime, task.ID)
  1662. if jobRes.JobStatus.CreatedTime > 0 {
  1663. task.StartTime = timeutil.TimeStamp(jobRes.JobStatus.CreatedTime / 1000)
  1664. if jobRes.JobStatus.CompletedTime > 0 {
  1665. task.EndTime = timeutil.TimeStamp(jobRes.JobStatus.CompletedTime / 1000)
  1666. } else {
  1667. task.EndTime = task.UpdatedUnix
  1668. }
  1669. } else {
  1670. task.StartTime = 0
  1671. task.EndTime = 0
  1672. }
  1673. if task.EndTime < task.StartTime {
  1674. log.Info("endTime[%v] is less than starTime[%v],jobId=%d", task.EndTime, task.StartTime, task.ID)
  1675. st := task.StartTime
  1676. task.StartTime = task.EndTime
  1677. task.EndTime = st
  1678. }
  1679. task.Duration = task.EndTime.AsTime().Unix() - task.StartTime.AsTime().Unix()
  1680. task.TrainJobDuration = models.ConvertDurationToStr(task.Duration)
  1681. err = models.UpdateJobDurationWithDeleted(task)
  1682. if err != nil {
  1683. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1684. }
  1685. }
  1686. } else if task.Type == models.TypeCloudBrainTwo {
  1687. if task.JobType == string(models.JobTypeDebug) {
  1688. //result, err := modelarts.GetJob(task.JobID)
  1689. result, err := modelarts.GetNotebook2(task.JobID)
  1690. if err != nil {
  1691. log.Error("GetJob(%s) failed:%v", task.JobName, err)
  1692. updateDefaultDuration(task)
  1693. continue
  1694. }
  1695. if result != nil {
  1696. task.Status = result.Status
  1697. startTime := result.Lease.CreateTime
  1698. duration := result.Lease.Duration / 1000
  1699. if startTime > 0 {
  1700. task.StartTime = timeutil.TimeStamp(startTime / 1000)
  1701. task.EndTime = task.StartTime.Add(duration)
  1702. }
  1703. task.CorrectCreateUnix()
  1704. task.ComputeAndSetDuration()
  1705. err = models.UpdateJobDurationWithDeleted(task)
  1706. if err != nil {
  1707. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1708. continue
  1709. }
  1710. }
  1711. } else if task.JobType == string(models.JobTypeTrain) || task.JobType == string(models.JobTypeInference) {
  1712. result, err := modelarts.GetTrainJob(task.JobID, strconv.FormatInt(task.VersionID, 10))
  1713. if err != nil {
  1714. log.Error("GetTrainJob(%s) failed:%v", task.JobName, err)
  1715. updateDefaultDuration(task)
  1716. continue
  1717. }
  1718. if result != nil {
  1719. startTime := result.StartTime / 1000
  1720. if startTime > 0 {
  1721. task.StartTime = timeutil.TimeStamp(startTime)
  1722. task.EndTime = task.StartTime.Add(result.Duration / 1000)
  1723. }
  1724. task.ComputeAndSetDuration()
  1725. err = models.UpdateJobDurationWithDeleted(task)
  1726. if err != nil {
  1727. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1728. continue
  1729. }
  1730. }
  1731. } else {
  1732. log.Error("task.JobType(%s) is error:%s", task.JobName, task.JobType)
  1733. }
  1734. } else {
  1735. log.Error("task.Type(%s) is error:%d", task.JobName, task.Type)
  1736. }
  1737. }
  1738. }
  1739. func updateDefaultDuration(task *models.Cloudbrain) {
  1740. log.Info("updateDefaultDuration: taskId=%d", task.ID)
  1741. task.StartTime = task.CreatedUnix
  1742. task.EndTime = task.UpdatedUnix
  1743. task.ComputeAndSetDuration()
  1744. err := models.UpdateJobDurationWithDeleted(task)
  1745. if err != nil {
  1746. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1747. }
  1748. }
  1749. func CloudBrainBenchmarkIndex(ctx *context.Context) {
  1750. MustEnableCloudbrain(ctx)
  1751. repo := ctx.Repo.Repository
  1752. page := ctx.QueryInt("page")
  1753. if page <= 0 {
  1754. page = 1
  1755. }
  1756. var jobTypes []string
  1757. jobTypes = append(jobTypes, string(models.JobTypeBenchmark), string(models.JobTypeBrainScore), string(models.JobTypeSnn4imagenet))
  1758. ciTasks, count, err := models.Cloudbrains(&models.CloudbrainsOptions{
  1759. ListOptions: models.ListOptions{
  1760. Page: page,
  1761. PageSize: setting.UI.IssuePagingNum,
  1762. },
  1763. RepoID: repo.ID,
  1764. Type: models.TypeCloudBrainOne,
  1765. JobTypes: jobTypes,
  1766. })
  1767. if err != nil {
  1768. ctx.ServerError("Get debugjob faild:", err)
  1769. return
  1770. }
  1771. for i, task := range ciTasks {
  1772. ciTasks[i].CanDel = cloudbrain.CanDeleteJob(ctx, &task.Cloudbrain)
  1773. ciTasks[i].Cloudbrain.ComputeResource = task.ComputeResource
  1774. if ciTasks[i].TrainJobDuration == "" {
  1775. if ciTasks[i].Duration == 0 {
  1776. var duration int64
  1777. if task.Status == string(models.JobRunning) {
  1778. duration = time.Now().Unix() - int64(task.Cloudbrain.CreatedUnix)
  1779. } else {
  1780. duration = int64(task.Cloudbrain.UpdatedUnix) - int64(task.Cloudbrain.CreatedUnix)
  1781. }
  1782. ciTasks[i].Duration = duration
  1783. }
  1784. ciTasks[i].TrainJobDuration = models.ConvertDurationToStr(ciTasks[i].Duration)
  1785. }
  1786. ciTasks[i].BenchmarkTypeName = ""
  1787. if ciTasks[i].JobType == string(models.JobTypeBenchmark) {
  1788. ciTasks[i].BenchmarkType = ctx.Tr("repo.cloudbrain.benchmark.algorithm")
  1789. } else if ciTasks[i].JobType == string(models.JobTypeSnn4imagenet) || ciTasks[i].JobType == string(models.JobTypeBrainScore) {
  1790. ciTasks[i].BenchmarkType = ctx.Tr("repo.cloudbrain.benchmark.model")
  1791. ciTasks[i].BenchmarkTypeName = ciTasks[i].JobType
  1792. if ciTasks[i].JobType == string(models.JobTypeSnn4imagenet) {
  1793. ciTasks[i].BenchmarkTypeRankLink = setting.Snn4imagenetServerHost
  1794. } else {
  1795. ciTasks[i].BenchmarkTypeRankLink = setting.BrainScoreServerHost
  1796. }
  1797. }
  1798. if task.BenchmarkTypeID > 0 {
  1799. for _, benchmarkType := range GetBenchmarkTypes(ctx).BenchmarkType {
  1800. if task.BenchmarkTypeID == benchmarkType.Id {
  1801. ciTasks[i].BenchmarkTypeRankLink = benchmarkType.RankLink
  1802. ciTasks[i].BenchmarkTypeName = benchmarkType.First
  1803. break
  1804. }
  1805. }
  1806. }
  1807. }
  1808. pager := context.NewPagination(int(count), setting.UI.IssuePagingNum, page, 5)
  1809. ctx.Data["Page"] = pager
  1810. ctx.Data["PageIsCloudBrain"] = true
  1811. ctx.Data["Tasks"] = ciTasks
  1812. ctx.Data["CanCreate"] = cloudbrain.CanCreateOrDebugJob(ctx)
  1813. ctx.Data["RepoIsEmpty"] = repo.IsEmpty
  1814. ctx.HTML(200, tplCloudBrainBenchmarkIndex)
  1815. }
  1816. func GetChildTypes(ctx *context.Context) {
  1817. benchmarkTypeID := ctx.QueryInt("benchmark_type_id")
  1818. re := make(map[string]interface{})
  1819. for {
  1820. var isExist bool
  1821. for _, benchmarkType := range GetBenchmarkTypes(ctx).BenchmarkType {
  1822. if benchmarkTypeID == benchmarkType.Id {
  1823. isExist = true
  1824. re["child_types"] = benchmarkType.Second
  1825. re["result_code"] = "0"
  1826. break
  1827. }
  1828. }
  1829. if !isExist {
  1830. re["result_code"] = "1"
  1831. log.Error("no such benchmark_type_id", ctx.Data["MsgID"])
  1832. re["errMsg"] = "system error"
  1833. break
  1834. }
  1835. break
  1836. }
  1837. ctx.JSON(200, re)
  1838. }
  1839. func CloudBrainBenchmarkNew(ctx *context.Context) {
  1840. ctx.Data["description"] = ""
  1841. ctx.Data["benchmarkTypeID"] = -1
  1842. ctx.Data["benchmark_child_types_id_hidden"] = -1
  1843. err := cloudBrainNewDataPrepare(ctx)
  1844. if err != nil {
  1845. ctx.ServerError("get new cloudbrain info failed", err)
  1846. return
  1847. }
  1848. ctx.HTML(200, tplCloudBrainBenchmarkNew)
  1849. }
  1850. func getBenchmarkAttachment(benchmarkTypeID, benchmarkChildTypeID int, ctx *context.Context) (*models.BenchmarkDataset, error) {
  1851. var childInfo *models.BenchmarkDataset
  1852. var isExist bool
  1853. for _, benchmarkType := range GetBenchmarkTypes(ctx).BenchmarkType {
  1854. if benchmarkType.Id == benchmarkTypeID {
  1855. for _, childType := range benchmarkType.Second {
  1856. if childType.Id == benchmarkChildTypeID {
  1857. childInfo = childType
  1858. isExist = true
  1859. break
  1860. }
  1861. }
  1862. break
  1863. }
  1864. }
  1865. if !isExist {
  1866. log.Error("no such benchmark_type_id&benchmark_child_type_id")
  1867. return childInfo, errors.New("no such benchmark_type_id&benchmark_child_type_id")
  1868. }
  1869. return childInfo, nil
  1870. }
  1871. func getBenchmarkGpuQueue(gpuQueue string) (string, error) {
  1872. queue := ""
  1873. if benchmarkGpuInfos == nil {
  1874. if err := json.Unmarshal([]byte(setting.BenchmarkGpuTypes), &benchmarkGpuInfos); err != nil {
  1875. log.Error("json.Unmarshal BenchmarkGpuTypes(%s) failed:%v", setting.BenchmarkGpuTypes, err)
  1876. return queue, err
  1877. }
  1878. }
  1879. var isExist bool
  1880. for _, gpuInfo := range benchmarkGpuInfos.GpuInfo {
  1881. if gpuQueue == gpuInfo.Queue {
  1882. isExist = true
  1883. queue = gpuQueue
  1884. break
  1885. }
  1886. }
  1887. if !isExist {
  1888. log.Error("no such gpuQueue, %s", gpuQueue)
  1889. return queue, errors.New("no such gpuQueue")
  1890. }
  1891. return queue, nil
  1892. }
  1893. func getBenchmarkResourceSpec(resourceSpecID int) (int, error) {
  1894. var id int
  1895. if benchmarkResourceSpecs == nil {
  1896. if err := json.Unmarshal([]byte(setting.BenchmarkResourceSpecs), &benchmarkResourceSpecs); err != nil {
  1897. log.Error("json.Unmarshal BenchmarkResourceSpecs(%s) failed:%v", setting.BenchmarkResourceSpecs, err)
  1898. return id, err
  1899. }
  1900. }
  1901. var isExist bool
  1902. for _, resourceSpec := range benchmarkResourceSpecs.ResourceSpec {
  1903. if resourceSpecID == resourceSpec.Id {
  1904. isExist = true
  1905. id = resourceSpecID
  1906. break
  1907. }
  1908. }
  1909. if !isExist {
  1910. log.Error("no such resourceSpecID, %d", resourceSpecID)
  1911. return id, errors.New("no such resourceSpec")
  1912. }
  1913. return id, nil
  1914. }
  1915. func CloudBrainBenchmarkCreate(ctx *context.Context, form auth.CreateCloudBrainForm) {
  1916. jobType := form.JobType
  1917. if jobType == string(models.JobTypeBenchmark) {
  1918. BenchMarkAlgorithmCreate(ctx, form)
  1919. } else {
  1920. ModelBenchmarkCreate(ctx, form)
  1921. }
  1922. }
  1923. func BenchMarkAlgorithmCreate(ctx *context.Context, form auth.CreateCloudBrainForm) {
  1924. ctx.Data["PageIsCloudBrain"] = true
  1925. displayJobName := form.DisplayJobName
  1926. jobName := util.ConvertDisplayJobNameToJobName(displayJobName)
  1927. image := strings.TrimSpace(form.Image)
  1928. gpuQueue := form.GpuType
  1929. command := cloudbrain.CommandBenchmark
  1930. codePath := setting.JobPath + jobName + cloudbrain.CodeMountPath
  1931. resourceSpecId := cloudbrain.BenchMarkResourceID
  1932. benchmarkTypeID := form.BenchmarkTypeID
  1933. benchmarkChildTypeID := form.BenchmarkChildTypeID
  1934. ctx.Data["description"] = form.Description
  1935. ctx.Data["benchmarkTypeID"] = benchmarkTypeID
  1936. ctx.Data["benchmark_child_types_id_hidden"] = benchmarkChildTypeID
  1937. repo := ctx.Repo.Repository
  1938. tasks, err := models.GetCloudbrainsByDisplayJobName(repo.ID, string(models.JobTypeBenchmark), displayJobName)
  1939. if err == nil {
  1940. if len(tasks) != 0 {
  1941. log.Error("the job name did already exist", ctx.Data["MsgID"])
  1942. cloudBrainNewDataPrepare(ctx)
  1943. ctx.RenderWithErr("the job name did already exist", tplCloudBrainBenchmarkNew, &form)
  1944. return
  1945. }
  1946. } else {
  1947. if !models.IsErrJobNotExist(err) {
  1948. log.Error("system error, %v", err, ctx.Data["MsgID"])
  1949. cloudBrainNewDataPrepare(ctx)
  1950. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  1951. return
  1952. }
  1953. }
  1954. if !jobNamePattern.MatchString(jobName) {
  1955. cloudBrainNewDataPrepare(ctx)
  1956. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_jobname_err"), tplCloudBrainBenchmarkNew, &form)
  1957. return
  1958. }
  1959. childInfo, err := getBenchmarkAttachment(benchmarkTypeID, benchmarkChildTypeID, ctx)
  1960. if err != nil {
  1961. log.Error("getBenchmarkAttachment failed:%v", err, ctx.Data["MsgID"])
  1962. cloudBrainNewDataPrepare(ctx)
  1963. ctx.RenderWithErr("benchmark type error", tplCloudBrainBenchmarkNew, &form)
  1964. return
  1965. }
  1966. _, err = getBenchmarkGpuQueue(gpuQueue)
  1967. if err != nil {
  1968. log.Error("getBenchmarkGpuQueue failed:%v", err, ctx.Data["MsgID"])
  1969. cloudBrainNewDataPrepare(ctx)
  1970. ctx.RenderWithErr("gpu queue error", tplCloudBrainBenchmarkNew, &form)
  1971. return
  1972. }
  1973. _, err = getBenchmarkResourceSpec(resourceSpecId)
  1974. if err != nil {
  1975. log.Error("getBenchmarkResourceSpec failed:%v", err, ctx.Data["MsgID"])
  1976. cloudBrainNewDataPrepare(ctx)
  1977. ctx.RenderWithErr("resource spec error", tplCloudBrainBenchmarkNew, &form)
  1978. return
  1979. }
  1980. count, err := models.GetBenchmarkCountByUserID(ctx.User.ID)
  1981. if err != nil {
  1982. log.Error("GetCloudbrainCountByUserID failed:%v", err, ctx.Data["MsgID"])
  1983. cloudBrainNewDataPrepare(ctx)
  1984. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  1985. return
  1986. } else {
  1987. if count >= 1 {
  1988. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  1989. cloudBrainNewDataPrepare(ctx)
  1990. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain.morethanonejob"), tplCloudBrainBenchmarkNew, &form)
  1991. return
  1992. }
  1993. }
  1994. os.RemoveAll(codePath)
  1995. if err := downloadCode(repo, codePath, cloudbrain.DefaultBranchName); err != nil {
  1996. log.Error("downloadCode failed, %v", err, ctx.Data["MsgID"])
  1997. cloudBrainNewDataPrepare(ctx)
  1998. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  1999. return
  2000. }
  2001. if _, err := os.Stat(codePath + "/train.py"); err != nil {
  2002. if os.IsNotExist(err) {
  2003. // file does not exist
  2004. log.Error("train.py does not exist, %v", err, ctx.Data["MsgID"])
  2005. cloudBrainNewDataPrepare(ctx)
  2006. ctx.RenderWithErr("train.py does not exist", tplCloudBrainBenchmarkNew, &form)
  2007. } else {
  2008. log.Error("Stat failed, %v", err, ctx.Data["MsgID"])
  2009. cloudBrainNewDataPrepare(ctx)
  2010. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  2011. }
  2012. return
  2013. } else if _, err := os.Stat(codePath + "/test.py"); err != nil {
  2014. if os.IsNotExist(err) {
  2015. // file does not exist
  2016. log.Error("test.py does not exist, %v", err, ctx.Data["MsgID"])
  2017. cloudBrainNewDataPrepare(ctx)
  2018. ctx.RenderWithErr("test.py does not exist", tplCloudBrainBenchmarkNew, &form)
  2019. } else {
  2020. log.Error("Stat failed, %v", err, ctx.Data["MsgID"])
  2021. cloudBrainNewDataPrepare(ctx)
  2022. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  2023. }
  2024. return
  2025. }
  2026. if err := uploadCodeToMinio(codePath+"/", jobName, cloudbrain.CodeMountPath+"/"); err != nil {
  2027. log.Error("uploadCodeToMinio failed, %v", err, ctx.Data["MsgID"])
  2028. cloudBrainNewDataPrepare(ctx)
  2029. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  2030. return
  2031. }
  2032. benchmarkPath := setting.JobPath + jobName + cloudbrain.BenchMarkMountPath
  2033. var gpuType string
  2034. for _, gpuInfo := range gpuInfos.GpuInfo {
  2035. if gpuInfo.Queue == gpuQueue {
  2036. gpuType = gpuInfo.Value
  2037. }
  2038. }
  2039. if err := downloadRateCode(repo, jobName, childInfo.Owner, childInfo.RepoName, benchmarkPath, form.BenchmarkCategory, gpuType, ctx.User.Name); err != nil {
  2040. log.Error("downloadRateCode failed, %v", err, ctx.Data["MsgID"])
  2041. //cloudBrainNewDataPrepare(ctx)
  2042. //ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  2043. //return
  2044. }
  2045. if err := uploadCodeToMinio(benchmarkPath+"/", jobName, cloudbrain.BenchMarkMountPath+"/"); err != nil {
  2046. log.Error("uploadCodeToMinio failed, %v", err, ctx.Data["MsgID"])
  2047. //cloudBrainNewDataPrepare(ctx)
  2048. //ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  2049. //return
  2050. }
  2051. uuid := childInfo.Attachment
  2052. datasetInfos, datasetNames, err := models.GetDatasetInfo(uuid)
  2053. if err != nil {
  2054. log.Error("GetDatasetInfo failed: %v", err, ctx.Data["MsgID"])
  2055. cloudBrainNewDataPrepare(ctx)
  2056. ctx.RenderWithErr(ctx.Tr("cloudbrain.error.dataset_select"), tplCloudBrainBenchmarkNew, &form)
  2057. return
  2058. }
  2059. req := cloudbrain.GenerateCloudBrainTaskReq{
  2060. Ctx: ctx,
  2061. DisplayJobName: displayJobName,
  2062. JobName: jobName,
  2063. Image: image,
  2064. Command: command,
  2065. Uuids: uuid,
  2066. DatasetNames: datasetNames,
  2067. DatasetInfos: datasetInfos,
  2068. CodePath: storage.GetMinioPath(jobName, cloudbrain.CodeMountPath+"/"),
  2069. ModelPath: storage.GetMinioPath(jobName, cloudbrain.ModelMountPath+"/"),
  2070. BenchmarkPath: storage.GetMinioPath(jobName, cloudbrain.BenchMarkMountPath+"/"),
  2071. Snn4ImageNetPath: storage.GetMinioPath(jobName, cloudbrain.Snn4imagenetMountPath+"/"),
  2072. BrainScorePath: storage.GetMinioPath(jobName, cloudbrain.BrainScoreMountPath+"/"),
  2073. JobType: string(models.JobTypeBenchmark),
  2074. GpuQueue: gpuQueue,
  2075. Description: form.Description,
  2076. BranchName: cloudbrain.DefaultBranchName,
  2077. BootFile: "",
  2078. Params: "",
  2079. CommitID: "",
  2080. BenchmarkTypeID: benchmarkTypeID,
  2081. BenchmarkChildTypeID: benchmarkChildTypeID,
  2082. ResourceSpecId: resourceSpecId,
  2083. ResultPath: storage.GetMinioPath(jobName, cloudbrain.ResultPath+"/"),
  2084. }
  2085. err = cloudbrain.GenerateTask(req)
  2086. if err != nil {
  2087. cloudBrainNewDataPrepare(ctx)
  2088. ctx.RenderWithErr(err.Error(), tplCloudBrainBenchmarkNew, &form)
  2089. return
  2090. }
  2091. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/cloudbrain/benchmark")
  2092. }
  2093. func ModelBenchmarkCreate(ctx *context.Context, form auth.CreateCloudBrainForm) {
  2094. ctx.Data["PageIsCloudBrain"] = true
  2095. displayJobName := form.DisplayJobName
  2096. jobName := util.ConvertDisplayJobNameToJobName(displayJobName)
  2097. image := form.Image
  2098. uuid := form.Attachment
  2099. jobType := form.JobType
  2100. gpuQueue := form.GpuType
  2101. codePath := setting.JobPath + jobName + cloudbrain.CodeMountPath
  2102. resourceSpecId := form.ResourceSpecId
  2103. branchName := cloudbrain.DefaultBranchName
  2104. repo := ctx.Repo.Repository
  2105. tpl := tplCloudBrainBenchmarkNew
  2106. command := cloudbrain.GetCloudbrainDebugCommand()
  2107. tasks, err := models.GetCloudbrainsByDisplayJobName(repo.ID, jobType, displayJobName)
  2108. if err == nil {
  2109. if len(tasks) != 0 {
  2110. log.Error("the job name did already exist", ctx.Data["MsgID"])
  2111. cloudBrainNewDataPrepare(ctx)
  2112. ctx.RenderWithErr("the job name did already exist", tpl, &form)
  2113. return
  2114. }
  2115. } else {
  2116. if !models.IsErrJobNotExist(err) {
  2117. log.Error("system error, %v", err, ctx.Data["MsgID"])
  2118. cloudBrainNewDataPrepare(ctx)
  2119. ctx.RenderWithErr("system error", tpl, &form)
  2120. return
  2121. }
  2122. }
  2123. if !jobNamePattern.MatchString(displayJobName) {
  2124. cloudBrainNewDataPrepare(ctx)
  2125. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_jobname_err"), tpl, &form)
  2126. return
  2127. }
  2128. if jobType != string(models.JobTypeSnn4imagenet) && jobType != string(models.JobTypeBrainScore) {
  2129. log.Error("jobtype error:", jobType, ctx.Data["MsgID"])
  2130. cloudBrainNewDataPrepare(ctx)
  2131. ctx.RenderWithErr("jobtype error", tpl, &form)
  2132. return
  2133. }
  2134. count, err := models.GetBenchmarkCountByUserID(ctx.User.ID)
  2135. if err != nil {
  2136. log.Error("GetCloudbrainCountByUserID failed:%v", err, ctx.Data["MsgID"])
  2137. cloudBrainNewDataPrepare(ctx)
  2138. ctx.RenderWithErr("system error", tpl, &form)
  2139. return
  2140. } else {
  2141. if count >= 1 {
  2142. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  2143. cloudBrainNewDataPrepare(ctx)
  2144. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain.morethanonejob"), tpl, &form)
  2145. return
  2146. }
  2147. }
  2148. downloadCode(repo, codePath, branchName)
  2149. uploadCodeToMinio(codePath+"/", jobName, cloudbrain.CodeMountPath+"/")
  2150. modelPath := setting.JobPath + jobName + cloudbrain.ModelMountPath + "/"
  2151. mkModelPath(modelPath)
  2152. uploadCodeToMinio(modelPath, jobName, cloudbrain.ModelMountPath+"/")
  2153. snn4imagenetPath := setting.JobPath + jobName + cloudbrain.Snn4imagenetMountPath
  2154. if setting.IsSnn4imagenetEnabled && jobType == string(models.JobTypeSnn4imagenet) {
  2155. downloadRateCode(repo, jobName, setting.Snn4imagenetOwner, setting.Snn4imagenetName, snn4imagenetPath, "", "", ctx.User.Name)
  2156. uploadCodeToMinio(snn4imagenetPath+"/", jobName, cloudbrain.Snn4imagenetMountPath+"/")
  2157. command = fmt.Sprintf(cloudbrain.Snn4imagenetCommand, displayJobName, trimSpaceNewlineInString(form.Description))
  2158. }
  2159. benchmarkChildTypeID := 0
  2160. brainScorePath := setting.JobPath + jobName + cloudbrain.BrainScoreMountPath
  2161. if setting.IsBrainScoreEnabled && jobType == string(models.JobTypeBrainScore) {
  2162. downloadRateCode(repo, jobName, setting.BrainScoreOwner, setting.BrainScoreName, brainScorePath, "", "", ctx.User.Name)
  2163. uploadCodeToMinio(brainScorePath+"/", jobName, cloudbrain.BrainScoreMountPath+"/")
  2164. benchmarkChildTypeID = form.BenchmarkChildTypeID
  2165. command = fmt.Sprintf(cloudbrain.BrainScoreCommand, getBrainRegion(benchmarkChildTypeID), displayJobName, trimSpaceNewlineInString(form.Description))
  2166. }
  2167. datasetInfos, datasetNames, err := models.GetDatasetInfo(uuid)
  2168. if err != nil {
  2169. log.Error("GetDatasetInfo failed: %v", err, ctx.Data["MsgID"])
  2170. cloudBrainNewDataPrepare(ctx)
  2171. ctx.RenderWithErr(ctx.Tr("cloudbrain.error.dataset_select"), tpl, &form)
  2172. return
  2173. }
  2174. req := cloudbrain.GenerateCloudBrainTaskReq{
  2175. Ctx: ctx,
  2176. DisplayJobName: displayJobName,
  2177. JobName: jobName,
  2178. Image: image,
  2179. Command: command,
  2180. Uuids: uuid,
  2181. DatasetNames: datasetNames,
  2182. DatasetInfos: datasetInfos,
  2183. CodePath: storage.GetMinioPath(jobName, cloudbrain.CodeMountPath+"/"),
  2184. ModelPath: storage.GetMinioPath(jobName, cloudbrain.ModelMountPath+"/"),
  2185. BenchmarkPath: storage.GetMinioPath(jobName, cloudbrain.BenchMarkMountPath+"/"),
  2186. Snn4ImageNetPath: storage.GetMinioPath(jobName, cloudbrain.Snn4imagenetMountPath+"/"),
  2187. BrainScorePath: storage.GetMinioPath(jobName, cloudbrain.BrainScoreMountPath+"/"),
  2188. JobType: jobType,
  2189. GpuQueue: gpuQueue,
  2190. Description: form.Description,
  2191. BranchName: branchName,
  2192. BootFile: form.BootFile,
  2193. Params: form.Params,
  2194. CommitID: "",
  2195. BenchmarkTypeID: 0,
  2196. BenchmarkChildTypeID: benchmarkChildTypeID,
  2197. ResourceSpecId: resourceSpecId,
  2198. ResultPath: storage.GetMinioPath(jobName, cloudbrain.ResultPath+"/"),
  2199. }
  2200. err = cloudbrain.GenerateTask(req)
  2201. if err != nil {
  2202. cloudBrainNewDataPrepare(ctx)
  2203. ctx.RenderWithErr(err.Error(), tpl, &form)
  2204. return
  2205. }
  2206. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/cloudbrain/benchmark")
  2207. }
  2208. func getBrainRegion(benchmarkChildTypeID int) string {
  2209. values := []string{"V1", "V2", "V4", "IT"}
  2210. return values[benchmarkChildTypeID]
  2211. }
  2212. func trimSpaceNewlineInString(s string) string {
  2213. re := regexp.MustCompile(`\r?\n`)
  2214. return re.ReplaceAllString(s, " ")
  2215. }
  2216. func BenchmarkDel(ctx *context.Context) {
  2217. if err := deleteCloudbrainJob(ctx); err != nil {
  2218. log.Error("deleteCloudbrainJob failed: %v", err, ctx.Data["msgID"])
  2219. ctx.ServerError(err.Error(), err)
  2220. return
  2221. }
  2222. var isAdminPage = ctx.Query("isadminpage")
  2223. var isHomePage = ctx.Query("ishomepage")
  2224. if ctx.IsUserSiteAdmin() && isAdminPage == "true" {
  2225. ctx.Redirect(setting.AppSubURL + "/admin" + "/cloudbrains")
  2226. } else if isHomePage == "true" {
  2227. ctx.Redirect(setting.AppSubURL + "/cloudbrains")
  2228. } else {
  2229. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/cloudbrain/benchmark")
  2230. }
  2231. }
  2232. func CloudBrainTrainJobNew(ctx *context.Context) {
  2233. err := cloudBrainNewDataPrepare(ctx)
  2234. if err != nil {
  2235. ctx.ServerError("get new train-job info failed", err)
  2236. return
  2237. }
  2238. ctx.HTML(http.StatusOK, tplCloudBrainTrainJobNew)
  2239. }
  2240. func InferenceCloudBrainJobNew(ctx *context.Context) {
  2241. err := cloudBrainNewDataPrepare(ctx)
  2242. if err != nil {
  2243. ctx.ServerError("get new train-job info failed", err)
  2244. return
  2245. }
  2246. ctx.HTML(http.StatusOK, tplCloudBrainInferenceJobNew)
  2247. }
  2248. func InferenceCloudBrainJobShow(ctx *context.Context) {
  2249. cloudBrainShow(ctx, tplCloudBrainInferenceJobShow, models.JobTypeInference)
  2250. }
  2251. func DownloadInferenceResultFile(ctx *context.Context) {
  2252. var jobID = ctx.Params(":jobid")
  2253. var versionName = ctx.Query("version_name")
  2254. task, err := models.GetCloudbrainByJobIDAndVersionName(jobID, versionName)
  2255. if err != nil {
  2256. log.Error("GetCloudbrainByJobID(%s) failed:%v", task.JobName, err.Error())
  2257. return
  2258. }
  2259. allFile, err := storage.GetAllObjectByBucketAndPrefixMinio(setting.Attachment.Minio.Bucket, task.ResultUrl)
  2260. returnFileName := task.DisplayJobName + ".zip"
  2261. MinioDownloadManyFile(task.ResultUrl, ctx, returnFileName, allFile)
  2262. }
  2263. func getInferenceJobCommand(form auth.CreateCloudBrainInferencForm) (string, error) {
  2264. var command string
  2265. bootFile := strings.TrimSpace(form.BootFile)
  2266. params := form.Params
  2267. if !strings.HasSuffix(bootFile, ".py") {
  2268. log.Error("bootFile(%s) format error", bootFile)
  2269. return command, errors.New("bootFile format error")
  2270. }
  2271. var parameters models.Parameters
  2272. var param string
  2273. if len(params) != 0 {
  2274. err := json.Unmarshal([]byte(params), &parameters)
  2275. if err != nil {
  2276. log.Error("Failed to Unmarshal params: %s (%v)", params, err)
  2277. return command, err
  2278. }
  2279. for _, parameter := range parameters.Parameter {
  2280. param += " --" + parameter.Label + "=" + parameter.Value
  2281. }
  2282. }
  2283. param += " --modelname" + "=" + form.CkptName
  2284. command += "python /code/" + bootFile + param + " > " + cloudbrain.ResultPath + "/" + form.DisplayJobName + "-" + cloudbrain.LogFile
  2285. return command, nil
  2286. }
  2287. func getTrainJobCommand(form auth.CreateCloudBrainForm) (string, error) {
  2288. var command string
  2289. bootFile := strings.TrimSpace(form.BootFile)
  2290. params := form.Params
  2291. if !strings.HasSuffix(bootFile, ".py") {
  2292. log.Error("bootFile(%s) format error", bootFile)
  2293. return command, errors.New("bootFile format error")
  2294. }
  2295. var parameters models.Parameters
  2296. var param string
  2297. if len(params) != 0 {
  2298. err := json.Unmarshal([]byte(params), &parameters)
  2299. if err != nil {
  2300. log.Error("Failed to Unmarshal params: %s (%v)", params, err)
  2301. return command, err
  2302. }
  2303. for _, parameter := range parameters.Parameter {
  2304. param += " --" + parameter.Label + "=" + parameter.Value
  2305. }
  2306. }
  2307. command += "python /code/" + bootFile + param + " > " + cloudbrain.ModelMountPath + "/" + form.DisplayJobName + "-" + cloudbrain.LogFile
  2308. return command, nil
  2309. }
  2310. func CloudBrainTrainJobDel(ctx *context.Context) {
  2311. var listType = ctx.Query("listType")
  2312. if err := deleteCloudbrainJob(ctx); err != nil {
  2313. log.Error("deleteCloudbrainJob failed: %v", err, ctx.Data["msgID"])
  2314. ctx.ServerError(err.Error(), err)
  2315. return
  2316. }
  2317. var isAdminPage = ctx.Query("isadminpage")
  2318. var isHomePage = ctx.Query("ishomepage")
  2319. if ctx.IsUserSiteAdmin() && isAdminPage == "true" {
  2320. ctx.Redirect(setting.AppSubURL + "/admin" + "/cloudbrains")
  2321. } else if isHomePage == "true" {
  2322. ctx.Redirect(setting.AppSubURL + "/cloudbrains")
  2323. } else {
  2324. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/train-job?listType=" + listType)
  2325. }
  2326. }
  2327. func GetBenchmarkTypes(ctx *context.Context) *models.BenchmarkTypes {
  2328. var lang = ctx.Locale.Language()
  2329. if benchmarkTypesMap[lang] == nil {
  2330. var val = i18n.Tr(lang, BENCHMARK_TYPE_CODE)
  2331. //use config
  2332. val = setting.BenchmarkTypes
  2333. var tempType *models.BenchmarkTypes
  2334. if err := json.Unmarshal([]byte(val), &tempType); err != nil {
  2335. log.Error("json.Unmarshal BenchmarkTypes(%s) failed:%v", val, err, ctx.Data["MsgID"])
  2336. return &models.BenchmarkTypes{}
  2337. }
  2338. benchmarkTypesMap[lang] = tempType
  2339. }
  2340. return benchmarkTypesMap[lang]
  2341. }