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