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

cloudbrain.go 92 kB

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