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

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