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

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