You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

grampus.go 37 kB

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