You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

cloudbrain.go 93 kB

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