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