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