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

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