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.

modelarts.go 97 kB

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
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
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
2 years ago
3 years ago
4 years ago
3 years ago
2 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
4 years ago
3 years ago
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
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
4 years ago
3 years ago
2 years ago
3 years ago
4 years ago
3 years ago
2 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
2 years ago
4 years ago
2 years ago
3 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
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
2 years ago
2 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
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
4 years ago
2 years ago
4 years ago
4 years ago
2 years ago
4 years ago
2 years ago
4 years ago
2 years ago
3 years ago
2 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
4 years ago
2 years ago
2 years ago
2 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
3 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
3 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
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
2 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
3 years ago
2 years ago
3 years ago
3 years ago
2 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
2 years ago
2 years ago
2 years ago
2 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
2 years ago
3 years ago
4 years ago
2 years ago
4 years ago
3 years ago
4 years ago
2 years ago
4 years ago
3 years ago
3 years ago
3 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
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
2 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
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
4 years ago
2 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
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
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
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
2 years ago
2 years ago
3 years ago
4 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
2 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
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
4 years ago
2 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
3 years ago
3 years ago
3 years ago
2 years ago
3 years ago
3 years ago
2 years ago
3 years ago
4 years ago
3 years ago
3 years ago
2 years ago
2 years ago
3 years ago
2 years ago
4 years ago
4 years ago
2 years ago
4 years ago
4 years ago
2 years ago
4 years ago
2 years ago
3 years ago
4 years ago
2 years ago
4 years ago
4 years ago
3 years ago
4 years ago
2 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
2 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
2 years ago
4 years ago
4 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
2 years ago
2 years ago
2 years ago
3 years ago
2 years ago
4 years ago
2 years ago
4 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
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
2 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
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
3 years ago
2 years ago
3 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
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
2 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
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
2 years ago
3 years ago
3 years ago
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
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
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
4 years ago
3 years ago
3 years ago
4 years ago
3 years ago
2 years ago
4 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
4 years ago
4 years ago
3 years ago
3 years ago
4 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
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
2 years ago
3 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
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
3 years ago
3 years ago
3 years ago
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
2 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
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
3 years ago
3 years ago
2 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
3 years ago
2 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
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
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996
  1. package repo
  2. import (
  3. "archive/zip"
  4. "code.gitea.io/gitea/services/lock"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "io"
  9. "io/ioutil"
  10. "net/http"
  11. "os"
  12. "path"
  13. "strconv"
  14. "strings"
  15. "time"
  16. "unicode/utf8"
  17. cloudbrainService "code.gitea.io/gitea/services/cloudbrain"
  18. "code.gitea.io/gitea/services/cloudbrain/cloudbrainTask"
  19. "code.gitea.io/gitea/modules/dataset"
  20. "code.gitea.io/gitea/modules/modelarts_cd"
  21. "code.gitea.io/gitea/services/cloudbrain/resource"
  22. "code.gitea.io/gitea/services/reward/point/account"
  23. "code.gitea.io/gitea/models"
  24. "code.gitea.io/gitea/modules/auth"
  25. "code.gitea.io/gitea/modules/base"
  26. "code.gitea.io/gitea/modules/cloudbrain"
  27. "code.gitea.io/gitea/modules/context"
  28. "code.gitea.io/gitea/modules/git"
  29. "code.gitea.io/gitea/modules/log"
  30. "code.gitea.io/gitea/modules/modelarts"
  31. "code.gitea.io/gitea/modules/notification"
  32. "code.gitea.io/gitea/modules/obs"
  33. "code.gitea.io/gitea/modules/setting"
  34. "code.gitea.io/gitea/modules/storage"
  35. "code.gitea.io/gitea/modules/timeutil"
  36. "code.gitea.io/gitea/modules/util"
  37. )
  38. const (
  39. tplDebugJobIndex base.TplName = "repo/debugjob/index"
  40. tplModelArtsNotebookIndex base.TplName = "repo/modelarts/notebook/index"
  41. tplModelArtsNotebookNew base.TplName = "repo/modelarts/notebook/new"
  42. tplModelArtsNotebookShow base.TplName = "repo/modelarts/notebook/show"
  43. tplModelArtsTrainJobIndex base.TplName = "repo/modelarts/trainjob/index"
  44. tplModelArtsTrainJobNew base.TplName = "repo/modelarts/trainjob/new"
  45. tplModelArtsTrainJobShow base.TplName = "repo/modelarts/trainjob/show"
  46. tplModelArtsTrainJobVersionNew base.TplName = "repo/modelarts/trainjob/version_new"
  47. tplModelArtsInferenceJobIndex base.TplName = "repo/modelarts/inferencejob/index"
  48. tplModelArtsInferenceJobNew base.TplName = "repo/modelarts/inferencejob/new"
  49. tplModelArtsInferenceJobShow base.TplName = "repo/modelarts/inferencejob/show"
  50. )
  51. func DebugJobIndex(ctx *context.Context) {
  52. listType := ctx.Query("debugListType")
  53. if listType == "" {
  54. listType = models.AllResource
  55. }
  56. ctx.Data["ListType"] = listType
  57. MustEnableCloudbrain(ctx)
  58. repo := ctx.Repo.Repository
  59. page := ctx.QueryInt("page")
  60. if page <= 0 {
  61. page = 1
  62. }
  63. jobTypeNot := false
  64. var computeResource string
  65. if listType != models.AllResource {
  66. computeResource = listType
  67. }
  68. var jobTypes []string
  69. jobTypes = append(jobTypes, string(models.JobTypeDebug))
  70. ciTasks, count, err := models.Cloudbrains(&models.CloudbrainsOptions{
  71. ListOptions: models.ListOptions{
  72. Page: page,
  73. PageSize: setting.UI.IssuePagingNum,
  74. },
  75. RepoID: repo.ID,
  76. ComputeResource: computeResource,
  77. Type: models.TypeCloudBrainAll,
  78. JobTypeNot: jobTypeNot,
  79. JobTypes: jobTypes,
  80. })
  81. if err != nil {
  82. ctx.ServerError("Get debugjob faild:", err)
  83. return
  84. }
  85. for i, task := range ciTasks {
  86. ciTasks[i].CanDebug = cloudbrain.CanModifyJob(ctx, &task.Cloudbrain)
  87. ciTasks[i].CanDel = cloudbrain.CanDeleteJob(ctx, &task.Cloudbrain)
  88. ciTasks[i].Cloudbrain.ComputeResource = task.ComputeResource
  89. }
  90. pager := context.NewPagination(int(count), setting.UI.IssuePagingNum, page, 5)
  91. pager.AddParam(ctx, "debugListType", "ListType")
  92. ctx.Data["Page"] = pager
  93. ctx.Data["PageIsCloudBrain"] = true
  94. ctx.Data["Tasks"] = ciTasks
  95. ctx.Data["CanCreate"] = cloudbrain.CanCreateOrDebugJob(ctx)
  96. ctx.Data["RepoIsEmpty"] = repo.IsEmpty
  97. ctx.Data["debugListType"] = listType
  98. ctx.HTML(200, tplDebugJobIndex)
  99. }
  100. // MustEnableDataset check if repository enable internal cb
  101. func MustEnableModelArts(ctx *context.Context) {
  102. if !ctx.Repo.CanRead(models.UnitTypeCloudBrain) {
  103. ctx.NotFound("MustEnableCloudbrain", nil)
  104. return
  105. }
  106. }
  107. func NotebookNew(ctx *context.Context) {
  108. notebookNewDataPrepare(ctx)
  109. ctx.HTML(200, tplModelArtsNotebookNew)
  110. }
  111. func notebookNewDataPrepare(ctx *context.Context) error {
  112. ctx.Data["PageIsCloudBrain"] = true
  113. var displayJobName = cloudbrainService.GetDisplayJobName(ctx.User.Name)
  114. ctx.Data["display_job_name"] = displayJobName
  115. attachs, err := models.GetModelArtsUserAttachments(ctx.User.ID)
  116. if err != nil {
  117. ctx.ServerError("GetAllUserAttachments failed:", err)
  118. return err
  119. }
  120. ctx.Data["attachments"] = attachs
  121. ctx.Data["images"] = setting.StImageInfos.ImageInfo
  122. prepareCloudbrainTwoDebugSpecs(ctx)
  123. ctx.Data["datasetType"] = models.TypeCloudBrainTwo
  124. waitCount := cloudbrain.GetWaitingCloudbrainCount(models.TypeCloudBrainTwo, "")
  125. ctx.Data["WaitCount"] = waitCount
  126. NotStopTaskCount, _ := cloudbrainTask.GetNotFinalStatusTaskCount(ctx.User.ID, models.TypeCloudBrainTwo, string(models.JobTypeDebug))
  127. ctx.Data["NotStopTaskCount"] = NotStopTaskCount
  128. return nil
  129. }
  130. func prepareCloudbrainTwoDebugSpecs(ctx *context.Context) {
  131. aiCenterCode := models.AICenterOfCloudBrainTwo
  132. if setting.ModelartsCD.Enabled {
  133. aiCenterCode = models.AICenterOfChengdu
  134. }
  135. noteBookSpecs, _ := resource.FindAvailableSpecs(ctx.User.ID, models.FindSpecsOptions{
  136. JobType: models.JobTypeDebug,
  137. ComputeResource: models.NPU,
  138. Cluster: models.OpenICluster,
  139. AiCenterCode: aiCenterCode,
  140. })
  141. ctx.Data["Specs"] = noteBookSpecs
  142. }
  143. func Notebook2Create(ctx *context.Context, form auth.CreateModelArtsNotebookForm) {
  144. ctx.Data["PageIsNotebook"] = true
  145. displayJobName := form.DisplayJobName
  146. jobName := util.ConvertDisplayJobNameToJobName(displayJobName)
  147. uuid := form.Attachment
  148. description := form.Description
  149. imageId := form.ImageId
  150. repo := ctx.Repo.Repository
  151. lockOperator, errMsg := cloudbrainService.Lock4CloudbrainCreation(&lock.LockContext{Repo: ctx.Repo.Repository, Task: &models.Cloudbrain{DisplayJobName: displayJobName, JobType: string(models.JobTypeDebug)}, User: ctx.User})
  152. defer func() {
  153. if lockOperator != nil {
  154. lockOperator.Unlock()
  155. }
  156. }()
  157. if errMsg != "" {
  158. log.Error("lock processed failed:%s", errMsg, ctx.Data["MsgID"])
  159. notebookNewDataPrepare(ctx)
  160. ctx.RenderWithErr(ctx.Tr(errMsg), tplModelArtsNotebookNew, &form)
  161. return
  162. }
  163. count, err := cloudbrainTask.GetNotFinalStatusTaskCount(ctx.User.ID, models.TypeCloudBrainTwo, string(models.JobTypeDebug))
  164. if err != nil {
  165. log.Error("GetCloudbrainNotebookCountByUserID failed:%v", err, ctx.Data["MsgID"])
  166. notebookNewDataPrepare(ctx)
  167. ctx.RenderWithErr("system error", tplModelArtsNotebookNew, &form)
  168. return
  169. } else {
  170. if count >= 1 {
  171. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  172. notebookNewDataPrepare(ctx)
  173. ctx.RenderWithErr("you have already a running or waiting task, can not create more", tplModelArtsNotebookNew, &form)
  174. return
  175. }
  176. }
  177. tasks, err := models.GetCloudbrainsByDisplayJobName(repo.ID, string(models.JobTypeDebug), displayJobName)
  178. if err == nil {
  179. if len(tasks) != 0 {
  180. log.Error("the job name did already exist", ctx.Data["MsgID"])
  181. notebookNewDataPrepare(ctx)
  182. ctx.RenderWithErr("the job name did already exist", tplModelArtsNotebookNew, &form)
  183. return
  184. }
  185. } else {
  186. if !models.IsErrJobNotExist(err) {
  187. log.Error("system error, %v", err, ctx.Data["MsgID"])
  188. notebookNewDataPrepare(ctx)
  189. ctx.RenderWithErr("system error", tplModelArtsNotebookNew, &form)
  190. return
  191. }
  192. }
  193. var datasetInfos map[string]models.DatasetInfo
  194. var attachSize int64
  195. if uuid != "" {
  196. datasetInfos, _, err = models.GetDatasetInfo(uuid)
  197. for _, infos := range datasetInfos {
  198. attachSize += infos.Size
  199. }
  200. if attachSize > int64(setting.DebugAttachSize*1000*1000*1000) {
  201. log.Error("The DatasetSize exceeds the limit (%dGB)", setting.DebugAttachSize) //GB
  202. notebookNewDataPrepare(ctx)
  203. ctx.RenderWithErr(ctx.Tr("cloudbrain.error.debug_datasetsize", setting.DebugAttachSize), tplModelArtsNotebookNew, &form)
  204. return
  205. }
  206. }
  207. var aiCenterCode = models.AICenterOfCloudBrainTwo
  208. if setting.ModelartsCD.Enabled {
  209. aiCenterCode = models.AICenterOfChengdu
  210. }
  211. spec, err := resource.GetAndCheckSpec(ctx.User.ID, form.SpecId, models.FindSpecsOptions{
  212. JobType: models.JobTypeDebug,
  213. ComputeResource: models.NPU,
  214. Cluster: models.OpenICluster,
  215. AiCenterCode: aiCenterCode})
  216. if err != nil || spec == nil {
  217. notebookNewDataPrepare(ctx)
  218. ctx.RenderWithErr("Resource specification not available", tplModelArtsNotebookNew, &form)
  219. return
  220. }
  221. if !account.IsPointBalanceEnough(ctx.User.ID, spec.UnitPrice) {
  222. log.Error("point balance is not enough,userId=%d specId=%d ", ctx.User.ID, spec.ID)
  223. notebookNewDataPrepare(ctx)
  224. ctx.RenderWithErr(ctx.Tr("points.insufficient_points_balance"), tplModelArtsNotebookNew, &form)
  225. return
  226. }
  227. req := cloudbrain.GenerateModelArtsNotebookReq{
  228. DisplayJobName: displayJobName,
  229. JobName: jobName,
  230. Description: description,
  231. Uuid: uuid,
  232. ImageId: imageId,
  233. Spec: spec,
  234. BootFile: "",
  235. AutoStopDurationMs: modelarts.AutoStopDurationMs,
  236. }
  237. if form.ModelName != "" { //使用预训练模型训练
  238. _, err := models.QueryModelByPath(form.PreTrainModelUrl)
  239. if err != nil {
  240. log.Error("Can not find model", err)
  241. notebookNewDataPrepare(ctx)
  242. ctx.RenderWithErr(ctx.Tr("repo.modelconvert.manage.model_not_exist"), tplModelArtsNotebookNew, &form)
  243. return
  244. }
  245. req.ModelName = form.ModelName
  246. req.LabelName = form.LabelName
  247. req.CkptName = form.CkptName
  248. req.ModelVersion = form.ModelVersion
  249. req.PreTrainModelUrl = form.PreTrainModelUrl
  250. }
  251. if setting.ModelartsCD.Enabled {
  252. _, err = modelarts_cd.GenerateNotebook(ctx, req)
  253. } else {
  254. _, err = modelarts.GenerateNotebook2(ctx, req)
  255. }
  256. if err != nil {
  257. log.Error("GenerateNotebook2 failed, %v", err, ctx.Data["MsgID"])
  258. notebookNewDataPrepare(ctx)
  259. ctx.RenderWithErr(err.Error(), tplModelArtsNotebookNew, &form)
  260. return
  261. }
  262. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/debugjob?debugListType=all")
  263. }
  264. func NotebookShow(ctx *context.Context) {
  265. ctx.Data["PageIsCloudBrain"] = true
  266. debugListType := ctx.Query("debugListType")
  267. if debugListType == "" {
  268. debugListType = "all"
  269. }
  270. var ID = ctx.Params(":id")
  271. task, err := models.GetCloudbrainByIDWithDeleted(ID)
  272. if err != nil {
  273. log.Error("GET job error", err.Error())
  274. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  275. return
  276. }
  277. if task.DeletedAt.IsZero() { //normal record
  278. err := modelarts.HandleNotebookInfo(task)
  279. if err != nil {
  280. ctx.Data["error"] = err.Error()
  281. ctx.RenderWithErr(err.Error(), tplModelArtsNotebookShow, nil)
  282. return
  283. }
  284. } else { //deleted record
  285. }
  286. datasetDownload := make([]*models.DatasetDownload, 0)
  287. var modelDownload models.ModelDownload
  288. if ctx.IsSigned {
  289. if task.Uuid != "" && task.UserID == ctx.User.ID {
  290. datasetDownload = GetCloudBrainDataSetInfo(task.Uuid, task.DatasetName, true)
  291. }
  292. if task.ModelName != "" && task.UserID == ctx.User.ID {
  293. modelDownload = GetModelDownload(task)
  294. }
  295. }
  296. user, err := models.GetUserByID(task.UserID)
  297. if err == nil {
  298. task.User = user
  299. }
  300. prepareSpec4Show(ctx, task)
  301. if task.TrainJobDuration == "" {
  302. if task.Duration == 0 {
  303. var duration int64
  304. if task.Status == string(models.JobRunning) {
  305. duration = time.Now().Unix() - int64(task.CreatedUnix)
  306. } else {
  307. duration = int64(task.UpdatedUnix) - int64(task.CreatedUnix)
  308. }
  309. task.Duration = duration
  310. }
  311. task.TrainJobDuration = models.ConvertDurationToStr(task.Duration)
  312. }
  313. ctx.Data["duration"] = task.TrainJobDuration
  314. ctx.Data["datasetDownload"] = datasetDownload
  315. ctx.Data["modelDownload"] = modelDownload
  316. ctx.Data["task"] = task
  317. ctx.Data["ID"] = ID
  318. ctx.Data["jobName"] = task.JobName
  319. ctx.Data["debugListType"] = debugListType
  320. ctx.HTML(200, tplModelArtsNotebookShow)
  321. }
  322. func GetModelDownload(task *models.Cloudbrain) models.ModelDownload {
  323. index := strings.Index(task.PreTrainModelUrl, "/")
  324. key := task.PreTrainModelUrl[index+1:] + task.CkptName
  325. url, _ := storage.GetObsCreateSignedUrlByBucketAndKey(setting.Bucket, key)
  326. modelDownload := models.ModelDownload{
  327. Name: task.CkptName,
  328. DownloadLink: url,
  329. IsDelete: false,
  330. }
  331. if !HasModelFile(task) {
  332. log.Warn("Can not get model by path:" + task.PreTrainModelUrl)
  333. modelDownload.IsDelete = true
  334. }
  335. return modelDownload
  336. }
  337. func GetCloudBrainDataSetInfo(uuid string, datasetname string, isNeedDown bool) []*models.DatasetDownload {
  338. datasetDownload := make([]*models.DatasetDownload, 0)
  339. if len(uuid) == 0 {
  340. return datasetDownload
  341. }
  342. uuidList := strings.Split(uuid, ";")
  343. datasetnameList := strings.Split(datasetname, ";")
  344. for i, uuidStr := range uuidList {
  345. name := ""
  346. link := ""
  347. url := ""
  348. isDelete := false
  349. attachment, err := models.GetAttachmentByUUID(uuidStr)
  350. if err != nil {
  351. log.Error("GetAttachmentByUUID failed:%v", err.Error())
  352. if len(datasetnameList) <= i || len(datasetname) == 0 {
  353. continue
  354. }
  355. name = datasetnameList[i]
  356. isDelete = true
  357. } else {
  358. name = attachment.Name
  359. dataset, err := models.GetDatasetByID(attachment.DatasetID)
  360. if err != nil {
  361. log.Error("GetDatasetByID failed:%v", err.Error())
  362. } else {
  363. repo, err := models.GetRepositoryByID(dataset.RepoID)
  364. if err != nil {
  365. log.Error("GetRepositoryByID failed:%v", err.Error())
  366. } else {
  367. link = repo.Link() + "/datasets"
  368. }
  369. }
  370. if isNeedDown {
  371. url = attachment.S3DownloadURL()
  372. }
  373. }
  374. datasetDownload = append(datasetDownload, &models.DatasetDownload{
  375. DatasetName: name,
  376. DatasetDownloadLink: url,
  377. RepositoryLink: link,
  378. IsDelete: isDelete,
  379. })
  380. }
  381. log.Info("dataset length=" + fmt.Sprint(len(datasetDownload)))
  382. return datasetDownload
  383. }
  384. func setShowSpecBySpecialPoolConfig(ctx *context.Context, findSpec bool, task *models.Cloudbrain) {
  385. modelarts.InitSpecialPool()
  386. if modelarts.SpecialPools != nil && !findSpec {
  387. for _, pool := range modelarts.SpecialPools.Pools {
  388. for _, flavor := range pool.Flavor {
  389. if flavor.Value == task.FlavorCode {
  390. ctx.Data["resource_spec"] = flavor.Desc
  391. }
  392. }
  393. }
  394. }
  395. }
  396. func NotebookDebug2(ctx *context.Context) {
  397. var err error
  398. var result *models.GetNotebook2Result
  399. task := ctx.Cloudbrain
  400. if task.Type == models.TypeCloudBrainTwo {
  401. result, err = modelarts.GetNotebook2(task.JobID)
  402. } else if task.Type == models.TypeCDCenter {
  403. result, err = modelarts_cd.GetNotebook(task.JobID)
  404. }
  405. if err != nil {
  406. ctx.RenderWithErr(err.Error(), tplModelArtsNotebookIndex, nil)
  407. return
  408. }
  409. if ctx.QueryTrim("file") != "" {
  410. ctx.Redirect(getFileUrl(result.Url, ctx.QueryTrim("file")) + "&token=" + result.Token)
  411. } else {
  412. if task.BootFile != "" {
  413. go cloudbrainTask.UploadNotebookFiles(task)
  414. }
  415. ctx.Redirect(result.Url + "?token=" + result.Token)
  416. }
  417. }
  418. func getFileUrl(url string, filename string) string {
  419. middle := ""
  420. if url[len(url)-3:] == "lab" || url[len(url)-4:] == "lab/" {
  421. if url[len(url)-1] == '/' {
  422. middle = "tree/"
  423. } else {
  424. middle = "/tree/"
  425. }
  426. } else {
  427. if url[len(url)-1] == '/' {
  428. middle = "lab/tree/"
  429. } else {
  430. middle = "/lab/tree/"
  431. }
  432. }
  433. return url + middle + filename + "?reset"
  434. }
  435. func NotebookRestart(ctx *context.Context) {
  436. var id = ctx.Params(":id")
  437. var resultCode = "-1"
  438. var errorMsg = ""
  439. var status = ""
  440. var spec *models.Specification
  441. task := ctx.Cloudbrain
  442. lockOperator, errMsg := cloudbrainService.Lock4CloudbrainRestart(&lock.LockContext{Repo: ctx.Repo.Repository, Task: &models.Cloudbrain{JobType: task.JobType}, User: ctx.User})
  443. defer func() {
  444. if lockOperator != nil {
  445. lockOperator.Unlock()
  446. }
  447. }()
  448. if errMsg != "" {
  449. log.Error("lock processed failed:%s", errMsg, ctx.Data["MsgID"])
  450. errorMsg = ctx.Tr(errMsg)
  451. }
  452. for {
  453. if errMsg != "" {
  454. break
  455. }
  456. ctx.CheckWechatBind()
  457. if ctx.Written() {
  458. return
  459. }
  460. if task.Status != string(models.ModelArtsStopped) && task.Status != string(models.ModelArtsStartFailed) && task.Status != string(models.ModelArtsCreateFailed) {
  461. log.Error("the job(%s) is not stopped", task.JobName, ctx.Data["MsgID"])
  462. errorMsg = "the job is not stopped"
  463. break
  464. }
  465. count, err := cloudbrainTask.GetNotFinalStatusTaskCount(ctx.User.ID, models.TypeCloudBrainTwo, string(models.JobTypeDebug))
  466. if err != nil {
  467. log.Error("GetCloudbrainNotebookCountByUserID failed:%v", err, ctx.Data["MsgID"])
  468. errorMsg = "system error"
  469. break
  470. } else {
  471. if count >= 1 {
  472. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  473. resultCode = "2"
  474. errorMsg = ctx.Tr("repo.cloudbrain.morethanonejob")
  475. break
  476. }
  477. }
  478. oldSpec, err := resource.GetCloudbrainSpec(task.ID)
  479. if err != nil || oldSpec == nil {
  480. log.Error("NotebookManage GetCloudbrainSpec error.%v", err)
  481. errorMsg = "Resource specification not available"
  482. break
  483. }
  484. aiCenterCode := models.AICenterOfCloudBrainTwo
  485. if task.Type == models.TypeCDCenter {
  486. aiCenterCode = models.AICenterOfChengdu
  487. }
  488. spec, err = resource.GetAndCheckSpec(ctx.User.ID, oldSpec.ID, models.FindSpecsOptions{
  489. JobType: models.JobType(task.JobType),
  490. ComputeResource: models.NPU,
  491. Cluster: models.OpenICluster,
  492. AiCenterCode: aiCenterCode})
  493. if err != nil || spec == nil {
  494. log.Error("NotebookManage GetAndCheckSpec error.task.id = %d", task.ID)
  495. errorMsg = "Resource specification not support any more"
  496. break
  497. }
  498. if !account.IsPointBalanceEnough(ctx.User.ID, spec.UnitPrice) {
  499. log.Error("point balance is not enough,userId=%d specId=%d", ctx.User.ID, spec.ID)
  500. errorMsg = ctx.Tr("points.insufficient_points_balance")
  501. break
  502. }
  503. if !HasModelFile(task) { //使用预训练模型训练
  504. errorMsg = ctx.Tr("repo.debug.manage.model_not_exist")
  505. break
  506. }
  507. if hasDatasetDeleted(task) {
  508. errorMsg = ctx.Tr("repo.debug.manage.dataset_not_exist")
  509. break
  510. }
  511. createTime := timeutil.TimeStampNow()
  512. param := models.NotebookAction{
  513. Action: models.ActionStart,
  514. }
  515. var res *models.NotebookActionResult
  516. if task.Type == models.TypeCloudBrainTwo {
  517. res, err = modelarts.ManageNotebook2(task.JobID, param)
  518. } else if task.Type == models.TypeCDCenter {
  519. res, err = modelarts_cd.ManageNotebook(task.JobID, param)
  520. }
  521. if err != nil {
  522. log.Error("ManageNotebook2(%s) failed:%v", task.DisplayJobName, err.Error(), ctx.Data["MsgID"])
  523. /* 暂不处理再次调试502的场景,详情见方案
  524. if strings.HasPrefix(err.Error(), modelarts.UnknownErrorPrefix) {
  525. log.Info("(%s)unknown error, set temp status", task.DisplayJobName)
  526. errTemp := models.InsertCloudbrainTemp(&models.CloudbrainTemp{
  527. JobID: task.JobID,
  528. VersionID: models.TempVersionId,
  529. Status: models.TempJobStatus,
  530. Type: task.Type,
  531. JobName: task.JobName,
  532. JobType: task.JobType,
  533. })
  534. if errTemp != nil {
  535. log.Error("InsertCloudbrainTemp failed: %v", errTemp.Error())
  536. }
  537. }
  538. */
  539. errorMsg = err.Error()
  540. break
  541. }
  542. newTask := &models.Cloudbrain{
  543. Status: res.Status,
  544. UserID: task.UserID,
  545. RepoID: task.RepoID,
  546. JobID: task.JobID,
  547. JobName: task.JobName,
  548. DisplayJobName: task.DisplayJobName,
  549. JobType: task.JobType,
  550. Type: task.Type,
  551. Uuid: task.Uuid,
  552. Image: task.Image,
  553. ComputeResource: task.ComputeResource,
  554. Description: task.Description,
  555. CreatedUnix: createTime,
  556. UpdatedUnix: createTime,
  557. Spec: spec,
  558. ModelName: task.ModelName,
  559. ModelVersion: task.ModelVersion,
  560. LabelName: task.LabelName,
  561. PreTrainModelUrl: task.PreTrainModelUrl,
  562. CkptName: task.CkptName,
  563. }
  564. err = models.RestartCloudbrain(task, newTask)
  565. if err != nil {
  566. log.Error("RestartCloudbrain(%s) failed:%v", task.JobName, err.Error(), ctx.Data["MsgID"])
  567. errorMsg = "system error"
  568. break
  569. }
  570. id = strconv.FormatInt(newTask.ID, 10)
  571. status = res.Status
  572. resultCode = "0"
  573. notification.NotifyOtherTask(ctx.User, ctx.Repo.Repository, id, newTask.DisplayJobName, models.ActionCreateDebugNPUTask)
  574. break
  575. }
  576. ctx.JSON(200, map[string]string{
  577. "result_code": resultCode,
  578. "error_msg": errorMsg,
  579. "status": status,
  580. "id": id,
  581. })
  582. }
  583. func NotebookStop(ctx *context.Context) {
  584. var id = ctx.Params(":id")
  585. var resultCode = "0"
  586. var errorMsg = ""
  587. var status = ""
  588. task := ctx.Cloudbrain
  589. for {
  590. if task.Status != string(models.ModelArtsRunning) {
  591. log.Error("the job(%s) is not running", task.JobName, ctx.Data["MsgID"])
  592. resultCode = "-1"
  593. errorMsg = ctx.Tr("cloudbrain.Already_stopped")
  594. break
  595. }
  596. err, res := StopModelArtsNotebook(task)
  597. if err != nil {
  598. log.Error("ManageNotebook2(%s) failed:%v", task.JobName, err.Error(), ctx.Data["MsgID"])
  599. resultCode = "-1"
  600. errorMsg = err.Error()
  601. if strings.Contains(err.Error(), modelarts.NotebookNotFound) {
  602. errorMsg = "the job's version is too old and can not be restarted"
  603. }
  604. break
  605. }
  606. status = res.Status
  607. oldStatus := task.Status
  608. task.Status = res.Status
  609. if task.EndTime == 0 && models.IsModelArtsDebugJobTerminal(task.Status) {
  610. task.EndTime = timeutil.TimeStampNow()
  611. }
  612. task.ComputeAndSetDuration()
  613. if oldStatus != task.Status {
  614. notification.NotifyChangeCloudbrainStatus(task, oldStatus)
  615. }
  616. err = models.UpdateJob(task)
  617. if err != nil {
  618. log.Error("UpdateJob(%s) failed:%v", task.JobName, err.Error(), ctx.Data["MsgID"])
  619. resultCode = "-1"
  620. errorMsg = "system error"
  621. break
  622. }
  623. break
  624. }
  625. ctx.JSON(200, map[string]string{
  626. "result_code": resultCode,
  627. "error_msg": errorMsg,
  628. "status": status,
  629. "id": id,
  630. })
  631. }
  632. func StopModelArtsNotebook(task *models.Cloudbrain) (error, *models.NotebookActionResult) {
  633. param := models.NotebookAction{
  634. Action: models.ActionStop,
  635. }
  636. var err error
  637. var res *models.NotebookActionResult
  638. if task.Type == models.TypeCloudBrainTwo {
  639. res, err = modelarts.ManageNotebook2(task.JobID, param)
  640. } else if task.Type == models.TypeCDCenter {
  641. res, err = modelarts_cd.ManageNotebook(task.JobID, param)
  642. }
  643. return err, res
  644. }
  645. func NotebookDel(ctx *context.Context) {
  646. var listType = ctx.Query("debugListType")
  647. task := ctx.Cloudbrain
  648. if task.Status != string(models.ModelArtsCreateFailed) && task.Status != string(models.ModelArtsStartFailed) && task.Status != string(models.ModelArtsStopped) && task.Status != string(models.ModelArtsDeleted) {
  649. log.Error("the job(%s) has not been stopped", task.JobName)
  650. ctx.RenderWithErr("the job has not been stopped", tplDebugJobIndex, nil)
  651. return
  652. }
  653. var err error
  654. if task.Type == models.TypeCloudBrainTwo {
  655. _, err = modelarts.DelNotebook2(task.JobID)
  656. } else if task.Type == models.TypeCDCenter {
  657. _, err = modelarts_cd.DelNotebook(task.JobID)
  658. }
  659. if err != nil {
  660. log.Error("DelNotebook2(%s) failed:%v", task.JobName, err.Error())
  661. if strings.Contains(err.Error(), modelarts.NotebookNotFound) || strings.Contains(err.Error(), modelarts.NotebookNoPermission) || strings.Contains(err.Error(), modelarts.NotebookInvalid) {
  662. log.Info("old notebook version")
  663. } else {
  664. ctx.RenderWithErr(err.Error(), tplDebugJobIndex, nil)
  665. return
  666. }
  667. }
  668. err = models.DeleteJob(task)
  669. if err != nil {
  670. ctx.RenderWithErr(err.Error(), tplDebugJobIndex, nil)
  671. return
  672. }
  673. var isAdminPage = ctx.Query("isadminpage")
  674. var isHomePage = ctx.Query("ishomepage")
  675. if ctx.IsUserSiteAdmin() && isAdminPage == "true" {
  676. ctx.Redirect(setting.AppSubURL + "/admin" + "/cloudbrains")
  677. } else if isHomePage == "true" {
  678. ctx.Redirect(setting.AppSubURL + "/cloudbrains")
  679. } else {
  680. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/debugjob?debugListType=" + listType)
  681. }
  682. }
  683. func TrainJobIndex(ctx *context.Context) {
  684. MustEnableModelArts(ctx)
  685. repo := ctx.Repo.Repository
  686. page := ctx.QueryInt("page")
  687. if page <= 0 {
  688. page = 1
  689. }
  690. listType := ctx.Query("listType")
  691. ctx.Data["ListType"] = listType
  692. if listType == models.AllResource {
  693. listType = ""
  694. }
  695. var jobTypes []string
  696. jobTypes = append(jobTypes, string(models.JobTypeTrain))
  697. tasks, count, err := models.Cloudbrains(&models.CloudbrainsOptions{
  698. ListOptions: models.ListOptions{
  699. Page: page,
  700. PageSize: setting.UI.IssuePagingNum,
  701. },
  702. RepoID: repo.ID,
  703. JobTypeNot: false,
  704. JobTypes: jobTypes,
  705. IsLatestVersion: modelarts.IsLatestVersion,
  706. ComputeResource: listType,
  707. Type: models.TypeCloudBrainAll,
  708. })
  709. if err != nil {
  710. ctx.ServerError("Cloudbrain", err)
  711. return
  712. }
  713. for i, task := range tasks {
  714. tasks[i].CanDel = cloudbrain.CanDeleteJob(ctx, &task.Cloudbrain)
  715. tasks[i].CanModify = cloudbrain.CanModifyJob(ctx, &task.Cloudbrain)
  716. }
  717. pager := context.NewPagination(int(count), setting.UI.IssuePagingNum, page, 5)
  718. pager.SetDefaultParams(ctx)
  719. pager.AddParam(ctx, "listType", "ListType")
  720. ctx.Data["Page"] = pager
  721. ctx.Data["PageIsCloudBrain"] = true
  722. ctx.Data["Tasks"] = tasks
  723. ctx.Data["CanCreate"] = cloudbrain.CanCreateOrDebugJob(ctx)
  724. ctx.Data["RepoIsEmpty"] = repo.IsEmpty
  725. ctx.HTML(200, tplModelArtsTrainJobIndex)
  726. }
  727. func TrainJobNew(ctx *context.Context) {
  728. err := trainJobNewDataPrepare(ctx)
  729. if err != nil {
  730. ctx.ServerError("get new train-job info failed", err)
  731. return
  732. }
  733. ctx.HTML(200, tplModelArtsTrainJobNew)
  734. }
  735. func trainJobNewDataPrepare(ctx *context.Context) error {
  736. ctx.Data["PageIsCloudBrain"] = true
  737. //can, err := canUserCreateTrainJob(ctx.User.ID)
  738. //if err != nil {
  739. // ctx.ServerError("canUserCreateTrainJob", err)
  740. // return
  741. //}
  742. //
  743. //if !can {
  744. // log.Error("the user can not create train-job")
  745. // ctx.ServerError("the user can not create train-job", fmt.Errorf("the user can not create train-job"))
  746. // return
  747. //}
  748. var displayJobName = cloudbrainService.GetDisplayJobName(ctx.User.Name)
  749. ctx.Data["display_job_name"] = displayJobName
  750. attachs, err := models.GetModelArtsTrainAttachments(ctx.User.ID)
  751. if err != nil {
  752. ctx.ServerError("GetAllUserAttachments failed:", err)
  753. return err
  754. }
  755. ctx.Data["attachments"] = attachs
  756. var resourcePools modelarts.ResourcePool
  757. if err = json.Unmarshal([]byte(setting.ResourcePools), &resourcePools); err != nil {
  758. ctx.ServerError("json.Unmarshal failed:", err)
  759. return err
  760. }
  761. ctx.Data["resource_pools"] = resourcePools.Info
  762. var engines modelarts.Engine
  763. if err = json.Unmarshal([]byte(setting.Engines), &engines); err != nil {
  764. ctx.ServerError("json.Unmarshal failed:", err)
  765. return err
  766. }
  767. ctx.Data["engines"] = engines.Info
  768. var versionInfos modelarts.VersionInfo
  769. if err = json.Unmarshal([]byte(setting.EngineVersions), &versionInfos); err != nil {
  770. ctx.ServerError("json.Unmarshal failed:", err)
  771. return err
  772. }
  773. ctx.Data["engine_versions"] = versionInfos.Version
  774. prepareCloudbrainTwoTrainSpecs(ctx)
  775. ctx.Data["params"] = ""
  776. ctx.Data["branchName"] = ctx.Repo.BranchName
  777. configList, err := getConfigList(modelarts.PerPage, 1, modelarts.SortByCreateTime, "desc", "", modelarts.ConfigTypeCustom)
  778. if err != nil {
  779. ctx.ServerError("getConfigList failed:", err)
  780. return err
  781. }
  782. ctx.Data["config_list"] = configList.ParaConfigs
  783. ctx.Data["datasetType"] = models.TypeCloudBrainTwo
  784. waitCount := cloudbrain.GetWaitingCloudbrainCount(models.TypeCloudBrainTwo, "")
  785. ctx.Data["WaitCount"] = waitCount
  786. NotStopTaskCount, _ := cloudbrainTask.GetNotFinalStatusTaskCount(ctx.User.ID, models.TypeCloudBrainTwo, string(models.JobTypeTrain))
  787. ctx.Data["NotStopTaskCount"] = NotStopTaskCount
  788. setMultiNodeIfConfigureMatch(ctx)
  789. return nil
  790. }
  791. func prepareCloudbrainTwoTrainSpecs(ctx *context.Context) {
  792. noteBookSpecs, _ := resource.FindAvailableSpecs(ctx.User.ID, models.FindSpecsOptions{
  793. JobType: models.JobTypeTrain,
  794. ComputeResource: models.NPU,
  795. Cluster: models.OpenICluster,
  796. AiCenterCode: models.AICenterOfCloudBrainTwo,
  797. })
  798. ctx.Data["Specs"] = noteBookSpecs
  799. }
  800. func setMultiNodeIfConfigureMatch(ctx *context.Context) {
  801. modelarts.InitMultiNode()
  802. if modelarts.MultiNodeConfig != nil {
  803. for _, info := range modelarts.MultiNodeConfig.Info {
  804. if isInOrg, _ := models.IsOrganizationMemberByOrgName(info.Org, ctx.User.ID); isInOrg {
  805. ctx.Data["WorkNode"] = info.Node
  806. break
  807. }
  808. }
  809. }
  810. }
  811. func setSpecBySpecialPoolConfig(ctx *context.Context, jobType string) {
  812. modelarts.InitSpecialPool()
  813. if modelarts.SpecialPools != nil {
  814. for _, specialPool := range modelarts.SpecialPools.Pools {
  815. if cloudbrain.IsElementExist(specialPool.JobType, jobType) {
  816. if isInOrg, _ := models.IsOrganizationMemberByOrgName(specialPool.Org, ctx.User.ID); isInOrg {
  817. var specialFlavor []struct {
  818. Code string
  819. Value string
  820. }
  821. if jobType == string(models.JobTypeDebug) {
  822. ctx.Data["flavors"] = specialPool.Flavor
  823. } else {
  824. for _, tempFlavor := range specialPool.Flavor {
  825. specialFlavor = append(specialFlavor, struct {
  826. Code string
  827. Value string
  828. }{Code: tempFlavor.Value, Value: tempFlavor.Desc})
  829. }
  830. ctx.Data["flavor_infos"] = specialFlavor
  831. }
  832. }
  833. }
  834. }
  835. }
  836. }
  837. func TrainJobNewVersion(ctx *context.Context) {
  838. err := trainJobNewVersionDataPrepare(ctx)
  839. if err != nil {
  840. ctx.ServerError("get new train-job info failed", err)
  841. return
  842. }
  843. ctx.HTML(200, tplModelArtsTrainJobVersionNew)
  844. }
  845. func trainJobNewVersionDataPrepare(ctx *context.Context) error {
  846. ctx.Data["PageIsCloudBrain"] = true
  847. var jobID = ctx.Params(":jobid")
  848. var versionName = ctx.Query("version_name")
  849. // canNewJob, err := canUserCreateTrainJobVersion(ctx, jobID, versionName)
  850. // if err != nil {
  851. // ctx.ServerError("canNewJob can info failed", err)
  852. // return err
  853. // }
  854. task, err := models.GetCloudbrainByJobIDAndVersionName(jobID, versionName)
  855. if err != nil {
  856. log.Error("GetCloudbrainByJobIDAndVersionName(%s) failed:%v", jobID, err.Error())
  857. return err
  858. }
  859. ctx.Data["display_job_name"] = task.DisplayJobName
  860. ctx.Data["job_name"] = task.JobName
  861. // attachs, err := models.GetModelArtsTrainAttachments(ctx.User.ID)
  862. // if err != nil {
  863. // ctx.ServerError("GetAllUserAttachments failed:", err)
  864. // return err
  865. // }
  866. // ctx.Data["attachments"] = attachs
  867. var resourcePools modelarts.ResourcePool
  868. if err = json.Unmarshal([]byte(setting.ResourcePools), &resourcePools); err != nil {
  869. ctx.ServerError("json.Unmarshal failed:", err)
  870. return err
  871. }
  872. ctx.Data["resource_pools"] = resourcePools.Info
  873. var engines modelarts.Engine
  874. if err = json.Unmarshal([]byte(setting.Engines), &engines); err != nil {
  875. ctx.ServerError("json.Unmarshal failed:", err)
  876. return err
  877. }
  878. ctx.Data["engines"] = engines.Info
  879. var versionInfos modelarts.VersionInfo
  880. if err = json.Unmarshal([]byte(setting.EngineVersions), &versionInfos); err != nil {
  881. ctx.ServerError("json.Unmarshal failed:", err)
  882. return err
  883. }
  884. ctx.Data["engine_versions"] = versionInfos.Version
  885. prepareCloudbrainTwoTrainSpecs(ctx)
  886. spec, _ := resource.GetCloudbrainSpec(task.ID)
  887. if spec != nil {
  888. log.Info("spec_id = %d", spec.ID)
  889. ctx.Data["spec_id"] = spec.ID
  890. }
  891. ctx.Data["run_para_list"] = task.Parameters
  892. branches, _, err := ctx.Repo.GitRepo.GetBranches(0, 0)
  893. if err != nil {
  894. ctx.ServerError("GetBranches error:", err)
  895. return err
  896. }
  897. uuids, datasetNames := dataset.GetFilterDeletedAttachments(task.Uuid)
  898. ctx.Data["dataset_name"] = datasetNames
  899. ctx.Data["branches"] = branches
  900. ctx.Data["branch_name"] = task.BranchName
  901. ctx.Data["description"] = task.Description
  902. ctx.Data["boot_file"] = task.BootFile
  903. ctx.Data["work_server_number"] = task.WorkServerNumber
  904. ctx.Data["flavor_name"] = task.FlavorName
  905. ctx.Data["engine_name"] = task.EngineName
  906. ctx.Data["attachment"] = uuids
  907. ctx.Data["flavor_code"] = task.FlavorCode
  908. ctx.Data["engine_id"] = task.EngineID
  909. ctx.Data["datasetType"] = models.TypeCloudBrainTwo
  910. //pretrain model
  911. ctx.Data["model_name"] = task.ModelName
  912. ctx.Data["model_version"] = task.ModelVersion
  913. ctx.Data["ckpt_name"] = task.CkptName
  914. ctx.Data["label_names"] = task.LabelName
  915. ctx.Data["pre_train_model_url"] = task.PreTrainModelUrl
  916. configList, err := getConfigList(modelarts.PerPage, 1, modelarts.SortByCreateTime, "desc", "", modelarts.ConfigTypeCustom)
  917. if err != nil {
  918. ctx.ServerError("getConfigList failed:", err)
  919. return err
  920. }
  921. ctx.Data["config_list"] = configList.ParaConfigs
  922. waitCount := cloudbrain.GetWaitingCloudbrainCount(models.TypeCloudBrainTwo, "")
  923. ctx.Data["WaitCount"] = waitCount
  924. NotStopTaskCount, _ := cloudbrainTask.GetNotFinalStatusTaskCount(ctx.User.ID, models.TypeCloudBrainTwo, string(models.JobTypeTrain))
  925. ctx.Data["NotStopTaskCount"] = NotStopTaskCount
  926. return nil
  927. }
  928. func TrainJobCreate(ctx *context.Context, form auth.CreateModelArtsTrainJobForm) {
  929. ctx.Data["PageIsTrainJob"] = true
  930. VersionOutputPath := modelarts.GetOutputPathByCount(modelarts.TotalVersionCount)
  931. displayJobName := form.DisplayJobName
  932. jobName := util.ConvertDisplayJobNameToJobName(displayJobName)
  933. uuid := form.Attachment
  934. description := form.Description
  935. workServerNumber := form.WorkServerNumber
  936. engineID := form.EngineID
  937. bootFile := strings.TrimSpace(form.BootFile)
  938. params := form.Params
  939. poolID := form.PoolID
  940. //isSaveParam := form.IsSaveParam
  941. repo := ctx.Repo.Repository
  942. codeLocalPath := setting.JobPath + jobName + modelarts.CodePath
  943. codeObsPath := "/" + setting.Bucket + modelarts.JobPath + jobName + modelarts.CodePath + VersionOutputPath + "/"
  944. outputObsPath := "/" + setting.Bucket + modelarts.JobPath + jobName + modelarts.OutputPath + VersionOutputPath + "/"
  945. logObsPath := "/" + setting.Bucket + modelarts.JobPath + jobName + modelarts.LogPath + VersionOutputPath + "/"
  946. // dataPath := "/" + setting.Bucket + "/" + setting.BasePath + path.Join(uuid[0:1], uuid[1:2]) + "/" + uuid + uuid + "/"
  947. branchName := form.BranchName
  948. isLatestVersion := modelarts.IsLatestVersion
  949. FlavorName := form.FlavorName
  950. VersionCount := modelarts.VersionCountOne
  951. EngineName := form.EngineName
  952. errStr := checkMultiNode(ctx.User.ID, form.WorkServerNumber)
  953. if errStr != "" {
  954. trainJobNewDataPrepare(ctx)
  955. ctx.RenderWithErr(ctx.Tr(errStr), tplModelArtsTrainJobNew, &form)
  956. return
  957. }
  958. lockOperator, errMsg := cloudbrainService.Lock4CloudbrainCreation(&lock.LockContext{Repo: ctx.Repo.Repository, Task: &models.Cloudbrain{DisplayJobName: displayJobName, JobType: string(models.JobTypeTrain)}, User: ctx.User})
  959. defer func() {
  960. if lockOperator != nil {
  961. lockOperator.Unlock()
  962. }
  963. }()
  964. if errMsg != "" {
  965. log.Error("lock processed failed:%s", errMsg, ctx.Data["MsgID"])
  966. trainJobNewDataPrepare(ctx)
  967. ctx.RenderWithErr(ctx.Tr(errMsg), tplModelArtsTrainJobNew, &form)
  968. return
  969. }
  970. count, err := cloudbrainTask.GetNotFinalStatusTaskCount(ctx.User.ID, models.TypeCloudBrainTwo, string(models.JobTypeTrain))
  971. if err != nil {
  972. log.Error("GetCloudbrainTrainJobCountByUserID failed:%v", err, ctx.Data["MsgID"])
  973. trainJobNewDataPrepare(ctx)
  974. ctx.RenderWithErr("system error", tplModelArtsTrainJobNew, &form)
  975. return
  976. } else {
  977. if count >= 1 {
  978. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  979. trainJobNewDataPrepare(ctx)
  980. ctx.RenderWithErr("you have already a running or waiting task, can not create more", tplModelArtsTrainJobNew, &form)
  981. return
  982. }
  983. }
  984. if err := paramCheckCreateTrainJob(form); err != nil {
  985. log.Error("paramCheckCreateTrainJob failed:(%v)", err)
  986. trainJobNewDataPrepare(ctx)
  987. ctx.RenderWithErr(err.Error(), tplModelArtsTrainJobNew, &form)
  988. return
  989. }
  990. bootFileExist, err := ctx.Repo.FileExists(bootFile, branchName)
  991. if err != nil || !bootFileExist {
  992. log.Error("Get bootfile error:", err)
  993. trainJobNewDataPrepare(ctx)
  994. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_bootfile_err"), tplModelArtsTrainJobNew, &form)
  995. return
  996. }
  997. spec, err := resource.GetAndCheckSpec(ctx.User.ID, form.SpecId, models.FindSpecsOptions{
  998. JobType: models.JobTypeTrain,
  999. ComputeResource: models.NPU,
  1000. Cluster: models.OpenICluster,
  1001. AiCenterCode: models.AICenterOfCloudBrainTwo})
  1002. if err != nil || spec == nil {
  1003. trainJobNewDataPrepare(ctx)
  1004. ctx.RenderWithErr("Resource specification not available", tplModelArtsTrainJobNew, &form)
  1005. return
  1006. }
  1007. if !account.IsPointBalanceEnough(ctx.User.ID, spec.UnitPrice*form.WorkServerNumber) {
  1008. log.Error("point balance is not enough,userId=%d specId=%d", ctx.User.ID, spec.ID)
  1009. trainJobNewDataPrepare(ctx)
  1010. ctx.RenderWithErr(ctx.Tr("points.insufficient_points_balance"), tplModelArtsTrainJobNew, &form)
  1011. return
  1012. }
  1013. //Determine whether the task name of the task in the project is duplicated
  1014. tasks, err := models.GetCloudbrainsByDisplayJobName(repo.ID, string(models.JobTypeTrain), displayJobName)
  1015. if err == nil {
  1016. if len(tasks) != 0 {
  1017. log.Error("the job name did already exist", ctx.Data["MsgID"])
  1018. trainJobNewDataPrepare(ctx)
  1019. ctx.RenderWithErr("the job name did already exist", tplModelArtsTrainJobNew, &form)
  1020. return
  1021. }
  1022. } else {
  1023. if !models.IsErrJobNotExist(err) {
  1024. log.Error("system error, %v", err, ctx.Data["MsgID"])
  1025. trainJobNewDataPrepare(ctx)
  1026. ctx.RenderWithErr("system error", tplModelArtsTrainJobNew, &form)
  1027. return
  1028. }
  1029. }
  1030. //todo: del the codeLocalPath
  1031. _, err = ioutil.ReadDir(codeLocalPath)
  1032. if err == nil {
  1033. os.RemoveAll(codeLocalPath)
  1034. }
  1035. gitRepo, _ := git.OpenRepository(repo.RepoPath())
  1036. commitID, _ := gitRepo.GetBranchCommitID(branchName)
  1037. if err := downloadCode(repo, codeLocalPath, branchName); err != nil {
  1038. log.Error("downloadCode failed, server timed out: %s (%v)", repo.FullName(), err)
  1039. trainJobNewDataPrepare(ctx)
  1040. ctx.RenderWithErr(ctx.Tr("cloudbrain.load_code_failed"), tplModelArtsTrainJobNew, &form)
  1041. return
  1042. }
  1043. //todo: upload code (send to file_server todo this work?)
  1044. if err := obsMkdir(setting.CodePathPrefix + jobName + modelarts.OutputPath + VersionOutputPath + "/"); err != nil {
  1045. log.Error("Failed to obsMkdir_output: %s (%v)", repo.FullName(), err)
  1046. trainJobNewDataPrepare(ctx)
  1047. ctx.RenderWithErr("Failed to obsMkdir_output", tplModelArtsTrainJobNew, &form)
  1048. return
  1049. }
  1050. if err := obsMkdir(setting.CodePathPrefix + jobName + modelarts.LogPath + VersionOutputPath + "/"); err != nil {
  1051. log.Error("Failed to obsMkdir_log: %s (%v)", repo.FullName(), err)
  1052. trainJobNewDataPrepare(ctx)
  1053. ctx.RenderWithErr("Failed to obsMkdir_log", tplModelArtsTrainJobNew, &form)
  1054. return
  1055. }
  1056. parentDir := VersionOutputPath + "/"
  1057. if err := uploadCodeToObs(codeLocalPath, jobName, parentDir); err != nil {
  1058. // if err := uploadCodeToObs(codeLocalPath, jobName, parentDir); err != nil {
  1059. log.Error("Failed to uploadCodeToObs: %s (%v)", repo.FullName(), err)
  1060. trainJobNewDataPrepare(ctx)
  1061. ctx.RenderWithErr(ctx.Tr("cloudbrain.load_code_failed"), tplModelArtsTrainJobNew, &form)
  1062. return
  1063. }
  1064. var parameters models.Parameters
  1065. param := make([]models.Parameter, 0)
  1066. existDeviceTarget := false
  1067. if len(params) != 0 {
  1068. err := json.Unmarshal([]byte(params), &parameters)
  1069. if err != nil {
  1070. log.Error("Failed to Unmarshal params: %s (%v)", params, err)
  1071. trainJobNewDataPrepare(ctx)
  1072. ctx.RenderWithErr("运行参数错误", tplModelArtsTrainJobNew, &form)
  1073. return
  1074. }
  1075. for _, parameter := range parameters.Parameter {
  1076. if parameter.Label == modelarts.DeviceTarget {
  1077. existDeviceTarget = true
  1078. }
  1079. if parameter.Label != modelarts.TrainUrl && parameter.Label != modelarts.DataUrl {
  1080. param = append(param, models.Parameter{
  1081. Label: parameter.Label,
  1082. Value: parameter.Value,
  1083. })
  1084. }
  1085. }
  1086. }
  1087. if !existDeviceTarget {
  1088. param = append(param, models.Parameter{
  1089. Label: modelarts.DeviceTarget,
  1090. Value: modelarts.Ascend,
  1091. })
  1092. }
  1093. datasUrlList, dataUrl, datasetNames, isMultiDataset, err := getDatasUrlListByUUIDS(uuid)
  1094. if err != nil {
  1095. log.Error("Failed to getDatasUrlListByUUIDS: %v", err)
  1096. trainJobNewDataPrepare(ctx)
  1097. ctx.RenderWithErr("Failed to getDatasUrlListByUUIDS:"+err.Error(), tplModelArtsTrainJobNew, &form)
  1098. return
  1099. }
  1100. dataPath := dataUrl
  1101. jsondatas, err := json.Marshal(datasUrlList)
  1102. if err != nil {
  1103. log.Error("Failed to Marshal: %v", err)
  1104. trainJobNewDataPrepare(ctx)
  1105. ctx.RenderWithErr("json error:"+err.Error(), tplModelArtsTrainJobNew, &form)
  1106. return
  1107. }
  1108. if isMultiDataset {
  1109. param = append(param, models.Parameter{
  1110. Label: modelarts.MultiDataUrl,
  1111. Value: string(jsondatas),
  1112. })
  1113. }
  1114. if form.ModelName != "" { //使用预训练模型训练
  1115. ckptUrl := "/" + form.PreTrainModelUrl + form.CkptName
  1116. param = append(param, models.Parameter{
  1117. Label: modelarts.CkptUrl,
  1118. Value: "s3:/" + ckptUrl,
  1119. })
  1120. }
  1121. //save param config
  1122. // if isSaveParam == "on" {
  1123. // saveparams := append(param, models.Parameter{
  1124. // Label: modelarts.TrainUrl,
  1125. // Value: outputObsPath,
  1126. // }, models.Parameter{
  1127. // Label: modelarts.DataUrl,
  1128. // Value: dataPath,
  1129. // })
  1130. // if form.ParameterTemplateName == "" {
  1131. // log.Error("ParameterTemplateName is empty")
  1132. // trainJobNewDataPrepare(ctx)
  1133. // ctx.RenderWithErr("保存作业参数时,作业参数名称不能为空", tplModelArtsTrainJobNew, &form)
  1134. // return
  1135. // }
  1136. // _, err := modelarts.CreateTrainJobConfig(models.CreateConfigParams{
  1137. // ConfigName: form.ParameterTemplateName,
  1138. // Description: form.PrameterDescription,
  1139. // DataUrl: dataPath,
  1140. // AppUrl: codeObsPath,
  1141. // BootFileUrl: codeObsPath + bootFile,
  1142. // TrainUrl: outputObsPath,
  1143. // Flavor: models.Flavor{
  1144. // Code: flavorCode,
  1145. // },
  1146. // WorkServerNum: workServerNumber,
  1147. // EngineID: int64(engineID),
  1148. // LogUrl: logObsPath,
  1149. // PoolID: poolID,
  1150. // Parameter: saveparams,
  1151. // })
  1152. // if err != nil {
  1153. // log.Error("Failed to CreateTrainJobConfig: %v", err)
  1154. // trainJobErrorNewDataPrepare(ctx, form)
  1155. // ctx.RenderWithErr("保存作业参数失败:"+err.Error(), tplModelArtsTrainJobNew, &form)
  1156. // return
  1157. // }
  1158. // }
  1159. req := &modelarts.GenerateTrainJobReq{
  1160. JobName: jobName,
  1161. DisplayJobName: displayJobName,
  1162. DataUrl: dataPath,
  1163. Description: description,
  1164. CodeObsPath: codeObsPath,
  1165. BootFileUrl: codeObsPath + bootFile,
  1166. BootFile: bootFile,
  1167. TrainUrl: outputObsPath,
  1168. WorkServerNumber: workServerNumber,
  1169. EngineID: int64(engineID),
  1170. LogUrl: logObsPath,
  1171. PoolID: poolID,
  1172. Uuid: uuid,
  1173. Parameters: param,
  1174. CommitID: commitID,
  1175. IsLatestVersion: isLatestVersion,
  1176. BranchName: branchName,
  1177. Params: form.Params,
  1178. FlavorName: FlavorName,
  1179. EngineName: EngineName,
  1180. VersionCount: VersionCount,
  1181. TotalVersionCount: modelarts.TotalVersionCount,
  1182. DatasetName: datasetNames,
  1183. Spec: spec,
  1184. }
  1185. if form.ModelName != "" { //使用预训练模型训练
  1186. req.ModelName = form.ModelName
  1187. req.LabelName = form.LabelName
  1188. req.CkptName = form.CkptName
  1189. req.ModelVersion = form.ModelVersion
  1190. req.PreTrainModelUrl = form.PreTrainModelUrl
  1191. }
  1192. userCommand, userImageUrl := getUserCommand(engineID, req)
  1193. req.UserCommand = userCommand
  1194. req.UserImageUrl = userImageUrl
  1195. //将params转换Parameters.Parameter,出错时返回给前端
  1196. var Parameters modelarts.Parameters
  1197. if err := json.Unmarshal([]byte(params), &Parameters); err != nil {
  1198. ctx.ServerError("json.Unmarshal failed:", err)
  1199. return
  1200. }
  1201. _, err = modelarts.GenerateTrainJob(ctx, req)
  1202. if err != nil {
  1203. log.Error("GenerateTrainJob failed:%v", err.Error())
  1204. trainJobNewDataPrepare(ctx)
  1205. ctx.RenderWithErr(err.Error(), tplModelArtsTrainJobNew, &form)
  1206. return
  1207. }
  1208. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/train-job")
  1209. }
  1210. func checkMultiNode(userId int64, serverNum int) string {
  1211. if serverNum == 1 {
  1212. return ""
  1213. }
  1214. modelarts.InitMultiNode()
  1215. var isServerNumValid = false
  1216. if modelarts.MultiNodeConfig != nil {
  1217. for _, info := range modelarts.MultiNodeConfig.Info {
  1218. if isInOrg, _ := models.IsOrganizationMemberByOrgName(info.Org, userId); isInOrg {
  1219. if isInNodes(info.Node, serverNum) {
  1220. isServerNumValid = true
  1221. break
  1222. }
  1223. }
  1224. }
  1225. }
  1226. if isServerNumValid {
  1227. return ""
  1228. } else {
  1229. return "repo.modelarts.no_node_right"
  1230. }
  1231. }
  1232. func checkInferenceJobMultiNode(userId int64, serverNum int) string {
  1233. if serverNum == 1 {
  1234. return ""
  1235. }
  1236. return "repo.modelarts.no_node_right"
  1237. }
  1238. func isInNodes(nodes []int, num int) bool {
  1239. for _, node := range nodes {
  1240. if node == num {
  1241. return true
  1242. }
  1243. }
  1244. return false
  1245. }
  1246. func getUserCommand(engineId int, req *modelarts.GenerateTrainJobReq) (string, string) {
  1247. userImageUrl := ""
  1248. userCommand := ""
  1249. if engineId < 0 {
  1250. tmpCodeObsPath := strings.Trim(req.CodeObsPath, "/")
  1251. tmpCodeObsPaths := strings.Split(tmpCodeObsPath, "/")
  1252. lastCodeDir := "code"
  1253. if len(tmpCodeObsPaths) > 0 {
  1254. lastCodeDir = tmpCodeObsPaths[len(tmpCodeObsPaths)-1]
  1255. }
  1256. userCommand = "/bin/bash /home/work/run_train.sh 's3://" + req.CodeObsPath + "' '" + lastCodeDir + "/" + req.BootFile + "' '/tmp/log/train.log' --'data_url'='s3://" + req.DataUrl + "' --'train_url'='s3://" + req.TrainUrl + "'"
  1257. var versionInfos modelarts.VersionInfo
  1258. if err := json.Unmarshal([]byte(setting.EngineVersions), &versionInfos); err != nil {
  1259. log.Info("json parse err." + err.Error())
  1260. } else {
  1261. for _, engine := range versionInfos.Version {
  1262. if engine.ID == engineId {
  1263. userImageUrl = engine.Url
  1264. break
  1265. }
  1266. }
  1267. }
  1268. for _, param := range req.Parameters {
  1269. userCommand += " --'" + param.Label + "'='" + param.Value + "'"
  1270. }
  1271. return userCommand, userImageUrl
  1272. }
  1273. return userCommand, userImageUrl
  1274. }
  1275. func getInfJobUserCommand(engineId int, req *modelarts.GenerateInferenceJobReq) (string, string) {
  1276. userImageUrl := ""
  1277. userCommand := ""
  1278. if engineId < 0 {
  1279. tmpCodeObsPath := strings.Trim(req.CodeObsPath, "/")
  1280. tmpCodeObsPaths := strings.Split(tmpCodeObsPath, "/")
  1281. lastCodeDir := "code"
  1282. if len(tmpCodeObsPaths) > 0 {
  1283. lastCodeDir = tmpCodeObsPaths[len(tmpCodeObsPaths)-1]
  1284. }
  1285. userCommand = "/bin/bash /home/work/run_train.sh 's3://" + req.CodeObsPath + "' '" + lastCodeDir + "/" + req.BootFile + "' '/tmp/log/train.log' --'data_url'='s3://" + req.DataUrl + "' --'train_url'='s3://" + req.TrainUrl + "'"
  1286. var versionInfos modelarts.VersionInfo
  1287. if err := json.Unmarshal([]byte(setting.EngineVersions), &versionInfos); err != nil {
  1288. log.Info("json parse err." + err.Error())
  1289. } else {
  1290. for _, engine := range versionInfos.Version {
  1291. if engine.ID == engineId {
  1292. userImageUrl = engine.Url
  1293. break
  1294. }
  1295. }
  1296. }
  1297. for _, param := range req.Parameters {
  1298. userCommand += " --'" + param.Label + "'='" + param.Value + "'"
  1299. }
  1300. return userCommand, userImageUrl
  1301. }
  1302. return userCommand, userImageUrl
  1303. }
  1304. func TrainJobCreateVersion(ctx *context.Context, form auth.CreateModelArtsTrainJobForm) {
  1305. ctx.Data["PageIsTrainJob"] = true
  1306. var jobID = ctx.Params(":jobid")
  1307. lockOperator, errMsg := cloudbrainService.Lock4CloudbrainCreation(&lock.LockContext{Repo: ctx.Repo.Repository, Task: &models.Cloudbrain{DisplayJobName: form.DisplayJobName, JobType: string(models.JobTypeTrain)}, User: ctx.User})
  1308. defer func() {
  1309. if lockOperator != nil {
  1310. lockOperator.Unlock()
  1311. }
  1312. }()
  1313. if errMsg != "" {
  1314. log.Error("lock processed failed:%s", errMsg, ctx.Data["MsgID"])
  1315. trainJobNewVersionDataPrepare(ctx)
  1316. ctx.RenderWithErr(ctx.Tr(errMsg), tplModelArtsTrainJobVersionNew, &form)
  1317. return
  1318. }
  1319. errStr := checkMultiNode(ctx.User.ID, form.WorkServerNumber)
  1320. if errStr != "" {
  1321. trainJobNewVersionDataPrepare(ctx)
  1322. ctx.RenderWithErr(ctx.Tr(errStr), tplModelArtsTrainJobVersionNew, &form)
  1323. return
  1324. }
  1325. count, err := cloudbrainTask.GetNotFinalStatusTaskCount(ctx.User.ID, models.TypeCloudBrainTwo, string(models.JobTypeTrain))
  1326. if err != nil {
  1327. log.Error("GetCloudbrainTrainJobCountByUserID failed:%v", err, ctx.Data["MsgID"])
  1328. trainJobNewVersionDataPrepare(ctx)
  1329. ctx.RenderWithErr("system error", tplModelArtsTrainJobVersionNew, &form)
  1330. return
  1331. } else {
  1332. if count >= 1 {
  1333. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  1334. trainJobNewVersionDataPrepare(ctx)
  1335. ctx.RenderWithErr("you have already a running or waiting task, can not create more", tplModelArtsTrainJobVersionNew, &form)
  1336. return
  1337. }
  1338. }
  1339. latestTask, err := models.GetCloudbrainByJobIDAndIsLatestVersion(jobID, modelarts.IsLatestVersion)
  1340. if err != nil {
  1341. ctx.ServerError("GetCloudbrainByJobIDAndIsLatestVersion faild:", err)
  1342. return
  1343. }
  1344. VersionOutputPath := modelarts.GetOutputPathByCount(latestTask.TotalVersionCount + 1)
  1345. displayJobName := form.DisplayJobName
  1346. jobName := form.JobName
  1347. uuid := form.Attachment
  1348. description := form.Description
  1349. workServerNumber := form.WorkServerNumber
  1350. engineID := form.EngineID
  1351. bootFile := strings.TrimSpace(form.BootFile)
  1352. params := form.Params
  1353. poolID := form.PoolID
  1354. //isSaveParam := form.IsSaveParam
  1355. repo := ctx.Repo.Repository
  1356. codeLocalPath := setting.JobPath + jobName + modelarts.CodePath
  1357. codeObsPath := "/" + setting.Bucket + modelarts.JobPath + jobName + modelarts.CodePath + VersionOutputPath + "/"
  1358. outputObsPath := "/" + setting.Bucket + modelarts.JobPath + jobName + modelarts.OutputPath + VersionOutputPath + "/"
  1359. logObsPath := "/" + setting.Bucket + modelarts.JobPath + jobName + modelarts.LogPath + VersionOutputPath + "/"
  1360. // dataPath := "/" + setting.Bucket + "/" + setting.BasePath + path.Join(uuid[0:1], uuid[1:2]) + "/" + uuid + uuid + "/"
  1361. branchName := form.BranchName
  1362. PreVersionName := form.VersionName
  1363. FlavorName := form.FlavorName
  1364. EngineName := form.EngineName
  1365. isLatestVersion := modelarts.IsLatestVersion
  1366. canNewJob, _ := canUserCreateTrainJobVersion(ctx, latestTask.UserID)
  1367. if !canNewJob {
  1368. trainJobNewVersionDataPrepare(ctx)
  1369. ctx.RenderWithErr("user cann't new trainjob", tplModelArtsTrainJobVersionNew, &form)
  1370. return
  1371. }
  1372. if err := paramCheckCreateTrainJob(form); err != nil {
  1373. log.Error("paramCheckCreateTrainJob failed:(%v)", err)
  1374. trainJobNewVersionDataPrepare(ctx)
  1375. ctx.RenderWithErr(err.Error(), tplModelArtsTrainJobVersionNew, &form)
  1376. return
  1377. }
  1378. bootFileExist, err := ctx.Repo.FileExists(bootFile, branchName)
  1379. if err != nil || !bootFileExist {
  1380. log.Error("Get bootfile error:", err)
  1381. trainJobNewVersionDataPrepare(ctx)
  1382. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_bootfile_err"), tplModelArtsTrainJobVersionNew, &form)
  1383. return
  1384. }
  1385. spec, err := resource.GetAndCheckSpec(ctx.User.ID, form.SpecId, models.FindSpecsOptions{
  1386. JobType: models.JobTypeTrain,
  1387. ComputeResource: models.NPU,
  1388. Cluster: models.OpenICluster,
  1389. AiCenterCode: models.AICenterOfCloudBrainTwo})
  1390. if err != nil || spec == nil {
  1391. trainJobNewVersionDataPrepare(ctx)
  1392. ctx.RenderWithErr("Resource specification not available", tplModelArtsTrainJobVersionNew, &form)
  1393. return
  1394. }
  1395. if !account.IsPointBalanceEnough(ctx.User.ID, spec.UnitPrice) {
  1396. log.Error("point balance is not enough,userId=%d specId=%d", ctx.User.ID, spec.ID)
  1397. trainJobNewVersionDataPrepare(ctx)
  1398. ctx.RenderWithErr(ctx.Tr("points.insufficient_points_balance"), tplModelArtsTrainJobVersionNew, &form)
  1399. return
  1400. }
  1401. //todo: del the codeLocalPath
  1402. _, err = ioutil.ReadDir(codeLocalPath)
  1403. if err == nil {
  1404. os.RemoveAll(codeLocalPath)
  1405. }
  1406. gitRepo, _ := git.OpenRepository(repo.RepoPath())
  1407. commitID, _ := gitRepo.GetBranchCommitID(branchName)
  1408. if err := downloadCode(repo, codeLocalPath, branchName); err != nil {
  1409. log.Error("Failed git clone repo to local(!: %s (%v)", repo.FullName(), err)
  1410. trainJobNewVersionDataPrepare(ctx)
  1411. ctx.RenderWithErr(ctx.Tr("cloudbrain.load_code_failed"), tplModelArtsTrainJobVersionNew, &form)
  1412. return
  1413. }
  1414. //todo: upload code (send to file_server todo this work?)
  1415. if err := obsMkdir(setting.CodePathPrefix + jobName + modelarts.OutputPath + VersionOutputPath + "/"); err != nil {
  1416. log.Error("Failed to obsMkdir_output: %s (%v)", repo.FullName(), err)
  1417. trainJobNewVersionDataPrepare(ctx)
  1418. ctx.RenderWithErr("Failed to obsMkdir_output", tplModelArtsTrainJobVersionNew, &form)
  1419. return
  1420. }
  1421. if err := obsMkdir(setting.CodePathPrefix + jobName + modelarts.LogPath + VersionOutputPath + "/"); err != nil {
  1422. log.Error("Failed to obsMkdir_log: %s (%v)", repo.FullName(), err)
  1423. trainJobNewVersionDataPrepare(ctx)
  1424. ctx.RenderWithErr("Failed to obsMkdir_log", tplModelArtsTrainJobVersionNew, &form)
  1425. return
  1426. }
  1427. parentDir := VersionOutputPath + "/"
  1428. // parentDir := ""
  1429. // if err := uploadCodeToObs(codeLocalPath, jobName, ""); err != nil {
  1430. if err := uploadCodeToObs(codeLocalPath, jobName, parentDir); err != nil {
  1431. log.Error("Failed to uploadCodeToObs: %s (%v)", repo.FullName(), err)
  1432. trainJobNewVersionDataPrepare(ctx)
  1433. ctx.RenderWithErr(ctx.Tr("cloudbrain.load_code_failed"), tplModelArtsTrainJobVersionNew, &form)
  1434. return
  1435. }
  1436. //todo: del local code?
  1437. var parameters models.Parameters
  1438. param := make([]models.Parameter, 0)
  1439. existDeviceTarget := false
  1440. if len(params) != 0 {
  1441. err := json.Unmarshal([]byte(params), &parameters)
  1442. if err != nil {
  1443. log.Error("Failed to Unmarshal params: %s (%v)", params, err)
  1444. trainJobNewVersionDataPrepare(ctx)
  1445. ctx.RenderWithErr("运行参数错误", tplModelArtsTrainJobVersionNew, &form)
  1446. return
  1447. }
  1448. for _, parameter := range parameters.Parameter {
  1449. if parameter.Label == modelarts.DeviceTarget {
  1450. existDeviceTarget = true
  1451. }
  1452. if parameter.Label != modelarts.TrainUrl && parameter.Label != modelarts.DataUrl {
  1453. param = append(param, models.Parameter{
  1454. Label: parameter.Label,
  1455. Value: parameter.Value,
  1456. })
  1457. }
  1458. }
  1459. }
  1460. if !existDeviceTarget {
  1461. param = append(param, models.Parameter{
  1462. Label: modelarts.DeviceTarget,
  1463. Value: modelarts.Ascend,
  1464. })
  1465. }
  1466. datasUrlList, dataUrl, datasetNames, isMultiDataset, err := getDatasUrlListByUUIDS(uuid)
  1467. if err != nil {
  1468. log.Error("Failed to getDatasUrlListByUUIDS: %v", err)
  1469. trainJobNewVersionDataPrepare(ctx)
  1470. ctx.RenderWithErr("Failed to getDatasUrlListByUUIDS:"+err.Error(), tplModelArtsTrainJobVersionNew, &form)
  1471. return
  1472. }
  1473. dataPath := dataUrl
  1474. jsondatas, err := json.Marshal(datasUrlList)
  1475. if err != nil {
  1476. log.Error("Failed to Marshal: %v", err)
  1477. trainJobNewVersionDataPrepare(ctx)
  1478. ctx.RenderWithErr("json error:"+err.Error(), tplModelArtsTrainJobVersionNew, &form)
  1479. return
  1480. }
  1481. if isMultiDataset {
  1482. param = append(param, models.Parameter{
  1483. Label: modelarts.MultiDataUrl,
  1484. Value: string(jsondatas),
  1485. })
  1486. }
  1487. if form.ModelName != "" { //使用预训练模型训练
  1488. ckptUrl := "/" + form.PreTrainModelUrl + form.CkptName
  1489. param = append(param, models.Parameter{
  1490. Label: modelarts.CkptUrl,
  1491. Value: "s3:/" + ckptUrl,
  1492. })
  1493. }
  1494. task, err := models.GetCloudbrainByJobIDAndVersionName(jobID, PreVersionName)
  1495. if err != nil {
  1496. log.Error("GetCloudbrainByJobIDAndVersionName(%s) failed:%v", jobID, err.Error())
  1497. ctx.RenderWithErr(err.Error(), tplModelArtsTrainJobVersionNew, &form)
  1498. return
  1499. }
  1500. req := &modelarts.GenerateTrainJobReq{
  1501. JobName: jobName,
  1502. DisplayJobName: displayJobName,
  1503. DataUrl: dataPath,
  1504. Description: description,
  1505. CodeObsPath: codeObsPath,
  1506. BootFileUrl: codeObsPath + bootFile,
  1507. BootFile: bootFile,
  1508. TrainUrl: outputObsPath,
  1509. WorkServerNumber: workServerNumber,
  1510. IsLatestVersion: isLatestVersion,
  1511. EngineID: int64(engineID),
  1512. LogUrl: logObsPath,
  1513. PoolID: poolID,
  1514. Uuid: uuid,
  1515. Params: form.Params,
  1516. Parameters: param,
  1517. PreVersionId: task.VersionID,
  1518. CommitID: commitID,
  1519. BranchName: branchName,
  1520. FlavorName: FlavorName,
  1521. EngineName: EngineName,
  1522. PreVersionName: PreVersionName,
  1523. TotalVersionCount: latestTask.TotalVersionCount + 1,
  1524. DatasetName: datasetNames,
  1525. Spec: spec,
  1526. }
  1527. if form.ModelName != "" { //使用预训练模型训练
  1528. req.ModelName = form.ModelName
  1529. req.LabelName = form.LabelName
  1530. req.CkptName = form.CkptName
  1531. req.ModelVersion = form.ModelVersion
  1532. req.PreTrainModelUrl = form.PreTrainModelUrl
  1533. }
  1534. userCommand, userImageUrl := getUserCommand(engineID, req)
  1535. req.UserCommand = userCommand
  1536. req.UserImageUrl = userImageUrl
  1537. err = modelarts.GenerateTrainJobVersion(ctx, req, jobID)
  1538. if err != nil {
  1539. log.Error("GenerateTrainJob failed:%v", err.Error())
  1540. trainJobNewVersionDataPrepare(ctx)
  1541. ctx.RenderWithErr(err.Error(), tplModelArtsTrainJobVersionNew, &form)
  1542. return
  1543. }
  1544. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/train-job/" + jobID)
  1545. // ctx.HTML(http.StatusOK, tplModelArtsTrainJobShow)
  1546. }
  1547. // readDir reads the directory named by dirname and returns
  1548. // a list of directory entries sorted by filename.
  1549. func readDir(dirname string) ([]os.FileInfo, error) {
  1550. f, err := os.Open(dirname)
  1551. if err != nil {
  1552. return nil, err
  1553. }
  1554. list, err := f.Readdir(0)
  1555. f.Close()
  1556. if err != nil {
  1557. //todo: can not upload empty folder
  1558. if err == io.EOF {
  1559. return nil, nil
  1560. }
  1561. return nil, err
  1562. }
  1563. //sort.Slice(list, func(i, j int) bool { return list[i].Name() < list[j].Name() })
  1564. return list, nil
  1565. }
  1566. func uploadCodeToObs(codePath, jobName, parentDir string) error {
  1567. files, err := readDir(codePath)
  1568. if err != nil {
  1569. log.Error("readDir(%s) failed: %s", codePath, err.Error())
  1570. return err
  1571. }
  1572. for _, file := range files {
  1573. if file.IsDir() {
  1574. input := &obs.PutObjectInput{}
  1575. input.Bucket = setting.Bucket
  1576. input.Key = parentDir + file.Name() + "/"
  1577. _, err = storage.ObsCli.PutObject(input)
  1578. if err != nil {
  1579. log.Error("PutObject(%s) failed: %s", input.Key, err.Error())
  1580. return err
  1581. }
  1582. if err = uploadCodeToObs(codePath+file.Name()+"/", jobName, parentDir+file.Name()+"/"); err != nil {
  1583. log.Error("uploadCodeToObs(%s) failed: %s", file.Name(), err.Error())
  1584. return err
  1585. }
  1586. } else {
  1587. input := &obs.PutFileInput{}
  1588. input.Bucket = setting.Bucket
  1589. input.Key = setting.CodePathPrefix + jobName + "/code/" + parentDir + file.Name()
  1590. input.SourceFile = codePath + file.Name()
  1591. _, err = storage.ObsCli.PutFile(input)
  1592. if err != nil {
  1593. log.Error("PutFile(%s) failed: %s", input.SourceFile, err.Error())
  1594. return err
  1595. }
  1596. }
  1597. }
  1598. return nil
  1599. }
  1600. func obsMkdir(dir string) error {
  1601. input := &obs.PutObjectInput{}
  1602. input.Bucket = setting.Bucket
  1603. input.Key = dir
  1604. _, err := storage.ObsCli.PutObject(input)
  1605. if err != nil {
  1606. log.Error("PutObject(%s) failed: %s", input.Key, err.Error())
  1607. return err
  1608. }
  1609. return nil
  1610. }
  1611. func paramCheckCreateTrainJob(form auth.CreateModelArtsTrainJobForm) error {
  1612. if !strings.HasSuffix(strings.TrimSpace(form.BootFile), ".py") {
  1613. log.Error("the boot file(%s) must be a python file", strings.TrimSpace(form.BootFile))
  1614. return errors.New("启动文件必须是python文件")
  1615. }
  1616. if form.BranchName == "" {
  1617. log.Error("the branch must not be null!", form.BranchName)
  1618. return errors.New("代码分支不能为空!")
  1619. }
  1620. return nil
  1621. }
  1622. func paramCheckCreateInferenceJob(form auth.CreateModelArtsInferenceJobForm) error {
  1623. if !strings.HasSuffix(strings.TrimSpace(form.BootFile), ".py") {
  1624. log.Error("the boot file(%s) must be a python file", strings.TrimSpace(form.BootFile))
  1625. return errors.New("启动文件必须是python文件")
  1626. }
  1627. if form.WorkServerNumber > 2 || form.WorkServerNumber < 1 {
  1628. log.Error("the WorkServerNumber(%d) must be in (1,2)", form.WorkServerNumber)
  1629. return errors.New("计算节点数必须在1-2之间")
  1630. }
  1631. if form.ModelName == "" {
  1632. log.Error("the ModelName(%d) must not be nil", form.ModelName)
  1633. return errors.New("模型名称不能为空")
  1634. }
  1635. if form.ModelVersion == "" {
  1636. log.Error("the ModelVersion(%d) must not be nil", form.ModelVersion)
  1637. return errors.New("模型版本不能为空")
  1638. }
  1639. if form.CkptName == "" {
  1640. log.Error("the CkptName(%d) must not be nil", form.CkptName)
  1641. return errors.New("权重文件不能为空")
  1642. }
  1643. if form.BranchName == "" {
  1644. log.Error("the Branch(%d) must not be nil", form.BranchName)
  1645. return errors.New("分支名不能为空")
  1646. }
  1647. if utf8.RuneCountInString(form.Description) > 255 {
  1648. log.Error("the Description length(%d) must not more than 255", form.Description)
  1649. return errors.New("描述字符不能超过255个字符")
  1650. }
  1651. return nil
  1652. }
  1653. func TrainJobShow(ctx *context.Context) {
  1654. ctx.Data["PageIsCloudBrain"] = true
  1655. var jobID = ctx.Params(":jobid")
  1656. repo := ctx.Repo.Repository
  1657. page := ctx.QueryInt("page")
  1658. if page <= 0 {
  1659. page = 1
  1660. }
  1661. var jobTypes []string
  1662. jobTypes = append(jobTypes, string(models.JobTypeTrain))
  1663. VersionListTasks, VersionListCount, err := models.CloudbrainsVersionList(&models.CloudbrainsOptions{
  1664. ListOptions: models.ListOptions{
  1665. Page: page,
  1666. PageSize: setting.UI.IssuePagingNum,
  1667. },
  1668. RepoID: repo.ID,
  1669. Type: models.TypeCloudBrainTwo,
  1670. JobTypes: jobTypes,
  1671. JobID: jobID,
  1672. })
  1673. if err != nil {
  1674. log.Error("GetVersionListTasks(%s) failed:%v", jobID, err.Error())
  1675. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  1676. return
  1677. }
  1678. if len(VersionListTasks) == 0 {
  1679. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  1680. return
  1681. }
  1682. //设置权限
  1683. canNewJob, err := canUserCreateTrainJobVersion(ctx, VersionListTasks[0].UserID)
  1684. if err != nil {
  1685. ctx.ServerError("canNewJob failed", err)
  1686. return
  1687. }
  1688. ctx.Data["canNewJob"] = canNewJob
  1689. datasetList := make([][]*models.DatasetDownload, 0)
  1690. //将运行参数转化为epoch_size = 3, device_target = Ascend的格式
  1691. for i, task := range VersionListTasks {
  1692. var parameters models.Parameters
  1693. err := json.Unmarshal([]byte(VersionListTasks[i].Parameters), &parameters)
  1694. if err != nil {
  1695. log.Error("Failed to Unmarshal Parameters: %s (%v)", VersionListTasks[i].Parameters, err)
  1696. trainJobNewDataPrepare(ctx)
  1697. return
  1698. }
  1699. if len(parameters.Parameter) > 0 {
  1700. paramTemp := ""
  1701. for _, Parameter := range parameters.Parameter {
  1702. param := Parameter.Label + " = " + Parameter.Value + "; "
  1703. paramTemp = paramTemp + param
  1704. }
  1705. VersionListTasks[i].Parameters = paramTemp[:len(paramTemp)-2]
  1706. } else {
  1707. VersionListTasks[i].Parameters = ""
  1708. }
  1709. datasetList = append(datasetList, GetCloudBrainDataSetInfo(task.Uuid, task.DatasetName, false))
  1710. VersionListTasks[i].CanDel = cloudbrain.CanDeleteJob(ctx, &task.Cloudbrain)
  1711. VersionListTasks[i].CanModify = cloudbrain.CanModifyJob(ctx, &task.Cloudbrain)
  1712. VersionListTasks[i].ContainerIp = ""
  1713. //add spec
  1714. s, err := resource.GetCloudbrainSpec(task.Cloudbrain.ID)
  1715. if err != nil {
  1716. log.Error("TrainJobShow GetCloudbrainSpec error:" + err.Error())
  1717. continue
  1718. }
  1719. VersionListTasks[i].Cloudbrain.Spec = s
  1720. }
  1721. pager := context.NewPagination(VersionListCount, setting.UI.IssuePagingNum, page, 5)
  1722. pager.SetDefaultParams(ctx)
  1723. ctx.Data["Page"] = pager
  1724. ctx.Data["jobID"] = jobID
  1725. ctx.Data["displayJobName"] = VersionListTasks[0].DisplayJobName
  1726. ctx.Data["version_list_task"] = VersionListTasks
  1727. ctx.Data["version_list_count"] = VersionListCount
  1728. ctx.Data["datasetList"] = datasetList
  1729. ctx.Data["canDownload"] = cloudbrain.CanModifyJob(ctx, &VersionListTasks[0].Cloudbrain)
  1730. ctx.HTML(http.StatusOK, tplModelArtsTrainJobShow)
  1731. }
  1732. func TrainJobDel(ctx *context.Context) {
  1733. var jobID = ctx.Params(":jobid")
  1734. var listType = ctx.Query("listType")
  1735. repo := ctx.Repo.Repository
  1736. var jobTypes []string
  1737. jobTypes = append(jobTypes, string(models.JobTypeTrain))
  1738. VersionListTasks, _, err := models.CloudbrainsVersionList(&models.CloudbrainsOptions{
  1739. RepoID: repo.ID,
  1740. Type: models.TypeCloudBrainTwo,
  1741. JobTypes: jobTypes,
  1742. JobID: jobID,
  1743. })
  1744. if err != nil {
  1745. ctx.ServerError("get VersionListTasks failed", err)
  1746. return
  1747. }
  1748. for _, task := range VersionListTasks {
  1749. if task.Status != string(models.ModelArtsTrainJobImageFailed) && task.Status != string(models.ModelArtsTrainJobSubmitFailed) && task.Status != string(models.ModelArtsTrainJobDeleteFailed) &&
  1750. task.Status != string(models.ModelArtsTrainJobCompleted) && task.Status != string(models.ModelArtsTrainJobFailed) &&
  1751. task.Status != string(models.ModelArtsTrainJobKilled) && task.Status != string(models.ModelArtsTrainJobCanceled) && task.Status != string(models.ModelArtsTrainJobLost) {
  1752. log.Error("the job(%s) version has not been stopped", task.JobName)
  1753. ctx.RenderWithErr("the job version has not been stopped", tplModelArtsTrainJobIndex, nil)
  1754. return
  1755. }
  1756. }
  1757. //删除modelarts上的任务记录
  1758. _, err = modelarts.DelTrainJob(jobID)
  1759. if err != nil {
  1760. log.Error("DelTrainJob(%s) failed:%v", jobID, err.Error())
  1761. ctx.RenderWithErr(err.Error(), tplModelArtsTrainJobIndex, nil)
  1762. return
  1763. }
  1764. //删除数据库Cloudbrain表的记录
  1765. for _, task := range VersionListTasks {
  1766. err = models.DeleteJob(&task.Cloudbrain)
  1767. if err != nil {
  1768. ctx.ServerError("DeleteJob failed", err)
  1769. return
  1770. }
  1771. }
  1772. //删除存储
  1773. if len(VersionListTasks) > 0 {
  1774. DeleteJobStorage(VersionListTasks[0].JobName)
  1775. }
  1776. var isAdminPage = ctx.Query("isadminpage")
  1777. var isHomePage = ctx.Query("ishomepage")
  1778. if ctx.IsUserSiteAdmin() && isAdminPage == "true" {
  1779. ctx.Redirect(setting.AppSubURL + "/admin" + "/cloudbrains")
  1780. } else if isHomePage == "true" {
  1781. ctx.Redirect(setting.AppSubURL + "/cloudbrains")
  1782. } else {
  1783. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/train-job?listType=" + listType)
  1784. }
  1785. }
  1786. func TrainJobStop(ctx *context.Context) {
  1787. var jobID = ctx.Params(":jobid")
  1788. var listType = ctx.Query("listType")
  1789. task := ctx.Cloudbrain
  1790. _, err := modelarts.StopTrainJob(jobID, strconv.FormatInt(task.VersionID, 10))
  1791. if err != nil {
  1792. log.Error("StopTrainJob(%s) failed:%v", task.JobName, err.Error())
  1793. ctx.RenderWithErr(err.Error(), tplModelArtsTrainJobIndex, nil)
  1794. return
  1795. }
  1796. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/train-job?listType=" + listType)
  1797. }
  1798. func canUserCreateTrainJobVersion(ctx *context.Context, userID int64) (bool, error) {
  1799. if ctx == nil || ctx.User == nil {
  1800. log.Error("user unlogin!")
  1801. return false, nil
  1802. }
  1803. if userID == ctx.User.ID || ctx.User.IsAdmin {
  1804. return true, nil
  1805. } else {
  1806. log.Error("Only user itself and admin can new trainjob!")
  1807. return false, nil
  1808. }
  1809. }
  1810. func TrainJobGetConfigList(ctx *context.Context) {
  1811. ctx.Data["PageIsTrainJob"] = true
  1812. var jobID = ctx.Params(":jobid")
  1813. var logFileName = ctx.Query("file_name")
  1814. var baseLine = ctx.Query("base_line")
  1815. var order = ctx.Query("order")
  1816. if order != modelarts.OrderDesc && order != modelarts.OrderAsc {
  1817. log.Error("order(%s) check failed", order)
  1818. ctx.HTML(http.StatusBadRequest, tplModelArtsTrainJobShow)
  1819. return
  1820. }
  1821. task, err := models.GetCloudbrainByJobID(jobID)
  1822. if err != nil {
  1823. log.Error("GetCloudbrainByJobID(%s) failed:%v", jobID, err.Error())
  1824. ctx.RenderWithErr(err.Error(), tplModelArtsTrainJobShow, nil)
  1825. return
  1826. }
  1827. result, err := modelarts.GetTrainJobLog(jobID, strconv.FormatInt(task.VersionID, 10), baseLine, logFileName, order, modelarts.Lines)
  1828. if err != nil {
  1829. log.Error("GetTrainJobLog(%s) failed:%v", jobID, err.Error())
  1830. ctx.RenderWithErr(err.Error(), tplModelArtsTrainJobShow, nil)
  1831. return
  1832. }
  1833. ctx.Data["log"] = result
  1834. //ctx.HTML(http.StatusOK, tplModelArtsTrainJobShow)
  1835. }
  1836. func getConfigList(perPage, page int, sortBy, order, searchContent, configType string) (*models.GetConfigListResult, error) {
  1837. var result models.GetConfigListResult
  1838. list, err := modelarts.GetConfigList(perPage, page, sortBy, order, searchContent, configType)
  1839. if err != nil {
  1840. log.Error("GetConfigList failed:", err)
  1841. return &result, err
  1842. }
  1843. for _, config := range list.ParaConfigs {
  1844. paraConfig, err := modelarts.GetParaConfig(config.ConfigName, configType)
  1845. if err != nil {
  1846. log.Error("GetParaConfig failed:", err)
  1847. return &result, err
  1848. }
  1849. config.Result = paraConfig
  1850. }
  1851. return list, nil
  1852. }
  1853. func InferenceJobCreate(ctx *context.Context, form auth.CreateModelArtsInferenceJobForm) {
  1854. ctx.Data["PageIsTrainJob"] = true
  1855. VersionOutputPath := modelarts.GetOutputPathByCount(modelarts.TotalVersionCount)
  1856. displayJobName := form.DisplayJobName
  1857. jobName := util.ConvertDisplayJobNameToJobName(displayJobName)
  1858. uuid := form.Attachment
  1859. description := form.Description
  1860. workServerNumber := form.WorkServerNumber
  1861. engineID := form.EngineID
  1862. bootFile := strings.TrimSpace(form.BootFile)
  1863. params := form.Params
  1864. poolID := form.PoolID
  1865. repo := ctx.Repo.Repository
  1866. codeLocalPath := setting.JobPath + jobName + modelarts.CodePath
  1867. codeObsPath := "/" + setting.Bucket + modelarts.JobPath + jobName + modelarts.CodePath
  1868. resultObsPath := "/" + setting.Bucket + modelarts.JobPath + jobName + modelarts.ResultPath + VersionOutputPath + "/"
  1869. logObsPath := "/" + setting.Bucket + modelarts.JobPath + jobName + modelarts.LogPath + VersionOutputPath + "/"
  1870. //dataPath := "/" + setting.Bucket + "/" + setting.BasePath + path.Join(uuid[0:1], uuid[1:2]) + "/" + uuid + uuid + "/"
  1871. branchName := form.BranchName
  1872. FlavorName := form.FlavorName
  1873. EngineName := form.EngineName
  1874. LabelName := form.LabelName
  1875. isLatestVersion := modelarts.IsLatestVersion
  1876. VersionCount := modelarts.VersionCountOne
  1877. trainUrl := form.TrainUrl
  1878. modelName := form.ModelName
  1879. modelVersion := form.ModelVersion
  1880. ckptName := form.CkptName
  1881. ckptUrl := "/" + form.TrainUrl + form.CkptName
  1882. log.Info("ckpt url:" + ckptUrl)
  1883. errStr := checkInferenceJobMultiNode(ctx.User.ID, form.WorkServerNumber)
  1884. if errStr != "" {
  1885. inferenceJobErrorNewDataPrepare(ctx, form)
  1886. ctx.RenderWithErr(ctx.Tr(errStr), tplModelArtsInferenceJobNew, &form)
  1887. return
  1888. }
  1889. lockOperator, errMsg := cloudbrainService.Lock4CloudbrainCreation(&lock.LockContext{Repo: ctx.Repo.Repository, Task: &models.Cloudbrain{DisplayJobName: displayJobName, JobType: string(models.JobTypeInference)}, User: ctx.User})
  1890. defer func() {
  1891. if lockOperator != nil {
  1892. lockOperator.Unlock()
  1893. }
  1894. }()
  1895. if errMsg != "" {
  1896. log.Error("lock processed failed:%s", errMsg, ctx.Data["MsgID"])
  1897. inferenceJobErrorNewDataPrepare(ctx, form)
  1898. ctx.RenderWithErr(ctx.Tr(errMsg), tplModelArtsInferenceJobNew, &form)
  1899. return
  1900. }
  1901. count, err := cloudbrainTask.GetNotFinalStatusTaskCount(ctx.User.ID, models.TypeCloudBrainTwo, string(models.JobTypeInference))
  1902. if err != nil {
  1903. log.Error("GetCloudbrainInferenceJobCountByUserID failed:%v", err, ctx.Data["MsgID"])
  1904. inferenceJobErrorNewDataPrepare(ctx, form)
  1905. ctx.RenderWithErr("system error", tplModelArtsInferenceJobNew, &form)
  1906. return
  1907. } else {
  1908. if count >= 1 {
  1909. log.Error("the user already has running or waiting inference task", ctx.Data["MsgID"])
  1910. inferenceJobErrorNewDataPrepare(ctx, form)
  1911. ctx.RenderWithErr("you have already a running or waiting inference task, can not create more", tplModelArtsInferenceJobNew, &form)
  1912. return
  1913. }
  1914. }
  1915. if err := paramCheckCreateInferenceJob(form); err != nil {
  1916. log.Error("paramCheckCreateInferenceJob failed:(%v)", err)
  1917. inferenceJobErrorNewDataPrepare(ctx, form)
  1918. ctx.RenderWithErr(err.Error(), tplModelArtsInferenceJobNew, &form)
  1919. return
  1920. }
  1921. bootFileExist, err := ctx.Repo.FileExists(bootFile, branchName)
  1922. if err != nil || !bootFileExist {
  1923. log.Error("Get bootfile error:", err)
  1924. inferenceJobErrorNewDataPrepare(ctx, form)
  1925. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_bootfile_err"), tplModelArtsInferenceJobNew, &form)
  1926. return
  1927. }
  1928. //Determine whether the task name of the task in the project is duplicated
  1929. tasks, err := models.GetCloudbrainsByDisplayJobName(repo.ID, string(models.JobTypeInference), displayJobName)
  1930. if err == nil {
  1931. if len(tasks) != 0 {
  1932. log.Error("the job name did already exist", ctx.Data["MsgID"])
  1933. inferenceJobErrorNewDataPrepare(ctx, form)
  1934. ctx.RenderWithErr("the job name did already exist", tplModelArtsInferenceJobNew, &form)
  1935. return
  1936. }
  1937. } else {
  1938. if !models.IsErrJobNotExist(err) {
  1939. log.Error("system error, %v", err, ctx.Data["MsgID"])
  1940. inferenceJobErrorNewDataPrepare(ctx, form)
  1941. ctx.RenderWithErr("system error", tplModelArtsInferenceJobNew, &form)
  1942. return
  1943. }
  1944. }
  1945. spec, err := resource.GetAndCheckSpec(ctx.User.ID, form.SpecId, models.FindSpecsOptions{
  1946. JobType: models.JobTypeInference,
  1947. ComputeResource: models.NPU,
  1948. Cluster: models.OpenICluster,
  1949. AiCenterCode: models.AICenterOfCloudBrainTwo})
  1950. if err != nil || spec == nil {
  1951. inferenceJobErrorNewDataPrepare(ctx, form)
  1952. ctx.RenderWithErr("Resource specification not available", tplModelArtsInferenceJobNew, &form)
  1953. return
  1954. }
  1955. if !account.IsPointBalanceEnough(ctx.User.ID, spec.UnitPrice) {
  1956. log.Error("point balance is not enough,userId=%d specId=%d ", ctx.User.ID, spec.ID)
  1957. inferenceJobErrorNewDataPrepare(ctx, form)
  1958. ctx.RenderWithErr(ctx.Tr("points.insufficient_points_balance"), tplModelArtsInferenceJobNew, &form)
  1959. return
  1960. }
  1961. //todo: del the codeLocalPath
  1962. _, err = ioutil.ReadDir(codeLocalPath)
  1963. if err == nil {
  1964. os.RemoveAll(codeLocalPath)
  1965. }
  1966. gitRepo, _ := git.OpenRepository(repo.RepoPath())
  1967. commitID, _ := gitRepo.GetBranchCommitID(branchName)
  1968. if err := downloadCode(repo, codeLocalPath, branchName); err != nil {
  1969. log.Error("Create task failed, server timed out: %s (%v)", repo.FullName(), err)
  1970. inferenceJobErrorNewDataPrepare(ctx, form)
  1971. ctx.RenderWithErr(ctx.Tr("cloudbrain.load_code_failed"), tplModelArtsInferenceJobNew, &form)
  1972. return
  1973. }
  1974. //todo: upload code (send to file_server todo this work?)
  1975. if err := obsMkdir(setting.CodePathPrefix + jobName + modelarts.ResultPath + VersionOutputPath + "/"); err != nil {
  1976. log.Error("Failed to obsMkdir_result: %s (%v)", repo.FullName(), err)
  1977. inferenceJobErrorNewDataPrepare(ctx, form)
  1978. ctx.RenderWithErr("Failed to obsMkdir_result", tplModelArtsInferenceJobNew, &form)
  1979. return
  1980. }
  1981. if err := obsMkdir(setting.CodePathPrefix + jobName + modelarts.LogPath + VersionOutputPath + "/"); err != nil {
  1982. log.Error("Failed to obsMkdir_log: %s (%v)", repo.FullName(), err)
  1983. inferenceJobErrorNewDataPrepare(ctx, form)
  1984. ctx.RenderWithErr("Failed to obsMkdir_log", tplModelArtsInferenceJobNew, &form)
  1985. return
  1986. }
  1987. if err := uploadCodeToObs(codeLocalPath, jobName, ""); err != nil {
  1988. log.Error("Failed to uploadCodeToObs: %s (%v)", repo.FullName(), err)
  1989. inferenceJobErrorNewDataPrepare(ctx, form)
  1990. ctx.RenderWithErr(ctx.Tr("cloudbrain.load_code_failed"), tplModelArtsInferenceJobNew, &form)
  1991. return
  1992. }
  1993. var parameters models.Parameters
  1994. param := make([]models.Parameter, 0)
  1995. param = append(param, models.Parameter{
  1996. Label: modelarts.ResultUrl,
  1997. Value: "s3:/" + resultObsPath,
  1998. }, models.Parameter{
  1999. Label: modelarts.CkptUrl,
  2000. Value: "s3:/" + ckptUrl,
  2001. })
  2002. datasUrlList, dataUrl, datasetNames, isMultiDataset, err := getDatasUrlListByUUIDS(uuid)
  2003. if err != nil {
  2004. inferenceJobErrorNewDataPrepare(ctx, form)
  2005. ctx.RenderWithErr(err.Error(), tplModelArtsInferenceJobNew, &form)
  2006. return
  2007. }
  2008. dataPath := dataUrl
  2009. jsondatas, err := json.Marshal(datasUrlList)
  2010. if err != nil {
  2011. log.Error("Failed to Marshal: %v", err)
  2012. inferenceJobErrorNewDataPrepare(ctx, form)
  2013. ctx.RenderWithErr("json error:"+err.Error(), tplModelArtsInferenceJobNew, &form)
  2014. return
  2015. }
  2016. if isMultiDataset {
  2017. param = append(param, models.Parameter{
  2018. Label: modelarts.MultiDataUrl,
  2019. Value: string(jsondatas),
  2020. })
  2021. }
  2022. existDeviceTarget := false
  2023. if len(params) != 0 {
  2024. err := json.Unmarshal([]byte(params), &parameters)
  2025. if err != nil {
  2026. log.Error("Failed to Unmarshal params: %s (%v)", params, err)
  2027. inferenceJobErrorNewDataPrepare(ctx, form)
  2028. ctx.RenderWithErr("运行参数错误", tplModelArtsInferenceJobNew, &form)
  2029. return
  2030. }
  2031. for _, parameter := range parameters.Parameter {
  2032. if parameter.Label == modelarts.DeviceTarget {
  2033. existDeviceTarget = true
  2034. }
  2035. if parameter.Label != modelarts.TrainUrl && parameter.Label != modelarts.DataUrl {
  2036. param = append(param, models.Parameter{
  2037. Label: parameter.Label,
  2038. Value: parameter.Value,
  2039. })
  2040. }
  2041. }
  2042. }
  2043. if !existDeviceTarget {
  2044. param = append(param, models.Parameter{
  2045. Label: modelarts.DeviceTarget,
  2046. Value: modelarts.Ascend,
  2047. })
  2048. }
  2049. req := &modelarts.GenerateInferenceJobReq{
  2050. JobName: jobName,
  2051. DisplayJobName: displayJobName,
  2052. DataUrl: dataPath,
  2053. Description: description,
  2054. CodeObsPath: codeObsPath,
  2055. BootFileUrl: codeObsPath + bootFile,
  2056. BootFile: bootFile,
  2057. TrainUrl: trainUrl,
  2058. WorkServerNumber: workServerNumber,
  2059. EngineID: int64(engineID),
  2060. LogUrl: logObsPath,
  2061. PoolID: poolID,
  2062. Uuid: uuid,
  2063. Parameters: param, //modelarts train parameters
  2064. CommitID: commitID,
  2065. BranchName: branchName,
  2066. Params: form.Params,
  2067. FlavorName: FlavorName,
  2068. EngineName: EngineName,
  2069. LabelName: LabelName,
  2070. IsLatestVersion: isLatestVersion,
  2071. VersionCount: VersionCount,
  2072. TotalVersionCount: modelarts.TotalVersionCount,
  2073. ModelName: modelName,
  2074. ModelVersion: modelVersion,
  2075. CkptName: ckptName,
  2076. ResultUrl: resultObsPath,
  2077. Spec: spec,
  2078. DatasetName: datasetNames,
  2079. JobType: string(models.JobTypeInference),
  2080. }
  2081. userCommand, userImageUrl := getInfJobUserCommand(engineID, req)
  2082. req.UserCommand = userCommand
  2083. req.UserImageUrl = userImageUrl
  2084. _, err = modelarts.GenerateInferenceJob(ctx, req)
  2085. if err != nil {
  2086. log.Error("GenerateTrainJob failed:%v", err.Error())
  2087. inferenceJobErrorNewDataPrepare(ctx, form)
  2088. ctx.RenderWithErr(err.Error(), tplModelArtsInferenceJobNew, &form)
  2089. return
  2090. }
  2091. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/inference-job")
  2092. }
  2093. func checkModelArtsSpecialPool(ctx *context.Context, flavorCode string, jobType string) string {
  2094. if modelarts.SpecialPools != nil {
  2095. isMatchPool := false
  2096. for _, specialPool := range modelarts.SpecialPools.Pools {
  2097. if cloudbrain.IsElementExist(specialPool.JobType, jobType) {
  2098. if isInOrg, _ := models.IsOrganizationMemberByOrgName(specialPool.Org, ctx.User.ID); isInOrg {
  2099. isMatchPool = true
  2100. isMatchSpec := false
  2101. for _, flavor := range specialPool.Flavor {
  2102. if flavor.Value == flavorCode {
  2103. isMatchSpec = true
  2104. break
  2105. }
  2106. }
  2107. if !isMatchSpec {
  2108. return "cloudbrain.wrong_specification"
  2109. }
  2110. }
  2111. }
  2112. }
  2113. if !isMatchPool {
  2114. isMatchSpec := false
  2115. if jobType == string(models.JobTypeDebug) {
  2116. for _, flavor := range setting.StFlavorInfo.FlavorInfo {
  2117. if flavor.Value == flavorCode {
  2118. isMatchSpec = true
  2119. break
  2120. }
  2121. }
  2122. } else {
  2123. var flavorInfos modelarts.Flavor
  2124. json.Unmarshal([]byte(setting.TrainJobFLAVORINFOS), &flavorInfos)
  2125. for _, flavor := range flavorInfos.Info {
  2126. if flavor.Code == flavorCode {
  2127. isMatchSpec = true
  2128. break
  2129. }
  2130. }
  2131. }
  2132. if !isMatchSpec {
  2133. return "cloudbrain.wrong_specification"
  2134. }
  2135. }
  2136. }
  2137. return ""
  2138. }
  2139. func InferenceJobIndex(ctx *context.Context) {
  2140. MustEnableModelArts(ctx)
  2141. repo := ctx.Repo.Repository
  2142. page := ctx.QueryInt("page")
  2143. if page <= 0 {
  2144. page = 1
  2145. }
  2146. listType := ctx.Query("listType")
  2147. ctx.Data["ListType"] = listType
  2148. if listType == models.AllResource {
  2149. listType = ""
  2150. }
  2151. var jobTypes []string
  2152. jobTypes = append(jobTypes, string(models.JobTypeInference))
  2153. tasks, count, err := models.Cloudbrains(&models.CloudbrainsOptions{
  2154. ListOptions: models.ListOptions{
  2155. Page: page,
  2156. PageSize: setting.UI.IssuePagingNum,
  2157. },
  2158. RepoID: repo.ID,
  2159. ComputeResource: listType,
  2160. JobTypes: jobTypes,
  2161. Type: models.TypeCloudBrainAll,
  2162. })
  2163. if err != nil {
  2164. ctx.ServerError("Cloudbrain", err)
  2165. return
  2166. }
  2167. for i, task := range tasks {
  2168. tasks[i].CanDel = cloudbrain.CanDeleteJob(ctx, &task.Cloudbrain)
  2169. tasks[i].CanModify = cloudbrain.CanModifyJob(ctx, &task.Cloudbrain)
  2170. if tasks[i].ComputeResource == "" {
  2171. tasks[i].ComputeResource = models.NPUResource
  2172. }
  2173. }
  2174. isQueryPrivate := isQueryPrivateModel(ctx)
  2175. repoId := ctx.Repo.Repository.ID
  2176. Type := -1
  2177. _, model_count, _ := models.QueryModel(&models.AiModelQueryOptions{
  2178. ListOptions: models.ListOptions{
  2179. Page: 1,
  2180. PageSize: 2,
  2181. },
  2182. RepoID: repoId,
  2183. Type: Type,
  2184. New: MODEL_LATEST,
  2185. IsOnlyThisRepo: true,
  2186. Status: 0,
  2187. IsQueryPrivate: isQueryPrivate,
  2188. })
  2189. ctx.Data["MODEL_COUNT"] = model_count
  2190. pager := context.NewPagination(int(count), setting.UI.IssuePagingNum, page, 5)
  2191. pager.SetDefaultParams(ctx)
  2192. ctx.Data["Page"] = pager
  2193. ctx.Data["PageIsCloudBrain"] = true
  2194. ctx.Data["Tasks"] = tasks
  2195. ctx.Data["CanCreate"] = cloudbrain.CanCreateOrDebugJob(ctx)
  2196. ctx.Data["RepoIsEmpty"] = repo.IsEmpty
  2197. ctx.HTML(200, tplModelArtsInferenceJobIndex)
  2198. }
  2199. func InferenceJobNew(ctx *context.Context) {
  2200. err := inferenceJobNewDataPrepare(ctx)
  2201. if err != nil {
  2202. ctx.ServerError("get new inference-job info failed", err)
  2203. return
  2204. }
  2205. ctx.HTML(200, tplModelArtsInferenceJobNew)
  2206. }
  2207. func inferenceJobNewDataPrepare(ctx *context.Context) error {
  2208. ctx.Data["PageIsCloudBrain"] = true
  2209. ctx.Data["newInference"] = true
  2210. var displayJobName = cloudbrainService.GetDisplayJobName(ctx.User.Name)
  2211. ctx.Data["display_job_name"] = displayJobName
  2212. attachs, err := models.GetModelArtsTrainAttachments(ctx.User.ID)
  2213. if err != nil {
  2214. ctx.ServerError("GetAllUserAttachments failed:", err)
  2215. return err
  2216. }
  2217. ctx.Data["attachments"] = attachs
  2218. var resourcePools modelarts.ResourcePool
  2219. if err = json.Unmarshal([]byte(setting.ResourcePools), &resourcePools); err != nil {
  2220. ctx.ServerError("json.Unmarshal failed:", err)
  2221. return err
  2222. }
  2223. ctx.Data["resource_pools"] = resourcePools.Info
  2224. var engines modelarts.Engine
  2225. if err = json.Unmarshal([]byte(setting.Engines), &engines); err != nil {
  2226. ctx.ServerError("json.Unmarshal failed:", err)
  2227. return err
  2228. }
  2229. ctx.Data["engines"] = engines.Info
  2230. var versionInfos modelarts.VersionInfo
  2231. if err = json.Unmarshal([]byte(setting.EngineVersions), &versionInfos); err != nil {
  2232. ctx.ServerError("json.Unmarshal failed:", err)
  2233. return err
  2234. }
  2235. ctx.Data["engine_versions"] = versionInfos.Version
  2236. prepareCloudbrainTwoInferenceSpecs(ctx)
  2237. ctx.Data["params"] = ""
  2238. ctx.Data["branchName"] = ctx.Repo.BranchName
  2239. configList, err := getConfigList(modelarts.PerPage, 1, modelarts.SortByCreateTime, "desc", "", modelarts.ConfigTypeCustom)
  2240. if err != nil {
  2241. ctx.ServerError("getConfigList failed:", err)
  2242. return err
  2243. }
  2244. ctx.Data["config_list"] = configList.ParaConfigs
  2245. isQueryPrivate := isQueryPrivateModel(ctx)
  2246. repoId := ctx.Repo.Repository.ID
  2247. Type := -1
  2248. _, model_count, _ := models.QueryModel(&models.AiModelQueryOptions{
  2249. ListOptions: models.ListOptions{
  2250. Page: 1,
  2251. PageSize: 2,
  2252. },
  2253. RepoID: repoId,
  2254. Type: Type,
  2255. New: MODEL_LATEST,
  2256. IsOnlyThisRepo: true,
  2257. Status: 0,
  2258. IsQueryPrivate: isQueryPrivate,
  2259. })
  2260. ctx.Data["MODEL_COUNT"] = model_count
  2261. ctx.Data["datasetType"] = models.TypeCloudBrainTwo
  2262. waitCount := cloudbrain.GetWaitingCloudbrainCount(models.TypeCloudBrainTwo, "")
  2263. ctx.Data["WaitCount"] = waitCount
  2264. NotStopTaskCount, _ := cloudbrainTask.GetNotFinalStatusTaskCount(ctx.User.ID, models.TypeCloudBrainTwo, string(models.JobTypeInference))
  2265. ctx.Data["NotStopTaskCount"] = NotStopTaskCount
  2266. return nil
  2267. }
  2268. func prepareCloudbrainTwoInferenceSpecs(ctx *context.Context) {
  2269. noteBookSpecs, _ := resource.FindAvailableSpecs(ctx.User.ID, models.FindSpecsOptions{
  2270. JobType: models.JobTypeInference,
  2271. ComputeResource: models.NPU,
  2272. Cluster: models.OpenICluster,
  2273. AiCenterCode: models.AICenterOfCloudBrainTwo,
  2274. })
  2275. ctx.Data["Specs"] = noteBookSpecs
  2276. }
  2277. func inferenceJobErrorNewDataPrepare(ctx *context.Context, form auth.CreateModelArtsInferenceJobForm) error {
  2278. ctx.Data["PageIsCloudBrain"] = true
  2279. t := time.Now()
  2280. var jobName = "inference" + t.Format("2006010215") + strconv.Itoa(int(t.Unix()))[5:]
  2281. ctx.Data["job_name"] = jobName
  2282. attachs, err := models.GetModelArtsTrainAttachments(ctx.User.ID)
  2283. if err != nil {
  2284. ctx.ServerError("GetAllUserAttachments failed:", err)
  2285. return err
  2286. }
  2287. ctx.Data["attachments"] = attachs
  2288. var resourcePools modelarts.ResourcePool
  2289. if err = json.Unmarshal([]byte(setting.ResourcePools), &resourcePools); err != nil {
  2290. ctx.ServerError("json.Unmarshal failed:", err)
  2291. return err
  2292. }
  2293. ctx.Data["resource_pools"] = resourcePools.Info
  2294. var engines modelarts.Engine
  2295. if err = json.Unmarshal([]byte(setting.Engines), &engines); err != nil {
  2296. ctx.ServerError("json.Unmarshal failed:", err)
  2297. return err
  2298. }
  2299. ctx.Data["engines"] = engines.Info
  2300. var versionInfos modelarts.VersionInfo
  2301. if err = json.Unmarshal([]byte(setting.EngineVersions), &versionInfos); err != nil {
  2302. ctx.ServerError("json.Unmarshal failed:", err)
  2303. return err
  2304. }
  2305. ctx.Data["engine_versions"] = versionInfos.Version
  2306. prepareCloudbrainTwoInferenceSpecs(ctx)
  2307. configList, err := getConfigList(modelarts.PerPage, 1, modelarts.SortByCreateTime, "desc", "", modelarts.ConfigTypeCustom)
  2308. if err != nil {
  2309. ctx.ServerError("getConfigList failed:", err)
  2310. return err
  2311. }
  2312. var Parameters modelarts.Parameters
  2313. if err = json.Unmarshal([]byte(form.Params), &Parameters); err != nil {
  2314. ctx.ServerError("json.Unmarshal failed:", err)
  2315. return err
  2316. }
  2317. ctx.Data["params"] = Parameters.Parameter
  2318. ctx.Data["config_list"] = configList.ParaConfigs
  2319. ctx.Data["bootFile"] = form.BootFile
  2320. ctx.Data["uuid"] = form.Attachment
  2321. _, datasetNames, err := models.GetDatasetInfo(form.Attachment)
  2322. if err != nil {
  2323. log.Error("GetDatasetInfo failed: %v", err, ctx.Data["MsgID"])
  2324. return nil
  2325. }
  2326. ctx.Data["dataset_name"] = datasetNames
  2327. ctx.Data["branch_name"] = form.BranchName
  2328. ctx.Data["model_name"] = form.ModelName
  2329. ctx.Data["model_version"] = form.ModelVersion
  2330. ctx.Data["ckpt_name"] = form.CkptName
  2331. ctx.Data["train_url"] = form.TrainUrl
  2332. ctx.Data["datasetType"] = models.TypeCloudBrainTwo
  2333. waitCount := cloudbrain.GetWaitingCloudbrainCount(models.TypeCloudBrainTwo, "")
  2334. ctx.Data["WaitCount"] = waitCount
  2335. NotStopTaskCount, _ := cloudbrainTask.GetNotFinalStatusTaskCount(ctx.User.ID, models.TypeCloudBrainTwo, string(models.JobTypeInference))
  2336. ctx.Data["NotStopTaskCount"] = NotStopTaskCount
  2337. return nil
  2338. }
  2339. func InferenceJobShow(ctx *context.Context) {
  2340. ctx.Data["PageIsCloudBrain"] = true
  2341. var jobID = ctx.Params(":jobid")
  2342. page := ctx.QueryInt("page")
  2343. if page <= 0 {
  2344. page = 1
  2345. }
  2346. task, err := models.GetCloudbrainByJobID(jobID)
  2347. if err != nil {
  2348. log.Error("GetInferenceTask(%s) failed:%v", jobID, err.Error())
  2349. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  2350. return
  2351. }
  2352. //设置权限
  2353. canNewJob, err := canUserCreateTrainJobVersion(ctx, task.UserID)
  2354. if err != nil {
  2355. ctx.ServerError("canNewJob failed", err)
  2356. return
  2357. }
  2358. ctx.Data["canNewJob"] = canNewJob
  2359. //将运行参数转化为epoch_size = 3, device_target = Ascend的格式
  2360. var parameters models.Parameters
  2361. err = json.Unmarshal([]byte(task.Parameters), &parameters)
  2362. if err != nil {
  2363. log.Error("Failed to Unmarshal Parameters: %s (%v)", task.Parameters, err)
  2364. trainJobNewDataPrepare(ctx)
  2365. return
  2366. }
  2367. if len(parameters.Parameter) > 0 {
  2368. paramTemp := ""
  2369. for _, Parameter := range parameters.Parameter {
  2370. param := Parameter.Label + " = " + Parameter.Value + "; "
  2371. paramTemp = paramTemp + param
  2372. }
  2373. task.Parameters = paramTemp[:len(paramTemp)-2]
  2374. } else {
  2375. task.Parameters = ""
  2376. }
  2377. prepareSpec4Show(ctx, task)
  2378. LabelName := strings.Fields(task.LabelName)
  2379. ctx.Data["labelName"] = LabelName
  2380. ctx.Data["jobID"] = jobID
  2381. ctx.Data["jobName"] = task.JobName
  2382. ctx.Data["displayJobName"] = task.DisplayJobName
  2383. ctx.Data["task"] = task
  2384. ctx.Data["canDownload"] = cloudbrain.CanModifyJob(ctx, task)
  2385. ctx.Data["datasetDownload"] = GetCloudBrainDataSetInfo(task.Uuid, task.DatasetName, false)
  2386. tempUids := []int64{}
  2387. tempUids = append(tempUids, task.UserID)
  2388. JobCreater, err := models.GetUserNamesByIDs(tempUids)
  2389. if err != nil {
  2390. log.Error("GetUserNamesByIDs (WhitelistUserIDs): %v", err)
  2391. }
  2392. ctx.Data["userName"] = JobCreater[0]
  2393. ctx.HTML(http.StatusOK, tplModelArtsInferenceJobShow)
  2394. }
  2395. func MultiModelDownload(ctx *context.Context) {
  2396. var (
  2397. err error
  2398. )
  2399. jobID := ctx.Params(":jobid")
  2400. versionName := ctx.Query("version_name")
  2401. parentDir := ctx.Query("parent_dir")
  2402. task, err := models.GetCloudbrainByJobIDAndVersionName(jobID, versionName)
  2403. if err != nil {
  2404. log.Error("GetCloudbrainByJobIDAndVersionName(%s) failed:%v", task.JobName, err.Error())
  2405. return
  2406. }
  2407. if task.ComputeResource == models.NPUResource {
  2408. path := strings.TrimPrefix(path.Join(setting.TrainJobModelPath, task.JobName, setting.OutPutPath, versionName, parentDir), "/")
  2409. path = strings.TrimSuffix(path, "/")
  2410. path += "/"
  2411. allFile, err := storage.GetAllObjectByBucketAndPrefix(setting.Bucket, path)
  2412. if err == nil {
  2413. returnFileName := task.DisplayJobName + ".zip"
  2414. ObsDownloadManyFile(path, ctx, returnFileName, allFile)
  2415. } else {
  2416. log.Info("error,msg=" + err.Error())
  2417. ctx.ServerError("no file to download.", err)
  2418. }
  2419. } else if task.ComputeResource == models.GPUResource {
  2420. filePath := setting.CBCodePathPrefix + task.JobName + cloudbrain.ModelMountPath + "/" + parentDir
  2421. allFile, err := storage.GetAllObjectByBucketAndPrefixMinio(setting.Attachment.Minio.Bucket, filePath)
  2422. if err == nil {
  2423. returnFileName := task.DisplayJobName + ".zip"
  2424. MinioDownloadManyFile(filePath, ctx, returnFileName, allFile)
  2425. } else {
  2426. log.Info("error,msg=" + err.Error())
  2427. ctx.ServerError("no file to download.", err)
  2428. }
  2429. }
  2430. }
  2431. func ModelDownload(ctx *context.Context) {
  2432. var (
  2433. err error
  2434. )
  2435. jobID := ctx.Params(":jobid")
  2436. versionName := ctx.Query("version_name")
  2437. parentDir := ctx.Query("parent_dir")
  2438. fileName := ctx.Query("file_name")
  2439. task, err := models.GetCloudbrainByJobIDAndVersionName(jobID, versionName)
  2440. if err != nil {
  2441. log.Error("GetCloudbrainByJobIDAndVersionName(%s) failed:%v", task.JobName, err.Error())
  2442. return
  2443. }
  2444. var url string
  2445. if task.ComputeResource == models.NPUResource {
  2446. path := strings.TrimPrefix(path.Join(setting.TrainJobModelPath, task.JobName, setting.OutPutPath, versionName, parentDir, fileName), "/")
  2447. url, err = storage.GetObsCreateSignedUrlByBucketAndKey(setting.Bucket, path)
  2448. if err != nil {
  2449. log.Error("GetObsCreateSignedUrl failed: %v", err.Error(), ctx.Data["msgID"])
  2450. ctx.ServerError("GetObsCreateSignedUrl", err)
  2451. return
  2452. }
  2453. } else if task.ComputeResource == models.GPUResource {
  2454. filePath := setting.CBCodePathPrefix + task.JobName + cloudbrain.ModelMountPath + "/" + parentDir
  2455. url, err = storage.Attachments.PresignedGetURL(filePath, fileName)
  2456. if err != nil {
  2457. log.Error("PresignedGetURL failed: %v", err.Error(), ctx.Data["msgID"])
  2458. ctx.ServerError("PresignedGetURL", err)
  2459. return
  2460. }
  2461. }
  2462. ctx.Resp.Header().Set("Cache-Control", "max-age=0")
  2463. http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusMovedPermanently)
  2464. }
  2465. func ResultDownload(ctx *context.Context) {
  2466. var (
  2467. err error
  2468. )
  2469. versionName := ctx.Query("version_name")
  2470. parentDir := ctx.Query("parent_dir")
  2471. fileName := ctx.Query("file_name")
  2472. task := ctx.Cloudbrain
  2473. if err != nil {
  2474. ctx.Data["error"] = err.Error()
  2475. }
  2476. path := strings.TrimPrefix(path.Join(setting.TrainJobModelPath, task.JobName, "result/", versionName, parentDir, fileName), "/")
  2477. url, err := storage.GetObsCreateSignedUrlByBucketAndKey(setting.Bucket, path)
  2478. if err != nil {
  2479. log.Error("GetObsCreateSignedUrl failed: %v", err.Error(), ctx.Data["msgID"])
  2480. ctx.ServerError("GetObsCreateSignedUrl", err)
  2481. return
  2482. }
  2483. ctx.Resp.Header().Set("Cache-Control", "max-age=0")
  2484. http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusMovedPermanently)
  2485. }
  2486. func DeleteJobStorage(jobName string) error {
  2487. //delete local
  2488. localJobPath := setting.JobPath + jobName
  2489. err := os.RemoveAll(localJobPath)
  2490. if err != nil {
  2491. log.Error("RemoveAll(%s) failed:%v", localJobPath, err)
  2492. }
  2493. //delete oss
  2494. dirPath := setting.CodePathPrefix + jobName + "/"
  2495. err = storage.ObsRemoveObject(setting.Bucket, dirPath)
  2496. if err != nil {
  2497. log.Error("ObsRemoveObject(%s) failed:%v", localJobPath, err)
  2498. }
  2499. return nil
  2500. }
  2501. func DownloadMultiResultFile(ctx *context.Context) {
  2502. var jobID = ctx.Params(":jobid")
  2503. var versionName = ctx.Query("version_name")
  2504. task, err := models.GetCloudbrainByJobIDAndVersionName(jobID, versionName)
  2505. if err != nil {
  2506. log.Error("GetCloudbrainByJobID(%s) failed:%v", task.JobName, err.Error())
  2507. return
  2508. }
  2509. // if !isCanDeleteOrDownload(ctx, task) {
  2510. // ctx.ServerError("no right.", errors.New(ctx.Tr("repo.model_noright")))
  2511. // return
  2512. // }
  2513. // path := Model_prefix + models.AttachmentRelativePath(id) + "/"
  2514. path := strings.TrimPrefix(path.Join(setting.TrainJobModelPath, task.JobName, "result/", versionName), "/") + "/"
  2515. allFile, err := storage.GetAllObjectByBucketAndPrefix(setting.Bucket, path)
  2516. if err == nil {
  2517. //count++
  2518. // models.ModifyModelDownloadCount(id)
  2519. returnFileName := task.DisplayJobName + ".zip"
  2520. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+returnFileName)
  2521. ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
  2522. w := zip.NewWriter(ctx.Resp)
  2523. defer w.Close()
  2524. for _, oneFile := range allFile {
  2525. if oneFile.IsDir {
  2526. log.Info("zip dir name:" + oneFile.FileName)
  2527. } else {
  2528. log.Info("zip file name:" + oneFile.FileName)
  2529. fDest, err := w.Create(oneFile.FileName)
  2530. if err != nil {
  2531. log.Info("create zip entry error, download file failed: %s\n", err.Error())
  2532. ctx.ServerError("download file failed:", err)
  2533. return
  2534. }
  2535. body, err := storage.ObsDownloadAFile(setting.Bucket, path+oneFile.FileName)
  2536. if err != nil {
  2537. log.Info("download file failed: %s\n", err.Error())
  2538. ctx.ServerError("download file failed:", err)
  2539. return
  2540. } else {
  2541. defer body.Close()
  2542. p := make([]byte, 1024)
  2543. var readErr error
  2544. var readCount int
  2545. // 读取对象内容
  2546. for {
  2547. readCount, readErr = body.Read(p)
  2548. if readCount > 0 {
  2549. fDest.Write(p[:readCount])
  2550. }
  2551. if readErr != nil {
  2552. break
  2553. }
  2554. }
  2555. }
  2556. }
  2557. }
  2558. } else {
  2559. log.Info("error,msg=" + err.Error())
  2560. ctx.ServerError("no file to download.", err)
  2561. }
  2562. }
  2563. func SetJobCount(ctx *context.Context) {
  2564. repoId := ctx.Repo.Repository.ID
  2565. _, jobCount, err := models.Cloudbrains(&models.CloudbrainsOptions{
  2566. RepoID: repoId,
  2567. Type: models.TypeCloudBrainAll,
  2568. })
  2569. if err != nil {
  2570. ctx.ServerError("Get job faild:", err)
  2571. return
  2572. }
  2573. ctx.Data["jobCount"] = jobCount
  2574. }
  2575. func TrainJobDownloadLogFile(ctx *context.Context) {
  2576. var (
  2577. err error
  2578. )
  2579. var jobID = ctx.Params(":jobid")
  2580. versionName := ctx.Query("version_name")
  2581. task, err := models.GetCloudbrainByJobIDAndVersionName(jobID, versionName)
  2582. if err != nil {
  2583. log.Error("GetCloudbrainByJobIDAndVersionName(%s) failed:%v", task.JobName, err.Error(), ctx.Data["msgID"])
  2584. ctx.ServerError("GetCloudbrainByJobIDAndVersionName", err)
  2585. return
  2586. }
  2587. prefix := strings.TrimPrefix(path.Join(setting.TrainJobModelPath, task.JobName, modelarts.LogPath, versionName), "/") + "/job"
  2588. key, err := storage.GetObsLogFileName(prefix)
  2589. if err != nil {
  2590. log.Error("GetObsLogFileName(%s) failed:%v", jobID, err.Error(), ctx.Data["msgID"])
  2591. ctx.ServerError("GetObsLogFileName", err)
  2592. return
  2593. }
  2594. if len(key) > 1 {
  2595. ObsDownloadManyFile(prefix[0:len(prefix)-3], ctx, task.DisplayJobName+".zip", key)
  2596. } else {
  2597. url, err := storage.GetObsCreateSignedUrlByBucketAndKey(setting.Bucket, key[0].ParenDir+key[0].FileName)
  2598. if err != nil {
  2599. log.Error("GetObsCreateSignedUrlByBucketAndKey failed: %v", err.Error(), ctx.Data["msgID"])
  2600. ctx.ServerError("GetObsCreateSignedUrlByBucketAndKey", err)
  2601. return
  2602. }
  2603. ctx.Resp.Header().Set("Cache-Control", "max-age=0")
  2604. http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusTemporaryRedirect)
  2605. }
  2606. }
  2607. func getDatasUrlListByUUIDS(uuidStr string) ([]models.Datasurl, string, string, bool, error) {
  2608. var isMultiDataset bool
  2609. var dataUrl string
  2610. var datasetNames string
  2611. var datasUrlList []models.Datasurl
  2612. uuids := strings.Split(uuidStr, ";")
  2613. if len(uuids) > setting.MaxDatasetNum {
  2614. log.Error("the dataset count(%d) exceed the limit", len(uuids))
  2615. return datasUrlList, dataUrl, datasetNames, isMultiDataset, errors.New("the dataset count exceed the limit")
  2616. }
  2617. datasetInfos := make(map[string]models.DatasetInfo)
  2618. attachs, err := models.GetAttachmentsByUUIDs(uuids)
  2619. if err != nil || len(attachs) != len(uuids) {
  2620. log.Error("GetAttachmentsByUUIDs failed: %v", err)
  2621. return datasUrlList, dataUrl, datasetNames, isMultiDataset, errors.New("GetAttachmentsByUUIDs failed")
  2622. }
  2623. for i, tmpUuid := range uuids {
  2624. var attach *models.Attachment
  2625. for _, tmpAttach := range attachs {
  2626. if tmpAttach.UUID == tmpUuid {
  2627. attach = tmpAttach
  2628. break
  2629. }
  2630. }
  2631. if attach == nil {
  2632. log.Error("GetAttachmentsByUUIDs failed: %v", err)
  2633. return datasUrlList, dataUrl, datasetNames, isMultiDataset, errors.New("GetAttachmentsByUUIDs failed")
  2634. }
  2635. fileName := strings.TrimSuffix(strings.TrimSuffix(strings.TrimSuffix(attach.Name, ".zip"), ".tar.gz"), ".tgz")
  2636. for _, datasetInfo := range datasetInfos {
  2637. if fileName == datasetInfo.Name {
  2638. log.Error("the dataset name is same: %v", attach.Name)
  2639. return datasUrlList, dataUrl, datasetNames, isMultiDataset, errors.New("the dataset name is same")
  2640. }
  2641. }
  2642. if len(attachs) <= 1 {
  2643. dataUrl = "/" + setting.Bucket + "/" + setting.BasePath + path.Join(attach.UUID[0:1], attach.UUID[1:2]) + "/" + attach.UUID + attach.UUID + "/"
  2644. isMultiDataset = false
  2645. } else {
  2646. dataUrl = "/" + setting.Bucket + "/" + setting.BasePath + path.Join(attachs[0].UUID[0:1], attachs[0].UUID[1:2]) + "/" + attachs[0].UUID + attachs[0].UUID + "/"
  2647. datasetUrl := "s3://" + setting.Bucket + "/" + setting.BasePath + path.Join(attach.UUID[0:1], attach.UUID[1:2]) + "/" + attach.UUID + attach.UUID + "/"
  2648. datasUrlList = append(datasUrlList, models.Datasurl{
  2649. DatasetUrl: datasetUrl,
  2650. DatasetName: fileName,
  2651. })
  2652. isMultiDataset = true
  2653. }
  2654. if i == 0 {
  2655. datasetNames = attach.Name
  2656. } else {
  2657. datasetNames += ";" + attach.Name
  2658. }
  2659. }
  2660. return datasUrlList, dataUrl, datasetNames, isMultiDataset, nil
  2661. }