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

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