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

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