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 26 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786
  1. package repo
  2. import (
  3. "code.gitea.io/gitea/modules/auth"
  4. "code.gitea.io/gitea/modules/git"
  5. "code.gitea.io/gitea/modules/grampus"
  6. "code.gitea.io/gitea/modules/modelarts"
  7. "code.gitea.io/gitea/modules/timeutil"
  8. "code.gitea.io/gitea/modules/util"
  9. "encoding/json"
  10. "errors"
  11. "github.com/unknwon/com"
  12. "io/ioutil"
  13. "net/http"
  14. "os"
  15. "path"
  16. "strconv"
  17. "strings"
  18. "time"
  19. "code.gitea.io/gitea/models"
  20. "code.gitea.io/gitea/modules/base"
  21. "code.gitea.io/gitea/modules/cloudbrain"
  22. "code.gitea.io/gitea/modules/context"
  23. "code.gitea.io/gitea/modules/log"
  24. "code.gitea.io/gitea/modules/setting"
  25. )
  26. const (
  27. tplGrampusTrainJobShow base.TplName = "repo/grampus/trainjob/show"
  28. //GPU
  29. tplGrampusTrainJobGPUNew base.TplName = "repo/grampus/trainjob/gpu/new"
  30. //NPU
  31. tplGrampusTrainJobNPUNew base.TplName = "repo/grampus/trainjob/npu/new"
  32. )
  33. func GrampusTrainJobGPUNew(ctx *context.Context) {
  34. ctx.Data["datasetType"] = models.TypeCloudBrainOne
  35. err := grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  36. if err != nil {
  37. ctx.ServerError("get new train-job info failed", err)
  38. return
  39. }
  40. ctx.HTML(http.StatusOK, tplGrampusTrainJobGPUNew)
  41. }
  42. func GrampusTrainJobNPUNew(ctx *context.Context) {
  43. ctx.Data["datasetType"] = models.TypeCloudBrainTwo
  44. err := grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  45. if err != nil {
  46. ctx.ServerError("get new train-job info failed", err)
  47. return
  48. }
  49. ctx.HTML(200, tplGrampusTrainJobNPUNew)
  50. }
  51. func grampusTrainJobNewDataPrepare(ctx *context.Context, processType string) error {
  52. ctx.Data["PageIsCloudBrain"] = true
  53. t := time.Now()
  54. var displayJobName = cutString(ctx.User.Name, 5) + t.Format("2006010215") + strconv.Itoa(int(t.Unix()))[5:]
  55. ctx.Data["display_job_name"] = displayJobName
  56. //get valid images
  57. images, err := grampus.GetImages(processType)
  58. if err != nil {
  59. log.Error("GetImages failed:", err.Error())
  60. } else {
  61. ctx.Data["images"] = images.Infos
  62. }
  63. grampus.InitSpecialPool()
  64. ctx.Data["GPUEnabled"] = true
  65. ctx.Data["NPUEnabled"] = true
  66. if grampus.SpecialPools != nil {
  67. for _, pool := range grampus.SpecialPools.Pools {
  68. if pool.IsExclusive {
  69. org, _ := models.GetOrgByName(pool.Org)
  70. if org != nil {
  71. isOrgMember, _ := models.IsOrganizationMember(org.ID, ctx.User.ID)
  72. if !isOrgMember {
  73. ctx.Data[pool.Type+"Enabled"] = false
  74. }
  75. }
  76. }
  77. }
  78. }
  79. //get valid resource specs
  80. specs, err := grampus.GetResourceSpecs(processType)
  81. if err != nil {
  82. log.Error("GetResourceSpecs failed:", err.Error())
  83. } else {
  84. ctx.Data["flavor_infos"] = specs.Infos
  85. }
  86. //get branches
  87. branches, _, err := ctx.Repo.GitRepo.GetBranches(0, 0)
  88. if err != nil {
  89. log.Error("GetBranches error:", err.Error())
  90. } else {
  91. ctx.Data["branches"] = branches
  92. }
  93. ctx.Data["branchName"] = ctx.Repo.BranchName
  94. if processType == grampus.ProcessorTypeGPU {
  95. ctx.Data["datasetType"] = models.TypeCloudBrainOne
  96. } else if processType == grampus.ProcessorTypeNPU {
  97. ctx.Data["datasetType"] = models.TypeCloudBrainTwo
  98. }
  99. return nil
  100. }
  101. func grampusParamCheckCreateTrainJob(form auth.CreateGrampusTrainJobForm) error {
  102. if !strings.HasSuffix(strings.TrimSpace(form.BootFile), ".py") {
  103. log.Error("the boot file(%s) must be a python file", form.BootFile)
  104. return errors.New("启动文件必须是python文件")
  105. }
  106. if form.BranchName == "" {
  107. log.Error("the branch must not be null!", form.BranchName)
  108. return errors.New("代码分支不能为空!")
  109. }
  110. return nil
  111. }
  112. func GrampusTrainJobGpuCreate(ctx *context.Context, form auth.CreateGrampusTrainJobForm) {
  113. displayJobName := form.DisplayJobName
  114. jobName := util.ConvertDisplayJobNameToJobName(displayJobName)
  115. uuid := form.Attachment
  116. description := form.Description
  117. bootFile := strings.TrimSpace(form.BootFile)
  118. params := form.Params
  119. repo := ctx.Repo.Repository
  120. codeLocalPath := setting.JobPath + jobName + cloudbrain.CodeMountPath + "/"
  121. codeMinioPath := setting.CBCodePathPrefix + jobName + cloudbrain.CodeMountPath + "/"
  122. dataMinioPath := setting.Attachment.Minio.BasePath + path.Join(uuid[0:1], uuid[1:2]) + "/" + uuid
  123. branchName := form.BranchName
  124. flavorName := form.FlavorName
  125. image := strings.TrimSpace(form.Image)
  126. if !jobNamePattern.MatchString(displayJobName) {
  127. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  128. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_jobname_err"), tplGrampusTrainJobGPUNew, &form)
  129. return
  130. }
  131. errStr := checkSpecialPool(ctx, "GPU")
  132. if errStr != "" {
  133. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  134. ctx.RenderWithErr(errStr, tplGrampusTrainJobGPUNew, &form)
  135. return
  136. }
  137. //check count limit
  138. count, err := models.GetGrampusCountByUserID(ctx.User.ID, string(models.JobTypeTrain), models.GPUResource)
  139. if err != nil {
  140. log.Error("GetGrampusCountByUserID failed:%v", err, ctx.Data["MsgID"])
  141. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  142. ctx.RenderWithErr("system error", tplGrampusTrainJobGPUNew, &form)
  143. return
  144. } else {
  145. if count >= 1 {
  146. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  147. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  148. ctx.RenderWithErr("you have already a running or waiting task, can not create more", tplGrampusTrainJobGPUNew, &form)
  149. return
  150. }
  151. }
  152. //check param
  153. if err := grampusParamCheckCreateTrainJob(form); err != nil {
  154. log.Error("paramCheckCreateTrainJob failed:(%v)", err, ctx.Data["MsgID"])
  155. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  156. ctx.RenderWithErr(err.Error(), tplGrampusTrainJobGPUNew, &form)
  157. return
  158. }
  159. //check whether the task name in the project is duplicated
  160. tasks, err := models.GetCloudbrainsByDisplayJobName(repo.ID, string(models.JobTypeTrain), displayJobName)
  161. if err == nil {
  162. if len(tasks) != 0 {
  163. log.Error("the job name did already exist", ctx.Data["MsgID"])
  164. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  165. ctx.RenderWithErr("the job name did already exist", tplGrampusTrainJobGPUNew, &form)
  166. return
  167. }
  168. } else {
  169. if !models.IsErrJobNotExist(err) {
  170. log.Error("system error, %v", err, ctx.Data["MsgID"])
  171. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  172. ctx.RenderWithErr("system error", tplGrampusTrainJobGPUNew, &form)
  173. return
  174. }
  175. }
  176. //check dataset
  177. attachment, err := models.GetAttachmentByUUID(uuid)
  178. if err != nil {
  179. log.Error("GetAttachmentByUUID failed:", err.Error(), ctx.Data["MsgID"])
  180. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  181. ctx.RenderWithErr("dataset is not exist", tplGrampusTrainJobGPUNew, &form)
  182. return
  183. }
  184. //prepare code and out path
  185. _, err = ioutil.ReadDir(codeLocalPath)
  186. if err == nil {
  187. os.RemoveAll(codeLocalPath)
  188. }
  189. if err := downloadZipCode(ctx, codeLocalPath, branchName); err != nil {
  190. log.Error("downloadZipCode failed, server timed out: %s (%v)", repo.FullName(), err, ctx.Data["MsgID"])
  191. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  192. ctx.RenderWithErr("Create task failed, internal error", tplGrampusTrainJobGPUNew, &form)
  193. return
  194. }
  195. //todo: upload code (send to file_server todo this work?)
  196. //upload code
  197. if err := uploadCodeToMinio(codeLocalPath+"/", jobName, cloudbrain.CodeMountPath+"/"); err != nil {
  198. log.Error("Failed to uploadCodeToMinio: %s (%v)", repo.FullName(), err, ctx.Data["MsgID"])
  199. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  200. ctx.RenderWithErr("Create task failed, internal error", tplGrampusTrainJobGPUNew, &form)
  201. return
  202. }
  203. modelPath := setting.JobPath + jobName + cloudbrain.ModelMountPath + "/"
  204. if err := mkModelPath(modelPath); err != nil {
  205. log.Error("Failed to mkModelPath: %s (%v)", repo.FullName(), err, ctx.Data["MsgID"])
  206. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  207. ctx.RenderWithErr("Create task failed, internal error", tplGrampusTrainJobGPUNew, &form)
  208. return
  209. }
  210. //init model readme
  211. if err := uploadCodeToMinio(modelPath, jobName, cloudbrain.ModelMountPath+"/"); err != nil {
  212. log.Error("Failed to uploadCodeToMinio: %s (%v)", repo.FullName(), err, ctx.Data["MsgID"])
  213. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  214. ctx.RenderWithErr("Create task failed, internal error", tplGrampusTrainJobGPUNew, &form)
  215. return
  216. }
  217. //prepare command
  218. command, err := generateCommand(repo.Name, grampus.ProcessorTypeGPU, codeMinioPath+cloudbrain.DefaultBranchName+".zip", dataMinioPath, bootFile, params, setting.CBCodePathPrefix+jobName+cloudbrain.ModelMountPath+"/", attachment.Name)
  219. if err != nil {
  220. log.Error("Failed to generateCommand: %s (%v)", displayJobName, err, ctx.Data["MsgID"])
  221. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  222. ctx.RenderWithErr("Create task failed, internal error", tplGrampusTrainJobGPUNew, &form)
  223. return
  224. }
  225. commitID, _ := ctx.Repo.GitRepo.GetBranchCommitID(branchName)
  226. req := &grampus.GenerateTrainJobReq{
  227. JobName: jobName,
  228. DisplayJobName: displayJobName,
  229. ComputeResource: models.GPUResource,
  230. Command: command,
  231. ResourceSpecId: form.FlavorID,
  232. ImageUrl: image,
  233. Description: description,
  234. BootFile: bootFile,
  235. Uuid: uuid,
  236. CommitID: commitID,
  237. BranchName: branchName,
  238. Params: form.Params,
  239. FlavorName: flavorName,
  240. EngineName: image,
  241. DatasetName: attachment.Name,
  242. IsLatestVersion: modelarts.IsLatestVersion,
  243. VersionCount: modelarts.VersionCount,
  244. WorkServerNumber: 1,
  245. }
  246. err = grampus.GenerateTrainJob(ctx, req)
  247. if err != nil {
  248. log.Error("GenerateTrainJob failed:%v", err.Error(), ctx.Data["MsgID"])
  249. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  250. ctx.RenderWithErr(err.Error(), tplGrampusTrainJobGPUNew, &form)
  251. return
  252. }
  253. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/train-job")
  254. }
  255. func checkSpecialPool(ctx *context.Context, resourceType string) string {
  256. grampus.InitSpecialPool()
  257. if grampus.SpecialPools != nil {
  258. for _, pool := range grampus.SpecialPools.Pools {
  259. if pool.IsExclusive && pool.Type == resourceType {
  260. org, _ := models.GetOrgByName(pool.Org)
  261. if org != nil {
  262. isOrgMember, _ := models.IsOrganizationMember(org.ID, ctx.User.ID)
  263. if !isOrgMember {
  264. return ctx.Tr("repo.grampus.no_operate_right")
  265. }
  266. }
  267. }
  268. }
  269. }
  270. return ""
  271. }
  272. func GrampusTrainJobNpuCreate(ctx *context.Context, form auth.CreateGrampusTrainJobForm) {
  273. displayJobName := form.DisplayJobName
  274. jobName := util.ConvertDisplayJobNameToJobName(displayJobName)
  275. uuid := form.Attachment
  276. description := form.Description
  277. bootFile := strings.TrimSpace(form.BootFile)
  278. params := form.Params
  279. repo := ctx.Repo.Repository
  280. codeLocalPath := setting.JobPath + jobName + modelarts.CodePath
  281. codeObsPath := grampus.JobPath + jobName + modelarts.CodePath
  282. dataObsPath := setting.BasePath + path.Join(uuid[0:1], uuid[1:2]) + "/" + uuid + "/"
  283. branchName := form.BranchName
  284. isLatestVersion := modelarts.IsLatestVersion
  285. flavorName := form.FlavorName
  286. versionCount := modelarts.VersionCount
  287. engineName := form.EngineName
  288. if !jobNamePattern.MatchString(displayJobName) {
  289. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  290. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_jobname_err"), tplGrampusTrainJobNPUNew, &form)
  291. return
  292. }
  293. errStr := checkSpecialPool(ctx, "NPU")
  294. if errStr != "" {
  295. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  296. ctx.RenderWithErr(errStr, tplGrampusTrainJobGPUNew, &form)
  297. return
  298. }
  299. //check count limit
  300. count, err := models.GetGrampusCountByUserID(ctx.User.ID, string(models.JobTypeTrain), models.NPUResource)
  301. if err != nil {
  302. log.Error("GetGrampusCountByUserID failed:%v", err, ctx.Data["MsgID"])
  303. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  304. ctx.RenderWithErr("system error", tplGrampusTrainJobNPUNew, &form)
  305. return
  306. } else {
  307. if count >= 1 {
  308. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  309. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  310. ctx.RenderWithErr("you have already a running or waiting task, can not create more", tplGrampusTrainJobNPUNew, &form)
  311. return
  312. }
  313. }
  314. //check param
  315. if err := grampusParamCheckCreateTrainJob(form); err != nil {
  316. log.Error("paramCheckCreateTrainJob failed:(%v)", err)
  317. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  318. ctx.RenderWithErr(err.Error(), tplGrampusTrainJobNPUNew, &form)
  319. return
  320. }
  321. //check whether the task name in the project is duplicated
  322. tasks, err := models.GetCloudbrainsByDisplayJobName(repo.ID, string(models.JobTypeTrain), displayJobName)
  323. if err == nil {
  324. if len(tasks) != 0 {
  325. log.Error("the job name did already exist", ctx.Data["MsgID"])
  326. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  327. ctx.RenderWithErr("the job name did already exist", tplGrampusTrainJobNPUNew, &form)
  328. return
  329. }
  330. } else {
  331. if !models.IsErrJobNotExist(err) {
  332. log.Error("system error, %v", err, ctx.Data["MsgID"])
  333. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  334. ctx.RenderWithErr("system error", tplGrampusTrainJobNPUNew, &form)
  335. return
  336. }
  337. }
  338. //check dataset
  339. attachment, err := models.GetAttachmentByUUID(uuid)
  340. if err != nil {
  341. log.Error("GetAttachmentByUUID failed:", err.Error(), ctx.Data["MsgID"])
  342. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  343. ctx.RenderWithErr("dataset is not exist", tplGrampusTrainJobNPUNew, &form)
  344. return
  345. }
  346. //prepare code and out path
  347. _, err = ioutil.ReadDir(codeLocalPath)
  348. if err == nil {
  349. os.RemoveAll(codeLocalPath)
  350. }
  351. if err := downloadZipCode(ctx, codeLocalPath, branchName); err != nil {
  352. log.Error("downloadZipCode failed, server timed out: %s (%v)", repo.FullName(), err)
  353. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  354. ctx.RenderWithErr("Create task failed, server timed out", tplGrampusTrainJobNPUNew, &form)
  355. return
  356. }
  357. //todo: upload code (send to file_server todo this work?)
  358. if err := obsMkdir(setting.CodePathPrefix + jobName + modelarts.OutputPath); err != nil {
  359. log.Error("Failed to obsMkdir_output: %s (%v)", repo.FullName(), err)
  360. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  361. ctx.RenderWithErr("Failed to obsMkdir_output", tplGrampusTrainJobNPUNew, &form)
  362. return
  363. }
  364. if err := uploadCodeToObs(codeLocalPath, jobName, ""); err != nil {
  365. log.Error("Failed to uploadCodeToObs: %s (%v)", repo.FullName(), err)
  366. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  367. ctx.RenderWithErr("Failed to uploadCodeToObs", tplGrampusTrainJobNPUNew, &form)
  368. return
  369. }
  370. //prepare command
  371. command, err := generateCommand(repo.Name, grampus.ProcessorTypeNPU, codeObsPath+cloudbrain.DefaultBranchName+".zip", dataObsPath+"'"+attachment.Name+"'", bootFile, params, setting.CodePathPrefix+jobName+modelarts.OutputPath, attachment.Name)
  372. if err != nil {
  373. log.Error("Failed to generateCommand: %s (%v)", displayJobName, err, ctx.Data["MsgID"])
  374. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  375. ctx.RenderWithErr("Create task failed, internal error", tplGrampusTrainJobNPUNew, &form)
  376. return
  377. }
  378. commitID, _ := ctx.Repo.GitRepo.GetBranchCommitID(branchName)
  379. req := &grampus.GenerateTrainJobReq{
  380. JobName: jobName,
  381. DisplayJobName: displayJobName,
  382. ComputeResource: models.NPUResource,
  383. Command: command,
  384. ResourceSpecId: form.FlavorID,
  385. ImageId: form.ImageID,
  386. DataUrl: dataObsPath,
  387. Description: description,
  388. CodeObsPath: codeObsPath,
  389. BootFileUrl: codeObsPath + bootFile,
  390. BootFile: bootFile,
  391. WorkServerNumber: form.WorkServerNumber,
  392. Uuid: uuid,
  393. CommitID: commitID,
  394. IsLatestVersion: isLatestVersion,
  395. BranchName: branchName,
  396. Params: form.Params,
  397. FlavorName: flavorName,
  398. EngineName: engineName,
  399. VersionCount: versionCount,
  400. TotalVersionCount: modelarts.TotalVersionCount,
  401. DatasetName: attachment.Name,
  402. }
  403. err = grampus.GenerateTrainJob(ctx, req)
  404. if err != nil {
  405. log.Error("GenerateTrainJob failed:%v", err.Error())
  406. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  407. ctx.RenderWithErr(err.Error(), tplGrampusTrainJobNPUNew, &form)
  408. return
  409. }
  410. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/train-job")
  411. }
  412. func GrampusStopJob(ctx *context.Context) {
  413. var ID = ctx.Params(":jobid")
  414. var resultCode = "0"
  415. var errorMsg = ""
  416. var status = ""
  417. task := ctx.Cloudbrain
  418. for {
  419. if task.Status == string(models.GrampusStatusStopped) || task.Status == string(models.GrampusStatusFailed) || task.Status == string(models.GrampusStatusSucceeded) {
  420. log.Error("the job(%s) has been stopped", task.JobName, ctx.Data["msgID"])
  421. resultCode = "-1"
  422. errorMsg = "system error"
  423. break
  424. }
  425. res, err := grampus.StopJob(task.JobID)
  426. if err != nil {
  427. log.Error("StopJob(%s) failed:%v", task.JobName, err, ctx.Data["msgID"])
  428. resultCode = strconv.Itoa(res.ErrorCode)
  429. errorMsg = res.ErrorMsg
  430. break
  431. }
  432. task.Status = string(models.GrampusStatusStopped)
  433. if task.EndTime == 0 {
  434. task.EndTime = timeutil.TimeStampNow()
  435. }
  436. task.ComputeAndSetDuration()
  437. err = models.UpdateJob(task)
  438. if err != nil {
  439. log.Error("UpdateJob(%s) failed:%v", task.JobName, err, ctx.Data["msgID"])
  440. resultCode = "-1"
  441. errorMsg = "system error"
  442. break
  443. }
  444. status = task.Status
  445. break
  446. }
  447. ctx.JSON(200, map[string]interface{}{
  448. "result_code": resultCode,
  449. "error_msg": errorMsg,
  450. "status": status,
  451. "id": ID,
  452. "StatusOK": 0,
  453. })
  454. }
  455. func GrampusTrainJobDel(ctx *context.Context) {
  456. var listType = ctx.Query("listType")
  457. if err := deleteGrampusJob(ctx); err != nil {
  458. log.Error("deleteGrampusJob failed: %v", err, ctx.Data["msgID"])
  459. ctx.ServerError(err.Error(), err)
  460. return
  461. }
  462. var isAdminPage = ctx.Query("isadminpage")
  463. var isHomePage = ctx.Query("ishomepage")
  464. if ctx.IsUserSiteAdmin() && isAdminPage == "true" {
  465. ctx.Redirect(setting.AppSubURL + "/admin" + "/cloudbrains")
  466. } else if isHomePage == "true" {
  467. ctx.Redirect(setting.AppSubURL + "/cloudbrains")
  468. } else {
  469. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/train-job?listType=" + listType)
  470. }
  471. }
  472. func deleteGrampusJob(ctx *context.Context) error {
  473. task := ctx.Cloudbrain
  474. if task.Status != string(models.GrampusStatusStopped) && task.Status != string(models.GrampusStatusSucceeded) && task.Status != string(models.GrampusStatusFailed) {
  475. log.Error("the job(%s) has not been stopped", task.JobName, ctx.Data["msgID"])
  476. return errors.New("the job has not been stopped")
  477. }
  478. err := models.DeleteJob(task)
  479. if err != nil {
  480. log.Error("DeleteJob failed: %v", err, ctx.Data["msgID"])
  481. return err
  482. }
  483. storageType := models.TypeCloudBrainOne
  484. if task.ComputeResource == models.NPUResource {
  485. storageType = models.TypeCloudBrainTwo
  486. }
  487. deleteJobStorage(task.JobName, storageType)
  488. return nil
  489. }
  490. func GrampusTrainJobShow(ctx *context.Context) {
  491. ctx.Data["PageIsCloudBrain"] = true
  492. var task *models.Cloudbrain
  493. task, err := models.GetCloudbrainByJobIDWithDeleted(ctx.Params(":jobid"))
  494. if err != nil {
  495. log.Error("GetCloudbrainByJobID failed:" + err.Error())
  496. ctx.ServerError("system error", err)
  497. return
  498. }
  499. if task.DeletedAt.IsZero() { //normal record
  500. result, err := grampus.GetJob(task.JobID)
  501. if err != nil {
  502. log.Error("GetJob failed:" + err.Error())
  503. //ctx.ServerError("GetJob failed", err)
  504. //return
  505. }
  506. if result != nil {
  507. if len(result.JobInfo.Tasks[0].CenterID) == 1 && len(result.JobInfo.Tasks[0].CenterName) == 1 {
  508. task.AiCenter = result.JobInfo.Tasks[0].CenterID[0] + "+" + result.JobInfo.Tasks[0].CenterName[0]
  509. }
  510. task.Status = grampus.TransTrainJobStatus(result.JobInfo.Status)
  511. if task.Status != result.JobInfo.Status || result.JobInfo.Status == models.GrampusStatusRunning {
  512. task.Duration = result.JobInfo.RunSec
  513. task.TrainJobDuration = models.ConvertDurationToStr(task.Duration)
  514. if task.StartTime == 0 && result.JobInfo.StartedAt > 0 {
  515. task.StartTime = timeutil.TimeStamp(result.JobInfo.StartedAt)
  516. }
  517. if task.EndTime == 0 && models.IsTrainJobTerminal(task.Status) && task.StartTime > 0 {
  518. task.EndTime = task.StartTime.Add(task.Duration)
  519. }
  520. task.CorrectCreateUnix()
  521. err = models.UpdateJob(task)
  522. if err != nil {
  523. log.Error("UpdateJob failed:" + err.Error())
  524. }
  525. }
  526. }
  527. }
  528. if len(task.Parameters) > 0 {
  529. var parameters models.Parameters
  530. err := json.Unmarshal([]byte(task.Parameters), &parameters)
  531. if err != nil {
  532. log.Error("Failed to Unmarshal Parameters: %s (%v)", task.Parameters, err)
  533. ctx.ServerError("system error", err)
  534. return
  535. }
  536. if len(parameters.Parameter) > 0 {
  537. paramTemp := ""
  538. for _, Parameter := range parameters.Parameter {
  539. param := Parameter.Label + " = " + Parameter.Value + "; "
  540. paramTemp = paramTemp + param
  541. }
  542. task.Parameters = paramTemp[:len(paramTemp)-2]
  543. } else {
  544. task.Parameters = ""
  545. }
  546. }
  547. taskList := make([]*models.Cloudbrain, 0)
  548. taskList = append(taskList, task)
  549. ctx.Data["version_list_task"] = taskList
  550. ctx.Data["canDownload"] = cloudbrain.CanModifyJob(ctx, task)
  551. ctx.Data["displayJobName"] = task.DisplayJobName
  552. aiCenterInfo := strings.Split(task.AiCenter, "+")
  553. if len(aiCenterInfo) == 2 {
  554. ctx.Data["ai_center"] = aiCenterInfo[1]
  555. }
  556. ctx.HTML(http.StatusOK, tplGrampusTrainJobShow)
  557. }
  558. func GrampusGetLog(ctx *context.Context) {
  559. jobID := ctx.Params(":jobid")
  560. job, err := models.GetCloudbrainByJobID(jobID)
  561. if err != nil {
  562. log.Error("GetCloudbrainByJobID failed: %v", err, ctx.Data["MsgID"])
  563. ctx.ServerError(err.Error(), err)
  564. return
  565. }
  566. content, err := grampus.GetTrainJobLog(job.JobID)
  567. if err != nil {
  568. log.Error("GetTrainJobLog failed: %v", err, ctx.Data["MsgID"])
  569. ctx.ServerError(err.Error(), err)
  570. return
  571. }
  572. ctx.JSON(http.StatusOK, map[string]interface{}{
  573. "JobName": job.JobName,
  574. "Content": content,
  575. })
  576. return
  577. }
  578. func generateCommand(repoName, processorType, codeRemotePath, dataRemotePath, bootFile, paramSrc, outputRemotePath, datasetName string) (string, error) {
  579. var command string
  580. workDir := grampus.NpuWorkDir
  581. if processorType == grampus.ProcessorTypeGPU {
  582. workDir = grampus.GpuWorkDir
  583. }
  584. command += "pwd;cd " + workDir + grampus.CommandPrepareScript
  585. //download code & dataset
  586. if processorType == grampus.ProcessorTypeNPU {
  587. commandDownload := "./downloader_for_obs " + setting.Bucket + " " + codeRemotePath + " " + grampus.CodeArchiveName + " " + dataRemotePath + " '" + datasetName + "';"
  588. command += commandDownload
  589. } else if processorType == grampus.ProcessorTypeGPU {
  590. commandDownload := "./downloader_for_minio " + setting.Grampus.Env + " " + codeRemotePath + " " + grampus.CodeArchiveName + " " + dataRemotePath + " '" + datasetName + "';"
  591. command += commandDownload
  592. }
  593. //check download result
  594. commandCheckRes := "bash -c \"[[ $? -eq 0 ]] && exit 0 || exit -1;\";"
  595. command += commandCheckRes
  596. //unzip code & dataset
  597. toolUnzip := "unzip -q '"
  598. if strings.HasSuffix(datasetName, ".tar.gz") {
  599. toolUnzip = "tar -zxvf '"
  600. }
  601. commandUnzip := "cd " + workDir + "code;unzip -q master.zip;echo \"start to unzip dataset\";cd " + workDir + "dataset;" + toolUnzip + datasetName + "';"
  602. command += commandUnzip
  603. //check unzip result
  604. commandCheckRes = "bash -c \"[[ $? -eq 0 ]] && exit 0 || exit -1;\";"
  605. command += commandCheckRes
  606. command += "echo \"unzip finished;start to exec code;\";"
  607. //exec code
  608. var parameters models.Parameters
  609. var paramCode string
  610. param := make([]models.Parameter, 0)
  611. if len(paramSrc) != 0 {
  612. err := json.Unmarshal([]byte(paramSrc), &parameters)
  613. if err != nil {
  614. log.Error("Failed to Unmarshal params: %s (%v)", paramSrc, err)
  615. return command, err
  616. }
  617. for _, parameter := range parameters.Parameter {
  618. param = append(param, models.Parameter{
  619. Label: parameter.Label,
  620. Value: parameter.Value,
  621. })
  622. paramCode += " --" + parameter.Label + "=" + parameter.Value
  623. }
  624. }
  625. commandCode := "cd " + workDir + "code/" + strings.ToLower(repoName) + ";python " + bootFile + paramCode + ";"
  626. command += commandCode
  627. //get exec result
  628. commandGetRes := "result=$?;"
  629. command += commandGetRes
  630. //upload models
  631. if processorType == grampus.ProcessorTypeNPU {
  632. commandUpload := "cd " + workDir + "script_for_grampus/;./uploader_for_obs " + setting.Bucket + " " + outputRemotePath + " " + workDir + "output/;"
  633. command += commandUpload
  634. } else if processorType == grampus.ProcessorTypeGPU {
  635. commandUpload := "cd " + workDir + "script_for_grampus/;./uploader_for_minio " + setting.Grampus.Env + " " + outputRemotePath + " " + workDir + "output/;"
  636. command += commandUpload
  637. }
  638. //check exec result
  639. commandCheckRes = "bash -c \"[[ $result -eq 0 ]] && exit 0 || exit -1;\""
  640. command += commandCheckRes
  641. return command, nil
  642. }
  643. func downloadZipCode(ctx *context.Context, codePath, branchName string) error {
  644. archiveType := git.ZIP
  645. archivePath := codePath
  646. if !com.IsDir(archivePath) {
  647. if err := os.MkdirAll(archivePath, os.ModePerm); err != nil {
  648. log.Error("MkdirAll failed:" + err.Error())
  649. return err
  650. }
  651. }
  652. // Get corresponding commit.
  653. var (
  654. commit *git.Commit
  655. err error
  656. )
  657. gitRepo := ctx.Repo.GitRepo
  658. if err != nil {
  659. log.Error("OpenRepository failed:" + err.Error())
  660. return err
  661. }
  662. if gitRepo.IsBranchExist(branchName) {
  663. commit, err = gitRepo.GetBranchCommit(branchName)
  664. if err != nil {
  665. log.Error("GetBranchCommit failed:" + err.Error())
  666. return err
  667. }
  668. }
  669. archivePath = path.Join(archivePath, grampus.CodeArchiveName)
  670. if !com.IsFile(archivePath) {
  671. if err := commit.CreateArchive(archivePath, git.CreateArchiveOpts{
  672. Format: archiveType,
  673. Prefix: setting.Repository.PrefixArchiveFiles,
  674. }); err != nil {
  675. log.Error("CreateArchive failed:" + err.Error())
  676. return err
  677. }
  678. }
  679. return nil
  680. }