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