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

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