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

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