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