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