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.

grampus.go 60 kB

3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
2 years ago
3 years ago
3 years ago
3 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773
  1. package repo
  2. import (
  3. "code.gitea.io/gitea/services/lock"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io/ioutil"
  8. "net/http"
  9. "os"
  10. "path"
  11. "strconv"
  12. "strings"
  13. "code.gitea.io/gitea/modules/urfs_client/urchin"
  14. "code.gitea.io/gitea/routers/response"
  15. "code.gitea.io/gitea/services/cloudbrain/cloudbrainTask"
  16. "code.gitea.io/gitea/modules/dataset"
  17. "code.gitea.io/gitea/services/cloudbrain/resource"
  18. "code.gitea.io/gitea/services/reward/point/account"
  19. "code.gitea.io/gitea/modules/auth"
  20. "code.gitea.io/gitea/modules/git"
  21. "code.gitea.io/gitea/modules/grampus"
  22. "code.gitea.io/gitea/modules/modelarts"
  23. "code.gitea.io/gitea/modules/notification"
  24. "code.gitea.io/gitea/modules/redis/redis_key"
  25. "code.gitea.io/gitea/modules/redis/redis_lock"
  26. "code.gitea.io/gitea/modules/timeutil"
  27. "code.gitea.io/gitea/modules/util"
  28. "github.com/unknwon/com"
  29. "code.gitea.io/gitea/models"
  30. "code.gitea.io/gitea/modules/base"
  31. "code.gitea.io/gitea/modules/cloudbrain"
  32. "code.gitea.io/gitea/modules/context"
  33. "code.gitea.io/gitea/modules/log"
  34. "code.gitea.io/gitea/modules/setting"
  35. cloudbrainService "code.gitea.io/gitea/services/cloudbrain"
  36. )
  37. const (
  38. tplGrampusTrainJobShow base.TplName = "repo/grampus/trainjob/show"
  39. tplGrampusNotebookShow base.TplName = "repo/grampus/notebook/show"
  40. //GPU
  41. tplGrampusNotebookGPUNew base.TplName = "repo/grampus/notebook/gpu/new"
  42. tplGrampusTrainJobGPUNew base.TplName = "repo/grampus/trainjob/gpu/new"
  43. //NPU
  44. tplGrampusNotebookNPUNew base.TplName = "repo/grampus/notebook/npu/new"
  45. tplGrampusTrainJobNPUNew base.TplName = "repo/grampus/trainjob/npu/new"
  46. //GCU
  47. tplGrampusNotebookGCUNew base.TplName = "repo/grampus/notebook/gcu/new"
  48. )
  49. func GrampusNotebookNew(ctx *context.Context) {
  50. ctx.Data["IsCreate"] = true
  51. notebookType := ctx.QueryInt("type")
  52. processType := grampus.ProcessorTypeGPU
  53. if notebookType == 1 {
  54. processType = grampus.ProcessorTypeNPU
  55. } else if notebookType == 2 {
  56. processType = grampus.ProcessorTypeGCU
  57. }
  58. err := grampusNotebookNewDataPrepare(ctx, processType)
  59. if err != nil {
  60. ctx.ServerError("get new notebook-job info failed", err)
  61. return
  62. }
  63. if processType == grampus.ProcessorTypeGPU {
  64. ctx.HTML(http.StatusOK, tplGrampusNotebookGPUNew)
  65. } else if processType == grampus.ProcessorTypeNPU {
  66. ctx.HTML(http.StatusOK, tplGrampusNotebookNPUNew)
  67. } else if processType == grampus.ProcessorTypeGCU {
  68. ctx.HTML(http.StatusOK, tplGrampusNotebookGCUNew)
  69. }
  70. }
  71. func GrampusTrainJobGPUNew(ctx *context.Context) {
  72. ctx.Data["IsCreate"] = true
  73. err := grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  74. if err != nil {
  75. ctx.ServerError("get new train-job info failed", err)
  76. return
  77. }
  78. ctx.HTML(http.StatusOK, tplGrampusTrainJobGPUNew)
  79. }
  80. func GrampusTrainJobNPUNew(ctx *context.Context) {
  81. ctx.Data["IsCreate"] = true
  82. err := grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  83. if err != nil {
  84. ctx.ServerError("get new train-job info failed", err)
  85. return
  86. }
  87. ctx.HTML(200, tplGrampusTrainJobNPUNew)
  88. }
  89. func GrampusNotebookCreate(ctx *context.Context, form auth.CreateGrampusNotebookForm) {
  90. ctx.Data["IsCreate"] = true
  91. displayJobName := form.DisplayJobName
  92. jobName := util.ConvertDisplayJobNameToJobName(displayJobName)
  93. uuid := form.Attachment
  94. description := form.Description
  95. repo := ctx.Repo.Repository
  96. branchName := form.BranchName
  97. image := strings.TrimSpace(form.Image)
  98. codeStoragePath := setting.CBCodePathPrefix + jobName + cloudbrain.CodeMountPath + "/"
  99. tpl := tplGrampusNotebookGPUNew
  100. processType := grampus.ProcessorTypeGPU
  101. computeSource := models.GPUResource
  102. computeSourceSimple := models.GPU
  103. if form.Type == 1 {
  104. tpl = tplGrampusNotebookNPUNew
  105. processType = grampus.ProcessorTypeNPU
  106. computeSource = models.NPUResource
  107. computeSourceSimple = models.NPU
  108. codeStoragePath = grampus.JobPath + jobName + modelarts.CodePath
  109. } else if form.Type == 2 {
  110. tpl = tplGrampusNotebookGCUNew
  111. processType = grampus.ProcessorTypeGCU
  112. computeSource = models.GCUResource
  113. computeSourceSimple = models.GCU
  114. codeStoragePath = setting.CBCodePathPrefix + jobName + cloudbrain.CodeMountPath + "/"
  115. }
  116. limiterCtx := &lock.LockContext{Repo: ctx.Repo.Repository, DisplayJobName: displayJobName, User: ctx.User}
  117. lockOperator, errMsg := cloudbrainService.Lock4CloudbrainCreation(limiterCtx)
  118. defer func() {
  119. if lockOperator != nil {
  120. lockOperator.Unlock(limiterCtx)
  121. }
  122. }()
  123. if errMsg != "" {
  124. log.Error("lock processed failed:%s", errMsg, ctx.Data["MsgID"])
  125. grampusNotebookNewDataPrepare(ctx, processType)
  126. ctx.RenderWithErr(ctx.Tr(errMsg), tpl, &form)
  127. return
  128. }
  129. if !jobNamePattern.MatchString(displayJobName) {
  130. grampusNotebookNewDataPrepare(ctx, processType)
  131. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_jobname_err"), tpl, &form)
  132. return
  133. }
  134. //check count limit
  135. count, err := cloudbrainTask.GetNotFinalStatusTaskCount(ctx.User.ID, models.TypeC2Net, string(models.JobTypeDebug), computeSource)
  136. if err != nil {
  137. log.Error("GetGrampusCountByUserID failed:%v", err, ctx.Data["MsgID"])
  138. grampusNotebookNewDataPrepare(ctx, processType)
  139. ctx.RenderWithErr("system error", tpl, &form)
  140. return
  141. } else {
  142. if count >= 1 {
  143. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  144. grampusNotebookNewDataPrepare(ctx, processType)
  145. ctx.RenderWithErr("you have already a running or waiting task, can not create more", tpl, &form)
  146. return
  147. }
  148. }
  149. //check whether the task name in the project is duplicated
  150. tasks, err := models.GetCloudbrainsByDisplayJobName(repo.ID, string(models.JobTypeDebug), displayJobName)
  151. if err == nil {
  152. if len(tasks) != 0 {
  153. log.Error("the job name did already exist", ctx.Data["MsgID"])
  154. grampusNotebookNewDataPrepare(ctx, processType)
  155. ctx.RenderWithErr("the job name did already exist", tpl, &form)
  156. return
  157. }
  158. } else {
  159. if !models.IsErrJobNotExist(err) {
  160. log.Error("system error, %v", err, ctx.Data["MsgID"])
  161. grampusNotebookNewDataPrepare(ctx, processType)
  162. ctx.RenderWithErr("system error", tpl, &form)
  163. return
  164. }
  165. }
  166. //check specification
  167. spec, err := resource.GetAndCheckSpec(ctx.User.ID, form.SpecId, models.FindSpecsOptions{
  168. JobType: models.JobTypeDebug,
  169. ComputeResource: computeSourceSimple,
  170. Cluster: models.C2NetCluster,
  171. })
  172. if err != nil || spec == nil {
  173. grampusNotebookNewDataPrepare(ctx, processType)
  174. ctx.RenderWithErr("Resource specification not available", tpl, &form)
  175. return
  176. }
  177. if !account.IsPointBalanceEnough(ctx.User.ID, spec.UnitPrice) {
  178. log.Error("point balance is not enough,userId=%d specId=%d", ctx.User.ID, spec.ID)
  179. grampusNotebookNewDataPrepare(ctx, processType)
  180. ctx.RenderWithErr(ctx.Tr("points.insufficient_points_balance"), tpl, &form)
  181. return
  182. }
  183. var datasetInfos map[string]models.DatasetInfo
  184. var datasetNames string
  185. //var
  186. if uuid != "" {
  187. datasetInfos, datasetNames, err = models.GetDatasetInfo(uuid, computeSourceSimple)
  188. if err != nil {
  189. log.Error("GetDatasetInfo failed: %v", err, ctx.Data["MsgID"])
  190. grampusNotebookNewDataPrepare(ctx, processType)
  191. ctx.RenderWithErr(ctx.Tr("cloudbrain.error.dataset_select"), tpl, &form)
  192. return
  193. }
  194. }
  195. //prepare code and out path
  196. codeLocalPath := setting.JobPath + jobName + cloudbrain.CodeMountPath + "/"
  197. _, err = ioutil.ReadDir(codeLocalPath)
  198. if err == nil {
  199. os.RemoveAll(codeLocalPath)
  200. }
  201. if err := downloadZipCode(ctx, codeLocalPath, branchName); err != nil {
  202. log.Error("downloadZipCode failed, server timed out: %s (%v)", repo.FullName(), err)
  203. grampusNotebookNewDataPrepare(ctx, processType)
  204. ctx.RenderWithErr(ctx.Tr("cloudbrain.load_code_failed"), tpl, &form)
  205. return
  206. }
  207. if processType == grampus.ProcessorTypeGPU || processType == grampus.ProcessorTypeGCU {
  208. if err := uploadCodeToMinio(codeLocalPath+"/", jobName, cloudbrain.CodeMountPath+"/"); err != nil {
  209. log.Error("Failed to uploadCodeToMinio: %s (%v)", repo.FullName(), err, ctx.Data["MsgID"])
  210. grampusNotebookNewDataPrepare(ctx, processType)
  211. ctx.RenderWithErr(ctx.Tr("cloudbrain.load_code_failed"), tpl, &form)
  212. return
  213. }
  214. } else {
  215. if err := uploadCodeToObs(codeLocalPath, jobName, ""); err != nil {
  216. log.Error("Failed to uploadCodeToObs: %s (%v)", repo.FullName(), err)
  217. grampusNotebookNewDataPrepare(ctx, processType)
  218. ctx.RenderWithErr(ctx.Tr("cloudbrain.load_code_failed"), tpl, &form)
  219. return
  220. }
  221. }
  222. commitID, _ := ctx.Repo.GitRepo.GetBranchCommitID(branchName)
  223. req := &grampus.GenerateNotebookJobReq{
  224. JobName: jobName,
  225. DisplayJobName: displayJobName,
  226. ComputeResource: computeSource,
  227. ProcessType: processType,
  228. ImageUrl: image,
  229. ImageId: form.ImageID,
  230. Description: description,
  231. Uuid: uuid,
  232. CommitID: commitID,
  233. BranchName: branchName,
  234. DatasetNames: datasetNames,
  235. DatasetInfos: datasetInfos,
  236. Spec: spec,
  237. CodeStoragePath: codeStoragePath,
  238. CodeName: strings.ToLower(repo.Name),
  239. }
  240. if form.ModelName != "" { //使用预训练模型训练
  241. m, err := models.QueryModelByPath(form.PreTrainModelUrl)
  242. if err != nil {
  243. log.Error("Can not find model", err)
  244. grampusNotebookNewDataPrepare(ctx, processType)
  245. ctx.RenderWithErr(ctx.Tr("repo.modelconvert.manage.model_not_exist"), tpl, &form)
  246. return
  247. }
  248. req.ModelName = form.ModelName
  249. req.LabelName = form.LabelName
  250. req.CkptName = form.CkptName
  251. req.ModelVersion = form.ModelVersion
  252. req.PreTrainModelUrl = form.PreTrainModelUrl
  253. req.PreTrainModelPath = getPreTrainModelPath(form.PreTrainModelUrl, form.CkptName)
  254. req.ModelStorageType = m.Type
  255. }
  256. _, err = grampus.GenerateNotebookJob(ctx, req)
  257. if err != nil {
  258. log.Error("GenerateNotebookJob failed:%v", err.Error(), ctx.Data["MsgID"])
  259. grampusTrainJobNewDataPrepare(ctx, processType)
  260. ctx.RenderWithErr(err.Error(), tpl, &form)
  261. return
  262. }
  263. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/debugjob?debugListType=all")
  264. }
  265. func grampusNotebookNewDataPrepare(ctx *context.Context, processType string) error {
  266. ctx.Data["PageIsCloudBrain"] = true
  267. var displayJobName = cloudbrainService.GetDisplayJobName(ctx.User.Name)
  268. ctx.Data["display_job_name"] = displayJobName
  269. //get valid images
  270. if processType == grampus.ProcessorTypeNPU || processType == grampus.ProcessorTypeGCU {
  271. images, err := grampus.GetImages(processType, string(models.JobTypeDebug))
  272. if err != nil {
  273. log.Error("GetImages failed:", err.Error())
  274. } else {
  275. ctx.Data["images"] = images.Infos
  276. }
  277. }
  278. //prepare available specs
  279. computeResourceSimple := models.GPU
  280. datasetType := models.TypeCloudBrainOne
  281. computeResource := models.GPUResource
  282. if processType == grampus.ProcessorTypeNPU {
  283. computeResourceSimple = models.NPU
  284. datasetType = models.TypeCloudBrainTwo
  285. computeResource = models.NPUResource
  286. } else if processType == grampus.ProcessorTypeGCU {
  287. computeResourceSimple = models.GCU
  288. datasetType = models.TypeCloudBrainAll
  289. computeResource = models.GCUResource
  290. }
  291. prepareGrampusSpecs(ctx, computeResourceSimple, models.JobTypeDebug)
  292. //get branches
  293. branches, _, err := ctx.Repo.GitRepo.GetBranches(0, 0)
  294. if err != nil {
  295. log.Error("GetBranches error:", err.Error())
  296. } else {
  297. ctx.Data["branches"] = branches
  298. }
  299. ctx.Data["branchName"] = ctx.Repo.BranchName
  300. ctx.Data["datasetType"] = datasetType
  301. waitCount := cloudbrain.GetWaitingCloudbrainCount(models.TypeC2Net, computeResource, models.JobTypeDebug)
  302. ctx.Data["WaitCount"] = waitCount
  303. NotStopTaskCount, _ := cloudbrainTask.GetNotFinalStatusTaskCount(ctx.User.ID, models.TypeC2Net, string(models.JobTypeDebug), computeResource)
  304. ctx.Data["NotStopTaskCount"] = NotStopTaskCount
  305. ctx.Data["code_path"] = cloudbrain.CodeMountPath
  306. ctx.Data["dataset_path"] = cloudbrain.DataSetMountPath
  307. ctx.Data["model_path"] = cloudbrain.ModelMountPath
  308. return nil
  309. }
  310. func grampusTrainJobNewDataPrepare(ctx *context.Context, processType string) error {
  311. ctx.Data["PageIsCloudBrain"] = true
  312. var displayJobName = cloudbrainService.GetDisplayJobName(ctx.User.Name)
  313. ctx.Data["display_job_name"] = displayJobName
  314. //get valid images
  315. if processType == grampus.ProcessorTypeNPU {
  316. images, err := grampus.GetImages(processType, string(models.JobTypeTrain))
  317. if err != nil {
  318. log.Error("GetImages failed:", err.Error())
  319. } else {
  320. ctx.Data["images"] = images.Infos
  321. }
  322. }
  323. //prepare available specs
  324. if processType == grampus.ProcessorTypeNPU {
  325. prepareGrampusSpecs(ctx, models.NPU)
  326. } else if processType == grampus.ProcessorTypeGPU {
  327. prepareGrampusSpecs(ctx, models.GPU)
  328. }
  329. //get branches
  330. branches, _, err := ctx.Repo.GitRepo.GetBranches(0, 0)
  331. if err != nil {
  332. log.Error("GetBranches error:", err.Error())
  333. } else {
  334. ctx.Data["branches"] = branches
  335. }
  336. ctx.Data["branchName"] = ctx.Repo.BranchName
  337. if processType == grampus.ProcessorTypeGPU {
  338. ctx.Data["datasetType"] = models.TypeCloudBrainOne
  339. waitCount := cloudbrain.GetWaitingCloudbrainCount(models.TypeC2Net, models.GPUResource, models.JobTypeTrain)
  340. ctx.Data["WaitCount"] = waitCount
  341. NotStopTaskCount, _ := cloudbrainTask.GetNotFinalStatusTaskCount(ctx.User.ID, models.TypeC2Net, string(models.JobTypeTrain), models.GPUResource)
  342. ctx.Data["NotStopTaskCount"] = NotStopTaskCount
  343. } else if processType == grampus.ProcessorTypeNPU {
  344. ctx.Data["datasetType"] = models.TypeCloudBrainTwo
  345. waitCount := cloudbrain.GetWaitingCloudbrainCount(models.TypeC2Net, models.NPUResource, models.JobTypeTrain)
  346. ctx.Data["WaitCount"] = waitCount
  347. NotStopTaskCount, _ := cloudbrainTask.GetNotFinalStatusTaskCount(ctx.User.ID, models.TypeC2Net, string(models.JobTypeTrain), models.NPUResource)
  348. ctx.Data["NotStopTaskCount"] = NotStopTaskCount
  349. }
  350. if ctx.Cloudbrain != nil {
  351. uuids, datasetNames := dataset.GetFilterDeletedAttachments(ctx.Cloudbrain.Uuid)
  352. ctx.Data["attachment"] = uuids
  353. ctx.Data["boot_file"] = ctx.Cloudbrain.BootFile
  354. ctx.Data["image_id"] = ctx.Cloudbrain.ImageID
  355. ctx.Data["run_para_list"] = ctx.Cloudbrain.Parameters
  356. ctx.Data["description"] = ctx.Cloudbrain.Description
  357. ctx.Data["branch_name"] = ctx.Cloudbrain.BranchName
  358. ctx.Data["engine_name"] = ctx.Cloudbrain.EngineName
  359. ctx.Data["work_server_number"] = ctx.Cloudbrain.WorkServerNumber
  360. if ctx.Cloudbrain.Image != "" {
  361. ctx.Data["image"] = ctx.Cloudbrain.Image
  362. } else {
  363. ctx.Data["image"] = ctx.Cloudbrain.EngineName
  364. }
  365. ctx.Data["dataset_name"] = datasetNames
  366. ctx.Data["model_name"] = ctx.Cloudbrain.ModelName
  367. ctx.Data["model_version"] = ctx.Cloudbrain.ModelVersion
  368. ctx.Data["ckpt_name"] = ctx.Cloudbrain.CkptName
  369. ctx.Data["label_names"] = ctx.Cloudbrain.LabelName
  370. ctx.Data["pre_train_model_url"] = ctx.Cloudbrain.PreTrainModelUrl
  371. spec, _ := resource.GetCloudbrainSpec(ctx.Cloudbrain.ID)
  372. if spec != nil {
  373. ctx.Data["spec_id"] = spec.ID
  374. }
  375. }
  376. return nil
  377. }
  378. func GrampusTrainJobVersionNew(ctx *context.Context) {
  379. task := ctx.Cloudbrain
  380. ctx.Data["IsCreate"] = false
  381. if task.ComputeResource == models.GPUResource {
  382. err := grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  383. if err != nil {
  384. ctx.ServerError("get new train-job version info failed", err)
  385. return
  386. }
  387. ctx.HTML(http.StatusOK, tplGrampusTrainJobGPUNew)
  388. } else if task.ComputeResource == models.NPUResource {
  389. err := grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  390. if err != nil {
  391. ctx.ServerError("get new train-job version info failed", err)
  392. return
  393. }
  394. ctx.HTML(200, tplGrampusTrainJobNPUNew)
  395. }
  396. }
  397. func prepareGrampusSpecs(ctx *context.Context, computeResource string, jobType ...models.JobType) {
  398. tempJobType := models.JobTypeTrain
  399. if len(jobType) > 0 {
  400. tempJobType = jobType[0]
  401. }
  402. noteBookSpecs, _ := resource.FindAvailableSpecs(ctx.User.ID, models.FindSpecsOptions{
  403. JobType: tempJobType,
  404. ComputeResource: computeResource,
  405. Cluster: models.C2NetCluster,
  406. })
  407. ctx.Data["Specs"] = noteBookSpecs
  408. }
  409. func grampusParamCheckCreateTrainJob(form auth.CreateGrampusTrainJobForm) error {
  410. if !strings.HasSuffix(strings.TrimSpace(form.BootFile), ".py") {
  411. log.Error("the boot file(%s) must be a python file", form.BootFile)
  412. return errors.New("启动文件必须是python文件")
  413. }
  414. if form.BranchName == "" {
  415. log.Error("the branch must not be null!", form.BranchName)
  416. return errors.New("代码分支不能为空!")
  417. }
  418. return nil
  419. }
  420. func GrampusTrainJobGpuCreate(ctx *context.Context, form auth.CreateGrampusTrainJobForm) {
  421. ctx.Data["IsCreate"] = true
  422. grampusTrainJobGpuCreate(ctx, form)
  423. }
  424. func grampusTrainJobGpuCreate(ctx *context.Context, form auth.CreateGrampusTrainJobForm) {
  425. displayJobName := form.DisplayJobName
  426. jobName := util.ConvertDisplayJobNameToJobName(displayJobName)
  427. uuid := form.Attachment
  428. description := form.Description
  429. bootFile := strings.TrimSpace(form.BootFile)
  430. params := form.Params
  431. repo := ctx.Repo.Repository
  432. codeLocalPath := setting.JobPath + jobName + cloudbrain.CodeMountPath + "/"
  433. codeMinioPath := setting.CBCodePathPrefix + jobName + cloudbrain.CodeMountPath + "/"
  434. branchName := form.BranchName
  435. image := strings.TrimSpace(form.Image)
  436. tpl := tplGrampusTrainJobGPUNew
  437. lock := redis_lock.NewDistributeLock(redis_key.CloudbrainBindingJobNameKey(fmt.Sprint(repo.ID), string(models.JobTypeTrain), displayJobName))
  438. isOk, err := lock.Lock(models.CloudbrainKeyDuration)
  439. if !isOk {
  440. log.Error("lock processed failed:%v", err, ctx.Data["MsgID"])
  441. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  442. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_samejob_err"), tplGrampusTrainJobGPUNew, &form)
  443. return
  444. }
  445. defer lock.UnLock()
  446. if !jobNamePattern.MatchString(displayJobName) {
  447. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  448. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_jobname_err"), tpl, &form)
  449. return
  450. }
  451. bootFileExist, err := ctx.Repo.FileExists(bootFile, branchName)
  452. if err != nil || !bootFileExist {
  453. log.Error("Get bootfile error:", err, ctx.Data["MsgID"])
  454. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  455. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_bootfile_err"), tpl, &form)
  456. return
  457. }
  458. //check count limit
  459. count, err := cloudbrainTask.GetNotFinalStatusTaskCount(ctx.User.ID, models.TypeC2Net, string(models.JobTypeTrain), models.GPUResource)
  460. if err != nil {
  461. log.Error("GetGrampusCountByUserID failed:%v", err, ctx.Data["MsgID"])
  462. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  463. ctx.RenderWithErr("system error", tpl, &form)
  464. return
  465. } else {
  466. if count >= 1 {
  467. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  468. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  469. ctx.RenderWithErr("you have already a running or waiting task, can not create more", tpl, &form)
  470. return
  471. }
  472. }
  473. //check param
  474. if err := grampusParamCheckCreateTrainJob(form); err != nil {
  475. log.Error("paramCheckCreateTrainJob failed:(%v)", err, ctx.Data["MsgID"])
  476. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  477. ctx.RenderWithErr(err.Error(), tpl, &form)
  478. return
  479. }
  480. //check whether the task name in the project is duplicated
  481. tasks, err := models.GetCloudbrainsByDisplayJobName(repo.ID, string(models.JobTypeTrain), displayJobName)
  482. if err == nil {
  483. if len(tasks) != 0 {
  484. log.Error("the job name did already exist", ctx.Data["MsgID"])
  485. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  486. ctx.RenderWithErr("the job name did already exist", tpl, &form)
  487. return
  488. }
  489. } else {
  490. if !models.IsErrJobNotExist(err) {
  491. log.Error("system error, %v", err, ctx.Data["MsgID"])
  492. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  493. ctx.RenderWithErr("system error", tpl, &form)
  494. return
  495. }
  496. }
  497. //check specification
  498. spec, err := resource.GetAndCheckSpec(ctx.User.ID, form.SpecId, models.FindSpecsOptions{
  499. JobType: models.JobTypeTrain,
  500. ComputeResource: models.GPU,
  501. Cluster: models.C2NetCluster,
  502. })
  503. if err != nil || spec == nil {
  504. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  505. ctx.RenderWithErr("Resource specification not available", tpl, &form)
  506. return
  507. }
  508. if !account.IsPointBalanceEnough(ctx.User.ID, spec.UnitPrice) {
  509. log.Error("point balance is not enough,userId=%d specId=%d", ctx.User.ID, spec.ID)
  510. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  511. ctx.RenderWithErr(ctx.Tr("points.insufficient_points_balance"), tplGrampusTrainJobGPUNew, &form)
  512. return
  513. }
  514. //check dataset
  515. datasetInfos, datasetNames, err := models.GetDatasetInfo(uuid, models.GPU)
  516. if err != nil {
  517. log.Error("GetDatasetInfo failed: %v", err, ctx.Data["MsgID"])
  518. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  519. ctx.RenderWithErr(ctx.Tr("cloudbrain.error.dataset_select"), tpl, &form)
  520. return
  521. }
  522. //prepare code and out path
  523. _, err = ioutil.ReadDir(codeLocalPath)
  524. if err == nil {
  525. os.RemoveAll(codeLocalPath)
  526. }
  527. if err := downloadZipCode(ctx, codeLocalPath, branchName); err != nil {
  528. log.Error("downloadZipCode failed, server timed out: %s (%v)", repo.FullName(), err, ctx.Data["MsgID"])
  529. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  530. ctx.RenderWithErr(ctx.Tr("cloudbrain.load_code_failed"), tpl, &form)
  531. return
  532. }
  533. //todo: upload code (send to file_server todo this work?)
  534. //upload code
  535. if err := uploadCodeToMinio(codeLocalPath+"/", jobName, cloudbrain.CodeMountPath+"/"); err != nil {
  536. log.Error("Failed to uploadCodeToMinio: %s (%v)", repo.FullName(), err, ctx.Data["MsgID"])
  537. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  538. ctx.RenderWithErr(ctx.Tr("cloudbrain.load_code_failed"), tpl, &form)
  539. return
  540. }
  541. modelPath := setting.JobPath + jobName + cloudbrain.ModelMountPath + "/"
  542. if err := mkModelPath(modelPath); err != nil {
  543. log.Error("Failed to mkModelPath: %s (%v)", repo.FullName(), err, ctx.Data["MsgID"])
  544. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  545. ctx.RenderWithErr(ctx.Tr("cloudbrain.load_code_failed"), tpl, &form)
  546. return
  547. }
  548. //init model readme
  549. if err := uploadCodeToMinio(modelPath, jobName, cloudbrain.ModelMountPath+"/"); err != nil {
  550. log.Error("Failed to uploadCodeToMinio: %s (%v)", repo.FullName(), err, ctx.Data["MsgID"])
  551. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  552. ctx.RenderWithErr(ctx.Tr("cloudbrain.load_code_failed"), tpl, &form)
  553. return
  554. }
  555. var datasetRemotePath, allFileName string
  556. for _, datasetInfo := range datasetInfos {
  557. if datasetRemotePath == "" {
  558. datasetRemotePath = datasetInfo.DataLocalPath
  559. allFileName = datasetInfo.FullName
  560. } else {
  561. datasetRemotePath = datasetRemotePath + ";" + datasetInfo.DataLocalPath
  562. allFileName = allFileName + ";" + datasetInfo.FullName
  563. }
  564. }
  565. //prepare command
  566. preTrainModelPath := getPreTrainModelPath(form.PreTrainModelUrl, form.CkptName)
  567. command, err := generateCommand(repo.Name, grampus.ProcessorTypeGPU, codeMinioPath+cloudbrain.DefaultBranchName+".zip", datasetRemotePath, bootFile, params, setting.CBCodePathPrefix+jobName+cloudbrain.ModelMountPath+"/", allFileName, preTrainModelPath, form.CkptName, "")
  568. if err != nil {
  569. log.Error("Failed to generateCommand: %s (%v)", displayJobName, err, ctx.Data["MsgID"])
  570. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  571. ctx.RenderWithErr("Create task failed, internal error", tpl, &form)
  572. return
  573. }
  574. commitID, _ := ctx.Repo.GitRepo.GetBranchCommitID(branchName)
  575. req := &grampus.GenerateTrainJobReq{
  576. JobName: jobName,
  577. DisplayJobName: displayJobName,
  578. ComputeResource: models.GPUResource,
  579. ProcessType: grampus.ProcessorTypeGPU,
  580. Command: command,
  581. ImageUrl: image,
  582. Description: description,
  583. BootFile: bootFile,
  584. Uuid: uuid,
  585. CommitID: commitID,
  586. BranchName: branchName,
  587. Params: form.Params,
  588. EngineName: image,
  589. DatasetNames: datasetNames,
  590. DatasetInfos: datasetInfos,
  591. IsLatestVersion: modelarts.IsLatestVersion,
  592. VersionCount: modelarts.VersionCountOne,
  593. WorkServerNumber: 1,
  594. Spec: spec,
  595. }
  596. if form.ModelName != "" { //使用预训练模型训练
  597. req.ModelName = form.ModelName
  598. req.LabelName = form.LabelName
  599. req.CkptName = form.CkptName
  600. req.ModelVersion = form.ModelVersion
  601. req.PreTrainModelUrl = form.PreTrainModelUrl
  602. }
  603. _, err = grampus.GenerateTrainJob(ctx, req)
  604. if err != nil {
  605. log.Error("GenerateTrainJob failed:%v", err.Error(), ctx.Data["MsgID"])
  606. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  607. ctx.RenderWithErr(err.Error(), tpl, &form)
  608. return
  609. }
  610. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/train-job")
  611. }
  612. func getPreTrainModelPath(pretrainModelDir string, fileName string) string {
  613. index := strings.Index(pretrainModelDir, "/")
  614. if index > 0 {
  615. filterBucket := pretrainModelDir[index+1:]
  616. return filterBucket + fileName
  617. } else {
  618. return ""
  619. }
  620. }
  621. func GrampusTrainJobVersionCreate(ctx *context.Context, form auth.CreateGrampusTrainJobForm) {
  622. ctx.Data["IsCreate"] = false
  623. computeResource := ctx.Query("compute_resource")
  624. if computeResource == models.GPUResource {
  625. grampusTrainJobGpuCreate(ctx, form)
  626. } else if computeResource == models.NPUResource {
  627. grampusTrainJobNpuCreate(ctx, form)
  628. } else {
  629. ctx.ServerError("resource error", errors.New("compute resource is not support"))
  630. return
  631. }
  632. }
  633. func GrampusTrainJobNpuCreate(ctx *context.Context, form auth.CreateGrampusTrainJobForm) {
  634. ctx.Data["IsCreate"] = true
  635. grampusTrainJobNpuCreate(ctx, form)
  636. }
  637. func grampusTrainJobNpuCreate(ctx *context.Context, form auth.CreateGrampusTrainJobForm) {
  638. displayJobName := form.DisplayJobName
  639. jobName := util.ConvertDisplayJobNameToJobName(displayJobName)
  640. uuid := form.Attachment
  641. description := form.Description
  642. bootFile := strings.TrimSpace(form.BootFile)
  643. params := form.Params
  644. repo := ctx.Repo.Repository
  645. codeLocalPath := setting.JobPath + jobName + modelarts.CodePath
  646. codeObsPath := grampus.JobPath + jobName + modelarts.CodePath
  647. //dataObsPath := setting.BasePath + path.Join(uuid[0:1], uuid[1:2]) + "/" + uuid + "/"
  648. branchName := form.BranchName
  649. isLatestVersion := modelarts.IsLatestVersion
  650. versionCount := modelarts.VersionCountOne
  651. engineName := form.EngineName
  652. tpl := tplGrampusTrainJobNPUNew
  653. lock := redis_lock.NewDistributeLock(redis_key.CloudbrainBindingJobNameKey(fmt.Sprint(repo.ID), string(models.JobTypeTrain), displayJobName))
  654. isOk, err := lock.Lock(models.CloudbrainKeyDuration)
  655. if !isOk {
  656. log.Error("lock processed failed:%v", err, ctx.Data["MsgID"])
  657. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  658. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_samejob_err"), tplGrampusTrainJobNPUNew, &form)
  659. return
  660. }
  661. defer lock.UnLock()
  662. if !jobNamePattern.MatchString(displayJobName) {
  663. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  664. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_jobname_err"), tpl, &form)
  665. return
  666. }
  667. bootFileExist, err := ctx.Repo.FileExists(bootFile, branchName)
  668. if err != nil || !bootFileExist {
  669. log.Error("Get bootfile error:", err, ctx.Data["MsgID"])
  670. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  671. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_bootfile_err"), tpl, &form)
  672. return
  673. }
  674. //check count limit
  675. count, err := cloudbrainTask.GetNotFinalStatusTaskCount(ctx.User.ID, models.TypeC2Net, string(models.JobTypeTrain), models.NPUResource)
  676. if err != nil {
  677. log.Error("GetGrampusCountByUserID failed:%v", err, ctx.Data["MsgID"])
  678. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  679. ctx.RenderWithErr("system error", tpl, &form)
  680. return
  681. } else {
  682. if count >= 1 {
  683. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  684. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  685. ctx.RenderWithErr("you have already a running or waiting task, can not create more", tpl, &form)
  686. return
  687. }
  688. }
  689. //check param
  690. if err := grampusParamCheckCreateTrainJob(form); err != nil {
  691. log.Error("paramCheckCreateTrainJob failed:(%v)", err)
  692. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  693. ctx.RenderWithErr(err.Error(), tpl, &form)
  694. return
  695. }
  696. //check whether the task name in the project is duplicated
  697. tasks, err := models.GetCloudbrainsByDisplayJobName(repo.ID, string(models.JobTypeTrain), displayJobName)
  698. if err == nil {
  699. if len(tasks) != 0 {
  700. log.Error("the job name did already exist", ctx.Data["MsgID"])
  701. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  702. ctx.RenderWithErr("the job name did already exist", tpl, &form)
  703. return
  704. }
  705. } else {
  706. if !models.IsErrJobNotExist(err) {
  707. log.Error("system error, %v", err, ctx.Data["MsgID"])
  708. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  709. ctx.RenderWithErr("system error", tpl, &form)
  710. return
  711. }
  712. }
  713. //check specification
  714. spec, err := resource.GetAndCheckSpec(ctx.User.ID, form.SpecId, models.FindSpecsOptions{
  715. JobType: models.JobTypeTrain,
  716. ComputeResource: models.NPU,
  717. Cluster: models.C2NetCluster,
  718. })
  719. if err != nil || spec == nil {
  720. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  721. ctx.RenderWithErr("Resource specification not available", tpl, &form)
  722. return
  723. }
  724. if !account.IsPointBalanceEnough(ctx.User.ID, spec.UnitPrice) {
  725. log.Error("point balance is not enough,userId=%d specId=%d", ctx.User.ID, spec.ID)
  726. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  727. ctx.RenderWithErr(ctx.Tr("points.insufficient_points_balance"), tplGrampusTrainJobNPUNew, &form)
  728. return
  729. }
  730. //check dataset
  731. datasetInfos, datasetNames, err := models.GetDatasetInfo(uuid, models.NPU)
  732. if err != nil {
  733. log.Error("GetDatasetInfo failed: %v", err, ctx.Data["MsgID"])
  734. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  735. ctx.RenderWithErr(ctx.Tr("cloudbrain.error.dataset_select"), tpl, &form)
  736. return
  737. }
  738. //prepare code and out path
  739. _, err = ioutil.ReadDir(codeLocalPath)
  740. if err == nil {
  741. os.RemoveAll(codeLocalPath)
  742. }
  743. if err := downloadZipCode(ctx, codeLocalPath, branchName); err != nil {
  744. log.Error("downloadZipCode failed, server timed out: %s (%v)", repo.FullName(), err)
  745. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  746. ctx.RenderWithErr(ctx.Tr("cloudbrain.load_code_failed"), tpl, &form)
  747. return
  748. }
  749. //todo: upload code (send to file_server todo this work?)
  750. if err := obsMkdir(setting.CodePathPrefix + jobName + modelarts.OutputPath); err != nil {
  751. log.Error("Failed to obsMkdir_output: %s (%v)", repo.FullName(), err)
  752. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  753. ctx.RenderWithErr(ctx.Tr("cloudbrain.load_code_failed"), tpl, &form)
  754. return
  755. }
  756. if err := uploadCodeToObs(codeLocalPath, jobName, ""); err != nil {
  757. log.Error("Failed to uploadCodeToObs: %s (%v)", repo.FullName(), err)
  758. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  759. ctx.RenderWithErr(ctx.Tr("cloudbrain.load_code_failed"), tpl, &form)
  760. return
  761. }
  762. var datasetRemotePath, allFileName string
  763. for _, datasetInfo := range datasetInfos {
  764. if datasetRemotePath == "" {
  765. datasetRemotePath = datasetInfo.DataLocalPath + "'" + datasetInfo.FullName + "'"
  766. allFileName = datasetInfo.FullName
  767. } else {
  768. datasetRemotePath = datasetRemotePath + ";" + datasetInfo.DataLocalPath + "'" + datasetInfo.FullName + "'"
  769. allFileName = allFileName + ";" + datasetInfo.FullName
  770. }
  771. }
  772. //prepare command
  773. preTrainModelPath := getPreTrainModelPath(form.PreTrainModelUrl, form.CkptName)
  774. command, err := generateCommand(repo.Name, grampus.ProcessorTypeNPU, codeObsPath+cloudbrain.DefaultBranchName+".zip", datasetRemotePath, bootFile, params, setting.CodePathPrefix+jobName+modelarts.OutputPath, allFileName, preTrainModelPath, form.CkptName, grampus.GetNpuModelRemoteObsUrl(jobName))
  775. if err != nil {
  776. log.Error("Failed to generateCommand: %s (%v)", displayJobName, err, ctx.Data["MsgID"])
  777. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  778. ctx.RenderWithErr("Create task failed, internal error", tpl, &form)
  779. return
  780. }
  781. commitID, _ := ctx.Repo.GitRepo.GetBranchCommitID(branchName)
  782. req := &grampus.GenerateTrainJobReq{
  783. JobName: jobName,
  784. DisplayJobName: displayJobName,
  785. ComputeResource: models.NPUResource,
  786. ProcessType: grampus.ProcessorTypeNPU,
  787. Command: command,
  788. ImageId: form.ImageID,
  789. Description: description,
  790. CodeObsPath: codeObsPath,
  791. BootFileUrl: codeObsPath + bootFile,
  792. BootFile: bootFile,
  793. WorkServerNumber: form.WorkServerNumber,
  794. Uuid: uuid,
  795. CommitID: commitID,
  796. IsLatestVersion: isLatestVersion,
  797. BranchName: branchName,
  798. Params: form.Params,
  799. EngineName: engineName,
  800. VersionCount: versionCount,
  801. TotalVersionCount: modelarts.TotalVersionCount,
  802. DatasetNames: datasetNames,
  803. DatasetInfos: datasetInfos,
  804. Spec: spec,
  805. CodeName: strings.ToLower(repo.Name),
  806. }
  807. if form.ModelName != "" { //使用预训练模型训练
  808. req.ModelName = form.ModelName
  809. req.LabelName = form.LabelName
  810. req.CkptName = form.CkptName
  811. req.ModelVersion = form.ModelVersion
  812. req.PreTrainModelUrl = form.PreTrainModelUrl
  813. req.PreTrainModelPath = preTrainModelPath
  814. }
  815. _, err = grampus.GenerateTrainJob(ctx, req)
  816. if err != nil {
  817. log.Error("GenerateTrainJob failed:%v", err.Error())
  818. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  819. ctx.RenderWithErr(err.Error(), tpl, &form)
  820. return
  821. }
  822. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/train-job")
  823. }
  824. func GetGrampusNotebook(ctx *context.APIContext) {
  825. var (
  826. err error
  827. )
  828. ID := ctx.Params(":id")
  829. job, err := models.GetCloudbrainByID(ID)
  830. if err != nil {
  831. ctx.NotFound("", err)
  832. log.Error("GetCloudbrainByID failed:", err)
  833. return
  834. }
  835. jobAfter, err := cloudbrainTask.SyncGrampusNotebookStatus(job)
  836. aiCenterName := cloudbrainService.GetAiCenterShow(jobAfter.AiCenter, ctx.Context)
  837. if err != nil {
  838. ctx.NotFound(err)
  839. log.Error("Sync cloud brain one status failed:", err)
  840. return
  841. }
  842. ctx.JSON(http.StatusOK, map[string]interface{}{
  843. "ID": ID,
  844. "JobName": jobAfter.JobName,
  845. "JobStatus": jobAfter.Status,
  846. "AiCenter": aiCenterName,
  847. "CreatedTime": jobAfter.CreatedUnix.Format("2006-01-02 15:04:05"),
  848. "CompletedTime": jobAfter.UpdatedUnix.Format("2006-01-02 15:04:05"),
  849. "JobDuration": jobAfter.TrainJobDuration,
  850. })
  851. }
  852. func GrampusStopJob(ctx *context.Context) {
  853. var ID = ctx.Params(":id")
  854. var resultCode = "0"
  855. var errorMsg = ""
  856. var status = ""
  857. task := ctx.Cloudbrain
  858. for {
  859. if task.Status == models.GrampusStatusStopped || task.Status == models.GrampusStatusFailed || task.Status == models.GrampusStatusSucceeded {
  860. log.Error("the job(%s) has been stopped", task.JobName, ctx.Data["msgID"])
  861. resultCode = "-1"
  862. errorMsg = ctx.Tr("cloudbrain.Already_stopped")
  863. break
  864. }
  865. res, err := grampus.StopJob(task.JobID, task.JobType)
  866. if err != nil {
  867. log.Error("StopJob(%s) failed:%v", task.JobName, err, ctx.Data["msgID"])
  868. resultCode = strconv.Itoa(res.ErrorCode)
  869. errorMsg = ctx.Tr("cloudbrain.Stopped_failed")
  870. break
  871. }
  872. oldStatus := task.Status
  873. task.Status = getStopJobResponseStatus(res)
  874. if task.EndTime == 0 {
  875. task.EndTime = timeutil.TimeStampNow()
  876. }
  877. task.ComputeAndSetDuration()
  878. if oldStatus != task.Status {
  879. notification.NotifyChangeCloudbrainStatus(task, oldStatus)
  880. }
  881. err = models.UpdateJob(task)
  882. if err != nil {
  883. log.Error("UpdateJob(%s) failed:%v", task.JobName, err, ctx.Data["msgID"])
  884. resultCode = "-1"
  885. errorMsg = "system error"
  886. break
  887. }
  888. status = task.Status
  889. break
  890. }
  891. ctx.JSON(200, map[string]interface{}{
  892. "result_code": resultCode,
  893. "error_msg": errorMsg,
  894. "status": status,
  895. "id": ID,
  896. "StatusOK": 0,
  897. })
  898. }
  899. func getStopJobResponseStatus(res *models.GrampusStopJobResponse) string {
  900. newStatus := models.GrampusStatusStopping
  901. if res.Status != "" {
  902. newStatus = grampus.TransTrainJobStatus(res.Status)
  903. }
  904. return newStatus
  905. }
  906. func GrampusNotebookDel(ctx *context.Context) {
  907. var listType = ctx.Query("listType")
  908. if err := deleteGrampusJob(ctx); err != nil {
  909. log.Error("deleteGrampusJob failed: %v", err, ctx.Data["msgID"])
  910. ctx.ServerError(err.Error(), err)
  911. return
  912. }
  913. var isAdminPage = ctx.Query("isadminpage")
  914. var isHomePage = ctx.Query("ishomepage")
  915. if ctx.IsUserSiteAdmin() && isAdminPage == "true" {
  916. ctx.Redirect(setting.AppSubURL + "/admin" + "/cloudbrains")
  917. } else if isHomePage == "true" {
  918. ctx.Redirect(setting.AppSubURL + "/cloudbrains")
  919. } else {
  920. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/debugjob?debugListType=" + listType)
  921. }
  922. }
  923. func GrampusTrainJobDel(ctx *context.Context) {
  924. var listType = ctx.Query("listType")
  925. if err := deleteGrampusJob(ctx); err != nil {
  926. log.Error("deleteGrampusJob failed: %v", err, ctx.Data["msgID"])
  927. ctx.ServerError(err.Error(), err)
  928. return
  929. }
  930. var isAdminPage = ctx.Query("isadminpage")
  931. var isHomePage = ctx.Query("ishomepage")
  932. if ctx.IsUserSiteAdmin() && isAdminPage == "true" {
  933. ctx.Redirect(setting.AppSubURL + "/admin" + "/cloudbrains")
  934. } else if isHomePage == "true" {
  935. ctx.Redirect(setting.AppSubURL + "/cloudbrains")
  936. } else {
  937. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/train-job?listType=" + listType)
  938. }
  939. }
  940. func deleteGrampusJob(ctx *context.Context) error {
  941. task := ctx.Cloudbrain
  942. if task.Status != models.GrampusStatusStopped && task.Status != models.GrampusStatusSucceeded && task.Status != models.GrampusStatusFailed {
  943. log.Error("the job(%s) has not been stopped", task.JobName, ctx.Data["msgID"])
  944. return errors.New(ctx.Tr("cloudbrain.Not_Stopped"))
  945. }
  946. err := models.DeleteJob(task)
  947. if err != nil {
  948. log.Error("DeleteJob failed: %v", err, ctx.Data["msgID"])
  949. return err
  950. }
  951. storageType := models.TypeCloudBrainOne
  952. if task.ComputeResource == models.NPUResource {
  953. storageType = models.TypeCloudBrainTwo
  954. }
  955. DeleteCloudbrainJobStorage(task.JobName, storageType)
  956. return nil
  957. }
  958. type NotebookDataset struct {
  959. DatasetUrl string `json:"dataset_url"`
  960. }
  961. func GrampusNotebookShow(ctx *context.Context) {
  962. ctx.Data["PageIsCloudBrain"] = true
  963. var task *models.Cloudbrain
  964. task, err := models.GetCloudbrainByIDWithDeleted(ctx.Params(":id"))
  965. if err != nil {
  966. log.Error("GetCloudbrainByID failed:" + err.Error())
  967. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  968. return
  969. }
  970. task.ContainerIp = ""
  971. if task.DeletedAt.IsZero() && cloudbrainTask.IsTaskNotStop(task) { //normal record
  972. result, err := grampus.GetNotebookJob(task.JobID)
  973. if err != nil {
  974. log.Error("GetJob failed:" + err.Error())
  975. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  976. return
  977. }
  978. if result != nil {
  979. if len(result.JobInfo.Tasks[0].CenterID) == 1 && len(result.JobInfo.Tasks[0].CenterName) == 1 {
  980. task.AiCenter = result.JobInfo.Tasks[0].CenterID[0] + "+" + result.JobInfo.Tasks[0].CenterName[0]
  981. }
  982. oldStatus := task.Status
  983. task.Status = grampus.TransTrainJobStatus(result.JobInfo.Status)
  984. if task.Status != oldStatus || task.Status == models.GrampusStatusRunning {
  985. task.Duration = result.JobInfo.RunSec
  986. if task.Duration < 0 {
  987. task.Duration = 0
  988. }
  989. task.TrainJobDuration = models.ConvertDurationToStr(task.Duration)
  990. if task.StartTime == 0 && result.JobInfo.StartedAt > 0 {
  991. task.StartTime = timeutil.TimeStamp(result.JobInfo.StartedAt)
  992. }
  993. if task.EndTime == 0 && models.IsTrainJobTerminal(task.Status) && task.StartTime > 0 {
  994. task.EndTime = task.StartTime.Add(task.Duration)
  995. }
  996. task.CorrectCreateUnix()
  997. if oldStatus != task.Status {
  998. notification.NotifyChangeCloudbrainStatus(task, oldStatus)
  999. if models.IsTrainJobTerminal(task.Status) && task.ComputeResource == models.NPUResource {
  1000. if len(result.JobInfo.Tasks[0].CenterID) == 1 {
  1001. urchin.GetBackNpuModel(task.ID, grampus.GetRemoteEndPoint(result.JobInfo.Tasks[0].CenterID[0]), grampus.BucketRemote, grampus.GetNpuModelObjectKey(task.JobName), grampus.GetCenterProxy(setting.Grampus.LocalCenterID))
  1002. }
  1003. }
  1004. }
  1005. }
  1006. err = models.UpdateJob(task)
  1007. if err != nil {
  1008. log.Error("UpdateJob failed:" + err.Error())
  1009. }
  1010. }
  1011. }
  1012. if len(task.Parameters) > 0 {
  1013. var parameters models.Parameters
  1014. err := json.Unmarshal([]byte(task.Parameters), &parameters)
  1015. if err != nil {
  1016. log.Error("Failed to Unmarshal Parameters: %s (%v)", task.Parameters, err)
  1017. ctx.ServerError("system error", err)
  1018. return
  1019. }
  1020. if len(parameters.Parameter) > 0 {
  1021. paramTemp := ""
  1022. for _, Parameter := range parameters.Parameter {
  1023. param := Parameter.Label + " = " + Parameter.Value + "; "
  1024. paramTemp = paramTemp + param
  1025. }
  1026. task.Parameters = paramTemp[:len(paramTemp)-2]
  1027. } else {
  1028. task.Parameters = ""
  1029. }
  1030. }
  1031. user, err := models.GetUserByID(task.UserID)
  1032. if err == nil {
  1033. task.User = user
  1034. }
  1035. prepareSpec4Show(ctx, task)
  1036. ctx.Data["task"] = task
  1037. ctx.Data["datasetDownload"] = getDatasetDownloadInfo(ctx, task)
  1038. ctx.Data["modelDownload"] = getModelDownloadInfo(ctx, task)
  1039. ctx.Data["canDownload"] = cloudbrain.CanModifyJob(ctx, task)
  1040. ctx.Data["ai_center"] = cloudbrainService.GetAiCenterShow(task.AiCenter, ctx)
  1041. ctx.Data["code_path"] = cloudbrain.CodeMountPath
  1042. ctx.Data["dataset_path"] = cloudbrain.DataSetMountPath
  1043. ctx.Data["model_path"] = cloudbrain.ModelMountPath
  1044. ctx.HTML(http.StatusOK, tplGrampusNotebookShow)
  1045. }
  1046. func getDatasetDownloadInfo(ctx *context.Context, task *models.Cloudbrain) []*models.DatasetDownload {
  1047. datasetDownload := make([]*models.DatasetDownload, 0)
  1048. if ctx.IsSigned {
  1049. if task.Uuid != "" && task.UserID == ctx.User.ID {
  1050. if task.IsGPUTask() {
  1051. return GetCloudBrainDataSetInfo(task.Uuid, task.DatasetName, false)
  1052. } else {
  1053. datasetDownload = GetCloudBrainDataSetInfo(task.Uuid, task.DatasetName, false)
  1054. datasetObsUrlList := make([]NotebookDataset, 0)
  1055. _ = json.Unmarshal([]byte(task.DataUrl), &datasetObsUrlList)
  1056. for _, datasetInfo := range datasetDownload {
  1057. for _, datasetObs := range datasetObsUrlList {
  1058. log.Info("datasetObsUrl:" + datasetObs.DatasetUrl + "datasetName:" + datasetInfo.DatasetName)
  1059. if strings.Contains(datasetObs.DatasetUrl, datasetInfo.DatasetName) {
  1060. datasetInfo.DatasetDownloadLink = datasetObs.DatasetUrl
  1061. break
  1062. }
  1063. }
  1064. }
  1065. }
  1066. }
  1067. }
  1068. return datasetDownload
  1069. }
  1070. func getModelDownloadInfo(ctx *context.Context, task *models.Cloudbrain) *models.ModelDownload {
  1071. var modelDownload models.ModelDownload
  1072. if ctx.IsSigned {
  1073. if task.ModelName != "" && task.UserID == ctx.User.ID {
  1074. if task.IsNPUTask() {
  1075. modelDownload = models.ModelDownload{
  1076. Name: task.CkptName,
  1077. DownloadLink: "",
  1078. IsDelete: false,
  1079. }
  1080. if !HasModelFile(task) {
  1081. modelDownload.IsDelete = true
  1082. }
  1083. datasetObsUrlList := make([]NotebookDataset, 0)
  1084. _ = json.Unmarshal([]byte(task.DataUrl), &datasetObsUrlList)
  1085. for _, datasetObs := range datasetObsUrlList {
  1086. if strings.Contains(datasetObs.DatasetUrl, task.CkptName) {
  1087. modelDownload.DownloadLink = datasetObs.DatasetUrl
  1088. break
  1089. }
  1090. }
  1091. }
  1092. }
  1093. }
  1094. return &modelDownload
  1095. }
  1096. func GrampusTrainJobShow(ctx *context.Context) {
  1097. ctx.Data["PageIsCloudBrain"] = true
  1098. var task *models.Cloudbrain
  1099. task, err := models.GetCloudbrainByJobIDWithDeleted(ctx.Params(":jobid"))
  1100. if err != nil {
  1101. log.Error("GetCloudbrainByJobID failed:" + err.Error())
  1102. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  1103. return
  1104. }
  1105. task.ContainerIp = ""
  1106. task.User, _ = models.GetUserByID(task.UserID)
  1107. if task.DeletedAt.IsZero() { //normal record
  1108. result, err := grampus.GetJob(task.JobID)
  1109. if err != nil {
  1110. log.Error("GetJob failed:" + err.Error())
  1111. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  1112. return
  1113. }
  1114. if result != nil {
  1115. if len(result.JobInfo.Tasks[0].CenterID) == 1 && len(result.JobInfo.Tasks[0].CenterName) == 1 {
  1116. task.AiCenter = result.JobInfo.Tasks[0].CenterID[0] + "+" + result.JobInfo.Tasks[0].CenterName[0]
  1117. }
  1118. oldStatus := task.Status
  1119. task.Status = grampus.TransTrainJobStatus(result.JobInfo.Status)
  1120. if task.Status != oldStatus || task.Status == models.GrampusStatusRunning {
  1121. task.Duration = result.JobInfo.RunSec
  1122. if task.Duration < 0 {
  1123. task.Duration = 0
  1124. }
  1125. task.TrainJobDuration = models.ConvertDurationToStr(task.Duration)
  1126. if task.StartTime == 0 && result.JobInfo.StartedAt > 0 {
  1127. task.StartTime = timeutil.TimeStamp(result.JobInfo.StartedAt)
  1128. }
  1129. if task.EndTime == 0 && models.IsTrainJobTerminal(task.Status) && task.StartTime > 0 {
  1130. task.EndTime = task.StartTime.Add(task.Duration)
  1131. }
  1132. task.CorrectCreateUnix()
  1133. if oldStatus != task.Status {
  1134. notification.NotifyChangeCloudbrainStatus(task, oldStatus)
  1135. if models.IsTrainJobTerminal(task.Status) && task.ComputeResource == models.NPUResource {
  1136. if len(result.JobInfo.Tasks[0].CenterID) == 1 {
  1137. urchin.GetBackNpuModel(task.ID, grampus.GetRemoteEndPoint(result.JobInfo.Tasks[0].CenterID[0]), grampus.BucketRemote, grampus.GetNpuModelObjectKey(task.JobName), grampus.GetCenterProxy(setting.Grampus.LocalCenterID))
  1138. }
  1139. }
  1140. }
  1141. }
  1142. err = models.UpdateJob(task)
  1143. if err != nil {
  1144. log.Error("UpdateJob failed:" + err.Error())
  1145. }
  1146. }
  1147. }
  1148. if len(task.Parameters) > 0 {
  1149. var parameters models.Parameters
  1150. err := json.Unmarshal([]byte(task.Parameters), &parameters)
  1151. if err != nil {
  1152. log.Error("Failed to Unmarshal Parameters: %s (%v)", task.Parameters, err)
  1153. ctx.ServerError("system error", err)
  1154. return
  1155. }
  1156. if len(parameters.Parameter) > 0 {
  1157. paramTemp := ""
  1158. for _, Parameter := range parameters.Parameter {
  1159. param := Parameter.Label + " = " + Parameter.Value + "; "
  1160. paramTemp = paramTemp + param
  1161. }
  1162. task.Parameters = paramTemp[:len(paramTemp)-2]
  1163. } else {
  1164. task.Parameters = ""
  1165. }
  1166. }
  1167. taskList := make([]*models.Cloudbrain, 0)
  1168. taskList = append(taskList, task)
  1169. prepareSpec4Show(ctx, task)
  1170. ctx.Data["version_list_task"] = taskList
  1171. ctx.Data["datasetDownload"] = GetCloudBrainDataSetInfo(task.Uuid, task.DatasetName, false)
  1172. ctx.Data["canDownload"] = cloudbrain.CanModifyJob(ctx, task)
  1173. ctx.Data["displayJobName"] = task.DisplayJobName
  1174. ctx.Data["ai_center"] = cloudbrainService.GetAiCenterShow(task.AiCenter, ctx)
  1175. ctx.HTML(http.StatusOK, tplGrampusTrainJobShow)
  1176. }
  1177. func GrampusDownloadLog(ctx *context.Context) {
  1178. jobID := ctx.Params(":jobid")
  1179. job, err := models.GetCloudbrainByJobID(jobID)
  1180. if err != nil {
  1181. log.Error("GetCloudbrainByJobID failed: %v", err, ctx.Data["MsgID"])
  1182. ctx.ServerError(err.Error(), err)
  1183. return
  1184. }
  1185. content, err := grampus.GetTrainJobLog(job.JobID)
  1186. if err != nil {
  1187. log.Error("GetTrainJobLog failed: %v", err, ctx.Data["MsgID"])
  1188. content = ""
  1189. }
  1190. fileName := job.JobName + "-log.txt"
  1191. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+fileName)
  1192. ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
  1193. var b []byte = []byte(content)
  1194. ctx.Resp.Write(b)
  1195. }
  1196. func GrampusGetLog(ctx *context.Context) {
  1197. jobID := ctx.Params(":jobid")
  1198. job, err := models.GetCloudbrainByJobID(jobID)
  1199. if err != nil {
  1200. log.Error("GetCloudbrainByJobID failed: %v", err, ctx.Data["MsgID"])
  1201. ctx.ServerError(err.Error(), err)
  1202. return
  1203. }
  1204. content, err := grampus.GetTrainJobLog(job.JobID)
  1205. if err != nil {
  1206. log.Error("GetTrainJobLog failed: %v", err, ctx.Data["MsgID"])
  1207. ctx.JSON(http.StatusOK, map[string]interface{}{
  1208. "JobName": job.JobName,
  1209. "Content": "",
  1210. "CanLogDownload": false,
  1211. })
  1212. return
  1213. }
  1214. canLogDownload := err == nil && job.IsUserHasRight(ctx.User)
  1215. ctx.JSON(http.StatusOK, map[string]interface{}{
  1216. "JobName": job.JobName,
  1217. "Content": content,
  1218. "CanLogDownload": canLogDownload,
  1219. })
  1220. return
  1221. }
  1222. func GrampusMetrics(ctx *context.Context) {
  1223. jobID := ctx.Params(":jobid")
  1224. job, err := models.GetCloudbrainByJobID(jobID)
  1225. if err != nil {
  1226. log.Error("GetCloudbrainByJobID failed: %v", err, ctx.Data["MsgID"])
  1227. ctx.ServerError(err.Error(), err)
  1228. return
  1229. }
  1230. result, err := grampus.GetGrampusMetrics(job.JobID)
  1231. if err != nil {
  1232. log.Error("GetTrainJobLog failed: %v", err, ctx.Data["MsgID"])
  1233. }
  1234. ctx.JSON(http.StatusOK, map[string]interface{}{
  1235. "JobID": jobID,
  1236. "Interval": result.Interval,
  1237. "MetricsInfo": result.MetricsInfo,
  1238. })
  1239. return
  1240. }
  1241. func generateCommand(repoName, processorType, codeRemotePath, dataRemotePath, bootFile, paramSrc, outputRemotePath, datasetName, pretrainModelPath, pretrainModelFileName, modelRemoteObsUrl string) (string, error) {
  1242. var command string
  1243. //prepare
  1244. workDir := grampus.NpuWorkDir
  1245. if processorType == grampus.ProcessorTypeNPU {
  1246. command += "pwd;cd " + workDir + grampus.CommandPrepareScriptNpu
  1247. } else if processorType == grampus.ProcessorTypeGPU {
  1248. workDir = grampus.GpuWorkDir
  1249. command += "pwd;cd " + workDir + fmt.Sprintf(grampus.CommandPrepareScriptGpu, setting.Grampus.SyncScriptProject, setting.Grampus.SyncScriptProject)
  1250. }
  1251. //download code & dataset
  1252. if processorType == grampus.ProcessorTypeNPU {
  1253. //no need to download code & dataset by internet
  1254. } else if processorType == grampus.ProcessorTypeGPU {
  1255. commandDownload := "./downloader_for_minio " + setting.Grampus.Env + " " + codeRemotePath + " " + grampus.CodeArchiveName + " '" + dataRemotePath + "' '" + datasetName + "'"
  1256. commandDownload = processPretrainModelParameter(pretrainModelPath, pretrainModelFileName, commandDownload)
  1257. command += commandDownload
  1258. }
  1259. //unzip code & dataset
  1260. if processorType == grampus.ProcessorTypeNPU {
  1261. //no need to process
  1262. } else if processorType == grampus.ProcessorTypeGPU {
  1263. unZipDatasetCommand := cloudbrainTask.GenerateDatasetUnzipCommand(datasetName)
  1264. commandUnzip := "cd " + workDir + "code;unzip -q master.zip;rm -f master.zip;echo \"start to unzip dataset\";cd " + workDir + "dataset;" + unZipDatasetCommand
  1265. command += commandUnzip
  1266. }
  1267. command += "echo \"unzip finished;start to exec code;\";"
  1268. // set export
  1269. var commandExport string
  1270. if processorType == grampus.ProcessorTypeNPU {
  1271. commandExport = "export bucket=" + setting.Bucket + " && export remote_path=" + outputRemotePath + ";"
  1272. } else if processorType == grampus.ProcessorTypeGPU {
  1273. commandExport = "export env=" + setting.Grampus.Env + " && export remote_path=" + outputRemotePath + ";"
  1274. }
  1275. command += commandExport
  1276. //exec code
  1277. var parameters models.Parameters
  1278. var paramCode string
  1279. if len(paramSrc) != 0 {
  1280. err := json.Unmarshal([]byte(paramSrc), &parameters)
  1281. if err != nil {
  1282. log.Error("Failed to Unmarshal params: %s (%v)", paramSrc, err)
  1283. return command, err
  1284. }
  1285. for _, parameter := range parameters.Parameter {
  1286. paramCode += " --" + parameter.Label + "=" + parameter.Value
  1287. }
  1288. }
  1289. var commandCode string
  1290. if processorType == grampus.ProcessorTypeNPU {
  1291. paramCode += " --model_url=" + modelRemoteObsUrl
  1292. commandCode = "/bin/bash /home/work/run_train_for_openi.sh /home/work/openi.py " + grampus.NpuLocalLogUrl + paramCode + ";"
  1293. } else if processorType == grampus.ProcessorTypeGPU {
  1294. if pretrainModelFileName != "" {
  1295. paramCode += " --ckpt_url" + "=" + workDir + "pretrainmodel/" + pretrainModelFileName
  1296. }
  1297. commandCode = "cd " + workDir + "code/" + strings.ToLower(repoName) + ";python " + bootFile + paramCode + ";"
  1298. }
  1299. command += commandCode
  1300. //get exec result
  1301. commandGetRes := "result=$?;"
  1302. command += commandGetRes
  1303. //upload models
  1304. if processorType == grampus.ProcessorTypeNPU {
  1305. // no need to upload
  1306. } else if processorType == grampus.ProcessorTypeGPU {
  1307. commandUpload := "cd " + workDir + setting.Grampus.SyncScriptProject + "/;./uploader_for_gpu " + setting.Grampus.Env + " " + outputRemotePath + " " + workDir + "output/;"
  1308. command += commandUpload
  1309. }
  1310. //check exec result
  1311. commandCheckRes := "bash -c \"[[ $result -eq 0 ]] && exit 0 || exit -1\""
  1312. command += commandCheckRes
  1313. return command, nil
  1314. }
  1315. func processPretrainModelParameter(pretrainModelPath string, pretrainModelFileName string, commandDownload string) string {
  1316. commandDownloadTemp := commandDownload
  1317. if pretrainModelPath != "" {
  1318. commandDownloadTemp += " '" + pretrainModelPath + "' '" + pretrainModelFileName + "'"
  1319. }
  1320. commandDownloadTemp += ";"
  1321. return commandDownloadTemp
  1322. }
  1323. func downloadZipCode(ctx *context.Context, codePath, branchName string) error {
  1324. archiveType := git.ZIP
  1325. archivePath := codePath
  1326. if !com.IsDir(archivePath) {
  1327. if err := os.MkdirAll(archivePath, os.ModePerm); err != nil {
  1328. log.Error("MkdirAll failed:" + err.Error())
  1329. return err
  1330. }
  1331. }
  1332. // Get corresponding commit.
  1333. var (
  1334. commit *git.Commit
  1335. err error
  1336. )
  1337. gitRepo := ctx.Repo.GitRepo
  1338. if err != nil {
  1339. log.Error("OpenRepository failed:" + err.Error())
  1340. return err
  1341. }
  1342. if gitRepo.IsBranchExist(branchName) {
  1343. commit, err = gitRepo.GetBranchCommit(branchName)
  1344. if err != nil {
  1345. log.Error("GetBranchCommit failed:" + err.Error())
  1346. return err
  1347. }
  1348. } else {
  1349. log.Error("the branch is not exist: " + branchName)
  1350. return fmt.Errorf("The branch does not exist.")
  1351. }
  1352. archivePath = path.Join(archivePath, grampus.CodeArchiveName)
  1353. if !com.IsFile(archivePath) {
  1354. if err := commit.CreateArchive(archivePath, git.CreateArchiveOpts{
  1355. Format: archiveType,
  1356. Prefix: setting.Repository.PrefixArchiveFiles,
  1357. }); err != nil {
  1358. log.Error("CreateArchive failed:" + err.Error())
  1359. return err
  1360. }
  1361. }
  1362. return nil
  1363. }
  1364. func HandleTaskWithAiCenter(ctx *context.Context) {
  1365. log.Info("HandleTaskWithAiCenter start")
  1366. updateCounts := 0
  1367. cloudBrains, err := models.GetC2NetWithAiCenterWrongJob()
  1368. if err != nil {
  1369. log.Error("GetC2NetWithAiCenterWrongJob failed:" + err.Error())
  1370. return
  1371. }
  1372. if len(cloudBrains) == 0 {
  1373. log.Info("HandleC2NetWithAiCenterWrongJob:no task need handle")
  1374. return
  1375. }
  1376. cloudBrainCounts := len(cloudBrains)
  1377. for _, task := range cloudBrains {
  1378. result, err := grampus.GetJob(task.JobID)
  1379. if err != nil {
  1380. log.Error("GetJob failed:" + err.Error())
  1381. continue
  1382. }
  1383. if len(result.JobInfo.Tasks) != 0 {
  1384. if len(result.JobInfo.Tasks[0].CenterID) == 1 && len(result.JobInfo.Tasks[0].CenterName) == 1 {
  1385. task.AiCenter = result.JobInfo.Tasks[0].CenterID[0] + "+" + result.JobInfo.Tasks[0].CenterName[0]
  1386. }
  1387. err = models.UpdateJob(task)
  1388. if err != nil {
  1389. log.Error("UpdateJob failed:" + err.Error())
  1390. }
  1391. updateCounts++
  1392. }
  1393. }
  1394. r := make(map[string]interface{}, 0)
  1395. r["cloudBrainCounts"] = cloudBrainCounts
  1396. r["updateCounts"] = updateCounts
  1397. ctx.JSON(http.StatusOK, response.SuccessWithData(r))
  1398. }
  1399. func GrampusNotebookDebug(ctx *context.Context) {
  1400. result, err := grampus.GetNotebookJob(ctx.Cloudbrain.JobID)
  1401. if err != nil {
  1402. ctx.RenderWithErr(err.Error(), tplDebugJobIndex, nil)
  1403. return
  1404. }
  1405. if len(result.JobInfo.Tasks) > 0 {
  1406. ctx.Redirect(result.JobInfo.Tasks[0].Url + "?token=" + result.JobInfo.Tasks[0].Token)
  1407. return
  1408. }
  1409. ctx.NotFound("Can not find the job.", nil)
  1410. }
  1411. func GrampusNotebookRestart(ctx *context.Context) {
  1412. var id = ctx.Params(":id")
  1413. var resultCode = "-1"
  1414. var errorMsg = ""
  1415. var status = ""
  1416. var spec *models.Specification
  1417. task := ctx.Cloudbrain
  1418. if ctx.Written() {
  1419. return
  1420. }
  1421. for {
  1422. if task.Status != models.GrampusStatusStopped && task.Status != models.GrampusStatusSucceeded && task.Status != models.GrampusStatusFailed {
  1423. log.Error("the job(%s) is not stopped", task.JobName, ctx.Data["MsgID"])
  1424. errorMsg = "the job is not stopped"
  1425. break
  1426. }
  1427. count, err := cloudbrainTask.GetNotFinalStatusTaskCount(ctx.User.ID, models.TypeC2Net, string(models.JobTypeDebug), task.ComputeResource)
  1428. if err != nil {
  1429. log.Error("GetCloudbrainNotebookCountByUserID failed:%v", err, ctx.Data["MsgID"])
  1430. errorMsg = "system error"
  1431. break
  1432. } else {
  1433. if count >= 1 {
  1434. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  1435. resultCode = "2"
  1436. errorMsg = ctx.Tr("repo.cloudbrain.morethanonejob")
  1437. break
  1438. }
  1439. }
  1440. oldSpec, err := resource.GetCloudbrainSpec(task.ID)
  1441. if err != nil || oldSpec == nil {
  1442. log.Error("NotebookManage GetCloudbrainSpec error.%v", err)
  1443. errorMsg = "Resource specification not available"
  1444. break
  1445. }
  1446. computeSourceSimple := models.GPU
  1447. action := models.ActionCreateGrampusGPUDebugTask
  1448. if task.ComputeResource == models.NPUResource {
  1449. computeSourceSimple = models.NPU
  1450. action = models.ActionCreateGrampusNPUDebugTask
  1451. } else if task.ComputeResource == models.GCUResource {
  1452. computeSourceSimple = models.GCU
  1453. action = models.ActionCreateGrampusGCUDebugTask
  1454. }
  1455. spec, err = resource.GetAndCheckSpec(ctx.User.ID, oldSpec.ID, models.FindSpecsOptions{
  1456. JobType: models.JobType(task.JobType),
  1457. ComputeResource: computeSourceSimple,
  1458. Cluster: models.C2NetCluster,
  1459. })
  1460. if err != nil || spec == nil {
  1461. log.Error("NotebookManage GetAndCheckSpec error.task.id = %d", task.ID)
  1462. errorMsg = "Resource specification not support any more"
  1463. break
  1464. }
  1465. if !account.IsPointBalanceEnough(ctx.User.ID, spec.UnitPrice) {
  1466. log.Error("point balance is not enough,userId=%d specId=%d", ctx.User.ID, spec.ID)
  1467. errorMsg = ctx.Tr("points.insufficient_points_balance")
  1468. break
  1469. }
  1470. if task.IsGPUTask() || task.IsGCUTask() {
  1471. if _, err := os.Stat(getOldJobPath(task)); err != nil {
  1472. log.Error("Can not find job minio path", err)
  1473. resultCode = "-1"
  1474. errorMsg = ctx.Tr("cloudbrain.result_cleared")
  1475. break
  1476. }
  1477. }
  1478. if !HasModelFile(task) { //使用预训练模型训练
  1479. errorMsg = ctx.Tr("repo.debug.manage.model_not_exist")
  1480. break
  1481. }
  1482. if hasDatasetDeleted(task) {
  1483. errorMsg = ctx.Tr("repo.debug.manage.dataset_not_exist")
  1484. break
  1485. }
  1486. createTime := timeutil.TimeStampNow()
  1487. res, err := grampus.RestartNotebookJob(task.JobID)
  1488. if err != nil {
  1489. log.Error("ManageNotebook2(%s) failed:%v", task.DisplayJobName, err.Error(), ctx.Data["MsgID"])
  1490. errorMsg = ctx.Tr("repo.debug_again_fail")
  1491. break
  1492. }
  1493. if res.GrampusResult.ErrorCode != 0 || res.NewId == "" {
  1494. log.Error("ManageNotebook2 failed:" + res.GrampusResult.ErrorMsg)
  1495. errorMsg = ctx.Tr("repo.debug_again_fail")
  1496. if res.GrampusResult.ErrorCode == 5005 {
  1497. errorMsg = ctx.Tr("repo.debug_again_fail_forever")
  1498. }
  1499. break
  1500. }
  1501. newTask := &models.Cloudbrain{
  1502. Status: res.Status,
  1503. UserID: task.UserID,
  1504. RepoID: task.RepoID,
  1505. JobID: res.NewId,
  1506. JobName: task.JobName,
  1507. DisplayJobName: task.DisplayJobName,
  1508. JobType: task.JobType,
  1509. Type: task.Type,
  1510. Uuid: task.Uuid,
  1511. Image: task.Image,
  1512. ImageID: task.ImageID,
  1513. EngineID: task.EngineID,
  1514. CommitID: task.CommitID,
  1515. EngineName: task.EngineName,
  1516. IsLatestVersion: "1",
  1517. BranchName: task.BranchName,
  1518. DatasetName: task.DatasetName,
  1519. ComputeResource: task.ComputeResource,
  1520. Description: task.Description,
  1521. CreatedUnix: createTime,
  1522. UpdatedUnix: createTime,
  1523. Spec: spec,
  1524. ModelName: task.ModelName,
  1525. ModelVersion: task.ModelVersion,
  1526. LabelName: task.LabelName,
  1527. PreTrainModelUrl: task.PreTrainModelUrl,
  1528. CkptName: task.CkptName,
  1529. WorkServerNumber: 1,
  1530. }
  1531. err = models.RestartCloudbrain(task, newTask)
  1532. if err != nil {
  1533. log.Error("RestartCloudbrain(%s) failed:%v", task.JobName, err.Error(), ctx.Data["MsgID"])
  1534. errorMsg = "system error"
  1535. break
  1536. }
  1537. id = strconv.FormatInt(newTask.ID, 10)
  1538. status = res.Status
  1539. resultCode = "0"
  1540. notification.NotifyOtherTask(ctx.User, ctx.Repo.Repository, id, newTask.DisplayJobName, action)
  1541. break
  1542. }
  1543. ctx.JSON(200, map[string]string{
  1544. "result_code": resultCode,
  1545. "error_msg": errorMsg,
  1546. "status": status,
  1547. "id": id,
  1548. })
  1549. }