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

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