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