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