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 20 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648
  1. package repo
  2. import (
  3. "code.gitea.io/gitea/modules/auth"
  4. "code.gitea.io/gitea/modules/git"
  5. "code.gitea.io/gitea/modules/grampus"
  6. "code.gitea.io/gitea/modules/modelarts"
  7. "code.gitea.io/gitea/modules/timeutil"
  8. "code.gitea.io/gitea/modules/util"
  9. "encoding/json"
  10. "errors"
  11. "github.com/unknwon/com"
  12. "io/ioutil"
  13. "net/http"
  14. "os"
  15. "path"
  16. "strconv"
  17. "strings"
  18. "time"
  19. "code.gitea.io/gitea/models"
  20. "code.gitea.io/gitea/modules/base"
  21. "code.gitea.io/gitea/modules/cloudbrain"
  22. "code.gitea.io/gitea/modules/context"
  23. "code.gitea.io/gitea/modules/log"
  24. "code.gitea.io/gitea/modules/setting"
  25. )
  26. const (
  27. tplGrampusTrainJobShow base.TplName = "repo/grampus/trainjob/show"
  28. //GPU
  29. tplGrampusTrainJobGPUNew base.TplName = "repo/grampus/trainjob/gpu/new"
  30. //NPU
  31. tplGrampusTrainJobNPUNew base.TplName = "repo/grampus/trainjob/npu/new"
  32. )
  33. func GrampusTrainJobGPUNew(ctx *context.Context) {
  34. err := grampusGpuNewDataPrepare(ctx)
  35. if err != nil {
  36. ctx.ServerError("get new train-job info failed", err)
  37. return
  38. }
  39. ctx.HTML(http.StatusOK, tplGrampusTrainJobGPUNew)
  40. }
  41. func grampusGpuNewDataPrepare(ctx *context.Context) error {
  42. ctx.Data["PageIsCloudBrain"] = true
  43. t := time.Now()
  44. var displayJobName = jobNamePrefixValid(cutString(ctx.User.Name, 5)) + t.Format("2006010215") + strconv.Itoa(int(t.Unix()))[5:]
  45. ctx.Data["display_job_name"] = displayJobName
  46. //get valid images
  47. result, err := cloudbrain.GetImages()
  48. if err != nil {
  49. ctx.Data["error"] = err.Error()
  50. log.Error("cloudbrain.GetImages failed:", err.Error(), ctx.Data["MsgID"])
  51. }
  52. for i, payload := range result.Payload.ImageInfo {
  53. if strings.HasPrefix(result.Payload.ImageInfo[i].Place, "192.168") {
  54. result.Payload.ImageInfo[i].PlaceView = payload.Place[strings.Index(payload.Place, "/"):len(payload.Place)]
  55. } else {
  56. result.Payload.ImageInfo[i].PlaceView = payload.Place
  57. }
  58. }
  59. ctx.Data["images"] = result.Payload.ImageInfo
  60. resultPublic, err := cloudbrain.GetPublicImages()
  61. if err != nil {
  62. ctx.Data["error"] = err.Error()
  63. log.Error("cloudbrain.GetPublicImages failed:", err.Error(), ctx.Data["MsgID"])
  64. }
  65. for i, payload := range resultPublic.Payload.ImageInfo {
  66. if strings.HasPrefix(resultPublic.Payload.ImageInfo[i].Place, "192.168") {
  67. resultPublic.Payload.ImageInfo[i].PlaceView = payload.Place[strings.Index(payload.Place, "/"):len(payload.Place)]
  68. } else {
  69. resultPublic.Payload.ImageInfo[i].PlaceView = payload.Place
  70. }
  71. }
  72. ctx.Data["public_images"] = resultPublic.Payload.ImageInfo
  73. //get valid dataset
  74. attachs, err := models.GetAllUserAttachments(ctx.User.ID)
  75. if err != nil {
  76. log.Error("GetAllUserAttachments failed: %v", err, ctx.Data["MsgID"])
  77. return err
  78. }
  79. ctx.Data["attachments"] = attachs
  80. ctx.Data["command"] = cloudbrain.Command
  81. ctx.Data["code_path"] = cloudbrain.CodeMountPath
  82. ctx.Data["dataset_path"] = cloudbrain.DataSetMountPath
  83. ctx.Data["model_path"] = cloudbrain.ModelMountPath
  84. ctx.Data["benchmark_path"] = cloudbrain.BenchMarkMountPath
  85. ctx.Data["is_benchmark_enabled"] = setting.IsBenchmarkEnabled
  86. //get valid resource specs
  87. if categories == nil {
  88. json.Unmarshal([]byte(setting.BenchmarkCategory), &categories)
  89. }
  90. ctx.Data["benchmark_categories"] = categories.Category
  91. ctx.Data["benchmark_types"] = GetBenchmarkTypes(ctx).BenchmarkType
  92. if gpuInfos == nil {
  93. json.Unmarshal([]byte(setting.GpuTypes), &gpuInfos)
  94. }
  95. ctx.Data["gpu_types"] = gpuInfos.GpuInfo
  96. if trainGpuInfos == nil {
  97. json.Unmarshal([]byte(setting.TrainGpuTypes), &trainGpuInfos)
  98. }
  99. ctx.Data["train_gpu_types"] = trainGpuInfos.GpuInfo
  100. if benchmarkGpuInfos == nil {
  101. json.Unmarshal([]byte(setting.BenchmarkGpuTypes), &benchmarkGpuInfos)
  102. }
  103. ctx.Data["benchmark_gpu_types"] = benchmarkGpuInfos.GpuInfo
  104. if benchmarkResourceSpecs == nil {
  105. json.Unmarshal([]byte(setting.BenchmarkResourceSpecs), &benchmarkResourceSpecs)
  106. }
  107. ctx.Data["benchmark_resource_specs"] = benchmarkResourceSpecs.ResourceSpec
  108. if cloudbrain.ResourceSpecs == nil {
  109. json.Unmarshal([]byte(setting.ResourceSpecs), &cloudbrain.ResourceSpecs)
  110. }
  111. ctx.Data["resource_specs"] = cloudbrain.ResourceSpecs.ResourceSpec
  112. if cloudbrain.TrainResourceSpecs == nil {
  113. json.Unmarshal([]byte(setting.TrainResourceSpecs), &cloudbrain.TrainResourceSpecs)
  114. }
  115. ctx.Data["train_resource_specs"] = cloudbrain.TrainResourceSpecs.ResourceSpec
  116. branches, _, err := ctx.Repo.GitRepo.GetBranches(0, 0)
  117. if err != nil {
  118. log.Error("GetBranches error:", err)
  119. }
  120. ctx.Data["branches"] = branches
  121. ctx.Data["branchName"] = ctx.Repo.BranchName
  122. return nil
  123. }
  124. func GrampusTrainJobNPUNew(ctx *context.Context) {
  125. err := grampusTrainJobNpuNewDataPrepare(ctx)
  126. if err != nil {
  127. ctx.ServerError("get new train-job info failed", err)
  128. return
  129. }
  130. ctx.HTML(200, tplGrampusTrainJobNPUNew)
  131. }
  132. func grampusTrainJobNpuNewDataPrepare(ctx *context.Context) error {
  133. ctx.Data["PageIsCloudBrain"] = true
  134. t := time.Now()
  135. var displayJobName = cutString(ctx.User.Name, 5) + t.Format("2006010215") + strconv.Itoa(int(t.Unix()))[5:]
  136. ctx.Data["display_job_name"] = displayJobName
  137. //get valid dataset
  138. attachs, err := models.GetModelArtsTrainAttachments(ctx.User.ID)
  139. if err != nil {
  140. log.Error("GetModelArtsTrainAttachments failed:", err.Error())
  141. } else {
  142. ctx.Data["attachments"] = attachs
  143. }
  144. //get valid engines
  145. images, err := grampus.GetImages(grampus.ProcessorTypeNPU)
  146. if err != nil {
  147. log.Error("GetResourceSpecs failed:", err.Error())
  148. } else {
  149. ctx.Data["engine_versions"] = images.Infos
  150. }
  151. //get valid resource specs
  152. specs, err := grampus.GetResourceSpecs(grampus.ProcessorTypeNPU)
  153. if err != nil {
  154. log.Error("GetResourceSpecs failed:", err.Error())
  155. } else {
  156. ctx.Data["flavor_infos"] = specs.Infos
  157. }
  158. //get branches
  159. branches, _, err := ctx.Repo.GitRepo.GetBranches(0, 0)
  160. if err != nil {
  161. log.Error("GetBranches error:", err.Error())
  162. } else {
  163. ctx.Data["branches"] = branches
  164. }
  165. ctx.Data["branchName"] = ctx.Repo.BranchName
  166. return nil
  167. }
  168. func grampusParamCheckCreateTrainJob(form auth.CreateGrampusTrainJobForm) error {
  169. if !strings.HasSuffix(form.BootFile, ".py") {
  170. log.Error("the boot file(%s) must be a python file", form.BootFile)
  171. return errors.New("启动文件必须是python文件")
  172. }
  173. if form.BranchName == "" {
  174. log.Error("the branch must not be null!", form.BranchName)
  175. return errors.New("代码分支不能为空!")
  176. }
  177. return nil
  178. }
  179. func GrampusTrainJobNpuCreate(ctx *context.Context, form auth.CreateGrampusTrainJobForm) {
  180. displayJobName := form.DisplayJobName
  181. jobName := util.ConvertDisplayJobNameToJobName(displayJobName)
  182. uuid := form.Attachment
  183. description := form.Description
  184. bootFile := form.BootFile
  185. params := form.Params
  186. repo := ctx.Repo.Repository
  187. codeLocalPath := setting.JobPath + jobName + modelarts.CodePath
  188. codeObsPath := grampus.JobPath + jobName + modelarts.CodePath
  189. dataObsPath := setting.BasePath + path.Join(uuid[0:1], uuid[1:2]) + "/" + uuid + "/"
  190. branchName := form.BranchName
  191. isLatestVersion := modelarts.IsLatestVersion
  192. flavorName := form.FlavorName
  193. versionCount := modelarts.VersionCount
  194. engineName := form.EngineName
  195. //check count limit
  196. count, err := models.GetGrampusCountByUserID(ctx.User.ID, string(models.JobTypeTrain), models.NPUResource)
  197. if err != nil {
  198. log.Error("GetGrampusCountByUserID failed:%v", err, ctx.Data["MsgID"])
  199. grampusTrainJobNpuNewDataPrepare(ctx)
  200. ctx.RenderWithErr("system error", tplGrampusTrainJobNPUNew, &form)
  201. return
  202. } else {
  203. if count >= 1 {
  204. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  205. grampusTrainJobNpuNewDataPrepare(ctx)
  206. ctx.RenderWithErr("you have already a running or waiting task, can not create more", tplGrampusTrainJobNPUNew, &form)
  207. return
  208. }
  209. }
  210. //check param
  211. if err := grampusParamCheckCreateTrainJob(form); err != nil {
  212. log.Error("paramCheckCreateTrainJob failed:(%v)", err)
  213. grampusTrainJobNpuNewDataPrepare(ctx)
  214. ctx.RenderWithErr(err.Error(), tplGrampusTrainJobNPUNew, &form)
  215. return
  216. }
  217. //check whether the task name in the project is duplicated
  218. tasks, err := models.GetCloudbrainsByDisplayJobName(repo.ID, string(models.JobTypeTrain), displayJobName)
  219. if err == nil {
  220. if len(tasks) != 0 {
  221. log.Error("the job name did already exist", ctx.Data["MsgID"])
  222. grampusTrainJobNpuNewDataPrepare(ctx)
  223. ctx.RenderWithErr("the job name did already exist", tplGrampusTrainJobNPUNew, &form)
  224. return
  225. }
  226. } else {
  227. if !models.IsErrJobNotExist(err) {
  228. log.Error("system error, %v", err, ctx.Data["MsgID"])
  229. grampusTrainJobNpuNewDataPrepare(ctx)
  230. ctx.RenderWithErr("system error", tplGrampusTrainJobNPUNew, &form)
  231. return
  232. }
  233. }
  234. //check dataset
  235. attachment, err := models.GetAttachmentByUUID(uuid)
  236. if err != nil {
  237. log.Error("GetAttachmentByUUID failed:", err.Error(), ctx.Data["MsgID"])
  238. grampusTrainJobNpuNewDataPrepare(ctx)
  239. ctx.RenderWithErr("dataset is not exist", tplGrampusTrainJobNPUNew, &form)
  240. return
  241. }
  242. //prepare code and out path
  243. _, err = ioutil.ReadDir(codeLocalPath)
  244. if err == nil {
  245. os.RemoveAll(codeLocalPath)
  246. }
  247. if err := downloadZipCode(ctx, codeLocalPath, branchName); err != nil {
  248. log.Error("downloadZipCode failed, server timed out: %s (%v)", repo.FullName(), err)
  249. grampusTrainJobNpuNewDataPrepare(ctx)
  250. ctx.RenderWithErr("Create task failed, server timed out", tplGrampusTrainJobNPUNew, &form)
  251. return
  252. }
  253. //todo: upload code (send to file_server todo this work?)
  254. if err := obsMkdir(setting.CodePathPrefix + jobName + modelarts.OutputPath); err != nil {
  255. log.Error("Failed to obsMkdir_output: %s (%v)", repo.FullName(), err)
  256. grampusTrainJobNpuNewDataPrepare(ctx)
  257. ctx.RenderWithErr("Failed to obsMkdir_output", tplGrampusTrainJobNPUNew, &form)
  258. return
  259. }
  260. if err := uploadCodeToObs(codeLocalPath, jobName, ""); err != nil {
  261. log.Error("Failed to uploadCodeToObs: %s (%v)", repo.FullName(), err)
  262. grampusTrainJobNpuNewDataPrepare(ctx)
  263. ctx.RenderWithErr("Failed to uploadCodeToObs", tplGrampusTrainJobNPUNew, &form)
  264. return
  265. }
  266. //prepare command
  267. command, err := generateCommand(repo.Name, grampus.ProcessorTypeNPU, codeObsPath+cloudbrain.DefaultBranchName+".zip", dataObsPath+attachment.Name, bootFile, params, setting.CodePathPrefix+jobName+modelarts.OutputPath, attachment.Name)
  268. commitID, _ := ctx.Repo.GitRepo.GetBranchCommitID(branchName)
  269. req := &grampus.GenerateTrainJobReq{
  270. JobName: jobName,
  271. DisplayJobName: displayJobName,
  272. ComputeResource: models.NPUResource,
  273. Command: command,
  274. ResourceSpecId: form.FlavorID,
  275. ImageUrl: "",
  276. ImageId: form.ImageID,
  277. DataUrl: dataObsPath,
  278. Description: description,
  279. CodeObsPath: codeObsPath,
  280. BootFileUrl: codeObsPath + bootFile,
  281. BootFile: bootFile,
  282. WorkServerNumber: form.WorkServerNumber,
  283. Uuid: uuid,
  284. CommitID: commitID,
  285. IsLatestVersion: isLatestVersion,
  286. BranchName: branchName,
  287. Params: form.Params,
  288. FlavorName: flavorName,
  289. EngineName: engineName,
  290. VersionCount: versionCount,
  291. TotalVersionCount: modelarts.TotalVersionCount,
  292. DatasetName: attachment.Name,
  293. }
  294. err = grampus.GenerateTrainJob(ctx, req)
  295. if err != nil {
  296. log.Error("GenerateTrainJob failed:%v", err.Error())
  297. grampusTrainJobNpuNewDataPrepare(ctx)
  298. ctx.RenderWithErr(err.Error(), tplGrampusTrainJobNPUNew, &form)
  299. return
  300. }
  301. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/train-job")
  302. }
  303. func GrampusStopJob(ctx *context.Context) {
  304. var ID = ctx.Params(":jobid")
  305. var resultCode = "0"
  306. var errorMsg = ""
  307. var status = ""
  308. task := ctx.Cloudbrain
  309. for {
  310. if task.Status == string(models.GrampusStatusStopped) || task.Status == string(models.GrampusStatusFailed) || task.Status == string(models.GrampusStatusSucceeded) {
  311. log.Error("the job(%s) has been stopped", task.JobName, ctx.Data["msgID"])
  312. resultCode = "-1"
  313. errorMsg = "system error"
  314. break
  315. }
  316. res, err := grampus.StopJob(task.JobID)
  317. if err != nil {
  318. log.Error("StopJob(%s) failed:%v", task.JobName, err, ctx.Data["msgID"])
  319. resultCode = strconv.Itoa(res.ErrorCode)
  320. errorMsg = res.ErrorMsg
  321. break
  322. }
  323. task.Status = string(models.GrampusStatusStopped)
  324. if task.EndTime == 0 {
  325. task.EndTime = timeutil.TimeStampNow()
  326. }
  327. task.ComputeAndSetDuration()
  328. err = models.UpdateJob(task)
  329. if err != nil {
  330. log.Error("UpdateJob(%s) failed:%v", task.JobName, err, ctx.Data["msgID"])
  331. resultCode = "-1"
  332. errorMsg = "system error"
  333. break
  334. }
  335. status = task.Status
  336. break
  337. }
  338. ctx.JSON(200, map[string]interface{}{
  339. "result_code": resultCode,
  340. "error_msg": errorMsg,
  341. "status": status,
  342. "id": ID,
  343. "StatusOK": 0,
  344. })
  345. }
  346. func GrampusTrainJobDel(ctx *context.Context) {
  347. var listType = ctx.Query("listType")
  348. if err := deleteGrampusJob(ctx); err != nil {
  349. log.Error("deleteGrampusJob failed: %v", err, ctx.Data["msgID"])
  350. ctx.ServerError(err.Error(), err)
  351. return
  352. }
  353. var isAdminPage = ctx.Query("isadminpage")
  354. var isHomePage = ctx.Query("ishomepage")
  355. if ctx.IsUserSiteAdmin() && isAdminPage == "true" {
  356. ctx.Redirect(setting.AppSubURL + "/admin" + "/cloudbrains")
  357. } else if isHomePage == "true" {
  358. ctx.Redirect(setting.AppSubURL + "/cloudbrains")
  359. } else {
  360. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/train-job?listType=" + listType)
  361. }
  362. }
  363. func deleteGrampusJob(ctx *context.Context) error {
  364. task := ctx.Cloudbrain
  365. if task.Status != string(models.GrampusStatusStopped) && task.Status != string(models.GrampusStatusSucceeded) && task.Status != string(models.GrampusStatusFailed) {
  366. log.Error("the job(%s) has not been stopped", task.JobName, ctx.Data["msgID"])
  367. return errors.New("the job has not been stopped")
  368. }
  369. err := models.DeleteJob(task)
  370. if err != nil {
  371. log.Error("DeleteJob failed: %v", err, ctx.Data["msgID"])
  372. return err
  373. }
  374. storageType := models.TypeCloudBrainOne
  375. if task.ComputeResource == models.NPUResource {
  376. storageType = models.TypeCloudBrainTwo
  377. }
  378. deleteJobStorage(task.JobName, storageType)
  379. return nil
  380. }
  381. func GrampusTrainJobShow(ctx *context.Context) {
  382. ctx.Data["PageIsCloudBrain"] = true
  383. var task *models.Cloudbrain
  384. task, err := models.GetCloudbrainByJobIDWithDeleted(ctx.Params(":jobid"))
  385. if err != nil {
  386. log.Error("GetCloudbrainByJobID failed:" + err.Error())
  387. ctx.ServerError("system error", err)
  388. return
  389. }
  390. if task.DeletedAt.IsZero() { //normal record
  391. result, err := grampus.GetJob(task.JobID)
  392. if err != nil {
  393. log.Error("GetJob failed:" + err.Error())
  394. //ctx.ServerError("GetJob failed", err)
  395. //return
  396. }
  397. if result != nil {
  398. if len(result.JobInfo.Tasks[0].CenterID) == 1 && len(result.JobInfo.Tasks[0].CenterName) == 1 {
  399. task.AiCenter = result.JobInfo.Tasks[0].CenterID[0] + "+" + result.JobInfo.Tasks[0].CenterName[0]
  400. }
  401. task.Status = grampus.TransTrainJobStatus(result.JobInfo.Status)
  402. if task.Status != result.JobInfo.Status || result.JobInfo.Status == models.GrampusStatusRunning {
  403. task.Duration = result.JobInfo.RunSec
  404. task.TrainJobDuration = models.ConvertDurationToStr(task.Duration)
  405. if task.StartTime == 0 && result.JobInfo.StartedAt > 0 {
  406. task.StartTime = timeutil.TimeStamp(result.JobInfo.StartedAt)
  407. }
  408. if task.EndTime == 0 && models.IsTrainJobTerminal(task.Status) && task.StartTime > 0 {
  409. task.EndTime = task.StartTime.Add(task.Duration)
  410. }
  411. task.CorrectCreateUnix()
  412. err = models.UpdateJob(task)
  413. if err != nil {
  414. log.Error("UpdateJob failed:" + err.Error())
  415. }
  416. }
  417. }
  418. }
  419. if len(task.Parameters) > 0 {
  420. var parameters models.Parameters
  421. err := json.Unmarshal([]byte(task.Parameters), &parameters)
  422. if err != nil {
  423. log.Error("Failed to Unmarshal Parameters: %s (%v)", task.Parameters, err)
  424. ctx.ServerError("system error", err)
  425. return
  426. }
  427. if len(parameters.Parameter) > 0 {
  428. paramTemp := ""
  429. for _, Parameter := range parameters.Parameter {
  430. param := Parameter.Label + " = " + Parameter.Value + "; "
  431. paramTemp = paramTemp + param
  432. }
  433. task.Parameters = paramTemp[:len(paramTemp)-2]
  434. } else {
  435. task.Parameters = ""
  436. }
  437. }
  438. taskList := make([]*models.Cloudbrain, 0)
  439. taskList = append(taskList, task)
  440. ctx.Data["version_list_task"] = taskList
  441. ctx.Data["canDownload"] = cloudbrain.CanModifyJob(ctx, task)
  442. aiCenterInfo := strings.Split(task.AiCenter, "+")
  443. if len(aiCenterInfo) == 2 {
  444. ctx.Data["ai_center"] = aiCenterInfo[1]
  445. }
  446. ctx.HTML(http.StatusOK, tplGrampusTrainJobShow)
  447. }
  448. func GrampusGetLog(ctx *context.Context) {
  449. jobID := ctx.Params(":jobid")
  450. job, err := models.GetCloudbrainByJobID(jobID)
  451. if err != nil {
  452. log.Error("GetCloudbrainByJobID failed: %v", err, ctx.Data["MsgID"])
  453. ctx.ServerError(err.Error(), err)
  454. return
  455. }
  456. content, err := grampus.GetTrainJobLog(job.JobID)
  457. if err != nil {
  458. log.Error("GetJobLog failed: %v", err, ctx.Data["MsgID"])
  459. ctx.ServerError(err.Error(), err)
  460. return
  461. }
  462. ctx.JSON(http.StatusOK, map[string]interface{}{
  463. "JobName": job.JobName,
  464. "Content": content,
  465. })
  466. return
  467. }
  468. func generateCommand(repoName, processorType, codeObsPath, dataObsPath, bootFile, paramSrc, outputObsPath, datasetName string) (string, error) {
  469. var command string
  470. command += grampus.CommandPrepareScript
  471. //download code & dataset
  472. if processorType == grampus.ProcessorTypeNPU {
  473. commandDownload := "./sync_for_arm " + setting.Bucket + " " + codeObsPath + " " + grampus.CodeArchiveName + " " + dataObsPath + " " + datasetName + ";"
  474. command += commandDownload
  475. } else if processorType == grampus.ProcessorTypeGPU {
  476. }
  477. //unzip code & dataset
  478. toolUnzip := "unzip -q "
  479. if strings.HasSuffix(datasetName, ".tar.gz") {
  480. toolUnzip = "tar -zxvf "
  481. }
  482. commandUnzip := "cd /tmp/dataset;" + toolUnzip + datasetName + ";cd /tmp/code;unzip -q master.zip;"
  483. command += commandUnzip
  484. //exec code
  485. var parameters models.Parameters
  486. var paramCode string
  487. param := make([]models.Parameter, 0)
  488. if len(paramSrc) != 0 {
  489. err := json.Unmarshal([]byte(paramSrc), &parameters)
  490. if err != nil {
  491. log.Error("Failed to Unmarshal params: %s (%v)", paramSrc, err)
  492. return command, err
  493. }
  494. for _, parameter := range parameters.Parameter {
  495. param = append(param, models.Parameter{
  496. Label: parameter.Label,
  497. Value: parameter.Value,
  498. })
  499. paramCode += " --" + parameter.Label + "=" + parameter.Value
  500. }
  501. }
  502. commandCode := "cd /tmp/code/" + repoName + ";python " + bootFile + paramCode + ";"
  503. command += commandCode
  504. //get exec result
  505. commandGetRes := "result=$?;"
  506. command += commandGetRes
  507. //upload models
  508. commandUpload := "cd /tmp/script_for_grampus/;./uploader_for_grampus " + setting.Bucket + " " + outputObsPath + " " + "/tmp/output/;"
  509. command += commandUpload
  510. //check exec result
  511. commandCheckRes := " [[ result -eq 0 ]] && echo success || ls failed;"
  512. command += commandCheckRes
  513. return command, nil
  514. }
  515. func downloadZipCode(ctx *context.Context, codePath, branchName string) error {
  516. archiveType := git.ZIP
  517. archivePath := codePath
  518. if !com.IsDir(archivePath) {
  519. if err := os.MkdirAll(archivePath, os.ModePerm); err != nil {
  520. log.Error("MkdirAll failed:" + err.Error())
  521. return err
  522. }
  523. }
  524. // Get corresponding commit.
  525. var (
  526. commit *git.Commit
  527. err error
  528. )
  529. gitRepo := ctx.Repo.GitRepo
  530. if err != nil {
  531. log.Error("OpenRepository failed:" + err.Error())
  532. return err
  533. }
  534. if gitRepo.IsBranchExist(branchName) {
  535. commit, err = gitRepo.GetBranchCommit(branchName)
  536. if err != nil {
  537. log.Error("GetBranchCommit failed:" + err.Error())
  538. return err
  539. }
  540. }
  541. archivePath = path.Join(archivePath, grampus.CodeArchiveName)
  542. if !com.IsFile(archivePath) {
  543. if err := commit.CreateArchive(archivePath, git.CreateArchiveOpts{
  544. Format: archiveType,
  545. Prefix: setting.Repository.PrefixArchiveFiles,
  546. }); err != nil {
  547. log.Error("CreateArchive failed:" + err.Error())
  548. return err
  549. }
  550. }
  551. return nil
  552. }