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

cloudbrain.go 94 kB

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