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