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

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