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