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