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