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