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