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

grampus.go 38 kB

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