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