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

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