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

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