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

grampus.go 38 kB

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