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

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