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.

modelarts.go 92 kB

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
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
3 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 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
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
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
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
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
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
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
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
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
4 years ago
4 years ago
3 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 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
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
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
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 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
3 years ago
3 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
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
3 years ago
4 years ago
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
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
4 years ago
4 years ago
3 years ago
3 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
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 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
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
4 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
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
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
4 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
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
4 years ago
4 years ago
3 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
3 years ago
4 years ago
4 years ago
4 years ago
3 years ago
3 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 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
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
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
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
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
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
4 years ago
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
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 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
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844
  1. package repo
  2. import (
  3. "archive/zip"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "io/ioutil"
  9. "net/http"
  10. "os"
  11. "path"
  12. "strconv"
  13. "strings"
  14. "time"
  15. "unicode/utf8"
  16. cloudbrainService "code.gitea.io/gitea/services/cloudbrain"
  17. "code.gitea.io/gitea/services/cloudbrain/cloudbrainTask"
  18. "code.gitea.io/gitea/modules/dataset"
  19. "code.gitea.io/gitea/modules/modelarts_cd"
  20. "code.gitea.io/gitea/services/cloudbrain/resource"
  21. "code.gitea.io/gitea/services/reward/point/account"
  22. "code.gitea.io/gitea/models"
  23. "code.gitea.io/gitea/modules/auth"
  24. "code.gitea.io/gitea/modules/base"
  25. "code.gitea.io/gitea/modules/cloudbrain"
  26. "code.gitea.io/gitea/modules/context"
  27. "code.gitea.io/gitea/modules/git"
  28. "code.gitea.io/gitea/modules/log"
  29. "code.gitea.io/gitea/modules/modelarts"
  30. "code.gitea.io/gitea/modules/notification"
  31. "code.gitea.io/gitea/modules/obs"
  32. "code.gitea.io/gitea/modules/redis/redis_key"
  33. "code.gitea.io/gitea/modules/redis/redis_lock"
  34. "code.gitea.io/gitea/modules/setting"
  35. "code.gitea.io/gitea/modules/storage"
  36. "code.gitea.io/gitea/modules/timeutil"
  37. "code.gitea.io/gitea/modules/util"
  38. )
  39. const (
  40. tplDebugJobIndex base.TplName = "repo/debugjob/index"
  41. tplModelArtsNotebookIndex base.TplName = "repo/modelarts/notebook/index"
  42. tplModelArtsNotebookNew base.TplName = "repo/modelarts/notebook/new"
  43. tplModelArtsNotebookShow base.TplName = "repo/modelarts/notebook/show"
  44. tplModelArtsTrainJobIndex base.TplName = "repo/modelarts/trainjob/index"
  45. tplModelArtsTrainJobNew base.TplName = "repo/modelarts/trainjob/new"
  46. tplModelArtsTrainJobShow base.TplName = "repo/modelarts/trainjob/show"
  47. tplModelArtsTrainJobVersionNew base.TplName = "repo/modelarts/trainjob/version_new"
  48. tplModelArtsInferenceJobIndex base.TplName = "repo/modelarts/inferencejob/index"
  49. tplModelArtsInferenceJobNew base.TplName = "repo/modelarts/inferencejob/new"
  50. tplModelArtsInferenceJobShow base.TplName = "repo/modelarts/inferencejob/show"
  51. )
  52. func DebugJobIndex(ctx *context.Context) {
  53. listType := ctx.Query("debugListType")
  54. if listType == "" {
  55. listType = models.AllResource
  56. }
  57. ctx.Data["ListType"] = listType
  58. MustEnableCloudbrain(ctx)
  59. repo := ctx.Repo.Repository
  60. page := ctx.QueryInt("page")
  61. if page <= 0 {
  62. page = 1
  63. }
  64. jobTypeNot := false
  65. var computeResource string
  66. if listType != models.AllResource {
  67. computeResource = listType
  68. }
  69. var jobTypes []string
  70. jobTypes = append(jobTypes, string(models.JobTypeDebug))
  71. ciTasks, count, err := models.Cloudbrains(&models.CloudbrainsOptions{
  72. ListOptions: models.ListOptions{
  73. Page: page,
  74. PageSize: setting.UI.IssuePagingNum,
  75. },
  76. RepoID: repo.ID,
  77. ComputeResource: computeResource,
  78. Type: models.TypeCloudBrainAll,
  79. JobTypeNot: jobTypeNot,
  80. JobTypes: jobTypes,
  81. })
  82. if err != nil {
  83. ctx.ServerError("Get debugjob faild:", err)
  84. return
  85. }
  86. for i, task := range ciTasks {
  87. ciTasks[i].CanDebug = cloudbrain.CanModifyJob(ctx, &task.Cloudbrain)
  88. ciTasks[i].CanDel = cloudbrain.CanDeleteJob(ctx, &task.Cloudbrain)
  89. ciTasks[i].Cloudbrain.ComputeResource = task.ComputeResource
  90. }
  91. pager := context.NewPagination(int(count), setting.UI.IssuePagingNum, page, 5)
  92. pager.AddParam(ctx, "debugListType", "ListType")
  93. ctx.Data["Page"] = pager
  94. ctx.Data["PageIsCloudBrain"] = true
  95. ctx.Data["Tasks"] = ciTasks
  96. ctx.Data["CanCreate"] = cloudbrain.CanCreateOrDebugJob(ctx)
  97. ctx.Data["RepoIsEmpty"] = repo.IsEmpty
  98. ctx.Data["debugListType"] = listType
  99. ctx.HTML(200, tplDebugJobIndex)
  100. }
  101. // MustEnableDataset check if repository enable internal cb
  102. func MustEnableModelArts(ctx *context.Context) {
  103. if !ctx.Repo.CanRead(models.UnitTypeCloudBrain) {
  104. ctx.NotFound("MustEnableCloudbrain", nil)
  105. return
  106. }
  107. }
  108. func NotebookNew(ctx *context.Context) {
  109. notebookNewDataPrepare(ctx)
  110. ctx.HTML(200, tplModelArtsNotebookNew)
  111. }
  112. func notebookNewDataPrepare(ctx *context.Context) error {
  113. ctx.Data["PageIsCloudBrain"] = true
  114. var displayJobName = cloudbrainService.GetDisplayJobName(ctx.User.Name)
  115. ctx.Data["display_job_name"] = displayJobName
  116. attachs, err := models.GetModelArtsUserAttachments(ctx.User.ID)
  117. if err != nil {
  118. ctx.ServerError("GetAllUserAttachments failed:", err)
  119. return err
  120. }
  121. ctx.Data["attachments"] = attachs
  122. ctx.Data["images"] = setting.StImageInfos.ImageInfo
  123. prepareCloudbrainTwoDebugSpecs(ctx)
  124. ctx.Data["datasetType"] = models.TypeCloudBrainTwo
  125. waitCount := cloudbrain.GetWaitingCloudbrainCount(models.TypeCloudBrainTwo, "")
  126. ctx.Data["WaitCount"] = waitCount
  127. NotStopTaskCount, _ := cloudbrainTask.GetNotFinalStatusTaskCount(ctx.User.ID, models.TypeCloudBrainTwo, string(models.JobTypeDebug))
  128. ctx.Data["NotStopTaskCount"] = NotStopTaskCount
  129. return nil
  130. }
  131. func prepareCloudbrainTwoDebugSpecs(ctx *context.Context) {
  132. aiCenterCode := models.AICenterOfCloudBrainTwo
  133. if setting.ModelartsCD.Enabled {
  134. aiCenterCode = models.AICenterOfChengdu
  135. }
  136. noteBookSpecs, _ := resource.FindAvailableSpecs(ctx.User.ID, models.FindSpecsOptions{
  137. JobType: models.JobTypeDebug,
  138. ComputeResource: models.NPU,
  139. Cluster: models.OpenICluster,
  140. AiCenterCode: aiCenterCode,
  141. })
  142. ctx.Data["Specs"] = noteBookSpecs
  143. }
  144. func Notebook2Create(ctx *context.Context, form auth.CreateModelArtsNotebookForm) {
  145. ctx.Data["PageIsNotebook"] = true
  146. displayJobName := form.DisplayJobName
  147. jobName := util.ConvertDisplayJobNameToJobName(displayJobName)
  148. uuid := form.Attachment
  149. description := form.Description
  150. imageId := form.ImageId
  151. repo := ctx.Repo.Repository
  152. lock := redis_lock.NewDistributeLock(redis_key.CloudbrainBindingJobNameKey(fmt.Sprint(repo.ID), string(models.JobTypeDebug), displayJobName))
  153. isOk, err := lock.Lock(models.CloudbrainKeyDuration)
  154. if !isOk {
  155. log.Error("lock processed failed:%v", err, ctx.Data["MsgID"])
  156. notebookNewDataPrepare(ctx)
  157. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_samejob_err"), tplModelArtsNotebookNew, &form)
  158. return
  159. }
  160. defer lock.UnLock()
  161. count, err := cloudbrainTask.GetNotFinalStatusTaskCount(ctx.User.ID, models.TypeCloudBrainTwo, string(models.JobTypeDebug))
  162. if err != nil {
  163. log.Error("GetCloudbrainNotebookCountByUserID failed:%v", err, ctx.Data["MsgID"])
  164. notebookNewDataPrepare(ctx)
  165. ctx.RenderWithErr("system error", tplModelArtsNotebookNew, &form)
  166. return
  167. } else {
  168. if count >= 1 {
  169. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  170. notebookNewDataPrepare(ctx)
  171. ctx.RenderWithErr("you have already a running or waiting task, can not create more", tplModelArtsNotebookNew, &form)
  172. return
  173. }
  174. }
  175. tasks, err := models.GetCloudbrainsByDisplayJobName(repo.ID, string(models.JobTypeDebug), displayJobName)
  176. if err == nil {
  177. if len(tasks) != 0 {
  178. log.Error("the job name did already exist", ctx.Data["MsgID"])
  179. notebookNewDataPrepare(ctx)
  180. ctx.RenderWithErr("the job name did already exist", tplModelArtsNotebookNew, &form)
  181. return
  182. }
  183. } else {
  184. if !models.IsErrJobNotExist(err) {
  185. log.Error("system error, %v", err, ctx.Data["MsgID"])
  186. notebookNewDataPrepare(ctx)
  187. ctx.RenderWithErr("system error", tplModelArtsNotebookNew, &form)
  188. return
  189. }
  190. }
  191. var datasetInfos map[string]models.DatasetInfo
  192. var attachSize int
  193. if uuid != "" {
  194. datasetInfos, _, err = models.GetDatasetInfo(uuid)
  195. for _, infos := range datasetInfos {
  196. attachSize += infos.Size
  197. }
  198. if attachSize > int(setting.DebugAttachSize * 1024 * 1024 * 1024) {
  199. log.Error("The DatasetSize exceeds the limit (%d)", int(setting.DebugAttachSize)) //GB
  200. notebookNewDataPrepare(ctx)
  201. ctx.RenderWithErr(ctx.Tr("cloudbrain.error.debug_datasetsize"), tplModelArtsNotebookNew, &form)
  202. return
  203. }
  204. }
  205. var aiCenterCode = models.AICenterOfCloudBrainTwo
  206. if setting.ModelartsCD.Enabled {
  207. aiCenterCode = models.AICenterOfChengdu
  208. }
  209. spec, err := resource.GetAndCheckSpec(ctx.User.ID, form.SpecId, models.FindSpecsOptions{
  210. JobType: models.JobTypeDebug,
  211. ComputeResource: models.NPU,
  212. Cluster: models.OpenICluster,
  213. AiCenterCode: aiCenterCode})
  214. if err != nil || spec == nil {
  215. notebookNewDataPrepare(ctx)
  216. ctx.RenderWithErr("Resource specification not available", tplModelArtsNotebookNew, &form)
  217. return
  218. }
  219. if !account.IsPointBalanceEnough(ctx.User.ID, spec.UnitPrice) {
  220. log.Error("point balance is not enough,userId=%d specId=%d ", ctx.User.ID, spec.ID)
  221. notebookNewDataPrepare(ctx)
  222. ctx.RenderWithErr(ctx.Tr("points.insufficient_points_balance"), tplModelArtsNotebookNew, &form)
  223. return
  224. }
  225. if setting.ModelartsCD.Enabled {
  226. _, err = modelarts_cd.GenerateNotebook(ctx, displayJobName, jobName, uuid, description, imageId, spec, "", modelarts.AutoStopDurationMs)
  227. } else {
  228. _, err = modelarts.GenerateNotebook2(ctx, displayJobName, jobName, uuid, description, imageId, spec, "", modelarts.AutoStopDurationMs)
  229. }
  230. if err != nil {
  231. log.Error("GenerateNotebook2 failed, %v", err, ctx.Data["MsgID"])
  232. notebookNewDataPrepare(ctx)
  233. ctx.RenderWithErr(err.Error(), tplModelArtsNotebookNew, &form)
  234. return
  235. }
  236. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/debugjob?debugListType=all")
  237. }
  238. func NotebookShow(ctx *context.Context) {
  239. ctx.Data["PageIsCloudBrain"] = true
  240. debugListType := ctx.Query("debugListType")
  241. if debugListType == "" {
  242. debugListType = "all"
  243. }
  244. var ID = ctx.Params(":id")
  245. task, err := models.GetCloudbrainByIDWithDeleted(ID)
  246. if err != nil {
  247. log.Error("GET job error", err.Error())
  248. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  249. return
  250. }
  251. if task.DeletedAt.IsZero() { //normal record
  252. err := modelarts.HandleNotebookInfo(task)
  253. if err != nil {
  254. ctx.Data["error"] = err.Error()
  255. ctx.RenderWithErr(err.Error(), tplModelArtsNotebookShow, nil)
  256. return
  257. }
  258. } else { //deleted record
  259. }
  260. datasetDownload := make([]models.DatasetDownload, 0)
  261. if ctx.IsSigned {
  262. if task.Uuid != "" && task.UserID == ctx.User.ID {
  263. datasetDownload = GetCloudBrainDataSetInfo(task.Uuid, task.DatasetName, true)
  264. }
  265. }
  266. user, err := models.GetUserByID(task.UserID)
  267. if err == nil {
  268. task.User = user
  269. }
  270. prepareSpec4Show(ctx, task)
  271. if task.TrainJobDuration == "" {
  272. if task.Duration == 0 {
  273. var duration int64
  274. if task.Status == string(models.JobRunning) {
  275. duration = time.Now().Unix() - int64(task.CreatedUnix)
  276. } else {
  277. duration = int64(task.UpdatedUnix) - int64(task.CreatedUnix)
  278. }
  279. task.Duration = duration
  280. }
  281. task.TrainJobDuration = models.ConvertDurationToStr(task.Duration)
  282. }
  283. ctx.Data["duration"] = task.TrainJobDuration
  284. ctx.Data["datasetDownload"] = datasetDownload
  285. ctx.Data["task"] = task
  286. ctx.Data["ID"] = ID
  287. ctx.Data["jobName"] = task.JobName
  288. ctx.Data["debugListType"] = debugListType
  289. ctx.HTML(200, tplModelArtsNotebookShow)
  290. }
  291. func GetCloudBrainDataSetInfo(uuid string, datasetname string, isNeedDown bool) []models.DatasetDownload {
  292. datasetDownload := make([]models.DatasetDownload, 0)
  293. if len(uuid) == 0 {
  294. return datasetDownload
  295. }
  296. uuidList := strings.Split(uuid, ";")
  297. datasetnameList := strings.Split(datasetname, ";")
  298. for i, uuidStr := range uuidList {
  299. name := ""
  300. link := ""
  301. url := ""
  302. isDelete := false
  303. attachment, err := models.GetAttachmentByUUID(uuidStr)
  304. if err != nil {
  305. log.Error("GetAttachmentByUUID failed:%v", err.Error())
  306. if len(datasetnameList) <= i || len(datasetname) == 0 {
  307. continue
  308. }
  309. name = datasetnameList[i]
  310. isDelete = true
  311. } else {
  312. name = attachment.Name
  313. dataset, err := models.GetDatasetByID(attachment.DatasetID)
  314. if err != nil {
  315. log.Error("GetDatasetByID failed:%v", err.Error())
  316. } else {
  317. repo, err := models.GetRepositoryByID(dataset.RepoID)
  318. if err != nil {
  319. log.Error("GetRepositoryByID failed:%v", err.Error())
  320. } else {
  321. link = repo.Link() + "/datasets"
  322. }
  323. }
  324. if isNeedDown {
  325. url = attachment.S3DownloadURL()
  326. }
  327. }
  328. datasetDownload = append(datasetDownload, models.DatasetDownload{
  329. DatasetName: name,
  330. DatasetDownloadLink: url,
  331. RepositoryLink: link,
  332. IsDelete: isDelete,
  333. })
  334. }
  335. log.Info("dataset length=" + fmt.Sprint(len(datasetDownload)))
  336. return datasetDownload
  337. }
  338. func setShowSpecBySpecialPoolConfig(ctx *context.Context, findSpec bool, task *models.Cloudbrain) {
  339. modelarts.InitSpecialPool()
  340. if modelarts.SpecialPools != nil && !findSpec {
  341. for _, pool := range modelarts.SpecialPools.Pools {
  342. for _, flavor := range pool.Flavor {
  343. if flavor.Value == task.FlavorCode {
  344. ctx.Data["resource_spec"] = flavor.Desc
  345. }
  346. }
  347. }
  348. }
  349. }
  350. func NotebookDebug2(ctx *context.Context) {
  351. var err error
  352. var result *models.GetNotebook2Result
  353. task := ctx.Cloudbrain
  354. if task.Type == models.TypeCloudBrainTwo {
  355. result, err = modelarts.GetNotebook2(task.JobID)
  356. } else if task.Type == models.TypeCDCenter {
  357. result, err = modelarts_cd.GetNotebook(task.JobID)
  358. }
  359. if err != nil {
  360. ctx.RenderWithErr(err.Error(), tplModelArtsNotebookIndex, nil)
  361. return
  362. }
  363. if task.BootFile != "" {
  364. ctx.Redirect(getFileUrl(result.Url, task.BootFile) + "?token=" + result.Token)
  365. } else {
  366. ctx.Redirect(result.Url + "?token=" + result.Token)
  367. }
  368. }
  369. func getFileUrl(url string, filename string) string {
  370. middle := ""
  371. if url[len(url)-3:] == "lab" || url[len(url)-4:] == "lab/" {
  372. if url[len(url)-1] == '/' {
  373. middle = "tree/"
  374. } else {
  375. middle = "/tree/"
  376. }
  377. } else {
  378. if url[len(url)-1] == '/' {
  379. middle = "lab/tree/"
  380. } else {
  381. middle = "/lab/tree/"
  382. }
  383. }
  384. return url + middle + path.Base(filename)
  385. }
  386. func NotebookRestart(ctx *context.Context) {
  387. var id = ctx.Params(":id")
  388. var resultCode = "-1"
  389. var errorMsg = ""
  390. var status = ""
  391. var spec *models.Specification
  392. task := ctx.Cloudbrain
  393. for {
  394. ctx.CheckWechatBind()
  395. if ctx.Written() {
  396. return
  397. }
  398. if task.Status != string(models.ModelArtsStopped) && task.Status != string(models.ModelArtsStartFailed) && task.Status != string(models.ModelArtsCreateFailed) {
  399. log.Error("the job(%s) is not stopped", task.JobName, ctx.Data["MsgID"])
  400. errorMsg = "the job is not stopped"
  401. break
  402. }
  403. count, err := cloudbrainTask.GetNotFinalStatusTaskCount(ctx.User.ID, models.TypeCloudBrainTwo, string(models.JobTypeDebug))
  404. if err != nil {
  405. log.Error("GetCloudbrainNotebookCountByUserID failed:%v", err, ctx.Data["MsgID"])
  406. errorMsg = "system error"
  407. break
  408. } else {
  409. if count >= 1 {
  410. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  411. resultCode = "2"
  412. errorMsg = ctx.Tr("repo.cloudbrain.morethanonejob")
  413. break
  414. }
  415. }
  416. oldSpec, err := resource.GetCloudbrainSpec(task.ID)
  417. if err != nil || oldSpec == nil {
  418. log.Error("NotebookManage GetCloudbrainSpec error.%v", err)
  419. errorMsg = "Resource specification not available"
  420. break
  421. }
  422. aiCenterCode := models.AICenterOfCloudBrainTwo
  423. if task.Type == models.TypeCDCenter {
  424. aiCenterCode = models.AICenterOfChengdu
  425. }
  426. spec, err = resource.GetAndCheckSpec(ctx.User.ID, oldSpec.ID, models.FindSpecsOptions{
  427. JobType: models.JobType(task.JobType),
  428. ComputeResource: models.NPU,
  429. Cluster: models.OpenICluster,
  430. AiCenterCode: aiCenterCode})
  431. if err != nil || spec == nil {
  432. log.Error("NotebookManage GetAndCheckSpec error.task.id = %d", task.ID)
  433. errorMsg = "Resource specification not support any more"
  434. break
  435. }
  436. if !account.IsPointBalanceEnough(ctx.User.ID, spec.UnitPrice) {
  437. log.Error("point balance is not enough,userId=%d specId=%d", ctx.User.ID, spec.ID)
  438. errorMsg = ctx.Tr("points.insufficient_points_balance")
  439. break
  440. }
  441. createTime := timeutil.TimeStampNow()
  442. param := models.NotebookAction{
  443. Action: models.ActionStart,
  444. }
  445. var res *models.NotebookActionResult
  446. if task.Type == models.TypeCloudBrainTwo {
  447. res, err = modelarts.ManageNotebook2(task.JobID, param)
  448. } else if task.Type == models.TypeCDCenter {
  449. res, err = modelarts_cd.ManageNotebook(task.JobID, param)
  450. }
  451. if err != nil {
  452. log.Error("ManageNotebook2(%s) failed:%v", task.DisplayJobName, err.Error(), ctx.Data["MsgID"])
  453. /* 暂不处理再次调试502的场景,详情见方案
  454. if strings.HasPrefix(err.Error(), modelarts.UnknownErrorPrefix) {
  455. log.Info("(%s)unknown error, set temp status", task.DisplayJobName)
  456. errTemp := models.InsertCloudbrainTemp(&models.CloudbrainTemp{
  457. JobID: task.JobID,
  458. VersionID: models.TempVersionId,
  459. Status: models.TempJobStatus,
  460. Type: task.Type,
  461. JobName: task.JobName,
  462. JobType: task.JobType,
  463. })
  464. if errTemp != nil {
  465. log.Error("InsertCloudbrainTemp failed: %v", errTemp.Error())
  466. }
  467. }
  468. */
  469. errorMsg = err.Error()
  470. break
  471. }
  472. newTask := &models.Cloudbrain{
  473. Status: res.Status,
  474. UserID: task.UserID,
  475. RepoID: task.RepoID,
  476. JobID: task.JobID,
  477. JobName: task.JobName,
  478. DisplayJobName: task.DisplayJobName,
  479. JobType: task.JobType,
  480. Type: task.Type,
  481. Uuid: task.Uuid,
  482. Image: task.Image,
  483. ComputeResource: task.ComputeResource,
  484. Description: task.Description,
  485. CreatedUnix: createTime,
  486. UpdatedUnix: createTime,
  487. Spec: spec,
  488. }
  489. err = models.RestartCloudbrain(task, newTask)
  490. if err != nil {
  491. log.Error("RestartCloudbrain(%s) failed:%v", task.JobName, err.Error(), ctx.Data["MsgID"])
  492. errorMsg = "system error"
  493. break
  494. }
  495. id = strconv.FormatInt(newTask.ID, 10)
  496. status = res.Status
  497. resultCode = "0"
  498. notification.NotifyOtherTask(ctx.User, ctx.Repo.Repository, id, newTask.DisplayJobName, models.ActionCreateDebugNPUTask)
  499. break
  500. }
  501. ctx.JSON(200, map[string]string{
  502. "result_code": resultCode,
  503. "error_msg": errorMsg,
  504. "status": status,
  505. "id": id,
  506. })
  507. }
  508. func NotebookStop(ctx *context.Context) {
  509. var id = ctx.Params(":id")
  510. var resultCode = "0"
  511. var errorMsg = ""
  512. var status = ""
  513. task := ctx.Cloudbrain
  514. for {
  515. if task.Status != string(models.ModelArtsRunning) {
  516. log.Error("the job(%s) is not running", task.JobName, ctx.Data["MsgID"])
  517. resultCode = "-1"
  518. errorMsg = "the job is not running"
  519. break
  520. }
  521. param := models.NotebookAction{
  522. Action: models.ActionStop,
  523. }
  524. var err error
  525. var res *models.NotebookActionResult
  526. if task.Type == models.TypeCloudBrainTwo {
  527. res, err = modelarts.ManageNotebook2(task.JobID, param)
  528. } else if task.Type == models.TypeCDCenter {
  529. res, err = modelarts_cd.ManageNotebook(task.JobID, param)
  530. }
  531. if err != nil {
  532. log.Error("ManageNotebook2(%s) failed:%v", task.JobName, err.Error(), ctx.Data["MsgID"])
  533. resultCode = "-1"
  534. errorMsg = err.Error()
  535. if strings.Contains(err.Error(), modelarts.NotebookNotFound) {
  536. errorMsg = "the job's version is too old and can not be restarted"
  537. }
  538. break
  539. }
  540. status = res.Status
  541. oldStatus := task.Status
  542. task.Status = res.Status
  543. if task.EndTime == 0 && models.IsModelArtsDebugJobTerminal(task.Status) {
  544. task.EndTime = timeutil.TimeStampNow()
  545. }
  546. task.ComputeAndSetDuration()
  547. if oldStatus != task.Status {
  548. notification.NotifyChangeCloudbrainStatus(task, oldStatus)
  549. }
  550. err = models.UpdateJob(task)
  551. if err != nil {
  552. log.Error("UpdateJob(%s) failed:%v", task.JobName, err.Error(), ctx.Data["MsgID"])
  553. resultCode = "-1"
  554. errorMsg = "system error"
  555. break
  556. }
  557. break
  558. }
  559. ctx.JSON(200, map[string]string{
  560. "result_code": resultCode,
  561. "error_msg": errorMsg,
  562. "status": status,
  563. "id": id,
  564. })
  565. }
  566. func NotebookDel(ctx *context.Context) {
  567. var listType = ctx.Query("debugListType")
  568. task := ctx.Cloudbrain
  569. if task.Status != string(models.ModelArtsCreateFailed) && task.Status != string(models.ModelArtsStartFailed) && task.Status != string(models.ModelArtsStopped) && task.Status != string(models.ModelArtsDeleted) {
  570. log.Error("the job(%s) has not been stopped", task.JobName)
  571. ctx.RenderWithErr("the job has not been stopped", tplDebugJobIndex, nil)
  572. return
  573. }
  574. var err error
  575. if task.Type == models.TypeCloudBrainTwo {
  576. _, err = modelarts.DelNotebook2(task.JobID)
  577. } else if task.Type == models.TypeCDCenter {
  578. _, err = modelarts_cd.DelNotebook(task.JobID)
  579. }
  580. if err != nil {
  581. log.Error("DelNotebook2(%s) failed:%v", task.JobName, err.Error())
  582. if strings.Contains(err.Error(), modelarts.NotebookNotFound) || strings.Contains(err.Error(), modelarts.NotebookNoPermission) || strings.Contains(err.Error(), modelarts.NotebookInvalid) {
  583. log.Info("old notebook version")
  584. } else {
  585. ctx.RenderWithErr(err.Error(), tplDebugJobIndex, nil)
  586. return
  587. }
  588. }
  589. err = models.DeleteJob(task)
  590. if err != nil {
  591. ctx.RenderWithErr(err.Error(), tplDebugJobIndex, nil)
  592. return
  593. }
  594. var isAdminPage = ctx.Query("isadminpage")
  595. var isHomePage = ctx.Query("ishomepage")
  596. if ctx.IsUserSiteAdmin() && isAdminPage == "true" {
  597. ctx.Redirect(setting.AppSubURL + "/admin" + "/cloudbrains")
  598. } else if isHomePage == "true" {
  599. ctx.Redirect(setting.AppSubURL + "/cloudbrains")
  600. } else {
  601. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/debugjob?debugListType=" + listType)
  602. }
  603. }
  604. func TrainJobIndex(ctx *context.Context) {
  605. MustEnableModelArts(ctx)
  606. repo := ctx.Repo.Repository
  607. page := ctx.QueryInt("page")
  608. if page <= 0 {
  609. page = 1
  610. }
  611. listType := ctx.Query("listType")
  612. ctx.Data["ListType"] = listType
  613. if listType == models.AllResource {
  614. listType = ""
  615. }
  616. var jobTypes []string
  617. jobTypes = append(jobTypes, string(models.JobTypeTrain))
  618. tasks, count, err := models.Cloudbrains(&models.CloudbrainsOptions{
  619. ListOptions: models.ListOptions{
  620. Page: page,
  621. PageSize: setting.UI.IssuePagingNum,
  622. },
  623. RepoID: repo.ID,
  624. JobTypeNot: false,
  625. JobTypes: jobTypes,
  626. IsLatestVersion: modelarts.IsLatestVersion,
  627. ComputeResource: listType,
  628. Type: models.TypeCloudBrainAll,
  629. })
  630. if err != nil {
  631. ctx.ServerError("Cloudbrain", err)
  632. return
  633. }
  634. for i, task := range tasks {
  635. tasks[i].CanDel = cloudbrain.CanDeleteJob(ctx, &task.Cloudbrain)
  636. tasks[i].CanModify = cloudbrain.CanModifyJob(ctx, &task.Cloudbrain)
  637. }
  638. pager := context.NewPagination(int(count), setting.UI.IssuePagingNum, page, 5)
  639. pager.SetDefaultParams(ctx)
  640. pager.AddParam(ctx, "listType", "ListType")
  641. ctx.Data["Page"] = pager
  642. ctx.Data["PageIsCloudBrain"] = true
  643. ctx.Data["Tasks"] = tasks
  644. ctx.Data["CanCreate"] = cloudbrain.CanCreateOrDebugJob(ctx)
  645. ctx.Data["RepoIsEmpty"] = repo.IsEmpty
  646. ctx.HTML(200, tplModelArtsTrainJobIndex)
  647. }
  648. func TrainJobNew(ctx *context.Context) {
  649. err := trainJobNewDataPrepare(ctx)
  650. if err != nil {
  651. ctx.ServerError("get new train-job info failed", err)
  652. return
  653. }
  654. ctx.HTML(200, tplModelArtsTrainJobNew)
  655. }
  656. func trainJobNewDataPrepare(ctx *context.Context) error {
  657. ctx.Data["PageIsCloudBrain"] = true
  658. //can, err := canUserCreateTrainJob(ctx.User.ID)
  659. //if err != nil {
  660. // ctx.ServerError("canUserCreateTrainJob", err)
  661. // return
  662. //}
  663. //
  664. //if !can {
  665. // log.Error("the user can not create train-job")
  666. // ctx.ServerError("the user can not create train-job", fmt.Errorf("the user can not create train-job"))
  667. // return
  668. //}
  669. var displayJobName = cloudbrainService.GetDisplayJobName(ctx.User.Name)
  670. ctx.Data["display_job_name"] = displayJobName
  671. attachs, err := models.GetModelArtsTrainAttachments(ctx.User.ID)
  672. if err != nil {
  673. ctx.ServerError("GetAllUserAttachments failed:", err)
  674. return err
  675. }
  676. ctx.Data["attachments"] = attachs
  677. var resourcePools modelarts.ResourcePool
  678. if err = json.Unmarshal([]byte(setting.ResourcePools), &resourcePools); err != nil {
  679. ctx.ServerError("json.Unmarshal failed:", err)
  680. return err
  681. }
  682. ctx.Data["resource_pools"] = resourcePools.Info
  683. var engines modelarts.Engine
  684. if err = json.Unmarshal([]byte(setting.Engines), &engines); err != nil {
  685. ctx.ServerError("json.Unmarshal failed:", err)
  686. return err
  687. }
  688. ctx.Data["engines"] = engines.Info
  689. var versionInfos modelarts.VersionInfo
  690. if err = json.Unmarshal([]byte(setting.EngineVersions), &versionInfos); err != nil {
  691. ctx.ServerError("json.Unmarshal failed:", err)
  692. return err
  693. }
  694. ctx.Data["engine_versions"] = versionInfos.Version
  695. prepareCloudbrainTwoTrainSpecs(ctx)
  696. ctx.Data["params"] = ""
  697. ctx.Data["branchName"] = ctx.Repo.BranchName
  698. configList, err := getConfigList(modelarts.PerPage, 1, modelarts.SortByCreateTime, "desc", "", modelarts.ConfigTypeCustom)
  699. if err != nil {
  700. ctx.ServerError("getConfigList failed:", err)
  701. return err
  702. }
  703. ctx.Data["config_list"] = configList.ParaConfigs
  704. ctx.Data["datasetType"] = models.TypeCloudBrainTwo
  705. waitCount := cloudbrain.GetWaitingCloudbrainCount(models.TypeCloudBrainTwo, "")
  706. ctx.Data["WaitCount"] = waitCount
  707. NotStopTaskCount, _ := cloudbrainTask.GetNotFinalStatusTaskCount(ctx.User.ID, models.TypeCloudBrainTwo, string(models.JobTypeTrain))
  708. ctx.Data["NotStopTaskCount"] = NotStopTaskCount
  709. setMultiNodeIfConfigureMatch(ctx)
  710. return nil
  711. }
  712. func prepareCloudbrainTwoTrainSpecs(ctx *context.Context) {
  713. noteBookSpecs, _ := resource.FindAvailableSpecs(ctx.User.ID, models.FindSpecsOptions{
  714. JobType: models.JobTypeTrain,
  715. ComputeResource: models.NPU,
  716. Cluster: models.OpenICluster,
  717. AiCenterCode: models.AICenterOfCloudBrainTwo,
  718. })
  719. ctx.Data["Specs"] = noteBookSpecs
  720. }
  721. func setMultiNodeIfConfigureMatch(ctx *context.Context) {
  722. modelarts.InitMultiNode()
  723. if modelarts.MultiNodeConfig != nil {
  724. for _, info := range modelarts.MultiNodeConfig.Info {
  725. if isInOrg, _ := models.IsOrganizationMemberByOrgName(info.Org, ctx.User.ID); isInOrg {
  726. ctx.Data["WorkNode"] = info.Node
  727. break
  728. }
  729. }
  730. }
  731. }
  732. func setSpecBySpecialPoolConfig(ctx *context.Context, jobType string) {
  733. modelarts.InitSpecialPool()
  734. if modelarts.SpecialPools != nil {
  735. for _, specialPool := range modelarts.SpecialPools.Pools {
  736. if cloudbrain.IsElementExist(specialPool.JobType, jobType) {
  737. if isInOrg, _ := models.IsOrganizationMemberByOrgName(specialPool.Org, ctx.User.ID); isInOrg {
  738. var specialFlavor []struct {
  739. Code string
  740. Value string
  741. }
  742. if jobType == string(models.JobTypeDebug) {
  743. ctx.Data["flavors"] = specialPool.Flavor
  744. } else {
  745. for _, tempFlavor := range specialPool.Flavor {
  746. specialFlavor = append(specialFlavor, struct {
  747. Code string
  748. Value string
  749. }{Code: tempFlavor.Value, Value: tempFlavor.Desc})
  750. }
  751. ctx.Data["flavor_infos"] = specialFlavor
  752. }
  753. }
  754. }
  755. }
  756. }
  757. }
  758. func TrainJobNewVersion(ctx *context.Context) {
  759. err := trainJobNewVersionDataPrepare(ctx)
  760. if err != nil {
  761. ctx.ServerError("get new train-job info failed", err)
  762. return
  763. }
  764. ctx.HTML(200, tplModelArtsTrainJobVersionNew)
  765. }
  766. func trainJobNewVersionDataPrepare(ctx *context.Context) error {
  767. ctx.Data["PageIsCloudBrain"] = true
  768. var jobID = ctx.Params(":jobid")
  769. var versionName = ctx.Query("version_name")
  770. // canNewJob, err := canUserCreateTrainJobVersion(ctx, jobID, versionName)
  771. // if err != nil {
  772. // ctx.ServerError("canNewJob can info failed", err)
  773. // return err
  774. // }
  775. task, err := models.GetCloudbrainByJobIDAndVersionName(jobID, versionName)
  776. if err != nil {
  777. log.Error("GetCloudbrainByJobIDAndVersionName(%s) failed:%v", jobID, err.Error())
  778. return err
  779. }
  780. ctx.Data["display_job_name"] = task.DisplayJobName
  781. ctx.Data["job_name"] = task.JobName
  782. // attachs, err := models.GetModelArtsTrainAttachments(ctx.User.ID)
  783. // if err != nil {
  784. // ctx.ServerError("GetAllUserAttachments failed:", err)
  785. // return err
  786. // }
  787. // ctx.Data["attachments"] = attachs
  788. var resourcePools modelarts.ResourcePool
  789. if err = json.Unmarshal([]byte(setting.ResourcePools), &resourcePools); err != nil {
  790. ctx.ServerError("json.Unmarshal failed:", err)
  791. return err
  792. }
  793. ctx.Data["resource_pools"] = resourcePools.Info
  794. var engines modelarts.Engine
  795. if err = json.Unmarshal([]byte(setting.Engines), &engines); err != nil {
  796. ctx.ServerError("json.Unmarshal failed:", err)
  797. return err
  798. }
  799. ctx.Data["engines"] = engines.Info
  800. var versionInfos modelarts.VersionInfo
  801. if err = json.Unmarshal([]byte(setting.EngineVersions), &versionInfos); err != nil {
  802. ctx.ServerError("json.Unmarshal failed:", err)
  803. return err
  804. }
  805. ctx.Data["engine_versions"] = versionInfos.Version
  806. prepareCloudbrainTwoTrainSpecs(ctx)
  807. spec, _ := resource.GetCloudbrainSpec(task.ID)
  808. if spec != nil {
  809. log.Info("spec_id = %d", spec.ID)
  810. ctx.Data["spec_id"] = spec.ID
  811. }
  812. ctx.Data["run_para_list"] = task.Parameters
  813. branches, _, err := ctx.Repo.GitRepo.GetBranches(0, 0)
  814. if err != nil {
  815. ctx.ServerError("GetBranches error:", err)
  816. return err
  817. }
  818. uuids, datasetNames := dataset.GetFilterDeletedAttachments(task.Uuid)
  819. ctx.Data["dataset_name"] = datasetNames
  820. ctx.Data["branches"] = branches
  821. ctx.Data["branch_name"] = task.BranchName
  822. ctx.Data["description"] = task.Description
  823. ctx.Data["boot_file"] = task.BootFile
  824. ctx.Data["work_server_number"] = task.WorkServerNumber
  825. ctx.Data["flavor_name"] = task.FlavorName
  826. ctx.Data["engine_name"] = task.EngineName
  827. ctx.Data["attachment"] = uuids
  828. ctx.Data["flavor_code"] = task.FlavorCode
  829. ctx.Data["engine_id"] = task.EngineID
  830. ctx.Data["datasetType"] = models.TypeCloudBrainTwo
  831. //pretrain model
  832. ctx.Data["model_name"] = task.ModelName
  833. ctx.Data["model_version"] = task.ModelVersion
  834. ctx.Data["ckpt_name"] = task.CkptName
  835. ctx.Data["label_names"] = task.LabelName
  836. ctx.Data["pre_train_model_url"] = task.PreTrainModelUrl
  837. configList, err := getConfigList(modelarts.PerPage, 1, modelarts.SortByCreateTime, "desc", "", modelarts.ConfigTypeCustom)
  838. if err != nil {
  839. ctx.ServerError("getConfigList failed:", err)
  840. return err
  841. }
  842. ctx.Data["config_list"] = configList.ParaConfigs
  843. waitCount := cloudbrain.GetWaitingCloudbrainCount(models.TypeCloudBrainTwo, "")
  844. ctx.Data["WaitCount"] = waitCount
  845. NotStopTaskCount, _ := cloudbrainTask.GetNotFinalStatusTaskCount(ctx.User.ID, models.TypeCloudBrainTwo, string(models.JobTypeTrain))
  846. ctx.Data["NotStopTaskCount"] = NotStopTaskCount
  847. return nil
  848. }
  849. func TrainJobCreate(ctx *context.Context, form auth.CreateModelArtsTrainJobForm) {
  850. ctx.Data["PageIsTrainJob"] = true
  851. VersionOutputPath := modelarts.GetOutputPathByCount(modelarts.TotalVersionCount)
  852. displayJobName := form.DisplayJobName
  853. jobName := util.ConvertDisplayJobNameToJobName(displayJobName)
  854. uuid := form.Attachment
  855. description := form.Description
  856. workServerNumber := form.WorkServerNumber
  857. engineID := form.EngineID
  858. bootFile := strings.TrimSpace(form.BootFile)
  859. params := form.Params
  860. poolID := form.PoolID
  861. //isSaveParam := form.IsSaveParam
  862. repo := ctx.Repo.Repository
  863. codeLocalPath := setting.JobPath + jobName + modelarts.CodePath
  864. codeObsPath := "/" + setting.Bucket + modelarts.JobPath + jobName + modelarts.CodePath + VersionOutputPath + "/"
  865. outputObsPath := "/" + setting.Bucket + modelarts.JobPath + jobName + modelarts.OutputPath + VersionOutputPath + "/"
  866. logObsPath := "/" + setting.Bucket + modelarts.JobPath + jobName + modelarts.LogPath + VersionOutputPath + "/"
  867. // dataPath := "/" + setting.Bucket + "/" + setting.BasePath + path.Join(uuid[0:1], uuid[1:2]) + "/" + uuid + uuid + "/"
  868. branchName := form.BranchName
  869. isLatestVersion := modelarts.IsLatestVersion
  870. FlavorName := form.FlavorName
  871. VersionCount := modelarts.VersionCountOne
  872. EngineName := form.EngineName
  873. errStr := checkMultiNode(ctx.User.ID, form.WorkServerNumber)
  874. if errStr != "" {
  875. trainJobNewDataPrepare(ctx)
  876. ctx.RenderWithErr(ctx.Tr(errStr), tplModelArtsTrainJobNew, &form)
  877. return
  878. }
  879. lock := redis_lock.NewDistributeLock(redis_key.CloudbrainBindingJobNameKey(fmt.Sprint(repo.ID), string(models.JobTypeTrain), displayJobName))
  880. isOk, err := lock.Lock(models.CloudbrainKeyDuration)
  881. if !isOk {
  882. log.Error("lock processed failed:%v", err, ctx.Data["MsgID"])
  883. trainJobNewDataPrepare(ctx)
  884. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_samejob_err"), tplModelArtsTrainJobNew, &form)
  885. return
  886. }
  887. defer lock.UnLock()
  888. count, err := cloudbrainTask.GetNotFinalStatusTaskCount(ctx.User.ID, models.TypeCloudBrainTwo, string(models.JobTypeTrain))
  889. if err != nil {
  890. log.Error("GetCloudbrainTrainJobCountByUserID failed:%v", err, ctx.Data["MsgID"])
  891. trainJobNewDataPrepare(ctx)
  892. ctx.RenderWithErr("system error", tplModelArtsTrainJobNew, &form)
  893. return
  894. } else {
  895. if count >= 1 {
  896. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  897. trainJobNewDataPrepare(ctx)
  898. ctx.RenderWithErr("you have already a running or waiting task, can not create more", tplModelArtsTrainJobNew, &form)
  899. return
  900. }
  901. }
  902. if err := paramCheckCreateTrainJob(form); err != nil {
  903. log.Error("paramCheckCreateTrainJob failed:(%v)", err)
  904. trainJobNewDataPrepare(ctx)
  905. ctx.RenderWithErr(err.Error(), tplModelArtsTrainJobNew, &form)
  906. return
  907. }
  908. bootFileExist, err := ctx.Repo.FileExists(bootFile, branchName)
  909. if err != nil || !bootFileExist {
  910. log.Error("Get bootfile error:", err)
  911. trainJobNewDataPrepare(ctx)
  912. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_bootfile_err"), tplModelArtsTrainJobNew, &form)
  913. return
  914. }
  915. spec, err := resource.GetAndCheckSpec(ctx.User.ID, form.SpecId, models.FindSpecsOptions{
  916. JobType: models.JobTypeTrain,
  917. ComputeResource: models.NPU,
  918. Cluster: models.OpenICluster,
  919. AiCenterCode: models.AICenterOfCloudBrainTwo})
  920. if err != nil || spec == nil {
  921. trainJobNewDataPrepare(ctx)
  922. ctx.RenderWithErr("Resource specification not available", tplModelArtsTrainJobNew, &form)
  923. return
  924. }
  925. if !account.IsPointBalanceEnough(ctx.User.ID, spec.UnitPrice*form.WorkServerNumber) {
  926. log.Error("point balance is not enough,userId=%d specId=%d", ctx.User.ID, spec.ID)
  927. trainJobNewDataPrepare(ctx)
  928. ctx.RenderWithErr(ctx.Tr("points.insufficient_points_balance"), tplModelArtsTrainJobNew, &form)
  929. return
  930. }
  931. //Determine whether the task name of the task in the project is duplicated
  932. tasks, err := models.GetCloudbrainsByDisplayJobName(repo.ID, string(models.JobTypeTrain), displayJobName)
  933. if err == nil {
  934. if len(tasks) != 0 {
  935. log.Error("the job name did already exist", ctx.Data["MsgID"])
  936. trainJobNewDataPrepare(ctx)
  937. ctx.RenderWithErr("the job name did already exist", tplModelArtsTrainJobNew, &form)
  938. return
  939. }
  940. } else {
  941. if !models.IsErrJobNotExist(err) {
  942. log.Error("system error, %v", err, ctx.Data["MsgID"])
  943. trainJobNewDataPrepare(ctx)
  944. ctx.RenderWithErr("system error", tplModelArtsTrainJobNew, &form)
  945. return
  946. }
  947. }
  948. //todo: del the codeLocalPath
  949. _, err = ioutil.ReadDir(codeLocalPath)
  950. if err == nil {
  951. os.RemoveAll(codeLocalPath)
  952. }
  953. gitRepo, _ := git.OpenRepository(repo.RepoPath())
  954. commitID, _ := gitRepo.GetBranchCommitID(branchName)
  955. if err := downloadCode(repo, codeLocalPath, branchName); err != nil {
  956. log.Error("downloadCode failed, server timed out: %s (%v)", repo.FullName(), err)
  957. trainJobNewDataPrepare(ctx)
  958. ctx.RenderWithErr(ctx.Tr("cloudbrain.load_code_failed"), tplModelArtsTrainJobNew, &form)
  959. return
  960. }
  961. //todo: upload code (send to file_server todo this work?)
  962. if err := obsMkdir(setting.CodePathPrefix + jobName + modelarts.OutputPath + VersionOutputPath + "/"); err != nil {
  963. log.Error("Failed to obsMkdir_output: %s (%v)", repo.FullName(), err)
  964. trainJobNewDataPrepare(ctx)
  965. ctx.RenderWithErr("Failed to obsMkdir_output", tplModelArtsTrainJobNew, &form)
  966. return
  967. }
  968. if err := obsMkdir(setting.CodePathPrefix + jobName + modelarts.LogPath + VersionOutputPath + "/"); err != nil {
  969. log.Error("Failed to obsMkdir_log: %s (%v)", repo.FullName(), err)
  970. trainJobNewDataPrepare(ctx)
  971. ctx.RenderWithErr("Failed to obsMkdir_log", tplModelArtsTrainJobNew, &form)
  972. return
  973. }
  974. parentDir := VersionOutputPath + "/"
  975. if err := uploadCodeToObs(codeLocalPath, jobName, parentDir); err != nil {
  976. // if err := uploadCodeToObs(codeLocalPath, jobName, parentDir); err != nil {
  977. log.Error("Failed to uploadCodeToObs: %s (%v)", repo.FullName(), err)
  978. trainJobNewDataPrepare(ctx)
  979. ctx.RenderWithErr(ctx.Tr("cloudbrain.load_code_failed"), tplModelArtsTrainJobNew, &form)
  980. return
  981. }
  982. var parameters models.Parameters
  983. param := make([]models.Parameter, 0)
  984. existDeviceTarget := false
  985. if len(params) != 0 {
  986. err := json.Unmarshal([]byte(params), &parameters)
  987. if err != nil {
  988. log.Error("Failed to Unmarshal params: %s (%v)", params, err)
  989. trainJobNewDataPrepare(ctx)
  990. ctx.RenderWithErr("运行参数错误", tplModelArtsTrainJobNew, &form)
  991. return
  992. }
  993. for _, parameter := range parameters.Parameter {
  994. if parameter.Label == modelarts.DeviceTarget {
  995. existDeviceTarget = true
  996. }
  997. if parameter.Label != modelarts.TrainUrl && parameter.Label != modelarts.DataUrl {
  998. param = append(param, models.Parameter{
  999. Label: parameter.Label,
  1000. Value: parameter.Value,
  1001. })
  1002. }
  1003. }
  1004. }
  1005. if !existDeviceTarget {
  1006. param = append(param, models.Parameter{
  1007. Label: modelarts.DeviceTarget,
  1008. Value: modelarts.Ascend,
  1009. })
  1010. }
  1011. datasUrlList, dataUrl, datasetNames, isMultiDataset, err := getDatasUrlListByUUIDS(uuid)
  1012. if err != nil {
  1013. log.Error("Failed to getDatasUrlListByUUIDS: %v", err)
  1014. trainJobNewDataPrepare(ctx)
  1015. ctx.RenderWithErr("Failed to getDatasUrlListByUUIDS:"+err.Error(), tplModelArtsTrainJobNew, &form)
  1016. return
  1017. }
  1018. dataPath := dataUrl
  1019. jsondatas, err := json.Marshal(datasUrlList)
  1020. if err != nil {
  1021. log.Error("Failed to Marshal: %v", err)
  1022. trainJobNewDataPrepare(ctx)
  1023. ctx.RenderWithErr("json error:"+err.Error(), tplModelArtsTrainJobNew, &form)
  1024. return
  1025. }
  1026. if isMultiDataset {
  1027. param = append(param, models.Parameter{
  1028. Label: modelarts.MultiDataUrl,
  1029. Value: string(jsondatas),
  1030. })
  1031. }
  1032. if form.ModelName != "" { //使用预训练模型训练
  1033. ckptUrl := "/" + form.PreTrainModelUrl + form.CkptName
  1034. param = append(param, models.Parameter{
  1035. Label: modelarts.CkptUrl,
  1036. Value: "s3:/" + ckptUrl,
  1037. })
  1038. }
  1039. //save param config
  1040. // if isSaveParam == "on" {
  1041. // saveparams := append(param, models.Parameter{
  1042. // Label: modelarts.TrainUrl,
  1043. // Value: outputObsPath,
  1044. // }, models.Parameter{
  1045. // Label: modelarts.DataUrl,
  1046. // Value: dataPath,
  1047. // })
  1048. // if form.ParameterTemplateName == "" {
  1049. // log.Error("ParameterTemplateName is empty")
  1050. // trainJobNewDataPrepare(ctx)
  1051. // ctx.RenderWithErr("保存作业参数时,作业参数名称不能为空", tplModelArtsTrainJobNew, &form)
  1052. // return
  1053. // }
  1054. // _, err := modelarts.CreateTrainJobConfig(models.CreateConfigParams{
  1055. // ConfigName: form.ParameterTemplateName,
  1056. // Description: form.PrameterDescription,
  1057. // DataUrl: dataPath,
  1058. // AppUrl: codeObsPath,
  1059. // BootFileUrl: codeObsPath + bootFile,
  1060. // TrainUrl: outputObsPath,
  1061. // Flavor: models.Flavor{
  1062. // Code: flavorCode,
  1063. // },
  1064. // WorkServerNum: workServerNumber,
  1065. // EngineID: int64(engineID),
  1066. // LogUrl: logObsPath,
  1067. // PoolID: poolID,
  1068. // Parameter: saveparams,
  1069. // })
  1070. // if err != nil {
  1071. // log.Error("Failed to CreateTrainJobConfig: %v", err)
  1072. // trainJobErrorNewDataPrepare(ctx, form)
  1073. // ctx.RenderWithErr("保存作业参数失败:"+err.Error(), tplModelArtsTrainJobNew, &form)
  1074. // return
  1075. // }
  1076. // }
  1077. req := &modelarts.GenerateTrainJobReq{
  1078. JobName: jobName,
  1079. DisplayJobName: displayJobName,
  1080. DataUrl: dataPath,
  1081. Description: description,
  1082. CodeObsPath: codeObsPath,
  1083. BootFileUrl: codeObsPath + bootFile,
  1084. BootFile: bootFile,
  1085. TrainUrl: outputObsPath,
  1086. WorkServerNumber: workServerNumber,
  1087. EngineID: int64(engineID),
  1088. LogUrl: logObsPath,
  1089. PoolID: poolID,
  1090. Uuid: uuid,
  1091. Parameters: param,
  1092. CommitID: commitID,
  1093. IsLatestVersion: isLatestVersion,
  1094. BranchName: branchName,
  1095. Params: form.Params,
  1096. FlavorName: FlavorName,
  1097. EngineName: EngineName,
  1098. VersionCount: VersionCount,
  1099. TotalVersionCount: modelarts.TotalVersionCount,
  1100. DatasetName: datasetNames,
  1101. Spec: spec,
  1102. }
  1103. if form.ModelName != "" { //使用预训练模型训练
  1104. req.ModelName = form.ModelName
  1105. req.LabelName = form.LabelName
  1106. req.CkptName = form.CkptName
  1107. req.ModelVersion = form.ModelVersion
  1108. req.PreTrainModelUrl = form.PreTrainModelUrl
  1109. }
  1110. userCommand, userImageUrl := getUserCommand(engineID, req)
  1111. req.UserCommand = userCommand
  1112. req.UserImageUrl = userImageUrl
  1113. //将params转换Parameters.Parameter,出错时返回给前端
  1114. var Parameters modelarts.Parameters
  1115. if err := json.Unmarshal([]byte(params), &Parameters); err != nil {
  1116. ctx.ServerError("json.Unmarshal failed:", err)
  1117. return
  1118. }
  1119. _, err = modelarts.GenerateTrainJob(ctx, req)
  1120. if err != nil {
  1121. log.Error("GenerateTrainJob failed:%v", err.Error())
  1122. trainJobNewDataPrepare(ctx)
  1123. ctx.RenderWithErr(err.Error(), tplModelArtsTrainJobNew, &form)
  1124. return
  1125. }
  1126. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/train-job")
  1127. }
  1128. func checkMultiNode(userId int64, serverNum int) string {
  1129. if serverNum == 1 {
  1130. return ""
  1131. }
  1132. modelarts.InitMultiNode()
  1133. var isServerNumValid = false
  1134. if modelarts.MultiNodeConfig != nil {
  1135. for _, info := range modelarts.MultiNodeConfig.Info {
  1136. if isInOrg, _ := models.IsOrganizationMemberByOrgName(info.Org, userId); isInOrg {
  1137. if isInNodes(info.Node, serverNum) {
  1138. isServerNumValid = true
  1139. break
  1140. }
  1141. }
  1142. }
  1143. }
  1144. if isServerNumValid {
  1145. return ""
  1146. } else {
  1147. return "repo.modelarts.no_node_right"
  1148. }
  1149. }
  1150. func checkInferenceJobMultiNode(userId int64, serverNum int) string {
  1151. if serverNum == 1 {
  1152. return ""
  1153. }
  1154. return "repo.modelarts.no_node_right"
  1155. }
  1156. func isInNodes(nodes []int, num int) bool {
  1157. for _, node := range nodes {
  1158. if node == num {
  1159. return true
  1160. }
  1161. }
  1162. return false
  1163. }
  1164. func getUserCommand(engineId int, req *modelarts.GenerateTrainJobReq) (string, string) {
  1165. userImageUrl := ""
  1166. userCommand := ""
  1167. if engineId < 0 {
  1168. tmpCodeObsPath := strings.Trim(req.CodeObsPath, "/")
  1169. tmpCodeObsPaths := strings.Split(tmpCodeObsPath, "/")
  1170. lastCodeDir := "code"
  1171. if len(tmpCodeObsPaths) > 0 {
  1172. lastCodeDir = tmpCodeObsPaths[len(tmpCodeObsPaths)-1]
  1173. }
  1174. userCommand = "/bin/bash /home/work/run_train.sh 's3://" + req.CodeObsPath + "' '" + lastCodeDir + "/" + req.BootFile + "' '/tmp/log/train.log' --'data_url'='s3://" + req.DataUrl + "' --'train_url'='s3://" + req.TrainUrl + "'"
  1175. var versionInfos modelarts.VersionInfo
  1176. if err := json.Unmarshal([]byte(setting.EngineVersions), &versionInfos); err != nil {
  1177. log.Info("json parse err." + err.Error())
  1178. } else {
  1179. for _, engine := range versionInfos.Version {
  1180. if engine.ID == engineId {
  1181. userImageUrl = engine.Url
  1182. break
  1183. }
  1184. }
  1185. }
  1186. for _, param := range req.Parameters {
  1187. userCommand += " --'" + param.Label + "'='" + param.Value + "'"
  1188. }
  1189. return userCommand, userImageUrl
  1190. }
  1191. return userCommand, userImageUrl
  1192. }
  1193. func getInfJobUserCommand(engineId int, req *modelarts.GenerateInferenceJobReq) (string, string) {
  1194. userImageUrl := ""
  1195. userCommand := ""
  1196. if engineId < 0 {
  1197. tmpCodeObsPath := strings.Trim(req.CodeObsPath, "/")
  1198. tmpCodeObsPaths := strings.Split(tmpCodeObsPath, "/")
  1199. lastCodeDir := "code"
  1200. if len(tmpCodeObsPaths) > 0 {
  1201. lastCodeDir = tmpCodeObsPaths[len(tmpCodeObsPaths)-1]
  1202. }
  1203. userCommand = "/bin/bash /home/work/run_train.sh 's3://" + req.CodeObsPath + "' '" + lastCodeDir + "/" + req.BootFile + "' '/tmp/log/train.log' --'data_url'='s3://" + req.DataUrl + "' --'train_url'='s3://" + req.TrainUrl + "'"
  1204. var versionInfos modelarts.VersionInfo
  1205. if err := json.Unmarshal([]byte(setting.EngineVersions), &versionInfos); err != nil {
  1206. log.Info("json parse err." + err.Error())
  1207. } else {
  1208. for _, engine := range versionInfos.Version {
  1209. if engine.ID == engineId {
  1210. userImageUrl = engine.Url
  1211. break
  1212. }
  1213. }
  1214. }
  1215. for _, param := range req.Parameters {
  1216. userCommand += " --'" + param.Label + "'='" + param.Value + "'"
  1217. }
  1218. return userCommand, userImageUrl
  1219. }
  1220. return userCommand, userImageUrl
  1221. }
  1222. func TrainJobCreateVersion(ctx *context.Context, form auth.CreateModelArtsTrainJobForm) {
  1223. ctx.Data["PageIsTrainJob"] = true
  1224. var jobID = ctx.Params(":jobid")
  1225. errStr := checkMultiNode(ctx.User.ID, form.WorkServerNumber)
  1226. if errStr != "" {
  1227. trainJobNewVersionDataPrepare(ctx)
  1228. ctx.RenderWithErr(ctx.Tr(errStr), tplModelArtsTrainJobVersionNew, &form)
  1229. return
  1230. }
  1231. count, err := cloudbrainTask.GetNotFinalStatusTaskCount(ctx.User.ID, models.TypeCloudBrainTwo, string(models.JobTypeTrain))
  1232. if err != nil {
  1233. log.Error("GetCloudbrainTrainJobCountByUserID failed:%v", err, ctx.Data["MsgID"])
  1234. trainJobNewVersionDataPrepare(ctx)
  1235. ctx.RenderWithErr("system error", tplModelArtsTrainJobVersionNew, &form)
  1236. return
  1237. } else {
  1238. if count >= 1 {
  1239. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  1240. trainJobNewVersionDataPrepare(ctx)
  1241. ctx.RenderWithErr("you have already a running or waiting task, can not create more", tplModelArtsTrainJobVersionNew, &form)
  1242. return
  1243. }
  1244. }
  1245. latestTask, err := models.GetCloudbrainByJobIDAndIsLatestVersion(jobID, modelarts.IsLatestVersion)
  1246. if err != nil {
  1247. ctx.ServerError("GetCloudbrainByJobIDAndIsLatestVersion faild:", err)
  1248. return
  1249. }
  1250. VersionOutputPath := modelarts.GetOutputPathByCount(latestTask.TotalVersionCount + 1)
  1251. displayJobName := form.DisplayJobName
  1252. jobName := form.JobName
  1253. uuid := form.Attachment
  1254. description := form.Description
  1255. workServerNumber := form.WorkServerNumber
  1256. engineID := form.EngineID
  1257. bootFile := strings.TrimSpace(form.BootFile)
  1258. params := form.Params
  1259. poolID := form.PoolID
  1260. //isSaveParam := form.IsSaveParam
  1261. repo := ctx.Repo.Repository
  1262. codeLocalPath := setting.JobPath + jobName + modelarts.CodePath
  1263. codeObsPath := "/" + setting.Bucket + modelarts.JobPath + jobName + modelarts.CodePath + VersionOutputPath + "/"
  1264. outputObsPath := "/" + setting.Bucket + modelarts.JobPath + jobName + modelarts.OutputPath + VersionOutputPath + "/"
  1265. logObsPath := "/" + setting.Bucket + modelarts.JobPath + jobName + modelarts.LogPath + VersionOutputPath + "/"
  1266. // dataPath := "/" + setting.Bucket + "/" + setting.BasePath + path.Join(uuid[0:1], uuid[1:2]) + "/" + uuid + uuid + "/"
  1267. branchName := form.BranchName
  1268. PreVersionName := form.VersionName
  1269. FlavorName := form.FlavorName
  1270. EngineName := form.EngineName
  1271. isLatestVersion := modelarts.IsLatestVersion
  1272. lock := redis_lock.NewDistributeLock(redis_key.CloudbrainBindingJobNameKey(fmt.Sprint(repo.ID), string(models.JobTypeTrain), displayJobName))
  1273. isOk, err := lock.Lock(models.CloudbrainKeyDuration)
  1274. if !isOk {
  1275. log.Error("lock processed failed:%v", err, ctx.Data["MsgID"])
  1276. trainJobNewVersionDataPrepare(ctx)
  1277. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_samejob_err"), tplModelArtsTrainJobVersionNew, &form)
  1278. return
  1279. }
  1280. defer lock.UnLock()
  1281. canNewJob, _ := canUserCreateTrainJobVersion(ctx, latestTask.UserID)
  1282. if !canNewJob {
  1283. trainJobNewVersionDataPrepare(ctx)
  1284. ctx.RenderWithErr("user cann't new trainjob", tplModelArtsTrainJobVersionNew, &form)
  1285. return
  1286. }
  1287. if err := paramCheckCreateTrainJob(form); err != nil {
  1288. log.Error("paramCheckCreateTrainJob failed:(%v)", err)
  1289. trainJobNewVersionDataPrepare(ctx)
  1290. ctx.RenderWithErr(err.Error(), tplModelArtsTrainJobVersionNew, &form)
  1291. return
  1292. }
  1293. bootFileExist, err := ctx.Repo.FileExists(bootFile, branchName)
  1294. if err != nil || !bootFileExist {
  1295. log.Error("Get bootfile error:", err)
  1296. trainJobNewVersionDataPrepare(ctx)
  1297. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_bootfile_err"), tplModelArtsTrainJobVersionNew, &form)
  1298. return
  1299. }
  1300. spec, err := resource.GetAndCheckSpec(ctx.User.ID, form.SpecId, models.FindSpecsOptions{
  1301. JobType: models.JobTypeTrain,
  1302. ComputeResource: models.NPU,
  1303. Cluster: models.OpenICluster,
  1304. AiCenterCode: models.AICenterOfCloudBrainTwo})
  1305. if err != nil || spec == nil {
  1306. trainJobNewVersionDataPrepare(ctx)
  1307. ctx.RenderWithErr("Resource specification not available", tplModelArtsTrainJobVersionNew, &form)
  1308. return
  1309. }
  1310. if !account.IsPointBalanceEnough(ctx.User.ID, spec.UnitPrice) {
  1311. log.Error("point balance is not enough,userId=%d specId=%d", ctx.User.ID, spec.ID)
  1312. trainJobNewVersionDataPrepare(ctx)
  1313. ctx.RenderWithErr(ctx.Tr("points.insufficient_points_balance"), tplModelArtsTrainJobVersionNew, &form)
  1314. return
  1315. }
  1316. //todo: del the codeLocalPath
  1317. _, err = ioutil.ReadDir(codeLocalPath)
  1318. if err == nil {
  1319. os.RemoveAll(codeLocalPath)
  1320. }
  1321. gitRepo, _ := git.OpenRepository(repo.RepoPath())
  1322. commitID, _ := gitRepo.GetBranchCommitID(branchName)
  1323. if err := downloadCode(repo, codeLocalPath, branchName); err != nil {
  1324. log.Error("Failed git clone repo to local(!: %s (%v)", repo.FullName(), err)
  1325. trainJobNewVersionDataPrepare(ctx)
  1326. ctx.RenderWithErr(ctx.Tr("cloudbrain.load_code_failed"), tplModelArtsTrainJobVersionNew, &form)
  1327. return
  1328. }
  1329. //todo: upload code (send to file_server todo this work?)
  1330. if err := obsMkdir(setting.CodePathPrefix + jobName + modelarts.OutputPath + VersionOutputPath + "/"); err != nil {
  1331. log.Error("Failed to obsMkdir_output: %s (%v)", repo.FullName(), err)
  1332. trainJobNewVersionDataPrepare(ctx)
  1333. ctx.RenderWithErr("Failed to obsMkdir_output", tplModelArtsTrainJobVersionNew, &form)
  1334. return
  1335. }
  1336. if err := obsMkdir(setting.CodePathPrefix + jobName + modelarts.LogPath + VersionOutputPath + "/"); err != nil {
  1337. log.Error("Failed to obsMkdir_log: %s (%v)", repo.FullName(), err)
  1338. trainJobNewVersionDataPrepare(ctx)
  1339. ctx.RenderWithErr("Failed to obsMkdir_log", tplModelArtsTrainJobVersionNew, &form)
  1340. return
  1341. }
  1342. parentDir := VersionOutputPath + "/"
  1343. // parentDir := ""
  1344. // if err := uploadCodeToObs(codeLocalPath, jobName, ""); err != nil {
  1345. if err := uploadCodeToObs(codeLocalPath, jobName, parentDir); err != nil {
  1346. log.Error("Failed to uploadCodeToObs: %s (%v)", repo.FullName(), err)
  1347. trainJobNewVersionDataPrepare(ctx)
  1348. ctx.RenderWithErr(ctx.Tr("cloudbrain.load_code_failed"), tplModelArtsTrainJobVersionNew, &form)
  1349. return
  1350. }
  1351. //todo: del local code?
  1352. var parameters models.Parameters
  1353. param := make([]models.Parameter, 0)
  1354. existDeviceTarget := false
  1355. if len(params) != 0 {
  1356. err := json.Unmarshal([]byte(params), &parameters)
  1357. if err != nil {
  1358. log.Error("Failed to Unmarshal params: %s (%v)", params, err)
  1359. trainJobNewVersionDataPrepare(ctx)
  1360. ctx.RenderWithErr("运行参数错误", tplModelArtsTrainJobVersionNew, &form)
  1361. return
  1362. }
  1363. for _, parameter := range parameters.Parameter {
  1364. if parameter.Label == modelarts.DeviceTarget {
  1365. existDeviceTarget = true
  1366. }
  1367. if parameter.Label != modelarts.TrainUrl && parameter.Label != modelarts.DataUrl {
  1368. param = append(param, models.Parameter{
  1369. Label: parameter.Label,
  1370. Value: parameter.Value,
  1371. })
  1372. }
  1373. }
  1374. }
  1375. if !existDeviceTarget {
  1376. param = append(param, models.Parameter{
  1377. Label: modelarts.DeviceTarget,
  1378. Value: modelarts.Ascend,
  1379. })
  1380. }
  1381. datasUrlList, dataUrl, datasetNames, isMultiDataset, err := getDatasUrlListByUUIDS(uuid)
  1382. if err != nil {
  1383. log.Error("Failed to getDatasUrlListByUUIDS: %v", err)
  1384. trainJobNewVersionDataPrepare(ctx)
  1385. ctx.RenderWithErr("Failed to getDatasUrlListByUUIDS:"+err.Error(), tplModelArtsTrainJobVersionNew, &form)
  1386. return
  1387. }
  1388. dataPath := dataUrl
  1389. jsondatas, err := json.Marshal(datasUrlList)
  1390. if err != nil {
  1391. log.Error("Failed to Marshal: %v", err)
  1392. trainJobNewVersionDataPrepare(ctx)
  1393. ctx.RenderWithErr("json error:"+err.Error(), tplModelArtsTrainJobVersionNew, &form)
  1394. return
  1395. }
  1396. if isMultiDataset {
  1397. param = append(param, models.Parameter{
  1398. Label: modelarts.MultiDataUrl,
  1399. Value: string(jsondatas),
  1400. })
  1401. }
  1402. if form.ModelName != "" { //使用预训练模型训练
  1403. ckptUrl := "/" + form.PreTrainModelUrl + form.CkptName
  1404. param = append(param, models.Parameter{
  1405. Label: modelarts.CkptUrl,
  1406. Value: "s3:/" + ckptUrl,
  1407. })
  1408. }
  1409. task, err := models.GetCloudbrainByJobIDAndVersionName(jobID, PreVersionName)
  1410. if err != nil {
  1411. log.Error("GetCloudbrainByJobIDAndVersionName(%s) failed:%v", jobID, err.Error())
  1412. ctx.RenderWithErr(err.Error(), tplModelArtsTrainJobVersionNew, &form)
  1413. return
  1414. }
  1415. req := &modelarts.GenerateTrainJobReq{
  1416. JobName: jobName,
  1417. DisplayJobName: displayJobName,
  1418. DataUrl: dataPath,
  1419. Description: description,
  1420. CodeObsPath: codeObsPath,
  1421. BootFileUrl: codeObsPath + bootFile,
  1422. BootFile: bootFile,
  1423. TrainUrl: outputObsPath,
  1424. WorkServerNumber: workServerNumber,
  1425. IsLatestVersion: isLatestVersion,
  1426. EngineID: int64(engineID),
  1427. LogUrl: logObsPath,
  1428. PoolID: poolID,
  1429. Uuid: uuid,
  1430. Params: form.Params,
  1431. Parameters: param,
  1432. PreVersionId: task.VersionID,
  1433. CommitID: commitID,
  1434. BranchName: branchName,
  1435. FlavorName: FlavorName,
  1436. EngineName: EngineName,
  1437. PreVersionName: PreVersionName,
  1438. TotalVersionCount: latestTask.TotalVersionCount + 1,
  1439. DatasetName: datasetNames,
  1440. Spec: spec,
  1441. }
  1442. if form.ModelName != "" { //使用预训练模型训练
  1443. req.ModelName = form.ModelName
  1444. req.LabelName = form.LabelName
  1445. req.CkptName = form.CkptName
  1446. req.ModelVersion = form.ModelVersion
  1447. req.PreTrainModelUrl = form.PreTrainModelUrl
  1448. }
  1449. userCommand, userImageUrl := getUserCommand(engineID, req)
  1450. req.UserCommand = userCommand
  1451. req.UserImageUrl = userImageUrl
  1452. err = modelarts.GenerateTrainJobVersion(ctx, req, jobID)
  1453. if err != nil {
  1454. log.Error("GenerateTrainJob failed:%v", err.Error())
  1455. trainJobNewVersionDataPrepare(ctx)
  1456. ctx.RenderWithErr(err.Error(), tplModelArtsTrainJobVersionNew, &form)
  1457. return
  1458. }
  1459. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/train-job/" + jobID)
  1460. // ctx.HTML(http.StatusOK, tplModelArtsTrainJobShow)
  1461. }
  1462. // readDir reads the directory named by dirname and returns
  1463. // a list of directory entries sorted by filename.
  1464. func readDir(dirname string) ([]os.FileInfo, error) {
  1465. f, err := os.Open(dirname)
  1466. if err != nil {
  1467. return nil, err
  1468. }
  1469. list, err := f.Readdir(0)
  1470. f.Close()
  1471. if err != nil {
  1472. //todo: can not upload empty folder
  1473. if err == io.EOF {
  1474. return nil, nil
  1475. }
  1476. return nil, err
  1477. }
  1478. //sort.Slice(list, func(i, j int) bool { return list[i].Name() < list[j].Name() })
  1479. return list, nil
  1480. }
  1481. func uploadCodeToObs(codePath, jobName, parentDir string) error {
  1482. files, err := readDir(codePath)
  1483. if err != nil {
  1484. log.Error("readDir(%s) failed: %s", codePath, err.Error())
  1485. return err
  1486. }
  1487. for _, file := range files {
  1488. if file.IsDir() {
  1489. input := &obs.PutObjectInput{}
  1490. input.Bucket = setting.Bucket
  1491. input.Key = parentDir + file.Name() + "/"
  1492. _, err = storage.ObsCli.PutObject(input)
  1493. if err != nil {
  1494. log.Error("PutObject(%s) failed: %s", input.Key, err.Error())
  1495. return err
  1496. }
  1497. if err = uploadCodeToObs(codePath+file.Name()+"/", jobName, parentDir+file.Name()+"/"); err != nil {
  1498. log.Error("uploadCodeToObs(%s) failed: %s", file.Name(), err.Error())
  1499. return err
  1500. }
  1501. } else {
  1502. input := &obs.PutFileInput{}
  1503. input.Bucket = setting.Bucket
  1504. input.Key = setting.CodePathPrefix + jobName + "/code/" + parentDir + file.Name()
  1505. input.SourceFile = codePath + file.Name()
  1506. _, err = storage.ObsCli.PutFile(input)
  1507. if err != nil {
  1508. log.Error("PutFile(%s) failed: %s", input.SourceFile, err.Error())
  1509. return err
  1510. }
  1511. }
  1512. }
  1513. return nil
  1514. }
  1515. func obsMkdir(dir string) error {
  1516. input := &obs.PutObjectInput{}
  1517. input.Bucket = setting.Bucket
  1518. input.Key = dir
  1519. _, err := storage.ObsCli.PutObject(input)
  1520. if err != nil {
  1521. log.Error("PutObject(%s) failed: %s", input.Key, err.Error())
  1522. return err
  1523. }
  1524. return nil
  1525. }
  1526. func paramCheckCreateTrainJob(form auth.CreateModelArtsTrainJobForm) error {
  1527. if !strings.HasSuffix(strings.TrimSpace(form.BootFile), ".py") {
  1528. log.Error("the boot file(%s) must be a python file", strings.TrimSpace(form.BootFile))
  1529. return errors.New("启动文件必须是python文件")
  1530. }
  1531. if form.BranchName == "" {
  1532. log.Error("the branch must not be null!", form.BranchName)
  1533. return errors.New("代码分支不能为空!")
  1534. }
  1535. return nil
  1536. }
  1537. func paramCheckCreateInferenceJob(form auth.CreateModelArtsInferenceJobForm) error {
  1538. if !strings.HasSuffix(strings.TrimSpace(form.BootFile), ".py") {
  1539. log.Error("the boot file(%s) must be a python file", strings.TrimSpace(form.BootFile))
  1540. return errors.New("启动文件必须是python文件")
  1541. }
  1542. if form.WorkServerNumber > 2 || form.WorkServerNumber < 1 {
  1543. log.Error("the WorkServerNumber(%d) must be in (1,2)", form.WorkServerNumber)
  1544. return errors.New("计算节点数必须在1-2之间")
  1545. }
  1546. if form.ModelName == "" {
  1547. log.Error("the ModelName(%d) must not be nil", form.ModelName)
  1548. return errors.New("模型名称不能为空")
  1549. }
  1550. if form.ModelVersion == "" {
  1551. log.Error("the ModelVersion(%d) must not be nil", form.ModelVersion)
  1552. return errors.New("模型版本不能为空")
  1553. }
  1554. if form.CkptName == "" {
  1555. log.Error("the CkptName(%d) must not be nil", form.CkptName)
  1556. return errors.New("权重文件不能为空")
  1557. }
  1558. if form.BranchName == "" {
  1559. log.Error("the Branch(%d) must not be nil", form.BranchName)
  1560. return errors.New("分支名不能为空")
  1561. }
  1562. if utf8.RuneCountInString(form.Description) > 255 {
  1563. log.Error("the Description length(%d) must not more than 255", form.Description)
  1564. return errors.New("描述字符不能超过255个字符")
  1565. }
  1566. return nil
  1567. }
  1568. func TrainJobShow(ctx *context.Context) {
  1569. ctx.Data["PageIsCloudBrain"] = true
  1570. var jobID = ctx.Params(":jobid")
  1571. repo := ctx.Repo.Repository
  1572. page := ctx.QueryInt("page")
  1573. if page <= 0 {
  1574. page = 1
  1575. }
  1576. var jobTypes []string
  1577. jobTypes = append(jobTypes, string(models.JobTypeTrain))
  1578. VersionListTasks, VersionListCount, err := models.CloudbrainsVersionList(&models.CloudbrainsOptions{
  1579. ListOptions: models.ListOptions{
  1580. Page: page,
  1581. PageSize: setting.UI.IssuePagingNum,
  1582. },
  1583. RepoID: repo.ID,
  1584. Type: models.TypeCloudBrainTwo,
  1585. JobTypes: jobTypes,
  1586. JobID: jobID,
  1587. })
  1588. if err != nil {
  1589. log.Error("GetVersionListTasks(%s) failed:%v", jobID, err.Error())
  1590. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  1591. return
  1592. }
  1593. if len(VersionListTasks) == 0 {
  1594. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  1595. return
  1596. }
  1597. //设置权限
  1598. canNewJob, err := canUserCreateTrainJobVersion(ctx, VersionListTasks[0].UserID)
  1599. if err != nil {
  1600. ctx.ServerError("canNewJob failed", err)
  1601. return
  1602. }
  1603. ctx.Data["canNewJob"] = canNewJob
  1604. datasetList := make([][]models.DatasetDownload, 0)
  1605. //将运行参数转化为epoch_size = 3, device_target = Ascend的格式
  1606. for i, task := range VersionListTasks {
  1607. var parameters models.Parameters
  1608. err := json.Unmarshal([]byte(VersionListTasks[i].Parameters), &parameters)
  1609. if err != nil {
  1610. log.Error("Failed to Unmarshal Parameters: %s (%v)", VersionListTasks[i].Parameters, err)
  1611. trainJobNewDataPrepare(ctx)
  1612. return
  1613. }
  1614. if len(parameters.Parameter) > 0 {
  1615. paramTemp := ""
  1616. for _, Parameter := range parameters.Parameter {
  1617. param := Parameter.Label + " = " + Parameter.Value + "; "
  1618. paramTemp = paramTemp + param
  1619. }
  1620. VersionListTasks[i].Parameters = paramTemp[:len(paramTemp)-2]
  1621. } else {
  1622. VersionListTasks[i].Parameters = ""
  1623. }
  1624. datasetList = append(datasetList, GetCloudBrainDataSetInfo(task.Uuid, task.DatasetName, false))
  1625. VersionListTasks[i].CanDel = cloudbrain.CanDeleteJob(ctx, &task.Cloudbrain)
  1626. VersionListTasks[i].CanModify = cloudbrain.CanModifyJob(ctx, &task.Cloudbrain)
  1627. VersionListTasks[i].ContainerIp = ""
  1628. //add spec
  1629. s, err := resource.GetCloudbrainSpec(task.Cloudbrain.ID)
  1630. if err != nil {
  1631. log.Error("TrainJobShow GetCloudbrainSpec error:" + err.Error())
  1632. continue
  1633. }
  1634. VersionListTasks[i].Cloudbrain.Spec = s
  1635. }
  1636. pager := context.NewPagination(VersionListCount, setting.UI.IssuePagingNum, page, 5)
  1637. pager.SetDefaultParams(ctx)
  1638. ctx.Data["Page"] = pager
  1639. ctx.Data["jobID"] = jobID
  1640. ctx.Data["displayJobName"] = VersionListTasks[0].DisplayJobName
  1641. ctx.Data["version_list_task"] = VersionListTasks
  1642. ctx.Data["version_list_count"] = VersionListCount
  1643. ctx.Data["datasetList"] = datasetList
  1644. ctx.Data["canDownload"] = cloudbrain.CanModifyJob(ctx, &VersionListTasks[0].Cloudbrain)
  1645. ctx.HTML(http.StatusOK, tplModelArtsTrainJobShow)
  1646. }
  1647. func TrainJobDel(ctx *context.Context) {
  1648. var jobID = ctx.Params(":jobid")
  1649. var listType = ctx.Query("listType")
  1650. repo := ctx.Repo.Repository
  1651. var jobTypes []string
  1652. jobTypes = append(jobTypes, string(models.JobTypeTrain))
  1653. VersionListTasks, _, err := models.CloudbrainsVersionList(&models.CloudbrainsOptions{
  1654. RepoID: repo.ID,
  1655. Type: models.TypeCloudBrainTwo,
  1656. JobTypes: jobTypes,
  1657. JobID: jobID,
  1658. })
  1659. if err != nil {
  1660. ctx.ServerError("get VersionListTasks failed", err)
  1661. return
  1662. }
  1663. for _, task := range VersionListTasks {
  1664. if task.Status != string(models.ModelArtsTrainJobImageFailed) && task.Status != string(models.ModelArtsTrainJobSubmitFailed) && task.Status != string(models.ModelArtsTrainJobDeleteFailed) &&
  1665. task.Status != string(models.ModelArtsTrainJobCompleted) && task.Status != string(models.ModelArtsTrainJobFailed) &&
  1666. task.Status != string(models.ModelArtsTrainJobKilled) && task.Status != string(models.ModelArtsTrainJobCanceled) && task.Status != string(models.ModelArtsTrainJobLost) {
  1667. log.Error("the job(%s) version has not been stopped", task.JobName)
  1668. ctx.RenderWithErr("the job version has not been stopped", tplModelArtsTrainJobIndex, nil)
  1669. return
  1670. }
  1671. }
  1672. //删除modelarts上的任务记录
  1673. _, err = modelarts.DelTrainJob(jobID)
  1674. if err != nil {
  1675. log.Error("DelTrainJob(%s) failed:%v", jobID, err.Error())
  1676. ctx.RenderWithErr(err.Error(), tplModelArtsTrainJobIndex, nil)
  1677. return
  1678. }
  1679. //删除数据库Cloudbrain表的记录
  1680. for _, task := range VersionListTasks {
  1681. err = models.DeleteJob(&task.Cloudbrain)
  1682. if err != nil {
  1683. ctx.ServerError("DeleteJob failed", err)
  1684. return
  1685. }
  1686. }
  1687. //删除存储
  1688. if len(VersionListTasks) > 0 {
  1689. DeleteJobStorage(VersionListTasks[0].JobName)
  1690. }
  1691. var isAdminPage = ctx.Query("isadminpage")
  1692. var isHomePage = ctx.Query("ishomepage")
  1693. if ctx.IsUserSiteAdmin() && isAdminPage == "true" {
  1694. ctx.Redirect(setting.AppSubURL + "/admin" + "/cloudbrains")
  1695. } else if isHomePage == "true" {
  1696. ctx.Redirect(setting.AppSubURL + "/cloudbrains")
  1697. } else {
  1698. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/train-job?listType=" + listType)
  1699. }
  1700. }
  1701. func TrainJobStop(ctx *context.Context) {
  1702. var jobID = ctx.Params(":jobid")
  1703. var listType = ctx.Query("listType")
  1704. task := ctx.Cloudbrain
  1705. _, err := modelarts.StopTrainJob(jobID, strconv.FormatInt(task.VersionID, 10))
  1706. if err != nil {
  1707. log.Error("StopTrainJob(%s) failed:%v", task.JobName, err.Error())
  1708. ctx.RenderWithErr(err.Error(), tplModelArtsTrainJobIndex, nil)
  1709. return
  1710. }
  1711. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/train-job?listType=" + listType)
  1712. }
  1713. func canUserCreateTrainJobVersion(ctx *context.Context, userID int64) (bool, error) {
  1714. if ctx == nil || ctx.User == nil {
  1715. log.Error("user unlogin!")
  1716. return false, nil
  1717. }
  1718. if userID == ctx.User.ID || ctx.User.IsAdmin {
  1719. return true, nil
  1720. } else {
  1721. log.Error("Only user itself and admin can new trainjob!")
  1722. return false, nil
  1723. }
  1724. }
  1725. func TrainJobGetConfigList(ctx *context.Context) {
  1726. ctx.Data["PageIsTrainJob"] = true
  1727. var jobID = ctx.Params(":jobid")
  1728. var logFileName = ctx.Query("file_name")
  1729. var baseLine = ctx.Query("base_line")
  1730. var order = ctx.Query("order")
  1731. if order != modelarts.OrderDesc && order != modelarts.OrderAsc {
  1732. log.Error("order(%s) check failed", order)
  1733. ctx.HTML(http.StatusBadRequest, tplModelArtsTrainJobShow)
  1734. return
  1735. }
  1736. task, err := models.GetCloudbrainByJobID(jobID)
  1737. if err != nil {
  1738. log.Error("GetCloudbrainByJobID(%s) failed:%v", jobID, err.Error())
  1739. ctx.RenderWithErr(err.Error(), tplModelArtsTrainJobShow, nil)
  1740. return
  1741. }
  1742. result, err := modelarts.GetTrainJobLog(jobID, strconv.FormatInt(task.VersionID, 10), baseLine, logFileName, order, modelarts.Lines)
  1743. if err != nil {
  1744. log.Error("GetTrainJobLog(%s) failed:%v", jobID, err.Error())
  1745. ctx.RenderWithErr(err.Error(), tplModelArtsTrainJobShow, nil)
  1746. return
  1747. }
  1748. ctx.Data["log"] = result
  1749. //ctx.HTML(http.StatusOK, tplModelArtsTrainJobShow)
  1750. }
  1751. func getConfigList(perPage, page int, sortBy, order, searchContent, configType string) (*models.GetConfigListResult, error) {
  1752. var result models.GetConfigListResult
  1753. list, err := modelarts.GetConfigList(perPage, page, sortBy, order, searchContent, configType)
  1754. if err != nil {
  1755. log.Error("GetConfigList failed:", err)
  1756. return &result, err
  1757. }
  1758. for _, config := range list.ParaConfigs {
  1759. paraConfig, err := modelarts.GetParaConfig(config.ConfigName, configType)
  1760. if err != nil {
  1761. log.Error("GetParaConfig failed:", err)
  1762. return &result, err
  1763. }
  1764. config.Result = paraConfig
  1765. }
  1766. return list, nil
  1767. }
  1768. func InferenceJobCreate(ctx *context.Context, form auth.CreateModelArtsInferenceJobForm) {
  1769. ctx.Data["PageIsTrainJob"] = true
  1770. VersionOutputPath := modelarts.GetOutputPathByCount(modelarts.TotalVersionCount)
  1771. displayJobName := form.DisplayJobName
  1772. jobName := util.ConvertDisplayJobNameToJobName(displayJobName)
  1773. uuid := form.Attachment
  1774. description := form.Description
  1775. workServerNumber := form.WorkServerNumber
  1776. engineID := form.EngineID
  1777. bootFile := strings.TrimSpace(form.BootFile)
  1778. params := form.Params
  1779. poolID := form.PoolID
  1780. repo := ctx.Repo.Repository
  1781. codeLocalPath := setting.JobPath + jobName + modelarts.CodePath
  1782. codeObsPath := "/" + setting.Bucket + modelarts.JobPath + jobName + modelarts.CodePath
  1783. resultObsPath := "/" + setting.Bucket + modelarts.JobPath + jobName + modelarts.ResultPath + VersionOutputPath + "/"
  1784. logObsPath := "/" + setting.Bucket + modelarts.JobPath + jobName + modelarts.LogPath + VersionOutputPath + "/"
  1785. //dataPath := "/" + setting.Bucket + "/" + setting.BasePath + path.Join(uuid[0:1], uuid[1:2]) + "/" + uuid + uuid + "/"
  1786. branchName := form.BranchName
  1787. FlavorName := form.FlavorName
  1788. EngineName := form.EngineName
  1789. LabelName := form.LabelName
  1790. isLatestVersion := modelarts.IsLatestVersion
  1791. VersionCount := modelarts.VersionCountOne
  1792. trainUrl := form.TrainUrl
  1793. modelName := form.ModelName
  1794. modelVersion := form.ModelVersion
  1795. ckptName := form.CkptName
  1796. ckptUrl := "/" + form.TrainUrl + form.CkptName
  1797. log.Info("ckpt url:" + ckptUrl)
  1798. errStr := checkInferenceJobMultiNode(ctx.User.ID, form.WorkServerNumber)
  1799. if errStr != "" {
  1800. inferenceJobErrorNewDataPrepare(ctx, form)
  1801. ctx.RenderWithErr(ctx.Tr(errStr), tplModelArtsInferenceJobNew, &form)
  1802. return
  1803. }
  1804. lock := redis_lock.NewDistributeLock(redis_key.CloudbrainBindingJobNameKey(fmt.Sprint(repo.ID), string(models.JobTypeInference), displayJobName))
  1805. isOk, err := lock.Lock(models.CloudbrainKeyDuration)
  1806. if !isOk {
  1807. log.Error("lock processed failed:%v", err, ctx.Data["MsgID"])
  1808. inferenceJobErrorNewDataPrepare(ctx, form)
  1809. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_samejob_err"), tplModelArtsInferenceJobNew, &form)
  1810. return
  1811. }
  1812. defer lock.UnLock()
  1813. count, err := cloudbrainTask.GetNotFinalStatusTaskCount(ctx.User.ID, models.TypeCloudBrainTwo, string(models.JobTypeInference))
  1814. if err != nil {
  1815. log.Error("GetCloudbrainInferenceJobCountByUserID failed:%v", err, ctx.Data["MsgID"])
  1816. inferenceJobErrorNewDataPrepare(ctx, form)
  1817. ctx.RenderWithErr("system error", tplModelArtsInferenceJobNew, &form)
  1818. return
  1819. } else {
  1820. if count >= 1 {
  1821. log.Error("the user already has running or waiting inference task", ctx.Data["MsgID"])
  1822. inferenceJobErrorNewDataPrepare(ctx, form)
  1823. ctx.RenderWithErr("you have already a running or waiting inference task, can not create more", tplModelArtsInferenceJobNew, &form)
  1824. return
  1825. }
  1826. }
  1827. if err := paramCheckCreateInferenceJob(form); err != nil {
  1828. log.Error("paramCheckCreateInferenceJob failed:(%v)", err)
  1829. inferenceJobErrorNewDataPrepare(ctx, form)
  1830. ctx.RenderWithErr(err.Error(), tplModelArtsInferenceJobNew, &form)
  1831. return
  1832. }
  1833. bootFileExist, err := ctx.Repo.FileExists(bootFile, branchName)
  1834. if err != nil || !bootFileExist {
  1835. log.Error("Get bootfile error:", err)
  1836. inferenceJobErrorNewDataPrepare(ctx, form)
  1837. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_bootfile_err"), tplModelArtsInferenceJobNew, &form)
  1838. return
  1839. }
  1840. //Determine whether the task name of the task in the project is duplicated
  1841. tasks, err := models.GetCloudbrainsByDisplayJobName(repo.ID, string(models.JobTypeInference), displayJobName)
  1842. if err == nil {
  1843. if len(tasks) != 0 {
  1844. log.Error("the job name did already exist", ctx.Data["MsgID"])
  1845. inferenceJobErrorNewDataPrepare(ctx, form)
  1846. ctx.RenderWithErr("the job name did already exist", tplModelArtsInferenceJobNew, &form)
  1847. return
  1848. }
  1849. } else {
  1850. if !models.IsErrJobNotExist(err) {
  1851. log.Error("system error, %v", err, ctx.Data["MsgID"])
  1852. inferenceJobErrorNewDataPrepare(ctx, form)
  1853. ctx.RenderWithErr("system error", tplModelArtsInferenceJobNew, &form)
  1854. return
  1855. }
  1856. }
  1857. spec, err := resource.GetAndCheckSpec(ctx.User.ID, form.SpecId, models.FindSpecsOptions{
  1858. JobType: models.JobTypeInference,
  1859. ComputeResource: models.NPU,
  1860. Cluster: models.OpenICluster,
  1861. AiCenterCode: models.AICenterOfCloudBrainTwo})
  1862. if err != nil || spec == nil {
  1863. inferenceJobErrorNewDataPrepare(ctx, form)
  1864. ctx.RenderWithErr("Resource specification not available", tplModelArtsInferenceJobNew, &form)
  1865. return
  1866. }
  1867. if !account.IsPointBalanceEnough(ctx.User.ID, spec.UnitPrice) {
  1868. log.Error("point balance is not enough,userId=%d specId=%d ", ctx.User.ID, spec.ID)
  1869. inferenceJobErrorNewDataPrepare(ctx, form)
  1870. ctx.RenderWithErr(ctx.Tr("points.insufficient_points_balance"), tplModelArtsInferenceJobNew, &form)
  1871. return
  1872. }
  1873. //todo: del the codeLocalPath
  1874. _, err = ioutil.ReadDir(codeLocalPath)
  1875. if err == nil {
  1876. os.RemoveAll(codeLocalPath)
  1877. }
  1878. gitRepo, _ := git.OpenRepository(repo.RepoPath())
  1879. commitID, _ := gitRepo.GetBranchCommitID(branchName)
  1880. if err := downloadCode(repo, codeLocalPath, branchName); err != nil {
  1881. log.Error("Create task failed, server timed out: %s (%v)", repo.FullName(), err)
  1882. inferenceJobErrorNewDataPrepare(ctx, form)
  1883. ctx.RenderWithErr(ctx.Tr("cloudbrain.load_code_failed"), tplModelArtsInferenceJobNew, &form)
  1884. return
  1885. }
  1886. //todo: upload code (send to file_server todo this work?)
  1887. if err := obsMkdir(setting.CodePathPrefix + jobName + modelarts.ResultPath + VersionOutputPath + "/"); err != nil {
  1888. log.Error("Failed to obsMkdir_result: %s (%v)", repo.FullName(), err)
  1889. inferenceJobErrorNewDataPrepare(ctx, form)
  1890. ctx.RenderWithErr("Failed to obsMkdir_result", tplModelArtsInferenceJobNew, &form)
  1891. return
  1892. }
  1893. if err := obsMkdir(setting.CodePathPrefix + jobName + modelarts.LogPath + VersionOutputPath + "/"); err != nil {
  1894. log.Error("Failed to obsMkdir_log: %s (%v)", repo.FullName(), err)
  1895. inferenceJobErrorNewDataPrepare(ctx, form)
  1896. ctx.RenderWithErr("Failed to obsMkdir_log", tplModelArtsInferenceJobNew, &form)
  1897. return
  1898. }
  1899. if err := uploadCodeToObs(codeLocalPath, jobName, ""); err != nil {
  1900. log.Error("Failed to uploadCodeToObs: %s (%v)", repo.FullName(), err)
  1901. inferenceJobErrorNewDataPrepare(ctx, form)
  1902. ctx.RenderWithErr(ctx.Tr("cloudbrain.load_code_failed"), tplModelArtsInferenceJobNew, &form)
  1903. return
  1904. }
  1905. var parameters models.Parameters
  1906. param := make([]models.Parameter, 0)
  1907. param = append(param, models.Parameter{
  1908. Label: modelarts.ResultUrl,
  1909. Value: "s3:/" + resultObsPath,
  1910. }, models.Parameter{
  1911. Label: modelarts.CkptUrl,
  1912. Value: "s3:/" + ckptUrl,
  1913. })
  1914. datasUrlList, dataUrl, datasetNames, isMultiDataset, err := getDatasUrlListByUUIDS(uuid)
  1915. if err != nil {
  1916. inferenceJobErrorNewDataPrepare(ctx, form)
  1917. ctx.RenderWithErr(err.Error(), tplModelArtsInferenceJobNew, &form)
  1918. return
  1919. }
  1920. dataPath := dataUrl
  1921. jsondatas, err := json.Marshal(datasUrlList)
  1922. if err != nil {
  1923. log.Error("Failed to Marshal: %v", err)
  1924. inferenceJobErrorNewDataPrepare(ctx, form)
  1925. ctx.RenderWithErr("json error:"+err.Error(), tplModelArtsInferenceJobNew, &form)
  1926. return
  1927. }
  1928. if isMultiDataset {
  1929. param = append(param, models.Parameter{
  1930. Label: modelarts.MultiDataUrl,
  1931. Value: string(jsondatas),
  1932. })
  1933. }
  1934. existDeviceTarget := false
  1935. if len(params) != 0 {
  1936. err := json.Unmarshal([]byte(params), &parameters)
  1937. if err != nil {
  1938. log.Error("Failed to Unmarshal params: %s (%v)", params, err)
  1939. inferenceJobErrorNewDataPrepare(ctx, form)
  1940. ctx.RenderWithErr("运行参数错误", tplModelArtsInferenceJobNew, &form)
  1941. return
  1942. }
  1943. for _, parameter := range parameters.Parameter {
  1944. if parameter.Label == modelarts.DeviceTarget {
  1945. existDeviceTarget = true
  1946. }
  1947. if parameter.Label != modelarts.TrainUrl && parameter.Label != modelarts.DataUrl {
  1948. param = append(param, models.Parameter{
  1949. Label: parameter.Label,
  1950. Value: parameter.Value,
  1951. })
  1952. }
  1953. }
  1954. }
  1955. if !existDeviceTarget {
  1956. param = append(param, models.Parameter{
  1957. Label: modelarts.DeviceTarget,
  1958. Value: modelarts.Ascend,
  1959. })
  1960. }
  1961. req := &modelarts.GenerateInferenceJobReq{
  1962. JobName: jobName,
  1963. DisplayJobName: displayJobName,
  1964. DataUrl: dataPath,
  1965. Description: description,
  1966. CodeObsPath: codeObsPath,
  1967. BootFileUrl: codeObsPath + bootFile,
  1968. BootFile: bootFile,
  1969. TrainUrl: trainUrl,
  1970. WorkServerNumber: workServerNumber,
  1971. EngineID: int64(engineID),
  1972. LogUrl: logObsPath,
  1973. PoolID: poolID,
  1974. Uuid: uuid,
  1975. Parameters: param, //modelarts train parameters
  1976. CommitID: commitID,
  1977. BranchName: branchName,
  1978. Params: form.Params,
  1979. FlavorName: FlavorName,
  1980. EngineName: EngineName,
  1981. LabelName: LabelName,
  1982. IsLatestVersion: isLatestVersion,
  1983. VersionCount: VersionCount,
  1984. TotalVersionCount: modelarts.TotalVersionCount,
  1985. ModelName: modelName,
  1986. ModelVersion: modelVersion,
  1987. CkptName: ckptName,
  1988. ResultUrl: resultObsPath,
  1989. Spec: spec,
  1990. DatasetName: datasetNames,
  1991. JobType: string(models.JobTypeInference),
  1992. }
  1993. userCommand, userImageUrl := getInfJobUserCommand(engineID, req)
  1994. req.UserCommand = userCommand
  1995. req.UserImageUrl = userImageUrl
  1996. _, err = modelarts.GenerateInferenceJob(ctx, req)
  1997. if err != nil {
  1998. log.Error("GenerateTrainJob failed:%v", err.Error())
  1999. inferenceJobErrorNewDataPrepare(ctx, form)
  2000. ctx.RenderWithErr(err.Error(), tplModelArtsInferenceJobNew, &form)
  2001. return
  2002. }
  2003. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/inference-job")
  2004. }
  2005. func checkModelArtsSpecialPool(ctx *context.Context, flavorCode string, jobType string) string {
  2006. if modelarts.SpecialPools != nil {
  2007. isMatchPool := false
  2008. for _, specialPool := range modelarts.SpecialPools.Pools {
  2009. if cloudbrain.IsElementExist(specialPool.JobType, jobType) {
  2010. if isInOrg, _ := models.IsOrganizationMemberByOrgName(specialPool.Org, ctx.User.ID); isInOrg {
  2011. isMatchPool = true
  2012. isMatchSpec := false
  2013. for _, flavor := range specialPool.Flavor {
  2014. if flavor.Value == flavorCode {
  2015. isMatchSpec = true
  2016. break
  2017. }
  2018. }
  2019. if !isMatchSpec {
  2020. return "cloudbrain.wrong_specification"
  2021. }
  2022. }
  2023. }
  2024. }
  2025. if !isMatchPool {
  2026. isMatchSpec := false
  2027. if jobType == string(models.JobTypeDebug) {
  2028. for _, flavor := range setting.StFlavorInfo.FlavorInfo {
  2029. if flavor.Value == flavorCode {
  2030. isMatchSpec = true
  2031. break
  2032. }
  2033. }
  2034. } else {
  2035. var flavorInfos modelarts.Flavor
  2036. json.Unmarshal([]byte(setting.TrainJobFLAVORINFOS), &flavorInfos)
  2037. for _, flavor := range flavorInfos.Info {
  2038. if flavor.Code == flavorCode {
  2039. isMatchSpec = true
  2040. break
  2041. }
  2042. }
  2043. }
  2044. if !isMatchSpec {
  2045. return "cloudbrain.wrong_specification"
  2046. }
  2047. }
  2048. }
  2049. return ""
  2050. }
  2051. func InferenceJobIndex(ctx *context.Context) {
  2052. MustEnableModelArts(ctx)
  2053. repo := ctx.Repo.Repository
  2054. page := ctx.QueryInt("page")
  2055. if page <= 0 {
  2056. page = 1
  2057. }
  2058. listType := ctx.Query("listType")
  2059. ctx.Data["ListType"] = listType
  2060. if listType == models.AllResource {
  2061. listType = ""
  2062. }
  2063. var jobTypes []string
  2064. jobTypes = append(jobTypes, string(models.JobTypeInference))
  2065. tasks, count, err := models.Cloudbrains(&models.CloudbrainsOptions{
  2066. ListOptions: models.ListOptions{
  2067. Page: page,
  2068. PageSize: setting.UI.IssuePagingNum,
  2069. },
  2070. RepoID: repo.ID,
  2071. ComputeResource: listType,
  2072. JobTypes: jobTypes,
  2073. Type: models.TypeCloudBrainAll,
  2074. })
  2075. if err != nil {
  2076. ctx.ServerError("Cloudbrain", err)
  2077. return
  2078. }
  2079. for i, task := range tasks {
  2080. tasks[i].CanDel = cloudbrain.CanDeleteJob(ctx, &task.Cloudbrain)
  2081. tasks[i].CanModify = cloudbrain.CanModifyJob(ctx, &task.Cloudbrain)
  2082. if tasks[i].ComputeResource == "" {
  2083. tasks[i].ComputeResource = models.NPUResource
  2084. }
  2085. }
  2086. repoId := ctx.Repo.Repository.ID
  2087. Type := -1
  2088. _, model_count, _ := models.QueryModel(&models.AiModelQueryOptions{
  2089. ListOptions: models.ListOptions{
  2090. Page: 1,
  2091. PageSize: 2,
  2092. },
  2093. RepoID: repoId,
  2094. Type: Type,
  2095. New: MODEL_LATEST,
  2096. Status: 0,
  2097. })
  2098. ctx.Data["MODEL_COUNT"] = model_count
  2099. pager := context.NewPagination(int(count), setting.UI.IssuePagingNum, page, 5)
  2100. pager.SetDefaultParams(ctx)
  2101. ctx.Data["Page"] = pager
  2102. ctx.Data["PageIsCloudBrain"] = true
  2103. ctx.Data["Tasks"] = tasks
  2104. ctx.Data["CanCreate"] = cloudbrain.CanCreateOrDebugJob(ctx)
  2105. ctx.Data["RepoIsEmpty"] = repo.IsEmpty
  2106. ctx.HTML(200, tplModelArtsInferenceJobIndex)
  2107. }
  2108. func InferenceJobNew(ctx *context.Context) {
  2109. err := inferenceJobNewDataPrepare(ctx)
  2110. if err != nil {
  2111. ctx.ServerError("get new inference-job info failed", err)
  2112. return
  2113. }
  2114. ctx.HTML(200, tplModelArtsInferenceJobNew)
  2115. }
  2116. func inferenceJobNewDataPrepare(ctx *context.Context) error {
  2117. ctx.Data["PageIsCloudBrain"] = true
  2118. ctx.Data["newInference"] = true
  2119. var displayJobName = cloudbrainService.GetDisplayJobName(ctx.User.Name)
  2120. ctx.Data["display_job_name"] = displayJobName
  2121. attachs, err := models.GetModelArtsTrainAttachments(ctx.User.ID)
  2122. if err != nil {
  2123. ctx.ServerError("GetAllUserAttachments failed:", err)
  2124. return err
  2125. }
  2126. ctx.Data["attachments"] = attachs
  2127. var resourcePools modelarts.ResourcePool
  2128. if err = json.Unmarshal([]byte(setting.ResourcePools), &resourcePools); err != nil {
  2129. ctx.ServerError("json.Unmarshal failed:", err)
  2130. return err
  2131. }
  2132. ctx.Data["resource_pools"] = resourcePools.Info
  2133. var engines modelarts.Engine
  2134. if err = json.Unmarshal([]byte(setting.Engines), &engines); err != nil {
  2135. ctx.ServerError("json.Unmarshal failed:", err)
  2136. return err
  2137. }
  2138. ctx.Data["engines"] = engines.Info
  2139. var versionInfos modelarts.VersionInfo
  2140. if err = json.Unmarshal([]byte(setting.EngineVersions), &versionInfos); err != nil {
  2141. ctx.ServerError("json.Unmarshal failed:", err)
  2142. return err
  2143. }
  2144. ctx.Data["engine_versions"] = versionInfos.Version
  2145. prepareCloudbrainTwoInferenceSpecs(ctx)
  2146. ctx.Data["params"] = ""
  2147. ctx.Data["branchName"] = ctx.Repo.BranchName
  2148. configList, err := getConfigList(modelarts.PerPage, 1, modelarts.SortByCreateTime, "desc", "", modelarts.ConfigTypeCustom)
  2149. if err != nil {
  2150. ctx.ServerError("getConfigList failed:", err)
  2151. return err
  2152. }
  2153. ctx.Data["config_list"] = configList.ParaConfigs
  2154. repoId := ctx.Repo.Repository.ID
  2155. Type := -1
  2156. _, model_count, _ := models.QueryModel(&models.AiModelQueryOptions{
  2157. ListOptions: models.ListOptions{
  2158. Page: 1,
  2159. PageSize: 2,
  2160. },
  2161. RepoID: repoId,
  2162. Type: Type,
  2163. New: MODEL_LATEST,
  2164. Status: 0,
  2165. })
  2166. ctx.Data["MODEL_COUNT"] = model_count
  2167. ctx.Data["datasetType"] = models.TypeCloudBrainTwo
  2168. waitCount := cloudbrain.GetWaitingCloudbrainCount(models.TypeCloudBrainTwo, "")
  2169. ctx.Data["WaitCount"] = waitCount
  2170. NotStopTaskCount, _ := cloudbrainTask.GetNotFinalStatusTaskCount(ctx.User.ID, models.TypeCloudBrainTwo, string(models.JobTypeInference))
  2171. ctx.Data["NotStopTaskCount"] = NotStopTaskCount
  2172. return nil
  2173. }
  2174. func prepareCloudbrainTwoInferenceSpecs(ctx *context.Context) {
  2175. noteBookSpecs, _ := resource.FindAvailableSpecs(ctx.User.ID, models.FindSpecsOptions{
  2176. JobType: models.JobTypeInference,
  2177. ComputeResource: models.NPU,
  2178. Cluster: models.OpenICluster,
  2179. AiCenterCode: models.AICenterOfCloudBrainTwo,
  2180. })
  2181. ctx.Data["Specs"] = noteBookSpecs
  2182. }
  2183. func inferenceJobErrorNewDataPrepare(ctx *context.Context, form auth.CreateModelArtsInferenceJobForm) error {
  2184. ctx.Data["PageIsCloudBrain"] = true
  2185. t := time.Now()
  2186. var jobName = "inference" + t.Format("2006010215") + strconv.Itoa(int(t.Unix()))[5:]
  2187. ctx.Data["job_name"] = jobName
  2188. attachs, err := models.GetModelArtsTrainAttachments(ctx.User.ID)
  2189. if err != nil {
  2190. ctx.ServerError("GetAllUserAttachments failed:", err)
  2191. return err
  2192. }
  2193. ctx.Data["attachments"] = attachs
  2194. var resourcePools modelarts.ResourcePool
  2195. if err = json.Unmarshal([]byte(setting.ResourcePools), &resourcePools); err != nil {
  2196. ctx.ServerError("json.Unmarshal failed:", err)
  2197. return err
  2198. }
  2199. ctx.Data["resource_pools"] = resourcePools.Info
  2200. var engines modelarts.Engine
  2201. if err = json.Unmarshal([]byte(setting.Engines), &engines); err != nil {
  2202. ctx.ServerError("json.Unmarshal failed:", err)
  2203. return err
  2204. }
  2205. ctx.Data["engines"] = engines.Info
  2206. var versionInfos modelarts.VersionInfo
  2207. if err = json.Unmarshal([]byte(setting.EngineVersions), &versionInfos); err != nil {
  2208. ctx.ServerError("json.Unmarshal failed:", err)
  2209. return err
  2210. }
  2211. ctx.Data["engine_versions"] = versionInfos.Version
  2212. prepareCloudbrainTwoInferenceSpecs(ctx)
  2213. configList, err := getConfigList(modelarts.PerPage, 1, modelarts.SortByCreateTime, "desc", "", modelarts.ConfigTypeCustom)
  2214. if err != nil {
  2215. ctx.ServerError("getConfigList failed:", err)
  2216. return err
  2217. }
  2218. var Parameters modelarts.Parameters
  2219. if err = json.Unmarshal([]byte(form.Params), &Parameters); err != nil {
  2220. ctx.ServerError("json.Unmarshal failed:", err)
  2221. return err
  2222. }
  2223. ctx.Data["params"] = Parameters.Parameter
  2224. ctx.Data["config_list"] = configList.ParaConfigs
  2225. ctx.Data["bootFile"] = form.BootFile
  2226. ctx.Data["uuid"] = form.Attachment
  2227. _, datasetNames, err := models.GetDatasetInfo(form.Attachment)
  2228. if err != nil {
  2229. log.Error("GetDatasetInfo failed: %v", err, ctx.Data["MsgID"])
  2230. return nil
  2231. }
  2232. ctx.Data["dataset_name"] = datasetNames
  2233. ctx.Data["branch_name"] = form.BranchName
  2234. ctx.Data["model_name"] = form.ModelName
  2235. ctx.Data["model_version"] = form.ModelVersion
  2236. ctx.Data["ckpt_name"] = form.CkptName
  2237. ctx.Data["train_url"] = form.TrainUrl
  2238. ctx.Data["datasetType"] = models.TypeCloudBrainTwo
  2239. waitCount := cloudbrain.GetWaitingCloudbrainCount(models.TypeCloudBrainTwo, "")
  2240. ctx.Data["WaitCount"] = waitCount
  2241. return nil
  2242. }
  2243. func InferenceJobShow(ctx *context.Context) {
  2244. ctx.Data["PageIsCloudBrain"] = true
  2245. var jobID = ctx.Params(":jobid")
  2246. page := ctx.QueryInt("page")
  2247. if page <= 0 {
  2248. page = 1
  2249. }
  2250. task, err := models.GetCloudbrainByJobID(jobID)
  2251. if err != nil {
  2252. log.Error("GetInferenceTask(%s) failed:%v", jobID, err.Error())
  2253. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  2254. return
  2255. }
  2256. //设置权限
  2257. canNewJob, err := canUserCreateTrainJobVersion(ctx, task.UserID)
  2258. if err != nil {
  2259. ctx.ServerError("canNewJob failed", err)
  2260. return
  2261. }
  2262. ctx.Data["canNewJob"] = canNewJob
  2263. //将运行参数转化为epoch_size = 3, device_target = Ascend的格式
  2264. var parameters models.Parameters
  2265. err = json.Unmarshal([]byte(task.Parameters), &parameters)
  2266. if err != nil {
  2267. log.Error("Failed to Unmarshal Parameters: %s (%v)", task.Parameters, err)
  2268. trainJobNewDataPrepare(ctx)
  2269. return
  2270. }
  2271. if len(parameters.Parameter) > 0 {
  2272. paramTemp := ""
  2273. for _, Parameter := range parameters.Parameter {
  2274. param := Parameter.Label + " = " + Parameter.Value + "; "
  2275. paramTemp = paramTemp + param
  2276. }
  2277. task.Parameters = paramTemp[:len(paramTemp)-2]
  2278. } else {
  2279. task.Parameters = ""
  2280. }
  2281. prepareSpec4Show(ctx, task)
  2282. LabelName := strings.Fields(task.LabelName)
  2283. ctx.Data["labelName"] = LabelName
  2284. ctx.Data["jobID"] = jobID
  2285. ctx.Data["jobName"] = task.JobName
  2286. ctx.Data["displayJobName"] = task.DisplayJobName
  2287. ctx.Data["task"] = task
  2288. ctx.Data["canDownload"] = cloudbrain.CanModifyJob(ctx, task)
  2289. ctx.Data["datasetDownload"] = GetCloudBrainDataSetInfo(task.Uuid, task.DatasetName, false)
  2290. tempUids := []int64{}
  2291. tempUids = append(tempUids, task.UserID)
  2292. JobCreater, err := models.GetUserNamesByIDs(tempUids)
  2293. if err != nil {
  2294. log.Error("GetUserNamesByIDs (WhitelistUserIDs): %v", err)
  2295. }
  2296. ctx.Data["userName"] = JobCreater[0]
  2297. ctx.HTML(http.StatusOK, tplModelArtsInferenceJobShow)
  2298. }
  2299. func ModelDownload(ctx *context.Context) {
  2300. var (
  2301. err error
  2302. )
  2303. jobID := ctx.Params(":jobid")
  2304. versionName := ctx.Query("version_name")
  2305. parentDir := ctx.Query("parent_dir")
  2306. fileName := ctx.Query("file_name")
  2307. task, err := models.GetCloudbrainByJobIDAndVersionName(jobID, versionName)
  2308. if err != nil {
  2309. log.Error("GetCloudbrainByJobIDAndVersionName(%s) failed:%v", task.JobName, err.Error())
  2310. return
  2311. }
  2312. var url string
  2313. if task.ComputeResource == models.NPUResource {
  2314. path := strings.TrimPrefix(path.Join(setting.TrainJobModelPath, task.JobName, setting.OutPutPath, versionName, parentDir, fileName), "/")
  2315. url, err = storage.GetObsCreateSignedUrlByBucketAndKey(setting.Bucket, path)
  2316. if err != nil {
  2317. log.Error("GetObsCreateSignedUrl failed: %v", err.Error(), ctx.Data["msgID"])
  2318. ctx.ServerError("GetObsCreateSignedUrl", err)
  2319. return
  2320. }
  2321. } else if task.ComputeResource == models.GPUResource {
  2322. filePath := setting.CBCodePathPrefix + task.JobName + cloudbrain.ModelMountPath + "/" + parentDir
  2323. url, err = storage.Attachments.PresignedGetURL(filePath, fileName)
  2324. if err != nil {
  2325. log.Error("PresignedGetURL failed: %v", err.Error(), ctx.Data["msgID"])
  2326. ctx.ServerError("PresignedGetURL", err)
  2327. return
  2328. }
  2329. }
  2330. ctx.Resp.Header().Set("Cache-Control", "max-age=0")
  2331. http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusMovedPermanently)
  2332. }
  2333. func ResultDownload(ctx *context.Context) {
  2334. var (
  2335. err error
  2336. )
  2337. versionName := ctx.Query("version_name")
  2338. parentDir := ctx.Query("parent_dir")
  2339. fileName := ctx.Query("file_name")
  2340. task := ctx.Cloudbrain
  2341. if err != nil {
  2342. ctx.Data["error"] = err.Error()
  2343. }
  2344. path := strings.TrimPrefix(path.Join(setting.TrainJobModelPath, task.JobName, "result/", versionName, parentDir, fileName), "/")
  2345. url, err := storage.GetObsCreateSignedUrlByBucketAndKey(setting.Bucket, path)
  2346. if err != nil {
  2347. log.Error("GetObsCreateSignedUrl failed: %v", err.Error(), ctx.Data["msgID"])
  2348. ctx.ServerError("GetObsCreateSignedUrl", err)
  2349. return
  2350. }
  2351. ctx.Resp.Header().Set("Cache-Control", "max-age=0")
  2352. http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusMovedPermanently)
  2353. }
  2354. func DeleteJobStorage(jobName string) error {
  2355. //delete local
  2356. localJobPath := setting.JobPath + jobName
  2357. err := os.RemoveAll(localJobPath)
  2358. if err != nil {
  2359. log.Error("RemoveAll(%s) failed:%v", localJobPath, err)
  2360. }
  2361. //delete oss
  2362. dirPath := setting.CodePathPrefix + jobName + "/"
  2363. err = storage.ObsRemoveObject(setting.Bucket, dirPath)
  2364. if err != nil {
  2365. log.Error("ObsRemoveObject(%s) failed:%v", localJobPath, err)
  2366. }
  2367. return nil
  2368. }
  2369. func DownloadMultiResultFile(ctx *context.Context) {
  2370. var jobID = ctx.Params(":jobid")
  2371. var versionName = ctx.Query("version_name")
  2372. task, err := models.GetCloudbrainByJobIDAndVersionName(jobID, versionName)
  2373. if err != nil {
  2374. log.Error("GetCloudbrainByJobID(%s) failed:%v", task.JobName, err.Error())
  2375. return
  2376. }
  2377. // if !isCanDeleteOrDownload(ctx, task) {
  2378. // ctx.ServerError("no right.", errors.New(ctx.Tr("repo.model_noright")))
  2379. // return
  2380. // }
  2381. // path := Model_prefix + models.AttachmentRelativePath(id) + "/"
  2382. path := strings.TrimPrefix(path.Join(setting.TrainJobModelPath, task.JobName, "result/", versionName), "/") + "/"
  2383. allFile, err := storage.GetAllObjectByBucketAndPrefix(setting.Bucket, path)
  2384. if err == nil {
  2385. //count++
  2386. // models.ModifyModelDownloadCount(id)
  2387. returnFileName := task.DisplayJobName + ".zip"
  2388. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+returnFileName)
  2389. ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
  2390. w := zip.NewWriter(ctx.Resp)
  2391. defer w.Close()
  2392. for _, oneFile := range allFile {
  2393. if oneFile.IsDir {
  2394. log.Info("zip dir name:" + oneFile.FileName)
  2395. } else {
  2396. log.Info("zip file name:" + oneFile.FileName)
  2397. fDest, err := w.Create(oneFile.FileName)
  2398. if err != nil {
  2399. log.Info("create zip entry error, download file failed: %s\n", err.Error())
  2400. ctx.ServerError("download file failed:", err)
  2401. return
  2402. }
  2403. body, err := storage.ObsDownloadAFile(setting.Bucket, path+oneFile.FileName)
  2404. if err != nil {
  2405. log.Info("download file failed: %s\n", err.Error())
  2406. ctx.ServerError("download file failed:", err)
  2407. return
  2408. } else {
  2409. defer body.Close()
  2410. p := make([]byte, 1024)
  2411. var readErr error
  2412. var readCount int
  2413. // 读取对象内容
  2414. for {
  2415. readCount, readErr = body.Read(p)
  2416. if readCount > 0 {
  2417. fDest.Write(p[:readCount])
  2418. }
  2419. if readErr != nil {
  2420. break
  2421. }
  2422. }
  2423. }
  2424. }
  2425. }
  2426. } else {
  2427. log.Info("error,msg=" + err.Error())
  2428. ctx.ServerError("no file to download.", err)
  2429. }
  2430. }
  2431. func SetJobCount(ctx *context.Context) {
  2432. repoId := ctx.Repo.Repository.ID
  2433. _, jobCount, err := models.Cloudbrains(&models.CloudbrainsOptions{
  2434. RepoID: repoId,
  2435. Type: models.TypeCloudBrainAll,
  2436. })
  2437. if err != nil {
  2438. ctx.ServerError("Get job faild:", err)
  2439. return
  2440. }
  2441. ctx.Data["jobCount"] = jobCount
  2442. }
  2443. func TrainJobDownloadLogFile(ctx *context.Context) {
  2444. var (
  2445. err error
  2446. )
  2447. var jobID = ctx.Params(":jobid")
  2448. versionName := ctx.Query("version_name")
  2449. task, err := models.GetCloudbrainByJobIDAndVersionName(jobID, versionName)
  2450. if err != nil {
  2451. log.Error("GetCloudbrainByJobIDAndVersionName(%s) failed:%v", task.JobName, err.Error(), ctx.Data["msgID"])
  2452. ctx.ServerError("GetCloudbrainByJobIDAndVersionName", err)
  2453. return
  2454. }
  2455. prefix := strings.TrimPrefix(path.Join(setting.TrainJobModelPath, task.JobName, modelarts.LogPath, versionName), "/") + "/job"
  2456. key, err := storage.GetObsLogFileName(prefix)
  2457. if err != nil {
  2458. log.Error("GetObsLogFileName(%s) failed:%v", jobID, err.Error(), ctx.Data["msgID"])
  2459. ctx.ServerError("GetObsLogFileName", err)
  2460. return
  2461. }
  2462. url, err := storage.GetObsCreateSignedUrlByBucketAndKey(setting.Bucket, key)
  2463. if err != nil {
  2464. log.Error("GetObsCreateSignedUrlByBucketAndKey failed: %v", err.Error(), ctx.Data["msgID"])
  2465. ctx.ServerError("GetObsCreateSignedUrlByBucketAndKey", err)
  2466. return
  2467. }
  2468. ctx.Resp.Header().Set("Cache-Control", "max-age=0")
  2469. http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusTemporaryRedirect)
  2470. }
  2471. func getDatasUrlListByUUIDS(uuidStr string) ([]models.Datasurl, string, string, bool, error) {
  2472. var isMultiDataset bool
  2473. var dataUrl string
  2474. var datasetNames string
  2475. var datasUrlList []models.Datasurl
  2476. uuids := strings.Split(uuidStr, ";")
  2477. if len(uuids) > setting.MaxDatasetNum {
  2478. log.Error("the dataset count(%d) exceed the limit", len(uuids))
  2479. return datasUrlList, dataUrl, datasetNames, isMultiDataset, errors.New("the dataset count exceed the limit")
  2480. }
  2481. datasetInfos := make(map[string]models.DatasetInfo)
  2482. attachs, err := models.GetAttachmentsByUUIDs(uuids)
  2483. if err != nil || len(attachs) != len(uuids) {
  2484. log.Error("GetAttachmentsByUUIDs failed: %v", err)
  2485. return datasUrlList, dataUrl, datasetNames, isMultiDataset, errors.New("GetAttachmentsByUUIDs failed")
  2486. }
  2487. for i, tmpUuid := range uuids {
  2488. var attach *models.Attachment
  2489. for _, tmpAttach := range attachs {
  2490. if tmpAttach.UUID == tmpUuid {
  2491. attach = tmpAttach
  2492. break
  2493. }
  2494. }
  2495. if attach == nil {
  2496. log.Error("GetAttachmentsByUUIDs failed: %v", err)
  2497. return datasUrlList, dataUrl, datasetNames, isMultiDataset, errors.New("GetAttachmentsByUUIDs failed")
  2498. }
  2499. fileName := strings.TrimSuffix(strings.TrimSuffix(strings.TrimSuffix(attach.Name, ".zip"), ".tar.gz"), ".tgz")
  2500. for _, datasetInfo := range datasetInfos {
  2501. if fileName == datasetInfo.Name {
  2502. log.Error("the dataset name is same: %v", attach.Name)
  2503. return datasUrlList, dataUrl, datasetNames, isMultiDataset, errors.New("the dataset name is same")
  2504. }
  2505. }
  2506. if len(attachs) <= 1 {
  2507. dataUrl = "/" + setting.Bucket + "/" + setting.BasePath + path.Join(attach.UUID[0:1], attach.UUID[1:2]) + "/" + attach.UUID + attach.UUID + "/"
  2508. isMultiDataset = false
  2509. } else {
  2510. dataUrl = "/" + setting.Bucket + "/" + setting.BasePath + path.Join(attachs[0].UUID[0:1], attachs[0].UUID[1:2]) + "/" + attachs[0].UUID + attachs[0].UUID + "/"
  2511. datasetUrl := "s3://" + setting.Bucket + "/" + setting.BasePath + path.Join(attach.UUID[0:1], attach.UUID[1:2]) + "/" + attach.UUID + attach.UUID + "/"
  2512. datasUrlList = append(datasUrlList, models.Datasurl{
  2513. DatasetUrl: datasetUrl,
  2514. DatasetName: fileName,
  2515. })
  2516. isMultiDataset = true
  2517. }
  2518. if i == 0 {
  2519. datasetNames = attach.Name
  2520. } else {
  2521. datasetNames += ";" + attach.Name
  2522. }
  2523. }
  2524. return datasUrlList, dataUrl, datasetNames, isMultiDataset, nil
  2525. }