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 96 kB

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