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

cloudbrain.go 94 kB

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