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.

cloudbrain.go 34 kB

4 years ago
5 years ago
4 years ago
5 years ago
5 years ago
3 years ago
5 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
4 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
5 years ago
3 years ago
4 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
5 years ago
5 years ago
3 years ago
5 years ago
4 years ago
4 years ago
5 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
5 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
5 years ago
5 years ago
5 years ago
4 years ago
4 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
3 years ago
5 years ago
5 years ago
3 years ago
5 years ago
3 years ago
5 years ago
5 years ago
5 years ago
3 years ago
3 years ago
5 years ago
3 years ago
3 years ago
5 years ago
3 years ago
3 years ago
5 years ago
3 years ago
3 years ago
3 years ago
5 years ago
3 years ago
3 years ago
3 years ago
3 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
5 years ago
5 years ago
4 years ago
4 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122
  1. package repo
  2. import (
  3. "bufio"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "net/http"
  9. "os"
  10. "regexp"
  11. "sort"
  12. "strconv"
  13. "strings"
  14. "time"
  15. "code.gitea.io/gitea/models"
  16. "code.gitea.io/gitea/modules/auth"
  17. "code.gitea.io/gitea/modules/base"
  18. "code.gitea.io/gitea/modules/cloudbrain"
  19. "code.gitea.io/gitea/modules/context"
  20. "code.gitea.io/gitea/modules/git"
  21. "code.gitea.io/gitea/modules/log"
  22. "code.gitea.io/gitea/modules/modelarts"
  23. "code.gitea.io/gitea/modules/setting"
  24. "code.gitea.io/gitea/modules/storage"
  25. "code.gitea.io/gitea/modules/util"
  26. )
  27. const (
  28. tplCloudBrainNew base.TplName = "repo/cloudbrain/new"
  29. tplCloudBrainShow base.TplName = "repo/cloudbrain/show"
  30. tplCloudBrainShowModels base.TplName = "repo/cloudbrain/models/index"
  31. tplCloudBrainBenchmarkIndex base.TplName = "repo/cloudbrain/benchmark/index"
  32. tplCloudBrainBenchmarkNew base.TplName = "repo/cloudbrain/benchmark/new"
  33. )
  34. var (
  35. gpuInfos *models.GpuInfos
  36. categories *models.Categories
  37. benchmarkTypes *models.BenchmarkTypes
  38. )
  39. var jobNamePattern = regexp.MustCompile(`^[a-z0-9][a-z0-9-_]{1,34}[a-z0-9-]$`)
  40. // MustEnableDataset check if repository enable internal cb
  41. func MustEnableCloudbrain(ctx *context.Context) {
  42. if !ctx.Repo.CanRead(models.UnitTypeCloudBrain) {
  43. ctx.NotFound("MustEnableCloudbrain", nil)
  44. return
  45. }
  46. }
  47. func cutString(str string, lens int) string {
  48. if len(str) < lens {
  49. return str
  50. }
  51. return str[:lens]
  52. }
  53. func jobNamePrefixValid(s string) string {
  54. lowStr := strings.ToLower(s)
  55. re := regexp.MustCompile(`[^a-z0-9_\\-]+`)
  56. removeSpecial := re.ReplaceAllString(lowStr, "")
  57. re = regexp.MustCompile(`^[_\\-]+`)
  58. return re.ReplaceAllString(removeSpecial, "")
  59. }
  60. func cloudBrainNewDataPrepare(ctx *context.Context) error {
  61. ctx.Data["PageIsCloudBrain"] = true
  62. t := time.Now()
  63. var jobName = jobNamePrefixValid(cutString(ctx.User.Name, 5)) + t.Format("2006010215") + strconv.Itoa(int(t.Unix()))[5:]
  64. ctx.Data["job_name"] = jobName
  65. result, err := cloudbrain.GetImages()
  66. if err != nil {
  67. ctx.Data["error"] = err.Error()
  68. log.Error("cloudbrain.GetImages failed:", err.Error(), ctx.Data["MsgID"])
  69. }
  70. for i, payload := range result.Payload.ImageInfo {
  71. if strings.HasPrefix(result.Payload.ImageInfo[i].Place, "192.168") {
  72. result.Payload.ImageInfo[i].PlaceView = payload.Place[strings.Index(payload.Place, "/"):len(payload.Place)]
  73. } else {
  74. result.Payload.ImageInfo[i].PlaceView = payload.Place
  75. }
  76. }
  77. ctx.Data["images"] = result.Payload.ImageInfo
  78. resultPublic, err := cloudbrain.GetPublicImages()
  79. if err != nil {
  80. ctx.Data["error"] = err.Error()
  81. log.Error("cloudbrain.GetPublicImages failed:", err.Error(), ctx.Data["MsgID"])
  82. }
  83. for i, payload := range resultPublic.Payload.ImageInfo {
  84. if strings.HasPrefix(resultPublic.Payload.ImageInfo[i].Place, "192.168") {
  85. resultPublic.Payload.ImageInfo[i].PlaceView = payload.Place[strings.Index(payload.Place, "/"):len(payload.Place)]
  86. } else {
  87. resultPublic.Payload.ImageInfo[i].PlaceView = payload.Place
  88. }
  89. }
  90. ctx.Data["public_images"] = resultPublic.Payload.ImageInfo
  91. attachs, err := models.GetAllUserAttachments(ctx.User.ID)
  92. if err != nil {
  93. log.Error("GetAllUserAttachments failed: %v", err, ctx.Data["MsgID"])
  94. return err
  95. }
  96. ctx.Data["attachments"] = attachs
  97. ctx.Data["command"] = cloudbrain.Command
  98. ctx.Data["code_path"] = cloudbrain.CodeMountPath
  99. ctx.Data["dataset_path"] = cloudbrain.DataSetMountPath
  100. ctx.Data["model_path"] = cloudbrain.ModelMountPath
  101. ctx.Data["benchmark_path"] = cloudbrain.BenchMarkMountPath
  102. ctx.Data["is_benchmark_enabled"] = setting.IsBenchmarkEnabled
  103. if categories == nil {
  104. json.Unmarshal([]byte(setting.BenchmarkCategory), &categories)
  105. }
  106. ctx.Data["benchmark_categories"] = categories.Category
  107. if benchmarkTypes == nil {
  108. if err := json.Unmarshal([]byte(setting.BenchmarkTypes), &benchmarkTypes); err != nil {
  109. log.Error("json.Unmarshal BenchmarkTypes(%s) failed:%v", setting.BenchmarkTypes, err, ctx.Data["MsgID"])
  110. }
  111. }
  112. ctx.Data["benchmark_types"] = benchmarkTypes.BenchmarkType
  113. if gpuInfos == nil {
  114. json.Unmarshal([]byte(setting.GpuTypes), &gpuInfos)
  115. }
  116. ctx.Data["gpu_types"] = gpuInfos.GpuInfo
  117. if cloudbrain.ResourceSpecs == nil {
  118. json.Unmarshal([]byte(setting.ResourceSpecs), &cloudbrain.ResourceSpecs)
  119. }
  120. ctx.Data["resource_specs"] = cloudbrain.ResourceSpecs.ResourceSpec
  121. ctx.Data["snn4imagenet_path"] = cloudbrain.Snn4imagenetMountPath
  122. ctx.Data["is_snn4imagenet_enabled"] = setting.IsSnn4imagenetEnabled
  123. ctx.Data["brainscore_path"] = cloudbrain.BrainScoreMountPath
  124. ctx.Data["is_brainscore_enabled"] = setting.IsBrainScoreEnabled
  125. return nil
  126. }
  127. func CloudBrainNew(ctx *context.Context) {
  128. err := cloudBrainNewDataPrepare(ctx)
  129. if err != nil {
  130. ctx.ServerError("get new cloudbrain info failed", err)
  131. return
  132. }
  133. ctx.HTML(200, tplCloudBrainNew)
  134. }
  135. func CloudBrainCreate(ctx *context.Context, form auth.CreateCloudBrainForm) {
  136. ctx.Data["PageIsCloudBrain"] = true
  137. jobName := form.JobName
  138. image := form.Image
  139. uuid := form.Attachment
  140. jobType := form.JobType
  141. command := cloudbrain.Command
  142. gpuQueue := form.GpuType
  143. codePath := setting.JobPath + jobName + cloudbrain.CodeMountPath
  144. resourceSpecId := form.ResourceSpecId
  145. if !jobNamePattern.MatchString(jobName) {
  146. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_jobname_err"), tplCloudBrainNew, &form)
  147. return
  148. }
  149. if jobType != string(models.JobTypeBenchmark) && jobType != string(models.JobTypeDebug) && jobType != string(models.JobTypeSnn4imagenet) && jobType != string(models.JobTypeBrainScore) {
  150. log.Error("jobtype error:", jobType, ctx.Data["MsgID"])
  151. cloudBrainNewDataPrepare(ctx)
  152. ctx.RenderWithErr("jobtype error", tplCloudBrainNew, &form)
  153. return
  154. }
  155. count, err := models.GetCloudbrainCountByUserID(ctx.User.ID, jobType)
  156. if err != nil {
  157. log.Error("GetCloudbrainCountByUserID failed:%v", err, ctx.Data["MsgID"])
  158. cloudBrainNewDataPrepare(ctx)
  159. ctx.RenderWithErr("system error", tplCloudBrainNew, &form)
  160. return
  161. } else {
  162. if count >= 1 {
  163. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  164. cloudBrainNewDataPrepare(ctx)
  165. ctx.RenderWithErr("you have already a running or waiting task, can not create more", tplCloudBrainNew, &form)
  166. return
  167. }
  168. }
  169. _, err = models.GetCloudbrainByName(jobName)
  170. if err == nil {
  171. log.Error("the job name did already exist", ctx.Data["MsgID"])
  172. cloudBrainNewDataPrepare(ctx)
  173. ctx.RenderWithErr("the job name did already exist", tplCloudBrainNew, &form)
  174. return
  175. } else {
  176. if !models.IsErrJobNotExist(err) {
  177. log.Error("system error, %v", err, ctx.Data["MsgID"])
  178. cloudBrainNewDataPrepare(ctx)
  179. ctx.RenderWithErr("system error", tplCloudBrainNew, &form)
  180. return
  181. }
  182. }
  183. repo := ctx.Repo.Repository
  184. downloadCode(repo, codePath)
  185. uploadCodeToMinio(codePath+"/", jobName, cloudbrain.CodeMountPath+"/")
  186. modelPath := setting.JobPath + jobName + cloudbrain.ModelMountPath + "/"
  187. mkModelPath(modelPath)
  188. uploadCodeToMinio(modelPath, jobName, cloudbrain.ModelMountPath+"/")
  189. benchmarkPath := setting.JobPath + jobName + cloudbrain.BenchMarkMountPath
  190. if setting.IsBenchmarkEnabled && jobType == string(models.JobTypeBenchmark) {
  191. var gpuType string
  192. for _, gpuInfo := range gpuInfos.GpuInfo {
  193. if gpuInfo.Queue == gpuQueue {
  194. gpuType = gpuInfo.Value
  195. }
  196. }
  197. downloadRateCode(repo, jobName, setting.BenchmarkOwner, setting.BenchmarkName, benchmarkPath, form.BenchmarkCategory, gpuType)
  198. uploadCodeToMinio(benchmarkPath+"/", jobName, cloudbrain.BenchMarkMountPath+"/")
  199. }
  200. snn4imagenetPath := setting.JobPath + jobName + cloudbrain.Snn4imagenetMountPath
  201. if setting.IsSnn4imagenetEnabled && jobType == string(models.JobTypeSnn4imagenet) {
  202. downloadRateCode(repo, jobName, setting.Snn4imagenetOwner, setting.Snn4imagenetName, snn4imagenetPath, "", "")
  203. uploadCodeToMinio(snn4imagenetPath+"/", jobName, cloudbrain.Snn4imagenetMountPath+"/")
  204. }
  205. brainScorePath := setting.JobPath + jobName + cloudbrain.BrainScoreMountPath
  206. if setting.IsBrainScoreEnabled && jobType == string(models.JobTypeBrainScore) {
  207. downloadRateCode(repo, jobName, setting.BrainScoreOwner, setting.BrainScoreName, brainScorePath, "", "")
  208. uploadCodeToMinio(brainScorePath+"/", jobName, cloudbrain.BrainScoreMountPath+"/")
  209. }
  210. err = cloudbrain.GenerateTask(ctx, jobName, image, command, uuid, storage.GetMinioPath(jobName, cloudbrain.CodeMountPath+"/"),
  211. storage.GetMinioPath(jobName, cloudbrain.ModelMountPath+"/"),
  212. storage.GetMinioPath(jobName, cloudbrain.BenchMarkMountPath+"/"), storage.GetMinioPath(jobName, cloudbrain.Snn4imagenetMountPath+"/"),
  213. storage.GetMinioPath(jobName, cloudbrain.BrainScoreMountPath+"/"), jobType, gpuQueue, 0, 0, resourceSpecId)
  214. if err != nil {
  215. cloudBrainNewDataPrepare(ctx)
  216. ctx.RenderWithErr(err.Error(), tplCloudBrainNew, &form)
  217. return
  218. }
  219. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/debugjob?debugListType=all")
  220. }
  221. func CloudBrainRestart(ctx *context.Context) {
  222. var jobID = ctx.Params(":jobid")
  223. var resultCode = "0"
  224. var errorMsg = ""
  225. var status = string(models.JobWaiting)
  226. task := ctx.Cloudbrain
  227. for {
  228. if task.Status != string(models.JobStopped) && task.Status != string(models.JobSucceeded) && task.Status != string(models.JobFailed) {
  229. log.Error("the job(%s) is not stopped", task.JobName, ctx.Data["MsgID"])
  230. resultCode = "-1"
  231. errorMsg = "the job is not stopped"
  232. break
  233. }
  234. if task.Image == "" || task.GpuQueue == "" || task.Type != models.TypeCloudBrainOne {
  235. log.Error("the job(%s) version is too old", task.JobName, ctx.Data["MsgID"])
  236. resultCode = "-1"
  237. errorMsg = "the job's version is too old and can not be restarted"
  238. break
  239. }
  240. if !ctx.IsSigned || (ctx.User.ID != task.UserID && !ctx.IsUserSiteAdmin()) {
  241. log.Error("the user has no right ro restart the job", task.JobName, ctx.Data["MsgID"])
  242. resultCode = "-1"
  243. errorMsg = "you have no right to restart the job"
  244. break
  245. }
  246. count, err := models.GetCloudbrainCountByUserID(ctx.User.ID, string(models.JobTypeDebug))
  247. if err != nil {
  248. log.Error("GetCloudbrainCountByUserID failed:%v", err, ctx.Data["MsgID"])
  249. resultCode = "-1"
  250. errorMsg = "system error"
  251. break
  252. } else {
  253. if count >= 1 {
  254. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  255. resultCode = "-1"
  256. errorMsg = "you have already a running or waiting task, can not create more"
  257. break
  258. }
  259. }
  260. err = cloudbrain.RestartTask(ctx, task, &jobID)
  261. if err != nil {
  262. log.Error("RestartTask failed:%v", err.Error(), ctx.Data["MsgID"])
  263. resultCode = "-1"
  264. errorMsg = "system error"
  265. break
  266. }
  267. break
  268. }
  269. ctx.JSON(200, map[string]string{
  270. "result_code": resultCode,
  271. "error_msg": errorMsg,
  272. "status": status,
  273. "job_id": jobID,
  274. })
  275. }
  276. func CloudBrainShow(ctx *context.Context) {
  277. ctx.Data["PageIsCloudBrain"] = true
  278. var jobID = ctx.Params(":jobid")
  279. task, err := models.GetCloudbrainByJobID(jobID)
  280. if err != nil {
  281. ctx.Data["error"] = err.Error()
  282. }
  283. result, err := cloudbrain.GetJob(jobID)
  284. if err != nil {
  285. ctx.Data["error"] = err.Error()
  286. }
  287. if result != nil {
  288. jobRes, _ := models.ConvertToJobResultPayload(result.Payload)
  289. jobRes.Resource.Memory = strings.ReplaceAll(jobRes.Resource.Memory, "Mi", "MB")
  290. taskRoles := jobRes.TaskRoles
  291. if jobRes.JobStatus.State != string(models.JobFailed) {
  292. taskRes, _ := models.ConvertToTaskPod(taskRoles[cloudbrain.SubTaskName].(map[string]interface{}))
  293. ctx.Data["taskRes"] = taskRes
  294. task.Status = taskRes.TaskStatuses[0].State
  295. task.ContainerID = taskRes.TaskStatuses[0].ContainerID
  296. task.ContainerIp = taskRes.TaskStatuses[0].ContainerIP
  297. err = models.UpdateJob(task)
  298. if err != nil {
  299. ctx.Data["error"] = err.Error()
  300. }
  301. } else {
  302. task.Status = jobRes.JobStatus.State
  303. taskRes := models.TaskPod{TaskStatuses: []models.TaskStatuses{
  304. {
  305. State: jobRes.JobStatus.State,
  306. },
  307. }}
  308. ctx.Data["taskRes"] = taskRes
  309. jobRes.JobStatus.StartTime = time.Unix(int64(task.CreatedUnix), 0).Format("2006-01-02 15:04:05")
  310. jobRes.JobStatus.EndTime = time.Unix(int64(task.UpdatedUnix), 0).Format("2006-01-02 15:04:05")
  311. }
  312. ctx.Data["result"] = jobRes
  313. }
  314. ctx.Data["task"] = task
  315. ctx.Data["jobID"] = jobID
  316. ctx.HTML(200, tplCloudBrainShow)
  317. }
  318. func CloudBrainDebug(ctx *context.Context) {
  319. debugUrl := setting.DebugServerHost + "jpylab_" + ctx.Cloudbrain.JobID + "_" + ctx.Cloudbrain.SubTaskName
  320. ctx.Redirect(debugUrl)
  321. }
  322. func CloudBrainCommitImage(ctx *context.Context, form auth.CommitImageCloudBrainForm) {
  323. err := cloudbrain.CommitImage(ctx.Cloudbrain.JobID, models.CommitImageParams{
  324. Ip: ctx.Cloudbrain.ContainerIp,
  325. TaskContainerId: ctx.Cloudbrain.ContainerID,
  326. ImageDescription: form.Description,
  327. ImageTag: form.Tag,
  328. })
  329. if err != nil {
  330. log.Error("CommitImage(%s) failed:%v", ctx.Cloudbrain.JobName, err.Error(), ctx.Data["msgID"])
  331. ctx.JSON(200, map[string]string{
  332. "result_code": "-1",
  333. "error_msg": "CommitImage failed",
  334. })
  335. return
  336. }
  337. ctx.JSON(200, map[string]string{
  338. "result_code": "0",
  339. "error_msg": "",
  340. })
  341. }
  342. func CloudBrainStop(ctx *context.Context) {
  343. var jobID = ctx.Params(":jobid")
  344. var resultCode = "0"
  345. var errorMsg = ""
  346. var status = ""
  347. task := ctx.Cloudbrain
  348. for {
  349. if task.Status == string(models.JobStopped) || task.Status == string(models.JobFailed) {
  350. log.Error("the job(%s) has been stopped", task.JobName, ctx.Data["msgID"])
  351. resultCode = "-1"
  352. errorMsg = "system error"
  353. break
  354. }
  355. err := cloudbrain.StopJob(jobID)
  356. if err != nil {
  357. log.Error("StopJob(%s) failed:%v", task.JobName, err, ctx.Data["msgID"])
  358. resultCode = "-1"
  359. errorMsg = "system error"
  360. break
  361. }
  362. task.Status = string(models.JobStopped)
  363. err = models.UpdateJob(task)
  364. if err != nil {
  365. log.Error("UpdateJob(%s) failed:%v", task.JobName, err, ctx.Data["msgID"])
  366. resultCode = "-1"
  367. errorMsg = "system error"
  368. break
  369. }
  370. status = task.Status
  371. break
  372. }
  373. ctx.JSON(200, map[string]string{
  374. "result_code": resultCode,
  375. "error_msg": errorMsg,
  376. "status": status,
  377. "job_id": jobID,
  378. })
  379. }
  380. func StopJobsByUserID(userID int64) {
  381. cloudBrains, err := models.GetCloudbrainsNeededStopByUserID(userID)
  382. if err != nil {
  383. log.Warn("Failed to get cloudBrain info", err)
  384. return
  385. }
  386. StopJobs(cloudBrains)
  387. }
  388. func StopJobsByRepoID(repoID int64) {
  389. cloudBrains, err := models.GetCloudbrainsNeededStopByRepoID(repoID)
  390. if err != nil {
  391. log.Warn("Failed to get cloudBrain info", err)
  392. return
  393. }
  394. StopJobs(cloudBrains)
  395. }
  396. /**
  397. */
  398. func StopJobs(cloudBrains []*models.Cloudbrain) {
  399. for _, taskInfo := range cloudBrains {
  400. if taskInfo.Type == models.TypeCloudBrainOne {
  401. err := retry(3, time.Second*30, func() error {
  402. return cloudbrain.StopJob(taskInfo.JobID)
  403. })
  404. logErrorAndUpdateJobStatus(err, taskInfo)
  405. } else {
  406. if taskInfo.JobType == string(models.JobTypeTrain) {
  407. err := retry(3, time.Second*30, func() error {
  408. _, err := modelarts.StopTrainJob(taskInfo.JobID, strconv.FormatInt(taskInfo.VersionID, 10))
  409. return err
  410. })
  411. logErrorAndUpdateJobStatus(err, taskInfo)
  412. } else {
  413. param := models.NotebookAction{
  414. Action: models.ActionStop,
  415. }
  416. err := retry(3, time.Second*30, func() error {
  417. _, err := modelarts.ManageNotebook(taskInfo.JobID, param)
  418. return err
  419. })
  420. logErrorAndUpdateJobStatus(err, taskInfo)
  421. }
  422. }
  423. }
  424. }
  425. func retry(attempts int, sleep time.Duration, f func() error) (err error) {
  426. for i := 0; i < attempts; i++ {
  427. if i > 0 {
  428. log.Warn("retrying after error:", err)
  429. time.Sleep(sleep)
  430. }
  431. err = f()
  432. if err == nil {
  433. return nil
  434. }
  435. }
  436. return fmt.Errorf("after %d attempts, last error: %s", attempts, err)
  437. }
  438. func logErrorAndUpdateJobStatus(err error, taskInfo *models.Cloudbrain) {
  439. if err != nil {
  440. log.Warn("Failed to stop cloudBrain job:"+taskInfo.JobID, err)
  441. } else {
  442. taskInfo.Status = string(models.JobStopped)
  443. err = models.UpdateJob(taskInfo)
  444. if err != nil {
  445. log.Warn("UpdateJob failed", err)
  446. }
  447. }
  448. }
  449. func CloudBrainDel(ctx *context.Context) {
  450. task := ctx.Cloudbrain
  451. if task.Status != string(models.JobStopped) && task.Status != string(models.JobFailed) {
  452. log.Error("the job(%s) has not been stopped", task.JobName, ctx.Data["msgID"])
  453. ctx.ServerError("the job has not been stopped", errors.New("the job has not been stopped"))
  454. return
  455. }
  456. err := models.DeleteJob(task)
  457. if err != nil {
  458. ctx.ServerError("DeleteJob failed", err)
  459. return
  460. }
  461. deleteJobStorage(task.JobName, models.TypeCloudBrainOne)
  462. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/debugjob?debugListType=all")
  463. }
  464. func CloudBrainShowModels(ctx *context.Context) {
  465. ctx.Data["PageIsCloudBrain"] = true
  466. jobID := ctx.Params(":jobid")
  467. parentDir := ctx.Query("parentDir")
  468. dirArray := strings.Split(parentDir, "/")
  469. task, err := models.GetCloudbrainByJobID(jobID)
  470. if err != nil {
  471. log.Error("no such job!", ctx.Data["msgID"])
  472. ctx.ServerError("no such job:", err)
  473. return
  474. }
  475. //get dirs
  476. dirs, err := GetModelDirs(task.JobName, parentDir)
  477. if err != nil {
  478. log.Error("GetModelDirs failed:%v", err.Error(), ctx.Data["msgID"])
  479. ctx.ServerError("GetModelDirs failed:", err)
  480. return
  481. }
  482. var fileInfos []storage.FileInfo
  483. err = json.Unmarshal([]byte(dirs), &fileInfos)
  484. if err != nil {
  485. log.Error("json.Unmarshal failed:%v", err.Error(), ctx.Data["msgID"])
  486. ctx.ServerError("json.Unmarshal failed:", err)
  487. return
  488. }
  489. for i, fileInfo := range fileInfos {
  490. temp, _ := time.Parse("2006-01-02 15:04:05", fileInfo.ModTime)
  491. fileInfos[i].ModTime = temp.Local().Format("2006-01-02 15:04:05")
  492. }
  493. sort.Slice(fileInfos, func(i, j int) bool {
  494. return fileInfos[i].ModTime > fileInfos[j].ModTime
  495. })
  496. ctx.Data["Path"] = dirArray
  497. ctx.Data["Dirs"] = fileInfos
  498. ctx.Data["task"] = task
  499. ctx.Data["JobID"] = jobID
  500. ctx.HTML(200, tplCloudBrainShowModels)
  501. }
  502. func GetPublicImages(ctx *context.Context) {
  503. getImages(ctx, cloudbrain.Public)
  504. }
  505. func GetCustomImages(ctx *context.Context) {
  506. getImages(ctx, cloudbrain.Custom)
  507. }
  508. func getImages(ctx *context.Context, imageType string) {
  509. log.Info("Get images begin")
  510. page := ctx.QueryInt("page")
  511. size := ctx.QueryInt("size")
  512. name := ctx.Query("name")
  513. getImagesResult, err := cloudbrain.GetImagesPageable(page, size, imageType, name)
  514. if err != nil {
  515. log.Error("Can not get images:%v", err)
  516. ctx.JSON(http.StatusOK, models.GetImagesPayload{
  517. Count: 0,
  518. TotalPages: 0,
  519. ImageInfo: []*models.ImageInfo{},
  520. })
  521. } else {
  522. ctx.JSON(http.StatusOK, getImagesResult.Payload)
  523. }
  524. log.Info("Get images end")
  525. }
  526. func GetModelDirs(jobName string, parentDir string) (string, error) {
  527. var req string
  528. modelActualPath := storage.GetMinioPath(jobName, cloudbrain.ModelMountPath+"/")
  529. if parentDir == "" {
  530. req = "baseDir=" + modelActualPath
  531. } else {
  532. req = "baseDir=" + modelActualPath + "&parentDir=" + parentDir
  533. }
  534. return getDirs(req)
  535. }
  536. func CloudBrainDownloadModel(ctx *context.Context) {
  537. parentDir := ctx.Query("parentDir")
  538. fileName := ctx.Query("fileName")
  539. jobName := ctx.Query("jobName")
  540. filePath := "jobs/" + jobName + "/model/" + parentDir
  541. url, err := storage.Attachments.PresignedGetURL(filePath, fileName)
  542. if err != nil {
  543. log.Error("PresignedGetURL failed: %v", err.Error(), ctx.Data["msgID"])
  544. ctx.ServerError("PresignedGetURL", err)
  545. return
  546. }
  547. http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusMovedPermanently)
  548. }
  549. func GetRate(ctx *context.Context) {
  550. var jobID = ctx.Params(":jobid")
  551. job, err := models.GetCloudbrainByJobID(jobID)
  552. if err != nil {
  553. ctx.ServerError("GetCloudbrainByJobID failed", err)
  554. return
  555. }
  556. if job.JobType == string(models.JobTypeBenchmark) {
  557. ctx.Redirect(setting.BenchmarkServerHost + "?username=" + ctx.User.Name)
  558. } else if job.JobType == string(models.JobTypeSnn4imagenet) {
  559. ctx.Redirect(setting.Snn4imagenetServerHost)
  560. } else if job.JobType == string(models.JobTypeBrainScore) {
  561. ctx.Redirect(setting.BrainScoreServerHost)
  562. } else {
  563. log.Error("JobType error:%s", job.JobType, ctx.Data["msgID"])
  564. }
  565. }
  566. func downloadCode(repo *models.Repository, codePath string) error {
  567. if err := git.Clone(repo.RepoPath(), codePath, git.CloneRepoOptions{}); err != nil {
  568. log.Error("Failed to clone repository: %s (%v)", repo.FullName(), err)
  569. return err
  570. }
  571. configFile, err := os.OpenFile(codePath+"/.git/config", os.O_RDWR, 0666)
  572. if err != nil {
  573. log.Error("open file(%s) failed:%v", codePath+"/,git/config", err)
  574. return err
  575. }
  576. defer configFile.Close()
  577. pos := int64(0)
  578. reader := bufio.NewReader(configFile)
  579. for {
  580. line, err := reader.ReadString('\n')
  581. if err != nil {
  582. if err == io.EOF {
  583. log.Error("not find the remote-url")
  584. return nil
  585. } else {
  586. log.Error("read error: %v", err)
  587. return err
  588. }
  589. }
  590. if strings.Contains(line, "url") && strings.Contains(line, ".git") {
  591. originUrl := "\turl = " + repo.CloneLink().HTTPS + "\n"
  592. if len(line) > len(originUrl) {
  593. originUrl += strings.Repeat(" ", len(line)-len(originUrl))
  594. }
  595. bytes := []byte(originUrl)
  596. _, err := configFile.WriteAt(bytes, pos)
  597. if err != nil {
  598. log.Error("WriteAt failed:%v", err)
  599. return err
  600. }
  601. break
  602. }
  603. pos += int64(len(line))
  604. }
  605. return nil
  606. }
  607. func downloadRateCode(repo *models.Repository, taskName, rateOwnerName, rateRepoName, codePath, benchmarkCategory, gpuType string) error {
  608. err := os.MkdirAll(codePath, os.ModePerm)
  609. if err != nil {
  610. log.Error("mkdir codePath failed", err.Error())
  611. return err
  612. }
  613. repoExt, err := models.GetRepositoryByOwnerAndName(rateOwnerName, rateRepoName)
  614. if err != nil {
  615. log.Error("GetRepositoryByOwnerAndName(%s) failed", rateRepoName, err.Error())
  616. return err
  617. }
  618. if err := git.Clone(repoExt.RepoPath(), codePath, git.CloneRepoOptions{}); err != nil {
  619. log.Error("Failed to clone repository: %s (%v)", repoExt.FullName(), err)
  620. return err
  621. }
  622. fileName := codePath + cloudbrain.TaskInfoName
  623. f, err := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.ModePerm)
  624. if err != nil {
  625. log.Error("OpenFile failed", err.Error())
  626. return err
  627. }
  628. defer f.Close()
  629. data, err := json.Marshal(models.TaskInfo{
  630. Username: repo.Owner.Name,
  631. TaskName: taskName,
  632. CodeName: repo.Name,
  633. BenchmarkCategory: strings.Split(benchmarkCategory, ","),
  634. CodeLink: strings.TrimSuffix(repo.CloneLink().HTTPS, ".git"),
  635. GpuType: gpuType,
  636. })
  637. if err != nil {
  638. log.Error("json.Marshal failed", err.Error())
  639. return err
  640. }
  641. _, err = f.Write(data)
  642. if err != nil {
  643. log.Error("WriteString failed", err.Error())
  644. return err
  645. }
  646. return nil
  647. }
  648. func uploadCodeToMinio(codePath, jobName, parentDir string) error {
  649. files, err := readDir(codePath)
  650. if err != nil {
  651. log.Error("readDir(%s) failed: %s", codePath, err.Error())
  652. return err
  653. }
  654. for _, file := range files {
  655. if file.IsDir() {
  656. if err = uploadCodeToMinio(codePath+file.Name()+"/", jobName, parentDir+file.Name()+"/"); err != nil {
  657. log.Error("uploadCodeToMinio(%s) failed: %s", file.Name(), err.Error())
  658. return err
  659. }
  660. } else {
  661. destObject := setting.CBCodePathPrefix + jobName + parentDir + file.Name()
  662. sourceFile := codePath + file.Name()
  663. err = storage.Attachments.UploadObject(destObject, sourceFile)
  664. if err != nil {
  665. log.Error("UploadObject(%s) failed: %s", file.Name(), err.Error())
  666. return err
  667. }
  668. }
  669. }
  670. return nil
  671. }
  672. func mkModelPath(modelPath string) error {
  673. err := os.MkdirAll(modelPath, os.ModePerm)
  674. if err != nil {
  675. log.Error("MkdirAll(%s) failed:%v", modelPath, err)
  676. return err
  677. }
  678. fileName := modelPath + "README"
  679. f, err := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.ModePerm)
  680. if err != nil {
  681. log.Error("OpenFile failed", err.Error())
  682. return err
  683. }
  684. defer f.Close()
  685. _, err = f.WriteString("You can put the model file into this directory and download it by the web page.")
  686. if err != nil {
  687. log.Error("WriteString failed", err.Error())
  688. return err
  689. }
  690. return nil
  691. }
  692. func deleteJobStorage(jobName string, cloudbrainType int) error {
  693. //delete local
  694. localJobPath := setting.JobPath + jobName
  695. err := os.RemoveAll(localJobPath)
  696. if err != nil {
  697. log.Error("RemoveAll(%s) failed:%v", localJobPath, err)
  698. }
  699. //delete oss
  700. if cloudbrainType == models.TypeCloudBrainOne {
  701. dirPath := setting.CBCodePathPrefix + jobName + "/"
  702. err = storage.Attachments.DeleteDir(dirPath)
  703. if err != nil {
  704. log.Error("DeleteDir(%s) failed:%v", localJobPath, err)
  705. }
  706. } else if cloudbrainType == models.TypeCloudBrainTwo {
  707. //dirPath := setting.CodePathPrefix + jobName + "/"
  708. //err = storage.ObsRemoveObject(setting.Bucket, dirPath)
  709. //if err != nil {
  710. // log.Error("ObsRemoveObject(%s) failed:%v", localJobPath, err)
  711. //}
  712. log.Info("no need to delete")
  713. } else {
  714. log.Error("cloudbrainType(%d) error", cloudbrainType)
  715. }
  716. return nil
  717. }
  718. func SyncCloudbrainStatus() {
  719. cloudBrains, err := models.GetCloudBrainUnStoppedJob()
  720. if err != nil {
  721. log.Error("GetCloudBrainUnStoppedJob failed:", err.Error())
  722. return
  723. }
  724. for _, task := range cloudBrains {
  725. if task.Type == models.TypeCloudBrainOne {
  726. result, err := cloudbrain.GetJob(task.JobID)
  727. if err != nil {
  728. log.Error("GetJob(%s) failed:%v", task.JobName, err)
  729. continue
  730. }
  731. if result != nil {
  732. jobRes, _ := models.ConvertToJobResultPayload(result.Payload)
  733. taskRoles := jobRes.TaskRoles
  734. taskRes, _ := models.ConvertToTaskPod(taskRoles[cloudbrain.SubTaskName].(map[string]interface{}))
  735. task.Status = taskRes.TaskStatuses[0].State
  736. if task.Status != string(models.JobWaiting) {
  737. task.Duration = time.Now().Unix() - taskRes.TaskStatuses[0].StartAt.Unix()
  738. err = models.UpdateJob(task)
  739. if err != nil {
  740. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  741. }
  742. if task.Duration >= setting.MaxDuration {
  743. log.Info("begin to stop job(%s), because of the duration", task.JobName)
  744. err = cloudbrain.StopJob(task.JobID)
  745. if err != nil {
  746. log.Error("StopJob(%s) failed:%v", task.JobName, err)
  747. continue
  748. }
  749. task.Status = string(models.JobStopped)
  750. err = models.UpdateJob(task)
  751. if err != nil {
  752. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  753. }
  754. }
  755. }
  756. }
  757. } else if task.Type == models.TypeCloudBrainTwo {
  758. if task.JobType == string(models.JobTypeDebug) {
  759. result, err := modelarts.GetJob(task.JobID)
  760. if err != nil {
  761. log.Error("GetJob(%s) failed:%v", task.JobName, err)
  762. continue
  763. }
  764. if result != nil {
  765. task.Status = result.Status
  766. err = models.UpdateJob(task)
  767. if err != nil {
  768. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  769. continue
  770. }
  771. }
  772. } else if task.JobType == string(models.JobTypeTrain) {
  773. result, err := modelarts.GetTrainJob(task.JobID, strconv.FormatInt(task.VersionID, 10))
  774. if err != nil {
  775. log.Error("GetTrainJob(%s) failed:%v", task.JobName, err)
  776. continue
  777. }
  778. if result != nil {
  779. task.Status = modelarts.TransTrainJobStatus(result.IntStatus)
  780. task.Duration = result.Duration
  781. task.TrainJobDuration = result.TrainJobDuration
  782. if result.Duration != 0 {
  783. task.TrainJobDuration = util.AddZero(result.Duration/3600000) + ":" + util.AddZero(result.Duration%3600000/60000) + ":" + util.AddZero(result.Duration%60000/1000)
  784. } else {
  785. task.TrainJobDuration = "00:00:00"
  786. }
  787. err = models.UpdateJob(task)
  788. if err != nil {
  789. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  790. continue
  791. }
  792. }
  793. } else {
  794. log.Error("task.JobType(%s) is error:%s", task.JobName, task.JobType)
  795. }
  796. } else {
  797. log.Error("task.Type(%s) is error:%d", task.JobName, task.Type)
  798. }
  799. }
  800. return
  801. }
  802. func CloudBrainBenchmarkIndex(ctx *context.Context) {
  803. MustEnableCloudbrain(ctx)
  804. repo := ctx.Repo.Repository
  805. page := ctx.QueryInt("page")
  806. if page <= 0 {
  807. page = 1
  808. }
  809. var jobTypes []string
  810. jobTypes = append(jobTypes, string(models.JobTypeBenchmark))
  811. ciTasks, count, err := models.Cloudbrains(&models.CloudbrainsOptions{
  812. ListOptions: models.ListOptions{
  813. Page: page,
  814. PageSize: setting.UI.IssuePagingNum,
  815. },
  816. RepoID: repo.ID,
  817. Type: models.TypeCloudBrainOne,
  818. JobTypes: jobTypes,
  819. })
  820. if err != nil {
  821. ctx.ServerError("Get debugjob faild:", err)
  822. return
  823. }
  824. for i, task := range ciTasks {
  825. ciTasks[i].CanDel = cloudbrain.CanDeleteJob(ctx, &task.Cloudbrain)
  826. ciTasks[i].Cloudbrain.ComputeResource = task.ComputeResource
  827. }
  828. pager := context.NewPagination(int(count), setting.UI.IssuePagingNum, page, 5)
  829. pager.AddParam(ctx, "debugListType", "ListType")
  830. ctx.Data["Page"] = pager
  831. ctx.Data["PageIsCloudBrain"] = true
  832. ctx.Data["Tasks"] = ciTasks
  833. ctx.Data["CanCreate"] = cloudbrain.CanCreateOrDebugJob(ctx)
  834. ctx.Data["RepoIsEmpty"] = repo.IsEmpty
  835. ctx.HTML(200, tplCloudBrainBenchmarkIndex)
  836. }
  837. func GetChildTypes(ctx *context.Context) {
  838. benchmarkTypeID := ctx.QueryInt("benchmark_type_id")
  839. resultCode := "-1"
  840. errMsg := ""
  841. childTypes := ""
  842. //
  843. for {
  844. if benchmarkTypes == nil {
  845. if err := json.Unmarshal([]byte(setting.BenchmarkTypes), &benchmarkTypes); err != nil {
  846. log.Error("json.Unmarshal BenchmarkTypes(%s) failed:%v", setting.BenchmarkTypes, err, ctx.Data["MsgID"])
  847. errMsg = "system error"
  848. break
  849. }
  850. }
  851. var isExist bool
  852. for id, _ := range benchmarkTypes.BenchmarkType {
  853. if id == benchmarkTypeID {
  854. isExist = true
  855. //childTypesInfo = benchmarkType.Second
  856. break
  857. }
  858. }
  859. if !isExist {
  860. log.Error("no such benchmark_type_id", ctx.Data["MsgID"])
  861. errMsg = "system error"
  862. break
  863. }
  864. break
  865. }
  866. ctx.JSON(200, map[string]string{
  867. "result_code": resultCode,
  868. "error_msg": errMsg,
  869. "child_types": childTypes,
  870. })
  871. }
  872. func CloudBrainBenchmarkNew(ctx *context.Context) {
  873. err := cloudBrainNewDataPrepare(ctx)
  874. if err != nil {
  875. ctx.ServerError("get new cloudbrain info failed", err)
  876. return
  877. }
  878. ctx.HTML(200, tplCloudBrainBenchmarkNew)
  879. }
  880. func CloudBrainBenchmarkCreate(ctx *context.Context, form auth.CreateCloudBrainForm) {
  881. ctx.Data["PageIsCloudBrain"] = true
  882. jobName := form.JobName
  883. image := form.Image
  884. uuid := form.Attachment
  885. gpuQueue := form.GpuType
  886. command := cloudbrain.CommandBenchmark
  887. codePath := setting.JobPath + jobName + cloudbrain.CodeMountPath
  888. resourceSpecId := form.ResourceSpecId
  889. benchmarkTypeID := form.BenchmarkTypeID
  890. benchmarkChildTypeID := form.BenchmarkChildTypeID
  891. if !jobNamePattern.MatchString(jobName) {
  892. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_jobname_err"), tplCloudBrainBenchmarkNew, &form)
  893. return
  894. }
  895. count, err := models.GetCloudbrainCountByUserID(ctx.User.ID, string(models.JobTypeBenchmark))
  896. if err != nil {
  897. log.Error("GetCloudbrainCountByUserID failed:%v", err, ctx.Data["MsgID"])
  898. cloudBrainNewDataPrepare(ctx)
  899. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  900. return
  901. } else {
  902. if count >= 1 {
  903. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  904. cloudBrainNewDataPrepare(ctx)
  905. ctx.RenderWithErr("you have already a running or waiting task, can not create more", tplCloudBrainBenchmarkNew, &form)
  906. return
  907. }
  908. }
  909. _, err = models.GetCloudbrainByName(jobName)
  910. if err == nil {
  911. log.Error("the job name did already exist", ctx.Data["MsgID"])
  912. cloudBrainNewDataPrepare(ctx)
  913. ctx.RenderWithErr("the job name did already exist", tplCloudBrainBenchmarkNew, &form)
  914. return
  915. } else {
  916. if !models.IsErrJobNotExist(err) {
  917. log.Error("system error, %v", err, ctx.Data["MsgID"])
  918. cloudBrainNewDataPrepare(ctx)
  919. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  920. return
  921. }
  922. }
  923. repo := ctx.Repo.Repository
  924. if err := downloadCode(repo, codePath); err != nil {
  925. log.Error("system error, %v", err, ctx.Data["MsgID"])
  926. cloudBrainNewDataPrepare(ctx)
  927. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  928. return
  929. }
  930. if err := uploadCodeToMinio(codePath+"/", jobName, cloudbrain.CodeMountPath+"/"); err != nil {
  931. log.Error("system error, %v", err, ctx.Data["MsgID"])
  932. cloudBrainNewDataPrepare(ctx)
  933. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  934. return
  935. }
  936. benchmarkPath := setting.JobPath + jobName + cloudbrain.BenchMarkMountPath
  937. var gpuType string
  938. for _, gpuInfo := range gpuInfos.GpuInfo {
  939. if gpuInfo.Queue == gpuQueue {
  940. gpuType = gpuInfo.Value
  941. }
  942. }
  943. if err := downloadRateCode(repo, jobName, setting.BenchmarkOwner, setting.BenchmarkName, benchmarkPath, form.BenchmarkCategory, gpuType); err != nil {
  944. log.Error("system error, %v", err, ctx.Data["MsgID"])
  945. cloudBrainNewDataPrepare(ctx)
  946. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  947. return
  948. }
  949. if err := uploadCodeToMinio(benchmarkPath+"/", jobName, cloudbrain.BenchMarkMountPath+"/"); err != nil {
  950. log.Error("system error, %v", err, ctx.Data["MsgID"])
  951. cloudBrainNewDataPrepare(ctx)
  952. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  953. return
  954. }
  955. err = cloudbrain.GenerateTask(ctx, jobName, image, command, uuid, storage.GetMinioPath(jobName, cloudbrain.CodeMountPath+"/"),
  956. storage.GetMinioPath(jobName, cloudbrain.ModelMountPath+"/"),
  957. storage.GetMinioPath(jobName, cloudbrain.BenchMarkMountPath+"/"), storage.GetMinioPath(jobName, cloudbrain.Snn4imagenetMountPath+"/"),
  958. storage.GetMinioPath(jobName, cloudbrain.BrainScoreMountPath+"/"), string(models.JobTypeBenchmark), gpuQueue, benchmarkTypeID, benchmarkChildTypeID, resourceSpecId)
  959. if err != nil {
  960. cloudBrainNewDataPrepare(ctx)
  961. ctx.RenderWithErr(err.Error(), tplCloudBrainBenchmarkNew, &form)
  962. return
  963. }
  964. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/cloudbrain/benchmark")
  965. }