You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

cloudbrain.go 92 kB

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