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

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