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