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

cloudbrain.go 92 kB

4 years ago
5 years ago
4 years ago
5 years ago
5 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
5 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
5 years ago
5 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
5 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
4 years ago
4 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
5 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
5 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
5 years ago
3 years ago
3 years ago
3 years ago
5 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
5 years ago
3 years ago
3 years ago
3 years ago
5 years ago
3 years ago
3 years ago
5 years ago
3 years ago
3 years ago
3 years ago
5 years ago
3 years ago
5 years ago
3 years ago
4 years ago
5 years ago
4 years ago
3 years ago
5 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
5 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
5 years ago
5 years ago
5 years ago
3 years ago
3 years ago
5 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
5 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
5 years ago
3 years ago
3 years ago
3 years ago
3 years ago
5 years ago
3 years ago
5 years ago
3 years ago
5 years ago
5 years ago
3 years ago
3 years ago
3 years ago
5 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
5 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
5 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
5 years ago
4 years ago
4 years ago
4 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
3 years ago
3 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
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
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
3 years ago
5 years ago
4 years ago
4 years ago
5 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 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
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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919
  1. package repo
  2. import (
  3. "bufio"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "net/http"
  9. "os"
  10. "regexp"
  11. "sort"
  12. "strconv"
  13. "strings"
  14. "time"
  15. "unicode/utf8"
  16. "code.gitea.io/gitea/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. if task == nil || err != nil {
  650. task, err = models.GetCloudbrainByJobID(ctx.Params(":id"))
  651. }
  652. }
  653. if task.JobType == string(models.JobTypeModelSafety) {
  654. GetAiSafetyTaskTmpl(ctx)
  655. return
  656. }
  657. if err != nil {
  658. log.Info("error:" + err.Error())
  659. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  660. return
  661. }
  662. result, err := cloudbrain.GetJob(task.JobID)
  663. if err != nil {
  664. log.Info("error:" + err.Error())
  665. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  666. return
  667. }
  668. prepareSpec4Show(ctx, task)
  669. if ctx.Written() {
  670. return
  671. }
  672. if result != nil {
  673. jobRes, _ := models.ConvertToJobResultPayload(result.Payload)
  674. taskRoles := jobRes.TaskRoles
  675. taskRes, _ := models.ConvertToTaskPod(taskRoles[cloudbrain.SubTaskName].(map[string]interface{}))
  676. ctx.Data["taskRes"] = taskRes
  677. ctx.Data["ExitDiagnostics"] = taskRes.TaskStatuses[0].ExitDiagnostics
  678. oldStatus := task.Status
  679. task.Status = taskRes.TaskStatuses[0].State
  680. task.ContainerIp = ""
  681. task.ContainerID = taskRes.TaskStatuses[0].ContainerID
  682. models.ParseAndSetDurationFromCloudBrainOne(jobRes, task)
  683. if task.DeletedAt.IsZero() { //normal record
  684. if oldStatus != task.Status {
  685. notification.NotifyChangeCloudbrainStatus(task, oldStatus)
  686. }
  687. err = models.UpdateJob(task)
  688. if err != nil {
  689. ctx.Data["error"] = err.Error()
  690. return
  691. }
  692. } else { //deleted record
  693. }
  694. ctx.Data["result"] = jobRes
  695. } else {
  696. log.Info("error:" + err.Error())
  697. return
  698. }
  699. user, err := models.GetUserByID(task.UserID)
  700. if err == nil {
  701. task.User = user
  702. }
  703. if task.BenchmarkTypeID > 0 {
  704. for _, benchmarkType := range GetBenchmarkTypes(ctx).BenchmarkType {
  705. if task.BenchmarkTypeID == benchmarkType.Id {
  706. ctx.Data["BenchmarkTypeName"] = benchmarkType.First
  707. task.BenchmarkTypeName = benchmarkType.First
  708. for _, benchmarkChildType := range benchmarkType.Second {
  709. if task.BenchmarkChildTypeID == benchmarkChildType.Id {
  710. ctx.Data["BenchmarkChildTypeName"] = benchmarkChildType.Value
  711. break
  712. }
  713. }
  714. break
  715. }
  716. }
  717. }
  718. if task.JobType == string(models.JobTypeBenchmark) {
  719. task.BenchmarkType = ctx.Tr("repo.cloudbrain.benchmark.algorithm")
  720. } else if task.JobType == string(models.JobTypeSnn4imagenet) || task.JobType == string(models.JobTypeBrainScore) {
  721. task.BenchmarkType = ctx.Tr("repo.cloudbrain.benchmark.model")
  722. task.BenchmarkTypeName = task.JobType
  723. ctx.Data["BenchmarkTypeName"] = task.JobType
  724. if task.JobType == string(models.JobTypeBrainScore) {
  725. ctx.Data["BenchmarkChildTypeName"] = getBrainRegion(task.BenchmarkChildTypeID)
  726. }
  727. }
  728. if task.TrainJobDuration == "" {
  729. if task.Duration == 0 {
  730. var duration int64
  731. if task.Status == string(models.JobWaiting) {
  732. duration = 0
  733. } else if task.Status == string(models.JobRunning) {
  734. duration = time.Now().Unix() - int64(task.CreatedUnix)
  735. } else {
  736. duration = int64(task.UpdatedUnix) - int64(task.CreatedUnix)
  737. }
  738. task.Duration = duration
  739. }
  740. task.TrainJobDuration = models.ConvertDurationToStr(task.Duration)
  741. }
  742. ctx.Data["duration"] = task.TrainJobDuration
  743. if len(task.Parameters) > 0 {
  744. var parameters models.Parameters
  745. err := json.Unmarshal([]byte(task.Parameters), &parameters)
  746. if err != nil {
  747. log.Error("Failed to Unmarshal Parameters: %s (%v)", task.Parameters, err)
  748. task.Parameters = ""
  749. } else {
  750. if len(parameters.Parameter) > 0 {
  751. paramTemp := ""
  752. for _, Parameter := range parameters.Parameter {
  753. param := Parameter.Label + " = " + Parameter.Value + "; "
  754. paramTemp = paramTemp + param
  755. }
  756. task.Parameters = paramTemp[:len(paramTemp)-2]
  757. } else {
  758. task.Parameters = ""
  759. }
  760. }
  761. }
  762. ctx.Data["datasetDownload"] = GetCloudBrainDataSetInfo(task.Uuid, task.DatasetName, false)
  763. ctx.Data["task"] = task
  764. labelName := strings.Fields(task.LabelName)
  765. ctx.Data["LabelName"] = labelName
  766. ctx.Data["jobName"] = task.JobName
  767. ctx.Data["displayJobName"] = task.DisplayJobName
  768. version_list_task := make([]*models.Cloudbrain, 0)
  769. version_list_task = append(version_list_task, task)
  770. ctx.Data["version_list_task"] = version_list_task
  771. ctx.Data["debugListType"] = debugListType
  772. ctx.Data["code_path"] = cloudbrain.CodeMountPath
  773. ctx.Data["dataset_path"] = cloudbrain.DataSetMountPath
  774. ctx.Data["model_path"] = cloudbrain.ModelMountPath
  775. ctx.Data["canDownload"] = cloudbrain.CanModifyJob(ctx, task)
  776. ctx.Data["branchName"] = task.BranchName
  777. ctx.HTML(200, tpName)
  778. }
  779. func CloudBrainDebug(ctx *context.Context) {
  780. task := ctx.Cloudbrain
  781. debugUrl := setting.DebugServerHost + "jpylab_" + task.JobID + "_" + task.SubTaskName
  782. ctx.Redirect(debugUrl)
  783. }
  784. func prepareSpec4Show(ctx *context.Context, task *models.Cloudbrain) {
  785. s, err := resource.GetCloudbrainSpec(task.ID)
  786. if err != nil {
  787. log.Info("error:" + err.Error())
  788. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  789. return
  790. }
  791. ctx.Data["Spec"] = s
  792. }
  793. func oldPrepareSpec4Show(ctx *context.Context, task *models.Cloudbrain) {
  794. hasSpec := false
  795. if task.JobType == string(models.JobTypeTrain) {
  796. if cloudbrain.TrainResourceSpecs == nil {
  797. json.Unmarshal([]byte(setting.TrainResourceSpecs), &cloudbrain.TrainResourceSpecs)
  798. }
  799. for _, tmp := range cloudbrain.TrainResourceSpecs.ResourceSpec {
  800. if tmp.Id == task.ResourceSpecId {
  801. hasSpec = true
  802. ctx.Data["GpuNum"] = tmp.GpuNum
  803. ctx.Data["CpuNum"] = tmp.CpuNum
  804. ctx.Data["MemMiB"] = tmp.MemMiB
  805. ctx.Data["ShareMemMiB"] = tmp.ShareMemMiB
  806. break
  807. }
  808. }
  809. } else if task.JobType == string(models.JobTypeInference) {
  810. if cloudbrain.InferenceResourceSpecs == nil {
  811. json.Unmarshal([]byte(setting.InferenceResourceSpecs), &cloudbrain.InferenceResourceSpecs)
  812. }
  813. for _, tmp := range cloudbrain.InferenceResourceSpecs.ResourceSpec {
  814. if tmp.Id == task.ResourceSpecId {
  815. hasSpec = true
  816. ctx.Data["GpuNum"] = tmp.GpuNum
  817. ctx.Data["CpuNum"] = tmp.CpuNum
  818. ctx.Data["MemMiB"] = tmp.MemMiB
  819. ctx.Data["ShareMemMiB"] = tmp.ShareMemMiB
  820. break
  821. }
  822. }
  823. } else {
  824. if cloudbrain.ResourceSpecs == nil {
  825. json.Unmarshal([]byte(setting.ResourceSpecs), &cloudbrain.ResourceSpecs)
  826. }
  827. for _, tmp := range cloudbrain.ResourceSpecs.ResourceSpec {
  828. if tmp.Id == task.ResourceSpecId {
  829. hasSpec = true
  830. ctx.Data["GpuNum"] = tmp.GpuNum
  831. ctx.Data["CpuNum"] = tmp.CpuNum
  832. ctx.Data["MemMiB"] = tmp.MemMiB
  833. ctx.Data["ShareMemMiB"] = tmp.ShareMemMiB
  834. break
  835. }
  836. }
  837. }
  838. if !hasSpec && cloudbrain.SpecialPools != nil {
  839. for _, specialPool := range cloudbrain.SpecialPools.Pools {
  840. if specialPool.ResourceSpec != nil {
  841. for _, spec := range specialPool.ResourceSpec {
  842. if task.ResourceSpecId == spec.Id {
  843. ctx.Data["GpuNum"] = spec.GpuNum
  844. ctx.Data["CpuNum"] = spec.CpuNum
  845. ctx.Data["MemMiB"] = spec.MemMiB
  846. ctx.Data["ShareMemMiB"] = spec.ShareMemMiB
  847. break
  848. }
  849. }
  850. }
  851. }
  852. }
  853. }
  854. func CloudBrainCommitImageShow(ctx *context.Context) {
  855. ctx.Data["PageIsCloudBrain"] = true
  856. ctx.Data["Type"] = ctx.Cloudbrain.Type
  857. ctx.HTML(200, tplCloudBrainImageSubmit)
  858. }
  859. func GetImage(ctx *context.Context) {
  860. var ID = ctx.Params(":id")
  861. id, _ := strconv.ParseInt(ID, 10, 64)
  862. image, err := models.GetImageByID(id)
  863. if err != nil {
  864. log.Error("GetImageByID failed:%v", err.Error())
  865. ctx.JSON(http.StatusNotFound, nil)
  866. }
  867. ctx.JSON(http.StatusOK, image)
  868. }
  869. func CloudBrainImageEdit(ctx *context.Context) {
  870. ctx.Data["PageIsImageEdit"] = true
  871. ctx.Data["PageFrom"] = ctx.Params(":from")
  872. var ID = ctx.Params(":id")
  873. id, err := strconv.ParseInt(ID, 10, 64)
  874. if err != nil {
  875. log.Error("GetImageByID failed:%v", err.Error())
  876. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  877. }
  878. image, err := models.GetImageByID(id)
  879. if err != nil {
  880. log.Error("GetImageByID failed:%v", err.Error())
  881. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  882. }
  883. ctx.Data["Image"] = image
  884. ctx.HTML(http.StatusOK, tplCloudBrainImageEdit)
  885. }
  886. func CloudBrainImageEditPost(ctx *context.Context, form auth.EditImageCloudBrainForm) {
  887. if utf8.RuneCountInString(form.Description) > 255 {
  888. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("dataset.description_format_err", 255)))
  889. return
  890. }
  891. validTopics, errMessage := checkTopics(form.Topics)
  892. if errMessage != "" {
  893. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr(errMessage)))
  894. return
  895. }
  896. image, err := models.GetImageByID(form.ID)
  897. if err != nil {
  898. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("repo.image_not_exist")))
  899. }
  900. image.IsPrivate = form.IsPrivate
  901. image.Description = form.Description
  902. err = models.WithTx(func(ctx models.DBContext) error {
  903. if err := models.UpdateLocalImage(image); err != nil {
  904. return err
  905. }
  906. if err := models.SaveImageTopics(image.ID, validTopics...); err != nil {
  907. return err
  908. }
  909. return nil
  910. })
  911. if err != nil {
  912. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("repo.image_not_exist")))
  913. } else {
  914. ctx.JSON(http.StatusOK, models.BaseOKMessage)
  915. }
  916. }
  917. func CloudBrainImageDelete(ctx *context.Context) {
  918. var ID = ctx.Params(":id")
  919. id, err := strconv.ParseInt(ID, 10, 64)
  920. if err != nil {
  921. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("repo.image_not_exist")))
  922. return
  923. }
  924. err = models.DeleteLocalImage(id)
  925. if err != nil {
  926. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("repo.image_delete_fail")))
  927. } else {
  928. ctx.JSON(http.StatusOK, models.BaseOKMessage)
  929. }
  930. }
  931. func CloudBrainCommitImageCheck(ctx *context.Context, form auth.CommitImageCloudBrainForm) {
  932. isExist, _ := models.IsImageExistByUser(form.Tag, ctx.User.ID)
  933. if isExist {
  934. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("repo.image_overwrite")))
  935. } else {
  936. ctx.JSON(http.StatusOK, models.BaseOKMessage)
  937. }
  938. }
  939. func CloudBrainAdminCommitImage(ctx *context.Context, form auth.CommitAdminImageCloudBrainForm) {
  940. if !NamePattern.MatchString(form.Tag) {
  941. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("dataset.title_format_err")))
  942. return
  943. }
  944. if utf8.RuneCountInString(form.Description) > 255 {
  945. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("dataset.description_format_err", 255)))
  946. return
  947. }
  948. validTopics, errMessage := checkTopics(form.Topics)
  949. if errMessage != "" {
  950. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr(errMessage)))
  951. return
  952. }
  953. err := cloudbrain.CommitAdminImage(models.CommitImageParams{
  954. CommitImageCloudBrainParams: models.CommitImageCloudBrainParams{
  955. ImageDescription: form.Description,
  956. ImageTag: form.Tag,
  957. },
  958. IsPrivate: form.IsPrivate,
  959. CloudBrainType: form.Type,
  960. Topics: validTopics,
  961. UID: ctx.User.ID,
  962. Type: models.GetRecommondType(form.IsRecommend),
  963. Place: form.Place,
  964. }, ctx.User)
  965. if err != nil {
  966. log.Error("CommitImagefailed")
  967. if models.IsErrImageTagExist(err) {
  968. ctx.JSON(200, models.BaseErrorMessage(ctx.Tr("repo.image_exist")))
  969. } else if models.IsErrorImageCommitting(err) {
  970. ctx.JSON(200, models.BaseErrorMessage(ctx.Tr("repo.image_committing")))
  971. } else {
  972. ctx.JSON(200, models.BaseErrorMessage(ctx.Tr("repo.image_commit_fail")))
  973. }
  974. return
  975. }
  976. ctx.JSON(200, models.BaseOKMessage)
  977. }
  978. func CloudBrainCommitImage(ctx *context.Context, form auth.CommitImageCloudBrainForm) {
  979. if !NamePattern.MatchString(form.Tag) {
  980. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("dataset.title_format_err")))
  981. return
  982. }
  983. if utf8.RuneCountInString(form.Description) > 255 {
  984. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("dataset.description_format_err", 255)))
  985. return
  986. }
  987. validTopics, errMessage := checkTopics(form.Topics)
  988. if errMessage != "" {
  989. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr(errMessage)))
  990. return
  991. }
  992. err := cloudbrain.CommitImage(ctx.Cloudbrain.JobID, models.CommitImageParams{
  993. CommitImageCloudBrainParams: models.CommitImageCloudBrainParams{
  994. Ip: ctx.Cloudbrain.ContainerIp,
  995. TaskContainerId: ctx.Cloudbrain.ContainerID,
  996. ImageDescription: form.Description,
  997. ImageTag: form.Tag,
  998. },
  999. IsPrivate: form.IsPrivate,
  1000. CloudBrainType: form.Type,
  1001. Topics: validTopics,
  1002. UID: ctx.User.ID,
  1003. }, ctx.User)
  1004. if err != nil {
  1005. log.Error("CommitImage(%s) failed:%v", ctx.Cloudbrain.JobName, err.Error(), ctx.Data["msgID"])
  1006. if models.IsErrImageTagExist(err) {
  1007. ctx.JSON(200, models.BaseErrorMessage(ctx.Tr("repo.image_exist")))
  1008. } else if models.IsErrorImageCommitting(err) {
  1009. ctx.JSON(200, models.BaseErrorMessage(ctx.Tr("repo.image_committing")))
  1010. } else if isOver20GError(err) {
  1011. ctx.JSON(200, models.BaseErrorMessage(ctx.Tr("repo.image_over_20g")))
  1012. } else {
  1013. ctx.JSON(200, models.BaseErrorMessage(ctx.Tr("repo.image_commit_fail")))
  1014. }
  1015. return
  1016. }
  1017. ctx.JSON(200, models.BaseOKMessage)
  1018. }
  1019. func isOver20GError(err error) bool {
  1020. return strings.Contains(err.Error(), "over max image size 20GB")
  1021. }
  1022. func checkTopics(Topics string) ([]string, string) {
  1023. var topics = make([]string, 0)
  1024. var topicsStr = strings.TrimSpace(Topics)
  1025. if len(topicsStr) > 0 {
  1026. topics = strings.Split(topicsStr, ",")
  1027. }
  1028. validTopics, invalidTopics := models.SanitizeAndValidateImageTopics(topics)
  1029. if len(validTopics) > 25 {
  1030. return nil, "repo.topic.count_prompt"
  1031. }
  1032. if len(invalidTopics) > 0 {
  1033. return nil, "repo.imagetopic.format_prompt"
  1034. }
  1035. return validTopics, ""
  1036. }
  1037. func CloudBrainStop(ctx *context.Context) {
  1038. var ID = ctx.Params(":id")
  1039. var resultCode = "0"
  1040. var errorMsg = ""
  1041. var status = ""
  1042. task := ctx.Cloudbrain
  1043. for {
  1044. if task.Status == string(models.JobStopped) || task.Status == string(models.JobFailed) || task.Status == string(models.JobSucceeded) {
  1045. log.Error("the job(%s) has been stopped", task.JobName, ctx.Data["msgID"])
  1046. resultCode = "-1"
  1047. errorMsg = "cloudbrain.Already_stopped"
  1048. resultCode = task.Status
  1049. break
  1050. }
  1051. err := cloudbrain.StopJob(task.JobID)
  1052. if err != nil {
  1053. log.Error("StopJob(%s) failed:%v", task.JobName, err, ctx.Data["msgID"])
  1054. resultCode = "-1"
  1055. errorMsg = "cloudbrain.Stopped_failed"
  1056. break
  1057. }
  1058. oldStatus := task.Status
  1059. task.Status = string(models.JobStopped)
  1060. if task.EndTime == 0 {
  1061. task.EndTime = timeutil.TimeStampNow()
  1062. }
  1063. task.ComputeAndSetDuration()
  1064. if oldStatus != task.Status {
  1065. notification.NotifyChangeCloudbrainStatus(task, oldStatus)
  1066. }
  1067. err = models.UpdateJob(task)
  1068. if err != nil {
  1069. log.Error("UpdateJob(%s) failed:%v", task.JobName, err, ctx.Data["msgID"])
  1070. resultCode = "-1"
  1071. errorMsg = "cloudbrain.Stopped_success_update_status_fail"
  1072. break
  1073. }
  1074. status = task.Status
  1075. break
  1076. }
  1077. ctx.JSON(200, map[string]interface{}{
  1078. "result_code": resultCode,
  1079. "error_msg": ctx.Tr(errorMsg),
  1080. "status": status,
  1081. "id": ID,
  1082. "StatusOK": 0,
  1083. })
  1084. }
  1085. func StopJobsByUserID(userID int64) {
  1086. cloudBrains, err := models.GetCloudbrainsNeededStopByUserID(userID)
  1087. if err != nil {
  1088. log.Warn("Failed to get cloudBrain info", err)
  1089. return
  1090. }
  1091. StopJobs(cloudBrains)
  1092. }
  1093. func StopJobsByRepoID(repoID int64) {
  1094. cloudBrains, err := models.GetCloudbrainsNeededStopByRepoID(repoID)
  1095. if err != nil {
  1096. log.Warn("Failed to get cloudBrain info", err)
  1097. return
  1098. }
  1099. StopJobs(cloudBrains)
  1100. }
  1101. func DeleteJobsByRepoID(repoID int64) {
  1102. cloudBrains, err := models.GetCloudbrainsNeededDeleteByRepoID(repoID)
  1103. if err != nil {
  1104. log.Warn("Failed to get cloudBrain info", err)
  1105. return
  1106. }
  1107. DeleteJobs(cloudBrains)
  1108. }
  1109. /**
  1110. */
  1111. func StopJobs(cloudBrains []*models.Cloudbrain) {
  1112. for _, taskInfo := range cloudBrains {
  1113. if taskInfo.Type == models.TypeCloudBrainOne {
  1114. err := retry(3, time.Second*30, func() error {
  1115. return cloudbrain.StopJob(taskInfo.JobID)
  1116. })
  1117. logErrorAndUpdateJobStatus(err, taskInfo)
  1118. } else if taskInfo.Type == models.TypeCloudBrainTwo {
  1119. if taskInfo.JobType == string(models.JobTypeTrain) {
  1120. err := retry(3, time.Second*30, func() error {
  1121. _, err := modelarts.StopTrainJob(taskInfo.JobID, strconv.FormatInt(taskInfo.VersionID, 10))
  1122. return err
  1123. })
  1124. logErrorAndUpdateJobStatus(err, taskInfo)
  1125. } else {
  1126. param := models.NotebookAction{
  1127. Action: models.ActionStop,
  1128. }
  1129. err := retry(3, time.Second*30, func() error {
  1130. _, err := modelarts.ManageNotebook(taskInfo.JobID, param)
  1131. return err
  1132. })
  1133. logErrorAndUpdateJobStatus(err, taskInfo)
  1134. }
  1135. } else if taskInfo.Type == models.TypeC2Net {
  1136. if taskInfo.JobType == string(models.JobTypeTrain) {
  1137. err := retry(3, time.Second*30, func() error {
  1138. _, err := grampus.StopJob(taskInfo.JobID)
  1139. return err
  1140. })
  1141. logErrorAndUpdateJobStatus(err, taskInfo)
  1142. }
  1143. }
  1144. }
  1145. }
  1146. func DeleteJobs(cloudBrains []*models.Cloudbrain) {
  1147. for _, taskInfo := range cloudBrains {
  1148. err := models.DeleteJob(taskInfo)
  1149. if err != nil {
  1150. log.Warn("Failed to DeleteJob:", err)
  1151. return
  1152. }
  1153. if taskInfo.Type == models.TypeCloudBrainOne {
  1154. cloudbrain.DelCloudBrainJob(taskInfo.JobName)
  1155. DeleteCloudbrainJobStorage(taskInfo.JobName, models.TypeCloudBrainOne)
  1156. }
  1157. if taskInfo.Type == models.TypeCloudBrainTwo {
  1158. if taskInfo.JobType == string(models.JobTypeTrain) || taskInfo.JobType == string(models.JobTypeInference) {
  1159. modelarts.DelTrainJob(taskInfo.JobID)
  1160. DeleteJobStorage(taskInfo.JobName)
  1161. }
  1162. if taskInfo.JobType == string(models.JobTypeDebug) {
  1163. modelarts.DelNotebook2(taskInfo.JobID)
  1164. }
  1165. }
  1166. if taskInfo.Type == models.TypeC2Net {
  1167. if taskInfo.JobType == string(models.JobTypeTrain) {
  1168. cloudbrain.DelCloudBrainJob(taskInfo.JobName)
  1169. DeleteCloudbrainJobStorage(taskInfo.JobName, models.TypeCloudBrainOne)
  1170. }
  1171. }
  1172. }
  1173. }
  1174. func retry(attempts int, sleep time.Duration, f func() error) (err error) {
  1175. for i := 0; i < attempts; i++ {
  1176. if i > 0 {
  1177. log.Warn("retrying after error:", err)
  1178. time.Sleep(sleep)
  1179. }
  1180. err = f()
  1181. if err == nil {
  1182. return nil
  1183. }
  1184. }
  1185. return fmt.Errorf("after %d attempts, last error: %s", attempts, err)
  1186. }
  1187. func logErrorAndUpdateJobStatus(err error, taskInfo *models.Cloudbrain) {
  1188. if err != nil {
  1189. log.Warn("Failed to stop cloudBrain job:"+taskInfo.JobID, err)
  1190. } else {
  1191. oldStatus := taskInfo.Status
  1192. taskInfo.Status = string(models.JobStopped)
  1193. if taskInfo.EndTime == 0 {
  1194. taskInfo.EndTime = timeutil.TimeStampNow()
  1195. }
  1196. taskInfo.ComputeAndSetDuration()
  1197. if oldStatus != taskInfo.Status {
  1198. notification.NotifyChangeCloudbrainStatus(taskInfo, oldStatus)
  1199. }
  1200. err = models.UpdateJob(taskInfo)
  1201. if err != nil {
  1202. log.Warn("UpdateJob failed", err)
  1203. }
  1204. }
  1205. }
  1206. func CloudBrainDel(ctx *context.Context) {
  1207. var listType = ctx.Query("debugListType")
  1208. if err := deleteCloudbrainJob(ctx); err != nil {
  1209. log.Error("deleteCloudbrainJob failed: %v", err, ctx.Data["msgID"])
  1210. ctx.ServerError(err.Error(), err)
  1211. return
  1212. }
  1213. var isAdminPage = ctx.Query("isadminpage")
  1214. var isHomePage = ctx.Query("ishomepage")
  1215. if ctx.IsUserSiteAdmin() && isAdminPage == "true" {
  1216. ctx.Redirect(setting.AppSubURL + "/admin" + "/cloudbrains")
  1217. } else if isHomePage == "true" {
  1218. ctx.Redirect(setting.AppSubURL + "/cloudbrains")
  1219. } else {
  1220. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/debugjob?debugListType=" + listType)
  1221. }
  1222. }
  1223. func deleteCloudbrainJob(ctx *context.Context) error {
  1224. task := ctx.Cloudbrain
  1225. if task.Status != string(models.JobStopped) && task.Status != string(models.JobFailed) && task.Status != string(models.JobSucceeded) {
  1226. log.Error("the job(%s) has not been stopped", task.JobName, ctx.Data["msgID"])
  1227. return errors.New("the job has not been stopped")
  1228. }
  1229. err := models.DeleteJob(task)
  1230. if err != nil {
  1231. log.Error("DeleteJob failed: %v", err, ctx.Data["msgID"])
  1232. return err
  1233. }
  1234. DeleteCloudbrainJobStorage(task.JobName, models.TypeCloudBrainOne)
  1235. return nil
  1236. }
  1237. func CloudBrainShowModels(ctx *context.Context) {
  1238. ctx.Data["PageIsCloudBrain"] = true
  1239. ID := ctx.Params(":id")
  1240. parentDir := ctx.Query("parentDir")
  1241. dirArray := strings.Split(parentDir, "/")
  1242. task, err := models.GetCloudbrainByID(ID)
  1243. if err != nil {
  1244. log.Error("no such job!", ctx.Data["msgID"])
  1245. ctx.ServerError("no such job:", err)
  1246. return
  1247. }
  1248. //get dirs
  1249. dirs, err := GetModelDirs(task.JobName, parentDir)
  1250. if err != nil {
  1251. log.Error("GetModelDirs failed:%v", err.Error(), ctx.Data["msgID"])
  1252. ctx.ServerError("GetModelDirs failed:", err)
  1253. return
  1254. }
  1255. var fileInfos []storage.FileInfo
  1256. err = json.Unmarshal([]byte(dirs), &fileInfos)
  1257. if err != nil {
  1258. log.Error("json.Unmarshal failed:%v", err.Error(), ctx.Data["msgID"])
  1259. ctx.ServerError("json.Unmarshal failed:", err)
  1260. return
  1261. }
  1262. for i, fileInfo := range fileInfos {
  1263. temp, _ := time.Parse("2006-01-02 15:04:05", fileInfo.ModTime)
  1264. fileInfos[i].ModTime = temp.Local().Format("2006-01-02 15:04:05")
  1265. }
  1266. sort.Slice(fileInfos, func(i, j int) bool {
  1267. return fileInfos[i].ModTime > fileInfos[j].ModTime
  1268. })
  1269. ctx.Data["Path"] = dirArray
  1270. ctx.Data["Dirs"] = fileInfos
  1271. ctx.Data["task"] = task
  1272. ctx.Data["ID"] = ID
  1273. ctx.HTML(200, tplCloudBrainShowModels)
  1274. }
  1275. func GetPublicImages(ctx *context.Context) {
  1276. uid := getUID(ctx)
  1277. opts := models.SearchImageOptions{
  1278. IncludePublicOnly: true,
  1279. UID: uid,
  1280. Keyword: ctx.Query("q"),
  1281. Topics: ctx.Query("topic"),
  1282. IncludeOfficialOnly: ctx.QueryBool("recommend"),
  1283. SearchOrderBy: "type desc, num_stars desc,id desc",
  1284. Status: models.IMAGE_STATUS_SUCCESS,
  1285. CloudbrainType: ctx.QueryInt("cloudbrainType"),
  1286. }
  1287. getImages(ctx, &opts)
  1288. }
  1289. func GetCustomImages(ctx *context.Context) {
  1290. uid := getUID(ctx)
  1291. opts := models.SearchImageOptions{
  1292. UID: uid,
  1293. IncludeOwnerOnly: true,
  1294. Keyword: ctx.Query("q"),
  1295. Topics: ctx.Query("topic"),
  1296. Status: -1,
  1297. SearchOrderBy: "id desc",
  1298. }
  1299. getImages(ctx, &opts)
  1300. }
  1301. func GetStarImages(ctx *context.Context) {
  1302. uid := getUID(ctx)
  1303. opts := models.SearchImageOptions{
  1304. UID: uid,
  1305. IncludeStarByMe: true,
  1306. Keyword: ctx.Query("q"),
  1307. Topics: ctx.Query("topic"),
  1308. Status: models.IMAGE_STATUS_SUCCESS,
  1309. SearchOrderBy: "id desc",
  1310. }
  1311. getImages(ctx, &opts)
  1312. }
  1313. func getUID(ctx *context.Context) int64 {
  1314. var uid int64 = -1
  1315. if ctx.IsSigned {
  1316. uid = ctx.User.ID
  1317. }
  1318. return uid
  1319. }
  1320. func GetAllImages(ctx *context.Context) {
  1321. uid := getUID(ctx)
  1322. opts := models.SearchImageOptions{
  1323. UID: uid,
  1324. Keyword: ctx.Query("q"),
  1325. Topics: ctx.Query("topic"),
  1326. IncludeOfficialOnly: ctx.QueryBool("recommend"),
  1327. SearchOrderBy: "id desc",
  1328. Status: -1,
  1329. }
  1330. if ctx.Query("private") != "" {
  1331. if ctx.QueryBool("private") {
  1332. opts.IncludePrivateOnly = true
  1333. } else {
  1334. opts.IncludePublicOnly = true
  1335. }
  1336. }
  1337. getImages(ctx, &opts)
  1338. }
  1339. func getImages(ctx *context.Context, opts *models.SearchImageOptions) {
  1340. page := ctx.QueryInt("page")
  1341. if page <= 0 {
  1342. page = 1
  1343. }
  1344. pageSize := ctx.QueryInt("pageSize")
  1345. if pageSize <= 0 {
  1346. pageSize = 15
  1347. }
  1348. opts.ListOptions = models.ListOptions{
  1349. Page: page,
  1350. PageSize: pageSize,
  1351. }
  1352. imageList, total, err := models.SearchImage(opts)
  1353. if err != nil {
  1354. log.Error("Can not get images:%v", err)
  1355. ctx.JSON(http.StatusOK, models.ImagesPageResult{
  1356. Count: 0,
  1357. Images: []*models.Image{},
  1358. })
  1359. } else {
  1360. ctx.JSON(http.StatusOK, models.ImagesPageResult{
  1361. Count: total,
  1362. Images: imageList,
  1363. })
  1364. }
  1365. }
  1366. func GetModelDirs(jobName string, parentDir string) (string, error) {
  1367. var req string
  1368. modelActualPath := storage.GetMinioPath(jobName, cloudbrain.ModelMountPath+"/")
  1369. if parentDir == "" {
  1370. req = "baseDir=" + modelActualPath
  1371. } else {
  1372. req = "baseDir=" + modelActualPath + "&parentDir=" + parentDir
  1373. }
  1374. return getDirs(req)
  1375. }
  1376. func GetResultDirs(jobName string, parentDir string) (string, error) {
  1377. var req string
  1378. modelActualPath := storage.GetMinioPath(jobName, cloudbrain.ResultPath+"/")
  1379. if parentDir == "" {
  1380. req = "baseDir=" + modelActualPath
  1381. } else {
  1382. req = "baseDir=" + modelActualPath + "&parentDir=" + parentDir
  1383. }
  1384. return getDirs(req)
  1385. }
  1386. func CloudBrainDownloadModel(ctx *context.Context) {
  1387. parentDir := ctx.Query("parentDir")
  1388. fileName := ctx.Query("fileName")
  1389. jobName := ctx.Query("jobName")
  1390. filePath := "jobs/" + jobName + "/model/" + parentDir
  1391. url, err := storage.Attachments.PresignedGetURL(filePath, fileName)
  1392. if err != nil {
  1393. log.Error("PresignedGetURL failed: %v", err.Error(), ctx.Data["msgID"])
  1394. ctx.ServerError("PresignedGetURL", err)
  1395. return
  1396. }
  1397. ctx.Resp.Header().Set("Cache-Control", "max-age=0")
  1398. http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusMovedPermanently)
  1399. }
  1400. func CloudBrainDownloadInferenceResult(ctx *context.Context) {
  1401. parentDir := ctx.Query("parentDir")
  1402. fileName := ctx.Query("fileName")
  1403. jobName := ctx.Query("jobName")
  1404. filePath := "jobs/" + jobName + "/result/" + parentDir
  1405. url, err := storage.Attachments.PresignedGetURL(filePath, fileName)
  1406. if err != nil {
  1407. log.Error("PresignedGetURL failed: %v", err.Error(), ctx.Data["msgID"])
  1408. ctx.ServerError("PresignedGetURL", err)
  1409. return
  1410. }
  1411. ctx.Resp.Header().Set("Cache-Control", "max-age=0")
  1412. http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusMovedPermanently)
  1413. }
  1414. func GetRate(ctx *context.Context) {
  1415. isObjectDetcionAll := ctx.QueryBool("isObjectDetcionAll")
  1416. if isObjectDetcionAll {
  1417. ctx.Redirect(setting.BenchmarkServerHost + "?username=admin")
  1418. return
  1419. }
  1420. var ID = ctx.Params(":id")
  1421. job, err := models.GetCloudbrainByID(ID)
  1422. if err != nil {
  1423. ctx.ServerError("GetCloudbrainByJobID failed", err)
  1424. return
  1425. }
  1426. if job.JobType == string(models.JobTypeBenchmark) {
  1427. log.Info("url=" + setting.BenchmarkServerHost + "?username=" + ctx.User.Name)
  1428. ctx.Redirect(setting.BenchmarkServerHost + "?username=" + ctx.User.Name)
  1429. } else if job.JobType == string(models.JobTypeSnn4imagenet) {
  1430. ctx.Redirect(setting.Snn4imagenetServerHost)
  1431. } else if job.JobType == string(models.JobTypeBrainScore) {
  1432. ctx.Redirect(setting.BrainScoreServerHost)
  1433. } else {
  1434. log.Error("JobType error:%s", job.JobType, ctx.Data["msgID"])
  1435. }
  1436. }
  1437. func downloadCode(repo *models.Repository, codePath, branchName string) error {
  1438. //add "file:///" prefix to make the depth valid
  1439. if err := git.Clone(CLONE_FILE_PREFIX+repo.RepoPath(), codePath, git.CloneRepoOptions{Branch: branchName, Depth: 1}); err != nil {
  1440. log.Error("Failed to clone repository: %s (%v)", repo.FullName(), err)
  1441. return err
  1442. }
  1443. configFile, err := os.OpenFile(codePath+"/.git/config", os.O_RDWR, 0666)
  1444. if err != nil {
  1445. log.Error("open file(%s) failed:%v", codePath+"/,git/config", err)
  1446. return err
  1447. }
  1448. defer configFile.Close()
  1449. pos := int64(0)
  1450. reader := bufio.NewReader(configFile)
  1451. for {
  1452. line, err := reader.ReadString('\n')
  1453. if err != nil {
  1454. if err == io.EOF {
  1455. log.Error("not find the remote-url")
  1456. return nil
  1457. } else {
  1458. log.Error("read error: %v", err)
  1459. return err
  1460. }
  1461. }
  1462. if strings.Contains(line, "url") && strings.Contains(line, ".git") {
  1463. originUrl := "\turl = " + repo.CloneLink().HTTPS + "\n"
  1464. if len(line) > len(originUrl) {
  1465. originUrl += strings.Repeat(" ", len(line)-len(originUrl))
  1466. }
  1467. bytes := []byte(originUrl)
  1468. _, err := configFile.WriteAt(bytes, pos)
  1469. if err != nil {
  1470. log.Error("WriteAt failed:%v", err)
  1471. return err
  1472. }
  1473. break
  1474. }
  1475. pos += int64(len(line))
  1476. }
  1477. return nil
  1478. }
  1479. func downloadRateCode(repo *models.Repository, taskName, rateOwnerName, rateRepoName, codePath, benchmarkCategory, gpuType, userName string) error {
  1480. err := os.MkdirAll(codePath, os.ModePerm)
  1481. if err != nil {
  1482. log.Error("mkdir codePath failed", err.Error())
  1483. return err
  1484. }
  1485. repoExt, err := models.GetRepositoryByOwnerAndName(rateOwnerName, rateRepoName)
  1486. if err != nil {
  1487. log.Error("GetRepositoryByOwnerAndName(%s) failed", rateRepoName, err.Error())
  1488. return err
  1489. }
  1490. if err := git.Clone(CLONE_FILE_PREFIX+repoExt.RepoPath(), codePath, git.CloneRepoOptions{Depth: 1}); err != nil {
  1491. log.Error("Failed to clone repository: %s (%v)", repoExt.FullName(), err)
  1492. return err
  1493. }
  1494. fileName := codePath + cloudbrain.TaskInfoName
  1495. f, err := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.ModePerm)
  1496. if err != nil {
  1497. log.Error("OpenFile failed", err.Error())
  1498. return err
  1499. }
  1500. defer f.Close()
  1501. data, err := json.Marshal(models.TaskInfo{
  1502. Username: userName,
  1503. TaskName: taskName,
  1504. CodeName: repo.Name,
  1505. BenchmarkCategory: strings.Split(benchmarkCategory, ","),
  1506. CodeLink: strings.TrimSuffix(repo.CloneLink().HTTPS, ".git"),
  1507. GpuType: gpuType,
  1508. })
  1509. if err != nil {
  1510. log.Error("json.Marshal failed", err.Error())
  1511. return err
  1512. }
  1513. _, err = f.Write(data)
  1514. if err != nil {
  1515. log.Error("WriteString failed", err.Error())
  1516. return err
  1517. }
  1518. return nil
  1519. }
  1520. func uploadCodeToMinio(codePath, jobName, parentDir string) error {
  1521. files, err := readDir(codePath)
  1522. if err != nil {
  1523. log.Error("readDir(%s) failed: %s", codePath, err.Error())
  1524. return err
  1525. }
  1526. for _, file := range files {
  1527. if file.IsDir() {
  1528. if err = uploadCodeToMinio(codePath+file.Name()+"/", jobName, parentDir+file.Name()+"/"); err != nil {
  1529. log.Error("uploadCodeToMinio(%s) failed: %s", file.Name(), err.Error())
  1530. return err
  1531. }
  1532. } else {
  1533. destObject := setting.CBCodePathPrefix + jobName + parentDir + file.Name()
  1534. sourceFile := codePath + file.Name()
  1535. err = storage.Attachments.UploadObject(destObject, sourceFile)
  1536. if err != nil {
  1537. log.Error("UploadObject(%s) failed: %s", file.Name(), err.Error())
  1538. return err
  1539. }
  1540. }
  1541. }
  1542. return nil
  1543. }
  1544. func mkModelPath(modelPath string) error {
  1545. return mkPathAndReadMeFile(modelPath, "You can put the files into this directory and download the files by the web page.")
  1546. }
  1547. func mkPathAndReadMeFile(path string, text string) error {
  1548. err := os.MkdirAll(path, os.ModePerm)
  1549. if err != nil {
  1550. log.Error("MkdirAll(%s) failed:%v", path, err)
  1551. return err
  1552. }
  1553. fileName := path + "README"
  1554. f, err := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.ModePerm)
  1555. if err != nil {
  1556. log.Error("OpenFile failed", err.Error())
  1557. return err
  1558. }
  1559. defer f.Close()
  1560. _, err = f.WriteString(text)
  1561. if err != nil {
  1562. log.Error("WriteString failed", err.Error())
  1563. return err
  1564. }
  1565. return nil
  1566. }
  1567. func DeleteCloudbrainJobStorage(jobName string, cloudbrainType int) error {
  1568. //delete local
  1569. localJobPath := setting.JobPath + jobName
  1570. err := os.RemoveAll(localJobPath)
  1571. if err != nil {
  1572. log.Error("RemoveAll(%s) failed:%v", localJobPath, err)
  1573. }
  1574. //delete oss
  1575. if cloudbrainType == models.TypeCloudBrainOne {
  1576. dirPath := setting.CBCodePathPrefix + jobName + "/"
  1577. err = storage.Attachments.DeleteDir(dirPath)
  1578. if err != nil {
  1579. log.Error("DeleteDir(%s) failed:%v", localJobPath, err)
  1580. }
  1581. } else if cloudbrainType == models.TypeCloudBrainTwo {
  1582. //dirPath := setting.CodePathPrefix + jobName + "/"
  1583. //err = storage.ObsRemoveObject(setting.Bucket, dirPath)
  1584. //if err != nil {
  1585. // log.Error("ObsRemoveObject(%s) failed:%v", localJobPath, err)
  1586. //}
  1587. log.Info("no need to delete")
  1588. } else {
  1589. log.Error("cloudbrainType(%d) error", cloudbrainType)
  1590. }
  1591. return nil
  1592. }
  1593. func SyncCloudbrainStatus() {
  1594. cloudBrains, err := models.GetCloudBrainUnStoppedJob()
  1595. if err != nil {
  1596. log.Error("GetCloudBrainUnStoppedJob failed:", err.Error())
  1597. return
  1598. }
  1599. for _, task := range cloudBrains {
  1600. if task.JobType == string(models.JobTypeModelSafety) {
  1601. continue
  1602. }
  1603. if task.Type == models.TypeCloudBrainOne {
  1604. result, err := cloudbrain.GetJob(task.JobID)
  1605. if err != nil {
  1606. log.Error("GetJob(%s) failed:%v", task.JobName, err)
  1607. continue
  1608. }
  1609. if result != nil {
  1610. jobRes, _ := models.ConvertToJobResultPayload(result.Payload)
  1611. taskRoles := jobRes.TaskRoles
  1612. taskRes, _ := models.ConvertToTaskPod(taskRoles[cloudbrain.SubTaskName].(map[string]interface{}))
  1613. oldStatus := task.Status
  1614. task.Status = taskRes.TaskStatuses[0].State
  1615. if task.Status != string(models.JobWaiting) {
  1616. models.ParseAndSetDurationFromCloudBrainOne(jobRes, task)
  1617. if oldStatus != task.Status {
  1618. notification.NotifyChangeCloudbrainStatus(task, oldStatus)
  1619. }
  1620. err = models.UpdateJob(task)
  1621. if err != nil {
  1622. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1623. }
  1624. var maxDuration int64
  1625. if task.JobType == string(models.JobTypeBenchmark) {
  1626. maxDuration = setting.BenchmarkMaxDuration
  1627. } else if task.JobType == string(models.JobTypeSnn4imagenet) || task.JobType == string(models.JobTypeBrainScore) {
  1628. maxDuration = setting.ModelBenchmarkMaxDuration
  1629. } else {
  1630. maxDuration = setting.MaxDuration
  1631. }
  1632. if task.Duration >= maxDuration && task.JobType != string(models.JobTypeTrain) {
  1633. log.Info("begin to stop job(%s), because of the duration", task.DisplayJobName)
  1634. err = cloudbrain.StopJob(task.JobID)
  1635. if err != nil {
  1636. log.Error("StopJob(%s) failed:%v", task.DisplayJobName, err)
  1637. continue
  1638. }
  1639. task.Status = string(models.JobStopped)
  1640. if task.EndTime == 0 {
  1641. task.EndTime = timeutil.TimeStampNow()
  1642. }
  1643. task.ComputeAndSetDuration()
  1644. if oldStatus != task.Status {
  1645. notification.NotifyChangeCloudbrainStatus(task, oldStatus)
  1646. }
  1647. err = models.UpdateJob(task)
  1648. if err != nil {
  1649. log.Error("UpdateJob(%s) failed:%v", task.DisplayJobName, err)
  1650. continue
  1651. }
  1652. }
  1653. }
  1654. }
  1655. } else if task.Type == models.TypeCloudBrainTwo {
  1656. if task.JobType == string(models.JobTypeDebug) {
  1657. err := modelarts.HandleNotebookInfo(task)
  1658. if err != nil {
  1659. log.Error("HandleNotebookInfo(%s) failed:%v", task.DisplayJobName, err)
  1660. continue
  1661. }
  1662. } else if task.JobType == string(models.JobTypeTrain) || task.JobType == string(models.JobTypeInference) {
  1663. err := modelarts.HandleTrainJobInfo(task)
  1664. if err != nil {
  1665. log.Error("HandleTrainJobInfo(%s) failed:%v", task.DisplayJobName, err)
  1666. continue
  1667. }
  1668. } else {
  1669. log.Error("task.JobType(%s) is error:%s", task.DisplayJobName, task.JobType)
  1670. }
  1671. } else if task.Type == models.TypeC2Net {
  1672. result, err := grampus.GetJob(task.JobID)
  1673. if err != nil {
  1674. log.Error("GetTrainJob(%s) failed:%v", task.DisplayJobName, err)
  1675. continue
  1676. }
  1677. if result != nil {
  1678. if len(result.JobInfo.Tasks[0].CenterID) == 1 && len(result.JobInfo.Tasks[0].CenterName) == 1 {
  1679. task.AiCenter = result.JobInfo.Tasks[0].CenterID[0] + "+" + result.JobInfo.Tasks[0].CenterName[0]
  1680. }
  1681. oldStatus := task.Status
  1682. task.Status = grampus.TransTrainJobStatus(result.JobInfo.Status)
  1683. task.Duration = result.JobInfo.RunSec
  1684. if task.Duration < 0 {
  1685. task.Duration = 0
  1686. }
  1687. task.TrainJobDuration = models.ConvertDurationToStr(task.Duration)
  1688. if task.StartTime == 0 && result.JobInfo.StartedAt > 0 {
  1689. task.StartTime = timeutil.TimeStamp(result.JobInfo.StartedAt)
  1690. }
  1691. if task.EndTime == 0 && models.IsTrainJobTerminal(task.Status) && task.StartTime > 0 {
  1692. task.EndTime = task.StartTime.Add(task.Duration)
  1693. }
  1694. task.CorrectCreateUnix()
  1695. if oldStatus != task.Status {
  1696. notification.NotifyChangeCloudbrainStatus(task, oldStatus)
  1697. }
  1698. err = models.UpdateJob(task)
  1699. if err != nil {
  1700. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1701. continue
  1702. }
  1703. }
  1704. } else {
  1705. log.Error("task.Type(%s) is error:%d", task.JobName, task.Type)
  1706. }
  1707. }
  1708. return
  1709. }
  1710. func HandleTaskWithNoDuration(ctx *context.Context) {
  1711. mode := ctx.Query("mode")
  1712. log.Info("HandleTaskWithNoDuration start")
  1713. count := 0
  1714. start := time.Now().Unix()
  1715. for {
  1716. var cloudBrains []*models.Cloudbrain
  1717. var err error
  1718. if mode == "1" {
  1719. cloudBrains, err = models.GetStoppedJobWithNoStartTimeEndTime()
  1720. } else {
  1721. cloudBrains, err = models.GetStoppedJobWithNoDurationJob()
  1722. }
  1723. if err != nil {
  1724. log.Error("HandleTaskWithNoTrainJobDuration failed:", err.Error())
  1725. break
  1726. }
  1727. if len(cloudBrains) == 0 {
  1728. log.Info("HandleTaskWithNoTrainJobDuration:no task need handle")
  1729. break
  1730. }
  1731. handleNoDurationTask(cloudBrains)
  1732. count += len(cloudBrains)
  1733. if len(cloudBrains) < 100 {
  1734. log.Info("HandleTaskWithNoTrainJobDuration:task less than 100")
  1735. break
  1736. }
  1737. if time.Now().Unix()-start > 600 {
  1738. log.Info("HandleTaskWithNoDuration : time out")
  1739. ctx.JSON(200, fmt.Sprintf("task stop for time out,count=%d", count))
  1740. return
  1741. }
  1742. }
  1743. log.Info("HandleTaskWithNoTrainJobDuration:count=%d", count)
  1744. ctx.JSON(200, fmt.Sprintf("success,count=%d", count))
  1745. }
  1746. func handleNoDurationTask(cloudBrains []*models.Cloudbrain) {
  1747. for _, task := range cloudBrains {
  1748. time.Sleep(time.Millisecond * 100)
  1749. log.Info("Handle job ,%+v", task)
  1750. if task.Type == models.TypeCloudBrainOne {
  1751. result, err := cloudbrain.GetJob(task.JobID)
  1752. if err != nil {
  1753. log.Error("GetJob(%s) failed:%v", task.JobName, err)
  1754. updateDefaultDuration(task)
  1755. continue
  1756. }
  1757. if result != nil {
  1758. if result.Msg != "success" {
  1759. updateDefaultDuration(task)
  1760. continue
  1761. }
  1762. jobRes, err := models.ConvertToJobResultPayload(result.Payload)
  1763. if err != nil || len(jobRes.TaskRoles) == 0 {
  1764. updateDefaultDuration(task)
  1765. continue
  1766. }
  1767. taskRoles := jobRes.TaskRoles
  1768. taskRes, err := models.ConvertToTaskPod(taskRoles[cloudbrain.SubTaskName].(map[string]interface{}))
  1769. if err != nil || len(taskRes.TaskStatuses) == 0 {
  1770. updateDefaultDuration(task)
  1771. continue
  1772. }
  1773. task.Status = taskRes.TaskStatuses[0].State
  1774. log.Info("task startTime = %v endTime= %v ,jobId=%d", jobRes.JobStatus.StartTime, jobRes.JobStatus.EndTime, task.ID)
  1775. if jobRes.JobStatus.CreatedTime > 0 {
  1776. task.StartTime = timeutil.TimeStamp(jobRes.JobStatus.CreatedTime / 1000)
  1777. if jobRes.JobStatus.CompletedTime > 0 {
  1778. task.EndTime = timeutil.TimeStamp(jobRes.JobStatus.CompletedTime / 1000)
  1779. } else {
  1780. task.EndTime = task.UpdatedUnix
  1781. }
  1782. } else {
  1783. task.StartTime = 0
  1784. task.EndTime = 0
  1785. }
  1786. if task.EndTime < task.StartTime {
  1787. log.Info("endTime[%v] is less than starTime[%v],jobId=%d", task.EndTime, task.StartTime, task.ID)
  1788. st := task.StartTime
  1789. task.StartTime = task.EndTime
  1790. task.EndTime = st
  1791. }
  1792. task.Duration = task.EndTime.AsTime().Unix() - task.StartTime.AsTime().Unix()
  1793. task.TrainJobDuration = models.ConvertDurationToStr(task.Duration)
  1794. err = models.UpdateJobDurationWithDeleted(task)
  1795. if err != nil {
  1796. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1797. }
  1798. }
  1799. } else if task.Type == models.TypeCloudBrainTwo {
  1800. if task.JobType == string(models.JobTypeDebug) {
  1801. //result, err := modelarts.GetJob(task.JobID)
  1802. result, err := modelarts.GetNotebook2(task.JobID)
  1803. if err != nil {
  1804. log.Error("GetJob(%s) failed:%v", task.JobName, err)
  1805. updateDefaultDuration(task)
  1806. continue
  1807. }
  1808. if result != nil {
  1809. task.Status = result.Status
  1810. startTime := result.Lease.CreateTime
  1811. duration := result.Lease.Duration / 1000
  1812. if startTime > 0 {
  1813. task.StartTime = timeutil.TimeStamp(startTime / 1000)
  1814. task.EndTime = task.StartTime.Add(duration)
  1815. }
  1816. task.CorrectCreateUnix()
  1817. task.ComputeAndSetDuration()
  1818. err = models.UpdateJobDurationWithDeleted(task)
  1819. if err != nil {
  1820. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1821. continue
  1822. }
  1823. }
  1824. } else if task.JobType == string(models.JobTypeTrain) || task.JobType == string(models.JobTypeInference) {
  1825. result, err := modelarts.GetTrainJob(task.JobID, strconv.FormatInt(task.VersionID, 10))
  1826. if err != nil {
  1827. log.Error("GetTrainJob(%s) failed:%v", task.JobName, err)
  1828. updateDefaultDuration(task)
  1829. continue
  1830. }
  1831. if result != nil {
  1832. startTime := result.StartTime / 1000
  1833. if startTime > 0 {
  1834. task.StartTime = timeutil.TimeStamp(startTime)
  1835. task.EndTime = task.StartTime.Add(result.Duration / 1000)
  1836. }
  1837. task.ComputeAndSetDuration()
  1838. err = models.UpdateJobDurationWithDeleted(task)
  1839. if err != nil {
  1840. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1841. continue
  1842. }
  1843. }
  1844. } else {
  1845. log.Error("task.JobType(%s) is error:%s", task.JobName, task.JobType)
  1846. }
  1847. } else {
  1848. log.Error("task.Type(%s) is error:%d", task.JobName, task.Type)
  1849. }
  1850. }
  1851. }
  1852. func updateDefaultDuration(task *models.Cloudbrain) {
  1853. log.Info("updateDefaultDuration: taskId=%d", task.ID)
  1854. task.StartTime = task.CreatedUnix
  1855. task.EndTime = task.UpdatedUnix
  1856. task.ComputeAndSetDuration()
  1857. err := models.UpdateJobDurationWithDeleted(task)
  1858. if err != nil {
  1859. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1860. }
  1861. }
  1862. func CloudBrainBenchmarkIndex(ctx *context.Context) {
  1863. MustEnableCloudbrain(ctx)
  1864. repo := ctx.Repo.Repository
  1865. page := ctx.QueryInt("page")
  1866. if page <= 0 {
  1867. page = 1
  1868. }
  1869. var jobTypes []string
  1870. jobTypes = append(jobTypes, string(models.JobTypeBenchmark), string(models.JobTypeBrainScore), string(models.JobTypeSnn4imagenet), string(models.JobTypeModelSafety))
  1871. ciTasks, count, err := models.Cloudbrains(&models.CloudbrainsOptions{
  1872. ListOptions: models.ListOptions{
  1873. Page: page,
  1874. PageSize: setting.UI.IssuePagingNum,
  1875. },
  1876. RepoID: repo.ID,
  1877. Type: -1,
  1878. JobTypes: jobTypes,
  1879. })
  1880. if err != nil {
  1881. ctx.ServerError("Get debugjob faild:", err)
  1882. return
  1883. }
  1884. for i, task := range ciTasks {
  1885. ciTasks[i].CanDel = cloudbrain.CanDeleteJob(ctx, &task.Cloudbrain)
  1886. ciTasks[i].Cloudbrain.ComputeResource = task.ComputeResource
  1887. if ciTasks[i].TrainJobDuration == "" {
  1888. if ciTasks[i].Duration == 0 {
  1889. var duration int64
  1890. if task.Status == string(models.JobRunning) {
  1891. duration = time.Now().Unix() - int64(task.Cloudbrain.CreatedUnix)
  1892. } else {
  1893. duration = int64(task.Cloudbrain.UpdatedUnix) - int64(task.Cloudbrain.CreatedUnix)
  1894. }
  1895. ciTasks[i].Duration = duration
  1896. }
  1897. ciTasks[i].TrainJobDuration = models.ConvertDurationToStr(ciTasks[i].Duration)
  1898. }
  1899. ciTasks[i].BenchmarkTypeName = ""
  1900. if ciTasks[i].JobType == string(models.JobTypeBenchmark) {
  1901. ciTasks[i].BenchmarkType = ctx.Tr("repo.cloudbrain.benchmark.algorithm")
  1902. } else if ciTasks[i].JobType == string(models.JobTypeSnn4imagenet) || ciTasks[i].JobType == string(models.JobTypeBrainScore) {
  1903. ciTasks[i].BenchmarkType = ctx.Tr("repo.cloudbrain.benchmark.model")
  1904. ciTasks[i].BenchmarkTypeName = ciTasks[i].JobType
  1905. if ciTasks[i].JobType == string(models.JobTypeSnn4imagenet) {
  1906. ciTasks[i].BenchmarkTypeRankLink = setting.Snn4imagenetServerHost
  1907. } else {
  1908. ciTasks[i].BenchmarkTypeRankLink = setting.BrainScoreServerHost
  1909. }
  1910. }
  1911. if task.BenchmarkTypeID > 0 {
  1912. for _, benchmarkType := range GetBenchmarkTypes(ctx).BenchmarkType {
  1913. if task.BenchmarkTypeID == benchmarkType.Id {
  1914. ciTasks[i].BenchmarkTypeRankLink = benchmarkType.RankLink
  1915. ciTasks[i].BenchmarkTypeName = benchmarkType.First
  1916. break
  1917. }
  1918. }
  1919. }
  1920. if task.JobType == string(models.JobTypeModelSafety) {
  1921. ciTasks[i].BenchmarkType = "安全评测"
  1922. ciTasks[i].BenchmarkTypeName = "Image Classification"
  1923. }
  1924. }
  1925. pager := context.NewPagination(int(count), setting.UI.IssuePagingNum, page, 5)
  1926. ctx.Data["Page"] = pager
  1927. ctx.Data["PageIsCloudBrain"] = true
  1928. ctx.Data["Tasks"] = ciTasks
  1929. ctx.Data["CanCreate"] = cloudbrain.CanCreateOrDebugJob(ctx)
  1930. ctx.Data["RepoIsEmpty"] = repo.IsEmpty
  1931. ctx.HTML(200, tplCloudBrainBenchmarkIndex)
  1932. }
  1933. func GetChildTypes(ctx *context.Context) {
  1934. benchmarkTypeID := ctx.QueryInt("benchmark_type_id")
  1935. re := make(map[string]interface{})
  1936. for {
  1937. var isExist bool
  1938. for _, benchmarkType := range GetBenchmarkTypes(ctx).BenchmarkType {
  1939. if benchmarkTypeID == benchmarkType.Id {
  1940. isExist = true
  1941. re["child_types"] = benchmarkType.Second
  1942. re["result_code"] = "0"
  1943. break
  1944. }
  1945. }
  1946. if !isExist {
  1947. re["result_code"] = "1"
  1948. log.Error("no such benchmark_type_id", ctx.Data["MsgID"])
  1949. re["errMsg"] = "system error"
  1950. break
  1951. }
  1952. break
  1953. }
  1954. ctx.JSON(200, re)
  1955. }
  1956. func CloudBrainBenchmarkNew(ctx *context.Context) {
  1957. ctx.Data["description"] = ""
  1958. ctx.Data["benchmarkTypeID"] = -1
  1959. ctx.Data["benchmark_child_types_id_hidden"] = -1
  1960. err := cloudBrainNewDataPrepare(ctx)
  1961. if err != nil {
  1962. ctx.ServerError("get new cloudbrain info failed", err)
  1963. return
  1964. }
  1965. ctx.HTML(200, tplCloudBrainBenchmarkNew)
  1966. }
  1967. func getBenchmarkAttachment(benchmarkTypeID, benchmarkChildTypeID int, ctx *context.Context) (*models.BenchmarkDataset, error) {
  1968. var childInfo *models.BenchmarkDataset
  1969. var isExist bool
  1970. for _, benchmarkType := range GetBenchmarkTypes(ctx).BenchmarkType {
  1971. if benchmarkType.Id == benchmarkTypeID {
  1972. for _, childType := range benchmarkType.Second {
  1973. if childType.Id == benchmarkChildTypeID {
  1974. childInfo = childType
  1975. isExist = true
  1976. break
  1977. }
  1978. }
  1979. break
  1980. }
  1981. }
  1982. if !isExist {
  1983. log.Error("no such benchmark_type_id&benchmark_child_type_id")
  1984. return childInfo, errors.New("no such benchmark_type_id&benchmark_child_type_id")
  1985. }
  1986. return childInfo, nil
  1987. }
  1988. func getBenchmarkGpuQueue(gpuQueue string) (string, error) {
  1989. queue := ""
  1990. if benchmarkGpuInfos == nil {
  1991. if err := json.Unmarshal([]byte(setting.BenchmarkGpuTypes), &benchmarkGpuInfos); err != nil {
  1992. log.Error("json.Unmarshal BenchmarkGpuTypes(%s) failed:%v", setting.BenchmarkGpuTypes, err)
  1993. return queue, err
  1994. }
  1995. }
  1996. var isExist bool
  1997. for _, gpuInfo := range benchmarkGpuInfos.GpuInfo {
  1998. if gpuQueue == gpuInfo.Queue {
  1999. isExist = true
  2000. queue = gpuQueue
  2001. break
  2002. }
  2003. }
  2004. if !isExist {
  2005. log.Error("no such gpuQueue, %s", gpuQueue)
  2006. return queue, errors.New("no such gpuQueue")
  2007. }
  2008. return queue, nil
  2009. }
  2010. func getBenchmarkResourceSpec(resourceSpecID int) (int, error) {
  2011. var id int
  2012. if benchmarkResourceSpecs == nil {
  2013. if err := json.Unmarshal([]byte(setting.BenchmarkResourceSpecs), &benchmarkResourceSpecs); err != nil {
  2014. log.Error("json.Unmarshal BenchmarkResourceSpecs(%s) failed:%v", setting.BenchmarkResourceSpecs, err)
  2015. return id, err
  2016. }
  2017. }
  2018. var isExist bool
  2019. for _, resourceSpec := range benchmarkResourceSpecs.ResourceSpec {
  2020. if resourceSpecID == resourceSpec.Id {
  2021. isExist = true
  2022. id = resourceSpecID
  2023. break
  2024. }
  2025. }
  2026. if !isExist {
  2027. log.Error("no such resourceSpecID, %d", resourceSpecID)
  2028. return id, errors.New("no such resourceSpec")
  2029. }
  2030. return id, nil
  2031. }
  2032. func CloudBrainBenchmarkCreate(ctx *context.Context, form auth.CreateCloudBrainForm) {
  2033. jobType := form.JobType
  2034. if jobType == string(models.JobTypeBenchmark) {
  2035. BenchMarkAlgorithmCreate(ctx, form)
  2036. } else {
  2037. ModelBenchmarkCreate(ctx, form)
  2038. }
  2039. }
  2040. func BenchMarkAlgorithmCreate(ctx *context.Context, form auth.CreateCloudBrainForm) {
  2041. ctx.Data["PageIsCloudBrain"] = true
  2042. displayJobName := form.DisplayJobName
  2043. jobName := util.ConvertDisplayJobNameToJobName(displayJobName)
  2044. image := strings.TrimSpace(form.Image)
  2045. command := cloudbrain.CommandBenchmark
  2046. codePath := setting.JobPath + jobName + cloudbrain.CodeMountPath
  2047. benchmarkTypeID := form.BenchmarkTypeID
  2048. benchmarkChildTypeID := form.BenchmarkChildTypeID
  2049. repo := ctx.Repo.Repository
  2050. ctx.Data["description"] = form.Description
  2051. ctx.Data["benchmarkTypeID"] = benchmarkTypeID
  2052. ctx.Data["benchmark_child_types_id_hidden"] = benchmarkChildTypeID
  2053. lock := redis_lock.NewDistributeLock(redis_key.CloudbrainBindingJobNameKey(fmt.Sprint(repo.ID), form.JobType, displayJobName))
  2054. isOk, err := lock.Lock(models.CloudbrainKeyDuration)
  2055. if !isOk {
  2056. log.Error("lock processed failed:%v", err, ctx.Data["MsgID"])
  2057. cloudBrainNewDataPrepare(ctx)
  2058. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_samejob_err"), tplCloudBrainBenchmarkNew, &form)
  2059. return
  2060. }
  2061. defer lock.UnLock()
  2062. tasks, err := models.GetCloudbrainsByDisplayJobName(repo.ID, string(models.JobTypeBenchmark), displayJobName)
  2063. if err == nil {
  2064. if len(tasks) != 0 {
  2065. log.Error("the job name did already exist", ctx.Data["MsgID"])
  2066. cloudBrainNewDataPrepare(ctx)
  2067. ctx.RenderWithErr("the job name did already exist", tplCloudBrainBenchmarkNew, &form)
  2068. return
  2069. }
  2070. } else {
  2071. if !models.IsErrJobNotExist(err) {
  2072. log.Error("system error, %v", err, ctx.Data["MsgID"])
  2073. cloudBrainNewDataPrepare(ctx)
  2074. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  2075. return
  2076. }
  2077. }
  2078. if !jobNamePattern.MatchString(jobName) {
  2079. cloudBrainNewDataPrepare(ctx)
  2080. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_jobname_err"), tplCloudBrainBenchmarkNew, &form)
  2081. return
  2082. }
  2083. childInfo, err := getBenchmarkAttachment(benchmarkTypeID, benchmarkChildTypeID, ctx)
  2084. if err != nil {
  2085. log.Error("getBenchmarkAttachment failed:%v", err, ctx.Data["MsgID"])
  2086. cloudBrainNewDataPrepare(ctx)
  2087. ctx.RenderWithErr("benchmark type error", tplCloudBrainBenchmarkNew, &form)
  2088. return
  2089. }
  2090. spec, err := resource.GetAndCheckSpec(ctx.User.ID, form.SpecId, models.FindSpecsOptions{
  2091. JobType: models.JobTypeBenchmark,
  2092. ComputeResource: models.GPU,
  2093. Cluster: models.OpenICluster,
  2094. AiCenterCode: models.AICenterOfCloudBrainOne})
  2095. if err != nil || spec == nil {
  2096. cloudBrainNewDataPrepare(ctx)
  2097. ctx.RenderWithErr("Resource specification not available", tplCloudBrainBenchmarkNew, &form)
  2098. return
  2099. }
  2100. if !account.IsPointBalanceEnough(ctx.User.ID, spec.UnitPrice) {
  2101. log.Error("point balance is not enough,userId=%d specId=%d", ctx.User.ID, spec.ID)
  2102. cloudBrainNewDataPrepare(ctx)
  2103. ctx.RenderWithErr(ctx.Tr("points.insufficient_points_balance"), tplCloudBrainBenchmarkNew, &form)
  2104. return
  2105. }
  2106. count, err := models.GetBenchmarkCountByUserID(ctx.User.ID)
  2107. if err != nil {
  2108. log.Error("GetCloudbrainCountByUserID failed:%v", err, ctx.Data["MsgID"])
  2109. cloudBrainNewDataPrepare(ctx)
  2110. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  2111. return
  2112. } else {
  2113. if count >= 1 {
  2114. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  2115. cloudBrainNewDataPrepare(ctx)
  2116. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain.morethanonejob"), tplCloudBrainBenchmarkNew, &form)
  2117. return
  2118. }
  2119. }
  2120. os.RemoveAll(codePath)
  2121. if err := downloadCode(repo, codePath, cloudbrain.DefaultBranchName); err != nil {
  2122. log.Error("downloadCode failed, %v", err, ctx.Data["MsgID"])
  2123. cloudBrainNewDataPrepare(ctx)
  2124. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  2125. return
  2126. }
  2127. if _, err := os.Stat(codePath + "/train.py"); err != nil {
  2128. if os.IsNotExist(err) {
  2129. // file does not exist
  2130. log.Error("train.py does not exist, %v", err, ctx.Data["MsgID"])
  2131. cloudBrainNewDataPrepare(ctx)
  2132. ctx.RenderWithErr("train.py does not exist", tplCloudBrainBenchmarkNew, &form)
  2133. } else {
  2134. log.Error("Stat failed, %v", err, ctx.Data["MsgID"])
  2135. cloudBrainNewDataPrepare(ctx)
  2136. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  2137. }
  2138. return
  2139. } else if _, err := os.Stat(codePath + "/test.py"); err != nil {
  2140. if os.IsNotExist(err) {
  2141. // file does not exist
  2142. log.Error("test.py does not exist, %v", err, ctx.Data["MsgID"])
  2143. cloudBrainNewDataPrepare(ctx)
  2144. ctx.RenderWithErr("test.py does not exist", tplCloudBrainBenchmarkNew, &form)
  2145. } else {
  2146. log.Error("Stat failed, %v", err, ctx.Data["MsgID"])
  2147. cloudBrainNewDataPrepare(ctx)
  2148. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  2149. }
  2150. return
  2151. }
  2152. if err := uploadCodeToMinio(codePath+"/", jobName, cloudbrain.CodeMountPath+"/"); err != nil {
  2153. log.Error("uploadCodeToMinio failed, %v", err, ctx.Data["MsgID"])
  2154. cloudBrainNewDataPrepare(ctx)
  2155. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  2156. return
  2157. }
  2158. benchmarkPath := setting.JobPath + jobName + cloudbrain.BenchMarkMountPath
  2159. if err := downloadRateCode(repo, jobName, childInfo.Owner, childInfo.RepoName, benchmarkPath, form.BenchmarkCategory, spec.AccCardType, ctx.User.Name); err != nil {
  2160. log.Error("downloadRateCode failed, %v", err, ctx.Data["MsgID"])
  2161. //cloudBrainNewDataPrepare(ctx)
  2162. //ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  2163. //return
  2164. }
  2165. if err := uploadCodeToMinio(benchmarkPath+"/", jobName, cloudbrain.BenchMarkMountPath+"/"); err != nil {
  2166. log.Error("uploadCodeToMinio failed, %v", err, ctx.Data["MsgID"])
  2167. //cloudBrainNewDataPrepare(ctx)
  2168. //ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  2169. //return
  2170. }
  2171. uuid := childInfo.Attachment
  2172. datasetInfos, datasetNames, err := models.GetDatasetInfo(uuid)
  2173. if err != nil {
  2174. log.Error("GetDatasetInfo failed: %v", err, ctx.Data["MsgID"])
  2175. cloudBrainNewDataPrepare(ctx)
  2176. ctx.RenderWithErr(ctx.Tr("cloudbrain.error.dataset_select"), tplCloudBrainBenchmarkNew, &form)
  2177. return
  2178. }
  2179. log.Info("Command=" + command)
  2180. log.Info("ModelPath=" + storage.GetMinioPath(jobName, cloudbrain.ModelMountPath+"/"))
  2181. req := cloudbrain.GenerateCloudBrainTaskReq{
  2182. Ctx: ctx,
  2183. DisplayJobName: displayJobName,
  2184. JobName: jobName,
  2185. Image: image,
  2186. Command: command,
  2187. Uuids: uuid,
  2188. DatasetNames: datasetNames,
  2189. DatasetInfos: datasetInfos,
  2190. CodePath: storage.GetMinioPath(jobName, cloudbrain.CodeMountPath+"/"),
  2191. ModelPath: storage.GetMinioPath(jobName, cloudbrain.ModelMountPath+"/"),
  2192. BenchmarkPath: storage.GetMinioPath(jobName, cloudbrain.BenchMarkMountPath+"/"),
  2193. Snn4ImageNetPath: storage.GetMinioPath(jobName, cloudbrain.Snn4imagenetMountPath+"/"),
  2194. BrainScorePath: storage.GetMinioPath(jobName, cloudbrain.BrainScoreMountPath+"/"),
  2195. JobType: string(models.JobTypeBenchmark),
  2196. Description: form.Description,
  2197. BranchName: cloudbrain.DefaultBranchName,
  2198. BootFile: "",
  2199. Params: "",
  2200. CommitID: "",
  2201. BenchmarkTypeID: benchmarkTypeID,
  2202. BenchmarkChildTypeID: benchmarkChildTypeID,
  2203. ResultPath: storage.GetMinioPath(jobName, cloudbrain.ResultPath+"/"),
  2204. Spec: spec,
  2205. }
  2206. err = cloudbrain.GenerateTask(req)
  2207. if err != nil {
  2208. cloudBrainNewDataPrepare(ctx)
  2209. ctx.RenderWithErr(err.Error(), tplCloudBrainBenchmarkNew, &form)
  2210. return
  2211. }
  2212. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/cloudbrain/benchmark")
  2213. }
  2214. func ModelBenchmarkCreate(ctx *context.Context, form auth.CreateCloudBrainForm) {
  2215. ctx.Data["PageIsCloudBrain"] = true
  2216. displayJobName := form.DisplayJobName
  2217. jobName := util.ConvertDisplayJobNameToJobName(displayJobName)
  2218. image := form.Image
  2219. uuid := form.Attachment
  2220. jobType := form.JobType
  2221. codePath := setting.JobPath + jobName + cloudbrain.CodeMountPath
  2222. branchName := cloudbrain.DefaultBranchName
  2223. repo := ctx.Repo.Repository
  2224. tpl := tplCloudBrainBenchmarkNew
  2225. command := cloudbrain.GetCloudbrainDebugCommand()
  2226. lock := redis_lock.NewDistributeLock(redis_key.CloudbrainBindingJobNameKey(fmt.Sprint(repo.ID), jobType, displayJobName))
  2227. isOk, err := lock.Lock(models.CloudbrainKeyDuration)
  2228. if !isOk {
  2229. log.Error("lock processed failed:%v", err, ctx.Data["MsgID"])
  2230. cloudBrainNewDataPrepare(ctx)
  2231. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_samejob_err"), tpl, &form)
  2232. return
  2233. }
  2234. defer lock.UnLock()
  2235. tasks, err := models.GetCloudbrainsByDisplayJobName(repo.ID, jobType, displayJobName)
  2236. if err == nil {
  2237. if len(tasks) != 0 {
  2238. log.Error("the job name did already exist", ctx.Data["MsgID"])
  2239. cloudBrainNewDataPrepare(ctx)
  2240. ctx.RenderWithErr("the job name did already exist", tpl, &form)
  2241. return
  2242. }
  2243. } else {
  2244. if !models.IsErrJobNotExist(err) {
  2245. log.Error("system error, %v", err, ctx.Data["MsgID"])
  2246. cloudBrainNewDataPrepare(ctx)
  2247. ctx.RenderWithErr("system error", tpl, &form)
  2248. return
  2249. }
  2250. }
  2251. if !jobNamePattern.MatchString(displayJobName) {
  2252. cloudBrainNewDataPrepare(ctx)
  2253. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_jobname_err"), tpl, &form)
  2254. return
  2255. }
  2256. if jobType != string(models.JobTypeSnn4imagenet) && jobType != string(models.JobTypeBrainScore) {
  2257. log.Error("jobtype error:", jobType, ctx.Data["MsgID"])
  2258. cloudBrainNewDataPrepare(ctx)
  2259. ctx.RenderWithErr("jobtype error", tpl, &form)
  2260. return
  2261. }
  2262. count, err := models.GetBenchmarkCountByUserID(ctx.User.ID)
  2263. if err != nil {
  2264. log.Error("GetCloudbrainCountByUserID failed:%v", err, ctx.Data["MsgID"])
  2265. cloudBrainNewDataPrepare(ctx)
  2266. ctx.RenderWithErr("system error", tpl, &form)
  2267. return
  2268. } else {
  2269. if count >= 1 {
  2270. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  2271. cloudBrainNewDataPrepare(ctx)
  2272. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain.morethanonejob"), tpl, &form)
  2273. return
  2274. }
  2275. }
  2276. downloadCode(repo, codePath, branchName)
  2277. uploadCodeToMinio(codePath+"/", jobName, cloudbrain.CodeMountPath+"/")
  2278. modelPath := setting.JobPath + jobName + cloudbrain.ModelMountPath + "/"
  2279. mkModelPath(modelPath)
  2280. uploadCodeToMinio(modelPath, jobName, cloudbrain.ModelMountPath+"/")
  2281. snn4imagenetPath := setting.JobPath + jobName + cloudbrain.Snn4imagenetMountPath
  2282. if setting.IsSnn4imagenetEnabled && jobType == string(models.JobTypeSnn4imagenet) {
  2283. downloadRateCode(repo, jobName, setting.Snn4imagenetOwner, setting.Snn4imagenetName, snn4imagenetPath, "", "", ctx.User.Name)
  2284. uploadCodeToMinio(snn4imagenetPath+"/", jobName, cloudbrain.Snn4imagenetMountPath+"/")
  2285. command = fmt.Sprintf(cloudbrain.Snn4imagenetCommand, displayJobName, trimSpaceNewlineInString(form.Description))
  2286. }
  2287. benchmarkChildTypeID := 0
  2288. brainScorePath := setting.JobPath + jobName + cloudbrain.BrainScoreMountPath
  2289. if setting.IsBrainScoreEnabled && jobType == string(models.JobTypeBrainScore) {
  2290. downloadRateCode(repo, jobName, setting.BrainScoreOwner, setting.BrainScoreName, brainScorePath, "", "", ctx.User.Name)
  2291. uploadCodeToMinio(brainScorePath+"/", jobName, cloudbrain.BrainScoreMountPath+"/")
  2292. benchmarkChildTypeID = form.BenchmarkChildTypeID
  2293. command = fmt.Sprintf(cloudbrain.BrainScoreCommand, getBrainRegion(benchmarkChildTypeID), displayJobName, trimSpaceNewlineInString(form.Description))
  2294. }
  2295. datasetInfos, datasetNames, err := models.GetDatasetInfo(uuid)
  2296. if err != nil {
  2297. log.Error("GetDatasetInfo failed: %v", err, ctx.Data["MsgID"])
  2298. cloudBrainNewDataPrepare(ctx)
  2299. ctx.RenderWithErr(ctx.Tr("cloudbrain.error.dataset_select"), tpl, &form)
  2300. return
  2301. }
  2302. spec, err := resource.GetAndCheckSpec(ctx.User.ID, form.SpecId, models.FindSpecsOptions{
  2303. JobType: models.JobTypeBenchmark,
  2304. ComputeResource: models.GPU,
  2305. Cluster: models.OpenICluster,
  2306. AiCenterCode: models.AICenterOfCloudBrainOne})
  2307. if err != nil || spec == nil {
  2308. cloudBrainNewDataPrepare(ctx)
  2309. ctx.RenderWithErr("Resource specification not available", tpl, &form)
  2310. return
  2311. }
  2312. if !account.IsPointBalanceEnough(ctx.User.ID, spec.UnitPrice) {
  2313. log.Error("point balance is not enough,userId=%d specId=%d", ctx.User.ID, spec.ID)
  2314. cloudBrainNewDataPrepare(ctx)
  2315. ctx.RenderWithErr(ctx.Tr("points.insufficient_points_balance"), tpl, &form)
  2316. return
  2317. }
  2318. log.Info("Command=" + command)
  2319. log.Info("ModelPath=" + storage.GetMinioPath(jobName, cloudbrain.ModelMountPath+"/"))
  2320. req := cloudbrain.GenerateCloudBrainTaskReq{
  2321. Ctx: ctx,
  2322. DisplayJobName: displayJobName,
  2323. JobName: jobName,
  2324. Image: image,
  2325. Command: command,
  2326. Uuids: uuid,
  2327. DatasetNames: datasetNames,
  2328. DatasetInfos: datasetInfos,
  2329. CodePath: storage.GetMinioPath(jobName, cloudbrain.CodeMountPath+"/"),
  2330. ModelPath: storage.GetMinioPath(jobName, cloudbrain.ModelMountPath+"/"),
  2331. BenchmarkPath: storage.GetMinioPath(jobName, cloudbrain.BenchMarkMountPath+"/"),
  2332. Snn4ImageNetPath: storage.GetMinioPath(jobName, cloudbrain.Snn4imagenetMountPath+"/"),
  2333. BrainScorePath: storage.GetMinioPath(jobName, cloudbrain.BrainScoreMountPath+"/"),
  2334. JobType: jobType,
  2335. Description: form.Description,
  2336. BranchName: branchName,
  2337. BootFile: form.BootFile,
  2338. Params: form.Params,
  2339. CommitID: "",
  2340. BenchmarkTypeID: 0,
  2341. BenchmarkChildTypeID: benchmarkChildTypeID,
  2342. ResultPath: storage.GetMinioPath(jobName, cloudbrain.ResultPath+"/"),
  2343. Spec: spec,
  2344. }
  2345. err = cloudbrain.GenerateTask(req)
  2346. if err != nil {
  2347. cloudBrainNewDataPrepare(ctx)
  2348. ctx.RenderWithErr(err.Error(), tpl, &form)
  2349. return
  2350. }
  2351. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/cloudbrain/benchmark")
  2352. }
  2353. func getBrainRegion(benchmarkChildTypeID int) string {
  2354. values := []string{"V1", "V2", "V4", "IT"}
  2355. return values[benchmarkChildTypeID]
  2356. }
  2357. func trimSpaceNewlineInString(s string) string {
  2358. re := regexp.MustCompile(`\r?\n`)
  2359. return re.ReplaceAllString(s, " ")
  2360. }
  2361. func BenchmarkDel(ctx *context.Context) {
  2362. if err := deleteCloudbrainJob(ctx); err != nil {
  2363. log.Error("deleteCloudbrainJob failed: %v", err, ctx.Data["msgID"])
  2364. ctx.ServerError(err.Error(), err)
  2365. return
  2366. }
  2367. var isAdminPage = ctx.Query("isadminpage")
  2368. var isHomePage = ctx.Query("ishomepage")
  2369. if ctx.IsUserSiteAdmin() && isAdminPage == "true" {
  2370. ctx.Redirect(setting.AppSubURL + "/admin" + "/cloudbrains")
  2371. } else if isHomePage == "true" {
  2372. ctx.Redirect(setting.AppSubURL + "/cloudbrains")
  2373. } else {
  2374. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/cloudbrain/benchmark")
  2375. }
  2376. }
  2377. func CloudBrainTrainJobNew(ctx *context.Context) {
  2378. ctx.Data["IsCreate"] = true
  2379. cloudBrainTrainJobCreate(ctx)
  2380. }
  2381. func CloudBrainTrainJobVersionNew(ctx *context.Context) {
  2382. ctx.Data["IsCreate"] = false
  2383. cloudBrainTrainJobCreate(ctx)
  2384. }
  2385. func cloudBrainTrainJobCreate(ctx *context.Context) {
  2386. err := cloudBrainNewDataPrepare(ctx)
  2387. if err != nil {
  2388. ctx.ServerError("get new train-job info failed", err)
  2389. return
  2390. }
  2391. ctx.HTML(http.StatusOK, tplCloudBrainTrainJobNew)
  2392. }
  2393. func InferenceCloudBrainJobNew(ctx *context.Context) {
  2394. err := cloudBrainNewDataPrepare(ctx)
  2395. if err != nil {
  2396. ctx.ServerError("get new train-job info failed", err)
  2397. return
  2398. }
  2399. ctx.HTML(http.StatusOK, tplCloudBrainInferenceJobNew)
  2400. }
  2401. func InferenceCloudBrainJobShow(ctx *context.Context) {
  2402. cloudBrainShow(ctx, tplCloudBrainInferenceJobShow, models.JobTypeInference)
  2403. }
  2404. func DownloadInferenceResultFile(ctx *context.Context) {
  2405. var jobID = ctx.Params(":jobid")
  2406. var versionName = ctx.Query("version_name")
  2407. task, err := models.GetCloudbrainByJobIDAndVersionName(jobID, versionName)
  2408. if err != nil {
  2409. log.Error("GetCloudbrainByJobID(%s) failed:%v", task.JobName, err.Error())
  2410. return
  2411. }
  2412. allFile, err := storage.GetAllObjectByBucketAndPrefixMinio(setting.Attachment.Minio.Bucket, task.ResultUrl)
  2413. returnFileName := task.DisplayJobName + ".zip"
  2414. MinioDownloadManyFile(task.ResultUrl, ctx, returnFileName, allFile)
  2415. }
  2416. func getInferenceJobCommand(form auth.CreateCloudBrainInferencForm) (string, error) {
  2417. var command string
  2418. bootFile := strings.TrimSpace(form.BootFile)
  2419. params := form.Params
  2420. if !strings.HasSuffix(bootFile, ".py") {
  2421. log.Error("bootFile(%s) format error", bootFile)
  2422. return command, errors.New("bootFile format error")
  2423. }
  2424. var parameters models.Parameters
  2425. var param string
  2426. if len(params) != 0 {
  2427. err := json.Unmarshal([]byte(params), &parameters)
  2428. if err != nil {
  2429. log.Error("Failed to Unmarshal params: %s (%v)", params, err)
  2430. return command, err
  2431. }
  2432. for _, parameter := range parameters.Parameter {
  2433. param += " --" + parameter.Label + "=" + parameter.Value
  2434. }
  2435. }
  2436. param += " --modelname" + "=" + form.CkptName
  2437. command += "python /code/" + bootFile + param + " > " + cloudbrain.ResultPath + "/" + form.DisplayJobName + "-" + cloudbrain.LogFile
  2438. return command, nil
  2439. }
  2440. func getTrainJobCommand(form auth.CreateCloudBrainForm) (string, error) {
  2441. var command string
  2442. bootFile := strings.TrimSpace(form.BootFile)
  2443. params := form.Params
  2444. if !strings.HasSuffix(bootFile, ".py") {
  2445. log.Error("bootFile(%s) format error", bootFile)
  2446. return command, errors.New("bootFile format error")
  2447. }
  2448. var parameters models.Parameters
  2449. var param string
  2450. if len(params) != 0 {
  2451. err := json.Unmarshal([]byte(params), &parameters)
  2452. if err != nil {
  2453. log.Error("Failed to Unmarshal params: %s (%v)", params, err)
  2454. return command, err
  2455. }
  2456. for _, parameter := range parameters.Parameter {
  2457. param += " --" + parameter.Label + "=" + parameter.Value
  2458. }
  2459. }
  2460. if form.CkptName != "" {
  2461. param += " --ckpt_url" + "=" + "/pretrainmodel/" + form.CkptName
  2462. }
  2463. command += "python /code/" + bootFile + param + " > " + cloudbrain.ModelMountPath + "/" + form.DisplayJobName + "-" + cloudbrain.LogFile
  2464. return command, nil
  2465. }
  2466. func CloudBrainTrainJobDel(ctx *context.Context) {
  2467. var listType = ctx.Query("listType")
  2468. if err := deleteCloudbrainJob(ctx); err != nil {
  2469. log.Error("deleteCloudbrainJob failed: %v", err, ctx.Data["msgID"])
  2470. ctx.ServerError(err.Error(), err)
  2471. return
  2472. }
  2473. var isAdminPage = ctx.Query("isadminpage")
  2474. var isHomePage = ctx.Query("ishomepage")
  2475. if ctx.IsUserSiteAdmin() && isAdminPage == "true" {
  2476. ctx.Redirect(setting.AppSubURL + "/admin" + "/cloudbrains")
  2477. } else if isHomePage == "true" {
  2478. ctx.Redirect(setting.AppSubURL + "/cloudbrains")
  2479. } else {
  2480. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/train-job?listType=" + listType)
  2481. }
  2482. }
  2483. func GetBenchmarkTypes(ctx *context.Context) *models.BenchmarkTypes {
  2484. var lang = ctx.Locale.Language()
  2485. if benchmarkTypesMap[lang] == nil {
  2486. var val = i18n.Tr(lang, BENCHMARK_TYPE_CODE)
  2487. //use config
  2488. val = setting.BenchmarkTypes
  2489. var tempType *models.BenchmarkTypes
  2490. if err := json.Unmarshal([]byte(val), &tempType); err != nil {
  2491. log.Error("json.Unmarshal BenchmarkTypes(%s) failed:%v", val, err, ctx.Data["MsgID"])
  2492. return &models.BenchmarkTypes{}
  2493. }
  2494. benchmarkTypesMap[lang] = tempType
  2495. }
  2496. return benchmarkTypesMap[lang]
  2497. }
  2498. func GetCloudbrainAiCenter(task models.Cloudbrain, ctx *context.Context) string {
  2499. if task.Spec != nil {
  2500. return task.Spec.AiCenterName
  2501. } else {
  2502. return ""
  2503. }
  2504. }
  2505. func getCutStringAiCenterByAiCenter(aiCenter string) string {
  2506. if aiCenter == "" {
  2507. return ""
  2508. }
  2509. index := strings.LastIndex(aiCenter, "+")
  2510. return aiCenter[index+1:]
  2511. }
  2512. func GetCloudbrainCluster(task models.Cloudbrain, ctx *context.Context) string {
  2513. if task.Type == models.TypeCloudBrainOne || task.Type == models.TypeCloudBrainTwo || task.Type == models.TypeCDCenter {
  2514. return ctx.Tr("cloudbrain.resource_cluster_openi")
  2515. } else if task.Type == models.TypeC2Net {
  2516. return ctx.Tr("cloudbrain.resource_cluster_c2net")
  2517. }
  2518. return ""
  2519. }
  2520. func GetCloudbrainCardDuration(task models.Cloudbrain) string {
  2521. cardNum := int(0)
  2522. spec, err := resource.GetCloudbrainSpec(task.ID)
  2523. if err != nil {
  2524. log.Info("error:" + err.Error())
  2525. return ""
  2526. }
  2527. if spec != nil {
  2528. cardNum = spec.AccCardsNum
  2529. } else {
  2530. cardNum = 1
  2531. }
  2532. var workServerNumber int64
  2533. if task.WorkServerNumber >= 1 {
  2534. workServerNumber = int64(task.WorkServerNumber)
  2535. } else {
  2536. workServerNumber = 1
  2537. }
  2538. cardDuration := models.ConvertDurationToStr(workServerNumber * int64(cardNum) * task.Duration)
  2539. return cardDuration
  2540. }
  2541. func GetCloudbrainWaitTime(task models.Cloudbrain) string {
  2542. var waitTime string
  2543. if task.Status == string(models.JobWaiting) {
  2544. waitTimeInt := time.Now().Unix() - task.CreatedUnix.AsTime().Unix()
  2545. waitTime = models.ConvertDurationToStr(waitTimeInt)
  2546. if waitTimeInt < 0 {
  2547. waitTime = "00:00:00"
  2548. }
  2549. } else if task.Status == string(models.JobStopped) && task.StartTime.AsTime().Unix() == 0 {
  2550. waitTimeInt := task.EndTime.AsTime().Unix() - task.CreatedUnix.AsTime().Unix()
  2551. waitTime = models.ConvertDurationToStr(waitTimeInt)
  2552. if waitTimeInt < 0 {
  2553. waitTime = "00:00:00"
  2554. }
  2555. } else {
  2556. waitTimeInt := task.StartTime.AsTime().Unix() - task.CreatedUnix.AsTime().Unix()
  2557. waitTime = models.ConvertDurationToStr(waitTimeInt)
  2558. if waitTimeInt < 0 {
  2559. waitTime = "00:00:00"
  2560. }
  2561. }
  2562. return waitTime
  2563. }
  2564. func GetCloudbrainFlavorName(task models.Cloudbrain) string {
  2565. if task.Spec != nil {
  2566. flavorName := task.Spec.ComputeResource + ":" + fmt.Sprint(task.Spec.AccCardsNum) + "*" + task.Spec.AccCardType +
  2567. ",内存:" + strconv.FormatInt(int64(task.Spec.MemGiB), 10) + "GB,共享内存:" + strconv.FormatInt(int64(task.Spec.ShareMemGiB), 10) + "GB"
  2568. return flavorName
  2569. } else {
  2570. return ""
  2571. }
  2572. }