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
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
4 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
4 years ago
4 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
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
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
3 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
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
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
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
4 years ago
3 years ago
3 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
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 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
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
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
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
3 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
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
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
4 years ago
4 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
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
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772
  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. image, err := models.GetImageByID(id)
  407. if err != nil {
  408. log.Error("GetImageByID failed:%v", err.Error())
  409. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  410. }
  411. ctx.Data["Image"] = image
  412. ctx.HTML(http.StatusOK, tplCloudBrainImageEdit)
  413. }
  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, 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.SanitizeAndValidateTopics(topics)
  504. if len(validTopics) > 25 {
  505. return nil, "repo.topic.count_prompt"
  506. }
  507. if len(invalidTopics) > 0 {
  508. return nil, "repo.topic.count_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. opts := models.SearchImageOptions{
  695. IncludePrivateOnly: true,
  696. UID: -1,
  697. Keyword: ctx.Query("q"),
  698. Topics: ctx.Query("topic"),
  699. IncludeOfficialOnly: ctx.QueryBool("recommend"),
  700. SearchOrderBy: "type desc, num_stars desc",
  701. }
  702. getImages(ctx, &opts)
  703. }
  704. func GetCustomImages(ctx *context.Context) {
  705. var uid int64 = -1
  706. if ctx.IsSigned {
  707. uid = ctx.User.ID
  708. }
  709. opts := models.SearchImageOptions{
  710. UID: uid,
  711. IncludeOwnerOnly: true,
  712. Keyword: ctx.Query("q"),
  713. Topics: ctx.Query("topic"),
  714. SearchOrderBy: "id desc",
  715. }
  716. getImages(ctx, &opts)
  717. }
  718. func GetStarImages(ctx *context.Context) {
  719. var uid int64 = -1
  720. if ctx.IsSigned {
  721. uid = ctx.User.ID
  722. }
  723. opts := models.SearchImageOptions{
  724. UID: uid,
  725. IncludeStarByMe: true,
  726. Keyword: ctx.Query("q"),
  727. Topics: ctx.Query("topic"),
  728. SearchOrderBy: "id desc",
  729. }
  730. getImages(ctx, &opts)
  731. }
  732. func GetAllImages(ctx *context.Context) {
  733. opts := models.SearchImageOptions{
  734. UID: -1,
  735. Keyword: ctx.Query("q"),
  736. Topics: ctx.Query("topic"),
  737. SearchOrderBy: "id desc",
  738. }
  739. if ctx.Query("private") != "" {
  740. if ctx.QueryBool("private") {
  741. opts.IncludePrivateOnly = true
  742. } else {
  743. opts.IncludePublicOnly = true
  744. }
  745. }
  746. getImages(ctx, &opts)
  747. }
  748. func getImages(ctx *context.Context, opts *models.SearchImageOptions) {
  749. page := ctx.QueryInt("page")
  750. if page <= 0 {
  751. page = 1
  752. }
  753. pageSize := ctx.QueryInt("pageSize")
  754. if pageSize <= 0 {
  755. pageSize = 15
  756. }
  757. opts.ListOptions = models.ListOptions{
  758. Page: page,
  759. PageSize: pageSize,
  760. }
  761. imageList, total, err := models.SearchImage(opts)
  762. if err != nil {
  763. log.Error("Can not get images:%v", err)
  764. ctx.JSON(http.StatusOK, models.ImagesPageResult{
  765. Count: 0,
  766. Images: []*models.Image{},
  767. })
  768. } else {
  769. ctx.JSON(http.StatusOK, models.ImagesPageResult{
  770. Count: total,
  771. Images: imageList,
  772. })
  773. }
  774. }
  775. func GetModelDirs(jobName string, parentDir string) (string, error) {
  776. var req string
  777. modelActualPath := storage.GetMinioPath(jobName, cloudbrain.ModelMountPath+"/")
  778. if parentDir == "" {
  779. req = "baseDir=" + modelActualPath
  780. } else {
  781. req = "baseDir=" + modelActualPath + "&parentDir=" + parentDir
  782. }
  783. return getDirs(req)
  784. }
  785. func CloudBrainDownloadModel(ctx *context.Context) {
  786. parentDir := ctx.Query("parentDir")
  787. fileName := ctx.Query("fileName")
  788. jobName := ctx.Query("jobName")
  789. filePath := "jobs/" + jobName + "/model/" + parentDir
  790. url, err := storage.Attachments.PresignedGetURL(filePath, fileName)
  791. if err != nil {
  792. log.Error("PresignedGetURL failed: %v", err.Error(), ctx.Data["msgID"])
  793. ctx.ServerError("PresignedGetURL", err)
  794. return
  795. }
  796. http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusMovedPermanently)
  797. }
  798. func GetRate(ctx *context.Context) {
  799. isObjectDetcionAll := ctx.QueryBool("isObjectDetcionAll")
  800. if isObjectDetcionAll {
  801. ctx.Redirect(setting.BenchmarkServerHost + "?username=admin")
  802. return
  803. }
  804. var ID = ctx.Params(":id")
  805. job, err := models.GetCloudbrainByID(ID)
  806. if err != nil {
  807. ctx.ServerError("GetCloudbrainByJobID failed", err)
  808. return
  809. }
  810. if job.JobType == string(models.JobTypeBenchmark) {
  811. log.Info("url=" + setting.BenchmarkServerHost + "?username=" + ctx.User.Name)
  812. ctx.Redirect(setting.BenchmarkServerHost + "?username=" + ctx.User.Name)
  813. } else if job.JobType == string(models.JobTypeSnn4imagenet) {
  814. ctx.Redirect(setting.Snn4imagenetServerHost)
  815. } else if job.JobType == string(models.JobTypeBrainScore) {
  816. ctx.Redirect(setting.BrainScoreServerHost)
  817. } else {
  818. log.Error("JobType error:%s", job.JobType, ctx.Data["msgID"])
  819. }
  820. }
  821. func downloadCode(repo *models.Repository, codePath string) error {
  822. if err := git.Clone(repo.RepoPath(), codePath, git.CloneRepoOptions{}); err != nil {
  823. log.Error("Failed to clone repository: %s (%v)", repo.FullName(), err)
  824. return err
  825. }
  826. configFile, err := os.OpenFile(codePath+"/.git/config", os.O_RDWR, 0666)
  827. if err != nil {
  828. log.Error("open file(%s) failed:%v", codePath+"/,git/config", err)
  829. return err
  830. }
  831. defer configFile.Close()
  832. pos := int64(0)
  833. reader := bufio.NewReader(configFile)
  834. for {
  835. line, err := reader.ReadString('\n')
  836. if err != nil {
  837. if err == io.EOF {
  838. log.Error("not find the remote-url")
  839. return nil
  840. } else {
  841. log.Error("read error: %v", err)
  842. return err
  843. }
  844. }
  845. if strings.Contains(line, "url") && strings.Contains(line, ".git") {
  846. originUrl := "\turl = " + repo.CloneLink().HTTPS + "\n"
  847. if len(line) > len(originUrl) {
  848. originUrl += strings.Repeat(" ", len(line)-len(originUrl))
  849. }
  850. bytes := []byte(originUrl)
  851. _, err := configFile.WriteAt(bytes, pos)
  852. if err != nil {
  853. log.Error("WriteAt failed:%v", err)
  854. return err
  855. }
  856. break
  857. }
  858. pos += int64(len(line))
  859. }
  860. return nil
  861. }
  862. func downloadRateCode(repo *models.Repository, taskName, rateOwnerName, rateRepoName, codePath, benchmarkCategory, gpuType string) error {
  863. err := os.MkdirAll(codePath, os.ModePerm)
  864. if err != nil {
  865. log.Error("mkdir codePath failed", err.Error())
  866. return err
  867. }
  868. repoExt, err := models.GetRepositoryByOwnerAndName(rateOwnerName, rateRepoName)
  869. if err != nil {
  870. log.Error("GetRepositoryByOwnerAndName(%s) failed", rateRepoName, err.Error())
  871. return err
  872. }
  873. if err := git.Clone(repoExt.RepoPath(), codePath, git.CloneRepoOptions{}); err != nil {
  874. log.Error("Failed to clone repository: %s (%v)", repoExt.FullName(), err)
  875. return err
  876. }
  877. fileName := codePath + cloudbrain.TaskInfoName
  878. f, err := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.ModePerm)
  879. if err != nil {
  880. log.Error("OpenFile failed", err.Error())
  881. return err
  882. }
  883. defer f.Close()
  884. data, err := json.Marshal(models.TaskInfo{
  885. Username: repo.Owner.Name,
  886. TaskName: taskName,
  887. CodeName: repo.Name,
  888. BenchmarkCategory: strings.Split(benchmarkCategory, ","),
  889. CodeLink: strings.TrimSuffix(repo.CloneLink().HTTPS, ".git"),
  890. GpuType: gpuType,
  891. })
  892. if err != nil {
  893. log.Error("json.Marshal failed", err.Error())
  894. return err
  895. }
  896. _, err = f.Write(data)
  897. if err != nil {
  898. log.Error("WriteString failed", err.Error())
  899. return err
  900. }
  901. return nil
  902. }
  903. func uploadCodeToMinio(codePath, jobName, parentDir string) error {
  904. files, err := readDir(codePath)
  905. if err != nil {
  906. log.Error("readDir(%s) failed: %s", codePath, err.Error())
  907. return err
  908. }
  909. for _, file := range files {
  910. if file.IsDir() {
  911. if err = uploadCodeToMinio(codePath+file.Name()+"/", jobName, parentDir+file.Name()+"/"); err != nil {
  912. log.Error("uploadCodeToMinio(%s) failed: %s", file.Name(), err.Error())
  913. return err
  914. }
  915. } else {
  916. destObject := setting.CBCodePathPrefix + jobName + parentDir + file.Name()
  917. sourceFile := codePath + file.Name()
  918. err = storage.Attachments.UploadObject(destObject, sourceFile)
  919. if err != nil {
  920. log.Error("UploadObject(%s) failed: %s", file.Name(), err.Error())
  921. return err
  922. }
  923. }
  924. }
  925. return nil
  926. }
  927. func mkModelPath(modelPath string) error {
  928. err := os.MkdirAll(modelPath, os.ModePerm)
  929. if err != nil {
  930. log.Error("MkdirAll(%s) failed:%v", modelPath, err)
  931. return err
  932. }
  933. fileName := modelPath + "README"
  934. f, err := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.ModePerm)
  935. if err != nil {
  936. log.Error("OpenFile failed", err.Error())
  937. return err
  938. }
  939. defer f.Close()
  940. _, err = f.WriteString("You can put the model file into this directory and download it by the web page.")
  941. if err != nil {
  942. log.Error("WriteString failed", err.Error())
  943. return err
  944. }
  945. return nil
  946. }
  947. func deleteJobStorage(jobName string, cloudbrainType int) error {
  948. //delete local
  949. localJobPath := setting.JobPath + jobName
  950. err := os.RemoveAll(localJobPath)
  951. if err != nil {
  952. log.Error("RemoveAll(%s) failed:%v", localJobPath, err)
  953. }
  954. //delete oss
  955. if cloudbrainType == models.TypeCloudBrainOne {
  956. dirPath := setting.CBCodePathPrefix + jobName + "/"
  957. err = storage.Attachments.DeleteDir(dirPath)
  958. if err != nil {
  959. log.Error("DeleteDir(%s) failed:%v", localJobPath, err)
  960. }
  961. } else if cloudbrainType == models.TypeCloudBrainTwo {
  962. //dirPath := setting.CodePathPrefix + jobName + "/"
  963. //err = storage.ObsRemoveObject(setting.Bucket, dirPath)
  964. //if err != nil {
  965. // log.Error("ObsRemoveObject(%s) failed:%v", localJobPath, err)
  966. //}
  967. log.Info("no need to delete")
  968. } else {
  969. log.Error("cloudbrainType(%d) error", cloudbrainType)
  970. }
  971. return nil
  972. }
  973. func SyncCloudbrainStatus() {
  974. cloudBrains, err := models.GetCloudBrainUnStoppedJob()
  975. if err != nil {
  976. log.Error("GetCloudBrainUnStoppedJob failed:", err.Error())
  977. return
  978. }
  979. for _, task := range cloudBrains {
  980. if task.Type == models.TypeCloudBrainOne {
  981. result, err := cloudbrain.GetJob(task.JobID)
  982. if err != nil {
  983. log.Error("GetJob(%s) failed:%v", task.JobName, err)
  984. continue
  985. }
  986. if result != nil {
  987. jobRes, _ := models.ConvertToJobResultPayload(result.Payload)
  988. taskRoles := jobRes.TaskRoles
  989. taskRes, _ := models.ConvertToTaskPod(taskRoles[cloudbrain.SubTaskName].(map[string]interface{}))
  990. task.Status = taskRes.TaskStatuses[0].State
  991. if task.Status != string(models.JobWaiting) {
  992. task.Duration = time.Now().Unix() - taskRes.TaskStatuses[0].StartAt.Unix()
  993. if task.StartTime == 0 && !taskRes.TaskStatuses[0].StartAt.IsZero() {
  994. task.StartTime = timeutil.TimeStamp(taskRes.TaskStatuses[0].StartAt.Unix())
  995. }
  996. if task.EndTime == 0 && models.IsCloudBrainOneDebugJobTerminal(task.Status) {
  997. task.EndTime = timeutil.TimeStampNow()
  998. }
  999. task.ComputeAndSetDuration()
  1000. err = models.UpdateJob(task)
  1001. if err != nil {
  1002. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1003. }
  1004. var maxDuration int64
  1005. if task.JobType == string(models.JobTypeBenchmark) {
  1006. maxDuration = setting.BenchmarkMaxDuration
  1007. } else {
  1008. maxDuration = setting.MaxDuration
  1009. }
  1010. if task.Duration >= maxDuration {
  1011. log.Info("begin to stop job(%s), because of the duration", task.JobName)
  1012. err = cloudbrain.StopJob(task.JobID)
  1013. if err != nil {
  1014. log.Error("StopJob(%s) failed:%v", task.JobName, err)
  1015. continue
  1016. }
  1017. task.Status = string(models.JobStopped)
  1018. if task.EndTime == 0 {
  1019. task.EndTime = timeutil.TimeStampNow()
  1020. }
  1021. task.ComputeAndSetDuration()
  1022. err = models.UpdateJob(task)
  1023. if err != nil {
  1024. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1025. }
  1026. }
  1027. }
  1028. }
  1029. } else if task.Type == models.TypeCloudBrainTwo {
  1030. if task.JobType == string(models.JobTypeDebug) {
  1031. //result, err := modelarts.GetJob(task.JobID)
  1032. result, err := modelarts.GetNotebook2(task.JobID)
  1033. if err != nil {
  1034. log.Error("GetJob(%s) failed:%v", task.JobName, err)
  1035. continue
  1036. }
  1037. if result != nil {
  1038. task.Status = result.Status
  1039. if task.StartTime == 0 && result.Lease.CreateTime > 0 {
  1040. task.StartTime = timeutil.TimeStamp(result.Lease.CreateTime / 1000)
  1041. }
  1042. if task.EndTime == 0 && models.IsModelArtsDebugJobTerminal(task.Status) {
  1043. task.EndTime = timeutil.TimeStampNow()
  1044. }
  1045. task.ComputeAndSetDuration()
  1046. err = models.UpdateJob(task)
  1047. if err != nil {
  1048. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1049. continue
  1050. }
  1051. }
  1052. } else if task.JobType == string(models.JobTypeTrain) {
  1053. result, err := modelarts.GetTrainJob(task.JobID, strconv.FormatInt(task.VersionID, 10))
  1054. if err != nil {
  1055. log.Error("GetTrainJob(%s) failed:%v", task.JobName, err)
  1056. continue
  1057. }
  1058. if result != nil {
  1059. task.Status = modelarts.TransTrainJobStatus(result.IntStatus)
  1060. task.Duration = result.Duration / 1000
  1061. task.TrainJobDuration = result.TrainJobDuration
  1062. if task.StartTime == 0 && result.StartTime > 0 {
  1063. task.StartTime = timeutil.TimeStamp(result.StartTime / 1000)
  1064. }
  1065. task.TrainJobDuration = models.ConvertDurationToStr(task.Duration)
  1066. if task.EndTime == 0 && models.IsTrainJobTerminal(task.Status) && task.StartTime > 0 {
  1067. task.EndTime = task.StartTime.Add(task.Duration)
  1068. }
  1069. err = models.UpdateJob(task)
  1070. if err != nil {
  1071. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1072. continue
  1073. }
  1074. }
  1075. } else {
  1076. log.Error("task.JobType(%s) is error:%s", task.JobName, task.JobType)
  1077. }
  1078. } else {
  1079. log.Error("task.Type(%s) is error:%d", task.JobName, task.Type)
  1080. }
  1081. }
  1082. return
  1083. }
  1084. func HandleTaskWithNoDuration(ctx *context.Context) {
  1085. log.Info("HandleTaskWithNoDuration start")
  1086. count := 0
  1087. for {
  1088. cloudBrains, err := models.GetStoppedJobWithNoDurationJob()
  1089. if err != nil {
  1090. log.Error("HandleTaskWithNoTrainJobDuration failed:", err.Error())
  1091. break
  1092. }
  1093. if len(cloudBrains) == 0 {
  1094. log.Info("HandleTaskWithNoTrainJobDuration:no task need handle")
  1095. break
  1096. }
  1097. handleNoDurationTask(cloudBrains)
  1098. count += len(cloudBrains)
  1099. if len(cloudBrains) < 100 {
  1100. log.Info("HandleTaskWithNoTrainJobDuration:task less than 100")
  1101. break
  1102. }
  1103. }
  1104. log.Info("HandleTaskWithNoTrainJobDuration:count=%d", count)
  1105. ctx.JSON(200, "success")
  1106. }
  1107. func handleNoDurationTask(cloudBrains []*models.Cloudbrain) {
  1108. for _, task := range cloudBrains {
  1109. log.Info("Handle job ,%+v", task)
  1110. if task.Type == models.TypeCloudBrainOne {
  1111. result, err := cloudbrain.GetJob(task.JobID)
  1112. if err != nil {
  1113. log.Error("GetJob(%s) failed:%v", task.JobName, err)
  1114. updateDefaultDuration(task)
  1115. continue
  1116. }
  1117. if result != nil {
  1118. if result.Msg != "success" {
  1119. updateDefaultDuration(task)
  1120. continue
  1121. }
  1122. jobRes, err := models.ConvertToJobResultPayload(result.Payload)
  1123. if err != nil || len(jobRes.TaskRoles) == 0 {
  1124. updateDefaultDuration(task)
  1125. continue
  1126. }
  1127. taskRoles := jobRes.TaskRoles
  1128. taskRes, err := models.ConvertToTaskPod(taskRoles[cloudbrain.SubTaskName].(map[string]interface{}))
  1129. if err != nil || len(taskRes.TaskStatuses) == 0 {
  1130. updateDefaultDuration(task)
  1131. continue
  1132. }
  1133. task.Status = taskRes.TaskStatuses[0].State
  1134. startTime := taskRes.TaskStatuses[0].StartAt.Unix()
  1135. endTime := taskRes.TaskStatuses[0].FinishedAt.Unix()
  1136. log.Info("task startTime = %v endTime= %v ,jobId=%d", startTime, endTime, task.ID)
  1137. if startTime > 0 {
  1138. task.StartTime = timeutil.TimeStamp(startTime)
  1139. } else {
  1140. task.StartTime = task.CreatedUnix
  1141. }
  1142. if endTime > 0 {
  1143. task.EndTime = timeutil.TimeStamp(endTime)
  1144. } else {
  1145. task.EndTime = task.UpdatedUnix
  1146. }
  1147. if task.EndTime < task.StartTime {
  1148. log.Info("endTime[%v] is less than starTime[%v],jobId=%d", task.EndTime, task.StartTime, task.ID)
  1149. st := task.StartTime
  1150. task.StartTime = task.EndTime
  1151. task.EndTime = st
  1152. }
  1153. task.ComputeAndSetDuration()
  1154. err = models.UpdateJob(task)
  1155. if err != nil {
  1156. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1157. }
  1158. }
  1159. } else if task.Type == models.TypeCloudBrainTwo {
  1160. if task.JobType == string(models.JobTypeDebug) {
  1161. //result, err := modelarts.GetJob(task.JobID)
  1162. result, err := modelarts.GetNotebook2(task.JobID)
  1163. if err != nil {
  1164. log.Error("GetJob(%s) failed:%v", task.JobName, err)
  1165. task.StartTime = task.CreatedUnix
  1166. task.EndTime = task.UpdatedUnix
  1167. task.ComputeAndSetDuration()
  1168. err = models.UpdateJob(task)
  1169. if err != nil {
  1170. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1171. }
  1172. continue
  1173. }
  1174. if result != nil {
  1175. task.Status = result.Status
  1176. startTime := result.Lease.CreateTime
  1177. duration := result.Lease.Duration / 1000
  1178. if startTime > 0 {
  1179. task.StartTime = timeutil.TimeStamp(startTime)
  1180. task.EndTime = task.StartTime.Add(duration)
  1181. }
  1182. task.ComputeAndSetDuration()
  1183. err = models.UpdateJob(task)
  1184. if err != nil {
  1185. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1186. continue
  1187. }
  1188. }
  1189. } else if task.JobType == string(models.JobTypeTrain) {
  1190. result, err := modelarts.GetTrainJob(task.JobID, strconv.FormatInt(task.VersionID, 10))
  1191. if err != nil {
  1192. log.Error("GetTrainJob(%s) failed:%v", task.JobName, err)
  1193. continue
  1194. }
  1195. if result != nil {
  1196. startTime := result.StartTime / 1000
  1197. if startTime > 0 {
  1198. task.StartTime = timeutil.TimeStamp(startTime)
  1199. task.EndTime = task.StartTime.Add(result.Duration / 1000)
  1200. }
  1201. task.ComputeAndSetDuration()
  1202. err = models.UpdateJob(task)
  1203. if err != nil {
  1204. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1205. continue
  1206. }
  1207. }
  1208. } else {
  1209. log.Error("task.JobType(%s) is error:%s", task.JobName, task.JobType)
  1210. }
  1211. } else {
  1212. log.Error("task.Type(%s) is error:%d", task.JobName, task.Type)
  1213. }
  1214. }
  1215. }
  1216. func updateDefaultDuration(task *models.Cloudbrain) {
  1217. log.Info("updateDefaultDuration: taskId=%d", task.ID)
  1218. task.StartTime = task.CreatedUnix
  1219. task.EndTime = task.UpdatedUnix
  1220. task.ComputeAndSetDuration()
  1221. err := models.UpdateJob(task)
  1222. if err != nil {
  1223. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1224. }
  1225. }
  1226. func CloudBrainBenchmarkIndex(ctx *context.Context) {
  1227. MustEnableCloudbrain(ctx)
  1228. repo := ctx.Repo.Repository
  1229. page := ctx.QueryInt("page")
  1230. if page <= 0 {
  1231. page = 1
  1232. }
  1233. var jobTypes []string
  1234. jobTypes = append(jobTypes, string(models.JobTypeBenchmark))
  1235. ciTasks, count, err := models.Cloudbrains(&models.CloudbrainsOptions{
  1236. ListOptions: models.ListOptions{
  1237. Page: page,
  1238. PageSize: setting.UI.IssuePagingNum,
  1239. },
  1240. RepoID: repo.ID,
  1241. Type: models.TypeCloudBrainOne,
  1242. JobTypes: jobTypes,
  1243. })
  1244. if err != nil {
  1245. ctx.ServerError("Get debugjob faild:", err)
  1246. return
  1247. }
  1248. for i, task := range ciTasks {
  1249. ciTasks[i].CanDel = cloudbrain.CanDeleteJob(ctx, &task.Cloudbrain)
  1250. ciTasks[i].Cloudbrain.ComputeResource = task.ComputeResource
  1251. if ciTasks[i].TrainJobDuration == "" {
  1252. if ciTasks[i].Duration == 0 {
  1253. var duration int64
  1254. if task.Status == string(models.JobRunning) {
  1255. duration = time.Now().Unix() - int64(task.Cloudbrain.CreatedUnix)
  1256. } else {
  1257. duration = int64(task.Cloudbrain.UpdatedUnix) - int64(task.Cloudbrain.CreatedUnix)
  1258. }
  1259. ciTasks[i].Duration = duration
  1260. }
  1261. ciTasks[i].TrainJobDuration = models.ConvertDurationToStr(ciTasks[i].Duration)
  1262. }
  1263. ciTasks[i].BenchmarkTypeName = ""
  1264. if task.BenchmarkTypeID > 0 {
  1265. for _, benchmarkType := range GetBenchmarkTypes(ctx).BenchmarkType {
  1266. if task.BenchmarkTypeID == benchmarkType.Id {
  1267. ciTasks[i].BenchmarkTypeRankLink = benchmarkType.RankLink
  1268. ciTasks[i].BenchmarkTypeName = benchmarkType.First
  1269. break
  1270. }
  1271. }
  1272. }
  1273. }
  1274. pager := context.NewPagination(int(count), setting.UI.IssuePagingNum, page, 5)
  1275. ctx.Data["Page"] = pager
  1276. ctx.Data["PageIsCloudBrain"] = true
  1277. ctx.Data["Tasks"] = ciTasks
  1278. ctx.Data["CanCreate"] = cloudbrain.CanCreateOrDebugJob(ctx)
  1279. ctx.Data["RepoIsEmpty"] = repo.IsEmpty
  1280. ctx.HTML(200, tplCloudBrainBenchmarkIndex)
  1281. }
  1282. func GetChildTypes(ctx *context.Context) {
  1283. benchmarkTypeID := ctx.QueryInt("benchmark_type_id")
  1284. re := make(map[string]interface{})
  1285. for {
  1286. var isExist bool
  1287. for _, benchmarkType := range GetBenchmarkTypes(ctx).BenchmarkType {
  1288. if benchmarkTypeID == benchmarkType.Id {
  1289. isExist = true
  1290. re["child_types"] = benchmarkType.Second
  1291. re["result_code"] = "0"
  1292. break
  1293. }
  1294. }
  1295. if !isExist {
  1296. re["result_code"] = "1"
  1297. log.Error("no such benchmark_type_id", ctx.Data["MsgID"])
  1298. re["errMsg"] = "system error"
  1299. break
  1300. }
  1301. break
  1302. }
  1303. ctx.JSON(200, re)
  1304. }
  1305. func CloudBrainBenchmarkNew(ctx *context.Context) {
  1306. ctx.Data["description"] = ""
  1307. ctx.Data["benchmarkTypeID"] = -1
  1308. ctx.Data["benchmark_child_types_id_hidden"] = -1
  1309. err := cloudBrainNewDataPrepare(ctx)
  1310. if err != nil {
  1311. ctx.ServerError("get new cloudbrain info failed", err)
  1312. return
  1313. }
  1314. ctx.HTML(200, tplCloudBrainBenchmarkNew)
  1315. }
  1316. func getBenchmarkAttachment(benchmarkTypeID, benchmarkChildTypeID int, ctx *context.Context) (*models.BenchmarkDataset, error) {
  1317. var childInfo *models.BenchmarkDataset
  1318. var isExist bool
  1319. for _, benchmarkType := range GetBenchmarkTypes(ctx).BenchmarkType {
  1320. if benchmarkType.Id == benchmarkTypeID {
  1321. for _, childType := range benchmarkType.Second {
  1322. if childType.Id == benchmarkChildTypeID {
  1323. childInfo = childType
  1324. isExist = true
  1325. break
  1326. }
  1327. }
  1328. break
  1329. }
  1330. }
  1331. if !isExist {
  1332. log.Error("no such benchmark_type_id&benchmark_child_type_id")
  1333. return childInfo, errors.New("no such benchmark_type_id&benchmark_child_type_id")
  1334. }
  1335. return childInfo, nil
  1336. }
  1337. func getBenchmarkGpuQueue(gpuQueue string) (string, error) {
  1338. queue := ""
  1339. if benchmarkGpuInfos == nil {
  1340. if err := json.Unmarshal([]byte(setting.BenchmarkGpuTypes), &benchmarkGpuInfos); err != nil {
  1341. log.Error("json.Unmarshal BenchmarkGpuTypes(%s) failed:%v", setting.BenchmarkGpuTypes, err)
  1342. return queue, err
  1343. }
  1344. }
  1345. var isExist bool
  1346. for _, gpuInfo := range benchmarkGpuInfos.GpuInfo {
  1347. if gpuQueue == gpuInfo.Queue {
  1348. isExist = true
  1349. queue = gpuQueue
  1350. break
  1351. }
  1352. }
  1353. if !isExist {
  1354. log.Error("no such gpuQueue, %s", gpuQueue)
  1355. return queue, errors.New("no such gpuQueue")
  1356. }
  1357. return queue, nil
  1358. }
  1359. func getBenchmarkResourceSpec(resourceSpecID int) (int, error) {
  1360. var id int
  1361. if benchmarkResourceSpecs == nil {
  1362. if err := json.Unmarshal([]byte(setting.BenchmarkResourceSpecs), &benchmarkResourceSpecs); err != nil {
  1363. log.Error("json.Unmarshal BenchmarkResourceSpecs(%s) failed:%v", setting.BenchmarkResourceSpecs, err)
  1364. return id, err
  1365. }
  1366. }
  1367. var isExist bool
  1368. for _, resourceSpec := range benchmarkResourceSpecs.ResourceSpec {
  1369. if resourceSpecID == resourceSpec.Id {
  1370. isExist = true
  1371. id = resourceSpecID
  1372. break
  1373. }
  1374. }
  1375. if !isExist {
  1376. log.Error("no such resourceSpecID, %d", resourceSpecID)
  1377. return id, errors.New("no such resourceSpec")
  1378. }
  1379. return id, nil
  1380. }
  1381. func CloudBrainBenchmarkCreate(ctx *context.Context, form auth.CreateCloudBrainForm) {
  1382. ctx.Data["PageIsCloudBrain"] = true
  1383. displayJobName := form.DisplayJobName
  1384. jobName := util.ConvertDisplayJobNameToJobName(displayJobName)
  1385. image := form.Image
  1386. gpuQueue := form.GpuType
  1387. command := cloudbrain.CommandBenchmark
  1388. codePath := setting.JobPath + jobName + cloudbrain.CodeMountPath
  1389. resourceSpecId := cloudbrain.BenchMarkResourceID
  1390. benchmarkTypeID := form.BenchmarkTypeID
  1391. benchmarkChildTypeID := form.BenchmarkChildTypeID
  1392. ctx.Data["description"] = form.Description
  1393. ctx.Data["benchmarkTypeID"] = benchmarkTypeID
  1394. ctx.Data["benchmark_child_types_id_hidden"] = benchmarkChildTypeID
  1395. repo := ctx.Repo.Repository
  1396. tasks, err := models.GetCloudbrainsByDisplayJobName(repo.ID, string(models.JobTypeBenchmark), displayJobName)
  1397. if err == nil {
  1398. if len(tasks) != 0 {
  1399. log.Error("the job name did already exist", ctx.Data["MsgID"])
  1400. cloudBrainNewDataPrepare(ctx)
  1401. ctx.RenderWithErr("the job name did already exist", tplCloudBrainBenchmarkNew, &form)
  1402. return
  1403. }
  1404. } else {
  1405. if !models.IsErrJobNotExist(err) {
  1406. log.Error("system error, %v", err, ctx.Data["MsgID"])
  1407. cloudBrainNewDataPrepare(ctx)
  1408. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  1409. return
  1410. }
  1411. }
  1412. if !jobNamePattern.MatchString(jobName) {
  1413. cloudBrainNewDataPrepare(ctx)
  1414. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_jobname_err"), tplCloudBrainBenchmarkNew, &form)
  1415. return
  1416. }
  1417. childInfo, err := getBenchmarkAttachment(benchmarkTypeID, benchmarkChildTypeID, ctx)
  1418. if err != nil {
  1419. log.Error("getBenchmarkAttachment failed:%v", err, ctx.Data["MsgID"])
  1420. cloudBrainNewDataPrepare(ctx)
  1421. ctx.RenderWithErr("benchmark type error", tplCloudBrainBenchmarkNew, &form)
  1422. return
  1423. }
  1424. _, err = getBenchmarkGpuQueue(gpuQueue)
  1425. if err != nil {
  1426. log.Error("getBenchmarkGpuQueue failed:%v", err, ctx.Data["MsgID"])
  1427. cloudBrainNewDataPrepare(ctx)
  1428. ctx.RenderWithErr("gpu queue error", tplCloudBrainBenchmarkNew, &form)
  1429. return
  1430. }
  1431. _, err = getBenchmarkResourceSpec(resourceSpecId)
  1432. if err != nil {
  1433. log.Error("getBenchmarkResourceSpec failed:%v", err, ctx.Data["MsgID"])
  1434. cloudBrainNewDataPrepare(ctx)
  1435. ctx.RenderWithErr("resource spec error", tplCloudBrainBenchmarkNew, &form)
  1436. return
  1437. }
  1438. count, err := models.GetCloudbrainCountByUserID(ctx.User.ID, string(models.JobTypeBenchmark))
  1439. if err != nil {
  1440. log.Error("GetCloudbrainCountByUserID failed:%v", err, ctx.Data["MsgID"])
  1441. cloudBrainNewDataPrepare(ctx)
  1442. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  1443. return
  1444. } else {
  1445. if count >= 1 {
  1446. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  1447. cloudBrainNewDataPrepare(ctx)
  1448. ctx.RenderWithErr("you have already a running or waiting task, can not create more", tplCloudBrainBenchmarkNew, &form)
  1449. return
  1450. }
  1451. }
  1452. os.RemoveAll(codePath)
  1453. if err := downloadCode(repo, codePath); err != nil {
  1454. log.Error("downloadCode failed, %v", err, ctx.Data["MsgID"])
  1455. cloudBrainNewDataPrepare(ctx)
  1456. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  1457. return
  1458. }
  1459. if _, err := os.Stat(codePath + "/train.py"); err != nil {
  1460. if os.IsNotExist(err) {
  1461. // file does not exist
  1462. log.Error("train.py does not exist, %v", err, ctx.Data["MsgID"])
  1463. cloudBrainNewDataPrepare(ctx)
  1464. ctx.RenderWithErr("train.py does not exist", tplCloudBrainBenchmarkNew, &form)
  1465. } else {
  1466. log.Error("Stat failed, %v", err, ctx.Data["MsgID"])
  1467. cloudBrainNewDataPrepare(ctx)
  1468. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  1469. }
  1470. return
  1471. } else if _, err := os.Stat(codePath + "/test.py"); err != nil {
  1472. if os.IsNotExist(err) {
  1473. // file does not exist
  1474. log.Error("test.py does not exist, %v", err, ctx.Data["MsgID"])
  1475. cloudBrainNewDataPrepare(ctx)
  1476. ctx.RenderWithErr("test.py does not exist", tplCloudBrainBenchmarkNew, &form)
  1477. } else {
  1478. log.Error("Stat failed, %v", err, ctx.Data["MsgID"])
  1479. cloudBrainNewDataPrepare(ctx)
  1480. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  1481. }
  1482. return
  1483. }
  1484. if err := uploadCodeToMinio(codePath+"/", jobName, cloudbrain.CodeMountPath+"/"); err != nil {
  1485. log.Error("uploadCodeToMinio failed, %v", err, ctx.Data["MsgID"])
  1486. cloudBrainNewDataPrepare(ctx)
  1487. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  1488. return
  1489. }
  1490. benchmarkPath := setting.JobPath + jobName + cloudbrain.BenchMarkMountPath
  1491. var gpuType string
  1492. for _, gpuInfo := range gpuInfos.GpuInfo {
  1493. if gpuInfo.Queue == gpuQueue {
  1494. gpuType = gpuInfo.Value
  1495. }
  1496. }
  1497. if err := downloadRateCode(repo, jobName, childInfo.Owner, childInfo.RepoName, benchmarkPath, form.BenchmarkCategory, gpuType); err != nil {
  1498. log.Error("downloadRateCode failed, %v", err, ctx.Data["MsgID"])
  1499. //cloudBrainNewDataPrepare(ctx)
  1500. //ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  1501. //return
  1502. }
  1503. if err := uploadCodeToMinio(benchmarkPath+"/", jobName, cloudbrain.BenchMarkMountPath+"/"); err != nil {
  1504. log.Error("uploadCodeToMinio failed, %v", err, ctx.Data["MsgID"])
  1505. //cloudBrainNewDataPrepare(ctx)
  1506. //ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  1507. //return
  1508. }
  1509. err = cloudbrain.GenerateTask(ctx, displayJobName, jobName, image, command, childInfo.Attachment, storage.GetMinioPath(jobName, cloudbrain.CodeMountPath+"/"),
  1510. storage.GetMinioPath(jobName, cloudbrain.ModelMountPath+"/"),
  1511. storage.GetMinioPath(jobName, cloudbrain.BenchMarkMountPath+"/"), storage.GetMinioPath(jobName, cloudbrain.Snn4imagenetMountPath+"/"),
  1512. storage.GetMinioPath(jobName, cloudbrain.BrainScoreMountPath+"/"), string(models.JobTypeBenchmark), gpuQueue, form.Description,
  1513. benchmarkTypeID, benchmarkChildTypeID, resourceSpecId)
  1514. if err != nil {
  1515. cloudBrainNewDataPrepare(ctx)
  1516. ctx.RenderWithErr(err.Error(), tplCloudBrainBenchmarkNew, &form)
  1517. return
  1518. }
  1519. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/cloudbrain/benchmark")
  1520. }
  1521. func BenchmarkDel(ctx *context.Context) {
  1522. if err := deleteCloudbrainJob(ctx); err != nil {
  1523. log.Error("deleteCloudbrainJob failed: %v", err, ctx.Data["msgID"])
  1524. ctx.ServerError(err.Error(), err)
  1525. return
  1526. }
  1527. var isAdminPage = ctx.Query("isadminpage")
  1528. if ctx.IsUserSiteAdmin() && isAdminPage == "true" {
  1529. ctx.Redirect(setting.AppSubURL + "/admin" + "/cloudbrains")
  1530. } else {
  1531. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/cloudbrain/benchmark")
  1532. }
  1533. }
  1534. func GetBenchmarkTypes(ctx *context.Context) *models.BenchmarkTypes {
  1535. var lang = ctx.Locale.Language()
  1536. if benchmarkTypesMap[lang] == nil {
  1537. var val = i18n.Tr(lang, BENCHMARK_TYPE_CODE)
  1538. var tempType *models.BenchmarkTypes
  1539. if err := json.Unmarshal([]byte(val), &tempType); err != nil {
  1540. log.Error("json.Unmarshal BenchmarkTypes(%s) failed:%v", val, err, ctx.Data["MsgID"])
  1541. return &models.BenchmarkTypes{}
  1542. }
  1543. benchmarkTypesMap[lang] = tempType
  1544. }
  1545. return benchmarkTypesMap[lang]
  1546. }