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