You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

modelarts.go 92 kB

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