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

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