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

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