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

grampus.go 38 kB

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