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