You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

modelarts.go 92 kB

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