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

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