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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906
  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_client"
  19. "code.gitea.io/gitea/modules/redis/redis_key"
  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. var taskJobNameKey = ctx.Query("taskJobNameKey")
  57. redis_client.Del(taskJobNameKey)
  58. ctx.Data["PageIsCloudBrain"] = true
  59. t := time.Now()
  60. var displayJobName = jobNamePrefixValid(cutString(ctx.User.Name, 5)) + t.Format("2006010215") + strconv.Itoa(int(t.Unix()))[5:]
  61. ctx.Data["display_job_name"] = displayJobName
  62. //get valid images
  63. images, err := grampus.GetImages(processType)
  64. if err != nil {
  65. log.Error("GetImages failed:", err.Error())
  66. } else {
  67. ctx.Data["images"] = images.Infos
  68. }
  69. grampus.InitSpecialPool()
  70. ctx.Data["GPUEnabled"] = true
  71. ctx.Data["NPUEnabled"] = true
  72. includeCenters := make(map[string]struct{})
  73. excludeCenters := make(map[string]struct{})
  74. if grampus.SpecialPools != nil {
  75. for _, pool := range grampus.SpecialPools.Pools {
  76. if pool.IsExclusive {
  77. if !IsUserInOrgPool(ctx.User.ID, pool) {
  78. ctx.Data[pool.Type+"Enabled"] = false
  79. }
  80. } else {
  81. if strings.Contains(strings.ToLower(processType), strings.ToLower(pool.Type)) {
  82. if IsUserInOrgPool(ctx.User.ID, pool) {
  83. for _, center := range pool.Pool {
  84. includeCenters[center.Queue] = struct{}{}
  85. }
  86. } else {
  87. for _, center := range pool.Pool {
  88. excludeCenters[center.Queue] = struct{}{}
  89. }
  90. }
  91. }
  92. }
  93. }
  94. }
  95. //get valid resource specs
  96. specs, err := grampus.GetResourceSpecs(processType)
  97. grampusSpecs := getFilterSpecBySpecialPool(specs, includeCenters, excludeCenters)
  98. if err != nil {
  99. log.Error("GetResourceSpecs failed:", err.Error())
  100. } else {
  101. ctx.Data["flavor_infos"] = grampusSpecs
  102. }
  103. //get branches
  104. branches, _, err := ctx.Repo.GitRepo.GetBranches(0, 0)
  105. if err != nil {
  106. log.Error("GetBranches error:", err.Error())
  107. } else {
  108. ctx.Data["branches"] = branches
  109. }
  110. ctx.Data["branchName"] = ctx.Repo.BranchName
  111. if processType == grampus.ProcessorTypeGPU {
  112. ctx.Data["datasetType"] = models.TypeCloudBrainOne
  113. waitCount := cloudbrain.GetWaitingCloudbrainCount(models.TypeC2Net, models.GPUResource, models.JobTypeTrain)
  114. ctx.Data["WaitCount"] = waitCount
  115. } else if processType == grampus.ProcessorTypeNPU {
  116. ctx.Data["datasetType"] = models.TypeCloudBrainTwo
  117. waitCount := cloudbrain.GetWaitingCloudbrainCount(models.TypeC2Net, models.NPUResource, models.JobTypeTrain)
  118. ctx.Data["WaitCount"] = waitCount
  119. }
  120. return nil
  121. }
  122. func getFilterSpecBySpecialPool(specs *models.GetGrampusResourceSpecsResult, includeCenters map[string]struct{}, excludeCenters map[string]struct{}) []models.GrampusSpec {
  123. if len(includeCenters) == 0 && len(excludeCenters) == 0 {
  124. return specs.Infos
  125. }
  126. var grampusSpecs []models.GrampusSpec
  127. for _, info := range specs.Infos {
  128. if isInIncludeCenters(info, includeCenters) || (len(excludeCenters) != 0 && isNotAllInExcludeCenters(info, excludeCenters)) {
  129. grampusSpecs = append(grampusSpecs, info)
  130. }
  131. }
  132. return grampusSpecs
  133. }
  134. func isInIncludeCenters(grampusSpec models.GrampusSpec, centers map[string]struct{}) bool {
  135. for _, center := range grampusSpec.Centers {
  136. if _, ok := centers[center.ID]; ok {
  137. return true
  138. }
  139. }
  140. return false
  141. }
  142. func isNotAllInExcludeCenters(grampusSpec models.GrampusSpec, centers map[string]struct{}) bool {
  143. for _, center := range grampusSpec.Centers {
  144. if _, ok := centers[center.ID]; !ok {
  145. return true
  146. }
  147. }
  148. return false
  149. }
  150. func IsUserInOrgPool(userId int64, pool *models.SpecialPool) bool {
  151. org, _ := models.GetOrgByName(pool.Org)
  152. if org != nil {
  153. isOrgMember, _ := models.IsOrganizationMember(org.ID, userId)
  154. return isOrgMember
  155. }
  156. return false
  157. }
  158. func grampusParamCheckCreateTrainJob(form auth.CreateGrampusTrainJobForm) error {
  159. if !strings.HasSuffix(strings.TrimSpace(form.BootFile), ".py") {
  160. log.Error("the boot file(%s) must be a python file", form.BootFile)
  161. return errors.New("启动文件必须是python文件")
  162. }
  163. if form.BranchName == "" {
  164. log.Error("the branch must not be null!", form.BranchName)
  165. return errors.New("代码分支不能为空!")
  166. }
  167. return nil
  168. }
  169. func GrampusTrainJobGpuCreate(ctx *context.Context, form auth.CreateGrampusTrainJobForm) {
  170. displayJobName := form.DisplayJobName
  171. jobName := util.ConvertDisplayJobNameToJobName(displayJobName)
  172. uuid := form.Attachment
  173. description := form.Description
  174. bootFile := strings.TrimSpace(form.BootFile)
  175. params := form.Params
  176. repo := ctx.Repo.Repository
  177. codeLocalPath := setting.JobPath + jobName + cloudbrain.CodeMountPath + "/"
  178. codeMinioPath := setting.CBCodePathPrefix + jobName + cloudbrain.CodeMountPath + "/"
  179. dataMinioPath := setting.Attachment.Minio.BasePath + path.Join(uuid[0:1], uuid[1:2]) + "/" + uuid
  180. branchName := form.BranchName
  181. flavorName := form.FlavorName
  182. image := strings.TrimSpace(form.Image)
  183. taskJobNameKey := redis_key.CloudbrainBindingJobNameKey(fmt.Sprint(repo.ID), string(models.JobTypeTrain), displayJobName)
  184. isOk, err := redis_client.Setnx(taskJobNameKey, "", 5*time.Second)
  185. ctx.Data["taskJobNameKey"] = taskJobNameKey
  186. if !isOk {
  187. log.Error("The task have been processed:%v", err, ctx.Data["MsgID"])
  188. ctx.RenderWithErr("The task have been processed, please wait a minute", tplGrampusTrainJobGPUNew, &form)
  189. return
  190. }
  191. if !jobNamePattern.MatchString(displayJobName) {
  192. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  193. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_jobname_err"), tplGrampusTrainJobGPUNew, &form)
  194. return
  195. }
  196. bootFileExist, err := ctx.Repo.FileExists(bootFile, branchName)
  197. if err != nil || !bootFileExist {
  198. log.Error("Get bootfile error:", err, ctx.Data["MsgID"])
  199. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  200. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_bootfile_err"), tplGrampusTrainJobGPUNew, &form)
  201. return
  202. }
  203. errStr := checkSpecialPool(ctx, "GPU")
  204. if errStr != "" {
  205. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  206. ctx.RenderWithErr(errStr, tplGrampusTrainJobGPUNew, &form)
  207. return
  208. }
  209. //check count limit
  210. count, err := models.GetGrampusCountByUserID(ctx.User.ID, string(models.JobTypeTrain), models.GPUResource)
  211. if err != nil {
  212. log.Error("GetGrampusCountByUserID failed:%v", err, ctx.Data["MsgID"])
  213. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  214. ctx.RenderWithErr("system error", tplGrampusTrainJobGPUNew, &form)
  215. return
  216. } else {
  217. if count >= 1 {
  218. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  219. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  220. ctx.RenderWithErr("you have already a running or waiting task, can not create more", tplGrampusTrainJobGPUNew, &form)
  221. return
  222. }
  223. }
  224. //check param
  225. if err := grampusParamCheckCreateTrainJob(form); err != nil {
  226. log.Error("paramCheckCreateTrainJob failed:(%v)", err, ctx.Data["MsgID"])
  227. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  228. ctx.RenderWithErr(err.Error(), tplGrampusTrainJobGPUNew, &form)
  229. return
  230. }
  231. //check whether the task name in the project is duplicated
  232. tasks, err := models.GetCloudbrainsByDisplayJobName(repo.ID, string(models.JobTypeTrain), displayJobName)
  233. if err == nil {
  234. if len(tasks) != 0 {
  235. log.Error("the job name did already exist", ctx.Data["MsgID"])
  236. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  237. ctx.RenderWithErr("the job name did already exist", tplGrampusTrainJobGPUNew, &form)
  238. return
  239. }
  240. } else {
  241. if !models.IsErrJobNotExist(err) {
  242. log.Error("system error, %v", err, ctx.Data["MsgID"])
  243. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  244. ctx.RenderWithErr("system error", tplGrampusTrainJobGPUNew, &form)
  245. return
  246. }
  247. }
  248. //check dataset
  249. attachment, err := models.GetAttachmentByUUID(uuid)
  250. if err != nil {
  251. log.Error("GetAttachmentByUUID failed:", err.Error(), ctx.Data["MsgID"])
  252. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  253. ctx.RenderWithErr("dataset is not exist", tplGrampusTrainJobGPUNew, &form)
  254. return
  255. }
  256. //prepare code and out path
  257. _, err = ioutil.ReadDir(codeLocalPath)
  258. if err == nil {
  259. os.RemoveAll(codeLocalPath)
  260. }
  261. if err := downloadZipCode(ctx, codeLocalPath, branchName); err != nil {
  262. log.Error("downloadZipCode failed, server timed out: %s (%v)", repo.FullName(), err, ctx.Data["MsgID"])
  263. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  264. ctx.RenderWithErr(ctx.Tr("cloudbrain.load_code_failed"), tplGrampusTrainJobGPUNew, &form)
  265. return
  266. }
  267. //todo: upload code (send to file_server todo this work?)
  268. //upload code
  269. if err := uploadCodeToMinio(codeLocalPath+"/", jobName, cloudbrain.CodeMountPath+"/"); err != nil {
  270. log.Error("Failed to uploadCodeToMinio: %s (%v)", repo.FullName(), err, ctx.Data["MsgID"])
  271. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  272. ctx.RenderWithErr(ctx.Tr("cloudbrain.load_code_failed"), tplGrampusTrainJobGPUNew, &form)
  273. return
  274. }
  275. modelPath := setting.JobPath + jobName + cloudbrain.ModelMountPath + "/"
  276. if err := mkModelPath(modelPath); err != nil {
  277. log.Error("Failed to mkModelPath: %s (%v)", repo.FullName(), err, ctx.Data["MsgID"])
  278. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  279. ctx.RenderWithErr(ctx.Tr("cloudbrain.load_code_failed"), tplGrampusTrainJobGPUNew, &form)
  280. return
  281. }
  282. //init model readme
  283. if err := uploadCodeToMinio(modelPath, jobName, cloudbrain.ModelMountPath+"/"); err != nil {
  284. log.Error("Failed to uploadCodeToMinio: %s (%v)", repo.FullName(), err, ctx.Data["MsgID"])
  285. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  286. ctx.RenderWithErr(ctx.Tr("cloudbrain.load_code_failed"), tplGrampusTrainJobGPUNew, &form)
  287. return
  288. }
  289. //prepare command
  290. command, err := generateCommand(repo.Name, grampus.ProcessorTypeGPU, codeMinioPath+cloudbrain.DefaultBranchName+".zip", dataMinioPath, bootFile, params, setting.CBCodePathPrefix+jobName+cloudbrain.ModelMountPath+"/", attachment.Name)
  291. if err != nil {
  292. log.Error("Failed to generateCommand: %s (%v)", displayJobName, err, ctx.Data["MsgID"])
  293. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  294. ctx.RenderWithErr("Create task failed, internal error", tplGrampusTrainJobGPUNew, &form)
  295. return
  296. }
  297. commitID, _ := ctx.Repo.GitRepo.GetBranchCommitID(branchName)
  298. req := &grampus.GenerateTrainJobReq{
  299. JobName: jobName,
  300. DisplayJobName: displayJobName,
  301. ComputeResource: models.GPUResource,
  302. ProcessType: grampus.ProcessorTypeGPU,
  303. Command: command,
  304. ResourceSpecId: form.FlavorID,
  305. ImageUrl: image,
  306. Description: description,
  307. BootFile: bootFile,
  308. Uuid: uuid,
  309. CommitID: commitID,
  310. BranchName: branchName,
  311. Params: form.Params,
  312. FlavorName: flavorName,
  313. EngineName: image,
  314. DatasetName: attachment.Name,
  315. IsLatestVersion: modelarts.IsLatestVersion,
  316. VersionCount: modelarts.VersionCountOne,
  317. WorkServerNumber: 1,
  318. }
  319. err = grampus.GenerateTrainJob(ctx, req)
  320. if err != nil {
  321. log.Error("GenerateTrainJob failed:%v", err.Error(), ctx.Data["MsgID"])
  322. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  323. ctx.RenderWithErr(err.Error(), tplGrampusTrainJobGPUNew, &form)
  324. return
  325. }
  326. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/train-job")
  327. }
  328. func checkSpecialPool(ctx *context.Context, resourceType string) string {
  329. grampus.InitSpecialPool()
  330. if grampus.SpecialPools != nil {
  331. for _, pool := range grampus.SpecialPools.Pools {
  332. if pool.IsExclusive && pool.Type == resourceType {
  333. org, _ := models.GetOrgByName(pool.Org)
  334. if org != nil {
  335. isOrgMember, _ := models.IsOrganizationMember(org.ID, ctx.User.ID)
  336. if !isOrgMember {
  337. return ctx.Tr("repo.grampus.no_operate_right")
  338. }
  339. }
  340. }
  341. }
  342. }
  343. return ""
  344. }
  345. func GrampusTrainJobNpuCreate(ctx *context.Context, form auth.CreateGrampusTrainJobForm) {
  346. displayJobName := form.DisplayJobName
  347. jobName := util.ConvertDisplayJobNameToJobName(displayJobName)
  348. uuid := form.Attachment
  349. description := form.Description
  350. bootFile := strings.TrimSpace(form.BootFile)
  351. params := form.Params
  352. repo := ctx.Repo.Repository
  353. codeLocalPath := setting.JobPath + jobName + modelarts.CodePath
  354. codeObsPath := grampus.JobPath + jobName + modelarts.CodePath
  355. dataObsPath := setting.BasePath + path.Join(uuid[0:1], uuid[1:2]) + "/" + uuid + "/"
  356. branchName := form.BranchName
  357. isLatestVersion := modelarts.IsLatestVersion
  358. flavorName := form.FlavorName
  359. versionCount := modelarts.VersionCountOne
  360. engineName := form.EngineName
  361. taskJobNameKey := redis_key.CloudbrainBindingJobNameKey(fmt.Sprint(repo.ID), string(models.JobTypeTrain), displayJobName)
  362. isOk, err := redis_client.Setnx(taskJobNameKey, "", 5*time.Second)
  363. ctx.Data["taskJobNameKey"] = taskJobNameKey
  364. if !isOk {
  365. log.Error("The task have been processed:%v", err, ctx.Data["MsgID"])
  366. ctx.RenderWithErr("The task have been processed, please wait a minute", tplGrampusTrainJobNPUNew, &form)
  367. return
  368. }
  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. deleteJobStorage(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, 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. //check download result
  692. commandCheckRes := "bash -c \"[[ $? -eq 0 ]] && exit 0 || exit -1;\";"
  693. command += commandCheckRes
  694. //unzip code & dataset
  695. toolUnzip := "unzip -q '"
  696. if strings.HasSuffix(datasetName, ".tar.gz") {
  697. toolUnzip = "tar -zxvf '"
  698. }
  699. commandUnzip := "cd " + workDir + "code;unzip -q master.zip;echo \"start to unzip dataset\";cd " + workDir + "dataset;" + toolUnzip + datasetName + "';"
  700. command += commandUnzip
  701. //check unzip result
  702. commandCheckRes = "bash -c \"[[ $? -eq 0 ]] && exit 0 || exit -1;\";"
  703. command += commandCheckRes
  704. command += "echo \"unzip finished;start to exec code;\";"
  705. //exec code
  706. var parameters models.Parameters
  707. var paramCode string
  708. param := make([]models.Parameter, 0)
  709. if len(paramSrc) != 0 {
  710. err := json.Unmarshal([]byte(paramSrc), &parameters)
  711. if err != nil {
  712. log.Error("Failed to Unmarshal params: %s (%v)", paramSrc, err)
  713. return command, err
  714. }
  715. for _, parameter := range parameters.Parameter {
  716. param = append(param, models.Parameter{
  717. Label: parameter.Label,
  718. Value: parameter.Value,
  719. })
  720. paramCode += " --" + parameter.Label + "=" + parameter.Value
  721. }
  722. }
  723. var commandCode string
  724. if processorType == grampus.ProcessorTypeNPU {
  725. commandCode = "/bin/bash /home/work/run_train_for_openi.sh " + workDir + "code/" + strings.ToLower(repoName) + "/" + bootFile + " /tmp/log/train.log" + paramCode + ";"
  726. } else if processorType == grampus.ProcessorTypeGPU {
  727. commandCode = "cd " + workDir + "code/" + strings.ToLower(repoName) + ";python " + bootFile + paramCode + ";"
  728. }
  729. command += commandCode
  730. //get exec result
  731. commandGetRes := "result=$?;"
  732. command += commandGetRes
  733. //upload models
  734. if processorType == grampus.ProcessorTypeNPU {
  735. commandUpload := "cd " + workDir + "script_for_grampus/;./uploader_for_obs " + setting.Bucket + " " + outputRemotePath + " " + workDir + "output/;"
  736. command += commandUpload
  737. } else if processorType == grampus.ProcessorTypeGPU {
  738. commandUpload := "cd " + workDir + "script_for_grampus/;./uploader_for_minio " + setting.Grampus.Env + " " + outputRemotePath + " " + workDir + "output/;"
  739. command += commandUpload
  740. }
  741. //check exec result
  742. commandCheckRes = "bash -c \"[[ $result -eq 0 ]] && exit 0 || exit -1\""
  743. command += commandCheckRes
  744. return command, nil
  745. }
  746. func downloadZipCode(ctx *context.Context, codePath, branchName string) error {
  747. archiveType := git.ZIP
  748. archivePath := codePath
  749. if !com.IsDir(archivePath) {
  750. if err := os.MkdirAll(archivePath, os.ModePerm); err != nil {
  751. log.Error("MkdirAll failed:" + err.Error())
  752. return err
  753. }
  754. }
  755. // Get corresponding commit.
  756. var (
  757. commit *git.Commit
  758. err error
  759. )
  760. gitRepo := ctx.Repo.GitRepo
  761. if err != nil {
  762. log.Error("OpenRepository failed:" + err.Error())
  763. return err
  764. }
  765. if gitRepo.IsBranchExist(branchName) {
  766. commit, err = gitRepo.GetBranchCommit(branchName)
  767. if err != nil {
  768. log.Error("GetBranchCommit failed:" + err.Error())
  769. return err
  770. }
  771. } else {
  772. log.Error("the branch is not exist: " + branchName)
  773. return fmt.Errorf("The branch does not exist.")
  774. }
  775. archivePath = path.Join(archivePath, grampus.CodeArchiveName)
  776. if !com.IsFile(archivePath) {
  777. if err := commit.CreateArchive(archivePath, git.CreateArchiveOpts{
  778. Format: archiveType,
  779. Prefix: setting.Repository.PrefixArchiveFiles,
  780. }); err != nil {
  781. log.Error("CreateArchive failed:" + err.Error())
  782. return err
  783. }
  784. }
  785. return nil
  786. }