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

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