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 38 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
3 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
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
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
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
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
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
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
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
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
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
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
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
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
2 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
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
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135
  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. CodeName: strings.ToLower(repo.Name),
  624. }
  625. if form.ModelName != "" { //使用预训练模型训练
  626. req.ModelName = form.ModelName
  627. req.LabelName = form.LabelName
  628. req.CkptName = form.CkptName
  629. req.ModelVersion = form.ModelVersion
  630. req.PreTrainModelUrl = form.PreTrainModelUrl
  631. req.PreTrainModelPath = preTrainModelPath
  632. }
  633. err = grampus.GenerateTrainJob(ctx, req)
  634. if err != nil {
  635. log.Error("GenerateTrainJob failed:%v", err.Error())
  636. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  637. ctx.RenderWithErr(err.Error(), tpl, &form)
  638. return
  639. }
  640. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/train-job")
  641. }
  642. func GrampusStopJob(ctx *context.Context) {
  643. var ID = ctx.Params(":jobid")
  644. var resultCode = "0"
  645. var errorMsg = ""
  646. var status = ""
  647. task := ctx.Cloudbrain
  648. for {
  649. if task.Status == string(models.GrampusStatusStopped) || task.Status == string(models.GrampusStatusFailed) || task.Status == string(models.GrampusStatusSucceeded) {
  650. log.Error("the job(%s) has been stopped", task.JobName, ctx.Data["msgID"])
  651. resultCode = "-1"
  652. errorMsg = "system error"
  653. break
  654. }
  655. res, err := grampus.StopJob(task.JobID)
  656. if err != nil {
  657. log.Error("StopJob(%s) failed:%v", task.JobName, err, ctx.Data["msgID"])
  658. resultCode = strconv.Itoa(res.ErrorCode)
  659. errorMsg = res.ErrorMsg
  660. break
  661. }
  662. oldStatus := task.Status
  663. task.Status = string(models.GrampusStatusStopped)
  664. if task.EndTime == 0 {
  665. task.EndTime = timeutil.TimeStampNow()
  666. }
  667. task.ComputeAndSetDuration()
  668. if oldStatus != task.Status {
  669. notification.NotifyChangeCloudbrainStatus(task, oldStatus)
  670. }
  671. err = models.UpdateJob(task)
  672. if err != nil {
  673. log.Error("UpdateJob(%s) failed:%v", task.JobName, err, ctx.Data["msgID"])
  674. resultCode = "-1"
  675. errorMsg = "system error"
  676. break
  677. }
  678. status = task.Status
  679. break
  680. }
  681. ctx.JSON(200, map[string]interface{}{
  682. "result_code": resultCode,
  683. "error_msg": errorMsg,
  684. "status": status,
  685. "id": ID,
  686. "StatusOK": 0,
  687. })
  688. }
  689. func GrampusTrainJobDel(ctx *context.Context) {
  690. var listType = ctx.Query("listType")
  691. if err := deleteGrampusJob(ctx); err != nil {
  692. log.Error("deleteGrampusJob failed: %v", err, ctx.Data["msgID"])
  693. ctx.ServerError(err.Error(), err)
  694. return
  695. }
  696. var isAdminPage = ctx.Query("isadminpage")
  697. var isHomePage = ctx.Query("ishomepage")
  698. if ctx.IsUserSiteAdmin() && isAdminPage == "true" {
  699. ctx.Redirect(setting.AppSubURL + "/admin" + "/cloudbrains")
  700. } else if isHomePage == "true" {
  701. ctx.Redirect(setting.AppSubURL + "/cloudbrains")
  702. } else {
  703. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/train-job?listType=" + listType)
  704. }
  705. }
  706. func deleteGrampusJob(ctx *context.Context) error {
  707. task := ctx.Cloudbrain
  708. if task.Status != string(models.GrampusStatusStopped) && task.Status != string(models.GrampusStatusSucceeded) && task.Status != string(models.GrampusStatusFailed) {
  709. log.Error("the job(%s) has not been stopped", task.JobName, ctx.Data["msgID"])
  710. return errors.New("the job has not been stopped")
  711. }
  712. err := models.DeleteJob(task)
  713. if err != nil {
  714. log.Error("DeleteJob failed: %v", err, ctx.Data["msgID"])
  715. return err
  716. }
  717. storageType := models.TypeCloudBrainOne
  718. if task.ComputeResource == models.NPUResource {
  719. storageType = models.TypeCloudBrainTwo
  720. }
  721. DeleteCloudbrainJobStorage(task.JobName, storageType)
  722. return nil
  723. }
  724. func GrampusTrainJobShow(ctx *context.Context) {
  725. ctx.Data["PageIsCloudBrain"] = true
  726. var task *models.Cloudbrain
  727. task, err := models.GetCloudbrainByJobIDWithDeleted(ctx.Params(":jobid"))
  728. if err != nil {
  729. log.Error("GetCloudbrainByJobID failed:" + err.Error())
  730. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  731. return
  732. }
  733. task.ContainerIp = ""
  734. if task.DeletedAt.IsZero() { //normal record
  735. result, err := grampus.GetJob(task.JobID)
  736. if err != nil {
  737. log.Error("GetJob failed:" + err.Error())
  738. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  739. return
  740. }
  741. if result != nil {
  742. if len(result.JobInfo.Tasks[0].CenterID) == 1 && len(result.JobInfo.Tasks[0].CenterName) == 1 {
  743. task.AiCenter = result.JobInfo.Tasks[0].CenterID[0] + "+" + result.JobInfo.Tasks[0].CenterName[0]
  744. }
  745. oldStatus := task.Status
  746. task.Status = grampus.TransTrainJobStatus(result.JobInfo.Status)
  747. if task.Status != result.JobInfo.Status || result.JobInfo.Status == models.GrampusStatusRunning {
  748. task.Duration = result.JobInfo.RunSec
  749. if task.Duration < 0 {
  750. task.Duration = 0
  751. }
  752. task.TrainJobDuration = models.ConvertDurationToStr(task.Duration)
  753. if task.StartTime == 0 && result.JobInfo.StartedAt > 0 {
  754. task.StartTime = timeutil.TimeStamp(result.JobInfo.StartedAt)
  755. }
  756. if task.EndTime == 0 && models.IsTrainJobTerminal(task.Status) && task.StartTime > 0 {
  757. task.EndTime = task.StartTime.Add(task.Duration)
  758. }
  759. task.CorrectCreateUnix()
  760. if oldStatus != task.Status {
  761. notification.NotifyChangeCloudbrainStatus(task, oldStatus)
  762. }
  763. err = models.UpdateJob(task)
  764. if err != nil {
  765. log.Error("UpdateJob failed:" + err.Error())
  766. }
  767. }
  768. }
  769. }
  770. if len(task.Parameters) > 0 {
  771. var parameters models.Parameters
  772. err := json.Unmarshal([]byte(task.Parameters), &parameters)
  773. if err != nil {
  774. log.Error("Failed to Unmarshal Parameters: %s (%v)", task.Parameters, err)
  775. ctx.ServerError("system error", err)
  776. return
  777. }
  778. if len(parameters.Parameter) > 0 {
  779. paramTemp := ""
  780. for _, Parameter := range parameters.Parameter {
  781. param := Parameter.Label + " = " + Parameter.Value + "; "
  782. paramTemp = paramTemp + param
  783. }
  784. task.Parameters = paramTemp[:len(paramTemp)-2]
  785. } else {
  786. task.Parameters = ""
  787. }
  788. }
  789. taskList := make([]*models.Cloudbrain, 0)
  790. taskList = append(taskList, task)
  791. prepareSpec4Show(ctx, task)
  792. ctx.Data["version_list_task"] = taskList
  793. ctx.Data["datasetDownload"] = GetCloudBrainDataSetInfo(task.Uuid, task.DatasetName, false)
  794. ctx.Data["canDownload"] = cloudbrain.CanModifyJob(ctx, task)
  795. ctx.Data["displayJobName"] = task.DisplayJobName
  796. aiCenterInfo := strings.Split(task.AiCenter, "+")
  797. if len(aiCenterInfo) == 2 {
  798. ctx.Data["ai_center"] = aiCenterInfo[1]
  799. }
  800. ctx.HTML(http.StatusOK, tplGrampusTrainJobShow)
  801. }
  802. func GrampusDownloadLog(ctx *context.Context) {
  803. jobID := ctx.Params(":jobid")
  804. job, err := models.GetCloudbrainByJobID(jobID)
  805. if err != nil {
  806. log.Error("GetCloudbrainByJobID failed: %v", err, ctx.Data["MsgID"])
  807. ctx.ServerError(err.Error(), err)
  808. return
  809. }
  810. content, err := grampus.GetTrainJobLog(job.JobID)
  811. if err != nil {
  812. log.Error("GetTrainJobLog failed: %v", err, ctx.Data["MsgID"])
  813. content = ""
  814. }
  815. fileName := job.JobName + "-log.txt"
  816. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+fileName)
  817. ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
  818. var b []byte = []byte(content)
  819. ctx.Resp.Write(b)
  820. }
  821. func GrampusGetLog(ctx *context.Context) {
  822. jobID := ctx.Params(":jobid")
  823. job, err := models.GetCloudbrainByJobID(jobID)
  824. if err != nil {
  825. log.Error("GetCloudbrainByJobID failed: %v", err, ctx.Data["MsgID"])
  826. ctx.ServerError(err.Error(), err)
  827. return
  828. }
  829. content, err := grampus.GetTrainJobLog(job.JobID)
  830. if err != nil {
  831. log.Error("GetTrainJobLog failed: %v", err, ctx.Data["MsgID"])
  832. ctx.ServerError(err.Error(), err)
  833. return
  834. }
  835. var canLogDownload bool
  836. if err != nil {
  837. canLogDownload = false
  838. } else {
  839. canLogDownload = true
  840. }
  841. ctx.JSON(http.StatusOK, map[string]interface{}{
  842. "JobName": job.JobName,
  843. "Content": content,
  844. "CanLogDownload": canLogDownload,
  845. })
  846. return
  847. }
  848. func generateCommand(repoName, processorType, codeRemotePath, dataRemotePath, bootFile, paramSrc, outputRemotePath, datasetName, pretrainModelPath, pretrainModelFileName string) (string, error) {
  849. var command string
  850. workDir := grampus.NpuWorkDir
  851. if processorType == grampus.ProcessorTypeGPU {
  852. workDir = grampus.GpuWorkDir
  853. }
  854. command += "pwd;cd " + workDir + fmt.Sprintf(grampus.CommandPrepareScript, setting.Grampus.SyncScriptProject, setting.Grampus.SyncScriptProject)
  855. //download code & dataset
  856. if processorType == grampus.ProcessorTypeNPU {
  857. //no need to download code & dataset by internet
  858. } else if processorType == grampus.ProcessorTypeGPU {
  859. commandDownload := "./downloader_for_minio " + setting.Grampus.Env + " " + codeRemotePath + " " + grampus.CodeArchiveName + " '" + dataRemotePath + "' '" + datasetName + "'"
  860. commandDownload = processPretrainModelParameter(pretrainModelPath, pretrainModelFileName, commandDownload)
  861. command += commandDownload
  862. }
  863. //unzip code & dataset
  864. if processorType == grampus.ProcessorTypeNPU {
  865. //no need to process
  866. } else if processorType == grampus.ProcessorTypeGPU {
  867. unZipDatasetCommand := generateDatasetUnzipCommand(datasetName)
  868. commandUnzip := "cd " + workDir + "code;unzip -q master.zip;echo \"start to unzip dataset\";cd " + workDir + "dataset;" + unZipDatasetCommand
  869. command += commandUnzip
  870. }
  871. command += "echo \"unzip finished;start to exec code;\";"
  872. // set export
  873. var commandExport string
  874. if processorType == grampus.ProcessorTypeNPU {
  875. commandExport = "export bucket=" + setting.Bucket + " && export remote_path=" + outputRemotePath + ";"
  876. } else if processorType == grampus.ProcessorTypeGPU {
  877. commandExport = "export env=" + setting.Grampus.Env + " && export remote_path=" + outputRemotePath + ";"
  878. }
  879. command += commandExport
  880. //exec code
  881. var parameters models.Parameters
  882. var paramCode string
  883. if len(paramSrc) != 0 {
  884. err := json.Unmarshal([]byte(paramSrc), &parameters)
  885. if err != nil {
  886. log.Error("Failed to Unmarshal params: %s (%v)", paramSrc, err)
  887. return command, err
  888. }
  889. for _, parameter := range parameters.Parameter {
  890. paramCode += " --" + parameter.Label + "=" + parameter.Value
  891. }
  892. }
  893. var commandCode string
  894. if processorType == grampus.ProcessorTypeNPU {
  895. commandCode = "/bin/bash /home/work/run_train_for_openi.sh /home/work/openi.py /tmp/log/train.log" + paramCode + ";"
  896. } else if processorType == grampus.ProcessorTypeGPU {
  897. if pretrainModelFileName != "" {
  898. paramCode += " --ckpt_url" + "=" + workDir + "pretrainmodel/" + pretrainModelFileName
  899. }
  900. commandCode = "cd " + workDir + "code/" + strings.ToLower(repoName) + ";python " + bootFile + paramCode + ";"
  901. }
  902. command += commandCode
  903. //get exec result
  904. commandGetRes := "result=$?;"
  905. command += commandGetRes
  906. //upload models
  907. if processorType == grampus.ProcessorTypeNPU {
  908. commandUpload := "cd " + workDir + setting.Grampus.SyncScriptProject + "/;./uploader_for_npu " + setting.Bucket + " " + outputRemotePath + " " + workDir + "output/;"
  909. command += commandUpload
  910. } else if processorType == grampus.ProcessorTypeGPU {
  911. commandUpload := "cd " + workDir + setting.Grampus.SyncScriptProject + "/;./uploader_for_gpu " + setting.Grampus.Env + " " + outputRemotePath + " " + workDir + "output/;"
  912. command += commandUpload
  913. }
  914. //check exec result
  915. commandCheckRes := "bash -c \"[[ $result -eq 0 ]] && exit 0 || exit -1\""
  916. command += commandCheckRes
  917. return command, nil
  918. }
  919. func processPretrainModelParameter(pretrainModelPath string, pretrainModelFileName string, commandDownload string) string {
  920. commandDownloadTemp := commandDownload
  921. if pretrainModelPath != "" {
  922. commandDownloadTemp += " '" + pretrainModelPath + "' '" + pretrainModelFileName + "'"
  923. }
  924. commandDownloadTemp += ";"
  925. return commandDownloadTemp
  926. }
  927. func generateDatasetUnzipCommand(datasetName string) string {
  928. var unZipDatasetCommand string
  929. datasetNameArray := strings.Split(datasetName, ";")
  930. if len(datasetNameArray) == 1 { //单数据集
  931. unZipDatasetCommand = "unzip -q '" + datasetName + "';"
  932. if strings.HasSuffix(datasetNameArray[0], ".tar.gz") {
  933. unZipDatasetCommand = "tar --strip-components=1 -zxvf '" + datasetName + "';"
  934. }
  935. } else { //多数据集
  936. for _, datasetNameTemp := range datasetNameArray {
  937. if strings.HasSuffix(datasetNameTemp, ".tar.gz") {
  938. unZipDatasetCommand = unZipDatasetCommand + "tar -zxvf '" + datasetNameTemp + "';"
  939. } else {
  940. unZipDatasetCommand = unZipDatasetCommand + "unzip -q '" + datasetNameTemp + "' -d './" + strings.TrimSuffix(datasetNameTemp, ".zip") + "';"
  941. }
  942. }
  943. }
  944. return unZipDatasetCommand
  945. }
  946. func downloadZipCode(ctx *context.Context, codePath, branchName string) error {
  947. archiveType := git.ZIP
  948. archivePath := codePath
  949. if !com.IsDir(archivePath) {
  950. if err := os.MkdirAll(archivePath, os.ModePerm); err != nil {
  951. log.Error("MkdirAll failed:" + err.Error())
  952. return err
  953. }
  954. }
  955. // Get corresponding commit.
  956. var (
  957. commit *git.Commit
  958. err error
  959. )
  960. gitRepo := ctx.Repo.GitRepo
  961. if err != nil {
  962. log.Error("OpenRepository failed:" + err.Error())
  963. return err
  964. }
  965. if gitRepo.IsBranchExist(branchName) {
  966. commit, err = gitRepo.GetBranchCommit(branchName)
  967. if err != nil {
  968. log.Error("GetBranchCommit failed:" + err.Error())
  969. return err
  970. }
  971. } else {
  972. log.Error("the branch is not exist: " + branchName)
  973. return fmt.Errorf("The branch does not exist.")
  974. }
  975. archivePath = path.Join(archivePath, grampus.CodeArchiveName)
  976. if !com.IsFile(archivePath) {
  977. if err := commit.CreateArchive(archivePath, git.CreateArchiveOpts{
  978. Format: archiveType,
  979. Prefix: setting.Repository.PrefixArchiveFiles,
  980. }); err != nil {
  981. log.Error("CreateArchive failed:" + err.Error())
  982. return err
  983. }
  984. }
  985. return nil
  986. }