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

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