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