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