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

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