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