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

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