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

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