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

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