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