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 96 kB

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