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 54 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
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
4 years ago
3 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
4 years ago
3 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
5 years ago
3 years ago
4 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
4 years ago
4 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
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
5 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
5 years ago
5 years ago
3 years ago
3 years ago
3 years ago
5 years ago
3 years ago
5 years ago
3 years ago
5 years ago
3 years ago
5 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
5 years ago
4 years ago
5 years ago
3 years ago
3 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
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
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 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
5 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
5 years ago
3 years ago
3 years ago
5 years ago
3 years ago
3 years ago
3 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
3 years ago
4 years ago
4 years ago
3 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
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
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
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
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
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
3 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 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
4 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
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
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774
  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. "unicode/utf8"
  16. "code.gitea.io/gitea/modules/timeutil"
  17. "github.com/unknwon/i18n"
  18. "code.gitea.io/gitea/models"
  19. "code.gitea.io/gitea/modules/auth"
  20. "code.gitea.io/gitea/modules/base"
  21. "code.gitea.io/gitea/modules/cloudbrain"
  22. "code.gitea.io/gitea/modules/context"
  23. "code.gitea.io/gitea/modules/git"
  24. "code.gitea.io/gitea/modules/log"
  25. "code.gitea.io/gitea/modules/modelarts"
  26. "code.gitea.io/gitea/modules/setting"
  27. "code.gitea.io/gitea/modules/storage"
  28. "code.gitea.io/gitea/modules/util"
  29. )
  30. const (
  31. tplCloudBrainNew base.TplName = "repo/cloudbrain/new"
  32. tplCloudBrainShow base.TplName = "repo/cloudbrain/show"
  33. tplCloudBrainShowModels base.TplName = "repo/cloudbrain/models/index"
  34. tplCloudBrainBenchmarkIndex base.TplName = "repo/cloudbrain/benchmark/index"
  35. tplCloudBrainBenchmarkNew base.TplName = "repo/cloudbrain/benchmark/new"
  36. tplCloudBrainBenchmarkShow base.TplName = "repo/cloudbrain/benchmark/show"
  37. tplCloudBrainImageSubmit base.TplName = "repo/cloudbrain/image/submit"
  38. tplCloudBrainImageEdit base.TplName = "repo/cloudbrain/image/edit"
  39. )
  40. var (
  41. gpuInfos *models.GpuInfos
  42. categories *models.Categories
  43. benchmarkTypes *models.BenchmarkTypes
  44. benchmarkGpuInfos *models.GpuInfos
  45. benchmarkResourceSpecs *models.ResourceSpecs
  46. )
  47. const BENCHMARK_TYPE_CODE = "repo.cloudbrain.benchmark.types"
  48. var benchmarkTypesMap = make(map[string]*models.BenchmarkTypes, 0)
  49. var jobNamePattern = regexp.MustCompile(`^[a-z0-9][a-z0-9-_]{1,34}[a-z0-9-]$`)
  50. // MustEnableDataset check if repository enable internal cb
  51. func MustEnableCloudbrain(ctx *context.Context) {
  52. if !ctx.Repo.CanRead(models.UnitTypeCloudBrain) {
  53. ctx.NotFound("MustEnableCloudbrain", nil)
  54. return
  55. }
  56. }
  57. func cutString(str string, lens int) string {
  58. if len(str) < lens {
  59. return str
  60. }
  61. return str[:lens]
  62. }
  63. func jobNamePrefixValid(s string) string {
  64. lowStr := strings.ToLower(s)
  65. re := regexp.MustCompile(`[^a-z0-9_\\-]+`)
  66. removeSpecial := re.ReplaceAllString(lowStr, "")
  67. re = regexp.MustCompile(`^[_\\-]+`)
  68. return re.ReplaceAllString(removeSpecial, "")
  69. }
  70. func cloudBrainNewDataPrepare(ctx *context.Context) error {
  71. ctx.Data["PageIsCloudBrain"] = true
  72. t := time.Now()
  73. var displayJobName = jobNamePrefixValid(cutString(ctx.User.Name, 5)) + t.Format("2006010215") + strconv.Itoa(int(t.Unix()))[5:]
  74. ctx.Data["display_job_name"] = displayJobName
  75. result, err := cloudbrain.GetImages()
  76. if err != nil {
  77. ctx.Data["error"] = err.Error()
  78. log.Error("cloudbrain.GetImages failed:", err.Error(), ctx.Data["MsgID"])
  79. }
  80. for i, payload := range result.Payload.ImageInfo {
  81. if strings.HasPrefix(result.Payload.ImageInfo[i].Place, "192.168") {
  82. result.Payload.ImageInfo[i].PlaceView = payload.Place[strings.Index(payload.Place, "/"):len(payload.Place)]
  83. } else {
  84. result.Payload.ImageInfo[i].PlaceView = payload.Place
  85. }
  86. }
  87. ctx.Data["images"] = result.Payload.ImageInfo
  88. resultPublic, err := cloudbrain.GetPublicImages()
  89. if err != nil {
  90. ctx.Data["error"] = err.Error()
  91. log.Error("cloudbrain.GetPublicImages failed:", err.Error(), ctx.Data["MsgID"])
  92. }
  93. for i, payload := range resultPublic.Payload.ImageInfo {
  94. if strings.HasPrefix(resultPublic.Payload.ImageInfo[i].Place, "192.168") {
  95. resultPublic.Payload.ImageInfo[i].PlaceView = payload.Place[strings.Index(payload.Place, "/"):len(payload.Place)]
  96. } else {
  97. resultPublic.Payload.ImageInfo[i].PlaceView = payload.Place
  98. }
  99. }
  100. ctx.Data["public_images"] = resultPublic.Payload.ImageInfo
  101. attachs, err := models.GetAllUserAttachments(ctx.User.ID)
  102. if err != nil {
  103. log.Error("GetAllUserAttachments failed: %v", err, ctx.Data["MsgID"])
  104. return err
  105. }
  106. ctx.Data["attachments"] = attachs
  107. ctx.Data["command"] = cloudbrain.Command
  108. ctx.Data["code_path"] = cloudbrain.CodeMountPath
  109. ctx.Data["dataset_path"] = cloudbrain.DataSetMountPath
  110. ctx.Data["model_path"] = cloudbrain.ModelMountPath
  111. ctx.Data["benchmark_path"] = cloudbrain.BenchMarkMountPath
  112. ctx.Data["is_benchmark_enabled"] = setting.IsBenchmarkEnabled
  113. if categories == nil {
  114. json.Unmarshal([]byte(setting.BenchmarkCategory), &categories)
  115. }
  116. ctx.Data["benchmark_categories"] = categories.Category
  117. ctx.Data["benchmark_types"] = GetBenchmarkTypes(ctx).BenchmarkType
  118. if gpuInfos == nil {
  119. json.Unmarshal([]byte(setting.GpuTypes), &gpuInfos)
  120. }
  121. ctx.Data["gpu_types"] = gpuInfos.GpuInfo
  122. if benchmarkGpuInfos == nil {
  123. json.Unmarshal([]byte(setting.BenchmarkGpuTypes), &benchmarkGpuInfos)
  124. }
  125. ctx.Data["benchmark_gpu_types"] = benchmarkGpuInfos.GpuInfo
  126. if benchmarkResourceSpecs == nil {
  127. json.Unmarshal([]byte(setting.BenchmarkResourceSpecs), &benchmarkResourceSpecs)
  128. }
  129. ctx.Data["benchmark_resource_specs"] = benchmarkResourceSpecs.ResourceSpec
  130. if cloudbrain.ResourceSpecs == nil {
  131. json.Unmarshal([]byte(setting.ResourceSpecs), &cloudbrain.ResourceSpecs)
  132. }
  133. ctx.Data["resource_specs"] = cloudbrain.ResourceSpecs.ResourceSpec
  134. ctx.Data["snn4imagenet_path"] = cloudbrain.Snn4imagenetMountPath
  135. ctx.Data["is_snn4imagenet_enabled"] = setting.IsSnn4imagenetEnabled
  136. ctx.Data["brainscore_path"] = cloudbrain.BrainScoreMountPath
  137. ctx.Data["is_brainscore_enabled"] = setting.IsBrainScoreEnabled
  138. ctx.Data["cloudbraintype"] = models.TypeCloudBrainOne
  139. return nil
  140. }
  141. func CloudBrainNew(ctx *context.Context) {
  142. err := cloudBrainNewDataPrepare(ctx)
  143. if err != nil {
  144. ctx.ServerError("get new cloudbrain info failed", err)
  145. return
  146. }
  147. ctx.HTML(200, tplCloudBrainNew)
  148. }
  149. func CloudBrainCreate(ctx *context.Context, form auth.CreateCloudBrainForm) {
  150. ctx.Data["PageIsCloudBrain"] = true
  151. displayJobName := form.DisplayJobName
  152. jobName := util.ConvertDisplayJobNameToJobName(displayJobName)
  153. image := form.Image
  154. uuid := form.Attachment
  155. jobType := form.JobType
  156. command := cloudbrain.Command
  157. gpuQueue := form.GpuType
  158. codePath := setting.JobPath + jobName + cloudbrain.CodeMountPath
  159. resourceSpecId := form.ResourceSpecId
  160. repo := ctx.Repo.Repository
  161. tasks, err := models.GetCloudbrainsByDisplayJobName(repo.ID, string(models.JobTypeDebug), displayJobName)
  162. if err == nil {
  163. if len(tasks) != 0 {
  164. log.Error("the job name did already exist", ctx.Data["MsgID"])
  165. cloudBrainNewDataPrepare(ctx)
  166. ctx.RenderWithErr("the job name did already exist", tplCloudBrainNew, &form)
  167. return
  168. }
  169. } else {
  170. if !models.IsErrJobNotExist(err) {
  171. log.Error("system error, %v", err, ctx.Data["MsgID"])
  172. cloudBrainNewDataPrepare(ctx)
  173. ctx.RenderWithErr("system error", tplCloudBrainNew, &form)
  174. return
  175. }
  176. }
  177. if !jobNamePattern.MatchString(displayJobName) {
  178. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_jobname_err"), tplCloudBrainNew, &form)
  179. return
  180. }
  181. if jobType != string(models.JobTypeBenchmark) && jobType != string(models.JobTypeDebug) && jobType != string(models.JobTypeSnn4imagenet) && jobType != string(models.JobTypeBrainScore) {
  182. log.Error("jobtype error:", jobType, ctx.Data["MsgID"])
  183. cloudBrainNewDataPrepare(ctx)
  184. ctx.RenderWithErr("jobtype error", tplCloudBrainNew, &form)
  185. return
  186. }
  187. count, err := models.GetCloudbrainCountByUserID(ctx.User.ID, jobType)
  188. if err != nil {
  189. log.Error("GetCloudbrainCountByUserID failed:%v", err, ctx.Data["MsgID"])
  190. cloudBrainNewDataPrepare(ctx)
  191. ctx.RenderWithErr("system error", tplCloudBrainNew, &form)
  192. return
  193. } else {
  194. if count >= 1 {
  195. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  196. cloudBrainNewDataPrepare(ctx)
  197. ctx.RenderWithErr("you have already a running or waiting task, can not create more", tplCloudBrainNew, &form)
  198. return
  199. }
  200. }
  201. downloadCode(repo, codePath)
  202. uploadCodeToMinio(codePath+"/", jobName, cloudbrain.CodeMountPath+"/")
  203. modelPath := setting.JobPath + jobName + cloudbrain.ModelMountPath + "/"
  204. mkModelPath(modelPath)
  205. uploadCodeToMinio(modelPath, jobName, cloudbrain.ModelMountPath+"/")
  206. benchmarkPath := setting.JobPath + jobName + cloudbrain.BenchMarkMountPath
  207. if setting.IsBenchmarkEnabled && jobType == string(models.JobTypeBenchmark) {
  208. var gpuType string
  209. for _, gpuInfo := range gpuInfos.GpuInfo {
  210. if gpuInfo.Queue == gpuQueue {
  211. gpuType = gpuInfo.Value
  212. }
  213. }
  214. downloadRateCode(repo, jobName, setting.BenchmarkOwner, setting.BenchmarkName, benchmarkPath, form.BenchmarkCategory, gpuType)
  215. uploadCodeToMinio(benchmarkPath+"/", jobName, cloudbrain.BenchMarkMountPath+"/")
  216. }
  217. snn4imagenetPath := setting.JobPath + jobName + cloudbrain.Snn4imagenetMountPath
  218. if setting.IsSnn4imagenetEnabled && jobType == string(models.JobTypeSnn4imagenet) {
  219. downloadRateCode(repo, jobName, setting.Snn4imagenetOwner, setting.Snn4imagenetName, snn4imagenetPath, "", "")
  220. uploadCodeToMinio(snn4imagenetPath+"/", jobName, cloudbrain.Snn4imagenetMountPath+"/")
  221. }
  222. brainScorePath := setting.JobPath + jobName + cloudbrain.BrainScoreMountPath
  223. if setting.IsBrainScoreEnabled && jobType == string(models.JobTypeBrainScore) {
  224. downloadRateCode(repo, jobName, setting.BrainScoreOwner, setting.BrainScoreName, brainScorePath, "", "")
  225. uploadCodeToMinio(brainScorePath+"/", jobName, cloudbrain.BrainScoreMountPath+"/")
  226. }
  227. err = cloudbrain.GenerateTask(ctx, displayJobName, jobName, image, command, uuid, storage.GetMinioPath(jobName, cloudbrain.CodeMountPath+"/"),
  228. storage.GetMinioPath(jobName, cloudbrain.ModelMountPath+"/"),
  229. storage.GetMinioPath(jobName, cloudbrain.BenchMarkMountPath+"/"), storage.GetMinioPath(jobName, cloudbrain.Snn4imagenetMountPath+"/"),
  230. storage.GetMinioPath(jobName, cloudbrain.BrainScoreMountPath+"/"), jobType, gpuQueue, form.Description,
  231. 0, 0, resourceSpecId)
  232. if err != nil {
  233. cloudBrainNewDataPrepare(ctx)
  234. ctx.RenderWithErr(err.Error(), tplCloudBrainNew, &form)
  235. return
  236. }
  237. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/debugjob?debugListType=all")
  238. }
  239. func CloudBrainRestart(ctx *context.Context) {
  240. var ID = ctx.Params(":id")
  241. var resultCode = "0"
  242. var errorMsg = ""
  243. var status = string(models.JobWaiting)
  244. task := ctx.Cloudbrain
  245. for {
  246. if task.Status != string(models.JobStopped) && task.Status != string(models.JobSucceeded) && task.Status != string(models.JobFailed) {
  247. log.Error("the job(%s) is not stopped", task.JobName, ctx.Data["MsgID"])
  248. resultCode = "-1"
  249. errorMsg = "the job is not stopped"
  250. break
  251. }
  252. if task.Image == "" || task.GpuQueue == "" || task.Type != models.TypeCloudBrainOne {
  253. log.Error("the job(%s) version is too old", task.JobName, ctx.Data["MsgID"])
  254. resultCode = "-1"
  255. errorMsg = "the job's version is too old and can not be restarted"
  256. break
  257. }
  258. if !ctx.IsSigned || (ctx.User.ID != task.UserID && !ctx.IsUserSiteAdmin()) {
  259. log.Error("the user has no right ro restart the job", task.JobName, ctx.Data["MsgID"])
  260. resultCode = "-1"
  261. errorMsg = "you have no right to restart the job"
  262. break
  263. }
  264. count, err := models.GetCloudbrainCountByUserID(ctx.User.ID, string(models.JobTypeDebug))
  265. if err != nil {
  266. log.Error("GetCloudbrainCountByUserID failed:%v", err, ctx.Data["MsgID"])
  267. resultCode = "-1"
  268. errorMsg = "system error"
  269. break
  270. } else {
  271. if count >= 1 {
  272. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  273. resultCode = "-1"
  274. errorMsg = "you have already a running or waiting task, can not create more"
  275. break
  276. }
  277. }
  278. err = cloudbrain.RestartTask(ctx, task, &ID)
  279. if err != nil {
  280. log.Error("RestartTask failed:%v", err.Error(), ctx.Data["MsgID"])
  281. resultCode = "-1"
  282. errorMsg = "system error"
  283. break
  284. }
  285. break
  286. }
  287. ctx.JSON(200, map[string]string{
  288. "result_code": resultCode,
  289. "error_msg": errorMsg,
  290. "status": status,
  291. "id": ID,
  292. })
  293. }
  294. func CloudBrainBenchMarkShow(ctx *context.Context) {
  295. cloudBrainShow(ctx, tplCloudBrainBenchmarkShow)
  296. }
  297. func CloudBrainShow(ctx *context.Context) {
  298. cloudBrainShow(ctx, tplCloudBrainShow)
  299. }
  300. func cloudBrainShow(ctx *context.Context, tpName base.TplName) {
  301. ctx.Data["PageIsCloudBrain"] = true
  302. var ID = ctx.Params(":id")
  303. debugListType := ctx.Query("debugListType")
  304. task, err := models.GetCloudbrainByID(ID)
  305. if err != nil {
  306. log.Info("error:" + err.Error())
  307. ctx.Data["error"] = err.Error()
  308. }
  309. result, err := cloudbrain.GetJob(task.JobID)
  310. if err != nil {
  311. log.Info("error:" + err.Error())
  312. ctx.Data["error"] = err.Error()
  313. }
  314. if result != nil {
  315. jobRes, _ := models.ConvertToJobResultPayload(result.Payload)
  316. jobRes.Resource.Memory = strings.ReplaceAll(jobRes.Resource.Memory, "Mi", "MB")
  317. spec := "GPU数:" + strconv.Itoa(jobRes.Resource.NvidiaComGpu) + ",CPU数:" + strconv.Itoa(jobRes.Resource.CPU) + ",内存(MB):" + jobRes.Resource.Memory
  318. ctx.Data["resource_spec"] = spec
  319. taskRoles := jobRes.TaskRoles
  320. if jobRes.JobStatus.State != string(models.JobFailed) {
  321. taskRes, _ := models.ConvertToTaskPod(taskRoles[cloudbrain.SubTaskName].(map[string]interface{}))
  322. ctx.Data["taskRes"] = taskRes
  323. task.Status = taskRes.TaskStatuses[0].State
  324. task.ContainerID = taskRes.TaskStatuses[0].ContainerID
  325. task.ContainerIp = taskRes.TaskStatuses[0].ContainerIP
  326. if task.StartTime == 0 && !taskRes.TaskStatuses[0].StartAt.IsZero() {
  327. task.StartTime = timeutil.TimeStamp(taskRes.TaskStatuses[0].StartAt.Unix())
  328. }
  329. err = models.UpdateJob(task)
  330. if err != nil {
  331. ctx.Data["error"] = err.Error()
  332. }
  333. } else {
  334. task.Status = jobRes.JobStatus.State
  335. taskRes := models.TaskPod{TaskStatuses: []models.TaskStatuses{
  336. {
  337. State: jobRes.JobStatus.State,
  338. },
  339. }}
  340. ctx.Data["taskRes"] = taskRes
  341. jobRes.JobStatus.StartTime = time.Unix(int64(task.CreatedUnix), 0).Format("2006-01-02 15:04:05")
  342. jobRes.JobStatus.EndTime = time.Unix(int64(task.UpdatedUnix), 0).Format("2006-01-02 15:04:05")
  343. }
  344. ctx.Data["result"] = jobRes
  345. } else {
  346. log.Info("error:" + err.Error())
  347. }
  348. user, err := models.GetUserByID(task.UserID)
  349. if err == nil {
  350. task.User = user
  351. }
  352. if task.BenchmarkTypeID > 0 {
  353. for _, benchmarkType := range GetBenchmarkTypes(ctx).BenchmarkType {
  354. if task.BenchmarkTypeID == benchmarkType.Id {
  355. ctx.Data["BenchmarkTypeName"] = benchmarkType.First
  356. for _, benchmarkChildType := range benchmarkType.Second {
  357. if task.BenchmarkChildTypeID == benchmarkChildType.Id {
  358. ctx.Data["BenchmarkChildTypeName"] = benchmarkChildType.Value
  359. break
  360. }
  361. }
  362. break
  363. }
  364. }
  365. }
  366. if task.TrainJobDuration == "" {
  367. if task.Duration == 0 {
  368. var duration int64
  369. if task.Status == string(models.JobRunning) {
  370. duration = time.Now().Unix() - int64(task.CreatedUnix)
  371. } else {
  372. duration = int64(task.UpdatedUnix) - int64(task.CreatedUnix)
  373. }
  374. task.Duration = duration
  375. }
  376. task.TrainJobDuration = models.ConvertDurationToStr(task.Duration)
  377. }
  378. ctx.Data["duration"] = task.TrainJobDuration
  379. ctx.Data["task"] = task
  380. ctx.Data["jobName"] = task.JobName
  381. ctx.Data["displayJobName"] = task.DisplayJobName
  382. version_list_task := make([]*models.Cloudbrain, 0)
  383. version_list_task = append(version_list_task, task)
  384. ctx.Data["version_list_task"] = version_list_task
  385. ctx.Data["debugListType"] = debugListType
  386. ctx.HTML(200, tpName)
  387. }
  388. func CloudBrainDebug(ctx *context.Context) {
  389. task := ctx.Cloudbrain
  390. debugUrl := setting.DebugServerHost + "jpylab_" + task.JobID + "_" + task.SubTaskName
  391. ctx.Redirect(debugUrl)
  392. }
  393. func CloudBrainCommitImageShow(ctx *context.Context) {
  394. ctx.Data["PageIsCloudBrain"] = true
  395. ctx.Data["Type"] = ctx.Cloudbrain.Type
  396. ctx.HTML(200, tplCloudBrainImageSubmit)
  397. }
  398. func CloudBrainImageEdit(ctx *context.Context) {
  399. ctx.Data["PageIsImageEdit"] = true
  400. ctx.Data["PageFrom"] = ctx.Params(":from")
  401. var ID = ctx.Params(":id")
  402. id, err := strconv.ParseInt(ID, 10, 64)
  403. if err != nil {
  404. log.Error("GetImageByID failed:%v", err.Error())
  405. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  406. }
  407. image, err := models.GetImageByID(id)
  408. if err != nil {
  409. log.Error("GetImageByID failed:%v", err.Error())
  410. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  411. }
  412. ctx.Data["Image"] = image
  413. ctx.HTML(http.StatusOK, tplCloudBrainImageEdit)
  414. }
  415. func CloudBrainImageEditPost(ctx *context.Context, form auth.EditImageCloudBrainForm) {
  416. if utf8.RuneCountInString(form.Description) > 255 {
  417. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("dataset.description_format_err", 255)))
  418. return
  419. }
  420. validTopics, errMessage := checkTopics(form.Topics)
  421. if errMessage != "" {
  422. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr(errMessage)))
  423. return
  424. }
  425. image, err := models.GetImageByID(form.ID)
  426. if err != nil {
  427. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("repo.image_not_exist")))
  428. }
  429. image.IsPrivate = form.IsPrivate
  430. image.Description = form.Description
  431. err = models.WithTx(func(ctx models.DBContext) error {
  432. if err := models.UpdateLocalImage(image); err != nil {
  433. return err
  434. }
  435. if err := models.SaveImageTopics(image.ID, validTopics...); err != nil {
  436. return err
  437. }
  438. return nil
  439. })
  440. if err != nil {
  441. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("repo.image_not_exist")))
  442. } else {
  443. ctx.JSON(http.StatusOK, models.BaseOKMessage)
  444. }
  445. }
  446. func CloudBrainImageDelete(ctx *context.Context) {
  447. var ID = ctx.Params(":id")
  448. id, err := strconv.ParseInt(ID, 10, 64)
  449. if err != nil {
  450. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("repo.image_not_exist")))
  451. return
  452. }
  453. err = models.DeleteLocalImage(id)
  454. if err != nil {
  455. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("repo.image_delete_fail")))
  456. } else {
  457. ctx.JSON(http.StatusOK, models.BaseOKMessage)
  458. }
  459. }
  460. func CloudBrainCommitImage(ctx *context.Context, form auth.CommitImageCloudBrainForm) {
  461. if !NamePattern.MatchString(form.Tag) {
  462. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("dataset.title_format_err")))
  463. return
  464. }
  465. if utf8.RuneCountInString(form.Description) > 255 {
  466. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("dataset.description_format_err", 255)))
  467. return
  468. }
  469. validTopics, errMessage := checkTopics(form.Topics)
  470. if errMessage != "" {
  471. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr(errMessage)))
  472. return
  473. }
  474. err := cloudbrain.CommitImage(ctx.Cloudbrain.JobID, models.CommitImageParams{
  475. CommitImageCloudBrainParams: models.CommitImageCloudBrainParams{
  476. Ip: ctx.Cloudbrain.ContainerIp,
  477. TaskContainerId: ctx.Cloudbrain.ContainerID,
  478. ImageDescription: form.Description,
  479. ImageTag: form.Tag,
  480. },
  481. IsPrivate: form.IsPrivate,
  482. CloudBrainType: form.Type,
  483. Topics: validTopics,
  484. UID: ctx.User.ID,
  485. })
  486. if err != nil {
  487. log.Error("CommitImage(%s) failed:%v", ctx.Cloudbrain.JobName, err.Error(), ctx.Data["msgID"])
  488. if models.IsErrImageTagExist(err) {
  489. ctx.JSON(200, models.BaseErrorMessage(ctx.Tr("repo.image_exist")))
  490. } else {
  491. ctx.JSON(200, models.BaseErrorMessage(ctx.Tr("repo.image_commit_fail")))
  492. }
  493. return
  494. }
  495. ctx.JSON(200, models.BaseOKMessage)
  496. }
  497. func checkTopics(Topics string) ([]string, string) {
  498. var topics = make([]string, 0)
  499. var topicsStr = strings.TrimSpace(Topics)
  500. if len(topicsStr) > 0 {
  501. topics = strings.Split(topicsStr, ",")
  502. }
  503. validTopics, invalidTopics := models.SanitizeAndValidateImageTopics(topics)
  504. if len(validTopics) > 25 {
  505. return nil, "repo.topic.count_prompt"
  506. }
  507. if len(invalidTopics) > 0 {
  508. return nil, "repo.imagetopic.format_prompt"
  509. }
  510. return validTopics, ""
  511. }
  512. func CloudBrainStop(ctx *context.Context) {
  513. var ID = ctx.Params(":id")
  514. var resultCode = "0"
  515. var errorMsg = ""
  516. var status = ""
  517. task := ctx.Cloudbrain
  518. for {
  519. if task.Status == string(models.JobStopped) || task.Status == string(models.JobFailed) || task.Status == string(models.JobSucceeded) {
  520. log.Error("the job(%s) has been stopped", task.JobName, ctx.Data["msgID"])
  521. resultCode = "-1"
  522. errorMsg = "system error"
  523. break
  524. }
  525. err := cloudbrain.StopJob(task.JobID)
  526. if err != nil {
  527. log.Error("StopJob(%s) failed:%v", task.JobName, err, ctx.Data["msgID"])
  528. resultCode = "-1"
  529. errorMsg = "system error"
  530. break
  531. }
  532. task.Status = string(models.JobStopped)
  533. if task.EndTime == 0 {
  534. task.EndTime = timeutil.TimeStampNow()
  535. }
  536. task.ComputeAndSetDuration()
  537. err = models.UpdateJob(task)
  538. if err != nil {
  539. log.Error("UpdateJob(%s) failed:%v", task.JobName, err, ctx.Data["msgID"])
  540. resultCode = "-1"
  541. errorMsg = "system error"
  542. break
  543. }
  544. status = task.Status
  545. break
  546. }
  547. ctx.JSON(200, map[string]string{
  548. "result_code": resultCode,
  549. "error_msg": errorMsg,
  550. "status": status,
  551. "id": ID,
  552. })
  553. }
  554. func StopJobsByUserID(userID int64) {
  555. cloudBrains, err := models.GetCloudbrainsNeededStopByUserID(userID)
  556. if err != nil {
  557. log.Warn("Failed to get cloudBrain info", err)
  558. return
  559. }
  560. StopJobs(cloudBrains)
  561. }
  562. func StopJobsByRepoID(repoID int64) {
  563. cloudBrains, err := models.GetCloudbrainsNeededStopByRepoID(repoID)
  564. if err != nil {
  565. log.Warn("Failed to get cloudBrain info", err)
  566. return
  567. }
  568. StopJobs(cloudBrains)
  569. }
  570. /**
  571. */
  572. func StopJobs(cloudBrains []*models.Cloudbrain) {
  573. for _, taskInfo := range cloudBrains {
  574. if taskInfo.Type == models.TypeCloudBrainOne {
  575. err := retry(3, time.Second*30, func() error {
  576. return cloudbrain.StopJob(taskInfo.JobID)
  577. })
  578. logErrorAndUpdateJobStatus(err, taskInfo)
  579. } else {
  580. if taskInfo.JobType == string(models.JobTypeTrain) {
  581. err := retry(3, time.Second*30, func() error {
  582. _, err := modelarts.StopTrainJob(taskInfo.JobID, strconv.FormatInt(taskInfo.VersionID, 10))
  583. return err
  584. })
  585. logErrorAndUpdateJobStatus(err, taskInfo)
  586. } else {
  587. param := models.NotebookAction{
  588. Action: models.ActionStop,
  589. }
  590. err := retry(3, time.Second*30, func() error {
  591. _, err := modelarts.ManageNotebook(taskInfo.JobID, param)
  592. return err
  593. })
  594. logErrorAndUpdateJobStatus(err, taskInfo)
  595. }
  596. }
  597. }
  598. }
  599. func retry(attempts int, sleep time.Duration, f func() error) (err error) {
  600. for i := 0; i < attempts; i++ {
  601. if i > 0 {
  602. log.Warn("retrying after error:", err)
  603. time.Sleep(sleep)
  604. }
  605. err = f()
  606. if err == nil {
  607. return nil
  608. }
  609. }
  610. return fmt.Errorf("after %d attempts, last error: %s", attempts, err)
  611. }
  612. func logErrorAndUpdateJobStatus(err error, taskInfo *models.Cloudbrain) {
  613. if err != nil {
  614. log.Warn("Failed to stop cloudBrain job:"+taskInfo.JobID, err)
  615. } else {
  616. taskInfo.Status = string(models.JobStopped)
  617. if taskInfo.EndTime == 0 {
  618. taskInfo.EndTime = timeutil.TimeStampNow()
  619. }
  620. taskInfo.ComputeAndSetDuration()
  621. err = models.UpdateJob(taskInfo)
  622. if err != nil {
  623. log.Warn("UpdateJob failed", err)
  624. }
  625. }
  626. }
  627. func CloudBrainDel(ctx *context.Context) {
  628. var listType = ctx.Query("debugListType")
  629. if err := deleteCloudbrainJob(ctx); err != nil {
  630. log.Error("deleteCloudbrainJob failed: %v", err, ctx.Data["msgID"])
  631. ctx.ServerError(err.Error(), err)
  632. return
  633. }
  634. var isAdminPage = ctx.Query("isadminpage")
  635. if ctx.IsUserSiteAdmin() && isAdminPage == "true" {
  636. ctx.Redirect(setting.AppSubURL + "/admin" + "/cloudbrains")
  637. } else {
  638. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/debugjob?debugListType=" + listType)
  639. }
  640. }
  641. func deleteCloudbrainJob(ctx *context.Context) error {
  642. task := ctx.Cloudbrain
  643. if task.Status != string(models.JobStopped) && task.Status != string(models.JobFailed) && task.Status != string(models.JobSucceeded) {
  644. log.Error("the job(%s) has not been stopped", task.JobName, ctx.Data["msgID"])
  645. return errors.New("the job has not been stopped")
  646. }
  647. err := models.DeleteJob(task)
  648. if err != nil {
  649. log.Error("DeleteJob failed: %v", err, ctx.Data["msgID"])
  650. return err
  651. }
  652. deleteJobStorage(task.JobName, models.TypeCloudBrainOne)
  653. return nil
  654. }
  655. func CloudBrainShowModels(ctx *context.Context) {
  656. ctx.Data["PageIsCloudBrain"] = true
  657. ID := ctx.Params(":id")
  658. parentDir := ctx.Query("parentDir")
  659. dirArray := strings.Split(parentDir, "/")
  660. task, err := models.GetCloudbrainByID(ID)
  661. if err != nil {
  662. log.Error("no such job!", ctx.Data["msgID"])
  663. ctx.ServerError("no such job:", err)
  664. return
  665. }
  666. //get dirs
  667. dirs, err := GetModelDirs(task.JobName, parentDir)
  668. if err != nil {
  669. log.Error("GetModelDirs failed:%v", err.Error(), ctx.Data["msgID"])
  670. ctx.ServerError("GetModelDirs failed:", err)
  671. return
  672. }
  673. var fileInfos []storage.FileInfo
  674. err = json.Unmarshal([]byte(dirs), &fileInfos)
  675. if err != nil {
  676. log.Error("json.Unmarshal failed:%v", err.Error(), ctx.Data["msgID"])
  677. ctx.ServerError("json.Unmarshal failed:", err)
  678. return
  679. }
  680. for i, fileInfo := range fileInfos {
  681. temp, _ := time.Parse("2006-01-02 15:04:05", fileInfo.ModTime)
  682. fileInfos[i].ModTime = temp.Local().Format("2006-01-02 15:04:05")
  683. }
  684. sort.Slice(fileInfos, func(i, j int) bool {
  685. return fileInfos[i].ModTime > fileInfos[j].ModTime
  686. })
  687. ctx.Data["Path"] = dirArray
  688. ctx.Data["Dirs"] = fileInfos
  689. ctx.Data["task"] = task
  690. ctx.Data["ID"] = ID
  691. ctx.HTML(200, tplCloudBrainShowModels)
  692. }
  693. func GetPublicImages(ctx *context.Context) {
  694. uid := getUID(ctx)
  695. opts := models.SearchImageOptions{
  696. IncludePublicOnly: true,
  697. UID: uid,
  698. Keyword: ctx.Query("q"),
  699. Topics: ctx.Query("topic"),
  700. IncludeOfficialOnly: ctx.QueryBool("recommend"),
  701. SearchOrderBy: "type desc, num_stars desc",
  702. }
  703. getImages(ctx, &opts)
  704. }
  705. func GetCustomImages(ctx *context.Context) {
  706. uid := getUID(ctx)
  707. opts := models.SearchImageOptions{
  708. UID: uid,
  709. IncludeOwnerOnly: true,
  710. Keyword: ctx.Query("q"),
  711. Topics: ctx.Query("topic"),
  712. SearchOrderBy: "id desc",
  713. }
  714. getImages(ctx, &opts)
  715. }
  716. func GetStarImages(ctx *context.Context) {
  717. uid := getUID(ctx)
  718. opts := models.SearchImageOptions{
  719. UID: uid,
  720. IncludeStarByMe: true,
  721. Keyword: ctx.Query("q"),
  722. Topics: ctx.Query("topic"),
  723. SearchOrderBy: "id desc",
  724. }
  725. getImages(ctx, &opts)
  726. }
  727. func getUID(ctx *context.Context) int64 {
  728. var uid int64 = -1
  729. if ctx.IsSigned {
  730. uid = ctx.User.ID
  731. }
  732. return uid
  733. }
  734. func GetAllImages(ctx *context.Context) {
  735. uid := getUID(ctx)
  736. opts := models.SearchImageOptions{
  737. UID: uid,
  738. Keyword: ctx.Query("q"),
  739. Topics: ctx.Query("topic"),
  740. SearchOrderBy: "id desc",
  741. }
  742. if ctx.Query("private") != "" {
  743. if ctx.QueryBool("private") {
  744. opts.IncludePrivateOnly = true
  745. } else {
  746. opts.IncludePublicOnly = true
  747. }
  748. }
  749. getImages(ctx, &opts)
  750. }
  751. func getImages(ctx *context.Context, opts *models.SearchImageOptions) {
  752. page := ctx.QueryInt("page")
  753. if page <= 0 {
  754. page = 1
  755. }
  756. pageSize := ctx.QueryInt("pageSize")
  757. if pageSize <= 0 {
  758. pageSize = 15
  759. }
  760. opts.ListOptions = models.ListOptions{
  761. Page: page,
  762. PageSize: pageSize,
  763. }
  764. imageList, total, err := models.SearchImage(opts)
  765. if err != nil {
  766. log.Error("Can not get images:%v", err)
  767. ctx.JSON(http.StatusOK, models.ImagesPageResult{
  768. Count: 0,
  769. Images: []*models.Image{},
  770. })
  771. } else {
  772. ctx.JSON(http.StatusOK, models.ImagesPageResult{
  773. Count: total,
  774. Images: imageList,
  775. })
  776. }
  777. }
  778. func GetModelDirs(jobName string, parentDir string) (string, error) {
  779. var req string
  780. modelActualPath := storage.GetMinioPath(jobName, cloudbrain.ModelMountPath+"/")
  781. if parentDir == "" {
  782. req = "baseDir=" + modelActualPath
  783. } else {
  784. req = "baseDir=" + modelActualPath + "&parentDir=" + parentDir
  785. }
  786. return getDirs(req)
  787. }
  788. func CloudBrainDownloadModel(ctx *context.Context) {
  789. parentDir := ctx.Query("parentDir")
  790. fileName := ctx.Query("fileName")
  791. jobName := ctx.Query("jobName")
  792. filePath := "jobs/" + jobName + "/model/" + parentDir
  793. url, err := storage.Attachments.PresignedGetURL(filePath, fileName)
  794. if err != nil {
  795. log.Error("PresignedGetURL failed: %v", err.Error(), ctx.Data["msgID"])
  796. ctx.ServerError("PresignedGetURL", err)
  797. return
  798. }
  799. http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusMovedPermanently)
  800. }
  801. func GetRate(ctx *context.Context) {
  802. isObjectDetcionAll := ctx.QueryBool("isObjectDetcionAll")
  803. if isObjectDetcionAll {
  804. ctx.Redirect(setting.BenchmarkServerHost + "?username=admin")
  805. return
  806. }
  807. var ID = ctx.Params(":id")
  808. job, err := models.GetCloudbrainByID(ID)
  809. if err != nil {
  810. ctx.ServerError("GetCloudbrainByJobID failed", err)
  811. return
  812. }
  813. if job.JobType == string(models.JobTypeBenchmark) {
  814. log.Info("url=" + setting.BenchmarkServerHost + "?username=" + ctx.User.Name)
  815. ctx.Redirect(setting.BenchmarkServerHost + "?username=" + ctx.User.Name)
  816. } else if job.JobType == string(models.JobTypeSnn4imagenet) {
  817. ctx.Redirect(setting.Snn4imagenetServerHost)
  818. } else if job.JobType == string(models.JobTypeBrainScore) {
  819. ctx.Redirect(setting.BrainScoreServerHost)
  820. } else {
  821. log.Error("JobType error:%s", job.JobType, ctx.Data["msgID"])
  822. }
  823. }
  824. func downloadCode(repo *models.Repository, codePath string) error {
  825. if err := git.Clone(repo.RepoPath(), codePath, git.CloneRepoOptions{}); err != nil {
  826. log.Error("Failed to clone repository: %s (%v)", repo.FullName(), err)
  827. return err
  828. }
  829. configFile, err := os.OpenFile(codePath+"/.git/config", os.O_RDWR, 0666)
  830. if err != nil {
  831. log.Error("open file(%s) failed:%v", codePath+"/,git/config", err)
  832. return err
  833. }
  834. defer configFile.Close()
  835. pos := int64(0)
  836. reader := bufio.NewReader(configFile)
  837. for {
  838. line, err := reader.ReadString('\n')
  839. if err != nil {
  840. if err == io.EOF {
  841. log.Error("not find the remote-url")
  842. return nil
  843. } else {
  844. log.Error("read error: %v", err)
  845. return err
  846. }
  847. }
  848. if strings.Contains(line, "url") && strings.Contains(line, ".git") {
  849. originUrl := "\turl = " + repo.CloneLink().HTTPS + "\n"
  850. if len(line) > len(originUrl) {
  851. originUrl += strings.Repeat(" ", len(line)-len(originUrl))
  852. }
  853. bytes := []byte(originUrl)
  854. _, err := configFile.WriteAt(bytes, pos)
  855. if err != nil {
  856. log.Error("WriteAt failed:%v", err)
  857. return err
  858. }
  859. break
  860. }
  861. pos += int64(len(line))
  862. }
  863. return nil
  864. }
  865. func downloadRateCode(repo *models.Repository, taskName, rateOwnerName, rateRepoName, codePath, benchmarkCategory, gpuType string) error {
  866. err := os.MkdirAll(codePath, os.ModePerm)
  867. if err != nil {
  868. log.Error("mkdir codePath failed", err.Error())
  869. return err
  870. }
  871. repoExt, err := models.GetRepositoryByOwnerAndName(rateOwnerName, rateRepoName)
  872. if err != nil {
  873. log.Error("GetRepositoryByOwnerAndName(%s) failed", rateRepoName, err.Error())
  874. return err
  875. }
  876. if err := git.Clone(repoExt.RepoPath(), codePath, git.CloneRepoOptions{}); err != nil {
  877. log.Error("Failed to clone repository: %s (%v)", repoExt.FullName(), err)
  878. return err
  879. }
  880. fileName := codePath + cloudbrain.TaskInfoName
  881. f, err := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.ModePerm)
  882. if err != nil {
  883. log.Error("OpenFile failed", err.Error())
  884. return err
  885. }
  886. defer f.Close()
  887. data, err := json.Marshal(models.TaskInfo{
  888. Username: repo.Owner.Name,
  889. TaskName: taskName,
  890. CodeName: repo.Name,
  891. BenchmarkCategory: strings.Split(benchmarkCategory, ","),
  892. CodeLink: strings.TrimSuffix(repo.CloneLink().HTTPS, ".git"),
  893. GpuType: gpuType,
  894. })
  895. if err != nil {
  896. log.Error("json.Marshal failed", err.Error())
  897. return err
  898. }
  899. _, err = f.Write(data)
  900. if err != nil {
  901. log.Error("WriteString failed", err.Error())
  902. return err
  903. }
  904. return nil
  905. }
  906. func uploadCodeToMinio(codePath, jobName, parentDir string) error {
  907. files, err := readDir(codePath)
  908. if err != nil {
  909. log.Error("readDir(%s) failed: %s", codePath, err.Error())
  910. return err
  911. }
  912. for _, file := range files {
  913. if file.IsDir() {
  914. if err = uploadCodeToMinio(codePath+file.Name()+"/", jobName, parentDir+file.Name()+"/"); err != nil {
  915. log.Error("uploadCodeToMinio(%s) failed: %s", file.Name(), err.Error())
  916. return err
  917. }
  918. } else {
  919. destObject := setting.CBCodePathPrefix + jobName + parentDir + file.Name()
  920. sourceFile := codePath + file.Name()
  921. err = storage.Attachments.UploadObject(destObject, sourceFile)
  922. if err != nil {
  923. log.Error("UploadObject(%s) failed: %s", file.Name(), err.Error())
  924. return err
  925. }
  926. }
  927. }
  928. return nil
  929. }
  930. func mkModelPath(modelPath string) error {
  931. err := os.MkdirAll(modelPath, os.ModePerm)
  932. if err != nil {
  933. log.Error("MkdirAll(%s) failed:%v", modelPath, err)
  934. return err
  935. }
  936. fileName := modelPath + "README"
  937. f, err := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.ModePerm)
  938. if err != nil {
  939. log.Error("OpenFile failed", err.Error())
  940. return err
  941. }
  942. defer f.Close()
  943. _, err = f.WriteString("You can put the model file into this directory and download it by the web page.")
  944. if err != nil {
  945. log.Error("WriteString failed", err.Error())
  946. return err
  947. }
  948. return nil
  949. }
  950. func deleteJobStorage(jobName string, cloudbrainType int) error {
  951. //delete local
  952. localJobPath := setting.JobPath + jobName
  953. err := os.RemoveAll(localJobPath)
  954. if err != nil {
  955. log.Error("RemoveAll(%s) failed:%v", localJobPath, err)
  956. }
  957. //delete oss
  958. if cloudbrainType == models.TypeCloudBrainOne {
  959. dirPath := setting.CBCodePathPrefix + jobName + "/"
  960. err = storage.Attachments.DeleteDir(dirPath)
  961. if err != nil {
  962. log.Error("DeleteDir(%s) failed:%v", localJobPath, err)
  963. }
  964. } else if cloudbrainType == models.TypeCloudBrainTwo {
  965. //dirPath := setting.CodePathPrefix + jobName + "/"
  966. //err = storage.ObsRemoveObject(setting.Bucket, dirPath)
  967. //if err != nil {
  968. // log.Error("ObsRemoveObject(%s) failed:%v", localJobPath, err)
  969. //}
  970. log.Info("no need to delete")
  971. } else {
  972. log.Error("cloudbrainType(%d) error", cloudbrainType)
  973. }
  974. return nil
  975. }
  976. func SyncCloudbrainStatus() {
  977. cloudBrains, err := models.GetCloudBrainUnStoppedJob()
  978. if err != nil {
  979. log.Error("GetCloudBrainUnStoppedJob failed:", err.Error())
  980. return
  981. }
  982. for _, task := range cloudBrains {
  983. if task.Type == models.TypeCloudBrainOne {
  984. result, err := cloudbrain.GetJob(task.JobID)
  985. if err != nil {
  986. log.Error("GetJob(%s) failed:%v", task.JobName, err)
  987. continue
  988. }
  989. if result != nil {
  990. jobRes, _ := models.ConvertToJobResultPayload(result.Payload)
  991. taskRoles := jobRes.TaskRoles
  992. taskRes, _ := models.ConvertToTaskPod(taskRoles[cloudbrain.SubTaskName].(map[string]interface{}))
  993. task.Status = taskRes.TaskStatuses[0].State
  994. if task.Status != string(models.JobWaiting) {
  995. task.Duration = time.Now().Unix() - taskRes.TaskStatuses[0].StartAt.Unix()
  996. if task.StartTime == 0 && !taskRes.TaskStatuses[0].StartAt.IsZero() {
  997. task.StartTime = timeutil.TimeStamp(taskRes.TaskStatuses[0].StartAt.Unix())
  998. }
  999. if task.EndTime == 0 && models.IsCloudBrainOneDebugJobTerminal(task.Status) {
  1000. task.EndTime = timeutil.TimeStampNow()
  1001. }
  1002. task.ComputeAndSetDuration()
  1003. err = models.UpdateJob(task)
  1004. if err != nil {
  1005. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1006. }
  1007. var maxDuration int64
  1008. if task.JobType == string(models.JobTypeBenchmark) {
  1009. maxDuration = setting.BenchmarkMaxDuration
  1010. } else {
  1011. maxDuration = setting.MaxDuration
  1012. }
  1013. if task.Duration >= maxDuration {
  1014. log.Info("begin to stop job(%s), because of the duration", task.JobName)
  1015. err = cloudbrain.StopJob(task.JobID)
  1016. if err != nil {
  1017. log.Error("StopJob(%s) failed:%v", task.JobName, err)
  1018. continue
  1019. }
  1020. task.Status = string(models.JobStopped)
  1021. if task.EndTime == 0 {
  1022. task.EndTime = timeutil.TimeStampNow()
  1023. }
  1024. task.ComputeAndSetDuration()
  1025. err = models.UpdateJob(task)
  1026. if err != nil {
  1027. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1028. }
  1029. }
  1030. }
  1031. }
  1032. } else if task.Type == models.TypeCloudBrainTwo {
  1033. if task.JobType == string(models.JobTypeDebug) {
  1034. //result, err := modelarts.GetJob(task.JobID)
  1035. result, err := modelarts.GetNotebook2(task.JobID)
  1036. if err != nil {
  1037. log.Error("GetJob(%s) failed:%v", task.JobName, err)
  1038. continue
  1039. }
  1040. if result != nil {
  1041. task.Status = result.Status
  1042. if task.StartTime == 0 && result.Lease.CreateTime > 0 {
  1043. task.StartTime = timeutil.TimeStamp(result.Lease.CreateTime / 1000)
  1044. }
  1045. if task.EndTime == 0 && models.IsModelArtsDebugJobTerminal(task.Status) {
  1046. task.EndTime = timeutil.TimeStampNow()
  1047. }
  1048. task.ComputeAndSetDuration()
  1049. err = models.UpdateJob(task)
  1050. if err != nil {
  1051. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1052. continue
  1053. }
  1054. }
  1055. } else if task.JobType == string(models.JobTypeTrain) {
  1056. result, err := modelarts.GetTrainJob(task.JobID, strconv.FormatInt(task.VersionID, 10))
  1057. if err != nil {
  1058. log.Error("GetTrainJob(%s) failed:%v", task.JobName, err)
  1059. continue
  1060. }
  1061. if result != nil {
  1062. task.Status = modelarts.TransTrainJobStatus(result.IntStatus)
  1063. task.Duration = result.Duration / 1000
  1064. task.TrainJobDuration = result.TrainJobDuration
  1065. if task.StartTime == 0 && result.StartTime > 0 {
  1066. task.StartTime = timeutil.TimeStamp(result.StartTime / 1000)
  1067. }
  1068. task.TrainJobDuration = models.ConvertDurationToStr(task.Duration)
  1069. if task.EndTime == 0 && models.IsTrainJobTerminal(task.Status) && task.StartTime > 0 {
  1070. task.EndTime = task.StartTime.Add(task.Duration)
  1071. }
  1072. err = models.UpdateJob(task)
  1073. if err != nil {
  1074. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1075. continue
  1076. }
  1077. }
  1078. } else {
  1079. log.Error("task.JobType(%s) is error:%s", task.JobName, task.JobType)
  1080. }
  1081. } else {
  1082. log.Error("task.Type(%s) is error:%d", task.JobName, task.Type)
  1083. }
  1084. }
  1085. return
  1086. }
  1087. func HandleTaskWithNoDuration(ctx *context.Context) {
  1088. log.Info("HandleTaskWithNoDuration start")
  1089. count := 0
  1090. for {
  1091. cloudBrains, err := models.GetStoppedJobWithNoDurationJob()
  1092. if err != nil {
  1093. log.Error("HandleTaskWithNoTrainJobDuration failed:", err.Error())
  1094. break
  1095. }
  1096. if len(cloudBrains) == 0 {
  1097. log.Info("HandleTaskWithNoTrainJobDuration:no task need handle")
  1098. break
  1099. }
  1100. handleNoDurationTask(cloudBrains)
  1101. count += len(cloudBrains)
  1102. if len(cloudBrains) < 100 {
  1103. log.Info("HandleTaskWithNoTrainJobDuration:task less than 100")
  1104. break
  1105. }
  1106. }
  1107. log.Info("HandleTaskWithNoTrainJobDuration:count=%d", count)
  1108. ctx.JSON(200, "success")
  1109. }
  1110. func handleNoDurationTask(cloudBrains []*models.Cloudbrain) {
  1111. for _, task := range cloudBrains {
  1112. log.Info("Handle job ,%+v", task)
  1113. if task.Type == models.TypeCloudBrainOne {
  1114. result, err := cloudbrain.GetJob(task.JobID)
  1115. if err != nil {
  1116. log.Error("GetJob(%s) failed:%v", task.JobName, err)
  1117. updateDefaultDuration(task)
  1118. continue
  1119. }
  1120. if result != nil {
  1121. if result.Msg != "success" {
  1122. updateDefaultDuration(task)
  1123. continue
  1124. }
  1125. jobRes, err := models.ConvertToJobResultPayload(result.Payload)
  1126. if err != nil || len(jobRes.TaskRoles) == 0 {
  1127. updateDefaultDuration(task)
  1128. continue
  1129. }
  1130. taskRoles := jobRes.TaskRoles
  1131. taskRes, err := models.ConvertToTaskPod(taskRoles[cloudbrain.SubTaskName].(map[string]interface{}))
  1132. if err != nil || len(taskRes.TaskStatuses) == 0 {
  1133. updateDefaultDuration(task)
  1134. continue
  1135. }
  1136. task.Status = taskRes.TaskStatuses[0].State
  1137. startTime := taskRes.TaskStatuses[0].StartAt.Unix()
  1138. endTime := taskRes.TaskStatuses[0].FinishedAt.Unix()
  1139. log.Info("task startTime = %v endTime= %v ,jobId=%d", startTime, endTime, task.ID)
  1140. if startTime > 0 {
  1141. task.StartTime = timeutil.TimeStamp(startTime)
  1142. } else {
  1143. task.StartTime = task.CreatedUnix
  1144. }
  1145. if endTime > 0 {
  1146. task.EndTime = timeutil.TimeStamp(endTime)
  1147. } else {
  1148. task.EndTime = task.UpdatedUnix
  1149. }
  1150. if task.EndTime < task.StartTime {
  1151. log.Info("endTime[%v] is less than starTime[%v],jobId=%d", task.EndTime, task.StartTime, task.ID)
  1152. st := task.StartTime
  1153. task.StartTime = task.EndTime
  1154. task.EndTime = st
  1155. }
  1156. task.ComputeAndSetDuration()
  1157. err = models.UpdateJob(task)
  1158. if err != nil {
  1159. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1160. }
  1161. }
  1162. } else if task.Type == models.TypeCloudBrainTwo {
  1163. if task.JobType == string(models.JobTypeDebug) {
  1164. //result, err := modelarts.GetJob(task.JobID)
  1165. result, err := modelarts.GetNotebook2(task.JobID)
  1166. if err != nil {
  1167. log.Error("GetJob(%s) failed:%v", task.JobName, err)
  1168. task.StartTime = task.CreatedUnix
  1169. task.EndTime = task.UpdatedUnix
  1170. task.ComputeAndSetDuration()
  1171. err = models.UpdateJob(task)
  1172. if err != nil {
  1173. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1174. }
  1175. continue
  1176. }
  1177. if result != nil {
  1178. task.Status = result.Status
  1179. startTime := result.Lease.CreateTime
  1180. duration := result.Lease.Duration / 1000
  1181. if startTime > 0 {
  1182. task.StartTime = timeutil.TimeStamp(startTime)
  1183. task.EndTime = task.StartTime.Add(duration)
  1184. }
  1185. task.ComputeAndSetDuration()
  1186. err = models.UpdateJob(task)
  1187. if err != nil {
  1188. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1189. continue
  1190. }
  1191. }
  1192. } else if task.JobType == string(models.JobTypeTrain) {
  1193. result, err := modelarts.GetTrainJob(task.JobID, strconv.FormatInt(task.VersionID, 10))
  1194. if err != nil {
  1195. log.Error("GetTrainJob(%s) failed:%v", task.JobName, err)
  1196. continue
  1197. }
  1198. if result != nil {
  1199. startTime := result.StartTime / 1000
  1200. if startTime > 0 {
  1201. task.StartTime = timeutil.TimeStamp(startTime)
  1202. task.EndTime = task.StartTime.Add(result.Duration / 1000)
  1203. }
  1204. task.ComputeAndSetDuration()
  1205. err = models.UpdateJob(task)
  1206. if err != nil {
  1207. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1208. continue
  1209. }
  1210. }
  1211. } else {
  1212. log.Error("task.JobType(%s) is error:%s", task.JobName, task.JobType)
  1213. }
  1214. } else {
  1215. log.Error("task.Type(%s) is error:%d", task.JobName, task.Type)
  1216. }
  1217. }
  1218. }
  1219. func updateDefaultDuration(task *models.Cloudbrain) {
  1220. log.Info("updateDefaultDuration: taskId=%d", task.ID)
  1221. task.StartTime = task.CreatedUnix
  1222. task.EndTime = task.UpdatedUnix
  1223. task.ComputeAndSetDuration()
  1224. err := models.UpdateJob(task)
  1225. if err != nil {
  1226. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1227. }
  1228. }
  1229. func CloudBrainBenchmarkIndex(ctx *context.Context) {
  1230. MustEnableCloudbrain(ctx)
  1231. repo := ctx.Repo.Repository
  1232. page := ctx.QueryInt("page")
  1233. if page <= 0 {
  1234. page = 1
  1235. }
  1236. var jobTypes []string
  1237. jobTypes = append(jobTypes, string(models.JobTypeBenchmark))
  1238. ciTasks, count, err := models.Cloudbrains(&models.CloudbrainsOptions{
  1239. ListOptions: models.ListOptions{
  1240. Page: page,
  1241. PageSize: setting.UI.IssuePagingNum,
  1242. },
  1243. RepoID: repo.ID,
  1244. Type: models.TypeCloudBrainOne,
  1245. JobTypes: jobTypes,
  1246. })
  1247. if err != nil {
  1248. ctx.ServerError("Get debugjob faild:", err)
  1249. return
  1250. }
  1251. for i, task := range ciTasks {
  1252. ciTasks[i].CanDel = cloudbrain.CanDeleteJob(ctx, &task.Cloudbrain)
  1253. ciTasks[i].Cloudbrain.ComputeResource = task.ComputeResource
  1254. if ciTasks[i].TrainJobDuration == "" {
  1255. if ciTasks[i].Duration == 0 {
  1256. var duration int64
  1257. if task.Status == string(models.JobRunning) {
  1258. duration = time.Now().Unix() - int64(task.Cloudbrain.CreatedUnix)
  1259. } else {
  1260. duration = int64(task.Cloudbrain.UpdatedUnix) - int64(task.Cloudbrain.CreatedUnix)
  1261. }
  1262. ciTasks[i].Duration = duration
  1263. }
  1264. ciTasks[i].TrainJobDuration = models.ConvertDurationToStr(ciTasks[i].Duration)
  1265. }
  1266. ciTasks[i].BenchmarkTypeName = ""
  1267. if task.BenchmarkTypeID > 0 {
  1268. for _, benchmarkType := range GetBenchmarkTypes(ctx).BenchmarkType {
  1269. if task.BenchmarkTypeID == benchmarkType.Id {
  1270. ciTasks[i].BenchmarkTypeRankLink = benchmarkType.RankLink
  1271. ciTasks[i].BenchmarkTypeName = benchmarkType.First
  1272. break
  1273. }
  1274. }
  1275. }
  1276. }
  1277. pager := context.NewPagination(int(count), setting.UI.IssuePagingNum, page, 5)
  1278. ctx.Data["Page"] = pager
  1279. ctx.Data["PageIsCloudBrain"] = true
  1280. ctx.Data["Tasks"] = ciTasks
  1281. ctx.Data["CanCreate"] = cloudbrain.CanCreateOrDebugJob(ctx)
  1282. ctx.Data["RepoIsEmpty"] = repo.IsEmpty
  1283. ctx.HTML(200, tplCloudBrainBenchmarkIndex)
  1284. }
  1285. func GetChildTypes(ctx *context.Context) {
  1286. benchmarkTypeID := ctx.QueryInt("benchmark_type_id")
  1287. re := make(map[string]interface{})
  1288. for {
  1289. var isExist bool
  1290. for _, benchmarkType := range GetBenchmarkTypes(ctx).BenchmarkType {
  1291. if benchmarkTypeID == benchmarkType.Id {
  1292. isExist = true
  1293. re["child_types"] = benchmarkType.Second
  1294. re["result_code"] = "0"
  1295. break
  1296. }
  1297. }
  1298. if !isExist {
  1299. re["result_code"] = "1"
  1300. log.Error("no such benchmark_type_id", ctx.Data["MsgID"])
  1301. re["errMsg"] = "system error"
  1302. break
  1303. }
  1304. break
  1305. }
  1306. ctx.JSON(200, re)
  1307. }
  1308. func CloudBrainBenchmarkNew(ctx *context.Context) {
  1309. ctx.Data["description"] = ""
  1310. ctx.Data["benchmarkTypeID"] = -1
  1311. ctx.Data["benchmark_child_types_id_hidden"] = -1
  1312. err := cloudBrainNewDataPrepare(ctx)
  1313. if err != nil {
  1314. ctx.ServerError("get new cloudbrain info failed", err)
  1315. return
  1316. }
  1317. ctx.HTML(200, tplCloudBrainBenchmarkNew)
  1318. }
  1319. func getBenchmarkAttachment(benchmarkTypeID, benchmarkChildTypeID int, ctx *context.Context) (*models.BenchmarkDataset, error) {
  1320. var childInfo *models.BenchmarkDataset
  1321. var isExist bool
  1322. for _, benchmarkType := range GetBenchmarkTypes(ctx).BenchmarkType {
  1323. if benchmarkType.Id == benchmarkTypeID {
  1324. for _, childType := range benchmarkType.Second {
  1325. if childType.Id == benchmarkChildTypeID {
  1326. childInfo = childType
  1327. isExist = true
  1328. break
  1329. }
  1330. }
  1331. break
  1332. }
  1333. }
  1334. if !isExist {
  1335. log.Error("no such benchmark_type_id&benchmark_child_type_id")
  1336. return childInfo, errors.New("no such benchmark_type_id&benchmark_child_type_id")
  1337. }
  1338. return childInfo, nil
  1339. }
  1340. func getBenchmarkGpuQueue(gpuQueue string) (string, error) {
  1341. queue := ""
  1342. if benchmarkGpuInfos == nil {
  1343. if err := json.Unmarshal([]byte(setting.BenchmarkGpuTypes), &benchmarkGpuInfos); err != nil {
  1344. log.Error("json.Unmarshal BenchmarkGpuTypes(%s) failed:%v", setting.BenchmarkGpuTypes, err)
  1345. return queue, err
  1346. }
  1347. }
  1348. var isExist bool
  1349. for _, gpuInfo := range benchmarkGpuInfos.GpuInfo {
  1350. if gpuQueue == gpuInfo.Queue {
  1351. isExist = true
  1352. queue = gpuQueue
  1353. break
  1354. }
  1355. }
  1356. if !isExist {
  1357. log.Error("no such gpuQueue, %s", gpuQueue)
  1358. return queue, errors.New("no such gpuQueue")
  1359. }
  1360. return queue, nil
  1361. }
  1362. func getBenchmarkResourceSpec(resourceSpecID int) (int, error) {
  1363. var id int
  1364. if benchmarkResourceSpecs == nil {
  1365. if err := json.Unmarshal([]byte(setting.BenchmarkResourceSpecs), &benchmarkResourceSpecs); err != nil {
  1366. log.Error("json.Unmarshal BenchmarkResourceSpecs(%s) failed:%v", setting.BenchmarkResourceSpecs, err)
  1367. return id, err
  1368. }
  1369. }
  1370. var isExist bool
  1371. for _, resourceSpec := range benchmarkResourceSpecs.ResourceSpec {
  1372. if resourceSpecID == resourceSpec.Id {
  1373. isExist = true
  1374. id = resourceSpecID
  1375. break
  1376. }
  1377. }
  1378. if !isExist {
  1379. log.Error("no such resourceSpecID, %d", resourceSpecID)
  1380. return id, errors.New("no such resourceSpec")
  1381. }
  1382. return id, nil
  1383. }
  1384. func CloudBrainBenchmarkCreate(ctx *context.Context, form auth.CreateCloudBrainForm) {
  1385. ctx.Data["PageIsCloudBrain"] = true
  1386. displayJobName := form.DisplayJobName
  1387. jobName := util.ConvertDisplayJobNameToJobName(displayJobName)
  1388. image := form.Image
  1389. gpuQueue := form.GpuType
  1390. command := cloudbrain.CommandBenchmark
  1391. codePath := setting.JobPath + jobName + cloudbrain.CodeMountPath
  1392. resourceSpecId := cloudbrain.BenchMarkResourceID
  1393. benchmarkTypeID := form.BenchmarkTypeID
  1394. benchmarkChildTypeID := form.BenchmarkChildTypeID
  1395. ctx.Data["description"] = form.Description
  1396. ctx.Data["benchmarkTypeID"] = benchmarkTypeID
  1397. ctx.Data["benchmark_child_types_id_hidden"] = benchmarkChildTypeID
  1398. repo := ctx.Repo.Repository
  1399. tasks, err := models.GetCloudbrainsByDisplayJobName(repo.ID, string(models.JobTypeBenchmark), displayJobName)
  1400. if err == nil {
  1401. if len(tasks) != 0 {
  1402. log.Error("the job name did already exist", ctx.Data["MsgID"])
  1403. cloudBrainNewDataPrepare(ctx)
  1404. ctx.RenderWithErr("the job name did already exist", tplCloudBrainBenchmarkNew, &form)
  1405. return
  1406. }
  1407. } else {
  1408. if !models.IsErrJobNotExist(err) {
  1409. log.Error("system error, %v", err, ctx.Data["MsgID"])
  1410. cloudBrainNewDataPrepare(ctx)
  1411. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  1412. return
  1413. }
  1414. }
  1415. if !jobNamePattern.MatchString(jobName) {
  1416. cloudBrainNewDataPrepare(ctx)
  1417. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_jobname_err"), tplCloudBrainBenchmarkNew, &form)
  1418. return
  1419. }
  1420. childInfo, err := getBenchmarkAttachment(benchmarkTypeID, benchmarkChildTypeID, ctx)
  1421. if err != nil {
  1422. log.Error("getBenchmarkAttachment failed:%v", err, ctx.Data["MsgID"])
  1423. cloudBrainNewDataPrepare(ctx)
  1424. ctx.RenderWithErr("benchmark type error", tplCloudBrainBenchmarkNew, &form)
  1425. return
  1426. }
  1427. _, err = getBenchmarkGpuQueue(gpuQueue)
  1428. if err != nil {
  1429. log.Error("getBenchmarkGpuQueue failed:%v", err, ctx.Data["MsgID"])
  1430. cloudBrainNewDataPrepare(ctx)
  1431. ctx.RenderWithErr("gpu queue error", tplCloudBrainBenchmarkNew, &form)
  1432. return
  1433. }
  1434. _, err = getBenchmarkResourceSpec(resourceSpecId)
  1435. if err != nil {
  1436. log.Error("getBenchmarkResourceSpec failed:%v", err, ctx.Data["MsgID"])
  1437. cloudBrainNewDataPrepare(ctx)
  1438. ctx.RenderWithErr("resource spec error", tplCloudBrainBenchmarkNew, &form)
  1439. return
  1440. }
  1441. count, err := models.GetCloudbrainCountByUserID(ctx.User.ID, string(models.JobTypeBenchmark))
  1442. if err != nil {
  1443. log.Error("GetCloudbrainCountByUserID failed:%v", err, ctx.Data["MsgID"])
  1444. cloudBrainNewDataPrepare(ctx)
  1445. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  1446. return
  1447. } else {
  1448. if count >= 1 {
  1449. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  1450. cloudBrainNewDataPrepare(ctx)
  1451. ctx.RenderWithErr("you have already a running or waiting task, can not create more", tplCloudBrainBenchmarkNew, &form)
  1452. return
  1453. }
  1454. }
  1455. os.RemoveAll(codePath)
  1456. if err := downloadCode(repo, codePath); err != nil {
  1457. log.Error("downloadCode failed, %v", err, ctx.Data["MsgID"])
  1458. cloudBrainNewDataPrepare(ctx)
  1459. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  1460. return
  1461. }
  1462. if _, err := os.Stat(codePath + "/train.py"); err != nil {
  1463. if os.IsNotExist(err) {
  1464. // file does not exist
  1465. log.Error("train.py does not exist, %v", err, ctx.Data["MsgID"])
  1466. cloudBrainNewDataPrepare(ctx)
  1467. ctx.RenderWithErr("train.py does not exist", tplCloudBrainBenchmarkNew, &form)
  1468. } else {
  1469. log.Error("Stat failed, %v", err, ctx.Data["MsgID"])
  1470. cloudBrainNewDataPrepare(ctx)
  1471. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  1472. }
  1473. return
  1474. } else if _, err := os.Stat(codePath + "/test.py"); err != nil {
  1475. if os.IsNotExist(err) {
  1476. // file does not exist
  1477. log.Error("test.py does not exist, %v", err, ctx.Data["MsgID"])
  1478. cloudBrainNewDataPrepare(ctx)
  1479. ctx.RenderWithErr("test.py does not exist", tplCloudBrainBenchmarkNew, &form)
  1480. } else {
  1481. log.Error("Stat failed, %v", err, ctx.Data["MsgID"])
  1482. cloudBrainNewDataPrepare(ctx)
  1483. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  1484. }
  1485. return
  1486. }
  1487. if err := uploadCodeToMinio(codePath+"/", jobName, cloudbrain.CodeMountPath+"/"); err != nil {
  1488. log.Error("uploadCodeToMinio failed, %v", err, ctx.Data["MsgID"])
  1489. cloudBrainNewDataPrepare(ctx)
  1490. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  1491. return
  1492. }
  1493. benchmarkPath := setting.JobPath + jobName + cloudbrain.BenchMarkMountPath
  1494. var gpuType string
  1495. for _, gpuInfo := range gpuInfos.GpuInfo {
  1496. if gpuInfo.Queue == gpuQueue {
  1497. gpuType = gpuInfo.Value
  1498. }
  1499. }
  1500. if err := downloadRateCode(repo, jobName, childInfo.Owner, childInfo.RepoName, benchmarkPath, form.BenchmarkCategory, gpuType); err != nil {
  1501. log.Error("downloadRateCode failed, %v", err, ctx.Data["MsgID"])
  1502. //cloudBrainNewDataPrepare(ctx)
  1503. //ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  1504. //return
  1505. }
  1506. if err := uploadCodeToMinio(benchmarkPath+"/", jobName, cloudbrain.BenchMarkMountPath+"/"); err != nil {
  1507. log.Error("uploadCodeToMinio failed, %v", err, ctx.Data["MsgID"])
  1508. //cloudBrainNewDataPrepare(ctx)
  1509. //ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  1510. //return
  1511. }
  1512. err = cloudbrain.GenerateTask(ctx, displayJobName, jobName, image, command, childInfo.Attachment, storage.GetMinioPath(jobName, cloudbrain.CodeMountPath+"/"),
  1513. storage.GetMinioPath(jobName, cloudbrain.ModelMountPath+"/"),
  1514. storage.GetMinioPath(jobName, cloudbrain.BenchMarkMountPath+"/"), storage.GetMinioPath(jobName, cloudbrain.Snn4imagenetMountPath+"/"),
  1515. storage.GetMinioPath(jobName, cloudbrain.BrainScoreMountPath+"/"), string(models.JobTypeBenchmark), gpuQueue, form.Description,
  1516. benchmarkTypeID, benchmarkChildTypeID, resourceSpecId)
  1517. if err != nil {
  1518. cloudBrainNewDataPrepare(ctx)
  1519. ctx.RenderWithErr(err.Error(), tplCloudBrainBenchmarkNew, &form)
  1520. return
  1521. }
  1522. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/cloudbrain/benchmark")
  1523. }
  1524. func BenchmarkDel(ctx *context.Context) {
  1525. if err := deleteCloudbrainJob(ctx); err != nil {
  1526. log.Error("deleteCloudbrainJob failed: %v", err, ctx.Data["msgID"])
  1527. ctx.ServerError(err.Error(), err)
  1528. return
  1529. }
  1530. var isAdminPage = ctx.Query("isadminpage")
  1531. if ctx.IsUserSiteAdmin() && isAdminPage == "true" {
  1532. ctx.Redirect(setting.AppSubURL + "/admin" + "/cloudbrains")
  1533. } else {
  1534. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/cloudbrain/benchmark")
  1535. }
  1536. }
  1537. func GetBenchmarkTypes(ctx *context.Context) *models.BenchmarkTypes {
  1538. var lang = ctx.Locale.Language()
  1539. if benchmarkTypesMap[lang] == nil {
  1540. var val = i18n.Tr(lang, BENCHMARK_TYPE_CODE)
  1541. var tempType *models.BenchmarkTypes
  1542. if err := json.Unmarshal([]byte(val), &tempType); err != nil {
  1543. log.Error("json.Unmarshal BenchmarkTypes(%s) failed:%v", val, err, ctx.Data["MsgID"])
  1544. return &models.BenchmarkTypes{}
  1545. }
  1546. benchmarkTypesMap[lang] = tempType
  1547. }
  1548. return benchmarkTypesMap[lang]
  1549. }