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

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