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
4 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
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
5 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 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
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
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
4 years ago
4 years ago
5 years ago
3 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
5 years ago
4 years ago
4 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
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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185
  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. log.Info("task is ...")
  296. jobRes, _ := models.ConvertToJobResultPayload(result.Payload)
  297. jobRes.Resource.Memory = strings.ReplaceAll(jobRes.Resource.Memory, "Mi", "MB")
  298. taskRoles := jobRes.TaskRoles
  299. if jobRes.JobStatus.State != string(models.JobFailed) {
  300. taskRes, _ := models.ConvertToTaskPod(taskRoles[cloudbrain.SubTaskName].(map[string]interface{}))
  301. ctx.Data["taskRes"] = taskRes
  302. task.Status = taskRes.TaskStatuses[0].State
  303. task.ContainerID = taskRes.TaskStatuses[0].ContainerID
  304. task.ContainerIp = taskRes.TaskStatuses[0].ContainerIP
  305. err = models.UpdateJob(task)
  306. if err != nil {
  307. ctx.Data["error"] = err.Error()
  308. }
  309. } else {
  310. task.Status = jobRes.JobStatus.State
  311. taskRes := models.TaskPod{TaskStatuses: []models.TaskStatuses{
  312. {
  313. State: jobRes.JobStatus.State,
  314. },
  315. }}
  316. ctx.Data["taskRes"] = taskRes
  317. jobRes.JobStatus.StartTime = time.Unix(int64(task.CreatedUnix), 0).Format("2006-01-02 15:04:05")
  318. jobRes.JobStatus.EndTime = time.Unix(int64(task.UpdatedUnix), 0).Format("2006-01-02 15:04:05")
  319. }
  320. ctx.Data["result"] = jobRes
  321. } else {
  322. log.Info("error:" + err.Error())
  323. }
  324. ctx.Data["task"] = task
  325. ctx.Data["jobID"] = jobID
  326. ctx.HTML(200, tpName)
  327. }
  328. func CloudBrainDebug(ctx *context.Context) {
  329. debugUrl := setting.DebugServerHost + "jpylab_" + ctx.Cloudbrain.JobID + "_" + ctx.Cloudbrain.SubTaskName
  330. ctx.Redirect(debugUrl)
  331. }
  332. func CloudBrainCommitImage(ctx *context.Context, form auth.CommitImageCloudBrainForm) {
  333. err := cloudbrain.CommitImage(ctx.Cloudbrain.JobID, models.CommitImageParams{
  334. Ip: ctx.Cloudbrain.ContainerIp,
  335. TaskContainerId: ctx.Cloudbrain.ContainerID,
  336. ImageDescription: form.Description,
  337. ImageTag: form.Tag,
  338. })
  339. if err != nil {
  340. log.Error("CommitImage(%s) failed:%v", ctx.Cloudbrain.JobName, err.Error(), ctx.Data["msgID"])
  341. ctx.JSON(200, map[string]string{
  342. "result_code": "-1",
  343. "error_msg": "CommitImage failed",
  344. })
  345. return
  346. }
  347. ctx.JSON(200, map[string]string{
  348. "result_code": "0",
  349. "error_msg": "",
  350. })
  351. }
  352. func CloudBrainStop(ctx *context.Context) {
  353. var jobID = ctx.Params(":jobid")
  354. var resultCode = "0"
  355. var errorMsg = ""
  356. var status = ""
  357. task := ctx.Cloudbrain
  358. for {
  359. if task.Status == string(models.JobStopped) || task.Status == string(models.JobFailed) {
  360. log.Error("the job(%s) has been stopped", task.JobName, ctx.Data["msgID"])
  361. resultCode = "-1"
  362. errorMsg = "system error"
  363. break
  364. }
  365. err := cloudbrain.StopJob(jobID)
  366. if err != nil {
  367. log.Error("StopJob(%s) failed:%v", task.JobName, err, ctx.Data["msgID"])
  368. resultCode = "-1"
  369. errorMsg = "system error"
  370. break
  371. }
  372. task.Status = string(models.JobStopped)
  373. err = models.UpdateJob(task)
  374. if err != nil {
  375. log.Error("UpdateJob(%s) failed:%v", task.JobName, err, ctx.Data["msgID"])
  376. resultCode = "-1"
  377. errorMsg = "system error"
  378. break
  379. }
  380. status = task.Status
  381. break
  382. }
  383. ctx.JSON(200, map[string]string{
  384. "result_code": resultCode,
  385. "error_msg": errorMsg,
  386. "status": status,
  387. "job_id": jobID,
  388. })
  389. }
  390. func StopJobsByUserID(userID int64) {
  391. cloudBrains, err := models.GetCloudbrainsNeededStopByUserID(userID)
  392. if err != nil {
  393. log.Warn("Failed to get cloudBrain info", err)
  394. return
  395. }
  396. StopJobs(cloudBrains)
  397. }
  398. func StopJobsByRepoID(repoID int64) {
  399. cloudBrains, err := models.GetCloudbrainsNeededStopByRepoID(repoID)
  400. if err != nil {
  401. log.Warn("Failed to get cloudBrain info", err)
  402. return
  403. }
  404. StopJobs(cloudBrains)
  405. }
  406. /**
  407. */
  408. func StopJobs(cloudBrains []*models.Cloudbrain) {
  409. for _, taskInfo := range cloudBrains {
  410. if taskInfo.Type == models.TypeCloudBrainOne {
  411. err := retry(3, time.Second*30, func() error {
  412. return cloudbrain.StopJob(taskInfo.JobID)
  413. })
  414. logErrorAndUpdateJobStatus(err, taskInfo)
  415. } else {
  416. if taskInfo.JobType == string(models.JobTypeTrain) {
  417. err := retry(3, time.Second*30, func() error {
  418. _, err := modelarts.StopTrainJob(taskInfo.JobID, strconv.FormatInt(taskInfo.VersionID, 10))
  419. return err
  420. })
  421. logErrorAndUpdateJobStatus(err, taskInfo)
  422. } else {
  423. param := models.NotebookAction{
  424. Action: models.ActionStop,
  425. }
  426. err := retry(3, time.Second*30, func() error {
  427. _, err := modelarts.ManageNotebook(taskInfo.JobID, param)
  428. return err
  429. })
  430. logErrorAndUpdateJobStatus(err, taskInfo)
  431. }
  432. }
  433. }
  434. }
  435. func retry(attempts int, sleep time.Duration, f func() error) (err error) {
  436. for i := 0; i < attempts; i++ {
  437. if i > 0 {
  438. log.Warn("retrying after error:", err)
  439. time.Sleep(sleep)
  440. }
  441. err = f()
  442. if err == nil {
  443. return nil
  444. }
  445. }
  446. return fmt.Errorf("after %d attempts, last error: %s", attempts, err)
  447. }
  448. func logErrorAndUpdateJobStatus(err error, taskInfo *models.Cloudbrain) {
  449. if err != nil {
  450. log.Warn("Failed to stop cloudBrain job:"+taskInfo.JobID, err)
  451. } else {
  452. taskInfo.Status = string(models.JobStopped)
  453. err = models.UpdateJob(taskInfo)
  454. if err != nil {
  455. log.Warn("UpdateJob failed", err)
  456. }
  457. }
  458. }
  459. func CloudBrainDel(ctx *context.Context) {
  460. task := ctx.Cloudbrain
  461. if task.Status != string(models.JobStopped) && task.Status != string(models.JobFailed) {
  462. log.Error("the job(%s) has not been stopped", task.JobName, ctx.Data["msgID"])
  463. ctx.ServerError("the job has not been stopped", errors.New("the job has not been stopped"))
  464. return
  465. }
  466. err := models.DeleteJob(task)
  467. if err != nil {
  468. ctx.ServerError("DeleteJob failed", err)
  469. return
  470. }
  471. deleteJobStorage(task.JobName, models.TypeCloudBrainOne)
  472. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/debugjob?debugListType=all")
  473. }
  474. func CloudBrainShowModels(ctx *context.Context) {
  475. ctx.Data["PageIsCloudBrain"] = true
  476. jobID := ctx.Params(":jobid")
  477. parentDir := ctx.Query("parentDir")
  478. dirArray := strings.Split(parentDir, "/")
  479. task, err := models.GetCloudbrainByJobID(jobID)
  480. if err != nil {
  481. log.Error("no such job!", ctx.Data["msgID"])
  482. ctx.ServerError("no such job:", err)
  483. return
  484. }
  485. //get dirs
  486. dirs, err := GetModelDirs(task.JobName, parentDir)
  487. if err != nil {
  488. log.Error("GetModelDirs failed:%v", err.Error(), ctx.Data["msgID"])
  489. ctx.ServerError("GetModelDirs failed:", err)
  490. return
  491. }
  492. var fileInfos []storage.FileInfo
  493. err = json.Unmarshal([]byte(dirs), &fileInfos)
  494. if err != nil {
  495. log.Error("json.Unmarshal failed:%v", err.Error(), ctx.Data["msgID"])
  496. ctx.ServerError("json.Unmarshal failed:", err)
  497. return
  498. }
  499. for i, fileInfo := range fileInfos {
  500. temp, _ := time.Parse("2006-01-02 15:04:05", fileInfo.ModTime)
  501. fileInfos[i].ModTime = temp.Local().Format("2006-01-02 15:04:05")
  502. }
  503. sort.Slice(fileInfos, func(i, j int) bool {
  504. return fileInfos[i].ModTime > fileInfos[j].ModTime
  505. })
  506. ctx.Data["Path"] = dirArray
  507. ctx.Data["Dirs"] = fileInfos
  508. ctx.Data["task"] = task
  509. ctx.Data["JobID"] = jobID
  510. ctx.HTML(200, tplCloudBrainShowModels)
  511. }
  512. func GetPublicImages(ctx *context.Context) {
  513. getImages(ctx, cloudbrain.Public)
  514. }
  515. func GetCustomImages(ctx *context.Context) {
  516. getImages(ctx, cloudbrain.Custom)
  517. }
  518. func getImages(ctx *context.Context, imageType string) {
  519. log.Info("Get images begin")
  520. page := ctx.QueryInt("page")
  521. size := ctx.QueryInt("size")
  522. name := ctx.Query("name")
  523. getImagesResult, err := cloudbrain.GetImagesPageable(page, size, imageType, name)
  524. if err != nil {
  525. log.Error("Can not get images:%v", err)
  526. ctx.JSON(http.StatusOK, models.GetImagesPayload{
  527. Count: 0,
  528. TotalPages: 0,
  529. ImageInfo: []*models.ImageInfo{},
  530. })
  531. } else {
  532. ctx.JSON(http.StatusOK, getImagesResult.Payload)
  533. }
  534. log.Info("Get images end")
  535. }
  536. func GetModelDirs(jobName string, parentDir string) (string, error) {
  537. var req string
  538. modelActualPath := storage.GetMinioPath(jobName, cloudbrain.ModelMountPath+"/")
  539. if parentDir == "" {
  540. req = "baseDir=" + modelActualPath
  541. } else {
  542. req = "baseDir=" + modelActualPath + "&parentDir=" + parentDir
  543. }
  544. return getDirs(req)
  545. }
  546. func CloudBrainDownloadModel(ctx *context.Context) {
  547. parentDir := ctx.Query("parentDir")
  548. fileName := ctx.Query("fileName")
  549. jobName := ctx.Query("jobName")
  550. filePath := "jobs/" + jobName + "/model/" + parentDir
  551. url, err := storage.Attachments.PresignedGetURL(filePath, fileName)
  552. if err != nil {
  553. log.Error("PresignedGetURL failed: %v", err.Error(), ctx.Data["msgID"])
  554. ctx.ServerError("PresignedGetURL", err)
  555. return
  556. }
  557. http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusMovedPermanently)
  558. }
  559. func GetRate(ctx *context.Context) {
  560. isObjectDetcionAll := ctx.QueryBool("isObjectDetcionAll")
  561. if isObjectDetcionAll {
  562. ctx.Redirect(setting.BenchmarkServerHost + "?username=admin")
  563. return
  564. }
  565. var jobID = ctx.Params(":jobid")
  566. job, err := models.GetCloudbrainByJobID(jobID)
  567. if err != nil {
  568. ctx.ServerError("GetCloudbrainByJobID failed", err)
  569. return
  570. }
  571. if job.JobType == string(models.JobTypeBenchmark) {
  572. log.Info("url=" + setting.BenchmarkServerHost + "?username=" + ctx.User.Name)
  573. ctx.Redirect(setting.BenchmarkServerHost + "?username=" + ctx.User.Name)
  574. } else if job.JobType == string(models.JobTypeSnn4imagenet) {
  575. ctx.Redirect(setting.Snn4imagenetServerHost)
  576. } else if job.JobType == string(models.JobTypeBrainScore) {
  577. ctx.Redirect(setting.BrainScoreServerHost)
  578. } else {
  579. log.Error("JobType error:%s", job.JobType, ctx.Data["msgID"])
  580. }
  581. }
  582. func downloadCode(repo *models.Repository, codePath string) error {
  583. if err := git.Clone(repo.RepoPath(), codePath, git.CloneRepoOptions{}); err != nil {
  584. log.Error("Failed to clone repository: %s (%v)", repo.FullName(), err)
  585. return err
  586. }
  587. configFile, err := os.OpenFile(codePath+"/.git/config", os.O_RDWR, 0666)
  588. if err != nil {
  589. log.Error("open file(%s) failed:%v", codePath+"/,git/config", err)
  590. return err
  591. }
  592. defer configFile.Close()
  593. pos := int64(0)
  594. reader := bufio.NewReader(configFile)
  595. for {
  596. line, err := reader.ReadString('\n')
  597. if err != nil {
  598. if err == io.EOF {
  599. log.Error("not find the remote-url")
  600. return nil
  601. } else {
  602. log.Error("read error: %v", err)
  603. return err
  604. }
  605. }
  606. if strings.Contains(line, "url") && strings.Contains(line, ".git") {
  607. originUrl := "\turl = " + repo.CloneLink().HTTPS + "\n"
  608. if len(line) > len(originUrl) {
  609. originUrl += strings.Repeat(" ", len(line)-len(originUrl))
  610. }
  611. bytes := []byte(originUrl)
  612. _, err := configFile.WriteAt(bytes, pos)
  613. if err != nil {
  614. log.Error("WriteAt failed:%v", err)
  615. return err
  616. }
  617. break
  618. }
  619. pos += int64(len(line))
  620. }
  621. return nil
  622. }
  623. func downloadRateCode(repo *models.Repository, taskName, rateOwnerName, rateRepoName, codePath, benchmarkCategory, gpuType string) error {
  624. err := os.MkdirAll(codePath, os.ModePerm)
  625. if err != nil {
  626. log.Error("mkdir codePath failed", err.Error())
  627. return err
  628. }
  629. repoExt, err := models.GetRepositoryByOwnerAndName(rateOwnerName, rateRepoName)
  630. if err != nil {
  631. log.Error("GetRepositoryByOwnerAndName(%s) failed", rateRepoName, err.Error())
  632. return err
  633. }
  634. if err := git.Clone(repoExt.RepoPath(), codePath, git.CloneRepoOptions{}); err != nil {
  635. log.Error("Failed to clone repository: %s (%v)", repoExt.FullName(), err)
  636. return err
  637. }
  638. fileName := codePath + cloudbrain.TaskInfoName
  639. f, err := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.ModePerm)
  640. if err != nil {
  641. log.Error("OpenFile failed", err.Error())
  642. return err
  643. }
  644. defer f.Close()
  645. data, err := json.Marshal(models.TaskInfo{
  646. Username: repo.Owner.Name,
  647. TaskName: taskName,
  648. CodeName: repo.Name,
  649. BenchmarkCategory: strings.Split(benchmarkCategory, ","),
  650. CodeLink: strings.TrimSuffix(repo.CloneLink().HTTPS, ".git"),
  651. GpuType: gpuType,
  652. })
  653. if err != nil {
  654. log.Error("json.Marshal failed", err.Error())
  655. return err
  656. }
  657. _, err = f.Write(data)
  658. if err != nil {
  659. log.Error("WriteString failed", err.Error())
  660. return err
  661. }
  662. return nil
  663. }
  664. func uploadCodeToMinio(codePath, jobName, parentDir string) error {
  665. files, err := readDir(codePath)
  666. if err != nil {
  667. log.Error("readDir(%s) failed: %s", codePath, err.Error())
  668. return err
  669. }
  670. for _, file := range files {
  671. if file.IsDir() {
  672. if err = uploadCodeToMinio(codePath+file.Name()+"/", jobName, parentDir+file.Name()+"/"); err != nil {
  673. log.Error("uploadCodeToMinio(%s) failed: %s", file.Name(), err.Error())
  674. return err
  675. }
  676. } else {
  677. destObject := setting.CBCodePathPrefix + jobName + parentDir + file.Name()
  678. sourceFile := codePath + file.Name()
  679. err = storage.Attachments.UploadObject(destObject, sourceFile)
  680. if err != nil {
  681. log.Error("UploadObject(%s) failed: %s", file.Name(), err.Error())
  682. return err
  683. }
  684. }
  685. }
  686. return nil
  687. }
  688. func mkModelPath(modelPath string) error {
  689. err := os.MkdirAll(modelPath, os.ModePerm)
  690. if err != nil {
  691. log.Error("MkdirAll(%s) failed:%v", modelPath, err)
  692. return err
  693. }
  694. fileName := modelPath + "README"
  695. f, err := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.ModePerm)
  696. if err != nil {
  697. log.Error("OpenFile failed", err.Error())
  698. return err
  699. }
  700. defer f.Close()
  701. _, err = f.WriteString("You can put the model file into this directory and download it by the web page.")
  702. if err != nil {
  703. log.Error("WriteString failed", err.Error())
  704. return err
  705. }
  706. return nil
  707. }
  708. func deleteJobStorage(jobName string, cloudbrainType int) error {
  709. //delete local
  710. localJobPath := setting.JobPath + jobName
  711. err := os.RemoveAll(localJobPath)
  712. if err != nil {
  713. log.Error("RemoveAll(%s) failed:%v", localJobPath, err)
  714. }
  715. //delete oss
  716. if cloudbrainType == models.TypeCloudBrainOne {
  717. dirPath := setting.CBCodePathPrefix + jobName + "/"
  718. err = storage.Attachments.DeleteDir(dirPath)
  719. if err != nil {
  720. log.Error("DeleteDir(%s) failed:%v", localJobPath, err)
  721. }
  722. } else if cloudbrainType == models.TypeCloudBrainTwo {
  723. //dirPath := setting.CodePathPrefix + jobName + "/"
  724. //err = storage.ObsRemoveObject(setting.Bucket, dirPath)
  725. //if err != nil {
  726. // log.Error("ObsRemoveObject(%s) failed:%v", localJobPath, err)
  727. //}
  728. log.Info("no need to delete")
  729. } else {
  730. log.Error("cloudbrainType(%d) error", cloudbrainType)
  731. }
  732. return nil
  733. }
  734. func SyncCloudbrainStatus() {
  735. cloudBrains, err := models.GetCloudBrainUnStoppedJob()
  736. if err != nil {
  737. log.Error("GetCloudBrainUnStoppedJob failed:", err.Error())
  738. return
  739. }
  740. for _, task := range cloudBrains {
  741. if task.Type == models.TypeCloudBrainOne {
  742. result, err := cloudbrain.GetJob(task.JobID)
  743. if err != nil {
  744. log.Error("GetJob(%s) failed:%v", task.JobName, err)
  745. continue
  746. }
  747. if result != nil {
  748. jobRes, _ := models.ConvertToJobResultPayload(result.Payload)
  749. taskRoles := jobRes.TaskRoles
  750. taskRes, _ := models.ConvertToTaskPod(taskRoles[cloudbrain.SubTaskName].(map[string]interface{}))
  751. task.Status = taskRes.TaskStatuses[0].State
  752. if task.Status != string(models.JobWaiting) {
  753. task.Duration = time.Now().Unix() - taskRes.TaskStatuses[0].StartAt.Unix()
  754. err = models.UpdateJob(task)
  755. if err != nil {
  756. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  757. }
  758. if task.Duration >= setting.MaxDuration {
  759. log.Info("begin to stop job(%s), because of the duration", task.JobName)
  760. err = cloudbrain.StopJob(task.JobID)
  761. if err != nil {
  762. log.Error("StopJob(%s) failed:%v", task.JobName, err)
  763. continue
  764. }
  765. task.Status = string(models.JobStopped)
  766. err = models.UpdateJob(task)
  767. if err != nil {
  768. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  769. }
  770. }
  771. }
  772. }
  773. } else if task.Type == models.TypeCloudBrainTwo {
  774. if task.JobType == string(models.JobTypeDebug) {
  775. result, err := modelarts.GetJob(task.JobID)
  776. if err != nil {
  777. log.Error("GetJob(%s) failed:%v", task.JobName, err)
  778. continue
  779. }
  780. if result != nil {
  781. task.Status = result.Status
  782. err = models.UpdateJob(task)
  783. if err != nil {
  784. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  785. continue
  786. }
  787. }
  788. } else if task.JobType == string(models.JobTypeTrain) {
  789. result, err := modelarts.GetTrainJob(task.JobID, strconv.FormatInt(task.VersionID, 10))
  790. if err != nil {
  791. log.Error("GetTrainJob(%s) failed:%v", task.JobName, err)
  792. continue
  793. }
  794. if result != nil {
  795. task.Status = modelarts.TransTrainJobStatus(result.IntStatus)
  796. task.Duration = result.Duration
  797. task.TrainJobDuration = result.TrainJobDuration
  798. if result.Duration != 0 {
  799. task.TrainJobDuration = util.AddZero(result.Duration/3600000) + ":" + util.AddZero(result.Duration%3600000/60000) + ":" + util.AddZero(result.Duration%60000/1000)
  800. } else {
  801. task.TrainJobDuration = "00:00:00"
  802. }
  803. err = models.UpdateJob(task)
  804. if err != nil {
  805. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  806. continue
  807. }
  808. }
  809. } else {
  810. log.Error("task.JobType(%s) is error:%s", task.JobName, task.JobType)
  811. }
  812. } else {
  813. log.Error("task.Type(%s) is error:%d", task.JobName, task.Type)
  814. }
  815. }
  816. return
  817. }
  818. func CloudBrainBenchmarkIndex(ctx *context.Context) {
  819. MustEnableCloudbrain(ctx)
  820. repo := ctx.Repo.Repository
  821. page := ctx.QueryInt("page")
  822. if page <= 0 {
  823. page = 1
  824. }
  825. var jobTypes []string
  826. jobTypes = append(jobTypes, string(models.JobTypeBenchmark))
  827. ciTasks, count, err := models.Cloudbrains(&models.CloudbrainsOptions{
  828. ListOptions: models.ListOptions{
  829. Page: page,
  830. PageSize: setting.UI.IssuePagingNum,
  831. },
  832. RepoID: repo.ID,
  833. Type: models.TypeCloudBrainOne,
  834. JobTypes: jobTypes,
  835. })
  836. if err != nil {
  837. ctx.ServerError("Get debugjob faild:", err)
  838. return
  839. }
  840. for i, task := range ciTasks {
  841. ciTasks[i].CanDel = cloudbrain.CanDeleteJob(ctx, &task.Cloudbrain)
  842. ciTasks[i].Cloudbrain.ComputeResource = task.ComputeResource
  843. }
  844. pager := context.NewPagination(int(count), setting.UI.IssuePagingNum, page, 5)
  845. pager.AddParam(ctx, "debugListType", "ListType")
  846. ctx.Data["Page"] = pager
  847. ctx.Data["PageIsCloudBrain"] = true
  848. ctx.Data["Tasks"] = ciTasks
  849. ctx.Data["CanCreate"] = cloudbrain.CanCreateOrDebugJob(ctx)
  850. ctx.Data["RepoIsEmpty"] = repo.IsEmpty
  851. ctx.HTML(200, tplCloudBrainBenchmarkIndex)
  852. }
  853. func GetChildTypes(ctx *context.Context) {
  854. benchmarkTypeID := ctx.QueryInt("benchmark_type_id")
  855. resultCode := "-1"
  856. errMsg := ""
  857. childTypes := ""
  858. for {
  859. if benchmarkTypes == nil {
  860. if err := json.Unmarshal([]byte(setting.BenchmarkTypes), &benchmarkTypes); err != nil {
  861. log.Error("json.Unmarshal BenchmarkTypes(%s) failed:%v", setting.BenchmarkTypes, err, ctx.Data["MsgID"])
  862. errMsg = "system error"
  863. break
  864. }
  865. }
  866. var isExist bool
  867. for id, benchmarkType := range benchmarkTypes.BenchmarkType {
  868. if id == benchmarkTypeID {
  869. isExist = true
  870. temp, err := json.Marshal(benchmarkType.Second)
  871. if err != nil {
  872. log.Error("json.Unmarshal BenchmarkTypes(%s) failed:%v", setting.BenchmarkTypes, err, ctx.Data["MsgID"])
  873. errMsg = "system error"
  874. break
  875. }
  876. childTypes = string(temp)
  877. resultCode = "0"
  878. break
  879. }
  880. }
  881. if !isExist {
  882. log.Error("no such benchmark_type_id", ctx.Data["MsgID"])
  883. errMsg = "system error"
  884. break
  885. }
  886. break
  887. }
  888. ctx.JSON(200, map[string]string{
  889. "result_code": resultCode,
  890. "error_msg": errMsg,
  891. "child_types": childTypes,
  892. })
  893. }
  894. func CloudBrainBenchmarkNew(ctx *context.Context) {
  895. err := cloudBrainNewDataPrepare(ctx)
  896. if err != nil {
  897. ctx.ServerError("get new cloudbrain info failed", err)
  898. return
  899. }
  900. ctx.HTML(200, tplCloudBrainBenchmarkNew)
  901. }
  902. func getBenchmarkAttachment(benchmarkTypeID, benchmarkChildTypeID int) (string, error) {
  903. uuid := ""
  904. if benchmarkTypes == nil {
  905. if err := json.Unmarshal([]byte(setting.BenchmarkTypes), &benchmarkTypes); err != nil {
  906. log.Error("json.Unmarshal BenchmarkTypes(%s) failed:%v", setting.BenchmarkTypes, err)
  907. return uuid, err
  908. }
  909. }
  910. var isExist bool
  911. for id, benchmarkType := range benchmarkTypes.BenchmarkType {
  912. if id == benchmarkTypeID {
  913. for childID, childType := range benchmarkType.Second {
  914. if childID == benchmarkChildTypeID {
  915. uuid = childType.Attachment
  916. isExist = true
  917. break
  918. }
  919. }
  920. break
  921. }
  922. }
  923. if !isExist {
  924. log.Error("no such benchmark_type_id&benchmark_child_type_id")
  925. return uuid, errors.New("no such benchmark_type_id&benchmark_child_type_id")
  926. }
  927. return uuid, nil
  928. }
  929. func CloudBrainBenchmarkCreate(ctx *context.Context, form auth.CreateCloudBrainForm) {
  930. ctx.Data["PageIsCloudBrain"] = true
  931. jobName := form.JobName
  932. image := form.Image
  933. gpuQueue := form.GpuType
  934. command := cloudbrain.CommandBenchmark
  935. codePath := setting.JobPath + jobName + cloudbrain.CodeMountPath
  936. resourceSpecId := cloudbrain.BenchMarkResourceID
  937. benchmarkTypeID := form.BenchmarkTypeID
  938. benchmarkChildTypeID := form.BenchmarkChildTypeID
  939. if !jobNamePattern.MatchString(jobName) {
  940. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_jobname_err"), tplCloudBrainBenchmarkNew, &form)
  941. return
  942. }
  943. uuid, err := getBenchmarkAttachment(benchmarkTypeID, benchmarkChildTypeID)
  944. if err != nil {
  945. log.Error("getBenchmarkAttachment failed:%v", err, ctx.Data["MsgID"])
  946. cloudBrainNewDataPrepare(ctx)
  947. ctx.RenderWithErr("benchmark type error", tplCloudBrainBenchmarkNew, &form)
  948. return
  949. }
  950. count, err := models.GetCloudbrainCountByUserID(ctx.User.ID, string(models.JobTypeBenchmark))
  951. if err != nil {
  952. log.Error("GetCloudbrainCountByUserID failed:%v", err, ctx.Data["MsgID"])
  953. cloudBrainNewDataPrepare(ctx)
  954. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  955. return
  956. } else {
  957. if count >= 1 {
  958. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  959. cloudBrainNewDataPrepare(ctx)
  960. ctx.RenderWithErr("you have already a running or waiting task, can not create more", tplCloudBrainBenchmarkNew, &form)
  961. return
  962. }
  963. }
  964. _, err = models.GetCloudbrainByName(jobName)
  965. if err == nil {
  966. log.Error("the job name did already exist", ctx.Data["MsgID"])
  967. cloudBrainNewDataPrepare(ctx)
  968. ctx.RenderWithErr("the job name did already exist", tplCloudBrainBenchmarkNew, &form)
  969. return
  970. } else {
  971. if !models.IsErrJobNotExist(err) {
  972. log.Error("system error, %v", err, ctx.Data["MsgID"])
  973. cloudBrainNewDataPrepare(ctx)
  974. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  975. return
  976. }
  977. }
  978. repo := ctx.Repo.Repository
  979. os.RemoveAll(codePath)
  980. if err := downloadCode(repo, codePath); err != nil {
  981. log.Error("system error, %v", err, ctx.Data["MsgID"])
  982. cloudBrainNewDataPrepare(ctx)
  983. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  984. return
  985. }
  986. if err := uploadCodeToMinio(codePath+"/", jobName, cloudbrain.CodeMountPath+"/"); err != nil {
  987. log.Error("system error, %v", err, ctx.Data["MsgID"])
  988. cloudBrainNewDataPrepare(ctx)
  989. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  990. return
  991. }
  992. benchmarkPath := setting.JobPath + jobName + cloudbrain.BenchMarkMountPath
  993. var gpuType string
  994. for _, gpuInfo := range gpuInfos.GpuInfo {
  995. if gpuInfo.Queue == gpuQueue {
  996. gpuType = gpuInfo.Value
  997. }
  998. }
  999. if err := downloadRateCode(repo, jobName, setting.BenchmarkOwner, setting.BenchmarkName, benchmarkPath, form.BenchmarkCategory, gpuType); err != nil {
  1000. log.Error("system error, %v", err, ctx.Data["MsgID"])
  1001. //cloudBrainNewDataPrepare(ctx)
  1002. //ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  1003. //return
  1004. }
  1005. if err := uploadCodeToMinio(benchmarkPath+"/", jobName, cloudbrain.BenchMarkMountPath+"/"); err != nil {
  1006. log.Error("system error, %v", err, ctx.Data["MsgID"])
  1007. //cloudBrainNewDataPrepare(ctx)
  1008. //ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  1009. //return
  1010. }
  1011. err = cloudbrain.GenerateTask(ctx, jobName, image, command, uuid, storage.GetMinioPath(jobName, cloudbrain.CodeMountPath+"/"),
  1012. storage.GetMinioPath(jobName, cloudbrain.ModelMountPath+"/"),
  1013. storage.GetMinioPath(jobName, cloudbrain.BenchMarkMountPath+"/"), storage.GetMinioPath(jobName, cloudbrain.Snn4imagenetMountPath+"/"),
  1014. storage.GetMinioPath(jobName, cloudbrain.BrainScoreMountPath+"/"), string(models.JobTypeBenchmark), gpuQueue, benchmarkTypeID, benchmarkChildTypeID, resourceSpecId)
  1015. if err != nil {
  1016. cloudBrainNewDataPrepare(ctx)
  1017. ctx.RenderWithErr(err.Error(), tplCloudBrainBenchmarkNew, &form)
  1018. return
  1019. }
  1020. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/cloudbrain/benchmark")
  1021. }