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

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