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

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