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