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