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.

cloudbrain.go 82 kB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
2 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
2 years ago
4 years ago
3 years ago
3 years ago
2 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
2 years ago
3 years ago
2 years ago
4 years ago
3 years ago
2 years ago
2 years ago
2 years ago
3 years ago
3 years ago
3 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
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
2 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 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
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
2 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
2 years ago
4 years ago
3 years ago
3 years ago
3 years ago
2 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
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
2 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
4 years ago
4 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
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
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
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
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
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
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
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
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
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
2 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
2 years ago
4 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
4 years ago
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
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 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
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
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
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
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
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
2 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
2 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
2 years ago
2 years ago
2 years ago
2 years ago
2 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628
  1. package repo
  2. import (
  3. "bufio"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "net/http"
  9. "os"
  10. "regexp"
  11. "sort"
  12. "strconv"
  13. "strings"
  14. "time"
  15. "unicode/utf8"
  16. "code.gitea.io/gitea/modules/grampus"
  17. "code.gitea.io/gitea/modules/timeutil"
  18. "github.com/unknwon/i18n"
  19. "code.gitea.io/gitea/models"
  20. "code.gitea.io/gitea/modules/auth"
  21. "code.gitea.io/gitea/modules/base"
  22. "code.gitea.io/gitea/modules/cloudbrain"
  23. "code.gitea.io/gitea/modules/context"
  24. "code.gitea.io/gitea/modules/git"
  25. "code.gitea.io/gitea/modules/log"
  26. "code.gitea.io/gitea/modules/modelarts"
  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. tplCloudBrainNew base.TplName = "repo/cloudbrain/new"
  33. tplCloudBrainShow base.TplName = "repo/cloudbrain/show"
  34. tplCloudBrainShowModels base.TplName = "repo/cloudbrain/models/index"
  35. tplCloudBrainBenchmarkIndex base.TplName = "repo/cloudbrain/benchmark/index"
  36. tplCloudBrainBenchmarkNew base.TplName = "repo/cloudbrain/benchmark/new"
  37. tplCloudBrainBenchmarkShow base.TplName = "repo/cloudbrain/benchmark/show"
  38. tplCloudBrainImageSubmit base.TplName = "repo/cloudbrain/image/submit"
  39. tplCloudBrainImageEdit base.TplName = "repo/cloudbrain/image/edit"
  40. tplCloudBrainTrainJobNew base.TplName = "repo/cloudbrain/trainjob/new"
  41. tplCloudBrainTrainJobShow base.TplName = "repo/cloudbrain/trainjob/show"
  42. tplCloudBrainInferenceJobNew base.TplName = "repo/cloudbrain/inference/new"
  43. tplCloudBrainInferenceJobShow base.TplName = "repo/cloudbrain/inference/show"
  44. )
  45. var (
  46. gpuInfos *models.GpuInfos
  47. categories *models.Categories
  48. benchmarkTypes *models.BenchmarkTypes
  49. benchmarkGpuInfos *models.GpuInfos
  50. benchmarkResourceSpecs *models.ResourceSpecs
  51. trainGpuInfos *models.GpuInfos
  52. inferenceGpuInfos *models.GpuInfos
  53. )
  54. const BENCHMARK_TYPE_CODE = "repo.cloudbrain.benchmark.types"
  55. const CLONE_FILE_PREFIX = "file:///"
  56. var benchmarkTypesMap = make(map[string]*models.BenchmarkTypes, 0)
  57. var jobNamePattern = regexp.MustCompile(`^[a-z0-9][a-z0-9-_]{1,34}[a-z0-9-]$`)
  58. // MustEnableDataset check if repository enable internal cb
  59. func MustEnableCloudbrain(ctx *context.Context) {
  60. if !ctx.Repo.CanRead(models.UnitTypeCloudBrain) {
  61. ctx.NotFound("MustEnableCloudbrain", nil)
  62. return
  63. }
  64. }
  65. func cutString(str string, lens int) string {
  66. if len(str) < lens {
  67. return str
  68. }
  69. return str[:lens]
  70. }
  71. func jobNamePrefixValid(s string) string {
  72. lowStr := strings.ToLower(s)
  73. re := regexp.MustCompile(`[^a-z0-9_\\-]+`)
  74. removeSpecial := re.ReplaceAllString(lowStr, "")
  75. re = regexp.MustCompile(`^[_\\-]+`)
  76. return re.ReplaceAllString(removeSpecial, "")
  77. }
  78. func cloudBrainNewDataPrepare(ctx *context.Context) error {
  79. ctx.Data["PageIsCloudBrain"] = true
  80. t := time.Now()
  81. var displayJobName = jobNamePrefixValid(cutString(ctx.User.Name, 5)) + t.Format("2006010215") + strconv.Itoa(int(t.Unix()))[5:]
  82. ctx.Data["display_job_name"] = displayJobName
  83. ctx.Data["command"] = cloudbrain.GetCloudbrainDebugCommand()
  84. ctx.Data["code_path"] = cloudbrain.CodeMountPath
  85. ctx.Data["dataset_path"] = cloudbrain.DataSetMountPath
  86. ctx.Data["model_path"] = cloudbrain.ModelMountPath
  87. ctx.Data["benchmark_path"] = cloudbrain.BenchMarkMountPath
  88. ctx.Data["is_benchmark_enabled"] = setting.IsBenchmarkEnabled
  89. if categories == nil {
  90. json.Unmarshal([]byte(setting.BenchmarkCategory), &categories)
  91. }
  92. ctx.Data["benchmark_categories"] = categories.Category
  93. ctx.Data["benchmark_types"] = GetBenchmarkTypes(ctx).BenchmarkType
  94. queuesDetail, _ := cloudbrain.GetQueuesDetail()
  95. if queuesDetail != nil {
  96. ctx.Data["QueuesDetail"] = queuesDetail
  97. }
  98. cloudbrain.InitSpecialPool()
  99. if gpuInfos == nil {
  100. json.Unmarshal([]byte(setting.GpuTypes), &gpuInfos)
  101. }
  102. ctx.Data["gpu_types"] = gpuInfos.GpuInfo
  103. if trainGpuInfos == nil {
  104. json.Unmarshal([]byte(setting.TrainGpuTypes), &trainGpuInfos)
  105. }
  106. ctx.Data["train_gpu_types"] = trainGpuInfos.GpuInfo
  107. if inferenceGpuInfos == nil {
  108. json.Unmarshal([]byte(setting.InferenceGpuTypes), &inferenceGpuInfos)
  109. }
  110. ctx.Data["inference_gpu_types"] = inferenceGpuInfos.GpuInfo
  111. if benchmarkGpuInfos == nil {
  112. json.Unmarshal([]byte(setting.BenchmarkGpuTypes), &benchmarkGpuInfos)
  113. }
  114. ctx.Data["benchmark_gpu_types"] = benchmarkGpuInfos.GpuInfo
  115. if benchmarkResourceSpecs == nil {
  116. json.Unmarshal([]byte(setting.BenchmarkResourceSpecs), &benchmarkResourceSpecs)
  117. }
  118. ctx.Data["benchmark_resource_specs"] = benchmarkResourceSpecs.ResourceSpec
  119. if cloudbrain.ResourceSpecs == nil {
  120. json.Unmarshal([]byte(setting.ResourceSpecs), &cloudbrain.ResourceSpecs)
  121. }
  122. ctx.Data["resource_specs"] = cloudbrain.ResourceSpecs.ResourceSpec
  123. if cloudbrain.TrainResourceSpecs == nil {
  124. json.Unmarshal([]byte(setting.TrainResourceSpecs), &cloudbrain.TrainResourceSpecs)
  125. }
  126. ctx.Data["train_resource_specs"] = cloudbrain.TrainResourceSpecs.ResourceSpec
  127. if cloudbrain.InferenceResourceSpecs == nil {
  128. json.Unmarshal([]byte(setting.InferenceResourceSpecs), &cloudbrain.InferenceResourceSpecs)
  129. }
  130. ctx.Data["inference_resource_specs"] = cloudbrain.InferenceResourceSpecs.ResourceSpec
  131. if cloudbrain.SpecialPools != nil {
  132. var debugGpuTypes []*models.GpuInfo
  133. var trainGpuTypes []*models.GpuInfo
  134. for _, pool := range cloudbrain.SpecialPools.Pools {
  135. org, _ := models.GetOrgByName(pool.Org)
  136. if org != nil {
  137. isOrgMember, _ := models.IsOrganizationMember(org.ID, ctx.User.ID)
  138. if isOrgMember {
  139. for _, jobType := range pool.JobType {
  140. if jobType == string(models.JobTypeDebug) {
  141. debugGpuTypes = append(debugGpuTypes, pool.Pool...)
  142. if pool.ResourceSpec != nil {
  143. ctx.Data["resource_specs"] = pool.ResourceSpec
  144. }
  145. } else if jobType == string(models.JobTypeTrain) {
  146. trainGpuTypes = append(trainGpuTypes, pool.Pool...)
  147. if pool.ResourceSpec != nil {
  148. ctx.Data["train_resource_specs"] = pool.ResourceSpec
  149. }
  150. }
  151. }
  152. break
  153. }
  154. }
  155. }
  156. if len(debugGpuTypes) > 0 {
  157. ctx.Data["gpu_types"] = debugGpuTypes
  158. }
  159. if len(trainGpuTypes) > 0 {
  160. ctx.Data["train_gpu_types"] = trainGpuTypes
  161. }
  162. }
  163. ctx.Data["params"] = ""
  164. ctx.Data["branchName"] = ctx.Repo.BranchName
  165. ctx.Data["snn4imagenet_path"] = cloudbrain.Snn4imagenetMountPath
  166. ctx.Data["is_snn4imagenet_enabled"] = setting.IsSnn4imagenetEnabled
  167. ctx.Data["brainscore_path"] = cloudbrain.BrainScoreMountPath
  168. ctx.Data["is_brainscore_enabled"] = setting.IsBrainScoreEnabled
  169. ctx.Data["datasetType"] = models.TypeCloudBrainOne
  170. ctx.Data["benchmarkMode"] = ctx.Query("benchmarkMode")
  171. return nil
  172. }
  173. func CloudBrainNew(ctx *context.Context) {
  174. err := cloudBrainNewDataPrepare(ctx)
  175. if err != nil {
  176. ctx.ServerError("get new cloudbrain info failed", err)
  177. return
  178. }
  179. ctx.HTML(200, tplCloudBrainNew)
  180. }
  181. func CloudBrainCreate(ctx *context.Context, form auth.CreateCloudBrainForm) {
  182. ctx.Data["PageIsCloudBrain"] = true
  183. displayJobName := form.DisplayJobName
  184. jobName := util.ConvertDisplayJobNameToJobName(displayJobName)
  185. image := strings.TrimSpace(form.Image)
  186. uuids := form.Attachment
  187. jobType := form.JobType
  188. gpuQueue := form.GpuType
  189. codePath := setting.JobPath + jobName + cloudbrain.CodeMountPath
  190. resourceSpecId := form.ResourceSpecId
  191. branchName := form.BranchName
  192. repo := ctx.Repo.Repository
  193. tpl := tplCloudBrainNew
  194. if jobType == string(models.JobTypeTrain) {
  195. tpl = tplCloudBrainTrainJobNew
  196. }
  197. tasks, err := models.GetCloudbrainsByDisplayJobName(repo.ID, jobType, displayJobName)
  198. if err == nil {
  199. if len(tasks) != 0 {
  200. log.Error("the job name did already exist", ctx.Data["MsgID"])
  201. cloudBrainNewDataPrepare(ctx)
  202. ctx.RenderWithErr("the job name did already exist", tpl, &form)
  203. return
  204. }
  205. } else {
  206. if !models.IsErrJobNotExist(err) {
  207. log.Error("system error, %v", err, ctx.Data["MsgID"])
  208. cloudBrainNewDataPrepare(ctx)
  209. ctx.RenderWithErr("system error", tpl, &form)
  210. return
  211. }
  212. }
  213. if !jobNamePattern.MatchString(displayJobName) {
  214. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_jobname_err"), tpl, &form)
  215. return
  216. }
  217. if jobType != string(models.JobTypeBenchmark) && jobType != string(models.JobTypeDebug) && jobType != string(models.JobTypeTrain) {
  218. log.Error("jobtype error:", jobType, ctx.Data["MsgID"])
  219. cloudBrainNewDataPrepare(ctx)
  220. ctx.RenderWithErr("jobtype error", tpl, &form)
  221. return
  222. }
  223. count, err := models.GetCloudbrainCountByUserID(ctx.User.ID, jobType)
  224. if err != nil {
  225. log.Error("GetCloudbrainCountByUserID failed:%v", err, ctx.Data["MsgID"])
  226. cloudBrainNewDataPrepare(ctx)
  227. ctx.RenderWithErr("system error", tpl, &form)
  228. return
  229. } else {
  230. if count >= 1 {
  231. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  232. cloudBrainNewDataPrepare(ctx)
  233. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain.morethanonejob"), tpl, &form)
  234. return
  235. }
  236. }
  237. datasetInfos, datasetNames, err := models.GetDatasetInfo(uuids)
  238. if err != nil {
  239. log.Error("GetDatasetInfo failed: %v", err, ctx.Data["MsgID"])
  240. cloudBrainNewDataPrepare(ctx)
  241. ctx.RenderWithErr(ctx.Tr("cloudbrain.error.dataset_select"), tpl, &form)
  242. return
  243. }
  244. command := cloudbrain.GetCloudbrainDebugCommand()
  245. if jobType == string(models.JobTypeTrain) {
  246. tpl = tplCloudBrainTrainJobNew
  247. commandTrain, err := getTrainJobCommand(form)
  248. if err != nil {
  249. log.Error("getTrainJobCommand failed: %v", err)
  250. ctx.RenderWithErr(err.Error(), tpl, &form)
  251. return
  252. }
  253. command = commandTrain
  254. }
  255. errStr := checkCloudBrainSpecialPool(ctx, jobType, gpuQueue, resourceSpecId)
  256. if errStr != "" {
  257. cloudBrainNewDataPrepare(ctx)
  258. ctx.RenderWithErr(errStr, tpl, &form)
  259. return
  260. }
  261. if branchName == "" {
  262. branchName = cloudbrain.DefaultBranchName
  263. }
  264. downloadCode(repo, codePath, branchName)
  265. uploadCodeToMinio(codePath+"/", jobName, cloudbrain.CodeMountPath+"/")
  266. modelPath := setting.JobPath + jobName + cloudbrain.ModelMountPath + "/"
  267. mkModelPath(modelPath)
  268. uploadCodeToMinio(modelPath, jobName, cloudbrain.ModelMountPath+"/")
  269. commitID, _ := ctx.Repo.GitRepo.GetBranchCommitID(branchName)
  270. req := cloudbrain.GenerateCloudBrainTaskReq{
  271. Ctx: ctx,
  272. DisplayJobName: displayJobName,
  273. JobName: jobName,
  274. Image: image,
  275. Command: command,
  276. Uuids: uuids,
  277. DatasetNames: datasetNames,
  278. DatasetInfos: datasetInfos,
  279. CodePath: storage.GetMinioPath(jobName, cloudbrain.CodeMountPath+"/"),
  280. ModelPath: storage.GetMinioPath(jobName, cloudbrain.ModelMountPath+"/"),
  281. BenchmarkPath: storage.GetMinioPath(jobName, cloudbrain.BenchMarkMountPath+"/"),
  282. Snn4ImageNetPath: storage.GetMinioPath(jobName, cloudbrain.Snn4imagenetMountPath+"/"),
  283. BrainScorePath: storage.GetMinioPath(jobName, cloudbrain.BrainScoreMountPath+"/"),
  284. JobType: jobType,
  285. GpuQueue: gpuQueue,
  286. Description: form.Description,
  287. BranchName: branchName,
  288. BootFile: form.BootFile,
  289. Params: form.Params,
  290. CommitID: commitID,
  291. BenchmarkTypeID: 0,
  292. BenchmarkChildTypeID: 0,
  293. ResourceSpecId: resourceSpecId,
  294. ResultPath: storage.GetMinioPath(jobName, cloudbrain.ResultPath+"/"),
  295. }
  296. err = cloudbrain.GenerateTask(req)
  297. if err != nil {
  298. cloudBrainNewDataPrepare(ctx)
  299. ctx.RenderWithErr(err.Error(), tpl, &form)
  300. return
  301. }
  302. if jobType == string(models.JobTypeTrain) {
  303. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/train-job?listType=all")
  304. } else {
  305. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/debugjob?debugListType=all")
  306. }
  307. }
  308. func CloudBrainInferenceJobCreate(ctx *context.Context, form auth.CreateCloudBrainInferencForm) {
  309. ctx.Data["PageIsCloudBrain"] = true
  310. displayJobName := form.DisplayJobName
  311. jobName := util.ConvertDisplayJobNameToJobName(displayJobName)
  312. image := strings.TrimSpace(form.Image)
  313. uuid := form.Attachment
  314. jobType := string(models.JobTypeInference)
  315. gpuQueue := form.GpuType
  316. codePath := setting.JobPath + jobName + cloudbrain.CodeMountPath
  317. resourceSpecId := form.ResourceSpecId
  318. branchName := form.BranchName
  319. repo := ctx.Repo.Repository
  320. ckptUrl := setting.Attachment.Minio.RealPath + form.TrainUrl + form.CkptName
  321. log.Info("ckpt url:" + ckptUrl)
  322. tpl := tplCloudBrainInferenceJobNew
  323. command, err := getInferenceJobCommand(form)
  324. if err != nil {
  325. log.Error("getTrainJobCommand failed: %v", err)
  326. ctx.RenderWithErr(err.Error(), tpl, &form)
  327. return
  328. }
  329. tasks, err := models.GetCloudbrainsByDisplayJobName(repo.ID, jobType, displayJobName)
  330. if err == nil {
  331. if len(tasks) != 0 {
  332. log.Error("the job name did already exist", ctx.Data["MsgID"])
  333. cloudBrainNewDataPrepare(ctx)
  334. ctx.RenderWithErr("the job name did already exist", tpl, &form)
  335. return
  336. }
  337. } else {
  338. if !models.IsErrJobNotExist(err) {
  339. log.Error("system error, %v", err, ctx.Data["MsgID"])
  340. cloudBrainNewDataPrepare(ctx)
  341. ctx.RenderWithErr("system error", tpl, &form)
  342. return
  343. }
  344. }
  345. if !jobNamePattern.MatchString(displayJobName) {
  346. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_jobname_err"), tpl, &form)
  347. return
  348. }
  349. count, err := models.GetCloudbrainCountByUserID(ctx.User.ID, jobType)
  350. if err != nil {
  351. log.Error("GetCloudbrainCountByUserID failed:%v", err, ctx.Data["MsgID"])
  352. cloudBrainNewDataPrepare(ctx)
  353. ctx.RenderWithErr("system error", tpl, &form)
  354. return
  355. } else {
  356. if count >= 1 {
  357. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  358. cloudBrainNewDataPrepare(ctx)
  359. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain.morethanonejob"), tpl, &form)
  360. return
  361. }
  362. }
  363. if branchName == "" {
  364. branchName = cloudbrain.DefaultBranchName
  365. }
  366. downloadCode(repo, codePath, branchName)
  367. uploadCodeToMinio(codePath+"/", jobName, cloudbrain.CodeMountPath+"/")
  368. resultPath := setting.JobPath + jobName + cloudbrain.ResultPath + "/"
  369. mkResultPath(resultPath)
  370. uploadCodeToMinio(resultPath, jobName, cloudbrain.ResultPath+"/")
  371. commitID, _ := ctx.Repo.GitRepo.GetBranchCommitID(branchName)
  372. datasetInfos, datasetNames, err := models.GetDatasetInfo(uuid)
  373. if err != nil {
  374. log.Error("GetDatasetInfo failed: %v", err, ctx.Data["MsgID"])
  375. cloudBrainNewDataPrepare(ctx)
  376. ctx.RenderWithErr(ctx.Tr("cloudbrain.error.dataset_select"), tpl, &form)
  377. return
  378. }
  379. req := cloudbrain.GenerateCloudBrainTaskReq{
  380. Ctx: ctx,
  381. DisplayJobName: displayJobName,
  382. JobName: jobName,
  383. Image: image,
  384. Command: command,
  385. Uuids: uuid,
  386. DatasetNames: datasetNames,
  387. DatasetInfos: datasetInfos,
  388. CodePath: storage.GetMinioPath(jobName, cloudbrain.CodeMountPath+"/"),
  389. ModelPath: setting.Attachment.Minio.RealPath + form.TrainUrl,
  390. BenchmarkPath: storage.GetMinioPath(jobName, cloudbrain.BenchMarkMountPath+"/"),
  391. Snn4ImageNetPath: storage.GetMinioPath(jobName, cloudbrain.Snn4imagenetMountPath+"/"),
  392. BrainScorePath: storage.GetMinioPath(jobName, cloudbrain.BrainScoreMountPath+"/"),
  393. JobType: jobType,
  394. GpuQueue: gpuQueue,
  395. Description: form.Description,
  396. BranchName: branchName,
  397. BootFile: form.BootFile,
  398. Params: form.Params,
  399. CommitID: commitID,
  400. ResourceSpecId: resourceSpecId,
  401. ResultPath: storage.GetMinioPath(jobName, cloudbrain.ResultPath+"/"),
  402. ModelName: form.ModelName,
  403. ModelVersion: form.ModelVersion,
  404. CkptName: form.CkptName,
  405. TrainUrl: form.TrainUrl,
  406. }
  407. err = cloudbrain.GenerateTask(req)
  408. if err != nil {
  409. cloudBrainNewDataPrepare(ctx)
  410. ctx.RenderWithErr(err.Error(), tpl, &form)
  411. return
  412. }
  413. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/inference-job")
  414. }
  415. /**
  416. 检查用户传输的参数是否符合专属资源池
  417. */
  418. func checkCloudBrainSpecialPool(ctx *context.Context, jobType string, queue string, resourceSpecId int) string {
  419. if cloudbrain.SpecialPools != nil {
  420. var isInPoolOrg = false
  421. var matchSpecialPool = false
  422. for _, specialPool := range cloudbrain.SpecialPools.Pools {
  423. if cloudbrain.IsElementExist(specialPool.JobType, jobType) && cloudbrain.IsQueueInSpecialtPool(specialPool.Pool, queue) {
  424. if cloudbrain.IsResourceSpecInSpecialPool(specialPool.ResourceSpec, resourceSpecId) {
  425. matchSpecialPool = true
  426. org, _ := models.GetOrgByName(specialPool.Org)
  427. if org != nil {
  428. isInPoolOrg, _ = models.IsOrganizationMember(org.ID, ctx.User.ID)
  429. if isInPoolOrg {
  430. break //传入参数,和专属资源池匹配上了,检查通过
  431. }
  432. }
  433. }
  434. }
  435. }
  436. //资源池有匹配上,但是用户不在相应的组织中,返回错误信息。界面已经过滤了选择,界面操作不会到这个逻辑
  437. if matchSpecialPool && !isInPoolOrg {
  438. return ctx.Tr("repo.grampus.no_operate_right")
  439. }
  440. }
  441. //没有匹配到资源池或者没有设置专属资源池,检查通过; 获取和资源池完全匹配检查通过
  442. return ""
  443. }
  444. func CloudBrainRestart(ctx *context.Context) {
  445. var ID = ctx.Params(":id")
  446. var resultCode = "0"
  447. var errorMsg = ""
  448. var status = string(models.JobWaiting)
  449. task := ctx.Cloudbrain
  450. for {
  451. if task.Status != string(models.JobStopped) && task.Status != string(models.JobSucceeded) && task.Status != string(models.JobFailed) {
  452. log.Error("the job(%s) is not stopped", task.JobName, ctx.Data["MsgID"])
  453. resultCode = "-1"
  454. errorMsg = "the job is not stopped"
  455. break
  456. }
  457. if task.Image == "" || task.GpuQueue == "" || task.Type != models.TypeCloudBrainOne {
  458. log.Error("the job(%s) version is too old", task.JobName, ctx.Data["MsgID"])
  459. resultCode = "-1"
  460. errorMsg = "the job's version is too old and can not be restarted"
  461. break
  462. }
  463. if !ctx.IsSigned || (ctx.User.ID != task.UserID && !ctx.IsUserSiteAdmin()) {
  464. log.Error("the user has no right ro restart the job", task.JobName, ctx.Data["MsgID"])
  465. resultCode = "-1"
  466. errorMsg = "you have no right to restart the job"
  467. break
  468. }
  469. var hasSameResource bool
  470. if gpuInfos == nil {
  471. json.Unmarshal([]byte(setting.GpuTypes), &gpuInfos)
  472. }
  473. for _, resourceType := range gpuInfos.GpuInfo {
  474. if resourceType.Queue == task.GpuQueue {
  475. hasSameResource = true
  476. break
  477. }
  478. }
  479. if !hasSameResource && cloudbrain.SpecialPools != nil {
  480. for _, specialPool := range cloudbrain.SpecialPools.Pools {
  481. cloudbrain.IsElementExist(specialPool.JobType, string(models.JobTypeDebug))
  482. for _, pool := range specialPool.Pool {
  483. if pool.Queue == task.GpuQueue {
  484. hasSameResource = true
  485. }
  486. }
  487. }
  488. }
  489. if !hasSameResource {
  490. log.Error("has no same resource, can not restart", ctx.Data["MsgID"])
  491. resultCode = "-1"
  492. errorMsg = "the job's version is too old and can not be restarted"
  493. break
  494. }
  495. count, err := models.GetCloudbrainCountByUserID(ctx.User.ID, string(models.JobTypeDebug))
  496. if err != nil {
  497. log.Error("GetCloudbrainCountByUserID failed:%v", err, ctx.Data["MsgID"])
  498. resultCode = "-1"
  499. errorMsg = "system error"
  500. break
  501. } else {
  502. if count >= 1 {
  503. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  504. resultCode = "-1"
  505. errorMsg = ctx.Tr("repo.cloudbrain.morethanonejob")
  506. break
  507. }
  508. }
  509. err = cloudbrain.RestartTask(ctx, task, &ID)
  510. if err != nil {
  511. log.Error("RestartTask failed:%v", err.Error(), ctx.Data["MsgID"])
  512. resultCode = "-1"
  513. errorMsg = "system error"
  514. break
  515. }
  516. break
  517. }
  518. ctx.JSON(200, map[string]string{
  519. "result_code": resultCode,
  520. "error_msg": errorMsg,
  521. "status": status,
  522. "id": ID,
  523. })
  524. }
  525. func CloudBrainBenchMarkShow(ctx *context.Context) {
  526. cloudBrainShow(ctx, tplCloudBrainBenchmarkShow, models.JobTypeBenchmark)
  527. }
  528. func CloudBrainShow(ctx *context.Context) {
  529. cloudBrainShow(ctx, tplCloudBrainShow, models.JobTypeDebug)
  530. }
  531. func CloudBrainTrainJobShow(ctx *context.Context) {
  532. cloudBrainShow(ctx, tplCloudBrainTrainJobShow, models.JobTypeTrain)
  533. }
  534. func cloudBrainShow(ctx *context.Context, tpName base.TplName, jobType models.JobType) {
  535. ctx.Data["PageIsCloudBrain"] = true
  536. debugListType := ctx.Query("debugListType")
  537. var task *models.Cloudbrain
  538. var err error
  539. if jobType == models.JobTypeTrain || jobType == models.JobTypeInference {
  540. task, err = models.GetCloudbrainByJobID(ctx.Params(":jobid"))
  541. } else {
  542. task, err = models.GetCloudbrainByIDWithDeleted(ctx.Params(":id"))
  543. }
  544. if err != nil {
  545. log.Info("error:" + err.Error())
  546. ctx.Data["error"] = err.Error()
  547. return
  548. }
  549. result, err := cloudbrain.GetJob(task.JobID)
  550. if err != nil {
  551. log.Info("error:" + err.Error())
  552. ctx.Data["error"] = err.Error()
  553. return
  554. }
  555. if task.JobType == string(models.JobTypeTrain) {
  556. if cloudbrain.TrainResourceSpecs == nil {
  557. json.Unmarshal([]byte(setting.TrainResourceSpecs), &cloudbrain.TrainResourceSpecs)
  558. }
  559. for _, tmp := range cloudbrain.TrainResourceSpecs.ResourceSpec {
  560. if tmp.Id == task.ResourceSpecId {
  561. ctx.Data["GpuNum"] = tmp.GpuNum
  562. ctx.Data["CpuNum"] = tmp.CpuNum
  563. ctx.Data["MemMiB"] = tmp.MemMiB
  564. ctx.Data["ShareMemMiB"] = tmp.ShareMemMiB
  565. }
  566. }
  567. } else if task.JobType == string(models.JobTypeInference) {
  568. if cloudbrain.InferenceResourceSpecs == nil {
  569. json.Unmarshal([]byte(setting.InferenceResourceSpecs), &cloudbrain.InferenceResourceSpecs)
  570. }
  571. for _, tmp := range cloudbrain.InferenceResourceSpecs.ResourceSpec {
  572. if tmp.Id == task.ResourceSpecId {
  573. ctx.Data["GpuNum"] = tmp.GpuNum
  574. ctx.Data["CpuNum"] = tmp.CpuNum
  575. ctx.Data["MemMiB"] = tmp.MemMiB
  576. ctx.Data["ShareMemMiB"] = tmp.ShareMemMiB
  577. }
  578. }
  579. } else {
  580. if cloudbrain.ResourceSpecs == nil {
  581. json.Unmarshal([]byte(setting.ResourceSpecs), &cloudbrain.ResourceSpecs)
  582. }
  583. for _, tmp := range cloudbrain.ResourceSpecs.ResourceSpec {
  584. if tmp.Id == task.ResourceSpecId {
  585. ctx.Data["GpuNum"] = tmp.GpuNum
  586. ctx.Data["CpuNum"] = tmp.CpuNum
  587. ctx.Data["MemMiB"] = tmp.MemMiB
  588. ctx.Data["ShareMemMiB"] = tmp.ShareMemMiB
  589. }
  590. }
  591. }
  592. if result != nil {
  593. jobRes, _ := models.ConvertToJobResultPayload(result.Payload)
  594. jobRes.Resource.Memory = strings.ReplaceAll(jobRes.Resource.Memory, "Mi", "MB")
  595. spec := "GPU数:" + strconv.Itoa(jobRes.Resource.NvidiaComGpu) + ",CPU数:" + strconv.Itoa(jobRes.Resource.CPU) + ",内存(MB):" + jobRes.Resource.Memory
  596. ctx.Data["resource_spec"] = spec
  597. if task.JobType == string(models.JobTypeTrain) {
  598. if trainGpuInfos == nil {
  599. json.Unmarshal([]byte(setting.TrainGpuTypes), &trainGpuInfos)
  600. }
  601. for _, resourceType := range trainGpuInfos.GpuInfo {
  602. if resourceType.Queue == jobRes.Config.GpuType {
  603. ctx.Data["resource_type"] = resourceType.Value
  604. }
  605. }
  606. } else if task.JobType == string(models.JobTypeInference) {
  607. if inferenceGpuInfos == nil {
  608. json.Unmarshal([]byte(setting.InferenceGpuTypes), &inferenceGpuInfos)
  609. }
  610. for _, resourceType := range inferenceGpuInfos.GpuInfo {
  611. if resourceType.Queue == jobRes.Config.GpuType {
  612. ctx.Data["resource_type"] = resourceType.Value
  613. }
  614. }
  615. } else if cloudbrain.IsBenchmarkJob(task.JobType) {
  616. if benchmarkGpuInfos == nil {
  617. json.Unmarshal([]byte(setting.BenchmarkGpuTypes), &benchmarkGpuInfos)
  618. }
  619. for _, resourceType := range benchmarkGpuInfos.GpuInfo {
  620. if resourceType.Queue == jobRes.Config.GpuType {
  621. ctx.Data["resource_type"] = resourceType.Value
  622. }
  623. }
  624. } else {
  625. if gpuInfos == nil {
  626. json.Unmarshal([]byte(setting.GpuTypes), &gpuInfos)
  627. }
  628. for _, resourceType := range gpuInfos.GpuInfo {
  629. if resourceType.Queue == jobRes.Config.GpuType {
  630. ctx.Data["resource_type"] = resourceType.Value
  631. }
  632. }
  633. }
  634. taskRoles := jobRes.TaskRoles
  635. taskRes, _ := models.ConvertToTaskPod(taskRoles[cloudbrain.SubTaskName].(map[string]interface{}))
  636. ctx.Data["taskRes"] = taskRes
  637. ctx.Data["ExitDiagnostics"] = taskRes.TaskStatuses[0].ExitDiagnostics
  638. task.Status = taskRes.TaskStatuses[0].State
  639. task.ContainerID = taskRes.TaskStatuses[0].ContainerID
  640. task.ContainerIp = taskRes.TaskStatuses[0].ContainerIP
  641. models.ParseAndSetDurationFromCloudBrainOne(jobRes, task)
  642. if task.DeletedAt.IsZero() { //normal record
  643. err = models.UpdateJob(task)
  644. if err != nil {
  645. ctx.Data["error"] = err.Error()
  646. return
  647. }
  648. } else { //deleted record
  649. }
  650. ctx.Data["result"] = jobRes
  651. } else {
  652. log.Info("error:" + err.Error())
  653. return
  654. }
  655. user, err := models.GetUserByID(task.UserID)
  656. if err == nil {
  657. task.User = user
  658. }
  659. if task.BenchmarkTypeID > 0 {
  660. for _, benchmarkType := range GetBenchmarkTypes(ctx).BenchmarkType {
  661. if task.BenchmarkTypeID == benchmarkType.Id {
  662. ctx.Data["BenchmarkTypeName"] = benchmarkType.First
  663. task.BenchmarkTypeName = benchmarkType.First
  664. for _, benchmarkChildType := range benchmarkType.Second {
  665. if task.BenchmarkChildTypeID == benchmarkChildType.Id {
  666. ctx.Data["BenchmarkChildTypeName"] = benchmarkChildType.Value
  667. break
  668. }
  669. }
  670. break
  671. }
  672. }
  673. }
  674. if task.JobType == string(models.JobTypeBenchmark) {
  675. task.BenchmarkType = ctx.Tr("repo.cloudbrain.benchmark.algorithm")
  676. } else if task.JobType == string(models.JobTypeSnn4imagenet) || task.JobType == string(models.JobTypeBrainScore) {
  677. task.BenchmarkType = ctx.Tr("repo.cloudbrain.benchmark.model")
  678. task.BenchmarkTypeName = task.JobType
  679. ctx.Data["BenchmarkTypeName"] = task.JobType
  680. if task.JobType == string(models.JobTypeBrainScore) {
  681. ctx.Data["BenchmarkChildTypeName"] = getBrainRegion(task.BenchmarkChildTypeID)
  682. }
  683. }
  684. if task.TrainJobDuration == "" {
  685. if task.Duration == 0 {
  686. var duration int64
  687. if task.Status == string(models.JobWaiting) {
  688. duration = 0
  689. } else if task.Status == string(models.JobRunning) {
  690. duration = time.Now().Unix() - int64(task.CreatedUnix)
  691. } else {
  692. duration = int64(task.UpdatedUnix) - int64(task.CreatedUnix)
  693. }
  694. task.Duration = duration
  695. }
  696. task.TrainJobDuration = models.ConvertDurationToStr(task.Duration)
  697. }
  698. ctx.Data["duration"] = task.TrainJobDuration
  699. if len(task.Parameters) > 0 {
  700. var parameters models.Parameters
  701. err := json.Unmarshal([]byte(task.Parameters), &parameters)
  702. if err != nil {
  703. log.Error("Failed to Unmarshal Parameters: %s (%v)", task.Parameters, err)
  704. task.Parameters = ""
  705. } else {
  706. if len(parameters.Parameter) > 0 {
  707. paramTemp := ""
  708. for _, Parameter := range parameters.Parameter {
  709. param := Parameter.Label + " = " + Parameter.Value + "; "
  710. paramTemp = paramTemp + param
  711. }
  712. task.Parameters = paramTemp[:len(paramTemp)-2]
  713. } else {
  714. task.Parameters = ""
  715. }
  716. }
  717. }
  718. ctx.Data["task"] = task
  719. ctx.Data["jobName"] = task.JobName
  720. ctx.Data["displayJobName"] = task.DisplayJobName
  721. version_list_task := make([]*models.Cloudbrain, 0)
  722. version_list_task = append(version_list_task, task)
  723. ctx.Data["version_list_task"] = version_list_task
  724. ctx.Data["debugListType"] = debugListType
  725. ctx.Data["code_path"] = cloudbrain.CodeMountPath
  726. ctx.Data["dataset_path"] = cloudbrain.DataSetMountPath
  727. ctx.Data["model_path"] = cloudbrain.ModelMountPath
  728. ctx.Data["canDownload"] = cloudbrain.CanModifyJob(ctx, task)
  729. ctx.Data["branchName"] = task.BranchName
  730. ctx.HTML(200, tpName)
  731. }
  732. func CloudBrainDebug(ctx *context.Context) {
  733. task := ctx.Cloudbrain
  734. debugUrl := setting.DebugServerHost + "jpylab_" + task.JobID + "_" + task.SubTaskName
  735. ctx.Redirect(debugUrl)
  736. }
  737. func CloudBrainCommitImageShow(ctx *context.Context) {
  738. ctx.Data["PageIsCloudBrain"] = true
  739. ctx.Data["Type"] = ctx.Cloudbrain.Type
  740. ctx.HTML(200, tplCloudBrainImageSubmit)
  741. }
  742. func CloudBrainImageEdit(ctx *context.Context) {
  743. ctx.Data["PageIsImageEdit"] = true
  744. ctx.Data["PageFrom"] = ctx.Params(":from")
  745. var ID = ctx.Params(":id")
  746. id, err := strconv.ParseInt(ID, 10, 64)
  747. if err != nil {
  748. log.Error("GetImageByID failed:%v", err.Error())
  749. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  750. }
  751. image, err := models.GetImageByID(id)
  752. if err != nil {
  753. log.Error("GetImageByID failed:%v", err.Error())
  754. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  755. }
  756. ctx.Data["Image"] = image
  757. ctx.HTML(http.StatusOK, tplCloudBrainImageEdit)
  758. }
  759. func CloudBrainImageEditPost(ctx *context.Context, form auth.EditImageCloudBrainForm) {
  760. if utf8.RuneCountInString(form.Description) > 255 {
  761. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("dataset.description_format_err", 255)))
  762. return
  763. }
  764. validTopics, errMessage := checkTopics(form.Topics)
  765. if errMessage != "" {
  766. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr(errMessage)))
  767. return
  768. }
  769. image, err := models.GetImageByID(form.ID)
  770. if err != nil {
  771. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("repo.image_not_exist")))
  772. }
  773. image.IsPrivate = form.IsPrivate
  774. image.Description = form.Description
  775. err = models.WithTx(func(ctx models.DBContext) error {
  776. if err := models.UpdateLocalImage(image); err != nil {
  777. return err
  778. }
  779. if err := models.SaveImageTopics(image.ID, validTopics...); err != nil {
  780. return err
  781. }
  782. return nil
  783. })
  784. if err != nil {
  785. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("repo.image_not_exist")))
  786. } else {
  787. ctx.JSON(http.StatusOK, models.BaseOKMessage)
  788. }
  789. }
  790. func CloudBrainImageDelete(ctx *context.Context) {
  791. var ID = ctx.Params(":id")
  792. id, err := strconv.ParseInt(ID, 10, 64)
  793. if err != nil {
  794. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("repo.image_not_exist")))
  795. return
  796. }
  797. err = models.DeleteLocalImage(id)
  798. if err != nil {
  799. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("repo.image_delete_fail")))
  800. } else {
  801. ctx.JSON(http.StatusOK, models.BaseOKMessage)
  802. }
  803. }
  804. func CloudBrainCommitImageCheck(ctx *context.Context, form auth.CommitImageCloudBrainForm) {
  805. isExist, _ := models.IsImageExistByUser(form.Tag, ctx.User.ID)
  806. if isExist {
  807. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("repo.image_overwrite")))
  808. } else {
  809. ctx.JSON(http.StatusOK, models.BaseOKMessage)
  810. }
  811. }
  812. func CloudBrainAdminCommitImage(ctx *context.Context, form auth.CommitAdminImageCloudBrainForm) {
  813. if !NamePattern.MatchString(form.Tag) {
  814. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("dataset.title_format_err")))
  815. return
  816. }
  817. if utf8.RuneCountInString(form.Description) > 255 {
  818. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("dataset.description_format_err", 255)))
  819. return
  820. }
  821. validTopics, errMessage := checkTopics(form.Topics)
  822. if errMessage != "" {
  823. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr(errMessage)))
  824. return
  825. }
  826. err := cloudbrain.CommitAdminImage(models.CommitImageParams{
  827. CommitImageCloudBrainParams: models.CommitImageCloudBrainParams{
  828. ImageDescription: form.Description,
  829. ImageTag: form.Tag,
  830. },
  831. IsPrivate: form.IsPrivate,
  832. CloudBrainType: form.Type,
  833. Topics: validTopics,
  834. UID: ctx.User.ID,
  835. Type: models.GetRecommondType(form.IsRecommend),
  836. Place: form.Place,
  837. })
  838. if err != nil {
  839. log.Error("CommitImagefailed")
  840. if models.IsErrImageTagExist(err) {
  841. ctx.JSON(200, models.BaseErrorMessage(ctx.Tr("repo.image_exist")))
  842. } else if models.IsErrorImageCommitting(err) {
  843. ctx.JSON(200, models.BaseErrorMessage(ctx.Tr("repo.image_committing")))
  844. } else {
  845. ctx.JSON(200, models.BaseErrorMessage(ctx.Tr("repo.image_commit_fail")))
  846. }
  847. return
  848. }
  849. ctx.JSON(200, models.BaseOKMessage)
  850. }
  851. func CloudBrainCommitImage(ctx *context.Context, form auth.CommitImageCloudBrainForm) {
  852. if !NamePattern.MatchString(form.Tag) {
  853. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("dataset.title_format_err")))
  854. return
  855. }
  856. if utf8.RuneCountInString(form.Description) > 255 {
  857. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("dataset.description_format_err", 255)))
  858. return
  859. }
  860. validTopics, errMessage := checkTopics(form.Topics)
  861. if errMessage != "" {
  862. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr(errMessage)))
  863. return
  864. }
  865. err := cloudbrain.CommitImage(ctx.Cloudbrain.JobID, models.CommitImageParams{
  866. CommitImageCloudBrainParams: models.CommitImageCloudBrainParams{
  867. Ip: ctx.Cloudbrain.ContainerIp,
  868. TaskContainerId: ctx.Cloudbrain.ContainerID,
  869. ImageDescription: form.Description,
  870. ImageTag: form.Tag,
  871. },
  872. IsPrivate: form.IsPrivate,
  873. CloudBrainType: form.Type,
  874. Topics: validTopics,
  875. UID: ctx.User.ID,
  876. })
  877. if err != nil {
  878. log.Error("CommitImage(%s) failed:%v", ctx.Cloudbrain.JobName, err.Error(), ctx.Data["msgID"])
  879. if models.IsErrImageTagExist(err) {
  880. ctx.JSON(200, models.BaseErrorMessage(ctx.Tr("repo.image_exist")))
  881. } else if models.IsErrorImageCommitting(err) {
  882. ctx.JSON(200, models.BaseErrorMessage(ctx.Tr("repo.image_committing")))
  883. } else {
  884. ctx.JSON(200, models.BaseErrorMessage(ctx.Tr("repo.image_commit_fail")))
  885. }
  886. return
  887. }
  888. ctx.JSON(200, models.BaseOKMessage)
  889. }
  890. func checkTopics(Topics string) ([]string, string) {
  891. var topics = make([]string, 0)
  892. var topicsStr = strings.TrimSpace(Topics)
  893. if len(topicsStr) > 0 {
  894. topics = strings.Split(topicsStr, ",")
  895. }
  896. validTopics, invalidTopics := models.SanitizeAndValidateImageTopics(topics)
  897. if len(validTopics) > 25 {
  898. return nil, "repo.topic.count_prompt"
  899. }
  900. if len(invalidTopics) > 0 {
  901. return nil, "repo.imagetopic.format_prompt"
  902. }
  903. return validTopics, ""
  904. }
  905. func CloudBrainStop(ctx *context.Context) {
  906. var ID = ctx.Params(":id")
  907. var resultCode = "0"
  908. var errorMsg = ""
  909. var status = ""
  910. task := ctx.Cloudbrain
  911. for {
  912. if task.Status == string(models.JobStopped) || task.Status == string(models.JobFailed) || task.Status == string(models.JobSucceeded) {
  913. log.Error("the job(%s) has been stopped", task.JobName, ctx.Data["msgID"])
  914. resultCode = "-1"
  915. errorMsg = "cloudbrain.Already_stopped"
  916. break
  917. }
  918. err := cloudbrain.StopJob(task.JobID)
  919. if err != nil {
  920. log.Error("StopJob(%s) failed:%v", task.JobName, err, ctx.Data["msgID"])
  921. resultCode = "-1"
  922. errorMsg = "cloudbrain.Stopped_failed"
  923. break
  924. }
  925. task.Status = string(models.JobStopped)
  926. if task.EndTime == 0 {
  927. task.EndTime = timeutil.TimeStampNow()
  928. }
  929. task.ComputeAndSetDuration()
  930. err = models.UpdateJob(task)
  931. if err != nil {
  932. log.Error("UpdateJob(%s) failed:%v", task.JobName, err, ctx.Data["msgID"])
  933. resultCode = "-1"
  934. errorMsg = "cloudbrain.Stopped_success_update_status_fail"
  935. break
  936. }
  937. status = task.Status
  938. break
  939. }
  940. ctx.JSON(200, map[string]interface{}{
  941. "result_code": resultCode,
  942. "error_msg": ctx.Tr(errorMsg),
  943. "status": status,
  944. "id": ID,
  945. "StatusOK": 0,
  946. })
  947. }
  948. func StopJobsByUserID(userID int64) {
  949. cloudBrains, err := models.GetCloudbrainsNeededStopByUserID(userID)
  950. if err != nil {
  951. log.Warn("Failed to get cloudBrain info", err)
  952. return
  953. }
  954. StopJobs(cloudBrains)
  955. }
  956. func StopJobsByRepoID(repoID int64) {
  957. cloudBrains, err := models.GetCloudbrainsNeededStopByRepoID(repoID)
  958. if err != nil {
  959. log.Warn("Failed to get cloudBrain info", err)
  960. return
  961. }
  962. StopJobs(cloudBrains)
  963. }
  964. /**
  965. */
  966. func StopJobs(cloudBrains []*models.Cloudbrain) {
  967. for _, taskInfo := range cloudBrains {
  968. if taskInfo.Type == models.TypeCloudBrainOne {
  969. err := retry(3, time.Second*30, func() error {
  970. return cloudbrain.StopJob(taskInfo.JobID)
  971. })
  972. logErrorAndUpdateJobStatus(err, taskInfo)
  973. } else {
  974. if taskInfo.JobType == string(models.JobTypeTrain) {
  975. err := retry(3, time.Second*30, func() error {
  976. _, err := modelarts.StopTrainJob(taskInfo.JobID, strconv.FormatInt(taskInfo.VersionID, 10))
  977. return err
  978. })
  979. logErrorAndUpdateJobStatus(err, taskInfo)
  980. } else {
  981. param := models.NotebookAction{
  982. Action: models.ActionStop,
  983. }
  984. err := retry(3, time.Second*30, func() error {
  985. _, err := modelarts.ManageNotebook(taskInfo.JobID, param)
  986. return err
  987. })
  988. logErrorAndUpdateJobStatus(err, taskInfo)
  989. }
  990. }
  991. }
  992. }
  993. func retry(attempts int, sleep time.Duration, f func() error) (err error) {
  994. for i := 0; i < attempts; i++ {
  995. if i > 0 {
  996. log.Warn("retrying after error:", err)
  997. time.Sleep(sleep)
  998. }
  999. err = f()
  1000. if err == nil {
  1001. return nil
  1002. }
  1003. }
  1004. return fmt.Errorf("after %d attempts, last error: %s", attempts, err)
  1005. }
  1006. func logErrorAndUpdateJobStatus(err error, taskInfo *models.Cloudbrain) {
  1007. if err != nil {
  1008. log.Warn("Failed to stop cloudBrain job:"+taskInfo.JobID, err)
  1009. } else {
  1010. taskInfo.Status = string(models.JobStopped)
  1011. if taskInfo.EndTime == 0 {
  1012. taskInfo.EndTime = timeutil.TimeStampNow()
  1013. }
  1014. taskInfo.ComputeAndSetDuration()
  1015. err = models.UpdateJob(taskInfo)
  1016. if err != nil {
  1017. log.Warn("UpdateJob failed", err)
  1018. }
  1019. }
  1020. }
  1021. func CloudBrainDel(ctx *context.Context) {
  1022. var listType = ctx.Query("debugListType")
  1023. if err := deleteCloudbrainJob(ctx); err != nil {
  1024. log.Error("deleteCloudbrainJob failed: %v", err, ctx.Data["msgID"])
  1025. ctx.ServerError(err.Error(), err)
  1026. return
  1027. }
  1028. var isAdminPage = ctx.Query("isadminpage")
  1029. var isHomePage = ctx.Query("ishomepage")
  1030. if ctx.IsUserSiteAdmin() && isAdminPage == "true" {
  1031. ctx.Redirect(setting.AppSubURL + "/admin" + "/cloudbrains")
  1032. } else if isHomePage == "true" {
  1033. ctx.Redirect(setting.AppSubURL + "/cloudbrains")
  1034. } else {
  1035. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/debugjob?debugListType=" + listType)
  1036. }
  1037. }
  1038. func deleteCloudbrainJob(ctx *context.Context) error {
  1039. task := ctx.Cloudbrain
  1040. if task.Status != string(models.JobStopped) && task.Status != string(models.JobFailed) && task.Status != string(models.JobSucceeded) {
  1041. log.Error("the job(%s) has not been stopped", task.JobName, ctx.Data["msgID"])
  1042. return errors.New("the job has not been stopped")
  1043. }
  1044. err := models.DeleteJob(task)
  1045. if err != nil {
  1046. log.Error("DeleteJob failed: %v", err, ctx.Data["msgID"])
  1047. return err
  1048. }
  1049. deleteJobStorage(task.JobName, models.TypeCloudBrainOne)
  1050. return nil
  1051. }
  1052. func CloudBrainShowModels(ctx *context.Context) {
  1053. ctx.Data["PageIsCloudBrain"] = true
  1054. ID := ctx.Params(":id")
  1055. parentDir := ctx.Query("parentDir")
  1056. dirArray := strings.Split(parentDir, "/")
  1057. task, err := models.GetCloudbrainByID(ID)
  1058. if err != nil {
  1059. log.Error("no such job!", ctx.Data["msgID"])
  1060. ctx.ServerError("no such job:", err)
  1061. return
  1062. }
  1063. //get dirs
  1064. dirs, err := GetModelDirs(task.JobName, parentDir)
  1065. if err != nil {
  1066. log.Error("GetModelDirs failed:%v", err.Error(), ctx.Data["msgID"])
  1067. ctx.ServerError("GetModelDirs failed:", err)
  1068. return
  1069. }
  1070. var fileInfos []storage.FileInfo
  1071. err = json.Unmarshal([]byte(dirs), &fileInfos)
  1072. if err != nil {
  1073. log.Error("json.Unmarshal failed:%v", err.Error(), ctx.Data["msgID"])
  1074. ctx.ServerError("json.Unmarshal failed:", err)
  1075. return
  1076. }
  1077. for i, fileInfo := range fileInfos {
  1078. temp, _ := time.Parse("2006-01-02 15:04:05", fileInfo.ModTime)
  1079. fileInfos[i].ModTime = temp.Local().Format("2006-01-02 15:04:05")
  1080. }
  1081. sort.Slice(fileInfos, func(i, j int) bool {
  1082. return fileInfos[i].ModTime > fileInfos[j].ModTime
  1083. })
  1084. ctx.Data["Path"] = dirArray
  1085. ctx.Data["Dirs"] = fileInfos
  1086. ctx.Data["task"] = task
  1087. ctx.Data["ID"] = ID
  1088. ctx.HTML(200, tplCloudBrainShowModels)
  1089. }
  1090. func GetPublicImages(ctx *context.Context) {
  1091. uid := getUID(ctx)
  1092. opts := models.SearchImageOptions{
  1093. IncludePublicOnly: true,
  1094. UID: uid,
  1095. Keyword: ctx.Query("q"),
  1096. Topics: ctx.Query("topic"),
  1097. IncludeOfficialOnly: ctx.QueryBool("recommend"),
  1098. SearchOrderBy: "type desc, num_stars desc,id desc",
  1099. Status: models.IMAGE_STATUS_SUCCESS,
  1100. CloudbrainType: ctx.QueryInt("cloudbrainType"),
  1101. }
  1102. getImages(ctx, &opts)
  1103. }
  1104. func GetCustomImages(ctx *context.Context) {
  1105. uid := getUID(ctx)
  1106. opts := models.SearchImageOptions{
  1107. UID: uid,
  1108. IncludeOwnerOnly: true,
  1109. Keyword: ctx.Query("q"),
  1110. Topics: ctx.Query("topic"),
  1111. Status: -1,
  1112. SearchOrderBy: "id desc",
  1113. }
  1114. getImages(ctx, &opts)
  1115. }
  1116. func GetStarImages(ctx *context.Context) {
  1117. uid := getUID(ctx)
  1118. opts := models.SearchImageOptions{
  1119. UID: uid,
  1120. IncludeStarByMe: true,
  1121. Keyword: ctx.Query("q"),
  1122. Topics: ctx.Query("topic"),
  1123. Status: models.IMAGE_STATUS_SUCCESS,
  1124. SearchOrderBy: "id desc",
  1125. }
  1126. getImages(ctx, &opts)
  1127. }
  1128. func getUID(ctx *context.Context) int64 {
  1129. var uid int64 = -1
  1130. if ctx.IsSigned {
  1131. uid = ctx.User.ID
  1132. }
  1133. return uid
  1134. }
  1135. func GetAllImages(ctx *context.Context) {
  1136. uid := getUID(ctx)
  1137. opts := models.SearchImageOptions{
  1138. UID: uid,
  1139. Keyword: ctx.Query("q"),
  1140. Topics: ctx.Query("topic"),
  1141. IncludeOfficialOnly: ctx.QueryBool("recommend"),
  1142. SearchOrderBy: "id desc",
  1143. Status: -1,
  1144. }
  1145. if ctx.Query("private") != "" {
  1146. if ctx.QueryBool("private") {
  1147. opts.IncludePrivateOnly = true
  1148. } else {
  1149. opts.IncludePublicOnly = true
  1150. }
  1151. }
  1152. getImages(ctx, &opts)
  1153. }
  1154. func getImages(ctx *context.Context, opts *models.SearchImageOptions) {
  1155. page := ctx.QueryInt("page")
  1156. if page <= 0 {
  1157. page = 1
  1158. }
  1159. pageSize := ctx.QueryInt("pageSize")
  1160. if pageSize <= 0 {
  1161. pageSize = 15
  1162. }
  1163. opts.ListOptions = models.ListOptions{
  1164. Page: page,
  1165. PageSize: pageSize,
  1166. }
  1167. imageList, total, err := models.SearchImage(opts)
  1168. if err != nil {
  1169. log.Error("Can not get images:%v", err)
  1170. ctx.JSON(http.StatusOK, models.ImagesPageResult{
  1171. Count: 0,
  1172. Images: []*models.Image{},
  1173. })
  1174. } else {
  1175. ctx.JSON(http.StatusOK, models.ImagesPageResult{
  1176. Count: total,
  1177. Images: imageList,
  1178. })
  1179. }
  1180. }
  1181. func GetModelDirs(jobName string, parentDir string) (string, error) {
  1182. var req string
  1183. modelActualPath := storage.GetMinioPath(jobName, cloudbrain.ModelMountPath+"/")
  1184. if parentDir == "" {
  1185. req = "baseDir=" + modelActualPath
  1186. } else {
  1187. req = "baseDir=" + modelActualPath + "&parentDir=" + parentDir
  1188. }
  1189. return getDirs(req)
  1190. }
  1191. func GetResultDirs(jobName string, parentDir string) (string, error) {
  1192. var req string
  1193. modelActualPath := storage.GetMinioPath(jobName, cloudbrain.ResultPath+"/")
  1194. if parentDir == "" {
  1195. req = "baseDir=" + modelActualPath
  1196. } else {
  1197. req = "baseDir=" + modelActualPath + "&parentDir=" + parentDir
  1198. }
  1199. return getDirs(req)
  1200. }
  1201. func CloudBrainDownloadModel(ctx *context.Context) {
  1202. parentDir := ctx.Query("parentDir")
  1203. fileName := ctx.Query("fileName")
  1204. jobName := ctx.Query("jobName")
  1205. filePath := "jobs/" + jobName + "/model/" + parentDir
  1206. url, err := storage.Attachments.PresignedGetURL(filePath, fileName)
  1207. if err != nil {
  1208. log.Error("PresignedGetURL failed: %v", err.Error(), ctx.Data["msgID"])
  1209. ctx.ServerError("PresignedGetURL", err)
  1210. return
  1211. }
  1212. ctx.Resp.Header().Set("Cache-Control", "max-age=0")
  1213. http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusMovedPermanently)
  1214. }
  1215. func CloudBrainDownloadInferenceResult(ctx *context.Context) {
  1216. parentDir := ctx.Query("parentDir")
  1217. fileName := ctx.Query("fileName")
  1218. jobName := ctx.Query("jobName")
  1219. filePath := "jobs/" + jobName + "/result/" + parentDir
  1220. url, err := storage.Attachments.PresignedGetURL(filePath, fileName)
  1221. if err != nil {
  1222. log.Error("PresignedGetURL failed: %v", err.Error(), ctx.Data["msgID"])
  1223. ctx.ServerError("PresignedGetURL", err)
  1224. return
  1225. }
  1226. ctx.Resp.Header().Set("Cache-Control", "max-age=0")
  1227. http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusMovedPermanently)
  1228. }
  1229. func GetRate(ctx *context.Context) {
  1230. isObjectDetcionAll := ctx.QueryBool("isObjectDetcionAll")
  1231. if isObjectDetcionAll {
  1232. ctx.Redirect(setting.BenchmarkServerHost + "?username=admin")
  1233. return
  1234. }
  1235. var ID = ctx.Params(":id")
  1236. job, err := models.GetCloudbrainByID(ID)
  1237. if err != nil {
  1238. ctx.ServerError("GetCloudbrainByJobID failed", err)
  1239. return
  1240. }
  1241. if job.JobType == string(models.JobTypeBenchmark) {
  1242. log.Info("url=" + setting.BenchmarkServerHost + "?username=" + ctx.User.Name)
  1243. ctx.Redirect(setting.BenchmarkServerHost + "?username=" + ctx.User.Name)
  1244. } else if job.JobType == string(models.JobTypeSnn4imagenet) {
  1245. ctx.Redirect(setting.Snn4imagenetServerHost)
  1246. } else if job.JobType == string(models.JobTypeBrainScore) {
  1247. ctx.Redirect(setting.BrainScoreServerHost)
  1248. } else {
  1249. log.Error("JobType error:%s", job.JobType, ctx.Data["msgID"])
  1250. }
  1251. }
  1252. func downloadCode(repo *models.Repository, codePath, branchName string) error {
  1253. //add "file:///" prefix to make the depth valid
  1254. if err := git.Clone(CLONE_FILE_PREFIX+repo.RepoPath(), codePath, git.CloneRepoOptions{Branch: branchName, Depth: 1}); err != nil {
  1255. log.Error("Failed to clone repository: %s (%v)", repo.FullName(), err)
  1256. return err
  1257. }
  1258. configFile, err := os.OpenFile(codePath+"/.git/config", os.O_RDWR, 0666)
  1259. if err != nil {
  1260. log.Error("open file(%s) failed:%v", codePath+"/,git/config", err)
  1261. return err
  1262. }
  1263. defer configFile.Close()
  1264. pos := int64(0)
  1265. reader := bufio.NewReader(configFile)
  1266. for {
  1267. line, err := reader.ReadString('\n')
  1268. if err != nil {
  1269. if err == io.EOF {
  1270. log.Error("not find the remote-url")
  1271. return nil
  1272. } else {
  1273. log.Error("read error: %v", err)
  1274. return err
  1275. }
  1276. }
  1277. if strings.Contains(line, "url") && strings.Contains(line, ".git") {
  1278. originUrl := "\turl = " + repo.CloneLink().HTTPS + "\n"
  1279. if len(line) > len(originUrl) {
  1280. originUrl += strings.Repeat(" ", len(line)-len(originUrl))
  1281. }
  1282. bytes := []byte(originUrl)
  1283. _, err := configFile.WriteAt(bytes, pos)
  1284. if err != nil {
  1285. log.Error("WriteAt failed:%v", err)
  1286. return err
  1287. }
  1288. break
  1289. }
  1290. pos += int64(len(line))
  1291. }
  1292. return nil
  1293. }
  1294. func downloadRateCode(repo *models.Repository, taskName, rateOwnerName, rateRepoName, codePath, benchmarkCategory, gpuType, userName string) error {
  1295. err := os.MkdirAll(codePath, os.ModePerm)
  1296. if err != nil {
  1297. log.Error("mkdir codePath failed", err.Error())
  1298. return err
  1299. }
  1300. repoExt, err := models.GetRepositoryByOwnerAndName(rateOwnerName, rateRepoName)
  1301. if err != nil {
  1302. log.Error("GetRepositoryByOwnerAndName(%s) failed", rateRepoName, err.Error())
  1303. return err
  1304. }
  1305. if err := git.Clone(CLONE_FILE_PREFIX+repoExt.RepoPath(), codePath, git.CloneRepoOptions{Depth: 1}); err != nil {
  1306. log.Error("Failed to clone repository: %s (%v)", repoExt.FullName(), err)
  1307. return err
  1308. }
  1309. fileName := codePath + cloudbrain.TaskInfoName
  1310. f, err := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.ModePerm)
  1311. if err != nil {
  1312. log.Error("OpenFile failed", err.Error())
  1313. return err
  1314. }
  1315. defer f.Close()
  1316. data, err := json.Marshal(models.TaskInfo{
  1317. Username: userName,
  1318. TaskName: taskName,
  1319. CodeName: repo.Name,
  1320. BenchmarkCategory: strings.Split(benchmarkCategory, ","),
  1321. CodeLink: strings.TrimSuffix(repo.CloneLink().HTTPS, ".git"),
  1322. GpuType: gpuType,
  1323. })
  1324. if err != nil {
  1325. log.Error("json.Marshal failed", err.Error())
  1326. return err
  1327. }
  1328. _, err = f.Write(data)
  1329. if err != nil {
  1330. log.Error("WriteString failed", err.Error())
  1331. return err
  1332. }
  1333. return nil
  1334. }
  1335. func uploadCodeToMinio(codePath, jobName, parentDir string) error {
  1336. files, err := readDir(codePath)
  1337. if err != nil {
  1338. log.Error("readDir(%s) failed: %s", codePath, err.Error())
  1339. return err
  1340. }
  1341. for _, file := range files {
  1342. if file.IsDir() {
  1343. if err = uploadCodeToMinio(codePath+file.Name()+"/", jobName, parentDir+file.Name()+"/"); err != nil {
  1344. log.Error("uploadCodeToMinio(%s) failed: %s", file.Name(), err.Error())
  1345. return err
  1346. }
  1347. } else {
  1348. destObject := setting.CBCodePathPrefix + jobName + parentDir + file.Name()
  1349. sourceFile := codePath + file.Name()
  1350. err = storage.Attachments.UploadObject(destObject, sourceFile)
  1351. if err != nil {
  1352. log.Error("UploadObject(%s) failed: %s", file.Name(), err.Error())
  1353. return err
  1354. }
  1355. }
  1356. }
  1357. return nil
  1358. }
  1359. func mkModelPath(modelPath string) error {
  1360. return mkPathAndReadMeFile(modelPath, "You can put the model file into this directory and download it by the web page.")
  1361. }
  1362. func mkResultPath(resultPath string) error {
  1363. return mkPathAndReadMeFile(resultPath, "You can put the result file into this directory and download it by the web page.")
  1364. }
  1365. func mkPathAndReadMeFile(path string, text string) error {
  1366. err := os.MkdirAll(path, os.ModePerm)
  1367. if err != nil {
  1368. log.Error("MkdirAll(%s) failed:%v", path, err)
  1369. return err
  1370. }
  1371. fileName := path + "README"
  1372. f, err := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.ModePerm)
  1373. if err != nil {
  1374. log.Error("OpenFile failed", err.Error())
  1375. return err
  1376. }
  1377. defer f.Close()
  1378. _, err = f.WriteString(text)
  1379. if err != nil {
  1380. log.Error("WriteString failed", err.Error())
  1381. return err
  1382. }
  1383. return nil
  1384. }
  1385. func deleteJobStorage(jobName string, cloudbrainType int) error {
  1386. //delete local
  1387. localJobPath := setting.JobPath + jobName
  1388. err := os.RemoveAll(localJobPath)
  1389. if err != nil {
  1390. log.Error("RemoveAll(%s) failed:%v", localJobPath, err)
  1391. }
  1392. //delete oss
  1393. if cloudbrainType == models.TypeCloudBrainOne {
  1394. dirPath := setting.CBCodePathPrefix + jobName + "/"
  1395. err = storage.Attachments.DeleteDir(dirPath)
  1396. if err != nil {
  1397. log.Error("DeleteDir(%s) failed:%v", localJobPath, err)
  1398. }
  1399. } else if cloudbrainType == models.TypeCloudBrainTwo {
  1400. //dirPath := setting.CodePathPrefix + jobName + "/"
  1401. //err = storage.ObsRemoveObject(setting.Bucket, dirPath)
  1402. //if err != nil {
  1403. // log.Error("ObsRemoveObject(%s) failed:%v", localJobPath, err)
  1404. //}
  1405. log.Info("no need to delete")
  1406. } else {
  1407. log.Error("cloudbrainType(%d) error", cloudbrainType)
  1408. }
  1409. return nil
  1410. }
  1411. func SyncCloudbrainStatus() {
  1412. cloudBrains, err := models.GetCloudBrainUnStoppedJob()
  1413. if err != nil {
  1414. log.Error("GetCloudBrainUnStoppedJob failed:", err.Error())
  1415. return
  1416. }
  1417. for _, task := range cloudBrains {
  1418. if task.Type == models.TypeCloudBrainOne {
  1419. result, err := cloudbrain.GetJob(task.JobID)
  1420. if err != nil {
  1421. log.Error("GetJob(%s) failed:%v", task.JobName, err)
  1422. continue
  1423. }
  1424. if result != nil {
  1425. jobRes, _ := models.ConvertToJobResultPayload(result.Payload)
  1426. taskRoles := jobRes.TaskRoles
  1427. taskRes, _ := models.ConvertToTaskPod(taskRoles[cloudbrain.SubTaskName].(map[string]interface{}))
  1428. task.Status = taskRes.TaskStatuses[0].State
  1429. if task.Status != string(models.JobWaiting) {
  1430. models.ParseAndSetDurationFromCloudBrainOne(jobRes, task)
  1431. err = models.UpdateJob(task)
  1432. if err != nil {
  1433. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1434. }
  1435. var maxDuration int64
  1436. if task.JobType == string(models.JobTypeBenchmark) {
  1437. maxDuration = setting.BenchmarkMaxDuration
  1438. } else if task.JobType == string(models.JobTypeSnn4imagenet) || task.JobType == string(models.JobTypeBrainScore) {
  1439. maxDuration = setting.ModelBenchmarkMaxDuration
  1440. } else {
  1441. maxDuration = setting.MaxDuration
  1442. }
  1443. if task.Duration >= maxDuration && task.JobType != string(models.JobTypeTrain) {
  1444. log.Info("begin to stop job(%s), because of the duration", task.DisplayJobName)
  1445. err = cloudbrain.StopJob(task.JobID)
  1446. if err != nil {
  1447. log.Error("StopJob(%s) failed:%v", task.DisplayJobName, err)
  1448. continue
  1449. }
  1450. task.Status = string(models.JobStopped)
  1451. if task.EndTime == 0 {
  1452. task.EndTime = timeutil.TimeStampNow()
  1453. }
  1454. task.ComputeAndSetDuration()
  1455. err = models.UpdateJob(task)
  1456. if err != nil {
  1457. log.Error("UpdateJob(%s) failed:%v", task.DisplayJobName, err)
  1458. continue
  1459. }
  1460. }
  1461. }
  1462. }
  1463. } else if task.Type == models.TypeCloudBrainTwo {
  1464. if task.JobType == string(models.JobTypeDebug) {
  1465. //result, err := modelarts.GetJob(task.JobID)
  1466. result, err := modelarts.GetNotebook2(task.JobID)
  1467. if err != nil {
  1468. log.Error("GetJob(%s) failed:%v", task.JobName, err)
  1469. continue
  1470. }
  1471. if result != nil {
  1472. task.Status = result.Status
  1473. if task.StartTime == 0 && result.Lease.UpdateTime > 0 {
  1474. task.StartTime = timeutil.TimeStamp(result.Lease.UpdateTime / 1000)
  1475. }
  1476. if task.EndTime == 0 && models.IsModelArtsDebugJobTerminal(task.Status) {
  1477. task.EndTime = timeutil.TimeStampNow()
  1478. }
  1479. task.CorrectCreateUnix()
  1480. task.ComputeAndSetDuration()
  1481. err = models.UpdateJob(task)
  1482. if err != nil {
  1483. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1484. continue
  1485. }
  1486. }
  1487. } else if task.JobType == string(models.JobTypeTrain) || task.JobType == string(models.JobTypeInference) {
  1488. result, err := modelarts.GetTrainJob(task.JobID, strconv.FormatInt(task.VersionID, 10))
  1489. if err != nil {
  1490. log.Error("GetTrainJob(%s) failed:%v", task.JobName, err)
  1491. continue
  1492. }
  1493. if result != nil {
  1494. task.Status = modelarts.TransTrainJobStatus(result.IntStatus)
  1495. task.Duration = result.Duration / 1000
  1496. task.TrainJobDuration = result.TrainJobDuration
  1497. if task.StartTime == 0 && result.StartTime > 0 {
  1498. task.StartTime = timeutil.TimeStamp(result.StartTime / 1000)
  1499. }
  1500. task.TrainJobDuration = models.ConvertDurationToStr(task.Duration)
  1501. if task.EndTime == 0 && models.IsTrainJobTerminal(task.Status) && task.StartTime > 0 {
  1502. task.EndTime = task.StartTime.Add(task.Duration)
  1503. }
  1504. task.CorrectCreateUnix()
  1505. err = models.UpdateJob(task)
  1506. if err != nil {
  1507. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1508. continue
  1509. }
  1510. }
  1511. } else {
  1512. log.Error("task.JobType(%s) is error:%s", task.JobName, task.JobType)
  1513. }
  1514. } else if task.Type == models.TypeC2Net {
  1515. result, err := grampus.GetJob(task.JobID)
  1516. if err != nil {
  1517. log.Error("GetTrainJob(%s) failed:%v", task.JobName, err)
  1518. continue
  1519. }
  1520. if result != nil {
  1521. if len(result.JobInfo.Tasks[0].CenterID) == 1 && len(result.JobInfo.Tasks[0].CenterName) == 1 {
  1522. task.AiCenter = result.JobInfo.Tasks[0].CenterID[0] + "+" + result.JobInfo.Tasks[0].CenterName[0]
  1523. }
  1524. task.Status = grampus.TransTrainJobStatus(result.JobInfo.Status)
  1525. task.Duration = result.JobInfo.RunSec
  1526. task.TrainJobDuration = models.ConvertDurationToStr(task.Duration)
  1527. if task.StartTime == 0 && result.JobInfo.StartedAt > 0 {
  1528. task.StartTime = timeutil.TimeStamp(result.JobInfo.StartedAt)
  1529. }
  1530. if task.EndTime == 0 && models.IsTrainJobTerminal(task.Status) && task.StartTime > 0 {
  1531. task.EndTime = task.StartTime.Add(task.Duration)
  1532. }
  1533. task.CorrectCreateUnix()
  1534. err = models.UpdateJob(task)
  1535. if err != nil {
  1536. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1537. continue
  1538. }
  1539. }
  1540. } else {
  1541. log.Error("task.Type(%s) is error:%d", task.JobName, task.Type)
  1542. }
  1543. }
  1544. return
  1545. }
  1546. func HandleTaskWithNoDuration(ctx *context.Context) {
  1547. mode := ctx.Query("mode")
  1548. log.Info("HandleTaskWithNoDuration start")
  1549. count := 0
  1550. start := time.Now().Unix()
  1551. for {
  1552. var cloudBrains []*models.Cloudbrain
  1553. var err error
  1554. if mode == "1" {
  1555. cloudBrains, err = models.GetStoppedJobWithNoStartTimeEndTime()
  1556. } else {
  1557. cloudBrains, err = models.GetStoppedJobWithNoDurationJob()
  1558. }
  1559. if err != nil {
  1560. log.Error("HandleTaskWithNoTrainJobDuration failed:", err.Error())
  1561. break
  1562. }
  1563. if len(cloudBrains) == 0 {
  1564. log.Info("HandleTaskWithNoTrainJobDuration:no task need handle")
  1565. break
  1566. }
  1567. handleNoDurationTask(cloudBrains)
  1568. count += len(cloudBrains)
  1569. if len(cloudBrains) < 100 {
  1570. log.Info("HandleTaskWithNoTrainJobDuration:task less than 100")
  1571. break
  1572. }
  1573. if time.Now().Unix()-start > 600 {
  1574. log.Info("HandleTaskWithNoDuration : time out")
  1575. ctx.JSON(200, fmt.Sprintf("task stop for time out,count=%d", count))
  1576. return
  1577. }
  1578. }
  1579. log.Info("HandleTaskWithNoTrainJobDuration:count=%d", count)
  1580. ctx.JSON(200, fmt.Sprintf("success,count=%d", count))
  1581. }
  1582. func handleNoDurationTask(cloudBrains []*models.Cloudbrain) {
  1583. for _, task := range cloudBrains {
  1584. time.Sleep(time.Millisecond * 100)
  1585. log.Info("Handle job ,%+v", task)
  1586. if task.Type == models.TypeCloudBrainOne {
  1587. result, err := cloudbrain.GetJob(task.JobID)
  1588. if err != nil {
  1589. log.Error("GetJob(%s) failed:%v", task.JobName, err)
  1590. updateDefaultDuration(task)
  1591. continue
  1592. }
  1593. if result != nil {
  1594. if result.Msg != "success" {
  1595. updateDefaultDuration(task)
  1596. continue
  1597. }
  1598. jobRes, err := models.ConvertToJobResultPayload(result.Payload)
  1599. if err != nil || len(jobRes.TaskRoles) == 0 {
  1600. updateDefaultDuration(task)
  1601. continue
  1602. }
  1603. taskRoles := jobRes.TaskRoles
  1604. taskRes, err := models.ConvertToTaskPod(taskRoles[cloudbrain.SubTaskName].(map[string]interface{}))
  1605. if err != nil || len(taskRes.TaskStatuses) == 0 {
  1606. updateDefaultDuration(task)
  1607. continue
  1608. }
  1609. task.Status = taskRes.TaskStatuses[0].State
  1610. log.Info("task startTime = %v endTime= %v ,jobId=%d", jobRes.JobStatus.StartTime, jobRes.JobStatus.EndTime, task.ID)
  1611. if jobRes.JobStatus.CreatedTime > 0 {
  1612. task.StartTime = timeutil.TimeStamp(jobRes.JobStatus.CreatedTime / 1000)
  1613. if jobRes.JobStatus.CompletedTime > 0 {
  1614. task.EndTime = timeutil.TimeStamp(jobRes.JobStatus.CompletedTime / 1000)
  1615. } else {
  1616. task.EndTime = task.UpdatedUnix
  1617. }
  1618. } else {
  1619. task.StartTime = 0
  1620. task.EndTime = 0
  1621. }
  1622. if task.EndTime < task.StartTime {
  1623. log.Info("endTime[%v] is less than starTime[%v],jobId=%d", task.EndTime, task.StartTime, task.ID)
  1624. st := task.StartTime
  1625. task.StartTime = task.EndTime
  1626. task.EndTime = st
  1627. }
  1628. task.Duration = task.EndTime.AsTime().Unix() - task.StartTime.AsTime().Unix()
  1629. task.TrainJobDuration = models.ConvertDurationToStr(task.Duration)
  1630. err = models.UpdateJobDurationWithDeleted(task)
  1631. if err != nil {
  1632. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1633. }
  1634. }
  1635. } else if task.Type == models.TypeCloudBrainTwo {
  1636. if task.JobType == string(models.JobTypeDebug) {
  1637. //result, err := modelarts.GetJob(task.JobID)
  1638. result, err := modelarts.GetNotebook2(task.JobID)
  1639. if err != nil {
  1640. log.Error("GetJob(%s) failed:%v", task.JobName, err)
  1641. updateDefaultDuration(task)
  1642. continue
  1643. }
  1644. if result != nil {
  1645. task.Status = result.Status
  1646. startTime := result.Lease.CreateTime
  1647. duration := result.Lease.Duration / 1000
  1648. if startTime > 0 {
  1649. task.StartTime = timeutil.TimeStamp(startTime / 1000)
  1650. task.EndTime = task.StartTime.Add(duration)
  1651. }
  1652. task.CorrectCreateUnix()
  1653. task.ComputeAndSetDuration()
  1654. err = models.UpdateJobDurationWithDeleted(task)
  1655. if err != nil {
  1656. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1657. continue
  1658. }
  1659. }
  1660. } else if task.JobType == string(models.JobTypeTrain) || task.JobType == string(models.JobTypeInference) {
  1661. result, err := modelarts.GetTrainJob(task.JobID, strconv.FormatInt(task.VersionID, 10))
  1662. if err != nil {
  1663. log.Error("GetTrainJob(%s) failed:%v", task.JobName, err)
  1664. updateDefaultDuration(task)
  1665. continue
  1666. }
  1667. if result != nil {
  1668. startTime := result.StartTime / 1000
  1669. if startTime > 0 {
  1670. task.StartTime = timeutil.TimeStamp(startTime)
  1671. task.EndTime = task.StartTime.Add(result.Duration / 1000)
  1672. }
  1673. task.ComputeAndSetDuration()
  1674. err = models.UpdateJobDurationWithDeleted(task)
  1675. if err != nil {
  1676. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1677. continue
  1678. }
  1679. }
  1680. } else {
  1681. log.Error("task.JobType(%s) is error:%s", task.JobName, task.JobType)
  1682. }
  1683. } else {
  1684. log.Error("task.Type(%s) is error:%d", task.JobName, task.Type)
  1685. }
  1686. }
  1687. }
  1688. func updateDefaultDuration(task *models.Cloudbrain) {
  1689. log.Info("updateDefaultDuration: taskId=%d", task.ID)
  1690. task.StartTime = task.CreatedUnix
  1691. task.EndTime = task.UpdatedUnix
  1692. task.ComputeAndSetDuration()
  1693. err := models.UpdateJobDurationWithDeleted(task)
  1694. if err != nil {
  1695. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1696. }
  1697. }
  1698. func CloudBrainBenchmarkIndex(ctx *context.Context) {
  1699. MustEnableCloudbrain(ctx)
  1700. repo := ctx.Repo.Repository
  1701. page := ctx.QueryInt("page")
  1702. if page <= 0 {
  1703. page = 1
  1704. }
  1705. var jobTypes []string
  1706. jobTypes = append(jobTypes, string(models.JobTypeBenchmark), string(models.JobTypeBrainScore), string(models.JobTypeSnn4imagenet))
  1707. ciTasks, count, err := models.Cloudbrains(&models.CloudbrainsOptions{
  1708. ListOptions: models.ListOptions{
  1709. Page: page,
  1710. PageSize: setting.UI.IssuePagingNum,
  1711. },
  1712. RepoID: repo.ID,
  1713. Type: models.TypeCloudBrainOne,
  1714. JobTypes: jobTypes,
  1715. })
  1716. if err != nil {
  1717. ctx.ServerError("Get debugjob faild:", err)
  1718. return
  1719. }
  1720. for i, task := range ciTasks {
  1721. ciTasks[i].CanDel = cloudbrain.CanDeleteJob(ctx, &task.Cloudbrain)
  1722. ciTasks[i].Cloudbrain.ComputeResource = task.ComputeResource
  1723. if ciTasks[i].TrainJobDuration == "" {
  1724. if ciTasks[i].Duration == 0 {
  1725. var duration int64
  1726. if task.Status == string(models.JobRunning) {
  1727. duration = time.Now().Unix() - int64(task.Cloudbrain.CreatedUnix)
  1728. } else {
  1729. duration = int64(task.Cloudbrain.UpdatedUnix) - int64(task.Cloudbrain.CreatedUnix)
  1730. }
  1731. ciTasks[i].Duration = duration
  1732. }
  1733. ciTasks[i].TrainJobDuration = models.ConvertDurationToStr(ciTasks[i].Duration)
  1734. }
  1735. ciTasks[i].BenchmarkTypeName = ""
  1736. if ciTasks[i].JobType == string(models.JobTypeBenchmark) {
  1737. ciTasks[i].BenchmarkType = ctx.Tr("repo.cloudbrain.benchmark.algorithm")
  1738. } else if ciTasks[i].JobType == string(models.JobTypeSnn4imagenet) || ciTasks[i].JobType == string(models.JobTypeBrainScore) {
  1739. ciTasks[i].BenchmarkType = ctx.Tr("repo.cloudbrain.benchmark.model")
  1740. ciTasks[i].BenchmarkTypeName = ciTasks[i].JobType
  1741. if ciTasks[i].JobType == string(models.JobTypeSnn4imagenet) {
  1742. ciTasks[i].BenchmarkTypeRankLink = setting.Snn4imagenetServerHost
  1743. } else {
  1744. ciTasks[i].BenchmarkTypeRankLink = setting.BrainScoreServerHost
  1745. }
  1746. }
  1747. if task.BenchmarkTypeID > 0 {
  1748. for _, benchmarkType := range GetBenchmarkTypes(ctx).BenchmarkType {
  1749. if task.BenchmarkTypeID == benchmarkType.Id {
  1750. ciTasks[i].BenchmarkTypeRankLink = benchmarkType.RankLink
  1751. ciTasks[i].BenchmarkTypeName = benchmarkType.First
  1752. break
  1753. }
  1754. }
  1755. }
  1756. }
  1757. pager := context.NewPagination(int(count), setting.UI.IssuePagingNum, page, 5)
  1758. ctx.Data["Page"] = pager
  1759. ctx.Data["PageIsCloudBrain"] = true
  1760. ctx.Data["Tasks"] = ciTasks
  1761. ctx.Data["CanCreate"] = cloudbrain.CanCreateOrDebugJob(ctx)
  1762. ctx.Data["RepoIsEmpty"] = repo.IsEmpty
  1763. ctx.HTML(200, tplCloudBrainBenchmarkIndex)
  1764. }
  1765. func GetChildTypes(ctx *context.Context) {
  1766. benchmarkTypeID := ctx.QueryInt("benchmark_type_id")
  1767. re := make(map[string]interface{})
  1768. for {
  1769. var isExist bool
  1770. for _, benchmarkType := range GetBenchmarkTypes(ctx).BenchmarkType {
  1771. if benchmarkTypeID == benchmarkType.Id {
  1772. isExist = true
  1773. re["child_types"] = benchmarkType.Second
  1774. re["result_code"] = "0"
  1775. break
  1776. }
  1777. }
  1778. if !isExist {
  1779. re["result_code"] = "1"
  1780. log.Error("no such benchmark_type_id", ctx.Data["MsgID"])
  1781. re["errMsg"] = "system error"
  1782. break
  1783. }
  1784. break
  1785. }
  1786. ctx.JSON(200, re)
  1787. }
  1788. func CloudBrainBenchmarkNew(ctx *context.Context) {
  1789. ctx.Data["description"] = ""
  1790. ctx.Data["benchmarkTypeID"] = -1
  1791. ctx.Data["benchmark_child_types_id_hidden"] = -1
  1792. err := cloudBrainNewDataPrepare(ctx)
  1793. if err != nil {
  1794. ctx.ServerError("get new cloudbrain info failed", err)
  1795. return
  1796. }
  1797. ctx.HTML(200, tplCloudBrainBenchmarkNew)
  1798. }
  1799. func getBenchmarkAttachment(benchmarkTypeID, benchmarkChildTypeID int, ctx *context.Context) (*models.BenchmarkDataset, error) {
  1800. var childInfo *models.BenchmarkDataset
  1801. var isExist bool
  1802. for _, benchmarkType := range GetBenchmarkTypes(ctx).BenchmarkType {
  1803. if benchmarkType.Id == benchmarkTypeID {
  1804. for _, childType := range benchmarkType.Second {
  1805. if childType.Id == benchmarkChildTypeID {
  1806. childInfo = childType
  1807. isExist = true
  1808. break
  1809. }
  1810. }
  1811. break
  1812. }
  1813. }
  1814. if !isExist {
  1815. log.Error("no such benchmark_type_id&benchmark_child_type_id")
  1816. return childInfo, errors.New("no such benchmark_type_id&benchmark_child_type_id")
  1817. }
  1818. return childInfo, nil
  1819. }
  1820. func getBenchmarkGpuQueue(gpuQueue string) (string, error) {
  1821. queue := ""
  1822. if benchmarkGpuInfos == nil {
  1823. if err := json.Unmarshal([]byte(setting.BenchmarkGpuTypes), &benchmarkGpuInfos); err != nil {
  1824. log.Error("json.Unmarshal BenchmarkGpuTypes(%s) failed:%v", setting.BenchmarkGpuTypes, err)
  1825. return queue, err
  1826. }
  1827. }
  1828. var isExist bool
  1829. for _, gpuInfo := range benchmarkGpuInfos.GpuInfo {
  1830. if gpuQueue == gpuInfo.Queue {
  1831. isExist = true
  1832. queue = gpuQueue
  1833. break
  1834. }
  1835. }
  1836. if !isExist {
  1837. log.Error("no such gpuQueue, %s", gpuQueue)
  1838. return queue, errors.New("no such gpuQueue")
  1839. }
  1840. return queue, nil
  1841. }
  1842. func getBenchmarkResourceSpec(resourceSpecID int) (int, error) {
  1843. var id int
  1844. if benchmarkResourceSpecs == nil {
  1845. if err := json.Unmarshal([]byte(setting.BenchmarkResourceSpecs), &benchmarkResourceSpecs); err != nil {
  1846. log.Error("json.Unmarshal BenchmarkResourceSpecs(%s) failed:%v", setting.BenchmarkResourceSpecs, err)
  1847. return id, err
  1848. }
  1849. }
  1850. var isExist bool
  1851. for _, resourceSpec := range benchmarkResourceSpecs.ResourceSpec {
  1852. if resourceSpecID == resourceSpec.Id {
  1853. isExist = true
  1854. id = resourceSpecID
  1855. break
  1856. }
  1857. }
  1858. if !isExist {
  1859. log.Error("no such resourceSpecID, %d", resourceSpecID)
  1860. return id, errors.New("no such resourceSpec")
  1861. }
  1862. return id, nil
  1863. }
  1864. func CloudBrainBenchmarkCreate(ctx *context.Context, form auth.CreateCloudBrainForm) {
  1865. jobType := form.JobType
  1866. if jobType == string(models.JobTypeBenchmark) {
  1867. BenchMarkAlgorithmCreate(ctx, form)
  1868. } else {
  1869. ModelBenchmarkCreate(ctx, form)
  1870. }
  1871. }
  1872. func BenchMarkAlgorithmCreate(ctx *context.Context, form auth.CreateCloudBrainForm) {
  1873. ctx.Data["PageIsCloudBrain"] = true
  1874. displayJobName := form.DisplayJobName
  1875. jobName := util.ConvertDisplayJobNameToJobName(displayJobName)
  1876. image := strings.TrimSpace(form.Image)
  1877. gpuQueue := form.GpuType
  1878. command := cloudbrain.CommandBenchmark
  1879. codePath := setting.JobPath + jobName + cloudbrain.CodeMountPath
  1880. resourceSpecId := cloudbrain.BenchMarkResourceID
  1881. benchmarkTypeID := form.BenchmarkTypeID
  1882. benchmarkChildTypeID := form.BenchmarkChildTypeID
  1883. ctx.Data["description"] = form.Description
  1884. ctx.Data["benchmarkTypeID"] = benchmarkTypeID
  1885. ctx.Data["benchmark_child_types_id_hidden"] = benchmarkChildTypeID
  1886. repo := ctx.Repo.Repository
  1887. tasks, err := models.GetCloudbrainsByDisplayJobName(repo.ID, string(models.JobTypeBenchmark), displayJobName)
  1888. if err == nil {
  1889. if len(tasks) != 0 {
  1890. log.Error("the job name did already exist", ctx.Data["MsgID"])
  1891. cloudBrainNewDataPrepare(ctx)
  1892. ctx.RenderWithErr("the job name did already exist", tplCloudBrainBenchmarkNew, &form)
  1893. return
  1894. }
  1895. } else {
  1896. if !models.IsErrJobNotExist(err) {
  1897. log.Error("system error, %v", err, ctx.Data["MsgID"])
  1898. cloudBrainNewDataPrepare(ctx)
  1899. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  1900. return
  1901. }
  1902. }
  1903. if !jobNamePattern.MatchString(jobName) {
  1904. cloudBrainNewDataPrepare(ctx)
  1905. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_jobname_err"), tplCloudBrainBenchmarkNew, &form)
  1906. return
  1907. }
  1908. childInfo, err := getBenchmarkAttachment(benchmarkTypeID, benchmarkChildTypeID, ctx)
  1909. if err != nil {
  1910. log.Error("getBenchmarkAttachment failed:%v", err, ctx.Data["MsgID"])
  1911. cloudBrainNewDataPrepare(ctx)
  1912. ctx.RenderWithErr("benchmark type error", tplCloudBrainBenchmarkNew, &form)
  1913. return
  1914. }
  1915. _, err = getBenchmarkGpuQueue(gpuQueue)
  1916. if err != nil {
  1917. log.Error("getBenchmarkGpuQueue failed:%v", err, ctx.Data["MsgID"])
  1918. cloudBrainNewDataPrepare(ctx)
  1919. ctx.RenderWithErr("gpu queue error", tplCloudBrainBenchmarkNew, &form)
  1920. return
  1921. }
  1922. _, err = getBenchmarkResourceSpec(resourceSpecId)
  1923. if err != nil {
  1924. log.Error("getBenchmarkResourceSpec failed:%v", err, ctx.Data["MsgID"])
  1925. cloudBrainNewDataPrepare(ctx)
  1926. ctx.RenderWithErr("resource spec error", tplCloudBrainBenchmarkNew, &form)
  1927. return
  1928. }
  1929. count, err := models.GetBenchmarkCountByUserID(ctx.User.ID)
  1930. if err != nil {
  1931. log.Error("GetCloudbrainCountByUserID failed:%v", err, ctx.Data["MsgID"])
  1932. cloudBrainNewDataPrepare(ctx)
  1933. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  1934. return
  1935. } else {
  1936. if count >= 1 {
  1937. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  1938. cloudBrainNewDataPrepare(ctx)
  1939. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain.morethanonejob"), tplCloudBrainBenchmarkNew, &form)
  1940. return
  1941. }
  1942. }
  1943. os.RemoveAll(codePath)
  1944. if err := downloadCode(repo, codePath, cloudbrain.DefaultBranchName); err != nil {
  1945. log.Error("downloadCode failed, %v", err, ctx.Data["MsgID"])
  1946. cloudBrainNewDataPrepare(ctx)
  1947. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  1948. return
  1949. }
  1950. if _, err := os.Stat(codePath + "/train.py"); err != nil {
  1951. if os.IsNotExist(err) {
  1952. // file does not exist
  1953. log.Error("train.py does not exist, %v", err, ctx.Data["MsgID"])
  1954. cloudBrainNewDataPrepare(ctx)
  1955. ctx.RenderWithErr("train.py does not exist", tplCloudBrainBenchmarkNew, &form)
  1956. } else {
  1957. log.Error("Stat failed, %v", err, ctx.Data["MsgID"])
  1958. cloudBrainNewDataPrepare(ctx)
  1959. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  1960. }
  1961. return
  1962. } else if _, err := os.Stat(codePath + "/test.py"); err != nil {
  1963. if os.IsNotExist(err) {
  1964. // file does not exist
  1965. log.Error("test.py does not exist, %v", err, ctx.Data["MsgID"])
  1966. cloudBrainNewDataPrepare(ctx)
  1967. ctx.RenderWithErr("test.py does not exist", tplCloudBrainBenchmarkNew, &form)
  1968. } else {
  1969. log.Error("Stat failed, %v", err, ctx.Data["MsgID"])
  1970. cloudBrainNewDataPrepare(ctx)
  1971. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  1972. }
  1973. return
  1974. }
  1975. if err := uploadCodeToMinio(codePath+"/", jobName, cloudbrain.CodeMountPath+"/"); err != nil {
  1976. log.Error("uploadCodeToMinio failed, %v", err, ctx.Data["MsgID"])
  1977. cloudBrainNewDataPrepare(ctx)
  1978. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  1979. return
  1980. }
  1981. benchmarkPath := setting.JobPath + jobName + cloudbrain.BenchMarkMountPath
  1982. var gpuType string
  1983. for _, gpuInfo := range gpuInfos.GpuInfo {
  1984. if gpuInfo.Queue == gpuQueue {
  1985. gpuType = gpuInfo.Value
  1986. }
  1987. }
  1988. if err := downloadRateCode(repo, jobName, childInfo.Owner, childInfo.RepoName, benchmarkPath, form.BenchmarkCategory, gpuType, ctx.User.Name); err != nil {
  1989. log.Error("downloadRateCode failed, %v", err, ctx.Data["MsgID"])
  1990. //cloudBrainNewDataPrepare(ctx)
  1991. //ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  1992. //return
  1993. }
  1994. if err := uploadCodeToMinio(benchmarkPath+"/", jobName, cloudbrain.BenchMarkMountPath+"/"); err != nil {
  1995. log.Error("uploadCodeToMinio failed, %v", err, ctx.Data["MsgID"])
  1996. //cloudBrainNewDataPrepare(ctx)
  1997. //ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  1998. //return
  1999. }
  2000. uuid := childInfo.Attachment
  2001. datasetInfos, datasetNames, err := models.GetDatasetInfo(uuid)
  2002. if err != nil {
  2003. log.Error("GetDatasetInfo failed: %v", err, ctx.Data["MsgID"])
  2004. cloudBrainNewDataPrepare(ctx)
  2005. ctx.RenderWithErr(ctx.Tr("cloudbrain.error.dataset_select"), tplCloudBrainBenchmarkNew, &form)
  2006. return
  2007. }
  2008. req := cloudbrain.GenerateCloudBrainTaskReq{
  2009. Ctx: ctx,
  2010. DisplayJobName: displayJobName,
  2011. JobName: jobName,
  2012. Image: image,
  2013. Command: command,
  2014. Uuids: uuid,
  2015. DatasetNames: datasetNames,
  2016. DatasetInfos: datasetInfos,
  2017. CodePath: storage.GetMinioPath(jobName, cloudbrain.CodeMountPath+"/"),
  2018. ModelPath: storage.GetMinioPath(jobName, cloudbrain.ModelMountPath+"/"),
  2019. BenchmarkPath: storage.GetMinioPath(jobName, cloudbrain.BenchMarkMountPath+"/"),
  2020. Snn4ImageNetPath: storage.GetMinioPath(jobName, cloudbrain.Snn4imagenetMountPath+"/"),
  2021. BrainScorePath: storage.GetMinioPath(jobName, cloudbrain.BrainScoreMountPath+"/"),
  2022. JobType: string(models.JobTypeBenchmark),
  2023. GpuQueue: gpuQueue,
  2024. Description: form.Description,
  2025. BranchName: cloudbrain.DefaultBranchName,
  2026. BootFile: "",
  2027. Params: "",
  2028. CommitID: "",
  2029. BenchmarkTypeID: benchmarkTypeID,
  2030. BenchmarkChildTypeID: benchmarkChildTypeID,
  2031. ResourceSpecId: resourceSpecId,
  2032. ResultPath: storage.GetMinioPath(jobName, cloudbrain.ResultPath+"/"),
  2033. }
  2034. err = cloudbrain.GenerateTask(req)
  2035. if err != nil {
  2036. cloudBrainNewDataPrepare(ctx)
  2037. ctx.RenderWithErr(err.Error(), tplCloudBrainBenchmarkNew, &form)
  2038. return
  2039. }
  2040. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/cloudbrain/benchmark")
  2041. }
  2042. func ModelBenchmarkCreate(ctx *context.Context, form auth.CreateCloudBrainForm) {
  2043. ctx.Data["PageIsCloudBrain"] = true
  2044. displayJobName := form.DisplayJobName
  2045. jobName := util.ConvertDisplayJobNameToJobName(displayJobName)
  2046. image := form.Image
  2047. uuid := form.Attachment
  2048. jobType := form.JobType
  2049. gpuQueue := form.GpuType
  2050. codePath := setting.JobPath + jobName + cloudbrain.CodeMountPath
  2051. resourceSpecId := form.ResourceSpecId
  2052. branchName := cloudbrain.DefaultBranchName
  2053. repo := ctx.Repo.Repository
  2054. tpl := tplCloudBrainBenchmarkNew
  2055. command := cloudbrain.GetCloudbrainDebugCommand()
  2056. tasks, err := models.GetCloudbrainsByDisplayJobName(repo.ID, jobType, displayJobName)
  2057. if err == nil {
  2058. if len(tasks) != 0 {
  2059. log.Error("the job name did already exist", ctx.Data["MsgID"])
  2060. cloudBrainNewDataPrepare(ctx)
  2061. ctx.RenderWithErr("the job name did already exist", tpl, &form)
  2062. return
  2063. }
  2064. } else {
  2065. if !models.IsErrJobNotExist(err) {
  2066. log.Error("system error, %v", err, ctx.Data["MsgID"])
  2067. cloudBrainNewDataPrepare(ctx)
  2068. ctx.RenderWithErr("system error", tpl, &form)
  2069. return
  2070. }
  2071. }
  2072. if !jobNamePattern.MatchString(displayJobName) {
  2073. cloudBrainNewDataPrepare(ctx)
  2074. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_jobname_err"), tpl, &form)
  2075. return
  2076. }
  2077. if jobType != string(models.JobTypeSnn4imagenet) && jobType != string(models.JobTypeBrainScore) {
  2078. log.Error("jobtype error:", jobType, ctx.Data["MsgID"])
  2079. cloudBrainNewDataPrepare(ctx)
  2080. ctx.RenderWithErr("jobtype error", tpl, &form)
  2081. return
  2082. }
  2083. count, err := models.GetBenchmarkCountByUserID(ctx.User.ID)
  2084. if err != nil {
  2085. log.Error("GetCloudbrainCountByUserID failed:%v", err, ctx.Data["MsgID"])
  2086. cloudBrainNewDataPrepare(ctx)
  2087. ctx.RenderWithErr("system error", tpl, &form)
  2088. return
  2089. } else {
  2090. if count >= 1 {
  2091. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  2092. cloudBrainNewDataPrepare(ctx)
  2093. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain.morethanonejob"), tpl, &form)
  2094. return
  2095. }
  2096. }
  2097. downloadCode(repo, codePath, branchName)
  2098. uploadCodeToMinio(codePath+"/", jobName, cloudbrain.CodeMountPath+"/")
  2099. modelPath := setting.JobPath + jobName + cloudbrain.ModelMountPath + "/"
  2100. mkModelPath(modelPath)
  2101. uploadCodeToMinio(modelPath, jobName, cloudbrain.ModelMountPath+"/")
  2102. snn4imagenetPath := setting.JobPath + jobName + cloudbrain.Snn4imagenetMountPath
  2103. if setting.IsSnn4imagenetEnabled && jobType == string(models.JobTypeSnn4imagenet) {
  2104. downloadRateCode(repo, jobName, setting.Snn4imagenetOwner, setting.Snn4imagenetName, snn4imagenetPath, "", "", ctx.User.Name)
  2105. uploadCodeToMinio(snn4imagenetPath+"/", jobName, cloudbrain.Snn4imagenetMountPath+"/")
  2106. command = fmt.Sprintf(cloudbrain.Snn4imagenetCommand, displayJobName, trimSpaceNewlineInString(form.Description))
  2107. }
  2108. benchmarkChildTypeID := 0
  2109. brainScorePath := setting.JobPath + jobName + cloudbrain.BrainScoreMountPath
  2110. if setting.IsBrainScoreEnabled && jobType == string(models.JobTypeBrainScore) {
  2111. downloadRateCode(repo, jobName, setting.BrainScoreOwner, setting.BrainScoreName, brainScorePath, "", "", ctx.User.Name)
  2112. uploadCodeToMinio(brainScorePath+"/", jobName, cloudbrain.BrainScoreMountPath+"/")
  2113. benchmarkChildTypeID = form.BenchmarkChildTypeID
  2114. command = fmt.Sprintf(cloudbrain.BrainScoreCommand, getBrainRegion(benchmarkChildTypeID), displayJobName, trimSpaceNewlineInString(form.Description))
  2115. }
  2116. datasetInfos, datasetNames, err := models.GetDatasetInfo(uuid)
  2117. if err != nil {
  2118. log.Error("GetDatasetInfo failed: %v", err, ctx.Data["MsgID"])
  2119. cloudBrainNewDataPrepare(ctx)
  2120. ctx.RenderWithErr(ctx.Tr("cloudbrain.error.dataset_select"), tpl, &form)
  2121. return
  2122. }
  2123. req := cloudbrain.GenerateCloudBrainTaskReq{
  2124. Ctx: ctx,
  2125. DisplayJobName: displayJobName,
  2126. JobName: jobName,
  2127. Image: image,
  2128. Command: command,
  2129. Uuids: uuid,
  2130. DatasetNames: datasetNames,
  2131. DatasetInfos: datasetInfos,
  2132. CodePath: storage.GetMinioPath(jobName, cloudbrain.CodeMountPath+"/"),
  2133. ModelPath: storage.GetMinioPath(jobName, cloudbrain.ModelMountPath+"/"),
  2134. BenchmarkPath: storage.GetMinioPath(jobName, cloudbrain.BenchMarkMountPath+"/"),
  2135. Snn4ImageNetPath: storage.GetMinioPath(jobName, cloudbrain.Snn4imagenetMountPath+"/"),
  2136. BrainScorePath: storage.GetMinioPath(jobName, cloudbrain.BrainScoreMountPath+"/"),
  2137. JobType: jobType,
  2138. GpuQueue: gpuQueue,
  2139. Description: form.Description,
  2140. BranchName: branchName,
  2141. BootFile: form.BootFile,
  2142. Params: form.Params,
  2143. CommitID: "",
  2144. BenchmarkTypeID: 0,
  2145. BenchmarkChildTypeID: benchmarkChildTypeID,
  2146. ResourceSpecId: resourceSpecId,
  2147. ResultPath: storage.GetMinioPath(jobName, cloudbrain.ResultPath+"/"),
  2148. }
  2149. err = cloudbrain.GenerateTask(req)
  2150. if err != nil {
  2151. cloudBrainNewDataPrepare(ctx)
  2152. ctx.RenderWithErr(err.Error(), tpl, &form)
  2153. return
  2154. }
  2155. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/cloudbrain/benchmark")
  2156. }
  2157. func getBrainRegion(benchmarkChildTypeID int) string {
  2158. values := []string{"V1", "V2", "V4", "IT"}
  2159. return values[benchmarkChildTypeID]
  2160. }
  2161. func trimSpaceNewlineInString(s string) string {
  2162. re := regexp.MustCompile(`\r?\n`)
  2163. return re.ReplaceAllString(s, " ")
  2164. }
  2165. func BenchmarkDel(ctx *context.Context) {
  2166. if err := deleteCloudbrainJob(ctx); err != nil {
  2167. log.Error("deleteCloudbrainJob failed: %v", err, ctx.Data["msgID"])
  2168. ctx.ServerError(err.Error(), err)
  2169. return
  2170. }
  2171. var isAdminPage = ctx.Query("isadminpage")
  2172. var isHomePage = ctx.Query("ishomepage")
  2173. if ctx.IsUserSiteAdmin() && isAdminPage == "true" {
  2174. ctx.Redirect(setting.AppSubURL + "/admin" + "/cloudbrains")
  2175. } else if isHomePage == "true" {
  2176. ctx.Redirect(setting.AppSubURL + "/cloudbrains")
  2177. } else {
  2178. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/cloudbrain/benchmark")
  2179. }
  2180. }
  2181. func CloudBrainTrainJobNew(ctx *context.Context) {
  2182. err := cloudBrainNewDataPrepare(ctx)
  2183. if err != nil {
  2184. ctx.ServerError("get new train-job info failed", err)
  2185. return
  2186. }
  2187. ctx.HTML(http.StatusOK, tplCloudBrainTrainJobNew)
  2188. }
  2189. func InferenceCloudBrainJobNew(ctx *context.Context) {
  2190. err := cloudBrainNewDataPrepare(ctx)
  2191. if err != nil {
  2192. ctx.ServerError("get new train-job info failed", err)
  2193. return
  2194. }
  2195. ctx.HTML(http.StatusOK, tplCloudBrainInferenceJobNew)
  2196. }
  2197. func InferenceCloudBrainJobShow(ctx *context.Context) {
  2198. cloudBrainShow(ctx, tplCloudBrainInferenceJobShow, models.JobTypeInference)
  2199. }
  2200. func DownloadInferenceResultFile(ctx *context.Context) {
  2201. var jobID = ctx.Params(":jobid")
  2202. var versionName = ctx.Query("version_name")
  2203. task, err := models.GetCloudbrainByJobIDAndVersionName(jobID, versionName)
  2204. if err != nil {
  2205. log.Error("GetCloudbrainByJobID(%s) failed:%v", task.JobName, err.Error())
  2206. return
  2207. }
  2208. allFile, err := storage.GetAllObjectByBucketAndPrefixMinio(setting.Attachment.Minio.Bucket, task.ResultUrl)
  2209. returnFileName := task.DisplayJobName + ".zip"
  2210. MinioDownloadManyFile(task.ResultUrl, ctx, returnFileName, allFile)
  2211. }
  2212. func getInferenceJobCommand(form auth.CreateCloudBrainInferencForm) (string, error) {
  2213. var command string
  2214. bootFile := strings.TrimSpace(form.BootFile)
  2215. params := form.Params
  2216. if !strings.HasSuffix(bootFile, ".py") {
  2217. log.Error("bootFile(%s) format error", bootFile)
  2218. return command, errors.New("bootFile format error")
  2219. }
  2220. var parameters models.Parameters
  2221. var param string
  2222. if len(params) != 0 {
  2223. err := json.Unmarshal([]byte(params), &parameters)
  2224. if err != nil {
  2225. log.Error("Failed to Unmarshal params: %s (%v)", params, err)
  2226. return command, err
  2227. }
  2228. for _, parameter := range parameters.Parameter {
  2229. param += " --" + parameter.Label + "=" + parameter.Value
  2230. }
  2231. }
  2232. param += " --modelname" + "=" + form.CkptName
  2233. command += "python /code/" + bootFile + param + " > " + cloudbrain.ResultPath + "/" + form.DisplayJobName + "-" + cloudbrain.LogFile
  2234. return command, nil
  2235. }
  2236. func getTrainJobCommand(form auth.CreateCloudBrainForm) (string, error) {
  2237. var command string
  2238. bootFile := strings.TrimSpace(form.BootFile)
  2239. params := form.Params
  2240. if !strings.HasSuffix(bootFile, ".py") {
  2241. log.Error("bootFile(%s) format error", bootFile)
  2242. return command, errors.New("bootFile format error")
  2243. }
  2244. var parameters models.Parameters
  2245. var param string
  2246. if len(params) != 0 {
  2247. err := json.Unmarshal([]byte(params), &parameters)
  2248. if err != nil {
  2249. log.Error("Failed to Unmarshal params: %s (%v)", params, err)
  2250. return command, err
  2251. }
  2252. for _, parameter := range parameters.Parameter {
  2253. param += " --" + parameter.Label + "=" + parameter.Value
  2254. }
  2255. }
  2256. command += "python /code/" + bootFile + param + " > " + cloudbrain.ModelMountPath + "/" + form.DisplayJobName + "-" + cloudbrain.LogFile
  2257. return command, nil
  2258. }
  2259. func CloudBrainTrainJobDel(ctx *context.Context) {
  2260. var listType = ctx.Query("listType")
  2261. if err := deleteCloudbrainJob(ctx); err != nil {
  2262. log.Error("deleteCloudbrainJob failed: %v", err, ctx.Data["msgID"])
  2263. ctx.ServerError(err.Error(), err)
  2264. return
  2265. }
  2266. var isAdminPage = ctx.Query("isadminpage")
  2267. var isHomePage = ctx.Query("ishomepage")
  2268. if ctx.IsUserSiteAdmin() && isAdminPage == "true" {
  2269. ctx.Redirect(setting.AppSubURL + "/admin" + "/cloudbrains")
  2270. } else if isHomePage == "true" {
  2271. ctx.Redirect(setting.AppSubURL + "/cloudbrains")
  2272. } else {
  2273. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/train-job?listType=" + listType)
  2274. }
  2275. }
  2276. func GetBenchmarkTypes(ctx *context.Context) *models.BenchmarkTypes {
  2277. var lang = ctx.Locale.Language()
  2278. if benchmarkTypesMap[lang] == nil {
  2279. var val = i18n.Tr(lang, BENCHMARK_TYPE_CODE)
  2280. //use config
  2281. val = setting.BenchmarkTypes
  2282. var tempType *models.BenchmarkTypes
  2283. if err := json.Unmarshal([]byte(val), &tempType); err != nil {
  2284. log.Error("json.Unmarshal BenchmarkTypes(%s) failed:%v", val, err, ctx.Data["MsgID"])
  2285. return &models.BenchmarkTypes{}
  2286. }
  2287. benchmarkTypesMap[lang] = tempType
  2288. }
  2289. return benchmarkTypesMap[lang]
  2290. }