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