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

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