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

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