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 41 kB

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