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