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

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