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

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