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
3 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009
  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. if taskInfo.JobType == string(models.JobTypeTrain) {
  1177. err := retry(3, time.Second*30, func() error {
  1178. _, err := grampus.StopJob(taskInfo.JobID)
  1179. return err
  1180. })
  1181. logErrorAndUpdateJobStatus(err, taskInfo)
  1182. }
  1183. }
  1184. }
  1185. }
  1186. func DeleteJobs(cloudBrains []*models.Cloudbrain) {
  1187. for _, taskInfo := range cloudBrains {
  1188. err := models.DeleteJob(taskInfo)
  1189. if err != nil {
  1190. log.Warn("Failed to DeleteJob:", err)
  1191. return
  1192. }
  1193. if taskInfo.Type == models.TypeCloudBrainOne {
  1194. cloudbrain.DelCloudBrainJob(taskInfo.JobName)
  1195. DeleteCloudbrainJobStorage(taskInfo.JobName, models.TypeCloudBrainOne)
  1196. }
  1197. if taskInfo.Type == models.TypeCloudBrainTwo {
  1198. if taskInfo.JobType == string(models.JobTypeTrain) || taskInfo.JobType == string(models.JobTypeInference) {
  1199. modelarts.DelTrainJob(taskInfo.JobID)
  1200. DeleteJobStorage(taskInfo.JobName)
  1201. }
  1202. if taskInfo.JobType == string(models.JobTypeDebug) {
  1203. modelarts.DelNotebook2(taskInfo.JobID)
  1204. }
  1205. }
  1206. if taskInfo.Type == models.TypeC2Net {
  1207. if taskInfo.JobType == string(models.JobTypeTrain) {
  1208. cloudbrain.DelCloudBrainJob(taskInfo.JobName)
  1209. DeleteCloudbrainJobStorage(taskInfo.JobName, models.TypeCloudBrainOne)
  1210. }
  1211. }
  1212. }
  1213. }
  1214. func retry(attempts int, sleep time.Duration, f func() error) (err error) {
  1215. for i := 0; i < attempts; i++ {
  1216. if i > 0 {
  1217. log.Warn("retrying after error:", err)
  1218. time.Sleep(sleep)
  1219. }
  1220. err = f()
  1221. if err == nil {
  1222. return nil
  1223. }
  1224. }
  1225. return fmt.Errorf("after %d attempts, last error: %s", attempts, err)
  1226. }
  1227. func logErrorAndUpdateJobStatus(err error, taskInfo *models.Cloudbrain) {
  1228. if err != nil {
  1229. log.Warn("Failed to stop cloudBrain job:"+taskInfo.JobID, err)
  1230. } else {
  1231. oldStatus := taskInfo.Status
  1232. taskInfo.Status = string(models.JobStopped)
  1233. if taskInfo.EndTime == 0 {
  1234. taskInfo.EndTime = timeutil.TimeStampNow()
  1235. }
  1236. taskInfo.ComputeAndSetDuration()
  1237. if oldStatus != taskInfo.Status {
  1238. notification.NotifyChangeCloudbrainStatus(taskInfo, oldStatus)
  1239. }
  1240. err = models.UpdateJob(taskInfo)
  1241. if err != nil {
  1242. log.Warn("UpdateJob failed", err)
  1243. }
  1244. }
  1245. }
  1246. func CloudBrainDel(ctx *context.Context) {
  1247. var listType = ctx.Query("debugListType")
  1248. if err := deleteCloudbrainJob(ctx); err != nil {
  1249. log.Error("deleteCloudbrainJob failed: %v", err, ctx.Data["msgID"])
  1250. ctx.ServerError(err.Error(), err)
  1251. return
  1252. }
  1253. var isAdminPage = ctx.Query("isadminpage")
  1254. var isHomePage = ctx.Query("ishomepage")
  1255. if ctx.IsUserSiteAdmin() && isAdminPage == "true" {
  1256. ctx.Redirect(setting.AppSubURL + "/admin" + "/cloudbrains")
  1257. } else if isHomePage == "true" {
  1258. ctx.Redirect(setting.AppSubURL + "/cloudbrains")
  1259. } else {
  1260. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/debugjob?debugListType=" + listType)
  1261. }
  1262. }
  1263. func deleteCloudbrainJob(ctx *context.Context) error {
  1264. task := ctx.Cloudbrain
  1265. if task.Status != string(models.JobStopped) && task.Status != string(models.JobFailed) && task.Status != string(models.JobSucceeded) {
  1266. log.Error("the job(%s) has not been stopped", task.JobName, ctx.Data["msgID"])
  1267. return errors.New("the job has not been stopped")
  1268. }
  1269. err := models.DeleteJob(task)
  1270. if err != nil {
  1271. log.Error("DeleteJob failed: %v", err, ctx.Data["msgID"])
  1272. return err
  1273. }
  1274. DeleteCloudbrainJobStorage(task.JobName, models.TypeCloudBrainOne)
  1275. return nil
  1276. }
  1277. func CloudBrainShowModels(ctx *context.Context) {
  1278. ctx.Data["PageIsCloudBrain"] = true
  1279. ID := ctx.Params(":id")
  1280. parentDir := ctx.Query("parentDir")
  1281. dirArray := strings.Split(parentDir, "/")
  1282. task, err := models.GetCloudbrainByID(ID)
  1283. if err != nil {
  1284. log.Error("no such job!", ctx.Data["msgID"])
  1285. ctx.ServerError("no such job:", err)
  1286. return
  1287. }
  1288. //get dirs
  1289. dirs, err := GetModelDirs(task.JobName, parentDir)
  1290. if err != nil {
  1291. log.Error("GetModelDirs failed:%v", err.Error(), ctx.Data["msgID"])
  1292. ctx.ServerError("GetModelDirs failed:", err)
  1293. return
  1294. }
  1295. var fileInfos []storage.FileInfo
  1296. err = json.Unmarshal([]byte(dirs), &fileInfos)
  1297. if err != nil {
  1298. log.Error("json.Unmarshal failed:%v", err.Error(), ctx.Data["msgID"])
  1299. ctx.ServerError("json.Unmarshal failed:", err)
  1300. return
  1301. }
  1302. for i, fileInfo := range fileInfos {
  1303. temp, _ := time.Parse("2006-01-02 15:04:05", fileInfo.ModTime)
  1304. fileInfos[i].ModTime = temp.Local().Format("2006-01-02 15:04:05")
  1305. }
  1306. sort.Slice(fileInfos, func(i, j int) bool {
  1307. return fileInfos[i].ModTime > fileInfos[j].ModTime
  1308. })
  1309. ctx.Data["Path"] = dirArray
  1310. ctx.Data["Dirs"] = fileInfos
  1311. ctx.Data["task"] = task
  1312. ctx.Data["ID"] = ID
  1313. ctx.HTML(200, tplCloudBrainShowModels)
  1314. }
  1315. func GetPublicImages(ctx *context.Context) {
  1316. uid := getUID(ctx)
  1317. opts := models.SearchImageOptions{
  1318. IncludePublicOnly: true,
  1319. UID: uid,
  1320. Keyword: ctx.Query("q"),
  1321. Topics: ctx.Query("topic"),
  1322. IncludeOfficialOnly: ctx.QueryBool("recommend"),
  1323. SearchOrderBy: "type desc, num_stars desc,id desc",
  1324. Status: models.IMAGE_STATUS_SUCCESS,
  1325. CloudbrainType: ctx.QueryInt("cloudbrainType"),
  1326. }
  1327. getImages(ctx, &opts)
  1328. }
  1329. func GetCustomImages(ctx *context.Context) {
  1330. uid := getUID(ctx)
  1331. opts := models.SearchImageOptions{
  1332. UID: uid,
  1333. IncludeOwnerOnly: true,
  1334. Keyword: ctx.Query("q"),
  1335. Topics: ctx.Query("topic"),
  1336. Status: -1,
  1337. SearchOrderBy: "id desc",
  1338. }
  1339. getImages(ctx, &opts)
  1340. }
  1341. func GetStarImages(ctx *context.Context) {
  1342. uid := getUID(ctx)
  1343. opts := models.SearchImageOptions{
  1344. UID: uid,
  1345. IncludeStarByMe: true,
  1346. Keyword: ctx.Query("q"),
  1347. Topics: ctx.Query("topic"),
  1348. Status: models.IMAGE_STATUS_SUCCESS,
  1349. SearchOrderBy: "id desc",
  1350. }
  1351. getImages(ctx, &opts)
  1352. }
  1353. func getUID(ctx *context.Context) int64 {
  1354. var uid int64 = -1
  1355. if ctx.IsSigned {
  1356. uid = ctx.User.ID
  1357. }
  1358. return uid
  1359. }
  1360. func GetAllImages(ctx *context.Context) {
  1361. uid := getUID(ctx)
  1362. opts := models.SearchImageOptions{
  1363. UID: uid,
  1364. Keyword: ctx.Query("q"),
  1365. Topics: ctx.Query("topic"),
  1366. IncludeOfficialOnly: ctx.QueryBool("recommend"),
  1367. SearchOrderBy: "id desc",
  1368. Status: -1,
  1369. }
  1370. if ctx.Query("private") != "" {
  1371. if ctx.QueryBool("private") {
  1372. opts.IncludePrivateOnly = true
  1373. } else {
  1374. opts.IncludePublicOnly = true
  1375. }
  1376. }
  1377. getImages(ctx, &opts)
  1378. }
  1379. func getImages(ctx *context.Context, opts *models.SearchImageOptions) {
  1380. page := ctx.QueryInt("page")
  1381. if page <= 0 {
  1382. page = 1
  1383. }
  1384. pageSize := ctx.QueryInt("pageSize")
  1385. if pageSize <= 0 {
  1386. pageSize = 15
  1387. }
  1388. opts.ListOptions = models.ListOptions{
  1389. Page: page,
  1390. PageSize: pageSize,
  1391. }
  1392. imageList, total, err := models.SearchImage(opts)
  1393. if err != nil {
  1394. log.Error("Can not get images:%v", err)
  1395. ctx.JSON(http.StatusOK, models.ImagesPageResult{
  1396. Count: 0,
  1397. Images: []*models.Image{},
  1398. })
  1399. } else {
  1400. ctx.JSON(http.StatusOK, models.ImagesPageResult{
  1401. Count: total,
  1402. Images: imageList,
  1403. })
  1404. }
  1405. }
  1406. func GetModelDirs(jobName string, parentDir string) (string, error) {
  1407. var req string
  1408. modelActualPath := storage.GetMinioPath(jobName, cloudbrain.ModelMountPath+"/")
  1409. if parentDir == "" {
  1410. req = "baseDir=" + modelActualPath
  1411. } else {
  1412. req = "baseDir=" + modelActualPath + "&parentDir=" + parentDir
  1413. }
  1414. return getDirs(req)
  1415. }
  1416. func GetResultDirs(jobName string, parentDir string) (string, error) {
  1417. var req string
  1418. modelActualPath := storage.GetMinioPath(jobName, cloudbrain.ResultPath+"/")
  1419. if parentDir == "" {
  1420. req = "baseDir=" + modelActualPath
  1421. } else {
  1422. req = "baseDir=" + modelActualPath + "&parentDir=" + parentDir
  1423. }
  1424. return getDirs(req)
  1425. }
  1426. func CloudBrainDownloadModel(ctx *context.Context) {
  1427. parentDir := ctx.Query("parentDir")
  1428. fileName := ctx.Query("fileName")
  1429. jobName := ctx.Query("jobName")
  1430. filePath := "jobs/" + jobName + "/model/" + parentDir
  1431. url, err := storage.Attachments.PresignedGetURL(filePath, fileName)
  1432. if err != nil {
  1433. log.Error("PresignedGetURL failed: %v", err.Error(), ctx.Data["msgID"])
  1434. ctx.ServerError("PresignedGetURL", err)
  1435. return
  1436. }
  1437. ctx.Resp.Header().Set("Cache-Control", "max-age=0")
  1438. http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusMovedPermanently)
  1439. }
  1440. func CloudBrainDownloadMultiModel(ctx *context.Context) {
  1441. parentDir := ctx.Query("parentDir")
  1442. jobName := ctx.Query("jobName")
  1443. filePath := "jobs/" + jobName + "/model/" + parentDir
  1444. allFile, err := storage.GetAllObjectByBucketAndPrefixMinio(setting.Attachment.Minio.Bucket, filePath)
  1445. if err == nil {
  1446. returnFileName := jobName + ".zip"
  1447. MinioDownloadManyFile(filePath, ctx, returnFileName, allFile)
  1448. } else {
  1449. log.Info("error,msg=" + err.Error())
  1450. ctx.ServerError("no file to download.", err)
  1451. }
  1452. }
  1453. func CloudBrainDownloadInferenceResult(ctx *context.Context) {
  1454. parentDir := ctx.Query("parentDir")
  1455. fileName := ctx.Query("fileName")
  1456. jobName := ctx.Query("jobName")
  1457. filePath := "jobs/" + jobName + "/result/" + parentDir
  1458. url, err := storage.Attachments.PresignedGetURL(filePath, fileName)
  1459. if err != nil {
  1460. log.Error("PresignedGetURL failed: %v", err.Error(), ctx.Data["msgID"])
  1461. ctx.ServerError("PresignedGetURL", err)
  1462. return
  1463. }
  1464. ctx.Resp.Header().Set("Cache-Control", "max-age=0")
  1465. http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusMovedPermanently)
  1466. }
  1467. func GetRate(ctx *context.Context) {
  1468. isObjectDetcionAll := ctx.QueryBool("isObjectDetcionAll")
  1469. if isObjectDetcionAll {
  1470. ctx.Redirect(setting.BenchmarkServerHost + "?username=admin")
  1471. return
  1472. }
  1473. var ID = ctx.Params(":id")
  1474. job, err := models.GetCloudbrainByID(ID)
  1475. if err != nil {
  1476. ctx.ServerError("GetCloudbrainByJobID failed", err)
  1477. return
  1478. }
  1479. if job.JobType == string(models.JobTypeBenchmark) {
  1480. log.Info("url=" + setting.BenchmarkServerHost + "?username=" + ctx.User.Name)
  1481. ctx.Redirect(setting.BenchmarkServerHost + "?username=" + ctx.User.Name)
  1482. } else if job.JobType == string(models.JobTypeSnn4imagenet) {
  1483. ctx.Redirect(setting.Snn4imagenetServerHost)
  1484. } else if job.JobType == string(models.JobTypeBrainScore) {
  1485. ctx.Redirect(setting.BrainScoreServerHost)
  1486. } else if job.JobType == string(models.JobTypeSnn4Ecoset) {
  1487. ctx.Redirect(setting.Snn4EcosetServerHost)
  1488. } else {
  1489. log.Error("JobType error:%s", job.JobType, ctx.Data["msgID"])
  1490. }
  1491. }
  1492. func downloadCode(repo *models.Repository, codePath, branchName string) error {
  1493. //add "file:///" prefix to make the depth valid
  1494. if err := git.Clone(CLONE_FILE_PREFIX+repo.RepoPath(), codePath, git.CloneRepoOptions{Branch: branchName, Depth: 1}); err != nil {
  1495. log.Error("Failed to clone repository: %s (%v)", repo.FullName(), err)
  1496. return err
  1497. }
  1498. configFile, err := os.OpenFile(codePath+"/.git/config", os.O_RDWR, 0666)
  1499. if err != nil {
  1500. log.Error("open file(%s) failed:%v", codePath+"/,git/config", err)
  1501. return err
  1502. }
  1503. defer configFile.Close()
  1504. pos := int64(0)
  1505. reader := bufio.NewReader(configFile)
  1506. for {
  1507. line, err := reader.ReadString('\n')
  1508. if err != nil {
  1509. if err == io.EOF {
  1510. log.Error("not find the remote-url")
  1511. return nil
  1512. } else {
  1513. log.Error("read error: %v", err)
  1514. return err
  1515. }
  1516. }
  1517. if strings.Contains(line, "url") && strings.Contains(line, ".git") {
  1518. originUrl := "\turl = " + repo.CloneLink().HTTPS + "\n"
  1519. if len(line) > len(originUrl) {
  1520. originUrl += strings.Repeat(" ", len(line)-len(originUrl))
  1521. }
  1522. bytes := []byte(originUrl)
  1523. _, err := configFile.WriteAt(bytes, pos)
  1524. if err != nil {
  1525. log.Error("WriteAt failed:%v", err)
  1526. return err
  1527. }
  1528. break
  1529. }
  1530. pos += int64(len(line))
  1531. }
  1532. return nil
  1533. }
  1534. func downloadRateCode(repo *models.Repository, taskName, rateOwnerName, rateRepoName, codePath, benchmarkCategory, gpuType, userName string) error {
  1535. err := os.MkdirAll(codePath, os.ModePerm)
  1536. if err != nil {
  1537. log.Error("mkdir codePath failed", err.Error())
  1538. return err
  1539. }
  1540. repoExt, err := models.GetRepositoryByOwnerAndName(rateOwnerName, rateRepoName)
  1541. if err != nil {
  1542. log.Error("GetRepositoryByOwnerAndName(%s) failed", rateRepoName, err.Error())
  1543. return err
  1544. }
  1545. if err := git.Clone(CLONE_FILE_PREFIX+repoExt.RepoPath(), codePath, git.CloneRepoOptions{Depth: 1}); err != nil {
  1546. log.Error("Failed to clone repository: %s (%v)", repoExt.FullName(), err)
  1547. return err
  1548. }
  1549. fileName := codePath + cloudbrain.TaskInfoName
  1550. f, err := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.ModePerm)
  1551. if err != nil {
  1552. log.Error("OpenFile failed", err.Error())
  1553. return err
  1554. }
  1555. defer f.Close()
  1556. data, err := json.Marshal(models.TaskInfo{
  1557. Username: userName,
  1558. TaskName: taskName,
  1559. CodeName: repo.Name,
  1560. BenchmarkCategory: strings.Split(benchmarkCategory, ","),
  1561. CodeLink: strings.TrimSuffix(repo.CloneLink().HTTPS, ".git"),
  1562. GpuType: gpuType,
  1563. })
  1564. if err != nil {
  1565. log.Error("json.Marshal failed", err.Error())
  1566. return err
  1567. }
  1568. _, err = f.Write(data)
  1569. if err != nil {
  1570. log.Error("WriteString failed", err.Error())
  1571. return err
  1572. }
  1573. return nil
  1574. }
  1575. func uploadCodeToMinio(codePath, jobName, parentDir string) error {
  1576. files, err := readDir(codePath)
  1577. if err != nil {
  1578. log.Error("readDir(%s) failed: %s", codePath, err.Error())
  1579. return err
  1580. }
  1581. for _, file := range files {
  1582. if file.IsDir() {
  1583. if err = uploadCodeToMinio(codePath+file.Name()+"/", jobName, parentDir+file.Name()+"/"); err != nil {
  1584. log.Error("uploadCodeToMinio(%s) failed: %s", file.Name(), err.Error())
  1585. return err
  1586. }
  1587. } else {
  1588. destObject := setting.CBCodePathPrefix + jobName + parentDir + file.Name()
  1589. sourceFile := codePath + file.Name()
  1590. err = storage.Attachments.UploadObject(destObject, sourceFile)
  1591. if err != nil {
  1592. log.Error("UploadObject(%s) failed: %s", file.Name(), err.Error())
  1593. return err
  1594. }
  1595. }
  1596. }
  1597. return nil
  1598. }
  1599. func mkModelPath(modelPath string) error {
  1600. return mkPathAndReadMeFile(modelPath, "You can put the files into this directory and download the files by the web page.")
  1601. }
  1602. func mkPathAndReadMeFile(path string, text string) error {
  1603. err := os.MkdirAll(path, os.ModePerm)
  1604. if err != nil {
  1605. log.Error("MkdirAll(%s) failed:%v", path, err)
  1606. return err
  1607. }
  1608. fileName := path + README
  1609. f, err := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.ModePerm)
  1610. if err != nil {
  1611. log.Error("OpenFile failed", err.Error())
  1612. return err
  1613. }
  1614. defer f.Close()
  1615. _, err = f.WriteString(text)
  1616. if err != nil {
  1617. log.Error("WriteString failed", err.Error())
  1618. return err
  1619. }
  1620. return nil
  1621. }
  1622. func DeleteCloudbrainJobStorage(jobName string, cloudbrainType int) error {
  1623. //delete local
  1624. localJobPath := setting.JobPath + jobName
  1625. err := os.RemoveAll(localJobPath)
  1626. if err != nil {
  1627. log.Error("RemoveAll(%s) failed:%v", localJobPath, err)
  1628. }
  1629. //delete oss
  1630. if cloudbrainType == models.TypeCloudBrainOne {
  1631. dirPath := setting.CBCodePathPrefix + jobName + "/"
  1632. err = storage.Attachments.DeleteDir(dirPath)
  1633. if err != nil {
  1634. log.Error("DeleteDir(%s) failed:%v", localJobPath, err)
  1635. }
  1636. } else if cloudbrainType == models.TypeCloudBrainTwo {
  1637. //dirPath := setting.CodePathPrefix + jobName + "/"
  1638. //err = storage.ObsRemoveObject(setting.Bucket, dirPath)
  1639. //if err != nil {
  1640. // log.Error("ObsRemoveObject(%s) failed:%v", localJobPath, err)
  1641. //}
  1642. log.Info("no need to delete")
  1643. } else {
  1644. log.Error("cloudbrainType(%d) error", cloudbrainType)
  1645. }
  1646. return nil
  1647. }
  1648. func SyncCloudbrainStatus() {
  1649. cloudBrains, err := models.GetCloudBrainUnStoppedJob()
  1650. if err != nil {
  1651. log.Error("GetCloudBrainUnStoppedJob failed:", err.Error())
  1652. return
  1653. }
  1654. for _, task := range cloudBrains {
  1655. if task.JobType == string(models.JobTypeModelSafety) {
  1656. continue
  1657. }
  1658. if task.Type == models.TypeCloudBrainOne {
  1659. task, err = cloudbrainTask.SyncCloudBrainOneStatus(task)
  1660. if err != nil {
  1661. log.Error("Sync cloud brain one (%s) failed:%v", task.JobName, err)
  1662. continue
  1663. }
  1664. } else if task.Type == models.TypeCloudBrainTwo || task.Type == models.TypeCDCenter {
  1665. if task.JobType == string(models.JobTypeDebug) {
  1666. err := modelarts.HandleNotebookInfo(task)
  1667. if err != nil {
  1668. log.Error("HandleNotebookInfo(%s) failed:%v", task.DisplayJobName, err)
  1669. continue
  1670. }
  1671. } else if task.JobType == string(models.JobTypeTrain) || task.JobType == string(models.JobTypeInference) {
  1672. err := modelarts.HandleTrainJobInfo(task)
  1673. if err != nil {
  1674. log.Error("HandleTrainJobInfo(%s) failed:%v", task.DisplayJobName, err)
  1675. continue
  1676. }
  1677. } else {
  1678. log.Error("task.JobType(%s) is error:%s", task.DisplayJobName, task.JobType)
  1679. }
  1680. } else if task.Type == models.TypeC2Net {
  1681. if task.JobType == string(models.JobTypeDebug) {
  1682. cloudbrainTask.SyncGrampusNotebookStatus(task)
  1683. } else {
  1684. result, err := grampus.GetJob(task.JobID)
  1685. if err != nil {
  1686. log.Error("GetTrainJob(%s) failed:%v", task.DisplayJobName, err)
  1687. continue
  1688. }
  1689. if result != nil {
  1690. if len(result.JobInfo.Tasks[0].CenterID) == 1 && len(result.JobInfo.Tasks[0].CenterName) == 1 {
  1691. task.AiCenter = result.JobInfo.Tasks[0].CenterID[0] + "+" + result.JobInfo.Tasks[0].CenterName[0]
  1692. }
  1693. oldStatus := task.Status
  1694. task.Status = grampus.TransTrainJobStatus(result.JobInfo.Status)
  1695. task.Duration = result.JobInfo.RunSec
  1696. if task.Duration < 0 {
  1697. task.Duration = 0
  1698. }
  1699. task.TrainJobDuration = models.ConvertDurationToStr(task.Duration)
  1700. if task.StartTime == 0 && result.JobInfo.StartedAt > 0 {
  1701. task.StartTime = timeutil.TimeStamp(result.JobInfo.StartedAt)
  1702. }
  1703. if task.EndTime == 0 && models.IsTrainJobTerminal(task.Status) && task.StartTime > 0 {
  1704. task.EndTime = task.StartTime.Add(task.Duration)
  1705. }
  1706. task.CorrectCreateUnix()
  1707. if oldStatus != task.Status {
  1708. notification.NotifyChangeCloudbrainStatus(task, oldStatus)
  1709. if models.IsTrainJobTerminal(task.Status) && task.ComputeResource == models.NPUResource {
  1710. if len(result.JobInfo.Tasks[0].CenterID) == 1 {
  1711. urchin.GetBackNpuModel(task.ID, grampus.GetRemoteEndPoint(result.JobInfo.Tasks[0].CenterID[0]), grampus.BucketRemote, grampus.GetNpuModelObjectKey(task.JobName), grampus.GetCenterProxy(setting.Grampus.LocalCenterID))
  1712. }
  1713. }
  1714. }
  1715. err = models.UpdateJob(task)
  1716. if err != nil {
  1717. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1718. continue
  1719. }
  1720. }
  1721. }
  1722. } else {
  1723. log.Error("task.Type(%s) is error:%d", task.JobName, task.Type)
  1724. }
  1725. if task.Status != string(models.JobWaiting) {
  1726. if task.Duration >= setting.MaxDuration && task.JobType == string(models.JobTypeDebug) {
  1727. log.Info("begin to stop job(%s), because of the duration", task.DisplayJobName)
  1728. err = cloudbrainTask.StopDebugJob(task)
  1729. if err != nil {
  1730. log.Error("StopJob(%s) failed:%v", task.DisplayJobName, err)
  1731. continue
  1732. }
  1733. oldStatus := task.Status
  1734. task.Status = string(models.JobStopped)
  1735. if task.EndTime == 0 {
  1736. task.EndTime = timeutil.TimeStampNow()
  1737. }
  1738. task.ComputeAndSetDuration()
  1739. if oldStatus != task.Status {
  1740. notification.NotifyChangeCloudbrainStatus(task, oldStatus)
  1741. }
  1742. err = models.UpdateJob(task)
  1743. if err != nil {
  1744. log.Error("UpdateJob(%s) failed:%v", task.DisplayJobName, err)
  1745. continue
  1746. }
  1747. }
  1748. }
  1749. }
  1750. return
  1751. }
  1752. func HandleTaskWithNoDuration(ctx *context.Context) {
  1753. mode := ctx.Query("mode")
  1754. log.Info("HandleTaskWithNoDuration start")
  1755. count := 0
  1756. start := time.Now().Unix()
  1757. for {
  1758. var cloudBrains []*models.Cloudbrain
  1759. var err error
  1760. if mode == "1" {
  1761. cloudBrains, err = models.GetStoppedJobWithNoStartTimeEndTime()
  1762. } else {
  1763. cloudBrains, err = models.GetStoppedJobWithNoDurationJob()
  1764. }
  1765. if err != nil {
  1766. log.Error("HandleTaskWithNoTrainJobDuration failed:", err.Error())
  1767. break
  1768. }
  1769. if len(cloudBrains) == 0 {
  1770. log.Info("HandleTaskWithNoTrainJobDuration:no task need handle")
  1771. break
  1772. }
  1773. handleNoDurationTask(cloudBrains)
  1774. count += len(cloudBrains)
  1775. if len(cloudBrains) < 100 {
  1776. log.Info("HandleTaskWithNoTrainJobDuration:task less than 100")
  1777. break
  1778. }
  1779. if time.Now().Unix()-start > 600 {
  1780. log.Info("HandleTaskWithNoDuration : time out")
  1781. ctx.JSON(200, fmt.Sprintf("task stop for time out,count=%d", count))
  1782. return
  1783. }
  1784. }
  1785. log.Info("HandleTaskWithNoTrainJobDuration:count=%d", count)
  1786. ctx.JSON(200, fmt.Sprintf("success,count=%d", count))
  1787. }
  1788. func handleNoDurationTask(cloudBrains []*models.Cloudbrain) {
  1789. for _, task := range cloudBrains {
  1790. time.Sleep(time.Millisecond * 100)
  1791. log.Info("Handle job ,%+v", task)
  1792. if task.Type == models.TypeCloudBrainOne {
  1793. result, err := cloudbrain.GetJob(task.JobID)
  1794. if err != nil {
  1795. log.Error("GetJob(%s) failed:%v", task.JobName, err)
  1796. updateDefaultDuration(task)
  1797. continue
  1798. }
  1799. if result != nil {
  1800. if result.Msg != "success" {
  1801. updateDefaultDuration(task)
  1802. continue
  1803. }
  1804. jobRes, err := models.ConvertToJobResultPayload(result.Payload)
  1805. if err != nil || len(jobRes.TaskRoles) == 0 {
  1806. updateDefaultDuration(task)
  1807. continue
  1808. }
  1809. taskRoles := jobRes.TaskRoles
  1810. taskRes, err := models.ConvertToTaskPod(taskRoles[cloudbrain.SubTaskName].(map[string]interface{}))
  1811. if err != nil || len(taskRes.TaskStatuses) == 0 {
  1812. updateDefaultDuration(task)
  1813. continue
  1814. }
  1815. task.Status = taskRes.TaskStatuses[0].State
  1816. log.Info("task startTime = %v endTime= %v ,jobId=%d", jobRes.JobStatus.StartTime, jobRes.JobStatus.EndTime, task.ID)
  1817. if jobRes.JobStatus.CreatedTime > 0 {
  1818. task.StartTime = timeutil.TimeStamp(jobRes.JobStatus.CreatedTime / 1000)
  1819. if jobRes.JobStatus.CompletedTime > 0 {
  1820. task.EndTime = timeutil.TimeStamp(jobRes.JobStatus.CompletedTime / 1000)
  1821. } else {
  1822. task.EndTime = task.UpdatedUnix
  1823. }
  1824. } else {
  1825. task.StartTime = 0
  1826. task.EndTime = 0
  1827. }
  1828. if task.EndTime < task.StartTime {
  1829. log.Info("endTime[%v] is less than starTime[%v],jobId=%d", task.EndTime, task.StartTime, task.ID)
  1830. st := task.StartTime
  1831. task.StartTime = task.EndTime
  1832. task.EndTime = st
  1833. }
  1834. task.Duration = task.EndTime.AsTime().Unix() - task.StartTime.AsTime().Unix()
  1835. task.TrainJobDuration = models.ConvertDurationToStr(task.Duration)
  1836. err = models.UpdateJobDurationWithDeleted(task)
  1837. if err != nil {
  1838. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1839. }
  1840. }
  1841. } else if task.Type == models.TypeCloudBrainTwo {
  1842. if task.JobType == string(models.JobTypeDebug) {
  1843. //result, err := modelarts.GetJob(task.JobID)
  1844. result, err := modelarts.GetNotebook2(task.JobID)
  1845. if err != nil {
  1846. log.Error("GetJob(%s) failed:%v", task.JobName, err)
  1847. updateDefaultDuration(task)
  1848. continue
  1849. }
  1850. if result != nil {
  1851. task.Status = result.Status
  1852. startTime := result.Lease.CreateTime
  1853. duration := result.Lease.Duration / 1000
  1854. if startTime > 0 {
  1855. task.StartTime = timeutil.TimeStamp(startTime / 1000)
  1856. task.EndTime = task.StartTime.Add(duration)
  1857. }
  1858. task.CorrectCreateUnix()
  1859. task.ComputeAndSetDuration()
  1860. err = models.UpdateJobDurationWithDeleted(task)
  1861. if err != nil {
  1862. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1863. continue
  1864. }
  1865. }
  1866. } else if task.JobType == string(models.JobTypeTrain) || task.JobType == string(models.JobTypeInference) {
  1867. result, err := modelarts.GetTrainJob(task.JobID, strconv.FormatInt(task.VersionID, 10))
  1868. if err != nil {
  1869. log.Error("GetTrainJob(%s) failed:%v", task.JobName, err)
  1870. updateDefaultDuration(task)
  1871. continue
  1872. }
  1873. if result != nil {
  1874. startTime := result.StartTime / 1000
  1875. if startTime > 0 {
  1876. task.StartTime = timeutil.TimeStamp(startTime)
  1877. task.EndTime = task.StartTime.Add(result.Duration / 1000)
  1878. }
  1879. task.ComputeAndSetDuration()
  1880. err = models.UpdateJobDurationWithDeleted(task)
  1881. if err != nil {
  1882. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1883. continue
  1884. }
  1885. }
  1886. } else {
  1887. log.Error("task.JobType(%s) is error:%s", task.JobName, task.JobType)
  1888. }
  1889. } else {
  1890. log.Error("task.Type(%s) is error:%d", task.JobName, task.Type)
  1891. }
  1892. }
  1893. }
  1894. func updateDefaultDuration(task *models.Cloudbrain) {
  1895. log.Info("updateDefaultDuration: taskId=%d", task.ID)
  1896. task.StartTime = task.CreatedUnix
  1897. task.EndTime = task.UpdatedUnix
  1898. task.ComputeAndSetDuration()
  1899. err := models.UpdateJobDurationWithDeleted(task)
  1900. if err != nil {
  1901. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1902. }
  1903. }
  1904. func CloudBrainBenchmarkIndex(ctx *context.Context) {
  1905. MustEnableCloudbrain(ctx)
  1906. repo := ctx.Repo.Repository
  1907. page := ctx.QueryInt("page")
  1908. if page <= 0 {
  1909. page = 1
  1910. }
  1911. var jobTypes []string
  1912. jobTypes = append(jobTypes, string(models.JobTypeBenchmark), string(models.JobTypeBrainScore), string(models.JobTypeSnn4imagenet), string(models.JobTypeSnn4Ecoset), string(models.JobTypeModelSafety))
  1913. ciTasks, count, err := models.Cloudbrains(&models.CloudbrainsOptions{
  1914. ListOptions: models.ListOptions{
  1915. Page: page,
  1916. PageSize: setting.UI.IssuePagingNum,
  1917. },
  1918. RepoID: repo.ID,
  1919. Type: -1,
  1920. JobTypes: jobTypes,
  1921. })
  1922. if err != nil {
  1923. ctx.ServerError("Get debugjob faild:", err)
  1924. return
  1925. }
  1926. for i, task := range ciTasks {
  1927. ciTasks[i].CanDel = cloudbrain.CanDeleteJob(ctx, &task.Cloudbrain)
  1928. ciTasks[i].Cloudbrain.ComputeResource = task.ComputeResource
  1929. if ciTasks[i].TrainJobDuration == "" {
  1930. if ciTasks[i].Duration == 0 {
  1931. var duration int64
  1932. if task.Status == string(models.JobRunning) {
  1933. duration = time.Now().Unix() - int64(task.Cloudbrain.CreatedUnix)
  1934. } else {
  1935. duration = int64(task.Cloudbrain.UpdatedUnix) - int64(task.Cloudbrain.CreatedUnix)
  1936. }
  1937. ciTasks[i].Duration = duration
  1938. }
  1939. ciTasks[i].TrainJobDuration = models.ConvertDurationToStr(ciTasks[i].Duration)
  1940. }
  1941. ciTasks[i].BenchmarkTypeName = ""
  1942. if ciTasks[i].JobType == string(models.JobTypeBenchmark) {
  1943. ciTasks[i].BenchmarkType = ctx.Tr("repo.cloudbrain.benchmark.algorithm")
  1944. } else if models.IsModelBenchMarkJobType(ciTasks[i].JobType) {
  1945. ciTasks[i].BenchmarkType = ctx.Tr("repo.cloudbrain.benchmark.model")
  1946. ciTasks[i].BenchmarkTypeName = ciTasks[i].JobType
  1947. if ciTasks[i].JobType == string(models.JobTypeSnn4imagenet) {
  1948. ciTasks[i].BenchmarkTypeRankLink = setting.Snn4imagenetServerHost
  1949. } else if ciTasks[i].JobType == string(models.JobTypeBrainScore) {
  1950. ciTasks[i].BenchmarkTypeRankLink = setting.BrainScoreServerHost
  1951. } else {
  1952. ciTasks[i].BenchmarkTypeRankLink = setting.Snn4EcosetServerHost
  1953. }
  1954. }
  1955. if task.BenchmarkTypeID > 0 {
  1956. for _, benchmarkType := range GetBenchmarkTypes(ctx).BenchmarkType {
  1957. if task.BenchmarkTypeID == benchmarkType.Id {
  1958. ciTasks[i].BenchmarkTypeRankLink = benchmarkType.RankLink
  1959. ciTasks[i].BenchmarkTypeName = benchmarkType.First
  1960. break
  1961. }
  1962. }
  1963. }
  1964. if task.JobType == string(models.JobTypeModelSafety) {
  1965. ciTasks[i].BenchmarkType = "安全评测"
  1966. ciTasks[i].BenchmarkTypeName = "Image Classification"
  1967. }
  1968. }
  1969. pager := context.NewPagination(int(count), setting.UI.IssuePagingNum, page, 5)
  1970. ctx.Data["Page"] = pager
  1971. ctx.Data["PageIsCloudBrain"] = true
  1972. ctx.Data["Tasks"] = ciTasks
  1973. ctx.Data["CanCreate"] = cloudbrain.CanCreateOrDebugJob(ctx)
  1974. ctx.Data["RepoIsEmpty"] = repo.IsEmpty
  1975. ctx.HTML(200, tplCloudBrainBenchmarkIndex)
  1976. }
  1977. func GetChildTypes(ctx *context.Context) {
  1978. benchmarkTypeID := ctx.QueryInt("benchmark_type_id")
  1979. re := make(map[string]interface{})
  1980. for {
  1981. var isExist bool
  1982. for _, benchmarkType := range GetBenchmarkTypes(ctx).BenchmarkType {
  1983. if benchmarkTypeID == benchmarkType.Id {
  1984. isExist = true
  1985. re["child_types"] = benchmarkType.Second
  1986. re["result_code"] = "0"
  1987. break
  1988. }
  1989. }
  1990. if !isExist {
  1991. re["result_code"] = "1"
  1992. log.Error("no such benchmark_type_id", ctx.Data["MsgID"])
  1993. re["errMsg"] = "system error"
  1994. break
  1995. }
  1996. break
  1997. }
  1998. ctx.JSON(200, re)
  1999. }
  2000. func CloudBrainBenchmarkNew(ctx *context.Context) {
  2001. ctx.Data["description"] = ""
  2002. ctx.Data["benchmarkTypeID"] = -1
  2003. ctx.Data["benchmark_child_types_id_hidden"] = -1
  2004. err := cloudBrainNewDataPrepare(ctx, string(models.JobTypeBenchmark))
  2005. if err != nil {
  2006. ctx.ServerError("get new cloudbrain info failed", err)
  2007. return
  2008. }
  2009. ctx.HTML(200, tplCloudBrainBenchmarkNew)
  2010. }
  2011. func getBenchmarkAttachment(benchmarkTypeID, benchmarkChildTypeID int, ctx *context.Context) (*models.BenchmarkDataset, error) {
  2012. var childInfo *models.BenchmarkDataset
  2013. var isExist bool
  2014. for _, benchmarkType := range GetBenchmarkTypes(ctx).BenchmarkType {
  2015. if benchmarkType.Id == benchmarkTypeID {
  2016. for _, childType := range benchmarkType.Second {
  2017. if childType.Id == benchmarkChildTypeID {
  2018. childInfo = childType
  2019. isExist = true
  2020. break
  2021. }
  2022. }
  2023. break
  2024. }
  2025. }
  2026. if !isExist {
  2027. log.Error("no such benchmark_type_id&benchmark_child_type_id")
  2028. return childInfo, errors.New("no such benchmark_type_id&benchmark_child_type_id")
  2029. }
  2030. return childInfo, nil
  2031. }
  2032. func getBenchmarkGpuQueue(gpuQueue string) (string, error) {
  2033. queue := ""
  2034. if benchmarkGpuInfos == nil {
  2035. if err := json.Unmarshal([]byte(setting.BenchmarkGpuTypes), &benchmarkGpuInfos); err != nil {
  2036. log.Error("json.Unmarshal BenchmarkGpuTypes(%s) failed:%v", setting.BenchmarkGpuTypes, err)
  2037. return queue, err
  2038. }
  2039. }
  2040. var isExist bool
  2041. for _, gpuInfo := range benchmarkGpuInfos.GpuInfo {
  2042. if gpuQueue == gpuInfo.Queue {
  2043. isExist = true
  2044. queue = gpuQueue
  2045. break
  2046. }
  2047. }
  2048. if !isExist {
  2049. log.Error("no such gpuQueue, %s", gpuQueue)
  2050. return queue, errors.New("no such gpuQueue")
  2051. }
  2052. return queue, nil
  2053. }
  2054. func getBenchmarkResourceSpec(resourceSpecID int) (int, error) {
  2055. var id int
  2056. if benchmarkResourceSpecs == nil {
  2057. if err := json.Unmarshal([]byte(setting.BenchmarkResourceSpecs), &benchmarkResourceSpecs); err != nil {
  2058. log.Error("json.Unmarshal BenchmarkResourceSpecs(%s) failed:%v", setting.BenchmarkResourceSpecs, err)
  2059. return id, err
  2060. }
  2061. }
  2062. var isExist bool
  2063. for _, resourceSpec := range benchmarkResourceSpecs.ResourceSpec {
  2064. if resourceSpecID == resourceSpec.Id {
  2065. isExist = true
  2066. id = resourceSpecID
  2067. break
  2068. }
  2069. }
  2070. if !isExist {
  2071. log.Error("no such resourceSpecID, %d", resourceSpecID)
  2072. return id, errors.New("no such resourceSpec")
  2073. }
  2074. return id, nil
  2075. }
  2076. func CloudBrainBenchmarkCreate(ctx *context.Context, form auth.CreateCloudBrainForm) {
  2077. jobType := form.JobType
  2078. if jobType == string(models.JobTypeBenchmark) {
  2079. BenchMarkAlgorithmCreate(ctx, form)
  2080. } else {
  2081. ModelBenchmarkCreate(ctx, form)
  2082. }
  2083. }
  2084. func BenchMarkAlgorithmCreate(ctx *context.Context, form auth.CreateCloudBrainForm) {
  2085. ctx.Data["PageIsCloudBrain"] = true
  2086. displayJobName := form.DisplayJobName
  2087. jobName := util.ConvertDisplayJobNameToJobName(displayJobName)
  2088. image := strings.TrimSpace(form.Image)
  2089. command := cloudbrain.CommandBenchmark
  2090. codePath := setting.JobPath + jobName + cloudbrain.CodeMountPath
  2091. benchmarkTypeID := form.BenchmarkTypeID
  2092. benchmarkChildTypeID := form.BenchmarkChildTypeID
  2093. repo := ctx.Repo.Repository
  2094. jobType := form.JobType
  2095. ctx.Data["description"] = form.Description
  2096. ctx.Data["benchmarkTypeID"] = benchmarkTypeID
  2097. ctx.Data["benchmark_child_types_id_hidden"] = benchmarkChildTypeID
  2098. lock := redis_lock.NewDistributeLock(redis_key.CloudbrainBindingJobNameKey(fmt.Sprint(repo.ID), form.JobType, displayJobName))
  2099. isOk, err := lock.Lock(models.CloudbrainKeyDuration)
  2100. if !isOk {
  2101. log.Error("lock processed failed:%v", err, ctx.Data["MsgID"])
  2102. cloudBrainNewDataPrepare(ctx, jobType)
  2103. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_samejob_err"), tplCloudBrainBenchmarkNew, &form)
  2104. return
  2105. }
  2106. defer lock.UnLock()
  2107. tasks, err := models.GetCloudbrainsByDisplayJobName(repo.ID, jobType, displayJobName)
  2108. if err == nil {
  2109. if len(tasks) != 0 {
  2110. log.Error("the job name did already exist", ctx.Data["MsgID"])
  2111. cloudBrainNewDataPrepare(ctx, jobType)
  2112. ctx.RenderWithErr("the job name did already exist", tplCloudBrainBenchmarkNew, &form)
  2113. return
  2114. }
  2115. } else {
  2116. if !models.IsErrJobNotExist(err) {
  2117. log.Error("system error, %v", err, ctx.Data["MsgID"])
  2118. cloudBrainNewDataPrepare(ctx, jobType)
  2119. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  2120. return
  2121. }
  2122. }
  2123. if !jobNamePattern.MatchString(jobName) {
  2124. cloudBrainNewDataPrepare(ctx, jobType)
  2125. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_jobname_err"), tplCloudBrainBenchmarkNew, &form)
  2126. return
  2127. }
  2128. childInfo, err := getBenchmarkAttachment(benchmarkTypeID, benchmarkChildTypeID, ctx)
  2129. if err != nil {
  2130. log.Error("getBenchmarkAttachment failed:%v", err, ctx.Data["MsgID"])
  2131. cloudBrainNewDataPrepare(ctx, jobType)
  2132. ctx.RenderWithErr("benchmark type error", tplCloudBrainBenchmarkNew, &form)
  2133. return
  2134. }
  2135. spec, err := resource.GetAndCheckSpec(ctx.User.ID, form.SpecId, models.FindSpecsOptions{
  2136. JobType: models.JobTypeBenchmark,
  2137. ComputeResource: models.GPU,
  2138. Cluster: models.OpenICluster,
  2139. AiCenterCode: models.AICenterOfCloudBrainOne})
  2140. if err != nil || spec == nil {
  2141. cloudBrainNewDataPrepare(ctx, jobType)
  2142. ctx.RenderWithErr("Resource specification not available", tplCloudBrainBenchmarkNew, &form)
  2143. return
  2144. }
  2145. if !account.IsPointBalanceEnough(ctx.User.ID, spec.UnitPrice) {
  2146. log.Error("point balance is not enough,userId=%d specId=%d", ctx.User.ID, spec.ID)
  2147. cloudBrainNewDataPrepare(ctx, jobType)
  2148. ctx.RenderWithErr(ctx.Tr("points.insufficient_points_balance"), tplCloudBrainBenchmarkNew, &form)
  2149. return
  2150. }
  2151. count, err := cloudbrainTask.GetNotFinalStatusTaskCount(ctx.User.ID, models.TypeCloudBrainOne, jobType)
  2152. if err != nil {
  2153. log.Error("GetCloudbrainCountByUserID failed:%v", err, ctx.Data["MsgID"])
  2154. cloudBrainNewDataPrepare(ctx, jobType)
  2155. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  2156. return
  2157. } else {
  2158. if count >= 1 {
  2159. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  2160. cloudBrainNewDataPrepare(ctx, jobType)
  2161. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain.morethanonejob"), tplCloudBrainBenchmarkNew, &form)
  2162. return
  2163. }
  2164. }
  2165. os.RemoveAll(codePath)
  2166. if err := downloadCode(repo, codePath, cloudbrain.DefaultBranchName); err != nil {
  2167. log.Error("downloadCode failed, %v", err, ctx.Data["MsgID"])
  2168. cloudBrainNewDataPrepare(ctx, jobType)
  2169. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  2170. return
  2171. }
  2172. if _, err := os.Stat(codePath + "/train.py"); err != nil {
  2173. if os.IsNotExist(err) {
  2174. // file does not exist
  2175. log.Error("train.py does not exist, %v", err, ctx.Data["MsgID"])
  2176. cloudBrainNewDataPrepare(ctx, jobType)
  2177. ctx.RenderWithErr("train.py does not exist", tplCloudBrainBenchmarkNew, &form)
  2178. } else {
  2179. log.Error("Stat failed, %v", err, ctx.Data["MsgID"])
  2180. cloudBrainNewDataPrepare(ctx, jobType)
  2181. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  2182. }
  2183. return
  2184. } else if _, err := os.Stat(codePath + "/test.py"); err != nil {
  2185. if os.IsNotExist(err) {
  2186. // file does not exist
  2187. log.Error("test.py does not exist, %v", err, ctx.Data["MsgID"])
  2188. cloudBrainNewDataPrepare(ctx, jobType)
  2189. ctx.RenderWithErr("test.py does not exist", tplCloudBrainBenchmarkNew, &form)
  2190. } else {
  2191. log.Error("Stat failed, %v", err, ctx.Data["MsgID"])
  2192. cloudBrainNewDataPrepare(ctx, jobType)
  2193. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  2194. }
  2195. return
  2196. }
  2197. if err := uploadCodeToMinio(codePath+"/", jobName, cloudbrain.CodeMountPath+"/"); err != nil {
  2198. log.Error("uploadCodeToMinio failed, %v", err, ctx.Data["MsgID"])
  2199. cloudBrainNewDataPrepare(ctx, jobType)
  2200. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  2201. return
  2202. }
  2203. benchmarkPath := setting.JobPath + jobName + cloudbrain.BenchMarkMountPath
  2204. if err := downloadRateCode(repo, jobName, childInfo.Owner, childInfo.RepoName, benchmarkPath, form.BenchmarkCategory, spec.AccCardType, ctx.User.Name); err != nil {
  2205. log.Error("downloadRateCode failed, %v", err, ctx.Data["MsgID"])
  2206. //cloudBrainNewDataPrepare(ctx)
  2207. //ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  2208. //return
  2209. }
  2210. if err := uploadCodeToMinio(benchmarkPath+"/", jobName, cloudbrain.BenchMarkMountPath+"/"); err != nil {
  2211. log.Error("uploadCodeToMinio failed, %v", err, ctx.Data["MsgID"])
  2212. //cloudBrainNewDataPrepare(ctx)
  2213. //ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  2214. //return
  2215. }
  2216. uuid := childInfo.Attachment
  2217. datasetInfos, datasetNames, err := models.GetDatasetInfo(uuid)
  2218. if err != nil {
  2219. log.Error("GetDatasetInfo failed: %v", err, ctx.Data["MsgID"])
  2220. cloudBrainNewDataPrepare(ctx, jobType)
  2221. ctx.RenderWithErr(ctx.Tr("cloudbrain.error.dataset_select"), tplCloudBrainBenchmarkNew, &form)
  2222. return
  2223. }
  2224. log.Info("Command=" + command)
  2225. log.Info("ModelPath=" + storage.GetMinioPath(jobName, cloudbrain.ModelMountPath+"/"))
  2226. req := cloudbrain.GenerateCloudBrainTaskReq{
  2227. Ctx: ctx,
  2228. DisplayJobName: displayJobName,
  2229. JobName: jobName,
  2230. Image: image,
  2231. Command: command,
  2232. Uuids: uuid,
  2233. DatasetNames: datasetNames,
  2234. DatasetInfos: datasetInfos,
  2235. CodePath: storage.GetMinioPath(jobName, cloudbrain.CodeMountPath+"/"),
  2236. ModelPath: storage.GetMinioPath(jobName, cloudbrain.ModelMountPath+"/"),
  2237. BenchmarkPath: storage.GetMinioPath(jobName, cloudbrain.BenchMarkMountPath+"/"),
  2238. Snn4ImageNetPath: storage.GetMinioPath(jobName, cloudbrain.Snn4imagenetMountPath+"/"),
  2239. BrainScorePath: storage.GetMinioPath(jobName, cloudbrain.BrainScoreMountPath+"/"),
  2240. JobType: string(models.JobTypeBenchmark),
  2241. Description: form.Description,
  2242. BranchName: cloudbrain.DefaultBranchName,
  2243. BootFile: "",
  2244. Params: "",
  2245. CommitID: "",
  2246. BenchmarkTypeID: benchmarkTypeID,
  2247. BenchmarkChildTypeID: benchmarkChildTypeID,
  2248. ResultPath: storage.GetMinioPath(jobName, cloudbrain.ResultPath+"/"),
  2249. Spec: spec,
  2250. }
  2251. _, err = cloudbrain.GenerateTask(req)
  2252. if err != nil {
  2253. cloudBrainNewDataPrepare(ctx, jobType)
  2254. ctx.RenderWithErr(err.Error(), tplCloudBrainBenchmarkNew, &form)
  2255. return
  2256. }
  2257. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/cloudbrain/benchmark")
  2258. }
  2259. func ModelBenchmarkCreate(ctx *context.Context, form auth.CreateCloudBrainForm) {
  2260. ctx.Data["PageIsCloudBrain"] = true
  2261. displayJobName := form.DisplayJobName
  2262. jobName := util.ConvertDisplayJobNameToJobName(displayJobName)
  2263. image := form.Image
  2264. jobType := form.JobType
  2265. codePath := setting.JobPath + jobName + cloudbrain.CodeMountPath
  2266. branchName := cloudbrain.DefaultBranchName
  2267. repo := ctx.Repo.Repository
  2268. tpl := tplCloudBrainBenchmarkNew
  2269. command := cloudbrain.GetCloudbrainDebugCommand()
  2270. lock := redis_lock.NewDistributeLock(redis_key.CloudbrainBindingJobNameKey(fmt.Sprint(repo.ID), jobType, displayJobName))
  2271. isOk, err := lock.Lock(models.CloudbrainKeyDuration)
  2272. if !isOk {
  2273. log.Error("lock processed failed:%v", err, ctx.Data["MsgID"])
  2274. cloudBrainNewDataPrepare(ctx, jobType)
  2275. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_samejob_err"), tpl, &form)
  2276. return
  2277. }
  2278. defer lock.UnLock()
  2279. tasks, err := models.GetCloudbrainsByDisplayJobName(repo.ID, jobType, displayJobName)
  2280. if err == nil {
  2281. if len(tasks) != 0 {
  2282. log.Error("the job name did already exist", ctx.Data["MsgID"])
  2283. cloudBrainNewDataPrepare(ctx, jobType)
  2284. ctx.RenderWithErr("the job name did already exist", tpl, &form)
  2285. return
  2286. }
  2287. } else {
  2288. if !models.IsErrJobNotExist(err) {
  2289. log.Error("system error, %v", err, ctx.Data["MsgID"])
  2290. cloudBrainNewDataPrepare(ctx, jobType)
  2291. ctx.RenderWithErr("system error", tpl, &form)
  2292. return
  2293. }
  2294. }
  2295. if !jobNamePattern.MatchString(displayJobName) {
  2296. cloudBrainNewDataPrepare(ctx, jobType)
  2297. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_jobname_err"), tpl, &form)
  2298. return
  2299. }
  2300. if !models.IsModelBenchMarkJobType(jobType) {
  2301. log.Error("jobtype error:", jobType, ctx.Data["MsgID"])
  2302. cloudBrainNewDataPrepare(ctx, jobType)
  2303. ctx.RenderWithErr("jobtype error", tpl, &form)
  2304. return
  2305. }
  2306. count, err := cloudbrainTask.GetNotFinalStatusTaskCount(ctx.User.ID, models.TypeCloudBrainOne, jobType)
  2307. if err != nil {
  2308. log.Error("GetCloudbrainCountByUserID failed:%v", err, ctx.Data["MsgID"])
  2309. cloudBrainNewDataPrepare(ctx, jobType)
  2310. ctx.RenderWithErr("system error", tpl, &form)
  2311. return
  2312. } else {
  2313. if count >= 1 {
  2314. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  2315. cloudBrainNewDataPrepare(ctx, jobType)
  2316. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain.morethanonejob"), tpl, &form)
  2317. return
  2318. }
  2319. }
  2320. downloadCode(repo, codePath, branchName)
  2321. uploadCodeToMinio(codePath+"/", jobName, cloudbrain.CodeMountPath+"/")
  2322. modelPath := setting.JobPath + jobName + cloudbrain.ModelMountPath + "/"
  2323. mkModelPath(modelPath)
  2324. uploadCodeToMinio(modelPath, jobName, cloudbrain.ModelMountPath+"/")
  2325. benchmarkPath := setting.JobPath + jobName + cloudbrain.BenchMarkMountPath
  2326. if setting.IsSnn4imagenetEnabled && jobType == string(models.JobTypeSnn4imagenet) {
  2327. downloadRateCode(repo, jobName, setting.Snn4imagenetOwner, setting.Snn4imagenetName, benchmarkPath, "", "", ctx.User.Name)
  2328. uploadCodeToMinio(benchmarkPath+"/", jobName, cloudbrain.BenchMarkMountPath+"/")
  2329. command = fmt.Sprintf(cloudbrain.Snn4imagenetCommand, displayJobName, form.CkptName, trimSpaceNewlineInString(form.Description))
  2330. }
  2331. benchmarkChildTypeID := 0
  2332. if setting.IsBrainScoreEnabled && jobType == string(models.JobTypeBrainScore) {
  2333. downloadRateCode(repo, jobName, setting.BrainScoreOwner, setting.BrainScoreName, benchmarkPath, "", "", ctx.User.Name)
  2334. uploadCodeToMinio(benchmarkPath+"/", jobName, cloudbrain.BenchMarkMountPath+"/")
  2335. benchmarkChildTypeID = form.BenchmarkChildTypeID
  2336. command = fmt.Sprintf(cloudbrain.BrainScoreCommand, getBrainRegion(benchmarkChildTypeID), displayJobName, form.CkptName, trimSpaceNewlineInString(form.Description))
  2337. }
  2338. var uuid string
  2339. var datasetInfos map[string]models.DatasetInfo
  2340. var datasetNames string
  2341. if setting.IsSnn4EcosetEnabled && jobType == string(models.JobTypeSnn4Ecoset) {
  2342. downloadRateCode(repo, jobName, setting.Snn4EcosetOwner, setting.Snn4EcosetName, benchmarkPath, "", "", ctx.User.Name)
  2343. uploadCodeToMinio(benchmarkPath+"/", jobName, cloudbrain.BenchMarkMountPath+"/")
  2344. command = fmt.Sprintf(cloudbrain.Snn4EcosetCommand, displayJobName, form.CkptName, trimSpaceNewlineInString(form.Description))
  2345. attachment, err := getEcosetAttachment()
  2346. if err != nil {
  2347. log.Error("load benchmark code failed", err)
  2348. cloudBrainNewDataPrepare(ctx, jobType)
  2349. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain.morethanonejob"), tpl, &form)
  2350. return
  2351. }
  2352. uuid = attachment.UUID
  2353. datasetInfos, datasetNames, _ = models.GetDatasetInfo(uuid)
  2354. }
  2355. spec, err := resource.GetAndCheckSpec(ctx.User.ID, form.SpecId, models.FindSpecsOptions{
  2356. JobType: models.JobTypeBenchmark,
  2357. ComputeResource: models.GPU,
  2358. Cluster: models.OpenICluster,
  2359. AiCenterCode: models.AICenterOfCloudBrainOne})
  2360. if err != nil || spec == nil {
  2361. cloudBrainNewDataPrepare(ctx, jobType)
  2362. ctx.RenderWithErr("Resource specification not available", tpl, &form)
  2363. return
  2364. }
  2365. if !account.IsPointBalanceEnough(ctx.User.ID, spec.UnitPrice) {
  2366. log.Error("point balance is not enough,userId=%d specId=%d", ctx.User.ID, spec.ID)
  2367. cloudBrainNewDataPrepare(ctx, jobType)
  2368. ctx.RenderWithErr(ctx.Tr("points.insufficient_points_balance"), tpl, &form)
  2369. return
  2370. }
  2371. log.Info("Command=" + command)
  2372. log.Info("ModelPath=" + storage.GetMinioPath(jobName, cloudbrain.ModelMountPath+"/"))
  2373. req := cloudbrain.GenerateCloudBrainTaskReq{
  2374. Ctx: ctx,
  2375. DisplayJobName: displayJobName,
  2376. JobName: jobName,
  2377. Image: image,
  2378. Command: command,
  2379. Uuids: uuid,
  2380. DatasetNames: datasetNames,
  2381. DatasetInfos: datasetInfos,
  2382. CodePath: storage.GetMinioPath(jobName, cloudbrain.CodeMountPath+"/"),
  2383. ModelPath: storage.GetMinioPath(jobName, cloudbrain.ModelMountPath+"/"),
  2384. BenchmarkPath: storage.GetMinioPath(jobName, cloudbrain.BenchMarkMountPath+"/"),
  2385. JobType: jobType,
  2386. Description: form.Description,
  2387. BranchName: branchName,
  2388. BootFile: form.BootFile,
  2389. Params: form.Params,
  2390. CommitID: "",
  2391. BenchmarkTypeID: 0,
  2392. BenchmarkChildTypeID: benchmarkChildTypeID,
  2393. ResultPath: storage.GetMinioPath(jobName, cloudbrain.ResultPath+"/"),
  2394. Spec: spec,
  2395. }
  2396. if form.ModelName != "" {
  2397. req.ModelName = form.ModelName
  2398. req.LabelName = form.LabelName
  2399. req.CkptName = form.CkptName
  2400. req.ModelVersion = form.ModelVersion
  2401. req.PreTrainModelPath = setting.Attachment.Minio.RealPath + form.PreTrainModelUrl
  2402. req.PreTrainModelUrl = form.PreTrainModelUrl
  2403. }
  2404. _, err = cloudbrain.GenerateTask(req)
  2405. if err != nil {
  2406. cloudBrainNewDataPrepare(ctx, jobType)
  2407. ctx.RenderWithErr(err.Error(), tpl, &form)
  2408. return
  2409. }
  2410. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/cloudbrain/benchmark")
  2411. }
  2412. func getEcosetAttachment() (*models.Attachment, error) {
  2413. ecosetRepo, err := models.GetRepositoryByOwnerAndName(setting.Snn4EcosetOwner, setting.Snn4EcosetName)
  2414. if err != nil {
  2415. return nil, err
  2416. }
  2417. datasetInfo, err := models.GetDatasetByRepo(ecosetRepo)
  2418. if err != nil {
  2419. return nil, err
  2420. }
  2421. return models.GetAttachmentByDatasetIdFileName(setting.Snn4AttachmentName, datasetInfo.ID)
  2422. }
  2423. func getBrainRegion(benchmarkChildTypeID int) string {
  2424. values := []string{"V1", "V2", "V4", "IT"}
  2425. return values[benchmarkChildTypeID]
  2426. }
  2427. func trimSpaceNewlineInString(s string) string {
  2428. re := regexp.MustCompile(`\r?\n`)
  2429. return re.ReplaceAllString(s, " ")
  2430. }
  2431. func BenchmarkDel(ctx *context.Context) {
  2432. if err := deleteCloudbrainJob(ctx); err != nil {
  2433. log.Error("deleteCloudbrainJob failed: %v", err, ctx.Data["msgID"])
  2434. ctx.ServerError(err.Error(), err)
  2435. return
  2436. }
  2437. var isAdminPage = ctx.Query("isadminpage")
  2438. var isHomePage = ctx.Query("ishomepage")
  2439. if ctx.IsUserSiteAdmin() && isAdminPage == "true" {
  2440. ctx.Redirect(setting.AppSubURL + "/admin" + "/cloudbrains")
  2441. } else if isHomePage == "true" {
  2442. ctx.Redirect(setting.AppSubURL + "/cloudbrains")
  2443. } else {
  2444. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/cloudbrain/benchmark")
  2445. }
  2446. }
  2447. func CloudBrainTrainJobNew(ctx *context.Context) {
  2448. ctx.Data["IsCreate"] = true
  2449. cloudBrainTrainJobCreate(ctx)
  2450. }
  2451. func CloudBrainTrainJobVersionNew(ctx *context.Context) {
  2452. ctx.Data["IsCreate"] = false
  2453. cloudBrainTrainJobCreate(ctx)
  2454. }
  2455. func cloudBrainTrainJobCreate(ctx *context.Context) {
  2456. err := cloudBrainNewDataPrepare(ctx, string(models.JobTypeTrain))
  2457. if err != nil {
  2458. ctx.ServerError("get new train-job info failed", err)
  2459. return
  2460. }
  2461. ctx.HTML(http.StatusOK, tplCloudBrainTrainJobNew)
  2462. }
  2463. func InferenceCloudBrainJobNew(ctx *context.Context) {
  2464. err := cloudBrainNewDataPrepare(ctx, string(models.JobTypeInference))
  2465. if err != nil {
  2466. ctx.ServerError("get new train-job info failed", err)
  2467. return
  2468. }
  2469. ctx.HTML(http.StatusOK, tplCloudBrainInferenceJobNew)
  2470. }
  2471. func InferenceCloudBrainJobShow(ctx *context.Context) {
  2472. cloudBrainShow(ctx, tplCloudBrainInferenceJobShow, models.JobTypeInference)
  2473. }
  2474. func DownloadGPUInferenceResultFile(ctx *context.Context) {
  2475. var jobID = ctx.Params(":jobid")
  2476. task, err := models.GetCloudbrainByJobID(jobID)
  2477. if err != nil {
  2478. log.Error("GetCloudbrainByJobID(%s) failed:%v", task.JobName, err.Error())
  2479. return
  2480. }
  2481. parentDir := ctx.Query("parentDir")
  2482. filePath := "jobs/" + task.JobName + "/result/" + parentDir
  2483. log.Info("prefix=" + filePath)
  2484. allFile, err := storage.GetAllObjectByBucketAndPrefixMinio(setting.Attachment.Minio.Bucket, filePath)
  2485. if err == nil {
  2486. returnFileName := task.DisplayJobName + ".zip"
  2487. MinioDownloadManyFile(filePath, ctx, returnFileName, allFile)
  2488. } else {
  2489. log.Info("error,msg=" + err.Error())
  2490. ctx.ServerError("no file to download.", err)
  2491. }
  2492. }
  2493. func getInferenceJobCommand(form auth.CreateCloudBrainInferencForm) (string, error) {
  2494. var command string
  2495. bootFile := strings.TrimSpace(form.BootFile)
  2496. params := form.Params
  2497. if !strings.HasSuffix(bootFile, ".py") {
  2498. log.Error("bootFile(%s) format error", bootFile)
  2499. return command, errors.New("bootFile format error")
  2500. }
  2501. var parameters models.Parameters
  2502. var param string
  2503. if len(params) != 0 {
  2504. err := json.Unmarshal([]byte(params), &parameters)
  2505. if err != nil {
  2506. log.Error("Failed to Unmarshal params: %s (%v)", params, err)
  2507. return command, err
  2508. }
  2509. for _, parameter := range parameters.Parameter {
  2510. param += " --" + parameter.Label + "=" + parameter.Value
  2511. }
  2512. }
  2513. param += " --modelname" + "=" + form.CkptName
  2514. command += "python /code/" + bootFile + param + " > " + cloudbrain.ResultPath + "/" + form.DisplayJobName + "-" + cloudbrain.LogFile
  2515. return command, nil
  2516. }
  2517. func getTrainJobCommand(form auth.CreateCloudBrainForm) (string, error) {
  2518. var command string
  2519. bootFile := strings.TrimSpace(form.BootFile)
  2520. params := form.Params
  2521. if !strings.HasSuffix(bootFile, ".py") {
  2522. log.Error("bootFile(%s) format error", bootFile)
  2523. return command, errors.New("bootFile format error")
  2524. }
  2525. var parameters models.Parameters
  2526. var param string
  2527. if len(params) != 0 {
  2528. err := json.Unmarshal([]byte(params), &parameters)
  2529. if err != nil {
  2530. log.Error("Failed to Unmarshal params: %s (%v)", params, err)
  2531. return command, err
  2532. }
  2533. for _, parameter := range parameters.Parameter {
  2534. param += " --" + parameter.Label + "=" + parameter.Value
  2535. }
  2536. }
  2537. if form.CkptName != "" {
  2538. param += " --ckpt_url" + "=" + "/pretrainmodel/" + form.CkptName
  2539. }
  2540. command += "python /code/" + bootFile + param + " > " + cloudbrain.ModelMountPath + "/" + form.DisplayJobName + "-" + cloudbrain.LogFile
  2541. return command, nil
  2542. }
  2543. func CloudBrainTrainJobDel(ctx *context.Context) {
  2544. var listType = ctx.Query("listType")
  2545. if err := deleteCloudbrainJob(ctx); err != nil {
  2546. log.Error("deleteCloudbrainJob failed: %v", err, ctx.Data["msgID"])
  2547. ctx.ServerError(err.Error(), err)
  2548. return
  2549. }
  2550. var isAdminPage = ctx.Query("isadminpage")
  2551. var isHomePage = ctx.Query("ishomepage")
  2552. if ctx.IsUserSiteAdmin() && isAdminPage == "true" {
  2553. ctx.Redirect(setting.AppSubURL + "/admin" + "/cloudbrains")
  2554. } else if isHomePage == "true" {
  2555. ctx.Redirect(setting.AppSubURL + "/cloudbrains")
  2556. } else {
  2557. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/train-job?listType=" + listType)
  2558. }
  2559. }
  2560. func GetBenchmarkTypes(ctx *context.Context) *models.BenchmarkTypes {
  2561. var lang = ctx.Locale.Language()
  2562. if benchmarkTypesMap[lang] == nil {
  2563. var val = i18n.Tr(lang, BENCHMARK_TYPE_CODE)
  2564. //use config
  2565. val = setting.BenchmarkTypes
  2566. var tempType *models.BenchmarkTypes
  2567. if err := json.Unmarshal([]byte(val), &tempType); err != nil {
  2568. log.Error("json.Unmarshal BenchmarkTypes(%s) failed:%v", val, err, ctx.Data["MsgID"])
  2569. return &models.BenchmarkTypes{}
  2570. }
  2571. benchmarkTypesMap[lang] = tempType
  2572. }
  2573. return benchmarkTypesMap[lang]
  2574. }
  2575. func GetCloudbrainAiCenter(task models.Cloudbrain, ctx *context.Context) string {
  2576. if task.Spec != nil {
  2577. return task.Spec.AiCenterName
  2578. } else {
  2579. return ""
  2580. }
  2581. }
  2582. func getCutStringAiCenterByAiCenter(aiCenter string) string {
  2583. if aiCenter == "" {
  2584. return ""
  2585. }
  2586. index := strings.LastIndex(aiCenter, "+")
  2587. return aiCenter[index+1:]
  2588. }
  2589. func GetCloudbrainCluster(task models.Cloudbrain, ctx *context.Context) string {
  2590. if task.Type == models.TypeCloudBrainOne || task.Type == models.TypeCloudBrainTwo || task.Type == models.TypeCDCenter {
  2591. return ctx.Tr("cloudbrain.resource_cluster_openi")
  2592. } else if task.Type == models.TypeC2Net {
  2593. return ctx.Tr("cloudbrain.resource_cluster_c2net")
  2594. }
  2595. return ""
  2596. }
  2597. func GetCloudbrainCardDuration(task models.Cloudbrain) string {
  2598. cardNum := int(0)
  2599. spec, err := resource.GetCloudbrainSpec(task.ID)
  2600. if err != nil {
  2601. log.Info("error:" + err.Error())
  2602. return ""
  2603. }
  2604. if spec != nil {
  2605. cardNum = spec.AccCardsNum
  2606. } else {
  2607. cardNum = 1
  2608. }
  2609. var workServerNumber int64
  2610. if task.WorkServerNumber >= 1 {
  2611. workServerNumber = int64(task.WorkServerNumber)
  2612. } else {
  2613. workServerNumber = 1
  2614. }
  2615. cardDuration := models.ConvertDurationToStr(workServerNumber * int64(cardNum) * task.Duration)
  2616. return cardDuration
  2617. }
  2618. func GetCloudbrainWaitTime(task models.Cloudbrain) string {
  2619. var waitTime string
  2620. if task.Status == string(models.JobWaiting) {
  2621. waitTimeInt := time.Now().Unix() - task.CreatedUnix.AsTime().Unix()
  2622. waitTime = models.ConvertDurationToStr(waitTimeInt)
  2623. if waitTimeInt < 0 {
  2624. waitTime = "00:00:00"
  2625. }
  2626. } else if task.Status == string(models.JobStopped) && task.StartTime.AsTime().Unix() == 0 {
  2627. waitTimeInt := task.EndTime.AsTime().Unix() - task.CreatedUnix.AsTime().Unix()
  2628. waitTime = models.ConvertDurationToStr(waitTimeInt)
  2629. if waitTimeInt < 0 {
  2630. waitTime = "00:00:00"
  2631. }
  2632. } else {
  2633. waitTimeInt := task.StartTime.AsTime().Unix() - task.CreatedUnix.AsTime().Unix()
  2634. waitTime = models.ConvertDurationToStr(waitTimeInt)
  2635. if waitTimeInt < 0 {
  2636. waitTime = "00:00:00"
  2637. }
  2638. }
  2639. return waitTime
  2640. }
  2641. func GetCloudbrainFlavorName(task models.Cloudbrain) string {
  2642. if task.Spec != nil {
  2643. flavorName := task.Spec.ComputeResource + ":" + fmt.Sprint(task.Spec.AccCardsNum) + "*" + task.Spec.AccCardType +
  2644. ",内存:" + strconv.FormatInt(int64(task.Spec.MemGiB), 10) + "GB,共享内存:" + strconv.FormatInt(int64(task.Spec.ShareMemGiB), 10) + "GB"
  2645. return flavorName
  2646. } else {
  2647. return ""
  2648. }
  2649. }