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