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

cloudbrain.go 96 kB

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