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