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

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