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

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