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

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